diff --git "a/2637.jsonl" "b/2637.jsonl" new file mode 100644--- /dev/null +++ "b/2637.jsonl" @@ -0,0 +1,752 @@ +{"seq_id":"85134631","text":"import cv2\nimport json\nfrom django.shortcuts import render\nfrom django.core.files.storage import FileSystemStorage\nfrom bdetector.buildDetector import buildDetector\nfrom bdetector.buildDetector import postprocessor\nfrom django.conf import settings\nfrom keras import backend as K\n\nBUILD_DETECTOR = buildDetector.BuildDetector()\nPOSTPROCESSOR = postprocessor.Postprocessor()\n\ndef index(request):\n \n if request.POST:\n image = request.FILES['docfile']\n fs = FileSystemStorage()\n image_file = fs.save(image.name, image)\n\n seg_image, data, mask = BUILD_DETECTOR.buildDetector(settings.MEDIA_ROOT + '/' + image.name)\n K.clear_session()\n\n image = cv2.imread(settings.MEDIA_ROOT + '/' + image.name)\n image = POSTPROCESSOR.rescalate_image(image)\n\n cv2.imwrite(settings.MEDIA_ROOT + '/img.png', image) \n cv2.imwrite(settings.MEDIA_ROOT + '/seg_img.png', seg_image)\n\n data_file = settings.MEDIA_ROOT + '/data.json'\n\n with open(data_file, 'w') as f:\n json.dump(data, f)\n\n context = {\n 'image' : 'media/img.png',\n 'seg_img' : 'media/seg_img.png',\n 'data' : json.loads(data),\n 'data_file': data_file,\n }\n \n return render(request, 'output.html', context)\n\n else:\n return render(request, 'index.html', {})\n\n\ndef output(request):\n\n return render(request, 'output.html', {})\n","sub_path":"src/bdserver/bdetector/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"314763140","text":"import math\n\n\nclass Point:\n def __init__(self, arg1, arg2, arg3):\n self.arg1 = arg1\n self.arg2 = arg2\n self.arg3 = arg3\n\n def sumOfSquareArgs(self):\n print((math.pow(self.arg1, 2)) +\n (math.pow(self.arg2, 2))+(math.pow(self.arg3, 2)))\n\n\np1 = Point(10, 20, 30)\np1.sumOfSquareArgs()\n","sub_path":"10.challenge1.py","file_name":"10.challenge1.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"529415483","text":"import unittest\n\nfrom rh.sensors import Sensors, I2CSensor\nimport sys\n\ntry:\n from smbus2 import SMBus\nexcept:\n import fake_rpi\n sys.modules['smbus2'] = fake_rpi.smbus\n\nfrom rh.helpers.i2c_helper import I2CBus\nimport tests as tests_pkg\n\nclass SensorsTest(unittest.TestCase):\n def setUp(self):\n self.i2c_bus = I2CBus(1)\n self.sensors = Sensors()\n\n def tearDown(self):\n pass\n\n def test_update(self):\n self.sensors.discover(tests_pkg)\n self.assertEqual(len(self.sensors), 1)\n before = self.sensors[0].getReadings()\n self.sensors.update_environmental_data()\n self.sensors.update_environmental_data()\n after = self.sensors[0].getReadings()\n self.assertEqual(after['counter']['value'], before['counter']['value']+1)\n\n def test_i2c_sensor(self):\n sensor = I2CSensor('i2c test', 8, self.i2c_bus)\n self.assertEqual(sensor.url, 'i2c:1/0x08')\n self.assertEqual(sensor.name, 'i2c test')\n self.assertEqual(sensor.i2c_address, 8)\n self.assertEqual(sensor.i2c_bus.id, 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/tests/test_sensors.py","file_name":"test_sensors.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398647249","text":"# -*- coding: utf-8 -*-\n\nimport gameutils\n\nclass Poison(object):\n name = \"中毒\".decode('utf-8')\n def __init__(self, val):\n self.val = val\n\n def applied(self, target, logrec):\n dmg_c = gameutils.magic_damage_calc(self.val, 1, 0, target._def, 0, 100, 0)\n dmg = dmg_c[1]\n # Applied Damage\n if target.hp < dmg:\n dmg = target.hp\n target.hp -= dmg\n logrec.stat_run(self.name, target.name, dmg)\n\n","sub_path":"crystalland/gamecore/debuffstats.py","file_name":"debuffstats.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"105911030","text":"# Determine if one string is a permutation of another \n\ndef check_permutation(s1,s2):\n dict = {}\n for letter in s1.lower().replace(' ', ''):\n if letter in dict:\n dict[letter] += 1 \n else:\n dict[letter] =1 \n\n for letter in s2.lower().replace(' ',''):\n if letter in dict:\n dict[letter] -=1 \n else:\n dict[letter] =1 \n\n # for letter in dict:\n # if dict[letter] != 0: \n # return False \n # return True\n return all(value == 0 for value in dict.values())\n\n\nprint(check_permutation('Google', 'Ooggle')) # True\nprint(check_permutation('top', 'pat')) # False","sub_path":"Educative.io/String_Processing/check_permutation.py","file_name":"check_permutation.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"379102569","text":"#!/usr/bin/python3\nfrom scapy.all import UDP,PcapReader\nimport socket\nimport struct\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='UDP unicast to multicast bridge')\n parser.add_argument('--inputfile', '-i', type=str, help=\"PCAP recording input file\", required=True)\n parser.add_argument('--port', '-p', type=int, help=\"unicast UDP port to forward.\", required=True)\n parser.add_argument('--num-packets', '-n', type=int, help=\"Number of packets to send. Default is all.\", default=0, required=False)\n parser.add_argument('--mcast-group', '-g', type=str, help=\"Multicast output group (IPv4 IP)\", required=True)\n parser.add_argument('--mcast-port', '-m', type=int, help=\"Multicast output port\", required=True)\n parser.add_argument('-v',\"--verbose\",help=\"Stdout message when a packet is transmitted\", action='store_true')\n \n args = parser.parse_args()\n\n try:\n print(\"Reading pcap file...\")\n pcapreader = PcapReader(args.inputfile)\n except KeyboardInterrupt:\n print(\"Read interrupted. Exiting.\")\n exit(0)\n except:\n print(\"Error reading pcap file \" + args.inputfile)\n exit(1)\n\n # Set up multicast output\n mcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n mcast_dest = (args.mcast_group, args.mcast_port)\n # Limit multicast scope to local segment\n ttl = struct.pack('b', 1)\n mcast_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n\n print(\"UDP port to monitor: \" + str(args.port))\n \n i=0\n \n try:\n # for curPacket in packets[0:max_packets]:\n for curPacket in pcapreader:\n try:\n bytes=curPacket[UDP].payload.load\n except:\n # Ignore non-UDP packets\n continue\n \n if curPacket[UDP].dport != args.port:\n # Ignore packets that aren't destined for the correct port\n continue\n\n if args.verbose:\n print(\"Sending \" + str(len(bytes)) + \" bytes to \" + str(mcast_dest) + \" counter=\" + str(i))\n \n mcast_socket.sendto(bytes, mcast_dest)\n \n i+= 1\n \n if args.num_packets > 0:\n if i >= args.num_packets:\n break\n except KeyboardInterrupt:\n # Can do cleanup here if necessary\n pass\n except Exception as e:\n print(\"Unhandled exception occurred: \" + str(e))\n print(\"Exiting.\")\n exit(2)\n \n print(\"Done.\")\n \n","sub_path":"apps/replay_pcap_to_mcast.py","file_name":"replay_pcap_to_mcast.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"645115954","text":"import os, pathlib\nfrom .. project.importer import import_module\nfrom .. util import deprecated, log\n\nCOMMANDS = (\n 'animations', 'all_pixel', 'all_pixel_test', 'clear_cache', 'demo',\n 'devices', 'info', 'monitor', 'new', 'run')\n\nif deprecated.allowed(): # pragma: no cover\n SIGNAL_COMMANDS = 'kill', 'pid', 'restart', 'shutdown'\n COMMANDS += SIGNAL_COMMANDS\n\nMODULES = {c: import_module('bibliopixel.main.' + c) for c in COMMANDS}\n\n\nBP_DELETED_COMMANDS = False\n\nif os.environ.get('BP_DELETED_COMMANDS', BP_DELETED_COMMANDS):\n DELETED = (\n 'list', 'load', 'remove', 'reset', 'save', 'set', 'show', 'update')\n MODULES.update({\n c: import_module('bibliopixel.main.deleted.' + c) for c in DELETED})\n\nFILE = pathlib.Path(__file__).parent / 'commands.rst.tmpl'\n\nHELP = FILE.open().read().format(\n command_count=len(COMMANDS),\n commands=[\n ', '.join(COMMANDS[0:8]),\n ', '.join(COMMANDS[8:])])\n\nBP_HEADER = \"\"\"\nAPPENDIX: ``bp --help`` for each command\n==================================================\n\"\"\"\n\nBP_TEMPLATE = \"\"\"\\\n``bp {command}``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n{doc}\n\n{description}\n\"\"\"\n\nSEPARATOR = \"\"\"\n------------------------------------\n\n\"\"\"\n\n\ndef get_command_help(command):\n module = MODULES[command]\n return BP_TEMPLATE.format(\n command=command,\n module=module,\n doc=module.__doc__.strip(),\n description=getattr(module, 'DESCRIPTION', ''))\n\n\nBP_HELP = SEPARATOR.join(get_command_help(c) for c in COMMANDS)\n\n\ndef print_help():\n print(HELP)\n print(BP_HEADER)\n print(BP_HELP)\n\n\nif __name__ == '__main__':\n print_help()\n","sub_path":"bibliopixel/main/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"300200218","text":"# -*- coding : utf-8 -*-\r\n\r\n'''\r\nCalculate the sum of two integers a and b, but you are not allowed to use the operator + and -.\r\n\r\nExample:\r\nGiven a = 1 and b = 2, return 3.\r\n'''\r\n\r\nclass Solution(object):\r\n def getSum(self, a, b):\r\n \"\"\"\r\n :type a: int\r\n :type b: int\r\n :rtype: int\r\n \"\"\"\r\n MAX = 0x7FFFFFFF\r\n MIN = 0x80000000\r\n mask = 0xFFFFFFFF\r\n while b != 0:\r\n a, b = (a ^ b) & mask, ((a & b) << 1) & mask #转化为正数来表示\r\n return a if a <= MAX else ~(a ^ mask)\r\n \r\n # sum = a #此方法python不能AC python整型不方便表示负数二进制\r\n # print(a, b, a^b)\r\n # while b != 0:\r\n # sum = a ^ b #异或 无进位加法\r\n # b = (a & b) << 1 #进位\r\n # a = sum \r\n # print(a,b)\r\n # return a \r\n \r\nif __name__ == '__main__':\r\n so = Solution()\r\n a, b = 1, -2 \r\n print(so.getSum(a, b))","sub_path":"371. Sum-of-Two-Integers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"281901565","text":"from django.conf import settings\n\nfrom boundary.models import BoundaryStateCode\n\n\nclass AggMixin(object):\n\n def get_queryset(self):\n institution_id = self.request.query_params.get('institution_id', None)\n boundary_id = self.request.query_params.get('boundary_id', None)\n if institution_id:\n return self.institution_queryset.filter(\n institution_id=institution_id)\n if boundary_id:\n return self.boundary_queryset.filter(\n boundary_id=boundary_id)\n\n state_id = BoundaryStateCode.objects.get(\n char_id=settings.ILP_STATE_ID).boundary_id\n return self.boundary_queryset.filter(boundary_id=state_id)\n","sub_path":"apps/assessments/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122940232","text":"import hashlib\nimport logger\nimport os\n\nfrom flask import Blueprint, jsonify, session, request\nfrom flask import current_app as app\nfrom werkzeug import secure_filename\n\nfrom models import db, Files, Problems, Solves, Teams\nfrom decorators import admins_only, api_wrapper, login_required, InternalException, WebException\n\nblueprint = Blueprint(\"problem\", __name__)\n\n@blueprint.route(\"/add\", methods=[\"POST\"])\n@admins_only\n@api_wrapper\ndef problem_add():\n\tname = request.form[\"name\"]\n\tcategory = request.form[\"category\"]\n\tdescription = request.form[\"description\"]\n\thint = request.form[\"problem-hint\"]\n\tflag = request.form[\"flag\"]\n\tvalue = request.form[\"value\"]\n\n\tname_exists = Problems.query.filter_by(name=name).first()\n\tif name_exists:\n\t\traise WebException(\"Problem name already taken.\")\n\tproblem = Problems(name, category, description, hint, flag, value)\n\tdb.session.add(problem)\n\tdb.session.commit()\n\n\tfiles = request.files.getlist(\"files[]\")\n\tfor _file in files:\n\t\tfilename = secure_filename(_file.filename)\n\n\t\tif len(filename) == 0:\n\t\t\tcontinue\n\n\t\tfile_path = os.path.join(app.config[\"UPLOAD_FOLDER\"], filename)\n\n\t\t_file.save(file_path)\n\t\tdb_file = Files(problem.pid, \"/\".join(file_path.split(\"/\")[2:]))\n\t\tdb.session.add(db_file)\n\n\tdb.session.commit()\n\n\treturn { \"success\": 1, \"message\": \"Success!\" }\n\n@blueprint.route(\"/delete\", methods=[\"POST\"])\n@admins_only\n@api_wrapper\ndef problem_delete():\n\tpid = request.form[\"pid\"]\n\tproblem = Problems.query.filter_by(pid=pid).first()\n\tif problem:\n\t\tSolves.query.filter_by(pid=pid).delete()\n\t\tProblems.query.filter_by(pid=pid).delete()\n\t\tdb.session.commit()\n\t\treturn { \"success\": 1, \"message\": \"Success!\" }\n\traise WebException(\"Problem does not exist!\")\n\n@blueprint.route(\"/update\", methods=[\"POST\"])\n@admins_only\n@api_wrapper\ndef problem_update():\n\tpid = request.form[\"pid\"]\n\tname = request.form[\"name\"]\n\tcategory = request.form[\"category\"]\n\tdescription = request.form[\"description\"]\n\thint = request.form[\"hint\"]\n\tflag = request.form[\"flag\"]\n\tdisabled = request.form.get(\"disabled\", 0)\n\tvalue = request.form[\"value\"]\n\n\tproblem = Problems.query.filter_by(pid=pid).first()\n\tif problem:\n\t\tproblem.name = name\n\t\tproblem.category = category\n\t\tproblem.description = description\n\t\tproblem.hint = hint\n\t\tproblem.flag = flag\n\t\tproblem.disabled = disabled\n\t\tproblem.value = value\n\n\t\tdb.session.add(problem)\n\t\tdb.session.commit()\n\n\t\treturn { \"success\": 1, \"message\": \"Success!\" }\n\traise WebException(\"Problem does not exist!\")\n\n@blueprint.route(\"/submit\", methods=[\"POST\"])\n@api_wrapper\n@login_required\ndef problem_submit():\n\tpid = request.form[\"pid\"]\n\tflag = request.form[\"flag\"]\n\ttid = session[\"tid\"]\n\n\tproblem = Problems.query.filter_by(pid=pid).first()\n\tteam = Teams.query.filter_by(tid=tid).first()\n\tif problem:\n\t\tif flag == problem.flag:\n\t\t\tsolve = Solves(pid, tid)\n\t\t\tteam.score += problem.value\n\t\t\tproblem.solves += 1\n\t\t\tdb.session.add(solve)\n\t\t\tdb.session.add(team)\n\t\t\tdb.session.add(problem)\n\t\t\tdb.session.commit()\n\n\t\t\tlogger.log(__name__, logger.WARNING, \"%s has solved %s by submitting %s\" % (team.name, problem.name, flag))\n\t\t\treturn { \"success\": 1, \"message\": \"Correct!\" }\n\n\t\telse:\n\t\t\tlogger.log(__name__, logger.WARNING, \"%s has incorrectly submitted %s to %s\" % (team.name, flag, problem.name))\n\t\t\traise WebException(\"Incorrect.\")\n\n\telse:\n\t\traise WebException(\"Problem does not exist!\")\n\n@blueprint.route(\"/data\", methods=[\"POST\"])\n#@api_wrapper # Disable atm due to json serialization issues: will fix\n@login_required\ndef problem_data():\n\tproblems = Problems.query.add_columns(\"pid\", \"name\", \"category\", \"description\", \"hint\", \"value\", \"solves\").order_by(Problems.value).filter_by(disabled=False).all()\n\tjason = []\n\n\tfor problem in problems:\n\t\tproblem_files = [ str(_file.location) for _file in Files.query.filter_by(pid=int(problem.pid)).all() ]\n\t\tjason.append({\"pid\": problem[1], \"name\": problem[2] ,\"category\": problem[3], \"description\": problem[4], \"hint\": problem[5], \"value\": problem[6], \"solves\": problem[7], \"files\": problem_files})\n\n\treturn jsonify(data=jason)\n\ndef insert_problem(data, force=False):\n\twith app.app_context():\n\t\tif len(list(get_problem(pid=data[\"pid\"]).all())) > 0:\n\t\t\tif force == True:\n\t\t\t\t_problem = Problems.query.filter_by(pid=data[\"pid\"]).first()\n\t\t\t\tdb.session.delete(_problem)\n\t\t\t\tdb.session.commit()\n\t\t\telse:\n\t\t\t\traise InternalException(\"Problem already exists.\")\n\n\t\tinsert = Problems(data[\"pid\"], data[\"title\"], data[\"category\"], data[\"description\"], data[\"value\"])\n\t\tif \"hint\" in data: insert.hint = data[\"hint\"]\n\t\tif \"autogen\" in data: insert.autogen = data[\"autogen\"]\n\t\tif \"bonus\" in data: insert.bonus = data[\"bonus\"]\n\t\tif \"threshold\" in data: insert.threshold = data[\"threshold\"]\n\t\tif \"weightmap\" in data: insert.weightmap = data[\"weightmap\"]\n\t\tdb.session.add(insert)\n\t\tdb.session.commit()\n\n\treturn True\n\ndef get_problem(title=None, pid=None):\n\tmatch = {}\n\tif title != None:\n\t\tmatch.update({ \"title\": title })\n\telif pid != None:\n\t\tmatch.update({ \"pid\": pid })\n\twith app.app_context():\n\t\tresult = Problems.query.filter_by(**match)\n\t\treturn result","sub_path":"server/api/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"464250670","text":"from tkinter import Tk, Canvas\nfrom math import sqrt\n\n\ncount = 0\n\nsize = 380\nborder = 15\nspacing = (size-2*border)/14\nplayer = \"black\"\nflag = True\nlists = [[0 for i in range(15)] for i in range(15)]\nstack = []\n\n\ndef draw_chessboard():\n global count\n for i in range(15):\n canvas.create_line(border, border+i*spacing, border+14*spacing, border+i*spacing)\n canvas.create_line(border+i*spacing, border, border+i*spacing, border+14*spacing)\n count = count + 2\n point = [(border+7*spacing, border+7*spacing), (border+3*spacing, border+3*spacing), (border+11*spacing, border+3*spacing), (border+3*spacing, border+11*spacing), (border+11*spacing, border+11*spacing)]\n for x,y in point:\n canvas.create_rectangle(x-2, y-2, x+2, y+2, fill='black')\n count = count + 1\n\n\ndef draw_chessman(event):\n global player, count\n if flag:\n for i in range(15):\n for j in range(15):\n x = border+j*spacing\n y = border+i*spacing\n r = sqrt(pow(x-event.x, 2) + pow(y-event.y, 2))\n if r <= 10 and lists[i][j] == 0:\n if player == \"black\":\n canvas.create_oval(x-10, y-10, x+10, y+10, fill='black')\n lists[i][j] = 1\n player = \"white\"\n else:\n canvas.create_oval(x-10, y-10, x+10, y+10, fill='white')\n lists[i][j] = 2\n player = \"black\"\n count = count + 1\n stack.append((count, i, j))\n game_over()\n\n\ndef game_over():\n global flag, count\n black_chess = 0\n white_chess = 0\n for i in range(15):\n for j in range(11):\n if lists[i][j] == 1 and lists[i][j+1] == 1 and lists[i][j+2] == 1 and lists[i][j+3] == 1 and lists[i][j+4] == 1:\n black_chess = 1\n elif lists[i][j] == 2 and lists[i][j+1] == 2 and lists[i][j+2] == 2 and lists[i][j+3] == 2 and lists[i][j+4] == 2:\n white_chess = 1\n for i in range(15):\n for j in range(11):\n if lists[j][i] == 1 and lists[j+1][i] == 1 and lists[j+2][i] == 1 and lists[j+3][i] == 1 and lists[j+4][i] == 1:\n black_chess = 1\n elif lists[j][i] == 2 and lists[j+1][i] == 2 and lists[j+2][i] == 2 and lists[j+3][i] == 2 and lists[j+4][i] == 2:\n white_chess = 1\n for i in range(11):\n for j in range(4, 15):\n if lists[i][j] == 1 and lists[i+1][j-1] == 1 and lists[i+2][j-2] == 1 and lists[i+3][j-3] == 1 and lists[i+4][j-4] == 1:\n black_chess = 1\n elif lists[i][j] == 2 and lists[i+1][j-1] == 2 and lists[i+2][j-2] == 2 and lists[i+3][j-3] == 2 and lists[i+4][j-4] == 2:\n white_chess = 1\n for i in range(11):\n for j in range(11):\n if lists[i][j] == 1 and lists[i+1][j+1] == 1 and lists[i+2][j+2] == 1 and lists[i+3][j+3] == 1 and lists[i+4][j+4] == 1:\n black_chess = 1\n elif lists[i][j] == 2 and lists[i+1][j+1] == 2 and lists[i+2][j+2] == 2 and lists[i+3][j+3] == 2 and lists[i+4][j+4] == 2:\n white_chess = 1\n if black_chess == 1:\n canvas.create_text(border+7*spacing, border+7*spacing, text=\"black win\", fill='red')\n flag = False\n count = count + 1\n elif white_chess == 1:\n canvas.create_text(border+7*spacing, border+7*spacing, text=\"white win\", fill='green')\n flag = False\n count = count + 1\n\n\ndef restart(event):\n global flag\n while len(stack) > 0:\n tag, i, j = stack.pop()\n canvas.delete(tag)\n lists[i][j] = 0\n flag = True\n draw_chessboard()\n\n\ndef undo(event):\n if len(stack) > 0:\n tag, i, j = stack.pop()\n canvas.delete(tag)\n lists[i][j] = 0\n global player\n if player == \"white\":\n player = \"black\"\n else:\n player = \"white\"\n\n\nroot = Tk()\nroot.title(\"five-in-a-row\")\nroot.resizable(0, 0)\ncanvas = Canvas(root, width=size, height=size, background='white')\ncanvas.pack()\ndraw_chessboard()\ncanvas.bind('', draw_chessman)\ncanvas.bind('', restart)\ncanvas.bind('', undo)\nroot.mainloop()","sub_path":"five-in-a-row/five-in-a-row.py","file_name":"five-in-a-row.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"286707","text":"# pylint: disable=missing-module-docstring\n\n__all__ = ['RawClient']\n\nimport asyncio\nimport time\nfrom typing import Optional, Dict\n\nimport pyrogram.raw.functions as funcs\nimport pyrogram.raw.types as types\nfrom pyrogram import Client\nfrom pyrogram.session import Session\nfrom pyrogram.raw.core import TLObject\n\nimport xdecha # pylint: disable=unused-import\n\n_LOG = xdecha.logging.getLogger(__name__)\n_LOG_STR = \"<<>>\"\n\n\nclass RawClient(Client):\n \"\"\" xdecha raw client \"\"\"\n DUAL_MODE = False\n LAST_OUTGOING_TIME = time.time()\n\n REQ_LOGS: Dict[int, 'ChatReq'] = {}\n DELAY_BET_MSG_REQ = 1\n MSG_REQ_PER_MIN = 20\n REQ_LOCK = asyncio.Lock()\n\n def __init__(self, bot: Optional['xdecha.core.client.xdechaBot'] = None, **kwargs) -> None:\n self._bot = bot\n super().__init__(**kwargs)\n self._channel = xdecha.core.types.new.ChannelLogger(self, \"CORE\")\n xdecha.core.types.new.Conversation.init(self)\n\n async def send(self, data: TLObject, retries: int = Session.MAX_RETRIES,\n timeout: float = Session.WAIT_TIMEOUT, sleep_threshold: float = None):\n key = 0\n if isinstance(data, (funcs.messages.SendMessage,\n funcs.messages.EditMessage,\n funcs.messages.ForwardMessages)):\n if isinstance(data, funcs.messages.ForwardMessages):\n tmp = data.to_peer\n else:\n tmp = data.peer\n if isinstance(tmp, (types.InputPeerChannel, types.InputPeerChannelFromMessage)):\n key = int(tmp.channel_id)\n elif isinstance(tmp, types.InputPeerChat):\n key = int(tmp.chat_id)\n elif isinstance(tmp, (types.InputPeerUser, types.InputPeerUserFromMessage)):\n key = int(tmp.user_id)\n elif isinstance(data, funcs.channels.DeleteMessages):\n if isinstance(data.channel, (types.InputChannel, types.InputChannelFromMessage)):\n key = int(data.channel.channel_id)\n if key:\n async def slp(to_sl: float) -> None:\n if to_sl > 0.1:\n if to_sl > 1:\n _LOG.info(_LOG_STR, to_sl, key)\n else:\n _LOG.debug(_LOG_STR, to_sl, key)\n await asyncio.sleep(to_sl)\n async with self.REQ_LOCK:\n if key in self.REQ_LOGS:\n chat_req = self.REQ_LOGS[key]\n else:\n chat_req = self.REQ_LOGS[key] = ChatReq()\n diff = chat_req.small_diff\n if 0 < diff < self.DELAY_BET_MSG_REQ:\n await slp(1 - diff)\n diff = chat_req.big_diff\n if diff >= 60:\n chat_req.reset()\n elif chat_req.count > self.MSG_REQ_PER_MIN:\n await slp(60 - diff)\n chat_req.reset()\n else:\n chat_req.update()\n return await super().send(data, retries, timeout, sleep_threshold)\n\n\nclass ChatReq:\n def __init__(self) -> None:\n self._first = self._last = time.time()\n self._count = 0\n\n @property\n def small_diff(self) -> float:\n return time.time() - self._last\n\n @property\n def big_diff(self) -> float:\n return time.time() - self._first\n\n @property\n def count(self) -> float:\n return self._count\n\n def reset(self) -> None:\n self._first = self._last = time.time()\n self._count = 1\n\n def update(self) -> None:\n self._last = time.time()\n self._count += 1\n","sub_path":"xdecha/core/ext/raw_client.py","file_name":"raw_client.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"322779362","text":"import time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport utilities\nfrom Pages.promo_detail_page.PromoDetailPage import PromoDetailPage\nfrom utilities import CustomWaits\nfrom utilities.BaseForm import BaseForm\nfrom utilities.DataBase import DataBase\nfrom utilities.Parser import Parser\nfrom utilities.Table import Table\n\n\nclass NewPromoTypePage(BaseForm):\n browser = Parser().get_browser_name()\n\n \"\"\"HEADER\"\"\"\n back_button = (By.CSS_SELECTOR, 'a[class*=\"k-button k-button-icontex\"]')\n save_button = (By.ID, 'save')\n new_promo_button = (By.ID, 'new-promo')\n create_template_button = (By.ID, 'new-template')\n title = (By.TAG_NAME, 'h2')\n\n \"\"\"PROMO TYPE INFORMATION FORM\"\"\"\n table = (By.CLASS_NAME, 'b-form__content')\n\n \"\"\"Editable_elements\"\"\"\n \"\"\"Really input\"\"\"\n name_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Name\"]')\n key_promotion_name_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: KeyName\"]')\n key_promotion_code_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: KeyCode\"]')\n number_validy_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: ValidityNumber\"]')\n number_range_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: RangeNumber\"]')\n external_agency_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: ExternalAgency\"]')\n duration_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Duration\"]')\n\n \"\"\"Dropdown (getting from the parent of the input)\"\"\"\n promo_kind_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: PromoKindId\"]')\n validity_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Validity\"]')\n start_date_validy_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: DayOfWeek\"]')\n date_validy_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Date\"]')\n range_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Range\"]')\n how_to_order_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: HowToOrder\"]')\n workflow_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Workflow\"]')\n\n \"\"\"Checkboxes\"\"\"\n setting_targets = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsSettingTargets\"]')\n split_KPI_per_pages = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsSplitKPIPerPages\"]')\n one_supplier = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsOneSupplier\"]')\n only_goods = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsOnlyGoodsOnStock\"]')\n order_planning = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsOrderPlanning\"]')\n mutation = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsMutation\"]')\n electronic_version = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsElectronicVersion\"]')\n web_globus = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsWebGlobus\"]')\n web_shop = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsWebShop\"]')\n direct_mail = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsDirectMail\"]')\n shelf_labels = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsShelfLabels\"]')\n defined_direct_costs = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsDefinedDirectCosts\"]')\n suppliers_contributions = (By.CSS_SELECTOR, 'input[data-bind=\"checked: IsSupplierContributions\"]')\n\n \"\"\"Multiselect dropdown\"\"\"\n parametrs_split_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Parameters\"]')\n assortment_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Assortment\"]')\n region_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Region\"]')\n supermarket_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Supermarket\"]')\n distribution_channel_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: DistributionChannel\"]')\n advertising_channel_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: AdvertisingChannel\"]')\n print_advertising_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: PrintAdvertising\"]')\n format_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Format\"]')\n distribution_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: Distribution\"]')\n type_of_labels_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: TypeOfLabeles\"]')\n pos_support_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: POSSupport\"]')\n\n \"\"\"Calendar\"\"\"\n validy_from_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: ValidFrom\"]')\n validy_to_input = (By.CSS_SELECTOR, 'input[data-bind=\"value: ValidTo\"]')\n\n def get_form(self):\n return self.wait.until(EC.presence_of_element_located(self.table), 'Table is absent') \\\n .find_element_by_tag_name('table')\n\n def get_title(self):\n return self.wait.until(EC.visibility_of_element_located(self.title),\n '\"New promo type\" title is not visible').text\n\n def get_all_labels_text(self):\n labels_list = []\n form = Table(self.driver, self.get_form())\n cells = form.get_all_cells_element()\n for cell in cells:\n labels_list.append(cell[0].text)\n return labels_list\n\n def is_supermarket_required(self):\n field = self.wait.until(EC.presence_of_element_located(self.supermarket_input))\n div_parent_element = WebDriverWait(field, 5).until(EC.presence_of_element_located((By.XPATH, '../..')))\n if 'required' in div_parent_element.get_attribute('class'):\n return True\n else:\n return False\n\n def choose_promo_kind(self, state):\n state_dict = {\n 'Promo kind 1': 0,\n 'Promo kind 2': 1,\n 'Promo kind 3': 2\n }\n dropdown = self.get_dropdown(self.promo_kind_input)\n self.click_and_select_dropdown_option(state_dict, state, '\"Promo kind\" is not choosable', dropdown)\n return self\n\n def choose_validity(self, state):\n state_dict = {\n 'Day(s)': 1,\n 'Month(s)': 2,\n 'Quater(s)': 0\n }\n dropdown = self.get_dropdown(self.validity_input)\n self.click_and_select_dropdown_option(state_dict, state, '\"Validity\" is not choosable', dropdown)\n return self\n\n def choose_start_date(self, state):\n state_dict = {\n 'Monday': 0,\n 'Tuesday': 1,\n 'Wednesday': 2,\n 'Thursday': 3,\n 'Friday': 4,\n 'Saturday': 5,\n 'Sunday': 6\n }\n dropdown = self.get_dropdown(self.start_date_validy_input)\n if self.is_dropdown_disabled(self.start_date_validy_input):\n raise Exception('\"Start date (day of week)\" is disabled')\n self.click_and_select_dropdown_option(state_dict, state, '\"Start date (day of week)\" is not choosable', dropdown)\n return self\n\n def choose_date(self, state):\n state_dict = {\n 'First day of month': 0,\n 'First day of quarter': 1\n }\n dropdown = self.get_dropdown(self.date_validy_input)\n if self.is_dropdown_disabled(self.date_validy_input):\n raise Exception('\"Date\" is disabled')\n self.click_and_select_dropdown_option(state_dict, state, '\"Date\" is not choosable', dropdown)\n return self\n\n def choose_range(self, state):\n state_dict = {\n 'Article(s)': 0,\n 'Page(s)': 1,\n 'Vaucher(s)': 2\n }\n dropdown = self.get_dropdown(self.range_input)\n self.click_and_select_dropdown_option(state_dict, state, '\"Range\" is not choosable', dropdown)\n return self\n\n def choose_how_to_order(self, state):\n state_dict = {\n 'Action planning': 0,\n 'cross-dock': 1,\n 'pre-orders': 2\n }\n dropdown = self.get_dropdown(self.how_to_order_input)\n self.click_and_select_dropdown_option(state_dict, state, '\"How to order\" is not choosable', dropdown)\n return self\n\n def choose_workflow(self, state):\n workflow_list = DataBase(utilities.DataBase.get_connection_parameters()) \\\n .select_in_list(\"SELECT [Name] FROM [PromoToolGlobus].[PromoTool].[WorkflowTemplate]\")\n state_dict = {}\n i = 0\n for element in workflow_list:\n state_dict[element[0]] = i\n i += 1\n if state not in state_dict:\n state = workflow_list[0][0]\n dropdown = self.get_dropdown(self.workflow_input)\n self.click_and_select_dropdown_option(state_dict, state, '\"Workflow\" is not choosable', dropdown)\n return self\n\n def click_back_button(self):\n self.wait.until(EC.element_to_be_clickable(self.back_button), 'Back button is not clicable').click()\n return self\n\n def click_save_button(self):\n self.wait_spiner_loading()\n button = self.wait.until(EC.visibility_of_element_located(self.save_button), 'Save button is missing')\n self.wait_element_has_not_state(self.save_button, 'k-state-disabled', 'Save button is disabled')\n button.click()\n self.wait_spiner_loading()\n # if self.is_button_disabled(self.save_button, 'Save'):\n # return self\n # else:\n # raise Exception('\"Save\" button should be disabled after saving')\n return self\n\n\n def choose_assortment(self):\n input = self.wait.until(EC.presence_of_element_located(self.assortment_input),\n '\"Assortment\" field is absent')\n assortment = WebDriverWait(input, 5).until(EC.presence_of_element_located((By.XPATH, '..')),\n '\"Assortment\" field is invisible')\n self.driver.execute_script(\"return arguments[0].scrollIntoView();\", assortment)\n assortment.click()\n self.get_widget_window('\"Assortment\" window is invisible')\n list = self.wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, 'span[class=\"k-in\"]')),\n 'There is no option for Assortment')\n for el in list:\n el.click()\n self.close_widget_window()\n return self\n\n def choose_assortment_by_index(self, list_of_index):\n input = self.wait.until(EC.presence_of_element_located(self.assortment_input),\n '\"Assortment\" field is absent')\n assortment = WebDriverWait(input, 5).until(EC.presence_of_element_located((By.XPATH, '..')),\n '\"Assortment\" field is invisible')\n self.driver.execute_script(\"return arguments[0].scrollIntoView();\", assortment)\n assortment.click()\n self.get_widget_window('\"Assortment\" window is invisible')\n list = self.wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, 'span[class=\"k-in\"]')),\n 'There is no option for Assortment')\n try:\n for index in list_of_index:\n list[index].click()\n except IndexError:\n print('There is no element with index ' + str(list_of_index))\n self.close_widget_window()\n return self\n\n def choose_supermarket(self):\n input = self.wait.until(EC.presence_of_element_located(self.supermarket_input),\n '\"Supermarket\" field is absent')\n supermarket = WebDriverWait(input, 5).until(EC.presence_of_element_located((By.XPATH, '..')),\n '\"Supermarket\" field is invisible')\n self.driver.execute_script(\"return arguments[0].scrollIntoView();\", supermarket)\n supermarket.click()\n self.get_widget_window('\"Supermarket\" window is invisible')\n list = self.wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, 'span[class=\"k-in\"]')),\n 'There is no option for Supermarket')\n for el in list:\n el.click()\n self.close_widget_window()\n return self\n\n def click_create_template_button(self):\n button = self.wait.until(EC.visibility_of_element_located(self.create_template_button),\n '\"Create template\" button is not visible')\n self.wait_element_has_not_state(self.create_template_button, 'k-state-disabled',\n '\"Create template\" button should be active')\n button.click()\n return PromoDetailPage(self.driver)\n\n def click_new_promo_button(self):\n button = self.wait.until(EC.visibility_of_element_located(self.new_promo_button),\n 'New Promo button is invisible')\n self.wait_element_has_not_state(self.new_promo_button, 'k-state-disabled', \"New promo button still be disabled\")\n button.click()\n return PromoDetailPage(self.driver)\n\n\n def click_yes_to_pop_up_dialog(self):\n toolbar = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'ul[role=\"toolbar\"]')),\n 'Button group is not visible in Message pop up')\n\n WebDriverWait(toolbar, 5).until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, 'li[role=\"button\"]')),\n 'Buttons are not visible in Message pop up')[0].click()\n return PromoDetailPage(self.driver)\n\n def is_assortment_from_additional_info_disabled(self):\n field = self.wait.until(EC.presence_of_all_elements_located(self.assortment_input))\n assortment = field[len(field)-1]\n if 'true' in assortment.get_attribute('aria-disabled'):\n return True\n else:\n return False\n\n def get_assortment_value_from_additional_info(self):\n assortment_fields = self.wait.until(EC.presence_of_all_elements_located(self.assortment_input),\n 'Assortment field for additional info is absent')\n field = assortment_fields[len(assortment_fields)-1]\n div_parent_element = WebDriverWait(field, 5).until(EC.visibility_of_element_located((By.XPATH, '..')))\n self.driver.execute_script(\"return arguments[0].scrollIntoView();\", div_parent_element)\n list_elements = div_parent_element.find_elements_by_tag_name('li')\n list_options_text = []\n for el in list_elements:\n list_options_text.append(el.text)\n return list_options_text\n","sub_path":"Pages/promo_type_page/NewPromoTypePage.py","file_name":"NewPromoTypePage.py","file_ext":"py","file_size_in_byte":14186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"328272466","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division, absolute_import, unicode_literals\nfrom __future__ import print_function\n\nimport re\nimport json\n\nfrom lxml import html\nfrom scrapy import Request\nfrom urllib.parse import urljoin\nfrom fetch_product_links.settings import *\n\nfrom fetch_product_links.spiders import BaseProduct\n\nclass CentrisProductsSpider(BaseProduct):\n name = 'centris_products'\n allowed_domains = ['centris.ca']\n start_urls = [\n 'https://www.centris.ca/en/commercial-properties~for-rent?view=Thumbnail',\n 'https://www.centris.ca/en/properties~for-rent?view=Thumbnail',\n 'https://www.centris.ca/en/commercial-properties~for-sale?view=Thumbnail',\n 'https://www.centris.ca/en/properties~for-sale?view=Thumbnail'\n ]\n\n\n product_api_url = 'https://www.centris.ca/Mvc/Property/GetInscriptions'\n\n headers = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Content-Type': 'application/json; charset=UTF-8',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/75.0.3770.100 Safari/537.36'\n }\n\n search_url = 'https://www.centris.ca/fr/propriete-commerciale~a-vendre~{keyword}?view=Thumbnail'\n get_key_req_url = 'https://www.centris.ca/Property/PropertyWebService.asmx/GetAutoCompleteData'\n\n title_list = {}\n i = 0\n def start_requests(self):\n # for url in self.start_urls:\n # yield Request(\n # url=self._clean_text(url),\n # meta={'start_position': 0, 'url': url},\n # callback=self._start_requests,\n # dont_filter=True\n # )\n yield Request(\n url=self.start_urls[0],\n meta={'start_position': 0, 'url': self.start_urls[0], 'next_urls': self.start_urls[1:]},\n callback=self._start_requests\n )\n\n def _start_requests(self, response):\n start_position = response.meta.get('start_position')\n url = response.meta.get('url')\n data = {'startPosition': start_position}\n\n response.meta['start_position'] = start_position\n self.headers['Referer'] = self._clean_text(url)\n yield Request(\n url=self.product_api_url,\n method='POST',\n body=json.dumps(data),\n headers=self.headers,\n dont_filter=True,\n meta=response.meta\n )\n\n def parse(self, response):\n if response.meta.get('start_position') > 19:\n start_position = response.meta.get('start_position')\n\n data = {'startPosition': start_position}\n\n yield Request(\n url=self.product_api_url,\n method='POST',\n body=json.dumps(data),\n headers=self.headers,\n dont_filter=True,\n meta=response.meta,\n callback=self._get_product_\n )\n else:\n start_position = response.meta.get('start_position')\n try:\n json_data = json.loads(response.text)\n result = json_data.get('d', {}).get('Result', {})\n tree_html = html.fromstring(result.get('html'))\n except Exception as e:\n result = None\n print(e)\n return None\n\n\n product_links = tree_html.xpath(\"//a[contains(@class, 'a-more-detail')]/@href\")\n\n for i, link in enumerate(product_links):\n url = urljoin(response.url, link)\n\n yield Request(url, callback=self.parse_single_product)\n\n start_position += 20\n\n total_matches = result.get('count')\n\n data = {'startPosition': start_position}\n response.meta['start_position'] = start_position\n response.meta['total_matches'] = total_matches\n\n yield Request(\n url=self.product_api_url,\n method='POST',\n body=json.dumps(data),\n headers=self.headers,\n dont_filter=True,\n meta=response.meta,\n callback=self._get_product_\n )\n\n def parse_single_product(self, response):\n product = {}\n\n products = response.xpath(\"//div[@class='grid_3']//div[@class='description']//table//tr\")\n centris_number = ' '.join(response.xpath(\"//span[@id='ListingDisplayId']/text()\").extract())\n title = ' '.join(response.xpath(\"//h1[@itemprop='category']//span/text()\").extract())\n address = ' '.join(response.xpath(\"//h2[@itemprop='address']/text()\").extract())\n price = ' '.join(response.xpath(\"//div[@class='price']//span/text()\").extract())\n description = self._clean_text(' '.join(response.xpath(\"//div[@itemprop='description']/text()\").extract()))\n bathbeds = ' '.join(response.xpath(\"//div[@class='teaser']//span/text()\").extract())\n walkscore = ' '.join(response.xpath(\"//div[@class='walkscore']//span/text()\").extract())\n geo_coordinates = ' '.join(response.xpath(\"//div[@itemprop='geo']//meta/@content\").extract())\n real_estate_agent_name = ' '.join(response.xpath(\"//p[@class='middle']//span[@itemprop='name']/text()\").extract())\n\n product['number'] = centris_number\n product['title'] = title\n product['address'] = address\n product['price'] = price\n product['description'] = description\n product['bedbaths'] = bathbeds\n product['walkscore'] = walkscore\n product['geo_coordinates'] = geo_coordinates\n product['real_estate_agent_name'] = real_estate_agent_name\n\n for item in products:\n\n key = self._clean_text(item.xpath('.//td/text()').extract_first())\n value = self._clean_text(item.xpath('.//td/span/text()').extract_first())\n\n product[key] = value\n\n\n if key not in self.title_list.values():\n self.i = self.i + 1\n self.title_list[self.i] = key\n\n product['all_keys'] = self.title_list\n\n return product\n\n def _clean_text(self, text):\n text = text.replace(\"\\n\", \" \").replace(\"\\t\", \" \").replace(\"\\r\", \" \")\n text = re.sub(\" \", \" \", text).strip()\n return re.sub(r'\\s+', ' ', text)\n\n def _get_product_(self, response):\n product = {}\n start_position = response.meta.get('start_position')\n try:\n json_data = json.loads(response.text)\n result = json_data.get('d', {}).get('Result', {})\n tree_html = html.fromstring(result.get('html'))\n except Exception as e:\n print(e)\n return None\n products = tree_html.xpath(\"//div[@class='grid_3']//div[@class='description']//table//tr\")\n centris_number = ' '.join(tree_html.xpath(\"//span[@id='ListingDisplayId']/text()\"))\n title = ' '.join(tree_html.xpath(\"//h1[@itemprop='category']//span/text()\"))\n address = ' '.join(tree_html.xpath(\"//h2[@itemprop='address']/text()\"))\n price = ' '.join(tree_html.xpath(\"//div[@class='price']//span/text()\"))\n description = self._clean_text(' '.join(tree_html.xpath(\"//div[@itemprop='description']/text()\")))\n bathbeds = ' '.join(tree_html.xpath(\"//div[@class='teaser']//span/text()\"))\n walkscore = ' '.join(tree_html.xpath(\"//div[@class='walkscore']//span/text()\"))\n geo_coordinates = ' '.join(tree_html.xpath(\"//div[@itemprop='geo']//meta/@content\"))\n real_estate_agent_name = ', '.join(tree_html.xpath(\"//p[@class='middle']//span[@itemprop='name']/@content\")[0])\n\n product['number'] = centris_number\n product['title'] = title\n product['address'] = address\n product['price'] = price\n product['description'] = description\n product['bedbaths'] = bathbeds\n product['walkscore'] = walkscore\n product['geo_coordinates'] = geo_coordinates\n product['real_estate_agent_name'] = real_estate_agent_name\n for item in products:\n key = self._clean_text(item.xpath('.//td/text()')[0])\n value = self._clean_text(item.xpath('.//td/span/text()')[0])\n\n product[key] = value\n\n if key not in self.title_list.values():\n self.i = self.i + 1\n self.title_list[self.i] = key\n\n product['all_keys'] = self.title_list\n\n yield product\n\n start_position = response.meta.get('start_position')\n total_matches = response.meta.get('total_matches')\n\n if start_position < total_matches - 1:\n start_position += 1\n response.meta['start_position'] = start_position\n data = {'startPosition': start_position}\n\n yield Request(\n url=self.product_api_url,\n method='POST',\n body=json.dumps(data),\n headers=self.headers,\n dont_filter=True,\n meta=response.meta,\n callback=self._get_product_\n )\n\n else:\n next_urls = response.meta.get('next_urls')\n if next_urls:\n response.meta['next_urls'] = next_urls[1:] if len(next_urls) > 1 else None\n response.meta['start_position'] = 0\n response.meta['total_matches'] = None\n response.meta['url'] = next_urls[0]\n yield Request(\n url=next_urls[0],\n callback=self._start_requests,\n meta=response.meta\n )\n # yield Request(\n # url=self.start_urls[0],\n # meta={'start_position': 0, 'url': self.start_urls[0], 'next_urls': self.start_urls[1:]},\n # callback=self._start_requests\n # )","sub_path":"fetch_product_links/spiders/centris.py","file_name":"centris.py","file_ext":"py","file_size_in_byte":9860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"277795670","text":"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom preprocessing import preprocessing as pre\nfrom preprocessing import plot\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\n\n\ndef discriminator(layers_):\n legos = []\n for idx in range(len(layers_) - 1):\n in_n = layers_[idx]\n out_n = layers_[idx + 1]\n\n # linear sum\n legos.append(nn.Linear(in_n, out_n))\n\n if idx != (len(layers_) - 2): # range: -1 & in_n: -1, therefore: -2\n # act. func.\n # todo: 왜 BatchNorm 을 썼을 때 학습이 더 안될까...?\n # legos.append(nn.BatchNorm1d(out_n))\n legos.append(nn.LeakyReLU(0.2))\n\n # output layer\n legos.append(nn.Sigmoid())\n\n _model = nn.Sequential(*legos)\n\n if torch.cuda.is_available():\n _model.cuda()\n\n return _model\n\n\ndef generator(layers_):\n legos = []\n for idx in range(len(layers_) - 1):\n in_n = layers_[idx]\n out_n = layers_[idx + 1]\n\n # linear sum\n legos.append(nn.Linear(in_n, out_n))\n\n if idx != (len(layers_) - 2): # range: -1 & in_n: -1, therefore: -2\n # act. func.\n # legos.append(nn.BatchNorm1d(out_n))\n legos.append(nn.LeakyReLU(0.2))\n # legos.append(nn.Tanh())\n\n # output layer\n # legos.append(nn.Tanh())\n\n _model = nn.Sequential(*legos)\n\n if torch.cuda.is_available():\n _model.cuda()\n\n return _model\n\n\nif __name__ == \"__main__\":\n n_row = 1500\n data = pre.get_normal_data(mu_=0, sigma_=1, n_=int(n_row), dim_=2, is_return_tensor_var=True)\n\n # --- layer setting --- #\n dim = 2\n D = discriminator([dim, 5, 5, 1])\n\n g_input_dim = 2\n G = generator([g_input_dim, 5, 5, 2])\n\n # --- optimizer --- #\n learning_rate = 0.001\n d_optimizer = optim.Adam(D.parameters(), lr=learning_rate)\n g_optimizer = optim.Adam(G.parameters(), lr=learning_rate)\n\n # --- hyper parameter --- #\n epochs, d_epochs, g_epochs = 100, 10, 1\n batch_size = 100\n total_batch = n_row // batch_size\n\n # --- train --- #\n for epoch in tqdm(range(epochs)):\n data = data[np.random.choice(n_row, size=n_row, replace=False), :] # shuffle\n\n for _ in range(d_epochs):\n for batch_idx in range(total_batch):\n\n mb_data = data[(batch_size * batch_idx):(batch_size * (batch_idx + 1)), :] # b: mini-batch\n z_noise = pre.get_normal_data(mu_=0, sigma_=1, n_=batch_size, dim_=g_input_dim,\n is_return_tensor_var=True)\n gen_data = G(z_noise)\n\n D.zero_grad()\n # d_error = -torch.log(D(mb_data)) - torch.log(1-D(gen_data)) # vanilla gan\n d_error = (1/2)*((D(mb_data)-1)**2) + (1/2)*(D(gen_data-0)**2) # lsgan\n d_error = torch.mean(d_error)\n d_error.backward()\n d_optimizer.step()\n\n for _ in range(g_epochs):\n for batch_idx in range(total_batch):\n\n z_noise = pre.get_normal_data(mu_=0, sigma_=1, n_=batch_size, dim_=g_input_dim,\n is_return_tensor_var=True)\n gen_data = G(z_noise)\n\n G.zero_grad()\n # g_error = -torch.log(D(gen_data)) # vanilla gan\n g_error = (1/2)*((D(gen_data)-1)**2) # lsgan\n g_error = torch.mean(g_error)\n g_error.backward()\n g_optimizer.step()\n\n # save plot\n z_noise = pre.get_normal_data(mu_=0, sigma_=1, n_=n_row, dim_=g_input_dim,\n is_return_tensor_var=True)\n gen_data = G(z_noise)\n plot.plot_gan_d_boundary(D, n=10000, min_=-10, max_=10, is_prob=False)\n plot.plot_two_dataset(data, gen_data)\n plt.savefig('./GAN_result/images_%d_boundary_D.png' % (epoch + 1))\n plt.close()\n\n if epoch % 10 == 0:\n print(\"\\n\\n\", \"D loss: \", round(d_error.data[0], 2), round(D(mb_data).mean().data[0], 2))\n print(\"\\n\\n\", \"G loss: \", round(g_error.data[0], 2), round(D(gen_data).mean().data[0], 2))\n\n # --- plot --- #\n z_noise = pre.get_normal_data(mu_=0, sigma_=1, n_=n_row, dim_=g_input_dim,\n is_return_tensor_var=True)\n gen_data = G(z_noise)\n plot.plot_gan_d_boundary(D, n=10000, min_=-10, max_=10, is_prob=False)\n plot.plot_two_dataset(data, gen_data)\n plt.show()\n\n","sub_path":"GAN/LSGAN_gaussian.py","file_name":"LSGAN_gaussian.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"264639599","text":"# -*- coding: utf-8 -*-\n__author__ = 'lateink'\nimport hashlib\nimport re\nimport datetime\n\n\ndef get_md5(url):\n if isinstance(url, str):\n url = url.encode('utf-8')\n m = hashlib.md5()\n m.update(url)\n return m.hexdigest()\n\n\ndef split_blank(value_list):\n print(value_list)\n value_list = [value.replace(\" \", \"\") for value in value_list]\n value_list = [value.replace(\"\\n\", \"\") for value in value_list]\n print(value_list)\n sep = \",\"\n value = sep.join(value_list)\n print(value)\n return value\n\n\ndef date_converts(value):\n value = value.replace('\\n', '')\n value = value.replace(' ', '')\n regex_str = \".*?(\\d+(-\\d*-\\d*)*).*\"\n match_obj = re.match(regex_str, value)\n if match_obj:\n value = match_obj.group(1)\n else:\n value = \"\"\n return value\n\n\ndef get_place(value):\n regex = re.compile('[\\u4e00-\\u9fa5]+')\n value = regex.findall(value)\n if len(value) != 0:\n return value[0]\n else:\n return \"\"\n\n\ndef return_value(value):\n return value\n\n\ndef get_film_id(url):\n regex_str = \".*?(\\d+)\"\n match_obj = re.match(regex_str, url)\n value = \"\"\n if match_obj:\n value = match_obj.group(1)\n return value\n\nif __name__ == '__main__':\n # print(date_converts(\"\\n \\n 2017-10-14 \\n中国大陆\\n sdf\\n\"))\n # print(get_place(\"\\n 2017 中国大陆 \\n\"))\n split_blank(['\\n lateink\\n', '\\n bojack\\n', 'lexburner'])\n","sub_path":"maoyan/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600895634","text":"import os\nfrom src import togo\nimport unittest\nimport tempfile\n\nclass TogoTestCase(unittest.TestCase):\n def setUp(self):\n self.db_fd, togo.togo.app.config[\"DATABASE\"] = tempfile.mkstemp()\n togo.togo.app.config[\"TESTING\"] = True\n self.app = togo.togo.app.test_client()\n togo.database.init_db()\n\n def tearDown(self):\n os.close(self.db_fd)\n os.unlink(togo.togo.app.config[\"DATABASE\"])\n\n def test_index(self):\n rv = self.app.get(\"/\", follow_redirects = True)\n assert \"logged out\" in rv.data\n","sub_path":"tests/test_togo.py","file_name":"test_togo.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"82350998","text":"#!/usr/bin/env python\n\n\"\"\"getText.py: An algorithm to find horizontal text in a binary image. \"\"\"\n\n__author__ = \"Abtin Rasoulian\"\n__copyright__ = \"Copyright 2013, The Thumbnail Project\"\n__credits__ = [\"Abtin Rasoulian\"]\n__license__ = \"GPL\"\n__version__ = \"1.1\"\n__maintainer__ = \"Abtin Rasoulian\"\n__email__ = \"abtinr@ece.ubc.ca\"\n__status__ = \"Production\"\n\nimport numpy\nimport scipy.signal as signal\nfrom scipy.ndimage.measurements import label\n\n\ndef findTextInImage(Image, options):\n\t\n\t# Design a filter \n\tfilter = numpy.ones((1,options.text_wordDistance))\n\tI_text = signal.convolve(Image,filter,mode='same') > 0\n\t\n\ttext = []\n\t# Find connected components and detect text\n\tlabel_im, nb_labels = label(I_text)\n\tfor i in range(1, nb_labels):\n\t\tcomponent_sizeX = max(numpy.where(label_im == i)[0])-min(numpy.where(label_im == i)[0])\n\t\tcomponent_sizeY = max(numpy.where(label_im == i)[1])-min(numpy.where(label_im == i)[1])\n\t\tif(component_sizeX > options.text_minSizeX and component_sizeY > options.text_minSizeY):\n\t\t\tposX = (max(numpy.where(label_im == i)[0])+min(numpy.where(label_im == i)[0]))/2\n\t\t\tposY1 = min(numpy.where(label_im == i)[1])+options.text_wordDistance\n\t\t\tposY2 = max(numpy.where(label_im == i)[1])-options.text_wordDistance\n\t\t\ttext.append((posX, posY1, posX, posY2))\n\t\t\t\n\treturn text","sub_path":"getText.py","file_name":"getText.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"251180115","text":"import os\n\nfrom malcolm.compat import OrderedDict\nfrom malcolm.modules.builtin.parts import GroupPart, IconPart, TitlePart, \\\n HelpPart\nfrom malcolm.core import Widget, group_tag, Port, config_tag, \\\n BooleanMeta, ChoiceMeta, NumberMeta, StringMeta, TableMeta\nfrom .pandablocksactionpart import PandABlocksActionPart\nfrom .pandablocksfieldpart import PandABlocksFieldPart\nfrom .pandablockstablepart import PandABlocksTablePart\n\n\nSVG_DIR = os.path.join(os.path.dirname(__file__), \"..\", \"icons\")\n\n\ndef make_meta(subtyp, description, tags, writeable=True, labels=None):\n if subtyp == \"enum\":\n meta = ChoiceMeta(description, labels)\n elif subtyp == \"bit\":\n meta = BooleanMeta(description)\n elif subtyp in (\"uint\", \"\"):\n meta = NumberMeta(\"uint32\", description)\n elif subtyp in (\"int\", \"pos\"):\n meta = NumberMeta(\"int32\", description)\n elif subtyp in (\"scalar\", \"xadc\"):\n meta = NumberMeta(\"float64\", description)\n elif subtyp == \"lut\":\n meta = StringMeta(description)\n else:\n raise ValueError(\"Unknown subtype %r\" % subtyp)\n meta.set_writeable(writeable)\n tags.append(meta.default_widget().tag())\n meta.set_tags(tags)\n return meta\n\n\nclass PandABlocksMaker(object):\n def __init__(self, client, block_name, block_data, doc_url_base):\n self.client = client\n self.block_name = block_name\n self.block_data = block_data\n self.doc_url_base = doc_url_base\n self.parts = OrderedDict()\n # Make an icon\n self._make_icon_label()\n for field_name, field_data in block_data.fields.items():\n self.make_parts_for(field_name, field_data)\n\n def make_parts_for(self, field_name, field_data):\n \"\"\"Create the relevant parts for this field\n\n Args:\n field_name (str): Short field name, e.g. VAL\n field_data (FieldData): Field data object\n \"\"\"\n typ = field_data.field_type\n subtyp = field_data.field_subtype\n\n if typ in (\"read\", \"xadc\"):\n writeable = False\n else:\n writeable = True\n\n if typ == \"time\" or typ in (\"param\", \"read\") and subtyp == \"time\":\n self._make_time_parts(field_name, field_data, writeable)\n elif typ == \"write\" and subtyp == \"action\":\n self._make_action_part(field_name, field_data)\n elif typ in (\"param\", \"read\", \"write\", \"xadc\"):\n self._make_param_part(field_name, field_data, writeable)\n elif typ == \"bit_out\":\n self._make_out(field_name, field_data, \"bit\")\n elif typ == \"pos_out\":\n self._make_out(field_name, field_data, \"pos\")\n self._make_scale_offset(field_name)\n self._make_out_capture(field_name, field_data)\n elif typ == \"ext_out\":\n self._make_out_capture(field_name, field_data)\n elif typ == \"bit_mux\":\n self._make_mux(field_name, field_data, \"bit\")\n self._make_mux_delay(field_name)\n elif typ == \"pos_mux\":\n self._make_mux(field_name, field_data, \"pos\")\n elif typ == \"table\":\n self._make_table(field_name, field_data)\n else:\n raise ValueError(\"Unknown type %r subtype %r\" % (typ, subtyp))\n\n def _make_icon_label(self):\n block_type = self.block_name.rstrip(\"0123456789\")\n svg_name = block_type + \".svg\"\n part = IconPart(svg=os.path.join(SVG_DIR, svg_name))\n self._add_part(\"icon\", part)\n label = self.block_data.description + \" \" + \\\n self.block_name[len(block_type):]\n part = TitlePart(value=label)\n self._add_part(\"label\", part)\n part = HelpPart(\"%s/build/%s_doc.html\" % (\n self.doc_url_base, block_type.lower()))\n self._add_part(\"help\", part)\n\n def _make_scale_offset(self, field_name):\n group = self._make_group(\"outputs\")\n meta = StringMeta(\"Units for position fields on this block\",\n tags=[group, Widget.TEXTINPUT.tag()])\n self._make_field_part(field_name + \".UNITS\", meta, writeable=True)\n meta = NumberMeta(\"float64\", \"Scale for block position fields\",\n tags=[group, Widget.TEXTINPUT.tag()])\n self._make_field_part(field_name + \".SCALE\", meta, writeable=True)\n meta = NumberMeta(\"float64\", \"Offset for block position fields\",\n tags=[group, Widget.TEXTINPUT.tag()])\n self._make_field_part(field_name + \".OFFSET\", meta, writeable=True)\n meta = NumberMeta(\"float64\", \"Current scaled value of position field\",\n tags=[group, Widget.TEXTUPDATE.tag()])\n self._make_field_part(field_name + \".SCALED\", meta, writeable=False)\n\n def _make_time_parts(self, field_name, field_data, writeable):\n description = field_data.description\n if writeable:\n widget = Widget.TEXTINPUT\n group = self._make_group(\"parameters\")\n else:\n widget = Widget.TEXTUPDATE\n group = self._make_group(\"readbacks\")\n meta = NumberMeta(\"float64\", description, [group, widget.tag()])\n # We must change time units before value, so restore value in 2nd\n # iteration\n self._make_field_part(field_name, meta, writeable, iteration=2)\n meta = ChoiceMeta(description + \" time units\", [\"s\", \"ms\", \"us\"],\n tags=[group, Widget.COMBO.tag()])\n self._make_field_part(field_name + \".UNITS\", meta, writeable=True)\n\n def _make_param_part(self, field_name, field_data, writeable):\n if writeable:\n group = self._make_group(\"parameters\")\n else:\n group = self._make_group(\"readbacks\")\n if field_data.field_type == \"xadc\":\n subtype = \"xadc\"\n else:\n subtype = field_data.field_subtype\n meta = make_meta(subtype, field_data.description,\n [group], writeable, field_data.labels)\n self._make_field_part(field_name, meta, writeable)\n\n def _make_action_part(self, field_name, field_data):\n group = self._make_group(\"parameters\")\n part = PandABlocksActionPart(\n self.client, self.block_name, field_name,\n field_data.description, [group])\n self._add_part(field_name, part)\n\n def _make_out(self, field_name, field_data, typ):\n group = self._make_group(\"outputs\")\n if typ == \"bit\":\n port_type = Port.BOOL\n else:\n port_type = Port.INT32\n flow_tag = port_type.source_port_tag(\n \"%s.%s\" % (self.block_name, field_name))\n meta = make_meta(typ, field_data.description,\n tags=[group, flow_tag], writeable=False)\n self._make_field_part(field_name, meta, writeable=False)\n\n def _make_out_capture(self, field_name, field_data):\n group = self._make_group(\"outputs\")\n meta = ChoiceMeta(\"Capture %s in PCAP?\" % field_name,\n field_data.labels, tags=[group, Widget.COMBO.tag()])\n self._make_field_part(field_name + \".CAPTURE\", meta, writeable=True)\n\n def _make_mux(self, field_name, field_data, typ):\n group = self._make_group(\"inputs\")\n if typ == \"bit\":\n port_type = Port.BOOL\n else:\n port_type = Port.INT32\n labels = [x for x in field_data.labels if x in (\"ZERO\", \"ONE\")] + \\\n sorted(x for x in field_data.labels if x not in (\"ZERO\", \"ONE\"))\n meta = ChoiceMeta(field_data.description, labels, tags=[\n group, port_type.sink_port_tag(\"ZERO\"),\n Widget.COMBO.tag()])\n self._make_field_part(field_name, meta, writeable=True)\n meta = make_meta(typ, \"%s current value\" % field_name,\n tags=[group], writeable=False)\n self._make_field_part(field_name + \".CURRENT\", meta, writeable=False)\n\n def _make_mux_delay(self, field_name):\n group = self._make_group(\"inputs\")\n meta = NumberMeta(\n \"uint8\", \"How many FPGA ticks to delay input\",\n tags=[group, Widget.TEXTINPUT.tag()])\n self._make_field_part(field_name + \".DELAY\", meta, writeable=True)\n\n def _make_table(self, field_name, field_data):\n group = self._make_group(\"parameters\")\n tags = [Widget.TABLE.tag(), group, config_tag()]\n meta = TableMeta(field_data.description, tags, writeable=True)\n part = PandABlocksTablePart(self.client, meta,\n self.block_name, field_name)\n self._add_part(field_name, part)\n\n def _add_part(self, field_name, part):\n assert field_name not in self.parts, \\\n \"Already have a field %r\" % field_name\n self.parts[field_name] = part\n\n def _make_field_part(self, field_name, meta, writeable, initial_value=None,\n iteration=1):\n if writeable:\n meta.set_tags(list(meta.tags) + [config_tag(iteration)])\n meta.set_writeable(True)\n part = PandABlocksFieldPart(self.client, meta,\n self.block_name, field_name, initial_value)\n self._add_part(field_name, part)\n\n def _make_group(self, attr_name):\n if attr_name not in self.parts:\n part = GroupPart(attr_name, \"All %s attributes\" % attr_name)\n self._add_part(attr_name, part)\n group = group_tag(attr_name)\n return group\n","sub_path":"malcolm/modules/pandablocks/parts/pandablocksmaker.py","file_name":"pandablocksmaker.py","file_ext":"py","file_size_in_byte":9448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539071514","text":"import django_tables2 as tables\nfrom django_tables2.utils import A\n\nfrom browsing.browsing_utils import MergeColumn\nfrom entities.models import *\n\n\nclass PersonPersonTable(tables.Table):\n id = tables.LinkColumn()\n source = tables.LinkColumn(\n 'entities:person_detail',\n args=[A('source.id')], verbose_name='Source'\n )\n rel_type = tables.Column()\n target = tables.LinkColumn(\n 'entities:person_detail',\n args=[A('target.id')], verbose_name='Target'\n )\n\n class Meta:\n model = PersonPerson\n sequence = ('id', 'source', 'rel_type', 'target')\n attrs = {\"class\": \"table table-responsive table-hover\"}\n\n\nclass PersonTable(tables.Table):\n id = tables.LinkColumn(\n 'entities:person_detail',\n args=[A('pk')], verbose_name='ID'\n )\n name = tables.LinkColumn(\n 'entities:person_detail',\n args=[A('pk')], verbose_name='Name'\n )\n mentioned_in_entry = tables.TemplateColumn(\n \"{% for x in record.mentioned_in_entry.all %}\\\n {{ x }} |{% endfor %}\",\n orderable=False\n )\n profession = tables.ManyToManyColumn()\n merge = MergeColumn(verbose_name='keep | remove', accessor='pk')\n\n class Meta:\n model = Person\n sequence = ('id', 'written_name',)\n attrs = {\"class\": \"table table-responsive table-hover\"}\n\n\nclass InstitutionTable(tables.Table):\n id = tables.LinkColumn(\n 'entities:institution_detail',\n args=[A('pk')], verbose_name='ID'\n )\n written_name = tables.LinkColumn(\n 'entities:institution_detail',\n args=[A('pk')], verbose_name='Name'\n )\n location = tables.Column()\n\n class Meta:\n model = Institution\n sequence = ('id', 'written_name',)\n attrs = {\"class\": \"table table-responsive table-hover\"}\n\n\nclass PlaceTable(tables.Table):\n name = tables.LinkColumn(\n 'entities:place_detail',\n args=[A('pk')], verbose_name='Name'\n )\n part_of = tables.Column()\n\n class Meta:\n model = Place\n sequence = ('id', 'name',)\n attrs = {\"class\": \"table table-responsive table-hover\"}\n\n\nclass AlternativeNameTable(tables.Table):\n name = tables.LinkColumn(\n 'entities:alternativename_detail',\n args=[A('pk')], verbose_name='Name'\n )\n\n class Meta:\n model = AlternativeName\n sequence = ('name',)\n attrs = {\"class\": \"table table-responsive table-hover\"}\n","sub_path":"entities/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"85263470","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\nbl_info = {\n 'name': 'My Addon',\n 'version': (0, 1),\n 'description': 'Addon group test',\n 'category': '3D View',\n}\n\n\nif 'bpy' in locals():\n import importlib\n importlib.reload(addongroup)\n MyAddonPreferences.reload_sub_modules()\nelse:\n from . import addongroup\n\nimport bpy\n\n\nclass MyAddonPreferences(\n addongroup.AddonGroupPreferences,\n bpy.types.AddonPreferences if '.' not in __name__ else\n bpy.types.PropertyGroup):\n bl_idname = __name__\n\n sub_modules = None\n\n prop = bpy.props.IntProperty(name='MyAddon Prop')\n\n def draw(self, context):\n layout = self.layout\n layout.prop(self, 'prop')\n\n layout.separator()\n super().draw(context)\n\n @classmethod\n def register(cls):\n super().register()\n\n @classmethod\n def unregister(cls):\n super().unregister()\n\n\nclasses = [\n MyAddonPreferences,\n]\n\n\n@MyAddonPreferences.module_register\ndef register():\n for cls in classes:\n bpy.utils.register_class(cls)\n\n prefs = MyAddonPreferences.get_instance()\n value = prefs.prop # value of bpy.props.IntProperty(name='MyAddon Prop')\n\n\ndef unregister():\n for cls in classes[::-1]:\n bpy.utils.unregister_class(cls)\n","sub_path":"addongroup_sample/base_addon/my_addon/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486713558","text":"#-*- coding: utf-8 -*\nfrom django.views.generic import ListView\nfrom linde_app2.models import Stocktaking, StocktakingStatus, StocktakingType\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import RequestContext, loader\n\nclass ChoseStocktakingView(ListView):\n template_name = \"chosestocktaking.html\"\n model = Stocktaking\n scroll_size = 50\n action = \"returns-chose-stocksheet\"\n\n def get_context_data(self, **kwargs):\n context = super(ChoseStocktakingView, self).get_context_data(**kwargs)\n page_number = 0\n if 'page_number' in self.kwargs:\n page_number = int(self.kwargs['page_number'])\n maxpage = Stocktaking.objects.count() / self.scroll_size \n if Stocktaking.objects.count() % self.scroll_size != 0:\n maxpage += 1\n context['prev_page_num'] = page_number - 1\n context['next_page_num'] = page_number + 1\n context['maxpage'] = maxpage\n context['action'] = self.action\n return context\n \n def get_queryset(self):\n page_number = 0\n limit = 0\n if 'page_number' in self.kwargs:\n page_number = int(self.kwargs['page_number'])\n offset = page_number * self.scroll_size\n queryset = Stocktaking.objects.filter(status=1).order_by('-stocktaking_number').prefetch_related('type', 'status')[offset:offset + self.scroll_size]\n for item in queryset:\n if item.status == StocktakingStatus.objects.get(id=2):\n item.processed = True\n return queryset\n","sub_path":"linde_returns/views_app/ChoseStocktakingView.py","file_name":"ChoseStocktakingView.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"10073195","text":"import pydoc\nimport sys\n\n__all__ = [\"AmbiguousLookupError\", \"NotFoundLookupError\"]\n\n\nclass AmbiguousLookupError(LookupError):\n \"\"\"A signature cannot be resolved due to ambiguity.\"\"\"\n\n\nclass NotFoundLookupError(LookupError):\n \"\"\"A signature cannot be resolved because no applicable method can be found.\"\"\"\n\n\ndef _document(f):\n \"\"\"Generate documentation for a function `f`.\n\n The generated documentation contains both the function definition and the\n docstring. The docstring is on the same level of indentation of the function\n definition. There will be no trailing newlines.\n\n If the package :mod:`sphinx` is not imported, then the function definition will\n be preceded by the string ``.\n\n If the package :mod:`sphinx` is imported, then the function definition will include\n a Sphinx directive to displays the function definition in a nice way.\n\n Args:\n f (function): Function.\n\n Returns:\n str: Documentation for `f`.\n \"\"\"\n # :class:`pydoc._PlainTextDoc` removes styling. This styling will display\n # erroneously in Sphinx.\n parts = pydoc._PlainTextDoc().document(f).rstrip().split(\"\\n\")\n\n # Separate out the function definition and the lines corresponding to the body.\n title = parts[0]\n body = parts[1:]\n\n # Remove indentation from every line of the body. This indentation defaults to\n # four spaces.\n body = [line[4:] for line in body]\n\n # If `sphinx` is imported, assume that we're building the documentation. In that\n # case, display the function definition in a nice way.\n if \"sphinx\" in sys.modules:\n title = \".. py:function:: \" + title + \"\\n :noindex:\"\n else:\n title = \"\\n\\n\" + title\n title += \"\\n\" # Add a newline to separate the title from the body.\n\n # Ensure that there are no trailing newlines. This can happen if the body is empty.\n return \"\\n\".join([title] + body).rstrip()\n\n\nclass Resolver:\n \"\"\"Method resolver.\n\n Attributes:\n signatures (list[:class:`.signature.Signature`]): Registered signatures.\n is_faithful (bool): Whether all signatures are faithful or not.\n \"\"\"\n\n def __init__(self):\n self.signatures = []\n self.is_faithful = True\n\n def doc(self, exclude=None):\n \"\"\"Concatenate the docstrings of all methods of this function. Remove duplicate\n docstrings before concatenating.\n\n Args:\n exclude (function, optional): Exclude this implementation from the\n concatenation.\n\n Returns:\n str: Concatenation of all docstrings.\n \"\"\"\n # Generate all docstrings, possibly excluding `exclude`.\n docs = [\n _document(sig.implementation)\n for sig in self.signatures\n if not (exclude and sig.implementation == exclude)\n ]\n # This can yield duplicates, because of extra methods automatically generated by\n # :func:`.signature.append_default_args`. We remove these by simply only\n # keeping unique docstrings.\n unique_docs = []\n for d in docs:\n if d not in unique_docs:\n unique_docs.append(d)\n # The unique documentations have no trailing newlines, so separate them with\n # a newline.\n return \"\\n\\n\".join(unique_docs)\n\n def register(self, signature):\n \"\"\"Register a new signature.\n\n Args:\n signature (:class:`.signature.Signature`): Signature to add.\n \"\"\"\n existing = [s == signature for s in self.signatures]\n if any(existing):\n if sum(existing) != 1:\n raise AssertionError(\n f\"The added signature `{signature}` is equal to {sum(existing)} \"\n f\"existing signatures. This should never happen.\"\n )\n self.signatures[existing.index(True)] = signature\n else:\n self.signatures.append(signature)\n\n # Use a double negation for slightly better performance.\n self.is_faithful = not any(not s.is_faithful for s in self.signatures)\n\n def __len__(self):\n return len(self.signatures)\n\n def resolve(self, target):\n \"\"\"Find the most specific signature that satisfies a target.\n\n Args:\n target (:class:`.signature.Signature` or tuple[object]): Target to resolve.\n Must be either a signature to be encompassed or a tuple of arguments.\n\n Returns:\n :class:`.signature.Signature`: The most specific signature satisfying\n `target`.\n \"\"\"\n if isinstance(target, tuple):\n\n def check(s):\n # `target` are concrete arguments.\n return s.match(target)\n\n else:\n\n def check(s):\n # `target` is a signature that must be encompassed.\n return target <= s\n\n candidates = []\n for signature in [s for s in self.signatures if check(s)]:\n # If none of the candidates are comparable, then add the method as\n # a new candidate and continue.\n if not any(c.is_comparable(signature) for c in candidates):\n candidates += [signature]\n continue\n\n # The signature under consideration is comparable with at least one\n # of the candidates. First, filter any strictly more general candidates.\n new_candidates = [c for c in candidates if not signature < c]\n\n # If the signature under consideration is as specific as at least\n # one candidate, then and only then add it as a candidate.\n if any(signature <= c for c in candidates):\n candidates = new_candidates + [signature]\n else:\n candidates = new_candidates\n\n if len(candidates) == 0:\n # There is no matching signature.\n raise NotFoundLookupError(f\"`{target}` could not be resolved.\")\n elif len(candidates) == 1:\n # There is exactly one matching signature. Success!\n return candidates[0]\n else:\n # There are multiple matching signatures. Before raising an exception,\n # attempt to resolve the ambiguity using the precedence of the signatures.\n precedences = [c.precedence for c in candidates]\n max_precendence = max(precedences)\n if sum([p == max_precendence for p in precedences]) == 1:\n return candidates[precedences.index(max_precendence)]\n else:\n # Could not resolve the ambiguity, so error. First, make a nice list\n # of the candidates and their precedences.\n listed_candidates = \"\\n \".join(\n [f\"{c} (precedence: {c.precedence})\" for c in candidates]\n )\n raise AmbiguousLookupError(\n f\"`{target}` is ambiguous among the following:\\n\"\n f\" {listed_candidates}\"\n )\n","sub_path":"plum/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"208050742","text":"import face_recognition\nimport pathlib\nimport PIL.ImageDraw\nimport PIL.Image\n\n#loading the image\nknown_image=face_recognition.load_image_file(\"//IMAGE FILE\")\n\n#encoded value for known image\nknown_image_encoded_value=face_recognition.face_encodings(known_image)[0]\n#for first single face\n#for multiple face remove [0] and modify the code\n\n#setting up default paramaters\nbest_image= None\nbest_euclidean_distance=0.6\n\n#to scan and compare all images in a folder using pathlib library\nfor image_location in Path(\"//DirecoryName\").glob(\"*png\",\"*jpg\"):\n #loading unknown image to compare\n unknown_image=face_recognition.load_image_file(image_location)\n #getting face locations manually for more accuracy\n unknown_image_face_locations=face_recognition.face_locations(unknown_image,number_of_times_to_upsample=2)\n #number_of_times_to_upsample=2 magnifies image 2 times for more accuracy to avoid small resolution error\n #getting face encodings\n unknown_image_encoded_value=face_recognition.face_encodings(unknown_image,known_face_locations=unknown_image_face_locations)\n #comparing 2 images using euclidean distnce\n euclidean_distance=face_recognition.compare_faces(unknown_image_encoded_value,known_image_encoded_value)[0]\n # for multiple face remove [0] and modify the code\n #update to sort the best results further\n if euclidean_distance intersection[text]:\n intersection[text] = value_dict[title_string]\n\n for k in intersection.keys():\n output_dict[k]['aviso'] = inverse_value_dict[intersection[k]]\n\n return output_dict, SA_polygon, SA_layer\n","sub_path":"src/Dash/cptec.py","file_name":"cptec.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214518637","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Installer for the tribuna.policy package.\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nimport os\n\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nlong_description = \\\n read('README.rst') + \\\n read('docs', 'CHANGELOG.rst') + \\\n read('docs', 'LICENSE.rst')\n\nsetup(\n name='tribuna.policy',\n version='0.2dev',\n description=\"Policy package for Tribuna webpage\",\n long_description=long_description,\n # Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='tribuna, policy',\n author='Termitnjak d.o.o.',\n author_email='info@termitnjak.si',\n url='',\n license='MIT',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['tribuna'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'collective.z3cform.widgets',\n 'five.grok',\n 'five.pt',\n # needed if we re-enable populator.py,\n #'loremipsum',\n 'mobile.sniffer',\n 'Pillow',\n 'Plone',\n 'plone.api',\n 'plone.app.jquerytools',\n 'plone.app.caching',\n 'plone.formwidget.captcha',\n 'setuptools',\n 'tribuna.annotator',\n 'tribuna.content',\n 'tribuna.diazotheme',\n 'collective.cookiecuttr',\n 'z3c.jbot'\n ],\n extras_require={\n 'test': [\n 'mock',\n 'plone.app.testing',\n 'unittest2',\n ],\n 'develop': [\n 'coverage',\n 'flake8',\n 'i18ndude',\n 'jarn.mkrelease',\n 'loremipsum',\n 'niteoweb.loginas',\n 'plone.app.debugtoolbar',\n 'plone.reload',\n 'Products.Clouseau',\n 'Products.DocFinderTab',\n 'Products.PDBDebugMode',\n 'Products.PrintingMailHost',\n 'Sphinx',\n 'zest.releaser',\n 'zptlint',\n ],\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"497484628","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pywt\nfrom statsmodels.tsa.stattools import adfuller\nimport statsmodels.api as sm\nfrom statsmodels.tsa.arima_model import ARMA\nimport warnings\n\n\nurl = 'http://cloud.bdsmc.net:8006/devicedata?mac=000300000079&num=1000'\ndata = pd.read_json(url)\nwarnings.filterwarnings(\"ignore\")\n\n\nprd_interval = 7\nrolling_range_set = -100\nrolling_range = -1 * int(abs(rolling_range_set) / prd_interval) * prd_interval\nlooking_range = 100\nprd_window = -800\nwavelet_type = 'db4'\nwavelet_len = 4\nlevel = 2\nmode = 'sym'\n\nprd_res = np.array(data['z'].values)[:rolling_range]\ncur_prd = np.array([])\n\n\ndef wavelet_analyze(data):\n for interval in range(1, int(abs(rolling_range) / prd_interval) + 1):\n if rolling_range+prd_interval*interval == 0:\n index_for_predict = np.array(data['gps_time'])[rolling_range+prd_interval*(interval-1):]\n data_list2 = np.array(data['z'])[rolling_range+prd_interval*(interval-1):]\n else:\n index_for_predict = np.array(data['gps_time'])[rolling_range+prd_interval*(interval-1):rolling_range+prd_interval*interval]\n data_list2 = np.array(data['z'])[rolling_range+prd_interval*(interval-1):rolling_range+prd_interval*interval]\n index_list = np.array(data['gps_time'])[prd_window+interval*prd_interval:rolling_range + prd_interval * interval - prd_interval]\n data_list1 = np.array(data['z'])[prd_window+interval*prd_interval:rolling_range + prd_interval * interval - prd_interval]\n # print(len(index_list))\n coeff = pywt.wavedec(data_list1, wavelet_type, mode=mode, level=level)\n\n # 选择模型阶数\n order = []\n model = []\n result = []\n Is_diff=np.zeros(len(coeff))\n for item_index,item in enumerate(coeff):\n dftest = adfuller(item)\n if dftest[1] > 0.05:\n print(dftest)\n print(len(item))\n temp_item = pd.DataFrame(item)\n base = temp_item.diff(1)\n base.dropna(inplace=True)\n Is_diff[item_index] = 1\n item = base.T.values[0]\n print(adfuller(item))\n else:\n base = item\n order_A2 = sm.tsa.arma_order_select_ic(base, ic='aic')['aic_min_order']\n order.append(order_A2)\n\n # 模型构建\n model_A2 = ARMA(base, order=order_A2)\n model.append(model_A2)\n\n results_A2 = model_A2.fit()\n result.append(results_A2)\n\n wave_len = len(index_list) + prd_interval\n t_len = int((wave_len - 1) / 2 + wavelet_len)\n # 预测小波系数\n AD = []\n # cA2,cD2,cD1\n for level_index in range(level + 1):\n if t_len == len(coeff[-1 - level_index]):\n pAD = coeff[-1 - level_index]\n else:\n pAD = np.hstack([coeff[-1 - level_index],model[-1-level_index].predict(params=result[-1 - level_index].params, start=len(coeff[-1 - level_index]),end=t_len - 1)])\n if level_index < level - 1:\n t_len = int((t_len - 1) / 2 + wavelet_len)\n AD.append(pAD)\n AD.reverse()\n\n coeff_new = AD\n predict_wave = pywt.waverec(coeff_new, wavelet_type)\n if Is_diff[item_index]:\n predict_wave = pd.DataFrame(predict_wave)\n diff_shift_prd = base.shift(1)\n predict_wave = predict_wave.add(diff_shift_prd).values[-prd_interval:]\n else:\n predict_wave=predict_wave[-prd_interval:]\n prd_res = np.hstack([prd_res, predict_wave])\n cur_prd = np.hstack([cur_prd,predict_wave])\n\n\n # 10个预测值\n print(interval)\n temp_data_wt = np.array([data_list2,predict_wave,predict_wave-data_list2,(predict_wave-data_list2)/data_list2*100])\n print(np.shape(temp_data_wt.T))\n predict_wt = pd.DataFrame(temp_data_wt.T,index = index_for_predict,columns=['real_value','pre_value_wt','err_wt','err_rate_wt/%'])\n print(predict_wt)\n plt.figure(figsize=(15, 5))\n plt.plot(data['z'].values[-1 * looking_range:], 'b')\n plt.plot(prd_res[-1 * looking_range:], 'r')\n plt.show()","sub_path":"main/tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615273502","text":"from console import Console\nfrom hero import Hero\nfrom sound import Sound\n\nclass Game:\n \n def Menu():\n Console.clear()\n Sound.Menu()\n Console.write(\"Добро пожаловать в NewGame!!!\", 0.07)\n print()\n #playsound('background sound.wav')\n Console.write(\"1. Новая игра.\", 0.05)\n Console.write(\"2. Выход.\", 0.05)\n print()\n\n while(True):\n a = input()\n if (a == \"1\"):\n Console.clear()\n Game.MainGame()\n elif (a == \"2\" or \"exit\"):\n exit(0)\n else:\n Console.write(\"Ошибка ввода, попробуйте еще раз\", 0.05)\n\n def MainGame():\n MainHero = Hero()\n MainHero.EnterName()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101142040","text":"import tensorflow as tf\nfrom tensorflow.keras import Sequential, Input\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dense\n\nfrom typing import List\n\nimport numpy as np\n\n\nclass MLPDiscreteActor:\n \"\"\" Actor network for discrete action space \"\"\"\n\n model: Sequential\n loss_func: SparseCategoricalCrossentropy\n optimizer: Adam\n\n def __init__(self) -> None:\n self.model_name = self.__class__.__name__\n\n def build(self,\n obs_size: int,\n action_size: int,\n hidden_units: List[int],\n learning_rate: float) -> None:\n \"\"\" Build the actor network for discrete action space \"\"\"\n\n input_layer = Input(shape=(obs_size,))\n hidden_layers = [\n Dense(hidden_unit, activation=\"relu\") for hidden_unit in hidden_units\n ]\n output_layer = Dense(action_size, activation=\"softmax\")\n\n self.model = Sequential(\n layers=[\n input_layer,\n *hidden_layers,\n output_layer\n ],\n name=self.model_name\n )\n\n self.loss_func = SparseCategoricalCrossentropy(from_logits=False)\n self.optimizer = Adam(learning_rate=learning_rate)\n\n\n def fit(\n self,\n observations: np.ndarray,\n actions: np.ndarray,\n advantages: np.ndarray,\n ) -> np.ndarray:\n \"\"\"Train the actor model.\"\"\"\n\n with tf.GradientTape() as tape:\n probs = self.model(observations, training=True)\n\n # Estimate policy gradient (Pseudocode line 6)\n action_probs = tf.gather_nd(\n probs,\n indices=np.vstack([np.arange(probs.shape[0]), actions[:, 0]]).T,\n )\n action_log_probs = tf.math.log(action_probs)\n # Minus sign changes gradient ascent into gradient descent\n actor_loss = -tf.math.reduce_mean(\n action_log_probs\n * tf.cast(tf.stop_gradient(advantages[:, 0]), tf.float32),\n )\n\n # Compute policy update (Pseudocode line 7)\n grads = tape.gradient(actor_loss, self.model.trainable_variables)\n self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))\n\n return actor_loss\n","sub_path":"sit_il/models/rl/npg/vpg/mlp_discrete_actor.py","file_name":"mlp_discrete_actor.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"594535062","text":"#-*- coding: utf-8 -*-\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nimport sys\nimport json\nfrom models import *\n\ndef query_class(request):\n classnum = request.GET.get('classnum')\n res = []\n res.append({'classnum':u'没有找到班级', 'detail':(u'创建专属%s班' % classnum)})\n for i in Class.objects.filter(classnum=classnum):\n line = {}\n detail = '%s/%s/%s' % (i.department.college.province.proname,\\\n i.department.college.colname, i.department.depname)\n line.update({'classnum':classnum, 'classid':i.classid, 'detail':detail})\n res.append(line)\n return HttpResponse(json.dumps(res))\n\ndef create_class(request):\n return HttpResponse(json.dumps([{'state':'state', 'process':'process'}]))\n\ndef query_college(request):\n proid = request.GET.get('proid')\n res = []\n for i in College.objects.filter(province=proid):\n res.append({'name':i.colname, 'link':i.colid})\n return HttpResponse(json.dumps(res)) \n\ndef query_department(request):\n colid = request.GET.get('colid')\n res = []\n for i in Department.objects.filter(college=colid):\n res.append({'name':i.depname, 'link':i.depid})\n return HttpResponse(json.dumps(res)) ","sub_path":"classmate/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101497736","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 18-3-30 下午3:00\n@Author : Longjy\n@File : ToExcel.py\n\"\"\"\nfrom UserAcademy.DataValidation.SysDataImport.SysDataImport import DBDataImport\nimport xlwt\nimport os\nimport datetime\n\n\nclass ToExcel:\n \"\"\"\n 通过DBDataImport模块从数据库导入数据,将数据写入excel保存到本地,并准备发送邮件\n \"\"\"\n dir_path = os.getcwd()\n\n def __init__(self, fileName, forecastNum=None):\n if forecastNum is None:\n self.name0 = \"%s%s.xls\" % (fileName, datetime.date.strftime(datetime.datetime.now(),\"%m%d\"))\n else:\n self.name0 = \"%s%s%s.xls\" % (fileName, datetime.date.strftime(datetime.datetime.now(),\"%m%d\"), forecastNum)\n self.fileName = os.path.join(self.dir_path, self.name0)\n\n def writeFile(self, dbdata, handList=None, sheetName=None):\n \"\"\"\n 写入excel\n :param dbdata: 数据列表\n :param handList: 表头\n :param sheetName: sheet页名称\n :return:\n \"\"\"\n if os.path.exists(self.fileName):\n os.remove(self.fileName)\n f_w = xlwt.Workbook(encoding='utf8')\n if sheetName is None:\n sheet = f_w.add_sheet(\"data\")\n else:\n sheet = f_w.add_sheet(sheetName)\n dbdataList = list(dbdata)\n if handList is not None:\n dbdataList.insert(0, handList)\n rowNum = 0\n for row in dbdataList:\n for value_num in range(0, len(row)):\n sheet.write(rowNum, value_num, row[value_num])\n rowNum += 1\n f_w.save(self.fileName)\n print('excel表写入完成', self.fileName, datetime.datetime.now())\n\n def nWriteSheet(self, *args):\n \"\"\"\n 多个列表写入多个sheet页,第一个列表为各个sheet的名称,列表和列表名称需要对应\n :param args: 第一个列表为各个sheet的名称,列表和列表名称需要对应\n :return: None\n \"\"\"\n if os.path.exists(self.fileName):\n os.remove(self.fileName)\n f_w = xlwt.Workbook(encoding='utf8')\n for sheetIndex in range(len(args[0])):\n sheet = f_w.add_sheet(args[0][sheetIndex], cell_overwrite_ok=True)\n rowNum = 0\n for row in args[sheetIndex + 1]:\n if type(row) == int:\n sheet.write(rowNum, 0, row)\n else:\n for value_num in range(0, len(row)):\n sheet.write(rowNum, value_num, row[value_num])\n rowNum += 1\n f_w.save(self.fileName)\n\n def setStyle(self, isTitle: int):\n \"\"\"\n 设置单元格格式\n :param isTitle: 判断是否是标题\n :return: 单元格格式对象\n \"\"\"\n style = xlwt.XFStyle()\n if isTitle == 0:\n font = xlwt.Font()\n font.bold = False\n font.name = '微软雅黑'\n font.colour_index = 2\n font.height = 200\n style.font = font\n elif isTitle == 1:\n font = xlwt.Font()\n font.bold = True\n font.name = '微软雅黑'\n font.height = 210\n font.colour_index = 10\n style.font = font\n elif isTitle == 2:\n font = xlwt.Font()\n font.bold = False\n font.name = '微软雅黑'\n font.height = 200\n style.font = font\n\n borders = xlwt.Borders()\n borders.left = xlwt.Borders.THIN\n borders.right = xlwt.Borders.THIN\n borders.top = xlwt.Borders.THIN\n borders.bottom = xlwt.Borders.THIN\n style.borders = borders\n return style\n\n def nListWrite(self, *args):\n \"\"\"\n 将多个列表写到一个sheet中,按顺序上下排列,列表和列表名称需要对应\n :param args: 第一个列表为各个sheet的名称,列表和列表名称需要对应\n :return: None\n \"\"\"\n if os.path.exists(self.fileName):\n os.remove(self.fileName)\n\n rowNum = 0\n style0 = self.setStyle(isTitle=0)\n style1 = self.setStyle(isTitle=1)\n style2 = self.setStyle(isTitle=2)\n f_w = xlwt.Workbook(encoding='utf8')\n sheet = f_w.add_sheet(\"data\", cell_overwrite_ok=True)\n for index0 in range(len(args[0])):\n rowNum += 2\n if index0 + 1 <= len(args[0]):\n sheet.write(rowNum, 0, args[0][index0], style0)\n rowNum += 1\n for row in args[index0 + 1]:\n for value_num in range(0, len(row)):\n if index0 == 0:\n sheet.write(rowNum, value_num, row[value_num], style1)\n else:\n sheet.write(rowNum, value_num, row[value_num], style2)\n rowNum += 1\n f_w.save(self.fileName)\n\n def NsheetNlist(self, **kwargs):\n \"\"\"\n 将多个表写入到多个sheet中, 第一个元素的key必须是sheetNames,sheetNames的value是一个字典,\n 里面包含了其他要写到各sheet页的sheet名称;\n 如果一个sheet中有多个列表,每个列表要的第一个item 为列表的标题,第二个元素为列表的数据,第三个为列表的style对象;\n 如果一个sheet中只有一个列表,第一个元素为列表的数据,第二个元素为列表的style对象;\n 列表的style对象可以省略\n :param kwargs: {sheetNames: {sheet0: sheetName0, sheet1: sheetName1},\n sheet0: [[title0, l0, sty0], [title1, l1, sty1], [title2, l2],],\n sheet1: [l3, sty3]}\n :return: None\n \"\"\"\n if os.path.exists(self.fileName):\n os.remove(self.fileName)\n f_w = xlwt.Workbook(encoding='utf8')\n for sname in kwargs['sheetNames']:\n rowNum = 0\n sheet = f_w.add_sheet(kwargs['sheetNames'][sname], cell_overwrite_ok=True)\n if len(kwargs[sname]) > 1:\n for lst in kwargs[sname]:\n if len(lst[1]) == 1:\n rowNum += 2\n sheet.write(rowNum, 0, lst[0])\n rowNum += 1\n sheet.write(rowNum, 0, lst[1][0][0], lst[2])\n rowNum += 2\n else:\n for item in lst:\n if type(item) == str:\n sheet.write(rowNum, 0, item)\n elif type(item) == list:\n for row in range(len(item)):\n for index in range(len(item[row])):\n if len(lst) == 2:\n sheet.write(rowNum, index, item[row][index])\n if len(lst) > 2:\n sheet.write(rowNum, index, item[row][index], lst[2])\n rowNum += 1\n rowNum += 1\n else:\n rowNum = 0\n for row in range(len(kwargs[sname][0][0])):\n for index in range(len(kwargs[sname][0][0][row])):\n if len(kwargs[sname][0]) == 1:\n sheet.write(rowNum, index, kwargs[sname][0][0][row][index])\n if len(kwargs[sname][0]) > 1:\n sheet.write(rowNum, index, kwargs[sname][0][0][row][index], kwargs[sname][0][1])\n rowNum += 1\n f_w.save(self.fileName)\n\n\n\nif __name__ == '__main__':\n dbdata = DBDataImport()\n data0 = dbdata.YesterdaySaleData()\n handList = ['日期', '产品id', '产品名称', '一级品类id',\n '一级品类名称', '二级品类id', '二级品类名称',\n '三级品类id', '三级品类名称', '总销售数量', '总销售金额']\n fileName = 'sdf'\n excel0 = ToExcel(fileName=fileName)\n excel0.writeFile(data0, handList=handList)\n","sub_path":"UserAcademy/DataValidation/SysDataImport/ToExcel.py","file_name":"ToExcel.py","file_ext":"py","file_size_in_byte":8109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"633334318","text":"#!/usr/bin/env python3\n'''\nCreated on 2012-5-26\n\n@author: hewenxiang\n'''\n\nimport threading\nimport socketserver\nimport json\nimport uuid \nimport datetime\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nimport smtplib\nfrom configparser import ConfigParser\nimport os.path\nimport psycopg2\nimport csv\nimport subprocess\nfrom uuid import uuid4\nimport gzip\nimport sys\nimport traceback\n\nclass ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n \n \n def handle(self):\n self.conn = psycopg2.connect(host=HOST, port=PORT, database=DB,\n user=USER, password=PASS)\n self.cur = self.conn.cursor()\n self.data = \"\"\n #cur_thread = threading.current_thread()\n while True:\n buf = str(self.request.recv(1024), 'utf-8')\n if not len(buf):\n break\n self.data += buf\n try:\n self.data = json.loads(self.data)\n self.ready_rate()\n self.compress_file()\n self.get_subject_content();\n self.send_mail()\n except smtplib.SMTPException as e:\n self.status = 2\n print(e)\n traceback.print_exc()\n except psycopg2.DatabaseError as e:\n self.status = 1\n print(e)\n traceback.print_exc()\n except Exception as e:\n self.status = 3\n print(e)\n traceback.print_exc()\n else:\n self.status = 0\n finally:\n self.logging()\n self.conn.commit()\n self.cur.close()\n self.conn.close()\n \n def compress_file(self):\n gz_path = os.path.join(os.path.dirname(__file__), 'files',\"{0}_{1}.csv.gz\".format(datetime.date.today(), uuid.uuid4()))\n with open(self.filepath, 'rb') as fhandle:\n with gzip.open(gz_path, 'wb') as ghandle:\n ghandle.writelines(fhandle)\n self.filepath = gz_path\n\n gz_path = os.path.join(os.path.dirname(__file__), 'files',\"{0}_{1}.csv.gz\".format(datetime.date.today(), uuid.uuid4()))\n with open(self.filepath_changed, 'rb') as fhandle:\n with gzip.open(gz_path, 'wb') as ghandle:\n ghandle.writelines(fhandle)\n self.filepath_changed = gz_path\n \n def ready_rate(self):\n self.filepath = \"/tmp/exports/rate_{0}.csv\".format(uuid.uuid4())\n codenames_list = [ \"'{}'\".format(codename) for codename in self.data['code_names']\n if codename != '']\n codenames = ','.join(codenames_list)\n \n columns_fields = {\n 'code' : 'code',\n 'inter_rate' : 'inter_rate as interstate_rate',\n 'intra_rate' : 'intra_rate as intrastate_rate',\n 'new_rate' : 'rate',\n 'interval' : 'interval',\n 'min_time' : 'min_time',\n 'effective_date' : 'effective_date',\n 'country' : 'country',\n 'code_name' : 'code_name',\n }\n \n print(self.data['columns'])\n columns = [columns_fields[column] for column in self.data['columns'] if column not in ('status','current_rate')]\n column_query = ','.join(columns)\n \n is_header = '' if 'status' in self.data['columns'] else ' HEADER'\n \n sql = \"\"\"\n COPY (\n SELECT\n distinct\n {4}\n FROM rate\n where rate_table_id = {3} and code_name in ({0}) AND ((effective_date <= '{1}' AND end_date IS NULL)\n OR \n (effective_date <= '{1}' AND end_date >= '{1}'))\n ) TO '{2}' WITH DELIMITER AS ',' CSV {5}\n \"\"\".format(codenames, self.data['effective_date'], self.filepath, self.data['rate_table'], column_query, is_header)\n self.cur.execute(sql)\n\n if 'status' in self.data['columns']:\n self.filepath_current = self.filepath + \".current\"\n sql = \"\"\"\n COPY (\n SELECT \n distinct\n code, rate\n from rate\n where rate_table_id = {0} and code_name in ({1}) AND ((effective_date <= CURRENT_TIMESTAMP AND end_date IS NULL)\n OR \n (effective_date <= CURRENT_TIMESTAMP AND end_date >= CURRENT_TIMESTAMP))\n ) TO '{2}' WITH DELIMITER AS ',' CSV\"\"\".format(self.data['rate_table'], codenames, self.filepath_current)\n self.cur.execute(sql)\n self.insert_status()\n \n def insert_status(self):\n \"\"\"\n join -t ',' -a1 -j1 1 -j2 1 test1.csv test2.csv\n \"\"\"\n columns = self.data['columns'][:]\n print(columns)\n print(self.filepath_current)\n status_index = self.data['columns'].index('status')\n current_rate_index2 = self.data['columns'].index('current_rate')\n del self.data['columns'][status_index]\n del self.data['columns'][current_rate_index2]\n #self.data['columns'].remove('status')\n index = self.data['columns'].index('code') + 1\n effective_rate_index = self.data['columns'].index('new_rate')\n current_rate_index = len(self.data['columns'])\n print(current_rate_index, effective_rate_index)\n self.filepath_new = os.path.join(os.path.dirname(__file__), 'files', str(uuid4()) + '.csv')\n cmd = \"join -t ',' -a1 -j1 {0:d} -j2 1 {1:s} {2:s} > {3:s} 2>&1\".format(index, self.filepath, self.filepath_current, self.filepath_new)\n print(cmd)\n subprocess.call(cmd, shell=True)\n self.filepath = os.path.join(os.path.dirname(__file__), 'files', str(uuid4()) + '.csv')\n self.filepath_changed = os.path.join(os.path.dirname(__file__), 'files', str(uuid4()) + '.csv')\n with open(self.filepath_new) as reader_handle, open(self.filepath, \"w\" , newline='') as write_handle, open(self.filepath_changed, \"w\", newline='') as write_handle_changed:\n reader = csv.reader(reader_handle)\n writer = csv.writer(write_handle)\n writer_changed = csv.writer(write_handle_changed)\n writer.writerow(columns)\n writer_changed.writerow(columns)\n print(columns)\n for row in reader:\n print(row)\n if len(row) == current_rate_index:\n row.insert(status_index, 'new')\n row.insert(current_rate_index2, '')\n writer_changed.writerow(row)\n elif abs(row[current_rate_index] - row[effective_rate_index]) < 0.00001:\n row.insert(current_rate_index2, row.pop(current_rate_index))\n row.insert(status_index, 'current')\n elif row[current_rate_index] > row[effective_rate_index]:\n row.insert(current_rate_index2, row.pop(current_rate_index))\n row.insert(status_index, 'decrease')\n writer_changed.writerow(row)\n else:\n row.insert(current_rate_index2, row.pop(current_rate_index))\n row.insert(status_index, 'increase')\n writer_changed.writerow(row)\n writer.writerow(row)\n print(\"Done...\")\n \n \n \n \n def send_mail(self):\n if self.data['send_method'] == '1':\n carrier_list = [ carrier for carrier in self.data['carrier']\n if carrier != '']\n carriers = ','.join(carrier_list)\n sql = \"\"\"SELECT rate_email FROM client WHERE client_id IN ({0})\"\"\".format(carriers)\n self.cur.execute(sql)\n data = self.cur.fetchall()\n mail_to_list = [mail for mail, in data if mail != '']\n elif self.data['send_method'] == '0':\n mail_to_list = [self.data['email'],]\n else:\n with open(self.data['myfile_guid'], \"rt\") as handle:\n mail_to_list = [line.strip() for line in handle if line.strip()]\n\n #if self.data['cc']:\n # mail_to_list.append(self.data['cc'])\n \n sql = \"\"\"SELECT smtphost,smtpport,emailusername,emailpassword FROM\n system_parameter\"\"\"\n self.cur.execute(sql)\n smtp_host, smtp_port, smtp_user, smtp_pass = self.cur.fetchone()\n\n for mail_to in mail_to_list:\n\n msg = MIMEMultipart()\n msg['Subject'] = self.subject\n msg['From'] = smtp_user\n msg['to'] = mail_to\n msg['cc'] = self.data['cc']\n \n file_name = os.path.basename(self.filepath)\n part = MIMEText(self.content, 'plain') \n msg.attach(part)\n \n attache = MIMEApplication(open(self.filepath, 'rb').read())\n #attache['Content-Type'] = 'application/octet-stream'\n attache['Content-Disposition'] = 'attrachment; filename=\"%s\"' % (self.data['filename'] + \"_full.csv.gz\")\n msg.attach(attache)\n \n attache2 = MIMEApplication(open(self.filepath_changed, 'rb').read())\n attache2['Content-Disposition'] = 'attrachment; filename=\"%s\"' % (self.data['filename'] + \"_changed.csv.gz\")\n msg.attach(attache2)\n \n smtp = smtplib.SMTP(smtp_host, smtp_port)\n #smtp.set_debuglevel(1) #开启发送邮件debug模式\n smtp.ehlo()\n smtp.login(smtp_user, smtp_pass)\n smtp.sendmail(smtp_user, [mail_to, self.data['cc']], msg.as_string())\n smtp.quit() \n \n \n \n def get_subject_content(self):\n sql = \"SELECT subject, content FROM send_rate_template WHERE id = {0:d}\".format(int(self.data['template']))\n self.cur.execute(sql)\n self.subject, self.content = self.cur.fetchone()\n \n def logging(self):\n sql = \"INSERT INTO rate_send_logging (data, log_datetime, status, file) values (%s, CURRENT_TIMESTAMP(0), %s, %s)\"\n self.cur.execute(sql, (str(self.data), self.status, self.filepath))\n \n \nclass ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n pass\n\n\ndef init_config():\n global HOST, PORT, DB, USER, PASS, SOCK_HOST, SOCK_PORT\n conf_path = os.path.join(os.path.dirname(__file__), 'config.ini')\n # read config db info\n cfg = ConfigParser()\n cfg.read(conf_path)\n HOST = cfg.get('db', 'host')\n PORT = cfg.get('db', 'port')\n DB = cfg.get('db', 'database')\n USER = cfg.get('db', 'user')\n PASS = cfg.get('db', 'password')\n SOCK_HOST = cfg.get('sock', 'sock_host')\n SOCK_PORT = int(cfg.get('sock', 'sock_port'))\n \n\n \nif __name__ == \"__main__\":\n init_config()\n server = ThreadedTCPServer((SOCK_HOST, SOCK_PORT), ThreadedTCPRequestHandler)\n server_thread = threading.Thread(target=server.serve_forever)\n server_thread.setDaemon(True)\n server_thread.start()\n server.serve_forever()\n","sub_path":"frontend/script/class4_send_rate.py","file_name":"class4_send_rate.py","file_ext":"py","file_size_in_byte":10928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"528197661","text":"\n# (deck) トランプを作る: 得点を数えられるようにする\n# (deal) トランプを二枚配る: 絵札(J,Q,K)で表示させる\n# (hand) プレイヤーに配られたカードを記録する\n# (hit) ヒットの場合 hand を追加する\n# (game) 実際にプレーする\n# (total) プレイヤーの合計を求める\n# TODO (result) 勝ち負けを表記する\n# (play_again) もう一度プライする\n\nimport random\n\ndeck = [1,2,3,4,5,6,7,8,9,10,11,12,13] * 4\n\ndef deal():\n hand = []\n for i in range(2):\n random.shuffle(deck)\n card = deck.pop()\n if card == 11:\n card = \"J\"\n if card == 12:\n card = \"Q\"\n if card == 13:\n card = \"K\"\n if card == 1:\n card = \"A\"\n hand.append(card)\n return hand\n \ndef hit(hand):\n \n random.shuffle(deck)\n card = deck.pop()\n if card == 11:\n card = \"J\"\n if card == 12:\n card = \"Q\"\n if card == 13:\n card = \"K\"\n if card == 1:\n card = \"A\"\n hand.append(card)\n return hand\n\n\ndef total(hand):\n score = 0\n for card in hand:\n if card == \"J\" or card == \"Q\" or card == \"K\":\n score = score+10\n elif card == \"A\":\n if score >= 11:\n score += 1\n else:\n score += 11\n else:\n score += card\n \n return score\n \n\ndef play_again():\n again = input(\"もう一度プレーしますか? (y/n):\")\n if again == \"y\" or again == \"Y\":\n game()\n return\n else:\n print(\"お疲れ様でした\")\n exit()\n \n \ndef result(dealer_hand, player_hand):\n if total(player_hand) > total(dealer_hand):\n print(f\"\\nディーラーの合計は{total(dealer_hand)}あなたの合計は{total(player_hand)}です。You Win!\")\n elif total(dealer_hand) > total(player_hand):\n print(f\"\\nディーラーの合計は{total(dealer_hand)}あなたの合計は{total(player_hand)}です。You Lose....\")\n\ndef game():\n dealer_hand = deal()\n player_hand = deal()\n print(f\"ディーラーカードの{dealer_hand[0]}です\")\n print(f\"プレイヤーのカードは{player_hand}合計は{total(player_hand)}です\")\n \n \n choice = 0\n \n while choice != quit:\n choice = input(\"ヒットしますか? スタンドしますか? (HIT/STAND):\").lower()\n if choice ==\"hit\":\n hit(player_hand)\n print(f\"\\nあなたに {player_hand[-1]} が配られ、カードは {player_hand}です。 合計は {total(player_hand)} です\")\n if total(player_hand) > 21:\n print(\"あなたは21を超えてしました。You Lose.....\")\n choice = quit\n \n elif choice == \"stand\":\n print(f\"\\nディーラーの2枚目のカードは{dealer_hand[1]} 合計は{total(dealer_hand)}です。\")\n while total(dealer_hand) < 17:\n hit(dealer_hand)\n print(f\"ディーラーに {dealer_hand[-1]} のカードが配られ、カードは {dealer_hand}です。 合計は {total(dealer_hand)} です\")\n if total(dealer_hand) > 21:\n print(\"ディーラーは21を超えてしました。You Win\")\n choice = quit\n if total(dealer_hand) <= 21:\n result(dealer_hand, player_hand)\n choice = quit\n \ngame()\nplay_again()\n","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36468531","text":"import vrep\r\nimport sys\r\nimport math\r\nimport numpy as np\r\n\r\nvrep.simxFinish(-1)\r\nr=[[1.5, 6.8], [1.4331414059619192, 6.868538765892675], [-1.6064300122745405, 5.986789631594058], [-2.0092298657086225, 5.614086365025141], [-2.686519892090655, 4.897192170902571], [-3.0950828616208685, 4.492526509371485], [-4.770610672014685, 2.573660911430492], [-5.8039380948073624, 1.311042619328609], [-6.792951845413683, 0.03204117765496167], [-9, -1]]\r\n#r.reverse()\r\ntext_file = open(\"x.txt\", \"w\")\r\ntext_file1 = open(\"x.txt\", \"w\")\r\nfor i in range(len(r)):\r\n r[i][0]=(r[i][0]+12.5)*10\r\n r[i][1]=(r[i][1]+7.5)*10\r\n text_file.write(str(r[i][0])+'\\n')\r\n text_file1.write(str(r[i][1])+'\\n')\r\n#print(r)\r\ntext_file.close()\r\ntext_file1.close()\r\nclientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) # Connect to V-REP\r\nif clientID!=-1:\r\n print ('Connected to remote API server')\r\nelse:\r\n print('Connection unsuccessful!')\r\n sys.exit(\"Could not connect\")\r\n \r\n\r\n#errorCode,left_motor_handle=vrep.simxGetObjectHandle(clientID,'wheel_left_joint',vrep.simx_opmode_blocking)\r\n#errorCodeR,right_motor_handle=vrep.simxGetObjectHandle(clientID,'wheel_right_joint',vrep.simx_opmode_blocking)\r\n#returncode,bot = vrep.simxGetObjectHandle(clientID,'Turtlebot2_target', vrep.simx_opmode_oneshot_wait)\r\n#err,simtime = vrep.simxGetFloatSignal(clientID,'Turtlebot2_simulation_time',vrep.simx_opmode_streaming)\r\n##returnCode = vrep.simxSetObjectPosition(clientID,bot,h,-1,vrep.simx_opmode_oneshot)\r\n#returnCode=vrep.simxSetObjectPosition(clientID,bot,-1,[100,100,0],vrep.simx_opmode_buffer)\r\n#\r\n#\r\n#vrep.simxFinish(-1)\r\n \r\n[s,left_wheel] = vrep.simxGetObjectHandle(clientID,'wheel_left_joint',vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\n[s,right_wheel]=vrep.simxGetObjectHandle(clientID,'wheel_right_joint',vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\n[s,reference_frame]=vrep.simxGetObjectHandle(clientID,'Dummy',vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\n[s,turtlebot]=vrep.simxGetObjectHandle(clientID,'Turtlebot2',vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\n[s,start_position]=vrep.simxGetObjectPosition(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\n \r\n\r\ns = vrep.simxSetJointTargetVelocity(clientID,left_wheel,1,vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\ns = vrep.simxSetJointTargetVelocity(clientID,right_wheel,0.5,vrep.simx_opmode_oneshot_wait)\r\nif s != 0:\r\n print(\"Error\")\r\n\r\nfor i in range(1,len(r)):\r\n print(r[i])\r\n [_,position]=vrep.simxGetObjectPosition(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait)\r\n [s,theta]=vrep.simxGetObjectOrientation(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n theta_req = math.atan2(r[i][1]-position[1],r[i][0]-position[0])\r\n# print('i',i)\r\n\r\n while abs(theta[2] - theta_req)> 0.5:\r\n# print(theta[2],' ', theta_req,' ,diff',abs(theta[2] - theta_req))\r\n if theta[2] < theta_req:\r\n if(np.abs(theta[2] - theta_req)<1):\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,-1,vrep.simx_opmode_oneshot_wait);\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,1,vrep.simx_opmode_oneshot_wait);\r\n\r\n else:\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,-2,vrep.simx_opmode_oneshot_wait);\r\n\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,2,vrep.simx_opmode_oneshot_wait);\r\n \r\n if s != 0:\r\n print(\"Error\");\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,2,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n else:\r\n if(np.abs(theta[2] - theta_req)<1):\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,1,vrep.simx_opmode_oneshot_wait);\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,-1,vrep.simx_opmode_oneshot_wait);\r\n\r\n else:\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,2,vrep.simx_opmode_oneshot_wait);\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,-2,vrep.simx_opmode_oneshot_wait);\r\n if s != 0:\r\n print(\"Error\")\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,-2,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n \r\n [s,theta]=vrep.simxGetObjectOrientation(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\");\r\n# print(abs(theta[2] - theta_req)) \r\n [s,position]=vrep.simxGetObjectPosition(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait);\r\n if s != 0:\r\n print(\"Error\")\r\n \r\n k=1\r\n while 1:\r\n k=k+1\r\n [s,position]=vrep.simxGetObjectPosition(clientID, turtlebot,reference_frame,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n \r\n if abs(position[0] - r[i][0]) < 0.5 and abs(position[1] - r[i][1]) < 0.5 :\r\n break\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,10,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,10,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n\r\n if k>10:\r\n print(\"Here\")\r\n break\r\n \r\n\r\n print(\"Location Reached\");\r\n s = vrep.simxSetJointTargetVelocity(clientID,left_wheel,0,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n s = vrep.simxSetJointTargetVelocity(clientID,right_wheel,0,vrep.simx_opmode_oneshot_wait)\r\n if s != 0:\r\n print(\"Error\")\r\n \r\nvrep.simxFinish(-1);\r\n","sub_path":"Comparative Study of Planning Algorithms in Maze Environment/Codes/RRTStar/VREP/testVrep5.py","file_name":"testVrep5.py","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"440973257","text":"import socket\nimport pyaudio\nimport sounddevice as sd\n\n# Socket\nHOST = socket.gethostbyname('mustin.workisboring.com')\nPORT = 5000\n\n# Audio\nCHUNK = 1024 * 4\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\np = pyaudio.PyAudio()\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True)\n\n#sd.play(stream, RATE)\n\nprint(\"Recording\")\n\nwith socket.socket() as client_socket:\n client_socket.connect((HOST, PORT))\n while True:\n data = stream.read(CHUNK)\n client_socket.send(data)\n","sub_path":"streamAudioClient.py","file_name":"streamAudioClient.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"534492363","text":"import psycopg2\nimport json\nimport sqlalchemy\nfrom sqlalchemy import MetaData, Table, Column\nfrom sqlalchemy.sql import text\n\nfrom datetime import datetime\nfrom flask import jsonify\nfrom collections import namedtuple\nfrom db.database import pg_session\nfrom lib import utils\n\n\n# Type Convert\ndef Convert(value):\n return value\n #if type(value) is datetime:\n # return value.strftime(\"%Y-%m-%d %H:%M:%S\")\n #else: \n # return value\n\n# Dict\ndef Query(sql, **params):\n try:\n comment = text(sql)\n session = pg_session()\n proxy = session.execute(comment, params)\n descrip = proxy._cursor_description()\n cur = proxy.fetchall()\n data = [dict((descrip[i][0], Convert(value)) \\\n for i, value in enumerate(row)) for row in cur]\n \n #return {'status':200, 'message': 'OK', 'data': data}\n return data\n except sqlalchemy.exc.SQLAlchemyError as e:\n error, = e.args\n utils.logger.error(error)\n raise e\n finally:\n session.close()\n \n# Start Transaction\ndef StartTransaction():\n try:\n session = pg_session()\n return session\n except sqlalchemy.exc.DatabaseError as e:\n error, = e.args\n utils.logger.error('pgdb error:{0}'.format(error))\n raise e\n\n# Rollback Transaction\ndef Rollback(trans):\n try:\n trans.rollback()\n trans.close()\n return True\n except sqlalchemy.exc.DatabaseError as e:\n error, = e.args\n utils.logger.error('pgdb error:{0}'.format(error))\n trans.close()\n raise e \n\n# Commit Transaction\ndef Commit(trans):\n try:\n trans.commit()\n trans.close()\n return True\n except sqlalchemy.exc.DatabaseError as e:\n error, = e.args\n utils.logger.error('pgdb error:{0}'.format(error))\n trans.rollback()\n trans.close()\n raise e \n \n# Execute\ndef ExecSQL(trans, sql, **params):\n try:\n comment = text(sql)\n proxy = trans.execute(comment, params)\n return True \n except sqlalchemy.exc.DatabaseError as e:\n error, = e.args\n utils.logger.error('pgdb error:{0}'.format(error))\n raise e ","sub_path":"db/dbpg.py","file_name":"dbpg.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459473372","text":"\"\"\"\nGiven a string, find the length of the longest substring without repeating characters.\n\nExamples:\n\nGiven \"abcabcbb\", the answer is \"abc\", which the length is 3.\n\nGiven \"bbbbb\", the answer is \"b\", with the length of 1.\n\nGiven \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\"\"\"\n\nimport unittest\n\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = 0\n foundWord = []\n for c in s:\n o = foundWord[-1] if len(foundWord) > 0 else None\n if o is None:\n foundWord.append(c)\n continue\n if o == c or c in foundWord:\n if len(foundWord) > l:\n l = len(foundWord)\n if o == c:\n foundWord = []\n foundWord.append(c)\n elif c in foundWord:\n foundWord = foundWord[foundWord.index(c)+1:]\n foundWord.append(c)\n else:\n foundWord.append(c)\n if len(foundWord) > l:\n return len(foundWord)\n return l\n\nclass TestStringMethods(unittest.TestCase):\n sol = Solution()\n def test(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"bbbb\"), 1)\n def test2(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"abcabcbb\"), 3)\n def test3(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"pwwkew\"), 3)\n def test4(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"c\"), 1)\n def test5(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"dvdf\"), 3)\n def test6(self):\n self.assertEqual(self.sol.lengthOfLongestSubstring(\"abcabcbb\"), 3)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Longest_Substring_Without_Repeating_Characters.py","file_name":"Longest_Substring_Without_Repeating_Characters.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"580485597","text":"import json\nimport random\nimport re\nimport string\nimport threading\nimport time\nimport queue\n\nfrom bs4 import BeautifulSoup\n\nfrom ClipboardWatcher import ClipboardWatcher, log_clipboard\nimport requests\n\nPREVIOUS_STATUS_CODE = None\n\nSTATUS_CODE_OK = 1\nSTATUS_CODE_SKIP = 2\nSTATUS_CODE_REPEAT = 3\n\nAPI_KEY = None\n\n\ndef parse_clipboard(url):\n if url.startswith(\"http://\") or url.startswith(\"https://\"):\n q.put(url)\n return True\n return False\n\n\ndef queue_processor(i, queue_obj):\n while True:\n current_url = queue_obj.get()\n print(\"Looking up \" + current_url)\n try:\n response = lookup_url(current_url)\n except DailyLimitReachedException:\n response = lookup_url(current_url, get_new_api_key())\n f = open(\"links_saucenao.txt\", \"a\")\n url_to_use = None\n done = False\n for result in response['results']:\n if done:\n break\n similarity = float(result['header']['similarity'])\n if similarity > 80:\n for url in result['data']['ext_urls']:\n if url.startswith(\"https://www.pixiv.net\"):\n response = requests.get(url)\n if not response.status_code == 404:\n print(\"Found sauce: \" + url)\n url_to_use = url\n done = True\n break\n elif url.startswith(\"https://danbooru.donmai.us/post/show/\"):\n response = requests.get(url)\n if not response.status_code == 404:\n print(\"Found sauce: \" + url)\n url_to_use = url\n done = True\n break\n else:\n continue\n\n if url_to_use:\n f.write(url_to_use + \"\\n\")\n else:\n f.write(current_url + \"\\n\")\n\n f.close()\n print(\"Done\")\n queue_obj.task_done()\n\n\ndef main():\n watcher = ClipboardWatcher(parse_clipboard,\n log_clipboard,\n 0.5)\n watcher.start()\n\n for i in range(1):\n queue_worker = threading.Thread(target=queue_processor, args=(i, q))\n queue_worker.start()\n\n while True:\n try:\n print(\"Waiting for changed clipboard...\")\n time.sleep(10)\n except KeyboardInterrupt:\n watcher.stop()\n break\n\n\ndef get_http_params(url: str, api_key=None):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/63.0.3239.84 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Language': 'en-DE,en-US;q=0.9,en;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'DNT': '1',\n 'Connection': 'keep-alive'\n }\n\n params = {\n 'file': '',\n 'Content-Type': 'application/octet-stream',\n # parameters taken from form on main page: https://saucenao.com/\n 'url': url,\n 'frame': 1,\n 'hide': 0,\n # parameters taken from API documentation: https://saucenao.com/user.php?page=search-api\n 'output_type': 2,\n 'db': 999,\n }\n\n if api_key:\n params['api_key'] = api_key\n\n return params, headers\n\n\ndef randomString(stringLength=10):\n \"\"\"Generate a random string of fixed length \"\"\"\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\n\n\ndef get_new_api_key():\n request = requests.get(\"https://saucenao.com/user.php\")\n soup = BeautifulSoup(request.text, features=\"html.parser\")\n token = soup.find(\"input\", {\"name\": \"token\"})['value']\n username = randomString()\n password = randomString()\n params = {\n 'username': username,\n 'email': username + \"@gmail.com\",\n 'password': password,\n 'password_conf': password,\n 'token': token\n }\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/63.0.3239.84 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Language': 'en-DE,en-US;q=0.9,en;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'DNT': '1',\n 'Connection': 'keep-alive'\n }\n\n cookies = {'token': token}\n\n register_response = requests.post(url='https://saucenao.com/user.php?page=register', data=params, headers=headers,\n cookies=cookies)\n if register_response.status_code == 200:\n api_page = requests.get(\"https://saucenao.com/user.php?page=search-api\", cookies=register_response.cookies)\n if api_page.status_code == 200:\n soup = BeautifulSoup(api_page.text, features=\"html.parser\")\n api_key_search = soup.find_all(text=re.compile(\"^api key: \"))\n api_key = api_key_search[0].partition(\": \")[2]\n return api_key\n\n\ndef lookup_url(url: str, api_key=None):\n global PREVIOUS_STATUS_CODE\n params, headers = get_http_params(url, api_key)\n link = requests.post(url='http://saucenao.com/search.php', params=params, headers=headers)\n\n code, msg = verify_status_code(link, url)\n\n if code == 2:\n print(msg)\n return json.dumps({'results': []})\n elif code == 3:\n if not PREVIOUS_STATUS_CODE:\n PREVIOUS_STATUS_CODE = code\n print(\n \"Received an unexpected status code (message: {msg}), repeating after 10 seconds...\".format(msg=msg)\n )\n time.sleep(10)\n return self.lookup_url(url)\n else:\n raise UnknownStatusCodeException(msg)\n else:\n PREVIOUS_STATUS_CODE = None\n\n return json.loads(link.text)\n\n\ndef verify_status_code(request_response: requests.Response, url: str) -> tuple:\n global STATUS_CODE_OK, STATUS_CODE_REPEAT, STATUS_CODE_SKIP\n if request_response.status_code == 200:\n return STATUS_CODE_OK, ''\n\n elif request_response.status_code == 429:\n if 'user\\'s rate limit' in request_response.text:\n msg = \"Search rate limit reached\"\n return STATUS_CODE_REPEAT, msg\n if 'limit of 150 searches' in request_response.text:\n raise DailyLimitReachedException('Daily search limit for unregistered users reached')\n elif 'limit of 300 searches' in request_response.text:\n raise DailyLimitReachedException('Daily search limit for basic users reached')\n else:\n raise DailyLimitReachedException('Daily search limit reached')\n elif request_response.status_code == 403:\n raise InvalidOrWrongApiKeyException(\"Invalid or wrong API key\")\n elif request_response.status_code == 413:\n msg = \"Payload too large, skipping file: {0:s}\".format(url)\n return STATUS_CODE_SKIP, msg\n else:\n msg = \"Unknown status code: {0:d}\".format(request_response.status_code)\n return STATUS_CODE_REPEAT, msg\n\n\nclass DailyLimitReachedException(Exception):\n pass\n\n\nclass InvalidOrWrongApiKeyException(Exception):\n pass\n\n\nclass UnknownStatusCodeException(Exception):\n pass\n\n\nif __name__ == \"__main__\":\n q = queue.Queue()\n main()\n","sub_path":"sauce_nao_lookup.py","file_name":"sauce_nao_lookup.py","file_ext":"py","file_size_in_byte":7492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"332003765","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\n\nimport textract\n\n\ndef walkFile(file):\n for root, dirs, files in os.walk(file):\n\n # 遍历文件\n for f in files:\n yield os.path.join(root, f)\n\n\n\n\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.pdfparser import PDFParser\nfrom pdfminer.pdfdocument import PDFDocument\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.pdfpage import PDFTextExtractionNotAllowed\nfrom pdfminer.pdfinterp import PDFResourceManager\nfrom pdfminer.pdfinterp import PDFPageInterpreter\nfrom pdfminer.layout import *\nimport re\n\n\ndef pdf2txt(fn):\n #打开一个pdf文件\n # fn = r'C:\\Users\\1TSH4W2\\Desktop/有三AI+视觉算法工程师成长指导手册_20190812_192257.pdf'\n fp = open(fn, 'rb')\n #创建一个PDF文档解析器对象\n parser = PDFParser(fp)\n #创建一个PDF文档对象存储文档结构\n #提供密码初始化,没有就不用传该参数\n #document = PDFDocument(parser, password)\n document = PDFDocument(parser)\n #检查文件是否允许文本提取\n if not document.is_extractable:\n raise PDFTextExtractionNotAllowed\n #创建一个PDF资源管理器对象来存储共享资源\n #caching = False不缓存\n rsrcmgr = PDFResourceManager(caching = False)\n # 创建一个PDF设备对象\n laparams = LAParams()\n # 创建一个PDF页面聚合对象\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n #创建一个PDF解析器对象\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n #处理文档当中的每个页面\n\n # doc.get_pages() 获取page列表\n #for i, page in enumerate(document.get_pages()):\n #PDFPage.create_pages(document) 获取page列表的另一种方式\n replace=re.compile(r'\\s+')\n # 循环遍历列表,每次处理一个page的内容\n for page in PDFPage.create_pages(document):\n interpreter.process_page(page)\n # 接受该页面的LTPage对象\n layout=device.get_result()\n # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象\n # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等\n for x in layout:\n #如果x是水平文本对象的话\n if(isinstance(x,LTTextBoxHorizontal)):\n text=re.sub(replace,'',x.get_text())\n if len(text)!=0:\n print(text)\n\n\n\ndata_dir =None\n\nfor name in walkFile(data_dir):\n try:\n # text = textract.process(name)\n # text = text.decode('utf-8')\n pdf2txt(name)\n # print(text)\n except Exception as e:\n print(e)\n","sub_path":"utils/pdf_to_txt.py","file_name":"pdf_to_txt.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"64576273","text":"def draw_line(width,edge,filling):\r\n print(filling.join([edge]*(width+1)))\r\n \r\ndef draw_board (width,height):\r\n draw_line(width,\" \",\"_\")\r\n \r\n for i in range(height):\r\n draw_line(width,\"|\",\"_\")\r\n print(\"\\n\")\r\n \r\ndef display_winner(player):\r\n if player==0:\r\n print(\"Tie\")\r\n \r\n else:\r\n print(\"Player\" + str(player)+\"wins!\")\r\n \r\ndef check_row_winner(row):\r\n #return the player number that wins for that row. If there is no winner return 0.\r\n if row[0]==row[1] and row[1]==row[2]:\r\n return row[0]\r\n return 0\r\n\r\ndef get_col(game,col_number):\r\n return[game[x][col_number] for x in range(3)]\r\n\r\ndef get_row(game,row_number):\r\n return game[row_number]\r\n\r\ndef check_winner(game):\r\n game_slices=[]\r\n for index in range(3):\r\n game_slices.append(get_row(game,index))\r\n game_slices.append(get_col(game, index))\r\n \r\n \r\n down_diagonal=[game[x][x] for x in range(3)]\r\n up_diagonal=[game[0][2],game[1][1],game[2][0]]\r\n game_slices.append(down_diagonal)\r\n game_slices.append(up_diagonal)\r\n \r\n \r\n for game_slice in game_slices:\r\n winner=check_row_winner(game_slice)\r\n if winner!=0:\r\n display_winner(winner)\r\n return winner\r\n display_winner(winner)\r\n return winner\r\n\r\n\r\ndef start_game():\r\n return[[0,0,0] for x in range(3)]\r\n\r\n\r\ndef display_game(game):\r\n d={2:\"O\", 1: \"X\", 0:\" \"}\r\n game_string=[]\r\n for row_num in range(3):\r\n new_row=[]\r\n for col_num in range(3):\r\n new_row.append(d[game[row_num][col_num]])\r\n game_string.append(new_row)\r\n print(game_string)\r\n \r\n \r\ndef add_piece(game,player,row,column):\r\n game[row][column]=player\r\n return game\r\n\r\ndef convert_input_to_coordinate(user_input):\r\n return user_input -1\r\n\r\n\r\ndef switch_player(player):\r\n if player == 1:\r\n return 2\r\n else:\r\n return 1\r\n \r\n \r\nif _name_=='_main_':\r\n game=start_game()\r\n display_game(game)\r\n player=1\r\n \r\n \r\n while True:\r\n print(\"Currently player: \"+ str(player))\r\n row=conver_input_to_coordinate(int(input(\"Which row?(start with 1)\")))\r\n \r\n column=conver_input_to_coordinate(int(input(\"Which column?(start with 1)\")))\r\n \r\n game=add_piece(game,player,row,column)\r\n display_game(game)\r\n player=switch_player(player)","sub_path":"TIC_TAC_TOE.py","file_name":"TIC_TAC_TOE.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"70568095","text":"# course: Object-oriented programming, year 2, semester 1\n# academic year: 201920\n# author: B. Schoen-Phelan\n# date: 17-10-2019\n# purpose: Lab 5 - GUI and card game using queue\n\nfrom tkinter import *\n\n# to use the queue FIFO\nfrom queue import LifoQueue\n\nimport os\n\n# to use the shuffle for shuffling the cards\nfrom random import shuffle\n\n\nclass CardGame(Frame):\n\n # initialises the application\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n # set up game logic here:\n # shuffle the cards before first use\n # create LIFO Queue to store cards\n self.card_stack = LifoQueue(maxsize=52)\n\n # store cards in a list\n self.cards = os.listdir(\"cards\")\n self.cards.remove('Icon\\r')\n self.cards.remove('closed_deck.gif')\n self.cards.remove('.idea')\n\n # For the first game, the cards are shuffled twice\n shuffle(self.cards)\n\n # variable for holding the score\n self.player_score = 0\n\n self.init_window()\n\n # used by __init__\n # initialises the GUI window\n def init_window(self):\n self.pack(expand=True)\n\n # shuffle cards\n shuffle(self.cards)\n\n # clear self.card_stack\n self.card_stack.queue.clear()\n\n # add cards into LIFO queue\n for next_card in self.cards:\n self.card_stack.put(next_card)\n\n first_card = self.card_stack.get()\n\n # reset score\n self.player_score = 0\n\n # frames hold the elements of the window\n # grid arranges the elements in a tabular manner\n # see mock-up screen in lab sheet for the layout design\n cards_frame = LabelFrame(self)\n cards_frame.grid(row=0, column=0)\n button_frame = LabelFrame(self)\n button_frame.grid(row=0, column=1)\n score_frame = LabelFrame(self)\n score_frame.grid(row=1, column=0, columnspan=2)\n\n # add elements into the frames\n self.open_card = Button(cards_frame)\n the_card = PhotoImage(file='cards/' + first_card)\n self.open_card.config(image=the_card)\n self.open_card.grid(row=0, column=0, padx=2, pady=2)\n self.open_card.photo = the_card\n\n self.closed_deck = Button(cards_frame, command=self.next_card)\n closed_card = PhotoImage(file='cards/closed_deck.gif')\n self.closed_deck.config(image=closed_card)\n self.closed_deck.grid(row=0, column=1, padx=2, pady=2)\n self.closed_deck.photo = closed_card\n\n self.done_button = Button(button_frame, text=\"I'm done!\", command=self.finished)\n self.done_button.grid(row=0, column=0, pady=12)\n new_game_button = Button(button_frame, text=\"New Game\", command=self.init_window)\n new_game_button.grid(row=1, column=0, pady=13)\n exit_button = Button(button_frame, text=\"Exit\", command=self.game_exit)\n exit_button.grid(row=2, column=0, pady=13)\n\n self.score_label = Label(score_frame, text=\"Your score: \" + str(self.player_score), justify=LEFT)\n self.score_label.pack()\n\n self.update_score(first_card)\n\n # called by the exit_button Button\n # ends the GUI application\n def game_exit(self):\n exit()\n\n # method to show next card\n def next_card(self):\n if self.card_stack.empty():\n self.init_window()\n\n new_card = self.card_stack.get()\n the_card = PhotoImage(file='cards/' + new_card)\n self.open_card.config(image=the_card)\n self.open_card.grid(row=0, column=0, padx=2, pady=2)\n self.open_card.photo = the_card\n\n self.update_score(new_card)\n\n def finished(self):\n self.closed_deck['state'] = DISABLED\n self.done_button['state'] = DISABLED\n score_frame = LabelFrame(self)\n score_frame.grid(row=1, column=0, columnspan=2)\n self.score_label = Label(score_frame, text=\"Your score: \" + str(self.player_score) + \" Thanks for playing\", justify=LEFT)\n self.score_label.pack()\n\n def update_score(self, current_card):\n score = str(current_card)[0]\n\n if score == 'j' or score == 'q' or score == 'k':\n self.player_score += int(10)\n else:\n self.player_score += int(score)\n\n self.score_label.config(text=\"Your score \" + str(self.player_score))\n self.score_label.update_idletasks()\n\n if self.player_score == 21:\n self.win()\n elif self.player_score > 21:\n self.lose()\n\n def win(self):\n self.closed_deck['state'] = DISABLED\n self.done_button['state'] = DISABLED\n score_frame = LabelFrame(self)\n score_frame.grid(row=1, column=0, columnspan=2)\n self.score_label = Label(score_frame, text=\"Your score: \" + str(self.player_score) + \" You Win!\", justify=LEFT)\n self.score_label.pack()\n\n def lose(self):\n self.closed_deck['state'] = DISABLED\n self.done_button['state'] = DISABLED\n score_frame = LabelFrame(self)\n score_frame.grid(row=1, column=0, columnspan=2)\n self.score_label = Label(score_frame, text=\"Your score: \" + str(self.player_score) + \" You lose!\", justify=LEFT)\n self.score_label.pack()\n\n\n\n\n\n\n # def really(self):\n # button_frame = LabelFrame(self)®\n # button_frame.grid(row=0, column=1)\n # done_button = Button(button_frame, text=\"Really?\")\n # done_button.grid(row=0, column=0, pady=12)\n\n\n# object creation here:\nroot = Tk()\nroot.geometry(\"300x200\")\nroot.title(\"Card Game\")\napp = CardGame(root)\nroot.mainloop()\n","sub_path":"lab5_card_game.py","file_name":"lab5_card_game.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"22455848","text":"import json\r\nimport score\r\nimport os\r\nimport shutil\r\nfrom collections import OrderedDict\r\nimport copy\r\nimport sys\r\n\r\ndef if_has_flag(merge_file):\r\n\tff = 0\r\n\twith open(merge_file, 'r') as f:\r\n\t\tfor line in f.readlines():\r\n\t\t\tif disambiguate_flag in line:\r\n\t\t\t\tff += 1\r\n\treturn ff\r\n\r\n#把对齐后的文件读出来\r\ndef read_file(merge_file):\r\n\twith open(merge_file, 'r') as f:\r\n\t\tdictionary = json.load(f)\r\n\treturn dictionary\r\n\r\n#给消歧标记重新编号\r\ndef change_flag(dictionary):\r\n\tglobal num #消歧标记的编号\r\n\tglobal number\r\n\tfor key, value in dictionary.items():\r\n\t\t#消歧标记都在列表下面\r\n\t\tif (type(value).__name__=='list'):\r\n\t\t\tflag_list = [] #每个list下的编号集合\r\n\t\t\t#把每个list下的消歧标记编号放到列表中\r\n\t\t\tfor i in value:\r\n\t\t\t\tif disambiguate_flag in i:\r\n\t\t\t\t\t#给每个值加一个id\r\n\t\t\t\t\ti[disambiguate_id] = number\r\n\t\t\t\t\tnumber += 1\r\n\t\t\t\t\t#把每个list下的消歧标记编号放到列表中\r\n\t\t\t\t\tflag_list.append(i[disambiguate_flag])\r\n\t\t\t#如果是相同的消歧标记\r\n\t\t\tif len(set(flag_list)) == 1:\r\n\t\t\t\tfor i in value:\r\n\t\t\t\t\t#把新的消歧标记设置成num\r\n\t\t\t\t\tif disambiguate_flag in i:\r\n\t\t\t\t\t\ti[disambiguate_flag] = num\r\n\t\t\t\tnum += 1\r\n\t\t\t#如果有多种消歧标记\r\n\t\t\telif len(set(flag_list)) > 1:\r\n\t\t\t\t#对于每一种消歧标记分别重新设置num\r\n\t\t\t\tfor f in set(flag_list):\r\n\t\t\t\t\tfor i in value:\r\n\t\t\t\t\t\tif disambiguate_flag in i and i[disambiguate_flag] == f:\r\n\t\t\t\t\t\t\ti[disambiguate_flag] = num\r\n\t\t\t\t\t\t\t#print(value[i][disambiguate_flag])\r\n\t\t\t\t\tnum += 1\r\n\t\t#如果是字典就递归调用函数\r\n\t\telif (type(value).__name__=='dict'):\r\n\t\t\tchange_flag(value)\r\n\r\n'''\r\n找出有消歧标记的属性,没有消歧标记的属性标-1\r\n'''\r\ndef add_delete_flag(dictionary):\r\n\tfor key, value in dictionary.items():\r\n\t\t#如果有消歧标记,value一定是字典\r\n\t\tif (type(value).__name__=='str'):\r\n\t\t\tdictionary[key]\t= -1\r\n\t\t#有时是列表嵌套字典\r\n\t\telif (type(value).__name__=='list'):\r\n\t\t\tfor i in range(len(value)):\r\n\t\t\t\tif disambiguate_flag not in value[i]:\r\n\t\t\t\t\tvalue[i] = -1\r\n\t\t#如果是字典就递归调用函数\r\n\t\telse:\r\n\t\t\tadd_delete_flag(value)\r\n\r\n'''\r\n把所有标-1的属性都删除\r\n'''\r\ndef del_value(dictionary):\r\n\t#遍历字典的值,如果是-1就删除\r\n\tfor key in list(dictionary.keys()):\r\n\t\tif dictionary[key] == -1:\r\n\t\t\tdel(dictionary[key])\r\n\tfor value in dictionary.values():\r\n\t\t#如果值是列表,遍历列表的拷贝,如果有-1就删除\r\n\t\tif (type(value).__name__=='list'):\r\n\t\t\tcopy_value = value[:]\r\n\t\t\tfor i in copy_value:\r\n\t\t\t\tif i == -1:\r\n\t\t\t\t\tvalue.remove(i)\r\n\t\t#如果值是字典就递归调用\r\n\t\telif (type(value).__name__=='dict'):\r\n\t\t\tdel_value(value)\r\n\r\n'''\r\n删除属性后会有一些属性值为空,把所有空值删除\r\n'''\r\ndef del_empty_array(dictionary):\r\n\t#遍历字典,如果是空值就删除\r\n\tfor key in list(dictionary.keys()):\r\n\t\tif not dictionary[key]:\r\n\t\t\tdel(dictionary[key])\r\n\t#遍历值,如果是字典就递归调用\r\n\tfor value in dictionary.values():\r\n\t\tif (type(value).__name__=='dict'):\r\n\t\t\tdel_empty_array(value)\r\n\r\ndef find_same_flag(dictionary):\r\n\txiaoqi_list = []\r\n\tfor key, value in dictionary.items():\r\n\t\t#基本信息\r\n\t\tif key == headline['jibenxinxi']:\r\n\t\t\t#is_multi_value = 1\r\n\t\t\t#[职业,毕业院校...]\r\n\t\t\tfor va in value:\r\n\t\t\t\t#[职业..., 职业...]\r\n\t\t\t\tfor v in value[va]:\r\n\t\t\t\t\tnum = v[disambiguate_flag]\r\n\t\t\t\t\tnumber = v[disambiguate_id]\r\n\t\t\t\t\t#print(number)\r\n\t\t\t\t\t#{'职业': '学者,教授', '消歧标记': 1, '来源': 'fang_hudong'}\r\n\t\t\t\t\tfor k in v:\r\n\t\t\t\t\t\tif k != disambiguate_flag and k != source and k != disambiguate_id:\r\n\t\t\t\t\t\t\tif k in multi_values:\r\n\t\t\t\t\t\t\t\tis_multi_value = 1\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tis_multi_value = 0\r\n\t\t\t\t\t\t\t#方滨兴 职业:学者,教授0\r\n\t\t\t\t\t\t\t#print(name + ' ' + k + ' ' + str(v[k]) + ' ' + str(num) + ' '+ \r\n\t\t\t\t\t\t\t#\tstr(is_multi_value) + ' ' + str(number))\r\n\t\t\t\t\t\t\txiaoqi_list.append(name + ' ' + k + ' ' + v[k] + '|' + str(num) + ' '+ \r\n\t\t\t\t\t\t\t\tstr(is_multi_value) + ' ' + str(number))\r\n\t\t#人物履历\r\n\t\telif key == headline['renwulvli']:\r\n\t\t\tis_multi_value = 0\r\n\t\t\t#[教育经历,工作经历]\r\n\t\t\tfor key1 in value:\r\n\t\t\t\tif key1 == headline2['jiaoyujingli']:\r\n\t\t\t\t\t#[本科,硕士,博士,博士后]\r\n\t\t\t\t\tfor key2 in value[key1]:\r\n\t\t\t\t\t\t#[结束时间,学位...]\r\n\t\t\t\t\t\tfor key3 in value[key1][key2]:\r\n\t\t\t\t\t\t\t#[结束时间,结束时间...]\r\n\t\t\t\t\t\t\t#for key4 in value[key1][key2][key3]:\r\n\t\t\t\t\t\t\t\t#{'结束时间': '1981', '消歧标记': 1, '来源': 'fang_hudong,fang_360,fang_wiki'}\r\n\t\t\t\t\t\t\t\tfor k in key3:\r\n\t\t\t\t\t\t\t\t\tnum = key3[disambiguate_flag]\r\n\t\t\t\t\t\t\t\t\tnumber = key3[disambiguate_id]\r\n\t\t\t\t\t\t\t\t\t#print(number)\r\n\t\t\t\t\t\t\t\t\tif k != disambiguate_flag and k != source and k != disambiguate_id:\r\n\t\t\t\t\t\t\t\t\t\t#print(name + ' ' + key2 + k + ' ' + str(key4[k]) + ' ' + str(num) \r\n\t\t\t\t\t\t\t\t\t\t#\t+ ' '+ str(is_multi_value) + ' ' + str(number))\r\n\t\t\t\t\t\t\t\t\t\txiaoqi_list.append(name + ' ' + key2 + k + ' ' + str(key3[k]) + '|' + \r\n\t\t\t\t\t\t\t\t\t\t\tstr(num) + ' '+ str(is_multi_value) + ' ' + str(number))\r\n\t\t\t\telif key1 == headline2['gongzuojingli']:\r\n\t\t\t\t\t#任职\r\n\t\t\t\t\tfor key2 in value[key1]:\r\n\t\t\t\t\t\t#print(key2)\r\n\t\t\t\t\t\tvalue_list = [] #把多种消歧标志放到列表里\r\n\t\t\t\t\t\t#[所在单位,起始时间...]\r\n\t\t\t\t\t\tfor key3 in value[key1][key2]:\r\n\t\t\t\t\t\t\t#[所在单位,起始时间]\r\n\t\t\t\t\t\t\tfor key4 in key3:\r\n\t\t\t\t\t\t\t\tif key4 == disambiguate_flag:\r\n\t\t\t\t\t\t\t\t\tvalue_list.append(key3[key4])\r\n\t\t\t\t\t\t#print(value_list)\r\n\t\t\t\t\t\tfor i in set(value_list):\r\n\t\t\t\t\t\t\tfor key3 in value[key1][key2]:\r\n\t\t\t\t\t\t\t\tif key3[disambiguate_flag] == i:\r\n\t\t\t\t\t\t\t\t\tif key2 == headline2['renzhi']:\r\n\t\t\t\t\t\t\t\t\t\txiaoqi_list.append(name + ' ' + key3[headline2['qishishijian']] + '-' + \r\n\t\t\t\t\t\t\t\t\t\t\tkey3[headline2['zhongzhishijian']] + \r\n\t\t\t\t\t\t\t\t\t\t\tkey3[headline2['suozaidanwei']] + ' ' + key3[headline2['zhicheng']]\r\n\t\t\t\t\t\t\t\t\t\t\t+ '|' + str(i) + ' '+ str(is_multi_value) + ' ' + str(key3[disambiguate_id]))\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t#任免_辞职\r\n\t\t\t\t\t\t\t\t\telif key2 == headline2['renmian_cizhi']:\r\n\t\t\t\t\t\t\t\t\t\txiaoqi_list.append(name + ' ' + key3[headline2['shijian']] + \r\n\t\t\t\t\t\t\t\t\t\t\theadline2['renmian_cizhi'] + ' ' + key3[headline2['renmianzhiwei_zhicheng']]\r\n\t\t\t\t\t\t\t\t\t\t\t + '|' + str(i) + ' '+ str(is_multi_value) + ' ' + str(key3[disambiguate_id]))\r\n\r\n\t\t#社会任职\r\n\t\telif key == headline['shehuirenzhi']:\r\n\t\t\tis_multi_value = 1\r\n\t\t\tfor v in dictionary[key]:\r\n\t\t\t\tnum = v[disambiguate_flag]\r\n\t\t\t\tnumber = v[disambiguate_id]\r\n\t\t\t\txiaoqi_list.append(name + ' ' + v[headline2['qishishijian']] + v[headline2['zhongzhishijian']] \r\n\t\t\t\t\t+ ' ' + v[headline2['zhicheng']] + '|' + str(num) + \r\n\t\t\t\t\t' '+ str(is_multi_value) + ' ' + str(number))\r\n\r\n\t\t#成就\r\n\t\telif key == headline['chengjiu']:\r\n\t\t\tis_multi_value = 1\r\n\t\t\tfor key1 in dictionary[key]:\t\r\n\t\t\t\tif key1 == headline2['chengdanxiangmulei']:\r\n\t\t\t\t\tfor v in dictionary[key][key1]:\r\n\t\t\t\t\t\tnum = v[disambiguate_flag]\r\n\t\t\t\t\t\tnumber = v[disambiguate_id]\r\n\t\t\t\t\t\t#print(name + ' ' + v[headline2['shijiandian']] + v[headline2['banjiangdanwei']] + \r\n\t\t\t\t\t\t#\t' ' + v[headline2['shouyujiangxiangmingcheng']] + ' ' + str(number) + ' '+ str(is_multi_value))\r\n\t\t\t\t\t\txiaoqi_list.append(name + ' ' + v[headline2['qishishijian']] + ' ' + v[headline2['zhongzhishijian']] + v[headline2['xiangmu']] \r\n\t\t\t\t\t\t\t+ '|' + str(num) + ' '+ str(is_multi_value) + ' ' + str(number))\r\n\t\t\t\t#科研方向、研究领域、发明专利类、人才培养类\r\n\t\t\t\telif key1 == headline2['keyanfangxiang'] or key1 == headline2['yanjiulingyu'] or key1 == headline2['famingzhuanlilei'] or key1 == headline2['rencaipeiyanglei']:\r\n\t\t\t\t\tpass\r\n\t\t\t\t#主要荣誉、学术论著类、研究成果类、散文类\r\n\t\t\t\telse:\r\n\t\t\t\t\tvalue_list = [] #把多种消歧标志放到列表\r\n\t\t\t\t\t#[时间点,论著名称...]\r\n\t\t\t\t\tfor k in dictionary[key][key1]:\r\n\t\t\t\t\t\tvalue_list.append(k[disambiguate_flag])\r\n\t\t\t\t\tfor i in set(value_list):\r\n\t\t\t\t\t\tfor k in dictionary[key][key1]:\r\n\t\t\t\t\t\t\tvv = [] #存放关键词\r\n\t\t\t\t\t\t\tfor kk in k:\r\n\t\t\t\t\t\t\t\tif kk != disambiguate_flag and kk != disambiguate_id and kk != source:\r\n\t\t\t\t\t\t\t\t\tvv.append(k[kk])\r\n\t\t\t\t\t\t\tif k[disambiguate_flag] == i:\r\n\t\t\t\t\t\t\t\t#print(name + ' ' + k[headline2['shijiandian']] + ' ' + k[headline2['lunzhumingcheng']]\r\n\t\t\t\t\t\t\t\t#\t + ' ' + str(i) + ' '+ str(is_multi_value))\r\n\t\t\t\t\t\t\t\txiaoqi_list.append(name + ' ' + vv[0] + ' ' + vv[1] + '|' + str(i) + ' '+ \r\n\t\t\t\t\t\t\t\t\tstr(is_multi_value) + ' ' + str(k[disambiguate_id]))\r\n\t\t\t\t\t\r\n\r\n\t\t#学术报告\r\n\t\telif key == headline['xueshubaogao']:\r\n\t\t\tpass\r\n\t\t#人物评价/外界评价\r\n\t\telif key == headline['renwupingjia']:\r\n\t\t\tpass\r\n\t\t#人物影响\r\n\t\telif key == headline['renwuyingxiang']:\r\n\t\t\tpass\r\n\t\t#个性寄语\r\n\t\telif key == headline['gexingjiyu']:\r\n\t\t\tpass\r\n\t\t#社会争议_争议事件\r\n\t\telif key == headline['shehuizhengyi']:\r\n\t\t\tpass\r\n\t\t#获奖争议\r\n\t\telif key == headline['huojiangzhengyi']:\r\n\t\t\tpass\r\n\t\t#院士名\r\n\t\telif key == headline['yuanshiming']:\r\n\t\t\tpass\r\n\treturn xiaoqi_list\r\n\r\n#把关键字写入文件\r\ndef write_keywords_to_file(xiaoqi_list):\r\n\twith open('keywords.txt', 'w', encoding = 'utf-8') as f:\r\n\t\tfor i in xiaoqi_list:\r\n\t\t\tf.write(i)\r\n\t\t\tf.write('\\n')\r\n\t\tprint('success')\r\n\r\n#把分数写回去\r\ndef add_score(score, dictionary):\r\n\tfor key, value in dictionary.items():\r\n\t\tif (type(value).__name__=='list'):\r\n\t\t\tfor i in value:\r\n\t\t\t\tif disambiguate_id in i:\r\n\t\t\t\t\tfor s in score:\r\n\t\t\t\t\t\tif i[disambiguate_id] == int(s['disambiguate_id']):\r\n\t\t\t\t\t\t\ti[dis_score] = s['score']\r\n\t\t#如果是字典就递归调用函数\r\n\t\telif (type(value).__name__=='dict'):\r\n\t\t\tadd_score(score, value)\r\n\r\n#记录需要保留的消歧编号\r\ndef record_id(disambiguate):\r\n\tdisambiguate_id_list = []\r\n\tfor d in disambiguate:\r\n\t\tdisambiguate_id_list.append(d['disambiguate_id'])\r\n\t#print(disambiguate_id_list)\r\n\treturn disambiguate_id_list\r\n\r\n#不在列表中的属性删除\r\ndef find_flag(disambiguate_id_list, dictionary):\r\n\tfor key, value in dictionary.items():\r\n\t\tif (type(value).__name__=='list'):\r\n\t\t\tvalue_copy = value[:]\r\n\t\t\tfor i in value_copy:\r\n\t\t\t\t#如果需要消歧,且编号不在消歧列表中,删除该元素\r\n\t\t\t\tif disambiguate_id in i and str(i[disambiguate_id]) not in disambiguate_id_list:\r\n\t\t\t\t\t#print(i)\r\n\t\t\t\t\tvalue.remove(i)\r\n\t\t#如果是字典就递归调用函数\r\n\t\telif (type(value).__name__=='dict'):\r\n\t\t\tfind_flag(disambiguate_id_list, value)\r\n\r\n#删除消歧编号、消歧标记\r\ndef delete_flag(dictionary):\r\n\tfor key, value in dictionary.items():\r\n\t\tif (type(value).__name__=='list'):\r\n\t\t\tvalue_copy = value[:]\r\n\t\t\tfor i in value_copy:\r\n\t\t\t\tif disambiguate_flag in i:\r\n\t\t\t\t\tdel i[disambiguate_flag]\r\n\t\t\t\t\tdel i[disambiguate_id]\r\n\t#如果是字典就递归调用函数\r\n\t\telif (type(value).__name__=='dict'):\r\n\t\t\tdelete_flag(value)\r\n\r\n#给字典重新排序(字典是无序的)\r\ndef merge_dict(dictionary):\t\r\n\tmonitorItems = OrderedDict()\r\n\talist = [headline['jibenxinxi'], headline['renwulvli'], headline['shehuirenzhi'], \r\n\t\theadline['chengjiu'], headline['xueshubaogao'], \r\n\t\theadline['renwupingjia'], headline['renwuyingxiang'], headline['gexingjiyu'], headline['shehuizhengyi'], \r\n\t\theadline['huojiangzhengyi'], headline['yuanshiming'], headline2['zhongwenming'], headline2['waiwenming'], headline2['xingbie'], \r\n\t\theadline2['chushengriqi'], headline2['chushengdi'], headline2['guoji'], headline2['minzu'], headline2['zhiye'], \r\n\t\theadline2['biyeyuanxiao'], headline2['zhengzhimianmao'], headline2['daibiaozuopin'], headline2['zhuyaochengjiu'], \r\n\t\theadline2['cengrenzhi'], headline2['xinyang'], headline2['yuanji'], headline2['jiaoyujingli'], headline2['gongzuojingli'],\r\n\t\theadline2['benke'], headline2['shuoshiyanjiusheng'], headline2['boshiyanjiusheng'], headline2['boshihou'],\r\n\t\theadline2['renzhi'], headline2['renmian_cizhi'], headline2['keyanfangxiang'], headline2['yanjiulingyu'], headline2['zhuyaorongyu'], \r\n\t\theadline2['xueshulunzhulei'], headline2['sanwenlei'], headline2['chengdanxiangmulei'],\r\n\t\theadline2['yanjiuchengguolei'], headline2['famingzhuanlilei'], headline2['rencaipeiyanglei'], headline2['qishishijian'], \r\n\t\theadline2['jieshushijian'], headline2['xuexiaomingcheng'], headline2['suoshuyuanximing'], headline2['xuexiaomingcheng_keyanjigou'], \r\n\t\theadline2['suoshuyuanximing_ketizu'], headline2['daoshi'], headline2['xueli'], headline2['xuewei'], source]\r\n\tfor key in alist:\r\n\t if dictionary.get(key) is not None:#python2用的是row.has_key(key)\r\n\t monitorItems[key] = dictionary.get(key)\r\n\treturn monitorItems\r\n\r\n#循环遍历字典,值是字典的话就重新排序,然后用排序后的value替换之前的value\r\ndef loop_dict(dictionary):\r\n\tfor key, value in dictionary.items():\r\n\t\tif (type(value).__name__=='dict'):\r\n\t\t\tnew_value = merge_dict(value)\r\n\t\t\t#print('key', key)\r\n\t\t\t#print('new value\\n', new_value)\r\n\t\t\tdictionary[key] = new_value\r\n\t\t\tloop_dict(new_value)\r\n\t\telse:\r\n\t\t\tpass\r\n\r\ndef xiaoqi(name, merge_file):\r\n\tfff = if_has_flag(merge_file)\r\n\tif fff == 0:\r\n\t\tprint('文件不需要消歧')\r\n\t\tsys.exit(0)\r\n\tdictionary = read_file(merge_file) #把文件读到字典中\r\n\tchange_flag(dictionary)\r\n\tmerge_change = copy.deepcopy(dictionary)\r\n\tadd_delete_flag(dictionary)\r\n\tdel_value(dictionary)\r\n\t#字典最多四层,删除四次\r\n\t# for i in range(4):\r\n\t# \tdel_empty_array(dictionary)\r\n\tdelete_json = copy.deepcopy(dictionary)\r\n\r\n\t#disambiguate\r\n\txiaoqi_list = find_same_flag(delete_json)\r\n\twrite_keywords_to_file(xiaoqi_list)\r\n\t# 判断是否有keywords文件 有就删除\r\n\tif os.path.exists('spider1/keywords.txt'):\r\n\t\tos.remove('spider1/keywords.txt')\r\n\tshutil.move('keywords.txt', 'spider1') #把关键字移动到爬虫目录\r\n\tos.chdir('spider1') # 进入爬虫目录\r\n\t# 如果有items.json就删除\r\n\tif os.path.exists('items.json'):\r\n\t\tos.remove('items.json')\r\n\tos.system(r\"scrapy crawl spider1 -o items.json\") #运行爬虫\r\n\t# 保存爬虫结果\r\n\twith open('items.json','r', encoding ='utf-8') as f:\r\n\t\tdata = json.load(f)\r\n\tos.remove('keywords.txt')\r\n\tos.remove('items.json')\r\n\tos.chdir('../') \r\n\tsco, disambiguate = score.score(data)\r\n\r\n\t#generate_resume1 有分数\r\n\tmerge_change2 = copy.deepcopy(merge_change)\r\n\tadd_score(sco, merge_change)\r\n\tmonitorItems = merge_dict(merge_change)\r\n\tloop_dict(monitorItems)\r\n\twith open('final.json', 'w', encoding = 'utf-8') as file:\r\n\t\tjson.dump(monitorItems, file, ensure_ascii = False, indent = 4)\r\n\t\tprint(\"success\")\r\n\r\n\t#generate_resume2 没分数\r\n\tdisambiguate_id_list = record_id(disambiguate)\r\n\tfind_flag(disambiguate_id_list, merge_change2)\r\n\tdelete_flag(merge_change2)\r\n\tmonitorItems = merge_dict(merge_change2)\r\n\tloop_dict(monitorItems)\t\r\n\twith open('final2.json', 'w', encoding = 'utf-8') as file:\r\n\t\tjson.dump(monitorItems, file, ensure_ascii = False, indent = 4)\r\n\t\tprint(\"success\")\r\n\r\nif __name__ == '__main__':\r\n\tdisambiguate_flag = '消歧标记'\r\n\tdisambiguate_id = '消歧编号'\r\n\tname = '何继善' #院士姓名\r\n\tsource = '来源'\r\n\tdis_score = '消歧得分'\r\n\theadline = {'jibenxinxi':'基本信息', 'renwulvli':'人物履历', 'shehuirenzhi':'社会任职', \r\n\t\t'chengjiu':'成就','xueshubaogao':'学术报告', 'renwupingjia':'外界评价',\r\n\t\t'renwuyingxiang':'人物影响', 'gexingjiyu':'个性寄语', 'shehuizhengyi':'社会争议_争议事件', \r\n\t\t'huojiangzhengyi':'获奖争议', 'yuanshiming':'院士名'}\r\n\theadline2 = {'zhongwenming':'中文名', 'waiwenming':'外文名', 'xingbie':'性别', 'chushengriqi':'出生日期', 'chushengdi':'出生地',\r\n\t\t'guoji':'国籍', 'minzu':'民族', 'zhiye':'职业', 'biyeyuanxiao':'毕业院校', 'zhengzhimianmao':'政治面貌', 'daibiaozuopin':'代表作品',\r\n\t\t'zhuyaochengjiu':'主要成就', 'cengrenzhi':'曾任职', 'xinyang':'信仰', 'yuanji':'原籍', 'jiaoyujingli':'教育经历', 'gongzuojingli':'工作经历',\r\n\t\t'benke':'本科', 'shuoshiyanjiusheng':'硕士研究生', 'boshiyanjiusheng':'博士研究生', 'qishishijian':'起始时间', 'jieshushijian':'结束时间', 'zhongzhishijian':'终止时间',\r\n\t\t'xuexiaomingcheng':'学校名称', 'suoshuyuanximing':'所属院系名', 'xueli':'学历', 'xuewei':'学位', 'daoshi':'导师', 'boshihou':'博士后',\r\n\t\t'renzhi':'任职', 'renmian_cizhi':'任免_辞职', 'xuexiaomingcheng_keyanjigou':'学校名称_科研机构', 'suoshuyuanximing_ketizu':'所属院系名_课题组',\r\n\t\t'didian':'地点', 'suozaidanwei':'所在单位', 'zhicheng':'职称', 'shijian':'时间', 'xinxigongbuquanweijiguan':'信息公布权威机构',\r\n\t\t'renmianzhiwei_zhicheng':'任免职位_职称', 'zuzhijigou':'组织机构','zhiwei_zhicheng':'职位_职称', 'keyanfangxiang':'科研方向', \r\n\t\t'yanjiulingyu':'研究领域', 'zhuyaorongyu':'主要荣誉', 'fangxiang':'方向', 'rongyu':'荣誉',\r\n\t\t'xueshulunzhulei':'学术论著类', 'sanwenlei':'散文类', 'lunzhumingcheng':'论著名称', 'sanwenmingcheng':'散文名称', 'chengdanxiangmulei':'承担项目类',\r\n\t\t'xiangmu':'项目','yanjiuchengguolei':'研究成果类', 'yanjiuchengguomingcheng':'研究成果名称', 'famingzhuanlilei':'发明专利类', \r\n\t\t'zhuanlimingcheng':'专利名称', 'rencaipeiyanglei':'人才培养类', 'jiaoyulinian_zhidaoxuesheng':'教育理念_指导学生', 'shi_jian':'事件'}\r\n\tmulti_values = ['职业', '毕业院校', '代表作品', '���要成就', '曾任职','承担项目类','学术论著类', '研究成果类']\r\n\t#xiaoqi_list = [] #定义要消歧的三元组列表\r\n\t#disambiguate_id_list = []\r\n\tnum = 100 #消歧标记的编号 change_flag(dictionary)\r\n\tnumber = 0 #消歧编号\r\n\tmerge_file = '何继善.json' #对齐文件的路径\r\n\r\n\txiaoqi(name, merge_file)","sub_path":"xiaoqi2.py","file_name":"xiaoqi2.py","file_ext":"py","file_size_in_byte":17495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"3677164","text":"# -*- coding: utf-8 -*-\n# Copyright 2018-2021 CERN\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# Authors:\n# - Cedric Serfon , 2018-2019\n# - Martin Barisits , 2018-2019\n# - Andrew Lister , 2019\n# - Brandon White , 2019\n# - Thomas Beermann , 2020\n# - Patrick Austin , 2020\n# - Eli Chadwick , 2020\n# - Benedikt Ziemons , 2020\n# - Dimitrios Christidis , 2021\n\nfrom __future__ import division\n\nimport logging\nimport math\nimport os\nimport socket\nimport threading\nimport time\nimport traceback\nfrom datetime import datetime\nfrom sys import stdout\n\nimport rucio.db.sqla.util\nfrom rucio.common.config import config_get\nfrom rucio.common.exception import UnsupportedOperation, DataIdentifierNotFound, ReplicaNotFound, DatabaseException\nfrom rucio.common.utils import chunks\nfrom rucio.core import heartbeat\nfrom rucio.core.did import get_metadata\nfrom rucio.core.replica import (get_bad_pfns, get_pfn_to_rse, declare_bad_file_replicas,\n get_did_from_pfns, update_replicas_states, bulk_add_bad_replicas,\n bulk_delete_bad_pfns, get_replicas_state)\nfrom rucio.core.rse import get_rse_name\nfrom rucio.db.sqla.constants import BadFilesStatus, BadPFNStatus, ReplicaState\nfrom rucio.db.sqla.session import get_session\n\nlogging.basicConfig(stream=stdout,\n level=getattr(logging,\n config_get('common', 'loglevel',\n raise_exception=False,\n default='DEBUG').upper()),\n format='%(asctime)s\\t%(process)d\\t%(levelname)s\\t%(message)s')\n\n\ngraceful_stop = threading.Event()\n\n\ndef minos(bulk=1000, once=False, sleep_time=60):\n \"\"\"\n Creates a Minos Worker that gets a list of bad PFNs,\n extract the scope, name and rse_id and fill the bad_replicas table.\n\n :param bulk: The number of requests to process.\n :param once: Run only once.\n :param sleep_time: Time between two cycles.\n \"\"\"\n\n executable = 'minos'\n hostname = socket.getfqdn()\n pid = os.getpid()\n hb_thread = threading.current_thread()\n heartbeat.sanity_check(executable=executable, hostname=hostname)\n hb_thread = threading.current_thread()\n heartbeat.sanity_check(executable=executable, hostname=hostname)\n heart_beat = heartbeat.live(executable, hostname, pid, hb_thread)\n prepend_str = 'Thread [%i/%i] : ' % (heart_beat['assign_thread'], heart_beat['nr_threads'])\n logging.info(prepend_str + 'Minos starting')\n\n time.sleep(10) # To prevent running on the same partition if all the daemons restart at the same time\n heart_beat = heartbeat.live(executable, hostname, pid, hb_thread)\n prepend_str = 'Thread [%i/%i] : ' % (heart_beat['assign_thread'], heart_beat['nr_threads'])\n\n states_mapping = {BadPFNStatus.BAD: BadFilesStatus.BAD,\n BadPFNStatus.SUSPICIOUS: BadFilesStatus.SUSPICIOUS,\n BadPFNStatus.TEMPORARY_UNAVAILABLE: BadFilesStatus.TEMPORARY_UNAVAILABLE}\n logging.info(prepend_str + 'Minos started')\n\n chunk_size = 10 # The chunk size used for the commits\n\n while not graceful_stop.is_set():\n start_time = time.time()\n heart_beat = heartbeat.live(executable, hostname, pid, hb_thread)\n prepend_str = 'Thread [%i/%i] : ' % (heart_beat['assign_thread'], heart_beat['nr_threads'])\n pfns = []\n try:\n bad_replicas = {}\n temporary_unvailables = {}\n pfns = get_bad_pfns(thread=heart_beat['assign_thread'], total_threads=heart_beat['nr_threads'], limit=bulk)\n\n # Class the PFNs into bad_replicas and temporary_unavailable\n for pfn in pfns:\n path = pfn['pfn']\n account = pfn['account']\n reason = pfn['reason']\n expires_at = pfn['expires_at']\n state = states_mapping[pfn['state']]\n if state in [BadFilesStatus.BAD, BadFilesStatus.SUSPICIOUS]:\n if (account, reason, state) not in bad_replicas:\n bad_replicas[(account, reason, state)] = []\n bad_replicas[(account, reason, state)].append(path)\n elif state == BadFilesStatus.TEMPORARY_UNAVAILABLE:\n if (account, reason, expires_at) not in temporary_unvailables:\n temporary_unvailables[(account, reason, expires_at)] = []\n temporary_unvailables[(account, reason, expires_at)].append(path)\n\n # Process the bad and suspicious files\n # The scope, name, rse_id are extracted and filled into the bad_replicas table\n for account, reason, state in bad_replicas:\n vo = account.vo\n pfns = bad_replicas[(account, reason, state)]\n logging.info(prepend_str + 'Declaring %s replicas with state %s and reason %s' % (len(pfns), str(state), reason))\n session = get_session()\n schemes = {}\n dict_rse = {}\n unknown_replicas = []\n try:\n # Splitting the PFNs by schemes\n for pfn in pfns:\n scheme = pfn.split(':')[0]\n if scheme not in schemes:\n schemes[scheme] = []\n schemes[scheme].append(pfn)\n for scheme in schemes:\n _, tmp_dict_rse, tmp_unknown_replicas = get_pfn_to_rse(schemes[scheme], vo=vo)\n for rse_id in tmp_dict_rse:\n if rse_id not in dict_rse:\n dict_rse[rse_id] = []\n dict_rse[rse_id].extend(tmp_dict_rse[rse_id])\n unknown_replicas.extend(tmp_unknown_replicas.get('unknown', []))\n # The replicas in unknown_replicas do not exist, so we flush them from bad_pfns\n if unknown_replicas:\n logging.info(prepend_str + 'The following replicas are unknown and will be removed : %s' % str(unknown_replicas))\n bulk_delete_bad_pfns(pfns=unknown_replicas, session=None)\n\n for rse_id in dict_rse:\n vo_str = '' if vo == 'def' else ' on VO ' + vo\n logging.debug(prepend_str + 'Running on RSE %s%s with %s replicas' % (get_rse_name(rse_id=rse_id), vo_str, len(dict_rse[rse_id])))\n nchunk = 0\n tot_chunk = int(math.ceil(len(dict_rse[rse_id]) / chunk_size))\n for chunk in chunks(dict_rse[rse_id], chunk_size):\n nchunk += 1\n logging.debug(prepend_str + 'Running on %s chunk out of %s' % (nchunk, tot_chunk))\n unknown_replicas = declare_bad_file_replicas(pfns=chunk, reason=reason, issuer=account, status=state, session=session)\n if unknown_replicas:\n logging.debug(prepend_str + 'Unknown replicas : %s' % (str(unknown_replicas)))\n bulk_delete_bad_pfns(pfns=chunk, session=session)\n session.commit() # pylint: disable=no-member\n except Exception:\n session.rollback() # pylint: disable=no-member\n logging.critical(traceback.format_exc())\n\n # Now get the temporary unavailable and update the replicas states\n for account, reason, expires_at in temporary_unvailables:\n vo = account.vo\n pfns = temporary_unvailables[(account, reason, expires_at)]\n logging.info(prepend_str + 'Declaring %s replicas temporary available with timeout %s and reason %s' % (len(pfns), str(expires_at), reason))\n logging.debug(prepend_str + 'Extracting RSEs')\n schemes = {}\n dict_rse = {}\n unknown_replicas = []\n\n # Splitting the PFNs by schemes\n for pfn in pfns:\n scheme = pfn.split(':')[0]\n if scheme not in schemes:\n schemes[scheme] = []\n schemes[scheme].append(pfn)\n for scheme in schemes:\n _, tmp_dict_rse, tmp_unknown_replicas = get_pfn_to_rse(schemes[scheme], vo=vo)\n for rse_id in tmp_dict_rse:\n if rse_id not in dict_rse:\n dict_rse[rse_id] = []\n dict_rse[rse_id].extend(tmp_dict_rse[rse_id])\n unknown_replicas.extend(tmp_unknown_replicas.get('unknown', []))\n\n # The replicas in unknown_replicas do not exist, so we flush them from bad_pfns\n if unknown_replicas:\n logging.info(prepend_str + 'The following replicas are unknown and will be removed : %s' % str(unknown_replicas))\n bulk_delete_bad_pfns(pfns=unknown_replicas, session=None)\n\n for rse_id in dict_rse:\n replicas = []\n rse = get_rse_name(rse_id=rse_id, session=None)\n rse_vo_str = rse if vo == 'def' else '{} on {}'.format(rse, vo)\n logging.debug(prepend_str + 'Running on RSE %s' % rse_vo_str)\n for rep in get_did_from_pfns(pfns=dict_rse[rse_id], rse_id=None, vo=vo, session=None):\n for pfn in rep:\n scope = rep[pfn]['scope']\n name = rep[pfn]['name']\n replicas.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'state': ReplicaState.TEMPORARY_UNAVAILABLE, 'pfn': pfn})\n # The following part needs to be atomic\n # We update the replicas states to TEMPORARY_UNAVAILABLE\n # then insert a row in the bad_replicas table. TODO Update the row if it already exists\n # then delete the corresponding rows into the bad_pfns table\n logging.debug(prepend_str + 'Running on %s replicas on RSE %s' % (len(replicas), rse_vo_str))\n nchunk = 0\n tot_chunk = int(math.ceil(len(replicas) / float(chunk_size)))\n session = get_session()\n for chunk in chunks(replicas, chunk_size):\n try:\n nchunk += 1\n logging.debug(prepend_str + 'Running on %s chunk out of %s' % (nchunk, tot_chunk))\n update_replicas_states(chunk, nowait=False, session=session)\n bulk_add_bad_replicas(chunk, account, state=BadFilesStatus.TEMPORARY_UNAVAILABLE, reason=None, expires_at=expires_at, session=session)\n pfns = [entry['pfn'] for entry in chunk]\n bulk_delete_bad_pfns(pfns=pfns, session=session)\n session.commit() # pylint: disable=no-member\n except (UnsupportedOperation, ReplicaNotFound) as error:\n session.rollback() # pylint: disable=no-member\n logging.error(prepend_str + 'Problem to bulk update PFNs. PFNs will be updated individually. Error : %s' % str(error))\n for rep in chunk:\n logging.debug(prepend_str + 'Working on %s' % (str(rep)))\n try:\n get_metadata(rep['scope'], rep['name'])\n unavailable_states = []\n rep_state = get_replicas_state(rep['scope'], rep['name'])\n unavailable_states.extend(rep_state.get(ReplicaState.TEMPORARY_UNAVAILABLE, []))\n unavailable_states.extend(rep_state.get(ReplicaState.BEING_DELETED, []))\n unavailable_states.extend(rep_state.get(ReplicaState.BAD, []))\n if rep['rse_id'] in unavailable_states:\n logging.info(prepend_str + '%s is in unavailable state. Will be removed from the list of bad PFNs' % str(rep['pfn']))\n bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)\n elif expires_at < datetime.now():\n logging.info('%s PFN %s expiration time (%s) is older than now and is not in unavailable state. Removing the PFNs from bad_pfns', prepend_str, str(rep['pfn']), expires_at)\n bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)\n except (DataIdentifierNotFound, ReplicaNotFound):\n logging.error(prepend_str + 'Will remove %s from the list of bad PFNs' % str(rep['pfn']))\n bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)\n session = get_session()\n except Exception:\n session.rollback() # pylint: disable=no-member\n logging.critical(traceback.format_exc())\n session = get_session()\n\n except Exception as error:\n logging.error(prepend_str + '%s' % (str(error)))\n\n tottime = time.time() - start_time\n if once:\n break\n if len(pfns) == bulk:\n logging.info(prepend_str + 'Processed maximum number of pfns according to the bulk size. Restart immediately next cycle')\n elif tottime < sleep_time:\n logging.info(prepend_str + 'Will sleep for %s seconds' % (sleep_time - tottime))\n time.sleep(sleep_time - tottime)\n\n heartbeat.die(executable, hostname, pid, hb_thread)\n logging.info(prepend_str + 'Graceful stop requested')\n logging.info(prepend_str + 'Graceful stop done')\n\n\ndef run(threads=1, bulk=100, once=False, sleep_time=60):\n \"\"\"\n Starts up the minos threads.\n \"\"\"\n if rucio.db.sqla.util.is_old_db():\n raise DatabaseException('Database was not updated, daemon won\\'t start')\n\n if once:\n logging.info('Will run only one iteration in a single threaded mode')\n minos(bulk=bulk, once=once)\n else:\n logging.info('starting transmogrifier threads')\n thread_list = [threading.Thread(target=minos, kwargs={'once': once,\n 'sleep_time': sleep_time,\n 'bulk': bulk}) for _ in range(0, threads)]\n [thread.start() for thread in thread_list]\n logging.info('waiting for interrupts')\n # Interruptible joins require a timeout.\n while thread_list:\n thread_list = [thread.join(timeout=3.14) for thread in thread_list if thread and thread.isAlive()]\n\n\ndef stop(signum=None, frame=None):\n \"\"\"\n Graceful exit.\n \"\"\"\n graceful_stop.set()\n","sub_path":"lib/rucio/daemons/badreplicas/minos.py","file_name":"minos.py","file_ext":"py","file_size_in_byte":15926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"400980874","text":"import numpy as np\nimport pandas as pd\nfrom enum import Enum\n\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\nclass KindNormalization(Enum):\n\tScaling = 1,\n\tZscore = 2,\n\nclass TimeSeriesData(Dataset):\n\tdef __init__(self, input_path, n_columns, idx_class, normalise, kind_normalization, range=(0,1)):\n\n\t\tnp.set_printoptions(suppress=True)\n\n\t\t# com index_col ja não inclui a coluna index \n\t\tdataframe = pd.read_csv(input_path, header=0, index_col=['Date'], engine='python')\n\n\t\t#self.x_scaler = MinMaxScaler(feature_range=(0, 1))\n\t\tdata = []\n\n\t\tif kind_normalization == KindNormalization.Zscore:\n\t\t\tself.x_scaler = StandardScaler() # mean and standart desviation\n\t\t\tself.y_scaler = StandardScaler() # mean and standart desviation\n\n\t\telif kind_normalization== KindNormalization.Scaling:\n\t\t\tself.x_scaler = MinMaxScaler(feature_range=range)\n\t\t\tself.y_scaler = MinMaxScaler(feature_range=range)\n\n\t\t#i_split = round(len(data) * split)\n\t\t#print(\"[Data] Splitting data at %d with %s\" %(i_split, split))\n\n\t\t# iloc é uma propiedade que funciona so com Dataframe e não se apliquei df.values\n\n\t\tx_data = dataframe.iloc[0:,0:n_columns]\n\t\ty_data = dataframe.iloc[0:,0:idx_class]\n\t\ty_data = y_data.shift(-1, axis=0)\n\n\t\tframe = [x_data, y_data]\n\t\tresult = pd.concat(frame, axis=1)\n\t\tresult = result.dropna()\n\n\t\tself.x_data = result.iloc[0:,0:n_columns]\n\t\tself.y_data = result.iloc[0:,-idx_class:] # the last column\n\t\t\n\t\tself.len = len(self.x_data) \n\n\t\tif normalise:\n\t\t\tself.x_data = self.x_scaler.fit_transform(self.x_data)\n\t\t\tself.y_data = self.y_scaler.fit_transform(self.y_data)\n\t\t\tself.x_data = pd.DataFrame(self.x_data)\n\t\t\tself.y_data = pd.DataFrame(self.y_data)\n\t\t#else:\n\t\t\t#data = pd.DataFrame(dataframe.values)\n\n\t\tprint(\"[Data] shape data X: \", self.x_data.shape)\n\t\tprint(\"[Data] shape data y: \", self.y_data.shape)\n\t\tprint('[Data] len:', self.len)\n\n\t\t# no pode retornar\n\t\t#return (x_data.values, y_data.values)\n\t\n\tdef load_data_series(self, split=0):\n\n\t\t#self.data = self.data.values\n\t\ti_split = round(len(self.x_data) * split)\n\n\t\tprint(\"[Data] Splitting data at %d with %s\" %(i_split, split))\n\n\t\tif i_split > 0:\n\t\t\tx_train = self.x_data.iloc[0:i_split,0:].values\n\t\t\ty_train = self.y_data.iloc[0:i_split,0:].values\n\n\t\t\tx_test = self.x_data.iloc[i_split:,0:].values\n\t\t\ty_test = self.y_data.iloc[i_split:,0:].values\n\n\t\t\treturn (x_train, y_train, x_test, y_test)\n\t\telif i_split == 0:\n\t\t\tx_data = self.x_data.iloc[0:,0:].values\n\t\t\ty_data = self.y_data.iloc[0:,0:].values\n\n\t\t\treturn (x_data, y_data)\n\n\tdef __getitem__(self, index):\n\t\t\n\t\tx = self.x_data.iloc[index,0:].values.astype(np.float).reshape(1,self.x_data.shape[1])\n\t\ty = self.y_data.iloc[index,0]\n\n\t\treturn\tx, y\n\n\tdef __len__(self):\n\t\treturn self.len\n\n\tdef inverse_transform_x(self, x):\n\t\treturn self.x_scaler.inverse_transform(x)\n\n\tdef inverse_transform_y(self, y):\n\t\treturn self.y_scaler.inverse_transform(y)\t\t","sub_path":"src/core/data/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"119347891","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, Http404\nfrom django.templatetags.static import static\nfrom .models import Images, Location, Category\nfrom django.db.models.query import QuerySet\n\ndef home(request):\n images = Images.objects.all()\n location = Location.objects.all()\n context = {\n \"images\":images,\n \"location\":location,\n }\n return render(request, 'home.html', context)\n\ndef images(request, images_id):\n try:\n images = Images.objects.get(id = images_id)\n except DoesNotExist:\n raise Http404()\n return render(request,\"gall/gallery.html\", {\"images\":images})\n\ndef search_image(request):\n if 'images' in request.GET and request.GET['images']:\n search_term = request.GET[\"images\"]\n searched_images = Images.search_by_category(search_term)\n message = f'{search_term}'\n location = Location.objects.all()\n context = {\n \"location\":location,\n \"message\":message,\n \"images\":searched_images\n }\n return render(request, 'gall/search.html',context)\n\n else:\n message = \"You haven't searched for any image\"\n return render(request, 'gall/search.html', {\"message\":message})\n\ndef display_by_location(request, id):\n location = Location.objects.all()\n images = Images.objects.filter(location__id=id)\n context = {\n \"location\":location,\n \"images\":images,\n }\n return render(request, \"location.html\", context)\n","sub_path":"photo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"395418963","text":"import numpy as np\nimport pyrealsense2 as rs\n\n\nclass RealsenseCapture:\n\n def __init__(self):\n \"\"\"\n initialize realsense streaming parameters\n \"\"\"\n\n self.width = 640\n self.height = 480\n self.fps = 30\n\n self.config = rs.config()\n self.config.enable_stream(rs.stream.color, self.width, self.height, rs.format.bgr8, self.fps)\n self.config.enable_stream(rs.stream.depth, self.width, self.height, rs.format.z16, self.fps)\n\n def start(self):\n \"\"\"\n start realsense camera\n \"\"\"\n self.pipeline = rs.pipeline()\n self.pipeline.start(self.config)\n print('starting realsense pipeline')\n\n def read(self, img_array=True):\n \"\"\"\n read each frame and convert it into numpy array\n \"\"\"\n frames = self.pipeline.wait_for_frames()\n self.color_frame = frames.get_color_frame()\n self.depth_frame = frames.get_depth_frame()\n\n if not self.color_frame or not self.depth_frame:\n return (none, none)\n\n elif img_array:\n rgb = np.asanyarray(self.color_frame.get_data())\n depth = np.asanyarray(self.depth_frame.get_data())\n return (rgb, depth)\n\n else:\n return (self.color_frame, self.depth_frame)\n\n def stop(self):\n self.pipeline.stop()","sub_path":"realsenseCapture.py","file_name":"realsenseCapture.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"620403923","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2020/03/16\nFeature selection: Relief-based feature selection algorithm.\n------\n@author: LI Chao\n\"\"\"\n\nimport numpy as np\nfrom sklearn import preprocessing\nimport os\nfrom sklearn.externals import joblib\n\nfrom el_classify_sensitive_person_train_validation import ClassifyFourKindOfPersonTrain\nfrom eslearn.utils.lc_evaluation_model_performances import eval_performance\n\n\nclass ClassifyFourKindOfPersonTest():\n \"\"\"\n This class is used to testing classification model for 2 kind of sensitive person identification.\n\n Parameters\n ----------\n data_test_file: path str \n Path of the dataset\n\n label_test_file: path str \n Path of the label\n\n path_out : \n Path to save results\n\n is_feature_selection : bool\n if perfrome feature selection.\n\n is_showfig_finally: bool\n If show figure after all iteration finished.\n\n Returns\n -------\n Save all classification results and figures to local disk.\n \"\"\"\n def __init__(selftest,\n data_test_file=None,\n label_test_file=None,\n data_train_file=None,\n models_path=None,\n path_out=None,\n is_feature_selection=False,\n is_showfig_finally=True):\n\n selftest.data_test_file = data_test_file\n selftest.label_test_file = label_test_file\n selftest.data_train_file = data_train_file\n selftest.path_out = path_out\n selftest.models_path = models_path\n selftest.is_feature_selection = is_feature_selection\n selftest.is_showfig_finally = is_showfig_finally\n\n\n def main_function(selftest):\n \"\"\"\n \"\"\"\n print('Training model and testing...\\n')\n\n # load data and mask\n mask_lassocv = joblib.load(os.path.join(selftest.path_out, 'mask_selected_features_lassocv.pkl'))\n model_feature_selection = joblib.load(os.path.join(selftest.models_path, 'model_feature_selection.pkl'))\n model_classification = joblib.load(os.path.join(selftest.models_path, 'model_classification.pkl'))\n feature_test, selftest.label_test, feature_train = selftest._load_data() \n\n # Age encoding\n feature_test[:,2] = ClassifyFourKindOfPersonTrain().age_encodeing(feature_train[:,2], feature_test[:,2])\n\n # Feature selection\n if selftest.is_feature_selection: \n feature_test = feature_test[:, mask_lassocv != 0]\n \n # Testting\n selftest.prediction, selftest.decision = selftest.testing(model_classification, feature_test)\n\n # Evaluating classification performances\n selftest.accuracy, selftest.sensitivity, selftest.specificity, selftest.AUC = eval_performance(selftest.label_test, selftest.prediction, selftest.decision, \n accuracy_kfold=None, sensitivity_kfold=None, specificity_kfold=None, AUC_kfold=None,\n verbose=1, is_showfig=0)\n\n # Save results and fig to local path\n selftest.save_results()\n selftest.save_fig()\n \n print(\"--\" * 10 + \"Done!\" + \"--\" * 10 )\n return selftest\n\n\n def _load_data(selftest):\n \"\"\"\n Load data\n \"\"\"\n data_test = np.load(selftest.data_test_file)\n label_test = np.load(selftest.label_test_file)\n data_train = np.load(selftest.data_train_file)\n return data_test, label_test, data_train\n\n def testing(selftest, model, test_X):\n predict = model.predict(test_X)\n decision = model.decision_function(test_X)\n return predict, decision\n\n def save_results(selftest):\n # Save performances and others\n import pandas as pd\n performances_to_save = np.array([selftest.accuracy, selftest.sensitivity, selftest.specificity, selftest.AUC]).reshape(1,4)\n de_pred_label_to_save = np.vstack([selftest.decision.T, selftest.prediction.T, selftest.label_test.T]).T\n performances_to_save = pd.DataFrame(performances_to_save, columns=[['Accuracy','Sensitivity', 'Specificity', 'AUC']])\n de_pred_label_to_save = pd.DataFrame(de_pred_label_to_save, columns=[['Decision','Prediction', 'Sorted_Real_Label']])\n \n performances_to_save.to_csv(os.path.join(selftest.path_out, 'test_Performances.txt'), index=False, header=True)\n de_pred_label_to_save.to_csv(os.path.join(selftest.path_out, 'test_Decision_prediction_label.txt'), index=False, header=True)\n \n def save_fig(selftest):\n # Save ROC and Classification 2D figure\n acc, sens, spec, auc = eval_performance(selftest.label_test, selftest.prediction, selftest.decision, \n selftest.accuracy, selftest.sensitivity, selftest.specificity, selftest.AUC,\n verbose=0, is_showfig=selftest.is_showfig_finally, is_savefig=1, \n out_name=os.path.join(selftest.path_out, 'Classification_performances_test.pdf'),\n legend1='Healthy', legend2='Unhealthy')\n\n#\nif __name__ == '__main__':\n # =============================================================================\n # All inputs\n data_file = r'D:\\workstation_b\\Fundation\\给黎超.xlsx'\n path_out = r'D:\\workstation_b\\Fundation'\n models_path = r'D:\\workstation_b\\Fundation'\n # =============================================================================\n \n selftest = ClassifyFourKindOfPersonTest(data_test_file=r'D:\\workstation_b\\Fundation\\feature_test.npy',\n label_test_file=r'D:\\workstation_b\\Fundation\\label_test.npy',\n data_train_file=r'D:\\workstation_b\\Fundation\\feature_train.npy',\n path_out=path_out,\n models_path=models_path,\n is_feature_selection=1)\n\n\n selftest.main_function()\n","sub_path":"eslearn/machine_learning/classfication/el_classfication_of_test_for_excel_like_data.py","file_name":"el_classfication_of_test_for_excel_like_data.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"551220774","text":"in1 = open('pan.in')\nout1 = open('pan.out', 'w')\n\n\nn = int(in1.readline())\n\nfor i in range(0, n):\n str = in1.readline()\n flip = 0\n l = len(str)-1\n \n for j in range(0, l-1):\n if str[j] == str[j+1]: continue\n flip += 1\n if str[l-1] == '-': flip += 1\n \n out1.write(\"Case #%d: %d\\n\" %(i+1, flip))\n\nin1.close();\nout1.close();\n","sub_path":"codes/CodeJamCrawler/16_0_2/neoloong/pan.py","file_name":"pan.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"299290873","text":"from dados import database_info as database_configs\nfrom office365.runtime.auth.user_credential import UserCredential\nfrom office365.sharepoint.client_context import ClientContext\n\nclass Database:\n class Sharepoint:\n def __init__(self):\n self.cliente_context = ClientContext(\n database_configs[\"Sharepoint\"][\"url_site\"]\n ).with_credentials(\n UserCredential(\n database_configs[\"Sharepoint\"][\"Usuario_dados\"][\"Usuario\"],\n database_configs[\"Sharepoint\"][\"Usuario_dados\"][\"Senha\"],\n )\n )\n\n def Itens_lista_UT(self):\n sp_list = database_configs[\"Sharepoint\"][\"list_name\"]\n sp_lists = self.cliente_context.web.lists\n s_list = sp_lists.get_by_title(sp_list)\n l_items = s_list.get_items()\n self.cliente_context.load(l_items)\n self.cliente_context.execute_query()\n return l_items\n\n def dicionario_UTs(self):\n itens = self.Itens_lista_UT()\n dicionario = {\n \"UT\": [],\n \"Coligada\": [],\n \"Nomeclatura\": [],\n \"Em Atividade\": [],\n \"Relatorio_Telemetria\": [],\n \"Relatorio_Pool\": [],\n \"Relatorio_Suprimentos\": [],\n }\n for item in itens:\n dicionario[\"UT\"].append(item.properties[\"UT\"])\n dicionario[\"Coligada\"].append(item.properties[\"Nomeclatura_UT\"])\n dicionario[\"Nomeclatura\"].append(item.properties[\"Nome_UT\"])\n dicionario[\"Em Atividade\"].append(item.properties[\"UTAtiva_x003f_\"])\n dicionario[\"Relatorio_Telemetria\"].append(\n item.properties[\"Utiliza_x00e7__x00e3_oTelemetria\"]\n )\n dicionario[\"Relatorio_Pool\"].append(\n item.properties[\"Utiliza_x00e7__x00e3_oPool\"]\n )\n dicionario[\"Relatorio_Suprimentos\"].append(\n item.properties[\"Utiliza_x00e7__x00e3_oSuprimento\"]\n )\n return dicionario","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"380278374","text":"#!/usr/bin/env python\n# coding: utf-8\nimport random\nimport Tkinter\n\n\ndef create_random_numbers():\n minimum = int(min_number.get())\n maximum = int(max_number.get())\n count = int(count_random_numbers.get())\n numbers = random.sample(range(minimum, maximum + 1), count)\n drawn_numbers.config(text=\", \".join(map(str, numbers)))\n\n\nwidth = \"300\"\nheight = \"300\"\n\nwindow = Tkinter.Tk()\nwindow.geometry(width + \"x\" + height)\nwindow.title('Lottery')\n\ninfo_min = Tkinter.Label(window, text=\"Minimum number:\")\ninfo_min.pack()\n\nmin_number = Tkinter.Entry(window)\nmin_number.pack()\n\ninfo_max = Tkinter.Label(window, text=\"Maximum number:\")\ninfo_max.pack()\n\nmax_number = Tkinter.Entry(window)\nmax_number.pack()\n\ninfo_count = Tkinter.Label(window, text=\"How many numbers from 1 to 100\\n do you want to draw?\")\ninfo_count.pack()\n\ncount_random_numbers = Tkinter.Entry(window)\ncount_random_numbers.pack()\n\nbtn_draw_numbers = Tkinter.Button(window, text=\"Draw Numbers\", command=create_random_numbers)\nbtn_draw_numbers.configure(background='#00FF00')\nbtn_draw_numbers.pack()\n\nresult = Tkinter.Label(window, text=\"Result:\")\nresult.pack()\n\ndrawn_numbers = Tkinter.Label(window, text=\"\", wraplengt=width)\ndrawn_numbers.pack(fill=Tkinter.BOTH, expand=True)\n\n\nwindow.mainloop()\n","sub_path":"14_01_GUI_Ex_1/lottery.py","file_name":"lottery.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"289241720","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n # 在查找回文串之前,先对原串预处理,避免对偶数回文串特殊处理\n ss = '#' + '#'.join([x for x in s]) + '$'\n print(ss)\n\n idx = 0 # 记录当前回文串右边界最大的中心下标\n mx = 0 # 记录当前回文串最大右边界的下标\n p = [0] * len(ss) # 记录下标为i的回文串的半径,不包含i本身 \n maxStr = \"\"\n\n for i in range(1, len(ss)-1): # 开始和结尾的特殊符号可以不处理\n if i < mx:\n j = idx * 2 - i # 关于中心点对称下标\n p[i] = min(mx-i, p[j])\n\n # 重新拓展比较\n while ss[i - p[i] - 1] == ss[i + p[i] + 1]: # 不必担心溢出,首尾都是特殊符号\n p[i] += 1\n\n # 更新中心下标\n if i + p[i] > mx:\n mx = i + p[i]\n idx = i\n\n # 更新最长串\n if 1 + 2 * p[i] >= len(maxStr) * 2 + 1:\n tmpStr = ss[i-p[i] : i+p[i]+1].replace('#', '')\n if len(tmpStr) > len(maxStr):\n maxStr = tmpStr\n return maxStr\n","sub_path":"Q1-Q9/Q5_LongestPalindrome.py","file_name":"Q5_LongestPalindrome.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"323394868","text":"# claude_low_level_library with numba acceleration\n\n# claude low level library\n\nimport numpy as np\nfrom numba import njit, prange\n\ninv_180 = np.pi/180\ninv_90 = np.pi/90\nsigma = 5.67E-8\n\n# define various useful differential functions:\n# gradient of scalar field a in the local x direction at point i,j\n@njit(cache=True)\ndef scalar_gradient_x(a, dx, nlon, i, j, k):\n\treturn (a[i,(j+1)%nlon,k]-a[i,(j-1)%nlon,k])/dx[i]\n\n@njit(cache=True)\ndef scalar_gradient_x_2D(a, dx, nlon, i, j):\n\treturn (a[i,(j+1)%nlon]-a[i,(j-1)%nlon])/dx[i]\n\n\n# gradient of scalar field a in the local y direction at point i,j\n@njit(cache=True)\ndef scalar_gradient_y(a, dy, nlat, i, j, k):\n\tif i == 0:\n\t\treturn 2*(a[i+1,j,k]-a[i,j,k])/dy\n\telif i == nlat-1:\n\t\treturn 2*(a[i,j,k]-a[i-1,j,k])/dy\n\telse:\n\t\treturn (a[i+1,j,k]-a[i-1,j,k])/dy\n\n\n@njit(cache=True)\ndef scalar_gradient_y_2D(dy, nlat, i, j):\n\tif i == 0:\n\t\treturn 2*(a[i+1,j]-a[i,j])/dy\n\telif i == nlat-1:\n\t\treturn 2*(a[i,j]-a[i-1,j])/dy\n\telse:\n\t\treturn (a[i+1,j]-a[i-1,j])/dy\n\n@njit(cache=True)\ndef scalar_gradient_z_1D(a, pressure_levels, k):\n\tnlevels = len(pressure_levels)\n\tif k == 0:\n\t\treturn -(a[k+1]-a[k])/(pressure_levels[k+1]-pressure_levels[k])\n\telif k == nlevels-1:\n\t\treturn -(a[k]-a[k-1])/(pressure_levels[k]-pressure_levels[k-1])\n\telse:\n\t\treturn -(a[k+1]-a[k-1])/(pressure_levels[k+1]-pressure_levels[k-1])\n\n\n@njit(cache=True)\ndef surface_optical_depth(lat):\n\treturn 4# + np.cos(lat*inv_90)*2\n\n@njit(cache=True)\ndef thermal_radiation(a):\n\treturn sigma*(a**4)\n\n# power incident on (lat,lon) at time t\n@njit(cache=True)\ndef solar(insolation, lat, lon, t, day, year, axial_tilt):\n\tsun_longitude = -t % day\n\tsun_latitude = axial_tilt*np.cos(t*2*np.pi/year)\n\tvalue = insolation*np.cos((lat-sun_latitude)*inv_180)\n\tlon_diff = cos_lon = 0.0\n\n\tif value < 0:\t\n\t\treturn 0\n\telse:\n\t\tsun_longitude *= 360/day\n\t\tlon_diff = lon-sun_longitude\n\t\tcos_lon = np.cos(lon_diff*inv_180) \n\t\tvalue *= cos_lon\n\t\t\n\t\tif value < 0:\n\t\t\tif lat + sun_latitude > 90:\n\t\t\t\treturn insolation*np.cos((lat+sun_latitude)*inv_180)*cos_lon\n\t\t\telif lat + sun_latitude < -90:\n\t\t\t\treturn insolation*np.cos((lat+sun_latitude)*inv_180)*cos_lon\n\t\t\telse:\n\t\t\t\treturn 0\n\t\telse:\n\t\t\treturn value\n\n@njit(cache=True)\ndef profile(a):\n\treturn np.mean(np.mean(a,axis=0),axis=0)\n\n@njit(cache=True, parallel=True)\ndef t_to_theta(temperature_atmos, pressure_levels):\n\toutput = np.zeros_like(temperature_atmos)\n\tk = 0\n\tinv_p0 = 0.0\n\n\tinv_p0 = 1/pressure_levels[0]\n\tfor k in prange(len(pressure_levels)):\n\t\toutput[:,:,k] = temperature_atmos[:,:,k]*(pressure_levels[k]*inv_p0)**(-0.286)\n\n\treturn output\n\n@njit(cache=True, parallel=True)\ndef theta_to_t(theta, pressure_levels):\n\toutput = np.zeros_like(theta)\n\n\tinv_p0 = 1/pressure_levels[0]\n\tfor k in prange(len(pressure_levels)):\n\t\toutput[:,:,k] = theta[:,:,k]*(pressure_levels[k]*inv_p0)**(0.286)\n\n\treturn output","sub_path":"claude_low_level_library_numba.py","file_name":"claude_low_level_library_numba.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"277118085","text":"import webapp2\nimport MySQLdb\nimport json\n\nfrom contextlib import closing\n\nfrom lib.hitchcfg import CONFIG\nfrom lib.util import connectdb, errorMessage, writeOut\nfrom lib.util import checkCntType, checkLogin, checkJsonStruct\nfrom lib.geo import *\nfrom lib.sql import SQLqueries\n\nclass PostSpotHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\twriteOut(self, 405, \"BAD_REQ\")\n\t\t\n\tdef post(self):\n\t\tif not checkCntType(self):\n\t\t\treturn\n\t\t\n\t\ttry:\n\t\t\tjsonData = json.loads(self.request.body)\n\t\texcept ValueError:\n\t\t\twriteOut(self, 400, \"BAD_JSON\")\n\t\t\treturn\n\t\t\n\t\tif not checkValues(self, jsonData):\n\t\t\treturn\n\t\t\n\t\twith closing(connectdb()) as db:\n\t\t\tdb.autocommit(False)\n\t\t\t\n\t\t\tuserid = jsonData['userid']\n\t\t\thash = jsonData['hash']\n\t\t\tlat = jsonData['pos']['lat']\n\t\t\tlng = jsonData['pos']['lng']\n\t\t\tdesc = jsonData['description']\n\t\t\t\n\t\t\tif not checkLogin(self, db, userid, hash):\n\t\t\t\treturn\n\t\t\t\n\t\t\ttry:\n\t\t\t\twith closing(db.cursor()) as cursor:\n\t\t\t\t\tborders = geocalc(lat, lng, 0.015)\n\t\t\t\t\tcursor.execute(SQLqueries.select_spots_close, borders2tuple(borders))\n\t\t\t\t\t\n\t\t\t\t\tif cursor.rowcount > 0:\n\t\t\t\t\t\twriteOut(self, 400, \"SPOT_EXISTS\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tcursor.execute(\"\"\"\n\t\t\t\t\t\tINSERT INTO spots (lat, lng, nrides, userid, description)\n\t\t\t\t\t\tVALUES (%s, %s, 0, %s, %s)\"\"\", (lat, lng, userid, desc))\n\t\t\t\t\t\tdb.commit()\n\t\t\t\t\t\twriteOut(self, 200, \"OK\")\n\t\t\texcept MySQLdb.Error:\n\t\t\t\tdb.rollback()\n\t\t\t\twriteOut(self, 501, \"MYSQL_ERROR\")\n\ndef checkValues(self, jsonData):\n\texpected = {\n\t\t'userid': 'int',\n\t\t'hash': 'string',\n\t\t'description': 'string',\n\t\t'pos': {\n\t\t\t'lat': 'float',\n\t\t\t'lng': 'float'\n\t\t}\n\t}\n\t\n\tif not checkJsonStruct(expected, jsonData):\n\t\twriteOut(self, 400, 'INVAL_STRUCT')\n\t\treturn False\n\t\t\n\tif jsonData['userid'] < 1:\n\t\twriteOut(self, 400, 'INVAL_UID')\n\t\treturn False\n\t\t\n\tif not len(jsonData['hash']) == 32:\n\t\twriteOut(self, 400, 'INVAL_HASH')\n\t\treturn False\n\t\n\tif jsonData['pos']['lat'] < -90 or jsonData['pos']['lat'] > 90:\n\t\twriteOut(self, 400, 'INVAL_LAT:pos')\n\t\treturn False\n\t\t\n\tif jsonData['pos']['lng'] < -180 or jsonData['pos']['lng'] > 180:\n\t\twriteOut(self, 400, 'INVAL_LNG:pos')\n\t\treturn False\n\t\n\tif len(jsonData['description']) > 400:\n\t\twriteOut(self, 400, 'INVAL_DESC')\n\t\treturn False\n\t\n\treturn True","sub_path":"Backend/app/postspot.py","file_name":"postspot.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"95401499","text":"#!/usr/bin/env python3\n\ndef factors_2(n):\n for k in range(1,n+1):\n if n % k == 0:\n yield k\n \ndef factors_3(n):\n k = 1\n rem_factors = []\n while k * k < n:\n if n % k == 0:\n yield k\n rem_factors.append(n //k)\n k += 1\n if k * k == n:\n rem_factors.append(k)\n\n while rem_factors:\n yield rem_factors.pop()\n \nif __name__ =='__main__':\n gen2 = factors_2(100)\n for factor in gen2:\n print(factor)\n\n print('\\n')\n \n gen3 = factors_3(100)\n for factor in gen3:\n print(factor)\n \n \n","sub_path":"Chapter#01/ex_C_1_27.py","file_name":"ex_C_1_27.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45646201","text":"def distance_on_unit_sphere(lat1, long1, lat2, long2):\n \"\"\" function to calculate the distance in miles between two nodes (assuming straight line segments on spherical globe) \"\"\"\n \n import math\n \n if(lat1 - lat2 == 0 and long1 - long2 == 0):\n return 0.\n else:\n degrees_to_radians = math.pi/180.0\n phi1 = (90.0 - lat1)*degrees_to_radians\n phi2 = (90.0 - lat2)*degrees_to_radians\n theta1 = long1*degrees_to_radians\n theta2 = long2*degrees_to_radians\n cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2))\n arc = math.acos(cos)\n return arc*3960.\n\ndef distance_between_points(lat1, long1, lat2, long2):\n \"\"\" function to calculate the distance in miles between two nodes assuming straight line on flat surface \"\"\"\n\n xdiff = abs(long2 - long1)*57.912\n ydiff = abs(lat2 - lat1)*69.172\n distance = (xdiff**2 + ydiff**2)**(0.5)\n return distance","sub_path":"app/dist_sphere.py","file_name":"dist_sphere.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"476662539","text":"# 가장 작은 데이터를 선택해 맨 앞에 있는 데이터와 바꾸고,\n# # 그 다음 작은 데이터를 선택해 앞에서 두번째 데이터와 바꾸는 과정 반복\n#\n# array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\n#\n# for i in range(len(array)):\n# min_index = i\n# for j in range(i + 1, len(array)):\n# if array[min_index] > array[j]:\n# min_index = j\n# array[i], array[min_index] = array[min_index], array[i] # 스왑 코드\n#\n# print(array)\n#\n# # 시간 복잡도 - O(n^2) -- 데이터 개수가 늘어 날 수록 엄청 커짐\n\n##############################################\n\narray = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\n\nfor i in range(len(array)):\n min_value = i\n for j in range(i + 1, len(array)):\n if array[min_value] > array[j]:\n min_value = j\n array[i], array[min_value] = array[min_value], array[i]\n\nprint(array)\n\n################################# 스왑\na = 3;\nb = 5;\n\ntemp = a;\na = b;\nb = temp;\n\na, b = b, a","sub_path":"python_grammer/dataStructure/sortEx/선택정렬.py","file_name":"선택정렬.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"212254384","text":"import pygame, random\r\nimport cores\r\nimport entidades\r\n\r\nclass Lana(entidades.Entidade):\r\n\tdef __init__(self, x, y, largura, altura, cor):\r\n\t\tentidades.Entidade.__init__(self, x, y, largura, altura, cor)\r\n\t\tself.velocidadeX = 0.0\r\n\t\tself.velocidadeXMax = 5.0\r\n\t\tself.velocidadeY = 0.0\r\n\t\tself.velocidadeYMax = 20.0\r\n\t\tself.gravidade = 0.3\r\n\t\tself.colidindo = False\r\n\t\tself.ad = [False, False]\r\n\t\tself.forcaDoPulo = -8\r\n\t\tself.impulso = 0\r\n\r\n\tdef atualizarPosicao(self, largura, altura, tempo):\r\n\t\t#Eixo X\r\n\t\tif(self.ad[0] == True and self.x > 0):\r\n\t\t\tself.x -= self.velocidadeXMax * tempo\r\n\t\tif(self.ad[1] == True and self.x < (largura - self.largura)):\r\n\t\t\tself.x += self.velocidadeXMax * tempo\r\n\t\t#Eixo Y\r\n\t\tif(self.colidindo == False):\r\n\t\t\tif(self.velocidadeY < self.velocidadeYMax):\r\n\t\t\t\tself.velocidadeY += self.gravidade * tempo\r\n\t\t\tself.y += self.velocidadeY * tempo\r\n\t\telse:\r\n\t\t\tself.velocidadeY = self.impulso * tempo\r\n\r\n\t\t#AtualizarPosisoes\r\n\t\tself.corpo = pygame.Rect(self.x, self.y, self.largura, self.altura)\r\n\t\tself.topo = pygame.Rect(self.x, (self.y - self.alturaTB), self.larguraTB, self.alturaTB)\r\n\t\tself.base = pygame.Rect(self.x, (self.y + self.altura), self.larguraTB, self.alturaTB)\r\n\t\tself.direita = pygame.Rect((self.x - self.larguraDE), self.y, self.larguraDE, self.alturaDE)\r\n\t\tself.esquerda = pygame.Rect((self.x + self.largura), self.y, self.larguraDE, self.alturaDE)\r\n\r\n\tdef botaoPressionado(self, key):\r\n\t\tif(key == pygame.K_a):\r\n\t\t\tself.ad[0] = True\r\n\t\tif(key == pygame.K_d):\r\n\t\t\tself.ad[1] = True\r\n\t\tif(key == pygame.K_w):\r\n\t\t\tself.colidindo = False\r\n\t\t\tself.velocidadeY = self.forcaDoPulo\r\n\r\n\r\n\tdef botaoSolto(self, key):\r\n\t\tif(key == pygame.K_a):\r\n\t\t\tself.ad[0] = False\r\n\t\tif(key == pygame.K_d):\r\n\t\t\tself.ad[1] = False\t\r\n\r\n\tdef colidiuTopo(self, y):\r\n\t\tif(self.velocidadeY < 0):\r\n\t\t\tself.velocidadeY = (self.velocidadeY * (-1)) * 0.5\r\n\r\n\tdef colidiuBase(self, y):\r\n\t\tif(self.velocidadeY < 0):\r\n\t\t\tself.colidindo = False\r\n\t\telse:\r\n\t\t\tself.colidindo = True\r\n\t\t\tself.y = y - self.altura - 4\r\n\r\n\tdef colidiuDireita(self, x, largura):\r\n\t\tself.x = x + largura + 8\r\n\r\n\tdef colidiuEsquerda(self, x):\r\n\t\tself.x = x - self.largura - 8\r\n\t\t\r\n\r\n\t\t\r\n\tdef vibrar(self):\r\n\t\tself.x += random.randint(-1, 1)\r\n\t\tself.y += random.randint(-1, 1)\r\n\t\tself.corpo = pygame.Rect(self.x, self.y, self.largura, self.altura)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"614504416","text":"'''\nimports\n'''\nfrom mock import patch\nfrom app.compute_data import BitBucket, GitHub\n\n\nclass TestBitBucket:\n \"\"\"\n test suite for computed bitbucket data\n \"\"\"\n def test_bitbucket_data(self, bb_results):\n with patch('app.compute_data.BitBucket.bit_results') as mock_data:\n mock_data.return_value = bb_results\n\n b = BitBucket('pygame')\n result = b.bit_results()\n assert result == bb_results\n\n\nclass TestGitHub:\n \"\"\"\n test suite for computed github data\n \"\"\"\n def test_github_data(self, g_results):\n with patch('app.compute_data.GitHub.git_results') as mock_data:\n mock_data.return_value = g_results\n\n g = GitHub('pygame')\n result = g.git_results()\n assert result == g_results\n\n","sub_path":"tests/test_compute_data.py","file_name":"test_compute_data.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"392416997","text":"# This is an implementation of the Heuristics method for Hexapawn game operating on 5x5 board. \n# Computer (B) plays second and always guarantees to win. Player (W) plays first. \n# The explanation of the Hexapawn game can be found here: https://en.wikipedia.org/wiki/Hexapawn\n\nimport sys\n\ndef drawBoard(board):\n # This function prints out the board that it was passed.\n\n # \"board\" is a list of 10 strings representing the board (ignore index 0)\n print(' ')\n print(' 1 | 2 | 3 | 4 | 5')\n print(' ' + board[21] + ' | ' + board[22] + ' | ' + board[23] + ' | ' + board[24] + ' | ' + board[25])\n print(' ---------------------')\n print(' ' + board[16] + ' | ' + board[17] + ' | ' + board[18] + ' | ' + board[19] + ' | ' + board[20])\n print(' ---------------------')\n print(' ' + board[11] + ' | ' + board[12] + ' | ' + board[13] + ' | ' + board[14] + ' | ' + board[15])\n print(' ---------------------')\n print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + ' | ' + board[10])\n print(' ---------------------')\n print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + ' | ' + board[4] + ' | ' + board[5])\n \ndef getCompMoves(board):\n pmoves = []\n for i in range(1, 26):\n if board[i] == 'B':\n if goodMove(board, i-5):\n pmoves.append((i-5, i))\n if (i == 21 or i == 16 or i == 11 or i == 6) and (killPRight(board, i)):\n pmoves.append((i-4, i))\n elif (i == 25 or i == 20 or i == 15 or i == 10) and (killPLeft(board, i)):\n pmoves.append((i-6, i))\n else:\n if killPRight(board, i):\n pmoves.append((i-4, i))\n if killPLeft(board, i):\n pmoves.append((i-6, i)) \n return pmoves\n\ndef getPlayMoves(board):\n pmoves = []\n for i in range(1, 26):\n if board[i] == 'W':\n if goodMove(board, i+5):\n pmoves.append((i+5, i))\n if (i == 1 or i == 16 or i == 11 or i == 6) and (killCRight(board, i)):\n pmoves.append((i+6, i))\n elif (i == 5 or i == 20 or i == 15 or i == 10) and (killCLeft(board, i)):\n pmoves.append((i+4, i))\n elif (i == 21 or i==22 or i==23 or i==25):\n print(\"here\")\n else:\n if killCLeft(board, i):\n pmoves.append((i+4, i))\n if killCRight(board, i):\n pmoves.append((i+6, i)) \n return pmoves\n\ndef killPRight(board, position):\n if position == 20 or position == 15 or position == 10:\n return False\n if board[position - 4] == 'W':\n return True\n else:\n return False\n \ndef killPLeft(board, position):\n if position == 16 or position == 11 or position == 6:\n return False\n if board[position - 6] == 'W':\n return True\n else:\n return False\n\ndef killCRight(board, position):\n if position == 20 or position == 15 or position == 10:\n return False\n if board[position + 6] == 'B':\n return True\n else:\n return False\n \ndef killCLeft(board, position):\n if position == 16 or position == 11 or position == 6:\n return False\n if board[position + 4] == 'B':\n return True\n else:\n return False\n\n\ndef goodMove(board, position):\n if board[position] == ' ':\n return True\n else:\n return False\n\ndef call(board):\n x = getCompMoves(board) \n t = -1\n a = -30\n for l in range(1, 26):\n if board[l] == 'B':\n if killPLeft(board,l):\n return (l-6, l)\n if killPRight(board,l):\n print(\"here\")\n return (l-4, l)\n\n for i in x:\n testBoard = board[:]\n makeMove(testBoard, i, 'B')\n y = recur(testBoard, getEnemy('B'), -25, 25, 0)\n \n if y >a:\n a = y\n t = i\n print(t)\n return t\n \ndef getEnemy(player):\n if (player == 'W'):\n newPlayer = 'B'\n else:\n newPlayer = 'W'\n return newPlayer\n \ndef heuristic(board):\n points = 0\n for i in range(1, 26):\n if board[i] == 'W':\n if killCLeft(board,i):\n points += 10\n if killCRight(board,i):\n points += 10\n if i == 16 or i == 17 or i == 18 or i == 19 or i == 20:\n if killCRight(board, i) or killCLeft(board, i):\n points += 10\n else:\n points -= 10\n \n if i == 11 or i == 12 or i == 13 or i == 14 or i == 15:\n if killCRight(board, i) or killCLeft(board, i):\n points += 5\n else:\n points -= 5\n \n else:\n points -= 3\n if board[i] == 'B':\n if killPLeft(board,i):\n points -= 10\n if killPRight(board,i):\n points -= 10\n if i == 6 or i == 7 or i == 8 or i == 9 or i == 10:\n if killPRight(board, i) or killPLeft(board, i):\n points -= 10\n else:\n points += 10\n if i == 11 or i == 12 or i == 13 or i == 14 or i == 15:\n if killPRight(board, i) or killPLeft(board, i):\n points -= 5\n else:\n points += 5\n else:\n points += 3\n return points\n\ndef recur(board, player, alpha, beta, countit):\n if player == 'W':\n moves = getCompMoves(board)\n else:\n moves = getPlayMoves(board)\n if Win(board, 'B') == 1:\n return 1000\n \n elif Win(board, 'W') == 1:\n return -1000\n \n elif player == 'B' and len(moves) == 0: \n return -1000\n elif player == 'W' and len(moves) == 0: \n return 1000\n elif countit == 7:\n points = heuristic(board)\n return points\n\n \n else:\n countit += 1\n \n for i in moves:\n \n testBoard = board[:]\n makeMove(testBoard, i, player)\n x = recur(testBoard, getEnemy(player), alpha, beta, countit)\n if player == 'B':\n if x > alpha:\n alpha = x\n \n\n else:\n if x < beta:\n beta = x\n \n if player == 'B':\n return alpha\n else:\n return beta\n \ndef Win(board, player):\n if player == 'W':\n if board[21] =='W':\n return 1\n if board[22] == 'W':\n return 1\n if board[23] == 'W':\n return 1\n if board[24] == 'W':\n return 1\n if board[25] == 'W':\n return 1\n else:\n return 0\n else:\n if board[1] == 'B':\n return 1\n if board[2] == 'B':\n return 1\n if board[3] == 'B':\n return 1\n if board[4] == 'B':\n return 1\n if board[5] == 'B':\n return 1\n else:\n return 0\n \ndef makeMove(board, tups, player):\n delete = tups[1]\n moveit = tups[0]\n board[delete] = ' '\n board[moveit] = player\n\ndef Pmoves(board):\n pmoves = []\n if board[4] == ' ' and board[1] == 'W':\n pmoves.append((4,1))\n if board[4] == 'B' and board[2] == 'W':\n pmoves.append((4,2))\n if board[5] == ' ' and board[2] == 'W':\n pmoves.append((5,2))\n if board[5] == 'B' and board[1] == 'W':\n pmoves.append((5,1))\n if board[5] == 'B' and board[3] == 'W':\n pmoves.append((5,3))\n if board[6] == ' ' and board[3] == 'W':\n pmoves.append((6,3))\n if board[6] == 'B' and board[2] == 'W':\n pmoves.append((6,2))\n if board[7] == ' ' and board[4] == 'W':\n pmoves.append((7,4))\n if board[7] == 'B' and board[5] == 'W':\n pmoves.append((7,5))\n if board[8] == ' ' and board[5] == 'W':\n pmoves.append((8,5))\n if board[8] == 'B' and board[4] == 'W':\n pmoves.append((8,4))\n if board[8] == 'B' and board[6] == 'W':\n pmoves.append((8,6))\n if board[9] == ' ' and board[6] == 'W':\n pmoves.append((9,6))\n if board[9] == 'B' and board[5] == 'W':\n pmoves.append((9,5))\n return pmoves\n \ndef Cmoves(board):\n pmoves = []\n if board[4] == ' ' and board[7] == 'B':\n pmoves.append((4,7))\n if board[4] == 'W' and board[8] == 'B':\n pmoves.append((4,8))\n if board[5] == ' ' and board[8] == 'B':\n pmoves.append((5,8))\n if board[5] == 'W' and board[7] == 'B':\n pmoves.append((5,7))\n if board[5] == 'W' and board[9] == 'B':\n pmoves.append((5,9))\n if board[6] == ' ' and board[9] == 'B':\n pmoves.append((6,9))\n if board[6] == 'W' and board[8] == 'B':\n pmoves.append((6,8))\n if board[1] == ' ' and board[4] == 'B':\n pmoves.append((1,4))\n if board[1] == 'W' and board[5] == 'B':\n pmoves.append((1,5))\n if board[2] == ' ' and board[5] == 'B':\n pmoves.append((2,5))\n if board[2] == 'W' and board[4] == 'B':\n pmoves.append((2,4))\n if board[2] == 'W' and board[6] == 'B':\n pmoves.append((2,6))\n if board[3] == ' ' and board[6] == 'B':\n pmoves.append((3,6))\n if board[3] == 'W' and board[5] == 'B':\n pmoves.append((3,5))\n return pmoves\n\n\n\nplayer1 = 'W'\nplayer2 = 'B'\n\n # Reset the board\ngameBoard = [' '] * 26\ngameBoard[1] = 'W'\ngameBoard[2] = 'W'\ngameBoard[3] = 'W'\ngameBoard[4] = 'W'\ngameBoard[5] = 'W'\n\ngameBoard[21] = 'B'\ngameBoard[22] = 'B'\ngameBoard[23] = 'B'\ngameBoard[24] = 'B'\ngameBoard[25] = 'B'\n\ngameIsPlaying = True\ndrawBoard(gameBoard)\nwhile (gameIsPlaying == True):\n p1 = True\n while( p1 == True):\n user = input(\"Position of W to move (1-25): \")\n user2 = input(\"Move to (1-25): \")\n \n themove = (int(user2),int(user))\n makeMove(gameBoard, themove, 'W')\n drawBoard(gameBoard)\n if Win(gameBoard, 'W') == 1:\n print(\"You Win!\")\n sys.exit()\n x = getCompMoves(gameBoard)\n if len(x) == 0:\n print(\"You Win!\")\n sys.exit()\n\n\n test = getCompMoves(gameBoard)\n t = call(gameBoard)\n makeMove(gameBoard, t, 'B')\n drawBoard(gameBoard)\n if Win(gameBoard, 'B') == 1:\n print(\"You Lose!\")\n sys.exit()\n y = getPlayMoves(gameBoard)\n if len(y) == 0:\n print(\"You Lose!\")\n sys.exit()\n\n","sub_path":"5hexapawn.py","file_name":"5hexapawn.py","file_ext":"py","file_size_in_byte":10677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"198896838","text":"import pygame\nimport random\n\n# screen parameters\nSIZE = (900, 500)\nscreen = pygame.display.set_mode(SIZE)\npygame.display.set_caption('MIS PRIMERAS FIGURAS')\npygame.display.set_icon(pygame.image.load('logo.png'))\npygame.init()\n\n\n# images\nmenu_bg = pygame.image.load('MenuPrincipal.png')\nlevel1_bg = pygame.image.load('Facil.png')\nlevel2_bg = pygame.image.load('Medio.png')\nlevel3_bg = pygame.image.load('Dificil.png')\nvictory_bg = pygame.image.load('PantallaGanado.png')\ndefeat_bg = pygame.image.load('PantallaPerdido.png')\ncredits_img = pygame.image.load('TextoCreditos.png')\n\n# font\nfont = pygame.font.Font('Pixelmania.ttf', 25)\n\n# dictionary\nfigures = {0: 'CIRCULO', 1: 'RECTANGULO', 2: 'CUADRADO', 3: 'ROMBO',\n 4: 'CORAZON', 5: 'FLECHA', 6: 'PENTAGONO', 7: 'HEXAGONO', 8: 'CRUZ',\n 9: 'ESTRELLA', 10: 'TRIANGULO', 11: 'TRIANGULO', 12: 'TRIANGULO',\n 13: 'TRIANGULO', 14: 'ROMBOIDE', 15: 'ELIPSE', 16: 'TRAPECIO',\n 17: 'TRAPEZOIDE', 18: 'MEDIO CIRCULO', 19: 'CUBO', 20: 'PIRAMIDE',\n 21: 'CILINDRO', 22: 'CONO', 23: 'ESFERA', 24: 'ELIPSOIDE',\n 25: 'PRISMA', 26: 'PRISMA'}\ntriangles = {0: 'EQUILATERO', 1: 'ESCALENO', 2: 'RECTANGULO', 3: 'ISOCELES'}\nprism = {5: 'RECTANGULAR', 6: 'TRIANGULAR'}\n\n\n# Classes\nclass SpriteSheet:\n def __init__(self, f_name):\n self.image = pygame.image.load(f_name) # sprite sheet\n self.sprites = [] # list of sprites\n self.current_sprite = 0\n\n # obtains sprites from the sheet\n def get_sprite(self, width, height, x, y):\n self.sprites.append(self.image.subsurface(x, y, width, height))\n\n # updates sprites and changes the image\n def update(self, speed):\n self.current_sprite += speed\n if self.current_sprite >= len(self.sprites):\n self.current_sprite = 0\n self.image = self.sprites[int(self.current_sprite)]\n\n\nclass Card:\n def __init__(self):\n self.boxes = []\n self.ready = True\n self.guessed = []\n\n # fill with random numbers the boxes in the card\n def fill_boxes(self, diff):\n j = 0\n if self.ready:\n if diff == 0:\n max_range = 8\n elif diff == 1:\n max_range = 18\n else:\n max_range = 26\n while j < 9:\n rn = random.randint(0, max_range)\n if rn not in self.boxes:\n self.boxes.append(rn)\n self.guessed.append(False)\n j += 1\n self.ready = False\n\n\n# width & height\nAX = 960 / 3\nAY = 1280 / 4\nFX = 650 / 4\nFY = 813 / 5\nGX = (476, 591, 707)\nGY = (102, 222, 342)\n\n\n# all stages of the game\nclass GameStage:\n def __init__(self):\n self.stage = 0\n self.actual_stage = 0\n self.card = Card()\n self.easy_figures = SpriteSheet('Figuras1.png')\n self.medium_figures = SpriteSheet('Figuras1.png')\n self.hard_figures = SpriteSheet('Figuras_3d1.png')\n self.tiger = SpriteSheet('animals.png')\n self.panda = SpriteSheet('animals.png')\n self.sloth = SpriteSheet('animals.png')\n self.frog = SpriteSheet('animals.png')\n self.medal = SpriteSheet('animals.png')\n self.mark = SpriteSheet('marks1.png')\n self.lifes = []\n self.lifes.append(SpriteSheet('corazon.png'))\n self.lifes.append(SpriteSheet('corazon.png'))\n self.lifes.append(SpriteSheet('corazon.png'))\n self.credits_bg = SpriteSheet('Fondo_geometrico1.png')\n self.figures_ready = True\n self.figures = []\n self.corrects = 0\n self.errors = 0\n self.actual_figure = 0\n self.get_sprites()\n\n # Fills the list figures with random values\n def fill_figures(self, min_value, max_value, stg):\n i = 0\n if self.figures_ready:\n self.actual_stage = stg\n while i <= max_value:\n rn = random.randint(min_value, max_value)\n if rn not in self.figures:\n self.figures.append(rn)\n i += 1\n self.figures_ready = False\n\n # checks if the figure choosen is the same as the one asked\n def check_figure(self, i):\n if i != -1:\n if self.card.boxes[i] == self.figures[self.actual_figure]:\n self.actual_figure += 1\n self.corrects += 1\n self.card.guessed[i] = True\n return\n elif self.figures[self.actual_figure] not in self.card.boxes and i == -1:\n self.actual_figure += 1\n return\n self.errors += 1\n self.lifes[self.errors -1].update(1)\n draw_img(self.mark.sprites[1], 641 - 250, 271 - 250)\n pygame.display.flip()\n pygame.time.delay(500)\n return\n\n # reset values in order to proceed\n def reset(self, stg):\n i = 0\n while i < 3:\n if self.lifes[i].current_sprite == 1:\n self.lifes[i].update(1)\n i += 1\n self.stage = stg\n self.actual_stage = stg\n self.errors = 0\n self.actual_figure = 0\n self.corrects = 0\n self.figures_ready = True\n self.figures = []\n self.card.ready = True\n self.card.boxes = []\n self.card.guessed = []\n\n # obtains sprites for each object\n def get_sprites(self):\n self.tiger.get_sprite(AX, AY, 0, 0)\n self.tiger.get_sprite(AX, AY, AX, 0)\n self.panda.get_sprite(AX, AY, AX * 2, 0)\n self.panda.get_sprite(AX, AY, 0, AY)\n self.sloth.get_sprite(AX, AY, AX, AY)\n self.sloth.get_sprite(AX, AY, AX * 2, AY)\n self.frog.get_sprite(AX, AY, 0, AY * 2)\n self.frog.get_sprite(AX, AY, AX, AY * 2)\n self.frog.get_sprite(AX, AY, AX * 2, AY * 2)\n self.medal.get_sprite(AX, AY, 0, AY * 3)\n self.medal.get_sprite(AX, AY, AX, AY * 3)\n self.medal.get_sprite(AX, AY, AX * 2, AY * 3)\n self.mark.get_sprite(FX, FY, 0, 0)\n self.mark.get_sprite(FX, FY, 0, FY)\n self.mark.sprites[1] = pygame.transform.scale(self.mark.sprites[1], (500, 500))\n self.easy_figures.get_sprite(FX, FY, 0, 0)\n self.easy_figures.get_sprite(FX, FY, FX, 0)\n self.easy_figures.get_sprite(FX, FY, FX * 2, 0)\n self.easy_figures.get_sprite(FX, FY, FX * 3, 0)\n self.easy_figures.get_sprite(FX, FY, 0, FY)\n self.easy_figures.get_sprite(FX, FY, FX, FY)\n self.easy_figures.get_sprite(FX, FY, FX * 2, FY)\n self.easy_figures.get_sprite(FX, FY, FX * 3, FY)\n self.easy_figures.get_sprite(FX, FY, 0, FY * 2)\n self.medium_figures.sprites = self.easy_figures.sprites\n self.medium_figures.get_sprite(FX, FY, FX, FY * 2)\n self.medium_figures.get_sprite(FX, FY, FX * 2, FY * 2)\n self.medium_figures.get_sprite(FX, FY, FX * 3, FY * 2)\n self.medium_figures.get_sprite(FX, FY, 0, FY * 3)\n self.medium_figures.get_sprite(FX, FY, FX, FY * 3)\n self.medium_figures.get_sprite(FX, FY, FX * 2, FY * 3)\n self.medium_figures.get_sprite(FX, FY, FX * 3, FY * 3)\n self.medium_figures.get_sprite(FX, FY, 0, FY * 4)\n self.medium_figures.get_sprite(FX, FY, FX, FY * 4)\n self.medium_figures.get_sprite(FX, FY, FX * 2, FY * 4)\n self.hard_figures.sprites = self.medium_figures.sprites\n self.hard_figures.get_sprite(FX, FY, 0, 0)\n self.hard_figures.get_sprite(FX, FY, FX, 0)\n self.hard_figures.get_sprite(FX, FY, FX * 2, 0)\n self.hard_figures.get_sprite(FX - 1, FY, FX * 3, 0)\n self.hard_figures.get_sprite(FX, FY, 0, FY)\n self.hard_figures.get_sprite(FX, FY, FX, FY)\n self.hard_figures.get_sprite(FX, FY, FX * 2, FY)\n self.hard_figures.get_sprite(FX - 1, FY, FX * 3, FY)\n self.lifes[0].get_sprite(42, 42, 0, 0)\n self.lifes[0].get_sprite(42, 42, 42, 0)\n self.lifes[0].update(0)\n self.lifes[1].get_sprite(42, 42, 0, 0)\n self.lifes[1].get_sprite(42, 42, 42, 0)\n self.lifes[1].update(0)\n self.lifes[2].get_sprite(42, 42, 0, 0)\n self.lifes[2].get_sprite(42, 42, 42, 0)\n self.lifes[2].update(0)\n self.credits_bg.get_sprite(900, 900, 0, 0)\n self.credits_bg.get_sprite(900, 900, 900, 0)\n self.credits_bg.get_sprite(900, 900, 0, 900)\n\n # shows the medal earned\n def victory(self):\n draw_img(victory_bg)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.reset(0)\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 35 <= mouse_pos[0] <= 139 and 461 <= mouse_pos[1] <= 480:\n self.reset(0)\n return\n if 679 <= mouse_pos[0] <= 884 and 461 <= mouse_pos[1] <= 480:\n self.reset(self.actual_stage + 1)\n return\n if self.errors == 0:\n draw_img(self.medal.sprites[2], int(450 - AX / 2), int(250 - AY / 2 + 50))\n if self.errors == 1:\n draw_img(self.medal.sprites[1], int(450 - AX / 2), int(250 - AY / 2 + 50))\n if self.errors == 2:\n draw_img(self.medal.sprites[0], int(450 - AX / 2), int(250 - AY / 2 + 50))\n pygame.display.flip()\n\n def defeat(self):\n draw_img(defeat_bg)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.reset(0)\n if event.type == pygame.MOUSEBUTTONDOWN:\n pass\n pygame.display.flip()\n\n # Draws the figure or the mark\n def draw_figure(self, diff):\n i = 0\n k = 0\n x = 323\n if diff == 1:\n diff_figures = self.easy_figures\n elif diff == 2:\n diff_figures = self.medium_figures\n else:\n diff_figures = self.hard_figures\n while i < 3:\n j = 0\n draw_img(self.lifes[i].image, x, 10)\n while j < 3:\n if not self.card.guessed[k]:\n draw_img(diff_figures.sprites[self.card.boxes[k]], int(GX[j] + 49 - 162 / 2),\n int(GY[i] + 49 - 162 / 2))\n else:\n draw_img(self.mark.sprites[0], int(GX[j] + 49 - 162 / 2), int(GY[i] + 49 - 162 / 2))\n j += 1\n k += 1\n i += 1\n x += 35\n\n # show credits\n def credits(self, y):\n self.credits_bg.update(0.5)\n draw_img(self.credits_bg.image, 0, -20)\n draw_img(credits_img, 0, y)\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.stage = 0 # returns to menu\n return 0\n if y == -2480:\n y = 0\n self.stage = 0\n else:\n y += -.8\n clock.tick(30)\n return y\n\n # main menu\n def menu(self):\n draw_img(menu_bg)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 700 <= mouse_pos[0] <= 875 and 289 <= mouse_pos[1] <= 320:\n self.stage = 1 # takes to level 1\n if 608 <= mouse_pos[0] <= 875 and 348 <= mouse_pos[1] <= 377:\n self.stage = 4 # takes to credits\n if 720 <= mouse_pos[0] <= 875 and 405 <= mouse_pos[1] <= 433:\n return False\n if 166 <= mouse_pos[0] <= 282 and 185 <= mouse_pos[1] <= 497:\n self.stage = 2\n pygame.display.flip()\n clock.tick(30)\n return True\n\n # level 1\n def level_1(self):\n draw_img(level1_bg)\n self.card.fill_boxes(0)\n self.fill_figures(0, 8, 1)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.reset(0)\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 476 <= mouse_pos[0] <= 574 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(0)\n if 591 <= mouse_pos[0] <= 689 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(1)\n if 707 <= mouse_pos[0] <= 805 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(2)\n if 476 <= mouse_pos[0] <= 574 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(3)\n if 591 <= mouse_pos[0] <= 689 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(4)\n if 707 <= mouse_pos[0] <= 805 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(5)\n if 476 <= mouse_pos[0] <= 574 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(6)\n if 591 <= mouse_pos[0] <= 689 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(7)\n if 707 <= mouse_pos[0] <= 805 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(8)\n if 10 <= mouse_pos[0] <= 64 and 37 <= mouse_pos[1] <= 64:\n self.stage = 0\n self.reset(0)\n return\n if self.corrects == 9:\n self.stage = 5 # takes to victory\n return\n if self.errors == 3:\n self.stage = 6\n return\n self.panda.update(0.08)\n draw_img(self.panda.image, int(450 / 2 - AX / 2), 70)\n text = font.render(f'{figures[self.figures[self.actual_figure]]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 400)\n self.draw_figure(1)\n clock.tick(30)\n pygame.display.flip()\n\n # level 2\n def level_2(self):\n draw_img(level2_bg)\n self.card.fill_boxes(1)\n self.fill_figures(0, 18, 2)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.reset(0)\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 476 <= mouse_pos[0] <= 574 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(0)\n if 591 <= mouse_pos[0] <= 689 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(1)\n if 707 <= mouse_pos[0] <= 805 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(2)\n if 476 <= mouse_pos[0] <= 574 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(3)\n if 591 <= mouse_pos[0] <= 689 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(4)\n if 707 <= mouse_pos[0] <= 805 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(5)\n if 476 <= mouse_pos[0] <= 574 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(6)\n if 591 <= mouse_pos[0] <= 689 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(7)\n if 707 <= mouse_pos[0] <= 805 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(8)\n if 92 <= mouse_pos[0] <= 306 and 460 <= mouse_pos[1] <= 477:\n self.check_figure(-1)\n if 10 <= mouse_pos[0] <= 64 and 37 <= mouse_pos[1] <= 64:\n self.stage = 0\n self.reset(0)\n return\n if self.corrects == 9:\n self.stage = 5 # takes to victory\n return\n if self.errors == 3:\n self.stage = 6\n return\n self.tiger.update(0.08)\n draw_img(self.tiger.image, int(450 / 2 - AX / 2))\n text = font.render(f'{figures[self.figures[self.actual_figure]]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 300)\n if 10 <= self.figures[self.actual_figure] <= 13:\n text = font.render(f'{triangles[self.figures[self.actual_figure] % 10]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 350)\n self.draw_figure(2)\n clock.tick(30)\n pygame.display.flip()\n\n def level_3(self):\n draw_img(level3_bg)\n self.card.fill_boxes(2)\n self.fill_figures(0, 26, 3)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.reset(0)\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouse_pos = pygame.mouse.get_pos()\n if 476 <= mouse_pos[0] <= 574 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(0)\n if 591 <= mouse_pos[0] <= 689 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(1)\n if 707 <= mouse_pos[0] <= 805 and 102 <= mouse_pos[1] <= 200:\n self.check_figure(2)\n if 476 <= mouse_pos[0] <= 574 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(3)\n if 591 <= mouse_pos[0] <= 689 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(4)\n if 707 <= mouse_pos[0] <= 805 and 222 <= mouse_pos[1] <= 320:\n self.check_figure(5)\n if 476 <= mouse_pos[0] <= 574 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(6)\n if 591 <= mouse_pos[0] <= 689 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(7)\n if 707 <= mouse_pos[0] <= 805 and 342 <= mouse_pos[1] <= 440:\n self.check_figure(8)\n if 92 <= mouse_pos[0] <= 306 and 460 <= mouse_pos[1] <= 477:\n self.check_figure(-1)\n if 10 <= mouse_pos[0] <= 64 and 37 <= mouse_pos[1] <= 64:\n self.stage = 0\n self.reset(0)\n return\n if self.corrects == 9:\n self.stage = 5 # takes to victory\n return\n if self.errors == 3:\n self.stage = 6\n return\n self.sloth.update(0.08)\n draw_img(self.sloth.image, int(450 / 2 - AX / 2))\n text = font.render(f'{figures[self.figures[self.actual_figure]]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 300)\n if 10 <= self.figures[self.actual_figure] <= 13:\n text = font.render(f'{triangles[self.figures[self.actual_figure] % 10]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 350)\n if 25 <= self.figures[self.actual_figure] <= 26:\n text = font.render(f'{prism[self.figures[self.actual_figure] % 20]}', False, (255, 255, 255))\n draw_img(text, 450 / 2 - text.get_width() / 2, 350)\n self.draw_figure(2)\n clock.tick(30)\n pygame.display.flip()\n\n\n# functions\ndef draw_img(img, x=0, y=0):\n screen.blit(img, (x, y))\n\n\n# variables\nclock = pygame.time.Clock()\nstage = GameStage()\n\n\ndef main():\n y = 0\n run = True\n while run:\n if stage.stage == 0: # if its menu\n run = stage.menu()\n elif stage.stage == 1: # if its level 1\n stage.level_1()\n elif stage.stage == 2: # if its level 2\n stage.level_2()\n elif stage.stage == 3: # if its level 3\n stage.level_3()\n elif stage.stage == 4: # if its credits\n y = stage.credits(y)\n elif stage.stage == 5: # if its victory\n stage.victory()\n elif stage.stage == 6: # if defeat\n stage.defeat()\n pygame.quit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Figuras.py","file_name":"Figuras.py","file_ext":"py","file_size_in_byte":20314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"133604025","text":"import matplotlib.pyplot as plt\n\npoints = [1, 2, 4, 8, 12, 17, 9]\nplt.plot(points, linewidth=5)\n\n# Chart title, label axes\nplt.title(\"Representation of My List\", fontsize=20)\nplt.xlabel(\"Index\", fontsize=14)\nplt.ylabel(\"Value\", fontsize=14)\n\n# Size of tick labels\nplt.tick_params(axis=\"both\", labelsize=14)\n\nplt.show()\n","sub_path":"02-readability/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"197435719","text":"import os\n\nfrom exceptions import DockerVMTestException\n\nimport yaml\n\n# Load env config file\nCONFIGFILE = 'env.yaml'\n\nif os.path.isfile(CONFIGFILE):\n with open(CONFIGFILE) as f:\n test_env = yaml.safe_load(f.read())\nelse:\n DockerVMTestException(f'{CONFIGFILE} test config file not found')\n\n# Verify all required env variables have values\ntry:\n for value in test_env['env'].values():\n assert value\nexcept AssertionError:\n DockerVMTestException(f'{CONFIGFILE} file has missing or incorrect values')\n\n# Initialize local variables from env.yaml for code readability\n\ndocker_manager_path = test_env['env']['DM_PATH']\ndocker_machine_host = test_env['env']['DM_HOST']\ndocker_machine_driver = test_env['env']['DM_DRIVER']\ndocker_machine_image = test_env['env']['DM_IMAGE']\nvirtual_box_cli = test_env['env']['VBOX_CLI']\n","sub_path":"config_env.py","file_name":"config_env.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408733841","text":"\n\n\n# Copyright Qwilt, 2011\n# \n# The code contained in this file may not be used by any other entities without explicit written permission from Qwilt.\n# \n# Author: orens\n\nfrom a.infra.misc.enum_with_value import EnumWithValue\nfrom a.infra.basic.return_codes import ReturnCodes\n\nimport socket\n\n\n\nclass PredictionData(object):\n\n def __init__ (self):\n\n self.estimatedDeliveryTrxPerConnection = 0\n self._myHasEstimatedDeliveryTrxPerConnection=False\n \n self.simulatedDiskSizeGb = 0\n self._myHasSimulatedDiskSizeGb=False\n \n self.deliveryMaxActiveConnections = 0\n self._myHasDeliveryMaxActiveConnections=False\n \n self.enabled = False\n self._myHasEnabled=False\n \n self.deliveryMaxBwMbps = 0\n self._myHasDeliveryMaxBwMbps=False\n \n\n def copyFrom (self, other):\n\n self.estimatedDeliveryTrxPerConnection=other.estimatedDeliveryTrxPerConnection\n self._myHasEstimatedDeliveryTrxPerConnection=other._myHasEstimatedDeliveryTrxPerConnection\n \n self.simulatedDiskSizeGb=other.simulatedDiskSizeGb\n self._myHasSimulatedDiskSizeGb=other._myHasSimulatedDiskSizeGb\n \n self.deliveryMaxActiveConnections=other.deliveryMaxActiveConnections\n self._myHasDeliveryMaxActiveConnections=other._myHasDeliveryMaxActiveConnections\n \n self.enabled=other.enabled\n self._myHasEnabled=other._myHasEnabled\n \n self.deliveryMaxBwMbps=other.deliveryMaxBwMbps\n self._myHasDeliveryMaxBwMbps=other._myHasDeliveryMaxBwMbps\n \n # has...() methods\n\n def hasEstimatedDeliveryTrxPerConnection (self):\n return self._myHasEstimatedDeliveryTrxPerConnection\n\n def hasSimulatedDiskSizeGb (self):\n return self._myHasSimulatedDiskSizeGb\n\n def hasDeliveryMaxActiveConnections (self):\n return self._myHasDeliveryMaxActiveConnections\n\n def hasEnabled (self):\n return self._myHasEnabled\n\n def hasDeliveryMaxBwMbps (self):\n return self._myHasDeliveryMaxBwMbps\n\n\n # setHas...() methods\n\n def setHasEstimatedDeliveryTrxPerConnection (self):\n self._myHasEstimatedDeliveryTrxPerConnection=True\n\n def setHasSimulatedDiskSizeGb (self):\n self._myHasSimulatedDiskSizeGb=True\n\n def setHasDeliveryMaxActiveConnections (self):\n self._myHasDeliveryMaxActiveConnections=True\n\n def setHasEnabled (self):\n self._myHasEnabled=True\n\n def setHasDeliveryMaxBwMbps (self):\n self._myHasDeliveryMaxBwMbps=True\n\n\n def clearAllHas (self):\n\n self._myHasEstimatedDeliveryTrxPerConnection=False\n\n self._myHasSimulatedDiskSizeGb=False\n\n self._myHasDeliveryMaxActiveConnections=False\n\n self._myHasEnabled=False\n\n self._myHasDeliveryMaxBwMbps=False\n\n\n def __str__ (self):\n items=[]\n\n x=\"\"\n if self._myHasEstimatedDeliveryTrxPerConnection:\n x = \"+\"\n leafStr = str(self.estimatedDeliveryTrxPerConnection)\n items.append(x + \"EstimatedDeliveryTrxPerConnection=\"+leafStr)\n\n x=\"\"\n if self._myHasSimulatedDiskSizeGb:\n x = \"+\"\n leafStr = str(self.simulatedDiskSizeGb)\n items.append(x + \"SimulatedDiskSizeGb=\"+leafStr)\n\n x=\"\"\n if self._myHasDeliveryMaxActiveConnections:\n x = \"+\"\n leafStr = str(self.deliveryMaxActiveConnections)\n items.append(x + \"DeliveryMaxActiveConnections=\"+leafStr)\n\n x=\"\"\n if self._myHasEnabled:\n x = \"+\"\n leafStr = str(self.enabled)\n items.append(x + \"Enabled=\"+leafStr)\n\n x=\"\"\n if self._myHasDeliveryMaxBwMbps:\n x = \"+\"\n leafStr = str(self.deliveryMaxBwMbps)\n items.append(x + \"DeliveryMaxBwMbps=\"+leafStr)\n\n return \"{PredictionData: \"+\",\".join(items)+\"}\"\n\n\"\"\"\nExtracted from the below data: \n{\n \"node\": {\n \"className\": \"PredictionData\", \n \"namespace\": \"prediction\", \n \"importStatement\": \"from a.api.yang.modules.tech.content.qwilt_tech_content_line.tech.content.line.analyzer.prediction.prediction_data_gen import PredictionData\"\n }, \n \"ancestors\": [\n {\n \"namespace\": \"tech\", \n \"isCurrent\": false\n }, \n {\n \"namespace\": \"content\", \n \"isCurrent\": false\n }, \n {\n \"namespace\": \"line\", \n \"isCurrent\": false\n }, \n {\n \"namespace\": \"analyzer\", \n \"isCurrent\": false\n }, \n {\n \"namespace\": \"prediction\", \n \"isCurrent\": true\n }\n ], \n \"conditionalDebugName\": null, \n \"leaves\": [\n {\n \"typeHandler\": \"handler: IntHandler\", \n \"memberName\": \"estimatedDeliveryTrxPerConnection\", \n \"yangName\": \"estimated-delivery-trx-per-connection\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": true\n }, \n {\n \"typeHandler\": \"handler: IntHandler\", \n \"memberName\": \"simulatedDiskSizeGb\", \n \"yangName\": \"simulated-disk-size-gb\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": true\n }, \n {\n \"typeHandler\": \"handler: IntHandler\", \n \"memberName\": \"deliveryMaxActiveConnections\", \n \"yangName\": \"delivery-max-active-connections\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": true\n }, \n {\n \"typeHandler\": \"handler: BoolPyHandler\", \n \"memberName\": \"enabled\", \n \"yangName\": \"enabled\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": true\n }, \n {\n \"typeHandler\": \"handler: IntHandler\", \n \"memberName\": \"deliveryMaxBwMbps\", \n \"yangName\": \"delivery-max-bw-mbps\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": true\n }\n ], \n \"module\": {}, \n \"env\": {\n \"namespaces\": [\n \"a\", \n \"api\", \n \"yang\", \n \"modules\", \n \"tech\", \n \"content\", \n \"qwilt_tech_content_line\"\n ]\n }, \n \"createTime\": \"2013\"\n}\n\"\"\"\n\n\n","sub_path":"oscar/a/api/yang/modules/tech/content/qwilt_tech_content_line/tech/content/line/analyzer/prediction/prediction_data_gen.py","file_name":"prediction_data_gen.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"203393288","text":"#Despertador simples\n#Install MPG123 for play Song\n\nfrom datetime import datetime\nimport subprocess\nimport sys\n\nacorda = sys.argv\n\nwhile 1:\n\tatual = datetime.now()\n\ttroca = str(atual.hour) + \":\" + str(atual.minute)\n\tif troca == str(acorda[1]):\n\t\tsubprocess.run([\"clear\"])\n\t\tprint('''\n\t\t\t ___ _____ _________________ ___ \n\t\t\t / _ \\/ __ \\ _ | ___ \\ _ \\/ _ \\ \n\t\t\t/ /_\\ \\ / \\/ | | | |_/ / | | / /_\\ \\\n\t\t\t\n\t\t\t| | | | \\__/\\ \\_/ / |\\ \\| |/ /| | | |\n\t\t\t\\_| |_/\\____/\\___/\\_| \\_|___/ \\_| |_/\n \t\t\t''')\n\t\tsubprocess.run([\"mpg123\",\"street_fighter_2_guiles_theme-1.mp3\"])\n\t\tbreak\n","sub_path":"Simple_Apps/Despertador/despertador.py","file_name":"despertador.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205962714","text":"import os\nimport tempfile\nimport shutil\n\nimport pytest\n\n\nfrom flask_bootstrap.core import (bootstrap_project_dir, bootstrap_project_git_dir, bootstrap)\n\n\n@pytest.fixture()\ndef tmp_dir():\n _tmp_dir = tempfile.mkdtemp()\n yield _tmp_dir\n print('start to teardown...')\n shutil.rmtree(_tmp_dir)\n\n\n@pytest.fixture()\ndef project_name():\n return 'test'\n\n\n@pytest.fixture()\ndef project_description():\n return 'test'\n\n\ndef test_bootstrap_project_dir(tmp_dir, project_name, project_description):\n bootstrap_project_dir(tmp_dir, project_name, project_description)\n assert os.path.exists(f'{tmp_dir}') is True\n assert os.path.exists(f'{tmp_dir}/README.md') is True\n assert os.path.exists(f'{tmp_dir}/{project_name}/wsgi.py') is True\n assert os.path.exists(f'{tmp_dir}/{project_name}/settings.py') is True\n assert os.path.exists(f'{tmp_dir}/{project_name}/__init__.py') is True\n\n\ndef test_bootstrap_project_git_dir(tmp_dir):\n bootstrap_project_git_dir(tmp_dir)\n assert os.path.exists(f'{tmp_dir}/.git') is True\n\n\ndef test_bootstrap(project_name, project_description):\n pwd = os.getcwd()\n tmp_dir = tempfile.mkdtemp()\n os.chdir(tmp_dir)\n project_root_dir = bootstrap(project_name, project_description, True)\n import platform\n if platform.system() == 'Darwin':\n tmp_dir = f'/private{tmp_dir}'\n assert project_root_dir == f'{tmp_dir}/{project_name}'\n assert os.path.exists(f'{project_root_dir}') is True\n assert os.path.exists(f'{project_root_dir}/README.md') is True\n assert os.path.exists(f'{project_root_dir}/{project_name}/wsgi.py') is True\n assert os.path.exists(f'{project_root_dir}/{project_name}/settings.py') is True\n assert os.path.exists(f'{project_root_dir}/{project_name}/__init__.py') is True\n shutil.rmtree(tmp_dir)\n os.chdir(pwd)\n","sub_path":"tests/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"1995353","text":"import os\nimport sys\nimport queue\nfrom .parse_specification import file_archive_attributes\nfrom typing import List, Union\n\nfrom .exceptions import *\nfrom .. import irods_os\nfrom ..transfer_engine import TransferManager\nfrom ..transfer_tasks import UploadTask\nfrom ..transfer_tasks.exceptions import DirectoryPermissionError, FilePermissionError\nfrom ..tombstone import tombstone_free\n\n\ndef command_line_create_upload_task(file_path: str,\n archive_path: str,\n attributes: List[irods_os.metadata.Attribute],\n trust_hpf_copy: bool = False,\n trust_irods_copy: bool = False) -> Union[UploadTask, None]:\n \"\"\" Returns None if this upload task should be skipped, otherwise returns the UploadTask.\n Prints explanations for why files were skipped to stderr, and adds error reports to the provided error queue.\n \"\"\"\n args = dict(file_path=file_path, archive_path=archive_path, metadata=attributes) # type: dict\n error_args = args.copy()\n error_args['perform_checks'] = False\n\n try:\n return UploadTask(**args)\n except FileNotFoundError:\n # File-to-be-archived doesn't exist\n print(\"The file to be uploaded doesn't exist:\", file_path, file=sys.stderr)\n return None\n except DirectoryPermissionError:\n # Don't have write permissions necessary for creating the tombstone\n print(\"You are lacking write permissions for the directory containing the file to be uploaded\"\n \"(this is needed to create the tombstone file:\",\n file_path,\n file=sys.stderr)\n return None\n except FilePermissionError:\n # Don't have read permissions necessary to upload the file\n print(\"You are lacking read permissions for the file to be uploaded\"\n \"(this is needed for uploading):\",\n file_path,\n file=sys.stderr)\n return None\n except FileExistsError:\n tombstone = file_path + os.path.extsep + 'tombstone'\n # There has been an attempt to upload the file previously\n try:\n # Do all the checks that are performed in the tombstone free command\n # but don't actually delete anything.\n # If there are any errors, then we know that the previous upload was not successful.\n tombstone_free.safe_delete(tombstone, dry_run=True)\n except (tombstone_free.ArchiveFileNotFoundError,\n tombstone_free.ArchiveFileSizeMismatchError,\n tombstone_free.ChecksumsNotEqualError,\n FileNotFoundError):\n # Something went wrong with the previous upload\n if trust_hpf_copy:\n # Re-upload (over-writing the iRODS copy with the HPF copy\n irods_os.remove(archive_path)\n try:\n os.remove(tombstone)\n except FileNotFoundError:\n pass\n return command_line_create_upload_task(file_path, archive_path, attributes)\n else:\n if trust_irods_copy:\n print('Skipping', file_path, 'because it has already been uploaded.', file=sys.stderr)\n return None\n # re-raise the exception\n raise\n\n else:\n # The previous upload was successful\n return None\n\n\ndef upload(manifests: List[str],\n transfer_error_file: str,\n dry_run: bool,\n trust_hpf_copy: bool,\n trust_irods_copy: bool) -> List[str]:\n upload_task_list = list()\n total_size = 0\n\n for file_path, archive_path, attributes in file_archive_attributes(manifests):\n upload_task = command_line_create_upload_task(file_path,\n archive_path,\n attributes,\n trust_hpf_copy,\n trust_irods_copy)\n if upload_task is not None:\n # upload small files first instead of big ones: get the easy ones out of the way.\n upload_task.priority = upload_task.file_size\n total_size += upload_task.file_size\n upload_task_list.append(upload_task)\n\n if dry_run:\n return [u.file_path for u in upload_task_list]\n\n print('Uploading {} Tb to iRODS'.format(total_size * 1e-12), file=sys.stderr)\n\n # Launch the uploads\n # ------------------\n with TransferManager(min(12, len(upload_task_list)), error_dump_file=transfer_error_file) as transfer_manager:\n for node, transfer_engine in zip(transfer_manager.connected_nodes, transfer_manager.transfer_engines):\n print('connected to data-node',\n node,\n 'tracking download progress @',\n transfer_engine.iput_o_log,\n file=sys.stderr)\n for upload_task in upload_task_list:\n transfer_manager.task_queue.put(upload_task)\n\n return [u.file_path for u in upload_task_list\n if u.file_path not in transfer_manager.failed_files]\n\n\ndef upload_command(manifests: List[str],\n transfer_error_file: str,\n dry_run: bool,\n trust_hpf_copy: bool,\n trust_irods_copy: bool) -> List[str]:\n try:\n return upload(manifests, transfer_error_file, dry_run, trust_hpf_copy, trust_irods_copy)\n except (MissingRequiredFieldClassError,\n UnrecognizedFieldNameError,\n UnrecognizedValueForFieldError) as error:\n print(error.message, sys.stderr)\n raise SystemExit\n","sub_path":"irods_archiving/manifest/manifest_upload.py","file_name":"manifest_upload.py","file_ext":"py","file_size_in_byte":5765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"34154302","text":"# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'JComentario'\n db.create_table(u'comentarios_jcomentario', (\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('comentario', self.gf('django.db.models.fields.TextField')()),\n ))\n db.send_create_signal(u'comentarios', ['JComentario'])\n\n\n def backwards(self, orm):\n # Deleting model 'JComentario'\n db.delete_table(u'comentarios_jcomentario')\n\n\n models = {\n u'comentarios.jcomentario': {\n 'Meta': {'object_name': 'JComentario'},\n 'comentario': ('django.db.models.fields.TextField', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})\n }\n }\n\n complete_apps = ['comentarios']","sub_path":"comentarios/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"424782203","text":"from setuptools import setup\nimport os\nimport stepic\n\nversion = stepic.__version__\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='stepic',\n version=version,\n description='Python image steganography',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Lenny Domnitser',\n author_email='lenny@domnit.org',\n maintainer=\"Scott Kitterman\",\n maintainer_email=\"scott@kitterman.com\",\n url='https://launchpad.net/stepic',\n license='GPL',\n packages=['stepic'],\n entry_points={\n 'console_scripts' : [\n 'stepic = stepic:main',\n ],\n },\n install_requires=['pillow',],\n include_package_data=True,\n zip_safe=False,\n data_files=[(os.path.join('share', 'man', 'man1'), ['stepic.1'])],\n classifiers=[\n 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',\n 'Environment :: Console',\n 'Topic :: Multimedia :: Graphics',\n 'Topic :: Utilities',\n 'Development Status :: 6 - Mature',\n 'Programming Language :: Python :: 3 :: Only'\n ]\n )\n","sub_path":"pypi_install_script/stepic-0.5.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"136027864","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 20 19:30:47 2017\r\n\r\n@author: USER_\r\n\"\"\"\r\n\r\n# -----------------------------------------------------\r\n# Chapter 2: ToolBoxes for Data Scientists\r\n# -----------------------------------------------------\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# The Dataframe with DataStructure\r\n\r\ndata = {\r\n 'year': [\r\n 2010, 2011, 2012, \r\n 2013, 2014, 2015,\r\n 2016, 2017, 2018\r\n ],\r\n 'team': [\r\n 'Barcelona', 'Chelsea', 'Bayern',\r\n 'Real Madrid', 'Barcelona', 'Real Madrid',\r\n 'Real Madrid', 'PSG', 'Manchester City'\r\n ],\r\n 'wins': [\r\n 30, 28, 32, \r\n 29, 32, 26,\r\n 21, 17, 19\r\n ],\r\n 'draws': [\r\n 6, 7, 4, \r\n 5, 4, 7,\r\n 8, 10, 8\r\n ],\r\n 'losses': [\r\n 2, 3, 2, \r\n 4, 2, 5,\r\n 9, 11, 11 \r\n ]\r\n}\r\n\r\nfootball = pd.DataFrame(data, columns = [\r\n 'year', 'team', 'wins', 'draws', 'losses' \r\n])\r\n\r\n\r\n#-- manipulacao de dados usando pandas --\r\n\r\n#levar os dados do formato csv para um dataframe de python\r\nedu = pd.read_csv('educ_figdp_1_Data.csv', na_values = ':',usecols = [\r\n \"TIME\",\"GEO\",\"Value\"])\r\n\r\n#listar primeiros elementos do dataframe\r\nprint(edu.head(10))\r\n\r\n#listar ultimos elementos do dataframe\r\nprint(edu.tail(10))\r\n\r\n#dados estatisticos principais\r\nprint(edu.describe())\r\n\r\n#selecionar dados\r\nprint(edu['TIME'].head(10))\r\nprint(edu['Value'].tail(10))\r\nprint(edu[10:14])\r\nprint(edu[10:14]['TIME'])\r\nprint(edu.ix[90:94, ['TIME','GEO']])\r\n\r\n#filtragem de dados\r\nprint(edu[edu['Value']>6.5])\r\nprint(edu[edu['Value']>6.5].tail())\r\nprint(edu[edu['Value']>6.5].head())\r\n\r\n#filtragem de valores NaN \r\nprint(edu[edu['Value'].isnull()])\r\nprint(edu[edu['Value'].isnull()].count())\r\nprint(edu.max(axis = 0))\r\n# axis = 0 ==> rows | axis = 1 ==> columns\r\n\r\n#funcao maximo para python\r\nprint(max(edu['Value']))\r\n\r\n#funcao maximo para pandas\r\nprint(edu['Value'].max())\r\nprint((edu['Value']/100).head())\r\n\r\n#aplicacao de funcoes matematicas\r\ns = edu['Value'].apply(np.sqrt)\r\nt = edu['Value'].apply(np.log10)\r\nprint(s.head())\r\nprint(t.head())\r\n\r\n#funcao lambda \r\ns = edu['Value'].apply(lambda x: x**2)\r\nprint(s.head(10))\r\n\r\n#criacao de uma nova medida apartir de uma funcao matematica\r\nedu['ValueNorm'] = edu['Value'] / edu['Value'].max()\r\nedu['ValueLog'] = edu['Value'].apply(np.log10)\r\nedu['ValueUser'] = edu['Value'].apply(lambda x: x**2)\r\nprint(edu.head(10))\r\n\r\n#funcao append como insertor de dados\r\nedu = edu.append({'TIME': 2000, 'GEO': 'a', 'Value': 5.00}, ignore_index = True)\r\nprint(edu.tail())\r\n\r\n#funcao drop como eliminador de dados\r\nedu.drop(max(edu.index), axis = 0, inplace = True)\r\n# elimina a fila com o maior indice e nao faz copia do valor original\r\nprint(edu.tail())\r\n\r\n#eliminar missing values\r\neduDrop = edu.drop(edu['Value'].isnull(), axis = 0)\r\nprint(eduDrop.head())\r\n\r\n#outra forma com uma funcao generica\r\neduDrop = edu.dropna(how = 'any', subset = ['Value'])\r\nprint(eduDrop)\r\n\r\n#preencher valores nulos\r\neduFilled = edu.fillna(value = {'Value': edu['Value'].mean()})\r\n\r\n#ordenacao de dados\r\nedu.sort_values(by = 'Value', ascending = True, inplace = True)\r\nprint(edu.head())\r\n\r\n#agrupamento de dados\r\ngrupo1 = edu[['GEO', 'Value']].groupby('GEO').mean()\r\nprint(grupo1)\r\n\r\n#filtragem ao estilo select from\r\ndados_filter = edu[edu['TIME']>2005]\r\n\r\n#rearranjo de dados\r\nimport pandas as pd\r\ntbl = pd.pivot_table(dados_filter, values = 'Value', index = ['GEO'], columns = ['TIME'])\r\nprint(tbl)\r\n\r\namostra = tbl.ix[['France', 'Spain'], [2009,2010, 2011]]\r\nprint(amostra)\r\n\r\n#eliminar filas de acordo com os indices\r\ntbl = tbl.drop([\r\n 'Euro area (13 countries)', 'Euro area (15 countries)', 'Euro area (17 countries)',\r\n 'Euro area (18 countries)', 'European Union (25 countries)', 'European Union (27 countries)',\r\n 'European Union (28 countries)'], axis = 0)\r\n\r\n#editar indice de uma fila \r\ntbl = tbl.rename(index = {'Germany (until 1990 former territory of the FRG)' : 'Germany'})\r\n\r\n#eliminar filas com dados NaN\r\ntbl = tbl.dropna()\r\n\r\n#ordenacao dos dados\r\ntbl.rank(ascending = False, method = 'first')\r\n\r\n#organizar dados pela soma dos valores de receita dos ultimos 6 anos\r\ntotal_tbl = tbl.sum(axis = 1)\r\n\r\ntotal_tbl.rank(ascending = False, method = 'dense').sort_values()\r\n\r\n# method first ==> recebe uma posicao no ranking diferente\r\n# method dense ==> recebe uma posicao = em caso de empate\r\n\r\n# plotting\r\n\r\n#obter o total de receita dos ultimos 6 anos em ordem descendente\r\ntotalSum = tbl.sum(axis = 1).sort_values(ascending = False)\r\n\r\n#graficar os resultados\r\n# kind => tipo de grafico || style => cor blue || alpha => intensidade, brilho\r\ntotalSum.plot(kind = 'bar', style = 'b', alpha = 0.5, title = 'Total Renenue')\r\n\r\n#grafica por anos 2006 || 2011\r\nmy_colors = ['b', 'r', 'g', 'y', 'm', 'c']\r\n# kind => tipo de grafico || stacked => nro de series\r\nax = tbl.plot(kind = 'barh', stacked = True, color = my_colors)\r\nax.legend(loc = 'center left', bbox_to_anchor = (2, 1))\r\n\r\n","sub_path":"chap2.py","file_name":"chap2.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"452500996","text":"import os\nfrom ML.MLmodels import *\nimport optparse\nfrom samples.samplesUL import *\nimport copy\nfrom datetime import datetime\nfrom ExtractCondor import FindModels\n#os.system(\"reset\")\n\nusage = 'python3 CombineCondor.py -d dataset_name -f destination_folder -y year'\nparser = optparse.OptionParser(usage)\nparser.add_option('--folder', dest='folder', type='string', default = 'vUL025', help = 'Analysis folder')\nparser.add_option('--user', dest='user', type='string', default = 'apiccine', help = 'Username')\nparser.add_option('--notImpacts', dest='impacts', default = True, action='store_false', help = 'Default does impacts')\nparser.add_option('--notUncBreak', dest='uncbreak', default = True, action='store_false', help = 'Default does unc. breaking')\nparser.add_option('--plot', dest='plotvar', type='string', default = 'fitvar', help = 'Specify variables to plot in postfit')\nparser.add_option('--year', dest='year', type='string', default = 'RunII', help = 'Specify year, default is RunII')\nparser.add_option('--cut', dest='cut', type='string', default = 'not', help = 'Specify cut, if needed')\nparser.add_option('--sm', dest='sm', default = False, action='store_true', help = 'Default does not run SM significance')\nparser.add_option('--noFit', dest='dofit', default = True, action='store_false', help = 'Default does not run SM significance')\nparser.add_option('--doPost', dest='postfit', default = False, action='store_true', help = 'Default does not run postfit plots')\nparser.add_option('-m', '--models', dest='models', type=str, default = 'vbs', help='Please enter a dataset name')\nparser.add_option('--Lambda8', dest='Lambda8', default = False, action='store_true', help='add dim8 quad in 2D fits')\nparser.add_option('--srvar', dest='srvar', type=str, default = 'm_o1', help='var in sr')\nparser.add_option('--crvar', dest='crvar', type=str, default = 'same', help='var in cr')\nparser.add_option('--notCI', dest='doCI', default = True, action='store_false', help = 'Default does not run postfit plots')\nparser.add_option('--tDMcut', dest='tDMcut', default = False, action='store_true', help='Enable tau DecayMode cut')\nparser.add_option('--test', dest='test', default = False, action='store_true', help='Enable test')\nparser.add_option('--vbroad', dest='vbroad', default = False, action='store_true', help='Enable vbroad')\nparser.add_option('--vvbroad', dest='vvbroad', default = False, action='store_true', help='Enable vvery broad')\nparser.add_option('--vvvbroad', dest='vvvbroad', default = False, action='store_true', help='Enable vvvery broad')\nparser.add_option('--noflat', dest='flat', default = True, action='store_false', help='Disable flattening bin')\nparser.add_option('-u', '--unblind', dest = 'unblind', default = False, action = 'store_true', help = 'unblinding SR, default not')\nparser.add_option('--PDFWithTTDY', dest='pdfttdy', default = False, action='store_true', help = 'apply pdf to ttbar and dy')\nparser.add_option('--DYrp', dest='DYrp', default = False, action='store_true', help = 'apply rateParam to dy')\nparser.add_option('--pdf', dest='pdf', type='string', default = 'total', help = 'Specify type of pdf')\nparser.add_option('--flnN', dest='flnN', default = False, action='store_true', help = 'apply lognormal to fakes')\nparser.add_option('--frp', dest='frp', default = False, action='store_true', help = 'apply rateParam to fakes')\nparser.add_option('--noQCDScale', dest='noQCDScale', default = False, action='store_true', help = 'QCDScale not')\nparser.add_option('--profile', dest='profile', default = False, action='store_true', help = 'apply profiling to 2D fits eft')\nparser.add_option('--regions', dest='regions', type='string', default = 'SR,CRTT,CROS,CRF', help = 'Regions to fit')\nparser.add_option('--leptons', dest='leptons', type='string', default = 'muon,electron', help = 'Channels to include')\nparser.add_option('--HN', dest='HN', default = False, action='store_true', help = 'fit with HybridNew instead of AsymptoticLimits')\n\n(opt, args) = parser.parse_args()\n\nmodels = opt.models.split(\",\")\nsrvars = opt.srvar.split(\":\")\nregions = opt.regions.split(\":\")\nleptons = opt.leptons.split(\":\")\n\nif opt.crvar == \"same\":\n crvars = copy.deepcopy(srvars)\nelse:\n crvars = opt.crvar.split(\":\")\n\nplotvars = []\nif opt.postfit:\n if opt.plotvar == \"fitvar\":\n plotvars = copy.deepcopy(srvars)\n else:\n plotvars = opt.plotvar.split(\":\")\n if len(plotvars) != len(srvars):\n raise ValueError(\"number of plotvars has to be equal to number of srvars\")\n\nif len(srvars) != len(crvars):\n raise ValueError(\"number of srvars has to be equal to number of crvars\")\n\nusername = str(os.environ.get('USER'))\ninituser = str(os.environ.get('USER')[0])\nif username == 'mmagheri':\n uid = 102889\nelif username == 'apiccine':\n uid = 124949\nelif username == 'ttedesch':\n uid = 103343\n\nnow = datetime.now().time().strftime(\"%H%M%S%f\")\n\nsubfold = \"combinecondor_\" + opt.pdf\ncondorsub = \"condorcombine_\" + opt.pdf\nexe = \"branchcombine_\" + opt.pdf\n\nif opt.unblind:\n condorsub += \"_DF\"\n subfold += \"_DF\"\n exe += \"_DF\"\nelse:\n condorsub += \"_TF\"\n subfold += \"_TF\"\n exe += \"_TF\"\n\n#condorsub += opt.regions.replace(\",\", \"-\") + \"_\" + opt.leptons.replace(\",\", \"-\")\n#subfold += opt.regions.replace(\",\", \"-\") + \"_\" + opt.leptons.replace(\",\", \"-\")\n#exe += opt.regions.replace(\",\", \"-\") + \"_\" + opt.leptons.replace(\",\", \"-\")\n\nif opt.DYrp:\n condorsub += \"_OSrp\"\n subfold += \"_OSrp\"\n exe += \"_OSyrp\"\nif opt.flnN:\n condorsub += \"_flnN\"\n subfold += \"_flnN\"\n exe += \"_flnN\"\nif opt.frp:\n condorsub += \"_frp\"\n subfold += \"_frp\"\n exe += \"_frp\"\nif opt.pdfttdy:\n condorsub += \"_PDFwithTTDY\"\n subfold += \"_PDFwithTTDY\" \n exe += \"_PDFwithTTDY\" \nif opt.Lambda8:\n condorsub += \"_Lambda8\"\n subfold += \"_Lambda8\"\n exe += \"_Lambda8\"\nif opt.tDMcut:\n condorsub += \"_tDM\"\n subfold += \"_tDM\"\n exe += \"_tDM\"\nelif opt.test:\n condorsub += \"_test\"\n subfold += \"_test\"\n exe += \"_test\"\nelif opt.vbroad:\n condorsub += \"_vbroad\"\n subfold += \"_vbroad\"\n exe += \"_vbroad\"\nelif opt.vvbroad:\n condorsub += \"_vvbroad\"\n subfold += \"_vvbroad\"\n exe += \"_vvbroad\"\nelif opt.vvvbroad:\n condorsub += \"_vvvbroad\"\n subfold += \"_vvvbroad\"\n exe += \"_vvvbroad\"\nif not opt.flat:\n condorsub += \"_noflat\"\n subfold += \"_noflat\"\n exe += \"_noflat\"\nif opt.noQCDScale:\n condorsub += \"_noQCDScale\"\n subfold += \"_noQCDScale\"\n exe += \"_noQCDScale\"\n#if opt.flat:\n #condorsub += \"_flat\"\n #subfold += \"_flat\"\n #exe += \"_flat\"\nif opt.profile:\n condorsub += \"_profile\"\n subfold += \"_profile\"\n exe += \"_profile\"\nif opt.HN:\n condorsub += \"_HN\"\n subfold += \"_HN\"\n exe += \"_HN\"\n\ncondorsub += \"_\"\nsubfold += \"_\" + opt.folder\n \nif not os.path.exists(subfold):\n os.system(\"mkdir \" + subfold)\n\noutcore = condorsub + opt.folder + \"/output/\"\nerrcore = condorsub + opt.folder + \"/error/\"\nlogcore = condorsub + opt.folder + \"/log/\"\n\nif not os.path.exists(outcore):\n os.system(\"mkdir -p \" + outcore)\nif not os.path.exists(errcore):\n os.system(\"mkdir -p \" + errcore)\nif not os.path.exists(logcore):\n os.system(\"mkdir -p \" + logcore)\n\ndef submitter(model, srvar, crvar, argsins, folder, lepton, region):\n exesh = subfold + \"/\" + exe + \"_\" + folder + \"_\" + model + \"_\" + srvar + \"_\" + crvar + \"_\" + lepton.replace(\",\", \"-\") + \"_\" + region.replace(\",\", \"-\") + \".sh\"\n fsh = open(exesh, \"w\")\n fsh.write(\"#!/bin/bash\\n\")\n fsh.write(\"cd /afs/cern.ch/user/a/apiccine\\n\")\n fsh.write(\"source setenv_combine.sh\\n\")\n fsh.write(\"cd Stat/Limits/test\\n\")\n for argsin in argsins:\n fsh.write(\"python \" + pymacro + \" \" + argsin + \"\\n\")\n fsh.close()\n \n condorsubb = condorsub + folder + \"_\" + model + \"_\" + srvar + \"_\" + crvar + \"_\" + lepton.replace(\",\", \"-\") + \"_\" + region.replace(\",\", \"-\") + \".sub\"\n f = open(condorsubb, \"w\")\n f.write(\"Proxy_filename = x509up\\n\")\n f.write(\"Proxy_path = /afs/cern.ch/user/\" + inituser + \"/\" + username + \"/private/$(Proxy_filename)\\n\")\n f.write(\"universe = vanilla\\n\")\n f.write(\"x509userproxy = $(Proxy_path)\\n\")\n f.write(\"use_x509userproxy = true\\n\")\n f.write(\"should_transfer_files = YES\\n\")\n f.write(\"when_to_transfer_output = ON_EXIT\\n\")\n inputfiles = \"transfer_input_files = $(Proxy_path)\\n\"\n f.write(inputfiles)\n if (model.startswith(\"c\") and \":\" in model):\n f.write(\"+JobFlavour = \\\"nextweek\\\"\\n\") # options are espresso = 20 minutes, microcentury = 1 hour, longlunch = 2 hours, workday = 8 hours, tomorrow = 1 day, testmatch = 3 days, nextweek = 1 week\n else: \n f.write(\"+JobFlavour = \\\"testmatch\\\"\\n\") # options are espresso = 20 minutes, microcentury = 1 hour, longlunch = 2 hours, workday = 8 hours, tomorrow = 1 day, testmatch = 3 days, nextweek = 1 week\n f.write(\"executable = \" + exesh + \"\\n\")\n f.write(\"arguments = \\'\\'\\n\") # + argsin + \"\\n\")\n if (model.startswith(\"c\") and \":\" in model) or model == \"EWvsQCD\":\n f.write(\"request_cpus = 10\\n\")\n elif model.startswith(\"c\") or model.startswith(\"F\"):\n f.write(\"request_cpus = 6\\n\")\n else:\n f.write(\"request_cpus = 6\\n\")\n output = outcore + folder + \"_\" + model + \"_\" + srvar + \"_\" + crvar + \"_\" + lepton.replace(\",\", \"-\") + \"_\" + region.replace(\",\", \"-\") + \".out\"\n log = logcore + folder + \"_\" + model + \"_\" + srvar + \"_\" + crvar + \"_\" + lepton.replace(\",\", \"-\") + \"_\" + region.replace(\",\", \"-\") + \".log\"\n error = errcore + folder + \"_\" + model + \"_\" + srvar + \"_\" + crvar + \"_\" + lepton.replace(\",\", \"-\") + \"_\" + region.replace(\",\", \"-\") + \".err\"\n f.write(\"output = \" + output + \"\\n\")\n f.write(\"error = \" + error + \"\\n\")\n f.write(\"log = \" + log + \"\\n\")\n f.write(\"queue\\n\")\n f.close()\n if os.path.exists(output):\n os.system(\"rm \" + output)\n if os.path.exists(log):\n os.system(\"rm \" + log)\n if os.path.exists(error):\n os.system(\"rm \" + error)\n \n os.system(\"condor_submit \" + condorsubb)\n os.system(\"mv \" + condorsubb + \" \" + subfold)\n\nfolder = opt.folder\npymacro = \"FitAndPlot\"\npymacro += \".py\"\n\narg0 = \" --folder \" + folder \narg0 += \" --year \" + opt.year\n\nif opt.unblind:\n arg0 += \" -u\"\nif not opt.impacts:\n arg0 += \" --notImpacts\"\nif not opt.uncbreak:\n arg0 += \" --notUncBreak\"\nif not opt.dofit:\n arg0 += \" --noFit\"\nif opt.noQCDScale:\n arg0 += \" --noQCDScale\"\n#runningmodels = FindModels()\n\n#print(runningmodels)\n\nfor model in models:\n arg1 = \"\"\n #if not (\"cqq3_\" in model or \"cqq31_\" in model or \"cqq11_\" in model):\n #continue\n #if \"cqq1_\" in model:\n #continue\n #if not \"cW_\" in model:\n #continue\n #if not (\":FT\" in model or \":FS\" in model or \":FM\" in model):\n #continue\n\n #if model in runningmodels:\n #continue\n \n if model.startswith(\"vbs\"):\n arg1 += \" --sm --vbs\"\n if model != \"vbs\":\n arg1 += \" --pol \" + model.replace(\"vbs\", \"\")\n elif model.startswith(\"wpwp\"):\n arg1 += \" --sm --\" + model\n elif model == \"EWvsQCD\":\n arg1 += \" --\" + model\n else:\n arg1 += \" --eft \" + model\n if not opt.doCI:\n arg1 += \" --notCI\"\n if opt.Lambda8:\n arg1 += \" --Lambda8\"\n if opt.profile:\n arg1 += \" --profile\"\n if opt.HN:\n arg1 += \" --HN\" \n for idsr, srvar in enumerate(srvars):\n arg2 = \"\"\n arg2 = arg0 + arg1 + \" --fit \" + srvar\n\n if not opt.crvar == \"same\":\n arg2 += \" --cr \" + crvars[idsr]\n crvar = crvars[idsr]\n else:\n crvar = srvar\n\n if opt.postfit:\n arg2 += \" --doPost --plot \" + plotvars[idsr]\n\n if opt.tDMcut:\n arg2 += \" --tDMcut\"\n elif opt.test:\n arg2 += \" --test\"\n elif opt.vbroad:\n arg2 += \" --vbroad\"\n elif opt.vvbroad:\n arg2 += \" --vvbroad\"\n elif opt.vvvbroad:\n arg2 += \" --vvvbroad\"\n if not opt.flat:\n arg2 += \" --noflat\"\n #if opt.flat:\n #arg2 += \" --flat\"\n\n if opt.pdfttdy:\n arg2 += \" --PDFWithTTDY\"\n if opt.DYrp:\n arg2 += \" --DYrp\"\n if opt.flnN:\n arg2 += \" --flnN\"\n if opt.frp:\n arg2 += \" --frp\"\n\n arg2 += \" --pdf \" + opt.pdf\n \n for lepton in leptons:\n for region in regions:\n argss = []\n arg3 = arg2 + \" --regions \" + region + \" --leptons \" + lepton\n arg3 += \" > /dev/null \"\n\n argss.append(arg3)\n submitter(model, srvar, crvar, argss, folder, lepton, region)\n \n \n","sub_path":"python/postprocessing/CombineCondor.py","file_name":"CombineCondor.py","file_ext":"py","file_size_in_byte":12891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224681073","text":"# vector.py\n# Use this to do math stuffs!\n# by James Fulford\n# Began: 6/8/2016\n# Stopped Developing:\n\nimport math\n\n\ndef polarToCartesian(argument_radians, magnitude):\n \"\"\"\n mathematics.vector.polarToCartesian\n Returns a 2-tuple (x, y) representation of given arg and mag.\n \"\"\"\n x = math.cos(argument_radians) * magnitude\n y = math.sin(argument_radians) * magnitude\n return (x, y)\n\n\ndef addTuples(tuple1, tuple2):\n \"\"\"\n mathematics.vector.addTuples\n Adds each entry of two tuples to one another. Returns a tuple.\n \"\"\"\n result = []\n for i in range(0, max(len(tuple1), len(tuple2))):\n try:\n result.append(tuple1[i] + tuple2[i])\n except:\n try:\n result.append(tuple1[i])\n except:\n try:\n result.append(tuple2[i])\n except:\n result.append(0) # this shouldn't run,\n # because the range shouldn't let it.\n return tuple(result)\n","sub_path":"mathematics/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"498003088","text":"# Python 训练营 第一周作业 第一部分 20200304 00:36 \nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom time import sleep\nimport re\nimport csv\nimport unicodedata\n\n#通过输入网址返回BS对象\ndef get_url(url):\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'\n header = {}\n header['user-agent'] = user_agent\n response = requests.get(url,headers=header)\n bs_response=bs(response.text,'html.parser')\n return bs_response\n\n#通过输入网址区配解析内容并按行写入CSV\ndef get_films(url):\n bs_info= get_url(url)\n for tags in bs_info.find_all('div',attrs={'class': 'info'}):\n comment_url = tags.find('a').get('href')\n film_name = tags.find('a').find('span').get_text()\n film_rating = tags.find('span',attrs={'class': 'rating_num'}).get_text()\n film_comment_num = tags.find(string=re.compile('评价')).replace('人评价','')\n film_comments = get_comments(comment_url)\n f = open('top25.csv',mode ='a' , encoding= 'utf-8')\n csv_writer = csv.writer(f, lineterminator='\\n')\n csv_writer.writerow([film_name,film_rating,film_comment_num,film_comments])\n f.close()\n\n#通过输入网址解析评论内容并优化后返回数组\ndef get_comments(url): \n bscomment = get_url(url)\n comments = []\n sleep(10)\n for tags in bscomment.find_all('span',attrs={'class': 'short'}):\n comments.append(unicodedata.normalize('NFKC',tags.get_text()).replace('\\n','').strip())\n return comments\n\n#定义采集网址入口列表\nurls = tuple(f'https://movie.douban.com/top250?start={ page * 25 }' for page in range(10))\n\n#程序主入口\nif __name__ == '__main__':\n for url in urls:\n print(url)\n get_films(url)","sub_path":"Week_01/G20190282010037/top25.py","file_name":"top25.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205686970","text":"import copy\nimport json\nimport os\nimport random\nimport shutil\nfrom collections import OrderedDict\nfrom typing import Iterable\n\nimport numpy\nimport pandas\nfrom sklearn.model_selection import LeaveOneGroupOut, train_test_split, KFold\n\nfrom pyxai import Tools\nfrom pyxai.sources.core.structure.boostedTrees import BoostedTrees\nfrom pyxai.sources.core.structure.decisionTree import DecisionTree\nfrom pyxai.sources.core.structure.randomForest import RandomForest\nfrom pyxai.sources.core.structure.type import EvaluationMethod, EvaluationOutput, Indexes\nfrom pyxai.sources.core.tools.utils import flatten, compute_accuracy\n\n\nclass LearnerInformation:\n def __init__(self, raw_model, training_index=None, test_index=None, group=None, accuracy=None):\n self.raw_model = raw_model\n self.training_index = training_index\n self.test_index = test_index\n self.group = group\n self.accuracy = accuracy\n self.solver_name = None\n self.feature_names = None\n self.evaluation_method = None\n self.evaluation_output = None\n\n\n def set_solver_name(self, solver_name):\n self.solver_name = solver_name\n\n\n def set_feature_names(self, feature_names):\n self.feature_names = feature_names\n\n\n def set_evaluation_method(self, evaluation_method):\n self.evaluation_method = str(evaluation_method)\n\n\n def set_evaluation_output(self, evaluation_output):\n self.evaluation_output = str(evaluation_output)\n\n\nclass NoneData:\n pass\n\n\nclass Learner:\n \"\"\"\n Load the dataset, rename the attributes and separe the prediction from the data\n instance = observation \n labels != prediction\n attributes = features\n \"\"\"\n\n\n def __init__(self, data=NoneData):\n self.dict_labels = None\n self.data = None\n self.labels = None\n self.n_labels = None\n self.n_features = None\n self.dataset_name = None\n self.n_instances = None\n self.feature_names = None\n self.learner_information = []\n data, name = self.parse_data(data)\n if data is not None:\n self.load_data(data, name)\n\n\n def parse_data(self, data=NoneData, skip=None, n=None):\n if data is NoneData:\n return None, None\n\n if isinstance(data, str):\n if os.path.isfile(data):\n if data.endswith(\".csv\"):\n return pandas.read_csv(data, skiprows=skip, nrows=n).copy(), data\n elif data.endswith(\".xlsx\"):\n return pandas.read_excel(data, skiprows=skip, nrows=n).copy(), data\n else:\n raise ValueError(\"If data is a string, it must be a csv or excel file with the .csv or .xlsx extension.\")\n raise FileNotFoundError(\"The file \" + data + \" is not found.\")\n\n if isinstance(data, pandas.core.frame.DataFrame):\n return data, \"pandas.core.frame.DataFrame\"\n\n if data is None:\n raise ValueError(\"The data parameter is set but None (can be optional, but not None).\")\n\n raise ValueError(\"The data parameter is either a string representing a csv or excel file or a pandas.core.frame.DataFrame object.\")\n\n\n @staticmethod\n def count_lines(filename):\n with open(filename) as f:\n return sum(1 for _ in f)\n\n\n def load_data_limited(self, datasetname, possibles_indexes, n):\n self.dataset_name = datasetname\n n_indexes = self.count_lines(datasetname) - 1 # to skip the first line\n\n skip = [i + 1 for i in range(n_indexes) if i not in possibles_indexes] if possibles_indexes is not None else None\n\n # create a map to get the good order of instances\n if skip is not None:\n sorted_possibles_indexes = sorted(possibles_indexes)\n map_possibles_indexes = [sorted_possibles_indexes.index(index) for index in possibles_indexes]\n\n data = pandas.read_csv(\n datasetname,\n skiprows=skip,\n nrows=n\n )\n\n # recreate the dataframe object but with the good order of instances\n if skip is not None:\n sorted_data = pandas.DataFrame(columns=data.columns).astype(data.dtypes)\n for i in range(data.shape[0]):\n sorted_data = sorted_data.append(data.loc[map_possibles_indexes[i]].to_dict(), ignore_index=True)\n sorted_data = sorted_data.astype(data.dtypes)\n\n n_instances, n_features = data.shape\n self.feature_names = data.columns.values.tolist()\n self.rename_attributes(data)\n data, labels = self.remove_labels(data, n_features)\n labels = self.labels_to_values(labels)\n data = data.to_numpy()\n\n return data, labels\n\n\n def load_data(self, dataframe, datasetname):\n \"\"\"\n dataframe: A pandas.core.frame.DataFrame object.\n \"\"\"\n self.dataset_name = datasetname\n self.data = dataframe\n Tools.verbose(\"data:\")\n Tools.verbose(self.data)\n self.n_instances, self.n_features = self.data.shape\n self.feature_names = self.data.columns.values.tolist()\n\n self.rename_attributes(self.data)\n\n self.data, self.labels = self.remove_labels(self.data, self.n_features)\n self.create_dict_labels(self.labels)\n self.labels = self.labels_to_values(self.labels)\n\n self.n_labels = len(set(self.labels))\n self.data = self.data.to_numpy() # remove the first line (attributes) and now the first dimension represents the instances :)!\n self.learner_information = []\n Tools.verbose(\"--------------- Information ---------------\")\n Tools.verbose(\"Dataset name:\", self.dataset_name)\n Tools.verbose(\"nFeatures (nAttributes, with the labels):\", self.n_features)\n Tools.verbose(\"nInstances (nObservations):\", self.n_instances)\n Tools.verbose(\"nLabels:\", self.n_labels)\n\n\n \"\"\"\n Rename attributes in self.data in string of integers from 0 to 'self.n_attributes'\n \"\"\"\n\n\n @staticmethod\n def rename_attributes(data):\n rename_dictionary = {element: str(i) for i, element in enumerate(data.columns)}\n data.rename(columns=rename_dictionary, inplace=True)\n\n\n def create_dict_labels(self, labels):\n index = 0\n self.dict_labels = OrderedDict()\n for p in labels:\n if str(p) not in self.dict_labels:\n self.dict_labels[str(p)] = index\n index += 1\n\n\n \"\"\"\n Convert labels (predictions) into binary values\n Using of OrderedDict in order to be reproducible.\n \"\"\"\n\n\n def labels_to_values(self, labels):\n return [self.dict_labels[str(element)] for element in labels]\n\n\n \"\"\"\n Remove and get the prediction: it is the last attribute (column) in the file\n \"\"\"\n\n\n @staticmethod\n def remove_labels(data, n_features):\n prediction = data[str(n_features - 1)].copy().to_numpy()\n data = data.drop(columns=[str(n_features - 1)])\n return data, prediction\n\n\n \"\"\"\n Method:\n\n \"\"\"\n\n\n def evaluate(self, *, method, output, n_models=10, test_size=0.3, max_depth=None, seed=0, model_directory=None):\n Tools.verbose(\"--------------- Evaluation ---------------\")\n Tools.verbose(\"method:\", str(method))\n Tools.verbose(\"output:\", str(output))\n\n if method == EvaluationMethod.HoldOut:\n self.hold_out_evaluation(output, test_size=test_size, max_depth=max_depth, seed=seed)\n elif method == EvaluationMethod.LeaveOneGroupOut:\n self.leave_one_group_out_evaluation(output, n_trees=n_models, max_depth=max_depth, seed=seed)\n elif method == EvaluationMethod.KFolds:\n self.k_folds_evaluation(output, n_models=n_models, max_depth=max_depth, seed=seed)\n else:\n assert False, \"Not implemented !\"\n\n for learner_information in self.learner_information:\n learner_information.set_solver_name(self.get_solver_name())\n learner_information.set_feature_names(self.feature_names)\n learner_information.set_evaluation_method(method)\n learner_information.set_evaluation_output(output)\n\n Tools.verbose(\"--------- Evaluation Information ---------\")\n for i, result in enumerate(self.learner_information):\n Tools.verbose(\"For the evaluation number \" + str(i) + \":\")\n Tools.verbose(\"accuracy:\", result.accuracy)\n Tools.verbose(\"nTraining instances:\", len(result.training_index))\n Tools.verbose(\"nTest instances:\", len(result.test_index))\n Tools.verbose()\n\n Tools.verbose(\"--------------- Explainer ----------------\")\n result_output = None\n if output == EvaluationOutput.DT:\n result_output = self.to_DT(self.learner_information)\n elif output == EvaluationOutput.RF:\n result_output = self.to_RF(self.learner_information)\n elif output == EvaluationOutput.BT:\n result_output = self.to_BT(self.learner_information)\n else:\n assert False, \"Not implemented !\"\n # elif output == EvaluationOutput.SAVE:\n # self.save_model(model_directory)\n # result_output = self.to_BT()\n\n for i, result in enumerate(result_output):\n Tools.verbose(\"For the evaluation number \" + str(i) + \":\")\n Tools.verbose(result)\n return result_output if len(result_output) != 1 else result_output[0]\n\n\n def load_get_files(self, models_directory):\n assert models_directory is not None and os.path.exists(models_directory), \"The path of models_directory do not exist: \" + str(\n models_directory)\n\n self.learner_information.clear()\n # get the files\n files = []\n index = 0\n found = True\n while found:\n found = False\n for filename in os.listdir(models_directory):\n model_file = os.path.join(models_directory, filename)\n if os.path.isfile(model_file) and model_file.endswith(str(index) + \".model\"):\n map_file = model_file.replace(\".model\", \".map\")\n assert os.path.isfile(map_file), \"A '.model' file must be accompanied by a '.map' file !\"\n files.append((model_file, map_file))\n index += 1\n found = True\n break\n\n assert len(files) != 0, \"No file representing a model in the path: \" + models_directory\n return files\n\n\n def load(self, *, models_directory, with_tests=False):\n files = self.load_get_files(models_directory)\n\n for _, model in enumerate(files):\n model_file, map_file = model\n\n # recuperate map\n f = open(map_file)\n data = json.loads(json.load(f))\n training_index = data['training_index']\n test_index = data['test_index']\n accuracy_saved = data['accuracy']\n solver_name = data['solver_name']\n evaluation_method = data['evaluation_method']\n evaluation_output = data['evaluation_output']\n\n self.n_features = data['n_features']\n self.n_labels = data[\"n_labels\"]\n self.dict_labels = data[\"dict_labels\"]\n self.feature_names = data[\"feature_names\"]\n\n f.close()\n\n assert self.get_solver_name() == solver_name, \"You try to load a model with \" + self.get_solver_name() + \", but you have save the model with \" + solver_name + \" !\"\n\n # load model\n classifier = self.load_model(model_file)\n\n Tools.verbose(\"---------- Loading Information -----------\")\n Tools.verbose(\"mapping file:\", map_file)\n Tools.verbose(\"nFeatures (nAttributes, with the labels):\", self.n_features)\n Tools.verbose(\"nInstances (nObservations):\", len(training_index) + len(test_index))\n Tools.verbose(\"nLabels:\", self.n_labels)\n if with_tests:\n # Test phase\n instances_test = [self.data[i] for i in test_index]\n labels_test = [self.labels[i] for i in test_index]\n result = classifier.predict(instances_test)\n accuracy = compute_accuracy(result, labels_test)\n assert accuracy == accuracy_saved, \"The accuracy between the model loaded and the one determined at its creation is not the same !\"\n self.learner_information.append(LearnerInformation(copy.deepcopy(classifier), training_index, test_index, None, accuracy_saved))\n self.learner_information[-1].set_solver_name(solver_name)\n self.learner_information[-1].set_evaluation_method(evaluation_method)\n self.learner_information[-1].set_evaluation_output(evaluation_output)\n self.learner_information[-1].set_feature_names(self.feature_names)\n\n assert all(learner_information.evaluation_output == self.learner_information[-1].evaluation_output for learner_information in\n self.learner_information), \"All evaluation outputs have to be the same !\"\n\n Tools.verbose(\"--------- Evaluation Information ---------\")\n for i, result in enumerate(self.learner_information):\n Tools.verbose(\"For the evaluation number \" + str(i) + \":\")\n Tools.verbose(\"accuracy:\", result.accuracy)\n Tools.verbose(\"nTraining instances:\", len(result.training_index))\n Tools.verbose(\"nTest instances:\", len(result.test_index))\n Tools.verbose()\n\n Tools.verbose(\"--------------- Explainer ----------------\")\n output = EvaluationOutput.from_str(self.learner_information[-1].evaluation_output)\n result_output = None\n\n if output == EvaluationOutput.DT:\n result_output = self.to_DT(self.learner_information)\n elif output == EvaluationOutput.RF:\n result_output = self.to_RF(self.learner_information)\n elif output == EvaluationOutput.BT:\n result_output = self.to_BT(self.learner_information)\n else:\n assert False, \"Not implemented !\"\n\n for i, result in enumerate(result_output):\n Tools.verbose(\"For the evaluation number \" + str(i) + \":\")\n Tools.verbose(result)\n return result_output if len(result_output) != 1 else result_output[0]\n\n\n def save(self, models, save_directory, generic=False):\n\n name = self.dataset_name.split(os.sep)[-1].split('.')[0]\n if save_directory is not None:\n if not os.path.exists(save_directory):\n os.makedirs(save_directory)\n base_directory = save_directory\n else:\n base_directory = \"\"\n\n shutil.rmtree(base_directory, ignore_errors=True)\n os.mkdir(base_directory)\n\n if not isinstance(models, Iterable):\n models = [models]\n\n for i, trees in enumerate(models):\n learner_information = trees.learner_information\n filename = base_directory + os.sep + name + '.' + str(i)\n # model:\n if not generic:\n self.save_model(learner_information, filename)\n else:\n\n self.save_model_generic(trees, filename)\n # map of indexes for training and test part\n data = {\"training_index\": learner_information.training_index.tolist(),\n \"test_index\": learner_information.test_index.tolist(),\n \"accuracy\": learner_information.accuracy,\n \"solver_name\": learner_information.solver_name if not generic else \"Generic\",\n \"evaluation_method\": learner_information.evaluation_method,\n \"evaluation_output\": learner_information.evaluation_output,\n \"format\": str(format),\n\n \"n_features\": self.n_features,\n \"n_labels\": self.n_labels,\n \"dict_labels\": self.dict_labels,\n \"feature_names\": self.feature_names}\n\n json_string = json.dumps(data)\n with open(filename + \".map\", 'w') as outfile:\n json.dump(json_string, outfile)\n\n Tools.verbose(\"Model saved:\", filename + \".model\")\n Tools.verbose(\"Model saved:\", filename + \".map\")\n\n\n def save_model_generic(self, trees, filename):\n json_string = json.dumps(trees.raw_data())\n with open(filename + \".model\", 'w') as outfile:\n json.dump(json_string, outfile)\n\n\n def hold_out_evaluation(self, output, *, seed=0, max_depth=None, test_size=0.3):\n self.learner_information.clear()\n assert self.data is not None, \"You have to put the dataset in the class parameters.\"\n # spliting\n indices = numpy.arange(len(self.data))\n instances_training, instances_test, labels_training, labels_test, training_index, test_index = train_test_split(self.data, self.labels,\n indices, test_size=test_size,\n random_state=seed)\n\n # solving\n if output == EvaluationOutput.DT:\n tree, accuracy = self.fit_and_predict_DT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth, seed=seed)\n elif output == EvaluationOutput.RF:\n tree, accuracy = self.fit_and_predict_RF(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth, seed=seed)\n elif output == EvaluationOutput.BT:\n tree, accuracy = self.fit_and_predict_BT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth, seed=seed)\n else:\n assert False, \"hold_out_evaluation: EvaluationOutput Not implemented !\"\n self.learner_information.append(LearnerInformation(tree, training_index, test_index, None, accuracy))\n return self\n\n\n def k_folds_evaluation(self, output, *, n_models=10, max_depth=None, seed=0):\n assert self.data is not None, \"You have to put the dataset in the class parameters.\"\n assert n_models > 1, \"This k_folds_evaluation() expects at least 2 parts. For just one tree, please use hold_out_evaluation()\"\n self.learner_information.clear()\n\n cross_validator = KFold(n_splits=n_models, random_state=seed, shuffle=True)\n\n for training_index, test_index in cross_validator.split(self.data):\n # Select good observations for each of the 'n_trees' experiments.\n instances_training = [self.data[i] for i in training_index]\n labels_training = [self.labels[i] for i in training_index]\n instances_test = [self.data[i] for i in test_index]\n labels_test = [self.labels[i] for i in test_index]\n\n # solving\n if output == EvaluationOutput.DT:\n tree, accuracy = self.fit_and_predict_DT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n elif output == EvaluationOutput.RF:\n tree, accuracy = self.fit_and_predict_RF(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n elif output == EvaluationOutput.BT:\n tree, accuracy = self.fit_and_predict_BT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n else:\n assert False, \"leave_one_group_out_evaluation: EvaluationOutput Not implemented !\"\n\n # Save some information\n self.learner_information.append(LearnerInformation(tree, training_index, test_index, None, accuracy))\n return self\n\n\n def leave_one_group_out_evaluation(self, output, *, n_trees=10, max_depth=None, seed=0):\n assert self.data is not None, \"You have to put the dataset in the class parameters.\"\n assert n_trees > 1, \"cross_validation() expects at least 2 trees. For just one tree, please use simple_validation()\"\n self.learner_information.clear()\n\n # spliting\n quotient, remainder = (self.n_instances // n_trees, self.n_instances % n_trees)\n groups = flatten([quotient * [i] for i in range(1, n_trees + 1)]) + [i for i in range(1, remainder + 1)]\n random.Random(seed).shuffle(groups)\n cross_validator = LeaveOneGroupOut()\n\n for training_index, test_index in cross_validator.split(self.data, self.labels, groups):\n # Select good observations for each of the 'n_trees' experiments.\n instances_training = [self.data[i] for i in training_index]\n labels_training = [self.labels[i] for i in training_index]\n instances_test = [self.data[i] for i in test_index]\n labels_test = [self.labels[i] for i in test_index]\n\n # solving\n # solving\n if output == EvaluationOutput.DT:\n tree, accuracy = self.fit_and_predict_DT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n elif output == EvaluationOutput.RF:\n tree, accuracy = self.fit_and_predict_RF(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n elif output == EvaluationOutput.BT:\n tree, accuracy = self.fit_and_predict_BT(instances_training, instances_test, labels_training, labels_test, max_depth=max_depth,\n seed=seed)\n else:\n assert False, \"leave_one_group_out_evaluation: EvaluationOutput Not implemented !\"\n\n # Save some information\n self.learner_information.append(LearnerInformation(tree, training_index, test_index, groups, accuracy))\n return self\n\n\n \"\"\"\n Return couples (instance, prediction) from data and the classifier results.\n \n 'indexes': take only into account some indexes of instances\n - Indexes.Training: indexes from the training instances of a particular model \n - Indexes.Test: indexes from the test instances of a particular model\n - Indexes.Mixed: take firsly indexes from the test set and next from the training set in order to have at least 'n' instances. \n - Indexes.All: all indexes are take into account\n - string: A file contening specific indexes \n \n 'dataset': \n - can be None if the dataset is already loaded\n - the dataset if you have not loaded it yet\n \n 'model':\n - a model for the 'type=training' or 'type=test'\n \n 'n': The desired number of instances (None for all).\n\n 'correct': only available if a model is given \n - None: all instances\n - True: only correctly classified instances by the model \n - False: only misclassified instances by the model \n\n 'classes': \n - None: all instances\n - []: List of integers representing the classes/labels for the desired instances \n\n 'backup_directory': save the instance indexes in a file in the directory given by this parameter \n \"\"\"\n\n\n def get_instances(self, model=None, indexes=Indexes.All, *, dataset=None, n=None, correct=None, predictions=None, save_directory=None,\n instances_id=None, seed=0):\n\n # 1: Check parameters and get the associated solver\n Tools.verbose(\"--------------- Instances ----------------\")\n #Tools.verbose(\"Correctness of instances : \", correct)\n #Tools.verbose(\"Predictions of instances : \", predictions)\n classifier = None\n id_solver_results = None\n results = None\n\n assert isinstance(indexes, (Indexes, str)), \"Bad value in the parameter 'indexes'\"\n\n if self.get_solver_name() == \"Generic\":\n assert correct is None, \"Please insert the model to use this parameter !\"\n assert predictions is None, \"Please insert the model to use this parameter !\"\n\n if model is None:\n assert indexes == Indexes.All, \"Please insert the model to use this parameter !\"\n assert correct is None, \"Please insert the model to use this parameter !\"\n assert predictions is None, \"Please insert the model to use this parameter !\"\n # In this case, no prediction, just return some instances\n elif isinstance(model, Iterable):\n assert False, \"The model is not a model !\"\n else:\n # depending of the model\n if isinstance(model, BoostedTrees):\n id_solver_results = model.forest[0].id_solver_results\n classifier = self.learner_information[id_solver_results].raw_model\n results = self.learner_information[id_solver_results]\n if isinstance(model, RandomForest):\n id_solver_results = model.forest[0].id_solver_results\n classifier = self.learner_information[id_solver_results].raw_model\n results = self.learner_information[id_solver_results]\n if isinstance(model, DecisionTree):\n id_solver_results = model.id_solver_results\n classifier = self.learner_information[id_solver_results].raw_model\n results = self.learner_information[id_solver_results]\n\n # 2: Get the correct indexes:\n possible_indexes = None\n\n if isinstance(indexes, str):\n if os.path.isfile(indexes):\n files_indexes = indexes\n elif os.path.isdir(indexes):\n if instances_id is None:\n found = False\n for filename in os.listdir(indexes):\n file = os.path.join(indexes, filename)\n if os.path.isfile(file) and file.endswith(\".instances\"):\n files_indexes = file\n assert not found, \"Too many .instances files in the directory: \" + indexes + \". Please put directly the good file in the option or use the instances_id parameter.\"\n found = True\n else:\n found = False\n for filename in os.listdir(indexes):\n file = os.path.join(indexes, filename)\n if os.path.isfile(file) and file.endswith(\".\" + str(instances_id) + \".instances\"):\n files_indexes = file\n found = True\n break\n assert found, \"No .\" + str(\n instances_id) + \".instances\" + \" files in the directory: \" + indexes + \" Please put directly the good file in the option or use the instances_id parameter !\"\n\n Tools.verbose(\"Loading instances file:\", files_indexes)\n f = open(files_indexes)\n data = json.loads(json.load(f))\n possible_indexes = data['indexes']\n f.close()\n\n elif indexes == Indexes.Training or indexes == Indexes.Test or indexes == Indexes.Mixed:\n possible_indexes = results.training_index if indexes == Indexes.Training else results.test_index\n if indexes == Indexes.Mixed and n is not None and len(possible_indexes) < n:\n for i in range(n + 1 - len(possible_indexes)):\n if i < len(results.training_index):\n possible_indexes = numpy.append(possible_indexes, results.training_index[i])\n # Tools.verbose(\"possible indexes:\", possible_indexes, n)\n # load data and get instances\n # 2b : shuffle data if asked\n if isinstance(possible_indexes, numpy.ndarray):\n possible_indexes = possible_indexes.tolist()\n\n # 3: Get the correct data (select only data that we need):\n if self.data is None:\n assert dataset is not None, \"Data are not loaded yet. You have to put your dataset filename through the 'dataset' parameter !\"\n if possible_indexes is not None:\n data, labels = self.load_data_limited(dataset, possible_indexes, n)\n else:\n possible_indexes = [i for i in range(len(self.data))]\n data, name = self.parse_data(dataset)\n if data is not None:\n self.load_data(data, name)\n data = self.data\n labels = self.labels\n else:\n if possible_indexes is None:\n possible_indexes = [i for i in range(len(self.data))]\n data = [self.data[x] for x in possible_indexes]\n labels = self.labels\n else:\n data = numpy.array([self.data[x] for x in possible_indexes])\n labels = numpy.array([self.labels[x] for x in possible_indexes])\n\n # 4: Select instances according to parameters and data that is modify with only instances of possible_indexes.\n instances = []\n instances_indexes = []\n\n original_indexes = list(range(len(data)))\n if seed is not None:\n random.Random(seed).shuffle(original_indexes)\n else:\n random.shuffle(original_indexes)\n\n if model is None or self.get_solver_name() == \"Generic\":\n for j in original_indexes:\n current_index = possible_indexes[j]\n instances.append((data[j], None))\n instances_indexes.append(current_index)\n if isinstance(n, int) and len(instances) >= n:\n break\n else:\n for j in original_indexes:\n current_index = possible_indexes[j]\n\n prediction_solver = classifier.predict(data[j].reshape(1, -1))[\n 0] # J'ai, a priori de la chance, que la fonction predict de xgboost et scikit learnt ont la meme def !\n label = labels[j]\n if (correct and prediction_solver == label) \\\n or (not correct and prediction_solver != label) \\\n or (correct is None):\n if predictions is None or prediction_solver in predictions:\n instances.append((data[j], prediction_solver))\n instances_indexes.append(current_index)\n if isinstance(n, int) and len(instances) >= n:\n break\n if save_directory is not None:\n # we want to save the instances indexes in a file\n name = self.dataset_name.split(os.sep)[-1].split('.')[0]\n if not os.path.isdir(save_directory):\n os.mkdir(save_directory)\n base_directory = save_directory\n\n if instances_id is None:\n complete_name = base_directory + os.sep + name + \".instances\"\n else:\n complete_name = base_directory + os.sep + name + \".\" + str(instances_id) + \".instances\"\n data = {\"dataset\": name,\n \"n\": len(instances_indexes),\n \"indexes\": instances_indexes}\n\n json_string = json.dumps(data)\n with open(complete_name, 'w') as outfile:\n json.dump(json_string, outfile)\n\n Tools.verbose(\"Indexes of selected instances saved in:\", complete_name)\n Tools.verbose(\"number of instances selected:\", len(instances))\n Tools.verbose(\"----------------------------------------------\")\n if len(instances) == 0 and n == 1:\n return None, None\n return instances if n is None or n > 1 else instances[0]\n","sub_path":"sources/learning/Learner.py","file_name":"Learner.py","file_ext":"py","file_size_in_byte":31870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"453332988","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport re\nimport os\nimport time\n\nimport sys\nsys.setrecursionlimit(10000000) #设置递归限制为一千万\n\n#该文件使用说明\n#1、请修改16行和17行文件输入输出位置Location(默认输入、输出位置在本文件所在文件夹)\n#2、按照要求选择输出那种变异算子的变异体\n#3、如果程序崩溃请将df函数中的延迟注释取消\n4\n#Please modify the location of the file-------------------------------------------------------------------------Location\ninfilename = './test.c'\noutfilename = './'\n\ninfilenameinput = raw_input(\"Please enter the location of the test file.The default location is\\' ./test.c \\' :\\n\")\nif infilenameinput != \"\":\n infilename = infilenameinput\n\noutfilenameinput = raw_input(\"Please enter the location of the output.The default location is\\' ./ \\' :\\n\")\nif outfilenameinput != \"\":\n outfilename = outfilenameinput\n\n#Clear Note Start----------------------------------------------------------------------------------------------ClearNote\ndef clearNote():\n fp = open(infilename, \"r\")\n flag = 0\n quote = 0\n re = \"\"\n for line in fp:\n myline = \"\"\n length = len(line)\n for index in range(length):\n if flag == 0 and quote == 0 and line[index] == \"\\\"\":\n quote = 1\n myline += line[index]\n continue\n if flag == 0 and quote == 1 and line[index] == \"\\\"\":\n quote = 0\n myline += line[index]\n continue\n if quote != 1 and flag == 2 and line[index] == \"\\n\":\n flag = 0\n if quote != 1 and flag == 0 and line[index] == \"/\" and line[index + 1] == \"*\":\n flag = 1\n if quote != 1 and index > 0 and flag == 1 and line[index - 1] == \"/\" and line[index - 2] == \"*\":\n flag = 0\n if quote != 1 and flag == 0 and line[index] == \"/\" and line[index + 1] == \"/\":\n flag = 2\n if flag == 1 or flag == 2:\n continue\n myline += line[index]\n re += myline\n fp.close()\n with open(infilename, 'w') as f:\n f.write(re)\n pass\nclearNote()\n#Clear Note End---------------------------------------------------------------------------------------------------------\n\n#Construct Mutant Operator Classes-----------------------------------------------------------------------OperatorClasses\n#Absolute Value Insertion----------------------------------------ABS\nabs = [\"abs(\",\"(\"]\npattern_abs = re.compile(r' abs\\(')\n#Arithmetic Operator Replacement---------------------------------AOR\naor = [\" + \", \" - \", \" * \",\" / \",\" % \"]\npattern_aor = re.compile(r' \\+ | \\- | \\* | \\% | / ')\n#Logical Connector Replacement-----------------------------------LCR\nlcr = [\" && \", \" || \"]\npattern_lcr = re.compile(r' && | \\|\\| ')\n#Relational Operator Replacement---------------------------------ROR\nror = [\" <= \",\" >= \",\" == \",\" != \",\" > \",\" < \"]\npattern_ror = re.compile(r' <= | >= | < | > | == | != ')\n#Unary Operator Insertion----------------------------------------UOI\nuoi = [\"++\",\"--\"]\npattern_uoi = re.compile(r'\\+\\+|\\-\\-')\n#Construct Mutant Operator Classes--------------------------------------------------------------------------------------\n\n# Read File Contents--------------------------------------------------------------------------------------------readFile\nprint(\"loading file \\\" \"+ infilename +\" \\\".....................................................\")\nwith open(infilename) as f:\n contents = f.read()\n time.sleep(1)\n# Read File Contents----------------------------------------------------------------------------------------------------\n\n#mkdir-------------------------------------------------------------------------------------------------------------mkdir\nfilename = [\"AOR\",\"LCR\",\"ROR\",\"UOI\",\"ABS\"]\ndef mkdir(path):\n path = path.strip()\n\n isExists = os.path.exists(path)\n if not isExists:\n os.makedirs(path)\n return True\n else:\n return False\nprint (\"mkdir \" + outfilename + \"ABS /AOR /LCR /ROR /UOI successed......................................\")\nfor indexfilename in range(0,len(filename)):\n mkdir(outfilename+filename[indexfilename])\n#mkdir------------------------------------------------------------------------------------------------------------------\n\n\naor_rt = re.split(pattern_aor,contents)\nprint (\"The number of AOR Mutant Operator: \" + str(len(aor_rt) -1) + \" ; \" + \"The number of files can be produced: 5^\" + str(len(aor_rt) - 1))#, \" + \"变异算子为分别为:\" + str(pattern_aor.findall(contents)))\n\nlcr_rt = re.split(pattern_lcr,contents)\nprint (\"The number of LCR Mutant Operator: \" + str(len(lcr_rt) -1) + \" ; \" + \"The number of files can be produced: 2^\" + str(len(lcr_rt) - 1))#, \" + \"变异算子为分别为:\" + str(pattern_lcr.findall(contents)))\n\nror_rt = re.split(pattern_ror,contents)\nprint (\"The number of ROR Mutant Operator: \" + str(len(ror_rt) -1) + \" ; \" + \"The number of files can be produced: 6^\" + str(len(ror_rt) - 1))#, \" + \"变异算子为分别为:\" + str(pattern_ror.findall(contents)))\n\nuoi_rt = re.split(pattern_uoi,contents)\nprint (\"The number of UOI Mutant Operator: \" + str(len(uoi_rt) -1) + \" ; \" + \"The number of files can be produced: 2^\" + str(len(uoi_rt) - 1))#, \" + \"变异算子为分别为:\" + str(pattern_uoi.findall(contents)))\n\nabs_rt = re.split(pattern_abs,contents)\nprint (\"The number of ABS Mutant Operator: \" + str(len(abs_rt) -1) + \" ; \" + \"The number of files can be produced: 2^\" + str(len(abs_rt) - 1))#, \" + \"变异算子为分别为:\" + str(pattern_abs.findall(contents)))\n\n\n# 构造操作字符串数组\nglobal result\nresult = []\ndef constructResult(rt):\n for index in range(0, len(rt)):\n result.append(rt[index])\n result.append(\" \")\n pass\n\nglobal cont\ncont = 0\ndef printme(param,i):\n global cont\n cont += 1\n print (\"Start creating the\" + str(cont) + \"file.............................\")\n with open(outfilename + \"/\" + filename[i] + \"/\" + str(cont) + '.c', 'w') as f:\n f.write(param)\n\n return cont\n\nstri = raw_input(\"AOR input 0;\\t LCR input 1;\\t ROR input 2;\\t UOI input 3;\\t ABS input 4\\t\\nPlease input: \\n\")\n\nglobal maxTime\nmaxTime= raw_input(\"Please input the maxTime of output files : \")\n\ndef df(param,r,i):\n global endtime1\n endtime1 = int(round(time.time()*1000))\n\n if int(maxTime) <= int(endtime1 - starttime):\n return\n\n if param >= len(result) - 1:\n fileResult = \"\".join(result)\n printme(fileResult,i)\n # time.sleep(1)\n return\n\n for index2 in range(0, len(r)):\n result[param] = r[index2]\n df(param + 2, r, i)\n\nif stri == \"0\":\n starttime = int(round(time.time()*1000))\n constructResult(aor_rt)\n df(1, aor, 0)\n endtime = int(round(time.time()*1000))\nif stri == \"1\":\n starttime = int(round(time.time()*1000))\n constructResult(lcr_rt)\n df(1, lcr, 1)\n endtime = int(round(time.time()*1000))\nif stri == \"2\":\n starttime = int(round(time.time()*1000))\n constructResult(ror_rt)\n df(1, ror, 2)\n endtime = int(round(time.time()*1000))\nif stri == \"3\":\n starttime = int(round(time.time()*1000))\n constructResult(uoi_rt)\n df(1, uoi, 3)\n endtime = int(round(time.time()*1000))\nif stri == \"4\":\n starttime = int(round(time.time()*1000))\n constructResult(abs_rt)\n df(1, abs, 4)\n endtime = int(round(time.time()*1000))\n\n\nprint(str(cont)+\"files have been created. \"+\"Spend time \"+ str(endtime1-starttime) +\" ms\")\nend = raw_input(\"end\")","sub_path":"mutant generator1.0.3.py","file_name":"mutant generator1.0.3.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"542763678","text":"'''\nNapisz program zliczający liczbę znaków w podanym przez użytkownika napisie pomiędzy nawiasami <>.\nNawiasy mogą wystąpić tylko raz.\nAla ma , a kot ma Alę\n'''\n\n# 1 sprawdzam liczbe < i > - powinno byc po 1\n# 2 jak jest wiecej niz po 1 to koniec programy\n\n# 3 w petli sprawdzam czy:\n# mam zliczzac\n# mam przestac zliczac\n# czy zlicznie jest wlaczone i wtedy zliczam\n\nnapis = input(\"Podaj napis: \")\n\n# uzyjemy tu metody count ktora zlicza wystapienia danego czegos\nif napis.count('<') != 1 or napis.count('>') != 1:\n print(\"Nieprawidlowa ilosc nawiasiow !!!\")\n exit() #konczymy program\n\n\nliczba_znakow = napis.index('<') - napis.index('>') - 1\n\nprint(f\"W napisie '{napis}' znaleziono '{liczba_znakow}' znakow miedzy nawiasami <>\")\n","sub_path":"kolekcje_part_2/liczenie_znakow_w_napisie_miedzy_nawiasami_2.py","file_name":"liczenie_znakow_w_napisie_miedzy_nawiasami_2.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"320730427","text":"import sys\nfrom setuptools import setup, find_packages\nimport codecs\nimport os.path\n\n\ndef read(rel_path):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, rel_path), 'r') as fp:\n return fp.read()\n\n\ndef get_version(rel_path):\n for line in read(rel_path).splitlines():\n if line.startswith('__version__'):\n delim = '\"' if '\"' in line else \"'\"\n return line.split(delim)[1]\n else:\n raise RuntimeError(\"Unable to find version string.\")\n\n\ninstall_requires = [\n \"aiohttp==3.*\",\n \"aiohttp-cors==0.7.*\",\n \"etcd3-py==0.1.*\",\n \"keystoneauth1==4.*\",\n \"kubernetes-asyncio==22.*\",\n \"lark-parser==0.11.*\",\n \"makefun==1.*\",\n \"marshmallow==3.*\",\n \"marshmallow-enum\",\n \"marshmallow-oneofschema\",\n \"marshmallow-union\",\n \"mock\",\n \"pyOpenSSL\",\n \"python-magnumclient==3.*\",\n \"PyYAML==5.*\",\n \"requests==2.*\",\n \"SQLAlchemy==1.4.46\",\n \"oslo.db==11.3.0\",\n \"tosca-parser==2.6.*\",\n \"deepdiff==6.2.*\",\n \"yarl==1.8.*\",\n \"influxdb_client\",\n]\n\n# webargs\nif sys.version_info < (3, 10):\n install_requires.append(\"webargs==8.*\")\nelse:\n install_requires.append(\"webargs==6.*\")\n\n# The newest importlib_metadata version isn't completely compatible with the oldest\n# python version Krake supports (or better so, the tests we wrote with that).\nif sys.version_info < (3, 8):\n install_requires.append(\"importlib_metadata==3.6.*\")\n\n\nsetup(\n name=\"krake\",\n version=get_version(\"krake/__about__.py\"),\n description=\"\",\n url=\"https://gitlab.com/rak-n-rok/krake\",\n maintainer=\"Krake Development Team\",\n maintainer_email=\"krake@cloudandheat.com\",\n python_requires=\">=3.8\",\n packages=find_packages(),\n install_requires=install_requires,\n extras_require={\n \"dev\": {\n \"factory-boy==2.*\",\n \"mock==4.*\",\n \"prometheus-async==19.*\",\n \"prometheus-client==0.7.*\",\n \"pytest==6.*\",\n \"pytest-aiohttp==0.3.*\",\n \"pytest-cov==3.*\",\n \"pytest-httpserver==1.*\",\n \"pytz==2021.*\",\n \"tox==3.*\",\n \"pre-commit==2.*\",\n \"keystone==20.*\",\n \"pytest-httpserver==1.*\",\n },\n \"ansible\": {\n \"ansible>=2.9\",\n \"python-openstackclient\",\n \"openstacksdk\"\n },\n \"api_generator\": {\n \"black==21.11b1\",\n \"jinja2==3.*\"\n },\n },\n scripts=[\n \"scripts/krake_bootstrap_db\",\n \"scripts/krake_generate_config\"\n ],\n)\n","sub_path":"krake/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"51120637","text":"# Escreva um algoritmo para mostrar a média final de um aluno a partir de 4 notas. \r\n# Considere que as notas podem ter casas decimais.\r\n# Para o cálculo da média final, deve-se utilizar média ponderada, aplicando-se a seguinte fórmula:\r\n\r\n# M = ( ( p1 x 30) + (p2 x 40) + (t1 x 10) + (t2 x 20) ) / 100\r\n\r\n\r\nP1 = float(input('nota da primeira prova:'))\nP2 = float(input('nota da segunda prova:'))\nT1 = float(input('nota do primeiro trabalho:'))\nT2 = float(input('nota do segundo trabalho:'))\nM = ((P1*30)+(P2*40)+(T1*10)+(T2*20))/100\nprint('A média é:',M)\n","sub_path":"Ex1.py","file_name":"Ex1.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"239610598","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 26 15:33:27 2017\r\n\r\n@author: pkress\r\nDescription: Takes wafsum data, summary types, PCs and a variable to return \r\n correlation and pvalue information organized by sumtype for the \r\n variable across PCs.\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef vardf(wafsums, sumtypes, pcnosarr, var):\r\n varsumdfs = []\r\n for ip in sumtypes:\r\n varcorrs = wafsums[ip][1][0][var]\r\n varpvals = wafsums[ip][1][1][var]\r\n varsumdf = pd.DataFrame(np.transpose([varcorrs,varpvals]))\r\n varsumdf.columns = ['corrs','pvals']\r\n varsumdf.index = pcnosarr\r\n varsumdfs.append(varsumdf)\r\n varsumdict = {ip: varsumdfs[sumtypes.index(ip)] for ip in sumtypes}\r\n return varsumdict","sub_path":"vardf.py","file_name":"vardf.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"176324958","text":"# Original author: LMongoose\r\n\r\n# information about MS OOXML sourced from http://officeopenxml.com/index.php\r\n\r\nimport sys, re, zipfile\r\n\r\nclass Xlsx():\r\n\tdef __init__(self, p_filename):\r\n\t\twith open(p_filename,\"rb\") as sourcefile:\r\n\t\t\tsourcedata = sourcefile.read()\r\n\t\t\tif(sourcedata[:2] != b\"PK\"):\r\n\t\t\t\tprint(\"The file '\"+p_filename+\"' is not a valid excel xlsx workbook!\")\r\n\t\t\t\tsys.exit()\r\n\t\t\telse:\r\n\t\t\t\tself.collection = zipfile.ZipFile(p_filename, \"r\")\r\n\r\n\t@property\r\n\tdef cellsdata(self):\r\n\t\t\"\"\"\r\n\t\t\tContains the content of the cells in workbook\r\n\t\t\"\"\"\r\n\t\tfile_sharedstrings = self.collection.open(\"xl/sharedStrings.xml\",\"r\").read().decode()\r\n\t\tlist_strings = re.findall(\"\\(.+?)\\<\\/t\\>\", file_sharedstrings)\r\n\t\treturn list_strings\r\n\r\n\t@property\r\n\tdef worksheets(self):\r\n\t\t\"\"\"\r\n\t\t\tContains the sheet layout of the sheets in workbook\r\n\t\t\"\"\"\r\n\t\tlistsheets = []\r\n\t\tfor filename in self.collection.namelist():\r\n\t\t\tif(filename.startswith(\"xl/worksheets/\")):\r\n\t\t\t\tlistsheets.append(self.collection.open(filename,\"r\").read().decode())\r\n\t\treturn listsheets\r\n\t\t\r\n\t@property\r\n\tdef cells(self):\r\n\t\t\"\"\"\r\n\t\t\tContains a list of dicts, each dict containing \r\n\t\t\tthe cell attributes of each cell in workbook\r\n\t\t\"\"\"\r\n\t\tcells = []\r\n\t\tfor file_sheet in self.worksheets:\r\n\t\t\tfor raw_cell in re.findall(\"\\\", file_sheet):\r\n\t\t\t\tcell = {\r\n\t\t\t\t\t\"sheet_coord\": re.findall(\"r=\\\"(.+?)\\\"\",raw_cell)[0],\r\n\t\t\t\t\t\"data_type\": re.findall(\"t=\\\"(.+?)\\\"\",raw_cell)[0],\r\n\t\t\t\t\t\"pos_in_sharedstrings\": re.findall(\"(.+?)\",raw_cell)[0],\r\n\t\t\t\t\t\"data\": self.cellsdata[int(re.findall(\"(.+?)\",raw_cell)[0])]\r\n\t\t\t\t}\r\n\t\t\t\tcells.append(cell)\r\n\t\treturn cells\r\n\r\n# usage:\r\nexcel = Xlsx(\"file.xlsx\")\r\nfor item in excel.cells:\r\n\tprint(item)\r\n","sub_path":"scripts/v1/xlsxparser.py","file_name":"xlsxparser.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"445213962","text":"#!/usr/local/bin/python3\n\n###Script to extract phasiRNA from a cluster file for specific library\n### Used phased loci name as in PARE validation results or coords in csv format to extract the phasiRNAs\n### Requires 1) combined cluster fle matching p-value used to uniue phased loci 2) Non-redundant phased loci list 3)sRNA DB\n\nimport os,sys,difflib,time,operator\nimport mysql.connector as sql\n\n\n##########Settings###################\n\nclustfile = \"All.24Phas.score_p5e-07_sRNA_24_out.cluster\" ## Cluster file from phasing analysis, coul dbe for one lib or concatanated file for all libs\nfetchMax = 1 ## Fetch the max abundance phasi from tag position summmary, write in separate file\nfetchLibAbun = 0 ## 0: Fetch libwise abundances for tags with 'phase' len | 1: All tags from phaster\nsRNADB = \"DAYLILY_priv_sRNA\" ## if fetchMax == Y | Use this DB to get tag with max abundance\n\n\n#### User specifed coords in input file\ncoordsfile = \"test.phas.txt\" ## File with either phased loci ID 'Phas-100_w_7:6353898:6354260' or coords 'w,7,6353898,6354260'\nseqType = 1 ## 0: Genomic coords and normal seq files 1: PacBio/Trinity - with lots of stuff in header\nphase = 24\nhead = \"Y\"\ncoordsep ='\\t' ## Seprator used in the file\nphasedID = 'N' ## If given than phas ID is used to extract coords, if not than coords specified by user are used\nchrcol = 3 ## As in excel format\nstartcol = 4 ## As in excel format\nendcol = 5 ## As in excel format\n\nphasiLenFilter = 'Y' ## 'Y' then tags of phase length will be written from the cluster | 'N' - All tags will be written\nminAbun = 1 ## Minimum abundance of tag to be written\nmatchThres = 0.95 ## Ratio of match required by the cluster to phased loci\nstartbuff = 0 ## While extracting sequence through coords2FASTA a buffer is added to start, \n ## start position in phased ID has this buffer added, ## so minus this buffer \n ## for better matching with real loci\n\nlibType = 0 ## 0: Lib_ids (4518) | 1: lib_code ('leaf_1')\nexcludeLibs = [4518,5006,5003,5004,5005,4519,4521,4523,4525,4527,4520,4522,4524,4526,4528] ## Used if fetchMax == 'Y' | Libs you wish to exclude, your tag position summary table should have libs ids and not lib codes\n\ndataserver = 'tarkan.dbi.udel.edu'\nDB = \"kakrana\"\n\n############ FUNCTIONS ##############\n#####################################\n\ndef reader(coordsfile):\n '''\n Reads coordinates file and return a list of PHASE ID and their coords values\n '''\n\n fh_in = open(coordsfile)\n if head == 'Y':\n fh_in.readline()\n\n phasCount = 0 ## Count of entries read\n phasList = [] ## List to store results \n for ent in fh_in:\n\n # print('\\n\\nEntry from input file being matched: %s' % (ent))\n coords = ent.split(coordsep)\n #print('coords:',coords)\n if phasedID == 'Y': ## Extract coords from phased ID\n loci = coords[0].split('_') ## Phas-10_w_3:27574117:27574772\n # phasID = loci[0]\n fusedcoords = loci[2].split(':') ## 3:27574117:27574772\n get_chr_id = fusedcoords[0].replace(\"chr\",\"\").replace(\"Chr\",\"\")\n astart = fusedcoords[1]\n aend = fusedcoords[2]\n get_start = int(astart)+startbuff ## It should be added to reduce length of loci\n get_end = int(aend)+1 \n phasID = '%s_%s_%s' % (get_chr_id,astart,aend) ## 1 added because when opening a range using start and end, end number is not included in range\n phasCount += 1\n \n elif phasedID == 'N': ## User specified coords\n # print(\"File with user specified columns will be used\")\n get_chr_id = coords[chrcol-1]\n astart = coords[startcol-1]\n aend = coords[endcol-1] \n get_start = int(int(astart)+startbuff)\n get_end = int(aend)+1 ## 1 added because when opening a range using start and end, end number is not included in range\n phasID = '%s_%s_%s' % (get_chr_id,astart,aend) ## Name to be used in output file\n print(\"Phased Loci: %s #######################################################\" % (phasID))\n phasCount += 1\n\n else:\n print(\"Please input correct value for 'phasedID' or check your file\")\n\n get_value = (list(range(int(str(get_start)),int(str(get_end)))))\n phasList.append((phasID,get_chr_id,get_start,get_end,get_value))\n \n print(\"Entries read:%s | Entries cached:%s\" % (phasCount,len(phasList)))\n\n return phasList\n\ndef getClust(clustfile,phasList):\n \n fh_in = open(clustfile,'r')\n clusters = fh_in.read().split('>')\n \n resList = [] ## Store final results as (phas,[(phasiRNA),(PhasiRNA)],[extra info])\n \n phasCount = 0 ## Total phased loci in file\n uniqMatchCount = 0 ## Atleast one cluster present for one phased loci\n allMatchCount = 0 ## Total number of matched cluster\n \n for ent in phasList: ## Given an entry in coords file\n phasID,get_chr_id,get_start,get_end,get_value = ent\n # print(\"This is the PhasId: %s | values:%s\" % (phasID,get_value))\n print(\"\\n\\nPhaseID being queried:%s ##############\" % (phasID))\n phasCount +=1 \n print(\"%s/%s phasID\" % (phasCount,len(phasList)))\n\n ## Find matching cluster\n matchCount = 0 ## Total maching clusters for a phased loci - if same cluster in multiple libraries\n finalMatchList = [] ## Holds best cluster, from multiple libraries\n \n \n for aclust in clusters[1:]:\n tempMatchList = [] ## To hold results of current matching cluster\n aclust_splt = aclust.split('\\n')\n header = aclust_splt[0].split()\n clust_id = header[2]\n chr_id = header[6].replace(\"chr\",\"\").replace(\"Chr\",\"\")\n start = header[10]\n end = int(header[12])+1 ##1 added because when opening a range using start and end, end number is not included in range\n value = (list(range(int(str(start)),int(str(end)))))\n #print ('Cluster:', (value))\n\n if seqType == 0: \n ## Normal genomic coordinates with integer chr_id\n get_chr_id = int(get_chr_id)\n chr_id = int(chr_id)\n else:\n ## Chromosomes are transcript names i.e. strings\n pass\n\n \n if get_chr_id == chr_id:\n sm=difflib.SequenceMatcher(None,get_value,value)\n \n if round(sm.ratio(),2) >= matchThres:\n ### Matched - phasiRNA from this cluster\n print ('\\nMatching cluster found:%s' % ''.join(header))\n matchCount +=1\n \n phasiCyc = 0 ## Stores phasing cycles\n phasiSig = 0 ## Stores total abundance of phased sRNAs\n \n for i in aclust_splt[1:-1]:## Because header was the first entry of block and not required here, Last entry is always empty\n # print (\"Matched Cluster:\\n\",i)\n phasient = i.split('\\t')\n phasiname = phasient[4].replace(\"|\",\"_\")\n phasiseq = phasient[5]\n phasilen = int(phasient[6])\n phasiabun = int(phasient[7])\n phasihits = int(phasient[10].split(\"=\")[1])\n phasipos = int(phasient[3])\n\n # print(phasiname,phasiabun,phasiseq,phasilen)\n tempMatchList.append((phasiname,phasiabun,phasiseq,phasilen,phasihits,phasipos))\n\n if int(phasilen) == phase:\n phasiCyc +=1\n phasiSig += phasiabun\n \n print(\"Current Cycles:%s | Current sig. strength:%s\" % (phasiCyc,phasiSig))\n tempMatchList.append((phasiCyc,phasiSig,phasID,clust_id))\n\n ## Decide the best and remove other from list ##############################\n ############################################################################\n if finalMatchList:\n ## There exists a previosly matched cluster\n exist_phasiCyc = finalMatchList[-1][0]\n exist_phasiSig = finalMatchList[-1][1]\n print(\"Existing Cycles:%s | Existing sig. strength:%s\" % (exist_phasiCyc,exist_phasiSig))\n\n if phasiCyc > exist_phasiCyc: ## New cluster has more cycles\n del finalMatchList[0:]\n finalMatchList = list(tempMatchList)\n print(\"--- New cluster selected ---\")\n\n elif phasiCyc == exist_phasiCyc: ## Both have same cycles\n if phasiSig > exist_phasiSig: ## New one has more total abundance of phased siRNAs\n del finalMatchList[0:]\n finalMatchList = list(tempMatchList)\n print(\"--- New cluster selected ---\")\n \n else: ## Existing/old one was long i.e. had more cycles\n print(\"Earlier recorded cluster is retained\")\n pass\n\n else: ## This is the first cluster\n finalMatchList = list(tempMatchList)\n\n # print(\"\\nFinal Match List:\",finalMatchList)\n else:\n # print(\"No Match with this cluster\")\n pass\n\n resList.append((phasID,finalMatchList)) ## Add best matched entry to the final list, there has to be one best matched entry per PHAS\n \n allMatchCount += matchCount ## Add the matched cluster for each entry\n if matchCount > 0 :\n uniqMatchCount+=1\n \n print(\"\\nTotal phas loci: %s | Matched: %s\" % (len(phasList),len(resList)))\n print (\"SUMMARY: Phased loci in input file:%s | Loci match threshold: %s |Uniq matched cluster: %s | Total matched clusters found:%s\" % (phasCount,matchThres,uniqMatchCount,allMatchCount))\n print(\"NOTE: If matched clusters more then phased loci that means same cluster was present in different libs\\n\")\n # print(\"NOTE: Don't forget to uniq the miRNAs\")\n fh_in.close()\n\n return resList\n\ndef writer(resList,con):\n '''\n write the results\n '''\n\n print(\"\\n\\nFunction:Writer\\n\")\n\n outfile = clustfile+'thres_%s_phasi.csv' % matchThres ## 2437.txt.score_p1e-07_sRNA_21_out.cluster\n fh_out = open(outfile,'w')\n\n\n if fetchMax == 1: ### Fetch max phasi for each loci \n cur= con.cursor()\n queryLibs,sumLibs,finalLibs = prepareQuery(excludeLibs,cur)\n \n outfile2 = \"fetchMax.txt\"\n fh_out2 = open(outfile2,'w')\n libsHead = queryLibs.split(\",\")\n fh_out2.write(\"loci\\tmaxtag\\tmaxTagAbun\\ttotalPhasAbun\\t#phaseTags\\t%s\\n\" % ('\\t'.join(x for x in libsHead)))\n # print(queryLibs) ## Libs whose abindance will be summed to give final abundance of tags\n abunList = [] ### List to capture tags and abundance for each phased loci\n libAbunList = [] ## Lib-wise abundances of tag\n\n for ent in resList: ## entry corresponds to one phased loci\n print(\"\\nEntry\",ent)\n phasID = ent[0]\n phasCycles = ent[1][-1][0]\n phasSig = ent[1][-1][1]\n clustID = ent[1][-1][2]\n phasiList = ent[1][0:-1]\n # print(\"%s | phasCycles:%s | phasSig:%s\" % (phasID,phasCycles,phasSig))\n\n for i in phasiList:\n print(\"-Phasi\",i) ## Phasiname,phasiabun,phasiseq,phasilen,phasihits,phasipos\n tag = i[2]\n \n ## Write phasiRNAs \n if phasiLenFilter == 'Y': ## If tags filter is ON\n if int(i[3]) == int(phase) and int(i[1]) >= minAbun: ### Size specified in settings\n # print(phasID,clustID,i[0],i[1],i[2])\n fh_out.write('>%s_Clust%s_%s,%s,%s\\n%s,%s,%s\\n' % (phasID,clustID,i[0],i[1],i[4],tag,i[1],i[4]) ) ## phasID,clust_id,phasiname,phasiabun,phasiseq,phasiabun\n\n else:\n if int(i[1]) > minAbun:\n # print(phasID,clustID,i[0],i[1],i[2])\n fh_out.write('>%s_Clust%s_%s,%s,%sn%s,%s\\n' % (phasID,clustID,i[0],i[1],i[4],tag,i[1],i[4]) ) ## phasID,clust_id,phasiname,phasiabun,phasiseq,phasiabun\n pass\n\n ## Get max abundance phasiRNA for specified phase\n if fetchMax == 1:\n\n ## Get lib-wise abundaces mode\n if fetchLibAbun == 0:\n if len(tag) == int(phase):\n atag,abun_sum,lib_abun = getAbundance(cur,tag,finalLibs)\n libAbunList.append((lib_abun))\n\n elif fetchLibAbun == 1: ## All the tags\n atag,abun_sum,lib_abun = getAbundance(cur,tag,finalLibs)\n libAbunList.append((lib_abun))\n \n else:\n print(\"Libwise abundances won't be fetched\")\n pass\n\n ## Tag specific abundances for fetching most abundant tag\n if len(tag) == int(phase): ### Size specified in settings\n abunList.append((atag,abun_sum))\n\n\n print(\"Elements in phasiList:%s\" % (len(phasiList)))\n print(\"Elements in libAbunList:%s\" % (len(libAbunList)))\n\n\n ## Process Fetch max results for this phased loci\n #################\n if fetchMax == 1:\n abunList_sort = sorted(abunList, key=operator.itemgetter(1),reverse=True) ## Sort list on abundances to get max abundant phasiRNA\n print(\"\\nExample sorted values:%s\" % (abunList_sort[0:10]))\n maxTag = abunList_sort[0][0] ## max abundant tag\n maxAbun = abunList_sort[0][1] ## Abundance of max abundant tag\n totalAbun = sum(int(i[1]) for i in abunList_sort) ## Phased abundance\n\n ## Sum Lib-wise abundances for all tags\n libAbunSum = [0]*len(libAbunList[0]) ## This will hold sum of all tags, intialized for number of libraries\n for tag in libAbunList:\n # print(tag)\n libAbunSum = [sum(x) for x in zip(libAbunSum,tag)]\n \n print(\"Tag:%s | maxPhasTag:%s | totalPhasAbun:%s\" % (maxTag,maxAbun,totalAbun))\n print(\"Libwise Abundances\",libAbunSum)\n\n ## Write - Loci, most abundant tag, most abundant tag abun,total phased abun, number of phased tags, and lib-wise abundances\n fh_out2.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (phasID,maxTag,maxAbun,totalAbun,str(len(abunList_sort)),'\\t'.join(str(x) for x in libAbunSum)))\n abunList = [] ## Empty before next phased loci\n libAbunList = [] ## Empty lib-iwse abundances of tag list before next entry\n # sys.exit()\n\n fh_out.close()\n fh_out2.close()\n\n return outfile,outfile2\n\ndef getAbundance(cur,tag,finalLibs):\n '''Input is tag for each loci and out put is tag with maximmum abumdance and sum of phasiRNAs - \n rewritten in v1.0 for fetching tags from run master'''\n\n lib_abun = [] ## list to hold lib-wise abudnances\n \n for alib in finalLibs:\n # print(\"Lib:\",alib)\n \n cur.execute(\"SELECT tag,norm FROM %s.run_master where tag = '%s' and lib_id = %s\" % (sRNADB,tag,alib))### Convert intergenic to gene name so as to get strand\n info = cur.fetchall() ## Entries are redundant, one for every hit\n # print(\"Query fetched\", info)\n\n if info:\n atag,norm_abun = info[0]\n lib_abun.append(norm_abun)\n # print(\"--Tag abundance:%s for lib:%s\"% (tag,norm_abun))\n else:\n norm_abun = 0\n lib_abun.append(norm_abun)\n # print(\"--Tag abundance:%s for lib:%s\"% (tag,norm_abun))\n\n\n abun_sum = sum(lib_abun)\n print(\"--Lib-wise abundances\",lib_abun)\n print(\"--Sum of abundances:%s\\n\" % (abun_sum))\n\n # sys.exit()\n\n return tag,abun_sum,lib_abun\n \ndef prepareQuery(excludeLibs,cur):\n\n ### Prepare query of libs #################\n\n ### Get lib names\n columns = [] ## empty list\n cur.execute(\"SELECT DISTINCT(lib_id) FROM %s.run_master\" % (sRNADB))\n info = cur.fetchall()\n libs = [x[0] for x in info]\n\n print(\"\\nLibs:\",libs)\n\n if excludeLibs:\n print(\"\\n\\nLibs specifed in excludeLibs %s will be skipped\\n\\n\" % (excludeLibs))\n selectLibs = [] ## Columns excluding the unwanted libraries\n excludeLibs_s = [str(i) for i in excludeLibs] ## Converting all entries in exclude list to string for matching below\n \n for i in libs:\n\n ## Check if user made mistake in libType - as that will give results for all entries\n if type(i) is int and libType == 1:\n print(\"You seem to have input lib_id and chosen wrong libType\")\n print(\"Check libType and excludeLibs match - Script will exit now\")\n sys.exit()\n elif type(i) is str and libType == 0:\n print(\"You seem to have input lib_id and chosen wrong libType\")\n print(\"Check libType and excludeLibs match - Script will exit now\")\n sys.exit()\n else:\n print(\"All seems well\")\n pass\n\n ### Filter libraries\n if str(i) not in excludeLibs_s: ## Tested OK\n selectLibs.append(i)\n else:\n print(\"excluded:\",i)\n # sys.exit()\n pass\n \n finalLibs = selectLibs ## Norm_Sum and max_norm are not included\n\n else:\n finalLibs = libs ## ## Norm_Sum and max_norm are not included\n\n # print(\"finalLibs:%s\" % (finalLibs))\n \n lib_col =\",\".join(str(x) for x in finalLibs)### Manually mentioned strating lib column - should work on all tag position summary tables\n \n print(\"\\nLibrary Columns:\",lib_col)\n # queryLibs = 'SUM(%s)' % lib_col.replace(\",\",\"),SUM(\")\n sumLibs = \"%s\" % lib_col.replace(\",\",\"+\")\n queryLibs = \"%s\" % lib_col.replace(\",\",\",\")\n print(\"\\nThese are sumLibs:\",sumLibs)\n print(\"\\nThis is query Libs:\",queryLibs)\n # sys.exit()\n\n return queryLibs,sumLibs,finalLibs\n\ndef ConnectToDB(server, infile):\n \n ##infile values are '0' when you dont want to pulaod data from local file and '1' when you wish to upload data by local file\n ##EX:con=sql.connect(host= server, user='kakrana', passwd='livetheday', local_infile = infile)\n ##Now later in script you can\n ##cur.execute(\"LOAD DATA LOCAL INFILE './scoring_input_extend2' INTO TABLE bioinfo_data.mir_page_results FIELDS TERMINATED BY ','\")\n \n print ('\\nTrying to connect to mySQL server on %s' % (server))\n # Try to connect to the database\n try:\n con=sql.connect(host= server, user='kakrana', passwd='livetheday')###local_infile = 1 not supported yet so a table has to be updated on row basis\n print ('Connection Established\\n')\n\n # If we cannot connect to the database, send an error to the user and exit the program.\n except sql.Error:\n print (\"Error %d: %s\" % (sql.Error.args[0],sql.Error.args[1]))\n sys.exit(1)\n\n return con \n\n######## MAIN #######################\n####################################\ndef main():\n phasList = reader(coordsfile)\n time.sleep(1)\n\n resList = getClust(clustfile,phasList)\n\n con = ConnectToDB(dataserver,0)\n results,results2 = writer(resList,con)\n\n\nif __name__ == '__main__':\n main()\n print('\\n**script finished sucessfully**\\n')\n sys.exit()\n\n#### v0.1 -> v0.3\n## updated phas matching with chromosome not part of value instead matched before any ratio computation\n## If clusters for all libs are concatanated and same phased locus matches clusters from different libs then the longest phase cycle is slected and is phase cycle are same most abundant is selcted\n\n### v0.3 -> 0.4 [major][stable]\n### Organized script into functions\n### Added functionality to fetch max abundance phasiRNA for each locus\n\n## v0.4 -> v05 \n### Fixed bug fetching abundance of most abundant tag, norm sum was being fetched unstead of max norm for tag\n## Added fetching total abundance of phased tags - Useful for plotting\n\n## v05 -> v06\n## Added functionality to exclude libraries for which abundnace is not required\n## Made design more modular for functionality\n\n## v06 -> v07\n## Added functionality to work on transcipts -but not tested on PacBio\n\n## v07 -> v08\n## Added functionality to get lib-wise abundances of all tags (not filtered on size like maxTag, nTags, and totalAbun)\n## Fixed library exclusion - This needs to be propoagated to getCoords ABundances script\n\n## v08 -> v09\n## Added \"fetchLibAbun\" switch that fetches abudnances for all libs, either for tags that have len equal to phase or all tags irrespective of size\n\n## v09 -> v1.0\n## Elimnate need of tag position summary table requirement which is kind of unrealiable in case of non-genome species","sub_path":"PHAS/Old/phasiExtract.v1.0.py","file_name":"phasiExtract.v1.0.py","file_ext":"py","file_size_in_byte":22913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353085699","text":"import os\n\nfrom flask import render_template, redirect\nfrom flasgger import Swagger\nfrom app import create_app\nfrom instance.config import app_config\n\nconfig_name = os.getenv('FLASK_CONFIG') \napp = create_app(config_name)\n\nswag= Swagger(app,\n template={\n \"info\": {\n \"title\": \"Yummy Recipes api-v1\",\n \"description\": \"API that registers and logs in a user so as to use the features and functionality of yummy recipes.\"},\n \"securityDefinitions\":{\n \"TokenHeader\": {\n \"type\": \"apiKey\",\n \"name\": \"Authorization\",\n \"in\": \"header\"\n }\n }\n })\n@app.route(\"/\")\ndef main():\n return redirect('/apidocs')\n\n\nif __name__ == '__main__':\n app.run(port=5000)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214465271","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Created on 2013-1-31\n# User: Administrator\n# @author: JiangHuiliang\n# @email: jianghuiliang@hotmail.com\n#\n\n\n\n#import redis\nimport this\nimport os, sys, signal\n#import dircache\nimport time\nimport threading\n#import pexpect\n#import paramiko\nfrom socket import htons, htonl, ntohl , ntohs \nimport socket\ntry:\n import pycrypto\nexcept ImportError:\n print ('no packet')\nexcept NameError:\n print ('no name')\n\ndef ThreadFunction (a, b, c, t):\n print (t)\n time.sleep(20)\n \n return 0\n\ndef SignalHandler(sig, id):\n if sig == signal.SIGINT:\n print('Catch SIGINIT', id)\n if sig == signal.SIGTERM:\n print('Catch SIGTERM', id)\n sys.exit(0)\n\ndef main (argv):\n for a in argv:\n print (a)\n global mutex\n \n threads = []\n signal.signal(signal.SIGINT, SignalHandler)\n i=0\n while i < 1000:\n \n try:\n t = threading.Thread (target=ThreadFunction, args=(1, 2, 3, i))\n threads.append(t)\n t.start()\n ++i\n print('%s' % i)\n except RuntimeError:\n raise\n #t.start_new_thread(function, args)\n for t in threads:\n if not t.isDaemon():\n print (t.getName())\n t.join()\n \n \nif __name__ == '__main__':\n main(sys.argv)\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"162116885","text":"import xarray\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport argparse\n\nmpl.rc('figure', figsize = (15, 10))\nmpl.rc('font', size = 12)\nmpl.rc('axes.spines', top = False, right = False)\nmpl.rc('axes', grid = False)\nmpl.rc('axes', facecolor = 'white')\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input\", help=\"The PROMICE file you wish to convert to netCDF.\", type=str)\nparser.add_argument('year', help = 'Month you want to select', type = int)\nparser.add_argument('var', help = 'variable you want to analyse', type = str)\nargs = parser.parse_args()\n\nds = xarray.open_dataset(args.input)\ndf = ds.to_dataframe()\ndf = df[df.year == args.year]\n\ndf['julian_decimal_time'] = df['julian_decimal_time'].astype(int)\n\nyear = df['year']\njdt = df['julian_decimal_time']\n\ndf['temperature_tc_1'].replace([999.00], [245], inplace=True)\n\nvar_day_avg = df[args.var].groupby(jdt).mean()\nvar_day_max = df[args.var].groupby(jdt).max()\nvar_day_min = df[args.var].groupby(jdt).min()\n\nif year[0][0][0]%4 == 0:\n\tdays = range(1,367)\nelse:\n\tdays = range(1,366)\n\nplt.plot(days,var_day_avg, label='mean', color ='black')\n#plt.fill_between(days,var_day_max, var_day_min, label='max-min', facecolor='green', alpha=0.3)\nplt.plot(days,var_day_max, label='max', color = 'darkseagreen')\nplt.plot(days,var_day_min, label='min', color = 'lightskyblue')\nplt.legend(loc='best')\nplt.xlabel('Day of year')\nplt.ylabel('Temperature [Kelvin]')\nplt.title('Temperature at Summit for {}'.format(year[0][0][0]))\n\nplt.show()","sub_path":"analysis/annual_cycle.py","file_name":"annual_cycle.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"81506099","text":"# -*- coding: utf-8 -*-\n\"\"\"DrCIF test code.\"\"\"\nimport numpy as np\nfrom numpy import testing\nfrom sklearn.metrics import accuracy_score\n\nfrom sktime.classification.interval_based import DrCIF\nfrom sktime.datasets import load_basic_motions, load_unit_test\n\n\ndef test_drcif_on_unit_test_data():\n \"\"\"Test of DrCIF on unit test data.\"\"\"\n # load unit test data\n X_train, y_train = load_unit_test(split=\"train\", return_X_y=True)\n X_test, y_test = load_unit_test(split=\"test\", return_X_y=True)\n indices = np.random.RandomState(0).choice(len(y_train), 10, replace=False)\n\n # train DrCIF\n drcif = DrCIF(n_estimators=10, random_state=0, save_transformed_data=True)\n drcif.fit(X_train, y_train)\n\n # assert probabilities are the same\n probas = drcif.predict_proba(X_test.iloc[indices])\n testing.assert_array_equal(probas, drcif_unit_test_probas)\n\n # test train estimate\n train_probas = drcif._get_train_probs(X_train, y_train)\n train_preds = drcif.classes_[np.argmax(train_probas, axis=1)]\n assert accuracy_score(y_train, train_preds) >= 0.75\n\n\n# def test_contracted_drcif_on_unit_test_data():\n# \"\"\"Test of contracted DrCIF on unit test data.\"\"\"\n# # load unit test data\n# X_train, y_train = load_unit_test(split=\"train\", return_X_y=True)\n# X_test, y_test = load_unit_test(split=\"test\", return_X_y=True)\n#\n# # train contracted DrCIF\n# drcif = DrCIF(\n# time_limit_in_minutes=0.25,\n# contract_max_n_estimators=10,\n# random_state=0,\n# )\n# drcif.fit(X_train, y_train)\n#\n# assert len(drcif.estimators_) > 1\n# assert accuracy_score(y_test, drcif.predict(X_test)) >= 0.75\n\n\ndef test_drcif_on_basic_motions():\n \"\"\"Test of DrCIF on basic motions data.\"\"\"\n # load basic motions data\n X_train, y_train = load_basic_motions(split=\"train\", return_X_y=True)\n X_test, y_test = load_basic_motions(split=\"test\", return_X_y=True)\n indices = np.random.RandomState(4).choice(len(y_train), 10, replace=False)\n\n # train DrCIF\n drcif = DrCIF(n_estimators=10, random_state=0)\n drcif.fit(X_train.iloc[indices], y_train[indices])\n\n # assert probabilities are the same\n probas = drcif.predict_proba(X_test.iloc[indices])\n testing.assert_array_equal(probas, drcif_basic_motions_probas)\n\n\ndrcif_unit_test_probas = np.array(\n [\n [\n 0.1,\n 0.9,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.0,\n 1.0,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.9,\n 0.1,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.7,\n 0.3,\n ],\n [\n 0.0,\n 1.0,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 1.0,\n 0.0,\n ],\n ]\n)\ndrcif_basic_motions_probas = np.array(\n [\n [\n 0.0,\n 0.0,\n 0.0,\n 1.0,\n ],\n [\n 0.5,\n 0.5,\n 0.0,\n 0.0,\n ],\n [\n 0.0,\n 0.0,\n 0.6,\n 0.4,\n ],\n [\n 0.2,\n 0.7,\n 0.0,\n 0.1,\n ],\n [\n 0.0,\n 0.0,\n 0.2,\n 0.8,\n ],\n [\n 0.0,\n 0.1,\n 0.3,\n 0.6,\n ],\n [\n 0.7,\n 0.3,\n 0.0,\n 0.0,\n ],\n [\n 0.0,\n 0.1,\n 0.6,\n 0.3,\n ],\n [\n 0.3,\n 0.6,\n 0.0,\n 0.1,\n ],\n [\n 0.3,\n 0.7,\n 0.0,\n 0.0,\n ],\n ]\n)\n\n\n# def print_array(array):\n# print('[')\n# for sub_array in array:\n# print('[')\n# for value in sub_array:\n# print(value.astype(str), end='')\n# print(', ')\n# print('],')\n# print(']')\n#\n#\n# if __name__ == \"__main__\":\n# X_train, y_train = load_unit_test(split=\"train\", return_X_y=True)\n# X_test, y_test = load_unit_test(split=\"test\", return_X_y=True)\n# indices = np.random.RandomState(0).choice(len(y_train), 10, replace=False)\n#\n# drcif_u = DrCIF(n_estimators=10, random_state=0)\n#\n# drcif_u.fit(X_train, y_train)\n# probas = drcif_u.predict_proba(X_test.iloc[indices])\n# print_array(probas)\n#\n# X_train, y_train = load_basic_motions(split=\"train\", return_X_y=True)\n# X_test, y_test = load_basic_motions(split=\"test\", return_X_y=True)\n# indices = np.random.RandomState(4).choice(len(y_train), 10, replace=False)\n#\n# drcif_m = DrCIF(n_estimators=10, random_state=0)\n#\n# drcif_m.fit(X_train.iloc[indices], y_train[indices])\n# probas = drcif_m.predict_proba(X_test.iloc[indices])\n# print_array(probas)\n","sub_path":"sktime/classification/interval_based/tests/test_drcif.py","file_name":"test_drcif.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"204844316","text":"import csv\nimport os\nimport socket\nfrom os import path\nfrom queue import Queue\n\nfrom Server.centralCommunicator import centralCommunicator\nfrom Server.clientHandler import clientHandler\n\nHOST = ''\nPORT = 50000\n\n\n# CLIENT_TIMEOUT = 1800\n\n\n\nclass serverFindMyAdvisor:\n def __init__(self, inputDataLoc, finishedListLoc):\n print(\"begin initialization\")\n self.input_data_loc = inputDataLoc\n self.finished_list_loc = finishedListLoc\n\n self.url_list = Queue()\n self.finished_set = set()\n self.comm = centralCommunicator\n\n if not path.exists(\"../Data/finalTreeList\"):\n os.makedirs(\"../Data/finalTreeList\")\n\n self._init_connection()\n\n def _init_connection(self):\n try:\n print(\"this is server program, current hostname: \" + socket.gethostname(),\n \", ip: \" + socket.gethostbyname(socket.gethostname()))\n except Exception as e:\n print(e)\n self.socket_main = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket_main.bind((HOST, PORT,))\n self.socket_main.listen(120)\n self.accepted_sock_dict = {}\n\n print(\"socket initialization finsihed\")\n\n def _read_data(self):\n self.url_list.clear()\n if os.path.exists(self.finished_list_loc):\n with open(self.finished_list_loc, 'r') as ifile:\n for line in ifile:\n self.finishedSet.add(line.strip(' \\r\\n'))\n\n with open(self.input_data_loc, 'r') as ifile:\n reader = csv.reader(ifile)\n for line in reader:\n if line[1].strip(' \\r\\n') and (line[1].strip(' \\r\\n') not in self.finishedSet):\n self.url_list.put(tuple(line))\n # print(tuple(line))\n\n def run(self):\n self._read_data()\n while True:\n conn, addr = self.socket_main.accept()\n if self.comm.verify_worker(conn):\n t = clientHandler(conn, self.url_list, self.finished_set)\n t.start()\n self.threadPool.append(t)\n\n\nif __name__ == \"__main__\":\n findMyAdvisor = serverFindMyAdvisor(\"../Data/input.csv\", \"../Data/finishedUrl\")\n # findMyAdvisor.read_data()\n findMyAdvisor.run()\n","sub_path":"Bin/serverBin.py","file_name":"serverBin.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"157891761","text":"import os\nimport sys\nimport pygame\nimport config\nfrom sprites import Stone, Grass, Dune, Water, Road, Mud, Goal, Trail\n\n\nclass EndGame(Exception):\n pass\n\n\nclass Game:\n def __init__(self):\n self.path_cost = 0\n pygame.display.set_caption('PyTanja')\n values = Game.load_map(sys.argv[1] if len(sys.argv) > 1 else os.path.join(config.MAP_FOLDER, 'map0.txt'))\n self.char_map = values[0]\n self.start = values[1:3]\n self.goal = values[3:]\n # window scaling\n config.TILE_SIZE = min(config.MAX_HEIGHT // len(self.char_map), config.MAX_WIDTH // len(self.char_map[0]))\n config.HEIGHT = config.TILE_SIZE * len(self.char_map)\n config.WIDTH = config.TILE_SIZE * len(self.char_map[0])\n config.GAME_SPEED = int(config.TILE_SIZE * 2)\n pygame.font.init()\n config.GAME_FONT = pygame.font.Font(None, config.TILE_SIZE // 3)\n config.RIBBON_HEIGHT = int(config.GAME_FONT.size('')[1] * 1.5)\n self.screen = pygame.display.set_mode((config.WIDTH, config.HEIGHT + config.RIBBON_HEIGHT))\n self.tiles_sprites = pygame.sprite.Group()\n self.trails_sprites = pygame.sprite.Group()\n self.agents_sprites = pygame.sprite.Group()\n tile_map = []\n for i, row in enumerate(self.char_map):\n map_row = []\n for j, el in enumerate(row):\n if el == 's':\n t = Stone(i, j)\n elif el == 'w':\n t = Water(i, j)\n elif el == 'r':\n t = Road(i, j)\n elif el == 'g':\n t = Grass(i, j)\n elif el == 'm':\n t = Mud(i, j)\n elif el == 'd':\n t = Dune(i, j)\n else:\n t = Grass(i, j)\n self.tiles_sprites.add(t)\n map_row.append(t)\n tile_map.append(map_row)\n self.tile_map = tile_map\n self.tiles_sprites.add(Goal(self.goal[0], self.goal[1]))\n module = __import__('sprites')\n class_ = getattr(module, sys.argv[2] if len(sys.argv) > 2 else 'ExampleAgent')\n self.agent = class_(self.start[0], self.start[1],\n f'{sys.argv[2]}.png' if len(sys.argv) > 2 else 'ExampleAgent.png')\n self.agents_sprites.add(self.agent)\n self.clock = pygame.time.Clock()\n self.running = True\n self.playing = False\n self.game_over = False\n\n @staticmethod\n def load_map(map_name):\n try:\n with open(map_name, 'r') as f:\n ar, ac = [int(val) for val in f.readline().strip().split(',')]\n gr, gc = [int(val) for val in f.readline().strip().split(',')]\n matrix = []\n while True:\n line = f.readline().strip()\n if not len(line):\n break\n matrix.append([c for c in line])\n return matrix, ar, ac, gr, gc\n except Exception as e:\n raise e\n\n def check_move(self, old_x, old_y, x, y):\n if abs(old_x - x) + abs(old_y - y) != 1:\n raise Exception(f'ERR: Path nodes {old_x, old_y} and {x, y} are not adjacent!')\n if not (x in range(len(self.tile_map)) and y in range(len(self.tile_map[0]))):\n raise Exception(f'ERR: Agent {x, y} is out of bounds! '\n f'{len(self.tile_map), len(self.tile_map[0])}')\n\n def run(self):\n # game loop - set self.playing = False to end the game\n path = self.agent.get_agent_path(self.tile_map, self.goal)\n orig_path = [p for p in path]\n print(f\"Path: {', '.join([str(p.position()) for p in path])}\")\n print(f'Path length: {len(path)}')\n print(f'Path cost: {sum([t.cost() for t in path])}')\n tile = path.pop(0)\n x, y = tile.position()\n self.path_cost = tile.cost()\n step_count = 1\n game_time = 0\n while self.running:\n try:\n if self.playing:\n if not game_time:\n self.agent.place_to(x, y)\n self.trails_sprites.add(Trail(x, y, step_count))\n step_count += 1\n try:\n tile = path.pop(0)\n except IndexError:\n raise EndGame()\n old_x, old_y = x, y\n x, y = tile.position()\n self.check_move(old_x, old_y, x, y)\n self.path_cost += tile.cost()\n game_time += 1\n if game_time == config.TILE_SIZE:\n game_time = 0\n self.agent.move_towards(x, y)\n self.clock.tick(config.GAME_SPEED)\n self.events()\n self.draw()\n except EndGame:\n self.game_over = True\n self.playing = False\n if len(orig_path):\n self.path_cost = sum([t.cost() for t in orig_path])\n goal_x, goal_y = orig_path[-1].position()\n self.trails_sprites = pygame.sprite.Group()\n for num, tile in enumerate(orig_path):\n old_x, old_y = x, y\n x, y = tile.position()\n if num:\n self.check_move(old_x, old_y, x, y)\n self.trails_sprites.add(Trail(x, y, num + 1))\n self.agent.place_to(goal_x, goal_y)\n except Exception as e:\n self.game_over = True\n raise e\n\n def quit(self):\n self.running = False\n\n def draw(self):\n self.screen.fill(config.BLACK, rect=(0, config.HEIGHT, config.WIDTH, config.RIBBON_HEIGHT))\n self.tiles_sprites.draw(self.screen)\n self.trails_sprites.draw(self.screen)\n for t in self.trails_sprites:\n t.draw(self.screen)\n self.agents_sprites.draw(self.screen)\n cost = config.GAME_FONT.render(f'Score: {str(self.path_cost)}', True, config.GREEN)\n self.screen.blit(cost, (10, config.HEIGHT + config.RIBBON_HEIGHT // 5))\n if self.game_over:\n game_over = config.GAME_FONT.render('GAME OVER', True, config.RED)\n text_rect = game_over.get_rect(center=(config.WIDTH // 2, config.HEIGHT // 2))\n self.screen.blit(game_over, text_rect)\n pygame.display.flip()\n\n def events(self):\n # catch all events here\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n self.quit()\n if self.game_over:\n return\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\n self.playing = not self.playing\n elif event.type == pygame.KEYDOWN and event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):\n raise EndGame()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625035496","text":"from time import time\nfrom envs import envs\nimport oletools.oleid\nimport aioboto3\nimport asyncio\nimport boto3\n\n\nasync def main():\n async with aioboto3.resource('s3') as s3_resource:\n bucket = s3_resource.Bucket(name=envs.get(\"bucket_name\"))\n tasks = []\n async for obj in bucket.objects.all():\n task = asyncio.create_task(download_file(s3_resource, bucket, obj))\n tasks.append(task)\n \n await asyncio.gather(*tasks)\n\n\nasync def download_file(s3, bucket, obj):\n await s3.Object(bucket.name, obj.key).download_file(obj.key)\n parse_file(obj.key)\n\n\ndef parse_file(filename):\n oid = oletools.oleid.OleID(filename)\n\n print('============== checking file %s ====================' % filename)\n indicators = oid.check()\n print('Have found %d possible threats in the %s file' % (len(indicators), filename))\n for i in indicators:\n print('\\tIndicator id=%s name=\"%s\" type=%s value=%s' % (i.id, i.name, i.type, repr(i.value)))\n print('\\tdescription:', i.description)\n print('')\n\n print('====================================================')\n\n\nif __name__ == '__main__':\n t0 = time()\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n print(time() - t0)\n","sub_path":"init/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96795694","text":"import dataread\nimport numpy as np\nimport pygraphviz as pgv\nfrom copy import deepcopy\n\n###automata func\n\n#automata describe as matrix state transition\n#I: initial state in red, X: final state in grey, -1 is ne no transition state, state start at 1 in the \n\ndef generatestartautomata(nbtrantition):\n\tautomata=np.full((1,nbtrantition),-1)\n\treturn automata\n\n#in: all except clustall\n#out: generate all initial state of the automata\ndef generateinitialstate(automata,listofsequence,listoftransition,numberoftransition):\n\ti=0\n\tk=1 #transition created\n\tsetofinitial=set() #set of already done initial transition\n\twhile ival:\n\t\t\t\tautomata[i,j]-=1\n\t\t\tj+=1\n\t\tj=0\n\t\ti+=1\n\treturn automata\n\n#in: automata and two position two merge\n#out: the best val after merging the two state\ndef mergetwoval(automata,i1,i2,j):\n\ti1=np.float(i1)\n\ti2=np.float(i2)\n\t#print(i1,i2,automata[i1,j],automata[i2,j])\n\tif automata[i1,j]==-1 and automata[i2,j]==-1:\n\t\treturn -1\n\telif automata[i1,j]!=-1 and automata[i2,j]==-1:\n\t\treturn automata[i1,j]\n\telif automata[i1,j]==-1 and automata[i2,j]!=-1:\n\t\t#print(\"la\",i2,automata[i2,j],type(i2),type(automata[i2,j]))\n\t\tif automata[i2,j]==i2: #boucle en i2\n\t\t\treturn i1\n\t\telse:\n\t\t\treturn automata[i2,j]\n\telif automata[i1,j]!=-1 and automata[i2,j]!=-1:\n\t\tif automata[i1,j]==automata[i2,j]:\n\t\t\treturn automata[i2,j] #or i1\n\t\telif automata[i1,j]==i1 and automata[i2,j]==i2:\n\t\t\treturn i1\n\t\telse:\n\t\t\tprint(\"!!!ambiguite!!!\",automata[i1,j],automata[i2,j])\n\t\t\treturn np.minimum(automata[i1,j],automata[i2,j])\n\n#in: two state that have to be merge in the automata\n#out: the automata with that two state merge\ndef mergetwostate(automata,i1,i2,listoftransition,numberoftransition):\n\tj=0\n\twhile ji2 doit prendre moins 1\n\tautomata=givecoherenceaftermege(automata,i2)\n\treturn automata\n\n#in: automata and a seq\n#do: search in the automata how much of the seq is generate\n#out: isgenerate,stategenerate,statenotgenerate and line were automata stop\ndef isgenerate(automata,aseq,listoftransition):\n\t#print(\"debudage is generate\")\n\t#print(\"automate\",automata,\"seq\",aseq)\n\tgenerate=str()\n\tungenerate=str()\n\tnewindex=0\n\ti=1\n\tgenerate+=aseq[0] #first state is sure generate\n\t#print(generate,newindex,listoftransition.index(aseq[0]),aseq[0])\n\tindex=-2 #the old newindex.\n\tnewindex=automata[0,listoftransition.index(aseq[0])]\n\twhile i1:\n\t\tif aseq[0]==aseq[1]:\n\t\t\treturn True\n\treturn False\n\ndef isnextisaloop(aseq):\n\tif len(aseq)>2:\n\t\tif aseq[1]==aseq[2]:\n\t\t\treturn True\n\treturn False\n\n#in: all, clustal ali\n#out: automata with identified loop, clustal ali private from used ali, dictofpositionwhereloopisfind,dictofpositioninclustalwherethatloopisfind\ndef generateloop(automata,clustalalilist,listoftransition,numberoftransition):\n\t#generation of temporary clean copy\n\ti=0\n\tj=0\n\tk=list()\n\tl=0\n\tLi=len(clustalalilist) #number of seq\n\tLj=len(clustalalilist[0]) #len of one seq\n\tdposition=dict()\n\tdindex=dict()\n\t#!! parcours j puis i car col vers ligne\n\t#trouver les boucles potentiels\n\twhile j<(Lj-1):\n\t\twhile i0: #ajout des boucles trouver a la position j\n\t\t\t##! dont mean that the algo is in N3 complexity\n\t\t\twhile l2 len list\n\t\t\t\tdposition[i].__delitem__(j)\n\t\t\t\tdindex[i].__delitem__(j)\n\t#ajouter les boucles\n\tk=automata.shape[0] #nb de ligne dans l'automate\n\tlistposautomata=list() #list of loop position in the automata to connect #will be converted intonumpy array before return\n\tfor i in listoftransition:\n\t\tif dposition.__contains__(i):\n\t\t\tfor j in dposition[i]: #nombre de loop pour une transition\n\t\t\t\tnewrow=np.full((1,numberoftransition),-1)\n\t\t\t\tautomata=np.concatenate((automata,newrow))\n\t\t\t\tlistposautomata.append([i,k])\n\t\t\t\tautomata[k,listoftransition.index(i)]=k\n\t\t\t\tk+=1\n\treturn automata,dposition,dindex,np.array(listposautomata)\n\n\n#in: a seq, a pos where to stop\n#count the number of ungap in the seq\n#out: len(list),list of ungap\ndef numberofelementbeforeloop(aseq,pos):\n\ti=0\n\tlistofungap=list()\n\tnumberofungap=0\n\twhile i0:\n\t\t\t\t#print(automata[linestop,],j)\n\t\t\t\t\tautomata[linestop,j[0][0]]=-2\n\t\ti+=1\n\treturn automata\n###end automata func\n\n####graphic func\n\n#in: automata ; (nb state, nbtransition)\n#out: a graph in networkx format\ndef exportautomateasgraph(automate,final,transitionlistsorted,nameout):\n\tsize=automate.shape\n\tgraph=pgv.AGraph(directed=True)\n\tgraph.add_node(0,color=\"red\") #initial state\n\tlistendstate=np.where(automate==-2)\n\tif final:\n\t\t#print(listendstate)\n\t\tfor i in listendstate:\n\t\t\t#print(i[0])\n\t\t\tgraph.add_node(i[0],color=\"grey\")#final state\n\ti=0\n\tj=0\n\twhile i a+b:\n aa /= 2\n return a+b\n\n\nif __name__ == \"__main__\":\n core_nb = multiprocessing.cpu_count()\n p = Pool(processes=int(core_nb))\n\n nums = [1, 2, 3, 4,5,6,7,8,9,10]\n second_arg = 0\n\n result = p.starmap(calcNum, zip(nums, repeat(second_arg), repeat(3)))\n p.close()\n p.join()\n\n print(result)\n","sub_path":"multiprocessingTest.py","file_name":"multiprocessingTest.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"162908513","text":"from pymongo import MongoClient\n\n#Realiza a conexão\nconn = MongoClient('localhost', 27017)\n\n#Cria um banco de dados\n# ****** É apenas uma definição,\n# a criação é feita ao inserir o primeiro dado\ndb = conn.cadastrodb\n\n#Similar a uma tabela em SQL\ncolletiction = db.cadastrodb\n\n########\n\nimport datetime\n\n#cria um documento, um dicionário\npost1 = {\"codigo\": \"ID-99887725\",\n \"prod_name\":\"Geladeira\",\n \"marcas\":[\"brastemp\", \"consul\", \"electrolux\"],\n \"data_cadastro\":datetime.datetime.utcnow()}\n\n#Inserir na colletion\ncolletiction = db.posts\n\n#Inserção, insert_one\npost_id = colletiction.insert_one(post1)\n\nprint(post_id.inserted_id)\n\n#Dicionário 2, segundo documento; Registro\npost2 = {\"codigo\": \"ID-882233\",\n \"prod_name\": \"Televisor\",\n \"marcas\": [\"LG\", \"Samsung\", \"TCL\"],\n \"data_cadastro\": datetime.datetime.utcnow()}\n\ncolletiction = db.posts\n\npost_id = colletiction.insert_one(post2).inserted_id\n\nprint(post_id)\n\na = colletiction.find_one({\"prod_name\": \"Televisor\"})\n\nprint(a)\n\nfor post in colletiction.find():\n print(post)\n\nprint(db.name)\n\nprint(db.collection_names())","sub_path":"Exercicios/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"263018710","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'warning'\n\nurlpatterns = [\n # 预警列表首页\n url(r'index/.*?', views.index, name='index'),\n # 获取预警Json数据\n url(r'getWarningListJson/', views.getWarningListJson, name='getWarningListJson'),\n # 查看预警管理详情\n url(r'form/.*$', views.form, name='form'),\n # 保存预警已解决处理路由\n url(r'solveWarning', views.solveWarning, name='solveWarning'),\n # 每200毫秒请求一次预警路由信息 获取预警数量\n url(r'warning_numbers', views.warning_numbers, name='warning_numbers'),\n\n\n]\n","sub_path":"warning/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"12644615","text":"def sum_of_prev_numbers(list, number):\r\n for i in list:\r\n for j in list:\r\n if i + j == number and i != j:\r\n return True\r\n return False\r\n\r\nfile = open(\"9\", \"r\")\r\ncontent = file.read()\r\nfile.close()\r\n\r\nnumbers = [int(i) for i in content.split(\"\\n\")]\r\np_len = 25\r\nrun = True\r\nfirst_idx = 0\r\n\r\nwhile run:\r\n preamble = numbers[first_idx: first_idx + p_len]\r\n number = numbers[first_idx + p_len]\r\n if sum_of_prev_numbers(preamble, number):\r\n first_idx += 1\r\n else:\r\n run = False\r\n\r\nprint(numbers[first_idx + p_len])","sub_path":"AOC/9-1.py","file_name":"9-1.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"70771838","text":"import pyparsing as pp\n\n\nLPAR, RPAR = map(pp.Suppress, '()')\ncolumn = pp.Word(pp.alphas, pp.alphanums+\"_\")('column')\nfunction = (\n pp.CaselessKeyword('COUNT')\n)('function')\nalias = column.copy()\nalias_expr = pp.Suppress(pp.CaselessKeyword('AS')) + alias('alias')\n\nfunction_call = function('function') + LPAR + pp.delimitedList(column)('arguments') + RPAR\n\nexpr = pp.Forward()('expr')\nexpr <<= (\n function_call('function_call') | column('column')\n)\n\nfull_expr = pp.Group(expr)('expr') + pp.Optional(alias_expr)\n\nexprs = pp.delimitedList(pp.Group(full_expr('full_expr')))\n\nSOURCES = pp.oneOf('entries tags events')\n\nsource = pp.Suppress(pp.CaselessKeyword('FROM')) + SOURCES('source')\n\nquery = (\n pp.CaselessKeyword('SELECT')('statement') +\n exprs('exprs') +\n source\n)\n","sub_path":"tempo/query/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"239646227","text":"# clean.py\n# -------\n# Writes new CSVs that only have mutually shared tickers and are sorted by date\nimport pandas as pd\nimport databases as d\n\n# setup databases to read in from\ncompustat = d.PandasDatabase(\"compustat_full_month.csv\")\ncrsp = d.PandasDatabase(\"crsp_full_month.csv\")\ncog_c = d.PandasDatabase(\"cognism_current.csv\")\ncog_j = d.PandasDatabase(\"cognism_join.csv\")\ncog_l = d.PandasDatabase(\"cognism_leave.csv\")\n# Find shared firms between databases\ncompustat.recordTickers(\"tic\", False)\ncrsp.recordTickers(\"TICKER\", False)\ncog_c.recordTickers(\"Symbol\", False)\ncog_j.recordTickers(\"Symbol\", False)\ncog_l.recordTickers(\"Symbol\", False)\nsharedTics = list(set(compustat.tics) & set(crsp.tics) & set(cog_c.tics) & set(cog_j.tics) & set(cog_l.tics))\n\n\ndef keep_shared(file_name, new_name, shared_tics, tic_col_num, row_size):\n g = open(new_name, \"w+\")\n with open(file_name) as f:\n skip = True\n for line in f:\n if skip:\n g.write(line)\n skip = False\n continue\n current = line.rstrip('\\n').split(',')\n if (current[tic_col_num] in shared_tics) and len(current) == row_size:\n empty_check = False\n for v in current:\n if not v:\n empty_check = True\n break\n if not empty_check:\n g.write(line)\n g.close()\n\n\ndef sort_by_date(file_name, new_name, date_col_name):\n df = pd.read_csv(file_name)\n df.sort_values(by=[date_col_name], inplace=True)\n df.to_csv(new_name, index=False)\n\n\nkeep_shared(\"compustat_full_month.csv\", \"reduced_compustat_full_month.csv\", sharedTics, 4, 8)\nsort_by_date(\"reduced_compustat_full_month.csv\", \"reduced_compustat_full_month.csv\", \"rdq\")\nkeep_shared(\"crsp_full_month.csv\", \"reduced_crsp_full_month.csv\", sharedTics, 2, 8)\nsort_by_date(\"reduced_crsp_full_month.csv\", \"reduced_crsp_full_month.csv\", \"date\")\nkeep_shared(\"cognism_current.csv\", \"reduced_cognism_current.csv\", sharedTics, 0, 59)\nsort_by_date(\"reduced_cognism_current.csv\", \"reduced_cognism_current.csv\", \"YearMonth\")\nkeep_shared(\"cognism_join.csv\", \"reduced_cognism_join.csv\", sharedTics, 0, 59)\nsort_by_date(\"reduced_cognism_join.csv\", \"reduced_cognism_join.csv\", \"YearMonth\")\nkeep_shared(\"cognism_leave.csv\", \"reduced_cognism_leave.csv\", sharedTics, 0, 59)\nsort_by_date(\"reduced_cognism_leave.csv\", \"reduced_cognism_leave.csv\", \"YearMonth\")\n","sub_path":"skills/human-capital/deprecated/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"399176744","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nclass YsaleOrder(models.Model):\n _name = 'ysale.order'\n _description = 'Sale Order'\n\n name = fields.Char(string='订单号')\n order_line_ids = fields.One2many('ysale.order.line', 'order_id', string='订单明细', copy=True)\n pay_ids = fields.One2many('ysale.pay', 'order_id', string=\"付款明细\")\n amount_total = fields.Float(string='总计金额', store=True, readonly=True, compute='_amount_all', track_visibility='always')\n\n @api.one\n @api.depends('order_line_ids.subtotal')\n def _amount_all(self):\n \tfor order in self:\n\t \tfor line in self.order_line_ids:\n\t \t\torder.amount_total += line.subtotal\n\nclass YsaleOrderLine(models.Model):\n\t_name = 'ysale.order.line'\n\t_description = 'Sale Order Line'\n\n\torder_id = fields.Many2one('ysale.order', string='订单号', required=True, ondelete='cascade', index=True)\n\tname = fields.Char(string='备注')\n\tquantity = fields.Float(string='数量')\n\tprice_unit = fields.Float(string='单价')\n\tshipping_price = fields.Float(string='运费')\n\tproduct_id = fields.Many2one('yproduct.product', string='产品', index=True)\n\tsubtotal = fields.Float(string='金额', store=True, readonly=True, compute='_compute_amount')\n\n\t@api.multi\n\t@api.depends('quantity', 'price_unit')\n\tdef _compute_amount(self):\n\t\t\"\"\"\n\t\t计算订单行金额\n\t\t\"\"\"\n\t\tfor line in self:\n\t\t\tline.subtotal = line.quantity * line.price_unit\n\n\n\n\nclass YproductProdct(models.Model):\n\t_name = 'yproduct.product'\n\t_description = 'Yprodct Product'\n\n\tname = fields.Char('名称')\n\tsku = fields.Char('Sku')\n\n\nclass YsalePay(models.Model):\n\t_name = 'ysale.pay'\n\t_description = 'Ysale Pay'\n\n\tname = fields.Char('内容')\n\torder_id = fields.Many2one('ysale.order', string='订单号')\n\tproduct_id = fields.Many2one('yproduct.product', string='产品')\n\torder_type = fields.Selection([\n\t\t('order', '订单付款'),\n\t\t('service', '服务费'),\n\t\t('orther', '其他'),\n\t\t('oback','退款'),\n\t\t], string='交易类型', index=True)\n\tmoney = fields.Float('金额')\n","sub_path":"ysale/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"40719947","text":"import pygame, sys, time\r\nfrom constants import *\r\nfrom random import *\r\nfrom math import *\r\nfrom pygame.locals import *\r\n\r\nboard = 4\r\npoints = 0\r\nscore = 2\r\nr = [2, 4]\r\npygame.init()\r\npygame.mixer.init()\r\npygame.mixer.music.load(\"bensound-hipjazz.mp3\")\r\npygame.mixer.music.play(-1, 0.0)\r\ndisplay = pygame.display.set_mode((400, 500), 0, 32)\r\npygame.display.set_caption(\"2048\")\r\nmyfont = pygame.font.SysFont(\"monospace\", 40)\r\nendfont = pygame.font.SysFont(\"monospace\",20)\r\nscorefont = pygame.font.SysFont(\"monospace\", 30)\r\nmatrix = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\r\nundomat = []\r\n\r\ndef main(loaded=False):\r\n if not loaded:\r\n placerandom()\r\n placerandom()\r\n printmatrix()\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n close()\r\n\r\n if check() == True:\r\n if event.type == KEYDOWN:\r\n if arrow(event.key):\r\n rotations = getrotations(event.key)\r\n addtoundo()\r\n for i in range(0, rotations):\r\n rotateclockwise()\r\n\r\n if canmove():\r\n movetiles()\r\n mergetiles()\r\n placerandom()\r\n\r\n for j in range(0, (4 - rotations) % 4):\r\n rotateclockwise()\r\n printmatrix()\r\n else:\r\n gameover()\r\n if event.type == KEYDOWN:\r\n global board\r\n if event.key == pygame.K_r:\r\n reset()\r\n if 50 < event.key and 56 > event.key:\r\n board = i.key - 48\r\n reset()\r\n if event.key == pygame.K_s:\r\n\r\n savegame()\r\n elif event.key == pygame.K_l:\r\n loadgame()\r\n\r\n elif event.key == pygame.K_u:\r\n undo()\r\n elif event.key == pygame.K_q:\r\n close()\r\n elif event.key == pygame.K_h:\r\n highscore()\r\n pygame.display.update()\r\n\r\n\r\ndef canmove():\r\n for i in range(0, board):\r\n for j in range(1, board):\r\n if (matrix[i][j - 1] == 0 and matrix[i][j] > 0):\r\n return True\r\n elif (matrix[i][j - 1] == matrix[i][j]) and matrix[i][j - 1] != 0:\r\n return True\r\n return False\r\n\r\n\r\ndef movetiles():\r\n for i in range(0, board):\r\n for j in range(0, board - 1):\r\n while (matrix[i][j] == 0 and sum(matrix[i][j:]) > 0):\r\n for k in range(j, board - 1):\r\n matrix[i][k] = matrix[i][k + 1]\r\n matrix[i][board - 1] = 0\r\n\r\n\r\ndef mergetiles():\r\n global points\r\n for i in range(0, board):\r\n for j in range(0, board - 1):\r\n if matrix[i][j] == matrix[i][j + 1] and matrix[i][j] != 0:\r\n matrix[i][j] = matrix[i][j] * 2\r\n matrix[i][j + 1] = 0\r\n points += matrix[i][j]\r\n movetiles()\r\n\r\n\r\ndef placerandom():\r\n c = 0\r\n for i in range(0, board):\r\n for j in range(0, board):\r\n if matrix[i][j] == 0:\r\n c += 1\r\n k = floor(random() * board * board)\r\n while (matrix[floor(k / board)][k % board] != 0):\r\n k = floor(random() * board * board)\r\n matrix[floor(k / board)][k % board] = choice(r)\r\n\r\n\r\ndef printmatrix():\r\n display.fill(BLACK)\r\n global points\r\n global board\r\n for i in range(0, board):\r\n for j in range(0, board):\r\n pygame.draw.rect(display, getColor(matrix[i][j]),\r\n (i * (400 / board), j * (400 / board) + 100, 400 / board, 400 / board))\r\n label = myfont.render(str(matrix[i][j]), 1, (255, 255, 255))\r\n label2 = scorefont.render(\"YourScore:\" + str(points), 1, (255, 255, 255))\r\n display.blit(label, (i * (400 / board) + 30, j * (400 / board) + 130))\r\n display.blit(label2, (10, 20))\r\n\r\n\r\ndef check():\r\n for i in range(0, board ** 2):\r\n if matrix[floor(i / board)][i % board] == 0:\r\n return True\r\n for i in range(0, board):\r\n for j in range(0, board - 1):\r\n if matrix[i][j] == matrix[i][j + 1]:\r\n return True\r\n elif matrix[j][i] == matrix[j + 1][i]:\r\n return True\r\n return False\r\n\r\n\r\ndef convert():\r\n mat = []\r\n for i in range(0, board ** 2):\r\n mat.append(matrix[floor(i / board)][i % board])\r\n mat.append(points)\r\n return mat\r\n\r\n\r\ndef addtoundo():\r\n undomat.append(convert())\r\n\r\n\r\ndef rotateclockwise():\r\n for i in range(0, int(board / 2)):\r\n for j in range(i, int(board - i - 1)):\r\n temp1 = matrix[i][j]\r\n temp2 = matrix[board - 1 - j][i]\r\n temp3 = matrix[board - 1 - i][board - 1 - j]\r\n temp4 = matrix[j][board - 1 - i]\r\n\r\n matrix[board - 1 - j][i] = temp1\r\n matrix[board - 1 - i][board - 1 - j] = temp2\r\n matrix[j][board - 1 - i] = temp3\r\n matrix[i][j] = temp4\r\n\r\n\r\ndef gameover():\r\n pygame.mixer.music.stop()\r\n pygame.mixer.music.load(\"15 - 1-Down.mp3\")\r\n pygame.mixer.music.play(0, 0.0)\r\n pygame.mixer.music.stop()\r\n global points\r\n display.fill(BLACK)\r\n label = scorefont.render(\"Game Over\", 1, (255, 255, 255))\r\n label2 = scorefont.render(\"Score : \" + str(points), 1, (255, 255, 255))\r\n label3 = endfont.render(\"Press R to Play Again \", 1, (255, 255, 255))\r\n label4 = endfont.render(\"Press H to view Scores \", 1, (255, 255, 255))\r\n label5 = endfont.render(\"Press Q to Quit \", 1, (255, 255, 255))\r\n display.blit(label, (50, 50))\r\n display.blit(label2, (50, 100))\r\n display.blit(label3 , (50, 200))\r\n display.blit(label4, (50, 300))\r\n display.blit(label5, (50, 400))\r\n\r\ndef reset():\r\n global points\r\n global matrix\r\n points = 0\r\n display.fill(BLACK)\r\n for i in range(0, board):\r\n for j in range(0, board):\r\n matrix[i][j] = 0\r\n main()\r\n\r\n\r\ndef savegame():\r\n f = open(\"savedata\", \"w\")\r\n\r\n line1 = \" \".join([str(matrix[floor(x / board)][x % board]) for x in range(0, board ** 2)])\r\n f.write(line1 + \"\\n\")\r\n f.write(str(board) + \"\\n\")\r\n f.write(str(board))\r\n f.close()\r\n\r\n\r\ndef undo():\r\n if len(undomat) > 0:\r\n mat = undomat.pop()\r\n\r\n for i in range(0, board ** 2):\r\n matrix[floor(i / board)][i % board] = mat[i]\r\n global points\r\n points = mat[board ** 2]\r\n\r\n printmatrix()\r\n\r\n\r\ndef loadgame():\r\n global points\r\n global board\r\n global matrix\r\n\r\n f = open(\"savedata\", \"r\")\r\n\r\n mat = (f.readline()).split(' ', board ** 2)\r\n board = int(f.readline())\r\n points = int(f.readline())\r\n\r\n for i in range(0, board ** 2):\r\n matrix[floor(i / board)][i % board] = int(mat[i])\r\n\r\n f.close()\r\n\r\n main(True)\r\n\r\n\r\ndef arrow(k):\r\n return (k == pygame.K_UP or k == pygame.K_DOWN or k == pygame.K_LEFT or k == pygame.K_RIGHT)\r\n\r\n\r\ndef getrotations(k):\r\n if k == pygame.K_UP:\r\n return 0\r\n elif k == pygame.K_DOWN:\r\n return 2\r\n elif k == pygame.K_LEFT:\r\n return 1\r\n elif k == pygame.K_RIGHT:\r\n return 3\r\ndef close():\r\n global points\r\n from store import saving\r\n from record import fn,ln,age\r\n #print(fn,ln,age)\r\n saving(fn, ln, age, points)\r\n pygame.quit()\r\n sys.exit()\r\n\r\ndef highscore():\r\n from highscores import high\r\n high()","sub_path":"maingame.py","file_name":"maingame.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"332781468","text":"import random\n\n\ndef sorteia_carta(baralho_jogo, cartas_jogador, lista_numero_baralhos):\n # sorteia uma carta da lista de cartas do baralho do jogo\n carta = random.choice(list(baralho_jogo.keys()))\n # guarda esta carta na mesma lista que é dada como argumento para a função\n cartas_jogador.append(carta)\n # guarda o índice da carta sorteada no dicionário baralho_jogo\n indice_carta_sorteada = list(baralho_consulta.keys()).index(carta)\n # subtrai uma carta do índice da lista que representa o número de cartas\n lista_numero_baralhos[indice_carta_sorteada] = lista_numero_baralhos[indice_carta_sorteada] - 1\n # se a subtração for 0, significa que o número de cartas daquele naipe sorteado se esgotou, será deletado para não ser sorteado\n if (lista_numero_baralhos[indice_carta_sorteada] == 0):\n # a lógica utilizada para os múltiplos baralhos controla quantas vezes podemos sortear uma carta igual. Quando esgotamos o número de cartas do naipe específico que definimos, este naipe não será mais sorteado\n del baralho_jogo[carta]\n\n return cartas_jogador\n\n\ndef calcula_pontuacao(cartas_jogador):\n lista_pontos = [] # cria uma lista auxiliar para armazenar o valor de cada naipe\n\n for carta in cartas_jogador:\n lista_pontos.append(baralho_consulta[carta])\n pontos_jogada = sum(lista_pontos)\n\n if (pontos_jogada > 21):\n n_ases = 0\n for carta in cartas_jogador:\n if(carta == \"A♦\" or carta == \"A♣\" or carta == \"A♥\" or carta == \"A♠\"):\n n_ases = n_ases + 1\n\n pontos_jogada = pontos_jogada - (10 * n_ases)\n\n return pontos_jogada\n\n\ndef verifica_pontuacao_jogador(pontos):\n if (pontos == 21):\n return \"G\"\n elif (pontos < 21):\n return \"C\"\n elif (pontos > 21):\n return \"P\"\n\n\ndef verifica_pontuacao_croupier(pontos):\n if (pontos == 21):\n return \"CG\" # Croupier Ganhou\n elif (pontos < 21):\n return \"CC\" # Checa Cartas\n elif (pontos > 21):\n return \"TG\" # Todos ganham\n\n\nbaralho_jogo = {\n # dicionário onde as cartas vao sumindo\n \"A♦\": 11, \"2♦\": 2, \"3♦\": 3, \"4♦\": 4, \"5♦\": 5, \"6♦\": 6, \"7♦\": 7, \"8♦\": 8, \"9♦\": 9, \"10♦\": 10, \"J♦\": 10, \"Q♦\": 10, \"K♦\": 10,\n \"A♣\": 11, \"2♣\": 2, \"3♣\": 3, \"4♣\": 4, \"5♣\": 5, \"6♣\": 6, \"7♣\": 7, \"8♣\": 8, \"9♣\": 9, \"10♣\": 10, \"J♣\": 10, \"Q♣\": 10, \"K♣\": 10,\n \"A♥\": 11, \"2♥\": 2, \"3♥\": 3, \"4♥\": 4, \"5♥\": 5, \"6♥\": 6, \"7♥\": 7, \"8♥\": 8, \"9♥\": 9, \"10♥\": 10, \"J♥\": 10, \"Q♥\": 10, \"K♥\": 10,\n \"A♠\": 11, \"2♠\": 2, \"3♠\": 3, \"4♠\": 4, \"5♠\": 5, \"6♠\": 6, \"7♠\": 7, \"8♠\": 8, \"9♠\": 9, \"10♠\": 10, \"J♠\": 10, \"Q♠\": 10, \"K♠\": 10,\n}\n\nbaralho_consulta = {\n # dicionário onde consulto o valor das cartas\n \"A♦\": 11, \"2♦\": 2, \"3♦\": 3, \"4♦\": 4, \"5♦\": 5, \"6♦\": 6, \"7♦\": 7, \"8♦\": 8, \"9♦\": 9, \"10♦\": 10, \"J♦\": 10, \"Q♦\": 10, \"K♦\": 10,\n \"A♣\": 11, \"2♣\": 2, \"3♣\": 3, \"4♣\": 4, \"5♣\": 5, \"6♣\": 6, \"7♣\": 7, \"8♣\": 8, \"9♣\": 9, \"10♣\": 10, \"J♣\": 10, \"Q♣\": 10, \"K♣\": 10,\n \"A♥\": 11, \"2♥\": 2, \"3♥\": 3, \"4♥\": 4, \"5♥\": 5, \"6♥\": 6, \"7♥\": 7, \"8♥\": 8, \"9♥\": 9, \"10♥\": 10, \"J♥\": 10, \"Q♥\": 10, \"K♥\": 10,\n \"A♠\": 11, \"2♠\": 2, \"3♠\": 3, \"4♠\": 4, \"5♠\": 5, \"6♠\": 6, \"7♠\": 7, \"8♠\": 8, \"9♠\": 9, \"10♠\": 10, \"J♠\": 10, \"Q♠\": 10, \"K♠\": 10,\n}\n\nlista_numero_baralhos = [1]*52\n\nnome_jogadores = []\ncarteiras = []\n\n######################### DEFINE NÚMERO DE JOGADORES, SEUS NOMES E SUAS APOSTAS ###################################\n# Pergunta a quantidade de jogadores na partida\nn_jogadores = int(input(\"\\nQual o número de jogadores? \"))\n\nn_baralhos = 10 # força um valor maior que 8 para que a pergunta seja feita ao menos uma vez\nwhile (n_baralhos > 8):\n # Pergunta a quantidade de jogadores na partida\n n_baralhos = int(input(\"\\nQual o número de baralhos? [Entre 2 e 8] \"))\n if (n_baralhos > 8):\n print(\"Insira um número válido de baralhos! [Entre 2 e 8] \")\n\ni = 0\nwhile i < len(lista_numero_baralhos):\n lista_numero_baralhos[i] = lista_numero_baralhos[i] * \\\n n_baralhos # define a quantidade de baralhos no jogo\n i = i + 1\n\nprint(\"\\n\")\n\ni = 0\nwhile (i < n_jogadores): # Pede o nome de cada jogador\n carteiras.append(1000)\n nome_jogador = input(\"Insira o nome do jogador {0}: \".format(i + 1))\n nome_jogadores.append(nome_jogador)\n i = i + 1\n\nprint(\"\\n\")\n\ngame = True\n\n######################### JOGO INICIADO: loop principal #######################\n\nwhile game == True:\n # reset nas listas de variaveis na rodada atual\n cartas_jogadores = []\n cartas_croupier = []\n lista_apostas = []\n pontuacao_jogadores = []\n\n i = 0\n while (i < n_jogadores): # Pede a aposta de cada jogador\n valor_aposta = input(\n \"{0}, informe o valor de sua aposta em R$: \".format(nome_jogadores[i]))\n # verifica se a aposta é negativa ou se é maior que a carteira\n # se o jogador escreve \"fim\" na aposta, este sai da partida\n if(valor_aposta == \"fim\" or carteiras[i] == 0):\n print(\"O jogador {0} saiu do jogo.\".format(nome_jogadores[i]))\n del nome_jogadores[i]\n n_jogadores = n_jogadores - 1\n #i = i + 1\n # verifica se a aposta é um valor negativo ou se o jogador tem saldo suficiente\n elif (int(valor_aposta) < 0 or int(valor_aposta) > carteiras[i]):\n print(\"Valor inválido para a aposta!\")\n else:\n valor_aposta = int(valor_aposta)\n lista_apostas.append(int(valor_aposta))\n # retira o valor da aposta da carteira do jogaador\n carteiras[i] = carteiras[i] - valor_aposta\n i = i + 1\n\n print(\"\\nJogadores: \", nome_jogadores)\n print(\"Apostas: \", lista_apostas)\n print(\"Carteiras\", carteiras, \"\\n\")\n\n ######################### RODADA INICIAL: Duas cartas para cada jogador, já verificando vitória #######################\n\n fim_jogo = False\n i = 0\n while i < n_jogadores: # sorteio de 2 cartas iniciais para cada jogador\n cartas_jogador = []\n cartas_jogador = sorteia_carta(\n baralho_jogo, cartas_jogador, lista_numero_baralhos)\n cartas_jogador = sorteia_carta(\n baralho_jogo, cartas_jogador, lista_numero_baralhos)\n cartas_jogadores.append(cartas_jogador)\n pontuacao_jogadores.append(calcula_pontuacao(cartas_jogador))\n\n # Verifica se hove blackjack na primeira rodada\n if(verifica_pontuacao_jogador(pontuacao_jogadores[i]) == \"G\"):\n valor_ganho = lista_apostas[i]*1.5\n print(\"Blackjack! {0} ganhou R${1}\".format(\n nome_jogadores[i], valor_ganho))\n fim_jogo = True\n\n i = i + 1\n\n # sorteia as cartas do croupier\n cartas_croupier = sorteia_carta(\n baralho_jogo, cartas_croupier, lista_numero_baralhos)\n cartas_croupier = sorteia_carta(\n baralho_jogo, cartas_croupier, lista_numero_baralhos)\n pontuacao_croupier = calcula_pontuacao(cartas_croupier)\n print(\"Cartas croupier:\", cartas_croupier)\n print(\"Cartas jogadores: \", cartas_jogadores)\n print(\"Pontuação dos jogadores: \", pontuacao_jogadores)\n\n if(pontuacao_croupier == 21): # verifica se o croupier fez 21\n print(\"A casa ganhou! O croupier fez blackjack!\")\n fim_jogo = True\n\n ########################### RODADA: Tira uma carta para cada jogador até este passar ou estourar #############################\n i = 0\n while (i < n_jogadores and fim_jogo == False):\n\n rodada = verifica_pontuacao_jogador(pontuacao_jogadores[i])\n while (rodada == \"C\"): # Loop da rodada\n\n continuar = input(\n \"\\nMais uma, {0}? [S/N]\".format(nome_jogadores[i])).upper()\n\n if (continuar == \"S\"):\n cartas_jogador = [] # lista auxiliar que armazena uma carta sorteada\n # Sorteia uma carta e a armazena na lista criada anteriormente\n cartas_jogador = sorteia_carta(\n baralho_jogo, cartas_jogador, lista_numero_baralhos)\n # Adiciona o primeiro valor da lista criada a lista de cartas do jogador atual\n cartas_jogadores[i].append(cartas_jogador[0])\n print(\"Cartas jogadores: \", cartas_jogadores)\n #print(\"Cartas croupier: \", cartas_croupier)\n # calcula a pontuacao do jogador de acordo com a lista de suas cartas atualizada e atualiza a pontuacao do jogador atual\n pontuacao_jogadores[i] = calcula_pontuacao(cartas_jogadores[i])\n print(\"Pontuação jogadores: \", pontuacao_jogadores)\n # atualiza a instrução para o while da rodada\n rodada = verifica_pontuacao_jogador(pontuacao_jogadores[i])\n\n elif (continuar == \"N\"):\n rodada = \"X\" # letra genérica, para sair da rodada\n else:\n print(\"Comando inválido!\")\n\n if (verifica_pontuacao_jogador(pontuacao_jogadores[i]) == \"G\"):\n valor_ganho = lista_apostas[i] * 1.5\n print(\"Blackjack! {0} ganhou R${1}\".format(\n nome_jogadores[i], valor_ganho))\n print(\"Fim de jogo\")\n fim_jogo = True\n\n elif(verifica_pontuacao_jogador(pontuacao_jogadores[i]) == \"P\"):\n print(\"{0} perdeu!\".format(nome_jogadores[i]))\n\n i = i + 1\n ################################################# CROUPIER ################################################\n i = 0 # verifica se todo mundo perdeu ou saiu\n contador = 0\n todos_perderam = False\n while i < n_jogadores:\n if(pontuacao_jogadores[i] > 21):\n contador = contador + 1\n i = i + 1\n if(contador == n_jogadores):\n todos_perderam = True\n fim_jogo = True\n print(\"Todos perderam e a casa ganhou!\")\n\n if(n_jogadores == 0):\n fim_jogo = True\n print(\"Todos saíram do jogo!\")\n\n if (fim_jogo == False): # Verifica se houve blackjack\n\n if(todos_perderam == False): # O croupier joga\n print(\"Cartas croupier:\", cartas_croupier)\n print(\"Pontuação croupier: \", pontuacao_croupier)\n\n # se a pontuacao do croupier já for maior que 17, as cartas serão verificadas para ver quem ganhou\n if(pontuacao_croupier >= 17):\n maior_pontuacao = pontuacao_croupier\n i_nome = -1\n i = 0\n while i < n_jogadores:\n if(pontuacao_jogadores[i] > maior_pontuacao):\n maior_pontuacao = pontuacao_jogadores[i]\n i_nome = i\n i = i + 1\n # O jogador com a maior pontuação recebe o dobro que apostou\n valor_ganho = lista_apostas[i_nome]*2\n carteiras[i] = carteiras[i] + valor_ganho\n print(\"O jogador {0} ganhou R${1}!\".format(\n nome_jogadores[i_nome], valor_ganho))\n\n while(pontuacao_croupier < 17): # o croupier irá comprar cartas até ter 17 ou mais pontos\n cartas_croupier = sorteia_carta(\n baralho_jogo, cartas_croupier, lista_numero_baralhos)\n pontuacao_croupier = calcula_pontuacao(cartas_croupier)\n print(\"Cartas croupier: \", cartas_croupier)\n print(\"Pontuação croupier:\", pontuacao_croupier)\n\n if(verifica_pontuacao_croupier(pontuacao_croupier) == \"CG\"): # verifica se o croupier fez 21\n print(\"Cartas croupier: \", cartas_croupier)\n print(\"Pontuação croupier:\", pontuacao_croupier)\n print(\"A casa ganhou!\")\n\n # verifica se o croupier fez mais pontos\n elif(verifica_pontuacao_croupier(pontuacao_croupier) == \"CC\"):\n maior_pontuacao = pontuacao_croupier\n i = 0\n while i < n_jogadores:\n if(pontuacao_jogadores[i] > maior_pontuacao and pontuacao_jogadores[i] < 21 and pontuacao_jogadores[i] != pontuacao_croupier):\n maior_pontuacao = pontuacao_jogadores[i]\n i_nome = i\n elif(pontuacao_jogadores[i] == pontuacao_croupier):\n print(\n \"Empate! Os jogadores que ainda estão no jogo não perdem nada!\")\n i = i + 1\n # O jogador com a maior pontuação recebe o dobro que apostou\n valor_ganho = lista_apostas[i_nome] * 2\n carteiras[i] = carteiras[i] + valor_ganho\n print(\"O jogador {0} ganhou R${1}!\".format(\n nome_jogadores[i_nome], valor_ganho))\n\n elif(verifica_pontuacao_croupier(pontuacao_croupier) == \"TG\"):\n i = 0\n while i < n_jogadores:\n if(pontuacao_jogadores[i] < 21):\n valor_ganho = lista_apostas[i_nome]*2\n carteiras[i] = carteiras[i] + valor_ganho\n print(\"Parabéns! {0} ganhou R${1}!\".format(\n nome_jogadores[i], lista_apostas[i] * 2))\n i = i + 1\n\n elif(todos_perderam == True):\n print(\"A casa ganhou!\")\n\n sair = input(\n \"Aperte ENTER para continuar ou digite \\\"sair\\\" para encerrar o jogo: \")\n if sair == \"sair\":\n game = False\n","sub_path":"Blackjack_Insper_Luiz_Rodrigo.py","file_name":"Blackjack_Insper_Luiz_Rodrigo.py","file_ext":"py","file_size_in_byte":13517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234457547","text":"from django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom . models import File\nfrom . forms import FileForm\n\n\ndef list(request):\n\n if request.method == 'POST':\n form = FileForm(request.POST, request.FILES)\n if form.is_valid():\n f = File(docfile=request.FILES['docfile'])\n f.save()\n return HttpResponseRedirect(reverse('upload.views.list'))\n else:\n form = FileForm()\n\n files = File.objects.all()\n return render_to_response(\n 'list.html',\n {'files': files, 'form': form},\n context_instance=RequestContext(request)\n )\n","sub_path":"upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"367268033","text":"import subprocess\n\nfrom gitviewfs_objects import CommitPersonEmailFile, CommitContextNames,\\\n\tCommitPersonTypes\nfrom tests.structs.shallow import paths\nfrom tests.structs.shallow.utils import BaseDefaultDirStructTest,\\\n\tBaseDefaultDirStructIntegrationTest\n\n\nclass CommitAuthorEmailFilePathTest(BaseDefaultDirStructTest):\n\t\n\tdef test_path(self):\n\t\tself.assertPathIs(paths.COMMIT_AUTHOR_EMAIL_FILE, CommitPersonEmailFile)\n\t\tself.assertEqual(CommitPersonTypes.AUTHOR, self.obj.get_context_value(CommitContextNames.PERSON_TYPE))\n\n\nclass CommitAuthorEmailFileIntegrationTest(BaseDefaultDirStructIntegrationTest):\n\t\n\tdef test_content(self):\n\t\tAUTHOR_EMAIL = 'abc@xyz.com'\n\t\tsubprocess.check_call(['git', 'config', 'user.email', AUTHOR_EMAIL])\n\t\tself.create_and_commit_file()\n\t\tcommit_sha1 = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()\n\t\tcommit_author_email_file_path = self.make_commit_author_email_file_path(commit_sha1)\n\t\t\n\t\twith open(commit_author_email_file_path) as f:\n\t\t\tcommit_author_email = f.read()\n\t\t\n\t\tself.assertEqual(AUTHOR_EMAIL + '\\n', commit_author_email)\n","sub_path":"tests/structs/shallow/test_commit_author_email_file.py","file_name":"test_commit_author_email_file.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"389579132","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# Created @ 2015-02-19 21:17 by @radaiming\n#\n\n\nimport lxml\nfrom base_norss import NoRss\n\nclass DqdWorker(NoRss):\n def __init__(self):\n super(DqdWorker, self).__init__()\n self.site_name = 'dqd'\n # self.article_section_xpath = '//div[@class=\"detail\"]/div[1]'\n self.site_title = u'\\u61c2\\u7403\\u5e1d\\u56fd\\u5185\\u65b0\\u95fb'\n self.site_link = 'http://www.dongqiudi.com/?tab=56'\n self.site_desc = u'\\u61c2\\u7403\\u5e1d\\u56fd\\u5185\\u65b0\\u95fb'\n self.base_url = 'http://www.dongqiudi.com'\n\n self.get_elements_xpath = '//div[@id=\"news_list\"]/ol/li'\n self.title_xpath = 'h2/a/text()'\n self.url_xpath = 'h2/a/@href'\n self.pub_date_xpath = 'div[@class=\"info\"]/span/text()'\n\n def get_url(self, element):\n # href=\"/article/135548\"\n href = self.get_value(element, self.url_xpath)\n article_id = href.split('/')[-1]\n entry_url = 'http://www.dongqiudi.com/share/article/' + article_id\n return entry_url\n\n def get_pub_date(self, element):\n # publish date on their page is not reliable\n return ''\n #return self.get_value(element, self.pub_date_xpath).encode('ascii',errors='ignore')\n\n def crop_html(self, html):\n tree = lxml.html.fromstring(html)\n try:\n elements_list = tree.xpath('//div[@class=\"con\"]')\n except (lxml.etree.XMLSyntaxError, IndexError):\n return 'article or comment xpath error'\n cropped_html = ''\n for element in elements_list:\n cropped_html += lxml.etree.tostring(\n element,\n encoding='unicode',\n with_tail=False,\n )\n cropped_html += '-' * 20\n return cropped_html\n","sub_path":"workers/dongqiudi.py","file_name":"dongqiudi.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"295520727","text":"# https://www.hackerrank.com/challenges/capitalize/problem\n\ndef capitalize(string):\n l = list(string)\n c_curr = ' '\n for i in range(len(l)):\n if c_curr == ' ':\n l[i] = l[i].upper()\n c_curr = l[i]\n return ''.join(l)\n","sub_path":"hackerrank/python/strings/capitalize.py","file_name":"capitalize.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578656340","text":"import os\nimport os.path\nimport pandas as pd\nimport numpy as np\nimport torch\nimport cv2\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom skimage import io\nfrom skimage.transform import resize\n\n\nclass ImageDataset(Dataset):\n\n def __init__(self, root_dir):\n \"\"\"\n Args:\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.images = np.array([f for f in os.listdir(\n root_dir) if os.path.isfile(os.path.join(root_dir, f))])\n self.root_dir = root_dir\n self.transform = transforms.Compose(\n [\n transforms.ToPILImage(),\n transforms.ToTensor()\n ])\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, idx):\n img_name = self.images[idx]\n image = cv2.imread(os.path.join(self.root_dir, img_name))\n pts1 = np.float32([[280, 0], [360, 0], [0, 480], [640, 480]])\n pts2 = np.float32([[0, 0], [640, 0], [0, 480], [640, 480]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n image = cv2.warpPerspective(image, matrix, (640, 480))\n params = img_name.split('.png')[0].split('_')\n distance = float(params[1]) * 10\n angle = float(params[2]) * 10\n #image = image.transpose((1, 2, 0))\n image = self.transform(image)\n target = torch.FloatTensor([distance, angle])\n sample = (image, target, img_name)\n\n return sample\n","sub_path":"scripts/ImageDataset.py","file_name":"ImageDataset.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"354633498","text":"# -*- coding: utf-8 -*-\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport sys\nfrom modules.check import new_clock, second_clock\nfrom config import client, Telegram_user_id, aria2\nfrom pyrogram.handlers import MessageHandler, CallbackQueryHandler\nfrom pyrogram import filters\nfrom modules.pixiv import start_download_pixiv, start_download_id, start_download_pixivtg, start_download_pixivphoto, \\\n start_download_pixivtele,author,pixiv_topall,start_download_pixiv_top,pixiv_topillustration\nfrom modules.control import send_telegram_file, start_http_download, start_download, start_http_downloadtg, \\\n check_upload, get_free_space_mb, odshare_download\nfrom modules.call import start_pause, start_remove, start_Resume, start_benzi_down, start_download_video,start_get_author_info,get_song_url_info\nfrom modules.moretg import get_telegram_file, get_file_id, sendfile_by_id\nfrom modules.picacg import seach_main\nfrom modules.rclone import start_rclonecopy, start_rclonelsd, start_rclonels, start_rclonecopyurl\nfrom modules.video import start_get_video_info\nfrom modules.netease import get_song_info,search_song_list,edit_song_info,get_song_list_info,downloadplaylist\nimport hashlib\nimport os\nimport datetime\n\n\nstarttime = datetime.datetime.now()\n\n\nasync def chexk_group(_, client, query):\n print(query)\n try:\n info = await client.get_chat_member(chat_id=int(Telegram_user_id), user_id=query.from_user.id)\n print(info)\n sys.stdout.flush()\n return True\n except:\n return False\n\n\nasync def help(client, message):\n print(client)\n print(message)\n text = '''********** pixiv相关 **********\n/pixivauthor - 对Pixiv画师作品进行操作\n在命令后加入作品ID,使用示例\n/pixivauthor 9675329\n\n/pixivtop - 对综合排行榜进行操作\n/pixivtopillust - 对插画排行榜进行操作\n在命令后加入抓取页数,1页50张图片,使用示例(下载排行榜前50)\n/pixivtopall 1\n/pixivtopillust 1\n支持选择时间,请注意日期格式,使用示例\n/pixivtopall 1 20210501\n/pixivtopillust 1 20210501\n\n/pixivpid - 发送pixiv该id的图片\n在命令后加入作品ID,使用示例\n/pixivpid 88339301\n\n********** aria2相关 **********\n/magfile - 推送种子文件至aria2下载\n/mirror - 推送直链至aria2下载上传至网盘\n/mirrortg - 推送直链至aria2下载发送到TG\n/magnet - 推送磁力链接至aria2下载\n/odshare - 下载od公开分享链接,链接权限至少为任何人可查看\n以上在命令后加入链接\n\n********** 其它相关 **********\n/downtgfile - 发送TG文件并上传至网盘\n发送 /downtgfile 后按提示发送文件即可\n\n\n/rclonecopyurl - 用rclonecopyurl的方式直接上传直链文件\n示例 /rclonecopyurl 文件直链\n\n/getfileid - 发送文件获取fileid\n发送 /getfileid 后按提示发送文件即可\n\n/getfile - 发送fileid来获取文件\n示例 /getfile 文件直链\n\n/video - 使用youtube-dl下载视频\n示例 /video 视频链接\n目前测试youtube和哔哩哔哩(不包括番剧)完美适配\n\nneteaseid - 通过id获取歌曲信息\n示例 /neteaseid 1835951859\nid为分享链接: http://music.163.com/song?id=1835951859&userid=84589227 中id=和&的中间值,歌单类似\n\nsearchsong - 搜索网易云音乐歌曲\n示例 /searchsong 怪物\n\nplaylist - 获取歌单信息,后加歌单id\n示例 /playlist 5320586978\n\nBot相关联系:https://t.me/Ben_chao'''\n try:\n await client.send_message(chat_id=int(message.chat.id), text=text)\n except Exception as e:\n print(f\"help :{e}\")\n\n\nasync def status(client, message):\n endtime = datetime.datetime.now()\n\n m, s = divmod(int((endtime - starttime).seconds), 60)\n h, m = divmod(m, 60)\n print(\"%02d时%02d分%02d秒\" % (h, m, s))\n if h != 0:\n last_time = \"%d时%d分%d秒\" % (h, m, s)\n elif h == 0 and m != 0:\n last_time = \"%d分%d秒\" % (m, s)\n else:\n last_time = \"%d秒\" % s\n text = f\"Bot正在运行,已运行时间:`{last_time}`\\n磁盘剩余空间:`{get_free_space_mb()}GB`\"\n await client.send_message(chat_id=int(Telegram_user_id), text=text, parse_mode='markdown')\n\n\ndef start_bot():\n # scheduler = BlockingScheduler()\n scheduler = BackgroundScheduler()\n\n scheduler.add_job(new_clock, \"interval\", seconds=60)\n scheduler.add_job(second_clock, \"interval\", seconds=60)\n scheduler.start()\n print(\"开启监控\")\n\n sys.stdout.flush()\n print(\"开始bot\")\n print(Telegram_user_id)\n sys.stdout.flush()\n aria2.listen_to_notifications(on_download_complete=check_upload, threaded=True)\n\n start_message_handler = MessageHandler(\n status,\n\n filters=filters.command([\"start\"]) & filters.user(int(Telegram_user_id))\n )\n\n help_message_handler = MessageHandler(\n help,\n # filters=filters.command(\"start\") & filters.user(int(Telegram_user_id))\n filters=filters.command([\"help\"]) & filters.user(int(Telegram_user_id))\n )\n\n\n pixivid_message_handler = MessageHandler(\n start_download_id,\n filters=filters.command(\"pixivpid\") & filters.user(int(Telegram_user_id))\n )\n\n magfile_message_handler = MessageHandler(\n send_telegram_file,\n filters=filters.command(\"magfile\") & filters.user(int(Telegram_user_id))\n )\n\n http_download_message_handler = MessageHandler(\n start_http_download,\n filters=filters.command(\"mirror\") & filters.user(int(Telegram_user_id))\n )\n magnet_download_message_handler = MessageHandler(\n start_download,\n filters=filters.command(\"magnet\") & filters.user(int(Telegram_user_id))\n )\n\n telegram_file_message_handler = MessageHandler(\n get_telegram_file,\n filters=filters.command(\"downtgfile\") & filters.user(int(Telegram_user_id))\n )\n seach_main_file_message_handler = MessageHandler(\n seach_main,\n filters=filters.command(\"search\") & filters.user(int(Telegram_user_id))\n )\n\n\n\n start_http_downloadtg_message_handler = MessageHandler(\n start_http_downloadtg,\n filters=filters.command(\"mirrortg\") & filters.user(int(Telegram_user_id))\n )\n start_rclonecopy_message_handler = MessageHandler(\n start_rclonecopy,\n filters=filters.command(\"rclonecopy\") & filters.user(int(Telegram_user_id))\n )\n\n start_rclonelsd_message_handler = MessageHandler(\n start_rclonelsd,\n filters=filters.command(\"rclonelsd\") & filters.user(int(Telegram_user_id))\n )\n\n start_rclone_message_handler = MessageHandler(\n start_rclonels,\n filters=filters.command(\"rclone\") & filters.user(int(Telegram_user_id))\n )\n\n start_rclonecopyurl_message_handler = MessageHandler(\n start_rclonecopyurl,\n filters=filters.command(\"rclonecopyurl\") & filters.user(int(Telegram_user_id))\n )\n\n get_file_id_message_handler = MessageHandler(\n get_file_id,\n filters=filters.command(\"getfileid\") & filters.user(int(Telegram_user_id))\n )\n sendfile_by_id_message_handler = MessageHandler(\n sendfile_by_id,\n filters=filters.command(\"getfile\") & filters.user(int(Telegram_user_id))\n )\n\n\n\n start_get_video_info_message_handler = MessageHandler(\n start_get_video_info,\n filters=filters.command(\"video\") & filters.user(int(Telegram_user_id))\n )\n\n start_download_od_shareurl_handler = MessageHandler(\n odshare_download,\n filters=filters.command(\"odshare\") & filters.user(int(Telegram_user_id))\n )\n\n start_get_authorinfo_handler = MessageHandler(\n author,\n filters=filters.command(\"pixivauthor\") & filters.user(int(Telegram_user_id))\n )\n\n start_get_pixiv_top_handler = MessageHandler(\n pixiv_topall,\n filters=filters.command(\"pixivtopall\") & filters.user(int(Telegram_user_id))\n )\n\n start_pixiv_topillustration_handler = MessageHandler(\n pixiv_topillustration,\n filters=filters.command(\"pixivtopillust\") & filters.user(int(Telegram_user_id))\n\n )\n\n get_song_info_handler = MessageHandler(\n get_song_info,\n filters=filters.command(\"neteaseid\") & filters.user(int(Telegram_user_id))\n\n )\n\n search_song_list_handler = MessageHandler(\n search_song_list,\n filters=filters.command(\"searchsong\") & filters.user(int(Telegram_user_id))\n\n )\n\n get_song_list_info_handler = MessageHandler(\n get_song_list_info,\n filters=filters.command(\"playlist\") & filters.user(int(Telegram_user_id))\n\n )\n\n\n start_Resume_handler = CallbackQueryHandler(\n callback=start_Resume,\n filters=filters.create(lambda _, __, query: \"Resume\" in query.data)\n )\n\n start_pause_handler = CallbackQueryHandler(\n callback=start_pause,\n filters=filters.create(lambda _, __, query: \"Pause\" in query.data)\n )\n start_remove_handler = CallbackQueryHandler(\n callback=start_remove,\n filters=filters.create(lambda _, __, query: \"Remove\" in query.data)\n )\n\n start_benzi_down_handler = CallbackQueryHandler(\n callback=start_benzi_down,\n filters=filters.create(lambda _, __, query: \"down\" in query.data)\n )\n start_download_video_handler = CallbackQueryHandler(\n callback=start_download_video,\n filters=filters.create(lambda _, __, query: \"video\" in query.data or \"mp3\" in query.data)\n )\n\n start_call_author_handler = CallbackQueryHandler(\n callback=start_get_author_info,\n filters=filters.create(lambda _, __, query: \"pixivuser\" in query.data)\n )\n\n\n start_download_pixiv_top_handler = CallbackQueryHandler(\n callback=start_download_pixiv_top,\n filters=filters.create(lambda _, __, query: \"pixivtop\" in query.data)\n )\n\n\n get_song_url_info_handler = CallbackQueryHandler(\n callback=get_song_url_info,\n filters=filters.create(lambda _, __, query: \"netease\" in query.data)\n )\n\n edit_song_info_handler = CallbackQueryHandler(\n callback=edit_song_info,\n filters=filters.create(lambda _, __, query: \"editsong\" in query.data)\n )\n\n downloadplaylist_handler = CallbackQueryHandler(\n callback=downloadplaylist,\n filters=filters.create(lambda _, __, query: \"playlist\" in query.data)\n )\n\n\n\n\n client.add_handler(start_download_video_handler, group=0)\n client.add_handler(start_Resume_handler, group=0)\n client.add_handler(start_pause_handler, group=0)\n client.add_handler(start_remove_handler, group=0)\n client.add_handler(start_benzi_down_handler, group=0)\n\n client.add_handler(start_message_handler, group=1)\n client.add_handler(help_message_handler, group=1)\n\n\n client.add_handler(pixivid_message_handler, group=1)\n client.add_handler(magfile_message_handler, group=3)\n\n client.add_handler(http_download_message_handler, group=1)\n client.add_handler(magnet_download_message_handler, group=1)\n client.add_handler(telegram_file_message_handler, group=1)\n client.add_handler(seach_main_file_message_handler, group=1)\n\n client.add_handler(start_http_downloadtg_message_handler, group=1)\n client.add_handler(start_rclonecopy_message_handler, group=1)\n client.add_handler(start_rclonelsd_message_handler, group=1)\n client.add_handler(start_rclone_message_handler, group=1)\n client.add_handler(start_rclonecopyurl_message_handler, group=1)\n client.add_handler(get_file_id_message_handler, group=1)\n client.add_handler(sendfile_by_id_message_handler, group=1)\n\n client.add_handler(start_get_video_info_message_handler, group=1)\n client.add_handler(start_download_od_shareurl_handler, group=1)\n client.add_handler(start_get_authorinfo_handler, group=1)\n client.add_handler(start_call_author_handler, group=1)\n client.add_handler(start_get_pixiv_top_handler, group=1)\n client.add_handler(start_download_pixiv_top_handler, group=1)\n client.add_handler(start_pixiv_topillustration_handler, group=1)\n client.add_handler(get_song_url_info_handler, group=1)\n client.add_handler(get_song_info_handler, group=1)\n client.add_handler(search_song_list_handler, group=1)\n client.add_handler(edit_song_info_handler, group=1)\n client.add_handler(get_song_list_info_handler, group=1)\n client.add_handler(downloadplaylist_handler, group=1)\n\n\n\n client.run()\n\n\nif __name__ == '__main__':\n start_bot()\n\n","sub_path":"bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625154984","text":"from mongodb_migrations.base import BaseMigration\n\n\n########################################################################################################################\n#\n# Update invalid data for marshmallow\n#\n########################################################################################################################\n\n\nclass Migration(BaseMigration):\n def upgrade(self):\n for coverage in self.db[\"coverages\"].find():\n if \"grid_calendars_id\" in coverage:\n del coverage[\"grid_calendars_id\"]\n self.db[\"coverages\"].save(coverage)\n for contributor in self.db[\"contributors\"].find():\n for data_source in contributor.get(\"data_sources\", []):\n if \"export_data_source_id\" in data_source:\n del data_source[\"export_data_source_id\"]\n self.db[\"contributors\"].save(contributor)\n","sub_path":"migrations/20190225160304.py","file_name":"20190225160304.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"485653033","text":"from video import make_video\r\nfrom functools import lru_cache\r\nimport pygame\r\nimport math\r\npygame.init()# prepare the pygame module for use\r\n\r\n# Create a new surface and window.#\r\nsurface_size = 800\r\nsurface_x = 800\r\nsurface_y = 800\r\nmain_surface = pygame.display.set_mode((1600,900),pygame.HWSURFACE+pygame.DOUBLEBUF+pygame.FULLSCREEN)\r\nmy_clock = pygame.time.Clock()\r\nfont = pygame.font.Font(None, 36)\r\n\r\n\r\n\r\ndef draw_tree(gen, order, depthprint, theta, thetab, sz, posn, heading, color=(125,100,150), depth=0):\r\n\r\n trunk_ratio = 0.19 # How big is the trunk relative to whole tree?\r\n trunk = sz * trunk_ratio # length of trunk\r\n delta_x = trunk * math.cos(heading*1j.real)*math.sin(heading*1j.imag)\r\n delta_y = trunk * math.sin(heading*1j.imag)*math.cos(heading*1j.imag)\r\n (u, v) = posn\r\n newpos = (u + delta_x, v + delta_y )\r\n colju = (order-1)*16\r\n pygame.draw.line(main_surface, color, posn, newpos, order)\r\n\r\n # pygame.draw.polygon(main_surface, color, [[int(posn[0]),int(posn[1])], [(surface_size/2), (surface_size/2)], [(surface_size/2), (surface_size/2)]], 5)\r\n if order > 0: # Draw another layer of subtrees\r\n\r\n # These next six lines are a simple hack to make the two major halves\r\n # of the recursion different colors. Fiddle here to change colors\r\n # at other depths, or when depth is even, or odd, etc.\r\n depth = math.floor(depth)\r\n if depth == 0:\r\n color1 = color\r\n color2 = color\r\n elif depth%2 :\r\n color1 = (colju, colju, colju)\r\n color2 = (colju, colju, colju)\r\n elif depth%3 == 0 :\r\n color1 = (colju, 0, 0)\r\n color2 = (0, colju, colju)\r\n elif depth%4 == 0:\r\n color1 = (0, colju, 0)\r\n color2 = (colju, 0, colju)\r\n elif depth%5 == 0:\r\n color1 = (0, 0, colju)\r\n color2 = (colju, colju, 0)\r\n elif depth%6 == 0:\r\n color1 = (0, colju, colju)\r\n color2 = (colju, 0, 0)\r\n elif depth%7 == 0:\r\n color1 = (colju, 0, colju)\r\n color2 = (0, colju, 0)\r\n elif depth%8 == 0:\r\n color1 = (colju, colju,0)\r\n color2 = (0, 0, colju)\r\n elif depth%9 == 0:\r\n color1 = (colju, colju, colju)\r\n color2 = (0,0,0)\r\n elif depth%10 == 0:\r\n color1 = (255,255,255)\r\n color2 = (255,255,255)\r\n else:\r\n color1 = (colju, colju, colju)\r\n color2 = (colju, colju, colju)\r\n\r\n # make the recursive calls to draw the two subtrees\r\n newsz = sz*(1 - trunk_ratio)\r\n draw_tree(gen, order-1, depthprint, theta*math.cos(heading), thetab*math.sin(heading), newsz, newpos, heading+theta-5.3, color1, depth+math.sin(heading+math.pi))\r\n draw_tree(gen, order-1, depthprint, theta*math.cos(heading), thetab*math.sin(heading), newsz, newpos, heading+theta+1, color2, depth+math.sin(heading+math.pi))\r\n\r\ndef gameloop():\r\n gen = 1\r\n depthincr = 0\r\n theta1 = 0\r\n theta2 = 0\r\n save_screen = make_video(main_surface)\r\n ft = 0\r\n depthprint = 1\r\n #video = True\r\n video = False\r\n while True:\r\n \r\n # Handle evente from keyboard, mouse, etc.\r\n \r\n event = pygame.event.poll()\r\n \r\n\r\n if event.type == pygame.QUIT:\r\n break;\r\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\r\n break;\r\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_v:\r\n video = not video\r\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_c:\r\n gen+=0.1\r\n # Updates - change the angle\r\n theta1 += math.pi/500\r\n theta2 += math.pi/500\r\n #0.009\r\n depthincr =0\r\n\r\n # Draw everything\r\n main_surface.fill((0, 0, 0))\r\n text = font.render(\"theta1 \" + str(gen), 100, (250, 100, 100))\r\n textpos = text.get_rect(centerx=200)\r\n main_surface.blit(text, textpos)\r\n draw_tree(gen, 12, depthprint, theta1, theta2, surface_size*2, (pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]), 0,color=(10,10,10), depth=depthincr)\r\n #draw_tree(12, pygame.mouse.get_pos()[0]/100, pygame.mouse.get_pos()[1]/100, surface_size*0.9, , -math.pi/2, color=(0,0,0), depth=round(pygame.mouse.get_pos()[1]/10))(surface_size//2, surface_size-50)\r\n #draw_tree(10, (surface_x+pygame.mouse.get_pos()[0])/200, surface_y+pygame.mouse.get_pos()[1]/200, surface_y*0.8, (surface_x/2, surface_y), -math.pi/2)\r\n \r\n pygame.display.update()\r\n pygame.display.flip()\r\n \r\n my_clock.tick(60)\r\n #pygame.display.update() \r\n if video:\r\n if ft<600:\r\n ft+=1\r\n next(save_screen)\r\n else:\r\n video = not video\r\n\r\ngameloop()\r\npygame.quit()\r\n","sub_path":"2/wtf/fract5xpi.py","file_name":"fract5xpi.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"143916244","text":"#!/usr/bin/env python3\n# by Torben Menke https://entorb.net\n\"\"\"\nHTML modifications.\n\"\"\"\nimport os\nimport re\nimport sys\n\nos.chdir(os.path.dirname(sys.argv[0]) + \"/../..\")\n\nsource_file = \"tmp/hpmor-epub-5-html-unmod.html\"\ntarget_file = \"hpmor.html\"\n\nprint(\"=== 6. HTML modifications ===\")\n\n\nwith open(source_file, encoding=\"utf-8\", newline=\"\\n\") as fhIn:\n cont = fhIn.read()\n\n# remove strange leftovers from tex -> html conversion\ncont = re.sub(\n r\"().*?

Book :

\\n\",\n r\"\\1\",\n cont,\n flags=re.DOTALL | re.IGNORECASE,\n)\n\n# cleanup hp-intro leftovers\ncont = cont.replace(\n \"\"\"

Fanfiction based on the characters of

\n

J. K. ROWLING

\n

and her books:

\"\"\",\n \"

Fanfiction based on the characters of J. K. Rowling and her books:

\",\n)\ncont = cont.replace(\"

Year at Hogwarts

\\n\", \"\")\ncont = cont.replace(\n \"

\\n

Harry Potter and the\",\n \"
\\nHarry Potter and the\",\n)\n\n# doc structure (not needed any more, using calibi --level1-toc flag instead)\n# sed -i 's/

\" in cont:\n part_no += 1\n cont = cont.replace(\"

\", f\"{part_no}. \", 1)\ncont = cont.replace(\"\", \"

\")\n\n# add chapter numbers\nchapter_no = 0\nwhile \"

\" in cont:\n chapter_no += 1\n cont = cont.replace(\"

\", f\"{chapter_no}. \", 1)\ncont = cont.replace(\"\", \"

\")\n\n# fix double rules\n# cont = cont.replace(\"
\\n
\", \"
\")\ncont = re.sub(\n r\"
\\n
\",\n r\"
\",\n cont,\n flags=re.DOTALL | re.IGNORECASE,\n)\n# fixing linebreak at author's comment\ncont = cont.replace(\"

E. Y.: 

\\n

\", \"

E.Y.: \")\n\n# converting \"color-marked\" styles of 1.sh back to proper style classes\ncont = re.sub(\n r'<(div|span) style=\"color: (parsel|writtenNote|McGonagallWhiteBoard|headline)\"',\n r'<\\1 class=\"\\2\"',\n cont,\n)\n\n# add css style file format for \\emph in \\emph\nwith open(\"scripts/ebook/html.css\", encoding=\"utf-8\", newline=\"\\n\") as fhIn:\n css = fhIn.read()\ncont = cont.replace(\"\\n\", css + \"\\n\\n\")\n\n\nwith open(target_file, mode=\"w\", encoding=\"utf-8\", newline=\"\\n\") as fhOut:\n fhOut.write(cont)\n","sub_path":"scripts/ebook/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185892644","text":"import sys\nfrom PySide.QtCore import Qt, SIGNAL, SLOT\nfrom PySide.QtGui import QDialog, QApplication, QPushButton, QVBoxLayout, QFileDialog, QLabel, QCheckBox, QSpinBox, \\\n QGridLayout, QMessageBox\n\n__appname__ = \"Dumb Dialog Example\"\n\n\nclass Program(QDialog):\n\n def __init__(self, parent=None):\n super(Program, self).__init__(parent)\n\n btn = QPushButton(\"Open Dialog\")\n self.label1 = QLabel(\"Label 1 result\")\n self.label2 = QLabel(\"Label 2 result\")\n\n layout = QVBoxLayout()\n layout.addWidget(btn)\n layout.addWidget(self.label1)\n layout.addWidget(self.label2)\n self.setLayout(layout)\n\n btn.clicked.connect(self.open_dialog)\n\n # Force the window to stay on top\n self.setWindowFlags(Qt.WindowStaysOnTopHint)\n\n def open_dialog(self):\n dialog = Dialog()\n if dialog.exec_():\n # If dialog returns True (accept)\n self.label1.setText(\"SpinBox value is \" + str(dialog.spin_box.value()))\n self.label2.setText(\"CheckBox is \" + str(dialog.check_box.isChecked()))\n else:\n # Dialog rejected\n QMessageBox.warning(self, 'Warning', 'Dialog canceled')\n\n\nclass Dialog(QDialog):\n\n def __init__(self, parent=None):\n super(Dialog, self).__init__(parent)\n self.setWindowTitle('Dialog')\n\n self.check_box = QCheckBox()\n self.spin_box = QSpinBox()\n button_ok = QPushButton(\"OK\")\n cancle_ok = QPushButton(\"Cancle\")\n\n layout = QGridLayout()\n layout.addWidget(self.spin_box, 0, 0)\n layout.addWidget(self.check_box, 0, 1)\n layout.addWidget(cancle_ok)\n layout.addWidget(button_ok)\n\n self.setLayout(layout)\n\n self.connect(button_ok, SIGNAL(\"clicked()\"), self, SLOT(\"accept()\"))\n self.connect(cancle_ok, SIGNAL(\"clicked()\"), self, SLOT(\"reject()\"))\n\n\napp = QApplication(sys.argv)\nform = Program()\nform.show()\napp.exec_()\n","sub_path":"lecture_09_dumb_dialogs/dumb_dialogs.py","file_name":"dumb_dialogs.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"19032618","text":"changelog = { \n \"changelog\": [\n {\n \"version\": \"0.1.1\",\n \"date\": \"2020/03/29\",\n \"changed\": [\n \"Idioma del nombre de los países a comparar con Cuba al español.\",\n \"Enlace de Matcom.\",\n ],\n \"added\": [\n\n ],\n \"fixed\": [\n \"Errores ortográficos.\",\n \"Errores en las leyendas de las gráficas.\",\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.2.0\",\n \"date\": \"2020/03/30\",\n \"changed\": [\n \"Varias gráficas existentes.\"\n ],\n \"added\": [\n \"Presentación con consejos útiles sobre el Covid-19.\",\n \"Gráfica con información sobre la relación de los Test aplicados.\",\n \"Gráfica con información sobre la evolución de los Test aplicados.\",\n \"Varios enlaces de interés al menú lateral.\"\n ],\n \"fixed\": [\n \"Pequeños errores existentes en la aplicación.\"\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.2.1\",\n \"date\": \"2020/03/31\",\n \"changed\": [\n \"Mejoras a los mapas.\",\n ],\n \"added\": [\n \"Botón para actualizar la información en la esquina superior derecha.\",\n \"Enlace al bot de Telegram de Covid-19 Cuba Data en el menú lateral.\",\n ],\n \"fixed\": [\n\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.3.0\",\n \"date\": \"2020/04/02\",\n \"changed\": [\n \"Gráfico de Cantidad de Test aplicados acumulados por días a Cantidad de Test aplicados por días.\",\n ],\n \"added\": [\n \"Listado de las 10 provincias y 10 municipios con más casos diagnosticados.\",\n \"Notificación para recordar el aplauso de las 9 de la noche dedicado quienes trabajan por la salud y seguridad del pueblo.\",\n ],\n \"fixed\": [\n \"Errores en los mapas, como los colores de la escala.\",\n \"Errores menores en la aplicación.\",\n\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.3.1\",\n \"date\": \"2020/04/04\",\n \"changed\": [\n \"País por defecto para comparar con Cuba.\",\n ],\n \"added\": [\n\n ],\n \"fixed\": [\n \"Errores en las tablas de los 10 provincias y 10 municipios con mayor cantidad de casos diagnosticados.\",\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.4.0\",\n \"date\": \"2020/04/08\",\n \"changed\": [\n \"Comportamiento del país por defecto con que se compara Cuba. Ahora este será el último país con que se seleccionó para comparar.\",\n \"Datos en algunas gráficas.\",\n ],\n \"added\": [\n \"Información de los casos activos a la gráfica de Evolución de Casos por Días.\",\n \"Gráfica de la Evolución de Altas por Días.\",\n \"Gráfica de la Evolución de Muertes por Días.\",\n \"Tabla con los 20 países con más casos acumulados.\",\n \"Página de configuración accesible desde el menú lateral.\",\n \"Posibilidad de escoger el modo de conexión entre: solo utilizar un servidor ubicado en Cuba, utilizar solo uno externo a Cuba o por último utilizar primero uno ubicado en Cuba y, si algo falla durante el proceso, utilizar el externo a Cuba.\",\n ],\n \"fixed\": [\n \"Problema que impedía que las tablas de los municipios y provincias con más casos se mostrasen.\",\n ],\n \"deleted\": [\n\n ],\n },\n {\n \"version\": \"0.5.0\",\n \"date\": \"2020/04/13\",\n \"changed\": [\n \"Añadidos todos los países en la comparación con Cuba.\",\n \"Cambios en el menú lateral.\",\n ],\n \"added\": [\n \"Estadísticas por provincia accediendo desde el menú lateral.\",\n \"Gráfico para comparar los comportamientos exponenciales de la epidemia en los 20 países más afectados con Cuba.\"\n \"Pantalla para chequear si hay una actualización de la aplicación.\",\n \"Notificaciones de actualización de la aplicación.\",\n \"Notificaciones de actualización de la información.\",\n \"Nuevo sistema de caché para disminuir la transferencia de datos por la red.\",\n \"Animación al abrir y refrescar las pantallas.\",\n ],\n \"fixed\": [\n\n ],\n \"deleted\": [\n\n ],\n },\n ]\n}\n","sub_path":"app/v1/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"588051341","text":"# -*- coding: utf-8 -*-\nfrom south.v2 import DataMigration\n\nclass Migration(DataMigration):\n\n depends_on = (\n ('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),\n )\n\n def forwards(self, orm):\n orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))\n\n def backwards(self, orm):\n pass\n\n models = {\n u'robokassa.successnotification': {\n 'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'Meta': {'object_name': 'SuccessNotification'},\n 'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),\n 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})\n },\n u'payment.sourcetype': {\n 'Meta': {'object_name': 'SourceType'},\n 'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],\n {'allow_duplicates': 'False', 'max_length': '128', 'separator': \"u'-'\", 'blank': 'True',\n 'unique': 'True', 'populate_from': \"'name'\", 'overwrite': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})\n }\n }\n\n complete_apps = ['robokassa']\n symmetrical = True\n","sub_path":"robokassa/migrations/0003_load_source_type.py","file_name":"0003_load_source_type.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"316057183","text":"#!/usr/bin/env python3\n\n# type()动态语言和静态语言最大的不同,就是函数和类的定义,不是贬义时定义的,而是运行时动态创建的。\n\nclass Hello(object):\n def hello(self,name = 'world'):\n print('Hello, %s.' % name)\n\nh = Hello()\nh.hello()\nprint(type(Hello))\nprint(type(h))\n# type()函数可以查看一个类型或变量的类型,hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class hello\n\n# 我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数\n\n# type()函数既可以返回一个对象类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过classhello(object)。。定义\n\n# 定义函数\ndef fn(self,name = 'world'):\t\t\t\n\tprint('Hello, %s.' % name)\n\n# 创建hello class\nHello2 = type('Hello',(object,),dict(hello = fn))\n\n# 要创建一个class对象,type()函数依次传入3个参数:\n# 1, class的名称\n# 2, 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘记了tuple的单元素写法\n# 3, class的方法名称和函数绑定,这里我们把函数绑定到方法名hello上。\n\n# 通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class\n# 正常情况下,我们都是用class来定义类的,但是,type()函数叶允许我们动态的创建出类来,也就说,动态语言本身支持运行期动态创建类,这个和静态语言有非常大的不同,要在静态余元运行期间创建类,必须够着源代码字符串在调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会法非常的复杂\n \n## metaclass 元类\n# 除了使用type()动态创建类意外,爻控制类的创建行为,还可以使用metaclasss\n# meta 直译就是元类,简单来说就是当我们定义类以后,就可以根据这个类创建出实例,所以,先定义类,然后创建实例。\n# 但是如果我们想创建出类呢?那就必须根据metaclass创建出类,所以先定义metaclass,然后创建类\n# 链接起来就是,先定义metaclass,就可以创建类,最后创建实例\n# 所以,metaclass允许你创建类或者修改类,换句话说,你可以吧类看成是metaclass创建出来的实例。\n\n# metaclass是Python面向对象里最难理解的,也是最难使用的魔术代码,正常情况下,你不会碰到需要使用metaclass的情况,所以,一下内容看不懂叶没有关系,因为你基本不会使用到;\n\n# 使用metaclass可以给我们的自定义的类添加一个add方法\n\n# metaclass是类的模板,所以必须从'type'类型派生\nclass ListMetaclass(type):\n\tdef __new__(cls,name,bases,attrs):\n\t\tattrs['add'] = lambda self,value:self.append(value)\n\t\treturn type.__new__(cls,name,bases,attrs)\n\n# 按照默认的习惯,metaclass类名总是以metaclass结尾的,以便清楚地表示这是一个metaclass\n# 有了listmetalclass我们在定义类的时候还有指示使用listmetaclass来定制类,传入关键字参数metaclass\nclass MyList(list,metaclass=ListMetaclass):\n\tpass\n\n# 当我们传入关键字参数metaclass时,魔术就生效了,它指示Python解释器在创建mylist时要通过listmetaclass.__new__()来创建,再次我们可以修改类的定义,比如加上新的方法,然后可返回修改后的定义\n# __new__() 方法 接收到的参数依次是:\n# 1, 当前准备创建的类的对象\n# 2, 类的名字\n# 3, 类继承的父类集合\n# 4, 类的方法集合\n\n# 测试一下MyList是否可以调用add()方法\nL = MyList()\nL.add(1)\nprint(L)\n\n# 动态修改有什么意义吗?直接在MyLisy修改协商add(方法不是更简单吗?正常情况下确实应该直接写,通过metaclass修改纯属变态\n\n# 但是总会遇到通过metaclass来修改类定义的,ORM就是一个典型的例子\n# ORM全称Object Relational Mapping 即对象-关系映射,就是把关系数据库的一行映射为一个对象,也就是一个类对应一个表,这样写代码更简单,不用直接写SQL语句\n# 要编写一个ORM框架,所有的类智能动态定义,因为只有使用者才能根据表的结果定义出对应的类来\n# 编写底层模块的第一步,就是先把调用接口写出来,比如,使用者如果使用这个ORM框架,想定义一个user类来操作对应的数据库表user,我们期待他写出这样的代码\n\n\n\n# 其中,父类model和属性类型stringfield,integerField是有ORM框架提供的,剩下的魔术方法比如save()全部由metaclass自动生成,虽然metaclass的编写会比较复杂,但ORM的使用者用起来却异常简单\n\n# 现在,我们就按上面的接口实现该ORM\n# 首先定义field类,它复杂保存数据库表的字段名和字段类型\n\nclass Field(object):\n\t\"\"\"docstring for Field\"\"\"\n\tdef __init__(self, name, column_type):\n\t\tsuper( Field, self).__init__()\n\t\tself.name = name\n\t\tself.column_type = column_type\n\tdef __str__(self):\n\t\treturn '<%s:%s>' % (self.__class__.__name__,self.name)\n\n# 在field的基础上,进一步定义各种类型的Field,比如StringField,IntegerField等等\n\nclass StringField(Field):\n\tdef __init__(self, name):\n\t\tsuper(StringField, self).__init__(name,'varchar(100)')\n\t\tself.name = name\n\nclass IntegerField(Field):\n\tdef __init__(self, name):\n\t\tsuper(IntegerField, self).__init__(name,'bright')\n\t\tself.name = name\n\t\t\n# 下一步就是编写最复杂的modelmetaClass了\n\nclass ModelMetaclass(type):\n def __new__(cls,name,bases,attrs):\n if name == 'Model':\n return type.__new__(cls,name,bases,attrs)\n print('Found model:%s' % name)\n mappings = dict()\n for k ,v in attrs.items():\n \tif isinstance(v,Field):\n \t \tprint('Found mapping:%s ==> %s' % (k,v))\n \t \tmappings[k] = v\n for k in mappings.keys():\n \tattrs.pop(k)\n attrs['__mappings__'] = mappings #保存属性和列的映射关系\n attrs['__table__'] = name # 假设表名和类名一致\n return type.__new__(cls,name,bases,attrs)\n\n# 基类\nclass Model(dict,metaclass = ModelMetaclass):\n\t\"\"\"docstring for Model\"\"\"\n\tdef __init__(self, **kw):\n\t\tsuper(Model, self).__init__(**kw)\n\t\tself.kw = kw\n\tdef __getter__(self,key):\n\t\ttry:\n\t\t\treturn self[key]\n\t\texcept KeyError:\t\n\t\t\traise AttributeError(r\"'Model' object has no attribute '%s'\" % key)\n\n\tdef __setter__(self,key,value):\n\t\tself[key] = value\n\tdef save(self):\n\t\tfilelds = []\n\t\tparams = []\n\t\targs = []\n\t\tfor k,v in self.__mappings__.items():\n\t\t\tfilelds.append(v.name)\n\t\t\tparams.append('?')\n\t\t\targs.append(getattr(self,k,None))\n\t\tsql = 'insert into %s (%s) values (%s)' % (self.__table__,','.join(filelds),','.join(params))\n\t\tprint('SQL:%s' % sql)\n\t\tprint('ARGS:%s' % str(args))\n\n\nclass User(Model):\n id = IntegerField('id')\n name = StringField('username')\n emial = StringField('email')\n password = StringField('password')\n\n# 定义类的属性到列的映射:\n# 创建一个实例:\nu = User(id = 12345,name = 'Michael',email = '1032401678@qq.com',password = 'my-pwd')\n\n#保存到数据库\nu.save()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"metalClass.py","file_name":"metalClass.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"437973937","text":"import numpy as np\nimport pandas as pd\n \ndef computeLanguageError(freq):\n # Computes the squared error between the letter frequencies given\n # as input and the letter frequencies of 15 languages stored in the\n # file letter_frequencies.csv\n \n # Open the file letter_frequencies.\n data = pd.read_csv(\"letter_frequencies.csv\")\n \n # Extract a matrix containing the letter frequencies for the 15\n # languages and transpose it to yield a size 15 x 26 matrix\n languageFrequencies = np.array(data.iloc[0:26, 1:16]).T\n \n # Compute the squared errors. Subtracting a vector from a matrix will\n # \"recycle\" the vector, so it is subtracted from each row.\n E = np.sum((languageFrequencies - freq)**2, axis=1)\n return E","sub_path":"python/02631_IntrProg/week006/computeLanguageError.py","file_name":"computeLanguageError.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"397198437","text":"\"\"\"\nImage classification with Azure Custom Vision\n\"\"\"\nimport json\nimport argparse\nfrom azure.cognitiveservices.vision.customvision.training import (\n CustomVisionTrainingClient,\n)\n\nfrom azure.cognitiveservices.vision.customvision.prediction import (\n CustomVisionPredictionClient,\n)\nfrom msrest.authentication import ApiKeyCredentials\n\n# Now there is a trained endpoint that can be used to make a prediction\n\n\ndef parse_args():\n \"\"\"\n Parse arguments\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--image\", help=\"image path\", type=str)\n parser.add_argument(\n \"-c\",\n \"--config\",\n help=\"cofigure file path\",\n type=str,\n default=\"image_classification_config.json\",\n )\n args = parser.parse_args()\n return args\n\n\ndef get_project_id(config):\n \"\"\"\n Get the project ID list\n \"\"\"\n credentials = ApiKeyCredentials(in_headers={\"Training-key\": config[\"training_key\"]})\n trainer = CustomVisionTrainingClient(config[\"ENDPOINT\"], credentials)\n project_id = next(\n proj.id\n for proj in trainer.get_projects()\n if proj.name == config[\"project_name\"]\n )\n return project_id\n\n\ndef main():\n \"\"\"\n Image classification\n \"\"\"\n args = parse_args()\n config = json.load(open(args.config, \"r\"))\n\n # Get the predictor\n prediction_credentials = ApiKeyCredentials(\n in_headers={\"Prediction-key\": config[\"prediction_key\"]}\n )\n predictor = CustomVisionPredictionClient(config[\"ENDPOINT\"], prediction_credentials)\n\n # ======================================================================================\n # Open the sample image and get back the prediction results.\n project_id = get_project_id(config)\n with open(args.image, \"rb\") as image_contents:\n results = predictor.classify_image(\n project_id,\n config[\"publish_iteration_name\"],\n image_contents.read(),\n )\n\n # Display the results.\n for prediction in results.predictions:\n print(\n \"{0}: {1:.2f}%\".format(\n prediction.tag_name, prediction.probability * 100\n )\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"azure_cognitive_services/classify_image.py","file_name":"classify_image.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"339510882","text":"\"\"\"\nContains unit tests that reproduce previous issues. Whenever a new issue is\ndiscovered, a failing test should be added to this file first before the issue\nis fixed.\n\"\"\"\nfrom collections import namedtuple\n\nimport declxml as xml\nfrom .helpers import strip_xml\n\n\ndef test_serialize_none_namedtuple_issue_7():\n \"\"\"Tests attempting to serialize a named tuple value that is None\"\"\"\n Athlete = namedtuple('Athlete', [\n 'name',\n 'age',\n ])\n \n processor = xml.dictionary('race-result', [\n xml.floating_point('time'),\n xml.named_tuple('athlete', Athlete, [\n xml.string('name'),\n xml.integer('age'),\n ], required=False)\n ])\n\n value = {\n 'time': 87.5,\n 'athlete': None, \n }\n\n expected_xml = strip_xml(\"\"\"\n \n \n \n \"\"\")\n\n actual_xml = xml.serialize_to_string(processor, value)\n\n assert expected_xml == actual_xml\n\n\ndef test_serialize_none_object_issue_7():\n \"\"\"Attempts to serialize an object value that is None\"\"\"\n class Athlete(object):\n\n def __init__(self):\n self.name = ''\n self.age = 0 \n\n\n processor = xml.dictionary('race-result', [\n xml.floating_point('time'),\n xml.user_object('athete', Athlete, [\n xml.string('name'),\n xml.integer('age'),\n ], required=False)\n ])\n\n value = {\n 'time': 87.5,\n 'athlete': None,\n }\n\n expected_xml = strip_xml(\"\"\"\n \n \n \n \"\"\")\n\n actual_xml = xml.serialize_to_string(processor, value)\n\n assert expected_xml == actual_xml\n","sub_path":"tests/test_issues.py","file_name":"test_issues.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"250447921","text":"import fabtools.require\n\nfrom fabric.api import *\nfrom fabric.contrib.files import *\n\nfrom fabtools.files import watch\nfrom fabtools.require import deb\n\nimport yaml\n\n@task\n@roles('debian-uwsgi')\ndef uwsgi_install():\n 'Install uWSGI from unstable'\n for pkg in ['uwsgi', 'uwsgi-plugin-python', 'uwsgi-plugin-python3']:\n if not deb.is_installed(pkg):\n deb.package(pkg + '/unstable')\n\n@task\n@roles('debian-uwsgi')\ndef uwsgi_create_run_uwsgi():\n 'Create /run/uwsgi directory'\n if not exists('/etc/tmpfiles.d/run_uwsgi.conf'):\n fabtools.require.file('/etc/tmpfiles.d/run_uwsgi.conf',\n 'd /run/uwsgi 0755 www-data www-data - -')\n run('systemctl restart systemd-tmpfiles-setup')\n\n@task\n@roles('debian-uwsgi')\ndef uwsgi_create_systemd_unit_files():\n 'Create unit files for socket-activated uWSGI apps (awesome)'\n fabtools.require.file('/etc/systemd/system/uwsgi@.service', UWSGI_SERVICE)\n fabtools.require.file('/etc/systemd/system/uwsgi@.socket', UWSGI_SOCKET)\n\n@task\n@roles('debian-uwsgi')\ndef uwsgi_create_uwsgi_apps():\n 'Enable and start sockets for uWSGI apps'\n for app in env.config[env.host_string]['uwsgi']:\n if not exists('/etc/systemd/system/sockets.target.wants/uwsgi@{name}.socket'.format(**app)):\n run('systemctl enable uwsgi@{name}.socket'.format(**app))\n run('systemctl start uwsgi@{name}.socket'.format(**app))\n config = yaml.dump(app['config'], default_flow_style=False)\n if not exists('/etc/uwsgi/apps-enabled/{name}.yaml'.format(**app)):\n run('touch /etc/uwsgi/apps-enabled/{name}.yaml'.format(**app))\n with watch('/etc/uwsgi/apps-enabled/{name}.yaml'.format(**app)) as config_yaml:\n fabtools.require.file('/etc/uwsgi/apps-enabled/{name}.yaml'.format(**app), contents=config)\n if config_yaml.changed:\n run('systemctl stop uwsgi@{name}.service'.format(**app))\n\n@task(default=True)\n@roles('debian-uwsgi')\ndef uwsgi():\n 'Do all the uWSGI things'\n execute(uwsgi_install)\n execute(uwsgi_create_run_uwsgi)\n execute(uwsgi_create_systemd_unit_files)\n execute(uwsgi_create_uwsgi_apps)\n\nUWSGI_SERVICE = \"\"\"\n[Unit]\nDescription=uWSGI server for %i\nAfter=syslog.target\n\n[Service]\nExecStart=/usr/bin/uwsgi \\\\\n --socket=/run/uwsgi/%i.socket \\\\\n --yaml=/etc/uwsgi/apps-enabled/%i.yaml\nKillSignal=SIGQUIT\nType=notify\nStandardOutput=syslog\nStandardError=syslog\nNotifyAccess=all\nUser=www-data\nGroup=www-data\n\"\"\"\n\nUWSGI_SOCKET = \"\"\"\n[Unit]\nDescription=uWSGI socket for %i\n\n[Socket]\nListenStream=/run/uwsgi/%i.socket\nUser=www-data\nGroup=www-data\n\n[Install]\nWantedBy=sockets.target\n\"\"\"\n","sub_path":"debian/uwsgi.py","file_name":"uwsgi.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"239345735","text":"Ivan ={\r\n \"name\": \"ivan\",\r\n \"age\": 34,\r\n \"children\": [{\r\n \"name\": \"vasja\",\r\n \"age\": 12,\r\n },{\r\n \"name\": \"petja\",\r\n \"age\": 10,\r\n }],\r\n}\r\n\r\nDarja ={\r\n \"name\": \"darja\",\r\n \"age\": 41,\r\n \"children\": [{\r\n \"name\": \"kirill\",\r\n \"age\": 21,\r\n },{\r\n \"name\": \"pavel\",\r\n \"age\": 15,\r\n }],\r\n}\r\n\r\nemps = [Ivan, Darja]\r\n\r\nfor k in emps:\r\n for j in k[\"children\"]:\r\n if (j[\"age\"])>18:\r\n print(k[\"name\"])\r\n pass\r\n","sub_path":"LICENSE.md/dict_algs.py","file_name":"dict_algs.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"515749622","text":"from tkinter import *\nfrom tkinter import filedialog\nimport os\nimport shutil\n\n\nextList = [\"nes\", \"fds\"]\n#path = ('/media/hmp/68C628FE738DB200/Jogos/roms/NES')\n#path = ('/home/hmp/NES1')\n\nsuffix_list = ['[', '(']\nsuffix = '[!]'\npos_control = 0\npath =''\n\ndef full_list_generator(path, extlist):\n final_list = []\n files = [arq for arq in os.listdir(path) if os.path.isfile(os.path.join(path, arq))]\n\n for i in range(0, len(extlist)):\n files_extension = [arq for arq in files if\n arq.lower().endswith(\".\" + extlist[i])] # testa se as extenções são validas\n final_list = final_list + files_extension\n final_list.sort()\n return final_list\n\n\ndef dict_gen(filelist):\n all_dict = {}\n filelist.sort()\n arq = \"\"\n for file in filelist:\n for letter in file:\n if letter == '[' or letter == '(' or letter == '.': break\n arq = arq + letter\n if arq.endswith(\" \"):\n arq = arq[0:-1]\n all_dict[arq] = []\n print(len(arq))\n all_dict[arq] = [file for file in filelist if file.startswith(arq) and (file[len(arq)] == ' ' or file[len(arq)] == '.')]\n arq = \"\"\n print(all_dict)\n\n final_dict_rep = {key: all_dict[key] for key in all_dict if len(all_dict[key]) > 1}\n final_dict_single = {key: all_dict[key] for key in all_dict if len(all_dict[key]) == 1}\n print(final_dict_single)\n print(final_dict_rep)\n return final_dict_rep, final_dict_single\n\n\ndef start_org(dict):\n if not os.path.exists(tmppath):\n try:\n os.mkdir(tmppath)\n except:\n print(\"Impossible to create dir\")\n quit()\n print(dict)\n for key, value in dict.items():\n if len(value) <= 1: shutil.copy(path + '/' + value[0], tmppath)\n\n\ndef next_list(dict):\n global pos_control\n try:\n actual_key = list(dict.keys())[pos_control]\n except:\n return print('Finish')\n pos_control = pos_control + 1\n files_lbox.bind('<>', copyselect)\n files_lbox.delete(0, END)\n for value in dict[actual_key]:\n files_lbox.insert(END, value)\n\ndef copyselect(evt):\n value = files_lbox.get(ANCHOR)\n shutil.copy(path + '/' + value, tmppath)\n\n\n# pega todos os arquivos na pasta PATH e salva em file_list\npath = filedialog.askdirectory()\ntmppath = path + '/tmp'\n\nfile_list = full_list_generator(path, extList)\nrepeated_dict, single_dict = dict_gen(file_list)\nroot = Tk()\n\n\nfilesLabel = Label(root, text=\"Files:\", bg=\"red\", fg=\"black\")\nfilesLabel.pack()\nbuttonLabel = Label(root)\nbuttonLabel.pack()\n\nleftFrame = Frame(root)\nleftFrame.pack(side=LEFT, expand=YES)\n\nrightFrame = Frame(root)\nrightFrame.pack(side=RIGHT)\n\nfiles_lbox = Listbox(leftFrame)\nfiles_lbox.pack(fill=BOTH, expand=YES)\n\nstart_button = Button(rightFrame, text=\"start\", command=lambda: start_org(single_dict))\nnext_button = Button(rightFrame, text=\"next\", command=lambda: next_list(repeated_dict))\nstart_button.pack()\nnext_button.pack()\n\n\n# lista os arquivos ao abrir o programa - sera substituido por um navegador de arquivo.\nfor item in file_list:\n files_lbox.insert(END, item)\n# fim da listagem inicial - todas as outras vem do refresh button\n\n#comentario\nroot.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"249488051","text":"import os\nimport glob\nfrom bs4 import BeautifulSoup as BS\n\n\n\"\"\"Globs all the files and places them into a list\"\"\"\ndef glob_file():\n glob_file_list = []\n my_path = r'C:\\Users\\nix\\Desktop\\text_processing\\semester_project\\Holland_data'\n for filename in sorted(glob.glob(os.path.join(my_path, '*.html'))):\n glob_file_list.append(filename)\n return glob_file_list\n\n\n\nfor filename in glob_file():\n with open(filename, 'r', encoding='utf-8') as input_file:\n html_code = input_file.read()\n html_soup = BS(html_code, 'html.parser')\n\n with open(filename.replace('.html', '.txt'), 'w') as txt_file:\n if html_soup is not None:\n for talk_title in html_soup.find_all('html'):\n print(talk_title.title.string, file=txt_file)\n for p in html_soup.find_all('p'):\n text = p.get_text()\n print(text, file=txt_file)\n","sub_path":"LING360/semester_project/gen_conf_speaker_parser.py","file_name":"gen_conf_speaker_parser.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"319544155","text":"\"\"\"\r\nThis module is a VERY BASIC introduction to the Create robot.\r\nWe'll use it to:\r\n -- Help you figure out the mechanics of establishing and using\r\n a Bluetooth connection to the robot.\r\n -- Serve as a basic example.\r\n\r\nAuthors: David Mutchler, Amanda Stouder, Chandan Rupakheti, Katie Dion,\r\n Claude Anderson, Delvin Defoe, Curt Clifton, Matt Boutell,\r\n Dave Fisher and their colleagues. December 2013.\r\n\"\"\"\r\n\r\nimport new_create\r\nimport time\r\n\r\n\r\ndef main():\r\n # ------------------------------------------------------------------\r\n # Set the port to whatever COM number YOUR laptop is using\r\n # for its connection to the BAM on the Create robot.\r\n # Then connect to a Create via that port.\r\n # Put the robot in \"full mode\" so that sensors don't stop the robot.\r\n # ------------------------------------------------------------------\r\n port = 3 # Use YOUR laptop's COM number\r\n robot = new_create.Create(port)\r\n robot.toFullMode()\r\n\r\n # ------------------------------------------------------------------\r\n # Start moving:\r\n # -- left wheel at 30 centimeters per second forwards,\r\n # -- right wheel at 25 centimeters per second forwards.\r\n # (so forward but veering to the right).\r\n # Sleep for 4 seconds (while doing the above motion),\r\n # then stop.\r\n # ------------------------------------------------------------------\r\n robot.driveDirect(30, 25)\r\n time.sleep(4.0)\r\n robot.stop()\r\n\r\n # ------------------------------------------------------------------\r\n # All sensor data is obtained by the getSensor method.\r\n # The Sensors class has constants for all sensor names available.\r\n # ------------------------------------------------------------------\r\n sensor = new_create.Sensors.cliff_front_left_signal\r\n reflectance = robot.getSensor(sensor)\r\n print('Current value of the front left cliff sensor:', reflectance)\r\n\r\n # ------------------------------------------------------------------\r\n # ALWAYS execute the following before your program ends. Otherwise,\r\n # your robot may be left in a funky state and on the NEXT run,\r\n # it might fail to connect or it might run incorrectly.\r\n # ------------------------------------------------------------------\r\n robot.shutdown()\r\n\r\n# ----------------------------------------------------------------------\r\n# If this module is running at the top level (as opposed to being\r\n# imported by another module), then call the 'main' function.\r\n# ----------------------------------------------------------------------\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Session06_Robots_MovingAndSensing/src/m1e_first_robot.py","file_name":"m1e_first_robot.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221734217","text":"from agilent import agilentImage\nfrom data import AgilentImageReader\nimport numpy as np\nimport os\n\n\nfrom tkinter import filedialog as fd\nfrom tkinter import Tk\n\n\nroot = Tk()\nroot.withdraw()\nfolder = fd.askdirectory(title=\"Select folder with all *.dat files\")\nfiles = os.listdir(folder)\n\nprint(folder)\nfor name in files:\n if name.split('.')[-1] == 'dat':\n try:\n path_dat = str(folder) + '/' + str(name)\n\n print(path_dat.split('/')[-1], '-- CONVERTING . . . ')\n\n dat_file = AgilentImageReader(path_dat)\n result = dat_file.read_spectra()\n\n xs, vals, additional = result\n\n meta_dados = np.array(additional.metas)\n\n total = np.concatenate((meta_dados, vals), axis=1)\n\n information = 'X,' + 'Y,' + \\\n str(xs).replace('[', '').replace(']', '').replace(',', ',')\n \n path_save = str(path_dat).replace('.dat', '')\n np.savetxt(f'{path_save}_converted.csv',\n total,\n fmt='%.8f',\n delimiter=',',\n newline='\\n',\n header=f'{information}',\n footer='',\n comments='',\n encoding='UTF-8')\n \n print(path_dat.split('/')[-1],' DONE')\n except:\n print(path_dat.split('/')[-1],' Fail')\n\nprint('Files was converted')","sub_path":"convert_file.py","file_name":"convert_file.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"550927686","text":"# -*- coding: utf-8 -*-\nfrom platinumegg.test.base import ApiTestBase, AppTestError\nfrom platinumegg.lib.opensocial.util import OSAUtil\nfrom platinumegg.test.dummy_factory import DummyType\nfrom platinumegg.app.cabaret.util.scout import ScoutDropItemData\nfrom defines import Defines\nfrom platinumegg.app.cabaret.util.db_util import ModelRequestMgr\nfrom platinumegg.app.cabaret.util.api import BackendApi\nfrom platinumegg.app.cabaret.models.Player import PlayerFriend\n\nclass ApiTest(ApiTestBase):\n \"\"\"レイドフレンド選択(設定).\n \"\"\"\n def setUp(self):\n # Player.\n self.__player0 = self.create_dummy(DummyType.PLAYER)\n self.__player0.friendlimit = 10\n self.__player0.getModel(PlayerFriend).save()\n \n # アイテム.\n itemmaster = self.create_dummy(DummyType.ITEM_MASTER)\n data = ScoutDropItemData.create(Defines.ItemType.ITEM, itemmaster.id, filters={'ptype':Defines.CharacterType.TYPE_001}, rate=10000)\n items = [data.get_dropitem_dict()]\n \n # レイドマスター.\n raidmaster = self.create_dummy(DummyType.RAID_MASTER)\n self.__raidmaster = raidmaster\n \n # ハプニング.\n happeningmaster = self.create_dummy(DummyType.HAPPENING_MASTER, raidmaster.id, items=items)\n self.__happeningmaster = happeningmaster\n \n # ハプニング情報.\n happening = self.create_dummy(DummyType.HAPPENING, self.__player0.id, self.__happeningmaster.id, progress=happeningmaster.execution)\n self.__happening = happening\n \n # レイド.\n raid = self.create_dummy(DummyType.RAID, self.__player0, happeningmaster, happening)\n self.__raid = raid\n \n def addRequest(v_player, o_player):\n model_mgr = ModelRequestMgr()\n BackendApi.tr_add_friendrequest(model_mgr, v_player, o_player)\n model_mgr.write_all()\n model_mgr.write_end()\n \n def addFriend(v_player, o_player):\n model_mgr = ModelRequestMgr()\n BackendApi.tr_add_friend(model_mgr, v_player.id, o_player.id)\n model_mgr.write_all()\n model_mgr.write_end()\n \n self.__o_player = self.create_dummy(DummyType.PLAYER)\n addRequest(self.__player0, self.__o_player)\n addFriend(self.__o_player, self.__player0)\n \n def get_urlargs(self):\n \"\"\"URLでAPIに送る引数.\n \"\"\"\n return u'/set/%d/%d' % (self.__raid.id, self.__o_player.id)\n \n def get_query_params(self):\n return {\n OSAUtil.KEY_OWNER_ID:self.__player0.dmmid,\n }\n \n def check(self):\n model_mgr = ModelRequestMgr()\n cardset = BackendApi.get_raidhelpcard(model_mgr, self.__player0.id, self.__raid.id)\n leader = BackendApi.get_leaders([self.__o_player.id]).get(self.__o_player.id)\n if cardset is None:\n raise AppTestError(u'カードが設定されていない')\n elif leader.id != cardset.id:\n raise AppTestError(u'カードが違う')\n elif cardset.card.uid != self.__o_player.id:\n raise AppTestError(u'ユーザーが違う')\n elif leader.power != cardset.power:\n raise AppTestError(u'パラメータが違う')\n elif leader.card.skilllevel != cardset.card.skilllevel:\n raise AppTestError(u'スキルレベルが違う')\n","sub_path":"src/dprj/platinumegg/test/raidfriendselect/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"504666219","text":"def build_net(imageSize = 64, nChannel = 3, nClasses = 2, n_layers = 4, rate = 6, nz = 300):\n\n\t### Builds the network\n\tinitialValue = 2**(n_layers + rate)\n\n\tgen = InputLayer(shape=(None,nz))\n\tgen = DenseLayer(incoming=gen, num_units=initialValue*4*4)\n\tgen = reshape(incoming=gen, shape=(-1,initialValue,4,4))\n\tfor i in range(n_layers):\n\t\tgen = batch_norm(Deconv2DLayer(incoming=gen, num_filters=int(initialValue/2**(i+1)), filter_size=4, stride=2, nonlinearity=relu, crop=1))\n\t\n\tshape = lasagne.layers.get_output_shape(gen)\n\tgen_outputshape = shape[-1]\n\tif gen_outputshape <= imageSize:\n\t\t#### output_size = strides*(size_input -1) + filtre - 2*pad\n\t\t#### filter = output_size + 2*pad + strides - strides* size_input ---> strides = 1, pad = 1, filter = output_size - input_size + 3 \n\t\tgen = Deconv2DLayer(incoming=gen, num_filters=nChannel, filter_size= imageSize - gen_outputshape + 3, stride=1, nonlinearity=relu, crop=1)\t\t\n\telse:\n\t\t# conv : output_size = floor[(input_size + 2*pad - filter_size)/[stride]] + 1\n\t\t# filterSize = input_size + 2*pad - stride * (output_size - 1)\n\t\tgen = Conv2DLayer(incoming=gen, num_filters= nChannel, filter_size= gen_outputshape + 3 - imageSize,stride=1,pad=1, nonlinearity=relu)\n\n\n\tdis = InputLayer(shape=(None,nChannel,imageSize,imageSize)) ### \n\t\n\tfor i in range(n_layers): ### Will generate a set of convultion layers\n\t\tdis = batch_norm(Conv2DLayer(incoming=dis, num_filters=128*(2**(i)), filter_size=3,stride=2, nonlinearity=lrelu(0.2),pad=2))\n\t\n\tdis = flatten(incoming=dis, outdim = 2)\n\tdis = DenseLayer(incoming=dis, num_units=nClasses, nonlinearity=softmax)\n\t\n\treturn gen, dis","sub_path":"cnn/example_model.py","file_name":"example_model.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"374942194","text":"import glob\nimport re\nimport datetime\n\nfrom sqlalchemy import create_engine, ForeignKey\nfrom sqlalchemy import Column, Date, Integer, String, Float\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, backref\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nimport natsort\n\n#engine = create_engine('sqlite:////home/juho/Dropbox/srk/laulut.db', echo=False)\nengine = create_engine('mysql://root:4udo4ka@localhost:3306/majakka_auth?charset=utf8', echo=False)\nBase = declarative_base()\n\n#awk 'NR==1{sub(/^\\xef\\xbb\\xbf/,\"\")}1' virsi\\ 328\\ nyt\\ kiitos\\ jumalan.txt > virsi\\ 328\\ nyt\\ kiitos\\ jumalan.txt\n\nclass Song(Base):\n \"\"\"Dishes consist of ingredients. \"\"\"\n __tablename__ = \"songs\"\n \n id = Column(Integer, primary_key=True)\n title = Column(String(999)) \n filename = Column(String(299)) \n sav = Column(String(99)) \n san = Column(String(99)) \n added = Column(Date)\n\n def __init__(self, filename, title='', sav='', san='', suomsan=''):\n self.title = title\n self.sav = sav\n self.san = san\n self.filename = filename\n self.suomsan = suomsan\n self.added = datetime.datetime.today().strftime('%Y-%m-%d')\n\n\nclass Verse(Base):\n \"\"\"Ingredients are linked to dishes by the linkid column\"\"\"\n __tablename__ = \"verses\"\n \n id = Column(Integer, primary_key=True)\n content = Column(String(2000)) \n # If you want to clssify ingerdients some way\n versetype = Column(String(2000))\n song_id = Column(Integer, ForeignKey(\"songs.id\"))\n song = relationship(\"Song\", backref=backref(\"verses\", order_by=id))\n \n def __init__(self, content, versetype = 'unspecified' ):\n \"\"\"initialize so that column names don't have to be specified\"\"\"\n self.content = content\n self.versetype = versetype\n\n\n#=====================================================================\n\nif __name__ == \"__main__\":\n Base.metadata.create_all(engine)\n\n songpath = '/home/juho/Dropbox/laulut/*.txt'\n\n Session = sessionmaker(bind=engine)\n session = Session()\n songnames = list()\n\n\n i = 0\n upcount = 0\n for songfile in glob.glob(songpath):\n i += 1\n #strip slashes and file endings from filename\n fname = songfile[songfile.rfind('/')+1:]\n #!lowercase!\n fname = fname[:-4].lower()\n\n songnames.append(fname)\n if not 'laulut.txt' in songfile and not '_laulujen lista.txt' in songfile:\n with open(songfile,'r') as f:\n laulu_raw = f.read()\n #Split if 2 or more consequtive unix line breaks\n verses = list()\n verses = re.split('\\n{2,}',laulu_raw)\n thistitle = verses[0]\n res = None\n res = session.query(Song.filename).filter(Song.filename==fname).first()\n if not res and 'euvonen' not in thistitle and 'suom. san' not in thistitle:\n #If no previous song by this name\n sav = ''\n san = ''\n suomsan = ''\n if \"säv\" in thistitle and \"san\" in thistitle:\n thistitle = input('Varmista laulun nimi: {}\\n>'.format(thistitle))\n sav = input('Sävel:')\n san = input('Sanat:')\n suomsan = input('Suom.sanat:')\n #new song object\n laulu = Song(fname, thistitle,sav,san,suomsan)\n laulu.verses = []\n for verse in verses[1:]:\n laulu.verses.append(Verse(content=verse))\n session.add(laulu)\n upcount += 1\n print('{}/{}'.format(i,len(glob.glob(songpath))), end='\\r')\n session.commit()\n\n #update the list of songs for the web app\n songnames = natsort.natsorted(songnames)\n with open('/home/juho/Dropbox/laulut/laulut.txt','w') as f:\n f.write('\\n'.join(songnames))\n\n\n print('Done. Updated {} new songs.'.format(upcount))\n","sub_path":"songstodb.py","file_name":"songstodb.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"308312887","text":"#!/bin/env python\nimport subprocess\nimport re\nfrom collections import OrderedDict\n\nclass EFIBootMgr:\n def __init__(self):\n self.bootorder, self.entries = self.parse_entries()\n self.mount_points = self.get_mount_points()\n\n def parse_entries(self):\n r = subprocess.run('efibootmgr', shell=True, stdout=subprocess.PIPE, encoding='utf8')\n m = re.search(r'BootOrder:\\s+([0-9A-F,]+)', r.stdout)\n bootorder = m.group(1).split(',')\n entries = {}\n m = re.findall(r'Boot(\\d{4})\\*?\\s+((\\w|[^\\S\\n])+)', r.stdout)\n for bootnum, label, *_ in m:\n entries[bootnum] = label\n return bootorder, entries\n\n def print_entries(self):\n for bootnum in self.bootorder:\n print(f'{bootnum}: {self.entries[bootnum]}')\n for bootnum, label in entries.items():\n if bootnum not in self.bootorder:\n print(f'{bootnum}: {self.entries[bootnum]}')\n\n def delete_entry(self):\n self.print_entries()\n bootnum = input('Enter a boot number')\n if bootnum in entries:\n print(f'efibootmgr --delete-bootnum {bootnum}')\n else:\n print('Invalid boot number')\n\n def set_bootnext(self):\n self.print_entries()\n bootnum = input('Enter a boot number')\n if bootnum in entries:\n print(f'efibootmgr --bootnext {bootnum}')\n else:\n print('Invalid boot number')\n\n def parse_device(self, device):\n if device.startswith('nvme'):\n pattern = r'(.*)p(\\d+)'\n else:\n pattern = r'(.*)(\\d+)'\n m = re.match(pattern, device)\n disk = m.group(1)\n part = m.group(2)\n return disk, part\n\n def create_entry(self):\n efi_file = input('Input the EFI file path: ')\n label = input('Enter the entry label: ')\n for mount_point, device in self.mount_points.items():\n if efi_file.startswith(mount_point):\n disk, part = self.parse_device(device)\n loader = efi_file[len(mount_point):].replace('/', '\\\\')\n print(f\"efibootmgr -c -L {label} -d {disk} -p {part} -l '{loader}'\")\n break\n\n def get_mount_points(self):\n mount_points = {}\n r = subprocess.run('lsblk', shell=True, stdout=subprocess.PIPE, encoding='utf8')\n for line in r.stdout.split('\\n')[2:]:\n xs = line.split()\n if len(xs) == 7:\n device = re.sub(r'[^a-z0-9]', '', xs[0])\n mount_point = xs[-1]\n mount_points[mount_point] = device\n return mount_points\n\n def main(self):\n while True:\n print('''1. Set bootnext.\n2. Delete a boot entry.\n3. Add a boot entry.\n4. Set boot order\n5. Exit''')\n option = input('Enter an option: ')\n if option == '1':\n self.set_bootnext()\n elif option == '2':\n self.delete_entry()\n elif option == '3':\n self.create_entry()\n elif option == '4':\n self.set_bootorder()\n elif option == '5':\n return\n else:\n print('Invalid option.')\n\nif __name__ == '__main__':\n efibootmgr = EFIBootMgr()\n efibootmgr.main()\n","sub_path":"py/efibootmgr.py","file_name":"efibootmgr.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"440537438","text":"import pyrebase\n\nconfig = {\n \"apiKey\": \"AIzaSyBEWe5NAhhwqOVge-kMvQjBUhWnm4U4Yk8\",\n \"authDomain\": \"learnpython-88c3f.firebaseapp.com\",\n \"databaseURL\": \"https://learnpython-88c3f.firebaseio.com\",\n \"projectId\": \"learnpython-88c3f\",\n \"storageBucket\": \"learnpython-88c3f.appspot.com\",\n \"messagingSenderId\": \"132293237205\"\n}\n\nfirebase = pyrebase.initialize_app(config=config)\n\nauth = firebase.auth()\n\nstorage = firebase.storage()\n\n# if __name__ == '__main__':\n# auth.send_password_reset_email(\"namtran09061992@gmail.com\")\n# email = input(\"Please input email\")\n# password = input(\"Please input password\")\n\n# user = auth.create_user_with_email_and_password(email,password)\n#\n# user = auth.sign_in_with_email_and_password(email,password)\n#\n# if user['idToken']:\n# print(auth.get_account_info(user['idToken']))\n# auth.send_email_verification(user['idToken'])\n","sub_path":"practice10/learn_firebase.py","file_name":"learn_firebase.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"506736743","text":"#!/usr/bin/env python\n\n# monitor for EHT observations\n# run from control computer\n# inspired by Helge's start_eht script\n# 2018.04.22 LLB\n\nimport sys\nimport argparse\nfrom subprocess import check_output\nimport xml.etree.ElementTree as ET\nfrom datetime import datetime, timedelta\nfrom time import sleep\nimport glob\n\nschedules = sorted(glob.glob('e?????.xml'), key=lambda x: x[-6:])\nif len(schedules) > 0:\n lastxml = schedules[-1]\n nargs = '?'\nelse:\n lastxml = None\n nargs = 1\n\nparser = argparse.ArgumentParser()\nparser.add_argument('schedule', nargs=nargs, help='xml schedule (from vex2xml)', default=lastxml)\nparser.add_argument('-a', '--alc', help='do alc seconds before scan start time (default 5)',\n nargs='?', const=5., type=float, default=None)\nparser.add_argument('-n', '--newlines', help='put each status report on new line', action='store_true', default=False)\nargs = parser.parse_args()\n\nr2dbes = ['r2dbe1', 'r2dbe2', 'r2dbe3', 'r2dbe4']\nalc = \"/home/oper/bin/alc.py\"\n\ntree = ET.parse(args.schedule)\nroot = tree.getroot()\nif args.newlines:\n preline = '\\n'\nelse:\n preline = 30 * '\\b' + 30 * ' ' + 30 * '\\b'\n\ndef timersleep(until, line='waiting.. '):\n now = datetime.utcnow()\n if now > until:\n return False\n sys.stdout.write(preline)\n while now < until:\n wait = (until - now).total_seconds()\n sys.stdout.write('\\r%s%.0f ' % (line, wait))\n sys.stdout.flush()\n sleep(0.1 + wait % 1.0)\n now = datetime.utcnow()\n return True\n\ndef runalc(r2dbes, line='alc '):\n sys.stdout.write('%s\\r%s' % (preline, line))\n for r2 in r2dbes:\n out = check_output([alc, r2])\n (th0, th1) = (int(a[4:].replace(',','')) for a in out.split('\\n')[2].split()[-2:])\n sys.stdout.write('%d:%d ' % (th0, th1))\n sys.stdout.flush()\n\nfor scan in root.findall(\"scan\"):\n\n name = scan.get('scan_name')\n duration = int(scan.get('duration'))\n source = scan.get('source')\n start = datetime.strptime(scan.get('start_time'), '%Y%j%H%M%S')\n stop = start + timedelta(seconds=duration)\n\n if (args.alc is not None) and timersleep(start - timedelta(seconds=float(args.alc)), line='[%s %s] alc in.. ' % (name, source)):\n runalc(r2dbes, line='[%s %s] alc ' % (name, source))\n timersleep(start, line='[%s %s] starts in.. ' % (name, source))\n timersleep(stop, line='[%s %s] recording.. ' % (name, source))\n\n","sub_path":"automon.py","file_name":"automon.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"116586450","text":"import re\n\nfrom aip import AipOcr\n\nAPP_ID = '23019380'\nAPI_KEY = 'dv4p2h8RhPWH42AZPreN0FLf'\nSECRECT_KEY = 'RzIgq0MoSdKhYFh1XIs1obORAGs6Wl7z'\nEXCLUDE_WORDS = [\n '今日未上',\n '报',\n '代填',\n '今日未上代填',\n '今日未上「代填',\n '研究生',\n '加载完成',\n '今日上代填',\n 'C加载中',\n '确'\n]\nclient = AipOcr(APP_ID, API_KEY, SECRECT_KEY)\n\nclass Student:\n stu_no = ''\n stu_name = ''\n\nif __name__ == '__main__':\n img = open('../image/打卡/20201120-4.jpeg', 'rb').read()\n # ret = client.basicGeneral(img)\n ret = client.basicAccurate(img)\n clear_words = []\n students = []\n clear_words2 = []\n\n next_except = False\n for index, item in enumerate(ret['words_result']):\n words = item['words']\n if index <= 5: continue\n if words in EXCLUDE_WORDS: continue\n if next_except == True:\n clear_words2.append(words)\n next_except = False\n if '研究生' in words:\n words = words.replace('研究生', '')\n clear_words2.append(words)\n next_except = True\n continue\n clear_words.append(words)\n print(words)\n print('')\n\n student = Student()\n for index, word in enumerate(clear_words):\n if (index + 1) % 3 == 0:\n student.stu_no += word\n contains_num = bool(re.search(r'\\d', student.stu_name))\n if contains_num == True:\n # stu_no: 马亮45 stu_name: ZF20212\n tmp_stu_no = student.stu_name\n student.stu_name = student.stu_no[:-2]\n student.stu_no = tmp_stu_no + student.stu_no[-2:]\n print(student.stu_no, student.stu_name)\n students.append(student)\n student = Student()\n if (index + 1) % 3 == 1:\n student.stu_no = word\n if (index + 1) % 3 == 2:\n student.stu_name = word\n for index, word in enumerate(clear_words2):\n if index % 2 == 0:\n # ['钟一钧2F20214', '50']\n student = Student()\n student.stu_no = word[-7:]\n student.stu_name = word[:-7]\n continue\n student.stu_no += word\n if student.stu_no.startswith('2'):\n student.stu_no = student.stu_no.replace('2', 'Z', 1)\n print(student.stu_no, student.stu_name)\n students.append(student)\n student = Student()\n","sub_path":"Spider/PocketLifeSpider/PocketLifeSpider/spiders/buaa_daka_orc_bak.py","file_name":"buaa_daka_orc_bak.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"440928","text":"# coding: utf-8\nimport logging\nimport logging.handlers\n\n# from seafevents.app.config import appconfig\nfrom .db_oper import add_offline_download_record\n\n\ndef OfflineDownloadEventHandler(session, msg):\n elements = msg['content'].split('\\t')\n if len(elements) != 5:\n logging.warning(\"got bad message: %s\", elements)\n logging.debug(\"Expected 4 arguments, found %d.\", len(elements))\n return\n repo_id = elements[1]\n path = elements[2]\n user_name = elements[3]\n url = elements[4]\n\n # add_offline_download_record(appconfig.session_cls(), repo_id, path, user_name)\n add_offline_download_record(session, repo_id, path, user_name, url)\n\n\ndef register_handlers(handlers):\n handlers.add_handler('seahub.stats:offline-file-upload', OfflineDownloadEventHandler)\n","sub_path":"python/seafevents/offline_downloader/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"67591699","text":"__author__ = 'nadeemaslam'\n\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom django.core.mail import EmailMessage\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.core import management\nfrom django.core.management.base import BaseCommand\nfrom casereport.models import CaseReport\nfrom casereport.constants import WorkflowState\n\n\nclass Command(BaseCommand):\n help = 'posting of approved case reports to live site using update solr command'\n\n def handle(self, *args, **options):\n prev_day = datetime.today() - timedelta(1)\n casereports = CaseReport.objects.filter(modified_on__gte=prev_day,\n workflow_state=WorkflowState.LIVE)\n self.reindexsolr()\n for case in casereports:\n self.live_case_mail(case)\n\n def reindexsolr(request):\n management.call_command('update_index', interactive=False)\n\n\n def live_case_mail(self, case):\n Headers = {'Reply-To': settings.SERVER_EMAIL}\n recipient = []\n authorized_recipient = []\n for author in case.authorized_reps.all():\n authorized_recipient.append(str(author))\n for coauthor in case.co_author.all():\n recipient.append(str(coauthor.email))\n message = render_to_string('live_case_email.html', {'recipient': case.co_author.all(),\n 'title': case.title,\n 'id': case.id,\n 'DOMAIN': settings.DOMAIN})\n msg = EmailMessage(settings.CASE_LIVE, message, settings.SERVER_EMAIL, recipient,\n headers=Headers, cc=authorized_recipient, bcc=settings.BCC_LIST)\n msg.content_subtype = \"html\"\n msg.send()\n","sub_path":"casereport/management/commands/live_casereport.py","file_name":"live_casereport.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"528449001","text":"import requests\nfrom TotalScoring import TotalScoring\nfrom requests.exceptions import ConnectionError\nimport json\nimport numpy\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.integer):\n return int(obj)\n elif isinstance(obj, numpy.floating):\n return float(obj)\n elif isinstance(obj, numpy.ndarray):\n return obj.tolist()\n elif isinstance(obj, numpy.bool_):\n return bool(obj)\n else:\n return super(MyEncoder, self).default(obj)\n\nclass connectionHandler():\n \n def __init__(self, config):\n self.config = config\n self.scoring = TotalScoring(self.config)\n \n def login(self, email, password):\n addr = self.config['WIFI']['serverAddress']\n port = self.config['WIFI'].getint('serverPort')\n url = \"http://{}:{}/token\".format(addr, port)\n values = {'email':email, 'password':password}\n r = requests.post(url, data=values)\n return r.text, r.status_code\n \n def addSensor(self, token, name):\n addr = self.config['WIFI']['serverAddress']\n port = self.config['WIFI'].getint('serverPort')\n url = \"http://{}:{}/sensor\".format(addr, port)\n values = {'name':name}\n r = requests.post(url, data=values, headers={'token': token})\n return r.text, r.status_code\n \n def sendMeasurement(self):\n addr = self.config['WIFI']['serverAddress']\n port = self.config['WIFI'].getint('serverPort')\n url = \"http://{}:{}/measurement\".format(addr, port)\n measurement = self.scoring.read()\n measurement = json.dumps(measurement, cls=MyEncoder)\n values = {'measurement': measurement}\n headers = {'token': self.config['WIFI']['token']}\n try:\n r = requests.post(url, headers=headers, data=values)\n except ConnectionError as e:\n print(e)\n return False\n print(r.text)\n return r.status_code == 200\n \n","sub_path":"embedded/connectionHandler.py","file_name":"connectionHandler.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"17277375","text":"'''\ndawere programa romelic ricxvebis masividan amoshlis gameorebul ricxvebs da bolos\ndagitovebs marto unikalur ricxvebs igive tanmimdevrobit rac tavidanve iyo. 3 4 4 5 1 5 -> 3 4 5 1\n'''\n\ndef uniques(nums):\n # print('NUMS: ', nums)\n # uniques = []\n # for i in nums:\n # if i not in uniques:\n # uniques.append(i)\n\n # return uniques\n\n\n print('NUMS: ', nums)\n uniques = []\n for i in nums:\n if not in_uniques(i, uniques):\n uniques.append(i)\n\n return uniques\n\n# NOTE saxeli aralogikuradaa darqmeuli. is_unique logikurad True unda iyos tu Uniquea da ara piriqit.\ndef in_uniques(i, uniques):\n for x in uniques:\n if x == i:\n return True\n return False\n\nprint('UNIQUES: ', uniques([-99,0,0,2,2,4,4]))\nprint('UNIQUES: ', uniques([-99,0,0,22,3,22,4,4,99]))\nprint('UNIQUES: ', uniques([3]))\nprint('UNIQUES: ', uniques([3,-3,-2,3,1,3,4]))\n\n\n","sub_path":"Algorithms2/UniqueNumbers.py","file_name":"UniqueNumbers.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"652712726","text":"#!/usr/bin/env python\n\nimport twitter\nimport config as c\nimport json\nfrom datetime import datetime, timedelta\nfrom flask import Flask, render_template, Markup, request\nfrom werkzeug.contrib.cache import SimpleCache\n\ncache = SimpleCache()\n\napi = twitter.Api(consumer_key=c.consumer_key,\n consumer_secret=c.consumer_secret,\n access_token_key=c.access_token_key,\n access_token_secret=c.access_token_secret)\n\n\napp = Flask(__name__)\n\n@app.template_filter('date')\ndef date(date_string):\n time = datetime.strptime(date_string, '%a %b %d %H:%M:%S +0000 %Y')\n return datetime.strftime(time, '%-d. %-m. %Y')\n\n@app.template_filter('tweet')\ndef tweet(t):\n text = t.text\n if t.urls:\n for url in t.urls:\n expanded = url.expanded_url\n text = text.replace(url.url, '%s' % (expanded, expanded))\n return Markup(text)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/user_timeline')\ndef user_timeline():\n\n screen_name = request.args.get('screen_name', None, type=str)\n count = request.args.get('count', 20, type=int)\n\n cache_id = '%s-%s' % (screen_name, count)\n rv = cache.get(cache_id)\n if rv is None:\n rv = api.GetUserTimeline(screen_name=screen_name, exclude_replies=True, include_rts=False, count=count)\n cache.set(cache_id, rv, timeout=10 * 60)\n\n statuses = rv\n\n # if json is requested first we deliver a json representation of the statuses\n if request.accept_mimetypes.best == 'application/json':\n\n statuses_array = []\n for s in statuses:\n # fix bug in twitter library\n s_dict = s.AsDict()\n s_dict['id_str'] = str(s.id)\n statuses_array.append(s_dict)\n\n return json.dumps(statuses_array), 200, {'Content-Type': 'application/json; charset=utf-8',\n 'Access-Control-Allow-Origin': '*'}\n\n # otherwise we generate and return html\n else:\n\n size = 2\n sliced_statuses = [statuses[i:i+size] for i in range(0, len(statuses), size)]\n\n copies = request.args.get('copies', 1, type=int)\n for i in range(copies - 1):\n sliced_statuses = sliced_statuses + sliced_statuses\n\n html = render_template('user_timeline.html',\n statuses=sliced_statuses,\n screen_name=screen_name,\n count=count)\n return html\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"twitter-printer.py","file_name":"twitter-printer.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519954500","text":"#!/usr/bin/env python3\n# Copyright 2019, Nihon Unisys, Ltd.\n#\n# This source code is licensed under the BSD license. \n\nimport argparse\nimport json\nimport collections\nfrom collections import defaultdict\nimport attr_list\n\nall_attributes = collections.OrderedDict()\n\ndef process(dataset_2019):\n ENE = dataset_2019['ENE']\n title = dataset_2019['title']\n page_id = dataset_2019['page_id']\n if not page_id in all_attributes:\n all_attributes[page_id] = collections.OrderedDict()\n all_attributes[page_id]['ENE'] = ENE\n all_attributes[page_id]['title'] = title\n all_attributes[page_id]['page_id'] = page_id\n all_attributes[page_id]['Attributes_html'] = {att:[] for att in attr_list.attrs[ENE]}\n all_attributes[page_id]['Attributes_text'] = {att:[] for att in attr_list.attrs[ENE]}\n \n attribute = dataset_2019['attribute']\n html_offset = dataset_2019['html_offset']\n text_offset = dataset_2019['text_offset']\n all_attributes[page_id]['Attributes_html'][attribute].append(html_offset)\n all_attributes[page_id]['Attributes_text'][attribute].append(text_offset)\n \ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('input', type=str)\n parser.add_argument('output', type=str)\n parser.add_argument('--split_test', type=float, default=0.90,\n help='start point of test data')\n\n args = parser.parse_args()\n\n with open(args.input) as f:\n for line in f:\n dataset_2019 = json.loads(line)\n process(dataset_2019)\n \n with open(args.output, 'w') as f:\n f.write('{\"entry\":[\\n')\n json_str = []\n for attr in all_attributes.values():\n json_str.append(json.dumps(attr, ensure_ascii=False))\n f.write(',\\n'.join(json_str))\n f.write('\\n]}\\n')\n \n import util\n split_dataset = util.make_split_data(list(all_attributes.values()), split_nums=[args.split_test])\n with open(args.output.replace('.json', '-test.json'), 'w') as f:\n f.write('{\"entry\":[\\n')\n json_str = []\n for attr in split_dataset[1]:\n json_str.append(json.dumps(attr, ensure_ascii=False))\n f.write(',\\n'.join(json_str))\n f.write('\\n]}\\n')\n \nmain()\n","sub_path":"scripts/shinra/shinra2019_to_2018.py","file_name":"shinra2019_to_2018.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537236850","text":"import pinocchio as se3\nfrom pinocchio.robot_wrapper import RobotWrapper\nimport os\n\nclass RobotState:\n def __init__(self):\n filename = str(os.path.dirname(os.path.abspath(__file__)))\n pkg = filename + '/../../Model'\n urdf = pkg + '/jet_description/urdf/dyros_jet_robot.urdf'\n self.robot = RobotWrapper.BuildFromURDF(urdf,[pkg,])\n self.srdf = pkg + '/srdf/dyros_jet_robot.srdf'\n self.model = self.robot.model\n self.data = self.robot.data\n\n def setWorldSE3(self, world):\n self.world = world\n\n def updateKinematics(self, q, qdot):\n self.q = q\n self.qdot = qdot\n self.robot.forwardKinematics(q)\n\n def placement(self, joint_name):\n index = self.model.getJointId(joint_name)\n return self.data.oMi[index]","sub_path":"src/Controller/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"93983905","text":"def solution(skill, skill_trees):\n answer =0\n for i in range(0,len(skill_trees)):\n if(skillCheck(skill,skill_trees[i])):\n answer = answer + 1\n return answer\n\ndef skillCheck(skill,skill_tree):\n cursor = 0\n for i in range(0,len(skill_tree)):\n for j in range(0,len(skill)):\n if(skill_tree[i]==skill[j]):\n if(j == cursor):\n cursor= cursor+1\n else:\n return False\n return True","sub_path":"Programmers/winte2018/skill.py","file_name":"skill.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"284893657","text":"# simple implementation with list\nclass ArrayStack:\n # constructor\n def __init__(self):\n self.stack = []\n\n # check if the stack is empty\n def is_empty(self):\n return len(self.stack) == 0\n\n # peek the top of the stack\n def peek(self):\n # if empty\n if self.is_empty():\n print(\"The stack is empty!\")\n return self.stack[-1] # not empty, peek it\n\n # push value into the stack\n def push(self, value):\n self.stack.append(value)\n \n # pop the top of the stack\n def pop(self):\n # if empty\n if self.is_empty():\n print(\"The stack is empty!\")\n return\n self.stack.pop() # pop if not empty\n\n # size of the stack\n def size(self):\n return len(self.stack)\n \n # output the stack\n def output(self):\n if self.is_empty():\n print(\"stack is empty!\")\n print(\"contents: \"),\n print(self.stack[::-1])\n print\n\n# ============================\n# testing the stack class\n# ============================\n\nprint(\"\\nList implementation of stack!\\n\")\n\n# create a new ArrayStack object\nstack = ArrayStack()\nprint(\"- New ArrayStack object created\")\nstack.output()\n\n# push value into the stack\nstack.push(1)\nstack.push(2)\nstack.push(3)\nprint(\"- New values are pushed into the stack\")\nstack.output()\n\n# peek value\nprint(\"- Peek the top of the stack: \" + str(stack.peek()))\nprint\n\n# pop the top of the stack\nstack.pop()\nprint(\"- Pop the top of the stack\")\nstack.output()\n\n# get size of the stack\nprint(\"- Size of the stack: \" + str(stack.size()))\nprint","sub_path":"Data Structures/4. Stack/arrayStack.py","file_name":"arrayStack.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"219765537","text":"from selenium.webdriver import Firefox\nfrom selenium.webdriver.common.by import By\nfrom minutos import colors_bets\nimport datetime\nimport time\nimport pyodbc\n\n\nserver = 'DESKTOP-JJO8LEQ;'\ndatabase = 'scrapper_blaze;'\n\n\ndef sqlconnect():\n try:\n return pyodbc.connect('DRIVER={SQL Server};'\n 'SERVER='+server+';'\n 'DATABASE='+database+';'\n 'Trusted_Connection=yes')\n except:\n print (\"Conexão falhou. Reveja os parametros passados.\")\n\n\ndef insert(color, number, time):\n mydb = sqlconnect()\n query = mydb.cursor()\n query.execute(\"SELECT id FROM rolldice_tbo WHERE number = %s AND datetime = '%s'\" % (number, str(time)))\n result = query.fetchone()\n print(result)\n\n if result == None:\n sql = \"INSERT INTO rolldice_tbo (color,number,datetime) VALUES (?, ?, ?)\"\n val = (color, number, str(time))\n query.execute(sql, val)\n mydb.commit()\n\n elif result == None:\n sql = \"INSERT INTO rolldice_tbo (color,number,datetime) VALUES (?, ?, ?)\"\n val = (color, number, str(time))\n query.execute(sql, val)\n mydb.commit()\n\n\n\nbrowser = Firefox(executable_path=r\"C:\\selenium\\geckodriver.exe\")\nbrowser.get(\"https://blaze.com/pt/games/double\")\nfirst = True\n\n\ntime.sleep(3)\nwhile True:\n roulette_timer = (By.CSS_SELECTOR, \"#roulette-timer\")\n roulette = browser.find_element(*roulette_timer).get_attribute('innerHTML')\n qtd = len(roulette.split('\"time-left\">Blaze Girou '))\n\n if qtd == 2:\n time.sleep(3)\n colors_bets()\n if first:\n time.sleep(2)\n locator = (By.CSS_SELECTOR, \".roulette-previous\")\n numbers = (browser.find_element(*locator).get_attribute('innerHTML'))\n now = datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')\n\n numbers = numbers.split('class=\"roulette-tile\">

'))[0]\n if color == \"white\":\n number = 0\n else:\n number = (num.split('class=\"number\">'))\n number = number[1].split(\"
\")\n number = number[0]\n print(color, number, now)\n first = False\n else:\n first = True\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"293358155","text":"from django.db import models\nfrom django.core.validators import RegexValidator\n\n\nclass Application_form_model(models.Model):\n user_name = models.CharField(\n 'Ім\\'я',\n max_length=30,\n null=True,\n error_messages={'required': 'Custom message'},\n )\n# phone_regex = RegexValidator(\n# regex=r'^\\+?1?\\d{9,12}$',\n# message=\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\",\n# code='invalid_phone_number'\n# )\n phone_number = models.CharField(\n 'Телефон (не обов\\'язково)',\n# validators=[phone_regex],\n max_length=17,\n blank=True\n )\n user_email = models.EmailField(\n 'Електронна пошта',\n max_length=254,\n null=True\n )\n user_question = models.TextField(\n 'Зміст запитання',\n max_length=1000,\n null=True\n )\n\n files = models.FileField(\n 'Файли архівом (до 15 мб)',\n max_length=300,\n upload_to='file_to_question',\n blank=True\n )\n\n def __str__(self):\n return self.user_name\n\n class Meta:\n verbose_name = 'Запитання з сайту'\n verbose_name_plural = 'Запитання з сайту'\n# Create your models here.\n","sub_path":"application_form/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"183675773","text":"\ndef isugly():\n\tnum=int(input(\"please enter :\"))\n\tif num == 0:\n\t\tprint(False)\n\tfor i in [2, 3, 5]:\n\t\twhile num % i == 0:\n\t\t\tnum /= i\n\tprint(num == 1)\nwhile True:\n\tisugly()","sub_path":"ugly.py","file_name":"ugly.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411209558","text":"import pickle as pkl \nimport pytest \nimport cv_plots as cvp \nimport build_test_cases as cases \n\n## test case 0 ##\npkl_case0 = cases.BuildPickles(shape=(5,3), rand_state=5)\npkl_case0.pickle_each_implementation(prefix='case0') #test\ncase0_truth = pkl_case0.imps_results #truth\ncase0_mtx_truth = pkl_case0.clean_mtx_truth\ncase0_filepaths = [f'data\\\\test-data\\\\case0_implementation_{i}.pickle' for i in range(len(case0_truth))]\n# order = [f'impl{i}' for i in range(3)]\ncase0_results = cvp.ResultsToDF(case0_filepaths, order=pkl_case0.impl_order, parameter_list=range(pkl_case0.shape[0]))\n# shape[0] represents the number of values in the parameter list\n\ndef test_models_results_list_case0():\n assert case0_truth[0] == case0_results._model_results_list[0] \n assert case0_truth[1] == case0_results._model_results_list[1]\n assert case0_truth[2] == case0_results._model_results_list[2]\n\ndef test_model_mtx_list_case0():\n for mtx, truth in zip(case0_results._model_mtx_list, case0_mtx_truth):\n #elementwise comparison\n assert (mtx == truth).all()\n\n\n## test case 1 ##\ncase1_filepaths = [f'data\\\\test-data\\\\case1_implementation_{i}.pickle' for i in range(3)]\norder = [f'impl_{i}' for i in range(3)]\ncase1_results = cvp.ResultsToDF(case1_filepaths, order=order, parameter_list=cvp.cv.ntree_list) \n\ndef test_models_results_list_case1():\n #written a little differntly bc using data not from build \n with open('data\\\\test-data\\\\case1_implementation_0.pickle', 'rb') as f:\n imp_0 = pkl.load(f)\n assert imp_0 == case1_results._model_results_list[0]\n\n with open('data\\\\test-data\\\\case1_implementation_1.pickle', 'rb') as f:\n imp_1 = pkl.load(f)\n assert imp_1 == case1_results._model_results_list[1]\n\n with open('data\\\\test-data\\\\case1_implementation_2.pickle', 'rb') as f:\n imp_2 = pkl.load(f)\n assert imp_2 == case1_results._model_results_list[2]\n\n@pytest.mark.skip(reason='Don\\'t have truth data ready')\ndef test_model_mtx_list_case1():\n pass\n\n\n## test case 2 ##\npkl_case2 = cases.BuildPickles(shape=(10,5), rand_state=12)\npkl_case2.pickle_each_implementation(prefix='case2')\ncase2_truths = pkl_case2.imps_results\ncase2_mtx_truth = pkl_case2.clean_mtx_truth\ncase2_filepaths = [f'data\\\\test-data\\\\case2_implementation_{i}.pickle' for i in range(5)]\ncase2_results = cvp.ResultsToDF(case2_filepaths, order=pkl_case2.impl_order, parameter_list=range(pkl_case2.shape[0]))\n\ndef test_models_results_list_case2():\n for i in range(pkl_case2.shape[1]):\n assert case2_truths[i] == case2_results._model_results_list[i]\n \ndef test_model_mtx_list_case2():\n for mtx, truth in zip(case2_results._model_mtx_list, case2_mtx_truth):\n assert (mtx == truth).all()\n\nif __name__ == '__main__':\n import numpy as np \n print(case0_truth)\n print('+++++++++')\n print(case0_results._model_mtx_list)\n","sub_path":"test_ResultsToDF.py","file_name":"test_ResultsToDF.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"356097909","text":"from quantumcore.storages import AttributeMapper\nimport copy\n\nclass ContentType(AttributeMapper):\n \"\"\"base type for content types. A content type is mostly a dictionary and\n we use this class to define it's attributes\"\"\"\n\n def __init__(self, _id, **data):\n \"\"\"initialize a content type\"\"\"\n\n default = {\n '_id' : _id, # required\n 'name' : u'', # human readable name\n 'description' : u'', # human readable description\n 'contains' : [], # list of content type it is allowed to contain or 'all', empty means none\n 'fields' : [('title', 'string')], # list of fields and types this type understands\n 'required_fields' : ['title'], # list of required fields\n 'reprs' : ['default', 'contents'], # list of representations\n 'default_repr' : 'default', # default representation\n 'mgr' : None, # instance of the responsible content manager \n 'cls' : None, # type implementation\n }\n\n d = copy.copy(default)\n d.update(data)\n self.update(d)\n @property\n def json(self):\n \"\"\"return a JSON compatible representation\"\"\"\n return {\n '_id' : self._id,\n 'name' : self.name,\n 'description' : self.description,\n }\n\nclass ContentTypeManager(AttributeMapper):\n \"\"\"a content type manager which is simply a dictionary\"\"\"\n\n def add(self, ct):\n \"\"\"add a content type\"\"\"\n self[ct._id] = ct\n\n @property\n def json(self):\n \"\"\"return a list of JSONified types\"\"\"\n return [t.json for t in self.values()]\n\n","sub_path":"quantumlounge/content/contenttypes.py","file_name":"contenttypes.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615705600","text":"'''\nCreated on 04/09/2014\n\n@author: algarra\n'''\n\nimport sys\nimport numpy as np\nimport datetime\nimport copy\nimport pickle\nimport sigmund_GLOBALS as sgGL\nimport os\n\nclass SimulationConditions():\n def __init__(self, filename ='', year_periods = '', hay_foodweb = False, \n hay_superpredadores = False ,\n data_save='', dirtrabajo ='', direntrada='', dirsal='',\n eliminarenlaces=0, pl_ext=[], pol_ext=[], output_suff ='', \n fichreport = '', com = '', algorithm = 'MoMutualism', \n plants_blossom_prob = 1.0, plants_blossom_sd = 0.01, \n plants_blossom_type = 'Binary', blossom_pert_list = '', \n verbose = True, exit_on_extinction = False,\n N0plants='', N0pols='', release='', Bssvar_data = ''):\n self.filename = filename\n self.year_periods = year_periods \n self.hay_foodweb = hay_foodweb\n self.hay_superpredadores = hay_superpredadores\n self.data_save = data_save\n self.dirtrabajo = dirtrabajo\n self.direntrada = direntrada\n self.dirsal = dirsal\n self.eliminarenlaces = eliminarenlaces\n self.pl_ext = copy.deepcopy(pl_ext)\n self.pol_ext = copy.deepcopy(pol_ext)\n self.output_suff = output_suff\n self.fichreport = fichreport\n self.com = com\n self.algorithm = algorithm\n self.plants_blossom_prob = plants_blossom_prob\n self.plants_blossom_sd = plants_blossom_sd\n self.plants_blossom_type = plants_blossom_type\n self.blossom_pert_list = blossom_pert_list\n self.verbose = verbose\n self.exit_on_extinction = exit_on_extinction\n self.N0plants = N0plants\n self.N0pols = N0pols\n self.release = release\n self.Bssvar_data = Bssvar_data\n \n def write2file(self,filesim):\n with open(filesim, 'wb') as outfile:\n pickle.dump(self, outfile, pickle.HIGHEST_PROTOCOL)\n \n \n\nclass MaximaValues():\n def __init__(self,maxa_individuos, maxb_individuos, max_reff, min_reff,\\\n max_requs, min_requs):\n self.maxa_individuos = maxa_individuos\n self.maxb_individuos = maxb_individuos\n self.max_reff = max_reff\n self.min_reff = min_reff\n self.max_requs = max_requs\n self.min_requs = min_requs\n \nclass BlossomVariability():\n def __init__(self, Bssvar_period, Bssvar_sd, Bssvar_modulationtype_list,\n Bssvar_species):\n self.Bssvar_period = Bssvar_period\n self.Bssvar_sd = Bssvar_sd\n self.Bssvar_modulationtype_list = Bssvar_modulationtype_list\n self.Bssvar_species = Bssvar_species\n \nclass SimulationReturnValues():\n def __init__(self, Nindividuals_a, Nindividuals_b, Nindividuals_c, ra_eff, \n rb_eff, ra_equs, rb_equs, mval, systemextinction, \n pBssvar_species, network_growth_power):\n self.systemextinction = systemextinction\n self.Nindividuals_a = Nindividuals_a\n self.Nindividuals_b = Nindividuals_b\n self.Nindividuals_c = Nindividuals_c\n self.ra_eff = copy.deepcopy(ra_eff)\n self.rb_eff = copy.deepcopy(rb_eff)\n self.ra_equs = copy.deepcopy(ra_equs)\n self.rb_equs = copy.deepcopy(ra_equs)\n self.maxminval = mval\n self.pBssvar_species = copy.deepcopy(pBssvar_species)\n self.network_growth_power = network_growth_power\n\nclass ExternalPerturbationConditions():\n def __init__(self,nperpl, inicioextplantas, periodoextpl, spikepl, \n nperpol, inicioextpol, periodoextpol, spikepol):\n self.nperpl = nperpl\n self.inicioextplantas = inicioextplantas\n self.periodoextpl = periodoextpl\n self.spikepl = spikepl\n self.nperpol = nperpol\n self.inicioextpol = inicioextpol\n self.periodoextpol = periodoextpol\n self.spikepol = spikepol\n \nclass CanalInfo():\n \"\"\" CanalInfo is a wrapper of status information channels such as stdout and\n the report file \"\"\"\n def __init__(self, device, newlinestr):\n self.device = device\n self.newline = newlinestr\n def write(self, texto):\n self.device.write(texto + self.newline)\n def close(self):\n self.device.close()\n \ndef inform_user(canalesinfo, texto):\n \"\"\" (list of CanalInfo, str) -> NoneType\n\n Execution status information for human user\n \n >>> ldevices = []\n >>> ldevices.append(CanalInfo(sys.stdout,'\\\\n'))\n >>> inform_user(ldevices, 'Info for you')\n Info for you\n \"\"\"\n [canal.write(texto) for canal in canalesinfo]\n \ndef close_info_channels(canalesinfo):\n [canal.close() for canal in canalesinfo]\n \ndef open_info_channels(verbose, fichreport, mode):\n ldev = []\n lfich = []\n if verbose: \n sout = CanalInfo(sys.stdout, '\\n')\n ldev.append(sout)\n if len(fichreport) > 0:\n frep = CanalInfo(open(fichreport, mode, encoding='utf-8'), '
')\n ldev.append(frep)\n lfich.append(frep)\n return ldev, lfich\n\ndef dlmreadlike(inputfile, direntrada):\n try:\n data = open(direntrada + inputfile)\n mtx_input = []\n for each_line in data:\n try:\n mtx_input.append(each_line.strip().split('\\t'))\n except ValueError:\n pass\n data.close()\n return(mtx_input)\n except IOError:\n print('The datafile %s is missing!' % inputfile)\n return(-1)\n \ndef dlmwritelike(input_file,sim_cond, nperiod, Nin, onecolumn = False):\n dsal = sim_cond.dirsal.replace('\\\\', '/')\n nsal = sgGL.OUTPUTDATA_PREFIX + input_file + '_' + sim_cond.output_suff + '_'+\\\n str(nperiod) + '.txt'\n print (\"Output file %s\" % dsal + nsal)\n \n if not os.path.exists(dsal):\n os.makedirs(dsal)\n \n salida = open(dsal + nsal, 'w', encoding='utf-8') \n for linea in Nin:\n if onecolumn:\n y = \"%.012f\" % linea\n salida.write(y + '\\n')\n else:\n for i in range(len(linea) - 1):\n y = \"%.012f\" % linea[i]\n salida.write(y + ',')\n salida.write(str(linea[-1]) + '\\n');\n salida.close()\n return(nsal)\n\ndef read_simulation_matrix(filename, dirtrabajo, direntrada, str_guild, \n name_guild, N0_guild, lfich_inf = ''): \n filename_x = filename + str_guild\n dt = dirtrabajo.replace('\\\\', '/')\n inform_user(lfich_inf, name_guild + \" matrix: \" +\\\n filename_x + \"\")\n l_minputchar_x = dlmreadlike(filename_x, direntrada)\n ''' If N0_guild provided by command line'''\n if len(N0_guild) > 0:\n l_minputchar_x[-sgGL.LINES_INFO_MATRIX][0] = int(N0_guild)\n minputchar_x = np.array(l_minputchar_x, dtype=float)\n try:\n nrows_x = len(minputchar_x)\n except:\n print(\"INPUT FILE BAD FORMAT\")\n ncols_x = len(minputchar_x[0])\n numspecies_x = ncols_x\n return numspecies_x, minputchar_x, nrows_x, ncols_x\n\ndef find_max_values(Nindividuals_a, Nindividuals_b, ra_eff, rb_eff, ra_equs, \n rb_equs): \n mval = MaximaValues(np.max(Nindividuals_a),np.max(Nindividuals_b),\n max(np.max([ra_eff]), np.max([rb_eff])),\n min(np.min([ra_eff]), np.min([rb_eff])),\n max(np.max([ra_equs]), np.max([rb_equs])),\n min(np.min([ra_equs]), np.min([rb_equs])) )\n return(mval)\n\n\ndef create_list_species_affected(speciestext):\n if (str(speciestext).upper() == 'ALL'):\n return(list(['ALL']))\n auxspec = speciestext.split(',')\n auxlspec = []\n for numspe in auxspec:\n if len(numspe) == 1:\n auxlspec.append([int(numspe)])\n else:\n rango = numspe.split(':')\n auxlspec.append([j for j in range(int(rango[0]), 1+int(rango[-1]))])\n listb = []\n for subla in auxlspec:\n for j in list(subla):\n listb.append(j) \n listb = sorted(set(listb)) \n return listb\n\ndef start_report(ldev_inf, filename, com, year_periods, algorithm, release, \n hay_foodweb):\n inform_user(ldev_inf, \\\n \"Binomial simulated mutualistic interaction. Input file: %s\" % (filename))\n inform_user(ldev_inf, 60 * '=')\n if len(com) > 0: inform_user(sgGL.ldev_inf, \"User Comment: %s\" % com)\n inform_user(ldev_inf, 'Span: %d years' % (year_periods))\n inform_user(ldev_inf, 'ALGORITHM: ' + algorithm)\n inform_user(ldev_inf, 'Release ' + ((\"%.02f\") % (release / 100)))\n if hay_foodweb:\n inform_user(ldev_inf, 'Food web superimposed') \n\ndef create_file_suffix(algorithm,output_suffix,ciclos):\n return('_'.join([algorithm,output_suffix,str(int(ciclos))]) )\n\ndef create_fichreport_name(reportpath,input_fname,file_suffix):\n return reportpath + 'rep_' + input_fname +'_'+file_suffix+ '.html'\n\ndef create_results_filename(sim_cond,string_file):\n return sim_cond.filename + '_' + sim_cond.algorithm + string_file\n\ndef end_report(ldev_inf, lfich_inf, sim_cond, tfin, tinic, periods, \n Nindividuals_a, ra_eff, ra_equs,\n Nindividuals_b, rb_eff, rb_equs, network_growth_power, Nindividuals_c):\n# network_growth_power = np.average(list(np.extract(Nindividuals_a[0,]>0,ra_equs[1,]))+\\\n# list(np.extract(Nindividuals_b[0,]>0,rb_equs[1,])))\n inform_user(ldev_inf, \"Initial Network growth power %.03f\" % network_growth_power[1] ) \n inform_user(ldev_inf, \"Elapsed time %.02f s\" % (tfin - tinic))\n speriodos = str(int(periods / sgGL.DAYS_YEAR))\n with open(sim_cond.dirsal+'/'+create_results_filename(sim_cond,\"_network_growth_power.txt\"), \"wt\") as out_file:\n out_file.write(\"%.03f\" % network_growth_power[1])\n if (sim_cond.data_save == 1):\n nsal = dlmwritelike(create_results_filename(sim_cond,\"_a_populations\"), \n sim_cond,speriodos, Nindividuals_a)\n rsal = dlmwritelike(create_results_filename(sim_cond,\"_a_rs\"),\n sim_cond,speriodos, ra_eff)\n requsal = dlmwritelike(create_results_filename(sim_cond,\"_a_requs\"), \n sim_cond,speriodos, ra_equs)\n inform_user(lfich_inf, \"Plant populations data: \" + nsal + \"\")\n inform_user(lfich_inf, \"Plant effective rates data: \" + rsal + \"\")\n inform_user(lfich_inf, \"Plant equivalent rates data: \" + requsal + \"\")\n nsal = dlmwritelike(create_results_filename(sim_cond,\"_b_populations\"), \n sim_cond,speriodos, Nindividuals_b)\n rsal = dlmwritelike(create_results_filename(sim_cond,\"_b_rs\"), \n sim_cond,speriodos, rb_eff)\n requsal = dlmwritelike(create_results_filename(sim_cond,\"_b_requs\"), \n sim_cond,speriodos, rb_equs)\n inform_user(lfich_inf, \"Pollinators evolution data: \" + nsal + \"\")\n inform_user(lfich_inf, \"Pollinators effective rates data: \" + rsal + \"\")\n inform_user(lfich_inf, \"Pollinators equivalent rates data: \" + requsal + \"\")\n network_growth_powersal = dlmwritelike(create_results_filename(sim_cond,\"_npg\"), \n sim_cond,speriodos, network_growth_power, onecolumn = True)\n inform_user(lfich_inf, \"Network growth power: \" + network_growth_powersal + \"\")\n if sim_cond.hay_foodweb:\n nsal = dlmwritelike(create_results_filename(sim_cond,\"_c\"), \n sim_cond,speriodos, Nindividuals_c)\n inform_user(lfich_inf, \n \"Predators evolution data: \" + nsal + \"
\")\n inform_user(ldev_inf, '')\n inform_user(ldev_inf, 'Created %s' % datetime.datetime.now())\n close_info_channels(lfich_inf)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()","sub_path":"src/pak_tfm/sigmund_common.py","file_name":"sigmund_common.py","file_ext":"py","file_size_in_byte":12539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625087159","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nexecute the unittest file in project root directory.\n\"\"\"\nimport sys\nsys.path.insert(0, r\"../actlet\")\n\nimport unittest\n\nimport pandas as pd\n\nfrom actlet.data import *\nfrom actlet.storage import *\nfrom actlet.storage.dbtable_storage import *\nimport actlet.storage.facade as sfd\nfrom sqlalchemy import create_engine\n\nmysql_db_url = create_mysql_dburl(\"localhost\", \"abc\", \"abc\", \"123456\", port = 8866)\nengine = create_engine(mysql_db_url)\n\n#sql_yueyuefa = \"\" \\\n#\" select cp.id, cp.uid, cp.corp, cp.status, cp.type, cp.fund, cp.refund, cp.paidfund, cp.service, cp.paidservice, cp.penalty, cp.paidpenalty, cp.paytime, cp.expiredate, cp.period, cp.applyuid from credit_payment cp;\"\n# sql_yueyuefa = \"\" \\\n# \" select *, (t1.not_paidfund + t1.not_paidservice + t1.not_paidpenalty) as not_sum from (\" \\\n# \" select cp.id, cp.uid, cp.corp, cp.status, cp.type, \" \\\n# \" \tcp.fund, cp.refund, cp.paidfund, cp.service, \" \\\n# \" cp.paidservice, cp.penalty, \" \\\n# \" cp.paidpenalty, cp.paytime, cp.expiredate, \" \\\n# \" cp.period, cp.applyuid ,\" \\\n# \" cp.clearofftime,\" \\\n# \" (cp.fund - cp.paidfund - cp.refund) as not_paidfund,\" \\\n# \" (cp.service - cp.paidservice) as not_paidservice,\" \\\n# \" (cp.penalty - cp.paidpenalty) as not_paidpenalty,\" \\\n# \" case cp.status\" \\\n# \" \t\twhen 1 then 0\" \\\n# \" when 2 then 0\" \\\n# \" when 3 then floor((UNIX_TIMESTAMP(cp.clearofftime) - UNIX_TIMESTAMP(cp.expiredate)) / (60*60*24))\" \\\n# \" when 4 then -1\" \\\n# \" else null\" \\\n# \" \tend as expired_days\" \\\n# \" from credit_payment cp) t1 \" \\\n#\" where t1.status = 4\";\n\nsql_yueyuefa = \"\" \\\n\" select full_table.*, \" \\\n\" \t\t(full_table.not_paidfund + full_table.not_paidservice + full_table.not_paidpenalty) as not_sum, \" \\\n\" \t\tacci.acct_name \" \\\n\" from \" \\\n\" ( \" \\\n\" \t(select t1.*, cpm.fund as fis_fund, cpm.optime as fis_optime from \" \\\n\" \t\t(select cp.id, cp.uid, cp.corp, cp.status, cp.type, \" \\\n\" \t\t\tcp.fund, cp.refund, cp.paidfund, cp.service, \" \\\n\" \t\t\t cp.paidservice, cp.penalty, \" \\\n\" \t\t\t cp.paidpenalty, cp.paytime, cp.expiredate, \" \\\n\" \t\t\t cp.period, cp.applyuid , \" \\\n\" \t\t\t cp.clearofftime, \" \\\n\" \t\t\t (cp.fund - cp.paidfund - cp.refund) as not_paidfund, \" \\\n\" \t\t\t (cp.service - cp.paidservice) as not_paidservice, \" \\\n\" \t\t\t (cp.penalty - cp.paidpenalty) as not_paidpenalty, \" \\\n\" \t\t\t case cp.status \" \\\n\" \t\t\t\twhen 1 then 0 \" \\\n\" \t\t\t\t when 2 then 0 \" \\\n\" \t\t\t\t when 3 then floor((UNIX_TIMESTAMP(cp.clearofftime) - UNIX_TIMESTAMP(cp.expiredate)) / (60*60*24)) \" \\\n\" \t\t\t\t when 4 then -1 \" \\\n\" \t\t\t\t else null \" \\\n\" \t\t\tend as expired_days \" \\\n\" \t\tfrom yueyuefa.credit_payment cp) t1 \" \\\n\" \tleft join yueyuefa.credit_payment_map cpm on t1.id = cpm.creditid) \" \\\n\" ) \" \\\n\" full_table \" \\\n\" left join yueyuefa.ods_fc_acct_info acci on full_table.uid = acci.acct_id \"\n\nresult = engine.execute(text(sql_yueyuefa), {})\nret_all = result.fetchall()\n#first = ret_all[:5]\n#print(first)\n\ndt_zhouzhouzhuan = DataTable(\"table_zhouzhouzhuan\",\n\tDataColumn(name = \"id\", caption = \"信用加款流水号\"),\n\tDataColumn(name = \"acct_name\", caption = \"账户名称\"),\n\tDataColumn(name = \"uid\", caption = \"账户ID\"),\n\tDataColumn(name = \"corp\", caption = \"所属分公司\"),\n\tDataColumn(name = \"status\", caption = \"当前支付状态\"),\n\tDataColumn(name = \"type\", caption = \"信用支付属性\"),\n\tDataColumn(name = \"fund\", caption = \"信用加款金额\"),\n\tDataColumn(name = \"refund\", caption = \"信用退款金额\"),\n\tDataColumn(name = \"paidfund\", caption = \"已还信用款额\"),\n\tDataColumn(name = \"not_paidfund\", caption = \"未还信用款额\"),\n\tDataColumn(name = \"service\", caption = \"手续费\"),\n\tDataColumn(name = \"paidservice\", caption = \"已还手续费\"),\n\tDataColumn(name = \"not_paidservice\", caption = \"未还手续费\"),\n\tDataColumn(name = \"penalty\", caption = \"违约金\"),\n\tDataColumn(name = \"paidpenalty\", caption = \"已还违约金\"),\n\tDataColumn(name = \"not_paidpenalty\", caption = \"未还违约金\"),\n\tDataColumn(name = \"not_sum\", caption = \"欠款总额\"),\n\tDataColumn(name = \"paytime\", caption = \"信用加款时间\"),\n\tDataColumn(name = \"expiredate\", caption = \"还款截止时间\"),\n\tDataColumn(name = \"period\", caption = \"授信账期\"),\n\tDataColumn(name = \"expired_days\", caption = \"逾期天数\"),\n\tDataColumn(name = \"applyuid\", caption = \"申请客服\"),\n\tDataColumn(name = \"fis_fund\", caption = \"还款金额\"),\n\tDataColumn(name = \"fis_optime\", caption = \"还款时间\"))\n\nfor row in ret_all:\n\tdt_zhouzhouzhuan.append(dict(row))\n\nprint(len(dt_zhouzhouzhuan))\n\nsfd.write_file(r\"D:\\zhouzhouzhuan.xlsx\", data = dt_zhouzhouzhuan, sheetIndex = 0, force = True, overwrite=True)\n\n# es_yueyuefa = sfd.create_file(r\"D:\\yueyuefa.xlsx\", sheetIndex = 0, force = True)\n# if es_yueyuefa.exists_file():\n\t# es_yueyuefa.remove()\n# es_yueyuefa.write(data = dt_yueyuefa)\n","sub_path":"tests/storage/export_mysql_zhouzhouzhuan.py","file_name":"export_mysql_zhouzhouzhuan.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"128358036","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 9 15:22:17 2018\n\n@author: ahmedosman\n\"\"\"\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg \nfrom matplotlib.figure import Figure\n#from matplotlib import pyplot as plt\n#import matplotlib.backend_bases\n#from PIL import Image\nimport matplotlib.image as mpimg\n#import matplotlib.cm as cm\nfrom tkinter import *\n#import tkinter as tk\nimport skimage.io\nfrom skimage.io import imread\nfrom skimage import io, color\n\n \nroot=Tk()\nroot.title(\"GUI\")\nroot.geometry(\"1000x500\")\nfpathentered=StringVar()\n\ndef displayimage():\n \n def clear(): \n canvas.get_tk_widget().destroy()\n \n txt=fpathentered.get()\n fpath=str(txt)\n img=imread(fpath)\n img_gray=color.rgb2gray(img)\n f = Figure()\n a = f.add_subplot(111)\n a.imshow(img_gray)\n canvas = FigureCanvasTkAgg(f, master=root)\n canvas.show()\n canvas.get_tk_widget().pack(side=\"top\", fill=\"both\", expand=1)\n canvas._tkcanvas.pack(side=\"top\", fill=\"both\", expand=1)\n \n button3=Button(root, text=\"Delete\", width=15, command=clear)\n button3.grid(row=20)\n \ndef showfilepath():\n s=fpathentered.get()\n filepath=str(s)\n #label2= Label(root, text=\"The file path entered is \" + txt + \"\\n\")\n #label2.pack()\n filepathdisplay.insert(0.0, \"The file path entered is \" + filepath + \"\\n\")\n \ndef diagnosis():\n p=fpathentered.get() \n ipath=str(p)\n print(\"the file path is \", p)\n return p\n\ndef displaystring():\n \n q=fpathentered.get()\n i=str(q)\n filepathdisplay1.insert(0.0, \"The skin lesion is \" + i + \"\\n\")\n\ndef closewindow():\n root.destroy()\n exit()\n \nlabel=Label(root, text=\"Skin Disease Classification System\")\nlabel.config(font=(\"Courier\", 20))\nlabel.grid(row=0)\n\nlabel1=Label(root,text=\"Enter file path of image:\", bg=\"white\", fg=\"black\", font=\"none 12 bold\")\nlabel1.grid(row=1)\n\n#enter text in entry box\n\nfilepathentry=Entry(root,width=20, bg=\"white\", textvariable=fpathentered)\nfilepathentry.grid(row=2)\n\nbutton = Button(root, text=\"Show Entry\", command=showfilepath)\nbutton.grid(row=3)\n \nbutton1=Button(root, text=\"Display Image\", width=14, command=displayimage)\nbutton1.grid(row=4 )\n\nbutton2=Button(root, text=\"Exit\", width=14, command=closewindow)\nbutton2.grid(row=5)\n\n#button3=Button(root, text=\"Delete\", width=15, command=clear)\n#button3.pack()\n\nfilepathdisplay=Text(root, width=30, height =2, wrap=WORD)\nfilepathdisplay.grid(row=6)\n\nfilepathdisplay1=Text(root, width=30, height =2, wrap=WORD)\nfilepathdisplay1.grid(row=7)\n\n\n\nroot.mainloop()\n\n","sub_path":"guiprototype2.py","file_name":"guiprototype2.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"126093137","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode\nfrom bs4 import BeautifulSoup\nimport youtube_dl\n\n\ndef get_video_url(query):\n \"\"\"\n Returns the top video url of the youtube searhc query.\n \"\"\"\n query = {'search_query': '{}'.format(query)}\n url = 'https://www.youtube.com/results?' + urlencode(query)\n response = urlopen(url)\n soup = BeautifulSoup(response.read().decode(), 'html.parser')\n for tag in soup.find_all('a', {'rel': 'spf-prefetch'}):\n video_url = 'https://youtube.com' + tag['href']\n yield video_url\n\n\ndef download(video_url):\n \"\"\"\n Donloads a music file in mp3 format.\n \"\"\"\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n os.chdir('/home/gunace/Desktop')\n ydl.download([video_url])\n\n\n\ndef main():\n \"\"\"\n Start.\n \"\"\"\n query = sys.argv[1:]\n video_url = get_video_url(query)\n download(video_url)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mp3downloader.py","file_name":"mp3downloader.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"427390410","text":"from . import ForecastMixin\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\n\nclass Forecast(ForecastMixin):\n date_format = '%Y-%m-%d'\n url = 'https://services8.arcgis.com/rxZzohbySMKHTNcy/arcgis/rest/services/ind_hdf_agglo/FeatureServer/0/query'\n\n @classmethod\n def insee_list(cls):\n return ['59350', '59183', '59178', '62041', '62160', '59606', '02691',\n '60175', '62765', '62193', '59392', '80021', '62119']\n\n @classmethod\n def params(cls, date, insee):\n parsed_date = parse(date)\n str_parsed_date = parsed_date.strftime(cls.date_format)\n str_parsed_date = parsed_date.timestamp()\n day_after = (parsed_date + timedelta(hours=24)).strftime(cls.date_format)\n day_after = (parsed_date + timedelta(hours=24)).timestamp()\n return {\n 'outFields': \",\".join(cls.outfields),\n 'where': f\"(date_ech>= '{date}') AND code_zone={insee}\",\n 'outSR': 4326,\n 'f': 'json'\n }\n\n @classmethod\n def getter(cls, feature):\n attributes = feature['attributes']\n dt = datetime.fromtimestamp(attributes['date_ech']/1000).strftime(cls.date_format)\n return {\n **{\n 'indice': feature['attributes']['valeur'],\n 'date': dt\n },\n **{k: feature['attributes'][k] for k in cls.outfields if k in feature}\n }","sub_path":"indice_pollution/regions/Hauts-de-France.py","file_name":"Hauts-de-France.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"651356265","text":"#!/usr/bin/env python3\n\"\"\"\nImplementation of virtual machine for open8 assembly language in python\n\"\"\"\n\n__version__ = '1.0'\n\nimport array\nimport select\nimport sys\nimport termios\nimport tty\nimport time\nimport numpy\nimport csv\n\n#Global variables\nUINT16_MAX = 2 ** 16\nDEBUG = False\nTERMINAL_OUT = True\nis_running = True\nmemory = None\nLIMIT = False\nADDR_LIMIT = 0x808d\nSTEP = False\nCLOCK_COUNTER = 0\n\ndef getchar():\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n if ord(ch) == 3:\n # h&le keyboard interrupt\n exit(130)\n return ch\n\ndef set_bit(value, bit):\n return value | (1<> 1) & 0x1)\n update_flags_012(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"adc \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef tx0(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[rn] \n update_flags_02(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"tx0 \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef or_(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[rn] | reg[R.R0]\n update_flags_02(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"or \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef and_(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[rn] & reg[R.R0]\n update_flags_02(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"and \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef xor(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[rn] ^ reg[R.R0]\n update_flags_02(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"xor \" +\"r\"+str(rn))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef rol(instr):\n # destination register\n rn = (instr) & 0x7\n tmp = (reg[rn] >> 7) & 0x1\n reg[rn] = (reg[rn] << 1) | ((reg[R.PSR] >> 1) & 0x1)\n update_flags_02(rn)\n if (tmp):\n reg[R.PSR] |= FL.CRY\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.CRY\n reg[rn] = reg[rn] & 0xFF\n if (DEBUG == True):\n print( \"rol \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\n\n\ndef ror(instr):\n # destination register\n rn = (instr) & 0x7\n tmp = reg[rn] & 0x1\n reg[rn] = (reg[rn] >> 1) | ((((reg[R.PSR] >> 1) & 0x1)) << 7) \n update_flags_02(rn)\n if (tmp):\n reg[R.PSR] |= FL.CRY\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.CRY\n reg[rn] = reg[rn] & 0xFF\n if (DEBUG == True):\n print( \"ror \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef dec(instr):\n # destination register\n rn = (instr) & 0x7\n reg[rn] = reg[rn] + 0xFF\n update_flags_012(rn)\n reg[rn] = reg[rn] & 0xFF\n if (DEBUG == True):\n print( \"dec \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef sbc(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[R.R0] + (-reg[rn]) - ((reg[R.PSR] >> 1) & 0x1) \n update_flags_012(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"sbc \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef add(instr):\n # destination register\n rn = (instr) & 0x7\n reg[R.R0] = reg[R.R0] + reg[rn]\n update_flags_012(R.R0)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"add \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef stp(instr):\n # destination register\n n = (instr) & 0x7\n reg[R.PSR] = reg[R.PSR] | ( 1 << n )\n if (DEBUG == True):\n print( \"stp \" + str(n))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef btt(instr):\n # destination register\n n = (instr) & 0x7\n if (((reg[R.R0] >> n) & 0x1) == 0):\n reg[R.PSR] |= FL.ZRO\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.ZRO\n if (reg[R.R0] >> 7) & 0x1:\n reg[R.PSR] |= FL.NEG\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.NEG\n if (DEBUG == True):\n print( \"btt \" + str(n))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef clp(instr):\n # destination register\n n = (instr) & 0x7\n reg[R.PSR] = reg[R.PSR] & ~( 1 << n )\n if (DEBUG == True):\n print( \"clp \" + str(n))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef t0x(instr):\n # destination register\n rn = (instr) & 0x7\n reg[rn] = reg[R.R0] \n update_flags_02(rn)\n reg[R.R0] = reg[R.R0] & 0xFF\n if (DEBUG == True):\n print( \"t0x \" +\"r\"+str(rn) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n\ndef cmp_(instr):\n # destination register\n rn = (instr) & 0x7\n tmp= reg[R.R0] + (-reg[rn])\n if tmp == 0:\n reg[R.PSR] |= FL.ZRO\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.ZRO\n if (tmp >> 8) & 0x1:\n reg[R.PSR] |= FL.CRY\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.CRY\n if (tmp >> 7) & 0x1:\n reg[R.PSR] |= FL.NEG\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.NEG\n if (DEBUG == True):\n print( \"cmp \" +\"r\"+str(rn)+\" psr \"+bin(reg[R.PSR]) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +1\n #input(\"Waiting...\")\n\ndef psh(instr):\n rn = (instr) & 0x7\n reg[R.STACK] = reg[R.STACK] - 1\n mem_write(reg[R.STACK], reg[rn])\n #reg[R.STACK] = reg[R.STACK] - 1\n if (DEBUG == True):\n print( \"psh \" +\"r\"+str(rn) +\" stack_pt=\"+str(reg[R.STACK]))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef pop(instr):\n rn = (instr) & 0x7\n #reg[R.STACK] = reg[R.STACK] + 1\n reg[rn] = mem_read(reg[R.STACK])\n reg[R.STACK] = reg[R.STACK] + 1\n if (DEBUG == True):\n print( \"pop \" +\"r\"+str(rn)+\" stack_pt=\"+str(reg[R.STACK]) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef br0(instr):\n bit = (instr) & 0x7\n pc_offset = sign_extend((mem_read(reg[R.PC])) & 0xff, 8)\n if ((reg[R.PSR]>>bit) & 0x1) == 0:\n reg[R.PC] += (pc_offset)+1\n else:\n reg[R.PC] +=1\n if (DEBUG == True):\n print( \"br0 \" +str(bit)+\" .\"+str(pc_offset) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef br1(instr):\n bit = (instr) & 0x7\n pc_offset = sign_extend((mem_read(reg[R.PC])) & 0xff, 8)\n if ((reg[R.PSR]>>bit) & 0x1) == 1:\n reg[R.PC] += (pc_offset)+1\n else:\n reg[R.PC] +=1\n if (DEBUG == True):\n print( \"br1 \" +str(bit)+\" .\"+str(pc_offset))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef dbnz(instr):\n rn = (instr) & 0x7\n reg[rn] = reg[rn] + 0xFF\n update_flags_012(rn)\n reg[rn] = reg[rn] & 0xFF \n pc_offset = sign_extend((mem_read(reg[R.PC])) & 0xff, 8)\n if ((reg[R.PSR]) & 0x1) == 1:\n reg[R.PC] += pc_offset\n if (DEBUG == True):\n print( \"dbnz \" +\"r\"+str(rn)+\" \"+str(pc_offset) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef int_(instr):\n n = (instr) & 0x7\n if (DEBUG == True):\n print( \"int\")\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +7\n pass\n #TODO: complete\n #if (n == 0) | ((((reg[R.PSR]>>3) & 0x1) == 1) & (((reg[R.INTERRUPT_MASK_REGISTER]>>n) & 0x1 )==1)):\n # mem_write(reg[R.STACK],reg[R.PSR])\n # reg[R.STACK] -= 1\n # mem_write(reg[R.STACK],(reg[R.PC]>>8)&0xFF)\n # reg[R.STACK] -= 1\n # mem_write(reg[R.STACK],reg[R.PC]&0xFF)\n # reg[R.STACK] -= 1\n # hi8 = mem_read(reg[R.VECTOR_BASE]+(n*2)+1)\n # lo8 = mem_read(reg[R.VECTOR_BASE]+(n*2))\n # reg[R.PC] = (hi8 << 8) | lo8\n\ndef mul(instr):\n rn = (instr) & 0x7\n tmp = reg[rn] * reg[R.R0]\n reg[R.R1] = (tmp >> 8 ) & 0xFF\n reg[R.R0] = (tmp ) & 0xFF\n if tmp == 0:\n reg[R.PSR] |= FL.ZRO\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.ZRO\n if (DEBUG == True):\n print( \"mul \" +str(rn))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +2\n\ndef special (instr):\n select = (instr) & 0x7\n global CLOCK_COUNTER\n if select == 0:\n if (Allow_Stack_Address_Move):\n if ((reg[R.PSR])>> 7) & 0x1:\n reg[R.STACK] = reg[R.R1] << 8 | reg[R.R0]\n else:\n tmp = reg[R.STACK] \n reg[R.R1]= (tmp >> 8) & 0xFF\n reg[R.R0]= (tmp >> 0) & 0xFF\n else:\n reg[R.STACK] = 0x007F\n if (DEBUG == True):\n print( \"rsp \")\n CLOCK_COUNTER=CLOCK_COUNTER +5 # due to retrive restore\n #RSP\n elif select == 1:\n addr = (mem_read(reg[R.STACK]+1) << 8) | mem_read(reg[R.STACK])\n reg[R.PC] = addr\n reg[R.STACK] += 2\n if (DEBUG == True):\n print( \"rts \"+str(addr))\n CLOCK_COUNTER=CLOCK_COUNTER +5\n #RTS\n elif select == 2: \n reg[R.PC] = (mem_read(reg[R.STACK]+1) << 8) | mem_read(reg[R.STACK])\n reg[R.PSR] = mem_read(reg[R.STACK]+2)\n reg[R.STACK] += 3\n if (DEBUG == True):\n print( \"rti \")\n CLOCK_COUNTER=CLOCK_COUNTER +5\n #RTI\n elif select == 3: \n if (DEBUG == True):\n print( \"brk \")\n CLOCK_COUNTER=CLOCK_COUNTER +1\n pass\n #BRK\n elif select == 4: \n lo8 = mem_read(reg[R.PC])\n hi8 = mem_read(reg[R.PC]+1)\n addr = (hi8 << 8) | lo8\n reg[R.PC] = addr\n if (DEBUG == True):\n print( \"jmp \"+str(addr))\n CLOCK_COUNTER=CLOCK_COUNTER +3\n #JMP\n elif select == 5: \n if (DEBUG == True):\n print( \"smsk\")\n CLOCK_COUNTER=CLOCK_COUNTER +1\n pass\n #SMSK\n elif select == 6: \n if (DEBUG == True):\n print( \"gmsk\")\n CLOCK_COUNTER=CLOCK_COUNTER +1\n pass\n #GMSK\n elif select == 7: \n tmp = reg[R.PC]+2\n lo8 = mem_read(reg[R.PC])\n hi8 = mem_read(reg[R.PC]+1)\n addr = (hi8 << 8) | lo8\n reg[R.STACK] -= 1\n mem_write(reg[R.STACK],(tmp >> 8) & 0xFF)\n reg[R.STACK] -= 1\n mem_write(reg[R.STACK],(tmp) & 0xFF)\n reg[R.PC] = addr\n if (DEBUG == True):\n print( \"jsr \"+str(addr))\n CLOCK_COUNTER=CLOCK_COUNTER +5\n #JSR\n else: \n pass\n\ndef upp(instr):\n rn = (instr) & 0x7\n tmp =(( reg[rn+1]<<8 ) | reg[rn]) + 1\n reg[rn+1] = (tmp >> 8) & 0xFF \n reg[rn] = (tmp >> 0) & 0xFF \n if (tmp >> 16) & 0x1:\n reg[R.PSR] |= FL.CRY\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.CRY\n if (DEBUG == True):\n print( \"upp \"+\"r\"+str(rn))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +2\n\ndef sta(instr):\n rn = (instr) & 0x7\n lo8 = mem_read(reg[R.PC])\n hi8 = mem_read(reg[R.PC]+1)\n addr = (hi8<<8) | lo8\n mem_write(addr,reg[rn])\n reg[R.PC] += 2\n if (DEBUG == True):\n print( \"sta \" +\"r\"+str(rn)+\" \"+str(addr) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +4\n\ndef stx(instr):\n rn = (instr) & 0x6\n a = (instr) & 0x1\n hi8 = reg[rn+1]\n lo8 = reg[rn]\n addr = (hi8<<8) | lo8\n mem_write(addr,reg[R.R0])\n addr += a\n reg[rn+1] = (addr >> 8) & 0xFF\n reg[rn] = addr & 0xFF\n if (DEBUG == True):\n if (a == 0):\n print( \"stx \" +\"r\"+str(rn) )\n else:\n print( \"stx \" +\"r\"+str(rn)+\"++\" )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef sto(instr):\n rn = (instr) & 0x6\n a = (instr) & 0x1\n offset = mem_read(reg[R.PC])\n hi8 = reg[rn+1]\n lo8 = reg[rn]\n addr = (hi8<<8) | lo8\n faddr=addr+offset\n mem_write(faddr,reg[R.R0])\n addr += a\n reg[rn+1] = (addr >> 8) & 0xFF\n reg[rn] = addr & 0xFF\n reg[R.PC] += 1\n if (DEBUG == True):\n if (a == 0):\n print( \"sto \" +\"r\"+str(rn)+\" \"+str(offset)+\" addr:\"+str(faddr) )\n else:\n print( \"sto \" +\"r\"+str(rn)+\"++ \"+str(offset)+\" addr:\"+str(faddr))\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +4\n\ndef ldi(instr):\n rn = (instr) & 0x7\n imm = mem_read(reg[R.PC])\n reg[rn] = imm\n update_flags_02(rn)\n reg[R.PC] += 1\n if (DEBUG == True):\n print( \"ldi \" +\"r\"+str(rn)+\" \"+str(imm) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +2\n\ndef lda(instr):\n rn = (instr) & 0x7\n lo8 = mem_read(reg[R.PC])\n hi8 = mem_read(reg[R.PC]+1)\n addr = (hi8<<8) | lo8\n reg[rn] = mem_read(addr)\n update_flags_02(rn)\n reg[R.PC] += 2\n if (DEBUG == True):\n print( \"lda \" +\"r\"+str(rn)+\" \"+str(addr)+\" \"+ str(reg[rn]) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +4\n\ndef ldx(instr):\n rn = (instr) & 0x6\n a = (instr) & 0x1\n hi8 = reg[rn+1]\n lo8 = reg[rn]\n addr = (hi8<<8) | lo8\n reg[R.R0] = mem_read(addr) \n update_flags_02(R.R0)\n addr += a\n reg[rn+1] = (addr >> 8) & 0xFF\n reg[rn] = addr & 0xFF\n if (DEBUG == True):\n if (a == 0):\n print( \"ldx \" +\"r\"+str(rn) )\n else:\n print( \"ldx \" +\"r\"+str(rn)+\"++\" )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +3\n\ndef ldo(instr):\n rn = (instr) & 0x6\n a = (instr) & 0x1\n offset = mem_read(reg[R.PC])\n hi8 = reg[rn+1]\n lo8 = reg[rn]\n addr = (hi8<<8) | lo8\n reg[R.R0] = mem_read(addr+offset)\n update_flags_02(R.R0)\n addr += a\n reg[rn+1] = (addr >> 8) & 0xFF\n reg[rn] = addr & 0xFF\n reg[R.PC] += 1\n if (DEBUG == True):\n if (a == 0):\n print( \"ldo \" +\"r\"+str(rn)+\" \"+str(offset)+\" addr:\"+str(addr+offset) )\n else:\n print( \"ldo \" +\"r\"+str(rn)+\"++ \"+str(offset)+\" addr:\"+str(addr+offset) )\n global CLOCK_COUNTER\n CLOCK_COUNTER=CLOCK_COUNTER +4\n\n\"\"\"\nTRAPs implementation\n\"\"\"\n\n\nclass Trap:\n GETC = 0x20 # get character from keyboard\n OUT = 0x21 # output a character\n PUTS = 0x22 # output a word string\n IN = 0x23 # input a string\n PUTSP = 0x24 # output a byte string\n HALT = 0x25 # halt the program\n\n\ndef trap(instr):\n traps.get(instr & 0xFF)()\n\n\ndef trap_putc():\n i = reg[R.R0]\n c = memory[i]\n while c != 0:\n sys.stdout.write(c)\n i += 1\n c = memory[i]\n sys.stdout.flush()\n\n\ndef trap_getc():\n reg[R.R0] = ord(getchar())\n\n\ndef trap_out():\n sys.stdout.write(chr(reg[R.R0]))\n sys.stdout.flush()\n\n\ndef trap_in():\n sys.stdout.write(\"Enter a character: \")\n sys.stdout.flush()\n reg[R.R0] = sys.stdout.read(1)\n\n\ndef trap_puts():\n for i in range(reg[R.R0], len(memory)):\n c = memory[i]\n if c == 0:\n break\n sys.stdout.write(chr(c))\n sys.stdout.flush()\n\n\ndef trap_putsp():\n for i in range(reg[R.R0], len(memory)):\n c = memory[i]\n if c == 0:\n break\n sys.stdout.write(chr(c & 0xFF))\n char = c >> 8\n if char:\n sys.stdout.write(chr(char))\n sys.stdout.flush()\n\n\ndef trap_halt():\n global is_running\n print('HALT')\n is_running = False\n\n\ntraps = {\n Trap.GETC: trap_getc,\n Trap.OUT: trap_out,\n Trap.PUTS: trap_puts,\n Trap.IN: trap_in,\n Trap.PUTSP: trap_putsp,\n Trap.HALT: trap_halt,\n}\n\n\nops = {\n OP.INC: inc,\n OP.ADC: adc,\n OP.TX0: tx0,\n OP.OR : or_ ,\n OP.AND: and_,\n OP.XOR: xor,\n OP.ROL: rol,\n OP.ROR: ror,\n OP.DEC: dec,\n OP.SBC: sbc,\n OP.ADD: add,\n OP.STP: stp,\n OP.BTT: btt,\n OP.CLP: clp,\n OP.T0X: t0x,\n OP.CMP: cmp_,\n OP.PSH: psh,\n OP.POP: pop,\n OP.BR0: br0,\n OP.BR1: br1,\n OP.DBNZ: dbnz,\n OP.INT: int_,\n OP.MUL: mul,\n OP.SPECIAL:special,\n OP.UPP: upp,\n OP.STA: sta,\n OP.STX: stx,\n OP.STO: sto,\n OP.LDI: ldi,\n OP.LDA: lda,\n OP.LDX: ldx,\n OP.LDO: ldo\n}\n\nclass memory_map:\n RAM_Address = 0x0000 ### System RAM\n ALU_Address = 0x1000 ### ALU16 coprocessor\n RTC_Address = 0x1100 ### System Timer / RT Clock\n ETC_Address = 0x1200 ### Epoch Timer/Alarm Clock\n TMR_Address = 0x1400 ### PIT timer\n SDLC_Address = 0x1800 ### LCD serial interface\n LED_Address = 0x2000 ### LED Display\n DSW_Address = 0x2100 ### Dip Switches\n BTN_Address = 0x2200 ### Push Buttons\n SER_Address = 0x2400 ### UART interface\n MAX_Address = 0x2800 ### Max 7221 base address\n VEC_Address = 0x3000 ### Vector RX base address\n CHR_Address = 0x3100 ### Elapsed Time / Chronometer\n ROM_Address = 0x8000 ### Application ROM\n ISR_Start_Addr = 0xFFF0 ### ISR Vector Table\n\nclass Mr:\n KBSR = memory_map.SER_Address\n KBDR = memory_map.SER_Address\n\ndef check_key():\n _, o, _ = select.select([], [sys.stdin], [], 0)\n for s in o:\n if s == sys.stdin:\n return True\n return False\n\n\ndef mem_write(address, val):\n global is_running\n address = address % UINT16_MAX\n global TERMINAL_OUT\n if (address == memory_map.SER_Address ):\n if TERMINAL_OUT:\n sys.stdout.write(chr(val))\n sys.stdout.flush()\n \"\"\"if ((address >= memory_map.ROM_Address) & (address <= memory_map.ISR_Start_Addr)):\n is_running = False\n print(\"Try to write rom memory in \"+hex(address))\"\"\"\n memory[address] = val\n\n\ndef mem_read(address):\n address = address % UINT16_MAX\n if address == Mr.KBDR:\n if check_key():\n #memory[Mr.KBSR] = 1 << 15\n memory[Mr.KBDR] = ord(getchar())\n else:\n #memory[Mr.KBSR] = 0\n memory[Mr.KBDR] = 0\n if address == memory_map.RTC_Address:\n memory[address] = (CLOCK_COUNTER >> 0) & 0xFF\n if address == memory_map.RTC_Address+1:\n memory[address] = (CLOCK_COUNTER >> 8) & 0xFF\n print(str(CLOCK_COUNTER)+\"_\\n\")\n if (address == memory_map.SER_Address+1 ):\n memory[address] = 0x52 # 0101, 0000, => TXFIFO and RXFIFO empty\n \"\"\"if address == memory_map.RTC_Address+2:\n memory[address] = (CLOCK_COUNTER >> 16) & 0xFF\n if address == memory_map.RTC_Address+3:\n memory[address] = (CLOCK_COUNTER >> 24) & 0xFF\"\"\"\n return memory[address]\n\n\ndef sign_extend(x, bit_count):\n if (x >> (bit_count - 1)) & 1:\n x |= 0xFFFF << bit_count\n return x & 0xffff\n\n\ndef update_flags_012(r):\n if reg[r] == 0:\n reg[R.PSR] |= FL.ZRO\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.ZRO\n if (reg[r] >> 8) & 0x1:\n reg[R.PSR] |= FL.CRY\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.CRY\n if (reg[r] >> 7) & 0x1:\n reg[R.PSR] |= FL.NEG\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.NEG\n\ndef update_flags_02(r):\n if reg[r] == 0:\n reg[R.PSR] |= FL.ZRO\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.ZRO\n if (reg[r] >> 7) & 0x1:\n reg[R.PSR] |= FL.NEG\n else:\n reg[R.PSR] = reg[R.PSR] & ~FL.NEG\n\n\ndef read_image_file(file_name):\n global memory\n with open(file_name, 'rb') as f:\n origin = memory_map.ROM_Address #int.from_bytes(f.read(1), byteorder='big')\n memory = array.array(\"B\", [0] * origin)\n max_read = UINT16_MAX - origin\n memory.frombytes(f.read(max_read))\n memory.byteswap()\n memory.fromlist([0]*(UINT16_MAX - len(memory)))\n #with open(file_name, 'rb') as f:\n # origin = int.from_bytes(f.read(1), byteorder='big')\n # memory = array.array(\"B\", [0] * origin)\n # max_read = UINT16_MAX - origin\n # memory.frombytes(f.read(max_read))\n # memory.byteswap()\n # memory.fromlist([0]*(UINT16_MAX - len(memory)))\n\ndef dump_memory(file_name):\n global memory\n #print(memory)\n a = numpy.asarray(memory)\n numpy.savetxt(file_name+\".csv\", a, delimiter=\",\")\n\ndef dump_regfile():\n global reg\n print(reg)\n with open('regfile.csv', 'w') as f: \n w = csv.DictWriter(f, reg.keys())\n w.writeheader()\n w.writerow(reg)\ndef print_register():\n global reg\n print(\"r0 \"+str(reg[R.R0])+\" \"+hex(reg[R.R0]))\n print(\"r1 \"+str(reg[R.R1])+\" \"+hex(reg[R.R1]))\n print(\"r2 \"+str(reg[R.R2])+\" \"+hex(reg[R.R2]))\n print(\"r3 \"+str(reg[R.R3])+\" \"+hex(reg[R.R3]))\n print(\"r4 \"+str(reg[R.R4])+\" \"+hex(reg[R.R4]))\n print(\"r5 \"+str(reg[R.R5])+\" \"+hex(reg[R.R5]))\n print(\"r6 \"+str(reg[R.R6])+\" \"+hex(reg[R.R6]))\n print(\"r7 \"+str(reg[R.R7])+\" \"+hex(reg[R.R7]))\n print(\"PSR \"+str(reg[R.PSR])+\" \"+hex(reg[R.PSR])+\" \"+bin(reg[R.PSR]))\n print(\"PC+ \"+str(reg[R.PC])+\" \"+hex(reg[R.PC]))\n print(\"STK \"+str(reg[R.STACK])+\" \"+hex(reg[R.STACK]))\n print(\"VEC \"+str(reg[R.VECTOR_BASE])+\" \"+hex(reg[R.VECTOR_BASE]))\n print(\"CLOCK \"+str(CLOCK_COUNTER)+\" \"+hex(CLOCK_COUNTER))\n\nProgram_Start_Addr = memory_map.ROM_Address \nISR_Start_Addr = 0xFFFF\nStack_Start_Addr = 0x0FFE\nAllow_Stack_Address_Move = True\nEnable_Auto_Increment = True\nBRK_Implements_WAI = True\nEnable_NMI = True\nSequential_Interrupts = True\nRTI_Ignores_GP_Flags = True\nDefault_Interrupt_Mask = 0x00\nClock_Frequency = 100000000.0\n\n\ndef main():\n if len(sys.argv) < 2:\n print('vm.py [obj-file]')\n exit(2)\n global DEBUG\n global TERMINAL_OUT\n global is_running\n global ADDR_LIMIT\n global LIMIT\n global STEP\n global DEBUG\n global CLOCK_COUNTER\n file_path = sys.argv[1]\n read_image_file(file_path)\n reg[R.PC] = Program_Start_Addr\n reg[R.STACK] = Stack_Start_Addr\n CLOCK_COUNTER= 0\n #dump_memory(\"initial\")\n try:\n while is_running:\n #for i in range(15):\n #print(reg)\n #if (CLOCK_COUNTER > 0xffffffff):\n # CLOCK_COUNTER = 0\n if (reg[R.STACK] > 0xfff):\n is_running = False;\n print(\"stack overflow\")\n if (DEBUG == True):\n print(hex(reg[R.PC]), end=\" \")\n instr = mem_read(reg[R.PC])\n reg[R.PC] += 1\n op = instr >> 3\n fun = ops.get(op, bad_opcode)\n fun(instr)\n if (DEBUG == True):\n print_register()\n if(STEP):\n input(\"Waiting...\")\n #dump_memory(\"final\")\n #dump_memory(\"final\")\n if (reg[R.PC] == ADDR_LIMIT) & LIMIT:\n STEP = True\n LIMIT = False\n #print_register()\n input(\"Waiting...\")\n #dump_memory(\"final\")\n except KeyboardInterrupt:\n exit();\n \n \n #dump_memory(\"final\")\n #dump_regfile()\n #print_register() \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"vm.py","file_name":"vm.py","file_ext":"py","file_size_in_byte":25357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"377725677","text":"#-*- coding: utf-8 -*-\n\nread = open(\"hightemp.txt\", \"r\")\nN = int(raw_input())\ncount = 0\nline = 0\nlists = []\n\nfor word in read:\n lists.append(word)\n line += 1\n\nwhile count < N:\n ans = \"\"\n w_file = open(\"split%d.txt\" % (count + 1), \"w\")\n if line % N != 0:\n temp = int(line / N) + 1\n else:\n temp = line / N\n for i in range(temp):\n if len(lists) == 0:\n break\n ans += lists.pop(0)\n w_file.write(ans)\n w_file.close()\n count += 1\n\nread.close()\n\n#UNIX command: split -l 10 hightemp.txt split_unix\n","sub_path":"Hayahide/chapter02/knock16.py","file_name":"knock16.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"3437531","text":"from random import uniform\r\nfrom textwrap import dedent\t\r\n\r\n\r\nclass Stock(object):\r\n\t\r\n\tdef __init__(self, buyPrice, symbol):\r\n\t\tself.buyPrice = buyPrice\r\n\t\tself.symbol = symbol\r\n\t\t\r\nclass MutualFund(object):\r\n\t\r\n\tdef __init__(self, symbol):\r\n\t\tself.symbol = symbol\r\n\t\tprice = 1\r\n\t\tself.price = price\r\n\r\nclass Portfolio(object):\r\n\t\r\n\tdef __init__(self):\r\n\t\ttotalCash = 0\r\n\t\tstocks = {}\r\n\t\tmfunds = {}\r\n\t\thist = []\r\n\t\tself.totalCash = totalCash\r\n\t\tself.stocks = stocks\r\n\t\tself.mfunds = mfunds\r\n\t\tself.hist = hist\r\n\t\t\r\n\r\n\tdef history(self):\r\n\t\t\r\n\t\tfor i in range(len(self.hist)):\r\n\t\t\tprint(self.hist[i])\r\n\t\t\r\n\tdef addCash(self, cash):\r\n\t\tself.totalCash += cash\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t${cash} added to balance.\r\n\t\t\tCurrent cash balance = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\r\n\tdef withdrawCash(self, cash):\r\n\t\tself.totalCash -= cash\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t${cash} withdrawn from cash balance.\r\n\t\t\tCurrent cash balance = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\t\r\n\t\r\n\tdef buyStock(self, shares, self_name):\r\n\t\tsuper(Stock).__init__()\r\n\t\tself.stocks[self_name.symbol] = self_name.buyPrice\r\n\t\tself.totalCash -= shares * self_name.buyPrice\r\n\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t{shares} shares of {self_name.symbol} bought for unit price of ${self_name.buyPrice}.\r\n\t\t\tCurrent cash balance = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\r\n\tdef sellStock(self, symbol, shares):\r\n\t\tprice = self.stocks.get(symbol)\r\n\t\tsell_price = price * uniform(0.5, 1.5)\r\n\t\t\r\n\t\tself.totalCash += sell_price\r\n\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t{shares} shares of {symbol} sold for unit price of ${sell_price}.\r\n\t\t\tCurrent portfolio:\r\n\t\t\tCash = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\t\t\r\n\tdef buyMutualFund(self, shares, self_name):\r\n\t\tsuper(MutualFund).__init__()\r\n\t\tself.totalCash -= shares * self_name.price\r\n\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t{shares} shares of {self_name.symbol} bought for ${self_name.price} each.\r\n\t\t\tCurrent portfolio:\r\n\t\t\tCash = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\r\n\tdef sellMutualFund(self, symbol, shares):\r\n\t\tmf_name = MutualFund(symbol)\r\n\t\tsell_price = mf_name.price * uniform(0.9, 1.2)\r\n\t\tself.totalCash += shares * sell_price\r\n\t\tself.hist.append(dedent(f\"\"\"\r\n\t\t\t{shares} shares of {mf_name.symbol} sold for ${sell_price} each.\r\n\t\t\tCurrent portfolio:\r\n\t\t\tCash = ${self.totalCash}\r\n\t\t\t\"\"\"))\r\n\r\n\t\t\r\n\t\r\n\r\nportfolio = Portfolio()\r\nportfolio.addCash(300.5)\r\n\r\ns = Stock(20, \"HFH\")\r\nportfolio.buyStock(5, s)\r\n\r\nmf1 = MutualFund(\"BRT\")\r\nmf2 = MutualFund(\"GHT\")\r\n\r\nportfolio.buyMutualFund(10.3, mf1)\r\nportfolio.buyMutualFund(2, mf2)\r\n\r\nportfolio.sellMutualFund(\"BRT\", 3)\r\nportfolio.sellStock(\"HFH\", 1)\r\n\r\n\r\nportfolio.history()","sub_path":"hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"19639165","text":"import datetime\nimport gc\n\nimport matplotlib.cm\nimport matplotlib.colors\nimport numpy as np\nimport sastool.io.credo_cct\nimport scipy.misc\nfrom PyQt5 import QtWidgets, QtGui\nfrom matplotlib.axes import Axes\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT\nfrom matplotlib.figure import Figure\nfrom sastool.classes2 import Exposure\n\nfrom .plotimage_ui import Ui_Form\n\n\ndef get_colormaps():\n return sorted(\n [cm for cm in dir(matplotlib.cm) if isinstance(getattr(matplotlib.cm, cm), matplotlib.colors.Colormap)],\n key=lambda x: x.lower())\n\n\nclass PlotImage(QtWidgets.QWidget, Ui_Form):\n lastinstances = []\n _exposure: Exposure=None\n\n def __init__(self, parent=None, register_instance=True):\n QtWidgets.QWidget.__init__(self, parent)\n self._exposure = None\n self.previous_extent = None\n self.previous_axestype = None\n self.setupUi(self)\n if register_instance:\n type(self).lastinstances.append(self)\n\n @classmethod\n def get_lastinstance(cls):\n if not cls.lastinstances:\n return cls()\n else:\n obj = cls.lastinstances[-1]\n try:\n assert isinstance(obj, cls)\n obj.windowTitle()\n return obj\n except RuntimeError:\n # wrapped C/C++ object of type PlotImage has been deleted\n cls.lastinstances.remove(obj)\n # try again\n return cls.get_lastinstance()\n\n def closeEvent(self, event: QtGui.QCloseEvent):\n try:\n type(self).lastinstances.remove(self)\n except ValueError:\n pass\n event.accept()\n\n def _testimage(self):\n header = sastool.io.credo_cct.Header(\n {'accounting':\n {'operator': 'Anonymous',\n 'projectid': 'Dummy project',\n },\n 'sample':\n {'title': 'Test image',\n 'transmission.val': 0.5,\n 'transmission.err': 0.01,\n 'thickness.val': 0.1,\n 'thickness.err': 0.001,\n 'distminus.val': 0,\n 'distminus.err': 0,\n 'positionx.val': 0,\n 'positiony.val': 0,\n 'positionx.err': 0,\n 'positiony.err': 0,\n },\n 'motors':\n {'dummy_motor': 0,\n },\n 'exposure':\n {'fsn': 0,\n 'exptime': 100,\n 'startdate': str(datetime.datetime.now()),\n },\n 'geometry':\n {'wavelength': 0.15418,\n 'wavelength.err': 0.001,\n 'truedistance': 100,\n 'truedistance.err': 0.05,\n 'beamposy': 200,\n 'beamposy.err': 0.5,\n 'beamposx': 100,\n 'beamposx.err': 0.5,\n 'pixelsize': 0.172,\n 'mask': 'mask.mat',\n },\n 'environment':\n {'temperature': 20,\n 'vacuum_pressure': 1e-5,\n },\n 'datareduction':\n {'flux': 10,\n 'flux.err': 0.1,\n 'emptybeamFSN': 0,\n 'absintrefFSN': 0,\n 'absintfactor': 1,\n 'absintfactor.err': 0,\n }\n })\n m = scipy.misc.face(True)\n self._exposure = sastool.io.credo_cct.Exposure(m * 1.0,\n m * 0.1,\n header,\n m - m.min() > 0.2 * (m.max() - m.min()))\n self.replot()\n\n def setPixelMode(self, pixelmode:bool):\n if pixelmode:\n self.axesComboBox.setCurrentIndex(self.axesComboBox.findText('abs. pixel'))\n self.axesComboBox.setVisible(not pixelmode)\n self.axesLabel.setVisible(not pixelmode)\n self.replot()\n\n def setupUi(self, Form):\n Ui_Form.setupUi(self, Form)\n #self.colourScaleComboBox.addItems(['linear', 'logarithmic', 'square', 'square root'])\n self.colourScaleComboBox.setCurrentIndex(self.colourScaleComboBox.findText('logarithmic'))\n self.paletteComboBox.addItems(get_colormaps())\n self.paletteComboBox.setCurrentIndex(self.paletteComboBox.findText(matplotlib.rcParams['image.cmap']))\n #self.axesComboBox.addItems(['abs. pixel', 'rel. pixel', 'detector radius', 'twotheta', 'q'])\n self.axesComboBox.setCurrentIndex(self.axesComboBox.findText('q'))\n layout = QtWidgets.QVBoxLayout(self.figureContainer)\n self.figure = Figure()\n self.canvas = FigureCanvasQTAgg(self.figure)\n self.axes = self.figure.add_subplot(1, 1, 1)\n assert isinstance(self.axes, Axes)\n self.axes.set_facecolor('black')\n layout.addWidget(self.canvas)\n self.figtoolbar = NavigationToolbar2QT(self.canvas, self.figureContainer)\n layout.addWidget(self.figtoolbar)\n assert isinstance(self.figtoolbar, QtWidgets.QToolBar)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/icons/plotimage_config.svg\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.showToolbarButton = QtWidgets.QToolButton(self.figtoolbar)\n self.showToolbarButton.setIcon(icon)\n self.showToolbarButton.setText('Plot setup')\n self.showToolbarButton.setCheckable(True)\n self.showToolbarButton.setChecked(False)\n self.toolbar.setVisible(False)\n self.showToolbarButton.toggled.connect(self.toolbarVisibility)\n self.figtoolbar.insertWidget(self.figtoolbar.actions()[-1], self.showToolbarButton).setVisible(True)\n self.colourScaleComboBox.currentIndexChanged.connect(self.colourScaleChanged)\n self.axesComboBox.currentIndexChanged.connect(self.axesTypeChanged)\n self.paletteComboBox.currentIndexChanged.connect(self.paletteChanged)\n self.showColourBarToolButton.toggled.connect(self.showColourBarChanged)\n self.showMaskToolButton.toggled.connect(self.showMaskChanged)\n self.showBeamToolButton.toggled.connect(self.showBeamChanged)\n self.equalAspectToolButton.toggled.connect(self.replot)\n self._testimage()\n self.figtoolbar.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)\n self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n self.canvas.mpl_connect('resize_event', self.onCanvasResize)\n\n def onCanvasResize(self, event):\n self.figure.tight_layout()\n self.canvas.draw()\n\n def toolbarVisibility(self, state):\n self.toolbar.setVisible(state)\n\n def showColourBarChanged(self, checked):\n self.replot_colourbar()\n self.canvas.draw()\n\n def showMaskChanged(self, checked):\n self.replot_mask()\n self.canvas.draw()\n\n def showBeamChanged(self, checked):\n self.replot_crosshair()\n self.canvas.draw()\n\n def colourScaleChanged(self):\n self.replot()\n\n def paletteChanged(self):\n self.replot()\n\n def axesTypeChanged(self):\n self.replot()\n\n def replot_colourbar(self):\n if hasattr(self, '_colorbar'):\n self._colorbar.remove()\n del self._colorbar\n if self.showColourBarToolButton.isChecked():\n self._colorbar = self.figure.colorbar(self._image, ax=self.axes, use_gridspec=True)\n\n def replot_mask(self):\n if hasattr(self, '_mask'):\n self._mask.remove()\n del self._mask\n if self.showMaskToolButton.isChecked():\n ex = self.exposure()\n assert isinstance(ex, Exposure)\n mf = np.ones(ex.shape, np.float)\n mf[ex.mask != 0] = np.nan\n aspect = ['auto','equal'][self.equalAspectToolButton.isChecked()]\n self._mask = self.axes.imshow(mf, cmap='gray_r', interpolation='nearest', aspect=aspect, alpha=0.7,\n origin='upper', extent=self._image.get_extent(), zorder=2)\n gc.collect()\n\n def replot_crosshair(self):\n if hasattr(self, '_crosshair'):\n for c in self._crosshair:\n c.remove()\n del self._crosshair\n if self.showBeamToolButton.isChecked():\n ex = self.exposure()\n assert isinstance(ex, Exposure)\n axestype = self.axesComboBox.currentText()\n if axestype == 'abs. pixel':\n matrix = self.exposure().intensity\n beampos = (ex.header.beamcenterx.val, ex.header.beamcentery.val)\n assert isinstance(self.axes, Axes)\n self._crosshair = self.axes.plot([0, matrix.shape[1]], [beampos[1], beampos[1]], 'w-',\n [beampos[0], beampos[0]], [0, matrix.shape[0]], 'w-',\n scalex=False, scaley=False)\n else:\n extent = self._image.get_extent()\n self._crosshair = self.axes.plot(extent[0:2], [0, 0], 'w-',\n [0, 0], extent[2:4], 'w-', scalex=False, scaley=False)\n gc.collect()\n\n def replot(self):\n ex = self.exposure()\n assert isinstance(ex, Exposure)\n assert isinstance(self.axes, Axes)\n if self.colourScaleComboBox.currentText() == 'linear':\n norm = matplotlib.colors.Normalize()\n elif self.colourScaleComboBox.currentText() == 'logarithmic':\n norm = matplotlib.colors.LogNorm()\n elif self.colourScaleComboBox.currentText() == 'square':\n norm = matplotlib.colors.PowerNorm(2)\n elif self.colourScaleComboBox.currentText() == 'square root':\n norm = matplotlib.colors.PowerNorm(0.5)\n else:\n assert False\n matrix = ex.intensity\n if self.colourScaleComboBox.currentText() in ['logarithmic', 'square', 'square root']:\n matrix[matrix <= 0] = np.nan\n\n beampos = (ex.header.beamcenterx.val, ex.header.beamcentery.val)\n distance = ex.header.distance.val\n wavelength = ex.header.wavelength.val\n pixelsize = ex.header.pixelsizex.val, ex.header.pixelsizey.val\n axesscale = self.axesComboBox.currentText()\n if axesscale != self.previous_axestype:\n self.previous_axestype = axesscale\n self.clear()\n return self.replot()\n if axesscale == 'abs. pixel':\n extent = (0, matrix.shape[1] - 1, matrix.shape[0] - 1, 0) # left, right, bottom, top\n elif axesscale == 'rel. pixel':\n extent = (0 - beampos[0], matrix.shape[1] - 1 - beampos[0],\n matrix.shape[0] - 1 - beampos[1], 0 - beampos[1],)\n elif axesscale == 'detector radius':\n extent = (\n (0 - beampos[0]) * pixelsize[0],\n (matrix.shape[1] - 1 - beampos[0]) * pixelsize[0],\n (matrix.shape[0] - 1 - beampos[1]) * pixelsize[1],\n (0 - beampos[1]) * pixelsize[1],\n )\n elif axesscale == 'twotheta':\n extent = (np.arctan((0 - beampos[0]) * pixelsize[0] / distance) * 180 / np.pi,\n np.arctan((matrix.shape[1] - 1 - beampos[\n 0]) * pixelsize[0] / distance) * 180 / np.pi,\n np.arctan((matrix.shape[0] - 1 - beampos[1]) *\n pixelsize[1] / distance) * 180 / np.pi,\n np.arctan((0 - beampos[1]) * pixelsize[1] / distance) * 180 / np.pi,\n )\n elif axesscale == 'q':\n extent = (4 * np.pi * np.sin(\n 0.5 * np.arctan((0 - beampos[0]) * pixelsize[0] / distance)) / wavelength,\n 4 * np.pi * np.sin(0.5 * np.arctan((matrix.shape[1] - 1 - beampos[\n 0]) * pixelsize[0] / distance)) / wavelength,\n 4 * np.pi * np.sin(0.5 * np.arctan((matrix.shape[0] - 1 - beampos[\n 1]) * pixelsize[1] / distance)) / wavelength,\n 4 * np.pi * np.sin(\n 0.5 * np.arctan(\n (0 - beampos[1]) * pixelsize[1] / distance)) / wavelength,\n )\n else:\n raise ValueError(axesscale)\n if extent != self.previous_extent:\n self.previous_extent = extent\n self.clear()\n return self.replot()\n if hasattr(self, '_image'):\n if hasattr(self, '_colorbar'):\n self._colorbar.remove()\n del self._colorbar\n if self._image.get_extent() != extent:\n self.axes.axis( extent)\n self._image.remove()\n del self._image\n firstplot = False\n else:\n firstplot = True\n aspect = ['auto','equal'][self.equalAspectToolButton.isChecked()]\n self._image = self.axes.imshow(matrix,\n cmap=self.paletteComboBox.currentText(), norm=norm,\n aspect=aspect, interpolation='nearest', origin='upper', zorder=1, extent=extent)\n if firstplot:\n self.figtoolbar.update()\n if np.isfinite(matrix).sum() > 0:\n self.replot_colourbar()\n self.replot_crosshair()\n self.replot_mask()\n try:\n title = ex.header.title\n except KeyError:\n title = 'Untitled'\n self._title = self.axes.set_title('#{:d}: {} ({:.2f} mm)'.format(ex.header.fsn,\n title,\n ex.header.distance))\n\n if axesscale == 'abs. pixel':\n self.axes.xaxis.set_label_text('Absolute column coordinate (pixel)')\n self.axes.yaxis.set_label_text('Absolute row coordinate (pixel)')\n elif axesscale == 'rel. pixel':\n self.axes.xaxis.set_label_text('Relative column coordinate (pixel)')\n self.axes.yaxis.set_label_text('Relative row coordinate (pixel)')\n elif axesscale == 'detector radius':\n self.axes.xaxis.set_label_text('Horizontal distance from the beam center (mm)')\n self.axes.yaxis.set_label_text('Vertical distance from the beam center (mm)')\n elif axesscale == 'twotheta':\n self.axes.xaxis.set_label_text('$2\\\\theta_x$ ($^\\circ$)')\n self.axes.yaxis.set_label_text('$2\\\\theta_y$ ($^\\circ$)')\n elif axesscale == 'q':\n self.axes.xaxis.set_label_text('$q_x$ (nm$^{-1}$)')\n self.axes.yaxis.set_label_text('$q_y$ (nm$^{-1}$)')\n else:\n assert False\n self.canvas.draw()\n gc.collect()\n\n def setExposure(self, exposure: Exposure):\n self._exposure = exposure\n del exposure\n self.replot()\n\n def exposure(self) -> Exposure:\n return self._exposure\n\n def setOnlyAbsPixel(self, status=True):\n if status:\n self.axesComboBox.setCurrentIndex(0)\n self.axesComboBox.setEnabled(False)\n else:\n self.axesComboBox.setEnabled(True)\n\n def setMaskMatrix(self, mask:np.ndarray):\n if self._exposure.mask.shape==mask.shape:\n self._exposure.mask = mask\n self.replot_mask()\n self.canvas.draw()\n else:\n raise ValueError('Mismatched mask shape ({0[0]:d}, {0[1]:d}) for image of shape ({1[0]:d}, {1[1]:d})'.format(mask.shape, self._exposure.shape))\n\n def maskMatrix(self)-> np.ndarray:\n return self._exposure.mask\n\n def clear(self):\n try:\n self._colorbar.remove()\n except (AttributeError, KeyError):\n pass\n for attr in ['_crosshair', '_image', '_mask', '_colorbar']:\n try:\n delattr(self, attr)\n except AttributeError:\n pass\n self.axes.clear()\n self.canvas.draw()\n","sub_path":"cct/qtgui/core/plotimage/plotimage.py","file_name":"plotimage.py","file_ext":"py","file_size_in_byte":16195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"558150657","text":"# -*- coding: utf-8 -*-\n# Copyright 2015 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport os\nfrom StringIO import StringIO\n\nimport pytest\nimport yaml\n\nfrom solar.events.controls import React, Dep\nfrom solar.core.resource import virtual_resource as vr\n\n\n@pytest.fixture\ndef good_events():\n events = '''\n - type: depends_on\n parent_action: 'service1.run'\n state: 'success'\n depend_action: 'config1.run'\n - type: react_on\n parent_action: 'config1.run'\n state: 'success'\n depend_action: 'service1.apply_config'\n'''\n return yaml.load(StringIO(events))\n\n@pytest.fixture\ndef bad_event_type():\n events = '''\n - type: skip\n parent_action: 'service1.run'\n state: 'success'\n depend_action: 'config1.run'\n'''\n return yaml.load(StringIO(events))\n\n\ndef test_create_resource():\n node_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n 'resource_fixtures', 'node')\n resources = vr.create('node1', node_path)\n assert len(resources) == 1\n assert resources[0].name == 'node1'\n\ndef test_create_virtual_resource(tmpdir):\n base_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n 'resource_fixtures')\n vr_tmpl_path = os.path.join(base_path, 'nodes.yaml.tmpl')\n node_resource_path = os.path.join(base_path, 'node')\n with open(vr_tmpl_path) as f:\n vr_data = f.read().format(resource_path=node_resource_path)\n vr_file = tmpdir.join('nodes.yaml')\n vr_file.write(vr_data)\n resources = vr.create('nodes', str(vr_file))\n assert len(resources) == 2\n\n\ndef test_parse_events(good_events):\n events =[Dep(parent='service1', parent_action='run',\n child='config1', child_action='run',\n state='success'),\n React(parent='config1', parent_action='run',\n child='service1', child_action='apply_config',\n state='success')]\n parsed = vr.parse_events(good_events)\n assert events == parsed\n\ndef test_parse_bad_event(bad_event_type):\n with pytest.raises(Exception) as execinfo:\n vr.parse_events(bad_event_type)\n error = 'Invalid event type: skip'\n assert error == str(execinfo.value)\n\n\ndef test_add_connections(mocker, resources):\n mocked_signals = mocker.patch('solar.core.resource.virtual_resource.signals')\n args = {'ip': 'node1::ip',\n 'servers': ['node1::ip', 'node2::ip'],\n 'alias': 'ser1'\n }\n vr.add_connections('service1', args)\n assert mocked_signals.connect.call_count == 3\n\n\ndef test_parse_connection():\n correct_connection = {'child': 'host_file',\n 'child_input': 'ip',\n 'parent' : 'node1',\n 'parent_input': 'ip',\n 'events' : None\n }\n connection = vr.parse_connection('host_file', 'ip', 'node1::ip')\n assert correct_connection == connection\n\ndef test_parse_connection_disable_events():\n correct_connection = {'child': 'host_file',\n 'child_input': 'ip',\n 'parent' : 'node1',\n 'parent_input': 'ip',\n 'events' : False\n }\n connection = vr.parse_connection('host_file', 'ip', 'node1::ip::NO_EVENTS')\n assert correct_connection == connection\n\ndef test_parse_connection_no_connection():\n connection = vr.parse_connection('host_file', 'ip', '10.0.0.2')\n assert None == connection\n","sub_path":"solar/solar/test/test_virtual_resource.py","file_name":"test_virtual_resource.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122991169","text":"#!/usr/bin/env python\n\nimport argparse, sys, os, itertools, gzip\nfrom Bio import SeqIO\n\ndef shared_id(rid):\n return rid.split()[0]\n\ndef new_id(location, barcode, direction):\n '''(location, barcode, direction) -> location#barcode/direction'''\n return \"%s#%s/%s\" %(location, barcode, direction)\n\nif __name__ == '__main__':\n # parse command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('forward_in', help='input forward reads fastq')\n parser.add_argument('reverse_in', help='input reverse reads fastq')\n parser.add_argument('index', help='input index reads fastq')\n parser.add_argument('forward_out', help='output forward reads fastq')\n parser.add_argument('reverse_out', help='output reverse reads fastq')\n parser.add_argument('--gzip', '-g', action='store_true', help='input files are gzipped?')\n args = parser.parse_args()\n\n # open up the filehandles, zipped or not\n if args.gzip:\n opener = lambda x: gzip.open(x)\n else:\n opener = lambda x: open(x)\n\n fih, rih, iih = [opener(fn) for fn in [args.forward_in, args.reverse_in, args.index]]\n \n with open(args.forward_out, 'w') as fo, open(args.reverse_out, 'w') as ro:\n fi = SeqIO.parse(fih, 'fastq')\n ri = SeqIO.parse(rih, 'fastq')\n ii = SeqIO.parse(iih, 'fastq')\n \n for fr, rr, ir in itertools.izip(fi, ri, ii):\n # check that the reads match\n if not (shared_id(fr.id) == shared_id(rr.id) == shared_id(ir.id)):\n raise RuntimeError(\"ids in corresponding entries did not match: %s %s %s\" %(fr.id, rr.id, ir.id))\n \n # the barcode is the sequence from the index read\n barcode = str(ir.seq)\n \n # amend the ids on the forward and reverse entries\n fr.id = new_id(fr.id, barcode, '1')\n rr.id = new_id(rr.id, barcode, '2')\n fr.description = ''\n rr.description = ''\n \n # write the entries to their output files\n SeqIO.write(fr, fo, 'fastq')\n SeqIO.write(rr, ro, 'fastq')\n","sub_path":"tools/convert_3file_to_2file.py","file_name":"convert_3file_to_2file.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"78598670","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 分析网页源码后发现,图片链接到一个URL(http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=44827)\n# 参数nothing后跟了五位数字,点击该链接后会给出新的数字,结合题目,应该就是不断地根据结果修改nothing参数值,直到得出答案\n\nimport requests\n\nurl = 'http://www.pythonchallenge.com/pc/def/linkedlist.php'\nkey = '12345'\npayload = {'nothing': key}\n\nglobal i\ni = 0\nwhile True:\n\tr = requests.get(url, params=payload)\n\tkey = r.text.split(' ')[-1]\n\ttry:\n\t\tint(key) \n\texcept ValueError as e:\n\t\tprint(r.text)\n\t\tbreak\n\tpayload = {'nothing': key}\n\tprint('%d times:' % i)\n\ti = i + 1\n\tprint(r.text)\n\n# 不断循环,题目说最多400次就得到结果,在我这里好像不是这样的,peak.html","sub_path":"level-04.py","file_name":"level-04.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96765000","text":"import tensorflow as tf\nimport numpy as np\nfrom data_reader import data_reader\n\n\nclass scGen(object):\n\n def __init__(self, train_data, valid_data,conditions,tr_ct_list =None,ho_ct_list=None,\n dr_rate=.2, learning_rate=0.001, batch_size=32, z_dimension=100, use_validation=True,\n model_path=\"./models/scGen\"):\n\n self.dr = data_reader(train_data, valid_data,conditions, tr_ct_list, ho_ct_list)\n self.train_real = self.dr.train_real\n self.use_validation = use_validation\n if self.use_validation:\n self.valid_real = self.dr.valid_real\n self.X_dim = self.train_real.shape[1]\n self.is_training = tf.placeholder(tf.bool, name='training_flag')\n self.z_dim = z_dimension\n self.lr = learning_rate\n self.conditions = conditions\n self.dr_rate = dr_rate\n self.model_to_use = model_path\n self.batch_size = batch_size\n self.global_step = tf.Variable(0, name='global_step', trainable=False, dtype=tf.int32)\n self.X = tf.placeholder(tf.float32, shape=[None, self.X_dim ], name=\"data\")\n self.z = tf.placeholder(tf.float32, shape=[None, self.z_dim], name=\"noise\")\n self.time_step = tf.placeholder(tf.int32)\n self.size = tf.placeholder(tf.int32)\n self.init_w = tf.contrib.layers.xavier_initializer()\n self._create_network()\n self._loss_function(self.X_hat,self.X,self.mu, self.log_var)\n self.sess = tf.InteractiveSession()\n self.saver = tf.train.Saver(max_to_keep=1)\n self.init = tf.global_variables_initializer().run()\n\n def _Q(self, reuse=False):\n with tf.variable_scope(\"gq\", reuse=reuse):\n h = tf.layers.dense(inputs=self.X, units=800, kernel_initializer=self.init_w, use_bias=False)\n h = tf.layers.batch_normalization(h, axis=1, training=self.is_training)\n h = tf.nn.leaky_relu(h)\n h = tf.layers.dropout(h, self.dr_rate, training=self.is_training)\n h = tf.layers.dense(inputs=h, units=800, kernel_initializer=self.init_w, use_bias=False)\n h = tf.layers.batch_normalization(h, axis=1, training=self.is_training)\n h = tf.nn.leaky_relu(h)\n h = tf.layers.dropout(h,self.dr_rate, training=self.is_training)\n mean = tf.layers.dense(inputs=h, units=self.z_dim, kernel_initializer=self.init_w)\n log_var = tf.layers.dense(inputs=h, units=self.z_dim, kernel_initializer=self.init_w)\n return mean, log_var\n\n def _P(self, z, reuse=False):\n with tf.variable_scope(\"gp\", reuse=reuse):\n h = tf.layers.dense(inputs=z, units=800, kernel_initializer=self.init_w, use_bias=False)\n h = tf.layers.batch_normalization(h, axis=1, training=self.is_training)\n h = tf.nn.leaky_relu(h)\n h = tf.layers.dropout(h, self.dr_rate, training=self.is_training)\n\n h = tf.layers.dense(inputs=h, units=800, kernel_initializer=self.init_w, use_bias=False)\n tf.layers.batch_normalization(h, axis=1, training=self.is_training)\n h = tf.nn.leaky_relu(h)\n h = tf.layers.dropout(h, self.dr_rate, training=self.is_training)\n h = tf.layers.dense(inputs=h, units=self.X_dim, kernel_initializer=self.init_w, use_bias=True)\n h = tf.nn.relu(h)\n return h\n\n def _sample_z(self, mu, log_var, size):\n eps = tf.random_normal(shape=[size, self.z_dim])\n return mu + tf.exp(log_var / 2) * eps\n\n def _create_network(self):\n self.mu, self.log_var = self._Q()\n self.z_mean = self._sample_z(self.mu, self.log_var, self.size)\n self.X_hat = self._P(self.z_mean)\n\n def _loss_function(self, x_hat, x, mu, log_var):\n kl_loss = 0.5 * tf.reduce_sum(tf.exp(log_var) + tf.square(log_var) - 1. - log_var, 1)\n recon_loss = 0.5 * tf.reduce_sum(tf.square((x - x_hat)), 1)\n self.vae_loss = tf.reduce_mean(recon_loss + .01 * kl_loss)\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n self.solver = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.vae_loss)\n\n def _to_latent(self, data):\n latent = self.sess.run(self.z_mean, feed_dict={self.X: data, self.size: len(data), self.is_training: False})\n return latent\n\n def _avg_vector(self,data):\n latent = self._to_latent(data)\n latent_avg = np.average(latent,axis=0)\n return latent_avg\n\n def _reconstruct(self, data,use_data=False):\n if(use_data):\n latent = data\n else:\n latent = self._to_latent(data)\n rec_data = self.sess.run(self.X_hat,feed_dict = {self.z_mean:latent, self.is_training:False})\n return rec_data\n\n def linear_interploation(self, x, y, nb_steps):\n start = self._to_latent(np.average(x, axis=0).reshape((1, x.shape[1])))\n end = self._to_latent(np.average(y, axis=0).reshape((1, x.shape[1])))\n vectors = np.zeros((nb_steps, start.shape[1]))\n alphaValues = np.linspace(0, 1, nb_steps)\n for i, alpha in enumerate(alphaValues):\n vector = start * (1 - alpha) + end * alpha\n vectors[i, :] = vector\n vectors = np.array(vectors)\n interpolation = self._reconstruct(vectors, use_data=True)\n return interpolation\n\n def predict(self, celltype_to_predict):\n cd_x = self.dr.train_real_adata[self.dr.train_real_adata.obs[\"condition\"] == self.conditions[\"ctrl\"], :]\n cd_x = self.dr.balancer(cd_x)\n stim_x = self.dr.train_real_adata[self.dr.train_real_adata.obs[\"condition\"] == self.conditions[\"stim\"], :]\n stim_x = self.dr.balancer(stim_x)\n cd_y = self.dr.extractor(self.dr.train_real_adata,celltype_to_predict)[1]\n eq = min(cd_x.X.shape[0], stim_x.X.shape[0])\n cd_ind = np.random.choice(range(cd_x.shape[0]), size=eq, replace=False)\n stim_ind = np.random.choice(range(stim_x.shape[0]), size=eq, replace=False)\n lat_cd = self._avg_vector(cd_x.X[cd_ind, :])\n lat_stim = self._avg_vector(stim_x.X[stim_ind, :])\n delta = lat_stim - lat_cd\n latent_cd = self._to_latent(cd_y.X)\n stim_pred = delta + latent_cd\n predicted_cells = self._reconstruct(stim_pred, use_data=True)\n return predicted_cells, delta\n\n\n def predict_cross(self, data):\n cd_x = self.dr.train_real_adata[self.dr.train_real_adata.obs[\"condition\"] == self.conditions[\"ctrl\"], :]\n cd_x = self.dr.balancer(cd_x)\n stim_x = self.dr.train_real_adata[self.dr.train_real_adata.obs[\"condition\"] == self.conditions[\"stim\"], :]\n stim_x = self.dr.balancer(stim_x)\n cd_y = data\n eq = min(cd_x.X.shape[0], stim_x.X.shape[0])\n cd_ind = np.random.choice(range(cd_x.shape[0]), size=eq, replace=False)\n stim_ind = np.random.choice(range(stim_x.shape[0]), size=eq, replace=False)\n lat_cd = self._avg_vector(cd_x.X[cd_ind, :])\n lat_stim = self._avg_vector(stim_x.X[stim_ind, :])\n delta = lat_stim - lat_cd\n latent_cd = self._to_latent(cd_y)\n stim_pred = delta + latent_cd\n predicted_cells = self._reconstruct(stim_pred, use_data=True)\n return predicted_cells, delta\n\n def restore_model(self):\n self.saver.restore(self.sess, self.model_to_use)\n\n def linear_interploation(self, x, y, nb_steps):\n start = self._to_latent(np.average(x, axis=0).reshape((1, x.shape[1])))\n end = self._to_latent(np.average(y, axis=0).reshape((1, x.shape[1])))\n vectors = np.zeros((nb_steps, start.shape[1]))\n alphaValues = np.linspace(0, 1, nb_steps)\n for i, alpha in enumerate(alphaValues):\n vector = start * (1 - alpha) + end * alpha\n vectors[i, :] = vector\n vectors = np.array(vectors)\n interpolation = self._reconstruct(vectors, use_data=True)\n return interpolation\n\n\n\n\n def train(self, n_epochs, early_stop_limit=20, threshold=0.0025, full_training=True, initial_run=True):\n if initial_run:\n print(\"----Training----\")\n assign_step_zero = tf.assign(self.global_step, 0)\n init_step = self.sess.run(assign_step_zero)\n if not initial_run:\n self.saver.restore(self.sess, self.model_to_use)\n loss_hist = []\n patience = early_stop_limit\n min_delta = threshold\n patience_cnt = 0\n for it in range(n_epochs):\n increment_global_step_op = tf.assign(self.global_step, self.global_step + 1)\n step = self.sess.run(increment_global_step_op)\n current_step = self.sess.run(self.global_step)\n train_loss = 0\n if (full_training):\n input_ltpm_matrix = self.train_real[0:self.train_real.shape[0] // self.batch_size * self.batch_size, :]\n if self.use_validation:\n X_valid = self.valid_real[0:self.valid_real.shape[0] // self.batch_size * self.batch_size, :]\n for lower in range(0, input_ltpm_matrix.shape[0], self.batch_size):\n upper = min(lower + self.batch_size, input_ltpm_matrix.shape[0])\n X_mb = input_ltpm_matrix[lower:upper, :]\n _, D_loss_curr = self.sess.run(\n [self.solver, self.vae_loss], feed_dict={self.X: X_mb, self.time_step: current_step,\n self.size: self.batch_size, self.is_training: True})\n train_loss += D_loss_curr\n\n if self.use_validation:\n valid_loss = 0\n for lower in range(0, X_valid.shape[0], self.batch_size):\n upper = min(lower + self.batch_size, X_valid.shape[0])\n\n X_mb = X_valid[lower:upper, :]\n valid_loss_epoch = self.sess.run(self.vae_loss, feed_dict={self.X: X_mb, self.time_step: current_step,\n self.size: self.batch_size, self.is_training: False})\n valid_loss += valid_loss_epoch\n loss_hist.append(valid_loss / X_valid.shape[0])\n if it > 0 and loss_hist[it - 1] - loss_hist[it] > min_delta:\n patience_cnt = 0\n else:\n patience_cnt += 1\n if patience_cnt > patience:\n save_path = self.saver.save(self.sess, self.model_to_use)\n break\n save_path = self.saver.save(self.sess, self.model_to_use)\n print(f\"Model saved in file: {save_path}\")\n print(f\"Training finished\")\n\n\n\n\n\n","sub_path":"code/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":10654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615192018","text":"import os\r\nos.chdir(\"C:\\\\Users\\minec\\Desktop\\Programming\\Python\\Internship\\BotGit\\\\v1.2\")\r\nimport requests\r\nimport json\r\nimport re\r\n\r\nclass DopFunc:\r\n def __init__(self):\r\n self.name_and_url = {}\r\n self.answer_for_search = \"\"\r\n\r\n def get_commits_message(self, repo_url):\r\n apiURL = 'api.github.com'\r\n message_id = 0\r\n url = repo_url.split('github.com')\r\n try:\r\n self.info = requests.get(f'{url[0]}{apiURL}/repos{url[1]}/commits').json()\r\n for part in self.info:\r\n self.name_and_url[part[\"commit\"][\"message\"] + \" id-\" + str(message_id)] = part[\"url\"]\r\n message_id = message_id + 1\r\n return \"U join!\"\r\n except:\r\n return \"Wrong repo url\"\r\n\r\n def search(self,pattern):\r\n self.answer_for_search = \"\"\r\n pattern = pattern.lstrip(\"find:\")\r\n for message in self.name_and_url.keys():\r\n if re.match(pattern,message):\r\n self.answer_for_search = self.answer_for_search + message + \" - \" + self.name_and_url[message] + \"\\n\"\r\n return \"Result of search: \\n\" + self.answer_for_search","sub_path":"Telebot/v1.2/DopFunc.py","file_name":"DopFunc.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"407613212","text":"# 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 def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return None\n\n def reverse(node):\n if not node or not node.next:\n return node\n head = reverse(node.next)\n node.next.next = node\n node.next = None\n return head\n\n def find_mid(node):\n slow = fast = node\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\n mid_node = find_mid(head)\n head2 = mid_node.next\n mid_node.next = None\n head2 = reverse(head2)\n\n dummy = ListNode(-1)\n cur = dummy\n flag = True\n while head and head2:\n if flag:\n cur.next = head\n head = head.next\n else:\n cur.next = head2\n head2 = head2.next\n cur = cur.next\n flag = not flag\n cur.next = head if head else head2\n return dummy.next","sub_path":"143_重排链表.py","file_name":"143_重排链表.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"431827811","text":"#!/usr/bin/python3\nfrom __future__ import print_function\nimport os\n\n\nimport datetime\n\nimport configparser\nimport time\n#import pytz\n\n\nfrom enum import Enum\n\nimport paho.mqtt.client as mqtt\nfrom threading import Thread\nfrom queue import Queue\n\n\n\nheatMgrQueue = 0\n\nECS_COMMAND_OFF = b'1'\nECS_COMMAND_ON = b'2'\n\n\nlastTemperatureUpdate = datetime.datetime.now()\ncurrentTemperatureUpdate = datetime.datetime.now()\nglobal configWarningSender, configWarningRecipient, configSmtpLogin, configSmtpPassword\nglobal ecsState, ecsRemoteState, ecsStateForced, ecsTemperature, ecsHeatTarget \nglobal warnSent\n\nwarnSent = False\ntargetReached = False\n\n\n#defines\nECS_HEAT_PROFILE_LOW = \"LOW\"\nECS_HEAT_PROFILE_MEDIUM = \"MEDIUM\"\nECS_HEAT_PROFILE_HIGH = \"HIGH\"\n\nECS_STATE_OFF = \"OFF\"\nECS_STATE_ON = \"ON\"\n\nECS_FORCE_DISABLED = \"FORCE_DISABLED\"\nECS_FORCE_OFF = \"FORCE_OFF\"\nECS_FORCE_ON = \"FORCE_ON\"\n\n\nOVERHEAT_TEMPERATURE = 61\nUNDERHEAT_TEMPERATURE = 16\n\n\n\nHEAT_MANAGER_PERIOD = 1\nDELAY_BETWEEN_TEMPERATURE_UPDATE = 60\n\nclass heatMgrMessage:\n def __init__(self, type, value, heatProfile=\"MEDIUM\"):\n self.type = type\n self.value = value\n self.heatProfile = heatProfile\n\n\n#=========================================================================# \n# callback definition for MQTT # \n#=========================================================================#\n\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 client.subscribe(\"ECS/temp2\")\n client.subscribe(\"ECS/force\")\n client.subscribe(\"ECS/command\")\n\ndef on_message(client, userdata, msg):\n tmpQueue = userdata\n tmpValue = \"\"\n #print (\"Callback tmpQueue : \") \n #print (tmpQueue)\n #print(msg.topic+\" \"+str(msg.payload) + \"\\n\")\n if msg.topic == \"ECS/force\":\n # print (\"Callback sending force command to heatManager\")\n if(msg.payload == b'0'):\n tmpValue = ECS_FORCE_DISABLED\n elif(msg.payload == b'1'):\n tmpValue = ECS_FORCE_OFF\n elif(msg.payload == b'2'):\n tmpValue = ECS_FORCE_ON\n else:\n print (\"Callback Error : Unknown Force command :\", msg.payload)\n tempMsg = heatMgrMessage('ECS_FORCE', tmpValue)\n tmpQueue.put(tempMsg)\n if msg.topic == \"ECS/temp2\":\n # print(\"Callback sending temperature to heatManager\")\n tempMsg = heatMgrMessage('ECS_TEMPERATURE', msg.payload)\n tmpQueue.put(tempMsg)\n if msg.topic == \"ECS/command\":\n # print(\"Callback sending ECS Command to heatManager\")\n tempMsg = heatMgrMessage('ECS_COMMAND', msg.payload)\n tmpQueue.put(tempMsg)\n\n\n\n \n \n#=========================================================================# \n# Heat profile to temperature conversion #\n#=========================================================================#\n \ndef getTargetTemperature(profile):\n if (profile == ECS_HEAT_PROFILE_HIGH):\n return 62\n elif (profile == ECS_HEAT_PROFILE_MEDIUM):\n return 58\n elif (profile == ECS_HEAT_PROFILE_LOW):\n return 53\n else:\n print(\"Unknown heatprofile. Defaulting to 53\", profile)\n return 53\n \n \ndef getStatusString():\n global ecsState, ecsRemoteState, ecsStateForced, ecsTemperature, ecsHeatTarget\n now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n result = \"\\n\\n=====================\\nTime : \"\n result += now\n result += \"\\n\\tECS state :\" + ecsState\n result += \"\\n\\tECS remote state :\" + ecsRemoteState\n result += \"\\n\\tECS force state :\" + str(ecsStateForced)\n result += \"\\n\\tECS temperature :\" + str(ecsTemperature)\n result += \"\\n\\tTarget temperature : \" + str(ecsHeatTarget)\n result += \"\\n=====================\"\n return result\n\n\ndef warnMessage(msg, mqttClient):\n print(msg) \n mqttClient.publish(\"ECS/warning\", payload=msg, qos=1, retain=True)\n return\n\ndef checkTemperatureValidity(temperature, mqttClient): \n global warnSent\n if(temperature < UNDERHEAT_TEMPERATURE):\n if(warnSent == False):\n warnMessage(\"Warning, the temperature of the ECS is getting low. Consider forcing ON\", mqttClient)\n warnSent = True\n if(temperature > OVERHEAT_TEMPERATURE):\n warnMessage(\"Warning, the temperature of the ECS is getting too high. Consider forcing OFF\", mqttClient)\n\n\n \n#=========================================================================#\n# Heat manager thread body #\n# processes messages from Queue : # \n# - ECS force state (from MQTTLoop thread) #\n# - temperature(s) (from MQTTLoop thread) #\n# - ECS command (from MQTTLoop thread) #\n#=========================================================================#\ndef heatManager(msqQueue, mqttClient):\n global ecsState, ecsRemoteState, ecsStateForced, ecsTemperature, ecsHeatTarget\n global lastTemperatureUpdate, currentTemperatureUpdate\n global targetReached\n global warnSent\n ecsState = ECS_STATE_OFF \n ecsRemoteState = ECS_STATE_OFF \n ecsStateForced = False\n ecsTemperature = 0\n ecsHeatTarget = 0\n\n nbMsg = 0\n \n while True:\n #print (\"HeatManager waiting for message\")\n msg = msqQueue.get()\n msgType = msg.type\n msgValue = msg.value\n msgHeatProfile = msg.heatProfile\n\n #print (\"HeatManager waking up. message received\")\n nbMsg += 1\n #print (\"nb message received\")\n print (\"#################################################\")\n now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (nbMsg, \"Time : \", now)\n\t\n \n \n #process messages\n if(msgType == \"ECS_COMMAND\"):\n #Reset warning message status\n warnSent = False\n \n print(getStatusString())\n print(\"====================================\")\n print(\"HeatManager : Processing ECS Command\")\n if (msgValue == ECS_COMMAND_OFF):\n print(\"Heat Manager : turning ECS OFF\")\n ecsState = ECS_STATE_OFF \n mqttClient.publish(\"ECS/state\", payload='1', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload='0', qos=1, retain=True)\n\n ecsRemoteState = ECS_STATE_OFF\n if(targetReached == False):\n warnMessage(\"Temperature not reached before turning Off\", mqttClient) \n\t \n\t\t \n elif (msgValue == ECS_COMMAND_ON):\n targetReached = False\n ecsState = ECS_STATE_ON\n ecsHeatTarget = getTargetTemperature(msgHeatProfile)\n \n #Check if temperature is recent enough to be valid, else warn user\n currentTime = datetime.datetime.now()\n deltaTime = currentTime - currentTemperatureUpdate\n deltaTimeInSeconds = deltaTime.total_seconds()\n if(deltaTimeInSeconds > DELAY_BETWEEN_TEMPERATURE_UPDATE *100):\n message = \"Warning : Switching ECS ON while temperature info may not be valid : \\nsensor update exceeded 100 times maximum delta time: \" + str(deltaTimeInSeconds) + \"seconds. \\nresetting temperature to avoid ON/OFF bypass\"\n ecsTemperature = 0\n warnMessage(message, mqttClient) \n \n if(ecsTemperature < ecsHeatTarget):\n print(\"Heat Manager : turning ECS ON\")\n mqttClient.publish(\"ECS/state\", payload='2', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload=ecsHeatTarget, qos=1, retain=True)\n\t\t\t\n ecsRemoteState = ECS_STATE_ON\n else:\n message = \"Heat Manager : No ECS ON despite command, due to target temperature already reached\" \n warnMessage(message, mqttClient) \n\n else: \n print(\"Heat Manager : Error : unknown EcsCommand %s in received message\" % msgValue)\n\n elif(msgType == \"ECS_TEMPERATURE\"):\n\n ecsTemperature = float(msgValue)\n\n lastTemperatureUpdate = currentTemperatureUpdate\n currentTemperatureUpdate = datetime.datetime.now()\n deltaTime = currentTemperatureUpdate - lastTemperatureUpdate\n deltaTimeInSeconds = deltaTime.total_seconds()\n \n if(deltaTimeInSeconds > DELAY_BETWEEN_TEMPERATURE_UPDATE * 4):\n message = \"Warning : Temperature update from sensor exceeded 4 times maximum delta time: \" + str(deltaTimeInSeconds) + \"seconds\"\n warnMessage(message, mqttClient)\n \n \n print (\"updating temperature : \", ecsTemperature, \" <> Target :\", ecsHeatTarget)\n checkTemperatureValidity(ecsTemperature, mqttClient)\n #Check against temperature target when ECS is ON and not in forced mode\n if ((ecsState == ECS_STATE_ON) and (ecsStateForced == False)):\n if (ecsTemperature > ecsHeatTarget):\n targetReached = True\n\n print(\"Heat Manager : Switching ECS OFF due to target temperature reached\")\n ecsState = ECS_STATE_OFF\n mqttClient.publish(\"ECS/state\", payload='1', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload='0', qos=1, retain=True)\n\n ecsRemoteState = ECS_STATE_OFF\n \n elif(msgType == \"ECS_FORCE\"): \n print(getStatusString())\n print (\"HeatMgr : ecsState\", ecsState)\n if (msgValue == ECS_FORCE_OFF):\n print(\"Heat Manager : Forcing ECS OFF\") \n ecsStateForced = True\n print(\"\\tHeat Manager : Switching ECS OFF\") \n mqttClient.publish(\"ECS/state\", payload='1', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload='0', qos=1, retain=True)\n\n ecsState = ECS_STATE_OFF\n ecsRemoteState = ECS_STATE_OFF\n\t\t\n elif (msgValue == ECS_FORCE_ON):\n print(\"Heat Manager : Forcing ECS ON\") \n ecsStateForced = True\n print(\"\\tHeat Manager : Switching ECS ON\") \n mqttClient.publish(\"ECS/state\", payload='2', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload='100', qos=1, retain=True)\n\n ecsState = ECS_STATE_ON\n ecsRemoteState = ECS_STATE_ON\n elif (msgValue == ECS_FORCE_DISABLED):\n print(\"Heat Manager : Disabling Forcing ECS\") \n ecsStateForced = False\n print(\"\\tHeat Manager FORCE DISABLED : Switching ECS OFF\") \n mqttClient.publish(\"ECS/state\", payload='1', qos=1, retain=True)\n mqttClient.publish(\"ECS/target\", payload='0', qos=1, retain=True)\n ecsState = ECS_STATE_OFF\n ecsRemoteState = ECS_STATE_OFF\n\n\n else: \n print(\"Heat Manager : Unknown message value %s \" % msgValue)\n \n else:\n print(\"Heat Manager : Unknown message type %s \" % msgType)\n\n\n\n\n \n#=========================================================================#\n# Main... #\n#=========================================================================# \ndef main():\n print(\"STARTING main process\")\n config = configparser.ConfigParser()\n config.read('myconf.conf')\n\n mqttAddress = config.get('MQTT', 'mqttAddress')\n mqttPort = int(config.get('MQTT', 'mqttPort'))\n \n global heatMgrQueue\n heatMgrQueue = Queue()\n \n mqttClient = mqtt.Client(userdata=heatMgrQueue)\n print (\"heatMgrQueue : \") \n print (heatMgrQueue)\n mqttClient.on_connect = on_connect\n mqttClient.on_message = on_message\n mqttClient.connect(mqttAddress, mqttPort)\n mqttClient.loop_start()\n \n HeatManagerThread = Thread(target=heatManager, args=(heatMgrQueue,mqttClient,)) \n HeatManagerThread.start() \n\n while 1:\n time.sleep(1000)\n\nif __name__ == '__main__':\n main()\n","sub_path":"server/ECS_scheduler_new.py","file_name":"ECS_scheduler_new.py","file_ext":"py","file_size_in_byte":12688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"89897500","text":"class Solution(object):\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n if not str:\n return 0\n str = str.strip()\n length = len(str)\n if length == 0:\n return 0\n\n if str[0] == '-' or str[0] == '+':\n i = 1\n else:\n i = 0\n\n result = 0\n while i < length and str[i].isdigit():\n result = result * 10 + int(str[i])\n i += 1\n\n if str[0] == '-':\n return max(-2147483648,-result)\n\n return min(2147483647, result)\n","sub_path":"8. String to Integer (atoi).py","file_name":"8. String to Integer (atoi).py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"555542855","text":"import numpy as np\nfrom keras.models import Model\nfrom keras.layers import Dense, Input, BatchNormalization, regularizers, Dropout, GaussianNoise, Activation\nfrom keras.optimizers import sgd, nadam, adam, Adadelta\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\n\n# https://github.com/benjaminirving/mlseminars-autoencoders\n\ndef sparse_ae(x_train, para):\n filepath = '../saved_models/' + para['model_name']\n nb_features = x_train.shape[1]\n # build model\n early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=2000, verbose=1, mode='auto')\n checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=False, mode='min')\n # callbacks_list = [early_stop, checkpoint]\n callbacks_list = []\n autoencoder = dynamic_build(nb_features, para)\n\n # sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n\n autoencoder.compile(loss='mse', optimizer=adam(lr=para['lr']))\n autoencoder.fit(x_train, x_train,\n epochs=para['nb_epoch'],\n batch_size=para['size_of_batch'],\n shuffle=True,\n validation_split=0.33,\n callbacks=callbacks_list\n )\n return autoencoder\n\n\ndef dynamic_build(nb_features, para):\n act_func = 'relu'\n input_L = Input(shape=(nb_features,))\n noise_L = GaussianNoise(para['g_noise'])(input_L)\n # encoding\n for inx, val in enumerate(para['nm_layer']):\n nm_nodes = np.round(nb_features * val, 0).astype(int)\n if inx == 0:\n encoded = Dense(nm_nodes)(noise_L)\n encoded = Activation(act_func)(encoded)\n\n else:\n encoded = Dense(nm_nodes)(encoded)\n encoded = Activation(act_func)(encoded)\n encoded = BatchNormalization()(encoded)\n encoded = Dropout(para['drop_rate'])(encoded)\n # dim\n if not para['nm_layer']:\n encoder_out = Dense(para['encoding_dim'], name='encoder_out', activation='relu',\n activity_regularizer=regularizers.l1(para['active_rug']))(input_L)\n else:\n encoder_out = Dense(para['encoding_dim'], name='encoder_out',\n activity_regularizer=regularizers.l1(para['active_rug']))(encoded)\n encoder_out = Dropout(para['drop_rate'])(encoder_out)\n # decoding\n for inx, val in enumerate(reversed(para['nm_layer'])):\n nm_nodes = np.round(nb_features * val, 0).astype(int)\n if inx == 0:\n decoded = Dense(nm_nodes)(encoder_out)\n decoded = Activation(act_func)(decoded)\n else:\n decoded = Dense(nm_nodes)(decoded)\n decoded = Activation(act_func)(decoded)\n decoded = BatchNormalization()(decoded)\n decoded = Dropout(para['drop_rate'])(decoded)\n if not para['nm_layer']:\n decoded = Dense(nb_features, activation='sigmoid')(encoder_out)\n else:\n decoded = Dense(nb_features, activation='sigmoid')(decoded)\n\n autoencoder = Model(inputs=input_L, outputs=decoded, name=para['model_name'])\n\n # construct the encoder model\n # encoder = Model(inputs=input_L, outputs=encoder_out)\n return autoencoder","sub_path":"models/autoencoder_model.py","file_name":"autoencoder_model.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"446919971","text":"\"\"\"\n1.\nНапишите итератор Fibonacci(n), который генерирует числа Фибоначчи до\nn включительно.\n\"\"\"\n\n\nclass Fib:\n def __init__(self, num):\n self.num = num\n self.cnt = 0\n\n def __next__(self):\n lst = [1, 1]\n while lst[-1] <= self.num:\n lst.append(lst[-1] + lst[-2])\n if lst[self.cnt] <= self.num:\n phase = self.cnt\n self.cnt += 1\n return lst[phase]\n raise StopIteration\n\n\n\"\"\"\n2.\nНапишите класс, объектом которого будет итератор производящий только\nчётные числа до n включительно.\n\"\"\"\n\n\nclass Even:\n def __init__(self, num):\n self.num = num\n self.start = 0\n\n def __next__(self):\n if self.start <= self.num:\n run = self.start\n self.start += 2\n return run\n raise StopIteration\n\n\n\"\"\"\n3.\nНапишите итератор factorials(n), генерирующий последовательность\nфакториалов натуральных чисел.\n\"\"\"\n\n\nclass Factorials:\n def __init__(self, num):\n self.num = num\n self.cnt = 0\n\n def __next__(self):\n lst = []\n val = 1\n for i in range(1, self.num + 1):\n val *= i\n lst.append(val)\n if self.cnt <= len(lst):\n phase = self.cnt\n self.cnt += 1\n try:\n return lst[phase]\n except IndexError:\n raise StopIteration\n\n\n\"\"\"\n4.*\nНапишите итератор BinomialCoefficients(n), генерирующий последовательность\nбиномиальных коэффициентов C0n,C1n,…,Cnn\nЗапрещается использовать факториалы.\n\"\"\"\n","sub_path":"lesson11/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"444960603","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 16 19:28:27 2017\n\n@author: LaVie\n\n1Day Close Price: \n 1. when bottom and how low; #Done\n 2. correlation: sector?Biotech only. Year/Month of IPO; #Done\n 3. match IPO scoop data w. Yahoo for split; Not needed for 1st day close.\n 4. 4m/1y/3y/AllTime low: only did all time.\n 5. 3 year high compare to IPO price (when, cmpared to offer and 1st day high): not needed for long term investor. \n 6. All time high: when and how. not practical for surviving company.\n 7. How many days stay below IPO price? Not important.\n\nData Quality:\n 1. Yahoo/Google can have data problem:\n CHRS, GWPH, SHPG wrong data\n SGYP 2011.12.1 transfer from OTC to NASDAQ Main\n VRTX Wrong data\n\n\"\"\"\n\nimport datetime\nimport time\nimport numpy as np\nimport pandas as pd\nimport pandas_datareader.data as web\nimport fix_yahoo_finance\n\nimport matplotlib.pyplot as plt\n\n#%% Get yahoo data\n\ndata = pd.read_csv('FBT.csv')\ndata['IPODate'] = \"\"\ndata['LowDate'] = \"\"\ndata['LowClose'] = np.nan\ndata['DaysToLow'] = np.nan\ndata['Low_pct_IPO'] = np.nan\n\nfor index, row in data.iterrows():\n history = web.get_data_yahoo(row.Tic)\n if len(history) == 0:\n print(row.Tic, \"empty\")\n continue\n data.loc[index, 'IPODate'] = history.index[0]\n data.loc[index, 'LowDate'] = history['Adj Close'].idxmin()\n data.loc[index, 'LowClose'] = history.loc[history['Adj Close'].idxmin()\n ].Close\n data.loc[index, 'DaysToLow'] = (\n history['Adj Close'].idxmin() - history.index[0]).total_seconds()/(24*60*60)\n data.loc[index, 'Low_pct_IPO'] = history['Adj Close'].min() / \\\n history['Adj Close'][0]\n time.sleep(0.2)\n\n# convert datetime to date. If empty will give error.\ndata['IPODate'] = data['IPODate'].dt.date\ndata['LowDate'] = data['LowDate'].dt.date\ndata.to_csv('IPO1DayPremium-FBT.csv')\n\n#%% Analysis\n\nplt.plot(data['IPODate'], data['Low_pct_IPO'], 'o')\nplt.show()\n\nplt.plot(data['IPODate'], data['DaysToLow'], 'o')\nplt.show()\n# take 10 years to reach low?\n\nplt.plot(data['IPODate'], data['LowDate'], 'o')\nplt.show()\n# 85-95 companies made low in 95; survivor prosper?\n\nplt.plot(data['LowDate'], data['Low_pct_IPO'], 'o')\n# 95, 03, 09 bear market; 09 worst\n\nplt.plot(data['LowDate'], data['DaysToLow'], 'o')\n# old companies making new low\n\nplt.plot(data['DaysToLow'], data['Low_pct_IPO'], 'o')\n# further -> deeper loss\n\ndata2 = data[data['IPODate'] < datetime.date(2009, 3, 1)]\nplt.plot(data2['IPODate'], data2['Low_pct_IPO'], 'o')\nplt.show()\ndata2['Low_pct_IPO'].describe()\n# mean 28% median 18% 75%: 37% 90%: 71%\n\n\n#%% Study LowClose **75min**. 25%-Median-75% 1.46-4.19-8.99\nplt.plot(data['IPODate'], data['LowClose'], 'o')\ndata2['LowClose'].describe()\n# IBB data2: 0.86-1.81-3.72 (Q0.9 = 6.75) (N>70, IPO<2009.3.1)\n# FBT data2: 2.4-4.3-7.0 much higher (N=22, IPO<2009.3.1) 19%-35%-70%, took three years to reach low.\n\n# Reflections:\n# use all time low as indicator?\n# what's the difference between XBI and IBB. Is IBB going to outperform?\n\n#%% study overlap 45min 06182017\n# IBB has many recent IPO who already dropped, but not in XBI.\nibb = pd.read_csv('IBB_20170615.csv')\nxbi = pd.read_csv('XBI20170617.csv')\noverlap = pd.merge(ibb, xbi, how='inner')\nibbUnique = ibb[~ibb.Tic.isin(overlap.Tic)]\nxbiUni = xbi[~xbi.Tic.isin(overlap.Tic)]\n\nibbData = pd.read_csv('IPO1DayPremium-IBB.csv',\n index_col=0, parse_dates=[2, 3])\nibbUniData = pd.merge(ibbData, ibbUnique, how='inner')\n\nxbiData = pd.read_csv('IPO1DayPremium-XBI.csv',\n index_col=0, parse_dates=[2, 3])\n\nplt.plot(ibbUniData['IPODate'], ibbUniData['Low_pct_IPO'], 'o')\nplt.show()\nplt.plot(xbiData['IPODate'], xbiData['Low_pct_IPO'], 'o')\nplt.show()\nplt.plot(ibbData['IPODate'], ibbData['Low_pct_IPO'], 'o')\nplt.show()\n\nless4 = ibbUniData[ibbUniData.Low_pct_IPO < 0.4]\ny12pct4 = less4[less4.IPODate > datetime.datetime(2012, 1, 1)]\n","sub_path":"IPOPremium/IPO1DayPremium.py","file_name":"IPO1DayPremium.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"61569900","text":"import numpy as np\ndef compute_G(A):\n # This method is OPTIONAL. If implemented, it should take the A\n # matrix (a numpy.ndarray) and return the appropriate G matrix\n # (also a numpy.ndarray). If you choose to use this method, you\n # will call it as part of encode().\n k=A.shape[0]\n I=np.identity(k,int)\n G=np.concatenate([I,A],axis=1)\n return G\n\ndef compute_H(A):\n # This method is OPTIONAL. If implemented, it should take the A\n # matrix (a numpy.ndarray) and return the appropriate H matrix\n # (also a numpy.ndarray). IF you choose to use this method, you\n # will call it as part of decode().\n k=A.shape[1]\n I=np.identity(k,int)\n H=np.concatenate([A.T,I], axis=1) \n return H\n\ndef compute_syndromes(H):\n # This method is OPTIONAL. If implemented, it should take the H\n # matrix (a numpy.ndarray) and return a dictionary that provides a\n # mapping between error vectors and their corresponding symbols.\n # The data structures used within the mapping will differ\n # depending on your implementation of decode; for this reason, we\n # do not provide an explicit testing method for this function. If\n # you choose to use this method, you will call it as part of\n # decode().\n pass\n\ndef encode(A, message):\n # This method is REQUIRED. Here, you should implement the linear\n # encoder. This requires the following steps:\n # 1. Calculate the G matrix\n # 2. Break the message into k-length blocks\n # 3. Use G to determine the codewords for each block\n # 4. Concatenate the codewords into a single string and return it\n G=compute_G(A)\n k=A.shape[0]\n blocks=[message[i:i+k] for i in range(0,len(message),k)]\n data_vectors=[np.array([[int(m) for m in message]]) for message in blocks]\n codewords=[((d.dot(G))%2).flatten().tolist() for d in data_vectors]\n #print codewords\n encoded_bits=[str(b) for codeword in codewords for b in codeword]\n #print encoded_bits\n return ''.join(encoded_bits)\n \n\ndef decode(A, encoded_bits):\n # This method is REQUIRED. Here you should implement the syndrome\n # decoder. This requires the following steps:\n # 1. Calculate the H matrix\n # 2. Use H to set up the syndrome table\n # 3. Break the message into n-length codewords\n # 4. For each codeword, calculate the error bits\n # 5. If the error bits are nonzero, use the syndrome table to correct the error.\n # 6. Return the corrected bitstring\n #\n # Though we are not requiring it, we recommend you set up the\n # syndrome table before you perform the decoding, via the\n # compute_syndromes() function. This will result in a more\n # organized design, and also a more efficient decoding procedure\n # (because you won't be recalculating the syndrome table for each\n # codeword).\n H=compute_H(A)\n k=A.shape[0]\n n=A.shape[0]+A.shape[1]#k+m\n errors=[i for i in np.identity(n,int)]#error patterns taken from rows of I_n\n syndrome_table={''.join([str(x) for x in (H.dot(i.T)%2).flatten().tolist()]): i for i in errors}#{H*error_pattern_i:error_pattern_i}=={syndrome_i:error_pattern_i} \n codewords=[encoded_bits[i:i+n] for i in range(0, len(encoded_bits), n)]#list of string chunks\n received=[np.array([[int(b) for b in bits]]) for bits in codewords]#comprehend string chunks into bits into (1xn) ndarray\n syndromes=[''.join([str(b) for b in (H.dot(r.T)%2).flatten().tolist()]) for r in received]#(syndrome of each received codeword, the received codeword)\n bitstrings=[]\n for s in range(len(syndromes)):\n if syndromes[s] in syndrome_table:\n bitstrings.append(((received[s]+syndrome_table[syndromes[s]].T)%2).flatten().tolist()[0:(n-k+1)])\n else: #zero syndrome\n bitstrings.append(received[s].flatten().tolist()[0:(n-k+1)])\n corrected=[str(b) for c in bitstrings for b in c]\n return ''.join(corrected)\n \n \n \n \n\n","sub_path":"6.02/PS2/PS2_code/PS2.py","file_name":"PS2.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"276903549","text":"# -*- coding: utf-8 -*-\n# -------------------------------------------------------------------------------\n# Copyright 2002 yafra.org\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#\n# external environment variables:\n# YAFRA_DEBUG (set with something means True, else False)\n\nimport os\n\n_basedir = os.path.abspath(os.path.dirname(__file__))\n\nif ('YAFRA_DEBUG' in os.environ):\n DEBUG = True\nelse:\n DEBUG = False\n\nVERSION=\"0.1.0\"\n\nRESTBASEURL=\"/yafraapi\"\nRESTVERURL=\"/v1\"\n\n# Enable reads (GET), inserts (POST) and DELETE for resources/collections\n# (if you omit this line, the API will default to ['GET'] and provide\n# read-only access to the endpoint).\nRESOURCE_METHODS = ['GET', 'POST', 'DELETE']\n\n# Enable reads (GET), edits (PATCH) and deletes of individual items\n# (defaults to read-only item access).\nITEM_METHODS = ['GET', 'PATCH', 'DELETE']\n\n# We enable standard client cache directives for all resources exposed by the\n# API. We can always override these global settings later.\nCACHE_CONTROL = 'max-age=20'\nCACHE_EXPIRES = 20","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"402325325","text":"import os\nimport json\nimport time\nimport importlib\nimport argparse\nimport numpy as np\nfrom collections import OrderedDict\nimport torch\nimport torch.nn as nn\nimport skimage.measure as measure #tcw201904101622tcw\nfrom torch.autograd import Variable\nfrom dataset_1203 import TestDataset\nfrom PIL import Image\nimport cv2 #201904111751tcwi\n#from torchsummary import summary #tcw20190623\n#from torchsummaryX import summary #tcw20190625\nos.environ['CUDA_VISIBLE_DEVICES']='3'\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", type=str, default = 'lesrcnn')\n parser.add_argument(\"--ckpt_path\", type=str, default = '1207_Steven_4x_2019data_lesrcnn_x4_1939.pth')\n parser.add_argument(\"--group\", type=int, default=1)\n parser.add_argument(\"--sample_dir\", type=str, default = './1207_Steven_4x_2019data_lesrcnn_x4_1939_SR_images')\n parser.add_argument(\"--test_data_dir\", type=str, default=\"../lj_test_images\")\n parser.add_argument(\"--cuda\", action=\"store_true\")\n parser.add_argument(\"--scale\", type=int, default=4)\n parser.add_argument(\"--shave\", type=int, default=20)\n\n return parser.parse_args()\n\ndef save_image(tensor, filename):\n tensor = tensor.cpu()\n ndarr = tensor.mul(255).clamp(0, 255).byte().permute(1, 2, 0).numpy()\n im = Image.fromarray(ndarr)\n im.save(filename)\n\n#tcw20190413043\ndef sample(net, device, dataset, cfg):\n scale = cfg.scale\n mean_psnr = 0\n mean_psnr1 = 0\n mean_psnr2 = 0\n mean_ssim = 0 #tcw20190413047\n for step, (lr, name) in enumerate(dataset):\n\n t1 = time.time()\n #print '--------'\n print(lr.size()) #e.g (3,512,512)\n lr = lr.unsqueeze(0).to(device)\n print(lr.size())\n #print lr.size() #(1,3,512,512)\n #b = net(lr, cfg.scale).detach()\n #print b.size() #(1,3,1024,1024)\n sr = net(lr, cfg.scale).detach().squeeze(0) #detach() break the reversed transformation.\n print(sr.size()) #(3,1024,1024)\n lr = lr.squeeze(0)\n #print lr.size() #(3,512,512)\n t2 = time.time()\n #print model_name\n sr_dir = cfg.sample_dir\n if not os.path.exists(sr_dir): #201904072208 tcw\n os.makedirs(sr_dir, mode=0o777)\n \n sr_name = name.split('.jpg')[0] + '_SR.png'\n sr_im_path = os.path.join(sr_dir, sr_name) \n save_image(sr, sr_im_path)\n \n\ndef main(cfg):\n module = importlib.import_module(\"model.{}\".format(cfg.model))\n ''' \n net = module.Net(multi_scale=False, \n group=cfg.group)\n '''\n net = module.Net(scale=cfg.scale, \n group=cfg.group)\n #print(net)\n '''\n #net = MyModel\n params = list(net.parameters())\n k = 0\n for i in params:\n l = 1\n\t#print('' + str(list(i.size())))\n\tfor j in i.size():\n l *= j\n\t #print('' + str(l))\n\t k = k + l\n\tprint(''+ str(k))\n '''\n #print(json.dumps(vars(cfg), indent=4, sort_keys=True)) #print cfg information according order.\n state_dict = torch.load(cfg.ckpt_path, map_location = 'cpu')\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = k\n # name = k[7:] # remove \"module.\"\n new_state_dict[name] = v\n\n net.load_state_dict(new_state_dict)\n #os.environ['CUDA_VISIBLE_DEVICES']='0,1'\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") #0 is number of gpu, if this gpu1 is work, you can set it into 1 (device=torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\"))\n net = net.to(device)\n #summary(net,[(3,240, 160),(3,1000, 2000)]) #tcw20190623\n #summary(net,[torch.zeros(1,3,240,160),2],2)\n\n dataset = TestDataset(cfg.test_data_dir, cfg.scale)\n sample(net, device, dataset, cfg)\n \n\nif __name__ == \"__main__\":\n cfg = parse_args()\n main(cfg)\n","sub_path":"1207_LESRCNN_test_CPU/1202_tcw_sample.py","file_name":"1202_tcw_sample.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"397253120","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse,JsonResponse, HttpRequest, HttpResponseRedirect\nfrom django.forms import modelformset_factory, formset_factory\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .forms import *\nfrom django.db.models import Avg\n\nListeArticles = Articles.objects.all()\nListeMedia = Media.objects.all()\nListeComments = Commentaires.objects.all()\n\n# Create your views here.\ndef article(request, slug,):\n article = ListeArticles.get(slug=slug)\n article.average = ListeComments.filter(comment_article=article.id).aggregate(Avg('comment_rating'))\n images = Media.objects.filter(media_article=article)\n Comments = ListeComments.filter(comment_article=article.id)\n CommentsForm = FormComment()\n CommentsForm.fields[\"comment_article\"].initial = article.id\n \n #si une reservation est faite\n if request.method == 'POST':\n form = FormComment(request.POST)\n if form.is_valid():\n form.save()\n return render(request, 'gestion_voies/article.html', locals())\n\ndef liste_annonces(request):\n ListeArticles = Articles.objects.all()\n #Ajoute pour chaque agences le nombre de voiture et le code postal\n for article in ListeArticles:\n article.img = Media.objects.filter(media_article=article.id).first()\n article.average = ListeComments.filter(comment_article=article.id).aggregate(Avg('comment_rating'))\n return render(request, 'gestion_voies/liste_annonces.html', locals())\n\ndef formulaire(request):\n article = FormArticle()\n images = FormMedia()\n if request.method == 'POST':\n form = FormArticle(request.POST)\n files = request.FILES.getlist('images')\n if form.is_valid():\n post_form = form.save()\n post_form.save()\n for f in files:\n Media.objects.create(media_article=post_form,media_img=f)\n return redirect('index')\n return render(request, 'gestion_voies/formulaire.html', locals())\n","sub_path":"enoki_climbing/gestion_voies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"271833194","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 29 23:59:30 2017\n\n@author: owen\n\"\"\"\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n#class Solution(object):\n# def findTilt(self, root):\n# \"\"\"\n# :type root: TreeNode\n# :rtype: int\n# \"\"\"\n# def postorder(node):\n# if not node:\n# return 0\n# right=postorder(node.right)\n# left=postorder(node.left)\n# self.res+=abs(left-right)\n# return left+right+node.val\n# \n# self.res=0\n# postorder(root)\n# return self.res\n\nclass Solution:\n def findTilt(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def tilt(root):\n if not root: \n return (0, 0)\n left = tilt(root.left)\n right = tilt(root.right)\n return (left[0] + right[0] + root.val, abs(left[0] - right[0]) + left[1] + right[1]) # [0] sum of subtree node values, [1] lower level abs diff\n \n return tilt(root)[1]\n \nif __name__==\"__main__\":\n root=TreeNode(1)\n root.left=TreeNode(2)\n root.right=TreeNode(3)\n print(Solution().findTilt(root))","sub_path":"563. Binary Tree Tilt.py","file_name":"563. Binary Tree Tilt.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"572059884","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2011 Nebula, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django import http\nfrom django.core.urlresolvers import reverse\nfrom mox import IgnoreArg, IsA\n\nfrom horizon import api\nfrom horizon import test\n\n\nINDEX_URL = reverse('horizon:syspanel:tenants:index')\n\n\nclass FakeResource(object):\n def __init__(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n\nclass TenantsViewTests(test.BaseAdminViewTests):\n def setUp(self):\n super(TenantsViewTests, self).setUp()\n\n self.tenant = FakeResource(id=self.TEST_TENANT,\n name=self.TEST_TENANT_NAME,\n enabled=True)\n\n self.quota_data = dict(metadata_items='1',\n injected_file_content_bytes='1',\n volumes='1',\n gigabytes='1',\n ram=1,\n floating_ips='1',\n instances='1',\n injected_files='1',\n cores='1')\n self.quota = FakeResource(id=self.TEST_TENANT, **self.quota_data)\n\n self.tenants = [self.tenant]\n\n def test_index(self):\n self.mox.StubOutWithMock(api, 'tenant_list')\n api.tenant_list(IsA(http.HttpRequest)).AndReturn(self.tenants)\n\n self.mox.ReplayAll()\n\n res = self.client.get(INDEX_URL)\n\n self.assertTemplateUsed(res, 'syspanel/tenants/index.html')\n self.assertItemsEqual(res.context['table'].data, self.tenants)\n\n def test_modify_quota(self):\n self.mox.StubOutWithMock(api.keystone, 'tenant_get')\n self.mox.StubOutWithMock(api.nova, 'tenant_quota_get')\n self.mox.StubOutWithMock(api.nova, 'tenant_quota_update')\n\n api.keystone.tenant_get(IgnoreArg(), self.TEST_TENANT) \\\n .AndReturn(self.tenant)\n api.nova.tenant_quota_get(IgnoreArg(), self.TEST_TENANT) \\\n .AndReturn(self.quota)\n api.nova.tenant_quota_update(IgnoreArg(),\n self.TEST_TENANT,\n **self.quota_data)\n\n self.mox.ReplayAll()\n\n url = reverse('horizon:syspanel:tenants:quotas',\n args=(self.TEST_TENANT,))\n data = {\"method\": \"UpdateQuotas\",\n \"tenant_id\": self.TEST_TENANT,\n \"metadata_items\": '1',\n \"injected_files\": '1',\n \"injected_file_content_bytes\": '1',\n \"cores\": '1',\n \"instances\": '1',\n \"volumes\": '1',\n \"gigabytes\": '1',\n \"ram\": 1,\n \"floating_ips\": '1'}\n res = self.client.post(url, data)\n self.assertRedirectsNoFollow(res, INDEX_URL)\n","sub_path":"horizon/horizon/dashboards/syspanel/tenants/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142967936","text":"def SearchInTrie(T, s):\n if len(s) == 0:\n # weird, should not happen\n return False\n\n if len(s) > 0 and len(T) == 0:\n return False\n\n if len(s) == 1:\n return T[ord(s[0]) - ord('a')][1]\n\n return SearchInTrie(T[ord(s[0]) - ord('a')][0], s[1:])\n\n\ndef InsertIntoTrie(T, s):\n \"\"\"\n You need to implement this method.\n You are certainly allowed to define any subroutines you want\n above this method in this file.\n \"\"\"\n if len(s) == 0:\n return\n\n if len(T) == 0: \n # Initialize the Tree\n T.extend([[[], False] for _ in range(26)])\n\n position = ord(s[0]) - ord('a')\n\n if len(s) == 1:\n T[position][1] = True\n else:\n InsertIntoTrie(T[position][0], s[1:])\n\ndef istriempty(T): \n\n if len(T)== 0:\n return True\n \n for value in T: \n if value[1] == True: \n return False \n \n elif value[1] == False and len(value[0]) != 0: \n return False \n\n for index in T: \n if index[1] == False and len(index[0]) == 0: \n return True \n\n\ndef DeleteFromTrie(T, s):\n \"\"\"\n You need to implement this method.\n You are certainly allowed to define any subroutines you want\n above this method in this file.\n \"\"\"\n if len(s) >0: \n position = ord(s[0]) - ord('a')\n\n if len(s) > 1: \n DeleteFromTrie(T[position][0], s[1:])\n\n\n elif len(s) == 1:\n T[position][1] = False\n\n if istriempty(T):\n T.clear()\n\n return\n \n\nif __name__ == \"__main__\": \n\n T = []\n s1 = \"ca\"\n s2 = \"cat\"\n\n\n InsertIntoTrie(T, s1)\n # InsertIntoTrie(T, s2)\n\n print(\"Before T: \", T)\n # value1 = SearchInTrie(T, s1)\n # value2 = SearchInTrie(T, s2)\n\n # print(\" Value1(True): \", value1)\n # print(\" Value2(True): \", value2)\n\n\n DeleteFromTrie(T, s1)\n # value3 = SearchInTrie(T, s1)\n # print(\" Value3(False): \", value3)\n\n # value4 = SearchInTrie(T, s2)\n # print(\" Value4(True): \", value4)\n\n # DeleteFromTrie(T, s2)\n # value5 = SearchInTrie(T, s2)\n # print(\" Value5(False): \", value5) \n\n print(\"\\n\\n T: \", T)\n","sub_path":"CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"365917756","text":"import csv\nfrom pathlib import Path\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import preprocessing\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport numpy.matlib\nimport math as math\nimport itertools\n\n\n## List of all ML constraints belonging to class - pos\nposMLCons = []\n\n## List of all ML constraints belonging to class - neg\nnegMLCons = []\n\n## Create a list of NL constraints belonging to class - pos and neg\nposNegNLCons = []\n\n## List of pairs of ML constraints (randomly selected)\nlistMLConsPairs = []\n\n## List of pairs of NL constraints (randomly selected)\nlistNLConsPairs = []\n\n\n## Generate constraint pairs\ndef createRandomConsPairs(listCons, n):\n ## Generate all possible non-repeating pairs\n pairsCons = list(itertools.combinations(listCons, 2))\n \n ## Randomly shuffle these pairs\n random.shuffle(pairsCons)\n \n ## Randomly pick and return required no of pairs\n return random.sample(pairsCons, n)\n\n\n\n## Create a list of all ML constraints\ndef createMLConsList():\n for index, row in trainData.iterrows():\n if float(row[\"mrt_liverfat_s2\"]) <= 10:\n negMLCons.append(index)\n #unlabDataInst.append(row)\n elif float(row[\"mrt_liverfat_s2\"]) > 10:\n posMLCons.append(index)\n #unlabDataInst.append(row)\n else:\n unlabDataInst.append(index)\n\n return createRandomConsPairs(posMLCons, int(noMLCons/2)) + createRandomConsPairs(negMLCons, int(noMLCons/2))\n\n\n## Create a list of (pairs of) all NL constraints\ndef createNLConsList():\n for i, j in zip(posMLCons, negMLCons):\n tupNLCons = (i, j)\n posNegNLCons.append(tupNLCons)\n\n ## Create a list of (pairs of) NL constraints\n return random.sample(posNegNLCons, noNLCons) \n\n\n## Check whether the feature is nominal or not\ndef checkNominal(feature):\n nominal = True\n \n return nominal\n\n\n## Calculate the distance between object pairs in a feature\ndef calculateSqDistDiff(feature, objPairX, objPairY): \n \n ## If both oject pairs are nominal\n #if (checkNominal(feature)):\n # if (objPairX == objPairY):\n # diffDist = 0\n # else:\n # diffDist = 1\n ## If both object pairs are continuous\n #else:\n diffDist = objPairX - objPairY\n #print(\"Feature:\", feature)\n #print(\"objPairX = \", type(objPairX))\n #print(\"objPairY = \", objPairY)\n \n return (diffDist ** 2)\n\n\n## Calculate distance between object pairs for every feature in a feature space using Heterogeneous Euclidean Overlap Metric\ndef calculateHEOM(subspace, objPairX, objPairY):\n sumDistSq = 0\n \n ## Calculate distance between object pairs for every feature in a feature space using Heterogeneous Euclidean Overlap Metric \n for feature in subspace.columns:\n sumDistSq = sumDistSq + calculateSqDistDiff(feature, subspace.iloc[objPairX][feature], subspace.iloc[objPairY][feature])\n \n return math.sqrt(sumDistSq)\n\n\n## Calculate the average distance between object pairs in a subspace \ndef calculateAvgDist(subspace, listConsPairs):\n totalDist = 0\n \n for consPair in listConsPairs:\n totalDist = calculateHEOM(subspace, consPair[0], consPair[1])\n \n ## Total no of ML/NL constraints\n noConst = len(listMLConsPairs) + len(listNLConsPairs)\n \n avgDist = totalDist/noConst\n \n return avgDist\n\n\n## Calculate the quality score of a subspace based on distance\ndef calculateDistScore(subspace):\n ## Average distance between ML objects pairs\n avgDistML = calculateAvgDist(subspace, listMLConsPairs)\n \n ## Average distance between NL objects pairs\n avgDistNL = calculateAvgDist(subspace, listNLConsPairs)\n\n ## Quality score based on distance\n qualScoreDist = avgDistNL - avgDistML\n \n return qualScoreDist\n\n## Calculate the total no of satisfied NL constraints\ndef calculateNoSatisNLCons():\n i = 0\n \n listClusterMLCons = []\n \n listClusterNLCons = []\n \n for constPair in listNLConsPairs:\n for clusterNo in range(len(position_list)):\n if constPair[0] in position_list[clusterNo]:\n listClusterMLCons.append(clusterNo)\n\n if constPair[1] in position_list[clusterNo]:\n listClusterNLCons.append(clusterNo)\n \n listCommCluster = list(set(listClusterMLCons) - (set(listClusterMLCons) - set(listClusterNLCons)))\n \n if len(listCommCluster) < 1:\n i = i + 1\n \n return i\n\n\n## Calculate the total no of satisfied ML constraints\ndef calculateNoSatisMLCons():\n i = 0\n \n for constPair in listMLConsPairs:\n for clusterNo in range(len(position_list)):\n if constPair[0] in position_list[clusterNo] and constPair[1] in position_list[clusterNo]:\n i = i + 1\n \n return i\n\n\n## Calculate the quality score of a subspace based on constraint satisfaction\ndef calculateConstScore(): \n ## No of satisfied ML constraints\n noSatisML = calculateNoSatisMLCons()\n \n ## No of satisfied NL constraints\n noSatisNL = calculateNoSatisNLCons()\n \n ## Total no of ML constraints\n totalNoML = len(listMLConsPairs)\n \n ## Total no of NL constraints\n totalNoNL = len(listNLConsPairs)\n \n ## Quality score based on constraint satisfaction\n qualScoreConst = (noSatisML + noSatisNL)/(totalNoML + totalNoNL)\n \n return qualScoreConst\n\n\n## Calculate the quality score of each subspace based on the clustering performed by DBSCAN algorithm.\n#Input:\n#Output: Quality score for each subspace.\ndef calculateSubspaceScore(subspace):\n ## Quality score based on constraint satisfaction\n constraintScore = calculateConstScore()\n \n ## Quality score based on distance\n distanceScore = calculateDistScore(subspace)\n \n ## Final quality score\n finalScore = constraintScore + distanceScore\n\n return finalScore\n\n\n\n\n\n# from IPython.display import display, HTML\n## Test Data\n#TRAIN_PATH = '/media/sumit/Entertainment/OVGU - DKE/Summer 2018/Medical Data Mining/csv_result-ship_14072018.csv'\n\n## Original Data\n#TRAIN_PATH = '/media/sumit/Entertainment/OVGU - DKE/Summer 2018/Medical Data Mining/csv_result-ship_22042018.csv'\n\n## Labeled Data\nTRAIN_PATH = '/media/sumit/Entertainment/OVGU - DKE/Summer 2018/Medical Data Mining/csv_result-ship_labeled_data.csv'\n\ndef loadDatasetWithPandas(path):\n # Reading the raw data from csv file\n rawData = pd.read_csv(path)\n # display(rawData)\n # replacing the string indicating missing values with the numpy value for missing values\n # NaNProcessedData = rawData.replace({'na': np.nan}, regex=True)\n NaNProcessedData = rawData\n return NaNProcessedData\n\n\n# This function is used to make subspaces, SelectedFeature will contain the previous best subspace.\ndef makeSubspaces(trainingData, selectedFeature):\n subspacesList = []\n if len(selectedFeature) == 0:\n for cols in trainingData.columns:\n # 'here we have included {} columns'.format(noOfFeature)\n subspacesList.append(cols)\n else:\n # subspacesList=[[cols,item] for cols in trainingData.columns for item in selectedFeature]\n for cols in trainingData.columns:\n # 'here we have included {} columns'.format(noOfFeature)\n subspacesList.append([cols, selectedFeature])\n\n return subspacesList\n\n\n# This function generates a random score.\n# Sumit_Respo\n#def calculateSubspaceScore(featureList):\n# ConstrainedScore = random.randint(0, 100)\n# DistanceScore = random.randint(0, 100)\n# FinalScore = ConstrainedScore + DistanceScore\n# return FinalScore\n\n\n# This function will perform the DB-Scan Clustering Alorithm and compute the score on each subspaces.\n# Input: Subspace of features.\n# Output: Quality score for each subspace.\ndef performDBScan(subspace):\n featureSpace = []\n\n if type(subspace) == list:\n print(\"Selected Subscape\")\n for i in subspace:\n if type(i) == list:\n for k in i:\n # print(k)\n featureSpace.append(k)\n else:\n # print(i)\n featureSpace.append(i)\n else:\n # print(\"Selected Subspace\")\n # print(subspace)\n featureSpace.append(subspace)\n\n print(\"main\")\n print(featureSpace)\n\n CandidateDataFrame = pd.DataFrame(trainData, columns=featureSpace)\n #print(\"dataframe is: \")\n #print(CandidateDataFrame)\n print(\"Colums are\")\n print (CandidateDataFrame.columns)\n \n print(\"calling DB scan\")\n FinalScore = CreateDBCluster(CandidateDataFrame)\n\n return FinalScore\n\n\nposition_list = []\n\n# Implementation of DB Scan Algo\ndef CreateDBCluster(CandidateDataFrame):\n \n ## FITING THE DATA WITH DBSCAN\n db = DBSCAN(eps=epsilon, min_samples=minPts).fit(CandidateDataFrame)\n\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n \n lable_list = []\n\n print(\"Labels are: \")\n a=0;\n for i in labels:\n lable_list.append(i)\n #print(lable_list)\n\n output = []\n for x in lable_list:\n if x not in output:\n output.append(x)\n print (\"Unique values\")\n print (output)\n\n #position_list = []\n for k in output:\n if k != -1:\n a = 0\n custer_list = []\n for l in lable_list:\n\n if l == k:\n custer_list.append(a)\n a = a + 1\n\n position_list.append(custer_list)\n\n #print(\"Position List\")\n #print(position_list)\n\n # number of cluster ignoring noise point\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n print(\"No of Clusters\")\n print(n_clusters_)\n \n FinalScore = calculateSubspaceScore(CandidateDataFrame)\n print(\"Final Score: \", FinalScore)\n return FinalScore\n\n\n# Append a feature with the score. Example: [Rajesh , 150]\ndef scoreCalculate(ssList):\n subspaceScoresList = []\n bestSubspaceScore = []\n # subArray = []\n previousScore = 0\n currentscore = 0\n\n previousfeature = \"\"\n currentfeature = \"\"\n \n for feature in ssList:\n\n if currentscore >= previousScore:\n\n # subArray.append(feature)\n\n FinalsubSpaceScore = performDBScan(feature)\n\n previousScore = currentscore\n currentscore = FinalsubSpaceScore\n\n previousfeature = currentfeature\n currentfeature = feature\n\n print(\"Current Feature: \", currentfeature)\n print(\"Previous Feature: \", previousfeature)\n print(\"Current Score: \", currentscore)\n print(\"Previous Score: \", previousScore)\n\n subspaceScoresList.append([feature, FinalsubSpaceScore])\n \n else:\n bestSubspaceScore.append([previousfeature, previousScore])\n break\n\n print(\"Subspace Score List Total\", subspaceScoresList)\n print(\"Subspace Best Score\", bestSubspaceScore)\n\n\n return bestSubspaceScore\n\n\ndef bestScore(ssScoresList):\n return max_by_score(ssScoresList)\n\n\n# Traverses the list to get the best score(Max score)\ndef max_by_score(sequence):\n if not sequence:\n raise ValueError('empty sequence')\n maximum = sequence[0]\n for item in sequence:\n if item[1] > maximum[1]:\n maximum = item\n return maximum\n\n\n# This function iterates through the supspaces collects the best one and increases the cardinality every single time.\n# df = Data, feat_select = Selected best feature, previousBestScore = Previous best feature according to the random score generated\n# currentBestScore = Current best feature according to the random score genearted.\n\ndef iter_subspace(df, feat_select, previousBestScore, currentBestScore):\n while previousBestScore <= currentBestScore:\n possible_sslist = makeSubspaces(df, feat_select)\n score_sslist = scoreCalculate(possible_sslist)\n featureset_score = bestScore(score_sslist)\n features_for_nxt_iter = [item for item in df.columns if item not in featureset_score[0]]\n if featureset_score[0] not in features_selected:\n features_selected.append(featureset_score[0])\n previousBestScore = currentBestScore\n currentBestScore = featureset_score[1]\n featu = []\n inter_results = ConvertList(features_selected, featu)\n features_selected_final = getUniqueItems(featu)\n # print(possible_sslist)\n # print('')\n # print(score_sslist)\n # print('')\n print(\"Subspace With Best Score for the iteration\")\n print(featureset_score)\n # print(features_for_nxt_iter)\n print('')\n print(features_selected_final)\n print(\"Previous Best Subspace Score\")\n print(previousBestScore)\n print(\"Current Best Subspace Score\")\n print(currentBestScore)\n # print('')\n # print('')\n iter_subspace(df[features_for_nxt_iter], features_selected_final, previousBestScore, currentBestScore)\n break\n\n\n# This function is used to removed any duplicates in the list.\ndef getUniqueItems(iterable):\n seen = set()\n result = []\n for item in iterable:\n if item not in seen:\n seen.add(item)\n result.append(item)\n return result\n\n\n# This function is used to convert any two Dimensional List to a single List.\ndef ConvertList(temp_list, featre):\n for ele in temp_list:\n if type(ele) == list:\n ConvertList(ele, featre)\n else:\n featre.append(ele)\n return featre\n\n## Calculate Min Points\ndef calcMinPts():\n count = trainData.shape[0]\n\n D = math.log(count)\n minPts = int(D)\n return minPts\n\ndef calcEpsilon():\n data = trainData\n \n minPts = calcMinPts()\n kneighbour = minPts - 1\n nbrs = NearestNeighbors(n_neighbors=minPts, algorithm='auto').fit(data)\n distances, indices = nbrs.kneighbors(data)\n \n\n d = distances[:, kneighbour]\n #i = indices[:, 0]\n sorted_distances = np.sort(d, axis=None)\n df = pd.DataFrame(data=sorted_distances, columns=['values'])\n\n # converts the dataframe values to a list\n values = list(df['values'])\n\n # get length of the value set\n nPoints = len(values)\n allkdistpoints = np.vstack((range(nPoints), values)).T\n\n # Access the first and last point and plot a line between them\n largestkdistpoint = allkdistpoints[0]\n kdistlinevector = allkdistpoints[-1] - allkdistpoints[0]\n kdistlinevectorNorm = kdistlinevector / np.sqrt(np.sum(kdistlinevector ** 2))\n\n # find the distance from each point to the line:\n # vector between all points and first point\n vectorWithlargestkpoint = allkdistpoints - largestkdistpoint\n\n scalarProduct = np.sum(vectorWithlargestkpoint * np.matlib.repmat(kdistlinevectorNorm, nPoints, 1), axis=1)\n vecFromFirstParallel = np.outer(scalarProduct, kdistlinevectorNorm)\n vecToLine = vectorWithlargestkpoint - vecFromFirstParallel\n\n # distance to line is the norm of vecToLine\n distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))\n maxdistance = np.amax(distToLine)\n # knee/elbow is the point with max distance value\n #idxOfBestPoint = np.argmax(distToLine)\n\n return maxdistance\n \n \n \n# Load Datasets\n###############################################\n# Load Train Dataset\ntrainData = loadDatasetWithPandas(TRAIN_PATH)\ntrainData = trainData.replace('?', str(np.NaN))\nprint(trainData)\n\n\n#trainData = pd.DataFrame([])\n\n#for index, row in trainDataRaw.iterrows():\n# if str(row[\"mrt_liverfat_s2\"]) != \"nan\":\n# trainData = trainData.append(row)\n\n#unlabDataInst = pd.DataFrame([])\n\n## User sets the no of ML constraints\n#noMLCons = input(\"Enter the number of must-link constraints to be used:\")\nnoMLCons = 10\n## User sets the no of NL constraints\n#noNLCons = input(\"Enter the number of not-link constraints to be used:\")\nnoNLCons = 10\n\n## List of randomly selected ML constraint pairs\nlistMLConsPairs = createMLConsList()\n\n## List of randomly selected NL constraint pairs\nlistNLConsPairs = createNLConsList()\n\n\n\n\n\n\n# =============================================================================\n# le = preprocessing.LabelEncoder()\n# trainData['stea_alt75_s0'] = le.fit_transform(trainData.stea_alt75_s0.values)\n# trainData['stea_s0'] = le.fit_transform(trainData.stea_s0.values)\n# trainData['stea_alt75_s2'] = le.fit_transform(trainData.stea_alt75_s2.values)\n# trainData['stea_s2'] = le.fit_transform(trainData.stea_s2.values)\n# trainData['mort_icd10_s0'] = le.fit_transform(trainData.mort_icd10_s0.values)\n# #trainData.apply(preprocessing.LabelEncoder().fit_transform(trainData['stea_alt75_s0', 'stea_s0', 'stea_alt75_s2', 'stea_s2', 'mort_icd10_s0']))\n# =============================================================================\n\nfor data in trainData.columns:\n if trainData[data].dtype == 'O':\n unique_elements = trainData[data].unique().tolist()\n \n trainData[data] = trainData[data].apply(lambda x:unique_elements.index(x))\n\ntrainData.drop(columns = ['id', 'mrt_liverfat_s2'])\nprint(\"Shape: \", trainData.shape)\n\nepsilon = calcEpsilon()\n\nminPts = calcMinPts()\n\n\n \n\n# The main function of the program.\ncurrentBestScore = 0\npreviousBestScore = 0\nfeatures_selected = []\niter_subspace(trainData, features_selected, previousBestScore, currentBestScore)","sub_path":"DRESS_Full_Optm.py","file_name":"DRESS_Full_Optm.py","file_ext":"py","file_size_in_byte":17469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"385622921","text":"\"\"\"\r\nProblem: \r\nGiven a sorted array pivoted at some point search for a target value. Return index of target value and -1 if target does not exist. Search must be performed in O(log n) \r\n\r\nAlgorithm: \r\nLet's start with an example array [4, 5, 1, 2, 3] pivoted at index 2 (value = 1). We are searching for target value of 5. If we consider the whole array where si = 0 and ei = length(array) - 1 = 4 our array mid point is index = 2. If value at start index <= value at mid point, we know that left side of the array is sorted, otherwise we know right side of array is sorted. In our example, we compare array[0] (value = 4) to array[2] (value = 1). We now know left side of array is not sorted which means right side of array must be. Now we can check if our target value lies this right side sorted array. That means checking if array[2] <= target <= array[4] translating to (1 <= 5 <= 3). This condition is false, so we know target value can possibly only exist on left side of the array. Move ei = mid - 1 and continue the search \r\n\r\nSolution: \r\nPlease debug a few examples of solution to understand algorithm. Tips to remember - in statement if nums[si] <= nums[mid]: remember to use <= and not < because if we were searching in an array of size 2 si and mid are both equal to 0. \r\n\r\nTime Complexity: O(log n) \r\nSpace Complexity: O(1) \r\n\"\"\"\r\nprint(__doc__)\r\n\r\nclass SolutionArraySearch(object):\r\n def search(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: int \r\n \"\"\"\r\n if not nums: \r\n return -1\r\n \r\n if len(nums) == 1: \r\n return 0 if nums[0] == target else -1\r\n \r\n si = 0 \r\n ei = len(nums) - 1\r\n location = -1\r\n while si <= ei: \r\n mid = (si + ei) // 2 \r\n \r\n if nums[mid] == target: \r\n location = mid\r\n break \r\n \r\n # Left side of the array is sorted since nums[si] <= nums[mid]\r\n if nums[si] <= nums[mid]:\r\n # Since left side is sorted we can check for value on the left side \r\n if nums[si] <= target <= nums[mid]:\r\n ei = mid - 1\r\n # Value must exist on the right side. \r\n else:\r\n si = mid + 1\r\n # Right side is sorted\r\n else:\r\n # Check if value lies between mid and end. \r\n if nums[mid] <= target <= nums[ei]:\r\n si = mid + 1\r\n # Move search to left side \r\n else:\r\n ei = mid - 1\r\n \r\n return location\r\n \r\n\r\nif __name__ == '__main__':\r\n s = SolutionArraySearch()\r\n array = [4, 5, 1, 2, 3]\r\n target = 2\r\n print(\"Input: Array = {}, Target = {}\".format(array, target))\r\n print(\"Answer: Target Index = {}\".format(s.search(array, target)))\r\n print() \r\n \r\n array = [5, 1, 2, 3, 4]\r\n target = 2\r\n print(\"Input: Array = {}, Target = {}\".format(array, target))\r\n print(\"Answer: Target Index = {}\".format(s.search(array, target)))\r\n print() \r\n \r\n array = [5, 1, 2, 3, 4]\r\n target = 9\r\n print(\"Input: Array = {}, Target = {}\".format(array, target))\r\n print(\"Answer: Target Index = {}\".format(s.search(array, target)))\r\n ","sub_path":"arrays/rotatedarraysearch.py","file_name":"rotatedarraysearch.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"491656479","text":"from django.views.generic import View, ListView, DetailView\nfrom django.shortcuts import render\nfrom product.models import Product\nfrom cart.models import Cart\nfrom django.http import JsonResponse, HttpResponse\nfrom cart.models import Cart\nimport json\n# Create your views here.\nclass ProductPage(ListView):\n model = Product\n template_name = 'product/product.html'\n context_object_name = 'Products'\n ordering = ['-uploadDateTime']\n paginate_by = 3\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(ProductPage, self).get_context_data(**kwargs)\n context['cart'] = Cart.objects.all()\n\n context['filter'] = self.kwargs.get('filter')\n context['category'] = self.kwargs.get('category')\n context['searchTerm'] = self.kwargs.get('searchTerm')\n return context\n def get_queryset(self):\n query = '-uploadDateTime'\n category_ = self.kwargs.get('category')\n productName_ = ''\n if(self.kwargs.get('searchTerm')!= 'all'):\n productName_ = self.kwargs.get('searchTerm')\n \n \n if self.kwargs.get('filter')== None :\n return Product.objects.order_by(query)\n if self.kwargs.get('filter')=='newest':\n query = '-uploadDateTime'\n if self.kwargs.get('filter')=='oldest':\n query = 'uploadDateTime'\n if self.kwargs.get('filter')=='highestPrice':\n query = '-price'\n if self.kwargs.get('filter')=='lowestPrice':\n query = 'price'\n if category_=='all':\n if productName_ != '':\n return Product.objects.filter(productName__icontains=productName_).order_by(query)\n else:\n return Product.objects.order_by(query)\n return Product.objects.filter(category=category_).filter(productName__icontains=productName_).order_by(query)\n\nclass ProductDetailPage(DetailView):\n model = Product\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(ProductDetailPage, self).get_context_data(**kwargs)\n context['cart'] = Cart.objects.all()\n return context\n def post(self, request, *args, **kwargs):\n body = json.loads(request.body)\n if body[\"action\"]==\"addToCart\":\n product = Product.objects.get(id=body[\"id\"])\n Cart.objects.create(product=product,price=product.price)\n return JsonResponse({\"status\":'success',\"id\":body[\"id\"]})\n\n\n","sub_path":"punda/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"22283961","text":"import sys\n\nfrom .Schema import *\nfrom Jumpscale import j\nfrom .DataObjBase import DataObjBase\n\nJSBASE = j.application.JSBaseClass\n\n\nclass SchemaFactory(j.application.JSBaseClass):\n __jslocation__ = \"j.data.schema\"\n\n def _init(self):\n\n self.__code_generation_dir = None\n self.db = j.clients.redis.core_get()\n self.schemas = {}\n self.schemas_versionless = {}\n self._md5_schema = {}\n\n self.DataObjBase = DataObjBase\n\n @property\n def SCHEMA_CLASS(self):\n return Schema\n\n @property\n def _code_generation_dir(self):\n if not self.__code_generation_dir:\n path = j.sal.fs.joinPaths(j.dirs.VARDIR, \"codegen\", \"schema\")\n j.sal.fs.createDir(path)\n if path not in sys.path:\n sys.path.append(path)\n j.sal.fs.touch(j.sal.fs.joinPaths(path, \"__init__.py\"))\n self._log_debug(\"codegendir:%s\" % path)\n self.__code_generation_dir = path\n return self.__code_generation_dir\n\n def reset(self):\n self.schemas = {}\n\n def get(self, schema_text=\"\", url=None, die=True):\n \"\"\"\n get schema from the url or schema_text\n\n Keyword Arguments:\n schema_text {str} -- schema file path or shcema string (default: {\"\"})\n url {[type]} -- url of your schema e.g. @url = despiegk.test (default: {None})\n\n if die False and schema is not found e.g. based on url, then will return None\n\n Returns:\n Schema\n \"\"\"\n if schema_text != \"\":\n if j.data.types.string.check(schema_text):\n return self._add(schema_text, url=url)\n else:\n raise RuntimeError(\"need to be text \")\n else:\n # check is in cash based on url & dbclient\n if url is not None:\n if url in self.schemas:\n return self.schemas[url]\n raise RuntimeError(\"could not find schema '%s'\" % url)\n\n def _md5(self, text):\n \"\"\"\n convert text to md5\n \"\"\"\n\n original_text = text.replace(\" \", \"\").replace(\"\\n\", \"\")\n ascii_text = j.core.text.strip_to_ascii_dense(original_text)\n return j.data.hash.md5_string(ascii_text)\n\n def exists(self, url):\n return self.get(url=url, die=False) is not None\n\n def _add(self, schema_text, url=None):\n \"\"\"\n :param schema_text or schema_path\n :return: incache,schema (incache is bool, when True means was in cache)\n \"\"\"\n block = \"\"\n blocks = []\n txt = j.core.text.strip(schema_text)\n for line in txt.split(\"\\n\"):\n\n strip_line = line.lower().strip()\n\n if block == \"\":\n if strip_line == \"\" or strip_line.startswith(\"#\"):\n continue\n\n if strip_line.startswith(\"@url\"):\n if block is not \"\":\n blocks.append(block)\n block = \"\"\n\n block += \"%s\\n\" % line\n\n # process last block\n if block is not \"\":\n blocks.append(block)\n\n if url and len(blocks) > 1:\n raise RuntimeError(\"can only use url if max 1 schema\")\n\n res = []\n for block in blocks:\n md5 = self._md5(block)\n if md5 in self._md5_schema:\n res.append(self._md5_schema[md5])\n else:\n s = Schema(text=block, url=url)\n if s._md5 in self._md5_schema:\n raise RuntimeError(\"should not be there\")\n else:\n res.append(s)\n self.schemas[s.url] = s\n\n if len(res) == 0:\n raise RuntimeError(\"did not find schema in txt\")\n\n return res[0]\n\n def test(self, name=\"\"):\n \"\"\"\n it's run all tests\n js_shell 'j.data.schema.test()'\n\n if want run specific test ( write the name of test ) e.g. j.data.schema.test(name=\"base\")\n \"\"\"\n self._test_run(name=name)\n","sub_path":"Jumpscale/data/schema/SchemaFactory.py","file_name":"SchemaFactory.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"315625008","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom utils.wrappers import *\nfrom carts.models import *\nfrom django.http import JsonResponse\n\n@check_permission\ndef index(request):\n # 取购物车数据\n carts = Cart.objects.filter(cart_user_id=get_session(request, 'uid'))\n # 记录总数量\n total = 0\n # 记录总价格\n money = 0\n\n # 遍历购物车统计\n for cart in carts:\n # 计算单品总价\n cart.single_total = cart.cart_amount * cart.cart_goods.goods_price\n # 累加商品总数量\n\n total += cart.cart_amount\n # 累加商品总价格\n money += cart.single_total\n\n carts.total = total\n carts.money = money\n\n return render(request,'carts/cart.html',locals())\n\n\n\n\n# 商品添加到购物车\ndef add_goods(request):\n\n # 1. 获取用户ID、商品ID、商品数量\n goods_id = get(request, 'goods_id')\n user_id = get_session(request, 'uid')\n goods_num = get(request, 'goods_num')\n\n goods_id = int(goods_id)\n user_id = int(user_id)\n goods_num = int(goods_num)\n\n # 2. 先判断该商品是否在购物车中存在\n\n # 2.1 如果存在,则只更新商品的数量\n try:\n cart = Cart.objects.get(cart_goods_id=goods_id, cart_user_id=user_id)\n cart.cart_amount = cart.cart_amount + goods_num\n cart.save()\n\n # 2.2 如果不存在,新增一条购物车商品数据\n except Cart.DoesNotExist:\n c = Cart()\n c.cart_goods_id = goods_id\n c.cart_user_id = user_id\n c.cart_amount = int(goods_num)\n c.save()\n\n # 将当前购物车商品数量总和返回\n # 通过聚合计算商品总数量\n # Cart.objects.filter(cart_user_id=user_id).aggregate(models.Sum('cart_amount'))\n carts = Cart.objects.filter(cart_user_id=user_id)\n total = 0\n for cart in carts:\n total += cart.cart_amount\n\n return JsonResponse({'total': total})\n\n# 修改商品数量\ndef edit_goods_num(request):\n\n # 获得商品ID\n goods_id = get(request, 'id')\n # 获得商品数量\n goods_num = get(request, 'num')\n # 更新当前用户购物车商品数量信息\n try:\n # 更新商品数量\n cart = Cart.objects.get(cart_user_id=get_session(request, 'uid'),cart_goods_id=goods_id)\n cart.cart_amount = goods_num\n cart.save()\n except Cart.DoesNotExist:\n return JsonResponse({'ret':0})\n\n return JsonResponse({'ret':1})\n\n\n# 删除购物车商品\ndef remove_goods(request):\n\n # 获得删除的商品ID\n goods_id = get(request, 'id')\n # 查询数据\n try:\n cart = Cart.objects.get(cart_user_id=get_session(request, 'uid'), cart_goods_id=goods_id)\n cart.delete()\n except:\n pass\n\n return JsonResponse({'ret':1})\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439216580","text":"import os\nimport re\nimport subprocess\nfrom datetime import datetime\nfrom typing import Tuple, List, Optional\n\nfrom plotman import plot_util, configuration, archive\n\n\nclass EgressArchiveJob:\n plot_id: str\n plot_k: int\n plot_timestamp: float\n source_disk: str\n dest_disk: str\n start_timestamp: float\n bw_limit: int\n\n\n @classmethod\n def get_archive_running_jobs(cls, arch_cfg: configuration.Archiving) -> List[\"EgressArchiveJob\"]:\n procs = archive.get_running_archive_jobs(arch_cfg)\n jobs = []\n for proc in procs:\n start_timestamp = proc.create_time()\n split = proc.cmdline()\n if len(split) != 9:\n continue\n plot_path = split[7]\n dest_disk = split[8]\n matches = re.search(r\"^rsync://\\S+@([\\w\\d]+):\\d+/[\\w\\d]+/(\\d+)/$\", dest_disk)\n if matches is not None:\n groups = matches.groups()\n dest_disk = f\"/{groups[1]}@{groups[0]}\"\n\n bw_limit = int(split[1].split('=')[1])\n matches = re.search(r\"^([/\\w\\d]+)/plot-k(\\d{2})-(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{2})-([\\w\\d]+)\\.plot$\", plot_path)\n if matches is not None:\n groups = matches.groups()\n source_disk = groups[0]\n plot_k = int(groups[1])\n year = int(groups[2])\n month = int(groups[3])\n day = int(groups[4])\n hour = int(groups[5])\n minute = int(groups[6])\n plot_id = groups[7]\n plot_timestamp = datetime.timestamp(datetime(year, month, day, hour, minute))\n job = cls(\n plot_id=plot_id,\n plot_k=plot_k,\n plot_timestamp=plot_timestamp,\n source_disk=source_disk,\n dest_disk=dest_disk,\n start_timestamp=start_timestamp,\n bw_limit=bw_limit\n )\n jobs.append(job)\n return jobs\n\n def __init__(\n self,\n plot_id: str,\n plot_k: int,\n plot_timestamp: float,\n source_disk: int,\n dest_disk: int,\n start_timestamp: float,\n bw_limit: int\n ) -> None:\n self.plot_id = plot_id\n self.plot_k = plot_k\n self.plot_timestamp = plot_timestamp\n self.source_disk = source_disk\n self.dest_disk = dest_disk\n self.start_timestamp = start_timestamp\n self.bw_limit = bw_limit\n self.timestamp = datetime.timestamp(datetime.now())\n\n def progress(self) -> float:\n now = datetime.timestamp(datetime.now())\n elapsed = now - self.start_timestamp\n return min(((elapsed * self.bw_limit * 1000) * 0.8) / plot_util.get_plotsize(self.plot_k), 1)\n\n\nclass IngressArchiveJob:\n job_id: str\n plot_id: str\n plot_k: int\n plot_timestamp: float\n disk: int\n is_local: bool\n transferred_bytes: int\n prev_transferred_bytes: Optional[List[Tuple[int, int]]]\n timestamp: float\n\n @classmethod\n def get_archive_running_jobs(cls, arch_cfg: configuration.Archiving, prev_jobs: List[\"IngressArchiveJob\"]) -> List[\"IngressArchiveJob\"]:\n local_jobs = archive.get_running_archive_jobs(arch_cfg)\n\n target = arch_cfg.target_definition()\n variables = {**os.environ, **arch_cfg.environment()}\n dest = target.transfer_process_argument_prefix.format(**variables)\n\n path = dest.strip() if dest.strip().endswith('/') else dest.strip() + '/'\n jobs = []\n timeout = 40\n try:\n completed_process = subprocess.run(\n ['find', path, '-name', '.plot-k*', '-ls'],\n env={**os.environ},\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired as e:\n print(e)\n else:\n stdout = completed_process.stdout.decode('utf-8', errors='ignore').strip()\n stderr = completed_process.stderr.decode('utf-8', errors='ignore').strip()\n for line in stderr.splitlines():\n raise Exception(line)\n for line in stdout.splitlines():\n line = line.strip()\n split = line.split()\n if len(split) != 11:\n continue\n job = split[10]\n space = split[6]\n job = job.strip()\n transferred_bytes = int(space)\n matches = re.search(rf\"^{path}(\\d{{3}})/\\.plot-k(\\d{{2}})-(\\d{{4}})-(\\d{{2}})-(\\d{{2}})-(\\d{{2}})-(\\d{{2}})-([\\w\\d]+)\\.plot\\.([\\w\\d]+)$\", job)\n if matches is not None:\n groups = matches.groups()\n disk = int(groups[0])\n plot_k = int(groups[1])\n year = int(groups[2])\n month = int(groups[3])\n day = int(groups[4])\n hour = int(groups[5])\n minute = int(groups[6])\n plot_id = groups[7]\n job_id = groups[8]\n is_local = any(plot_id in ' '.join(local_job.cmdline()) for local_job in local_jobs)\n plot_timestamp = datetime.timestamp(datetime(year, month, day, hour, minute))\n prev_transferred_bytes = []\n if prev_jobs is not None:\n prev_transferred_bytes = next(([(job.timestamp, job.transferred_bytes)] + job.prev_transferred_bytes for job in prev_jobs if job.job_id == job_id), [])\n job = cls(\n job_id=job_id,\n plot_id=plot_id,\n plot_k=plot_k,\n plot_timestamp=plot_timestamp,\n disk=disk,\n is_local=is_local,\n transferred_bytes=transferred_bytes,\n prev_transferred_bytes=prev_transferred_bytes,\n )\n jobs.append(job)\n return jobs\n\n def __init__(\n self,\n job_id: str,\n plot_id: str,\n plot_k: int,\n plot_timestamp: float,\n disk: int,\n is_local: bool,\n transferred_bytes: int,\n prev_transferred_bytes: List[Tuple[int, int]] = []\n ) -> None:\n self.job_id = job_id\n self.plot_id = plot_id\n self.plot_k = plot_k\n self.plot_timestamp = plot_timestamp\n self.disk = disk\n self.is_local = is_local\n self.transferred_bytes = transferred_bytes\n self.prev_transferred_bytes = prev_transferred_bytes\n self.timestamp = datetime.timestamp(datetime.now())\n\n def progress(self) -> float:\n return min(self.transferred_bytes / plot_util.get_plotsize(self.plot_k), 1)\n\n def estimated_remaining_time(self) -> Optional[int]:\n rate = self.estimated_transfer_rate()\n if rate is None or rate == 0:\n return None\n left = plot_util.get_plotsize(self.plot_k) - self.transferred_bytes\n return max(int(left / rate), 0)\n\n def estimated_transfer_rate(self) -> Optional[float]:\n if len(self.prev_transferred_bytes) == 0:\n return None\n prevs = sorted(self.prev_transferred_bytes, key=lambda tuple: tuple[0])\n prev = prevs[0]\n seconds = self.timestamp - prev[0]\n if seconds == 0:\n return None\n bytes_delta = self.transferred_bytes - prev[1]\n return bytes_delta / seconds\n","sub_path":"src/plotman/archive_job.py","file_name":"archive_job.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"150470413","text":"import pygame, sys, time\nfrom pygame.locals import *\nimport os\n\npygame.init()\nmainClock = pygame.time.Clock()\n\nW = 1280\nH = 720\n\nSurface = pygame.display.set_mode((W,H), 0, 32)\npygame.display.set_caption('Python Menus')\n\nBLACK = (0, 0, 0)\nGREEN = (0, 255, 0)\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\n\ngame = True\nmouse_pos = (0,0)\nmouse_click = (0,0)\ntext1_bool = False\ntext2_bool = False\ntext_next_bool = False\ntext3_bool = False\ntext4_bool = False\noutput = '?'\nn = 0\n\nactor_files = []\ni = 0\n\nwhile game == True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYUP:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEMOTION:\n mouse_pos = event.pos\n if event.type == MOUSEBUTTONUP:\n mouse_click = event.pos\n\n Surface.fill(BLACK)\n color = WHITE\n Font = pygame.font.SysFont('arial', 25)\n if text1_bool:\n color = RED\n text = Font.render('Rating-Genre',True,color)\n text_rect = text.get_rect()\n text_rect.center = (W/12,H/6)\n if text_rect.collidepoint(mouse_click):\n output = '1'\n barIMG1 = pygame.image.load('pic/1.png')\n barIMG1 = pygame.transform.scale(barIMG1,(800,600))\n Surface.blit(barIMG1,(W/3,H/10))\n\n if text_rect.collidepoint(mouse_pos):\n text1_bool = True\n else:\n text1_bool = False\n Surface.blit(text, text_rect)\n\n color = WHITE\n if text2_bool:\n color = RED\n Font = pygame.font.SysFont('arial', 25)\n text = Font.render('Rating-Actor(1)',True,color)\n text_rect = text.get_rect()\n text_rect.center = (W/12,H*2/6)\n if text_rect.collidepoint(mouse_click):\n output = '2'\n barIMG2 = pygame.image.load('pic/2-1.png')\n barIMG2 = pygame.transform.scale(barIMG2,(800,600))\n Surface.blit(barIMG2,(W/3,H/10))\n if text_rect.collidepoint(mouse_pos):\n text2_bool = True\n else:\n text2_bool = False\n Surface.blit(text, text_rect)\n\n color = WHITE\n if text3_bool:\n color = RED\n \n Font = pygame.font.SysFont('arial', 25)\n text = Font.render('Rating-Actor(2)',True,color)\n text_rect = text.get_rect()\n text_rect.center = (W/12,H*3/6)\n if text_rect.collidepoint(mouse_click):\n output = '3'\n barIMG3 = pygame.image.load('pic/2-2.png')\n barIMG3 = pygame.transform.scale(barIMG3,(800,600))\n Surface.blit(barIMG3,(W/3,H/10))\n if text_rect.collidepoint(mouse_pos):\n text3_bool = True\n else:\n text3_bool = False\n Surface.blit(text, text_rect)\n\n \n color = WHITE\n if text4_bool:\n color = RED\n Font = pygame.font.SysFont('arial', 25)\n text = Font.render('Genre-Year-Count',True,color)\n text_rect = text.get_rect()\n text_rect.center = (W/12,H*4/6)\n if text_rect.collidepoint(mouse_click):\n output = '4'\n barIMG3 = pygame.image.load('pic/3.png')\n barIMG3 = pygame.transform.scale(barIMG3,(800,600))\n Surface.blit(barIMG3,(W/3,H/10))\n if text_rect.collidepoint(mouse_pos):\n text4_bool = True\n else:\n text4_bool = False\n Surface.blit(text, text_rect)\n\n\n Font = pygame.font.SysFont('arial', 40)\n text = Font.render(output,True,BLUE)\n text_rect = text.get_rect()\n text_rect.center = (W/10,H*4/5)\n Surface.blit(text, text_rect)\n\n\n\n pygame.display.flip()\n mainClock.tick(100000)","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"605453726","text":"\r\n\r\ndef main():\r\n bill=open(\"bill.txt\")\r\n lnum=0\r\n cnum=0\r\n wnum=0\r\n wdict={}\r\n cdict={}\r\n for line in bill:\r\n lnum+=1 #行数\r\n for char in line:\r\n cnum+=1 #字符\r\n char=char.lower()\r\n if char.isalpha() and char in cdict:\r\n cdict[char]+=1\r\n elif char.isalpha():\r\n cdict[char]=1\r\n words = line.split()\r\n wlen=len(words)\r\n #print(wlen)\r\n wn=0\r\n lastflag=0\r\n for word in words:\r\n wn+=1 \r\n if wn==wlen-1:\r\n wwlen=len(word)\r\n if word[wwlen-1]=='-':\r\n wn-=1\r\n lastw=word[0:wwlen-1]\r\n lastflag=1\r\n continue\r\n else:\r\n lastflag=0\r\n if wn==1 and lastflag==1:\r\n word=lastw+word \r\n word=word.lower()\r\n if word in wdict:\r\n wdict[word]+=1\r\n else:\r\n wdict[word]=1\r\n wnum=wnum+wn #单词\r\n print(\"在文本文件中,包含%d个字符,%d行,%d个单词\" %(cnum,lnum,wnum)) \r\n #字母出现的频率\r\n print(\"文件中各字母出现的频率:\")\r\n csort = sorted(cdict.keys())\r\n for cs in csort:\r\n print(\"{:<10}{:.2%}\".format(cs,float(cdict[cs]/cnum)))\r\n #出现频率最高的单词\r\n wsort={}\r\n for key in wdict.keys():\r\n if wdict[key]>=4000:\r\n wsort[key]=wdict[key] \r\n del wdict\r\n class1 = sorted(wsort.items(),key=lambda kv:(kv[1],kv[0]),reverse=True)\r\n print(\"文件中出现频率最高的十个单词及其出现次数:\")\r\n n=0\r\n for x in class1 :\r\n n+=1\r\n if n==11:\r\n break\r\n print(\"{:<25}{:>10}\".format(x[0],x[1]))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"project_final/project/16300120183.py","file_name":"16300120183.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214673502","text":"from pandas import read_csv\nimport numpy\nimport time\n\n##############################################\n\nHISTORY_FILE = 'C:\\\\Users\\\\Admin\\\\Desktop\\\\duka-master\\\\EURUSD-2016_01_01-2017_07_17.csv'\n\n##############################################\n\nprint('reading csv file')\n\nstartTime = time.time()\n\ncontent = read_csv(HISTORY_FILE, header = None).values\n\nendTime = time.time()\n\nprint('reading csv file took: {}'.format(endTime - startTime))\n\nprint('storing data in npz')\n\nstartTime = time.time()\n\nnumpy.savez_compressed(HISTORY_FILE, content)\n\nendTime = time.time()\n\nprint('storing data in npz took: {}'.format(endTime - startTime))\n","sub_path":"convertDukascopyDataToNpy.py","file_name":"convertDukascopyDataToNpy.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"150825376","text":"\n\nfrom xai.brain.wordbase.nouns._oxide import _OXIDE\n\n#calss header\nclass _OXIDES(_OXIDE, ):\n\tdef __init__(self,): \n\t\t_OXIDE.__init__(self)\n\t\tself.name = \"OXIDES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"oxide\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_oxides.py","file_name":"_oxides.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245084462","text":"def cottruyen(nameplayer, nameBot1, loai_Zombie):\r\n print(\"Game này cho bạn vào một thế giới hỗn độn với Zombie ở khắp nơi bạn phải giết được Giê-su(thằng này nó già quá,\")\r\n print(\" bị bệnh thần kinh và đã tạo ra Zombie để hủy diệt loài người là) để chiến thắng(game này có thể có lỗi và chưa\")\r\n print(\" được tối ưu, hoàn thiện mọi command xin liên hệ Administrators: link FaceBook https://www.facebook.com/profile.php?id=100014034901974)\")\r\n\r\n while True:\r\n print(\"Bạn hãy chọn độ khó\")\r\n print(\"1. Dễ\")\r\n print(\"2. khó(khi DEF của kẻ địch hơn STR của nhân vật thì kẻ địch được tăng máu)\")\r\n traloicauhoi_dokho = input(\" \")\r\n if traloicauhoi_dokho == \"1\":\r\n print(\"Chế độ: Dễ\")\r\n break\r\n elif traloicauhoi_dokho == \"2\":\r\n print(\"Chế độ: Khó\")\r\n break\r\n else:\r\n print(\"Chỉ được nhập 1(Chế độ: Dễ) hoặc 2(Chế độ: Khó)\")\r\n\r\n while True:\r\n\r\n print(\"Để bắt đầu chơi hãy nhập (play)\")\r\n print(\"hoặc bạn có thể xem thông số của bạn bằng cách nhập (stats)\")\r\n gioithieugame = input(\" \")\r\n gioithieugame = gioithieugame.lower()\r\n\r\n if gioithieugame == \"cmd_hack\":\r\n cmd_hack = input(\" \")\r\n if cmd_hack == \"hack_stats\":\r\n hack_stats = input(\" \")\r\n if hack_stats == \"add_stats\":\r\n print(\"Tất cả chỉ số sẽ được tăng 1000 và LUCK sẽ được tăng max là 70\")\r\n player[\"HP\"] += 1000\r\n player[\"STR\"] += 1000\r\n player[\"DEF\"] += 1000\r\n player[\"LUCK\"] = 70\r\n player[\"CRT\"] += 1000\r\n player[\"EXP\"] += 1000\r\n player[\"LVL\"] += 1000\r\n\r\n if gioithieugame == \"stats\":\r\n show_index(player)\r\n\r\n elif gioithieugame == \"play\":\r\n print(\"Xin chào\", NAME, \", tôi tên là:\", Bot1[\"NAME\"])\r\n print(\"Bạn là một trong những người may mắn còn sống trong trận đại dịch Zombie\")\r\n print(\"Bạn phải sống sót và tập hợp những người sống sót,\")\r\n print(\"đi tìm nơi ở của Giê-su Zombie, giết nó và bạn sẽ giải cứu được thế giới\")\r\n print(\"Vậy bạn có đi tìm Giê-su Zombie cùng tôi không\")\r\n print(\"1. Có\")\r\n print(\"2. Không\")\r\n\r\n sudunglan2_list = [0]\r\n for _ in sudunglan2_list:\r\n\r\n dichuen = input(\"\")\r\n\r\n if dichuen == \"1\":\r\n print(\"Ở đằng kia có rất nhiều Zombie, có thể có Giê-su Zombie ở đó\")\r\n print(\"1. Đi ra đó\")\r\n print(\"2. Ở lại\")\r\n dichuen = input(\" \")\r\n if dichuen == \"1\":\r\n soluongzombie = range(randint(10, 20))\r\n print(\"Ở đó có:\", max(soluongzombie) + 1, \"con Zombie\")\r\n for slzb in soluongzombie:\r\n spawn = randint(0, 2)\r\n tinh_combat(nameplayer, nameBot1, loai_Zombie[spawn], traloicauhoi_dokho)\r\n elif dichuen == \"2\":\r\n print(\"Vì bạn đã đi ra khỏi nơi an toàn nên có rất nhiều Zombie xung quanh bạn bạn\")\r\n soluongzombie = range(randint(10, 20))\r\n print(\"Quanh bạn có:\", max(soluongzombie) + 1, \"con Zombie\")\r\n for slzb in soluongzombie:\r\n spawn = randint(0, 2)\r\n tinh_combat_khongcoBot(nameplayer, loai_Zombie[spawn], traloicauhoi_dokho)\r\n\r\n\r\n elif dichuen == \"2\":\r\n while True:\r\n print(\"Bạn ở lại một mình và chết đói vì không có thức ăn\")\r\n print(\"GAME OVER\")\r\n while True:\r\n print(\"Nếu muốn chơi lại hãy nhập (replay)\")\r\n choilai = input(\" \")\r\n choilai = choilai.lower()\r\n if choilai == \"replay\":\r\n cottruyen(nameplayer, nameBot1, loai_Zombie)\r\n break\r\n else:\r\n print(\"Xin nhập lại\")\r\n\r\n else:\r\n print(\"Tôi không hiểu ý bạn, bạn hãy trả lời lại\")\r\n\r\n\r\n else:\r\n if gioithieugame != \"cmd_hack\":\r\n print(\"Command của bạn không có trong từ điển của chúng tôi\")\r\n print(\"Xin bạn hãy nhập lại\")","sub_path":"Session 8/cốt truyện.py","file_name":"cốt truyện.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"433157258","text":"import time\nfrom helium_client import Helium\nhelium = Helium(b'/dev/ttyS5')\nhelium.connect()\nchannel = helium.create_channel(b\"Azure IoT App\")\n\ndef main():\n peoplestring = \"\"\n bottlestring = \"\"\n while True:\n file = open('people.txt', 'r')\n temp = str(file.read().replace('\\n',''))\n if peoplestring != temp and temp != '':\n peoplestring = temp\n channel.send(peoplestring.encode())\n print(peoplestring)\n file.close() \n file = open('bottles.txt', 'r')\n temp = str(file.read().replace('\\n',''))\n if bottlestring != temp and temp != '':\n bottlestring = temp\n channel.send(bottlestring.encode())\n print(bottlestring)\n file.close() \n time.sleep(1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"datasync.py","file_name":"datasync.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"621023766","text":"# Tai Sakuma \nimport pytest\nimport time\n\ntry:\n import unittest.mock as mock\nexcept ImportError:\n import mock\n\nfrom alphatwirl.progressbar import ProgressReporter\n\n##__________________________________________________________________||\n@pytest.fixture()\ndef queue():\n return mock.MagicMock()\n\n@pytest.fixture()\ndef mocktime():\n return mock.MagicMock(return_value = 1000.0)\n\n@pytest.fixture()\ndef reporter(queue, mocktime, monkeypatch):\n monkeypatch.setattr(time, 'time', mocktime)\n ret = ProgressReporter(queue)\n return ret\n\n@pytest.fixture()\ndef report():\n return mock.MagicMock(**{'last.return_value': False, 'first.return_value': False})\n\n@pytest.fixture()\ndef report_last():\n return mock.MagicMock(**{'last.return_value': True, 'first.return_value': False})\n\n@pytest.fixture()\ndef report_first():\n return mock.MagicMock(**{'last.return_value': False, 'first.return_value': True})\n\n##__________________________________________________________________||\ndef test_repr(reporter):\n repr(reporter)\n\n##__________________________________________________________________||\ndef test_report_no_need_to_report(reporter, monkeypatch, report):\n\n mock_report = mock.MagicMock()\n monkeypatch.setattr(reporter, '_report', mock_report)\n\n mock_need_to_report = mock.MagicMock()\n mock_need_to_report.return_value = False\n monkeypatch.setattr(reporter, '_need_to_report', mock_need_to_report)\n\n reporter.report(report)\n\n mock_report.assert_not_called()\n\ndef test_report_need_to_report(reporter, monkeypatch, report):\n\n mock_report = mock.MagicMock()\n monkeypatch.setattr(reporter, '_report', mock_report)\n\n mock_need_to_report = mock.MagicMock()\n mock_need_to_report.return_value = True\n monkeypatch.setattr(reporter, '_need_to_report', mock_need_to_report)\n\n reporter.report(report)\n\n mock_report.assert_called_once_with(report)\n\n##__________________________________________________________________||\ndef test__report(reporter, queue, mocktime, report):\n\n assert 1000.0 == reporter.last_time\n\n mocktime.return_value = 1000.2\n reporter._report(report)\n\n assert [mock.call(report)] == queue.put.call_args_list\n\n assert 1000.2 == reporter.last_time\n\ndef test_need_to_report(reporter, queue, mocktime, report, report_last,\n report_first):\n\n interval = reporter.interval\n assert 0.1 == interval\n\n assert 1000.0 == reporter.last_time\n\n # before the interval passes\n mocktime.return_value += 0.1*interval\n assert not reporter._need_to_report(report)\n\n # the first report before the interval passes\n assert reporter._need_to_report(report_first)\n\n # the last report before the interval passes\n assert reporter._need_to_report(report_last)\n\n # after the interval passes\n mocktime.return_value += 1.2*interval\n assert reporter._need_to_report(report)\n\n assert 1000.0 == reporter.last_time\n\n##__________________________________________________________________||\n","sub_path":"tests/unit/progressbar/test_ProgressReporter.py","file_name":"test_ProgressReporter.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"381384306","text":"\"\"\"\nDFS solution\n\"\"\"\nclass Solution(object):\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool\n \"\"\"\n def helper(data, index, word, wordList):\n # generate a list of \"XXX\" for a list of combinations of letters: [set'XY', set'KZ', set'ABC'...]\n if len(data) == len(word):\n wordList.append(word)\n return\n for i in data[index]:\n helper(data, index+1, word + i, wordList)\n\n def dfs(bottom):\n # dfs part with memorization\n if len(bottom) == 2:\n if bottom in allowedDict:\n return True\n return False\n nextBottom = []\n for i in range(len(bottom)-1):\n if bottom[i:i+2] not in allowedDict:\n return False\n nextBottom.append(allowedDict[bottom[i:i+2]])\n wordList = []\n helper(nextBottom, 0, \"\", wordList)\n for word in wordList:\n if word not in backtrackFail:\n if dfs(word):\n return True\n else:\n backtrackFail.add(word)\n return False\n\n allowedDict = {}\n for word in allowed:\n if word[:2] not in allowedDict:\n allowedDict[word[:2]] = set([word[2]])\n else:\n allowedDict[word[:2]].add(word[2])\n backtrackFail = set()\n return dfs(bottom)\n","sub_path":"solution/python/756.py","file_name":"756.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"86707436","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# this will emerge some programs...\n\n# copyright:\n# Holger Schroeder \n# Patrick Spendrin \n# Hannah von Reth \n\n# The minimum python version for emerge please edit here\n# if you add code that changes this requirement\n\nimport sys\n\nimport EmergeDebug\nimport EmergeTimer\n\nimport time\nimport datetime\nimport traceback\nimport argparse\nimport collections\nimport copy\n\nimport compiler\nimport portageSearch\nimport InstallDB\nimport portage\nimport utils\nimport threading\nfrom EmergeConfig import *\n\ndef destroyEmergeRoot():\n del InstallDB.installdb\n root = EmergeStandardDirs.emergeRoot()\n for entry in os.listdir(root):\n path = os.path.join(root, entry)\n if path == EmergeStandardDirs.etcDir():\n for entry in os.listdir(path):\n if not entry == \"kdesettings.ini\":\n etcPath = os.path.join(path, entry)\n if os.path.isdir(etcPath):\n utils.cleanDirectory(etcPath)\n utils.OsUtils.rmDir(etcPath, True)\n else:\n utils.OsUtils.rm(etcPath, True)\n elif not path in [ EmergeStandardDirs.downloadDir(), EmergeStandardDirs.emergeRepositoryDir(),\n os.path.join(EmergeStandardDirs.emergeRoot(), \"python\") ]:\n utils.cleanDirectory(path)\n utils.OsUtils.rmDir(path, True)\n\ndef packageIsOutdated( category, package ):\n newest = portage.PortageInstance.getNewestVersion( category, package )\n installed = InstallDB.installdb.getInstalledPackages( category, package )\n for pack in installed:\n version = pack.getVersion( )\n if newest != version:\n return True\n\n\n@utils.log\ndef doExec( package, action, continueFlag = False ):\n with EmergeTimer.Timer(\"%s for %s\" % ( action, package ), 1 ):\n EmergeDebug.info(\"Action: %s for %s\" % (action, package))\n ret = package.execute( action )\n if not ret:\n EmergeDebug.warning(\"Action: %s for %s FAILED\" % (action, package))\n return ret or continueFlag\n\n\ndef handlePackage( category, packageName, buildAction, continueFlag, skipUpToDateVcs ):\n with EmergeTimer.Timer(\"HandlePackage %s/%s\" % (category, packageName), 3) as timer:\n EmergeDebug.debug_line()\n EmergeDebug.info(\"Handling package: %s, action: %s\" % (packageName, buildAction))\n\n success = True\n package = portage.getPackageInstance( category, packageName )\n if package is None:\n raise portage.PortageException( \"Package not found\", category, packageName )\n\n if buildAction in [ \"all\", \"full-package\", \"update\", \"update-all\" ]:\n if emergeSettings.getboolean(\"ContinuousIntegration\", \"UseCache\", \"False\"):\n if doExec( package, \"fetch-binary\"):\n return True\n success = success and doExec( package, \"fetch\", continueFlag )\n skip = False\n if success and skipUpToDateVcs and package.subinfo.hasSvnTarget( ):\n revision = package.sourceVersion( )\n for p in InstallDB.installdb.getInstalledPackages( category, packageName ):\n if p.getRevision( ) == revision:\n EmergeDebug.info(\"Skipping further actions, package is up-to-date\")\n skip = True\n if not skip:\n success = success and doExec( package, \"unpack\", continueFlag )\n success = success and doExec( package, \"compile\" )\n success = success and doExec( package, \"cleanimage\" )\n success = success and doExec( package, \"install\" )\n if buildAction in [ \"all\", \"update\", \"update-all\" ]:\n success = success and doExec( package, \"qmerge\" )\n if buildAction == \"full-package\" or emergeSettings.getboolean(\"ContinuousIntegration\", \"CreateCache\"):\n success = success and doExec( package, \"package\" )\n success = success or continueFlag\n elif buildAction in [ \"fetch\", \"fetch-binary\", \"unpack\", \"configure\", \"compile\", \"make\", \"checkdigest\",\n \"dumpdeps\", \"test\",\n \"package\", \"unmerge\", \"cleanimage\", \"cleanbuild\", \"createpatch\",\n \"geturls\",\n \"print-revision\",\n \"print-files\"\n ]:\n success = doExec( package, buildAction, continueFlag )\n elif buildAction == \"install\":\n success = doExec( package, \"cleanimage\" )\n success = success and doExec( package, \"install\", continueFlag )\n elif buildAction == \"qmerge\":\n #success = doExec( package, \"cleanimage\" )\n #success = success and doExec( package, \"install\")\n success = success and doExec( package, \"qmerge\" )\n elif buildAction == \"print-source-version\":\n print( \"%s-%s\" % ( packageName, package.sourceVersion( ) ) )\n success = True\n elif buildAction == \"print-package-version\":\n print( \"%s-%s-%s\" % ( packageName, compiler.getCompilerName( ), package.sourceVersion( ) ) )\n success = True\n elif buildAction == \"print-targets\":\n portage.printTargets( category, packageName )\n success = True\n else:\n success = EmergeDebug.error(\"could not understand this buildAction: %s\" % buildAction)\n\n timer.stop()\n utils.notify( \"Emerge %s %s\" % (buildAction, \"succeeded\" if success else \"failed\"),\n \"%s of %s/%s %s after %s\" % ( buildAction, category, packageName, \"succeeded\" if success else \"failed\", timer), buildAction)\n return success\n\n\ndef handleSinglePackage( packageName, action, args ):\n deplist = [ ]\n packageList = [ ]\n originalPackageList = [ ]\n categoryList = [ ]\n targetDict = dict( )\n\n if action == \"update-all\":\n installedPackages = portage.PortageInstance.getInstallables( )\n if portage.PortageInstance.isCategory( packageName ):\n EmergeDebug.debug(\"Updating installed packages from category \" + packageName, 1)\n else:\n EmergeDebug.debug(\"Updating all installed packages\", 1)\n packageList = [ ]\n for mainCategory, mainPackage in installedPackages:\n if portage.PortageInstance.isCategory( packageName ) and ( mainCategory != packageName ):\n continue\n if InstallDB.installdb.isInstalled( mainCategory, mainPackage, args.buildType ) \\\n and portage.isPackageUpdateable( mainCategory, mainPackage ):\n categoryList.append( mainCategory )\n packageList.append( mainPackage )\n EmergeDebug.debug(\"Will update packages: \" + str(packageList), 1)\n elif args.list_file:\n listFileObject = open( args.list_file, 'r' )\n for line in listFileObject:\n if line.strip( ).startswith( '#' ): continue\n try:\n cat, pac, tar, _ = line.split( ',' )\n except:\n continue\n categoryList.append( cat )\n packageList.append( pac )\n originalPackageList.append( pac )\n targetDict[ cat + \"/\" + pac ] = tar\n elif packageName:\n packageList, categoryList = portage.getPackagesCategories( packageName )\n\n for entry in packageList:\n EmergeDebug.debug(\"Checking dependencies for: %s\" % entry, 1)\n\n for mainCategory, entry in zip( categoryList, packageList ):\n deplist = portage.solveDependencies( mainCategory, entry, deplist, args.dependencyType,\n maxDepth = args.dependencydepth )\n # no package found\n if len( deplist ) == 0:\n category = \"\"\n if not packageName.find( \"/\" ) == -1:\n (category, package) = packageName.split( \"/\" )\n portageSearch.printSearch( category, packageName )\n return False\n\n for item in deplist:\n item.enabled = args.ignoreAllInstalled\n\n if args.ignoreInstalled and item.category in categoryList and item.package in packageList or packageIsOutdated(\n item.category, item.package ):\n item.enabled = True\n\n if item.category + \"/\" + item.package in targetDict:\n item.target = targetDict[ item.category + \"/\" + item.package ]\n\n if args.target in list(\n portage.PortageInstance.getAllTargets( item.category, item.package ).keys( ) ):\n # if no target or a wrong one is defined, simply set the default target here\n item.target = args.target\n\n EmergeDebug.debug(\"dependency: %s\" % item, 1)\n if not deplist:\n EmergeDebug.debug(\"\", 1)\n\n EmergeDebug.debug_line(1)\n\n #for item in deplist:\n # cat = item[ 0 ]\n # pac = item[ 1 ]\n # ver = item[ 2 ]\n\n # if portage.isInstalled( cat, pac, ver, buildType) and updateAll and not portage.isPackageUpdateable( cat, pac, ver ):\n # print \"remove:\", cat, pac, ver\n # deplist.remove( item )\n\n if action == \"install-deps\":\n # the first dependency is the package itself - ignore it\n # TODO: why are we our own dependency?\n del deplist[ 0 ]\n elif action == \"update-direct-deps\":\n for item in deplist:\n item.enabled = True\n\n deplist.reverse( )\n\n # package[0] -> category\n # package[1] -> package\n # package[2] -> version\n\n info = deplist[ -1 ]\n if not portage.PortageInstance.isVirtualPackage( info.category, info.package ) and \\\n not action in [ \"all\", \"install-deps\"] and\\\n not args.list_file or\\\n action in [\"print-targets\"]:#not all commands should be executed on the deps if we are a virtual packages\n # if a buildAction is given, then do not try to build dependencies\n # and do the action although the package might already be installed.\n # This is still a bit problematic since packageName might not be a valid\n # package\n # for list files, we also want to handle fetching & packaging per package\n if not handlePackage( info.category, info.package, action, args.doContinue, args.update_fast ):\n return False\n\n else:\n if args.dumpDepsFile:\n dumpDepsFileObject = open( args.dumpDepsFile, 'w+' )\n dumpDepsFileObject.write( \"# dependency dump of package %s\\n\" % ( packageName ) )\n for info in deplist:\n isVCSTarget = False\n\n if args.dumpDepsFile:\n dumpDepsFileObject.write( \",\".join( [ info.category, info.package, info.target, \"\" ] ) + \"\\n\" )\n\n isLastPackage = info == deplist[ -1 ]\n if args.outDateVCS or (args.outDatePackage and isLastPackage):\n isVCSTarget = portage.PortageInstance.getUpdatableVCSTargets( info.category, info.package ) != [ ]\n isInstalled = InstallDB.installdb.isInstalled( info.category, info.package )\n if args.list_file and action != \"all\":\n info.enabled = info.package in originalPackageList\n if ( isInstalled and not info.enabled ) and not (\n isInstalled and (args.outDateVCS or (\n args.outDatePackage and isLastPackage) ) and isVCSTarget ):\n if EmergeDebug.verbose() > 1 and info.package == packageName:\n EmergeDebug.warning(\"already installed %s/%s\" % (info.category, info.package))\n elif EmergeDebug.verbose() > 2 and not info.package == packageName:\n EmergeDebug.warning(\"already installed %s/%s\" % (info.category, info.package))\n else:\n # in case we only want to see which packages are still to be build, simply return the package name\n if args.probe:\n EmergeDebug.warning(\"pretending %s\" % info)\n else:\n if action in [ \"install-deps\", \"update-direct-deps\" ]:\n action = \"all\"\n\n if not handlePackage( info.category, info.package, action, args.doContinue, args.update_fast ):\n EmergeDebug.error(\"fatal error: package %s/%s %s failed\" % \\\n ( info.category, info.package, action ))\n return False\n\n EmergeDebug.new_line()\n return True\n\nclass ActionHandler:\n class StoreTrueAction(argparse._StoreTrueAction):\n def __call__(self, parser, namespace, values, option_string=None):\n ActionHandler.StoreAction._addOrdered(namespace, self.dest, self.const)\n super().__call__(parser, namespace, values, option_string)\n\n class StoreAction(argparse._StoreAction):\n \"\"\"http://stackoverflow.com/a/9028031\"\"\"\n def __call__(self, parser, namespace, values, option_string=None):\n ActionHandler.StoreAction._addOrdered(namespace, self.dest, values)\n super().__call__(parser, namespace, values, option_string)\n\n @staticmethod\n def _addOrdered(namespace, key, value):\n if not 'ordered_args' in namespace:\n setattr(namespace, 'ordered_args', collections.OrderedDict())\n namespace.ordered_args[key] = value\n\n\n def __init__(self, parser):\n self.parser = parser\n self.actions = {}\n\n def _addAction(self, actionName, help = None, **kwargs):\n arg = self.parser.add_argument(\"--%s\" % actionName,\n help = \"[Action] %s\" % (help if help else \"\"), **kwargs)\n self.actions[arg.dest] = actionName\n\n def addAction(self, actionName, **kwargs):\n self._addAction(actionName, action = ActionHandler.StoreTrueAction, **kwargs)\n\n def addActionWithArg(self, actionName, **kwargs):\n self._addAction(actionName, action = ActionHandler.StoreAction, **kwargs)\n\n def parseFinalAction(self, args, defaultAction):\n '''Returns the list of actions or [defaultAction]'''\n return [self.actions[x] for x in args.ordered_args.keys()] if hasattr(args, \"ordered_args\") else [defaultAction]\n\n\ndef main( ):\n parser = argparse.ArgumentParser( prog = \"emerge\",\n description = \"Emerge is a tool for building KDE-related software under Windows. emerge automates it, looks for the dependencies and fetches them automatically.\\\n Some options should be used with extreme caution since they will make your kde installation unusable in 999 out of 1000 cases.\",\n epilog = \"\"\"More information see the README or http://windows.kde.org/.\n Send feedback to .\"\"\" )\n\n parser.add_argument( \"-p\", \"--probe\", action = \"store_true\",\n help = \"probing: emerge will only look which files it has to build according to the list of installed files and according to the dependencies of the package.\" )\n parser.add_argument( \"--list-file\", action = \"store\",\n help = \"Build all packages from the csv file provided\" )\n _def = emergeSettings.get( \"General\", \"EMERGE_OPTIONS\", \"\" )\n if _def == \"\": _def = []\n else: _def = _def.split( \";\" )\n parser.add_argument( \"--options\", action = \"append\",\n default = _def,\n help = \"Set emerge property from string . An example for is \\\"cmake.openIDE=1\\\" see options.py for more informations.\" )\n parser.add_argument( \"-z\", \"--outDateVCS\", action = \"store_true\",\n help = \"if packages from version control system sources are installed, it marks them as out of date and rebuilds them (tags are not marked as out of date).\" )\n parser.add_argument( \"-sz\", \"--outDatePackage\", action = \"store_true\",\n help = \"similar to -z, only that it acts only on the last package, and works as normal on the rest.\" )\n parser.add_argument( \"-q\", \"--stayquiet\", action = \"store_true\",\n dest = \"stayQuiet\",\n help = \"quiet: there should be no output - The verbose level should be 0\" )\n parser.add_argument( \"-t\", \"--buildtests\", action = \"store_true\", dest = \"buildTests\",\n default = emergeSettings.getboolean( \"Compile\", \"BuildTests\", False ) )\n parser.add_argument( \"-c\", \"--continue\", action = \"store_true\", dest = \"doContinue\" )\n parser.add_argument(\"-cc\", \"--create-cache\", action=\"store_true\", dest=\"createCache\",\n default=emergeSettings.getboolean(\"ContinuousIntegration\", \"CreateCache\", \"False\"))\n parser.add_argument(\"-uc\", \"--use-cache\", action=\"store_true\", dest=\"useCache\",\n default=emergeSettings.getboolean(\"ContinuousIntegration\", \"UseCache\", \"False\"))\n parser.add_argument( \"--destroy-emerge-root\", action = \"store_true\", dest = \"doDestroyEmergeRoot\",\n default=False)\n parser.add_argument( \"--offline\", action = \"store_true\",\n default = emergeSettings.getboolean( \"General\", \"WorkOffline\", False ),\n help = \"do not try to connect to the internet: KDE packages will try to use an existing source tree and other packages would try to use existing packages in the download directory.\\\n If that doesn't work, the build will fail.\" )\n parser.add_argument( \"-f\", \"--force\", action = \"store_true\", dest = \"forced\",\n default = emergeSettings.getboolean( \"General\", \"EMERGE_FORCED\", False ) )\n parser.add_argument( \"--buildtype\", choices = [ \"Release\", \"RelWithDebInfo\", \"MinSizeRel\", \"Debug\" ],\n dest = \"buildType\",\n default = emergeSettings.get( \"Compile\", \"BuildType\", \"RelWithDebInfo\" ),\n help = \"This will override the build type set in your kdesettings.ini.\" )\n parser.add_argument( \"-v\", \"--verbose\", action = \"count\",\n default = int( emergeSettings.get( \"EmergeDebug\", \"Verbose\", \"0\" ) ),\n help = \" verbose: increases the verbose level of emerge. Default is 1. verbose level 1 contains some notes from emerge, all output of cmake, make and other programs that are used.\\\n verbose level 2a dds an option VERBOSE=1 to make and emerge is more verbose highest level is verbose level 3.\" )\n parser.add_argument( \"--trace\", action = \"store\",\n default = int( emergeSettings.get( \"General\", \"EMERGE_TRACE\", \"0\" ) ), type = int )\n parser.add_argument( \"-i\", \"--ignoreInstalled\", action = \"store_true\",\n help = \"ignore install: using this option will install a package over an existing install. This can be useful if you want to check some new code and your last build isn't that old.\" )\n parser.add_argument( \"-ia\", \"--ignoreAllInstalled\", action = \"store_true\",\n help = \"ignore all install: using this option will install all package over an existing install. This can be useful if you want to check some new code and your last build isn't that old.\" )\n\n parser.add_argument( \"--target\", action = \"store\",\n help = \"This will override the build of the default target. The default Target is marked with a star in the printout of --print-targets\" )\n parser.add_argument( \"--search\", action = \"store_true\",\n help = \"This will search for a package or a description matching or similar to the search term.\" )\n parser.add_argument( \"--noclean\", action = \"store_true\",\n default = emergeSettings.getboolean( \"General\", \"EMERGE_NOCLEAN\", False ),\n help = \"this option will try to use an existing build directory. Please handle this option with care - it will possibly break if the directory isn't existing.\" )\n parser.add_argument( \"--clean\", action = \"store_false\", dest = \"noclean\",\n help = \"oposite of --noclean\" )\n parser.add_argument( \"--patchlevel\", action = \"store\",\n default = emergeSettings.get( \"General\", \"EMERGE_PKGPATCHLVL\", \"\" ),\n help = \"This will add a patch level when used together with --package\" )\n parser.add_argument( \"--log-dir\", action = \"store\",\n default = emergeSettings.get( \"General\", \"EMERGE_LOG_DIR\", \"\" ),\n help = \"This will log the build output to a logfile in LOG_DIR for each package. Logging information is appended to existing logs.\" )\n parser.add_argument( \"--dt\", action = \"store\", choices = [ \"both\", \"runtime\", \"buildtime\" ], default = \"both\",\n dest = \"dependencyType\" )\n parser.add_argument( \"--update-fast\", action = \"store_true\",\n help = \"If the package is installed from svn/git and the revision did not change all steps after fetch are skipped\" )\n parser.add_argument( \"-d\", \"--dependencydepth\", action = \"store\", type = int, default = -1,\n help = \"By default emerge resolves the whole dependency graph, this option limits the depth of the graph, so a value of 1 would mean only dependencies defined in that package\" )\n\n actionHandler = ActionHandler(parser)\n for x in sorted( [ \"fetch\", \"fetch-binary\", \"unpack\", \"configure\", \"compile\", \"make\",\n \"install\", \"install-deps\", \"qmerge\", \"manifest\", \"package\", \"unmerge\", \"test\",\n \"checkdigest\", \"dumpdeps\",\n \"full-package\", \"cleanimage\", \"cleanbuild\", \"createpatch\", \"geturls\"] ):\n actionHandler.addAction( x )\n actionHandler.addAction( \"update\", help = \"Update a single package\" )\n\n # read-only actions\n actionHandler.addAction( \"print-source-version\" )\n actionHandler.addAction( \"print-package-version\" )\n actionHandler.addAction( \"print-targets\",\n help = \"This will show a list of available targets for the package\" )\n actionHandler.addAction( \"print-installed\",\n help = \"This will show a list of all packages that are installed currently.\" )\n actionHandler.addAction( \"print-installable\",\n help = \"This will give you a list of packages that can be installed. Currently you don't need to enter the category and package: only the package will be enough.\" )\n actionHandler.addAction( \"print-revision\", help = \"Print the revision of the package and exit\" )\n actionHandler.addAction( \"print-files\", help = \"Print the files installed by the package and exit\" )\n actionHandler.addActionWithArg( \"search-file\", help = \"Print packages owning the file\" )\n\n # other actions\n actionHandler.addActionWithArg( \"dump-deps-file\", dest = \"dumpDepsFile\",\n help = \"Output the dependencies of this package as a csv file suitable for emerge server.\" )\n\n parser.add_argument( \"packageNames\", nargs = argparse.REMAINDER )\n\n args = parser.parse_args( )\n\n if args.doDestroyEmergeRoot:\n destroyEmergeRoot()\n return True\n\n\n if args.stayQuiet:\n EmergeDebug.setVerbose(-1)\n elif args.verbose:\n EmergeDebug.setVerbose(args.verbose)\n\n emergeSettings.set( \"General\", \"WorkOffline\", args.offline )\n emergeSettings.set( \"General\", \"EMERGE_NOCLEAN\", args.noclean )\n emergeSettings.set( \"General\", \"EMERGE_FORCED\", args.forced )\n emergeSettings.set( \"Compile\", \"BuildTests\", args.buildTests )\n emergeSettings.set( \"Compile\", \"BuildType\", args.buildType )\n emergeSettings.set( \"PortageVersions\", \"DefaultTarget\", args.target )\n emergeSettings.set( \"General\", \"EMERGE_OPTIONS\", \";\".join( args.options ) )\n emergeSettings.set( \"General\", \"EMERGE_LOG_DIR\", args.log_dir )\n emergeSettings.set( \"General\", \"EMERGE_TRACE\", args.trace )\n emergeSettings.set( \"General\", \"EMERGE_PKGPATCHLVL\", args.patchlevel )\n emergeSettings.set( \"ContinuousIntegration\", \"CreateCache\", args.createCache)\n emergeSettings.set( \"ContinuousIntegration\", \"UseCache\", args.useCache)\n\n portage.PortageInstance.options = args.options\n if args.search:\n for package in args.packageNames:\n category = \"\"\n if not package.find( \"/\" ) == -1:\n (category, package) = package.split( \"/\" )\n portageSearch.printSearch( category, package )\n return True\n\n\n for action in actionHandler.parseFinalAction(args, \"all\"):\n tempArgs = copy.deepcopy(args)\n\n if action in [ \"install-deps\", \"update\", \"update-all\", \"package\" ] or tempArgs.update_fast:\n tempArgs.ignoreInstalled = True\n\n if action in [ \"update\", \"update-all\" ]:\n tempArgs.noclean = True\n\n EmergeDebug.debug(\"buildAction: %s\" % action)\n EmergeDebug.debug(\"doPretend: %s\" % tempArgs.probe, 1)\n EmergeDebug.debug(\"packageName: %s\" % tempArgs.packageNames)\n EmergeDebug.debug(\"buildType: %s\" % tempArgs.buildType)\n EmergeDebug.debug(\"buildTests: %s\" % tempArgs.buildTests)\n EmergeDebug.debug(\"verbose: %d\" % EmergeDebug.verbose(), 1)\n EmergeDebug.debug(\"trace: %s\" % tempArgs.trace, 1)\n EmergeDebug.debug(\"KDEROOT: %s\" % EmergeStandardDirs.emergeRoot(), 1)\n EmergeDebug.debug_line()\n\n if action == \"print-installed\":\n InstallDB.printInstalled( )\n elif action == \"print-installable\":\n portage.printInstallables( )\n elif action == \"search-file\":\n portage.printPackagesForFileSearch(tempArgs.search_file)\n elif tempArgs.list_file:\n handleSinglePackage( \"\", action, tempArgs )\n else:\n for packageName in tempArgs.packageNames:\n if not handleSinglePackage( packageName, action, tempArgs ):\n return False\n return True\n\n\nif __name__ == '__main__':\n success= True\n with EmergeTimer.Timer(\"Emerge\", 0):\n try:\n doUpdateTitle = True\n\n def updateTitle( startTime, title ):\n while ( doUpdateTitle ):\n delta = datetime.datetime.now( ) - startTime\n utils.OsUtils.setConsoleTitle( \"emerge %s %s\" % (title, delta) )\n time.sleep( 1 )\n\n tittleThread = threading.Thread( target = updateTitle,\n args = (datetime.datetime.now( ), \" \".join( sys.argv[ 1: ] ),) )\n tittleThread.setDaemon( True )\n tittleThread.start( )\n success = main()\n except KeyboardInterrupt:\n pass\n except portage.PortageException as e:\n if e.exception:\n EmergeDebug.debug(e.exception, 0)\n traceback.print_tb( e.exception.__traceback__)\n EmergeDebug.error(e)\n except Exception as e:\n print( e )\n traceback.print_tb( e.__traceback__ )\n finally:\n doUpdateTitle = False\n if emergeSettings.getboolean( \"EmergeDebug\", \"DumpSettings\", False ):\n emergeSettings.dump( )\n if not success:\n exit( 1 )\n\n","sub_path":"bin/emerge.py","file_name":"emerge.py","file_ext":"py","file_size_in_byte":27401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"63540402","text":"import re\nfrom collections import defaultdict\n\n\n\n\ndef load_data(path):\n file = open(path,'r')\n data = file.readlines()\n file.close()\n # print(len(data))\n return(data)\n\n\n\n\ndef parse_data(data):\n\n p = 0\n # luggage_policy= {}\n # A nested dict has been created with the following structure ({parent:{child1:amount, child2:amount}})\n lug_dict = defaultdict(dict)\n\n parent_pattern = re.compile(\"(\\A\\w+\\s\\w+)\")\n child_pattern = re.compile(\"(\\d\\s\\w+\\s\\w+)\")\n\n for bag in data:\n parent_bag = re.findall(parent_pattern,bag)\n child_bags = re.findall(child_pattern,bag)\n\n for substring in child_bags:\n p +=1\n amount = re.match('\\d',substring).group()\n lug_type = re.findall('[a-zA-Z]+\\s[a-zA-Z]+',substring)\n lug_dict[parent_bag[0]][lug_type[0]] = amount\n return(lug_dict)\n\n\ndef breadth_first(policy_dict):\n\n answer = set() \n \n q = ['shiny gold'] # Work queue for traversing bags\n while len(q) != 0:\n current = q.pop(0)\n for key in policy_dict.keys():\n print(key)\n if key in answer: # Skip if already counted.\n continue\n if current in policy_dict[key]: # If bag contains current-bag,\n q.append(key) # add to queue and answer\n answer.add(key)\n\n return(len(answer))\n\n\n\n\n\n\n\nfilepath = '/home/kiagkons/Desktop/advent of code/day7/sample.in'\n\ndata = load_data(filepath)\ndict = parse_data(data)\nresult = breadth_first(dict)\nprint('The number of luggages is ',result)\n\n","sub_path":"day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"433688258","text":"from .reload import autoreload\n\n\ndef load_entry_point(entry_point, reload=False):\n \n # Parse the entry_point.\n parts = entry_point.split(':')\n if len(parts) != 2:\n raise ValueError('Entry point must look like \"package.module:function\"; got %r' % entry_point)\n \n module_name, attribute = parts\n \n # If we can't directly import it, then import the package and get the\n # module via attribute access. This is because of the `code` sub-package\n # on many of the older tools.\n try:\n module = __import__(module_name, fromlist=['.'])\n except ImportError as ie:\n parts = module_name.rsplit('.', 1)\n if len(parts) == 1:\n raise ie\n package_name, module_name = parts\n package = __import__(package_name, fromlist=['.'])\n module = getattr(package, module_name, None)\n if module is None:\n raise\n \n # Reload if requested. `reload is None` is automatic. `reload is True`\n # will always reload the direct module.\n if reload or reload is None:\n autoreload(module, force_self=bool(reload))\n \n # Grab the function.\n try:\n return getattr(module, attribute)\n except AttributeError:\n raise ValueError('%r module has no %r attribute' % (module.__name__, attribute))\n\n","sub_path":"metatools/imports/entry_points.py","file_name":"entry_points.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"357306899","text":"# Run in this in a new directory called 'buildmap' in the same dir as the RELION/SPIDER/binary dirs.\n# Then run \n# > relion_reconstruct --i EULER_1_of_20.star --angpix 1.2 --o RECONSTRUCT_1_of_20.mrc\n\n# Note that in this case this is for nClass of 20, whereas the default is 50, so change if needed.\n\nimport numpy as np\nimport mrcfile\nimport pandas as pd\n\nnPix = 160\n\nfor i in range(20):\n n = i+1\n\n binary_file = '../SPIDER/imgsSPIDER_trajectoryName_%s_of_20.dat'%n\n mrc_filename = 'particleIMGS_%s_of_20'%n\n \n align_file = '../RELION/align_%02d.dat'%n\n star_file = 'EULER_%s_of_20.star'%n \n\n\n binary_array = np.fromfile(binary_file,dtype=np.float32)\n\n # This builds a 3D array of nPix by nPix particles, skipping the headers\n my_particles = []\n # J iterates through particles\n for j in range(len(binary_array)/(nPix*nPix)):\n particle = []\n # i iterates through rows in the nPix x nPix particle\n for i in range(nPix):\n particle.append(binary_array[ (nPix*nPix*j) +(i+6+(3*j)) *nPix: (nPix*nPix*j) +(i+7+(3*j)) *nPix ])\n my_particles.append(particle)\n\n # We want to trim our number of particles, but before we do that we want to know the right number\n # of particles from our align file\n\n df_Euler = pd.read_csv(align_file,sep='\\s+') \n df_Euler.columns=['particle','#columns','psi','theta','phi']\n\n print('### Frame %s has %s particles. ###' %(n,len(df_Euler)))\n\n my_particles_trimmed = my_particles[0:len(df_Euler)]\n\n # Below here is to get the data in a format that the mrcfile package understands.\n # This may be somewhat overkill, but it works.\n df = pd.DataFrame(my_particles_trimmed)\n values = df.values\n list_values = []\n for value in values:\n list_values.append(value.tolist())\n list_values_array = np.asarray(list_values)\n\n # Then we save that to our mrc file!\n mrc = mrcfile.new('%s.mrcs'%mrc_filename,overwrite=True)\n\n # The -1 here inverts the image so the particles are white.\n mrc.set_data(list_values_array*-1)\n mrc.set_image_stack()\n mrc.close()\n\n # Now we write out our star file\n with open(star_file,'w') as text_file: \n text_file.write('\\ndata_ \\n \\nloop_ \\n \\n_rlnImageName #1 \\n_rlnAnglePsi #2 \\n_rlnAngleTilt #3 \\n_rlnAngleRot #4 \\n')\n for i in range(len(df_Euler)):\n text_file.write('%s@%s.mrcs %s %s %s\\n' %(df_Euler.particle[i],mrc_filename,df_Euler.psi[i],df_Euler.theta[i],df_Euler.phi[i]))\n","sub_path":"make_reconstruct_inputs.py","file_name":"make_reconstruct_inputs.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"461414521","text":"\n\nclass Species(object):\n def __init__(self, epochs=0, max_fitness=0, stagnant=0, allowed_offspring=0):\n self.epochs_lived = epochs\n self.max_fitness = max_fitness\n self.epochs_stagnant = stagnant\n self.allowed_offspring = allowed_offspring\n\n def __str__(self):\n return ('epochs_lives: {epochs_lived}\\n'\n 'max_fitness: {max_fitness}\\n'\n 'epochs_stagnant: {epochs_stagnant}\\n'\n 'allowed_offspring: {allowed_offspring}\\n'\n ).format(**self.__dict__)","sub_path":"Species.py","file_name":"Species.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"534614061","text":"import os\nimport sys\nimport logging\nimport logging.config\nimport pandas as pd\nimport sqlalchemy as sql\n\n\nfrom sqlalchemy import create_engine, Column, Integer, String, Text,Float\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, MetaData\n\nimport argparse\n\n#get logger\nlogging.basicConfig(level=logging.INFO, filename=\"logfile\")\nlogger = logging.getLogger('Create_database')\n\n#define base\nBase = declarative_base()\n\nclass user_input(Base):\n\t\"\"\" Defines the data model for the table `user_input. \"\"\"\n\t__tablename__ = 'user_input'\n\n\t#define each column name and variable type\n\tId = Column(Integer, primary_key=True, unique=True, nullable=False)\n\tsize_bytes = Column(String(100), unique=False, nullable=False)\n\tprice = Column(Float, unique=False, nullable=False)\n\tsup_devices_num = Column(Integer, unique=False, nullable=False)\n\tipadSc_urls_num = Column(Integer, unique=False, nullable=False)\n\tlang_num = Column(Integer, unique=False, nullable=False)\n\trating_count_tot = Column(String(100), unique=False, nullable=False)\n\trating_count_ver = Column(String(100), unique=False, nullable=False)\n\tcont_rating = Column(String(100), unique=False, nullable=False)\n\tprime_genre = Column(Text, unique=False, nullable=False)\n\tapp_desc = Column(Text, unique=False, nullable=False)\n\tprediction = Column(Float, unique=False, nullable=False)\n\n\tdef __repr__(self):\n\t\tuser_repr = \"\"\n\t\treturn user_repr % (self.Id, self.size_bytes, self.price, self.rating_count, self.cont_rating_tot, self.cont_rating_ver, self.prime_genre, self.sup_devices_num, self.ipadSc_urls_num, self.lang_num, self.app_desc)\n\ndef get_engine_string(RDS = False):\n\t\"\"\"Get database engine path.\"\"\"\n\tif RDS:\n\t\tconn_type = \"mysql+pymysql\"\n\t\tuser = os.environ.get(\"MYSQL_USER\")\n\t\tpassword = os.environ.get(\"MYSQL_PASSWORD\")\n\t\thost = os.environ.get(\"MYSQL_HOST\")\n\t\tport = os.environ.get(\"MYSQL_PORT\")\n\t\tDATABASE_NAME = 'msia423'\n\t\tengine_string = \"{}://{}:{}@{}:{}/{}\". \\\n\t\tformat(conn_type, user, password, host, port, DATABASE_NAME)\n\t\tlogging.debug(\"engine string: %s\"%engine_string)\n\t\treturn engine_string\n\telse:\n\t\treturn 'sqlite:///data/user_input.db' # relative path\n\n\ndef create_db(args, engine=None):\n\t\"\"\"Creates a database with the data models inherited from `Base`.\n\n Args:\n engine (:py:class:`sqlalchemy.engine.Engine`, default None): SQLAlchemy connection engine.\n If None, `engine_string` must be provided.\n engine_string (`str`, default None): String defining SQLAlchemy connection URI in the form of\n `dialect+driver://username:password@host:port/database`. If None, `engine` must be provided.\n\n Returns:\n None\n \"\"\"\n #if running on RDS\n\tif args.RDS:\n\t\tengine = sql.create_engine(get_engine_string(RDS = True))\n\t#if running a local\n\telse:\n\t\tengine = sql.create_engine(get_engine_string(RDS = False))\n\tlogger.info(\"RDS:%s\"%args.RDS)\n\n\n\tBase.metadata.create_all(engine)\n\tlogging.info(\"database created\")\n\n\t#create a db session\n\tSession = sessionmaker(bind=engine) \n\tsession = Session()\n\n\t#test unit for the user_input table\n\tuser1 = user_input(size_bytes='100788224', price=3.99, rating_count_tot=21292, rating_count_ver=26, cont_rating='4+', \n\t\t\t\t\t\tprime_genre='Games', sup_devices_num=38, ipadSc_urls_num=5, lang_num=10, app_desc='SAVE 20%, now only $3.99 for a limited time! One of the most popular video games in arcade history! 2015 World Video Game Hall of Fame Inductee', prediction = 4)\n\tsession.add(user1)\n\n\tlogger.info(\"Data added\")\n\tsession.commit()\n\n\treturn engine\n\n\nif __name__ == \"__main__\":\n\t#user input\n\tparser = argparse.ArgumentParser(description=\"Create Database\")\n\tparser.add_argument('--RDS', default = False, help='Whether connect to RDS')\n\t\n\n\targs = parser.parse_args()\n\n\tengine = create_db(args)\n\n\tquery = \"SELECT * FROM user_input\"\n\tdf = pd.read_sql(query, con=engine)\n\tprint(df)\n\n\n\t\n\n\n\n\t\n\n\n","sub_path":"src/Create_database.py","file_name":"Create_database.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"226348086","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\nimport sys\n\n\n'''\nStream classes for writing to files.\n'''\n\nclass PypsiStream(object):\n '''\n Unbuffered file output stream. This class should be used primarily\n for writing to :data:`sys.stdout` or :data:`sys.stderr`. The stream allows\n for prefix and postfix strings to be written to the file before or after\n each call to :func:`write`. This can be useful when printing colors to the\n screen or the log levels of messages.\n\n The wrapped file object can be a callable object that returns a file\n object. This object will then be called once during each\n invocation of :func:`write` to retrieve the current output file object.\n '''\n\n def __init__(self, fobj, prefix=None, postfix=None):\n '''\n :param file fobj: the file object to wrap or a function to retrieve the\n file object when writing to it\n :param str prefix: a string to write to the stream whenever :func:`write`\n is called\n :param str postfix: a string to write to the stream after :func:`write`\n is called\n '''\n self.fobj = fobj\n self.prefix = prefix\n self.postfix = postfix\n\n def __call__(self, *args):\n '''\n Alias for :func:`write`.\n '''\n return self.write(*args)\n\n def write(self, *args):\n '''\n Write any number of arguments to the stream.\n '''\n stream = self.fobj if not callable(self.fobj) else self.fobj()\n if self.prefix:\n stream.write(self.prefix)\n\n for s in args:\n if isinstance(s, str):\n stream.write(s)\n elif s is not None:\n stream.write(str(s))\n\n if self.postfix:\n stream.write(self.postfix)\n\n stream.flush()\n\n\nclass AnsiStream(object):\n TTY = 0\n ForceOn = 1\n ForceOff = 2\n\n def __init__(self, mode=TTY):\n self.mode = mode\n self.codes = {\n 'reset': '\\x1b[0m',\n 'gray': '\\x1b[1;30m',\n 'red': '\\x1b[1;31m',\n 'green': '\\x1b[1;32m',\n 'yellow': '\\x1b[1;33m',\n 'blue': '\\x1b[1;34m',\n 'purple': '\\x1b[1;35m',\n 'cyan': '\\x1b[1;36m',\n 'white': '\\x1b[1;37m',\n 'black': '\\x1b[0;30m',\n 'clear_screen': '\\x1b[2J\\x1b[;H'\n }\n\n def __getattr__(self, key):\n return self.__getitem__(key)\n\n def __getitem__(self, key):\n check = False\n if self.mode == self.TTY:\n check = self.isatty()\n elif self.mode == self.ForceOn:\n check = True\n elif self.mode == self.ForceOff:\n check = False\n\n return self.codes[key] if check else ''\n\n\nclass AnsiStdoutSingleton(AnsiStream):\n\n def isatty(self):\n return sys.stdout.isatty()\n\n\nclass AnsiStderrSingleton(AnsiStream):\n\n def isatty(self):\n return sys.stderr.isatty()\n\n\nAnsiStdout = AnsiStdoutSingleton()\nAnsiStderr = AnsiStderrSingleton()\n\n","sub_path":"pypsi/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"613662667","text":"from bs4 import BeautifulSoup\nimport requests\nfrom sopel import module\n\n\ndef get_hero_list():\n # Gets the free heroes from heroesofthestorm.gamepedia.com and puts them in a list\n soup = BeautifulSoup(requests.get('http://heroesofthestorm.gamepedia.com/Free_rotation').text, 'lxml')\n hero_list = []\n for div in soup.findAll('div', class_='hero-tile'):\n a = div.findAll('a')[1]\n hero_list.append(a.text)\n\n return hero_list\n\n\n@module.commands('rotation')\ndef rotation(bot, trigger):\n # Posts the current free hero rotation\n hero_list = get_hero_list()\n if hero_list:\n bot.say('Free rotation: ' + ', '.join(hero_list))\n else:\n bot.say('Free rotation not found.')\n","sub_path":"rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"546385375","text":"\n\nfrom xai.brain.wordbase.nouns._affair import _AFFAIR\n\n#calss header\nclass _AFFAIRS(_AFFAIR, ):\n\tdef __init__(self,): \n\t\t_AFFAIR.__init__(self)\n\t\tself.name = \"AFFAIRS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"affair\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_affairs.py","file_name":"_affairs.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398951998","text":"\"\"\"\n# NOTE (for Sam): Run on \"QSTrader\" Conda Virtual Enviroment \n > \"source activate QSTrader\"\n > Run via \"python coincap_ERC-20_ranker.py\"\n\nSummary of script\n 1) Open Top ERC-20 file & create a DataFrame with the info\n 2) Get ID's for all ERC-20 tokens using Global API\n 3) Use Ticker(Specific Currency) API to get info on each ERC-20 token\n 4) Create a DataFrame with all the info\n 5) Write DataFrame to .xlsx file\n\n# NOTE: Code must be run on a Virtual Environment in order to import \"prettytable\" (as least this was the case for me)\n\"\"\"\n\nimport re\nimport xlrd \nimport json\nimport requests\nimport datetime\nimport numpy as np\nimport pandas as pd\nfrom openpyxl import load_workbook\nfrom prettytable import PrettyTable\nfrom colorama import Fore, Back, Style\n\n\n\n### 1) Open Top ERC-20 Tokens File\nfile_path = r\"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/CMC-ID-Map.xlsx\"\n# top_ERC_df = pd.read_csv(file_path, header=0,index_col=0) # for .csv\ntop_ERC_df = pd.read_excel(file_path, sheet_name = 'Top ERC-20') # read all data from \"Top ERC-20\"\nheaders = list(top_ERC_df.columns.values) # get the headers --> ERC-20 Token, Ticker, ID, CoinMarketCap URL, Market Cap (yyyy-mm-dd) \ntop_ERC_df = pd.DataFrame(top_ERC_df) # convert top_ERC_df to a DateFrame\n\n# Get IDs\nERC_ID_List = top_ERC_df.iloc[:,2]\n\n# Set Currency\nconvert = 'USD'\n\n### CoinMarketCap API\n# EXAMPLE API KEY Call --> https://pro-api.coinmarketcap.com/v1/cryptocurrency/map?CMC_PRO_API_KEY=a3e5008f-c6b1-471d-9b4c-c4424e8b7d1f\nAPI_Key = '?CMC_PRO_API_KEY=3245f792-04f0-4517-86be-4c15c30edc1e' # Sam's personal API Key \n# listings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/historical' + API_Key # Not Supported in Free subscription plan\nlistings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' + API_Key # Listings Latest\nurl_end = '?structure=array&convert=' + convert # Might not be necessary anymore \n\nrequest = requests.get(listings_url)\nresults = request.json()\ndata = results['data'] # All Data\n#currencyData = results['data'][0] # All Currencies\n\n# print(json.dumps(results, sort_keys=True, indent=4))\n\n### Initilaize List elements --> will be used to create DataFrame --> used to create .xlsx file\nid_num_List = list()\nname_List = list()\nsymbol_List = list()\nwebsite_slug_List = list()\ncmc_rank_List = list()\nnum_markets_List = list()\ncirculating_supply_List = list()\ntotal_supply_List = list()\npercent_total_supply_circulating_List = list()\nmax_supply_List = list()\nlast_updated_List = list()\n# ['quote']['USD']\nprice_List = list()\nvolume_24h_List = list()\nmarket_cap_List = list()\npercent_change_1h_List = list()\npercent_change_24h_List = list()\npercent_change_7d_List = list()\n\njjj = 0\n#for currency in currencyData: # For each \nfor currency in data: # For each \n\n if currency['id'] in ERC_ID_List: # ONLY FOR ERC-20 Tokens\n ### Get Data for ticker \n id_num = currency['id']\n rank = currency['cmc_rank']\n name = currency['name']\n symbol = currency['symbol']\n website_slug = currency['slug']\n website_slug = \"https://coinmarketcap.com/currencies/\" + website_slug + \"/\"\n num_markets = currency['num_markets']\n circulating_supply = currency['circulating_supply']\n total_supply = currency['total_supply']\n\n if circulating_supply is None:\n circulating_supply = 0 \n if total_supply is None:\n total_supply = 0\n percent_total_supply_circulating = \"None\"\n else:\n # percent_total_supply_circulating = int(round(circulating_supply/total_supply*100))\n percent_total_supply_circulating = round(circulating_supply/total_supply*100)\n\n max_supply = currency['max_supply']\n last_updated = currency['last_updated']\n # Quotes\n quotes = currency['quote'][convert]\n price = round(quotes['price'],4)\n volume = round(quotes['volume_24h'])\n percent_change_1h = quotes['percent_change_1h']\n percent_change_24h = quotes['percent_change_24h']\n percent_change_7d = quotes['percent_change_7d']\n market_cap = quotes['market_cap']\n\n print(jjj,': ', name, \" (\", symbol, \")\")\n jjj += 1\n\n ### Append List Elements\n id_num_List.append(id_num)\n cmc_rank_List.append(rank)\n name_List.append(name)\n symbol_List.append(symbol)\n website_slug_List.append(website_slug)\n num_markets_List.append(num_markets)\n circulating_supply_List.append(circulating_supply)\n total_supply_List.append(total_supply)\n max_supply_List.append(max_supply)\n last_updated_List.append(last_updated)\n price_List.append(price)\n volume_24h_List.append(volume)\n percent_change_1h_List.append(percent_change_1h)\n percent_change_24h_List.append(percent_change_24h)\n percent_change_7d_List.append(percent_change_7d)\n market_cap_List.append(market_cap)\n\n\n### Create DataFrame from Lists\n##df = pd.DataFrame(data=temp, index=ranking)\nranker_List = pd.DataFrame(\n list(zip(\n cmc_rank_List,\n name_List,\n symbol_List,\n price_List,\n market_cap_List,\n volume_24h_List,\n num_markets_List,\n percent_total_supply_circulating_List,\n circulating_supply_List,\n total_supply_List,\n max_supply_List,\n percent_change_1h_List,\n percent_change_24h_List,\n percent_change_7d_List,\n id_num_List,\n last_updated_List,\n website_slug_List\n )),\n columns=[\n 'Name',\n 'Ticker',\n 'Price ($)',\n 'Market Cap ($)',\n 'Daily Volume ($)',\n 'Number of Markets',\n '% of Total Supply Circulating',\n 'Circulating Supply',\n 'Total Supply',\n 'Max Supply',\n '% Change: 1h',\n '% Change: 24h',\n '% Change: 7d',\n 'ID',\n 'Last Updated',\n 'CoinMarketCap URL'\n ],\n index=cmc_rank_List)\nranker_List.index.name = \"CMC Rank\" # Rename Index\n\n\"\"\"\n### Ordering in Excel Sheet\n cmc_rank_List\n name_List\n symbol_List\n\n price_List\n market_cap_List\n volume_24h_List\n num_markets_List\n\n percent_total_supply_circulating_List\n circulating_supply_List\n total_supply_List\n max_supply_List\n \n percent_change_1h_List\n percent_change_24h_List\n percent_change_7d_List\n\n id_num_List\n last_updated_List\n website_slug_List\n\"\"\"\n\n# Get Time stamp for market cap\ntimeStamp = str(datetime.datetime.today().strftime(' (%Y-%m-%d)')) # Today, as an Integer\n\n### Create Excel File\nfileName = \"MASTER-ERC-20\" + timeStamp\nfile_path_HardDrive = r\"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/\" + fileName + \".xlsx\"\nwriter_HardDrive = pd.ExcelWriter(file_path_HardDrive)#, engine='openpyxl')\nranker_List.to_excel(writer_HardDrive, startrow= 0 , index=True, sheet_name= 'Summary') # write to \"MASTER-Ercot.xlsx\" spreadsheet\n\nwriter_HardDrive.save()\nwriter_HardDrive.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"TokenScraper/CoinMarketCap Adv Project/coincap_ERC-20_DevAPI.py","file_name":"coincap_ERC-20_DevAPI.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"131513051","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom keras.optimizers import SGD, Adam\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.utils.np_utils import to_categorical\n#%matplotlib inline\ndataset = pd.read_csv(\"C:\\\\Users\\\\10651\\\\Desktop\\\\train.csv\")\ny_train = dataset['label']\nx_train = dataset.drop('label', axis=1)\ndel dataset\nx_train.describe()\nx_train['pixel0'].plot()\ndropped_columns = []\nfor column in x_train.columns:\n if x_train[column].max() == x_train[column].min():\n dropped_columns.append(column)\nx_train.drop(dropped_columns, axis = 1, inplace = True)\nprint('Dropped columns:', len(dropped_columns))\nprint('New shape of training dataset:', x_train.shape)\nfor column in x_train.columns:\n if x_train[column].isnull().any():\n print('Null value detected in the feature:', column)\nmin_train = {}\nmax_train = {}\nfor column in x_train.columns:\n min_train[column] = x_train[column].min()\n max_train[column] = x_train[column].max()\n x_train[column] = (x_train[column] - x_train[column].min()) / (x_train[column].max() - x_train[column].min()) # saving amplitudes\nx_train = x_train.values\ny_train.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=False)\ny_train = to_categorical(y_train, num_classes = 10)\nprint(y_train)\nFEATURES = 708\nlayer_1 = 128\nLABELS = 10\nmodel_LR = Sequential()\nmodel_LR.add(Dense(layer_1, input_shape = (FEATURES,)))\nmodel_LR.add(Activation('relu'))\nmodel_LR.add(Dense(LABELS))\nmodel_LR.add(Activation('softmax'))\nmodel_LR.summary()\nmodel_LR.compile(loss = 'categorical_crossentropy', optimizer = Adam(), metrics = ['accuracy'])\nEPOCHS = 10\nBATCH_SIZE = 100\nVALIDATION_SIZE = 0.1\ntraining_history = model_LR.fit(x_train,\n y_train,\n batch_size = BATCH_SIZE,\n epochs = EPOCHS,\n verbose = 1,\n validation_split = VALIDATION_SIZE)\n# model_LR.get_weights()\n# model_LR.getget_weights()\n# print(model_LR.get_config())\n# print(model_LR.get_weights())","sub_path":"Test/kerasNN.py","file_name":"kerasNN.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"512773982","text":"#!/usr/bin/python\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Author: Oliver\n# https://github.com/bucaojit/MyLists\n\nimport sys\nsys.path.append('/usr/local/lib/python2.7/dist-packages')\nfrom flask import Flask, session, redirect, url_for, escape, request, render_template, jsonify, flash\nfrom flask import Flask as flask\nfrom flask.ext.login import LoginManager\nimport flask.ext.login as flask_login\nfrom lib.forms import LoginForm\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nfrom pymongo import MongoClient\nimport pymongo\nimport lib.ListAccessObject as ListAccessObject\nfrom requests.sessions import Session\nfrom operator import itemgetter, attrgetter, methodcaller\nfrom pytz import timezone\nfrom datetime import datetime\nfrom flask_restful import Resource, Api\nimport configparser\nfrom lib.user import User\nimport json\nfrom werkzeug.security import check_password_hash\n\nconfigFile = 'config/lists.config'\nip_addr = 'localhost'\n\napp = Flask(__name__)\napp.config.from_object('config')\napi = Api(app)\nconnection = MongoClient(ip_addr, serverSelectionTimeoutMS=5000)\nConfig = configparser.ConfigParser()\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n# Adding config file to specify options ie database type, ip-address, port\nConfig.read(configFile)\n\n\ntry:\n connection.server_info() \nexcept pymongo.errors.ServerSelectionTimeoutError as err:\n print (\"Unable to connect to MongoDB, exiting\")\n print(err)\n sys.exit(1)\n\ndb = connection.lists\nlist_names = ListAccessObject.ListAccessObject(db,'listnames')\nlists = ListAccessObject.ListAccessObject(db,'myitems')\narchive = ListAccessObject.ListAccessObject(db,'archive')\nbacklog = ListAccessObject.ListAccessObject(db,'backlog')\nlogin = db['login']\n\n@login_manager.user_loader\ndef load_user(username):\n u = app.config['USERS_COLLECTION'].find_one({\"_id\": username})\n if not u:\n return None\n return User(u['_id'])\n\ndef getList(item):\n return str(item['list']).lower()\n\n\nclass SecondEndpoint(Resource):\n def get(self):\n listValues = lists.find_items()\n sortedVals = sorted(listValues, key=getList)\n return jsonify(result=sortedVals)\n\n\nclass LastInsertedEndpoint(Resource):\n def get(self, count):\n listValues = lists.last_items(count)\n return jsonify(result = listValues)\n\napi.add_resource(SecondEndpoint,'/endpoint')\napi.add_resource(LastInsertedEndpoint,'/latest/')\n\n@app.route('/test', methods=['GET', 'POST'])\ndef template_test():\n tableValues = lists.find_items()\n tableValues = sorted(tableValues, key=getList)\n return render_template('lists.html', items=tableValues)\n\n@app.route('/completed', methods=['GET', 'POST'])\n@login_required\ndef view_completed():\n if request.method == 'POST':\n hiddenValue = request.form.get('to_delete',None)\n archive.delete_item(hiddenValue)\n buttons = [ 'X' ]\n tableValues = archive.find_items()\n tableValues = sorted(tableValues, key=getList)\n return render_template('lists.html', \n items=tableValues,\n name='completed',\n buttons=buttons)\n\n@app.route('/backlog', methods=['GET', 'POST'])\n@login_required\ndef view_backlog():\n\n if request.method == 'POST':\n hiddenValue = request.form.get('to_delete',None)\n hiddenList = request.form.get('list_name', None)\n if request.form.get('Completed', None) is not None:\n archive.insert_item(hiddenList, hiddenValue)\n elif request.form.get('Backlog', None) is not None:\n backlog.insert_item(hiddenList, hiddenValue)\n elif request.form.get('CheckList', None) is not None:\n lists.insert_item(hiddenList, hiddenValue)\n \n backlog.delete_item(hiddenValue)\n buttons = [ 'CheckList', 'Completed', 'X' ]\n tableValues = backlog.find_items()\n tableValues = sorted(tableValues, key=getList)\n return render_template('lists.html', \n items=tableValues, \n name='backlog', \n buttons=buttons)\n\n@app.route('/namedlist', methods=['GET', 'POST'])\ndef namedlist():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n if not 'name' in request.args:\n return 'Missing name option, please add ie ?name='\n listName = request.args.get('name')\n namedlist = ListAccessObject.ListAccessObject(db, listName)\n if request.method == 'POST':\n variable = request.form.get('list',None)\n variable2 = request.form.get('item',None)\n hiddenValue = request.form.get('to_delete',None)\n hiddenList = request.form.get('list_name', None)\n if hiddenValue is None:\n namedlist.insert_item(variable, variable2)\n \n else:\n if request.form.get('Completed', None) is not None:\n archive.insert_item(hiddenList, hiddenValue)\n elif request.form.get('Backlog', None) is not None:\n backlog.insert_item(hiddenList, hiddenValue)\n namedlist.delete_item(hiddenValue)\n namedlist.delete_item(None)\n tableValues = namedlist.find_items()\n tableValues = sorted(tableValues, key=getList)\n tableValues = add_time(tableValues)\n \n return render_template('checklist.html', name=listName, session=session, items=tableValues)\n \n tableValues = namedlist.find_items()\n tableValues = sorted(tableValues, key=getList)\n \n tableValues = add_time(tableValues)\n\n return render_template('checklist.html', name=listName, session=session, items=tableValues)\n\n@app.route('/checklist', methods=['GET', 'POST'])\ndef add_item():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n if request.method == 'POST':\n variable = request.form.get('list',None)\n variable2 = request.form.get('item',None)\n hiddenValue = request.form.get('to_delete',None)\n hiddenList = request.form.get('list_name', None)\n if hiddenValue is None:\n lists.insert_item(variable, variable2)\n \n else:\n if request.form.get('Completed', None) is not None:\n archive.insert_item(hiddenList, hiddenValue)\n elif request.form.get('Backlog', None) is not None:\n backlog.insert_item(hiddenList, hiddenValue)\n lists.delete_item(hiddenValue)\n lists.delete_item(None)\n tableValues = lists.find_items()\n tableValues = sorted(tableValues, key=getList)\n tableValues = add_time(tableValues)\n \n return render_template('checklist.html', name='CheckList', session=session, items=tableValues)\n \n tableValues = lists.find_items()\n tableValues = sorted(tableValues, key=getList)\n \n tableValues = add_time(tableValues)\n\n return render_template('checklist.html', name='CheckList', session=session, items=tableValues)\n\n@app.route('/addlist', methods=['GET', 'POST'])\ndef add_list():\n if not current_user.is_authenticated:\n return redirect(url_for('login'))\n if request.method == 'POST':\n variable = request.form.get('list',None)\n hiddenValue = request.form.get('to_delete',None)\n hiddenList = request.form.get('list_name', None)\n if hiddenValue is None:\n list_names.insert_listname(variable)\n \n else:\n # delete the list from the database\n list_names.delete_listname(hiddenList)\n tableValues = list_names.find_lists()\n tableValues = sorted(tableValues, key=getList)\n \n return render_template('addlist.html', session=session, items=tableValues)\n tableValues = list_names.find_lists()\n tableValues = sorted(tableValues, key=getList)\n\n return render_template('addlist.html', session=session, items=tableValues)\n\ndef add_time(list_input):\n list_output = []\n for entry in list_input:\n entry['datetime'] = str(entry['timestamp'].astimezone(timezone('US/Pacific')).strftime(\"%m-%d-%Y %I:%M%p\"))\n list_output.append(entry)\n return list_output\n\n#@app.route('/')\n#def index():\n# return 'this is the index'\n\n@app.route('/moreo')\ndef hello_world4():\n return 'more4'\n\n@app.route('/lists')\ndef mylist():\n toOutput = lists.find_items()\n valueToOutput = \"Hello Lists

\"\n for value in toOutput:\n valueToOutput += str(value['item'])\n valueToOutput += '
'\n return valueToOutput\n\n@app.route('/more')\ndef hello_world3():\n return '''\n\n \n Hello\n \n
\n \n World\n \n\n'''\n\n@app.route(\"/logout\", methods=[\"GET\"])\n@login_required\ndef logout():\n \"\"\"Logout the current user.\"\"\"\n #user = current_user\n #user.authenticated = False\n #db.session.add(user)\n #db.session.commit()\n logout_user()\n return render_template(\"logout.html\")\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm(csrf_enabled=False)\n# Work in progress\n# user_id = request.cookies.get('SessionProdTools')\n# if user_id:\n# user = \n if request.method == 'POST' and form.validate_on_submit():\n user = app.config['USERS_COLLECTION'].find_one({\"_id\": form.username.data})\n #user = MongoClient()['blog'].users.find_one({\"_id\": form.username.data})\n\n if user and User.validate_login(user['password'], form.password.data):\n user_obj = User(user['_id'])\n login_user(user_obj, remember=True)\n flash(\"Logged in successfully!\", category='success')\n return redirect(request.args.get(\"next\") or url_for(\"add_item\"))\n flash(\"Wrong username or password!\", category='error')\n return render_template('login.html', title='login', form=form)\n\n\nif __name__ == '__main__':\n #app.secret_key = 'super secret key'\n #app.config['SESSION_TYPE'] = 'filesystem'\n\n #session.init_app(app)\n app.run(debug=True)\n\n\n@app.route('/additem', methods=['GET', 'POST'])\ndef add_form():\n formHtml = '''\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n List: \n \n \n
\n Item: \n \n \n
\n
\n '''\n cssHtml = '''\n \n \n MyLists\n \n \n \n '''\n\n \n if request.method == 'POST':\n variable = request.form.get('list',None)\n variable2 = request.form.get('item',None)\n hiddenValue = request.form.get('to_delete',None)\n if hiddenValue is None:\n lists.insert_item(variable, variable2)\n #print \"hello\"\n \n else:\n lists.delete_item(hiddenValue)\n lists.delete_item(None)\n #print \"nothing here\"\n output = cssHtml + \\\n formHtml \n return output\n\n output = cssHtml + \\\n formHtml\n return output\n\n","sub_path":"Lists/myLists.py","file_name":"myLists.py","file_ext":"py","file_size_in_byte":12717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"418430970","text":"import imp\nimport sys\nsys.path.append('/home/pi/bms/oud/')\n#\n#au = imp.load_source('module.name', '/home/pi/spi_auguste/spi_can/can_lib_auguste.py')\n\nimport can_lib_auguste as au\nimp.reload(au)\n\nau.master_init()\nau.getCurrent()\nmean, std, pop = au.currentCal(100)\nimport RPi.GPIO as GPIO\n\nau.getVoltageMaster()\nau.init_meting(slaves = [0x03, 0x02, 0x01])\n\nau.getVoltageSlaves([0x03, 0x02, 0x01])\n\nprint(\"DONE\")\nau.getVoltage()\nau.getRXBnSIDL()\nint(au.getRXBnSIDL(), 2) & 0x80\nau.getCANINTE()\n\nau.getVoltage()\nprint(au.getVoltage())\n\nau.setEFLG(0x00)\nau.setTXBnCTRL(0x00)\nau.getTEC()\nau.getREC()\nau.getEFLG()\n\n#-------------CALIBRATION DAY CMON--------------------\n\nimport time\nimport numpy as np\n\nnum_loops = 10\nres_list = []\nc_time = 0\n\nfor x in range(num_loops):\n c_time = time.time()\n au.setCANINTF(0x00)\n au.setTXBnCTRL(0x0B)\n volt = au.getVoltage()\n res_list.append(volt)\n while (time.time() < c_time + 1):\n pass\n\nwith open(\"dead_cell_performance\", \"w\") as text_file:\n for x in range(num_loops):\n text_file.write(\"%.8f\\n\" %(res_list[x]))\nprint(\"DONE\")\n\n\n\n#--------------RUN TEST CAN PERFORMANCE------------------------\n\nimport time\nimport numpy as np\n\nnum_loops = 10\nTEClist = []\nREClist = []\nvoltage = []\nfor x in range(num_loops):\n au.setCANINTF(0x00)\n au.setTXBnCTRL(0x08)\n while (int(au.getCANINTF()) & 0x01 != 1):\n time.sleep(0.1)\n print(\"waiting...\")\n TEClist.append(int(au.getTEC(), 2))\n REClist.append(int(au.getREC(), 2))\n voltage.append(au.getVoltage())\nwith open(\"%s, %s, %s.txt\" %(hex(CNF1), hex(CNF2), hex(CNF3)), \"w\") as text_file:\n text_file.write(\"TEC, REC, voltage\\n\")\n for x in range(num_loops):\n text_file.write(\"%d, %d, %.6f\\n\" %(TEClist[x], REClist[x], voltage[x]))\n text_file.write(\"mean: %.4f, %.4f\" %(np.mean(TEClist), np.mean(REClist)))\nprint(\"DONE\")\n\n#----------------------------END------------------------------\n\n\nprint(TEClist)\nprint(REClist)\nprint(voltage)\n\nau.master_exit()\n","sub_path":"python/oud/vimpythontest.py","file_name":"vimpythontest.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221109459","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef U(N,eta,lam,T,n):\n\tk = float(T)/N\n\tz = lam*k\n\tzeta1 = z + np.sqrt(z**2+1)\n\tzeta2 = z - np.sqrt(z**2+1)\n\tc1 = 0.5*eta*(1+(1+z**2)**(-1))\n\tc2 = 0.5*eta*(1-(1+z**2)**(-1))\n\treturn c1*zeta1**n + c2*zeta2**n\n\n# For our problem take N large\nN=1000\neta=1\nlam=-0.5\nT=8\nnn = np.linspace(0,N,N+1)\nun = U(N,eta,lam,T,nn)\ntn = np.linspace(0,T,N+1)\nutrue = lambda t : eta*np.exp(lam*t)\n\nplt.figure(1)\nplt.subplot(2,1,1)\nplt.plot(tn,un,'-bo',label='Computed solution')\nplt.plot(tn,utrue(tn),'k',label='True solution')\nplt.legend()\n\nplt.subplot(2,1,2)\nplt.plot(tn,abs(un-utrue(tn)),label='Absolute error')\nplt.ticklabel_format(style='sci',axis='y',scilimits=(0,5))\nplt.legend()\n\n\nplt.show()\n","sub_path":"spring2015/amath586/hw2/prob4.py","file_name":"prob4.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"52697718","text":"from PIL import Image\r\nimport os\r\nfrom multiprocessing import Pool\r\n\r\ndef func(t):\r\n root = '/media/zzx/DATA1/frames/'\r\n videos = os.listdir(os.path.join(root, t))\r\n for video in videos:\r\n frames = os.listdir(os.path.join(root, t, video))\r\n for frame in frames:\r\n if (frame.endswith('.bmp')):\r\n try:\r\n im = Image.open(os.path.join(root, t, video, frame))\r\n except Exception as e:\r\n print('Damaged file:', os.path.join(root,t,video,frame))\r\n print('Finished: '+ t)\r\n\r\nif __name__ == '__main__':\r\n \r\n root = '/media/zzx/DATA1/frames/'\r\n types = os.listdir(root)\r\n p = Pool(12)\r\n p.map(func, types)\r\n p.close()\r\n p.join()\r\n","sub_path":"fyp/d_checking.py","file_name":"d_checking.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163206964","text":"# Copyright 2018 Google LLC\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# [START gae_python37_app]\nimport numpy\nfrom flask import Flask\nfrom flask_json import FlaskJSON, as_json\nfrom pandas import read_csv\nimport math\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nimport json\nimport pickle\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n\n# convert an array of values into a dataset matrix\ndef create_dataset(dataset, look_back=1):\n dataX, dataY = [], []\n for i in range(len(dataset)-look_back-1):\n a = dataset[i:(i+look_back), 0]\n dataX.append(a)\n dataY.append(dataset[i + look_back, 0])\n return numpy.array(dataX), numpy.array(dataY)\n\n# fix random seed for reproducibility\nnumpy.random.seed(7)\n\n# load the dataset\ndataframe = read_csv(\"EURUSD.csv\", usecols=[1], engine='python')\ndataset = dataframe.values\ndataset = dataset.astype('float32')\n\n# normalize the dataset\nscaler = MinMaxScaler(feature_range=(0, 1))\ndataset = scaler.fit_transform(dataset)\n\n# split into train and test sets\ntrain_size = int(len(dataset) * 0.67)\ntest_size = len(dataset) - train_size\ntrain, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\n\n# reshape into X=t and Y=t+1\nlook_back = 1\ntrainX, trainY = create_dataset(train, look_back)\ntestX, testY = create_dataset(test, look_back)\n\n# reshape input to be [samples, time steps, features]\ntrainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\ntestX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n\n# create and fit the LSTM network\nmodel3 = Sequential()\nmodel3.add(LSTM(4, input_shape=(1,look_back), return_sequences=True))\nmodel3.add(LSTM(2, input_shape=(1,look_back)))\nmodel3.add(Dense(1))\nmodel3.compile(loss='mean_squared_error', optimizer='adam')\nmodel3.fit(trainX, trainY, epochs=10, batch_size=1, verbose=2)\n\n# make predictions\ntrainPredict = model3.predict(trainX)\ntestPredict = model3.predict(testX)\n\n# invert predictions\ntrainPredict = scaler.inverse_transform(trainPredict)\ntrainY = scaler.inverse_transform([trainY])\ntestPredict = scaler.inverse_transform(testPredict)\ntestY = scaler.inverse_transform([testY])\n\n# calculate root mean squared error\ntrainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))\nprint('Train Score: %.2f RMSE' % (trainScore))\ntestScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))\nprint('Test Score: %.2f RMSE' % (testScore))\n\n# shift train predictions for plotting\ntrainPredictPlot = numpy.empty_like(dataset)\ntrainPredictPlot[:, :] = numpy.nan\ntrainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict\n\n# shift test predictions for plotting\ntestPredictPlot = numpy.empty_like(dataset)\ntestPredictPlot[:, :] = numpy.nan\ntestPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict\n\n # shift test predictions for plotting\ntestPredictPlot = numpy.empty_like(dataset)\ntestPredictPlot[:, :] = numpy.nan\ntestPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict\n\n# Next day\nlast = 1.17\nx_input = numpy.array(last)\nmaxDataset = max(dataset)\nminDataset = min(dataset)\nx_input = x_input / (maxDataset - minDataset)\nx_input = x_input.reshape((1, 1, 1))\nnextPred = model3.predict(x_input)\nnextPred = scaler.inverse_transform(nextPred)\n\n\npercentagePM = (nextPred[0][0] - last) / last\n\npred = str(nextPred[0][0])\n# some JSON:\nprediction = {\n \"eur/usd\": pred\n}\n\njson_string = json.dumps(prediction)\n\n# parse x:\ny = json.loads(json_string)\n# If `entrypoint` is not defined in app.yaml, App Engine will look for an app\n# called `app` in `main.py`.\napp = Flask(__name__)\njson = FlaskJSON(app)\n\n@app.route('/')\n@as_json\ndef hello():\n \"\"\"Return a friendly HTTP greeting.\"\"\"\n return prediction\n\nif __name__ == '__main__':\n # This is used when running locally only. When deploying to Google App\n # Engine, a webserver process such as Gunicorn will serve the app. This\n # can be configured by adding an `entrypoint` to app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)\n\n# [END gae_python37_app]\n","sub_path":"appengine/standard_python37/hello_world/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"649242058","text":"from selenium import webdriver\nfrom time import sleep\n\n\ndef find(source_location,destination,sourceLocation,targetLocation,shortestRouteTitle,shortestRouteDistance):\n driver = webdriver.Chrome('/Users/dinaelhusseiny/Downloads/chromedriver')\n sleep(2)\n driver.get(\"https://www.google.com/maps/dir/\" + source_location)\n minDistance = 10000\n minIndex = 0\n routeTitleCol = []\n sleep(10)\n targetLocationInput = driver.find_element_by_xpath(\n '/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[2]/div[2]/div/div/input')\n targetLocationInput.send_keys(destination)\n sleep(10)\n searchButton = driver.find_element_by_xpath(\n '/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[2]/div[2]/button[1]')\n searchButton.click()\n sleep(10)\n routes = driver.find_elements_by_class_name('section-directions-trip-title')\n routes_distances = driver.find_elements_by_class_name('section-directions-trip-distance')\n print(len(routes))\n print(len(routes_distances))\n for routeTitle in routes:\n routeTitleText = routeTitle.text\n if routeTitleText != '':\n routeTitleCol.append(routeTitleText)\n count = 0\n for routeDistance in routes_distances:\n routeDistanceText = routeDistance.text.replace('km', '')\n routeDistanceInKM = routeDistanceText.replace('كم', '')\n minRouteDistance = float(routeDistanceInKM.strip())\n if minRouteDistance < minDistance:\n minDistance = minRouteDistance\n minIndex = count\n count = count + 1\n sourceLocation.append(source_location)\n targetLocation.append(destination)\n shortestRouteDistance.append(minDistance)\n shortestRouteTitle.append(routeTitleCol[minIndex])\n dict = {}\n dict[\"sourceLocation\"] = sourceLocation\n dict[\"targetLocation\"] = targetLocation\n dict[\"shortestRouteDistance\"] = shortestRouteDistance\n dict[\"shortestRouteTitle\"] = shortestRouteTitle\n driver.quit()\n return dict\n\n","sub_path":"ShortestDistance/PathCalculator.py","file_name":"PathCalculator.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"531606685","text":"from opengever.document.archival_file import ArchivalFileConverter\nfrom plone import api\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom time import sleep\nfrom zope.annotation import IAnnotations\nfrom zope.component import adapter\nfrom zope.component import getUtility\nfrom zope.interface import implementer\nfrom zope.interface import Interface\nfrom zope.intid.interfaces import IIntIds\nfrom zope.publisher.interfaces.browser import IBrowserRequest\nimport logging\n\n# Conditional import to not cause issues on og.core versions where\n# opengever.nightlyjobs.interfaces doesn't exist yet\ntry:\n from opengever.nightlyjobs.interfaces import INightlyJobProvider\nexcept ImportError:\n # Older og.core version - provide a dummy interface\n class INightlyJobProvider(Interface):\n pass\n\ntry:\n from opengever.nightlyjobs.provider import NightlyJobProviderBase\nexcept:\n # older og.core version, base class does not exist yet. In that case\n # it is not needed either, as the base class provides the newly required\n # methods (maybe_commit)\n NightlyJobProviderBase = object\n\nMISSING_ARCHIVAL_FILE_KEY = 'DOCS_WITH_MISSING_ARCHIVAL_FILE'\nMAX_CONVERSION_REQUESTS_PER_NIGHT = 10000\n\n# Track total number of conversion requests sent per nightly run\nsent_conversion_requests = 0\n\n\n@implementer(INightlyJobProvider)\n@adapter(IPloneSiteRoot, IBrowserRequest, logging.Logger)\nclass NightlyArchivalFileConversion(NightlyJobProviderBase):\n \"\"\"Trigger conversion of archival files for documents that have been put\n in the persistent queue (by the `ArchivalFileChecker`).\n \"\"\"\n\n def __init__(self, context, request, logger):\n self.context = context\n self.request = request\n self.logger = logger\n\n self.catalog = api.portal.get_tool('portal_catalog')\n self.intids = getUtility(IIntIds)\n\n def get_queue(self):\n \"\"\"The queue is a BTree in the site root's annotations.\n\n It is a mapping of dossier IntIds to lists of document IntIds (the\n documents being the ones that are missing their archival file).\n\n It is grouped by dossier because this allows us to process the queue\n in more reasonably sized chunks, instead of every single document\n being considered a \"job\" (which would lead to a commit every time).\n\n So the unit of work for this job is a dossier, and during the\n execution of that job it will trigger the conversion for that dossiers\n missing archival files.\n \"\"\"\n ann = IAnnotations(self.context)\n queue = ann.get(MISSING_ARCHIVAL_FILE_KEY, {})\n return queue\n\n def __iter__(self):\n \"\"\"Iterate over jobs, which as described above, are dossier IntIds.\n \"\"\"\n queue = self.get_queue()\n # Avoid list size changing during iteration\n jobs = list(queue.keys())\n\n for job in jobs:\n self.logger.info('sent_conversion_requests: %r' % sent_conversion_requests)\n if sent_conversion_requests >= MAX_CONVERSION_REQUESTS_PER_NIGHT:\n self.logger.warn(\n \"Reached MAX_CONVERSION_REQUESTS_PER_NIGHT \"\n \"(%r) limit, stopping work for tonight.\" %\n MAX_CONVERSION_REQUESTS_PER_NIGHT)\n raise StopIteration\n\n yield job\n\n def __len__(self):\n return len(self.get_queue())\n\n def trigger_conversion(self, doc):\n self.logger.info(\"Triggering conversion for %r\" % doc)\n ArchivalFileConverter(doc).trigger_conversion()\n\n def run_job(self, job, interrupt_if_necessary):\n \"\"\"Run the job for the dossier identified by the IntId `job`.\n\n This means getting all the document IntIds that this dossier IntIds\n points to in the queue, and triggering conversion for those documents.\n \"\"\"\n global sent_conversion_requests\n\n dossier_intid = job\n dossier = self.intids.getObject(dossier_intid)\n self.logger.info(\"Triggering conversion jobs for documents in %r\" % dossier)\n\n queue = self.get_queue()\n for doc_intid in queue[dossier_intid]:\n interrupt_if_necessary()\n doc = self.intids.getObject(doc_intid)\n self.trigger_conversion(doc)\n sent_conversion_requests += 1\n\n # Stagger conversion requests at least a little bit, in order to\n # avoid overloading Bumblebee. This likely will have to be tuned.\n sleep(1)\n\n queue.pop(dossier_intid)\n","sub_path":"opengever/maintenance/nightly_archival_file_job.py","file_name":"nightly_archival_file_job.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"229058748","text":"from aiohttp.web import json_response\nfrom tempfile import NamedTemporaryFile as TemporaryFile\n\nfrom airhead.library import TrackNotFoundError\nfrom airhead.playlist import DuplicateTrackError\nfrom airhead.transcoder import IllegalCodecError\n\n\nasync def store_file(reader):\n f = await reader.next()\n\n with TemporaryFile(delete=False) as fp:\n while True:\n chunk = await f.read_chunk()\n\n if not chunk:\n break\n\n fp.write(chunk)\n\n return fp.name\n\n\nasync def info(request):\n conf = request.app['config']\n return json_response({\n 'name': conf.get('INFO', 'Name'),\n 'greet_message': conf.get('INFO', 'GreetMessage'),\n 'stream_url': \"http://{}:{}/{}\"\n .format(conf.get('ICECAST', 'Host'),\n conf.get('ICECAST', 'Port'),\n conf.get('ICECAST', 'Mount'))\n })\n\n\nasync def library_query(request):\n # If the request URL has not the '?q=' parameter\n # catch the error and set q to None in order to call\n # Library.query(q=None) and get all the stored tracks.\n q = request.query.get('q', None)\n\n tracks = request.app['library'].query(q)\n return json_response({'tracks': tracks}, status=200)\n\n\nasync def library_get(request):\n uuid = request.match_info['uuid']\n\n try:\n track = request.app['library'].get_track(uuid)\n\n except TrackNotFoundError as e:\n return json_response({\n 'err': 'uuid_not_valid',\n 'msg': 'No track found with such UUID.'\n }, status=400)\n\n else:\n return json_response(track, status=200)\n\n\nasync def library_add(request):\n reader = await request.multipart()\n path = await store_file(reader)\n\n try:\n track = request.app['library'].add(path, delete=True)\n\n except FileNotFoundError:\n return json_response({\n 'err': 'upload_failed',\n 'msg': 'This is strange.'\n }, status=500)\n\n except IllegalCodecError as e:\n return json_response({\n 'err': 'illegal_codec',\n 'msg': 'This kind of file is not supported.'\n }, status=400)\n\n else:\n return json_response({'track': track}, status=200)\n\n\nasync def playlist_query(request):\n return json_response({\n 'current': request.app['playlist'].current_track,\n 'next': request.app['playlist'].next_tracks\n }, status=200)\n\n\nasync def playlist_add(request):\n uuid = request.match_info['uuid']\n\n try:\n request.app['playlist'].put(uuid)\n\n except TrackNotFoundError:\n return json_response({\n 'err': 'track_not_found',\n 'msg': 'No track found with such UUID.'\n }, status=400)\n\n except DuplicateTrackError:\n return json_response({\n 'err': 'duplicate',\n 'msg': 'The track is already present in the playlist.'\n }, status=400)\n\n else:\n return json_response({}, status=200)\n\n\nasync def playlist_remove(request):\n uuid = request.match_info['uuid']\n\n playlist = request.app['playlist']\n broadcaster = request.app['broadcaster']\n\n try:\n if uuid == playlist.current_track['uuid']:\n broadcaster.skip()\n else:\n playlist.remove(uuid)\n\n except TrackNotFoundError:\n return json_response({\n 'err': 'track_not_found',\n 'msg': 'No track found with such UUID.'\n }, status=400)\n\n else:\n return json_response({}, status=200)\n","sub_path":"airhead/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"292464751","text":"\nfrom klampt import WorldModel\nfrom klampt import vis\nfrom klampt import Simulator\nfrom src.utils import project_constants\n\nclass PhysicsSim:\n\n def __init__(self, robot, sim_world):\n self.robot = robot\n self.sim_world = sim_world\n self.suspend = False\n self.sim = Simulator(sim_world)\n self.sim.setGravity([0, 0, 0])\n\n self.controller = self.sim.controller(0)\n self.controller.setRate(project_constants.CONTROLLER_DT)\n\n def suspend(self):\n self.suspend = True\n\n def run(self):\n\n while not self.suspend:\n self.sim.updateWorld()\n self.sim.simulate(project_constants.CONTROLLER_DT)","sub_path":"src/physics_simulator/phsyics_simulator.py","file_name":"phsyics_simulator.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"409901020","text":"#!/usr/bin/env python\n\n# Copyright (c) 2021\n# All rights reserved.\n#\n# Permission to use, copy, modify, and distribute this software for any purpose\n# with or without fee is hereby granted, provided that the above copyright\n# notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n# PERFORMANCE OF THIS SOFTWARE.\n#\n# Jim Mainprice on Tue October 10 2021\n\nimport demos_common_imports\n\n# pybewego\nfrom pybewego import HarmonicPotentialDiffusion2D, ExtentBox\nfrom pybewego.workspace_geometry import create_bewego_workspace\n\n# pyrieef\nfrom pyrieef.geometry.workspace import *\nfrom pyrieef.rendering.workspace_planar import WorkspaceDrawer\n\n# external\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport itertools\n\nROWS = 1\nCOLS = 3\n\nNB_POINTS = 101\nTIME_STEP = 1e-5\nMAX_ITERATIONS = 2000\nN = 30\n\n# matplotlib.rcParams['pdf.fonttype'] = 42\n# matplotlib.rcParams['ps.fonttype'] = 42\n\ncircles = []\ncircles.append(Circle(origin=[.1, .0], radius=0.1))\ncircles.append(Circle(origin=[.1, .25], radius=0.05))\ncircles.append(Circle(origin=[.2, .25], radius=0.05))\ncircles.append(Circle(origin=[.0, .25], radius=0.05))\n\nworkspace = Workspace()\nworkspace.obstacles = circles\n\ngrid = workspace.pixel_map(NB_POINTS)\nX, Y = workspace.box.meshgrid(N)\nU, V = np.zeros(X.shape), np.zeros(Y.shape)\n\ndiffusion = HarmonicPotentialDiffusion2D(\n create_bewego_workspace(workspace),\n ExtentBox(workspace.box.extent_data()),\n grid.resolution,\n TIME_STEP,\n MAX_ITERATIONS)\ndiffusion.set_verbose(True)\ndiffusion.set_occupied_temperature(10)\n\n# interpolate=\"bicubic\",\nrenderer = WorkspaceDrawer(workspace, scale=.5, rows=ROWS, cols=COLS)\n\nfor i, iterations in enumerate(np.linspace(1, 4000, ROWS*COLS)):\n diffusion.set_max_iterations(int(iterations))\n phi = diffusion.diffuse([0, 0])\n renderer.set_drawing_axis(i)\n renderer.draw_ws_obstacles()\n renderer.background_matrix_eval = False\n renderer.draw_ws_background(\n phi, interpolate=\"bicubic\", color_style=plt.cm.tab20c)\n\n for i, j in itertools.product(range(X.shape[0]), range(X.shape[1])):\n g = phi.gradient([X[i, j], Y[i, j]])\n g /= np.linalg.norm(g)\n U[i, j] = g[0]\n V[i, j] = g[1]\n renderer._ax.quiver(X, Y, U, V, units='width')\n\nrenderer.show()\n","sub_path":"examples/geodesic_harmonic_potential.py","file_name":"geodesic_harmonic_potential.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"238814965","text":"##################################\n#encoding=utf8 #\n#version =py27, py33 #\n#author =sanhe #\n#date =2014-10-29 #\n# #\n# (\\ (\\ #\n# ( -.-)o I am a Rabbit! #\n# o_(\")(\") #\n# #\n##################################\n\nfrom __future__ import print_function\n\ndef tryit(howmany, func, *argv, **kwarg):\n \"\"\"这个函数使用了一个重要的技巧将原函数的参数原封不动的封装成tryit这个函数的参数了\n 用户只要跟使用func原函数一样使用tryit函数就好了,只不过在前面多了两个howmany和func的参数\n howmany 是尝试次数\n func 是你所要尝试的函数\n *argv, **kwarg 是func中的参数\n \n func函数一定要有如下特点:\n 如果能正常运行,说明一定其中没有异常。\n 如果有异常,一定要抛出异常,打断函数\n \"\"\"\n flag = 1\n while flag <= howmany:\n try:\n return func(*argv, **kwarg)\n except Exception as e:\n current_exception = e\n flag += 1\n raise current_exception","sub_path":"HSH/Misc/logicflow.py","file_name":"logicflow.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5511326","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module defines functions for parsing `STAR files`_.\n\n.. _STAR files: https://www2.mrc-lmb.cam.ac.uk/relion/index.php/Conventions_%26_File_formats#The_STAR_format\n\"\"\"\n\n\nfrom collections import defaultdict\nimport os.path\n\nimport numpy as np\n\nfrom prody.utilities import openFile\nfrom prody import LOGGER, SETTINGS\n\n__all__ = ['parseSTAR','writeSTAR']\n\ndef parseSTAR(filename):\n \"\"\"Returns a dictionary containing data\n parsed from a Relion STAR file.\n\n :arg filename: a filename\n The .star extension can be omitted.\n \"\"\"\n\n if not os.path.isfile(filename) and not os.path.isfile(filename + '.star'):\n raise IOError('There is no file with that name.')\n\n starfile = open(filename, 'r')\n lines = starfile.readlines()\n starfile.close()\n\n finalDictionary = {}\n currentLoop = -1\n fieldCounter = 0\n dataItemsCounter = 0\n lineNumber = 0\n for line in lines:\n if line.startswith('data_'):\n currentDataBlock = line[5:].strip()\n finalDictionary[currentDataBlock] = {}\n currentLoop = -1\n inLoop = False\n startingBlock = True\n fieldCounter = 0\n\n elif line.startswith('loop_'):\n currentLoop += 1\n inLoop = True\n finalDictionary[currentDataBlock][currentLoop] = {}\n finalDictionary[currentDataBlock][currentLoop]['fields'] = {}\n finalDictionary[currentDataBlock][currentLoop]['data'] = {}\n fieldCounter = 0\n\n elif line.startswith('_'):\n currentField = line.strip().split()[0]\n\n if inLoop:\n finalDictionary[currentDataBlock][currentLoop]['fields'][fieldCounter + 1] = currentField\n dataItemsCounter = 0\n else:\n if startingBlock:\n finalDictionary[currentDataBlock]['fields'] = {}\n finalDictionary[currentDataBlock]['data'] = {}\n startingBlock = False\n dataItemsCounter = 0\n finalDictionary[currentDataBlock]['fields'][fieldCounter + 1] = currentField\n finalDictionary[currentDataBlock]['data'][dataItemsCounter] = {}\n finalDictionary[currentDataBlock]['data'][dataItemsCounter][currentField] = line.strip().split()[1]\n dataItemsCounter += 1\n\n fieldCounter += 1\n\n elif line.strip() == '':\n pass\n\n elif len(line.split()) == fieldCounter:\n finalDictionary[currentDataBlock][currentLoop]['data'][dataItemsCounter] = {}\n fieldCounter = 0\n for fieldEntry in line.strip().split():\n currentField = finalDictionary[currentDataBlock][currentLoop]['fields'][fieldCounter + 1]\n finalDictionary[currentDataBlock][currentLoop]['data'][dataItemsCounter][currentField] = fieldEntry\n fieldCounter += 1\n dataItemsCounter += 1\n\n elif line.startswith('#'):\n pass\n\n else:\n raise TypeError('This file does not conform to the STAR file format.' \\\n 'There is a problem with line {0}:\\n {1}'.format(lineNumber, line))\n\n lineNumber += 1\n\n return finalDictionary\n\ndef writeSTAR(filename, starDict):\n \"\"\"Writes a STAR file from a dictionary containing data\n such as that parsed from a Relion STAR file.\n\n :arg filename: a filename\n The .star extension can be omitted.\n\n :arg dictionary: a dictionary in STAR format\n This should have nested entries starting with data blocks then loops/tables then\n field names and finally data.\n \"\"\"\n\n star = open(filename,'w')\n\n for dataBlockKey in starDict:\n star.write('\\ndata_' + dataBlockKey + '\\n')\n for loopNumber in starDict[dataBlockKey]:\n star.write('\\nloop_\\n')\n for fieldNumber in starDict[dataBlockKey][loopNumber]['fields']:\n star.write('_' + starDict[dataBlockKey][loopNumber]['fields'][fieldNumber] + '\\n')\n for dataItemNumber in starDict[dataBlockKey][loopNumber]['data']:\n for fieldNumber in starDict[dataBlockKey][loopNumber]['fields']:\n currentField = starDict[dataBlockKey][loopNumber]['fields'][fieldNumber]\n star.write(starDict[dataBlockKey][loopNumber]['data'][dataItemNumber][currentField] + ' ')\n star.write('\\n')\n\n star.close()\n return\n\n","sub_path":"Docker_Image/dock_multi_original/ProDy/prody/proteins/starfile.py","file_name":"starfile.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"605926629","text":"import sys\n\nfile = open(\"../inputs/day6input.txt\", \"r\")\ninput = file.read().split(\"\\n\")\ngrid =[[0 for i in range(0,1000)] for j in range(0,1000)]\ndirections = []\n\n\ndef performDirection(scrub, turnOn, startCoords, endCoords):\n\tglobal grid\n\tstartRow = startCoords[0]\n\tstartCol = startCoords[1]\n\tendRow = endCoords[0]\n\tendCol = endCoords[1]\n\tprint(startRow, startCol, endRow, endCol)\n\tfor y in range(startRow, endRow+1):\n\t\tfor x in range(startCol, endCol+1):\n\t\t\tif scrub == False:\n\t\t\t\t\tgrid[y][x]+=2\n\t\t\telse:\n\t\t\t\tif turnOn:\n\t\t\t\t\tgrid[y][x]+=1\n\t\t\t\telif grid[y][x] > 0:\n\t\t\t\t\tgrid[y][x]-=1\n\n\nfor i in input:\n\ttokens = i.split(\" \")\n\tstartCoords = []\n\tendCoords = []\n\t#turn on 774,539 through 778,786\n\t#toggle 341,780 through 861,813\n\tscrub = False\n\tturnOn = False\n\tprint(tokens)\n\tif tokens[0] == \"turn\":\n\t\tscrub = True\n\t\tif tokens[1] == \"on\":\n\t\t\tturnOn = True\n\t\tstartCoordsStrings = tokens[2].split(\",\")\n\t\tfor string in startCoordsStrings:\n\t\t\tstartCoords.append(int(string))\n\t\tendCoordsStrings = tokens[4].split(\",\")\n\t\tfor string in endCoordsStrings:\n\t\t\tendCoords.append(int(string))\n\telse:\n\t\tstartCoordsStrings = tokens[1].split(\",\")\n\t\tfor string in startCoordsStrings:\n\t\t\tstartCoords.append(int(string))\n\t\tendCoordsStrings = tokens[3].split(\",\")\n\t\tfor string in endCoordsStrings:\n\t\t\tendCoords.append(int(string))\n\n\tperformDirection(scrub, turnOn, startCoords, endCoords)\n\n\ncount = 0\nfor row in grid:\n\tfor light in row:\n\t\tcount += light\n\nprint(count)\n\n\n\n\n\n\n","sub_path":"2015/day6/day6p2.py","file_name":"day6p2.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"538973055","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n#from functions import ReverseLayerF\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 16, 2, 1)\n self.conv2 = nn.Conv2d(16, 32, 2, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(18432, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = nn.ReLU()(x)\n x = nn.MaxPool2d(2, 1)(x)\n x = self.dropout1(x)\n x = self.conv2(x)\n x = nn.ReLU()(x)\n x = nn.MaxPool2d(2, 1)(x)\n x = self.dropout2(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = nn.ReLU()(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\nclass Mclr_CrossEntropy(nn.Module):\n def __init__(self, input_dim = 784, output_dim = 10):\n super(Mclr_CrossEntropy, self).__init__()\n self.linear = torch.nn.Linear(input_dim, output_dim)\n\n def forward(self, x):\n x = torch.flatten(x, 1)\n outputs = self.linear(x)\n return outputs\n\nclass DNN(nn.Module):\n def __init__(self, input_dim = 784, mid_dim = 100, output_dim = 10):\n super(DNN, self).__init__()\n # define network layers\n self.fc1 = nn.Linear(input_dim, mid_dim)\n self.fc2 = nn.Linear(mid_dim, output_dim)\n self.weight_keys = [['fc1.weight', 'fc1.bias'],\n ['fc2.weight', 'fc2.bias']\n ]\n def forward(self, x):\n # define forward pass\n x = torch.flatten(x, 1)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n x = F.log_softmax(x, dim=1)\n return x\n\nclass DNN2(nn.Module):\n def __init__(self, input_dim = 784, mid_dim_in = 100, mid_dim_out= 100, output_dim = 10):\n super(DNN2, self).__init__()\n # define network layers\n self.fc1 = nn.Linear(input_dim, mid_dim_in)\n self.fc2 = nn.Linear(mid_dim_in, mid_dim_out)\n self.fc3 = nn.Linear(mid_dim_out, output_dim)\n \n def forward(self, x):\n # define forward pass\n x = torch.flatten(x, 1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n x = F.log_softmax(x, dim=1)\n return x\n#################################\n##### Neural Network model #####\n#################################\n\n\n\nclass MLP(nn.Module):\n def __init__(self, dim_in, dim_hidden, dim_out):\n super(MLP, self).__init__()\n self.layer_input = nn.Linear(dim_in, 512)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout()\n self.layer_hidden1 = nn.Linear(512, 256)\n self.layer_hidden2 = nn.Linear(256, 256)\n self.layer_hidden3 = nn.Linear(256, 128)\n self.layer_out = nn.Linear(128, dim_out)\n self.softmax = nn.Softmax(dim=1)\n \n self.weight_keys = [['layer_input.weight', 'layer_input.bias'],\n ['layer_hidden1.weight', 'layer_hidden1.bias'],\n ['layer_hidden2.weight', 'layer_hidden2.bias'],\n ['layer_hidden3.weight', 'layer_hidden3.bias'],\n ['layer_out.weight', 'layer_out.bias']\n ]\n\n def forward(self, x):\n x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])\n x = self.layer_input(x)\n x = self.relu(x)\n\n x = self.layer_hidden1(x)\n x = self.relu(x)\n\n x = self.layer_hidden2(x)\n x = self.relu(x)\n\n x = self.layer_hidden3(x)\n x = self.relu(x)\n\n x = self.layer_out(x)\n return self.softmax(x)\n\n\nclass CNNMnist(nn.Module):\n def __init__(self, args):\n super(CNNMnist, self).__init__()\n self.conv1 = nn.Conv2d(args.num_channels, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, args.num_classes)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, x.shape[1]*x.shape[2]*x.shape[3])\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n\nclass CNNCifar(nn.Module):\n def __init__(self, num_classes):\n super(CNNCifar, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 100)\n self.fc3 = nn.Linear(100, num_classes)\n\n self.weight_keys = [['fc1.weight', 'fc1.bias'],\n ['fc2.weight', 'fc2.bias'],\n ['fc3.weight', 'fc3.bias'],\n ['conv2.weight', 'conv2.bias'],\n ['conv1.weight', 'conv1.bias'],\n ]\n \n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return F.log_softmax(x, dim=1)\n\nclass Mclr_Logistic(nn.Module):\n def __init__(self, input_dim = 784, output_dim = 10):\n super(Mclr_Logistic, self).__init__()\n self.fc1 = nn.Linear(input_dim, output_dim)\n self.weight_keys = [['fc1.weight', 'fc1.bias']]\n\n def forward(self, x):\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n output = F.log_softmax(x, dim=1)\n return output\n\nclass LogisticModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.linear = nn.Linear(2352, 10)\n \n def forward(self, xb):\n xb = xb.reshape(-1, 2352)\n out = self.linear(xb)\n output = F.log_softmax(out, dim=1)\n return output\n\nclass CnnModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.network = nn.Sequential(\n nn.Conv2d(3, 16, kernel_size=3, padding=1),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n \n nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),\n #nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),\n #nn.BatchNorm2d(256),\n nn.ReLU(),\n \n nn.Conv2d(256, 16, kernel_size=1, stride=1, padding=0),\n nn.MaxPool2d(2, 2), # output: 16 x 14 x 14\n nn.Dropout(p=0.25),\n\n nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=0),\n #nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=0),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=0),\n #nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=0),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n\n nn.Conv2d(256, 10, kernel_size=1, stride=1, padding=1),\n #nn.MaxPool2d(2, 2), # output: 10 x 3 x 3\n\n nn.AvgPool2d(kernel_size=6), \n nn.Flatten(),\n nn.Softmax())\n \n def forward(self, xb):\n return self.network(xb)\n\nclass FeedFwdModel(nn.Module):\n \"\"\"Feedfoward neural network with 1 hidden layer\"\"\"\n def __init__(self, in_size, out_size):\n super().__init__()\n # hidden layer\n self.linear1 = nn.Linear(in_size, 16)\n # hidden layer 2\n self.linear2 = nn.Linear(16, 32)\n # output layer\n self.linear3 = nn.Linear(32, out_size)\n \n def forward(self, xb):\n # Flatten the image tensors\n out = xb.view(xb.size(0), -1)\n # Get intermediate outputs using hidden layer 1\n out = self.linear1(out)\n # Apply activation function\n out = F.relu(out)\n # Get intermediate outputs using hidden layer 2\n out = self.linear2(out)\n # Apply activation function\n out = F.relu(out)\n # Get predictions using output layer\n out = self.linear3(out)\n return F.log_softmax(out, dim=1)\n \nCONV_SIZE = 16 \nclass DANCNNModel(nn.Module):\n \n def __init__(self):\n super(DANCNNModel, self).__init__()\n #self.feature = nn.Sequential()\n self.f_conv1 = nn.Conv2d(3, CONV_SIZE, kernel_size=5)\n self.f_bn1 = nn.BatchNorm2d(CONV_SIZE)\n self.f_pool1 = nn.MaxPool2d(2)\n self.f_relu1 = nn.ReLU(True)\n self.f_conv2 = nn.Conv2d(CONV_SIZE, 50, kernel_size=5)\n self.f_bn2 = nn.BatchNorm2d(50)\n self.f_drop1 = nn.Dropout2d()\n self.f_pool2 = nn.MaxPool2d(2)\n self.f_relu2 = nn.ReLU(True)\n\n #classifier\n self.c_fc1 = nn.Linear(50 * 4 * 4, 100)\n self.c_bn1 = nn.BatchNorm1d(100)\n self.c_relu1 = nn.ReLU(True)\n self.c_drop1 = nn.Dropout()\n self.c_fc2 = nn.Linear(100, 100)\n self.c_bn2 = nn.BatchNorm1d(100)\n self.c_relu2 = nn.ReLU(True)\n self.c_fc3 = nn.Linear(100, 10)\n self.c_softmax = nn.LogSoftmax(dim=1)\n\n '''\n self.domain_classifier = nn.Sequential()\n self.domain_classifier.add_module('d_fc1', nn.Linear(50 * 4 * 4, 100))\n self.domain_classifier.add_module('d_bn1', nn.BatchNorm1d(100))\n self.domain_classifier.add_module('d_relu1', nn.ReLU(True))\n self.domain_classifier.add_module('d_fc2', nn.Linear(100, 2))\n self.domain_classifier.add_module('d_softmax', nn.LogSoftmax(dim=1))\n '''\n \n #xdef forward(self, input_data, alpha):\n def forward(self, input_data):\n #input_data = input_data.expand(input_data.data.shape[0], 3, 28, 28)\n out = self.f_conv1(input_data)\n out = self.f_bn1(out)\n out = self.f_pool1(out)\n out = self.f_relu1(out)\n out = self.f_conv2(out)\n out = self.f_bn2(out)\n out = self.f_drop1(out)\n out = self.f_pool2(out)\n feature = self.f_relu2(out)\n\n feature = feature.view(-1, 50 * 4 * 4)\n out = self.c_fc1(feature)\n out = self.c_bn1(out)\n out = self.c_relu1(out)\n out = self.c_drop1(out)\n out = self.c_fc2(out)\n out = self.c_bn2(out)\n out = self.c_relu2(out)\n out = self.c_fc3(out)\n class_output = self.c_softmax(out)\n\n return class_output#, domain_output","sub_path":"FLAlgorithms/trainmodel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"104655683","text":"from keras.applications.vgg16 import VGG16\n\nK.clear_session()\nmodel = VGG16(weights='imagenet')\n\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\nimport numpy as np\n\nimg_path = '/Users/fchollet/Downloads/creative_commons_elephant.jpg'\n\nimg = image.load_img(img_path, target_size=(224, 224)) # 大小为224*224的Python图像库图像\n\nx = image.img_to_array(img) # 形状为(224, 224, 3)的float32格式Numpy数组\n\nx = np.expand_dims(x, axis=0) # 添加一个维度,将数组转化为(1, 224, 224, 3)的形状批量\n\nx = preprocess_input(x) #按批量进行预处理(按通道颜色进行标准化)\n\npreds = model.predict(x)\nprint('Predicted:', decode_predictions(preds, top=3)[0])\n\nnp.argmax(preds[0])\n\nafrican_elephant_output = model.output[:, 386] # 预测向量中的非洲象元素\n\nlast_conv_layer = model.get_layer('block5_conv3') # block5_conv3层的输出特征图,它是VGG16的最后一个卷积层\n\ngrads = K.gradients(african_elephant_output, last_conv_layer.output)[0] # 非洲象类别相对于block5_conv3输出特征图的梯度\n\npooled_grads = K.mean(grads, axis=(0, 1, 2)) # 形状是(512, )的向量,每个元素是特定特征图通道的梯度平均大小\n\niterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]]) # 这个函数允许我们获取刚刚定义量的值:对于给定样本图像,pooled_grads和block5_conv3层的输出特征图\n\npooled_grads_value, conv_layer_output_value = iterate([x]) # 给我们两个大象样本图像,这两个量都是Numpy数组\n\nfor i in range(512):\n conv_layer_output_value[:, :, i] *= pooled_grads_value[i] # 将特征图数组的每个通道乘以这个通道对大象类别重要程度\n\nheatmap = np.mean(conv_layer_output_value, axis=-1) # 得到的特征图的逐通道的平均值即为类激活的热力图\n\nheatmap = np.maximum(heatmap, 0)\nheatmap /= np.max(heatmap)\nplt.matshow(heatmap)\nplt.show()\n\nimport cv2\n\nimg = cv2.imread(img_path) # 用cv2加载原始图像\n\nheatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0])) # 将热力图的大小调整为与原始图像相同\n\n\nheatmap = np.uint8(255 * heatmap) # 将热力图转换为RGB格式\n\nheatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) # 将热力图应用于原始图像\n\nsuperimposed_img = heatmap * 0.4 + img # 这里的0.4是热力图强度因子\n\ncv2.imwrite('/Users/fchollet/Downloads/elephant_cam.jpg', superimposed_img) # 将图像保存到硬盘","sub_path":"keras_heatmap.py","file_name":"keras_heatmap.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"295463504","text":"from urllib.parse import urlparse\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.cache import cache\nfrom django import forms\n# from django.db.models import Model\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .models import Url\n\n\nclass UrlForm(forms.ModelForm):\n class Meta:\n model = Url\n fields = ('url',)\n\n\ndef create_user(request):\n form = UserCreationForm(request.POST or None)\n if form.is_bound and form.is_valid():\n form.save()\n return redirect('index')\n return render(request, 'register.html', {'form': form})\n\n\ndef redirect_key(request, key):\n try:\n url = Url.objects.get(key=key)\n url.fanc_redirect_count()\n url = url.url\n except Url.DoesNotExist:\n url = reverse('index')\n return redirect(to=url)\n\t\n@login_required\ndef index(request):\n ctx = {}\n form = UrlForm(request.POST or None)\n if form.is_bound and form.is_valid():\n obj = form.save()\n ctx['key'] = obj.key\n form = UrlForm()\n ctx['form'] = form\n return render(request, 'index.html', ctx)\n","sub_path":"HW_6/hw_6_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"550378107","text":"''' Javascript Object Notation'''\r\n'''grabbing json data from public API'''\r\n#https://docs.python.org/3/library/json.html\r\n#https://www.youtube.com/watch?v=9N6a-VLBa2I&t=6s\r\n#É um formato de dados muito comum para armazenar algumas informações.\r\n\r\nimport json\r\n#makes request to the web API\r\nfrom urllib.request import urlopen\r\n\r\n#urlopen is a function\r\nwith urlopen(\"https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json\") as response:\r\n source = response.read()\r\n\r\n#data = json.loads(source)\r\n\r\n#print(json.dumps(data, indent=2))\r\n\r\n#confirms if there is really 188 resources in the list\r\n#print(len(data['list']['resources']))\r\n\r\n#let's make a convertion of dollars\r\nusd_rates = dict()\r\n\r\nfor item in data['list']['resources']:\r\n #print(item)\r\n name = item['resource']['fields']['name']\r\n price = item['resource']['fields']['price']\r\n usd_rates[name] = price\r\n#print(usd_rates['USD/EUR'])\r\n\r\n#converting 50 dollars to euros\r\nprint(50 * float(usd_rates['USD/EUR']))","sub_path":"j_lesson3.py","file_name":"j_lesson3.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459027126","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 15 11:39:20 2021\r\n\r\n@author: KKA\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef empty_function(*args):\r\n pass\r\n\r\ndef trackbaring(image, image_color, function_type):\r\n \"\"\"\r\n INPUT:\r\n image - 3D array of (grayscale) image in BGR scale (OpenCV default scale)\r\n function_type - string of what function type should be applied.\r\n [\"Canny\", \"threshold\", \"otsu\", \"HoughLinesP\", \"Laplacian\", \"adaptiveThreshold\",\r\n \"medianBlur\", \"GaussianBlur\", \"erode\", \"dilate\", \"MORPH_OPEN\", \"MORPH_COLSE\"]\r\n defaults - list of default values for trackbars, by default sets all 0\r\n \r\n OUTPUT:\r\n result - given method result\r\n showing - result showing in window w/o text (mostly drawn over original BGR image)\r\n trackbars - list of chosen parameter values (last one mainly for debugging)\r\n \"\"\"\r\n defaults=[0,0,0,0,0]\r\n win_name = \"Trackbars\"\r\n\r\n cv2.namedWindow(win_name)\r\n cv2.resizeWindow(win_name, 500,100)\r\n \r\n # Show window on top left corner on primary screen\r\n cv2.moveWindow(win_name, 10,50)\r\n \r\n # The one inserted in methods, when needed converted to grayscale\r\n img = image.copy()\r\n \r\n ##################### INITIALISING TRACKBARS ###############################\r\n # Depending on function_type the trackbars are created\r\n if function_type == \"Canny\":\r\n trackbar_names = [\"canny_th1\", \"canny_th2\"]#, \"kernel_size\", \"dilate_iter\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 255, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, 255, 255, empty_function)\r\n # cv2.createTrackbar(trackbar_names[2], win_name, 2, 7, empty_function)\r\n # cv2.createTrackbar(trackbar_names[3], win_name, 1, 5, empty_function)\r\n \r\n elif function_type == \"threshold\":\r\n trackbar_names = [\"threshold\", \"th_type\"]\r\n # Some thershold types seem to be doing nothing...\r\n threshold_type = [cv2.THRESH_BINARY,\r\n cv2.THRESH_BINARY_INV,\r\n cv2.THRESH_TRUNC,\r\n cv2.THRESH_TOZERO,\r\n cv2.THRESH_TOZERO_INV]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 255, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], len(threshold_type)-1, empty_function)\r\n \r\n elif function_type == \"thresh_binary\":\r\n # Needs grayscale as input\r\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n trackbar_names = [\"threshold\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, 50, 255, empty_function)\r\n \r\n elif function_type == \"HoughLinesP\":\r\n # Needs grayscale as input\r\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n trackbar_names = [\"min len\", \"max gap\"]\r\n #cv2.createTrackbar(trackbar_names[0], win_name, 1, 99, empty_function)\r\n #cv2.createTrackbar(trackbar_names[1], win_name, 0, 89, empty_function)\r\n #cv2.createTrackbar(trackbar_names[2], win_name, 100, 255, empty_function)\r\n cv2.createTrackbar(trackbar_names[0], win_name, 40, 500, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, 5, 250, empty_function)\r\n \r\n elif function_type == \"Laplacian\":\r\n # Needs grayscale as input\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n trackbar_names = [\"kernel_r\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 15, empty_function)\r\n \r\n elif function_type == \"adaptiveThreshold\":\r\n # Needs grayscale as input\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n trackbar_names = [\"adp_meth\", \"th_type\", \"kernel_r\", \"mean_C\"]\r\n adaptive_type = [cv2.ADAPTIVE_THRESH_MEAN_C,\r\n cv2.ADAPTIVE_THRESH_GAUSSIAN_C]\r\n threshold_type = [cv2.THRESH_BINARY,\r\n cv2.THRESH_BINARY_INV]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], len(adaptive_type)-1, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], len(threshold_type)-1, empty_function)\r\n cv2.createTrackbar(trackbar_names[2], win_name, defaults[2], 500, empty_function)\r\n cv2.createTrackbar(trackbar_names[3], win_name, defaults[3], 50, empty_function)\r\n \r\n elif function_type == \"medianBlur\":\r\n trackbar_names = [\"kernel_r\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 49, empty_function)\r\n \r\n elif function_type == \"GaussianBlur\":\r\n trackbar_names = [\"kernel_r\", \"std_x\", \"std_y\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 49, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], 100, empty_function)\r\n cv2.createTrackbar(trackbar_names[2], win_name, defaults[2], 100, empty_function)\r\n \r\n elif function_type == \"erode\":\r\n trackbar_names = [\"kernel\", \"iterations\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 100, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], 10, empty_function)\r\n \r\n elif function_type == \"dilate\":\r\n trackbar_names = [\"kernel\", \"iterations\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 100, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], 10, empty_function)\r\n \r\n elif function_type == \"MORPH_OPEN\":\r\n trackbar_names = [\"kernel\", \"iterations\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 100, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], 10, empty_function)\r\n \r\n elif function_type == \"MORPH_CLOSE\":\r\n trackbar_names = [\"kernel\", \"iterations\"]\r\n cv2.createTrackbar(trackbar_names[0], win_name, defaults[0], 100, empty_function)\r\n cv2.createTrackbar(trackbar_names[1], win_name, defaults[1], 10, empty_function)\r\n \r\n else:\r\n cv2.destroyAllWindows()\r\n raise Exception(\"Wrong function_type. Library doesn't include '{}'\".format(function_type))\r\n \r\n ############################# LIVE TRACKBARS ###############################\r\n # Making trackbars work\r\n while True:\r\n # Get trackbar values\r\n trackbars = []\r\n for i in range(len(trackbar_names)):\r\n trackbars.append(cv2.getTrackbarPos(trackbar_names[i], win_name))\r\n \r\n # So the initial image won't get overdrawn, this is always BGR!\r\n \r\n #showing = image_color.copy()\r\n \r\n ####################### FUNCTION CALCULATION ###########################\r\n \"\"\"\r\n Let OpenCV do it's magic with methods and draw it over the original input image\r\n Depends on function_type\r\n \r\n result - should not be changed between original method output and return\r\n img - is the one that should always be inserted to OpenCV method, it has correct colorscale\r\n showing - is first a copy of original BGR and used only to draw onto\r\n when copying result into showing, it should be guaranteed that it's BGR\r\n \"\"\"\r\n if function_type == \"Canny\":\r\n result = cv2.Canny(img, trackbars[0], trackbars[1])\r\n # kernel = np.ones((trackbars[2], trackbars[2]), np.uint8)\r\n # result = cv2.dilate(result,kernel,iterations = trackbars[3])\r\n showing=result.copy()\r\n #showing[result==255, 2] = result[result==255] # Draws red, BGR!\r\n \r\n elif function_type == \"threshold\":\r\n result = cv2.threshold(img, trackbars[0], 255, threshold_type[trackbars[1]])[1]\r\n #showing[result==255] = result[result==255] # Draws white, all channels\r\n showing=result.copy()\r\n \r\n elif function_type == \"thresh_binary\":\r\n print(str(trackbars[0]))\r\n ret, result = cv2.threshold(img, trackbars[0], 255, cv2.THRESH_BINARY)\r\n #showing[result==255, 2] = result[result==255] # Draws red, BGR\r\n \r\n showing=result.copy()\r\n \r\n \r\n elif function_type == \"HoughLinesP\":\r\n showing = image_color.copy()\r\n result = cv2.HoughLinesP(img,\r\n 1,\r\n np.pi/180,\r\n 100,\r\n None,\r\n minLineLength=trackbars[0],\r\n maxLineGap=trackbars[1])\r\n if result is not None:\r\n for i in range(0, len(result)):\r\n l = result[i][0]\r\n cv2.line(showing, (l[0], l[1]), (l[2], l[3]), (255,0,0), 2, cv2.LINE_AA)\r\n \r\n elif function_type == \"Laplacian\":\r\n result = cv2.Laplacian(img, ksize=2*trackbars[0]+1, ddepth=cv2.CV_FEATURE_PARAMS_HOG)\r\n # Set all channels constant where result>0\r\n # Setting them all zero is not good because on dark areas\r\n # it cannot then be seen which areas are also altered\r\n # Color transition is better (low cyan -> bright red-ish)\r\n showing[result>0, :] = 64\r\n showing[result>0, 2] = result[result>0] # Draws red, keeps other const, BGR\r\n \r\n elif function_type == \"adaptiveThreshold\":\r\n result = cv2.adaptiveThreshold(img, 255,\r\n adaptive_type[trackbars[0]],\r\n threshold_type[trackbars[1]],\r\n trackbars[2]*2+3,\r\n trackbars[3])\r\n showing[result==255, 2] = result[result==255] # Draws red, BGR\r\n \r\n elif function_type == \"medianBlur\":\r\n result = cv2.medianBlur(img, trackbars[0]*2+3) # outputs BGR here\r\n showing = result\r\n # saves memory compared to np.copy() and SHOULDN'T make a diference\r\n elif function_type == \"GaussianBlur\":\r\n result = cv2.GaussianBlur(img,\r\n (trackbars[0]*2+1, trackbars[0]*2+1),\r\n sigmaX = trackbars[1]*0.1,\r\n sigmaY = trackbars[2]*0.1) # outputs BGR here\r\n showing = result\r\n \r\n elif function_type == \"erode\":\r\n kernel = np.ones((trackbars[0]+1, trackbars[0]+1),np.uint8)\r\n result = cv2.erode(img,\r\n kernel,\r\n iterations=trackbars[1]) # outputs BGR here\r\n showing = result\r\n \r\n elif function_type == \"dilate\":\r\n kernel = np.ones((trackbars[0]+1, trackbars[0]+1),np.uint8)\r\n result = cv2.dilate(img,\r\n kernel,\r\n iterations=trackbars[1]) # outputs BGR here\r\n showing = result\r\n \r\n elif function_type == \"MORPH_OPEN\":\r\n kernel = np.ones((trackbars[0]+1, trackbars[0]+1),np.uint8)\r\n result = cv2.morphologyEx(img, cv2.MORPH_OPEN,\r\n kernel, iterations=trackbars[1]) # outputs BGR here\r\n showing = result\r\n \r\n elif function_type == \"MORPH_CLOSE\":\r\n kernel = np.ones((trackbars[0]+1, trackbars[0]+1),np.uint8)\r\n result = cv2.morphologyEx(img, cv2.MORPH_CLOSE,\r\n kernel, iterations=trackbars[1]) # outputs BGR here\r\n showing = result\r\n \r\n showing_temp = showing.copy()\r\n showing_temp = cv2.rectangle(showing_temp,(3,25),(250,5),color=(0,0,0),thickness=-1)\r\n cv2.putText(showing_temp, # image\r\n \"Press 'esc' to save and close!\", # text\r\n (5, 20), # location\r\n cv2.FONT_HERSHEY_SIMPLEX, # font\r\n 0.5, # size\r\n (255, 0, 0), # BGR\r\n 1, # thickness\r\n cv2.LINE_AA) # ?\r\n cv2.imshow(win_name, showing_temp)\r\n \r\n # Code exits \"while true loop\" by pressing letter 'c'\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == 27:#:\r\n break\r\n \r\n # Wrap it up\r\n cv2.destroyAllWindows()\r\n \r\n return result, showing, trackbars\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"trackbars_library.py","file_name":"trackbars_library.py","file_ext":"py","file_size_in_byte":12647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"551843268","text":"import numpy as np\r\nimport pandas as pd\r\nimport requests\r\nimport math\r\nfrom scipy.stats import percentileofscore as score\r\nimport xlsxwriter\r\nfrom config import IEX_Cloud_Api_Token\r\nfrom config import IEX_SANDBOX_API_TOKEN\r\nfrom config import Alpha_Vantage_Api_key\r\nimport json\r\nfrom alpha_vantage.timeseries import TimeSeries\r\nimport time\r\nfrom multiprocessing import Process\r\nfrom threading import Thread\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.pyplot import figure\r\nimport talib\r\nimport seaborn as sns\r\nimport statsmodels.api as sm\r\nfrom sklearn.tree import DecisionTreeRegressor\r\n\r\ndf_columns = [\r\n 'Ticker',\r\n 'Daily Closes',\r\n 'Daily Volumes',\r\n\r\n]\r\n\r\n\r\ndf = pd.DataFrame(columns=df_columns)\r\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\r\n\r\n\r\n\r\n\r\n\r\nsymbol = 'AAPL'\r\n\r\napi_url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={symbol}&outputsize=full&apikey={Alpha_Vantage_Api_key}'\r\ndata_daily = requests.get(api_url).json()\r\n#print(data_daily)\r\n\r\n\"\"\"def getList(diction):\r\n return diction.keys()\"\"\"\r\n\r\ndiction = list(data_daily['Time Series (Daily)'].keys())\r\nreal_dates = diction[::-1]\r\n#print(real_dates)\r\n#print(diction)\r\n#print(getList(diction))\r\n\r\n\r\ndef get_closes_daily():\r\n for data in data_daily['Time Series (Daily)']:\r\n c_data = data_daily['Time Series (Daily)'][data]['5. adjusted close']\r\n close_data.append(c_data)\r\n\r\n\r\nclose_data = []\r\nget_closes_daily()\r\n\r\ndef get_volumes_daily():\r\n for data in data_daily['Time Series (Daily)']:\r\n v_data = data_daily['Time Series (Daily)'][data]['6. volume']\r\n volume_data.append(v_data)\r\n\r\n\r\nvolume_data = []\r\nget_volumes_daily()\r\n\r\n\r\nclose_data.reverse()\r\nvolume_data.reverse()\r\n\r\nclose_data = close_data[-5000:]\r\nvolume_data = volume_data[-5000:]\r\nreal_dates = real_dates[-5000:]\r\n\r\n\r\nfor (close1D, volume1D) in zip(close_data, volume_data):\r\n df = df.append(\r\n pd.Series(\r\n [\r\n symbol,\r\n close1D,\r\n volume1D,\r\n\r\n ],\r\n index=df_columns),\r\n ignore_index=True\r\n )\r\n\r\n\r\ndf[['Daily Closes']] = df[['Daily Closes']].apply(pd.to_numeric)\r\ndf[['Daily Volumes']] = df[['Daily Volumes']].apply(pd.to_numeric)\r\ndf['Dates'] = real_dates\r\n\r\n\"\"\"df['Dates'] = df['Dates'][::-1]\"\"\"\r\ndf = df[[\r\n 'Dates',\r\n 'Ticker',\r\n 'Daily Closes',\r\n 'Daily Volumes']]\r\ndf['Dates'] = pd.to_datetime(df['Dates'], infer_datetime_format=True)\r\ndf.set_index('Dates', inplace=True, drop=True)\r\n\r\n#print(df)\r\n\r\n\r\n\"\"\"df['Daily Closes'].plot(label='SPY', legend=True)\r\n#plt.show()\r\nplt.clf()\r\n\r\nvol = df['Daily Volumes']\r\nvol.plot.hist(bins=25)\r\nplt.clf()\r\n#plt.show()\r\ndf['Daily Closes'].pct_change().plot.hist(bins=15)\r\n#df['Daily Closes PCT CHG'].plot.hist(bins=50)\r\nplt.xlabel('adjusted close 1-day percent change')\r\n#plt.show()\r\nplt.clf()\"\"\"\r\n\r\n\r\ndf['10D Daily Closes Future'] = df['Daily Closes'].shift(-10)\r\ndf['10D Daily Closes Future PCT CHG'] = df['10D Daily Closes Future'].pct_change(10)\r\ndf['10D Daily Closes PCT CHG'] = df['Daily Closes'].pct_change(10)\r\n#corr = df[['10D Daily Closes PCT CHG', '10D Daily Closes Future PCT CHG']].corr()\r\n#print(corr)\r\n\r\n\"\"\"plt.scatter(df['10D Daily Closes PCT CHG'], df['10D Daily Closes Future PCT CHG'])\r\n#plt.show()\r\nplt.clf()\"\"\"\r\n\r\n#Features are the parameters that are used in order to predict the 'targets'\r\n\"\"\"features = df[['Daily Closes', 'Daily Volumes']]\r\ntargets = df['Daily Closes Future']\r\nprint(type(features))\r\nprint(type(targets))\"\"\"\r\n\r\ndf['Daily Closes'] = df[['Daily Closes']].squeeze()\r\n#print(type(df['Daily Closes']))\r\n\r\n\r\n\r\nfeature_names = ['10D Daily Closes PCT CHG']\r\n\r\nfor n in [14, 30, 50,200]:\r\n df['ma' + str(n)] = talib.SMA(df['Daily Closes'].values, timeperiod=n) / df['Daily Closes']\r\n df['rsi' + str(n)] = talib.RSI(df['Daily Closes'].values, timeperiod=n)\r\n feature_names = feature_names + ['ma' + str(n), 'rsi' + str(n)]\r\n\r\n#print(feature_names)\r\n\r\ndf = df.dropna()\r\nfeatures = df[feature_names]\r\ntargets = df['10D Daily Closes Future PCT CHG']\r\nfeature_and_target_cols = ['10D Daily Closes Future PCT CHG'] + feature_names\r\nfeat_targ_df = df[feature_and_target_cols]\r\ncorr = feat_targ_df.corr()\r\nprint(corr)\r\nsns.heatmap(corr, annot= True, annot_kws = {\"size\": 14})\r\nplt.yticks(rotation=0, size = 14); plt.xticks(rotation=90, size = 14) # fix ticklabel directions and size\r\nplt.tight_layout() # fits plot area to the plot, \"tightly\"\r\n#plt.show()\r\nplt.clf()\r\n\r\nlinear_features = sm.add_constant(features)\r\ntrain_size = int(0.85 * features.shape[0])\r\ntrain_features = linear_features[:train_size]\r\ntrain_targets = targets[:train_size]\r\ntest_features = linear_features[train_size:]\r\ntest_targets = targets[train_size:]\r\n#print(linear_features.shape, train_features.shape, test_features.shape)\r\n\r\nmodel = sm.OLS(train_targets, train_features)\r\nresults = model.fit() # fit the model\r\n#print(results.summary())\r\n\r\n# examine pvalues\r\n# Features with p <= 0.05 are typically considered significantly different from 0\r\n#print(results.pvalues)\r\n\r\n# Make predictions from our model for train and test sets\r\ntrain_predictions = results.predict(train_features)\r\ntest_predictions = results.predict(test_features)\r\n\r\n# Scatter the predictions vs the targets with 20% opacity\r\n\"\"\"plt.scatter(train_predictions, train_targets, alpha=0.2, color='b', label='train')\r\nplt.scatter(test_predictions, test_targets, alpha=0.2, color='r', label='test')\"\"\"\r\n\r\n# Plot the perfect prediction line\r\nxmin, xmax = plt.xlim()\r\nplt.plot(np.arange(xmin, xmax, 0.01), np.arange(xmin, xmax, 0.01), c='k')\r\n\r\n# Set the axis labels and show the plot\r\nplt.xlabel('predictions')\r\nplt.ylabel('actual')\r\nplt.legend() # show the legend\r\n#plt.show()\r\nplt.clf()\r\n\r\n# Create 2 new volume features, 1-day % change and 5-day SMA of the % change\r\nnew_features = ['Adj_Volume_1d_change', 'Adj_Volume_1d_change_SMA']\r\nfeature_names.extend(new_features)\r\ndf['Adj_Volume_1d_change'] = df['Daily Volumes'].pct_change()\r\ndf['Adj_Volume_1d_change_SMA'] = talib.SMA(df['Adj_Volume_1d_change'].values,\r\n timeperiod=5)\r\n\r\n# Plot histogram of volume % change data\r\ndf[new_features].plot(kind='hist', sharex=False, bins=50)\r\n#plt.show()\r\n\r\n#df.index = pd.to_datetime(df.index)\r\n\r\n\r\n\r\n#print(df['Dates'])\r\n\r\n# Use pandas' get_dummies function to get dummies for day of the week\r\ndays_of_week = pd.get_dummies(df.index.dayofweek,\r\n prefix='weekday',\r\n drop_first=True)\r\n\r\n# Set the index as the original dataframe index for merging\r\ndays_of_week.index = df.index\r\n\r\n# Join the dataframe with the days of week dataframe\r\ndf = pd.concat([df, days_of_week], axis=1)\r\n\r\n# Add days of week to feature names\r\nfeature_names.extend(['weekday_' + str(i) for i in range(1, 5)])\r\ndf.dropna(inplace=True) # drop missing values in-place\r\n#print(df.head())\r\n\r\n# Add the weekday labels to the new_features list\r\nnew_features.extend(['weekday_' + str(i) for i in range(1, 5)])\r\n#print(feature_names)\r\n\r\n# Plot the correlations between the new features and the targets\r\nsns.heatmap(df[new_features + ['10D Daily Closes Future PCT CHG']].corr(), annot=True)\r\nplt.yticks(rotation=0) # ensure y-axis ticklabels are horizontal\r\nplt.xticks(rotation=90) # ensure x-axis ticklabels are vertical\r\nplt.tight_layout()\r\n#plt.show()\r\nplt.clf()\r\n\r\n\r\n\r\n # Create a decision tree regression model with default arguments\r\ndecision_tree = DecisionTreeRegressor()\r\n\r\n# Fit the model to the training features and targets\r\ndecision_tree.fit(train_features, train_targets)\r\n\r\n# Check the score on train and test\r\n#print(decision_tree.score(train_features, train_targets))\r\n#print(decision_tree.score(test_features, test_targets))\r\n\r\n\r\n# Loop through a few different max depths and check the performance\r\nfor d in [3, 5, 10]:\r\n # Create the tree and fit it\r\n decision_tree = DecisionTreeRegressor(max_depth=d)\r\n decision_tree.fit(train_features, train_targets)\r\n\r\n # Print out the scores on train and test\r\n #print('max_depth=', str(d))\r\n #print(decision_tree.score(train_features, train_targets))\r\n #print(decision_tree.score(test_features, test_targets), '\\n')\r\n\r\n\r\n\r\n# Use the best max_depth of 3 from last exercise to fit a decision tree\r\ndecision_tree = DecisionTreeRegressor(max_depth=3)\r\ndecision_tree.fit(train_features, train_targets)\r\n\r\n# Predict values for train and test\r\ntrain_predictions = decision_tree.predict(train_features)\r\ntest_predictions = decision_tree.predict(test_features)\r\n\r\n# Scatter the predictions vs actual values\r\nplt.scatter(train_predictions, train_targets, label='train')\r\nplt.scatter(test_predictions, test_targets, label='test')\r\n#plt.show()\r\nplt.clf()\r\n\r\n\r\n\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\n# Create the random forest model and fit to the training data\r\nrfr = RandomForestRegressor(n_estimators=200)\r\nrfr.fit(train_features, train_targets)\r\n\r\n# Look at the R^2 scores on train and test\r\n#print(rfr.score(train_features, train_targets))\r\n#print(rfr.score(test_features, test_targets))\r\n\r\n\r\nfrom sklearn.model_selection import ParameterGrid\r\n\r\n# Create a dictionary of hyperparameters to search\r\ngrid = {'n_estimators': [200], 'max_depth': [3], 'max_features': [4, 8], 'random_state': [42]}\r\ntest_scores = []\r\n\r\n# Loop through the parameter grid, set the hyperparameters, and save the scores\r\nfor g in ParameterGrid(grid):\r\n rfr.set_params(**g) # ** is \"unpacking\" the dictionary\r\n rfr.fit(train_features, train_targets)\r\n test_scores.append(rfr.score(test_features, test_targets))\r\n\r\n# Find best hyperparameters from the test score and print\r\nbest_idx = np.argmax(test_scores)\r\n#print(test_scores[best_idx], ParameterGrid(grid)[best_idx])\r\n\r\n\r\n\r\n# Use the best hyperparameters from before to fit a random forest model\r\nrfr = RandomForestRegressor(n_estimators=200, max_depth=3, max_features=4, random_state=42)\r\nrfr.fit(train_features, train_targets)\r\n\r\n# Make predictions with our model\r\ntrain_predictions = rfr.predict(train_features)\r\ntest_predictions = rfr.predict(test_features)\r\n\r\n# Create a scatter plot with train and test actual vs predictions\r\nplt.scatter(train_targets, train_predictions, label='train')\r\nplt.scatter(test_targets, test_predictions, label='test')\r\nplt.legend()\r\n#plt.show()\r\nplt.clf()\r\n\r\n# Get feature importances from our random forest model\r\nimportances = rfr.feature_importances_\r\n#print(importances)\r\n\r\n# Get the index of importances from greatest importance to least\r\nsorted_index = np.argsort(importances)[::-1]\r\nx = range(len(importances))\r\n\r\n# Create tick labels\r\nlabels = np.array(feature_names)[sorted_index]\r\nplt.bar(x, importances[sorted_index], tick_label=labels)\r\n\r\n# Rotate tick labels to vertical\r\nplt.xticks(rotation=90)\r\n#plt.show()\r\nplt.clf()\r\n\r\n\r\nfrom sklearn.ensemble import GradientBoostingRegressor\r\n\r\n# Create GB model -- hyperparameters have already been searched for you\r\ngbr = GradientBoostingRegressor(max_features=4,\r\n learning_rate=0.01,\r\n n_estimators=200,\r\n subsample=0.6,\r\n random_state=42)\r\ngbr.fit(train_features, train_targets)\r\n\r\n#print(gbr.score(train_features, train_targets))\r\n#print(gbr.score(test_features, test_targets))\r\n\r\n\r\n# Extract feature importances from the fitted gradient boosting model\r\nfeature_importances = gbr.feature_importances_\r\n\r\n# Get the indices of the largest to smallest feature importances\r\nsorted_index = np.argsort(feature_importances)[::-1]\r\nx = range(10)\r\n\"\"\"print(sorted_index)\r\nprint(x)\"\"\"\r\n# Create tick labels\r\nlabels = np.array(feature_names)[sorted_index]\r\n\r\nplt.bar(x, feature_importances[sorted_index], tick_label=labels)\r\n\r\n# Set the tick lables to be the feature names, according to the sorted feature_idx\r\nplt.xticks(rotation=90)\r\n#plt.show()\r\nplt.clf()\r\n\r\nfrom sklearn.preprocessing import scale\r\n\r\n# Remove unimportant features (weekdays)\r\ntrain_features = train_features.iloc[:, :-4]\r\ntest_features = test_features.iloc[:, :-4]\r\n\r\n# Standardize the train and test features\r\nscaled_train_features = scale(train_features)\r\nscaled_test_features = scale(test_features)\r\n\r\n# Plot histograms of the 14-day SMA RSI before and after scaling\r\nf, ax = plt.subplots(nrows=2, ncols=1)\r\ntrain_features.iloc[:, 2].hist(ax=ax[0])\r\nax[1].hist(scaled_train_features[:, 2])\r\n\r\n#plt.show()\r\nplt.clf()\r\nfrom sklearn.neighbors import KNeighborsRegressor\r\n\r\nfor n in range(2, 26):\r\n # Create and fit the KNN model\r\n knn = KNeighborsRegressor(n_neighbors=n)\r\n\r\n # Fit the model to the training data\r\n knn.fit(scaled_train_features, train_targets)\r\n\r\n # Print number of neighbors and the score to find the best value of n\r\n print(\"n_neighbors =\", n)\r\n print('train, test scores')\r\n print(knn.score(scaled_train_features, train_targets))\r\n print(knn.score(scaled_test_features, test_targets))\r\n print() # prints a blank line\r\n\r\n# Create the model with the best-performing n_neighbors of 5\r\nknn = KNeighborsRegressor(25)\r\n\r\n# Fit the model\r\nknn.fit(scaled_train_features, train_targets)\r\n\r\n# Get predictions for train and test sets\r\ntrain_predictions = knn.predict(scaled_train_features)\r\ntest_predictions = knn.predict(scaled_test_features)\r\n\r\n# Plot the actual vs predicted values\r\nplt.scatter(train_predictions, train_targets, label='train')\r\nplt.scatter(test_predictions, test_targets, label='test')\r\nplt.legend()\r\n#plt.show()\r\nplt.clf()\r\n# NEURAL NETS\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\n\r\n# Create the model\r\nmodel_1 = Sequential()\r\nmodel_1.add(Dense(100, input_dim=scaled_train_features.shape[1], activation='relu'))\r\nmodel_1.add(Dense(20, activation='relu'))\r\nmodel_1.add(Dense(1, activation='linear'))\r\n\r\n# Fit the model\r\nmodel_1.compile(optimizer='adam', loss='mse')\r\nhistory = model_1.fit(scaled_train_features, train_targets, epochs=25)\r\n\r\n\r\n# Plot the losses from the fit\r\nplt.plot(history.history['loss'])\r\n\r\n# Use the last loss as the title\r\nplt.title('loss:' + str(round(history.history['loss'][-1], 6)))\r\n#plt.show()\r\nplt.clf()\r\n\r\n\r\nfrom sklearn.metrics import r2_score\r\n\r\n# Calculate R^2 score\r\ntrain_preds = model_1.predict(scaled_train_features)\r\ntest_preds = model_1.predict(scaled_test_features)\r\nprint(r2_score(train_targets, train_preds))\r\nprint(r2_score(test_targets, test_preds))\r\n\r\n# Plot predictions vs actual\r\nplt.scatter(train_preds, train_targets, label='train')\r\nplt.scatter(test_preds, test_targets, label='test')\r\nplt.legend()\r\n#plt.show()\r\nplt.clf()\r\n\r\nimport keras.losses\r\nimport tensorflow as tf\r\n\r\n# Create loss function\r\ndef sign_penalty(y_true, y_pred):\r\n penalty = 100.\r\n loss = tf.where(tf.less(y_true * y_pred, 0), \\\r\n penalty * tf.square(y_true - y_pred), \\\r\n tf.square(y_true - y_pred))\r\n\r\n return tf.reduce_mean(loss, axis=-1)\r\n\r\nkeras.losses.sign_penalty = sign_penalty # enable use of loss with keras\r\nprint(keras.losses.sign_penalty)\r\n\r\n# Create the model\r\nmodel_2 = Sequential()\r\nmodel_2.add(Dense(100, input_dim=scaled_train_features.shape[1], activation='relu'))\r\nmodel_2.add(Dense(20, activation='relu'))\r\nmodel_2.add(Dense(1, activation='linear'))\r\n\r\n# Fit the model with our custom 'sign_penalty' loss function\r\nmodel_2.compile(optimizer='adam', loss='sign_penalty')\r\nhistory = model_2.fit(scaled_train_features, train_targets, epochs=25)\r\nplt.plot(history.history['loss'])\r\nplt.title('loss:' + str(round(history.history['loss'][-1], 6)))\r\n#plt.show()\r\nplt.clf()\r\n# Evaluate R^2 scores\r\ntrain_preds = model_2.predict(scaled_train_features)\r\ntest_preds = model_2.predict(scaled_test_features)\r\nprint(r2_score(train_targets, train_preds))\r\nprint(r2_score(test_targets, test_preds))\r\n\r\n# Scatter the predictions vs actual -- this one is interesting!\r\nplt.scatter(train_preds, train_targets, label='train')\r\nplt.scatter(test_preds, test_targets, label='test') # plot test set\r\n#plt.legend(); plt.show()\r\nplt.clf()\r\n\r\nfrom keras.layers import Dropout\r\n\r\n# Create model with dropout\r\nmodel_3 = Sequential()\r\nmodel_3.add(Dense(100, input_dim=scaled_train_features.shape[1], activation='relu'))\r\nmodel_3.add(Dropout(0.5))\r\nmodel_3.add(Dense(20, activation='relu'))\r\nmodel_3.add(Dense(1, activation='linear'))\r\n\r\n# Fit model with mean squared error loss function\r\nmodel_3.compile(optimizer='adam', loss='mse')\r\nhistory = model_3.fit(scaled_train_features, train_targets, epochs=25)\r\nplt.plot(history.history['loss'])\r\nplt.title('loss:' + str(round(history.history['loss'][-1], 6)))\r\n#plt.show()\r\nplt.clf()\r\n\r\n# Make predictions from the 3 neural net models\r\ntrain_pred1 = model_1.predict(scaled_train_features)\r\ntest_pred1 = model_1.predict(scaled_test_features)\r\n\r\ntrain_pred2 = model_2.predict(scaled_train_features)\r\ntest_pred2 = model_2.predict(scaled_test_features)\r\n\r\ntrain_pred3 = model_3.predict(scaled_train_features)\r\ntest_pred3 = model_3.predict(scaled_test_features)\r\n\r\n# Horizontally stack predictions and take the average across rows\r\ntrain_preds = np.mean(np.hstack((train_pred1, train_pred2, train_pred3)), axis=1)\r\ntest_preds = np.mean(np.hstack((test_pred1, test_pred2, test_pred3)), axis=1)\r\nprint(test_preds[-20:])\r\n\r\nfrom sklearn.metrics import r2_score\r\n\r\n# Evaluate the R^2 scores\r\nprint(r2_score(train_targets, train_preds))\r\nprint(r2_score(test_targets, test_preds))\r\n\r\n# Scatter the predictions vs actual -- this one is interesting!\r\nplt.scatter(train_preds, train_targets, label='train')\r\nplt.scatter(test_preds, test_targets, label='test')\r\nplt.legend()\r\nplt.show()","sub_path":"MLWillsee.py","file_name":"MLWillsee.py","file_ext":"py","file_size_in_byte":17798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376403147","text":"import collections\nimport re\n\n\ndef join_jsons(json_f_1, json_f_2):\n \"\"\"Opens files, reads, removes, them and\n combines it all in one line, and then write\n to a new full json file\n\n :param file1: 'winedata_1.json'\n :param file2: 'winedata_2.json'\n :return: concatinated text from two files\n \"\"\"\n with open(json_f_1, 'r', encoding='utf-8') as f1, \\\n open(json_f_2, 'r', encoding='utf-8') as f2:\n t1, t2 = f1.read().replace(\"]\", \"\"), f2.read().replace(\"[\", \"\")\n concat_text = t1 + \",\" + t2\n\n with open('winedata_full.json', 'w', encoding='utf-8') as full_json_file_wr:\n full_json_file_wr.write(concat_text)\n\n return concat_text\n\n\ndef extraction_data_between_braces(concat_json_file):\n \"\"\"The regex pattern allows us to get a list\n of elements that are between brackets\n\n :param concat_json_file:\n :return: keys, by_elems\n \"\"\"\n json = concat_json_file.replace(\"null\", '\"0\"')\n pattern_1 = r\"\\{(.*?)\\}\"\n rows_between_braces = re.findall(pattern_1, json)\n\n keys = [\n 'points',\n 'title',\n 'description',\n 'taster_name',\n 'taster_twitter_handle',\n 'price',\n 'designation',\n 'variety',\n 'region_1',\n 'region_2',\n 'province',\n 'country',\n 'winery',\n ]\n return keys, rows_between_braces\n\n\ndef get_wine_data(list_keys, datas_btw_braces):\n \"\"\"return a list of dicts data framed by braces\n\n :param keys: different keys in each row\n :param datas_btw_braces: {data1}, {bata2}... list without {}\n :return: datas for each wine\n \"\"\"\n list_wine_data = []\n for row in datas_btw_braces:\n pattern_2 = r'\\: \\\"(.*?)\\\"'\n list_values = re.findall(pattern_2, row)\n\n if '\"price\": \"0\"' not in row:\n pattern3 = r'\\\"price\\\"\\: (.*?)\\,'\n price_of_wine = list(map(int, re.findall(pattern3, row))) # find the price value and convert it to class int\n if price_of_wine[0] > 0:\n list_values.insert(5, price_of_wine[0])\n temp_dict = dict(zip(list_keys, list_values))\n list_wine_data.append(temp_dict)\n return list_wine_data\n\n\ndef sort_wine_data(list_wine_data):\n \"\"\"Function sorts a list of dictionaries\n by two keys: price and country\n\n :param list_wine_data: unsorted list dicts of wine data\n :return: sorted list dicts of wine data\n \"\"\"\n wine_data = sorted(list_wine_data, key=lambda k: (int(k['price']), k[\"country\"]), reverse=True)\n with open('winedata_full.json', 'w', encoding='utf-8') as full_json_file:\n json = f'{wine_data}'\n full_json_file.write(json)\n return wine_data\n\n\ndef calculate_avarage_price(varieties, wine_data):\n \"\"\"Calculation of the average price of wine\n\n :param varieties: variates of wine\n :param wine_data: data of each wine\n \"\"\"\n list_price = [int(x['price']) for x in wine_data if x['variety'] == varieties and int(x['price']) > 0]\n # if not len(list_price):\n if not list_price:\n print(f'\\tAvarage price for {varieties} is: ',0)\n return 0\n\n avarage_price = round(sum(list_price)/len(list_price), 3)\n print(f'\\tAvarage price for {varieties} is: ', avarage_price)\n return avarage_price\n\n\ndef calculate_min_price(varieties, wine_data):\n \"\"\"Calculation of the minimum price of wine\n \"\"\"\n list_price = [int(x['price']) for x in wine_data if x['variety'] == varieties and int(x['price']) > 0]\n # if not len(list_price):\n if not list_price:\n print(f'\\tMinimum price for {varieties} is: ', 0)\n return 0\n\n minimum_price = min(list_price)\n print(f'\\tMinimum price for {varieties} is: ',minimum_price)\n return minimum_price\n\n\ndef calculate_max_price(varieties, wine_data):\n \"\"\"Calculation of the maximum price of wine\n \"\"\"\n list_price = [int(x['price']) for x in wine_data if x['variety'] == varieties and int(x['price']) > 0]\n # if not len(list_price):\n if not list_price:\n print(f'\\tMaximum price for {varieties} is: ',0)\n return 0\n max_price = max(list_price)\n print(f'\\tMaximum price for {varieties} is: ', max_price)\n return max_price\n\n\ndef calculate_most_common_region(varieties, wine_data):\n \"\"\"Calculation of the region where most\n wines of this variety are produced\n \"\"\"\n region_1 = [x['region_1'] for x in wine_data if x['variety'] == varieties and x['region_1'] != '0']\n region_2 = [x['region_2'] for x in wine_data if x['variety'] == varieties and x['region_2'] != '0']\n regions = region_1 + region_2\n\n if not regions:\n print(f'\\tMost common region for {varieties} is: ',0)\n return 0\n\n region_counter = collections.defaultdict(int)\n for i in regions:\n region_counter[i] += 1\n max_val = max(region_counter.values())\n final_dict = {k: v for k, v in region_counter.items() if v == max_val}\n name = [i for i in final_dict.keys()]\n print(f'\\tMost common region for {varieties} is: ', name[0], max_val)\n return name[0], max_val\n\n\n\n\ndef calculate_most_common_country(varieties, wine_data):\n \"\"\"Calculation of the country where most\n wines of this variety are produced\n \"\"\"\n countries = [x['country'] for x in wine_data if x['variety'] == varieties and x['country'] != '0']\n\n if not countries:\n print(f'\\tMost common country for {varieties} is: ',0)\n return 0\n\n countries_counter = collections.defaultdict(int)\n for i in countries:\n countries_counter[i] += 1\n max_val = max(countries_counter.values())\n final_dict = {k: v for k, v in countries_counter.items() if v == max_val}\n name = [i for i in final_dict.keys()]\n print(f'\\tMost common country for {varieties} is: ',name[0], max_val)\n return name[0], max_val\n\n\ndef calculate_avarage_score(varieties, wine_data):\n \"\"\"Calculate avarage score for points\n \"\"\"\n points = [int(x['points']) for x in wine_data if x['variety'] == varieties and int(x['points']) > 0]\n if not points:\n print(f'\\tAvarage score for {varieties} is: ', 0)\n return 0\n avarage_points = round(sum(points)/len(points), 2)\n print(f'\\tAvarage score for {varieties} is: ', avarage_points, end=\"\\n\"*2)\n return avarage_points\n\n\ndef calculate_most_expensive_wine(wine_data):\n \"\"\"Calculate most expensive wine\n :return: tuple (name of wine, price)\n \"\"\"\n wine_data = sorted(wine_data, key=lambda k: int(k['price']), reverse=True)\n print(f'\\tMost expensive wine is: ', wine_data[0]['variety'], wine_data[0]['price'])\n return wine_data[0]['variety'], wine_data[0]['price']\n\n\ndef calculate_cheapest_wine(wine_data):\n \"\"\"Calculate most cheapest wine among\n countries\n :return: tuple (name of wine, price)\n \"\"\"\n cheapest = [(x['variety'], int(x['price'])) for x in wine_data if int(x['price']) > 0]\n d_cheapest = dict(cheapest)\n for k, v in d_cheapest.items():\n if v == 0:\n del d_cheapest[k]\n sort_cheapest = sorted(d_cheapest.items(), key=lambda k: k[1])\n print(\"\\tMost cheapest wine is: \", sort_cheapest[0][0], sort_cheapest[0][1])\n return sort_cheapest[0][0], sort_cheapest[0][1]\n\n\ndef calculate_highest_score(wine_data):\n \"\"\"Calculate most highest score\n :return: str \"score\"\n \"\"\"\n highest_score = max([int(data[\"points\"]) for data in wine_data])\n print(\"\\tHighest score is: \", highest_score)\n return highest_score\n\n\ndef calculate_lowest_score(wine_data):\n \"\"\"Calculate most lowest score\n :return: str \"score\"\n \"\"\"\n lowest_score = min([int(i['points']) for i in wine_data])\n print(\"\\tLowest score is: \", lowest_score)\n return lowest_score\n\n\ndef calculate_most_rated_country(wine_data):\n \"\"\"Calculate most rated country\n :return: tuple (name of the country, points)\n \"\"\"\n rated = [(x['country'], (x['points'])) for x in wine_data if x['country'] != '0' and int(x['points']) > 0]\n d_rated = dict(rated)\n sort_rated = sorted(d_rated.items(), key=lambda k: k[1], reverse=True)\n print(\"\\tMost rated country is: \",sort_rated[0])\n return sort_rated[0]\n\n\ndef calculate_most_active_commentator(wine_data):\n \"\"\"Caalculate most active commentator\n :return: tuple (Name, count)\n \"\"\"\n commentator_name = [x[\"taster_name\"] for x in wine_data if x[\"taster_name\"] != '0']\n activity_commentator = collections.defaultdict(int)\n for i in commentator_name:\n activity_commentator[i] += 1\n sorted_list_commentators = sorted(activity_commentator.items(), key=lambda k: k[1], reverse=True)\n print(\"\\tMost active commentator\", sorted_list_commentators[0])\n return sorted_list_commentators[0]\n\n\nif __name__ == '__main__':\n\n json_file_1 = 'winedata_1.json'\n json_file_2 = 'winedata_2.json'\n full_json = 'winedata_full.json'\n\n varieties_of_wines = ['Gew\\\\u00fcrztraminer',\n 'Riesling',\n 'Merlot',\n 'Madera',\n 'Tempranillo',\n 'Red Blend']\n\n concat_text = join_jsons(json_file_1, json_file_2)\n keys, datas_betw_braces = extraction_data_between_braces(concat_text)\n wine_data_unsort = get_wine_data(keys, datas_betw_braces)\n wine_data = sort_wine_data(wine_data_unsort)\n\n with open('mystats.json', 'w') as f:\n print('{\"statistics\": {', file=f)\n print('\\t\\t\"wine\": {', file=f)\n for varieties in varieties_of_wines:\n\n print(f\"\\nStatistic for Varieties: {varieties}\", end=\"\\n\"*2)\n\n print(f'\\t\\t\\t\"{varieties}\"' + ': {', file=f)\n\n print('\\t\\t\\t\\t\"avarege_price\":',\n f'\"{calculate_avarage_price(varieties, wine_data)}\", ', file=f)\n\n print('\\t\\t\\t\\t\"min_price\":',\n f'\"{calculate_min_price(varieties, wine_data)}\", ', file=f)\n\n print('\\t\\t\\t\\t\"max_price\":',\n f'\"{calculate_max_price(varieties, wine_data)}\", ', file=f)\n\n print('\\t\\t\\t\\t\"most_common_region\":',\n f'\"{calculate_most_common_region(varieties, wine_data)}\", ', file=f)\n\n print('\\t\\t\\t\\t\"most_common_country\":',\n f'\"{calculate_most_common_country(varieties, wine_data)}\", ', file=f)\n\n print('\\t\\t\\t\\t\"avarage_score\":',\n f'\"{calculate_avarage_score(varieties, wine_data)}\"', file=f)\n print('\\t\\t\\t\\t},', file=f)\n print(\"General results:\")\n print('\\t\\t},', file=f)\n\n print('\\t\\t\"most_expensive_wine\":',\n f'\"{calculate_most_expensive_wine(wine_data)}\",', file=f)\n\n print('\\t\\t\"cheapest_wine\":',\n f'\"{calculate_cheapest_wine(wine_data)}\",', file=f)\n\n print('\\t\\t\"highest_score\":',\n f'\"{calculate_highest_score(wine_data)}\",', file=f)\n\n print('\\t\\t\"lowest_score\":',\n f'\"{calculate_lowest_score(wine_data)}\",', file=f)\n\n print('\\t\\t\"most_rated_country\":',\n f'\"{calculate_most_rated_country(wine_data)}\",', file=f)\n\n print('\\t\\t\"most_active_commentator\":',\n f'\"{calculate_most_active_commentator(wine_data)}\",', file=f)\n print('\\t\\t}', file=f)\n print('}', file=f)","sub_path":"01-Data-Structures/hw/sticks/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":11165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"417994513","text":"from random import randint\nfrom lab1.liuvacuum import *\n\n\"\"\"\nSimple Reactive Vacuum agent\n\"\"\"\n\n\nclass ReactiveVacuumAgent(Agent):\n\n def __init__(self, world_width, world_height, log):\n super().__init__(self.execute)\n self.iteration_counter = 100\n self.log = log\n\n def execute(self, percept):\n\n bump = percept.attributes[\"bump\"]\n dirt = percept.attributes[\"dirt\"]\n home = percept.attributes[\"home\"]\n\n # Max iterations for the agent\n if self.iteration_counter < 1:\n if self.iteration_counter == 0:\n self.iteration_counter -= 1\n self.log(\"Iteration counter is now 0. Halting!\")\n self.log(\"Performance: {}\".format(self.performance))\n self.alive = False\n return ACTION_NOP\n\n self.iteration_counter -= 1\n\n random_action = randint(1, 8)\n # self.log(\"Rand: {}\".format(random_action))\n if dirt:\n self.log(\"DIRT -> choosing SUCK action!\")\n return ACTION_SUCK\n else:\n if bump:\n random_turn_action = randint(1, 2)\n if random_turn_action == 1:\n self.log(\"BUMP -> choosing TURN_LEFT action!\")\n return ACTION_TURN_LEFT\n else:\n self.log(\"BUMP -> choosing TURN_RIGHT action!\")\n return ACTION_TURN_RIGHT\n else:\n return ACTION_FORWARD\n","sub_path":"TDDC17_lab1_python/lab1/reactivevacuumagent.py","file_name":"reactivevacuumagent.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"264965419","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, redirect, render, get_object_or_404\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom kinger.models import Agency,School,Department,Group,Teacher,Student\nfrom oa.forms import SchoolForm\nfrom django.contrib import messages\nimport xlwt, xlrd\nfrom oa import helpers\nfrom django.utils.translation import ugettext as _\nfrom oa.decorators import Has_permission\n\n@Has_permission('manage_school')\ndef index(request,template_name=\"oa/school_list.html\"):\n \"\"\"学园管理列表页\"\"\"\n schools = helpers.get_schools(request.user)\n school_pks = [s.id for s in schools]\n query = request.GET.get(\"q\",'')\n if query:\n schools = School.objects.filter(name__contains=query,pk__in=school_pks)\n ctx = {'schools':schools,\"query\":query}\n return render(request, template_name, ctx)\n\n@Has_permission('manage_school')\ndef delete(request,school_id): \n \"\"\"删除学园\"\"\"\n school_pks = [s.id for s in helpers.get_schools(request.user)]\n school = get_object_or_404(School,pk=school_id,pk__in=school_pks)\n school.delete()\n messages.success(request, u'学园 %s 已删除' % school.name)\n return redirect(\"oa_school_list\")\n\n@Has_permission('manage_school')\ndef create(request,template_name=\"oa/school_form.html\"):\n \"\"\"创建学园\"\"\"\n ctx = {}\n schools = helpers.get_schools(request.user)\n try:\n agency = schools[0].parent\n except:\n agency = schools[0]\n if request.method == 'POST':\n form = SchoolForm(request.POST)\n \n if request.is_ajax():\n return helpers.ajax_validate_form(form)\n \n if form.is_valid():\n school = form.save(commit=False)\n school.creator = request.user\n school.parent = agency\n# admins = [u for u in agency.admins.all()]\n school.save()\n if school.id:\n# school.admins = admins\n messages.success(request, u'已成功创建学园 %s ' % school.name)\n return redirect(\"oa_school_list\")\n else:\n form = SchoolForm()\n ctx.update({'form':form})\n return render(request, template_name, ctx)\n\n@Has_permission('manage_school')\ndef update(request, school_id, template_name=\"oa/school_form.html\"):\n \"\"\"更新学园\"\"\"\n school_pks = [s.id for s in helpers.get_schools(request.user)]\n school = get_object_or_404(School,pk=school_id,pk__in=school_pks)\n# school = get_object_or_404(School, pk=school_id)\n if request.method == 'POST':\n form = SchoolForm(request.POST, instance=school)\n \n if request.is_ajax():\n return helpers.ajax_validate_form(form)\n \n if form.is_valid():\n form.save()\n messages.success(request, u\"已成功更新学园: %s \" % school.name)\n\n return redirect(\"oa_school_list\")\n else:\n form = SchoolForm(instance=school)\n\n ctx = {\"form\": form, \"school\": school}\n return render(request, template_name, ctx)\n\n@Has_permission('manage_school')\ndef update(request, school_id, template_name=\"oa/school_form.html\"):\n \"\"\"更新学园\"\"\"\n school_pks = [s.id for s in helpers.get_schools(request.user)]\n school = get_object_or_404(School,pk=school_id,pk__in=school_pks)\n# school = get_object_or_404(School, pk=school_id)\n if request.method == 'POST':\n form = SchoolForm(request.POST, instance=school)\n \n if request.is_ajax():\n return helpers.ajax_validate_form(form)\n \n if form.is_valid():\n form.save()\n messages.success(request, u\"已成功更新学园: %s \" % school.name)\n\n return redirect(\"oa_school_list\")\n else:\n form = SchoolForm(instance=school)\n\n ctx = {\"form\": form, \"school\": school}\n return render(request, template_name, ctx)\n\n@Has_permission('manage_school')\ndef export_member(request,school_id):\n school = School.objects.get(pk=school_id)\n ty = request.GET.get(\"ty\",'teacher')\n \n if ty == \"teacher\":\n teachers = Teacher.objects.filter(school=school)\n teachers = teachers.filter(is_delete=False)\n response = HttpResponse(mimetype=\"application/ms-excel\")\n response['Content-Disposition'] = 'attachment; filename=teachers.xls'\n \n wb = xlwt.Workbook()\n ws = wb.add_sheet(_(\"Teacher List\"))\n \n for idx, col in enumerate([ _(\"Name\"),_(\"Username\"), _(\"Mobile\")]):\n ws.write(0, idx, col)\n row = 0\n for s in teachers:\n row += 1 \n col = 0\n name = helpers.get_name(s.user)\n for c in [name,s.user.username,s.user.profile.mobile]: \n ws.write(row,col,c)\n col += 1\n wb.save(response)\n return response\n else:\n students = Student.objects.filter(school=school,is_delete=False)\n response = HttpResponse(mimetype=\"application/ms-excel\")\n response['Content-Disposition'] = 'attachment; filename=teachers.xls'\n \n wb = xlwt.Workbook()\n ws = wb.add_sheet(_(\"Teacher List\"))\n \n for idx, col in enumerate([ _(\"Name\"),_(\"Username\"), _(\"Mobile\"), _('school class')]):\n ws.write(0, idx, col)\n row = 0\n for s in students:\n col = 0\n name = helpers.get_name(s.user)\n try:\n student_info = [name,s.user.username,s.user.profile.mobile,s.group.name]\n row += 1 \n for c in student_info: \n ws.write(row,col,c)\n col += 1\n except:\n pass\n wb.save(response)\n return response\n\n\n","sub_path":"oa/views/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"212858622","text":"import string\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom pomegranate import *\r\nfrom skimage import img_as_ubyte\r\nfrom utils.data_conversions import *\r\nfrom utils.process_after_mutation import *\r\n\r\n\r\n# from utils import common\r\n\r\n\r\ndef do_mutate(data_list, mutate_function):\r\n \"\"\"\r\n 该函数为具体执行扰动方法的变异过程。\r\n :param data_list: 待变异数据\r\n :param mutate_function:选取的扰动方法\r\n :return: 变异后数据\r\n \"\"\"\r\n\r\n data_list = mutate_function(data_list)\r\n return data_list\r\n\r\n\r\ndef get_list():\r\n # 设置为元组,保证其不可变\r\n target_mutaion_functions = (mutate_erase_bytes,\r\n mutate_insert_bytes,\r\n mutate_change_byte,\r\n mutate_insert_repeated_bytes,\r\n mutate_change_ascii_integer,\r\n mutate_change_bit,\r\n mutate_white_noise,\r\n mutate_rotate,\r\n mutate_scale,\r\n mutate_triangular_matrix,\r\n mutate_kernel_matrix\r\n )\r\n return_list = list(target_mutaion_functions)\r\n return return_list\r\n\r\n\r\ndef mutate_for_li(li, target_id):\r\n \"\"\"\r\n :param li:\r\n :param target_id: 具体变异方法的编号\r\n :return:\r\n \"\"\"\r\n mutation_list = get_list()\r\n return mutation_list[target_id](li)\r\n\r\n\r\ndef list_to_byte(data, prob1=0.3, prob2=0.3, prob3=0.3):\r\n \"\"\"\r\n :param data: 待变异数据, list格式\r\n :param prob1: 变异概率1\r\n :param prob2: 变异概率2\r\n :param prob3: 变异概率3\r\n :return: 定位的具体二进制值\r\n \"\"\"\r\n data = np.array(data)\r\n for i in range(data.shape[0]):\r\n if random.random() > prob1:\r\n continue\r\n for j in range(data.shape[1]):\r\n if random.random() > prob2:\r\n continue\r\n for k in range(data.shape[2]):\r\n if random.random() < prob3:\r\n num = data[i][j][k]\r\n num = converse(num, float_to_byte)\r\n return num, [i, j, k]\r\n\r\n num = data[0][0][0]\r\n num = converse(num, float_to_byte)\r\n return num, [0, 0, 0]\r\n\r\n\r\ndef byte_to_list(data, num, location):\r\n # 处理\r\n i = location[0]\r\n j = location[1]\r\n k = location[2]\r\n num = process(num)\r\n # 转为double类型\r\n num = converse(num, byte_to_float)\r\n data[i][j][k] = num\r\n if not isinstance(data, np.ndarray):\r\n data = np.array(data)\r\n data = np.clip(data, a_min=0.0, a_max=1.0)\r\n return data\r\n\r\n\r\ndef mutate_sift(data, constraint=None, threshold=0.00, a_min=-1.0, a_max=1.0, ):\r\n SIGMA_CONSTANT = 15\r\n\r\n data = mutate_white_noise(data, sigma=0.2)\r\n keypoints = getSiftKeypoints(data)\r\n data_size = []\r\n\r\n data_size.append(len(data))\r\n element = data[0]\r\n\r\n data_size.append(len(element))\r\n element = element[0]\r\n\r\n data_size.append(len(element))\r\n # 图像调整\r\n for _ in range(np.random.randint(low=1, high=3)):\r\n index = np.random.randint(low=0, high=len(keypoints))\r\n mu_x, mu_y, sigma = int(round(keypoints[index][0].pt[0])), int(round(keypoints[index][0].pt[1])), \\\r\n keypoints[index][2]\r\n sigma += SIGMA_CONSTANT\r\n # 对点做正态分布\r\n d_x = NormalDistribution(mu_x, sigma)\r\n d_y = NormalDistribution(mu_y, sigma)\r\n x = int(d_x.sample())\r\n y = int(d_y.sample())\r\n\r\n if x >= data_size[0]:\r\n x = data_size[0] - 1\r\n elif x < 0:\r\n x = 0\r\n\r\n if y >= data_size[1]:\r\n y = data_size[1]\r\n elif y < 0:\r\n y = 0\r\n\r\n data[x][y] += keypoints[index][2]\r\n\r\n data = np.clip(data, a_min=a_min, a_max=a_max)\r\n return data\r\n\r\n\r\ndef getSiftKeypoints(image, threshold=0.00):\r\n img_unit8 = img_as_ubyte(image)\r\n\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n\r\n max_cnt = 100\r\n while max_cnt >= 0:\r\n max_cnt = max_cnt - 1\r\n kp, des = sift.detectAndCompute(img_unit8, None)\r\n if len(kp) != 0:\r\n break\r\n\r\n if not kp:\r\n keypoints = []\r\n return keypoints\r\n # FILTER RESPONSES:\r\n # 返回一个具体的响应值\r\n responses = []\r\n for x in kp:\r\n responses.append(x.response)\r\n responses.sort()\r\n\r\n keypoints = []\r\n index_tracker = 0\r\n for x in kp:\r\n if x.response >= threshold:\r\n keypoints.append((x, des[index_tracker], x.response))\r\n index_tracker = index_tracker + 1\r\n\r\n # 根据response值排序,由高到低\r\n keypoints = sorted(keypoints, key=lambda tup: tup[2])\r\n\r\n return keypoints\r\n\r\n\r\n# 随机减少字节\r\ndef mutate_erase_bytes(data):\r\n \"\"\"\r\n 随机删除字节\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n if len(num) == 0:\r\n return data\r\n idx = random.randrange(len(num))\r\n num = num[idx:random.randrange(idx, len(num))]\r\n data = byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\n# 随机插入字节\r\ndef mutate_insert_bytes(data):\r\n \"\"\"\r\n 随机删除字节\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n if len(num) == 0:\r\n return data\r\n idx = random.randrange(len(num))\r\n new_bytes = get_random_bytes(random.randrange(1, 5))\r\n num = num[:idx] + new_bytes + num[idx:]\r\n data = byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\n# 插入重复字节\r\ndef mutate_insert_repeated_bytes(data):\r\n \"\"\"\r\n 插入重复字节\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n if len(num) == 0:\r\n return data\r\n num = bytearray(num)\r\n idx = random.randrange(len(num))\r\n new_byte = get_random_byte()\r\n sz = random.randrange(5)\r\n num[idx:idx + sz] = bytes(new_byte) * sz\r\n num = bytes(num)\r\n data = byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\ndef get_random_bytes(size):\r\n return bytearray(random.getrandbits(8) for _ in range(size))\r\n\r\n\r\ndef get_random_byte():\r\n return random.getrandbits(8)\r\n\r\n\r\n# 随机改变字节\r\ndef mutate_change_byte(data):\r\n \"\"\"\r\n 随机改变字节\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n if len(num) == 0:\r\n return data\r\n num = bytearray(num)\r\n idx = random.randrange(len(num))\r\n byte = get_random_byte()\r\n num[idx] = byte\r\n num = bytes(num)\r\n data = byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\n# 改变bit\r\ndef mutate_change_bit(data):\r\n \"\"\"\r\n 改变bit\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n num = bytearray(num)\r\n if len(num) > 0:\r\n idx = random.randrange(len(num))\r\n num[idx] ^= 1 << random.randrange(8)\r\n num = bytes(num)\r\n data = byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\ndef mutate_change_ascii_integer(data):\r\n \"\"\"\r\n :param data:\r\n :return:\r\n \"\"\"\r\n num, location = list_to_byte(data)\r\n num = bytearray(num)\r\n start = random.randrange(len(num))\r\n while start < len(num) and chr(num[start]) not in string.digits:\r\n start += 1\r\n if start == len(num):\r\n return bytes(num)\r\n\r\n end = start\r\n while end < len(num) and chr(num[end]) in string.digits:\r\n end += 1\r\n\r\n value = int(num[start:end])\r\n choice = random.randrange(5)\r\n if choice == 0:\r\n value += 1\r\n elif choice == 1:\r\n value -= 1\r\n elif choice == 2:\r\n value //= 2\r\n elif choice == 3:\r\n value *= 2\r\n elif choice == 4:\r\n value *= value\r\n value = max(1, value)\r\n value = random.randrange(value)\r\n else:\r\n assert False\r\n\r\n to_insert = bytes(str(value), encoding='ascii')\r\n num[start:end] = to_insert\r\n num = bytes(num)\r\n byte_to_list(data, num, location)\r\n return data\r\n\r\n\r\ndef mutate_white_noise(data, a_min=0.0, a_max=1.0, sigma=5):\r\n \"\"\"\r\n 添加白噪音\r\n :param data: 待变异数据\r\n :param a_min: 噪声下界\r\n :param a_max: 噪声上界\r\n :return: 变异后值\r\n \"\"\"\r\n\r\n data_size = []\r\n\r\n data_size.append(len(data))\r\n element = data[0]\r\n\r\n data_size.append(len(element))\r\n element = element[0]\r\n\r\n data_size.append(len(element))\r\n\r\n noise = np.random.normal(size=data_size, scale=sigma)\r\n\r\n mutated_image = noise + data\r\n\r\n mutated_image = np.clip(mutated_image, a_min=a_min, a_max=a_max)\r\n return mutated_image\r\n\r\n\r\ndef mutate_rotate(data, angle=45, scale=1.0):\r\n (h, w) = len(data), len(data[0])\r\n center = (w // 2, h // 2)\r\n M = cv2.getRotationMatrix2D(center, angle, scale)\r\n data = np.array(data)\r\n rotated = cv2.warpAffine(data, M, (w, h)) # 13\r\n # cv2.imshow(\"Rotated by 45 Degrees\", rotated) # 14\r\n return rotated\r\n\r\n\r\ndef mutate_scale(data, scale=1):\r\n data = np.array(data)\r\n # 指定fx, fy缩放比例的缩放方式\r\n if isinstance(scale, list):\r\n data = cv2.resize(data, None, fx=scale[0], fy=scale[1], interpolation=cv2.INTER_CUBIC)\r\n # 指定同一缩放比例的缩放方式,此处不接受float\r\n elif isinstance(scale, int):\r\n (h, w) = len(data), len(data[0])\r\n data = cv2.resize(data, (scale * h, scale * w), interpolation=cv2.INTER_CUBIC)\r\n # cv2.imshow(\"Rotated by 45 Degrees\", data) # 14\r\n return data\r\n\r\n\r\ndef mutate_precision(data, precision=10, style=0):\r\n \"\"\"\r\n 精度变化算子,该算子只用于降低精度,不用于提高精度\r\n :param data: 待调整数据\r\n :param precision: 精度调整值\r\n :param style: 精度调整方式,0为全部调整,否则调整style个\r\n :return: 精度调整后数据\r\n \"\"\"\r\n if style < 0:\r\n return data\r\n if not style:\r\n data = np.array(data)\r\n new_data = [[[round(element, precision) for element in j] for j in i] for i in data]\r\n new_data = np.array(new_data)\r\n return new_data\r\n else:\r\n (h, w, c) = len(data), len(data[0]), len(data[0][0])\r\n if style >= h or style >= w:\r\n return data\r\n x = random.sample(range(0, h), style)\r\n y = random.sample(range(0, w), style)\r\n z = np.random.randint(0, c, style)\r\n for index in range(style):\r\n indexX = x[index]\r\n indexY = y[index]\r\n indexZ = z[index]\r\n # print(data[indexX][indexY][indexZ])\r\n data[indexX][indexY][indexZ] = round(data[indexX][indexY][indexZ], precision)\r\n # print(data[indexX][indexY][indexZ])\r\n return data\r\n\r\n\r\ndef mutate_triangular_matrix(data, style=1):\r\n \"\"\"\r\n 将data值直接转化为三角矩阵\r\n :param data: 待转化值\r\n :param style: 0或其他值为上三角, 1为下三角\r\n :return: 三角矩阵\r\n \"\"\"\r\n data = np.array(data)\r\n (h, w) = data.shape[0], data.shape[1]\r\n if style == 1:\r\n for i in range(h):\r\n for j in range(i + 1, h):\r\n data[i][j][0] = data[i][j][1] = data[i][j][2] = 0\r\n else:\r\n for i in range(1, h):\r\n for j in range(0, i):\r\n data[i][j][0] = data[i][j][1] = data[i][j][2] = 0\r\n return data\r\n\r\n\r\ndef mutate_kernel_matrix(data, kernel=([1, 1, 1], [0, 1, 0], [1, 1, 0])):\r\n data = np.array(data)\r\n (h_data, w_data) = data.shape[0], data.shape[1]\r\n kernel = np.array(kernel)\r\n (h_kernel, w_kernel) = kernel.shape[0], kernel.shape[1]\r\n (h_move, w_move) = h_data // h_kernel, w_data // w_kernel\r\n for i in range(h_move):\r\n for j in range(h_move):\r\n for channel in range(data.shape[2]):\r\n temp_array = data[i * h_kernel:i * h_kernel + h_kernel, j * w_kernel: j * w_kernel + w_kernel, channel]\r\n temp_array = np.dot(temp_array, kernel)\r\n data[i * h_kernel:i * h_kernel + h_kernel, j * w_kernel: j * w_kernel + w_kernel, channel] = temp_array\r\n\r\n return data\r\n\r\n\r\nif __name__ == '__main__':\r\n data = np.random.rand(28, 28, 3)\r\n data = mutate_kernel_matrix(data)\r\n","sub_path":"Web/utils/mutate_functions_by_bytes.py","file_name":"mutate_functions_by_bytes.py","file_ext":"py","file_size_in_byte":12214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"80378447","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nfrom geometry_msgs.msg import Twist\n\nclass Lqr:\n\n\tdef __init__(self, NILQR=21):\n\t\t\"\"\" initialize LQR controller\n\t\tNILQR: length of reference waypoints\n\t\t\"\"\"\n\n\t\t# constants\n\t\tself.n = NILQR\t\t\t\t\t\t\t\t\t\t\t# NILQR, N, n, var.nstep\n\t\tself.dt = 0.5\t\t\t\t\t\t\t\t\t\t\t# dt, Dt, ts\n\t\tself.nx = 5\t\t\t\t\t\t\t\t\t\t\t\t# var.nx, nx\n\t\tself.nu = 2\t\t\t\t\t\t\t\t\t\t\t\t# self.nu, nu\n\t\tself.thres = 1e-4\t\t\t\t\t\t\t\t\t\t# var.thres\n\t\tself.line_search_thres = 1e-4\t\t\t\t\t\t\t# var.lineSearchThres\n\t\tself.l2 = np.diag([70, 70, 0, 0, 0, 10, 10])\t\t\t# L2\n\n\t\tself.l1 = np.zeros((7, self.n))\t\t\t\t\t\t\t# L1\n\t\tself.u = np.zeros((2, self.n-1))\t\t\t\t\t\t# u - control input\t\t\t\t\n\t\tself.x = np.zeros((5, self.n))\t\t\t\t\t\t\t# x - states [x; y; ?; vx; wz]\n\n\t\t# input\n\t\tself.lqr_ref = np.zeros((5, self.n))\t\t\t\t\t# reference path - [x; y; 0; 0; 0]\n\n\tdef set_reference(self, ref, t):\n\t\tself.lqr_ref[0:2,:] = ref\n\t\tself.lqr_ref[2, 0] = t \n\t\tself.l1 = np.zeros((7, self.n))\n\t\tself.u = np.zeros((2, self.n-1))\n\t\tself.x = np.zeros((5, self.n))\n\n\tdef forward_sim_car(self):\n\t\tx = np.zeros((self.nx, self.n))\n\t\tx[:,0] = self.lqr_ref[:,0]\n\t\tcost = 0\n\n\t\tfor i in range(0, self.n-1):\n\t\t\tthk = x[2,i]\n\t\t\tvk = x[3,i]\n\t\t\tthdk = x[4,i]\n\t\t\tak = self.u[0,i]\n\t\t\tthak = self.u[1,i]\n\t\t\tthm = thk + 0.5*self.dt*thdk\n\n\t\t\tx[0,i+1] = x[0,i] + vk*self.dt*np.cos(thm)\n\t\t\tx[1,i+1] = x[1,i] + vk*self.dt*np.sin(thm)\n\t\t\tx[2,i+1] = x[2,i] + self.dt*thdk\n\t\t\tx[3,i+1] = x[3,i] + self.dt*ak\n\t\t\tx[4,i+1] = x[4,i] + self.dt*thak\n\n\t\t\tdz = np.concatenate((x[:,i+1]-self.lqr_ref[:,i+1], self.u[:,i]))\n\t\t\tcost += 0.5*dz.T.dot(self.l2).dot(dz)\n\t\tself.x = x\n\t\treturn cost\n\n\tdef linearize_ab_car(self):\n\t\ta = np.zeros((self.n-1, self.nx, self.nx))\n\t\tb = np.array([[0,0],[0,0],[0,0],[self.dt,0], [0,self.dt]])\n\n\t\tfor i in range(0, self.n-1):\n\t\t\tthk = self.x[2,i]\n\t\t\tvk = self.x[3,i]\n\t\t\tthdk = self.x[4,i]\n\t\t\tthm = thk + 0.5*self.dt*thdk\n\n\t\t\ta[i] = np.array([[1, 0, -vk*self.dt*np.sin(thm), self.dt*np.cos(thm), -0.5*pow(self.dt,2)*vk*np.sin(thm)],\n\t\t\t\t\t\t\t [0, 1, vk*self.dt*np.cos(thm), self.dt*np.sin(thm), 0.5*pow(self.dt, 2)*vk*np.cos(thm)],\n\t\t\t\t\t\t\t [0, 0, 1, 0, self.dt],\n\t\t\t\t\t\t\t [0, 0, 0, 1, 0],\n\t\t\t\t\t\t\t [0, 0, 0, 0, 1]])\n\t\treturn a,b\n\n\tdef modify_cost(self):\n\t\tfor i in range(0, self.n-1):\n\t\t\tself.l1[:,i] = self.l2.dot(np.concatenate((self.x[:,i].T, self.u[:,i].T))) - self.l2.dot(np.concatenate((self.lqr_ref[:,i].T, np.zeros(2))))\n\t\tself.l1[0:self.nx,-1] = self.l2[0:self.nx, 0:self.nx].dot(self.x[:,-1]) - self.l2[0:self.nx, 0:self.nx].dot(self.lqr_ref[:,-2])\n\n\tdef stochastic_lqr(self, a, b):\n\t\tvxx = self.l2[0:self.nx, 0:self.nx]\n\t\tvx = self.l1[0:self.nx, self.n-1]\n\t\tka = np.zeros((self.nu, self.n-1))\n\t\tkb = np.zeros((self.n-1, self.nu, self.nx))\n\t\tsigs = np.zeros((self.n-1, self.nu, self.nu))\n\n\t\tfor i in range(self.n-2, -1, -1):\n\t\t\tqxx = self.l2[0:self.nx, 0:self.nx] + a[i].T.dot(vxx).dot(a[i])\n\t\t\tquu = self.l2[self.nx:, self.nx:] + b.T.dot(vxx).dot(b)\n\t\t\tqux = self.l2[self.nx:, 0:self.nx] + b.T.dot(vxx).dot(a[i])\n\t\t\tqx = self.l1[0:self.nx, i] + a[i].T.dot(vx)\n\t\t\tqu = self.l1[self.nx:, i] + b.T.dot(vx)\n\t\t\tsig = np.linalg.inv(quu)\n\t\t\tsigs[i] = sig\n\t\t\tvx = qx - qux.T.dot(sig).dot(qu)\n\t\t\tvxx = qxx - qux.T.dot(sig).dot(qux)\n\t\t\tka[:,i] = -sig.dot(qu)\n\t\t\tkb[i] = -sig.dot(qux)\n\n\t\treturn ka, kb, sigs\n\n\tdef execute_policy(self, ka, kb):\n\t\tx = np.zeros((self.nx, self.n))\n\t\tx[:,0] = self.lqr_ref[:,0]\n\t\tcost = 0\n\t\tu = np.zeros((self.nu, self.n-1))\n\n\t\tfor i in range(0, self.n-1):\n\t\t\tu[:,i] = ka[:,i] + kb[i].dot(x[:,i])\n\t\t\tthk = x[2,i]\n\t\t\tvk = x[3,i]\n\t\t\tthdk = x[4,i]\n\t\t\tak = u[0,i]\n\t\t\tthak = u[1,i]\n\t\t\tthm = thk + 0.5*self.dt*thdk\n\n\t\t\tx[0,i+1] = x[0,i] + vk*self.dt*np.cos(thm)\n\t\t\tx[1,i+1] = x[1,i] + vk*self.dt*np.sin(thm)\n\t\t\tx[2,i+1] = x[2,i] + self.dt*thdk\n\t\t\tx[3,i+1] = x[3,i] + self.dt*ak\n\t\t\tx[4,i+1] = x[4,i] + self.dt*thak\n\n\t\t\tdz = np.concatenate((x[:,i+1]-self.lqr_ref[:,i+1], u[:,i]))\n\t\t\tcost += 0.5*dz.T.dot(self.l2).dot(dz)\n\t\treturn x, u, cost\n\n\tdef get_lqr_reference(self, ref, x):\n\t\t\"\"\" runs LQR controller\n\t\tINPUT\n\t\tref: reference waypoints\n\t\tx: current state [x, y, t, v, w]\n\t\tOUTPUT\n\t\tself.x: new waypoints\n\t\t\"\"\"\n\t\tif len(ref) is 0:\n\t\t\treturn\n\t\tself.set_reference(ref, x[2])\n\n\t\tmax_step = 100\n\n\t\tcost = self.forward_sim_car()\n\t\tJ = np.zeros(max_step)\n\t\tJ[0] = cost\n\n\t\tfor i in range(0, max_step-1):\n\t\t\tstop = 0\n\t\t\ta, b = self.linearize_ab_car()\n\t\t\tself.modify_cost()\n\t\t\tka, kb, sigs = self.stochastic_lqr(a,b)\n\t\t\tk1 = ka\n\t\t\tstep = 1.0\n\t\t\twhile(1):\n\t\t\t\tfor j in range(0, self.n-1):\n\t\t\t\t\tk1[:,j] = self.u[:,j] + step*ka[:,j] - kb[j].dot(self.x[:,j])\n\t\t\t\tx1, u1, cost1 = self.execute_policy(ka, kb)\n\t\t\t\tif cost1 < cost:\n\t\t\t\t\tcost = cost1\n\t\t\t\t\tJ[i+1] = cost\n\t\t\t\t\tself.x = x1\n\t\t\t\t\tself.u = u1\n\t\t\t\t\tbreak\n\t\t\t\tstep *= 0.5\n\t\t\t\tif step < self.line_search_thres:\n\t\t\t\t\tstop = 1\n\t\t\t\t\tself.x = x1\n\t\t\t\t\tself.u = u1\n\t\t\t\t\tbreak\n\t\t\tif stop == 1:\n\t\t\t\tbreak\n\t\t\tif J[i+1] is not 0 and (J[i] - J[i+1])/J[i+1] < self.thres:\n\t\t\t\tbreak\n\t\treturn self.x\n\n\t\t","sub_path":"low_level_control/src/lqr_module.py","file_name":"lqr_module.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"296829015","text":"from pyshorteners import Shortener\n\nfrom bot.commands.command import Command\nfrom bot.player.enums import Mode, State, TrackType\nfrom bot.TeamTalk.structs import UserRight\nfrom bot import errors, vars\n\n\nclass HelpCommand(Command):\n @property\n def help(self):\n return _('Shows command help')\n\n def __call__(self, arg, user):\n return self.command_processor.help(arg, user)\n\n\nclass AboutCommand(Command):\n @property\n def help(self):\n return _('Shows information about the bot')\n\n def __call__(self, arg, user):\n return vars.client_name + '\\n' + vars.about_text()\n\n\nclass PlayPauseCommand(Command):\n @property\n def help(self):\n return _('QUERY Plays tracks found for the query. If no query is given, plays or pauses current track')\n\n def __call__(self, arg, user):\n if arg:\n self.ttclient.send_message(_('Searching...'), user)\n try:\n track_list = self.service_manager.service.search(arg)\n if self.command_processor.send_channel_messages:\n self.ttclient.send_message(_(\"{nickname} requested {request}\").format(nickname=user.nickname, request=arg), type=2)\n self.player.play(track_list)\n return _('Playing {}').format(self.player.track.name)\n except errors.NothingFoundError:\n return _('Nothing is found for your query')\n except errors.ServiceError:\n return _('The selected service is currently unavailable')\n else:\n if self.player.state == State.Playing:\n self.player.pause()\n elif self.player.state == State.Paused:\n self.player.play()\n\n\nclass PlayUrlCommand(Command):\n @property\n def help(self):\n return _('URL Plays a stream from a given URL')\n\n def __call__(self, arg, user):\n if arg:\n try:\n tracks = self.module_manager.streamer.get(arg, user.is_admin)\n if self.command_processor.send_channel_messages:\n self.ttclient.send_message(_('{nickname} requested playing from a URL').format(nickname=user.nickname), type=2)\n self.player.play(tracks)\n except errors.IncorrectProtocolError:\n return _('Incorrect protocol')\n except errors.ServiceError:\n return _('Cannot process stream URL')\n except errors.PathNotFoundError:\n return _('The path cannot be found')\n else:\n raise errors.InvalidArgumentError\n\n\nclass StopCommand(Command):\n @property\n def help(self):\n return _('Stops playback')\n\n def __call__(self, arg, user):\n if self.player.state != State.Stopped:\n self.player.stop()\n if self.command_processor.send_channel_messages:\n self.ttclient.send_message(_(\"{nickname} stopped playback\").format(nickname=user.nickname), type=2)\n else:\n return _('Nothing is playing')\n\n\nclass VolumeCommand(Command):\n @property\n def help(self):\n return _('VOLUME Sets the volume to a value between 0 and {max_volume}. If no volume is specified, the current volume level is displayed').format(max_volume=self.player.max_volume)\n\n def __call__(self, arg, user):\n if arg:\n try:\n volume = int(arg)\n if 0 <= volume <= self.player.max_volume:\n self.player.set_volume(int(arg))\n else:\n raise ValueError\n except ValueError:\n raise errors.InvalidArgumentError\n else:\n return str(self.player.volume)\n\n\nclass SeekBackCommand(Command):\n @property\n def help(self):\n return _('STEP Seeks current track backward. the default step is {seek_step} seconds').format(seek_step=self.player.seek_step)\n\n def __call__(self, arg, user):\n if self.player.state == State.Stopped:\n return _('Nothing is playing')\n if arg:\n try:\n self.player.seek_back(float(arg))\n except ValueError:\n raise errors.InvalidArgumentError\n else:\n self.player.seek_back()\n\n\nclass SeekForwardCommand(Command):\n @property\n def help(self):\n return _('STEP Seeks current track forward. the default step is {seek_step} seconds').format(seek_step=self.player.seek_step)\n\n def __call__(self, arg, user):\n if self.player.state == State.Stopped:\n return _('Nothing is playing')\n if arg:\n try:\n self.player.seek_forward(float(arg))\n except ValueError:\n raise errors.InvalidArgumentError\n else:\n self.player.seek_forward()\n\n\nclass NextTrackCommand(Command):\n @property\n def help(self):\n return _('Plays next track')\n\n def __call__(self, arg, user):\n try:\n self.player.next()\n return _('Playing {}').format(self.player.track.name)\n except errors.NoNextTrackError:\n return _('No next track')\n except errors.NothingIsPlayingError:\n return _('Nothing is playing')\n\n\nclass PreviousTrackCommand(Command):\n @property\n def help(self):\n return _('Plays previous track')\n\n def __call__(self, arg, user):\n try:\n self.player.previous()\n return _('Playing {}').format(self.player.track.name)\n except errors.NoPreviousTrackError:\n return _('No previous track')\n except errors.NothingIsPlayingError:\n return _('Nothing is playing')\n\n\nclass ModeCommand(Command):\n def __init__(self, command_processor):\n super().__init__(command_processor)\n self.mode_names = {Mode.SingleTrack: _('Single Track'), Mode.RepeatTrack: _('Repeat Track'), Mode.TrackList: _('Track list'), Mode.RepeatTrackList: _('Repeat track list'), Mode.Random: _('Random')}\n\n @property\n def help(self):\n return _('MODE Sets the playback mode. If no mode is specified, the current mode and a list of modes are displayed')\n\n def __call__(self, arg, user):\n mode_help = _(\"Current mode: {current_mode}\\n{modes}\").format(current_mode=self.mode_names[self.player.mode], modes='\\n'.join(['{value} {name}'.format(name=self.mode_names[i], value=i.value) for i in Mode.__members__.values()]))\n if arg:\n try:\n mode = Mode(arg.lower())\n if mode == Mode .Random:\n self.player.shuffle(True)\n if self.player.mode == Mode.Random and mode != Mode.Random:\n self.player.shuffle(False)\n self.player.mode = Mode(mode)\n return _(\"Current mode: {mode}\").format(mode=self.mode_names[self.player.mode])\n except ValueError:\n return 'Incorrect mode\\n' + mode_help\n else:\n return mode_help\n\n\nclass ServiceCommand(Command):\n @property\n def help(self):\n return _('SERVICE Selects the service to play from. If no service is specified, the current service and a list of available services are displayed')\n\n def __call__(self, arg, user):\n service_help = _('Current service: {current_service}\\nAvailable: {available_services}').format(current_service=self.service_manager.service.name, available_services=', '.join([i for i in self.service_manager.available_services if not self.service_manager.available_services[i].hidden]))\n if arg:\n arg = arg.lower()\n if arg in self.service_manager.available_services and not self.service_manager.available_services[arg].hidden:\n self.service_manager.service = self.service_manager.available_services[arg]\n return _('Current service: {}').format(self.service_manager.service.name)\n else:\n return _('Unknown service.\\n{}').format(service_help)\n else:\n return service_help\n\n\nclass SelectTrackCommand(Command):\n @property\n def help(self):\n return _('NUMBER Selects track by number from the list of current results')\n\n def __call__(self, arg, user):\n if arg:\n try:\n number = int(arg)\n if number > 0:\n index = number - 1\n elif number < 0:\n index = number\n else:\n return _('Incorrect number')\n self.player.play_by_index(index)\n return _('Playing {} {}').format(arg, self.player.track.name)\n except errors.IncorrectTrackIndexError:\n return _('Out of list')\n except errors.NothingIsPlayingError:\n return _('Nothing is playing')\n except ValueError:\n raise errors.InvalidArgumentError\n else:\n if self.player.state != State.Stopped:\n return _('Playing {} {}').format(self.player.track_index + 1, self.player.track.name)\n else:\n return _('Nothing is playing')\n\n\nclass SpeedCommand(Command):\n @property\n def help(self):\n return _(\"SPEED Sets playback speed from 0.25 to 4. If no speed is given, shows current speed\")\n\n def __call__(self, arg, user):\n if not arg:\n return _(\"Current rate: {}\").format(str(self.player.get_speed()))\n else:\n try:\n self.player.set_speed(float(arg))\n except ValueError:\n raise errors.InvalidArgumentError()\n\n\nclass FavoritesCommand(Command):\n @property\n def help(self):\n return _('+/-NUMBER Manages favorite tracks. + adds the current track to favorites. - removes a track requested from favorites. If a number is specified after +/-, adds/removes a track with that number')\n\n def __call__(self, arg, user):\n if user.username == '':\n return _('This command is not available for guest users')\n if arg:\n if arg[0] == '+':\n return self._add(user)\n elif arg[0] == '-':\n return self._del(arg, user)\n else:\n return self._play(arg, user)\n else:\n return self._list(user)\n\n def _add(self, user):\n if self.player.state != State.Stopped:\n if user.username in self.cache.favorites:\n self.cache.favorites[user.username].append(self.player.track.get_raw())\n else:\n self.cache.favorites[user.username] = [self.player.track.get_raw()]\n self.cache.save()\n return _('Added')\n else:\n return _('Nothing is playing')\n\n def _del(self, arg, user):\n if (self.player.state != State.Stopped and len(arg) == 1) or len(arg) > 1:\n try:\n if len(arg) == 1:\n self.cache.favorites[user.username].remove(self.player.track)\n else:\n del self.cache.favorites[user.username][int(arg[1::]) - 1]\n self.cache.save()\n return _('Deleted')\n except IndexError:\n return _('Out of list')\n except ValueError:\n if not arg[1::].isdigit:\n return self.help\n return _('This track is not in favorites')\n else:\n return _('Nothing is playing')\n\n def _list(self, user):\n track_names = []\n try:\n for number, track in enumerate(self.cache.favorites[user.username]):\n track_names.append('{number}: {track_name}'.format(number=number + 1, track_name=track.name if track.name else track.url))\n except KeyError:\n pass\n if len(track_names) > 0:\n return '\\n'.join(track_names)\n else:\n return _('The list is empty')\n\n def _play(self, arg, user):\n try:\n self.player.play(self.cache.favorites[user.username], start_track_index=int(arg) - 1)\n except ValueError:\n return self.help\n except IndexError:\n return _('Out of list')\n except KeyError:\n return _('The list is empty')\n\n\nclass GetLinkCommand(Command):\n @property\n def help(self):\n return _('Gets a direct link to the current track')\n\n def __call__(self, arg, user):\n if self.player.state != State.Stopped:\n url = self.player.track.url\n if url:\n if self.config[\"shortening\"][\"shorten_links\"]:\n shortener = Shortener()\n url = shortener.clckru.short(url)\n return url\n else:\n return _('URL is not available')\n else:\n return _('Nothing is playing')\n\n\nclass RecentsCommand(Command):\n @property\n def help(self):\n return _('NUMBER Plays a track with the given number from a list of recent tracks. Without a number shows recent tracks')\n\n def __call__(self, arg, user):\n if arg:\n try:\n self.player.play(list(reversed(list(self.cache.recents))), start_track_index=int(arg) - 1)\n except ValueError:\n raise errors.InvalidArgumentError()\n except IndexError:\n return _('Out of list')\n else:\n track_names = []\n for number, track in enumerate(reversed(self.cache.recents)):\n if track.name:\n track_names.append(f'{number + 1}: {track.name}')\n else:\n track_names.append(f'{number + 1}: {track.url}')\n return '\\n'.join(track_names) if track_names else _('The list is empty')\n\n\nclass DownloadCommand(Command):\n @property\n def help(self):\n return _(\"Downloads the current track and uploads it to the channel\")\n\n def __call__(self, arg, user):\n if not (self.ttclient.user.user_account.rights & UserRight.UploadFiles == UserRight.UploadFiles):\n raise PermissionError(_(\"Cannot upload file to channel\"))\n if self.player.state != State.Stopped:\n track = self.player.track\n if track.url and (track.type == TrackType.Default or track.type == TrackType.Local):\n self.module_manager.downloader(self.player.track, user)\n return _(\"Downloading...\")\n else:\n return _('Live streams cannot be downloaded')\n else:\n return _('Nothing is playing')\n","sub_path":"bot/commands/user_commands.py","file_name":"user_commands.py","file_ext":"py","file_size_in_byte":14473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"319085225","text":"from rlserver import RLServer\nimport multiprocessing as mp\nimport subprocess as sp\n\nif __name__ == \"__main__\":\n\n corecode = [\"0x1\", \"0x2\", \"0x4\", \"0x8\", \"0x10\", \"0x20\", \"0x40\", \"0x80\"]\n port = 8000\n pool = mp.Pool(processes = mp.cpu_count())\n\n for i in range(mp.cpu_count() - 1):\n server = RLServer(port + i, 640, 480, 3)\n pool.apply_async(server, ({i},))\n sp.Popen([\"taskset\", corecode[mp.cpu_count()-1], \"/opt/torcs/bin/torcs\",\"-r\",\"/home/aitor/practice.xml\",\"-p\",str(port + i)])\n\n pool.close()\n pool.join()\n","sub_path":"runrlserver.py","file_name":"runrlserver.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39188260","text":"while True:\n string = input()\n\n if string == '*':\n break\n\n dataSplit = string.split(\" \")\n flag = 0\n if len(dataSplit) == 1:\n flag = 1\n \n else:\n\n for i in range(len(dataSplit)-1):\n if (dataSplit[0][:1].lower() == dataSplit[i+1][:1].lower() and dataSplit[0][:1].lower()):\n flag = 1\n else: \n flag = 0\n break\n\n # print(flag)\n \n if flag == 1:\n print(\"Y\", end='\\n')\n else: \n print(\"N\", end='\\n')\n","sub_path":"python/1140.py","file_name":"1140.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411869279","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\n\nfrom commons import logger, cache, get_func_name\nfrom feature_engineering import train_size, y, train_X, test_X, test_id_col\nfrom sklearn.cross_validation import KFold, ShuffleSplit\n\nnp.random.seed(0)\ninds_2000 = np.random.choice(range(train_size), 2000, False)\ntrain_1000 = inds_2000[:1000]\ntest_1000 = inds_2000[1000:]\n\nnp.random.seed(0)\ninds_20000 = np.random.choice(range(train_size), 20000, False)\ntrain_10000 = inds_20000[:10000]\ntest_10000 = inds_20000[10000:]\n\n@cache\ndef fit_model(model_fun, X, y, feats):\n model = model_fun()\n logger.info(\"fitting %s with feat extractor %s on %s examples\" \n % (model, feats, len(y)))\n model.fit(X, y)\n logger.info(\"DONE fitting %s with feat extractor %s on %s examples\" \n % (model, feats, len(y)))\n return model\n\ndef benchmark(model_fun, feature_extractor, train_inds, test_inds):\n X = feature_extractor()\n if type(X) == dict:\n X_train = {}\n for k, v in X.items():\n X_train[k] = v[train_inds]\n X_train = {k: v[train_inds] for k, v in X.items()}\n X_test = {k: v[test_inds] for k, v in X.items()}\n else:\n X_train = X[train_inds]\n X_test = X[test_inds]\n y_train = y[train_inds]\n y_test = y[test_inds]\n\n model = fit_model(model_fun, X_train, y_train, get_func_name(feature_extractor))\n #model.fit(X_train, y_train)\n\n return np.sqrt(mean_squared_error(model.predict(X_test), y_test))\n \ndef tiny_benchmark(model_fun, feature_extractor):\n return benchmark(model_fun, feature_extractor, train_1000, test_1000)\n\ndef small_benchmark(model_fun, feature_extractor):\n return benchmark(model_fun, feature_extractor, train_10000, test_10000)\n\ndef full_cv(model_fun, feature_extractor, folds=4, return_all_folds=False):\n results = []\n for i, (train_index, test_index) in enumerate(KFold(n=train_size, n_folds=folds, shuffle=True, random_state=0)):\n logger.info(\"benchmarking fold %s\" % i)\n results.append(benchmark(model_fun, feature_extractor, train_index, test_index))\n if return_all_folds:\n return results\n else:\n return np.mean(results)\n\ndef benme(model_fun, fun, modelname=None, funname=None):\n # default benchmarking function\n if funname is None:\n funname = get_func_name(fun)\n if modelname is None:\n modelname = str(model)\n result = full_cv(model_fun, fun)\n logger.info(\"got score %.4f with model %s on feats %s\" % (result, modelname, funname)) \n \n\n\ndef make_submission(model_fun, feature_extractor, filename):\n fun_name = get_func_name(feature_extractor)\n logger.info(\"making submission with %s and %s\" % (model, fun_name))\n model = fit_model(model_fun, train_X(feature_extractor), y, fun_name)\n predictions = model.predict(test_X(feature_extractor))\n predictions = [min(max(p, 1), 3) for p in predictions]\n pd.DataFrame({'id': test_id_col, 'relevance': predictions}).to_csv(filename, index=False)\n logger.info(\"submission made\")\n \n \n \n ","sub_path":"home_depot/benchmarks.py","file_name":"benchmarks.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"144754297","text":"import math\nimport matplotlib.pyplot as plt\nimport numpy as np\nwhile True:\n def main ():\n Semimajoraxis = float(input(\"What is the semi major Axis (a)? \"))\n Period = 0.0\n eccentricity = float(input(\"What is the eccentricity of the orbit? \"))\n loopcount = int(input(\"How many iterations do you want?\"))\n #mu = float(input(\"What is the sum of the two masses? \"))\n mu = float(input(\"What is the value of mu? \"))\n n = 0.0 \n n = math.pow(mu, .5) * math.pow(Semimajoraxis, -1.5)\n print (\"n = \",n)\n Period = (2*math.pi)/n\n print (\"period = \",Period)\n trate = Period/(loopcount)\n print(\"a = \", Semimajoraxis, \" \", \"e = \", eccentricity, \" \", \"mu = \", mu, \" \", \"Period = \", Period, file = open(\"ephem.txt\", \"w\"))\n tlist = []\n rlist = []\n flist = []\n Elist = []\n xlist = []\n ylist = []\n for j in range(loopcount):\n t = 0.0\n t = trate*j\n #print('t = ',t)\n tlist.insert(0,t)\n M = 0.0\n M = n * (t)\n #print (\"M = \",M)\n #graphing M to find E\n x = np.arange(0, 4*(np.pi), 0.005)\n y = (x) - eccentricity*np.sin(x) - M\n plt.plot(x,y)\n #plt.show()\n #finds y intercepts\n E = 0.0\n xintercept = []\n for x, y in zip(x, y):\n if y < 0.01 and y > -0.01:\n #print(x, y)\n xintercept.insert(0,x)\n #print (xintercept)\n E = np.median(xintercept)\n #print('E = ', E)\n Elist.insert(0,E)\n r = 0.0\n r = Semimajoraxis * (1-eccentricity*math.cos(E))\n rlist.insert(0,r)\n #print (\"r = \", rlist[0])\n #finding fs\n f = 0.0\n C = 0.0\n B = 0.0\n C = math.sqrt((1 + eccentricity)/(1-eccentricity))\n B = C * math.tan(E/2)\n f = 2 * math.atan(B)\n if f<0:\n f = f+2*(np.pi)\n flist.insert(0,f)\n #print (\"angle from perihelion =\", flist[0])\n xvalue = 0.0\n xvalue = r * np.cos(f)\n xlist.insert(0,xvalue)\n y = 0.0\n y = r * np.sin(f)\n ylist.insert(0,y)\n #saves to a file\n print(tlist[0], \" \", flist[0], \" \", rlist[0], \" \", xlist[0], \" \", ylist[0], file = open(\"ephem.txt\", \"a\"))\n\n #creates table\n plt.figure(1)\n plt.subplot(211)\n plt.plot(tlist,rlist)\n plt.ylabel('radius')\n plt.xlabel('time')\n plt.subplot(212)\n plt.plot(tlist,flist)\n #completes the loop\n tlist.insert(0,tlist[loopcount-1])\n rlist.insert(0,rlist[loopcount-1])\n flist.insert(0,flist[loopcount-1])\n xlist.insert(0,xlist[loopcount-1])\n ylist.insert(0,ylist[loopcount-1])\n plt.figure(2)\n plt.plot(xlist,ylist)\n \n plt.figure(3)\n theta = np.linspace(0,2*np.pi, 360)\n r = (Semimajoraxis*(1-eccentricity**2))/(1+eccentricity*np.cos(theta))\n plt.polar(theta, r)\n \n plt.show()\n plt.show()\n\n if __name__== \"__main__\":\n \n main()\n \n answer = str(input('Run again? (y/n): '))\n if answer == 'y':\n continue\n else:\n print ('Goodbye')\n break\n \n# if answer in ('y', 'n'):\n # break\n #print ('Invalid input.')\n\n\n\n\n\n","sub_path":"EllipticalOrbitVersion2.py","file_name":"EllipticalOrbitVersion2.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211696246","text":"from __future__ import print_function\nfrom keras.models import Sequential\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nfrom keras.losses import kullback_leibler_divergence, mean_absolute_error\nimport numpy as np\nimport matplotlib\nimport time\nmatplotlib.use('Agg') # matplotlib likes to crash if you don't do this.\nimport matplotlib.pyplot as plt\nfrom NetworkArchitectures import digit_generator, digit_discriminator, make_gan\nfrom keras.datasets.mnist import load_data\nimport tensorflow as tf\n'''\nVarious Notes:\n1) 1 is the discriminator's output for a \"real\" image, 0 is the output for a \"synthetic\" image.\n2) The training code is very barebones - it has a fixed learning rate, and there's no real trick involved.\n'''\n\n\ndef grab_discriminator_samples(dataset, labels, samples, index, permutation, model):\n train_mixed_digits = np.zeros([samples,28,28,1])\n train_mixed_labels = np.zeros([samples,11])\n for j in range(0, samples):\n train_mixed_digits[j, :, :, :] = dataset[permutation[(index*samples) + j], :, :, :]\n for k in range(0,10):\n train_mixed_labels[j,k] = labels[permutation[(index*samples)+j],k]\n return train_mixed_digits, train_mixed_labels\n\n\ndef grab_discriminator_real_samples(dataset, labels, samples, index, permutation):\n train_mixed_digits = np.zeros([samples,28,28,1])\n train_mixed_labels = np.zeros([samples,11])\n for j in range(0, samples// 2):\n train_mixed_digits[j, :, :, :] = dataset[permutation[(index*samples) + j], :, :, :]\n for k in range(0,10):\n train_mixed_labels[j,k] = labels[permutation[(index*samples)+j],k]\n fakes = grab_generated_samples(samples//2, model)\n for j in range(samples//2, samples):\n train_mixed_digits[j, :, :, :] = fakes[j - samples//2, :, :, :]\n train_mixed_labels[j,:] = np.zeros([11])\n train_mixed_labels[j,10] = 1\n return train_mixed_digits, train_mixed_labels\n\n\ndef grab_discriminator_fake_samples(samples, model):\n train_mixed_digits = np.zeros([samples,28,28,1])\n train_mixed_labels = np.zeros([samples,11])\n fakes = grab_generated_samples(samples//2, model)\n for j in range(0, samples):\n train_mixed_digits[j, :, :, :] = fakes[j - samples//2, :, :, :]\n train_mixed_labels[j,:] = np.zeros([11])\n train_mixed_labels[j,10] = 1\n return train_mixed_digits, train_mixed_labels\n\ndef embedding(val):\n emb = np.zeros([10])\n emb[val] = 1\n return emb\n\n\ndef grab_generated_samples(samples, model):\n train_noise = 2 * np.random.random([samples, latent_dimension]) - 1\n train_digits = np.zeros([samples,10])\n for i in range(0,samples):\n train_digits[i,:] = embedding(np.random.randint(0,9))\n synth_images = model.predict([train_noise,train_digits])\n return synth_images\n\n# Load Models\nlatent_dimension = 256\nmodel = digit_generator(latent_dimension,10)\ndiscriminator = digit_discriminator(10)\n\n# Set Training Parameters\nbatch_size = 32\nepochs = 100\nlearnrate = 5e-4\nlearnrate_disc = 5e-5\nlabel_noise_level = 0.00\n\n# Load Data\n(train_images_raw, train_labels_raw), (test_images_raw, test_labels_raw) = load_data()\ntrain_size = train_labels_raw.shape[0]\ntrain_images = np.zeros([train_size,28,28,1])\ntrain_labels = np.zeros([train_size,10])\nfor i in range(0,train_size):\n train_images[i,:,:,0] = train_images_raw[i,:,:]/255.0\n train_labels[i,:] = embedding(train_labels_raw[i])\nnum_batches = train_size // batch_size\n\n\n# Show off a few basic examples (Comment code out once run once, for efficiency.)\n'''\nfor i in range(10):\n for j in range(10):\n plt.subplot(10,10,1+10*i+j)\n plt.axis('off')\n example_digits = train_images[train_labels_raw == i]\n plt.imshow(example_digits[j,:,:,0], cmap='gray')\nplt.savefig(\"images.png\")\n'''\n\n# Compile models.\ndiscriminator.compile(loss='categorical_crossentropy',optimizer=Adam(lr=learnrate_disc, decay=1e-6),metrics=['accuracy'])\n\n# Create GAN\ngan = make_gan(model,discriminator,latent_dimension,10)\n\ngan.compile(loss='categorical_crossentropy', optimizer=Adam(lr=learnrate, decay=1e-6),metrics=['accuracy'])\n# Train\ntrain_loss_disc = np.zeros(epochs)\ntest_loss_disc = np.zeros(epochs)\n\nfor epoch in range(epochs):\n #Train generator and discriminator simultaneously\n\n permutation = np.random.permutation(train_size)\n for i in range(num_batches):\n start = time.time()\n print(\"Epoch \" + str(epoch + 1) + \"/\" + str(epochs) + \": Batch \" +str(i+1) +\"/\" +str(num_batches))\n # Grab Real samples and Synthetic samples, for discriminator training\n# train_mixed_digits, train_mixed_labels = grab_discriminator_samples(train_images,train_labels,batch_size,i,permutation, model)\n train_fake_digits, train_fake_labels = grab_discriminator_fake_samples(batch_size//2,model)\n train_real_digits, train_real_labels = grab_discriminator_real_samples(train_images,train_labels,batch_size//2,i,permutation)\n #disc_mets = discriminator.train_on_batch(train_mixed_digits, train_mixed_labels)\n disc_mets_1 = discriminator.train_on_batch(train_fake_digits,train_fake_labels)\n disc_mets_2 = discriminator.train_on_batch(train_real_digits,train_real_labels)\n train_noise = 2 * np.random.random([batch_size, latent_dimension]) - 1\n digits = np.zeros([batch_size, 10])\n target_fool = np.zeros([batch_size,11])\n for j in range(0, batch_size):\n digits[j, :] = embedding(np.random.randint(0, 9))\n for k in range(0,10):\n target_fool[j,k] = digits[j,k]\n model_mets = gan.train_on_batch([train_noise,digits], target_fool)\n time_taken = time.time() - start\n print(\"Discriminator accuracy:\" +str(disc_mets_1[1]) + \"\\t Generator Fool Rate:\" + str(model_mets[1]) + \"\\t Estimated time per epoch:\" + str(int(time_taken * num_batches)) + \" seconds\")\n\n print(\"Discriminator loss:\" + '%.5f' % disc_mets_1[0] + \"\\t Generator loss:\" + str(model_mets[0]))\n\n print(\"Discriminator classification accuracy:\" + str(disc_mets_2[1]) + \"\\t Discriminator classification loss:\" + str(disc_mets_2[0]))\n ## Generate images for the given epoch\n for i in range(10):\n noise = 2 * np.random.random([10, latent_dimension]) - 1\n digit = np.zeros([10,10])\n for j in range(10):\n digit[j,:] = embedding(i)\n example_images = model.predict([noise,digit])\n for j in range(10):\n plt.subplot(10, 10, 1 + 10 * i + j)\n plt.axis('off')\n plt.imshow(example_images[j, :, :, 0], cmap='gray')\n plt.savefig(\"generated_images_epoch_\" + str(epoch) + \".png\")\n","sub_path":"MNISTBased(Old)/DigitGenerator/NetworkTraining.py","file_name":"NetworkTraining.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"41328461","text":"import torch.nn as nn\nimport torch.nn.functional as F\nfrom deform_cov import DeformConv2D\nfrom SE_block import *\nimport torch\n#单独通道注意力机制\nclass SEconvLSTM(nn.Module):\n def __init__(self, in_channel=1, out_channel=10):\n super(SEconvLSTM, self).__init__()\n self.hidden_dim = 10\n self.num_layers = 2\n\n self.conv1 = nn.Conv2d(in_channel, 64, kernel_size=3, padding=1)\n self.embed1 = nn.Sequential(\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True))\n self.se1 = SELayer(64, 16)\n\n self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)\n self.embed2 = nn.Sequential(\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True))\n self.se2 = SELayer(64, 16)\n\n self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)\n self.embed3 = nn.Sequential(\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True))\n self.se3 = SELayer(128, 16)\n\n self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding=1)\n self.embed4 = nn.Sequential(\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True))\n self.se4 = SELayer(128, 16)\n\n self.conv5 = nn.Conv2d(128, 128, kernel_size=3, padding=1)\n self.embed5 = nn.Sequential(\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True))\n self.se5 = SELayer(128, 16)\n\n self.conv6 = nn.Conv2d(128, 256, kernel_size=3, padding=1)\n self.embed6 = nn.Sequential(\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True))\n self.se6 = SELayer(256, 16)\n\n self.conv7 = nn.Conv2d(256, 256, kernel_size=3, padding=1)\n self.embed7 = nn.Sequential(\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True))\n self.se7 = SELayer(256, 16)\n\n self.conv8 = nn.Conv2d(256, 256, kernel_size=3, padding=1)\n self.embed8 = nn.Sequential(\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True))\n self.se8 = SELayer(256, 16)\n\n self.bilstm = nn.LSTM(9, self.hidden_dim,\n num_layers=self.num_layers, bidirectional=False,\n batch_first=True, bias=False)\n\n self.hidden2label1 = nn.Sequential(nn.Linear(256 * self.hidden_dim, 400), nn.ReLU(),\n nn.Dropout())\n self.hidden2label2 = nn.Linear(400, out_channel)\n\n def forward(self, x):\n\n x = self.conv1(x)\n x = self.embed1(x)\n x = self.se1(x)\n\n x = self.conv2(x)\n x = self.embed2(x)\n x = F.max_pool2d(x, kernel_size=2, stride=2)\n x = self.se2(x)\n\n x = self.conv3(x)\n x = self.embed3(x)\n x = self.se3(x)\n\n x = self.conv4(x)\n x = self.embed4(x)\n x = self.se4(x)\n\n x = self.conv5(x)\n x = self.embed5(x)\n x = F.max_pool2d(x, kernel_size=2, stride=2)\n x = self.se5(x)\n\n x = self.conv6(x)\n x = self.embed6(x)\n x = self.se6(x)\n\n x = self.conv7(x)\n x = self.embed7(x)\n x = self.se7(x)\n\n x = self.conv8(x)\n x = self.embed8(x)\n x = F.max_pool2d(x, kernel_size=2, stride=2)\n x = self.se8(x)\n\n x = x.view(-1, 256, 9)\n\n bilstm_out, _ = self.bilstm(x)\n bilstm_out = torch.tanh(bilstm_out)\n bilstm_out = bilstm_out.view(bilstm_out.size(0), -1)\n logit = self.hidden2label1(bilstm_out)\n logit = self.hidden2label2(logit)\n\n return logit\n\n\n# net = convLSTM()\n#\n# from torchkeras import summary\n# import torch\n#\n# print(summary(net, input_shape=(1,24,24)))","sub_path":"DMACNN/SE.py","file_name":"SE.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"580330935","text":"import random\ndef coin_flip(user_prob):\n\t\twait = input()\n\t\tif wait == 'n':\n\t\t\tchoice = random.randint(1, user_prob)\n\t\t\tif choice == 1:\n\t\t\t\treturn \"T\"\n\t\t\telse:\n\t\t\t\treturn \"H\"\n\n\ndef no_wait_coin_fip():\n\tchoice = random.randint(1,2)\n\tif choice == 1:\n\t\treturn \"T\"\n\telse:\n\t\treturn \"H\"\n\n\ndef probability():\n\tuser_prob = 'a'\n\twhile not user_prob.isnumeric():\n\t\tuser_prob = input(\"Enter the probability of flipping heads: (ex: 5 means 5-1):\")\n\t\tif not user_prob.isnumeric():\n\t\t\tprint(\"Not an int, please try again.\")\n\t\telse:\n\t\t\tprint(coin_flip(int(user_prob)))\n\n\ndef fair_coin():\n\tflipped_list = []\n\tflip_times = 'a'\n\twhile not flip_times.isnumeric():\n\t\tflip_times = input(\"How many times do you want to flip the coin? \")\n\t\tif not flip_times.isnumeric():\n\t\t\tprint(\"Not an int, please try again.\")\n\t\telse:\n\t\t\tfor i in range(int(flip_times)):\n\t\t\t\tflipped_list.append(no_wait_coin_fip())\n\treturn flipped_list\n\n\nif __name__ == \"__main__\":\n\t#list = fair_coin()\n\t#print('The coin flipped heads ' + str(list.count('H')) + ' times')\n\t#print('The coin flipped tails ' + str(list.count('T')) + ' times')\n\tprobability()","sub_path":"Lab3/randomness.py","file_name":"randomness.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"262386639","text":"import requests\nimport time\nimport hashlib\nimport json\nimport os\n\n\n\ndef CreateSignature():\n apiKey = \"4dsv7koui930h1aagr5saqfq3p\"\n sharedSecret = \"d0r4gi4606t83\"\n timestamp = str(int(time.time()))\n hashValue = hashlib.sha512(apiKey.encode('utf-8') + sharedSecret.encode('utf-8') + timestamp.encode('utf-8')).hexdigest()\n authHeaderValue = \"EAN APIKey=\" + apiKey + \",Signature=\" + hashValue + \",timestamp=\" + timestamp\n return authHeaderValue\n\n\ndef CallExpediaService():\n url = \"https://api.ean.com/2.2/files/properties/catalog?language=en-US\"\n #$\"{_baseUrl}/2.2/files/properties/content?language=en-US\";\n headers = {\n 'Content-Type':'application/json',\n 'Accept':'application/json',\n 'Authorization':CreateSignature(),\n 'Customer-Session-Id':'Netactica-eb17-30f5-87b0-f09b75bd17e6',\n 'Accept-Encoding':'gzip, deflate',\n 'User-Agent':'Netactica/3.30.112'\n }\n result = requests.get(url=url, headers=headers)\n print(result.text)\n\n\nif __name__ == '__main__':\n CallExpediaService()\n","sub_path":"Pandas/ExpediaRapid/GetPropertiesFromRapid.py","file_name":"GetPropertiesFromRapid.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"204307283","text":"# Your code here\nwith open(\"robin.txt\") as f:\n\twords = f.read().lower()\n\ndef replaceMultiples(mainString, toBeReplaced, newString):\n\tfor elem in toBeReplaced :\n\t\tif elem in mainString :\n\t\t\tmainString = mainString.replace(elem, newString)\n\treturn mainString\n\ncache = {}\nall_words = words.split()\nwords_with_ignored = list(map(lambda st: replaceMultiples(st, ['\"', ':', ';', ',', '.', '-', '+', '=', '/', '\\\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&'], \"\"), all_words))\nwords_with_ignored.sort()\nfor word in words_with_ignored:\n\tif word not in cache:\n\t\tcache[word] = \"#\"\n\telse:\n\t\tcur_hash = cache[word]\n\t\tcur_hash = cur_hash+\"#\"\n\t\tcache[word] = cur_hash\n\nsorted_cache = {k: v for k, v in sorted(cache.items(), key=lambda item: item[1], reverse=True)}\n## Now we have our cache that is sorted by greatest used to least used.\nprint(\"\\n\".join(\"{0:<17}{1:<17}\".format(k, v) for k, v in sorted_cache.items()))\n","sub_path":"applications/histo/histo.py","file_name":"histo.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"483886780","text":"from django.shortcuts import render\r\nfrom django.template import loader,Context\r\nfrom django.http import HttpResponse\r\nfrom . import models\r\nfrom .forms import courier_form\r\nfrom django.http import *\r\n\r\n# Create your views here.\r\ndef index(request):\r\n template=loader.get_template('cms/index.html')\r\n\r\n context={\r\n 'hi':\"hi\",\r\n }\r\n return HttpResponse(template.render(context,request))\r\n\r\n\r\n\r\ndef cms(request):\r\n if request.method=='POST':\r\n form=courier_form(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return HttpResponseRedirect('/cms/')\r\n else:\r\n template=loader.get_template('cms/courier_form.html')\r\n form=courier_form()\r\n context={\r\n 'form':form,\r\n }\r\n return HttpResponse(template.render(context,request))\r\n\r\n\r\n\r\ndef list(request):\r\n couriers=models.courier.objects.all()\r\n template=loader.get_template('cms/list.html')\r\n context= {\r\n 'couriers':couriers,\r\n }\r\n return HttpResponse(template.render(context,request))\r\n","sub_path":"Courier_management/rss/cms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"29928341","text":"import urllib.request\nimport json\nfrom datetime import date\n\nday=date.today().day\nmonth=date.today().month\nyear=date.today().year\n\nnum = []\nnumtemp=[]\nnum_list=[]\nnum2=[]\nwhile True:\n try:\n if len(num)==0:\n print(\"Give 10 unique KINO numbers [1,80] and between them use space ' '\")\n num = input().split(\" \")\n else:\n if len(num)<10:\n x=10-len(num2)\n print(\"Give \", x ,\" unique KINO numbers [1,80] and between them use space ' '\")\n numtemp=input().split(\" \")\n numtemp=list(map(int,numtemp))\n num+=numtemp\n del numtemp[:]\n del num_list[:]\n num_list=list(map(int,num))\n for t in range(len(num_list)):\n if num_list[t] not in num2:\n num2.append(num_list[t])\n if len(num2)>10:\n dia=len(num2)-10\n for a in range(dia):\n del num2[-1]\n if len(num2)==10:\n counter=0\n for z in range(10):\n if int(num2[z])>=1 and int(num2[z])<=80:\n counter+=1\n else:\n num2[z]=0\n if counter==10:\n break\n else:\n for o in range(10-counter):\n num2.remove(0)\n del num[:]\n num=num2\n except (ValueError, TypeError):\n print(\"Wrong input...Try again\")\n del num[:]\n del num2[:]\n del numtemp[:]\n del num_list[:]\n\ndel num_list\nnum_list=num\nprint (\"Your numbers is \", num_list)\nday_win=[0]\n\nfor x in range(1, day+1):\n day_win.append(0)\n if x<10:\n d=\"0\"+str(x)\n else:\n d=str(x)\n if month<10:\n str_month=\"0\"+str(month)\n else:\n str_month=str(month)\n site = urllib.request.Request(\"http://applications.opap.gr/DrawsRestServices/kino/drawDate/\" + d + \"-\" + str_month + \"-\" + str(year) + \".json\")\n read_site = urllib.request.urlopen(site).read()\n data=json.loads(read_site.decode('utf-8'))\n last = len(data['draws']['draw'])\n for a in range(last):\n result = data['draws']['draw'][a]['results']\n o=0\n for i in range(10):\n if (num_list[i] in result):\n o+=1\n if o==4:\n counter=day_win.pop()\n counter+=1\n day_win.append(counter)\n break\n\n\nif max(day_win)==0:\n print(\"Your not lucky :-(\")\nelse:\n print(\"Most of the successes in this month's KINO will be on the day(s) \")\n for i in range(1, day + 1):\n if max(day_win) == day_win[i]:\n print(i)\n","sub_path":"askisi2.py","file_name":"askisi2.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"8077844","text":"import ConfigController\nimport AuditTrailController\nimport cx_Oracle\nimport traceback\nimport logging\nimport os\nfrom datetime import datetime\n#from subprocess import Popen, PIPE\n\nclass DBConnection:\n # Self Declaration\n def __init__(self):\n #print(\"welcome to DB-Connection class\")\n objSchemaPath = ConfigController.Configuration()\n self.ip = objSchemaPath.getConfiguration(\"Connection|ip\")\n self.port = objSchemaPath.getConfiguration(\"Connection|port\")\n self.SERVICE_NAME = objSchemaPath.getConfiguration(\"Connection|SID\")\n self.BASE_SQL_DIR = objSchemaPath.getConfiguration(\"SQL|sql_path\")\n self.DB_ORA_USER = os.environ['DB_ORA_USER']\n self.DB_ORA_PWD = os.environ['DB_ORA_PWD']\n nt_ora_conn = self.DB_ORA_USER + \"/\" + self.DB_ORA_PWD + \"@\" + self.ip + \":\" + self.port + \"/\" + self.SERVICE_NAME\n self.conn = nt_ora_conn\n\n def fn_format_json_timestamp(self, json_timestamp, type):\n if json_timestamp.find('.') > -1:\n ip_timestamp = datetime.strptime(json_timestamp, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n\n if type == 'DATE':\n op_timestamp = ip_timestamp.strftime(\"%Y-%m-%d\")\n else:\n op_timestamp = ip_timestamp.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3]\n\n return op_timestamp\n else:\n ip_timestamp = datetime.strptime(json_timestamp, \"%Y-%m-%dT%H:%M:%SZ\")\n\n if type == 'DATE':\n op_timestamp = ip_timestamp.strftime(\"%Y-%m-%d\")\n else:\n op_timestamp = ip_timestamp.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n return op_timestamp\n\n\n\n # function that takes the sqlCommand and connectString and returns the queryReslut and errorMessage (if any)\n #def fn_del_run_sql_script(self, filePath):\n # #try:\n # conn_str = self.conn\n # sqlplus = Popen(['sqlplus', '-S', conn_str], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n # sqlplus.stdin.write('@' + filePath)\n # return sqlplus.communicate()\n\n # function that takes the sqlCommand and connectString and returns the query result and errorMessage (if any)\n def fn_run_sql_script(self, eventId, domainName, filePath, msg_offset, msg_partition):\n objAuditController = AuditTrailController.AuditTrail()\n #dbreturn = 'F'\n safeDir = self.BASE_SQL_DIR\n if os.path.commonprefix([filePath, safeDir]) != safeDir:\n print(\"Bad request\")\n dbreturn = 'E'\n else:\n dbINConn = self.create_connection(self.conn)\n dbINConn.autocommit = False\n cursor = dbINConn.cursor()\n Sqlfl = open(filePath)\n full_sql = Sqlfl.read()\n #full_sql_new = full_sql[:-1]\n sql_commands = full_sql.split('|')\n InsCnt = len(sql_commands)\n len_error = 0\n #Loop start\n for sql_command in sql_commands:\n try:\n cursor.execute(sql_command)\n except Exception as e:\n print(e)\n print(\"Error sql :\" + sql_command)\n len_error = len(str(e))\n #logging.error(traceback.format_exc())\n End_st_f0 = \"Data Insertion Fail. Please check the Log file\" + '\\n' + \"Error : \" + str(e)\n End_tab_f0 = 'R'\n objAuditController.fn_AuditTrailInsertProcess(eventId, domainName, End_st_f0, End_tab_f0, '0', msg_offset, msg_partition)\n # Logs the error appropriately.\n break\n\n print(len_error)\n if (len_error) > 0:\n dbINConn.rollback\n dbreturn = 'E'\n else:\n dbINConn.commit()\n dbreturn = str(InsCnt - 1)\n\n self.close_connection(dbINConn, cursor)\n\n return dbreturn\n\n\n # SQL Query addition in .sql file\n def fn_sql_file_append(self, fileObj, str_query):\n try:\n print(str_query)\n fileObj.write(str_query)\n except Exception as e:\n print(e)\n logging.error(traceback.format_exc())\n # Logs the error appropriately.\n\n return None\n\n # Create column value based on oracle data type for Insert query\n def fn_col_val_gen(self, coloumn_value, coloumn_datatype):\n\n \"\"\" This function is intended to create column value based on column data type\n :param:col_val: column value\n :param:col_datatype: Data type of the column(Oracle)\n :return: string object\n \"\"\"\n date_format = 'YYYY-MM-DD'\n Timestamp_Format = \"RRRR-MM-DD HH24:MI:SS.FF\"\n coloumn_value_final = ''\n\n if coloumn_value == \"NULL\":\n coloumn_value_final = 'NULL'\n elif coloumn_value == \"None\":\n coloumn_value_final = 'NULL'\n elif coloumn_value == \"Null\":\n coloumn_value_final = 'NULL'\n elif coloumn_value == \"null\":\n coloumn_value_final = 'NULL'\n elif str.upper(coloumn_value) == str(\"NULL\"):\n coloumn_value_final = 'NULL'\n elif coloumn_value == '':\n coloumn_value_final = 'NULL'\n elif coloumn_value == \"\":\n coloumn_value_final = 'NULL'\n elif coloumn_value == ' ':\n coloumn_value_final = 'NULL'\n elif coloumn_value == \" \":\n coloumn_value_final = 'NULL'\n elif len(coloumn_value) == 0:\n coloumn_value_final = 'NULL'\n else:\n if coloumn_datatype == \"VARCHAR2\":\n coloumn_value_final = \"q'[\" + coloumn_value + \"]'\"\n elif coloumn_datatype == \"CHAR\":\n if str.upper(coloumn_value) == \"TRUE\" or coloumn_value == \"T\" or str.upper(coloumn_value) == \"YES\" or coloumn_value == \"Y\":\n Col_val = \"Y\"\n elif str.upper(coloumn_value) == \"FALSE\" or coloumn_value == \"F\" or str.upper(coloumn_value) == \"NO\" or coloumn_value == \"N\":\n Col_val = \"N\"\n else:\n Col_val = coloumn_value\n coloumn_value_final = \"q'[\" + Col_val + \"]'\"\n elif coloumn_datatype == \"CLOB\":\n coloumn_value_final = \"q'[\" + coloumn_value + \"]'\"\n elif coloumn_datatype == \"NUMBER\":\n #print(coloumn_value)\n if str(coloumn_value).find(\"e\") > -1 or str(coloumn_value).find(\"E\") > -1:\n col_val = \"{:.2f}\".format(float(coloumn_value))\n coloumn_value_final = \"TO_NUMBER('\" + str(col_val) + \"')\"\n else:\n coloumn_value_final = \"TO_NUMBER('\" + coloumn_value + \"')\"\n elif coloumn_datatype == \"DATE\":\n coloumn_value_final = \"TO_DATE('\" + self.fn_format_json_timestamp(coloumn_value, 'DATE') + \"', '\" + date_format + \"')\"\n elif coloumn_datatype == \"TIMESTAMP\":\n coloumn_value_final = \"TO_TIMESTAMP('\" + self.fn_format_json_timestamp(coloumn_value, 'TIMESTAMP') + \"', '\" + Timestamp_Format + \"')\"\n else:\n print(\"Wrong column Data Type mentioned in metadata.\")\n\n return coloumn_value_final\n\n # Create Insert statement for adding in .sql file\n def fn_str_insert_records(self, tableName, insertStr, strtCollist, fileObj):\n \"\"\" This routine is intended to\n insert records in the database table\n :param tableName: target table name\n :param insertStr: values to be inserted (as comma separated string input) to the target table_name\n :param strtCollist: Column List of the target database table.\n :return:None\n \"\"\"\n try:\n ins_header = 'BEGIN'\n ins_footer1 = 'EXCEPTION WHEN DUP_VAL_ON_INDEX THEN NULL;'\n ins_footer2 = 'END;'\n\n val = \"\"\n ins_flag = 'F'\n\n val_cnt = int(int(insertStr.count(\"|\")) - 1)\n val_chk = insertStr.split(\"|\")\n for i in range(len(val_chk)):\n if i < val_cnt:\n if len(str(val_chk[i])) == 0:\n ins_flag = \"T\"\n elif str(val_chk[i]).strip() == \"None\":\n ins_flag = \"T\"\n elif str(val_chk[i]) == \"None \":\n ins_flag = \"T\"\n elif str(val_chk[i]) == \"NULL\":\n ins_flag = \"T\"\n else:\n ins_flag = \"F\"\n break\n\n #print(ins_flag)\n if ins_flag == \"F\":\n str_insertVal = insertStr.split(\"|\")\n for i in range(len(str_insertVal)):\n if len(str(str_insertVal[i])) == 0:\n val = val + \"NULL,\"\n elif str(str_insertVal[i]) == \"None\":\n val = val + \"NULL,\"\n elif str(str_insertVal[i]) == \"None \":\n val = val + \"NULL,\"\n elif str(str_insertVal[i]).strip() == \"None\":\n val = val + \"NULL,\"\n elif str(str_insertVal[i]) == \"NULL\":\n val = val + \"NULL,\"\n else:\n val = val + str_insertVal[i] + \",\"\n\n val = val[:-1]\n # modifying insert string as a parameterised query\n #str_insertIn = \"INSERT INTO \" + tableName + \"(\" + strtCollist + \")\" + \" VALUES (\" + val + \")\" + ';\\n'\n str_insertIn = \"INSERT INTO {} ({}) VALUES ({}) \".format(tableName, strtCollist, val) + ';\\n'\n\n str_insertInto = '\\n' + ins_header + '\\n' + str_insertIn + ins_footer1 + '\\n' + ins_footer2 + '|\\n'\n\n self.fn_sql_file_append(fileObj, str_insertInto)\n else:\n print(\"All values fetched as NULL for the table \" + tableName)\n\n except Exception as e:\n print(e)\n logging.error(traceback.format_exc())\n # Logs the error appropriately.\n\n return None\n\n def fn_str_update_records(self, eventId, updkeyval, parentObj, upd_fields, updfileObj):\n \"\"\" This routine is intended to\n insert records in the database table\n :param tableName: target table name\n :param insertStr: values to be inserted (as comma separated string input) to the target table_name\n :param strtCollist: Column List of the target database table.\n :return:None\n \"\"\"\n try:\n upd_Table_Nm = str(upd_fields.split(\"~\")[0])\n upd_col_Nm = str(upd_fields.split(\"~\")[1])\n parent_attr = str(upd_fields.split(\"~\")[2])\n parent_col = str(upd_fields.split(\"~\")[3])\n\n if parent_attr in parentObj:\n parent_attr_val = str(parentObj[parent_attr])\n\n #str_where = \" WHERE BN_EVENT_ID = \" + \"'\" + eventId + \"'\" + \" AND \" + parent_col + \" = \" + \"'\" + parent_attr_val + \"'\"\n #str_update = \"UPDATE \" + upd_Table_Nm + \" SET \" + upd_col_Nm + \" = \" + updkeyval + str_where + \"|\\n\"\n\n # modifying update string as a parameterised query\n str_update = \"UPDATE {} SET {} = {} WHERE BN_EVENT_ID = '{}' and {} = '{}'\".format(upd_Table_Nm, upd_col_Nm, updkeyval, eventId, parent_col, parent_attr_val) + \"|\\n\"\n\n self.fn_sql_file_append(updfileObj, str_update)\n\n except Exception as e:\n print(e)\n logging.error(traceback.format_exc())\n # Logs the error appropriately.\n\n return None\n\n # Create Connection\n def create_connection(self, connStr):\n \n \"\"\" This routine is intended to create a database connection \n to the Oracle database specified by the connection string\n :param connstr: connection string\n :return: None\n \"\"\"\n try:\n conn = cx_Oracle.connect(connStr)\n return conn\n \n except cx_Oracle.Error as e:\n print(e)\n #return conn\n\n # Close open Connection\n def close_connection(self, conn, cur):\n\n \"\"\" This routine is intended to close a database connection\n specified by the conn\n :param conn: connection string\n :param cur: cursor object\n :return: None\n \"\"\"\n try:\n cur.close()\n conn.close()\n except conn.Error as e:\n print(e)\n\n return None\n\n def fn_db_insert(self, strInsert):\n\n \"\"\" This routine is intended to insert records into database table\n by executing all the queries run at a time\n :param:connStr: connection string given\n :param:strInsert: given insert string\n :return: None\n \"\"\"\n try:\n dbConn = self.create_connection(self.conn)\n cur = dbConn.cursor()\n cur.execute(strInsert)\n dbConn.commit()\n self.close_connection(dbConn, cur)\n\n except Exception as e:\n print(e)\n logging.error(traceback.format_exc())\n # Logs the error appropriately.\n\n return None\n\n def fn_fetch_record(self, strSelect):\n\n \"\"\" This routine is intended to insert records into database table\n by executing all the queries run at a time\n :param:connStr: connection string given\n :param:strInsert: given insert string\n :return: None\n \"\"\"\n try:\n connect = self.create_connection(self.conn)\n cursor = connect.cursor()\n cursor.execute(strSelect)\n records = cursor.fetchall()\n self.close_connection(connect, cursor)\n return records\n\n except Exception as e:\n print(e)\n logging.error(traceback.format_exc())\n # Logs the error appropriately.\n return None\n","sub_path":"SomTA_PythonParser_Dev/DBConnectionController/DBConnection.py","file_name":"DBConnection.py","file_ext":"py","file_size_in_byte":13845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"170317718","text":"#-------------------------------------------------------------------------------\n# Challenge 222E: Garland Words\n#-------------------------------------------------------------------------------\n\ndef garland(word):\n for i in range(1, len(word)):\n tail_index = word.find(word[0], i)\n tail = word[tail_index:]\n if word.startswith(tail):\n return len(tail), word\n return 0, word\n\n\ndef word_generator(path):\n with open(path) as f:\n for line in f:\n yield line.strip()\n\n\ndef look_for_the_greatest_degree(path):\n the_greatest = (0, None)\n for word in word_generator(path):\n o = garland(word)\n if o[0] > the_greatest[0]:\n the_greatest = o\n print(the_greatest)\n\ndef make_chain(word):\n garland_output = garland(word)\n degree = garland_output[0]\n if degree == 0:\n return\n word = garland_output[1]\n lev = len(word) - degree\n return word[:lev]*5 + word[:degree]\n\nword_list = [\"hehe\", \"onion\", \"programmer\", \"alfalfa\"]\n\nif __name__ == \"__main__\":\n print(\"-\"*20)\n print(\"#1 Run garland() with some words:\")\n for word in word_list:\n print(garland(word))\n print(\"-\"*10)\n print(\"#2 Given a garland word, print out the chain using that word:\")\n for word in word_list:\n print(make_chain(word))\n print(\"-\"*10)\n print(\"#3 Find the largest degree of any garland word in the enable1 English word list.\")\n look_for_the_greatest_degree(\"enable1.txt\")\n","sub_path":"223e.py","file_name":"223e.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185996107","text":"\"\"\"Function with subshells.\"\"\"\n\nimport textwrap\n\nfrom etest_test.fixtures_test.scripts_test import SCRIPTS\n\n_ = {\n \"uuid\": \"aed9113c97fd49f2b263b720d674c850\",\n \"description\": \"function with subshells\",\n \"text\": textwrap.dedent(\n \"\"\"\n src_configure() {\n econf \\\n $(use_enable python) \\\n $(use_enable java)\n }\n \"\"\",\n ),\n \"symbols\": {},\n \"correct\": None,\n}\n\nSCRIPTS.setdefault(\"all\", []).append(_)\nSCRIPTS.setdefault(\"bash\", []).append(_)\n","sub_path":"etest_test/fixtures_test/scripts_test/aed9113c97fd49f2b263b720d674c850.py","file_name":"aed9113c97fd49f2b263b720d674c850.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"3480308","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.3'\n\nlong_description = open('README.txt').read()\nnew_in_this_version = open('changes/changes.txt').read()\nhistory = open('changes/history.txt').read()\n\nlong_description = \"%s\\n\\nNew in version %s:\\n\\n%s\\n\\nHistory:\\n\\n%s\" % (long_description,version,new_in_this_version,history)\n\nsetup(name='svndjango',\n version=version,\n description=\"automatic backup of django model instances to a subversion repository\",\n long_description=long_description,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python',\n 'Framework :: Django',\n ],\n keywords='',\n author='Ethan Jucovy',\n author_email='ejucovy@gmail.com',\n url='',\n license='GPL',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'sven',\n ],\n entry_points=\"\"\"\n \"\"\",\n )\n","sub_path":"pypi_install_script/svndjango-0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"416699555","text":"\"\"\"\n\n REV SOFTWARE CONFIDENTIAL\n\n [2013] - [2016] Rev Software, Inc.\n All Rights Reserved.\n\n NOTICE: All information contained herein is, and remains\n the property of Rev Software, Inc. and its suppliers,\n if any. The intellectual and technical concepts contained\n herein are proprietary to Rev Software, Inc.\n and its suppliers and may be covered by U.S. and Foreign Patents,\n patents in process, and are protected by trade secret or copyright law.\n Dissemination of this information or reproduction of this material\n is strictly forbidden unless prior written permission is obtained\n from Rev Software, Inc.\n\n\"\"\"\n\nimport paramiko.client\nimport paramiko\nimport select\nimport sys\nimport settings\nimport logging\nfrom nagios import Nagios\n\nlogger = logging.getLogger('Server')\nlogger.setLevel(logging.DEBUG)\n\n\nclass Server(object):\n\n def debug(self, msg):\n logger.debug(\"%s: %s\" % (self.server_name, msg))\n\n def info(self, msg):\n logger.info(\"%s: %s\" % (self.server_name, msg))\n\n def error(self, msg):\n logger.error(\"%s: %s\" % (self.server_name, msg))\n\n def fatal(self, msg):\n logger.fatal(\"%s: %s\" % (self.server_name, msg))\n\n def __init__(self, server_name):\n server_name = server_name.upper()\n if not server_name.endswith(\".%s\" % settings.DEFAULT_DOMAIN):\n server_name = \"%s.%s\" % (server_name, settings.DEFAULT_DOMAIN)\n\n self.server_name = server_name\n self.nagios_name = server_name.split(\".\")[0]\n\n self.debug(\"Server class initilized.\")\n# self.channels = list()\n self.connect()\n\n# def __del__(self):\n# for channel in self.channels:\n# print \"Closing some channel\"\n# channel.shutdown(2)\n\n def nagios_schedule_downtime(self):\n nagios = Nagios()\n nagios.schedule_downtime(self.nagios_name)\n\n def nagios_cancel_downtime(self):\n nagios = Nagios()\n nagios.cancel_downtime(self.nagios_name)\n\n def connect(self):\n self.ssh = paramiko.client.SSHClient()\n self.ssh.load_system_host_keys()\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.ssh.connect(\n self.server_name,\n timeout=settings.SSH_CONNECT_TIMEOUT_SECONDS\n )\n self.debug(\"SSH connected.\")\n# def get_channel(self):\n# transport = self.ssh.get_transport()\n# channel = transport.open_session()\n# channel.get_pty()\n# self.channels.append(channel)\n# return channel\n#\n# def streamline_command(self,command):\n# channel = self.get_channel()\n# channel.exec_command(command)\n# previous_out = str()\n# while True:\n# rl, wl, xl = select.select([channel],[],[],0.0)\n# if len(rl) > 0:\n# # Must be stdout\n# out = channel.recv(1024)\n# if len(out) == 0:\n# \"\"\" End of command execution \"\"\"\n# if len(previous_out) > 0:\n# yield(previous_out)\n# return\n# else:\n# \"\"\" Got output from server, stream out buffer\n# line by line until can't find an end of a line \"\"\"\n# out = previous_out + out\n# try:\n# while True:\n# idx = out.index(\"\\n\")\n# yield(out[0:idx])\n# out = out[idx+1:]\n# except ValueError:\n# \"\"\" Cutted line, needs more input from server \"\"\"\n# previous_out = out\n\n def upload_file(self, local_name, remote_name):\n self.info(\"Uploading %s to %s:%s\" % (\n local_name, self.server_name, remote_name\n ))\n local_file = open(local_name, \"r\")\n sftp = paramiko.SFTPClient.from_transport(self.ssh.get_transport())\n sftp.put(local_name, remote_name)\n local_file.close()\n\n def command(self, command):\n self.debug(\"Executing command \\\"%s\\\".\" % command)\n \"\"\" Setup channel and execute command \"\"\"\n transport = self.ssh.get_transport()\n channel = transport.open_session()\n channel.set_combine_stderr(0)\n channel.setblocking(0)\n channel.exec_command(command)\n\n \"\"\" Get output \"\"\"\n response_out = str()\n response_err = str()\n response_status = None\n\n while True:\n \"\"\" Pause until data is avaiable \"\"\"\n rl, wl, xl = select.select([channel], [], [], 0.0)\n\n \"\"\" Intermidiate data reading, for clearing\n buffer while the command still runs \"\"\"\n\n \"\"\" STDOUT \"\"\"\n while channel.recv_ready():\n response_out += channel.recv(1024)\n\n \"\"\" STDERR \"\"\"\n while channel.recv_stderr_ready():\n response_err += channel.recv_stderr(1024)\n\n \"\"\" If command finished, set blocking and\n read the rest of the output \"\"\"\n if channel.exit_status_ready():\n response_status = channel.recv_exit_status()\n channel.setblocking(1)\n\n \"\"\" STDOUT \"\"\"\n while True:\n new_out = channel.recv(1024)\n if len(new_out) == 0:\n break\n response_out += new_out\n\n \"\"\" STDERR \"\"\"\n while True:\n new_err = channel.recv_stderr(1024)\n if len(new_err) == 0:\n break\n response_err += new_err\n\n \"\"\" Return out, err, and status code \"\"\"\n return (response_out, response_err, response_status)\n\n\nif __name__ == \"__main__\":\n s = Server(\"localhost\")\n out, err, code = s.command(\"cat /tmp/somefile\")\n# print \"Out:\\n%s\" % out\n# print \"Err:\\n%s\" % err\n# print \"Code:%d\" % code\n sys.stdout.write(out)\n","sub_path":"code_dir/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"278052424","text":"# Función ConvertirABinario: Recibe un número entero y devuelve una cadena de\n# caracteres con la representación binaria del número.\n# Parámetros de entrada: Número entero a convertir\n# Dato devuelto: Cadena de caracteres con el número binario\n\ndef ConvertirABinario(decimal):\n binario = \"\"\n # Realizo divisiones sucesivas entre 2 guardando el resto (1 o 0)\n while decimal>1:\n # Concatenamos en orden inverso los restos de la división entre 2.\n binario = str(decimal % 2) + binario\n decimal = decimal // 2\n binario = str(decimal) + binario\n return binario\n\n# Función ConvertirADecimal: Recibe una cadena de caracteres con la representación\n# de un número binario y devuelve el entero correspondiente.\n# Parámetros de entrada: Cadena de caracteres con el número binario\n# Dato devuelto: Entero\n\ndef ConvertirADecimal(binario):\n decimal = 0\n exponente = 1\n # Voy acumulando el valor de la cifra binario elevado a un exponente que\n #depende de su posición.\n # La última cifra hay que elevar al exponete 1, la siguiente 2, la siguiente\n # 4, y así sucesivamente.\n for caracter in binario[::-1]:\n if caracter == \"1\":\n decimal = decimal + exponente\n\t\t# El exponente se va doblando en cada iteración\n exponente = exponente * 2\n return decimal\n\n# Función EsBinario: Recibe una cadena de caracteres con la representación\n# de un número binario y devuelve un valor lógico indicando si realmente es un\n# número binario (Tienes 1 y 0) verdadero, y falso en caso contrario.\n# Parámetros de entrada: Cadena de caracteres con el número binario\n# Dato devuelto: Valor lógico\n\ndef EsBinario(binario):\n for caracter in binario:\n if caracter not in [\"1\",\"0\"]:\n return False\n return True\n\n# Crea un programa principal que permita convertir de decimal a binario y de\n# binario a decimal.\n\ndecimal = int(input(\"Dime un número decimal:\"))\nprint(\"Número binario:\",ConvertirABinario(decimal))\nwhile True:\n binario = input(\"Dime un número en binario:\")\n if EsBinario(binario):\n break\nprint(\"Número decimal:\",ConvertirADecimal(binario))\n","sub_path":"ejercicios/mas_ejercicios/ejercicio5.py","file_name":"ejercicio5.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"137342006","text":"\n'''\nMain PyMicroCT functions (run_analysis, vertebral_profiles and vertebral_angles) are here.\n'''\n\n# Python modules:\nimport os, cv2, pydicom, time, pickle, sys, glob\nimport numpy as np\nfrom datetime import date\nfrom scipy.interpolate import interp1d\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Custom modules:\nimport dicom # Custom module to bundle several .dcm files into one 3D numpy array.\nimport utilities as utils\nimport roi\nimport symmetry as sym\nfrom cython_code import cyutils\n\n\ndef run_analysis(session, mouse, datapath='/mnt/data/DATA_SSPO', struct='SPINE'):\n\n # Change default string for arg datapath depending on dataset:\n # datapath='/mnt/data/DATA_SSPO' for SSPO mice.\n # datapath='/mnt/data/DATA_MICROCT' for POC5 mice.\n\n # For debug:\n # datapath='/mnt/data/DATA_SSPO'\n # struct='SPINE'\n # session='SSPO_cohort-1_SPINE'\n # mouse='Mouse_53-2_Colonne'\n\n ''' Step 1: define paths '''\n\n subj_path = os.path.join(datapath, struct, session, mouse) # Animal directory.\n data_path = os.path.join(subj_path, 'data') # Location of DICOM (.dcm) file(s).\n if not os.path.exists(data_path):\n sys.exit('No data folder in ' + subj_path + '.')\n analysis_path = os.path.join(subj_path, 'analysis') # Where pmct will store its files.\n im_path = os.path.join(analysis_path, 'images') # Where pmct will store images.\n if not os.path.exists(im_path):\n os.makedirs(im_path)\n roi_path = os.path.join(analysis_path, 'rois') # Where pmct will store roi information.\n if not os.path.exists(roi_path):\n os.makedirs(roi_path)\n\n ''' Step 2: obtain 3D array and voxel info from .dcm file(s) '''\n\n dcm_files = glob.glob(data_path + '/*.dcm') # Looking for .dcm files in data folder.\n ndcm = len(dcm_files) # Number of .dcm files.\n\n if ndcm == 0: # Case .dcm file(s) missing.\n sys.exit('No .dcm file in ' + data_path + '.')\n\n if ndcm > 1: # Case several .dcm files.\n # Assuming data folder contains .dcm files with incremented names, belonging to same stack, e.g.:\n # mouseXXX_sessionYY_0001.dcm\n # mouseXXX_sessionYY_0002.dcm\n # ...\n # mouseXXX_sessionYY_0512.dcm\n # Using package dicom to read file.\n # Tested with .dcm files obtained with a Micro-CT Quantum FX (Perkin Elmer).\n\n # For debug:\n # data_path = '/mnt/data/DATA_MICROCT/SPINE/20190724_SPINE/BY927_23_Colonne_164250/data'\n\n arr3d_float32, voxel_spacing = dicom.load_stack(data_path) # Usually a 3D array of floats.\n\n if ndcm == 1: # Case one dcm file.\n # Assuming data folder has one .dcm file containing a stack of images.\n # Using package pydicom to read file.\n # Assuming file is built using the official DICOM Standard.\n # Useful information here: https://pydicom.github.io/pydicom/stable/tutorials/dataset_basics.html\n # Tested with a .dcm stack exported via Amide from data obtained using an Albira system (Bruker).\n\n # For debug:\n # src_dir = '/mnt/data/DATA_SSPO/SPINE/example_session_SPINE/example_mouse_Colonne/data/export_windows.dcm'\n\n data = pydicom.dcmread(dcm_files[0])\n # data.NumberOfSlices\n voxel_spacing = (float(data.SliceThickness),float(data.PixelSpacing[0]),float(data.PixelSpacing[1])) # voxel size in mm.\n arr = data.pixel_array\n arr3d_float32 = np.float32(arr)\n\n arr3d_8 = utils.imRescale2uint8(arr3d_float32) # Scale [min max] to [0 255] (i.e. convert to 8 bit).\n\n # The stack has (should have) the following dimensions:\n # Dimension 0 (X): rostro-caudal direction.\n # -> slices along dimension 0 are coronal slices (index 0 = most rostral slice).\n # Dimension 1 (Y): dorso-ventral direction.\n # -> slices along dimension 1 are transverse slices (index 0 = most dorsal pixel).\n # Dimension 2 (Z): medio-lateral axis.\n # -> slices along dimension 2 are (para)sagittal slices (index 0 = right side of animal).\n\n # Main assumption: when looking at transverse slices (top view), left of image is left of animal.\n # This assumptions sets the following right-handed reference frame:\n #\n # Y axis\n # (dorsal)\n # 0\n # |\n # (tail) arr.shape[0]-1 ------------ 0 (nose) X axis\n # |\n # arr.shape[1]-1\n # (ventral)\n #\n # Third axis (Z) along medio-lateral axis pointing toward observer (from LEFT to RIGHT).\n\n # Saving individual dicom images:\n # for i in range(512):\n # im = arr3d_8[:,:,i]\n # im = utils.imRescale2uint8(utils.imLevels(im, 10, 240))\n # cv2.imwrite('/mnt/data/DATA_SSPO/' + \"%03d\" % i + '.png',im)\n\n ''' Step 3: initialize class CustROI1 for working on rear and side views '''\n\n # Calculate rear view:\n # max projection along caudo-rostral axis, nose pointing away from observer;\n # the left of animal is on the left side of the resulting image.\n # Note the flip to obtain image in right orientation.\n im_rear = np.amax(arr3d_8, axis=0) # Projection along caudo-rostral axis (rear view).\n im_rear = utils.imRescale2uint8(utils.imLevels(im_rear,utils.imBackground(im_rear),255))\n cv2.imwrite(os.path.join(im_path, 'ORIGINAL_rear_view.png'), im_rear) # For illustration purposes.\n im_rear_rgb = cv2.merge(((im_rear,) * 3)) # Convert to RGB.\n # Dimensions of resulting 2D array:\n # Dimension 0 (rows): dorso-ventral direction (0 = most dorsal pixels).\n # Dimension 1 (columns): medio-lateral axis (0 = left side of animal, left side of image).\n # i.e.:\n # (left of animal, (0,0) ------------ (0,ncols) (right of animal,\n # dorsal) | | dorsal)\n # | |\n # (left of animal, | | (right of animal,\n # ventral) (nrows,0) -------- (nrows,ncols) ventral)\n\n # Calculate side view:\n # Note the transpose and flip steps to obtain image in proper orientation.\n im_side = np.flip(np.transpose(np.amax(arr3d_8, axis=2)), axis=1) # Projection (side view)\n im_side = utils.imRescale2uint8(utils.imLevels(im_side,utils.imBackground(im_side),255))\n cv2.imwrite(os.path.join(im_path, 'ORIGINAL_side_view.png'), im_side) # For illustration purposes.\n im_side_rgb = cv2.merge(((im_side,) * 3)) # Convert to RGB\n # Dimensions of resulting 2D array:\n # Dimension 0 (rows): dorso-ventral direction (0 = most dorsal pixels).\n # Dimension 1 (columns): caudo-rostral axis (0 = tail of animal, left of image).\n # i.e.:\n # (tail of animal, (0,0) ------------ (0,ncols) (nose of animal,\n # dorsal) | | dorsal)\n # | |\n # (tail of animal, | | (nose of animal,\n # ventral) (nrows,0) -------- (nrows,ncols) ventral)\n\n # Calculate top view (not used in CustROI1 but for illustration purposes):\n # Note the flip to bring the right of the animal on the right of the image.\n im_top = np.amax(arr3d_8, axis=1)\n im_top = utils.imRescale2uint8(utils.imLevels(im_top,utils.imBackground(im_top),255))\n cv2.imwrite(os.path.join(im_path, 'ORIGINAL_top_view.png'), im_top)\n # Dimensions of resulting 2D array:\n # Dimension 0 (rows): rostro-caudal direction (0 = toward nose).\n # Dimension 1 (columns): medio-lateral axis (0 = left of animal, left of image).\n # i.e.:\n # (left of animal, (0,0) -------- (0,ncols) (right of animal,\n # rostral) | | rostral)\n # | |\n # | |\n # | |\n # | |\n # (left of animal, | | (right of animal,\n # caudal) (nrows,0) ---- (nrows,ncols) ventral)\n\n # Build class CustROI1:\n im_rear_rgb_copy = im_rear_rgb.copy() # Copy used for drawing.\n roi1 = roi.CustROI1(imsrc_horiz=im_rear_rgb,\n msg_horiz='Draw mouse\\'s horizontal line (press \\'q\\' to escape)', fact_horiz=3,\n imsrc_rear=im_rear_rgb_copy,\n msg_rear='Draw mouse contour (press \\'q\\' to escape)', fact_rear=3,\n imsrc_side=im_side_rgb,\n msg_side='Draw spine contour (press \\'q\\' to escape)', fact_side=3)\n\n ''' Step 4: annotate rear and side views and apply rear mask '''\n\n # Draw horizontal line underneath mouse on rear view:\n roi1.tilt.horizontal_line()\n cv2.imwrite(os.path.join(im_path, 'ROI1_horiz_line.png'), roi1.tilt.im_resized)\n\n # Draw vertical line (= animal symetry line) on rear view:\n roi1.tilt.vertical_line()\n cv2.imwrite(os.path.join(im_path, 'ROI1_vert_line.png'), roi1.tilt.im_resized)\n\n # Draw mouse's contour on rear view to define rear mask.\n roi1.rear.drawpolygon()\n cv2.imwrite(os.path.join(im_path, 'ROI1_rear_roi.png'), roi1.rear.im)\n cv2.imwrite(os.path.join(im_path, 'ROI1_rear_mask.png'), roi1.rear.immask)\n\n # Draw contour of spine on side view to define side mask.\n roi1.side.drawpolygon()\n cv2.imwrite(os.path.join(im_path, 'ROI1_side_roi.png'), roi1.side.im)\n cv2.imwrite(os.path.join(im_path, 'ROI1_side_mask.png'), roi1.side.immask)\n\n # Apply rear mask on original 3d array:\n mask_rear = np.broadcast_to(roi1.rear.immask == 0, arr3d_float32.shape) # Compute rear mask.\n arr3d_float32_masked1 = np.ma.array(arr3d_float32, mask=mask_rear, fill_value=arr3d_float32.min()).filled()\n arr3d_8_masked1 = utils.imRescale2uint8(arr3d_float32_masked1) # Convert to uint8.\n\n # Save masked projections (for illustration purposes):\n im_rear_masked = np.amax(arr3d_8_masked1, axis=0)\n im_rear_masked = utils.imRescale2uint8(utils.imLevels(im_rear_masked,utils.imBackground(im_rear_masked),255))\n cv2.imwrite(os.path.join(im_path, 'MASKED_ROI1_rear_view.png'), im_rear_masked)\n im_side_masked = np.flip(np.transpose(np.amax(arr3d_8_masked1, axis=2)), axis=1)\n im_side_masked = utils.imRescale2uint8(utils.imLevels(im_side_masked,utils.imBackground(im_side_masked),255))\n cv2.imwrite(os.path.join(im_path, 'MASKED_ROI1_side_view.png'), im_side_masked)\n im_top_masked = np.amax(arr3d_8_masked1, axis=1)\n im_top_masked = utils.imRescale2uint8(utils.imLevels(im_top_masked,utils.imBackground(im_top_masked),255))\n cv2.imwrite(os.path.join(im_path, 'MASKED_ROI1_top_view.png'), im_top_masked)\n\n ''' Step 5: initialize class CustROI2 for working on top view '''\n\n im_top_masked_rgb = cv2.merge(((im_top_masked,) * 3)) # Convert to RGB (to draw color lines and points)\n roi2 = roi.CustROI2(imsrc_top = im_top_masked_rgb,\n msg_top = 'Draw spine axis (press \\'q\\' to escape)',\n fact_top = 3, width = (1,3))\n\n ''' Step 6: annotate top view and sequentially apply top and side masks '''\n\n # Draw position of L6 vertebrae:\n roi2.top.DrawL6()\n\n # Select reference points along spine; splines are drawn automatically:\n roi2.top.DrawSpline() # NOTE: reference points are in roi2.top.pts in resized coordinates.\n\n # Save images for illustration purposes:\n cv2.imwrite(os.path.join(im_path, 'ROI2_top_spline.png'), roi2.top.im)\n cv2.imwrite(os.path.join(im_path, 'ROI2_top_spline_mask.png'), roi2.top.immask)\n\n # Apply top mask on 3d array:\n # Note: the array is flipped and transposed before apply mask...\n # ...because of the mismatch between numpy and opencv (rows,columns) indexing.\n arr = np.transpose(np.flip(arr3d_float32_masked1, axis=1), (1, 0, 2)) # Necessary transformation to use np.broadcast\n mask_top = np.broadcast_to(roi2.top.immask == 0, arr.shape)\n arr3d_float32_masked2 = np.ma.array(arr, mask=mask_top, fill_value=arr3d_float32_masked1.min()).filled()\n arr3d_8_masked2 = utils.imRescale2uint8(arr3d_float32_masked2) # Convert to uint8.\n\n # Save top view obtained after applying top mask (for illustration purposes):\n im_top_masked2 = np.amax(arr3d_8_masked2, axis=0)\n im_top_masked2_vals = np.sort(np.unique(im_top_masked2.flatten()))\n minval = np.delete(im_top_masked2_vals,np.where(im_top_masked2_vals == 0)[0][0])[0]\n maxval = max(im_top_masked2_vals)\n im_top_masked2 = utils.imRescale2uint8(utils.imLevels(im_top_masked2,minval,maxval))\n cv2.imwrite(os.path.join(im_path, 'ROI2_top_view_masked.png'), im_top_masked2)\n\n # Apply side mask, so only the vertebrae are visible:\n # Note: again, flipping and transposing is necessary before applying mask.\n arr = np.transpose(np.flip(np.flip(arr3d_float32_masked2, axis=1), axis=0), (2, 0, 1))\n mask_side = np.broadcast_to(roi1.side.immask == 0, arr.shape)\n arr3d_float32_masked3 = np.ma.array(arr, mask=mask_side, fill_value=arr3d_float32_masked2.min()).filled()\n arr3d_8_masked3 = utils.imRescale2uint8(arr3d_float32_masked3) # Convert to uint8.\n\n # Compute and save side projection with both top and side masks applied:\n im_side_through_spine = np.amax(arr3d_8_masked3, axis=0)\n im_side_through_spine = utils.imRescale2uint8(utils.imLevels(im_side_through_spine,utils.imBackground(im_side_through_spine),255))\n cv2.imwrite(os.path.join(im_path, 'ROI2_side_through_spine.png'), im_side_through_spine)\n # Apply shapening kernel (which must equal to one eventually):\n kernel_sharpening = np.array([[-1, -1, -1],\n [-1, 9, -1],\n [-1, -1, -1]])\n im_side_through_spine_sharpened = cv2.filter2D(im_side_through_spine, -1, kernel_sharpening)\n cv2.imwrite(os.path.join(im_path, 'ROI2_side_through_spine_sharpened.png'), im_side_through_spine_sharpened)\n\n ''' Step 7: initialize CustROI3 for working on side view through spine '''\n\n im_side_through_spine_sharpened_rgb = cv2.merge(((im_side_through_spine_sharpened,) * 3))\n roi3 = roi.CustROI3(imsrc_side=im_side_through_spine_sharpened_rgb,\n msg_side='Draw limits of vertebrae (press \\'q\\' to escape)', fact_side=3,\n L6_position=im_side_through_spine_sharpened.shape[1]-1-roi2.top.L6_pos)\n\n ''' Step 8: draw limits of vertebrae on side projection '''\n\n roi3.side.DrawVertebrae()\n cv2.imwrite(os.path.join(im_path, 'ROI3_side_annotated.png'), roi3.side.im_resized)\n # NOTE: reference points are in roi3.side.pts in resized coordinates.\n\n ''' Step 9: compute 3D coordinates of vertebrae limits '''\n\n # Define coordinates of reference points drawn on top projection:\n pts_top_arr = np.array(roi2.top.pts)\n pts_top_arr_sorted = np.flip(pts_top_arr[np.argsort(pts_top_arr[:, 1])])\n pts_top_arr_sorted = -pts_top_arr_sorted\n pts_top_arr_sorted[:, 0] = pts_top_arr_sorted[:, 0] - pts_top_arr_sorted[0, 0]\n # in pts_top_arr_sorted, x is ascending caudo-rostral coordinate, y is ascending ML coordinate (from RIGHT to LEFT).\n # plt.plot(*pts_top_arr_sorted.T,'o')\n\n # Define coordinates of reference points drawn on side projection (vertebrae limits):\n pts_side_arr = np.array(roi3.side.pts)\n pts_side_arr_sorted = pts_side_arr[np.argsort(pts_side_arr[:, 0])]\n pts_side_arr_sorted[:, 1] = -pts_side_arr_sorted[:, 1] + arr3d_8.shape[1] * roi3.side.resize_factor\n # in pts_side_arr_sorted, x is ascending caudo-rostral coordinate, y is ascending ventro-dorsal coordinate\n # plt.plot(*pts_side_arr_sorted.T,'o')\n\n # Same for midpoints (center of vertebrae):\n midpts = np.array(roi3.side.midpnt)\n midpts_sorted = midpts[np.argsort(midpts[:, 0])]\n midpts_sorted[:, 1] = -midpts_sorted[:, 1] + arr3d_8.shape[1] * roi3.side.resize_factor\n # in midpts_sorted, x is ascending caudo-rostral coordinate, y is ascending ventro-dorsal coordinate\n # plt.plot(*midpts_sorted.T,'o')\n\n # Compute spline joining pts_top_arr_sorted\n x, y = pts_top_arr_sorted[:, 1], pts_top_arr_sorted[:, 0] # x: ascending ML coordinate (from RIGHT to LEFT); y: ascending caudo-rostral coordinate.\n f = interp1d(y, x, kind='cubic') # Compute spline function.\n\n # Control of result of spline interpolation:\n # ynew = np.linspace(np.min(y), np.max(y), num=500, endpoint=True)\n # spline_top = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n # plt.plot(*spline_top.T,'o')\n # In spline_top: x is ML coordinate from RIGHT to LEFT, y is ascending caudo-rostral coordinate,\n\n # Interpolation of vertebra limits (i.e. reference points) coordinate along media-lateral axis.\n ynew = pts_side_arr_sorted[:, 0] # ascending caudo-rostral coordinate.\n vlimits = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n vlimits[:, 0] = vlimits[:, 0] + arr3d_8.shape[1] * roi3.side.resize_factor\n # in vlimits: x is ascending RIGHT to LEFT coordinate, y is ascending caudo-rostral coordinate.\n # plt.plot(*vlimits.T,'o')\n\n # Interpolation of vertebrae midpoints coordinate along media-lateral axis.\n ynew = midpts_sorted[:, 0]\n center_v = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n center_v[:, 0] = center_v[:, 0] + arr3d_8.shape[1] * roi3.side.resize_factor\n # in center_v: x is ascending RIGHT to LEFT coordinate, y is ascending caudo-rostral coordinate.\n # plt.plot(*center_v.T,'o')\n\n ''' Step 10: save coordinates of vertebrae and params '''\n\n N_V_annotated = len(roi3.side.V_ID) # Number of vertebrae annotated.\n voxel_size = voxel_spacing[0] # Assuming voxel size is the same in all dimensions.\n\n # Save coordinates of vertebrae limits into file together with vertebrae ID.\n # The final reference frame is a bit different from the original one:\n # it is a right handed reference frame with:\n # - increasing x values along the caudo-rostral direction (positive x toward nose).\n # - increasing y values along the media-lateral axis with positive y toward left side.\n # - increasing z values along the ventro-dorsal axis with positive z toward dorsal side.\n with open(os.path.join(analysis_path, 'vertebrae_coordinates.txt'), 'w') as outfile:\n outfile.write(\"ID\\tx_cen\\ty_cen\\tz_cen\\tx_lim\\ty_lim\\tz_lim\\n\")\n for i in range(pts_side_arr_sorted.shape[0]-1):\n x_cen = (center_v[i, 1]/roi3.side.resize_factor)*voxel_size # Same as midpts_sorted[:, 0].\n y_cen = (center_v[i, 0]/roi3.side.resize_factor)*voxel_size # Interpolated with spline.\n z_cen = (midpts_sorted[i, 1]/roi3.side.resize_factor)*voxel_size # Ascending ventro-dorsal coordinate.\n x_lim = (pts_side_arr_sorted[i, 0]/roi3.side.resize_factor)*voxel_size\n y_lim = (vlimits[i, 0]/roi3.side.resize_factor)*voxel_size # Interpolated with spline.\n z_lim = (pts_side_arr_sorted[i, 1]/roi3.side.resize_factor)*voxel_size\n outfile.write(roi3.side.V_ID[i] + \"\\t\") # ID\n outfile.write(\"%f\" % x_cen + \"\\t\") # x_cen\n outfile.write(\"%f\" % y_cen + \"\\t\") # y_cen\n outfile.write(\"%f\" % z_cen + \"\\t\") # z_cen\n outfile.write(\"%f\" % x_lim + \"\\t\") # x_lim\n outfile.write(\"%f\" % y_lim + \"\\t\") # y_lim\n outfile.write(\"%f\" % z_lim + \"\\n\") # z_lim\n # Deal with last (most rostral) vertebrae.\n i = pts_side_arr_sorted.shape[0]-1\n x_lim = (pts_side_arr_sorted[i, 0] / roi3.side.resize_factor)*voxel_size\n y_lim = (vlimits[i, 0] / roi3.side.resize_factor)*voxel_size\n z_lim = (pts_side_arr_sorted[i, 1] / roi3.side.resize_factor)*voxel_size\n outfile.write(roi3.side.V_ID[i] + \"\\tnan\\tnan\\tnan\\t\")\n outfile.write(\"%f\" % x_lim + \"\\t\") # x_lim\n outfile.write(\"%f\" % y_lim + \"\\t\") # y_lim\n outfile.write(\"%f\" % z_lim + \"\\n\") # z_lim\n\n # Save relevant params in separate txt file.\n today = date.today()\n with open(os.path.join(analysis_path, 'params.txt'), 'w') as outfile:\n outfile.write(os.path.join(datapath, struct, session, mouse) + \"\\n\")\n outfile.write(\"Date = \" + today.strftime(\"%Y-%m-%d\") + \"\\n\")\n outfile.write(\"Horizontal tilt angle = \" + str(roi1.tilt.hangle) + \" deg\\n\")\n outfile.write(\"Vertical tilt angle = \" + str(roi1.tilt.vangle) + \" deg\\n\")\n outfile.write(\"Voxel size = \" + str(tuple([int(round(1000 * x)) for x in voxel_spacing])) + \" um\\n\")\n outfile.write(\"roi2.top.resize_factor = \" + str(roi2.top.resize_factor) + \"\\n\")\n outfile.write(\"roi3.side.resize_factor = \" + str(roi3.side.resize_factor) + \"\\n\")\n outfile.write(\"Number of vertebrae annotated = \" + str(N_V_annotated) + \"\\n\")\n\n ''' Step 11: save ROI objects in file '''\n\n for i in range(1,4):\n roi_name = 'roi' + str(i)\n with open(os.path.join(roi_path, roi_name + '.pickle'), 'wb') as f:\n pickle.dump(locals()[roi_name], f)\n\n\ndef vertebral_profiles(session, mouse, datapath='/mnt/data/DATA_SSPO', struct='SPINE'):\n # Debug:\n # datapath='/mnt/data/DATA_SSPO'\n # struct='SPINE'\n # session='example_session_SPINE'\n # mouse='example_mouse_Colonne'\n\n ''' Step 1: define paths '''\n analysis_path = os.path.join(datapath, struct, session, mouse, 'analysis')\n im_path = os.path.join(analysis_path, 'images')\n roi_path = os.path.join(analysis_path, 'rois')\n src_dir = os.path.join(datapath, struct, session, mouse, 'data')\n\n '''Step 2: load roi objects '''\n roi1 = pickle.load(open(os.path.join(analysis_path, 'rois', 'roi1.pickle'),'rb'))\n roi2 = pickle.load(open(os.path.join(analysis_path, 'rois', 'roi2.pickle'),'rb'))\n roi3 = pickle.load(open(os.path.join(analysis_path, 'rois', 'roi3.pickle'),'rb'))\n\n '''Step 3: regenerate arrays from data (see run_analysis function)'''\n dcm_files = glob.glob(src_dir + '/*.dcm')\n ndcm = len(dcm_files)\n if ndcm == 0:\n sys.exit('No .dcm file in ' + src_dir + '.')\n if ndcm > 1:\n arr3d_float32, voxel_spacing = dicom.load_stack(src_dir) # 3D array in float 32\n if ndcm == 1: # One stack of dcm images.\n dcm_data = pydicom.dcmread(dcm_files[0])\n voxel_spacing=(float(dcm_data.SliceThickness),float(dcm_data.PixelSpacing[0]),float(dcm_data.PixelSpacing[1])) # voxel size in mm.\n arr = dcm_data.pixel_array\n arr3d_float32 = np.float32(arr)\n arr3d_8 = utils.imRescale2uint8(arr3d_float32) # Scale [min max] to [0 255] (i.e. convert to 8 bit)\n mask_rear = np.broadcast_to(roi1.rear.immask == 0, arr3d_float32.shape)\n minval = np.ma.array(arr3d_float32, mask=mask_rear).min() # min pixel val within selected region\n arr3d_float32_masked1 = np.ma.array(arr3d_float32, mask=mask_rear, fill_value=minval).filled()\n arr3d_8_masked1 = utils.imRescale2uint8(arr3d_float32_masked1) # Convert to 8 bits\n\n ''' Step 4: compute 3D coordinates of vertebrae limits (same as in run_analysis function)'''\n # Define coordinates of reference points drawn on top projection\n pts_top_arr = np.array(roi2.top.pts)\n pts_top_arr_sorted = np.flip(pts_top_arr[np.argsort(pts_top_arr[:, 1])])\n pts_top_arr_sorted = -pts_top_arr_sorted\n pts_top_arr_sorted[:, 0] = pts_top_arr_sorted[:, 0] - pts_top_arr_sorted[0, 0]\n # in pts_top_arr_sorted, x is ascending caudo-rostral coordinate, y is ascending ML coordinate (from right to left)\n # Define coordinates of reference points drawn on side projection (vertebrae limits)\n pts_side_arr = np.array(roi3.side.pts)\n pts_side_arr_sorted = pts_side_arr[np.argsort(pts_side_arr[:, 0])]\n pts_side_arr_sorted[:, 1] = -pts_side_arr_sorted[:, 1] + arr3d_8.shape[1] * roi3.side.resize_factor\n # in pts_side_arr_sorted, x is ascending caudo-rostral coordinate, y is ascending ventro-dorsal coordinate\n # Same for midpoints (center of vertebrae)\n midpts = np.array(roi3.side.midpnt)\n midpts[:, 1] = -midpts[:, 1] + arr3d_8.shape[1] * roi3.side.resize_factor\n # Compute spline joining pts_top_arr_sorted\n x, y = np.array(pts_top_arr_sorted)[:, 1], np.array(pts_top_arr_sorted)[:, 0]\n f = interp1d(y, x, kind='cubic') # Compute spline function\n # ynew = np.linspace(np.min(y), np.max(y), num=500, endpoint=True)\n # spline_top = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n # spline_top[:,0] = -spline_top[:,0]\n # spline_top[:,1] = spline_top[:,1] - spline_top[0,1]\n # in spline.top, x is ascending left-to-right coordinate, y is ascending caudo-rostral coordinate\n ynew = pts_side_arr_sorted[:, 0]\n vlimits = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n vlimits[:, 0] = vlimits[:, 0] + arr3d_8.shape[1] * roi3.side.resize_factor\n # vlimits: coordinates of vertebrae limits, same coordinate system as spline.top...\n # ...(x is ascending left-to-right coordinate, y is ascending caudo-rostral coordinate)\n ynew = midpts[:, 0]\n center_v = np.vstack((np.array(f(ynew)), ynew)).T # Coordinates of spline points\n center_v[:, 0] = center_v[:, 0] + arr3d_8.shape[1] * roi3.side.resize_factor\n\n ''' Step 5: compute vertebrae profiles using projection plane perpendicular to spine axis'''\n # We use the midpoints calculated in run_analysis\n # u, v, w: reference frame\n u = np.array([1, 0, 0])\n v = np.array([0, 1, 0])\n w = np.array([0, 0, 1])\n arr = np.flip(np.flip(np.swapaxes(arr3d_8_masked1, 2, 1), 0), 2)\n v_analysis_path = os.path.join(im_path, 'vertebrae') # Where images will be saved\n if not os.path.exists(v_analysis_path):\n os.makedirs(v_analysis_path)\n if not os.path.exists(os.path.join(v_analysis_path, 'raw')):\n os.makedirs(os.path.join(v_analysis_path, 'raw'))\n if not os.path.exists(os.path.join(v_analysis_path, 'labeled')):\n os.makedirs(os.path.join(v_analysis_path, 'labeled'))\n # print('Computing oblique projections through vertebrae... ', end='')\n sys.stdout.write('Computing oblique projections through vertebrae... ')\n N_V_annotated = len(roi3.side.V_ID) # Number of vertebrae annotated\n for k in range(N_V_annotated):\n TV1 = pts_side_arr_sorted[k + 1] - pts_side_arr_sorted[k]\n TV2 = vlimits[k + 1] - vlimits[k]\n vec = utils.norml(np.array([TV1[0],TV2[0],TV1[1]]))\n up = utils.norml(utils.vprod(v, vec))\n vp = utils.norml(utils.vprod(vec, up))\n ori = np.array([midpts[k, 0], 3*arr3d_8.shape[1]-center_v[k, 0], midpts[k, 1]]) / 3\n v_im1 = np.zeros((71, 71))\n v_im2 = np.zeros((71, 71))\n v_im3 = np.zeros((71, 71))\n v_im4 = np.zeros((71, 71))\n v_im5 = np.zeros((71, 71))\n v_im6 = np.zeros((71, 71))\n v_im7 = np.zeros((71, 71))\n for i in np.linspace(-35,35,num=71):\n for j in np.linspace(-35,35,num=71):\n #\n coord = np.round(ori - (3*vec) + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im1[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im1[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori - (2*vec) + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im2[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im2[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori - vec + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im3[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im3[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im4[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im4[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori + vec + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im5[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im5[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori + (2*vec) + i * up + j * vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im6[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im6[int(i + 35), int(j + 35)] = 0\n #\n coord = np.round(ori - (3*vec) + i*up + j*vp).astype('int16')\n if not np.any((coord >= arr3d_8.shape[1]) | (coord <= 0)):\n v_im7[int(i + 35), int(j + 35)] = arr[coord[0], coord[1], coord[2]]\n else:\n v_im7[int(i + 35), int(j + 35)] = 0\n #\n v_im = np.amax(np.array([v_im1, v_im2, v_im3, v_im4, v_im5]), axis=0)\n v_im_resized, resize_factor = utils.customResize(v_im, 3)\n v_im_resized = utils.imRescale2uint8(v_im_resized)\n ret, v_im_bin = cv2.threshold(v_im_resized, 130, 255, cv2.THRESH_BINARY)\n # v_im_sharpened = cv2.filter2D(v_im, -1, kernel_sharpening)\n # v_im_resized, resize_factor = utils.customResize(v_im, 3)\n # v_im_resized = utils.imRescale2uint8(utils.imLevels(v_im_resized, 70, 220))\n # Save binary image (greyscale)\n cv2.imwrite(os.path.join(v_analysis_path,'raw', \"%02d\" % k + '_' + roi3.side.V_ID[k] + '.png'), v_im_resized)\n # Then save labeled image (rgb)\n v_im_bin_rgb = cv2.merge(((v_im_bin,) * 3))\n v_im_resized_rgb = cv2.merge(((v_im_resized,) * 3))\n cv2.line(v_im_resized_rgb, (107 - 10, 107), (107 + 10, 107), (0, 0, 255), 2)\n cv2.line(v_im_resized_rgb, (107, 107 - 10), (107, 107 + 10), (0, 0, 255), 2)\n cv2.putText(v_im_resized_rgb, roi3.side.V_ID[k], (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), lineType=cv2.LINE_AA)\n cv2.rectangle(v_im_resized_rgb, (0, 0), (int(71*resize_factor-1), int(71*resize_factor-1)), (130, 130, 130), 1)\n cv2.imwrite(os.path.join(v_analysis_path,'labeled', \"%02d\" % k + '_' + roi3.side.V_ID[k] + '.png'), v_im_resized_rgb)\n print('done.')\n\ndef vertebral_angles(session, mouse, datapath='/home/ghyomm/DATA_MICROCT', struct='SPINE'):\n\n ''' Step 1: define paths '''\n analysis_path = os.path.join(datapath, struct, session, mouse, 'analysis')\n raw_im_path = os.path.join(analysis_path, 'images','vertebrae','raw')\n sym_im_path = os.path.join(analysis_path, 'images','vertebrae','sym')\n if not os.path.exists(sym_im_path):\n os.makedirs(sym_im_path)\n\n '''Step 2: loop through vertebrae images and compute symmetry'''\n res = []\n for imfile in glob.glob(raw_im_path + '/*.png'):\n im = cv2.imread(imfile, cv2.IMREAD_GRAYSCALE)\n refpt = np.array([100,100],dtype=np.uint16)\n angle_range = np.array([-30,30],dtype=np.int16)\n hoffset_range = np.array([-20,21],dtype=np.int16)\n im_out = cyutils.compute_sym_axis(im,refpt,angle_range,hoffset_range)\n max_coord = np.where(im_out == np.amax(im_out))\n if len(max_coord[0]>1) or len(len(max_coord[1]>1)):\n best_angle = int(max_coord[0][0] + angle_range[0])\n best_offset = int(max_coord[1][0] + hoffset_range[0])\n else:\n best_angle = int(max_coord[0] + angle_range[0])\n best_offset = int(max_coord[1] + hoffset_range[0])\n imsym = sym.compute_angle_and_offset(im,best_angle,best_offset)\n im_filename = os.path.split(imfile)[-1]\n index = im_filename.split('_')[0]\n ID = im_filename.split('_')[1].split('.')[0]\n res.append({'index':int(index),'ID':ID,'angle':best_angle})\n cv2.imwrite(os.path.join(sym_im_path,os.path.split(imfile)[-1]), imsym)\n\n df = pd.DataFrame(res).sort_values(by='index')\n df.reset_index(inplace=True,drop=True)\n del df['index']\n df.to_csv(os.path.join(analysis_path,'vertebrae_angles.txt'),sep='\\t', index=True, header=True)\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":32420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"653201752","text":"import math\n\n\ndef find_leyland():\n \"\"\" None -> list\n Returns a list of all leyland numbers between 10000 and 100000\n \"\"\"\n leylands = []\n for i in range(2, int(math.log2(100000))):\n for j in range(2, int(math.log2(100000))):\n num = i**j + j**i\n if 10**4 <= num < 10**5:\n leylands.append(num)\n return leylands\n\n\ndef find_products(lst):\n \"\"\" list -> list\n Returns a list of all possible products of numbers in a list\n except for products of identical numbers (a.k.a squares)\n \"\"\"\n products = set()\n for num1 in lst:\n for num2 in lst:\n prod = num1 * num2\n if not num1 == num2 and not is_palindrome(prod):\n products.add(prod)\n return products\n\n\ndef is_palindrome(num):\n \"\"\" int -> bool\n Determines if a number is a palindrome\n \"\"\"\n num = str(num)\n return num == num[::-1]\n\n\ndef divisors(num):\n \"\"\" int -> list\n Returns a list of tuples which contain two numbers each.\n The two numbers in each tuple, when multiplied together,\n equate to the input number.\n \"\"\"\n divs = set()\n for i in range(1, int(num**0.5) + 1):\n j = num / i\n if j % 1 == 0.0:\n divs.add((i, int(j)))\n return divs\n\n\ndef leyland_process():\n lst1 = find_leyland()\n lst2 = find_products(lst1)\n top = max(lst2)\n return top, divisors(top)","sub_path":"leyland_nums.py","file_name":"leyland_nums.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101160991","text":"import json\nimport argparse\nimport numpy as np\nimport pickle as pkl\nimport os\nfrom collections import Counter\nimport nltk\nfrom pprint import pprint\n\ndef convert_kb_vocab(data_dir, cutoff=2):\n\tkb_vocab_file = os.path.join(data_dir, \"celeb_vocab_stats.pkl\")\n\toriginal_vocab_file = os.path.join(data_dir, \"vocab.pkl\")\n\tnew_vocab_file = os.path.join(data_dir, \"vocab_with_celeb.pkl\")\n\n\tword_counter = pkl.load(open(kb_vocab_file,'r'))\n\toriginal_vocab_dict = pkl.load(open(original_vocab_file,'r'))\n\n\tvocab_count = [x for x in word_counter.most_common() if x[1]>=cutoff]\n\tvocab_dict = original_vocab_dict[0]\n\n\ti = len(vocab_dict)\n\tprint(\"Original vocab dict size {}\".format(i))\n\tfor (word, count) in vocab_count:\n\t\tif not word in vocab_dict:\n\t\t\tvocab_dict[word] = i\n\t\t\ti += 1\n\tinverted_vocab_dict = {word_id:word for word, word_id in vocab_dict.iteritems()}\t\n\tboth_dict = [vocab_dict, inverted_vocab_dict]\n\twith open(new_vocab_file, 'wb') as f:\n\t\tpkl.dump(both_dict, f, protocol=pkl.HIGHEST_PROTOCOL)\n\n\tprint(\"New vocab dict size {}\".format(len(vocab_dict)))\n\ndef main(args):\n\tconvert_kb_vocab(args.data_dir)\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-data_dir', type=str, default='./',\n\t\t\t\t\t\thelp='data dir')\n\targs = parser.parse_args()\n\tmain(args)","sub_path":"data_processing/create_vocab_with_celeb.py","file_name":"create_vocab_with_celeb.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"95134471","text":"#! /bin/env python\nimport smu\nimport numpy\ns = smu.smu()\nIxy = numpy.logspace(-8, -2, 200)\nf = open('experiment2Source-1K.csv', 'w')\nf.write('\"Ix\",\"Iz\"\\n')\ns.set_voltage(2, 0.)\nfor val in Ixy:\n s.set_current(1, val*-1)\n s.autorange(1)\n s.autorange(2)\n f.write('{!s},{!s}\\n'.format(val*-1, s.get_current(2)))\ns.set_voltage(1, 0.)\ns.set_voltage(2, 0.)\nf.close()\n\n","sub_path":"4/3/singleSource.py","file_name":"singleSource.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"1451167","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom books.models import Book\n\nfrom books.forms import CreateBookForm, UpdateBookForm\n\nfrom django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView, DetailView\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\n# Create your views here.\n\n# def create_book_view(request):\n# if request.method == 'POST':\n# form = CreateBookForm(data=request.POST)\n# if form.is_valid():\n \n# return HttpResponseRedirect('/')\n# else:\n# form = CreateBookForm()\n# return render(\n# request, \n# template_name=\"book/create_book.html\", \n# context={'form': form})\n\ndef show_book_by_pk_view(request, book_id):\n\n book_obj = Book.objects.get(pk=book_id)\n # con = {'book': book_obj}\n return render(\n request, \n template_name=\"books/book.html\",\n context={'book': book_obj},\n )\n\n\nclass ShowBookListView(ListView):\n template_name = \"books/book_list.html\"\n paginate_by = 5\n model = Book\n \n\n def get_queryset(self):\n return super().get_queryset()[0:20]\n \nclass StaticView(TemplateView):\n template_name='books/static.html'\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"pop\"] = 'pops'\n return context\n \n#==============================================================\n\ndef create_book_view(request):\n if request.method == 'POST':\n form = CreateBookForm(data=request.POST)\n if form.is_valid():\n book = form.cleaned_data.get('aut_book')\n Book.objects.create(aut_book=book)\n \n return HttpResponseRedirect('/')\n else:\n form = CreateBookForm()\n return render(\n request, \n template_name=\"books/create_book.html\",\n context={'form': form})\n\nclass CreateBookView(LoginRequiredMixin, CreateView):\n model = Book\n form_class = CreateBookForm\n # fields = ['aut_book', 'publish', 'country', 'name_book', 'gener', 'coin']\n success_url=\"/\"\n login_url = '/admin/login'\n template_name = \"books/create_book.html\"\n\n # def get_context_data(self, **kwargs):\n # context = super().get_context_data(**kwargs)\n # print(self.request.user, 'liosha')\n # return context\n \n\ndef update_book_view(request, pk):\n if request.method == 'POST':\n form = CreateBookForm(data=request.POST)\n if form.is_valid(): \n book_name = form.cleaned_data.get('aut_book')\n Book.objects.create(aut_book=book_name)\n return HttpResponseRedirect('/')\n else:\n book = Book.objects.get(pk=pk)\n form = UpdateBookForm(data={'aut_book': book.aut_book, 'pk': book.pk})\n return render(\n request, \n template_name=\"books/create_book.html\", \n context={'form': form})\n\nclass UpdateBookView(UpdateView):\n model = Book\n fields = ['aut_book', 'publish', 'country', 'name_book', 'gener', 'coin']\n success_url=\"/\"\n template_name = \"books/create_book.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"rate\"] = 2.67\n return context\n \n\ndef delete_book_view(request, pk):\n if request.method == 'POST':\n book = Book.objects.delete(pk=pk)\n return HttpResponseRedirect('/')\n else:\n book = Book.objects.get(pk=pk)\n return render(\n request, \n template_name=\"books/delete_book.html\", \n context={'book': book})\n\nclass DeleteBookView(DeleteView):\n model = Book\n fields = ['aut_book', 'publish', 'country', 'name_book', 'gener', 'coin']\n success_url=\"/\"\n template_name = \"books/delete_book.html\"\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n Call the delete() method on the fetched object and then redirect to the\n success URL.\n \"\"\"\n self.object = self.get_object()\n success_url = self.get_success_url()\n self.object.delete()\n return HttpResponseRedirect('/')\n \n\nclass BookDetailView(DetailView):\n model = Book\n template_name = \"books/detail_book.html\"\n \n # def get_object(self, **kwargs):\n # return self.request.user","sub_path":"src/books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"463852714","text":"# *****************************************************************************\n# * Copyright 2019 Amazon.com, Inc. and its affiliates. All Rights Reserved. *\n# *\n# Licensed under the Amazon Software License (the \"License\"). *\n# You may not use this file except in compliance with the License. *\n# A copy of the License is located at *\n# *\n# http://aws.amazon.com/asl/ *\n# *\n# or in the \"license\" file accompanying this file. This file is distributed *\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either *\n# express or implied. See the License for the specific language governing *\n# permissions and limitations under the License. *\n# *****************************************************************************\nimport logging\n\nimport torch\nfrom torch import nn\n\n\nclass TripletLoss(nn.Module):\n \"\"\"\n Implement triplet loss based on hard triplet mining strategy in the paper - End-to-end Learning of Deep Visual Representations for Image Retrieval - https://arxiv.org/pdf/1610.07940.pdf\n\n\n ``To ensure that the sampled triplets are useful, we first select randomly N training samples, extract their features with the current model, and compute all possible triplets and their losses, which is fast once the features have been extracted.\n All the triplets that incur a loss are prese- lected as good candidates. Triplets can then be sampled from that set of good candidates, with a bias towards hard triplets, i.e. triplets that produce a high loss.\n In practice this is achieved by randomly sampling one of the N images with a uniform distribution and then ran- domly choosing one of the 25 triplets with the largest loss that involve that particular image as a query.\n Note that, in theory, one should recompute the set of good candidates every time the model gets updated, which is very time consuming.\n In practice, we assume that most of the hard triplets for a given model will remain hard even if the model gets updated a few times, and there- fore we only update the set of good candidates after the model has been updated k times.\n We used N = 5000 samples and k = 64 iterations with a batch size of 64 triplets per iteration in our experiments.\n ``\n The loss function for query sample q, postive sample p and negative sample n is and N total samples\n .. math::\n L (q, p, q) = 1/N \\Sigma max(d(q, p) - d(q, n) + margin, 0)\n\n Useful resources\n ================\n\n * https://omoindrot.github.io/triplet-loss\n \"\"\"\n\n def __init__(self, margin, topk=None):\n super().__init__()\n self.topk = topk\n self.margin = margin\n\n @property\n def logger(self):\n return logging.getLogger(__name__)\n\n def forward(self, pos_embedding, query_embedding, neg_embedding, target):\n \"\"\"\nComputes the triplet loss\n :param neg_embedding: a 2D tensor of embeddings negtive sample matching that does not match query class\n :param pos_embedding: a 2D tensor of embeddings positive sample matching query class\n :param query_embedding: a 2D tensor of embeddings\n :param target: 1d tensor of target\n :return: loss\n \"\"\"\n\n pos_distance = self._get_distance(pos_embedding, query_embedding)\n neg_distance = self._get_distance(neg_embedding, query_embedding)\n\n # use relu instead of max\n losses = torch.relu(pos_distance - neg_distance + self.margin)\n\n # Filter hard loss\n if self.topk is not None:\n losses = torch.topk(losses, k=min(losses.shape[0], self.topk))[0]\n\n loss = losses.mean()\n return loss\n\n def _get_distance(self, x, y):\n \"\"\"\n Returns the euclidean distance between x and y where x and y are 2D tensors and the length of xand y is the same\n :param x: 2d tensor\n :param y: 2d tensor\n :return: distance along the 1 dim\n \"\"\"\n assert x.shape == y.shape, \"Expecting the shapes of x and y to match\"\n\n result = torch.pow(x - y, 2).sum(1)\n\n return result\n","sub_path":"src/tripletloss.py","file_name":"tripletloss.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439696734","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# from activemri.baselines.loupe_codes.transforms import normalize\nimport pathlib\nfrom typing import Callable, List, Optional, Tuple\n\nimport fastmri\nimport h5py\nimport numpy as np\nimport torch.utils.data\nimport activemri\nimport scipy.ndimage as ndimage\n\nclass RealBrainData(torch.utils.data.Dataset):\n # This is the same as fastMRI singlecoil_knee, except we provide a custom test split\n # and also normalize images by the mean norm of the k-space over training data\n# KSPACE_WIDTH = 368\n# KSPACE_HEIGHT = 640\n# START_PADDING = 166\n# END_PADDING = 202\n# CENTER_CROP_SIZE = 320\n\n def __init__(\n self,\n root: pathlib.Path,\n image_shape: Tuple[int, int],\n transform: Callable,\n noise_type: str,\n noise_level: float = 5e-5,\n num_cols: Optional[int] = None,\n num_volumes: Optional[int] = None,\n num_rand_slices: Optional[int] = None,\n custom_split: Optional[str] = None,\n random_rotate=False \n ):\n self.image_shape = image_shape\n self.transform = transform\n self.noise_type = noise_type\n self.noise_level = noise_level\n self.examples: List[Tuple[pathlib.PurePath, int]] = []\n\n\n self.num_rand_slices = num_rand_slices\n self.rng = np.random.RandomState(1234)\n self.recons_key = 'reconstruction_rss'\n\n files = []\n for fname in list(pathlib.Path(root).iterdir()):\n data = h5py.File(fname, \"r\")\n if 'reconstruction_rss' not in data.keys():\n continue\n files.append(fname)\n\n self.train_mode = False \n\n \"\"\"if custom_split is not None:\n split_info = []\n with open(f\"activemri/data/splits/knee_singlecoil/{custom_split}.txt\") as f:\n for line in f:\n split_info.append(line.rsplit(\"\\n\")[0])\n files = [f for f in files if f.name in split_info]\n else:\n self.train_mode = True \n \"\"\"\n if num_volumes is not None:\n self.rng.shuffle(files)\n files = files[:num_volumes]\n\n for volume_i, fname in enumerate(sorted(files)):\n data = h5py.File(fname, \"r\")\n # kspace = data[\"kspace\"]\n\n if num_rand_slices is None:\n num_slices = data['reconstruction_rss'].shape[0]\n self.examples += [(fname, slice_id) for slice_id in range(num_slices)]\n else:\n assert 0 \n slice_ids = list(range(kspace.shape[0]))\n self.rng.seed(seed=volume_i)\n self.rng.shuffle(slice_ids)\n self.examples += [\n (fname, slice_id) for slice_id in slice_ids[:num_rand_slices]\n ]\n\n self.random_rotate = random_rotate\n if self.random_rotate:\n np.random.seed(42)\n self.random_angles = np.random.random(len(self)) * 30- 15\n\n def center_crop(self, data, shape):\n \"\"\"\n (Same as the one in activemri/baselines/policy_gradient_codes/helpers/transforms.py)\n Apply a center crop to the input real image or batch of real images.\n\n Args:\n data (torch.Tensor): The input tensor to be center cropped. It should have at\n least 2 dimensions and the cropping is applied along the last two dimensions.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-2]\n assert 0 < shape[1] <= data.shape[-1]\n w_from = (data.shape[-2] - shape[0]) // 2\n h_from = (data.shape[-1] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to]\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n fname, slice_id = self.examples[i]\n with h5py.File(fname, 'r') as data:\n \n # kspace = data[\"kspace\"][slice_id]\n # kspace = np.stack([kspace.real, kspace.imag], axis=-1)\n # if self.random_rotate:\n # kspace = ndimage.rotate(kspace, self.random_angles[i], reshape=False, mode='nearest')\n\n #kspace = torch.from_numpy(kspace).permute(2, 0, 1)\n #kspace = self.center_crop(kspace, self.image_shape).permute(1, 2, 0)\n \n #kspace = fastmri.ifftshift(kspace, dim=(0, 1))\n target = torch.from_numpy(data['reconstruction_rss'][slice_id]).unsqueeze(-1)\n target = torch.cat([target, torch.zeros_like(target)], dim=-1)\n target = self.center_crop(target.permute(2, 0, 1), self.image_shape).permute(1, 2, 0)\n \n kspace = fastmri.ifftshift(target, dim=(0, 1)).fft(2, normalized=False)\n\n\n # target = torch.ifft(kspace, 2, normalized=False)\n #target = fastmri.ifftshift(target, dim=(0, 1))\n \n\n # Normalize using mean of k-space in training data\n # target /= 7.072103529760345e-07\n # kspace /= 7.072103529760345e-07\n\n kspace = kspace.numpy()\n target = target.numpy()\n\n return self.transform(\n kspace,\n torch.zeros(kspace.shape[1]),\n target,\n dict(data.attrs),\n fname.name,\n slice_id\n )\n\n\"\"\"from activemri.envs.envs import ActiveMRIEnv\ndata = RealBrainData(\n 'datasets/brain/train_no_kspace',\n (128, 128),\n ActiveMRIEnv._void_transform,\n noise_type='none'\n)\n\ndata[0]\n\"\"\"","sub_path":"activemri/data/real_brain_data.py","file_name":"real_brain_data.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"494336970","text":"__all__ = ()\n\nimport warnings\nfrom functools import partial as partial_func\n\nfrom ...backend.utils import WeakReferer\n\nfrom .core import DEFAULT_EVENT_HANDLER, EVENT_HANDLER_NAME_TO_PARSER_NAMES, get_event_parser_parameter_count, \\\n PARSER_SETTINGS\nfrom .handling_helpers import ChunkWaiter, default_error_event, check_parameter_count_and_convert, asynclist, \\\n check_name\n\nclass EventHandlerManager:\n \"\"\"\n After a client gets a dispatch event from Discord, it's parser might ensure an event. These events are stored\n inside of a ``EventHandlerManager`` and can be accessed through ``Client.events``.\n \n Each added event should be an async callable accepting a predefined amount of positional parameters.\n \n Attributes\n ----------\n _launch_called : `bool`\n Whether The respective client's `.events.launch` was called already.\n client_reference : ``WeakReferer``\n Weak reference to the parent client to avoid reference loops.\n \n Additional Event Attributes\n --------------------------\n application_command_create(client: ``Client``, guild_id: `int`, application_command: ``ApplicationCommand``)\n Called when you create an application guild bound to a guild.\n \n application_command_delete(client: ``Client``, guild_id: `int`, application_command: ``ApplicationCommand``)\n Called when you delete one of your guild bound application commands.\n \n application_command_permission_update(client: ``Client``, \\\n application_command_permission: ``ApplicationCommandPermission``)\n Called when an application command's permissions are updated inside of a guild.\n \n application_command_update(client : ``Client``, guild_id: `int`, application_command: ``ApplicationCommand``, \\\n old_attributes : {`dict`, `None`})\n Called when you update one of your guild bound application command.\n \n `old_attributes` might be given as `None` if the `application_command` is not cached. If it is cached, is given\n as a `dict` which contains the updated attributes of the application command as keys and their old values as\n the values.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-----------------------+---------------------------------------------------+\n | Keys | Values |\n +=======================+===================================================+\n | default_permission | `bool` |\n +-----------------------+---------------------------------------------------+\n | description | `None` or `str` |\n +-----------------------+---------------------------------------------------+\n | name | `str` |\n +-----------------------+---------------------------------------------------+\n | options | `None` or `list` of ``ApplicationCommandOption`` |\n +-----------------------+---------------------------------------------------+\n | target_type | ``ApplicationCommandTargetType`` |\n +-----------------------+---------------------------------------------------+\n \n channel_create(client: ``Client``, channel: ``ChannelBase``)\n Called when a channel is created.\n \n > This event is not called when a private channel is created.\n \n channel_delete(client: ``Client``, channel: ``ChannelBase``)\n Called when a channel is deleted.\n \n channel_edit(client: ``Client``, channel: ``ChannelBase``, old_attributes: `dict`)\n Called when a channel is edited. The passed `old_attributes` parameter contains the channel's overwritten\n attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-----------------------+---------------------------------------+\n | Keys | Values |\n +=======================+=======================================+\n | archived | `bool` |\n +-----------------------+---------------------------------------+\n | archived_at | `None` or `datetime` |\n +-----------------------+---------------------------------------+\n | auto_archive_after | `int` |\n +-----------------------+---------------------------------------+\n | bitrate | `int` |\n +-----------------------+---------------------------------------+\n | icon | ``Icon`` |\n +-----------------------+---------------------------------------+\n | invitable | `bool` |\n +-----------------------+---------------------------------------+\n | parent_id | `int` |\n +-----------------------+---------------------------------------+\n | name | `str` |\n +-----------------------+---------------------------------------+\n | nsfw | `bool` |\n +-----------------------+---------------------------------------+\n | open | `bool` |\n +-----------------------+---------------------------------------+\n | overwrites | `list` of ``PermissionOverwrite`` |\n +-----------------------+---------------------------------------+\n | owner_id | `int` |\n +-----------------------+---------------------------------------+\n | position | `int` |\n +-----------------------+---------------------------------------+\n | region | `None` or ``VoiceRegion`` |\n +-----------------------+---------------------------------------+\n | slowmode | `int` |\n +-----------------------+---------------------------------------+\n | topic | `None` or `str` |\n +-----------------------+---------------------------------------+\n | type | `int` |\n +-----------------------+---------------------------------------+\n | user_limit | `int` |\n +-----------------------+---------------------------------------+\n | video_quality_mode | ``VideoQualityMode`` |\n +-----------------------+---------------------------------------+\n \n channel_group_user_add(client: ``Client``, channel: ``ChannelGroup``, user: ``ClientUserBase``):\n Called when a user is added to a group channel.\n \n channel_group_user_delete(client: ``Client``, channel: ``ChannelGroup``, user: ``ClientUserBase``):\n Called when a user is removed from a group channel.\n \n channel_pin_update(client: ``Client``, channel: ``ChannelTextBase``):\n Called when a channel's pins are updated.\n \n client_edit(client: ``Client``, old_attributes: `dict`):\n Called when the client is edited. The passed `old_attributes` parameter contains the client's overwritten\n attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-----------------------+-----------------------+\n | Keys | Values |\n +=======================+=======================+\n | avatar | ``Icon`` |\n +-----------------------+-----------------------+\n | banner | ``Icon`` |\n +-----------------------+-----------------------+\n | banner_color | `None` or ``Color`` |\n +-----------------------+-----------------------+\n | discriminator | `int` |\n +-----------------------+-----------------------+\n | email | `None` or `str` |\n +-----------------------+-----------------------+\n | flags | ``UserFlag`` |\n +-----------------------+-----------------------+\n | locale | `str |\n +-----------------------+-----------------------+\n | mfa | `bool` |\n +-----------------------+-----------------------+\n | name | `str |\n +-----------------------+-----------------------+\n | premium_type | ``PremiumType`` |\n +-----------------------+-----------------------+\n | verified | `bool` |\n +-----------------------+-----------------------+\n \n embed_update(client: ``Client``, message: ``Message``, change_state: `int`):\n Called when a message is not edited, only it's embeds are updated.\n \n Possible `change_state` values:\n \n +---------------------------+-------+\n | Respective name | Value |\n +===========================+=======+\n | EMBED_UPDATE_NONE | 0 |\n +---------------------------+-------+\n | EMBED_UPDATE_SIZE_UPDATE | 1 |\n +---------------------------+-------+\n | EMBED_UPDATE_EMBED_ADD | 2 |\n +---------------------------+-------+\n | EMBED_UPDATE_EMBED_REMOVE | 3 |\n +---------------------------+-------+\n \n At the case of `EMBED_UPDATE_NONE` the event is of course not called.\n \n emoji_create(client: ``Client``, emoji: ``Emoji``):\n Called when an emoji is created at a guild.\n \n emoji_delete(client: ``Client``, emoji: ``Emoji``):\n Called when an emoji is deleted.\n \n Deleted emoji's `.guild` attribute is set to `None`.\n \n emoji_edit(client : Client, emoji: ``Emoji``, old_attributes: `dict`):\n Called when an emoji is edited. The passed `old_attributes` parameter contains the emoji's overwritten\n attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-------------------+-------------------------------+\n | Keys | Values |\n +===================+===============================+\n | animated | `bool` |\n +-------------------+-------------------------------+\n | available | `bool` |\n +-------------------+-------------------------------+\n | managed | `bool` |\n +-------------------+-------------------------------+\n | name | `int` |\n +-------------------+-------------------------------+\n | require_colons | `bool` |\n +-------------------+-------------------------------+\n | role_ids | `None` or `tuple` of `int` |\n +-------------------+-------------------------------+\n \n error(client: ``Client``, name: `str`, err: `Any`):\n Called when an unexpected error happens. Mostly the user itself should define where it is called, because\n it is not Discord event bound, but an internal event.\n \n The `name` parameter should be a `str` what tell where the error occurred, and `err` should be a `BaseException`\n instance or an error message (can be other as type `str` as well.)\n \n > This event has a default handler called ``default_error_event``, which writes the error message to\n > `sys.stderr`.\n \n gift_update(client: ``Client``, gift: ``Gift``):\n Called when a gift code is sent to a channel.\n \n guild_ban_add(client: ``Client``, guild: ``Guild``, user: ``ClientUserBase``):\n Called when a user is banned from a guild.\n \n guild_ban_delete(client: ``Client``, guild: ``Guild``, user: ``ClientUserBase``):\n Called when a user is unbanned at a guild.\n \n guild_create(client: ``Client``, guild: ``Guild``):\n Called when a client joins or creates a guild.\n \n guild_delete(client: ``Client``, guild: ``Guild``, profile: ``GuildProfile``):\n Called when the guild is deleted or just the client left (kicked or banned as well) from it. The `profile`\n parameter is the client's respective guild profile for the guild.\n \n guild_edit(client: ``Client``, guild: ``Guild``, old_attributes: `dict`):\n Called when a guild is edited. The passed `old_attributes` parameter contains the guild's overwritten attributes\n in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +---------------------------+-------------------------------+\n | Keys | Values |\n +===========================+===============================+\n | afk_channel_id | `int` |\n +---------------------------+-------------------------------+\n | afk_timeout | `int` |\n +---------------------------+-------------------------------+\n | available | `bool` |\n +---------------------------+-------------------------------+\n | banner | ``Icon`` |\n +---------------------------+-------------------------------+\n | booster_count | `int` |\n +---------------------------+-------------------------------+\n | content_filter | ``ContentFilterLevel`` |\n +---------------------------+-------------------------------+\n | description | `None` or `str` |\n +---------------------------+-------------------------------+\n | discovery_splash | ``Icon`` |\n +---------------------------+-------------------------------+\n | features | `list` of ``GuildFeature`` |\n +---------------------------+-------------------------------+\n | icon | ``Icon`` |\n +---------------------------+-------------------------------+\n | invite_splash | ``Icon`` |\n +---------------------------+-------------------------------+\n | max_presences | `int` |\n +---------------------------+-------------------------------+\n | max_users | `int` |\n +---------------------------+-------------------------------+\n | max_video_channel_users | `int` |\n +---------------------------+-------------------------------+\n | message_notification | ``MessageNotificationLevel`` |\n +---------------------------+-------------------------------+\n | mfa | ``MFA`` |\n +---------------------------+-------------------------------+\n | name | `str` |\n +---------------------------+-------------------------------+\n | nsfw_level | `NsfwLevel` |\n +---------------------------+-------------------------------+\n | owner_id | `int` |\n +---------------------------+-------------------------------+\n | preferred_locale | `str` |\n +---------------------------+-------------------------------+\n | premium_tier | `int` |\n +---------------------------+-------------------------------+\n | public_updates_channel_id | `int` |\n +---------------------------+-------------------------------+\n | region | ``VoiceRegion`` |\n +---------------------------+-------------------------------+\n | rules_channel_id | `int` |\n +---------------------------+-------------------------------+\n | system_channel_id | `int` |\n +---------------------------+-------------------------------+\n | system_channel_flags | ``SystemChannelFlag`` |\n +---------------------------+-------------------------------+\n | vanity_code | `None` or `str` |\n +---------------------------+-------------------------------+\n | verification_level | ``VerificationLevel`` |\n +---------------------------+-------------------------------+\n | widget_channel_id | `int` |\n +---------------------------+-------------------------------+\n | widget_enabled | `bool` |\n +---------------------------+-------------------------------+\n \n guild_join_reject(client: ``Client``, guild: ``Guild``, user: ``ClientUserBase``):\n Called when a user leaves from a guild before completing it's verification screen.\n \n > ``.guild_user_delete`` is called as well.\n \n guild_user_add(client: ``Client``, guild: ``Guild``, user: ``ClientUserBase``):\n Called when a user joins a guild.\n \n guild_user_chunk(client: ``Client``, event: GuildUserChunkEvent):\n Called when a client receives a chunk of users from Discord requested by through it's gateway.\n \n The event has a default handler called ``ChunkWaiter``.\n \n guild_user_delete(client: ``Client``, guild: ``Guild``, user: ``ClientUserBase``, \\\n profile: ``GuildProfile``):\n Called when a user left (kicked or banned counts as well) from a guild. The `profile` parameter is the user's\n respective guild profile for the guild.\n \n guild_user_edit(client : Client, user: ``ClientUserBase``, guild: ``Guild``, old_attributes: `dict`):\n Called when a user's ``GuildProfile`` is updated. The passed `old_attributes` parameter contains the message's\n overwritten attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-------------------+-------------------------------+\n | Keys | Values |\n +===================+===============================+\n | avatar | ``Icon`` |\n +-------------------+-------------------------------+\n | boosts_since | `None` or `datetime` |\n +-------------------+-------------------------------+\n | nick | `None` or `str` |\n +-------------------+-------------------------------+\n | pending | `bool` |\n +-------------------+-------------------------------+\n | role_ids | `None` or `tuple` of `int` |\n +-------------------+-------------------------------+\n \n integration_create(client: ``Client``, guild: ``Guild``, integration: ``Integration``):\n Called when an integration is created inside of a guild. Includes cases when bots are added to the guild as\n well.\n \n integration_delete(client: ``Client``, guild: ``Guild``, integration_id: `int`, \\\n application_id: {`None`, `int`}):\n Called when a guild has one of it's integrations deleted. If the integration is bound to an application, like\n a bot, then `application_id` is given as `int`.\n \n integration_edit(client: ``Client``, guild: ``Guild``, integration: ``Integration``):\n Called when an integration is edited inside of a guild.\n \n integration_update(client: ``Client``, guild: ``Guild``):\n Called when an ``Integration`` of a guild is updated.\n \n > No integration data is included with the received dispatch event, so it cannot be passed to the event\n > handler either.\n \n interaction_create(client: ``Client``, event: ``InteractionEvent``)\n Called when a user interacts with an application command.\n \n invite_create(client: ``Client``, invite: Invite):\n Called when an invite is created at a guild.\n \n invite_delete(client: ``Client``, invite: Invite):\n Called when an invite is deleted at a guild.\n \n launch(client : ``Client``):\n called when the client is launched up and the first ready dispatch event is received.\n \n message_create(client: ``Client``, message: ``Message``):\n Called when a message is sent to any of the client's text channels.\n \n message_delete(client: ``Client``, message: {``Message``, ``MessageRepr``}):\n Called when a loaded message is deleted.\n \n > If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and an uncached message is deleted,\n > then `message` is given as ``MessageRepr`` instance.\n \n message_edit(client: ``Client``, message: ``Message``, old_attributes: {`None`, `dict`}):\n Called when a loaded message is edited. The passed `old_attributes` parameter contains the message's overwritten\n attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-------------------+-----------------------------------------------------------------------+\n | Keys | Values |\n +===================+=======================================================================+\n | activity | `None` or ``MessageActivity`` |\n +-------------------+-----------------------------------------------------------------------+\n | application | `None` or ``MessageApplication`` |\n +-------------------+-----------------------------------------------------------------------+\n | attachments | `None` or (`tuple` of ``Attachment``) |\n +-------------------+-----------------------------------------------------------------------+\n | components | `None` or (`tuple` of ``ComponentBase``) |\n +-------------------+-----------------------------------------------------------------------+\n | content | `None` or `str` |\n +-------------------+-----------------------------------------------------------------------+\n | cross_mentions | `None` or (`tuple` of (``ChannelBase`` or ``UnknownCrossMention``)) |\n +-------------------+-----------------------------------------------------------------------+\n | edited_at | `None` or `datetime` |\n +-------------------+-----------------------------------------------------------------------+\n | embeds | `None` or `(tuple` of ``EmbedCore``) |\n +-------------------+-----------------------------------------------------------------------+\n | flags | `UserFlag` |\n +-------------------+-----------------------------------------------------------------------+\n | mention_everyone | `bool` |\n +-------------------+-----------------------------------------------------------------------+\n | pinned | `bool` |\n +-------------------+-----------------------------------------------------------------------+\n | user_mentions | `None` or (`tuple` of ``UserBase``) |\n +-------------------+-----------------------------------------------------------------------+\n | role_mention_ids | `None` or (`tuple` of `int`) |\n +-------------------+-----------------------------------------------------------------------+\n \n A special case is if a message is (un)pinned or (un)suppressed, because then the `old_attributes` parameter is\n not going to contain `edited`, only `pinned` or `flags`. If the embeds are (un)suppressed of the message, then\n `old_attributes` might contain also `embeds`.\n \n > If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and an uncached message is updated,\n > then `old_attributes` is given as `None`.\n \n reaction_add(client: ``Client``, event: ``ReactionAddEvent``):\n Called when a user reacts on a message with the given emoji.\n \n > If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and the reaction is added on an\n > uncached message, then `message` is given as ``MessageRepr``.\n \n reaction_clear(client: ``Client``, message: {``Message``, ``MessageRepr``}, \\\n old_reactions: {`None`, ``reaction_mapping``}):\n Called when the reactions of a message are cleared. The passed `old_reactions` parameter are the old reactions\n of the message.\n \n > If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and the reactions are removed from\n > and uncached message, then `message` is given as ``MessageRepr`` and `old_reactions` as `None`.\n \n reaction_delete(client: ``Client``, event: ``ReactionDeleteEvent``):\n Called when a user removes it's reaction from a message.\n \n Note, if `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and the reaction is removed from\n and uncached message, then `message` is given as ``MessageRepr``.\n \n reaction_delete_emoji(client: ``Client``, message: {``Message``, ``MessageRepr``}, \\\n users: {`None`, ``reaction_mapping_line``}):\n Called when all the reactions of a specified emoji are removed from a message. The passed `users` parameter\n are the old reactor users of the given emoji.\n \n > If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, and the reactions are removed from\n > and uncached message, then `message` is given as ``MessageRepr`` and `users` as `None`.\n \n ready(client: ``Client``):\n Called when the client finishes logging in. The event might be called more times, because the clients might\n dis- and reconnect.\n \n relationship_add(client: ``Client``, new_relationship: ``Relationship``):\n Called when the client gets a new relationship independently from it's type.\n \n relationship_change(client: ``Client``, old_relationship: ``Relationship``, new_relationship: ``Relationship``):\n Called when one of the client's relationships change.\n \n relationship_delete(client: ``Client``, old_relationship: ``Relationship``):\n Called when a relationship of a client is removed.\n \n role_create(client: ``Client``, role: ``Role``):\n Called when a role is created at a guild.\n \n role_delete(client: ``Client``, role: ``Role``, guild: ``Guild``):\n Called when a role is deleted from a guild.\n \n Deleted role's `.guild` attribute is set as `None`.\n \n role_edit(client: ``Client``, role: ``Role``, old_attributes: `dict`):\n Called when a role is edited.\n \n Every item in `old_attributes` is optional and they can be any of the following:\n \n +---------------+-------------------+\n | Keys | Values |\n +===============+===================+\n | color | ``Color`` |\n +---------------+-------------------+\n | managed | `bool` |\n +---------------+-------------------+\n | mentionable | `bool` |\n +---------------+-------------------+\n | name | `str` |\n +---------------+-------------------+\n | permissions | ``Permission`` |\n +---------------+-------------------+\n | position | `int` |\n +---------------+-------------------+\n | separated | `bool` |\n +---------------+-------------------+\n \n stage_create(client: ``Client``, stage:: ``Stage``):\n Called when a stage is created.\n \n stage_delete(client: ``Client``, stage:: ``Stage``):\n Called when a stage is deleted.\n \n stage_edit(client: ``Client``, stage:: ``Stage``, old_attributes: `dict`):\n Called when a stage is edited.\n \n Every item in `old_attributes` is optional and they can be any of the following:\n \n +---------------+-----------------------+\n | Keys | Values |\n +===============+=======================+\n | discoverable | `bool` |\n +---------------+-----------------------+\n | invite_code | `None` or `str` |\n +---------------+-----------------------+\n | privacy_level | ``PrivacyLevel`` |\n +---------------+-----------------------+\n | topic | `str` |\n +---------------+-----------------------+\n \n sticker_create(client: ``Client``, sticker: ``Sticker``):\n Called when an sticker is created at a guild.\n \n sticker_delete(client: ``Client``, sticker: ``Sticker``):\n Called when an sticker is deleted.\n \n sticker_edit(client : Client, sticker: ``Sticker``, old_attributes: `dict`):\n Called when an sticker is edited. The passed `old_attributes` parameter contains the sticker's overwritten\n attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional and it's items can be any of the following:\n \n +-----------------------+-----------------------------------+\n | Keys | Values |\n +=======================+===================================+\n | available | `bool` |\n +-----------------------+-----------------------------------+\n | description | `None` or `str` |\n +-----------------------+-----------------------------------+\n | name | `str` |\n +-----------------------+-----------------------------------+\n | sort_value | `int` |\n +-----------------------+-----------------------------------+\n | tags | `None` or `frozenset` of `str` |\n +-----------------------+-----------------------------------+\n \n thread_user_add(client : ``Client``, thread_channel: ``ChannelThread``, user: ``ClientUserBase``):\n Called when a user is added or joined a thread channel.\n \n thread_user_delete(client : ``Client``, thread_channel: ``ChannelThread``, user: ``ClientUserBase``, \\\n thread_profile: ``ThreadProfile``):\n Called when a user is removed or left a thread channel.\n \n typing(client: ``Client``, channel: ``ChannelTextBase``, user: ``ClientUserBase``, timestamp: `datetime`):\n Called when a user is typing at a channel. The `timestamp` parameter represents when the typing started.\n \n However a typing requests stands for 8 seconds, but the official Discord client usually just spams it.\n \n user_edit(client: ``Client``, user: ``ClientUserBase``, old_attributes: `dict`):\n Called when a user is edited This event not includes guild profile changes. The passed `old_attributes`\n parameter contains the message's overwritten attributes in `attribute-name` - `old-value` relation.\n \n Every item in `old_attributes` is optional they can be any of the following:\n \n +---------------+-----------------------+\n | Keys | Values |\n +===============+=======================+\n | avatar | ``Icon`` |\n +---------------+-----------------------+\n | banner | ``Icon`` |\n +---------------+-----------------------+\n | banner_color | `None` or ``Color`` |\n +---------------+-----------------------+\n | discriminator | `int` |\n +---------------+-----------------------+\n | flags | ``UserFlag`` |\n +---------------+-----------------------+\n | name | `str` |\n +---------------+-----------------------+\n \n user_presence_update(client: ``Client``, user: ``ClientUserBase``, old_attributes: `dict`):\n Called when a user's presence is updated.\n \n The passed `old_attributes` parameter contain the user's changed presence related attributes in\n `attribute-name` - `old-value` relation. An exception from this is `activities`, because that is a\n ``ActivityChange`` instance containing all the changes of the user's activities.\n \n +---------------+-----------------------------------+\n | Keys | Values |\n +===============+===================================+\n | activities | ``ActivityChange`` |\n +---------------+-----------------------------------+\n | status | ``Status`` |\n +---------------+-----------------------------------+\n | statuses | `dict` of (`str`, `str`) items |\n +---------------+-----------------------------------+\n \n user_voice_join(client: ``Client``, voice_state: ``VoiceState``)\n Called when a user joins a voice channel.\n \n user_voice_leave(client: ``client``, voice_state: ``VoiceState``)\n Called when a user leaves from a voice channel.\n \n user_voice_update(client: ``Client``, voice_state: ``VoiceState``, old_attributes: `dict`):\n Called when a voice state of a user is updated.\n \n Every item in `old_attributes` is optional and they can be the following:\n \n +-----------------------+-----------------------+\n | Keys | Values |\n +=======================+=======================+\n | channel | ``ChannelVoice`` |\n +-----------------------+-----------------------+\n | deaf | `str` |\n +-----------------------+-----------------------+\n | is_speaker | `bool` |\n +-----------------------+-----------------------+\n | mute | `bool` |\n +-----------------------+-----------------------+\n | requested_to_speak_at | `None` or `datetime` |\n +-----------------------+-----------------------+\n | self_deaf | `bool` |\n +-----------------------+-----------------------+\n | self_mute | `bool` |\n +-----------------------+-----------------------+\n | self_stream | `bool` |\n +-----------------------+-----------------------+\n | self_video | `bool` |\n +-----------------------+-----------------------+\n \n webhook_update(client: ``Client``, channel: ``ChannelGuildBase``):\n Called when a webhook of a channel is updated. Discord not provides further details tho.\n \"\"\"\n __slots__ = ('client_reference', '_launch_called', *sorted(EVENT_HANDLER_NAME_TO_PARSER_NAMES))\n \n def __init__(self, client):\n \"\"\"\n Creates an ``EventHandlerManager`` for the given client.\n \n Parameters\n ----------\n client : ``Client``\n \"\"\"\n client_reference = WeakReferer(client)\n object.__setattr__(self, 'client_reference', client_reference)\n for name in EVENT_HANDLER_NAME_TO_PARSER_NAMES:\n object.__setattr__(self, name, DEFAULT_EVENT_HANDLER)\n object.__setattr__(self, 'error', default_error_event)\n object.__setattr__(self, '_launch_called', False)\n object.__setattr__(self, 'guild_user_chunk', ChunkWaiter())\n \n def __call__(self, func=None, name=None, overwrite=False):\n \"\"\"\n Adds the given `func` to the event descriptor as en event handler.\n \n Parameters\n ----------\n func : `callable`, Optional\n The async callable to add as an event handler.\n name : `None` or `str`, Optional\n A name to be used instead of the passed `func`'s when adding it.\n overwrite : `bool`, Optional\n Whether the passed `func` should overwrite the already added ones with the same name or extend them.\n \n Returns\n -------\n func : `callable`\n The added callable or `functools.partial` instance if `func` was not given.\n \n Raises\n ------\n AttributeError\n Invalid event name.\n TypeError\n - If `func` was not given as callable.\n - If `func` is not as async and neither cannot be converted to an async one.\n - If `func` expects less or more non reserved positional parameters as `expected` is.\n - If `name` was not passed as `None` or type `str`.\n \"\"\"\n if func is None:\n return partial_func(self, name=name, overwrite=overwrite)\n \n name = check_name(func, name)\n \n parameter_count = get_event_parser_parameter_count(name)\n func = check_parameter_count_and_convert(func, parameter_count, name=name)\n \n if overwrite:\n setattr(self, name, func)\n return func\n \n parser_names = EVENT_HANDLER_NAME_TO_PARSER_NAMES.get(name, None)\n if (parser_names is None):\n raise AttributeError(f'Event name: {name!r} is invalid.')\n \n if func is DEFAULT_EVENT_HANDLER:\n return func\n \n actual = getattr(self, name)\n if actual is DEFAULT_EVENT_HANDLER:\n object.__setattr__(self, name, func)\n \n for parser_name in parser_names:\n parser_setting = PARSER_SETTINGS[parser_name]\n parser_setting.add_mention(self.client_reference())\n return func\n \n if type(actual) is asynclist:\n list.append(actual, func)\n return func\n \n new = asynclist()\n list.append(new, actual)\n list.append(new, func)\n object.__setattr__(self, name, new)\n return func\n \n def clear(self):\n \"\"\"\n Clears the ``EventHandlerManager`` to the same state as it were just created.\n \"\"\"\n delete = type(self).__delattr__\n for name in EVENT_HANDLER_NAME_TO_PARSER_NAMES:\n delete(self, name)\n \n object.__setattr__(self, 'error', default_error_event)\n object.__setattr__(self, 'guild_user_chunk', ChunkWaiter())\n \n def __setattr__(self, name, value):\n \"\"\"\n Sets the given event handler under the specified event name. Updates the respective event's parser(s) if needed.\n \n Parameters\n ----------\n name : `str`\n The name of the event.\n value : `callable`\n The event handler.\n \n Raises\n ------\n AttributeError\n The ``EventHandlerManager`` has no attribute named as the given `name`.\n \"\"\"\n parser_names = EVENT_HANDLER_NAME_TO_PARSER_NAMES.get(name, None)\n if (parser_names is None) or (not parser_names):\n object.__setattr__(self, name, value)\n return\n \n for parser_name in parser_names:\n parser_setting = PARSER_SETTINGS[parser_name]\n actual = getattr(self, name)\n object.__setattr__(self, name, value)\n if actual is DEFAULT_EVENT_HANDLER:\n if value is DEFAULT_EVENT_HANDLER:\n continue\n \n parser_setting.add_mention(self.client_reference())\n continue\n \n if value is DEFAULT_EVENT_HANDLER:\n parser_setting.remove_mention(self.client_reference())\n continue\n \n def __delattr__(self, name):\n \"\"\"\n Removes the event with switching it to `DEFAULT_EVENT_HANDLER`, and updates the event's parser if needed.\n \n Parameters\n ----------\n name : `str`\n The name of the event.\n \n Raises\n ------\n AttributeError\n The ``EventHandlerManager`` has no attribute named as the given `name`.\n \"\"\"\n actual = getattr(self, name)\n if actual is DEFAULT_EVENT_HANDLER:\n return\n \n object.__setattr__(self, name, DEFAULT_EVENT_HANDLER)\n \n parser_names=EVENT_HANDLER_NAME_TO_PARSER_NAMES.get(name, None)\n if (parser_names is None) or (not parser_names):\n # parser name can be an empty string as well for internal events\n return\n \n for parser_name in parser_names:\n parser_setting = PARSER_SETTINGS[parser_name]\n parser_setting.remove_mention(self.client_reference())\n \n def get_handler(self, name, type_):\n \"\"\"\n Gets an event handler from the client's.\n \n Parameters\n ----------\n name : `str`\n The event's name.\n type_ : `type`\n The event handler's type.\n\n Returns\n -------\n event_handler : `str`, `None`\n The matched event handler if any.\n \"\"\"\n if name == 'client':\n return None\n \n try:\n actual = getattr(self, name)\n except AttributeError:\n return None\n \n if actual is DEFAULT_EVENT_HANDLER:\n return None\n \n if type(actual) is asynclist:\n for element in list.__iter__(actual):\n if type(element) is type_:\n return element\n else:\n if type(actual) is type_:\n return actual\n \n return None\n \n def remove(self, func, name=None, by_type=False, count=-1):\n \"\"\"\n Removes the given event handler from the the event descriptor.\n \n Parameters\n ----------\n func : `Any`\n The event handler to remove.\n name : `str`, Optional\n The event's name.\n by_type : `bool`, Optional\n Whether `func` was given as the type of the real event handler. Defaults to `False`.\n count : `int`, Optional\n The maximal amount of the same events to remove. Negative numbers count as unlimited. Defaults to `-1`.\n \"\"\"\n if (count == 0) or (name == 'client'):\n return\n \n name = check_name(func, name)\n \n try:\n actual = getattr(self, name)\n except AttributeError:\n return\n \n if actual is DEFAULT_EVENT_HANDLER:\n return\n \n if type(actual) is asynclist:\n for index in reversed(range(list.__len__(actual))):\n element = list.__getitem__(actual, index)\n if by_type:\n element = type(element)\n \n if element != func:\n continue\n \n list.__delitem__(actual, index)\n count -= 1\n if count == 0:\n break\n \n continue\n \n length = list.__len__(actual)\n if length > 1:\n return\n \n if length == 1:\n actual = list.__getitem__(actual, 0)\n object.__setattr__(self, name, actual)\n return\n \n else:\n if by_type:\n actual = type(actual)\n \n if actual != func:\n return\n \n object.__setattr__(self, name, DEFAULT_EVENT_HANDLER)\n \n parser_names = EVENT_HANDLER_NAME_TO_PARSER_NAMES.get(name, None)\n if (parser_names is None):\n return\n \n for parser_name in parser_names:\n parser_setting = PARSER_SETTINGS[parser_name]\n parser_setting.remove_mention(self.client_reference())\n return\n","sub_path":"hata/discord/events/event_handler_manager.py","file_name":"event_handler_manager.py","file_ext":"py","file_size_in_byte":45955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"326993875","text":"\n# Trainining with only sampling methods\nfrom pyDOE2 import lhs\nimport numpy as np\nfrom sklearn import svm\nfrom Auxiliarty_function_svm import test, check_class\nfrom Simulation import Simulation\n\nclass Sampling_based_SVM():\n def __init__(self, X_initial, max_itr, svm_classifier, report_frq, iteration, sampling_method, accuracy_method= 'F1', case = 'benchmark', svm_random_state = None, \n **kwargs):\n ''' \n Train SVM with data generated by sampling determined by method \n These data are added to initial samples (X_initial) \n\n X_initial : initial training data \n\n max_itr : maximum number of samples\n\n report_frq : report frequency\n\n iteration : number of iteration to calculate the mean/variance of svm accuracy score\n\n sampling_method: {'LHS' , 'Random'}\n\n accuracy_method: {'F1', 'MCC', 'Simple'}\n\n svm_random_state : random number\n\n '''\n self.X_initial = X_initial\n self.max_itr = max_itr\n self.report_frq = report_frq\n self.iteration = iteration\n self.sampling_method = sampling_method\n self.accuracy_method = accuracy_method\n self.svm_random_state = svm_random_state\n self.score_list = []\n \n if case == 'benchmark': \n if kwargs == None:\n raise ValueError('For benchmark case, function and feasibility condition should be set')\n else: \n self.condition = kwargs['condition']\n\n def train(self):\n score_list = self.score_list\n X_initial = self.X_initial\n dim = X_initial.shape[1]\n max_itr = self.max_itr\n report_frq = self.report_frq\n iteration = self.iteration\n sampling_method = self.sampling_method\n accuracy_method = self.accuracy_method\n\n for _num_iter in np.arange(0, max_itr + report_frq, report_frq):\n _score_lst = []\n for itr in range(iteration):\n if _num_iter == 0:\n X = X_initial.copy()\n\n else: \n if sampling_method == 'LHS':\n X_sample = lhs(dim, samples= _num_iter)\n elif sampling_method == 'Random':\n X_sample = np.random.random([_num_iter, dim])\n else:\n raise NotImplementedError('There is no such method')\n X = np.vstack([X_initial, X_sample])\n\n y = []\n for _X in X:\n if self.case == 'benchmark':\n y.append(check_class(_X, self.case, self.condition))\n else:\n y.append(check_class(_X, self.case))\n \n # Initial setting\n svm_classifier = svm.SVC(kernel='rbf', C = 10000, random_state = self.svm_random_state)\n\n # Fit the data\n svm_classifier.fit(X,y)\n\n # Test\n score = test(1000, dim, svm_classifier, check_class, method = accuracy_method)\n _score_lst.append(score)\n \n score_list.append(_score_lst)\n \n self.score_list = score_list","sub_path":"Sampling_based_SVM.py","file_name":"Sampling_based_SVM.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"388233736","text":"from __future__ import annotations\n\nfrom collections import deque\nfrom typing import Deque, Iterator, List, Optional, Set\n\nfrom app.uml.model import Class, Diagram\n\n\nclass Node:\n \"\"\"Allows searching for paths in the class diagram.\"\"\"\n\n def __init__(self, diagram: Diagram, cls: Class, parent: Optional[Node] = None):\n self._diag = diagram\n self._cls = cls\n self._parent = parent\n\n def __eq__(self, other: Node) -> bool:\n return self._cls == other._cls\n\n def __hash__(self) -> int:\n return self._cls.__hash__()\n\n def __repr__(self) -> str:\n return self._cls.__repr__()\n\n def children(self) -> Iterator[Node]:\n for cls in self._diag.related_classes(self._cls):\n yield Node(self._diag, cls, self)\n\n def path_to_root(self) -> List[Class]:\n path = []\n cur_node = self\n\n while cur_node:\n path.append(cur_node._cls)\n cur_node = cur_node._parent\n\n path.reverse()\n return path\n\n def search(self, goal: Class) -> List[Node]:\n solutions = []\n fringe: Deque[Node] = deque()\n closed: Set[Node] = set()\n fringe.append(self)\n\n while len(fringe):\n node = fringe.popleft()\n\n if node._cls == goal:\n solutions.append(node)\n\n if node not in closed:\n closed.add(node)\n fringe.extend(node.children())\n\n return solutions\n","sub_path":"app/cycle/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"303136796","text":"#!/usr/bin/python3\nfrom ewmh import EWMH\nfrom Xlib import Xatom, X, display\nfrom Xlib.protocol import request\nfrom Xlib.xobject.drawable import Window\nfrom Xlib.protocol.event import CreateNotify\nfrom subprocess import Popen\nfrom select import select\nfrom pprint import pprint\nfrom lib.window import Window\n\n\n\ndef get_property(wnd, name):\n type = request.InternAtom(display=wnd.display, name=name, only_if_exists=0).atom\n res = wnd.get_property(type, X.AnyPropertyType, 0, 100)\n if res:\n return res.value\n else:\n return []\n\n\ndef get_naming(atom):\n try:\n return request.GetAtomName(display=d.display, atom=atom).name\n except:\n print(atom)\n return 'UNKNOWN'\n\n\ndef get_pid(wnd):\n ret = get_property(wnd, '_NET_WM_PID')\n return ret[0] if len(ret) > 0 else 0\n\n\ndef check_wnd(window: Window):\n # print('checking wnd ' + get_property(window, '_NET_WM_NAME') + ' ')\n # types = get_property(window, '_NET_WM_WINDOW_TYPE')\n # print(types)\n # print(list(map(get_naming, types)))\n # print(window)\n return get_pid(window) == p1.pid\n\n\ndef got_wnd(window):\n global wnd\n print('window '+ window.get_wm_name())\n wnd = window\n\n\ndef handle_event(event):\n print('checking event ' + event.__class__.__name__)\n if isinstance(event, CreateNotify):\n check_wnd(event.window) and got_wnd(event.window)\n\n\ndef find_by_pid(pid):\n ewmh = EWMH()\n wnds = list(ewmh.getClientList())\n # pprint(wnds)\n matched = list(filter(check_wnd, wnds))\n if matched:\n got_wnd(matched[0])\n\n\nd = display.Display()\nr = d.screen().root\nr.change_attributes(event_mask=X.SubstructureNotifyMask | X.StructureNotifyMask)\nwnd = None\n\n\n\np1 = Popen([\"terminator\"])\nfind_by_pid(p1.pid)\nwhile not wnd:\n # Wait for display to send something, or a timeout of one second\n readable, w, e = select([d], [], [], 1)\n\n # if no files are ready to be read, it's an timeout\n if not readable:\n # raise TimeoutError('Can not launch subprocess')\n print('non-readable')\n find_by_pid(p1.pid)\n # if display is readable, handle as many events as have been recieved\n elif d in readable:\n i = d.pending_events()\n print('readable')\n while i > 0:\n event = d.next_event()\n handle_event(event)\n i -= 1\n\n\n\nWindow().loop()\n\np1.terminate()\n\nwhile 1: pass","sub_path":"splitter3/bak/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"467230059","text":"import serial, sys\nimport time\nimport picamera\nfrom picamera import PiCamera\nfrom picamera.array import PiRGBArray\nimport cv2\nimport numpy as np\n\n\ndef colorFilt(image, lim):\n #Convert to HSV\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n lowerBound = np.array([lim[0]*179, lim[2]*255, lim[4]*255], dtype = 'uint8')\n upperBound = np.array([lim[1]*179, lim[3]*255, lim[5]*255], dtype = 'uint8')\n\n # Use OpenCV inRange function\n mask = cv2.inRange(image, lowerBound, upperBound)\n\n return mask\n\ndef hough(mask, visuals=0):\n edge = cv2.Canny(mask, 50, 150)\n lines = cv2.HoughLines(edge, 1, np.pi/180, 20)\n\n print(type(lines))\n if lines == None:\n return\n\n if visuals == 1:\n for rho,theta in lines[:,0]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 300*(-b))\n y1 = int(y0 + 300*(a))\n x2 = int(x0 - 300*(-b))\n y2 = int(y0 - 300*(a))\n print(int(180*theta/np.pi))\n\n cv2.line(edge, (x1,y1), (x2, y2), 150, 2)\n\n cv2.imshow('Lines', edge)\n cv2.waitKey(1)\n\n # linesPaul = []\n # # Create an array we actually care about\n # for rho, theta in lines[:,0]:\n # if theta > \n\n\n\ndef main():\n yellow = [0.08, 0.4, 0.0, 0.4, 0.8, 1]\n\n camera = PiCamera()\n camera.resolution = (320, 240)\n camera.framerate = 15\n rawCapture = PiRGBArray(camera, size=(320, 240))\n\n #Allow the camera to warmup\n time.sleep(0.1)\n\n i = 0\n for frame in camera.capture_continuous(rawCapture, format='bgr', use_video_port=True):\n image = frame.array[150:320, :] #Need to decide how much to cut off\n\n mask = colorFilt(image, yellow)\n\n cv2.imshow(\"Image\", image);\n cv2.imshow(\"Masked\", mask);\n cv2.waitKey(1)\n\n hough(mask,1)\n rawCapture.truncate(0)\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214486909","text":"import math\n\nclass crashing(Actor.Actor):\n speed = 0.0\n WA = 0.00 # Wheel Angle\n CA = 275.00 # Car Angle\n fric = 0.0004\n collchk = False\n colltimecnt=0\n crash = 0\n\n def R2A(self,R):\n return (180*R/math.pi) # 라디안 -> 도 (PI -> 180)\n \n def A2R(self,A):\n return (A*math.pi/180) # 도 -> 라디안 (180 -> PI)\n\n def __init__(self):\n self.car=Container(0)\n return\n def OnCreate(self,uid):\n self.cartrans = self.car.FindComponentByType(\"TransformGroup\")\n self.carpos = self.cartrans.GetPosition()\n self.carrot = self.cartrans.GetRotation()\n return\n def OnDestory(self):\n return\n def OnEnable(self):\n return\n def OnDisable(self):\n return\n def Update(self):\n self.inkey()\n self.fricfunc()\n if(self.collchk):\n self.colliding()\n self.crash *= -1.02\n self.WA += self.crash\n self.move()\n \n def OnMessage(self, msg, number, Vector4_lparm, Vector4_wparam):\n\n if (msg == \"LButtonDown\"):\n self.speed=0.6\n self.crash = 0.01\n \n \n \n if(msg == \"Coll_detect\"):\n self.speed=self.speed*-1\n self.collchk=True\n\n\n return\n\n\n\n def fricfunc(self):\n if(self.speed>self.fric):\n self.speed-=self.fric\n elif(self.speed<0 and self.speed+self.fric<0):\n self.speed+=self.fric\n\n def inkey(self):\n\n if (self.speed != 0):\n if(self.WA<0):\n self.cartrans.Rotate(-10*self.speed,0,(0,1,0))\n self.CA -= 10*self.speed\n if(self.WA>0):\n self.cartrans.Rotate(10*self.speed,0,(0,1,0))\n self.CA += 10*self.speed\n #print(str(self.WA))\n\n def move(self):\n self.carpos.x += self.speed*(math.sin(self.A2R(self.WA+self.CA)))\n self.carpos.z += self.speed*(math.cos(self.A2R(self.WA+self.CA)))\n self.cartrans.SetPosition(self.carpos)\n\n \n def colliding(self):\n self.colltimecnt+=1\n if(self.colltimecnt==4):\n self.speed *= 0.2\n self.collchk=False\n self.colltimecnt=0\n\n def EulerToQuaternionFloat(self,euler):\n cosx2 = math.cos(euler.x / 2.0)\n sinx2 = math.sin(euler.x / 2.0)\n siny2 = math.sin(euler.y / 2.0)\n cosy2 = math.cos(euler.y / 2.0)\n sinz2 = math.sin(euler.z / 2.0)\n cosz2 = math.cos(euler.z / 2.0)\n \n x = siny2 * cosx2 * sinz2 + cosy2 * sinx2 * cosz2\n y = siny2 * cosx2 * cosz2 - cosy2 * sinx2 * sinz2\n z = cosy2 * cosx2 * sinz2 - siny2 * sinx2 * cosz2\n w = cosy2 * cosx2 * cosz2 + siny2 * sinx2 * sinz2\n \n r = Math3d.Vector4(x, y, z, w)\n\n return r\n","sub_path":"script/crashing.py","file_name":"crashing.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"302533219","text":"import inspect\nimport importlib\nimport os\nimport sys\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import ForwardRef\nfrom typing import Union\nfrom typing import Tuple\nfrom typing import Optional\nfrom typing import _GenericAlias\nfrom functools import update_wrapper\n\nfrom sortedcontainers import SortedKeyList\nfrom typeguard import check_type\n\nfrom .types import NextDispatch\nfrom .types import FunctionMixin\nfrom .types import Dispatcher\nfrom .types import DispatchedCallable\n\n\ndef _determine_priority(registry: SortedKeyList, priority: int):\n if priority is not None:\n return priority\n try:\n max_prio = max(f.priority for f in registry if f.priority < sys.maxsize)\n except ValueError:\n max_prio = -1\n return max_prio + 1\n\n\ndef metadispatch(base_func: Optional[callable] = None):\n \"\"\"This is a GenericFunction class without 'smart' registration. Why does\n this exist? Because the registration logic itself is a generic function! So\n we need a way to define a generic function that doesn't use the smart\n registration.\n \"\"\"\n\n registry = SortedKeyList(key=lambda f: f.priority)\n\n def dynamic_dispatcher(*args, **kwargs):\n \"\"\"Dispatch the registered functions.\"\"\"\n nonlocal registry\n for f in registry:\n try:\n if f.validate(args[0]):\n _kwargs = kwargs.copy()\n if '_globals' not in inspect.signature(f).parameters:\n _kwargs.pop('_globals', None)\n res = f(*args, **_kwargs)\n return res\n except NextDispatch:\n continue\n\n # let automatic typechecking in pycharm do its job\n dynamic_dispatcher: Dispatcher\n\n def register(\n check_func: Callable[[Any], bool],\n priority: int = None\n ):\n \"\"\"Unlike the actual GenericFunction class, this one only supports\n functions for checking, not other types.\n \"\"\"\n nonlocal registry\n def _wrap(func: callable):\n if isinstance(func, FunctionMixin):\n func = func.func\n new_func = DispatchedCallable(\n func=func,\n validate=check_func,\n priority=_determine_priority(registry, priority)\n )\n registry.add(new_func)\n return func\n return _wrap\n\n if base_func is None:\n def base_func(checked_input: Any, *args, **kwargs):\n raise TypeError('Valid implementation not found')\n base_func.__name__ = ''\n\n dynamic_dispatcher.register = register\n dynamic_dispatcher.registry = registry\n update_wrapper(dynamic_dispatcher, base_func)\n return dynamic_dispatcher\n\n\ndef create_default_metadispatcher(func: callable = None):\n f = metadispatch(func)\n\n @f.register(lambda c: isinstance(c, type),\n priority=100)\n def create_checker_type(val):\n \"\"\"Check against a single type.\"\"\"\n def checker(x):\n return isinstance(x, val)\n return checker\n\n @f.register(lambda val: isinstance(val, _GenericAlias),\n priority=101)\n def create_checker_generic_alias(val):\n \"\"\"Check against a single type.\"\"\"\n def checker(x):\n try:\n check_type('check', x, val)\n except TypeError:\n return False\n else:\n return True\n return checker\n\n # This func assumes strings are representations of Python objects.\n @f.register(lambda val: isinstance(val, str),\n priority=102)\n def create_checker_forward_ref(val, _globals: dict = None):\n \"\"\"Lazy load type, then check against it (attempt 1).\"\"\"\n _globals = _globals or {}\n try:\n target_type = ForwardRef(val)._evaluate(_globals, {})\n def checker(x):\n return isinstance(x, target_type)\n return checker\n except NameError:\n raise NextDispatch\n\n @f.register(lambda val: isinstance(val, str),\n priority=103)\n def create_checker_import_via_str(val):\n \"\"\"Lazy load type, then check against it (attempt 2).\"\"\"\n def checker(x):\n modname, typename = os.path.splitext(val)\n packagename = modname.split('.')[0]\n if repr(type(x)).find(packagename) == -1:\n # Avoid unnecessary imports\n return False\n mod = importlib.import_module(modname)\n target_type = getattr(mod, typename[1:])\n return isinstance(x, target_type)\n return checker\n\n @f.register(lambda val: callable(val),\n priority=104)\n def create_checker_generic_callable(val):\n \"\"\"Return the callable as-is.\"\"\"\n return val\n\n return f\n\n\n_default_metadispatcher = create_default_metadispatcher()\n\n\ndef dispatch(\n *func: Tuple[Optional[callable]],\n metadispatcher: Dispatcher = None,\n):\n if metadispatcher is None:\n metadispatcher = _default_metadispatcher\n\n if len(func) == 0:\n return lambda f: dispatch(f, metadispatcher=metadispatcher)\n elif len(func) > 1:\n raise TypeError(\n f'dispatch() takes 1 positional argument but {len(func)} were given'\n )\n\n if func[0] is None:\n def base_func(checked_input: Any, *args, **kwargs):\n raise TypeError('Valid implementation not found')\n base_func.__name__ = ''\n else:\n base_func: callable = func[0]\n\n registry = SortedKeyList(key=lambda f: f.priority)\n\n def register(\n check: Union[type, str, Callable[[Any], bool]] = None,\n priority: int = None\n ):\n nonlocal registry\n nonlocal metadispatcher\n\n def _wrap(func: callable):\n nonlocal check\n if isinstance(func, DispatchedCallable):\n func = func.func\n if check is None:\n check = list(inspect.signature(func).parameters.values())[0].annotation\n if check is inspect._empty:\n raise TypeError(\n 'You need to either register a type, or have a type '\n 'annotation in the first arg of the decorated '\n 'function.'\n )\n new_func = DispatchedCallable(\n func=func,\n validate=metadispatcher(check,\n _globals=func.__globals__),\n priority=_determine_priority(registry, priority)\n )\n registry.add(new_func)\n return func\n\n return _wrap\n\n def dynamic_dispatcher(*args, **kwargs):\n \"\"\"Dispatch the registered functions.\"\"\"\n nonlocal registry\n for f in registry:\n try:\n if f.validate(args[0]):\n res = f(*args, **kwargs)\n return res\n except NextDispatch:\n continue\n\n dynamic_dispatcher: Dispatcher\n dynamic_dispatcher.register = register\n dynamic_dispatcher.registry = registry\n\n dynamic_dispatcher.register(lambda x: True, priority=sys.maxsize)(base_func)\n update_wrapper(dynamic_dispatcher, base_func)\n\n return dynamic_dispatcher\n","sub_path":"dispatchlib/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"444349914","text":"## Donchian channel breakout strategy\n# Buy when the close at day x is the high for the given look back period\n# ex. close at day x is $130.00 and over the past 30 days (look back period, denoted lbp) is also $130.00\n# this is defined as a 'breakout channel' and is our buy signal. \n# Sell when the close at day x is the lbp min, determined similar to the lbp high\n\n\nimport sys\nfrom yahoo_finance import Share\nfrom math import floor\nimport matplotlib.pyplot as plt\n\n#start = sys.argv[1] #time period to be backtested, start format 'yyyy-mm-dd'\n#finish = sys.argv[2] #time period end, same format as above\n#symb = sys.argv[3] #stock symbol to backtest\n#lbp = sys.argv[4] #look back period for buy and sell signals\nstart = '2010-02-09'\nfinish = '2017-02-19'\nsymb = 'ibm'\n\n\n\nstockObj = Share(symb.upper())\ndata = stockObj.get_historical(start, finish)\nclose = []\ndate = []\ncashoutDate = []\nfor i in range(len(data),0,-1):\n\tclose.append(float(data[i-1]['Adj_Close']))\n\tdate.append(data[i-1]['Date'])\nlbp = 30-1\nstatus = 0\nc = []\ncash = 10000.00\nc.append(cash)\nci = float(10000)\nshares = 0\n\nfor day in range(lbp,len(close)):\n\t\n\tbreakout = max(close[day-lbp:day])\n\tstop = min(close[day-lbp:day])\n\tif (status == 0 and breakout >= close[day]):\n\t\tstatus = 1\n\t\tshares = floor(cash/close[day])\n\t\tcash = cash - shares * close[day]\n\n\tif (status == 1 and close[day] <= stop):\n\t\tstatus = 0\n\t\tcash = cash + shares * close[day]\n\t\tcashoutDate.append(date[day])\n\t\tc.append(cash)\n\t\tshares = 0\n\t\t\t\t\nif shares != 0:\n\tcash = shares * close[len(close)-1]\n\tc.append(cash)\n\t\t\t\nplt.plot(list(range(0,len(c))),c,'ro')\nplt.show()\n","sub_path":"donchian_channel_breakout.py","file_name":"donchian_channel_breakout.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142733748","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Client',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100, verbose_name='\\u0418\\u043c\\u044f')),\n ('surname', models.CharField(max_length=250, verbose_name='\\u0424\\u0430\\u043c\\u0438\\u043b\\u0438\\u044f')),\n ('age', models.IntegerField(verbose_name='\\u0412\\u043e\\u0437\\u0440\\u0430\\u0441\\u0442')),\n ('date', models.DateField(verbose_name='\\u0414\\u0430\\u0442\\u0430')),\n ('photo', models.ImageField(max_length=250, null=True, verbose_name='\\u0424\\u043e\\u0442\\u043e', upload_to='photo')),\n ('voite', models.IntegerField(default=0)),\n ],\n options={\n 'verbose_name': 'Client',\n 'verbose_name_plural': 'Clients',\n },\n ),\n ]\n","sub_path":"voite_project/clients/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"329373507","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom logging.config import fileConfig\n\nARTICLE_PER_PAGE = 15\nREPLY_PER_PAGE = 15\nCHAT_PER_PAGE = 20\nCHAT_CONNECTION_INTERVAL = 30\nDEBUG = False\nDB_CONNECTION_STRING = \"sqlite:///sqlite.db\"\nUSE_REDIS = False\nREDIS_CONNECT_ARGS = {\n \"host\": \"localhost\",\n \"port\": 6379,\n \"db\": 0,\n}\nlogger = logging.getLogger()\nfileConfig(\"logger.cnf\")\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"312598419","text":"# coding=utf-8\nfrom __future__ import print_function, absolute_import, unicode_literals\n\nimport datetime\nimport matplotlib.pyplot as plt\nimport pandas as pds\nfrom matplotlib import ticker\n\n\n# set_token(\"64530fa8930fec8fc135b8da3210ee75ffe2aba6\")\n\n\nclass Draw(object):\n def __init__(self, start_time, end_time):\n self.start_time = start_time\n self.end_time = end_time\n plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(20)) # 密度总坐标数除70\n plt.xticks(rotation=90) # 设置横坐标显示的角度,角度是逆时针,自己看\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签\n plt.rcParams['axes.unicode_minus'] = False\n\n def get_x_y(self, code, bond_code, trans_price):\n # stock_history_data = self.get_history_data(code)\n stock_history_data = pds.read_excel(\"data_202008/K线导出_{}_1分钟数据.xls\".format(code))\n stock_history_data = stock_history_data[[\"交易时间\", \"收盘价\"]][\n (stock_history_data[\"交易时间\"] > self.start_time) & (stock_history_data[\"交易时间\"] < self.end_time)].dropna(\n axis=0,\n how=\"any\")\n # stock_history_data = stock_history_data[[\"交易时间\", \"收盘价\"]]\n bond_history_data = pds.read_excel(\"data_202008/K线导出_{}_1分钟数据.xls\".format(bond_code))\n x_time = []\n y_value = []\n for _, bar in stock_history_data.iterrows():\n x_time_ = pds.to_datetime(bar[\"交易时间\"]).tz_localize(None)\n bond_price = bond_history_data[bond_history_data[\"交易时间\"] == x_time_][\"收盘价\"].values\n if len(bond_price) == 1:\n bond_price = bond_price[0]\n else:\n break\n y_value_ = bar[\"收盘价\"]\n premium_rate = bond_price / (100 / trans_price * y_value_) - 1\n premium_rt = premium_rate if premium_rate <= 0.005 else 0.005\n x_time.append(x_time_.strftime(\"%Y-%m-%d %H:%M:%S\"))\n y_value.append(premium_rt)\n print(x_time_,code,bond_code,y_value_,bond_price)\n return x_time, y_value\n\n @staticmethod\n def config():\n plt.grid() # 生成网格\n plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(20)) # 密度总坐标数除70\n plt.xticks(rotation=60, fontsize=3) # 设置横坐标显示的角度,角度是逆时针,自己看\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签\n plt.rcParams['axes.unicode_minus'] = False\n\n def draw(self, code, bond_code, trans_price, color, label, linestyle=None):\n\n x1, y1 = self.get_x_y(code, bond_code, trans_price)\n plt.plot(x1, y1, color, label=label, linestyle=linestyle, linewidth=0.5)\n\n def run(self):\n plt.figure(num=1, figsize=(15, 8), dpi=80)\n\n plt.subplot(2, 2, 1)\n self.config()\n self.draw(\"603626\", \"113521\", 8.7, \"b\", label=\"科森转债\")\n self.draw(\"300487\", \"123027\", 29.33, \"#FF0000\", label=\"蓝晓转债\")\n self.draw(\"300260\", \"123037\", 11.08, \"#00FFFF\", label=\"新莱转债\")\n self.draw(\"002727\", \"128067\", 26.83, \"#7FFFD4\", label=\"一心转债\")\n self.draw(\"603180\", \"113553\", 44.14, \"m\", label=\"金牌橱柜\")\n plt.legend(fontsize=3)\n\n plt.subplot(2, 2, 2)\n self.config()\n self.draw(\"603179\", \"113509\", 14.22, \"g\", label=\"新泉股份\")\n self.draw(\"603688\", \"113548\", 15.1, \"#FFDAB9\", label=\"石英转债\")\n self.draw(\"603089\", \"113561\", 10.23, \"#444444\", label=\"正裕转债\")\n self.draw(\"300545\", \"123038\", 25.29, \"#FFE4C4\", label=\"联得转债\")\n self.draw(\"603612\", \"113547\", 10.52, \"#660033\", label=\"索通发展\")\n plt.legend(fontsize=3)\n\n plt.subplot(2, 2, 3)\n self.config()\n self.draw(\"603035\", \"113550\", 9.65, \"#FF8C00\", label=\"常汽转债\")\n self.draw(\"601966\", \"113019\", 18.12, \"k\", label=\"玲珑轮胎\")\n self.draw(\"603313\", \"113520\", 14.28, \"#00FFFF\", label=\"百合转债\")\n self.draw(\"603733\", \"113554\", 13.27, \"#BDB76B\", label=\"仙鹤转债\")\n self.draw(\"002567\", \"128092\", 8.63, \"#ADFF2F\", label=\"唐人转债\")\n self.draw(\"601200\", \"113028\", 10.36, \"#EE82EE\", label=\"环境转债\")\n plt.legend(fontsize=3)\n\n plt.subplot(2, 2, 4)\n self.config()\n self.draw(\"002745\", \"128084\", 12.80, \"#8B0000\", label=\"木森转债\")\n self.draw(\"600105\", \"110058\", 5.04, \"#E9967A\", label=\"永鼎转债\")\n self.draw(\"600372\", \"110042\", 14.12, \"#2F4F4F\", label=\"航电转债\")\n self.draw(\"600326\", \"110060\", 7.16, \"#808080\", label=\"天路转债\")\n self.draw(\"002406\", \"128075\", 5.54, \"#00BFFF\", label=\"远东转债\")\n self.draw(\"300088\", \"123022\", 6.15, \"red\", label=\"长信转债\")\n plt.legend(fontsize=3)\n\n plt.savefig('my_picture/{}.png'.format(self.start_time.strftime('%Y-%m-%d %H:%M:%S').split(\" \")[0]), dpi=500,\n bbox_inches='tight')\n plt.show()\n\n\ndef run(start_time, days):\n day = 0\n num = 0\n start_time = datetime.datetime.strptime(start_time, \"%Y-%m-%d %H:%M:%S\")\n while True:\n if num >= days:\n break\n\n date = start_time + datetime.timedelta(days=+day)\n weekday = date.weekday()\n if weekday == 5 or weekday == 6:\n print(\"ssssss\")\n day += 1\n continue\n end_date = date + datetime.timedelta(hours=5.5)\n Draw(date, end_date).run()\n day += 1\n num += 1\n\n\nif __name__ == '__main__':\n # PremiumHistory(\"SHSE.601137\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.601137.xls\", trans_price=11.29, name=\"博威合金\").draw_picture()\n # PremiumHistory(\"SHSE.600326\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.600326.xls\", trans_price=7.16, name=\"西藏天路\").draw_picture()\n # PremiumHistory(\"SHSE.603023\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.603023.xls\", trans_price=3.99, name=\"威帝股份\").draw_picture()\n # PremiumHistory(\"SHSE.603179\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.603179.xls\", trans_price=14.22, name=\"新泉股份\").draw_picture()\n # PremiumHistory(\"SHSE.601966\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.601966.xls\", trans_price=18.12, name=\"玲珑轮胎\").draw_picture()\n # PremiumHistory(\"SHSE.603180\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SHSE.603180.xls\", trans_price=44.14, name=\"金牌橱柜\").draw_picture()\n # PremiumHistory(\"SZSE.002013\", start_time=\"2020-08-25 9:00:00\", end_time=\"2020-08-25 15:00:00\",\n # file=\"data/SZSE.002013.xls\", trans_price=7.57, name=\"中航机电\").draw_picture()\n\n # Draw(\"2020-08-25 9:00:00\", \"2020-08-25 15:00:00\").run()\n\n run(\"2020-08-5 9:30:00\", 18)\n","sub_path":"bond_history_premium.py","file_name":"bond_history_premium.py","file_ext":"py","file_size_in_byte":7123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"317073297","text":"from typing import NamedTuple\n\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\nfrom msg.models import Msg\n\n\nclass User(AbstractUser):\n phone_number: 'str' = models.CharField(max_length=255,\n null=True, blank=True)\n\n class HelloSMSMessage(NamedTuple):\n phone_number: 'str'\n username: 'str'\n\n def send_hello_sms(self):\n if not self.phone_number:\n raise ValueError('User has to have a phone number'\n 'to send a sms message.')\n hello = self.HelloSMSMessage(\n username=self.username,\n phone_number=self.phone_number,\n )\n Msg.new(hello, dispatch_now=True)\n","sub_path":"examples/ex3/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"637294633","text":"import sys, os, pickle\nfrom pathlib import PurePath\ncurrent_dir = os.path.realpath(__file__)\np = PurePath(current_dir)\nsys.path.append(str(p.parents[3]))\nfrom retrieve_performance_gain import retrieve_best_ML_and_stats_model\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\nfrom scipy.optimize import curve_fit\n\ndf_results = pd.read_pickle(str(p.parents[5])+'/test/df_results.plk')\nwith open(str(p.parents[5])+'/test/nested_results_prc.pickle', 'rb') as handle:\n nested_results_prc = pickle.load(handle) \n \n#AUC-ROC \nperformance_gain_prc = retrieve_best_ML_and_stats_model(nested_results_prc)[2]\nperformance_gain_prc_list = list(performance_gain_prc.values())\nmean_of_mean = df_results['Mean mean'].values.tolist()\n\n# #==============================================================================\n# # AUC-PRC\n# # Scatter plot: Plot performance gain vs. mean of mean value of features\n# #==============================================================================\nx = np.array(mean_of_mean)\ny = np.array(performance_gain_prc_list)\n\nfigure(num=None, figsize=(12, 8), dpi=120, facecolor='w', edgecolor='k')\nplt.plot(x, y, 'ro', label = 'Data')\nplt.xlabel(\"Mean of mean value of features\", fontsize=18)\nplt.ylabel(\"Performance gain of ML vs. Statistics\", fontsize=18)\nplt.title(\"Performance gain (AUC-PRC) vs. Mean of mean value of features\", fontsize=20)\nplt.xticks(fontsize=18)\nplt.legend(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xlim(-0.1e-15, .05e-14)\nplt.show()\n\n# def func(x, a, c, d):\n# return a*np.exp(-c*x)+d\n\n# figure(num=None, figsize=(12, 8), dpi=120, facecolor='w', edgecolor='k')\n# popt, pcov = curve_fit(func, x, y, p0=(1, 1e-3, 1))\n\n# xx = np.linspace(0, 0.05e-14)\n# yy = func(xx, *popt)\n# plt.plot(x, y, 'ro', label = 'Data')\n# plt.plot(xx, yy, 'b-', ls='--', label = 'Exponential fit')\n# plt.legend(fontsize=18)\n# plt.xlabel(\"Number of instances\", fontsize=18)\n# plt.ylabel(\"Performance gain of ML vs. Statistics\", fontsize=18)\n# plt.title(\"Performance gain (AUC-ROC) vs. Number of instances\", fontsize=20)\n# plt.xticks(fontsize=18)\n# plt.yticks(fontsize=18)\n# plt.show()","sub_path":"analysis/performance_gain_vs_metafeatures/linear_regression/mean_of_mean/AUC-PRC/gain_vs_mean_of_mean_PRC.py","file_name":"gain_vs_mean_of_mean_PRC.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"136212885","text":"import copy\r\nimport six\r\n\r\nfrom chainer.dataset import convert\r\nfrom chainer.dataset import iterator as iterator_module\r\nfrom chainer import function, variable\r\nfrom chainer.training.updater import StandardUpdater\r\n\r\nclass SubDivisionUpdater(StandardUpdater):\r\n\r\n\r\n def __init__(self, iterator, optimizer, converter=convert.concat_examples,\r\n subdivisions=1, device=None, loss_func=None):\r\n super(SubDivisionUpdater, self).__init__(\r\n iterator=iterator,\r\n optimizer=optimizer,\r\n converter=converter,\r\n device=device,\r\n loss_func=loss_func,\r\n )\r\n self._batchsize = self._iterators['main'].batch_size\r\n self._subdivisions = subdivisions\r\n self._n = int(self._batchsize / self._subdivisions)\r\n assert self._batchsize % self._subdivisions == 0, (self._batchsize, self._subdivisions)\r\n\r\n def update_core(self):\r\n batch = self._iterators['main'].next()\r\n #print(self._n)\r\n in_arrays_list = []\r\n for i in range(self._n):\r\n #in_arrays_list.append(self.converter(batch[i::self._subdivisions], self.device))\r\n in_arrays_list.append(self.converter(batch, self.device))\r\n optimizer = self._optimizers['main']\r\n loss_func = self.loss_func or optimizer.target\r\n loss_func.cleargrads()\r\n\r\n losses=[]\r\n\r\n for i, in_arrays in enumerate(in_arrays_list):\r\n if isinstance(in_arrays, tuple):\r\n in_vars = list(variable.Variable(x) for x in in_arrays)\r\n loss = loss_func(*in_vars)\r\n losses.append(loss)\r\n elif isinstance(in_arrays, dict):\r\n in_vars = {key: variable.Variable(x) for key, x in six.iteritems(in_arrays)}\r\n loss = loss_func(in_vars)\r\n losses.append(loss)\r\n else:\r\n print(type(in_arrays))\r\n loss.backward()\r\n \r\n optimizer.update()","sub_path":"utils/updater.py","file_name":"updater.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"561155706","text":"# -*- coding=utf-8 -*-\nimport re\n\n_numbers_digit = {\"零\" : 0, \"壹\" : 1, \"貳\" : 2, \"參\" : 3, \"肆\" : 4, \"伍\" : 5, \"陸\" : 6, \"柒\" : 7, \"捌\" : 8, \"玖\" : 9, \"拾\" : 10, \"兩\" : 2,\n \"〇\": 0, \"一\" : 1, \"二\" : 2, \"三\" : 3, \"四\" : 4, \"五\" : 5, \"六\" : 6, \"七\" : 7, \"八\" : 8, \"九\" : 9, \"十\" : 10, \"廿\" : 20, \"卅\" : 30, \"\" : 1}\n_numbers_unit = {\"拾\" : 10, \"十\" : 10, \"佰\" : 100, \"百\" : 100, \"仟\" : 1000, \"千\" : 1000, \"萬\" : 10000, \"億\" : 100000000, \"兆\" : 1000000000000}\n\n\ndef _below_thousand_convert(text):\n number = 0\n digit_pattern_text = \"[零壹貳參肆伍陸柒捌玖〇一二三四五六七八九兩]\"\n base_match = re.search(\"({0}?)[千仟]\".format(digit_pattern_text), text)\n if base_match is not None:\n tmp = base_match.group(1)\n number += _numbers_unit[\"千\"] * _numbers_digit[tmp]\n text = text.replace(base_match.group(), \"\")\n\n base_match = re.search(\"({0}?)[百佰]\".format(digit_pattern_text), text)\n if base_match is not None:\n tmp = base_match.group(1)\n number += _numbers_unit[\"百\"] * _numbers_digit[tmp]\n text = text.replace(base_match.group(), \"\")\n\n base_match = re.search(\"({0}?)[十拾]\".format(digit_pattern_text), text)\n if base_match is not None:\n tmp = base_match.group(1)\n number += _numbers_unit[\"十\"] * _numbers_digit[tmp]\n text = text.replace(base_match.group(), \"\")\n\n base_match = re.search(\"[廿卅]\".format(digit_pattern_text), text)\n if base_match is not None:\n tmp = base_match.group()\n number += _numbers_digit[tmp]\n text = text.replace(base_match.group(), \"\")\n\n if len(text) == 1:\n number += _numbers_digit[text]\n return number\n\n\ndef _general_number_convert(input):\n numbers = \"零壹貳參肆伍陸柒捌玖〇一二三四五六七八九兩\"\n base_unit = \"拾佰仟十百千\"\n\n numbers_only_pattern = \"[{0}]\".format(numbers)\n base_pattern = \"[{0}{1}]\".format(numbers, base_unit)\n\n start_pos = 0\n while True:\n if start_pos >= len(input):\n break\n\n pattern = \"({0}+[兆])?({0}+[億])?({0}+[萬])?({1}+[千仟])?({1}+[百佰])?({1}*[拾十廿卅])?({1})?\".format(base_pattern, numbers_only_pattern)\n pattern_search = re.compile(pattern)\n match_whole = pattern_search.search(input, start_pos)\n #match_whole = re.search(pattern, input)\n\n if match_whole is None:\n break\n\n start_pos = match_whole.end()\n whole_str = match_whole.group()\n if len(whole_str) == 0:\n start_pos = start_pos + 1\n continue\n\n number = 0\n pattern_partial = \"{0}+兆\".format(base_pattern)\n match_partial = re.search(pattern_partial, whole_str)\n if match_partial is not None:\n tmp = match_partial.group()[:-1]\n number += _below_thousand_convert(tmp) * _numbers_unit[\"兆\"]\n whole_str = whole_str.replace(match_partial.group(), \"\")\n\n pattern_partial = \"{0}+億\".format(base_pattern)\n match_partial = re.search(pattern_partial, whole_str)\n if match_partial is not None:\n tmp = match_partial.group()[:-1]\n number += _below_thousand_convert(tmp) * _numbers_unit[\"億\"]\n whole_str = whole_str.replace(match_partial.group(), \"\")\n\n pattern_partial = \"{0}+萬\".format(base_pattern)\n match_partial = re.search(pattern_partial, whole_str)\n if match_partial is not None:\n tmp = match_partial.group()[:-1]\n number += _below_thousand_convert(tmp) * _numbers_unit[\"萬\"]\n whole_str = whole_str.replace(match_partial.group(), \"\")\n\n number += _below_thousand_convert(whole_str)\n #input = re.sub(pattern, str(number), input)\n replacement = input[match_whole.start() : match_whole.end()].replace(match_whole.group(), str(number))\n input = input[:match_whole.start()] + replacement + input[match_whole.end():]\n\n return input\n\n\ndef _date_convert(input):\n while True:\n match_year = re.search(\"[零壹貳參肆伍陸柒捌玖〇一二三四五六七八九]+年\", input)\n if match_year is None:\n break\n tmp = match_year.group()[:-1]\n converted = \"\"\n for c in tmp:\n converted += str(_numbers_digit[c])\n input = input.replace(tmp, converted)\n\n while True:\n match_month = re.search(\"[十拾][壹貳一二]?月\", input)\n if match_month is None:\n break\n tmp = match_month.group()[:-1]\n month = 0\n for c in tmp:\n month += _numbers_digit[c]\n input = input.replace(tmp, str(month))\n\n while True:\n match_month = re.search(\"[壹貳參肆伍陸柒捌玖一二三四五六七八九]月\", input)\n if match_month is None:\n break\n tmp = match_month.group()[:-1]\n month = 0\n for c in tmp:\n month += _numbers_digit[c]\n input = input.replace(tmp, str(month))\n\n while True:\n match_day = re.search(\"[廿卅][壹貳參肆伍陸柒捌玖一二三四五六七八九]?[日號]\", input)\n if match_day is None:\n break\n tmp = match_day.group()[:-1]\n day = 0\n for c in tmp:\n day += _numbers_digit[c]\n input = input.replace(tmp, str(day))\n\n while True:\n match_day = re.search(\"[壹貳參一二三]?[十拾]?[壹貳參肆伍陸柒捌玖一二三四五六七八九]+[日號]\", input)\n if match_day is None:\n break\n tmp = match_day.group()[:-1]\n day = 0\n for c in tmp:\n day += _numbers_digit[c]\n input = input.replace(tmp, str(day))\n\n return input\n\ndef _clock_convert(input):\n return input\n\ndef _single_digit_convert(input):\n pattern = \"[零壹貳參肆伍陸柒捌玖〇一二三四五六七八九兩]+\"\n while True:\n match = re.search(pattern, input)\n if match is None:\n break\n\n tmp = match.group()\n if len(tmp) == 0:\n break\n text = \"\"\n for c in tmp:\n text += str(_numbers_digit[c])\n input = input.replace(tmp, text)\n\n return input\n\n\ndef convert(input):\n \"\"\"\n Convert Chinese numbers into arabic numbers.\n :param input(str): Text to convert.\n :return: Converted string.\n \"\"\"\n\n # Replace full width numbers.\n input = input.translate(str.maketrans(\"1234567890\", \"1234567890\"))\n #input = _date_convert(input)\n #input = _clock_convert(input)\n input = _general_number_convert(input)\n #input = _single_digit_convert(input)\n\n return input","sub_path":"preprocess/num_convert.py","file_name":"num_convert.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"344368073","text":"import numpy as np\nfrom hmmlearn import _hmmc\nfrom hmmlearn.utils import log_normalize\nfrom scipy.special import logsumexp\n# from pathos.multiprocessing import ProcessPool as ProcessPoolExecutor\nfrom concurrent.futures import ThreadPoolExecutor\n\n\ndef batch_forward_backward(\n log_startprob, log_transmat, framelogprob, seq_len=None,\n state_sequence=None, initial_state=None, final_state=None,\n max_workers=8\n):\n B, T, K = framelogprob.shape\n log_startprob = np.broadcast_to(log_startprob, (B, K))\n if seq_len is None:\n seq_len = B*[T]\n if state_sequence is None:\n state_sequence = B*[None]\n if initial_state is None:\n initial_state = B*[None]\n if final_state is None:\n final_state = B*[None]\n\n def fwd_bwd(args):\n log_startprob, framelogprob, seq_len, state_sequence, initial_state, final_state = args\n posteriors = np.zeros_like(framelogprob)\n framelogprob = framelogprob[:seq_len]\n posteriors[:seq_len], transitions = forward_backward(\n log_startprob, log_transmat, framelogprob,\n state_sequence=state_sequence,\n initial_state=initial_state, final_state=final_state\n )\n return posteriors, transitions\n\n with ThreadPoolExecutor(max_workers) as executor:\n posteriors, transitions = list(zip(*executor.map(\n fwd_bwd, zip(log_startprob, framelogprob, seq_len, state_sequence, initial_state, final_state)\n )))\n return np.stack(posteriors), np.stack(transitions)\n\n\ndef batch_viterbi(\n log_startprob, log_transmat, framelogprob, seq_len=None,\n state_sequence=None, initial_state=None, final_state=None, max_workers=8\n):\n B, T, K = framelogprob.shape\n log_startprob = np.broadcast_to(log_startprob, (B, K))\n if seq_len is None:\n seq_len = B*[T]\n if state_sequence is None:\n state_sequence = B*[None]\n if initial_state is None:\n initial_state = B*[None]\n if final_state is None:\n final_state = B*[None]\n\n def vit(args):\n log_startprob, framelogprob, seq_len, state_sequence, initial_state, final_state = args\n state_alignment = np.zeros(T)\n framelogprob = framelogprob[:seq_len]\n state_alignment[:seq_len] = viterbi(\n log_startprob, log_transmat, framelogprob,\n state_sequence=state_sequence,\n initial_state=initial_state, final_state=final_state\n )\n return state_alignment\n\n with ThreadPoolExecutor(max_workers) as executor:\n state_alignments = list(executor.map(\n vit, zip(log_startprob, framelogprob, seq_len, state_sequence, initial_state, final_state)\n ))\n return np.stack(state_alignments)\n\n\ndef forward_backward(\n log_startprob, log_transmat, framelogprob,\n state_sequence=None, initial_state=None, final_state=None\n):\n log_startprob = np.array(log_startprob)\n log_transmat = np.array(log_transmat)\n framelogprob = np.array(framelogprob)\n T, K = framelogprob.shape\n if state_sequence is not None:\n state_sequence = squeeze_sequence(state_sequence)\n log_startprob, log_transmat, framelogprob = prepare_obvserved_state_sequence(\n log_startprob, log_transmat, framelogprob, state_sequence\n )\n else:\n if initial_state is not None:\n log_startprob = set_initial_state(log_startprob, initial_state)\n if final_state is not None:\n framelogprob = set_final_state(framelogprob, final_state)\n\n posteriors, transitions = _forward_backward(\n log_startprob, log_transmat, framelogprob\n )\n\n if state_sequence is not None:\n posteriors, transitions = invert_observed_state_sequence(\n posteriors, transitions, state_sequence=state_sequence, n_states=K\n )\n\n return posteriors, transitions\n\n\ndef viterbi(\n log_startprob, log_transmat, framelogprob,\n state_sequence=None, initial_state=None, final_state=None\n):\n log_startprob = np.array(log_startprob)\n log_transmat = np.array(log_transmat)\n framelogprob = np.array(framelogprob)\n if state_sequence is not None:\n state_sequence = squeeze_sequence(state_sequence)\n log_startprob, log_transmat, framelogprob = prepare_obvserved_state_sequence(\n log_startprob, log_transmat, framelogprob, state_sequence\n )\n return state_sequence[_viterbi(log_startprob, log_transmat, framelogprob)]\n else:\n if initial_state is not None:\n log_startprob = set_initial_state(log_startprob, initial_state)\n if final_state is not None:\n framelogprob = set_final_state(framelogprob, final_state)\n return _viterbi(log_startprob, log_transmat, framelogprob)\n\n\ndef prepare_obvserved_state_sequence(\n log_startprob, log_transmat, framelogprob, state_sequence=None\n):\n \"\"\"\n transforms transition matrix to a large left to right hmm when state\n sequence is observed.\n\n Args:\n log_startprob:\n log_transmat:\n framelogprob:\n state_sequence:\n\n Returns:\n\n \"\"\"\n seqlen = len(state_sequence)\n log_startprob = log_startprob[state_sequence]\n log_mask = np.log(np.eye(seqlen) + np.eye(seqlen, k=1))\n log_transmat = log_transmat[state_sequence[:, None], state_sequence] + log_mask\n framelogprob = framelogprob[:, state_sequence]\n framelogprob[-1] = framelogprob[0] = -np.inf\n framelogprob[0, 0] = framelogprob[-1, -1] = 0.\n return log_startprob, log_transmat, framelogprob\n\n\ndef invert_observed_state_sequence(\n posteriors, transitions, state_sequence, n_states\n):\n \"\"\"\n computes posteriors and transitions for original hmm states\n\n Returns:\n\n \"\"\"\n n_steps = posteriors.shape[0]\n posteriors_ = np.zeros((n_steps, n_states))\n transitions_ = np.zeros((n_states, n_states))\n np.add.at(posteriors_, (np.arange(n_steps)[:, None], state_sequence), posteriors)\n np.add.at(transitions_, (state_sequence[:, None], state_sequence), transitions)\n return posteriors_, transitions_\n\n\ndef squeeze_sequence(seq):\n \"\"\"\n remove similar consecutive states\n\n Args:\n seq:\n\n Returns:\n\n \"\"\"\n return np.array([seq[i] for i in range(len(seq)) if i == 0 or seq[i] != seq[i - 1]])\n\n\ndef set_initial_state(logstartprob, initial_state):\n logstartprob = -np.inf*np.ones_like(logstartprob)\n logstartprob[initial_state] = 0.\n return logstartprob\n\n\ndef set_final_state(framelogprob, final_state):\n framelogprob[-1] = -np.inf\n framelogprob[-1, final_state] = 0.\n return framelogprob\n\n\ndef _forward_backward(log_startprob, log_transmat, framelogprob):\n logprob, alpha = _do_forward_pass(\n log_startprob, log_transmat, framelogprob\n )\n beta = _do_backward_pass(log_startprob, log_transmat, framelogprob)\n posteriors = _compute_posteriors(alpha, beta)\n expected_transitions = _compute_expected_transitions(\n log_transmat, framelogprob, alpha, beta\n )\n return posteriors, expected_transitions\n\n\ndef _do_forward_pass(log_startprob, log_transmat, framelogprob):\n n_samples, n_components = framelogprob.shape\n fwdlattice = np.zeros((n_samples, n_components))\n _hmmc._forward(\n n_samples, n_components, log_startprob, log_transmat, framelogprob,\n fwdlattice\n )\n return logsumexp(fwdlattice[-1]), fwdlattice\n\n\ndef _do_backward_pass(log_startprob, log_transmat, framelogprob):\n n_samples, n_components = framelogprob.shape\n bwdlattice = np.zeros((n_samples, n_components))\n _hmmc._backward(\n n_samples, n_components, log_startprob, log_transmat, framelogprob,\n bwdlattice\n )\n return bwdlattice\n\n\ndef _compute_expected_transitions(\n log_transmat, framelogprob, fwdlattice, bwdlattice):\n n_samples, n_components = framelogprob.shape\n log_xi_sum = np.full((n_components, n_components), -np.inf)\n _hmmc._compute_log_xi_sum(\n n_samples, n_components,\n fwdlattice, log_transmat, bwdlattice, framelogprob, log_xi_sum\n )\n return np.exp(log_xi_sum)\n\n\ndef _compute_posteriors(fwdlattice, bwdlattice):\n # gamma is guaranteed to be correctly normalized by logprob at\n # all frames, unless we do approximate inference using pruning.\n # So, we will normalize each frame explicitly in case we\n # pruned too aggressively.\n log_gamma = fwdlattice + bwdlattice\n log_normalize(log_gamma, axis=1)\n\n return np.exp(log_gamma)\n\n\ndef _viterbi(log_startprob, log_transmat, framelogprob):\n n_samples, n_components = framelogprob.shape\n ali, logprob = _hmmc._viterbi(\n n_samples, n_components, log_startprob, log_transmat, framelogprob\n )\n return ali\n","sub_path":"padertorch/contrib/je/modules/hmm_utils.py","file_name":"hmm_utils.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"361450426","text":"from flask_restful import Resource\r\nfrom models import file as f\r\nfrom os.path import exists\r\nimport json\r\n\r\nfile = '/home/hcesar/Documents/python_app/magic_cards_migration/tmp/cards_db.txt'\r\n\r\nclass GetCards(Resource):\r\n def get(self, id):\r\n\r\n if not exists(file):\r\n return {\"status\": \"HTTP 404\"}\r\n\r\n d =f.read_file(file)\r\n\r\n lines = d.split(\"\\n\")\r\n data = []\r\n list_item = []\r\n\r\n for line in lines:\r\n if not line == \"\":\r\n data = data + json.loads(line)\r\n print(line)\r\n\r\n for i in data:\r\n if i['GathererId'] == str(id):\r\n list_item.append(i)\r\n\r\n print(list_item)\r\n\r\n return {\"status\": \"success\", \"data\": list_item}, 200\r\n","sub_path":"resources/get_cards.py","file_name":"get_cards.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"339511338","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 25 10:27:59 2021\r\n\r\n@author: oislen\r\n\"\"\"\r\nimport os\r\nimport sys\r\nsys.path.append(os.path.dirname(os.getcwd()))\r\nimport cons\r\nimport numpy as np\r\nimport pandas as pd\r\nimport spacy\r\nimport langdetect\r\nimport re\r\nlangdetect.DetectorFactory.seed = 0\r\n# custom functions\r\nfrom normalise_tweet import normalise_tweet\r\nfrom spell_corrector import spell_corrector\r\nfrom token_dist_check import token_dist_check\r\n\r\n# TODO:\r\n# create custom word embeddings with word2vec (gensim)\r\n# GloVe (word vector embeddings)\r\n# lots of text cleaning (nltk?)\r\n\r\n# load in the raw data files\r\ntrain = pd.read_csv(cons.raw_train_fpath)\r\ntest = pd.read_csv(cons.raw_test_fpath)\r\nsample_submission = pd.read_csv(cons.raw_sample_submission_fpath)\r\n\r\n# dimensions of raw data files\r\ntrain.shape\r\ntest.shape\r\nsample_submission.shape\r\n\r\n# columns within raw data files\r\ntrain.columns\r\ntest.columns\r\nsample_submission.columns\r\n\r\n# view head of raw data files\r\ntrain.head()\r\ntest.head()\r\nsample_submission.head()\r\n\r\n# number of mising values per column\r\ntrain.isnull().sum()\r\ntest.isnull().sum()\r\nsample_submission.isnull().sum()\r\n\r\n# distinct values\r\ntrain.keyword.value_counts()\r\ntrain.target.value_counts()\r\ntrain.location.value_counts()\r\ntrain.text.value_counts()\r\n\r\n# crosstabs\r\ncrosstab_keywords_target = pd.crosstab(index = train.keyword, columns = train.target)\r\ncrosstab_location_target = pd.crosstab(index = train.location, columns = train.target)\r\ncrosstab_text_target = pd.crosstab(index = train.text, columns = train.target)\r\n\r\n# combine train and test\r\ntrain['dataset'] = 'train'\r\ntest['target'] = np.nan\r\ntest['dataset'] = 'test'\r\ndata = pd.concat(objs = [train, test], ignore_index = True)\r\n\r\n# determine which the languages of each tweet\r\n# data['language'] = data['text'].apply(lambda x: langdetect.detect(x))\r\n\r\n# run spell corrector\r\n# note this is super slow due to for loop iterating over each word in each tweet!\r\n# could alternatively create dictionary of incorrect_spelling:correct_spelling and map results acorss all strings?\r\n# data['text_spell_checked'] = data['text'].apply(lambda x: spell_corrector(x, lang = 'en'))\r\n\r\n# create spacy instance \r\nnlp = spacy.load('en_core_web_sm')\r\n\r\n# run text normalisation function\r\ndata['text_norm'] = data['text'].apply(lambda x: normalise_tweet(tweet = x, nlp = nlp, norm_configs = cons.norm_configs))\r\n\r\n# find lengths of normalised text\r\n# some lengths are zero\r\ndata['text_norm_len'] = data['text_norm'].apply(lambda x: len(x))\r\n\r\n# remove special @ characters\r\ndata['text_norm_clean'] = data['text_norm'].apply(lambda x: re.sub('@', '', x))\r\n\r\n# plot the tokens distribution\r\ntoken_dist_check(data = data, col ='text_norm_clean')\r\n\r\n# extract out all tokens seperated by spaces\r\ntokens = [word for tweet in data['text_norm_clean'].to_list() for word in tweet.split(' ')]\r\n# count up all tokens\r\ntokens_series = pd.Series(tokens).value_counts()\r\n# examine tokens with 1 occuence\r\ntokens_series_occur1 = tokens_series[tokens_series == 1]\r\ntokens_series_occur1.head(25)\r\n\r\n","sub_path":"competitions/Disaster_Tweets/scripts/edas/eda_raw_data.py","file_name":"eda_raw_data.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"394914759","text":"import itertools\nN, M = map(int,input().split())\nspace = []\nclist, hlist = [],[] #clist는 치킨집이 있는 좌표를 나타냄, hlist는 집이 있는 좌표를 나타내는 리스트\n\nfor i in range(N):\n a = list(map(int,input().split()))\n for s in range(N):\n if a[s] == 2:\n clist.append([i,s])\n if a[s] == 1:\n hlist.append([i,s])\n\n space.append(a)\n\nc = list (map(tuple, itertools.combinations(clist, M) ) ) # M개의 치킨집을 골라야 함으로.\nanswer = []\n\nprint(c)\nfor case in c:\n newclist = case\n result = []\n\n for y, x in hlist:\n dlist = []\n for cy,cx in newclist:\n d = abs(cy-y) + abs(cx-x)\n dlist.append(d)\n \n result.append(min(dlist))\n\n print(result)\n answer.append(sum(result))\n\nprint(min(answer))\n","sub_path":"BoJ/BoJ.15686.py","file_name":"BoJ.15686.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102158034","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom region_of_interest import get_RoI_vertices, apply_Region_of_Interest, draw_RoI\nfrom image_undistortion import get_objpoints_imgpoints_from_chessboard_images, cal_undistort\nfrom image_warping import get_PerspectiveTrans_vertices, image_warp\nfrom sliding_window_search import window_mask, find_window_centroids, apply_window_centroids_mask, polynomial_fit\n\ndef apply_color_threshold(img, color_space_conversion, color_thres):\n C012 = cv2.cvtColor(img, color_space_conversion)\n\n C0 = C012[:, :, 0]\n C1 = C012[:, :, 1]\n C2 = C012[:, :, 2]\n\n C0_binary_output = np.zeros_like(C0)\n C1_binary_output = np.zeros_like(C1)\n C2_binary_output = np.zeros_like(C2)\n\n C0_binary_output[(C0 > color_thres[0][0]) & (C0 < color_thres[0][1])] = 1\n C1_binary_output[(C1 > color_thres[1][0]) & (C1 < color_thres[1][1])] = 1\n C2_binary_output[(C2 > color_thres[2][0]) & (C2 < color_thres[2][1])] = 1\n\n return C0_binary_output, C1_binary_output, C2_binary_output\n\ndef image_process_pipeline(image, image_undistortion_params, previous_centers=None):\n # Input RGB\n\n # Image undistortion\n objpoints = image_undistortion_params['objpoints']\n imgpoints = image_undistortion_params['imgpoints']\n\n RoI_vertices = get_RoI_vertices(image)\n\n undistorted = cal_undistort(image, objpoints, imgpoints)\n\n # Apply color space thresold\n LAB_space = cv2.COLOR_RGB2LAB\n LAB_thres = [[210, 255], [0, 255], [150, 255]] # lower and upper bounds for L, A and B channel\n L_binary_output, A_binary_output, B_binary_output = apply_color_threshold(undistorted, LAB_space, LAB_thres)\n\n # Apply region of interest\n L_binary_output = apply_Region_of_Interest(L_binary_output, RoI_vertices)\n B_binary_output = apply_Region_of_Interest(B_binary_output, RoI_vertices)\n\n # Combine L and B binary output as final output\n bin_output = np.zeros_like(L_binary_output)\n bin_output[(L_binary_output == 1) | (B_binary_output == 1)] = 1\n\n # # Warped\n PerspectiveTrans_vertices = get_PerspectiveTrans_vertices(undistorted)\n #\n offsets = {\n 'vertical_offset': 670,\n 'horizontal_offset': 500\n }\n warped = image_warp(bin_output, PerspectiveTrans_vertices, offsets)\n\n # return np.array(cv2.merge((warped*255,warped*255,warped*255)),np.uint8)\n\n # find window centroids\n window_search_param = {\n 'window_width': 50,\n 'window_height': 80, # Break image into 9 vertical layers since image height is 720\n 'margin': 100, # How much to slide left and right for searching\n }\n\n window_centroids = find_window_centroids(warped, previous_centers=previous_centers, **window_search_param)\n\n l_points, r_points = apply_window_centroids_mask(warped, window_centroids, **window_search_param)\n\n ploty = np.linspace(0, 719, num=720).astype(np.uint)\n left_fitx, left_fit = polynomial_fit(l_points, ploty, return_fit=True)\n right_fitx, right_fit = polynomial_fit(r_points, ploty, return_fit=True)\n\n # for x, y in zip(left_fitx, ploty):\n # cv2.circle(undistorted, (np.int_(x), y), 1, (255, 0, 0))\n #\n # for x, y in zip(right_fitx, ploty):\n # cv2.circle(undistorted, (np.int_(x), y), 1, (0, 0, 255))\n\n y_eval = np.max(ploty)\n left_curverad = ((1 + (2 * left_fit[0] * y_eval + left_fit[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit[0])\n right_curverad = ((1 + (2 * right_fit[0] * y_eval + right_fit[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit[0])\n\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n\n # Unwarp color_warp\n newwarp = image_warp(color_warp, PerspectiveTrans_vertices, offsets, unwarp=True)\n\n # Combine color_warp and the original image\n undistorted = draw_RoI(undistorted, RoI_vertices)\n result = cv2.addWeighted(undistorted, 1, newwarp, 0.3, 0)\n\n image = result\n\n return image\n\ndef get_lr_points(undistorted, image_warping_params, RoI_vertices, window_search_params=None, previous_centers=None):\n # Apply color space thresold\n LAB_space = cv2.COLOR_RGB2LAB\n LAB_thres = [[210, 255], [0, 255], [150, 255]] # lower and upper bounds for L, A and B channel\n L_binary_output, A_binary_output, B_binary_output = apply_color_threshold(undistorted, LAB_space, LAB_thres)\n\n # Apply region of interest\n L_binary_output = apply_Region_of_Interest(L_binary_output, RoI_vertices)\n B_binary_output = apply_Region_of_Interest(B_binary_output, RoI_vertices)\n\n # Combine L and B binary output as final output\n bin_output = np.zeros_like(L_binary_output)\n bin_output[(L_binary_output >= 1) | (B_binary_output >= 1)] = 1\n\n # # Warped\n PerspectiveTrans_vertices = image_warping_params['PerspectiveTrans_vertices']# get_PerspectiveTrans_vertices(undistorted)\n offsets = image_warping_params['offsets']\n\n warped = image_warp(bin_output, PerspectiveTrans_vertices, offsets)\n\n # return np.array(cv2.merge((warped*255,warped*255,warped*255)),np.uint8)\n\n # find window centroids\n if window_search_params is None:\n window_search_params = {\n 'window_width': 50,\n 'window_height': 40, # Break image into 9 vertical layers since image height is 720 #80\n 'margin': 100, # How much to slide left and right for searching\n }\n\n window_centroids = find_window_centroids(warped, previous_centers=previous_centers, **window_search_params)\n\n l_points, r_points = apply_window_centroids_mask(warped, window_centroids, **window_search_params)\n\n return l_points, r_points\n\n# import glob\n# chessboard_image_paths = glob.glob('../camera_cal/calibration*.jpg')\n#\n# objpoints, imgpoints = get_objpoints_imgpoints_from_chessboard_images(chessboard_image_paths, 9, 6)\n#\n# image_undistortion_params = {'objpoints': objpoints, 'imgpoints': imgpoints}\n#\n# img = cv2.imread(\"../test_images/test1.jpg\") # project_video2.jpg\n# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n#\n# img = image_process_pipeline(img, image_undistortion_params)\n# plt.imshow(img, cmap='gray')\n# plt.show()\n# plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))","sub_path":"code/image_processing_pipeline.py","file_name":"image_processing_pipeline.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"203321764","text":"import sys\nln = sys.stdin.readline\n\nN = int(ln())\narr = list(map(int, ln().split()))\nmax_val = 2\ncheck = [0] * 41\n\nfor i in arr:\n check[i] += 1\n\nfor i in check:\n if i > max_val:\n print(0)\n exit()\n max_val = i\n\na = check.count(2)\nprint(2 ** (a + (1 if 1 in check else 0)))\n","sub_path":"김순석/백준특강/boj_12907_동물원.py","file_name":"boj_12907_동물원.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"649645174","text":"\"\"\"\nThis module contains class for fetching and showing rss-feed\n\"\"\"\n\n\nimport sys\nimport urllib.error\nimport feedparser\nfrom collections import namedtuple\nimport time\nimport json\nfrom rss_reader.cache_handlers import save_feed_into_cache\nfrom rss_reader import string_handlers\nfrom rss_reader.image_handlers import get_img_container, if_link_is_image\n\n\nclass RssParser:\n \"\"\"\n This class parses rss-feed and presents it in readable format\n \"\"\"\n def __init__(self, url, limit):\n self.url = url\n self.limit = limit\n self.items = []\n self.name = ''\n\n def get_feed(self):\n \"\"\"\n This function parses rss-feed\n :return: list with namedtuples representing feed items\n \"\"\"\n possible_endings = ('rss', 'rss/')\n if not self.url or not self.url.endswith(possible_endings):\n print('Please check URL(is RSS?) and Internet connection')\n sys.exit()\n try:\n data = feedparser.parse(self.url)\n except urllib.error.URLError:\n print('Please input correct URL')\n sys.exit()\n self.get_content(data)\n return self.items\n\n def get_content(self, data):\n \"\"\"\n This function aggregates feed from row data\n :param data: a bunch of raw data\n \"\"\"\n self.name = name = data['feed'].get('title')\n for feed in data['entries']:\n title = feed.get('title', 'Absence of title')\n link = feed.get('link', 'Absence of link')\n date = feed.get('published_parsed', 'Absence of date')\n img = get_img_container(link)\n summary_list = []\n links = []\n if feed.get('summary'):\n summary_list = [feed.get('summary')]\n if feed.get('links'):\n uncleaned_links = feed.get('links')\n links = string_handlers.get_links(uncleaned_links)\n img.extend(if_link_is_image(uncleaned_links))\n fields = 'name, title, link, date, img, content, links'\n item = namedtuple('item', fields)._make((name, title, link, date, img, summary_list, links))\n save_feed_into_cache(item)\n self.items.append(item)\n\n\ndef print_feed(list_with_items):\n \"\"\"\n Prints feed in readable format\n \"\"\"\n result_str = list_with_items[0].name + '\\n'\n for item in list_with_items:\n item_as_str = (f'Title: {item.title}\\nLink: {item.link}\\n'\n f'Date: {time.strftime(\"%y-%m-%d %H:%M\", tuple(item.date))}')\n result_str += item_as_str\n result_str += string_handlers.get_str_content(item.content)\n result_str += string_handlers.get_img_as_str(item.img)\n result_str += string_handlers.get_links_as_str(item.links) + '\\n\\n'\n return result_str\n\n\ndef convert_to_json(data):\n \"\"\"\n Converts feed items in json format\n \"\"\"\n return json.dumps({'items': [item._asdict() for item in data]}, ensure_ascii=False, indent=2)\n","sub_path":"rss_reader/rss_reader/rss_parser.py","file_name":"rss_parser.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"256407939","text":"\n\n#calss header\nclass _BAROQUE():\n\tdef __init__(self,): \n\t\tself.name = \"BAROQUE\"\n\t\tself.definitions = [u'relating to the heavily decorated style in buildings, art, and music that was popular in Europe in the 17th century and the early part of the 18th century: ']\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/_baroque.py","file_name":"_baroque.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"299456974","text":"import os\nimport pymongo\nfrom pymongo import MongoClient\nfrom datetime import datetime \n\n# Connexion au deamon\napp = MongoClient('localhost', 27017)\n\n# Base 1 qui recupère toutes les données sans sélection\ndb1 = app[\"database_1\"]\ncollection1 = db1[\"events\"]\n# Base 2 qui filtre\ndb2 = app[\"database_2\"]\ncollection2 = db2[\"processed\"]\n\n#### On écoute la collection et on est notifié après chaque insertion dans la collection\npipeline = [{'$match': {'operationType': 'insert'}}]\nwith collection1.watch(pipeline) as stream:\n for insert_change in stream:\n result = insert_change[\"fullDocument\"]\n data = result[\"Pays\"]\n tag = collection2.find_one({\"Pays\": data})\n if tag == None: # si aucune corrspondance dans la base2 (propre) => on insert\n collection2.insert_one(result)\n print(\"nouvelle insertion\")\n else: # Au cas contraire on met juste à jour la date de l'existant\n collection2.update_one({ \"Pays\": data}, { \"$set\": {\"Date\": datetime.now()}})\n print(\"Date mise à jour\")","sub_path":"watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"471421339","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0006_require_contenttypes_0002'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ChatUser',\n fields=[\n ('user', models.OneToOneField(primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='message',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.TextField()),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'ordering': ['date'],\n },\n ),\n migrations.CreateModel(\n name='room',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('room_id', models.TextField()),\n ('room_name', models.CharField(default=b'', max_length=30)),\n ('users', models.ManyToManyField(to='chat.ChatUser', blank=True)),\n ],\n ),\n migrations.AddField(\n model_name='message',\n name='room',\n field=models.ForeignKey(related_name='room', to='chat.room'),\n ),\n migrations.AddField(\n model_name='message',\n name='sender',\n field=models.ForeignKey(related_name='sender', to='chat.ChatUser'),\n ),\n migrations.AddField(\n model_name='chatuser',\n name='dialogs',\n field=models.ManyToManyField(to='chat.room', blank=True),\n ),\n migrations.AddField(\n model_name='chatuser',\n name='friends',\n field=models.ManyToManyField(related_name='friends_rel_+', to='chat.ChatUser', blank=True),\n ),\n ]\n","sub_path":"chat/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"37762663","text":"#!/usr/bin/python\nimport sys\nimport random\n\n# Global variables for the KB set, the INFER set and the set of identifiers\nkb = []\ninfer = []\nidentifiers = []\n\nclass Expression:\n \"\"\"\n A class for expressions. Expressions can either be unary or binary. The value of the operator can be one of\n the following: CONSTANT, IDENTIFIER, NEG, AND, OR, IMPLIES or EQUIV. Expressions always have an operator.\n CONSTANT and IDENTIFIER expressions also have a value for atom. Expressions with the NEG operator store the\n expression which is negated in operand1. Binary expressions (AND, OR, IMPLIES and EQUIV) store the left and right\n side of the expression in operand1 and operand2, respectively.\n \"\"\"\n\n def __init__(self, operator=None, atom=None, operand1=None, operand2=None):\n self.operator = operator\n self.atom = atom\n self.operand1 = operand1\n self.operand2 = operand2\n\ndef match(str, sentence):\n \"\"\"\n Checks whether the expected sequence of characters is actually in the sentence.\n If true, it returns the sentence with the expected sequence removed. If false, it throws an error.\n :param str: The character(s) to be matched\n :param sentence: The sentence to match str with\n :return: The input sentence with the matched character(s) removed\n \"\"\"\n assert str == sentence[:len(str)], \"Parsing failed. Expected \" + str\n\n if (len(sentence[len(str):]) == 0):\n # This only happens when the sentence ends with a ')', which would make the function return an empty string\n return \" \"\n\n return sentence[len(str):]\n\n\ndef make_constant_expression(value):\n \"\"\"\n Creates a constant expression (True or False)\n :param value: The truth value of the constant expression\n :return: An expression of type CONSTANT\n \"\"\"\n return Expression(operator=\"CONSTANT\", atom=value)\n\ndef make_identifier(id):\n \"\"\"\n If the input identifier is 'true' or 'false', this function creates a constant expression.\n Otherwise, it creates a new identifier with name id (if it does not already exist)\n :param id: The input identifier\n :return: Either an expression of type CONSTANT with value True or False,\n or an expression of type IDENTIFIER with the value in id\n \"\"\"\n if id == 'false':\n return make_constant_expression(False)\n if id == 'true':\n return make_constant_expression(True)\n\n if id not in identifiers:\n identifiers.append(id)\n\n return Expression(operator=\"IDENTIFIER\", atom=id)\n\ndef make_negation(expression):\n \"\"\"\n Makes a negation from the input expression\n :param expression: The expression to be negated\n :return: The negated expression\n \"\"\"\n return Expression(operator=\"NEG\", operand1=expression)\n\ndef make_binary_expression(operator, expression1, expression2):\n \"\"\"\n Makes a binary expressions from two expressions and an operator\n :param operator: The operator of the binary expression. This can be AND, OR, IMPLIES or EQUIV\n :param expression1: The expression on the left side of the operator\n :param expression2: The expression on the right side of the operator\n :return: A binary expression containing the input expressions and operator\n \"\"\"\n return Expression(operator=operator, operand1=expression1, operand2=expression2)\n\ndef print_expression(expression, end=True):\n \"\"\"\n Recursively prints an expression\n :param expression: The expression to be printed\n :param end: Whether a new line should be inserted after the last print statement\n \"\"\"\n if expression.operator == \"CONSTANT\":\n if end:\n print(expression.atom)\n else:\n print(expression.atom, end='')\n return\n\n if expression.operator == \"IDENTIFIER\":\n if end:\n print(expression.atom)\n else:\n print(expression.atom, end='')\n return\n\n if expression.operator == \"NEG\":\n print(\"!\", end='')\n print_expression(expression.operand1, end)\n return\n\n print(\"(\", end='')\n\n print_expression(expression.operand1, end=False)\n\n if (expression.operator == \"AND\"):\n print(\" * \", end='')\n\n if (expression.operator == \"OR\"):\n print(\" + \", end='')\n\n if (expression.operator == \"IMPLIES\"):\n print(\" => \", end='')\n\n if (expression.operator == \"EQUIV\"):\n print(\" <=> \", end='')\n\n print_expression(expression.operand2, end=False)\n\n if end:\n print(\")\")\n else:\n print(\")\", end='')\n\ndef print_expression_sets():\n \"\"\"\n Prints an expression set\n \"\"\"\n print(\"===============\")\n\n print(\"KB:\")\n for sen in kb:\n print_expression(sen)\n\n print()\n\n print(\"INFER:\")\n for sen in infer:\n print_expression(sen)\n\n print(\"===============\\n\")\n\n##\n# Start of recursive parsing functions\n# These functions recursively build a single expression. It checks whether the next part of the sentence is\n# either an equivalence, implication, disjunction, conjunction, term (a negation or term within brackets)\n# or atom (True, False or an identifier), in this order. If the program encounters a term within brackets, it\n# recursively calls parse_equivalence on the term\n##\n\ndef parse_atom(sentence):\n idx = 0\n id = ''\n\n assert sentence[idx].isalpha(), \"Parse error, expected false, true, identifier or (expression)\"\n\n while idx < len(sentence) and sentence[idx].isalpha():\n id += sentence[idx]\n idx += 1\n\n if idx != len(sentence):\n sentence = sentence[idx:]\n\n return make_identifier(id), sentence\n\ndef parse_term(sentence):\n if sentence[0] == \"!\":\n e = Expression()\n sentence = match(\"!\", sentence)\n e, sentence = parse_term(sentence)\n return make_negation(e), sentence\n\n if sentence[0] == \"(\":\n e = Expression()\n sentence = match(\"(\", sentence)\n e, sentence = parse_equivalence(sentence)\n sentence = match(\")\", sentence)\n return e, sentence\n\n return parse_atom(sentence)\n\ndef parse_conjunction(sentence):\n e0 = Expression()\n e0, sentence = parse_term(sentence)\n\n if (sentence[0] == '*'):\n e1 = Expression()\n sentence = match(\"*\", sentence)\n e1, sentence = parse_term(sentence)\n\n return make_binary_expression(\"AND\", e0, e1), sentence\n\n return e0, sentence\n\ndef parse_disjunction(sentence):\n e0 = Expression()\n e0, sentence = parse_conjunction(sentence)\n\n if (sentence[0] == '+'):\n e1 = Expression()\n sentence = match(\"+\", sentence)\n e1, sentence = parse_conjunction(sentence)\n\n return make_binary_expression(\"OR\", e0, e1), sentence\n\n return e0, sentence\n\ndef parse_implication(sentence):\n e0 = Expression()\n e0, sentence = parse_disjunction(sentence)\n\n if (sentence[0] == '='):\n e1 = Expression()\n sentence = match(\"=>\", sentence)\n e1, sentence = parse_disjunction(sentence)\n\n return make_binary_expression(\"IMPLIES\", e0, e1), sentence\n\n return e0, sentence\n\ndef parse_equivalence(sentence):\n e0 = Expression()\n e0, sentence = parse_implication(sentence)\n\n if (sentence[0] == '<'):\n e1 = Expression()\n sentence = match(\"<=>\", sentence)\n e1, sentence = parse_implication(sentence)\n\n return make_binary_expression(\"EQUIV\", e0, e1), sentence\n\n return e0, sentence\n\n##\n# End of set of recursive parsing functions\n##\n\ndef parse_sentence(sentence):\n \"\"\"\n This function recursively parses a sentence\n :param sentence: A sentence to be parsed\n :return: A parsed expression\n \"\"\"\n e = Expression()\n e, sentence = parse_equivalence(sentence)\n\n return e\n\ndef parse_sentence_set(set, parsed_set):\n \"\"\"\n Parses each sentence in the set and adds it to either kb or infer\n :param set: A set of sentences to be parsed\n :param parsed_set: The (initially) empty set of parsed sentences. This is either kb or infer (both are global)\n \"\"\"\n for sentence in set:\n sentence = sentence.replace(\" \", \"\").lower()\n parsed_set.append(parse_sentence(sentence))\n\ndef parse_input():\n \"\"\"\n Reads a model from the input file, parses the KB and INFER sentence sets and stores it in kb and infer\n \"\"\"\n assert len(sys.argv) > 1, \"No arguments given. Please provide a model in an input file as described in the pdf\"\n\n input_file = sys.argv[1]\n\n f = open(input_file, \"r\")\n infile = f.read()\n data = eval(infile)\n\n print(\"Complete input: \", data)\n assert 'KB' in data.keys(), \"Parsing failed, expected input to contain element 'KB'\"\n assert 'INFER' in data.keys(), \"Parsing failed, expected input to contain element 'INFER'\"\n\n parse_sentence_set(data['KB'], kb)\n parse_sentence_set(data['INFER'], infer)\n\n print(\"Identifiers: \", identifiers)\n\ndef evaluate_expression(e, model):\n \"\"\"\n Determines the truth value of a single expression\n :param e: The expression to be evaluated\n :param model: The model containing the evaluations of the identifiers\n :return: The truth value of the expression\n \"\"\"\n if e.operator == \"CONSTANT\":\n return e.atom\n\n if e.operator == \"IDENTIFIER\":\n return model[e.atom]\n\n if e.operator == \"EQUIV\":\n return evaluate_expression(e.operand1, model) == evaluate_expression(e.operand2, model)\n\n if e.operator == \"IMPLIES\":\n return (not evaluate_expression(e.operand1, model)) or evaluate_expression(e.operand2, model)\n\n if e.operator == \"AND\":\n return evaluate_expression(e.operand1, model) and evaluate_expression(e.operand2, model)\n\n if e.operator == \"OR\":\n return evaluate_expression(e.operand1, model) or evaluate_expression(e.operand2, model)\n\n if e.operator == \"NEG\":\n return not evaluate_expression(e.operand1, model)\n\n raise ValueError(\"Fatal error: we should never get here\")\n\ndef evaluate_expression_set(expression_set, model):\n \"\"\"\n Determines the truth value of an expression set\n :param expression_set: The expression set to be evaluated\n :param model: The model containing the evaluations of the identifiers\n :return: True if all expressions in the set evaluate to true, otherwise False\n \"\"\"\n for expression in expression_set:\n if not evaluate_expression(expression, model):\n return False\n\n return True\n\ndef evaluate_random_model():\n \"\"\"\n Assigns random truth values to the identifiers, evaluates the KB and INFER sets using this model\n and prints whether KB entails INFER\n \"\"\"\n model = {}\n\n for id in identifiers:\n model[id] = random.choice([True, False])\n\n print(\"Randomly chosen model: \", model)\n\n kb_eval = evaluate_expression_set(kb, model)\n infer_eval = evaluate_expression_set(infer, model)\n\n print(\" KB evaluates to: \", kb_eval)\n print(\" INFER evaluates to: \", infer_eval, \"\\n\")\n\n if kb_eval and not infer_eval:\n print(\"KB does not entail INFER\\n\")\n else:\n print(\"KB entails INFER\\KeyError: 'p'n\")\n\n##\n# It should not be necessary to change any code above this line!\n##\n\ndef check_all_models():\n # This function should return True if KB entails INFER, otherwise it should return False\n # Check all possible configurations of the Truth table. \n booleans = [True, False]\n iterators = [0,1]\n model = {}\n\n\n for i in iterators:\n model[identifiers[0]] = booleans[i]\n for j in iterators:\n model[identifiers[1]] = booleans[j]\n for h in iterators:\n model[identifiers[2]] = booleans[h]\n\n for i in model:\n print(model[i])\n \n kb_eval = evaluate_expression_set(kb, model)\n infer_eval = evaluate_expression_set(infer, model)\n\n print(\" KB evaluates to: \", kb_eval)\n print(\" INFER evaluates to: \", infer_eval, \"\\n\")\n\n if kb_eval and not infer_eval:\n print(\"KB does not entail INFER\\n\")\n else:\n print(\"KB entails INFER\\KeyError: 'p'n\")\n return True\n\n\ndef main():\n parse_input()\n print_expression_sets()\n #evaluate_random_model()\n check_all_models()\n\nif __name__ == \"__main__\":\n main()","sub_path":"Assignment4/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"140286145","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Lyfter Application\n# \n# Lyfter is a Python application that records the workouts of the user, utilizing knowledge of primary, secondary, and \n# tertiary movers for each exercise logged to calculate total sets per muscle group worked per week. Lyfter also employs the \n# use of an SQLite database to store workout information, total weekly muscle sets, and workout volume for later visualization \n# in order to track the user’s progression over time.\n\n# In[10]:\n\n\nimport sqlite3\nfrom datetime import datetime, date, timedelta\n\n# This is the muscle set dictionary that will be utilized every time workout data is input, whether it be a single\n# session, or multiple workouts input at once. Python will receive the workout data, convert it into a nested dict,\n# and update the muscle sets dict using the nested dict. After this, the data will be stored in SQL.\n\nmuscle_sets = {'Lats':0, 'Lower_Back':0,'Trapezius':0,\n 'Front_Deltoids':0, 'Side_Deltoids':0, 'Rear_Deltoids':0,\n 'Pectorals':0,\n 'Triceps':0, 'Biceps':0, 'Forearms':0,\n 'Abdominals':0,\n 'Glutes':0, 'Hamstrings':0, 'Quadriceps':0, 'Calves':0,\n 'Neck':0}\n\n# This is the exercise list dictionary that functions reference in order to determine what muscles were being worked\n# by which exercise. Based on whether the muscle is a primary, secondary, or tertiary mover, the number of sets\n# completed per muscle will be adjusted accordingly by a \"mover constant.\"\n\nexercise_list = {\n 'Barbell Bench Press': {'Pectorals': 1, 'Triceps': 1, 'Front_Deltoids': 1},\n 'Close Grip Barbell Bench Press': {'Pectorals': 1, 'Triceps': 1, 'Front_Deltoids': 1},\n 'DB Bench Press': {'Pectorals': 1, 'Triceps': 1, 'Front_Deltoids': 1},\n 'DB Incline Bench Press': {'Pectorals':1,'Front_Deltoids':1, 'Triceps':1},\n 'Decline Press Machine': {'Pectorals':1, 'Triceps':2},\n 'Back Squat': {'Quadriceps': 1, 'Glutes': 2, 'Lower_Back': 3},\n 'Paused Back Squats': {'Quadriceps': 1, 'Glutes': 2, 'Lower_Back': 3},\n 'Front Squat': {'Quadriceps': 1, 'Trapezius': 3},\n 'Paused Front Squats': {'Quadriceps': 1, 'Trapezius': 3},\n 'Smith Machine Hip Thrust': {'Glutes': 1, 'Hamstrings': 2},\n 'Barbell Overhead Press': {'Front_Deltoids': 1,'Side_Deltoids': 2,'Triceps': 2},\n 'DB Overhead Press': {'Front_Deltoids': 1,'Side_Deltoids': 2,'Triceps': 2},\n 'DB Lateral Raises': {'Side_Deltoids':1},\n 'Lateral Raise Machine': {'Side_Deltoids':1},\n 'Deadlift': {'Hamstrings': 1,'Glutes': 1,'Lower_Back': 1,'Forearms': 1,'Quadriceps': 2,'Trapezius': 2},\n 'Hex Bar Deadlift': {'Hamstrings': 1,'Glutes': 1,'Lower_Back': 1,'Quadriceps': 2,'Trapezius': 2},\n 'Romanian Deadlift': {'Hamstrings': 1,'Glutes': 1,'Lower_Back': 1,'Forearms': 2},\n 'Unilateral Leg Press': {'Quadriceps': 1},\n 'Seated Calf Raises': {'Calves': 1},\n 'Seated Calf Press Machine': {'Calves':1},\n 'Abdominal Crunch Machine': {'Abdominals': 1},\n 'Decline Crunch': {'Abdominals': 1},\n 'Seated Leg Curls': {'Hamstrings': 1},\n 'Lying Leg Curls': {'Hamstrings': 1},\n 'Gliding Leg Curls': {'Hamstrings': 1, 'Glutes': 3},\n 'Leg Extensions': {'Quadriceps': 1},\n 'Back Extensions': {'Lower_Back': 1, 'Hamstrings':3, 'Glutes': 3},\n 'Single DB Split Squat': {'Quadriceps': 1, 'Hamstrings': 2,'Glutes': 2},\n 'DB Split Squat': {'Quadriceps': 1, 'Hamstrings': 2, 'Glutes': 2},\n 'Leg Press Calf Raises': {'Calves': 1},\n 'Cable Bicep Curls': {'Biceps': 1},\n 'Cable Flys': {'Pectorals': 1},\n 'Rear Delt Facepulls': {'Rear_Deltoids':1},\n 'Barbell Pendlay Row': {'Trapezius':1, 'Lats':1, 'Biceps':2, 'Rear_Deltoids':2, 'Lower_Back':3},\n 'Barbell Bent Over Row': {'Trapezius':1, 'Lats':1, 'Biceps':2, 'Rear_Deltoids':2, 'Lower_Back':3},\n 'Lat Pulldowns': {'Lats':1, 'Trapezius':2, 'Biceps':2},\n 'EZ Bar Wrist Curls': {'Forearms':1},\n 'Walking DB Lunges': {'Quadriceps':1, 'Hamstrings':1,'Glutes':1},\n 'Ab Wheel Rollouts': {'Abdominals':1},\n 'DB Bicep Curls': {'Biceps':1},\n 'EZ Bar Bicep Curls': {'Biceps':1},\n 'Machine Preacher Curls': {'Biceps':1},\n 'Reverse Pec Deck': {'Rear_Deltoids':1},\n 'Pull Ups': {'Lats':1, 'Trapezius':1, 'Biceps':2},\n 'Low Row Machine': {'Trapezius':1, 'Lats':2, 'Rear_Deltoids':2},\n 'High Row Machine': {'Trapezius':1, 'Lats':2, 'Rear_Deltoids':2},\n 'French Press': {'Triceps':1}\n}\n\n\n# In[11]:\n\n\n# Creates the workout data dictionary with user input.\n\ndef create_workout_data():\n number_of_workouts = int(input(\"How many workouts are being recorded? \"))\n workout_dictionary = {}\n for i in range(number_of_workouts):\n if number_of_workouts == 1:\n date = input(\"What is the date of the workout? Please input the date in YYYY-MM-DD format. \")\n else:\n date = input('''What is the date of workout number ''' + str(i+1) + '''? \n Please input the date in YYYY-MM-DD format. ''')\n number_of_exercises = int(input(\"How many exercises are in the workout? \"))\n exercises = {}\n for i in range(number_of_exercises):\n rw_dict = {}\n exercise = input(\"What is exercise number \" + str(i+1) + \"? \")\n num_sets = int(input(\"How many working sets for this exercise? \"))\n equal_rw = input(\"Are reps and weight the same throughout all working sets? (Yes / No) \").strip().lower()\n while equal_rw not in ('yes','no'):\n equal_rw = input('''Are reps and weight the same throughout all \n working sets? (Yes / No) ''').strip().lower()\n if equal_rw in ('yes'):\n reps = int(input(\"How many reps for each set? \"))\n weight = float(input(\"How much weight for each set? \"))\n for i in range(num_sets):\n rw_dict.update({i+1:{'reps':reps,'weight':weight}})\n elif equal_rw in ('no'):\n for i in range(num_sets):\n reps = int(input(\"How many reps for set \" + str(i+1) + \"? \"))\n weight = float(input(\"How much weight for set \" + str(i+1) + \"? \"))\n rw_dict.update({i+1:{'reps':reps,'weight':weight}})\n exercises.update({exercise:rw_dict})\n workout_dictionary.update({date:exercises})\n return workout_dictionary\n\n# TEST create_workout_data()\n\n\n# Function that takes muscle sets dictionary and a week id and updates the WeeklyMuscleSets table in SQL.\n\ndef update_weekly_muscle_sets_table_in_sql(muscle_sets,week_id):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n for muscle in muscle_sets.keys():# Updates SQL table with the muscle_set data for that week\n num_sets = muscle_sets.get(muscle)\n if num_sets != 0:\n sql_statement = f'''UPDATE WeeklyMuscleSets \n SET {muscle} = {muscle} + (:num_sets) \n WHERE WeekID=(:week_id);'''\n parameters = {'num_sets':num_sets,'week_id':week_id}\n c.execute(sql_statement,parameters)\n \n conn.commit()\n conn.close()\n \n \n# Function that takes the workout dictionary created by \"create_workout_data\" and preps the data to be inserted into\n# the WeeklyMuscleSets table in SQL.\n\ndef update_muscle_sets_in_sql_from_py(workout_dictionary):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n unique_weeks = []\n \n for date in workout_dictionary.keys():\n week_number = int(datetime.strptime(date,'%Y-%m-%d').strftime('%V'))\n if week_number not in unique_weeks:\n unique_weeks.append(week_number)\n \n for date in workout_dictionary.keys():\n week_number = int(datetime.strptime(date,'%Y-%m-%d').strftime('%V'))\n for week_id in unique_weeks:\n muscle_sets = {'Lats':0, 'Lower_Back':0,'Trapezius':0,\n 'Front_Deltoids':0, 'Side_Deltoids':0, 'Rear_Deltoids':0,\n 'Pectorals':0,\n 'Triceps':0, 'Biceps':0, 'Forearms':0,\n 'Abdominals':0,\n 'Glutes':0, 'Hamstrings':0, 'Quadriceps':0, 'Calves':0,\n 'Neck':0}\n if week_id == week_number:\n daily_exercise_volume = workout_dictionary.get(date)\n for exercise,set_volume in daily_exercise_volume.items():\n muscle_groups = exercise_list.get(exercise)\n for muscle,mover_var in muscle_groups.items():\n if mover_var == 1:\n muscle_sets.update({muscle:(len(set_volume) + muscle_sets.get(muscle))})\n elif mover_var == 2:\n muscle_sets.update({muscle:(len(set_volume)*(2/3) + muscle_sets.get(muscle))})\n else:\n muscle_sets.update({muscle:(len(set_volume)*(1/3) + muscle_sets.get(muscle))})\n \n update_weekly_muscle_sets_table_in_sql(muscle_sets,week_id)\n \n \n# Function that takes the workout dictionary created by \"create_workout_data\" and updates WorkoutTable in SQL.\n\ndef update_workout_table_in_sql_from_py(workout_dictionary):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n for date in workout_dictionary.keys():\n workout_data = []\n workout = workout_dictionary.get(date)\n for exercise in workout.keys():\n working_sets = workout.get(exercise)\n for work_set in working_sets.keys():\n reps_weight = working_sets.get(work_set)\n workout_data.append((date,exercise,work_set,reps_weight.get('reps'),reps_weight.get('weight')))\n\n for element in workout_data:\n sql_date = element[0]\n sql_exercise = element[1]\n sql_set_number = element[2]\n sql_reps = element[3]\n sql_weight = element[4]\n\n sql_statement = '''INSERT INTO WorkoutTable \n VALUES (:sql_date,\n :sql_exercise,\n :sql_set_number,\n :sql_reps,\n :sql_weight);'''\n\n parameters = {'sql_date':sql_date,\n 'sql_exercise':sql_exercise,\n 'sql_set_number':sql_set_number,\n 'sql_reps':sql_reps,\n 'sql_weight':sql_weight}\n\n c.execute(sql_statement,parameters)\n\n conn.commit()\n conn.close()\n \n \n# User inputs their workout(s) and updates both workout data AND weekly muscle sets in SQL.\n\ndef insert_new_workout_into_sql():\n workout_dictionary = create_workout_data()\n \n update_muscle_sets_in_sql_from_py(workout_dictionary)\n \n update_workout_table_in_sql_from_py(workout_dictionary)\n\n\n# In[12]:\n\n\n# Updates WeeklyMuscleSets from a muscle set dictionary accquired from WorkoutTable.\n\ndef update_all_weekly_muscle_sets_in_sql_from_workout_table(muscle_sets):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n\n for muscle in muscle_sets.keys():\n num_sets = muscle_sets.get(muscle)\n if num_sets != 0:\n sql_statement = f\"UPDATE WeeklyMuscleSets SET {muscle} = (:num_sets) WHERE WeekID=(:week_id);\"\n parameters = {'num_sets':num_sets,'week_id':week_id}\n c.execute(sql_statement,parameters)\n \n conn.commit()\n conn.close()\n \n# Updates ALL of the rows in WeeklyMuscleSets from data accquired from WorkoutTable.\n\ndef update_all_weekly_muscle_sets_in_sql():\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n\n c.execute('SELECT Date,Exercise,COUNT(Exercise) FROM WorkoutTable GROUP BY Date,Exercise;')\n exercise_data_sql = c.fetchall()\n\n\n date_exercise_number_of_sets = [[int(datetime.strptime(data[0],'%Y-%m-%d').strftime('%V')),\n data[1],\n data[2]] for data in exercise_data_sql]\n\n\n unique_week_id = []\n for data in date_exercise_number_of_sets:\n week_id = data[0]\n if week_id not in unique_week_id:\n unique_week_id.append(week_id)\n\n for week_id in unique_week_id:\n\n muscle_sets = {'Lats':0, 'Lower_Back':0,'Trapezius':0,\n 'Front_Deltoids':0, 'Side_Deltoids':0, 'Rear_Deltoids':0,\n 'Pectorals':0,\n 'Triceps':0, 'Biceps':0, 'Forearms':0,\n 'Abdominals':0,\n 'Glutes':0, 'Hamstrings':0, 'Quadriceps':0, 'Calves':0,\n 'Neck':0}\n\n for data in date_exercise_number_of_sets:\n week_num = data[0]\n exercise = data[1]\n number_of_sets = data[2]\n\n if week_num == week_id:\n muscle_groups = exercise_list.get(exercise)\n for muscle,mover_var in muscle_groups.items():\n if mover_var == 1:\n muscle_sets[muscle] += number_of_sets\n elif mover_var == 2:\n muscle_sets[muscle] += number_of_sets*(2/3)\n else:\n muscle_sets[muscle] += number_of_sets*(1/3)\n \n\n update_all_muscle_sets_in_sql_from_workout_table(muscle_sets)\n \n conn.commit()\n conn.close()\n\n\n# In[13]:\n\n\n# Function gets the start and end date from a week number for the purpose of SQL querying.\n\ndef give_week_start_and_end_date_from_week_number(week_number):\n d = '{}-W{}'.format('2019',week_number)\n start_date = datetime.strptime(d + '-1', '%G-W%V-%u').date()\n end_date = datetime.strptime(d + '-7', '%G-W%V-%u').date()\n return [str(start_date),str(end_date)]\n\n\n# Function that returns \"date_exercise_number_of_sets\", a list that returns information from WorkoutTable in SQL in\n# a format that can be utilized by later functions.\n\ndef get_weekly_muscle_sets_from_sql_workout_table(week_id):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n\n start_date = give_week_start_and_end_date_from_week_number(week_id)[0]\n end_date = give_week_start_and_end_date_from_week_number(week_id)[-1]\n\n sql_statement = '''SELECT Date,Exercise,COUNT(Exercise) \n FROM WorkoutTable\n WHERE Date BETWEEN (:start_date) AND (:end_date)\n GROUP BY Date,Exercise'''\n parameters = {'start_date':start_date,'end_date':end_date}\n\n c.execute(sql_statement,parameters)\n exercise_data_sql = c.fetchall()\n \n date_exercise_number_of_sets = [[int(datetime.strptime(data[0],'%Y-%m-%d').strftime('%V')),\n data[1],\n data[2]] for data in exercise_data_sql]\n \n conn.commit()\n conn.close()\n \n return date_exercise_number_of_sets\n\n\n# Utilizes the \"date_exercise_number_of_sets\" list to create a python muscle set dictionary.\n\ndef create_py_muscle_sets_from_sql_workout_table(date_exercise_number_of_sets):\n \n muscle_sets = {'Lats':0.0, 'Lower_Back':0.0,'Trapezius':0.0,\n 'Front_Deltoids':0.0, 'Side_Deltoids':0.0, 'Rear_Deltoids':0.0,\n 'Pectorals':0.0,\n 'Triceps':0.0, 'Biceps':0.0, 'Forearms':0.0,\n 'Abdominals':0.0,\n 'Glutes':0.0, 'Hamstrings':0.0, 'Quadriceps':0.0, 'Calves':0.0,\n 'Neck':0.0}\n \n for data in date_exercise_number_of_sets:\n week_number = data[0]\n exercise = data[1]\n number_of_sets = data[2]\n \n muscle_groups = exercise_list.get(exercise)\n for muscle,mover_var in muscle_groups.items():\n if mover_var == 1:\n muscle_sets[muscle] += number_of_sets\n elif mover_var == 2:\n muscle_sets[muscle] += number_of_sets*(2/3)\n else:\n muscle_sets[muscle] += number_of_sets*(1/3)\n \n return muscle_sets\n\n \n# Updates the WeeklyMuscleSets table with information gained from the previous functions.\n\ndef update_weekly_muscle_sets_in_sql_from_workout_table(muscle_sets,week_id):\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n for muscle in muscle_sets.keys():# Updates SQL table with the muscle_set data for that week\n num_sets = muscle_sets.get(muscle)\n if num_sets != 0:\n sql_statement = f'''UPDATE WeeklyMuscleSets \n SET {muscle} = (:num_sets)\n WHERE WeekID=(:week_id);'''\n parameters = {'num_sets':num_sets,'week_id':week_id}\n c.execute(sql_statement,parameters)\n \n conn.commit()\n conn.close()\n \n \n# Takes a week number and updates the WeeklyMuscleSets table after a change in the data.\n\ndef specific_weekly_muscle_sets_update_sql(week_number):\n# week_number = int(datetime.strptime(date,'%Y-%m-%d').strftime('%V'))\n \n week_number_exercise_number_of_sets = get_weekly_muscle_sets_from_sql_workout_table(week_number)\n \n weekly_muscle_sets = create_py_muscle_sets_from_sql_workout_table(week_number_exercise_number_of_sets)\n \n update_weekly_muscle_sets_in_sql_from_workout_table(weekly_muscle_sets,week_number)\n\n\n# In[14]:\n\n\n# Function that allows the user to view workout data that has been logged.\n\ndef read():\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n workout_query = input(\"Do you want to look up a workout, an exercise, or both? \").strip().lower()\n while workout_query not in ('workout','exercise','both'):\n workout_query = input(\"Do you want to look up a workout, an exercise, or both? \").strip().lower()\n \n if workout_query == 'workout':\n date = input(\"What date do you want to view? YYYY-MM-DD \")\n \n sql_statement = '''SELECT * FROM WorkoutTable \n WHERE Date=(:date)\n GROUP BY Exercise,SetNumber;'''\n c.execute(sql_statement,{'date':date})\n\n return c.fetchall()\n elif workout_query == 'exercise':\n exercise = input(\"What exercise do you want to view? \")\n \n sql_statement = 'SELECT * FROM WorkoutTable WHERE Exercise=(:exercise) ORDER BY Date;'\n c.execute(sql_statement,{'exercise':exercise})\n \n return c.fetchall()\n else: # Update this with the capability of viewing multiple dates and exercises!\n date = input(\"What date do you want to view? YYYY-MM-DD \")\n exercise = input(\"What exercise do you want to view? \")\n \n sql_statement = 'SELECT * FROM WorkoutTable WHERE Date=(:date) AND Exercise=(:exercise);'\n c.execute(sql_statement,{'date':date,'exercise':exercise})\n \n return c.fetchall()\n \n conn.commit()\n conn.close()\n\n# Function that updates reps and weight in SQL; returns week number for use with the function responsible for\n# updating the WeeklyMuscleSets table.\n\ndef update_reps_and_weight():\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n\n date = input(\"What is the date of the workout you want to update? YYYY-MM-DD \")\n week_number = int(datetime.strptime(date,'%Y-%m-%d').strftime('%V'))\n exercise = input(\"What exercise do you want to update? \")\n set_number = int(input(\"What set number do you want to update? \"))\n \n rw = input(\"Do you want to update reps, weight, or both? \").strip().lower()\n while rw not in ('reps','weight','both'):\n rw = input(\"Do you want to update reps, weight, or both? \").strip().lower()\n \n if rw == 'reps':\n new_reps = int(input(\"How many reps? \"))\n sql_statement = '''UPDATE WorkoutTable \n SET Reps=(:new_reps) \n WHERE Date=(:date) AND Exercise=(:exercise) AND SetNumber=(:set_number);'''\n parameters = {'new_reps':new_reps,'date':date,'exercise':exercise,'set_number':set_number}\n c.execute(sql_statement,parameters)\n elif rw == 'weight':\n new_weight = float(input(\"How much weight? \"))\n sql_statement = '''UPDATE WorkoutTable \n SET Weight=(:new_weight) \n WHERE Date=(:date) AND Exercise=(:exercise) AND SetNumber=(:set_number);'''\n parameters = {'new_weight':new_weight,'date':date,'exercise':exercise,'set_number':set_number}\n c.execute(sql_statement,parameters)\n else:\n new_reps = int(input(\"How many reps? \"))\n new_weight = float(input(\"How much weight? \"))\n sql_statement = '''UPDATE WorkoutTable \n SET Reps=(:new_reps), Weight=(:new_weight) \n WHERE Date=(:date) AND Exercise=(:exercise) AND SetNumber=(:set_number);'''\n parameters = {'new_reps':new_reps,'new_weight':new_weight,'date':date,'exercise':exercise,'set_number':set_number}\n c.execute(sql_statement,parameters)\n \n conn.commit()\n conn.close()\n \n return week_number\n\n\n# Function that can delete an entire workout, exercise, or a set based on user input; returns week number \n# for use with the function responsible for updating the WeeklyMuscleSets table.\n\ndef delete():\n conn = sqlite3.connect('LyfterTestDatabase.db')\n c = conn.cursor()\n \n delete_query = input('''Do you want to delete a workout, an exercise from a workout, \n or a specific set from a workout? (workout, exercise, set) ''').strip().lower()\n while delete_query not in ('workout','exercise','set'):\n delete_query = input('''Do you want to delete a workout, an exercise from a workout, \n or a specific set from a workout? (workout, exercise, set) ''').strip().lower()\n \n date = input(\"Please specify the workout date. YYYY-MM-DD \")\n week_number = int(datetime.strptime(date,'%Y-%m-%d').strftime('%V'))\n \n if delete_query == 'workout':\n \n sql_statement = 'DELETE FROM WorkoutTable WHERE Date=(:date);'\n c.execute(sql_statement,{'date':date})\n \n elif delete_query == 'exercise':\n exercise = input(\"Please specify the exercise you wish to delete. \")\n \n sql_statement = 'DELETE FROM WorkoutTable WHERE Date=(:date) AND Exercise=(:exercise);'\n c.execute(sql_statement,{'date':date,'exercise':exercise})\n \n else:\n exercise = input(\"Please specify the exercise from the workout. \")\n set_number = int(input(\"Please specify the set number you wish to delete. \"))\n \n sql_statement = '''DELETE FROM WorkoutTable \n WHERE Date=(:date) AND Exercise=(:exercise) AND SetNumber=(:set_number);'''\n c.execute(sql_statement,{'date':date,'exercise':exercise,'set_number':set_number})\n \n conn.commit()\n conn.close()\n \n return week_number\n\n\n# Updates WeeklyMuscleSets after user updates reps and weight.\ndef full_update():\n week_number = update_reps_and_weight()\n \n specific_weekly_muscle_sets_update_sql(week_number)\n \n# Updates WeeklyMuscleSets after user deletes a workout, exercise, or set.\ndef full_delete():\n week_number = delete()\n \n specific_weekly_muscle_sets_update_sql(week_number)\n\n","sub_path":"API/Lyfter Algorithm.py","file_name":"Lyfter Algorithm.py","file_ext":"py","file_size_in_byte":23713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"498599425","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Vijay Joshi\n\n\"\"\"\n\nimport numpy as np\nimport math\n\nclass naiveBayes:\n\n def __init__(self, ipTrainingFile, ipTestFile):\n self.ipTrainingFile = ipTrainingFile\n self.ipTestFile = ipTestFile\n self.ipTrainingData = []\n self.ipTestData = []\n self.classLabels = []\n self.classes = []\n self.dimensions = 0\n\n def uploadData(self):\n\n # Reading Training and Test data file\n ipTrainingFile = open(self.ipTrainingFile, \"r\")\n ipTrainingFileLines = ipTrainingFile.readlines()\n\n ipTestFile = open(self.ipTestFile, \"r\")\n ipTestFileLines = ipTestFile.readlines()\n\n #Finding Dimensions based on first line\n #Later it will be subtracted with 1 as one of the dimension is for class label\n self.dimensions = len(list(filter(None, ipTrainingFileLines[1].split(\" \"))))\n print(\"Dimensions>>>>>\"+ str(self.dimensions))\n\n # Arrays for Training, Test and Class Label datasets\n self.ipTrainingData = np.zeros((1, self.dimensions - 1))\n self.ipTestData = np.zeros((1, self.dimensions))\n self.classLabels = np.zeros((1, 1))\n\n for trainData in ipTrainingFileLines:\n trainDataRow = trainData.split(\" \")\n trainDataRow = list(filter(None, trainDataRow))\n trainDataRow = list(map(float, trainDataRow))\n # Stacking Training Data and class Labels in arrays created\n self.ipTrainingData = np.vstack((self.ipTrainingData, trainDataRow[:-1]))\n self.classLabels = np.vstack((self.classLabels, trainDataRow[-1]))\n\n for testData in ipTestFileLines:\n testDataRow = testData.split(\" \")\n testDataRow = list(filter(None, testDataRow))\n testDataRow = list(map(float, testDataRow))\n self.ipTestData = np.vstack((self.ipTestData, testDataRow))\n\n self.ipTrainingData = self.ipTrainingData[1:]\n self.ipTestData = self.ipTestData[1:]\n self.classLabels = self.classLabels[1:]\n self.classes = np.unique(self.classLabels)\n\n def classificationAccuracy(labels, groundTruth, probability):\n maximumProbability = np.max(probability)\n maxProbIndex = np.nonzero(probability == maximumProbability)[0]\n labelPredicted = 0\n for i in maxProbIndex:\n i = int(i)\n if labels[i] == groundTruth:\n classificationAccuracy = 1 / maxProbIndex.shape[0]\n labelPredicted = groundTruth\n else:\n classificationAccuracy = 0.0\n labelPredicted = int(labels[i])\n return labelPredicted, maximumProbability, classificationAccuracy\n\n def displayResults(result):\n counter = 0\n\n for i in range(result.shape[0]):\n print(\"ID={:5d}, predicted={:3d}, probability= {:.4f}, true={:3d}, accuracy= {:4.2f}\".format(\n int(result[i, 0]),\n int(result[i, 1]),\n result[i, 2],\n int(result[i, 3]),\n result[i, 4]))\n if (result[i, 1] == result[i, 3]):\n counter += 1\n print(\"classification accuracy= {:6.4f}\".format(counter / result.shape[0]))\n\n\nclass gaussianClassifier(naiveBayes):\n def __init__(self, ipTrainingFile, ipTestFile):\n naiveBayes.__init__(self, ipTrainingFile, ipTestFile)\n\n def normalProbabilityDensity(self, x, mu, sigma):\n u = (x - mu) / abs(sigma)\n y = (1 / (np.sqrt(2 * math.pi) * abs(sigma))) * math.exp(-u * u / 2)\n return y\n\n def gaussianTraining(self):\n print(\"Starting : Gaussian Training >>>>>>>>>>>>>>>>>\")\n totalClasses = len(self.classes)\n print(\"Total classes>>>>>>\" + str(totalClasses))\n dimensions = self.dimensions - 1\n self.gaussianDistribution = np.empty((totalClasses, dimensions, 2))\n\n\n for classLabel in self.classes:\n classLabel = int(classLabel)\n classLabelIndex = np.nonzero(self.classLabels == classLabel)[0]\n for dimension in range(dimensions):\n mean = np.mean(self.ipTrainingData[classLabelIndex, dimension])\n stdev = np.std(self.ipTrainingData[classLabelIndex, dimension])\n if stdev < 0.01:\n stdev = 0.01\n print(\"Class {:d}, attribute {:d}, mean = {:.2f}, std = {:.2f}\".format(classLabel, dimension, mean, stdev))\n print(\"Class label {:d}, Current Dimension {:d} \".format((classLabel - 1), dimension))\n self.gaussianDistribution[classLabel - 1, dimension, 0] = mean\n self.gaussianDistribution[classLabel - 1, dimension, 1] = stdev\n print(\"Classification >>>>>>>>>>>>>>>>>\")\n\n def gaussianTesting(self):\n print(\"Gaussian Testing >>>>>>>>>>>>>>>>>\")\n testDataSize = self.ipTestData.shape[0]\n trainDataSize = self.ipTrainingData.shape[0]\n totalClasses = len(self.classes)\n dimensions = self.dimensions - 1\n testDataProbability = np.zeros((testDataSize, totalClasses))\n probabilityOfClass = np.divide(np.histogram(self.classLabels, range=(1, 10))[0], trainDataSize)\n result = np.empty((testDataSize, 5))\n\n for i in range(testDataSize):\n for j in range(totalClasses):\n probability = 1\n for dimension in range(dimensions):\n probability = probability * self.normalProbabilityDensity(self.ipTestData[i, dimension], self.gaussianDistribution[j, dimension, 0],\n self.gaussianDistribution[j, dimension, 1])\n testDataProbability[i, j] = probability * probabilityOfClass[j]\n testDataProbabilitySum = np.sum(testDataProbability[i, :])\n for j in range(totalClasses):\n if testDataProbabilitySum == 0:\n testDataProbability[i, j] = 1 / totalClasses\n else:\n testDataProbability[i, j] = np.divide(testDataProbability[i, j], testDataProbabilitySum)\n\n result[i, 0] = i + 1\n result[i, 3] = self.ipTestData[i, -1]\n result[i, 1], result[i, 2], result[i, 4] = naiveBayes.classificationAccuracy(labels=self.classes,\n groundTruth=self.ipTestData[i, -1],\n probability=testDataProbability[i, :])\n\n naiveBayes.displayResults(result)\n\ndef main():\n\n print(\"Provide the training & test data's file path in following format: \")\n print(\" \")\n inputFileLocation = input()\n fileLocationPath = inputFileLocation.split()\n if (len(fileLocationPath) > 1):\n gaussian = gaussianClassifier(ipTrainingFile=fileLocationPath[0], ipTestFile=fileLocationPath[1])\n gaussian.uploadData()\n gaussian.gaussianTraining()\n gaussian.gaussianTesting()\n else:\n print(\"File location doesn't contain both file location\")\n\n\nmain()","sub_path":"naive-bayes.py","file_name":"naive-bayes.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"341272144","text":"\"\"\"Code Python pour le cours IFT2015\n Mise à jour par François Major le 23 mars 2014.\n\"\"\"\n\nclass SkipListNode:\n\n __slots__ = '_elem', '_prev', '_next', '_belo', '_abov'\n def __init__( self, elem, prev = None, next = None, belo = None, abov = None ):\n self._elem = elem\n self._prev = prev\n self._next = next\n self._belo = belo\n self._abov = abov\n\n def __str__( self ):\n return \"(\" + str( self._elem ) + \")\"\n","sub_path":"weekly_classes/11-MAPS/SkipListNode.py","file_name":"SkipListNode.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"266701726","text":"import os\n\n\ndef non_divisible_subset(k, s):\n \"\"\"вход: два числа и строка\n n - количество элементов, k - делитель\n s - строка\n выход: количество элементов, сумма которых делится на делитель\n \"\"\"\n array_of_sum = [0] * k\n for x in s:\n array_of_sum[x % k] += 1\n count = min(array_of_sum[0], 1)\n for i in range(1, k // 2 + 1):\n if i != k - i:\n count += max(array_of_sum[i], array_of_sum[k - i])\n if k % 2 == 0:\n count += 1\n\n print(count)\n return count\n\nif __name__ == '__main__':\n os.environ['OUTPUT_PATH'] = 'test.txt'\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n s = list(map(int, input().rstrip().split()))\n\n result = non_divisible_subset(k, s)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"algorithms/Non-Divisible Subset.py","file_name":"Non-Divisible Subset.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"426130006","text":"# $Id:$\r\n# -*- coding: utf-8 -*-\r\n\r\n#\r\n#if you want js can access your python method\r\n#you need to use @PyQt4.QtCore.pyqtSlot decorator\r\n#\r\n\r\nimport json,time,threading,datetime\r\n\r\n\r\nfrom api import *\r\n\r\nfrom extapi.ekpmessage import EKPMessage\r\n\r\nclass PyPage(PyQt4.QtCore.QObject):\r\n def ONLOAD(self):\r\n easydom = self._easydom\r\n easydom('''div[id=\"cardno\"]''')[0].InnerXml = context._idcardno\r\n easydom('''div[id=\"patname\"]''')[0].InnerXml = context._idname\r\n easydom('''div[id=\"reqamount\"]''')[0].InnerXml = u\"%.2f\"%context._reqamount\r\n easydom('''div[id=\"amount\"]''')[0].InnerXml = u\"%.2f\"%context._amount\r\n \r\n apimessage.SETMESSAGEHANDLER(self.onmessage)\r\n \r\n \r\n if context._amount>=context._reqamount:\r\n self._zhaoling = int((context._amount-context._reqamount)*100)\r\n else:\r\n self._zhaoling = int(context._amount*100)\r\n \r\n if self._zhaoling==0:\r\n self.goback()\r\n else:\r\n self._state = 0\r\n \r\n self._zhaolingremain = self._zhaoling\r\n self._cny20 = self._zhaoling/2000\r\n self._cny5 = (self._zhaoling-self._cny20*2000)/500\r\n self._cny1 = (self._zhaoling-self._cny20*2000-self._cny5*500)/100\r\n self._cny05 = (self._zhaoling-self._cny20*2000-self._cny5*500-self._cny1*100)/50\r\n self._cny01 = (self._zhaoling-self._cny20*2000-self._cny5*500-self._cny1*100-self._cny05*50)/10\r\n\r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"NOTESUPPLIER\"\r\n msg.messagecode = \"EKP.DEVICE.OPEN\"\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"COINDISPENSER\"\r\n msg.messagecode = \"EKP.DEVICE.OPEN\"\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n self._timeremain = 10\r\n self.t = PyQt4.QtCore.QTimer(self)\r\n self.t.setInterval(1000)\r\n self.t.timeout.connect(self.onesecond)\r\n self.t.start()\r\n \r\n def onesecond(self):\r\n self._timeremain -= 1\r\n if self._timeremain<0:\r\n self.close()\r\n self.printreport()\r\n self.goback()\r\n \r\n def ONUNLOAD(self):\r\n pass\r\n \r\n def onmessage(self, msgstr):\r\n msg = EKPMessage(json.loads(msgstr))\r\n if msg.devicecode==\"NOTESUPPLIER\":\r\n if msg.messagecode==\"EKP.DEVICE.OPEN.RESULT\" and msg.resultcode=='0':\r\n self._state = 1\r\n self._timeremain = 10\r\n if self._cny20>0 or self._cny5>0:\r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"NOTESUPPLIER\"\r\n msg.messagecode = \"EKP.NOTESUPPLIER.DISPENSE\"\r\n msg.dispenserequest = {}\r\n msg.dispenserequest[\"CNY20\"] = str(self._cny20)\r\n msg.dispenserequest[\"CNY5\"] = str(self._cny5)\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n else:\r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"COINDISPENSER\"\r\n msg.messagecode = \"EKP.COINDISPENSER.PAY\"\r\n msg.paymoney = str(self._cny1*100+self._cny05*50+self._cny01*10)\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n if msg.messagecode==\"EKP.NOTESUPPLIER.DISPENSE.RESULT\" and msg.resultcode=='0':\r\n self._state = 3\r\n self._timeremain = 10\r\n \r\n self._cny1 += self._cny20-int(msg.dispenseresult[\"CNY20\"])\r\n self._cny1 += self._cny5-int(msg.dispenseresult[\"CNY5\"])\r\n self._zhaolingremain -= int(msg.dispenseresult[\"CNY20\"])*2000\r\n self._zhaolingremain -= int(msg.dispenseresult[\"CNY5\"])*500\r\n \r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"COINDISPENSER\"\r\n msg.messagecode = \"EKP.COINDISPENSER.PAY\"\r\n msg.paymoney = str(self._cny1*100+self._cny05*50+self._cny01*10)\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n if msg.devicecode==\"COINDISPENSER\":\r\n if msg.messagecode==\"EKP.DEVICE.OPEN.RESULT\" and msg.resultcode=='0':\r\n self._state = 2\r\n self._timeremain = 10\r\n if msg.messagecode==\"EKP.COINDISPENSER.PAY.RESULT\" and msg.resultcode=='0':\r\n self._state = 4\r\n self._zhaolingremain -= int(msg.paymoney)\r\n # self._zhaolingremain -= int(msg.dispenseresult[\"CNY05\"])*50\r\n # self._zhaolingremain -= int(msg.dispenseresult[\"CNY01\"])*10\r\n self._timeremain = -1\r\n\r\n \r\n def close(self):\r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"NOTESUPPLIER\"\r\n msg.messagecode = \"EKP.DEVICE.CLOSE\"\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n msg = EKPMessage()\r\n msg.kioskcode = context._config.KioskCode\r\n msg.devicecode = \"COINDISPENSER\"\r\n msg.messagecode = \"EKP.DEVICE.CLOSE\"\r\n apimessage.PUBMESSAGE(json.dumps(msg.todict()))\r\n \r\n def printreport(self): \r\n currenttime = datetime.datetime.now()\r\n pdfname = os.path.join(\"report\", \"out\", \"chongzhi%s.pdf\"%currenttime.strftime(\"%Y%m%d%H%M%S\"))\r\n datadict = {}\r\n datadict[\"currenttime\"] = currenttime.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n datadict[\"jylsh\"] = \"xxx\"\r\n datadict[\"cardno\"] = context._idcardno\r\n datadict[\"name\"] = context._idname\r\n datadict[\"reqamount\"] = \"%.2f\" %context._reqamount\r\n datadict[\"amount\"] = \"%.2f\" %context._amount\r\n if self._zhaolingremain>0:\r\n datadict[\"comment\"] = u\"找零失败,%.2f元未找,请到柜台处理。\"%(float(self._zhaolingremain)/100)\r\n else:\r\n datadict[\"comment\"] = u\"找零成功\"\r\n apireport.MAKORML2PDF(\"chongzhi.rml\", datadict, pdfname)\r\n apireport.PRINTPDF(pdfname, context._config.ReceiptPrinter)\r\n \r\n def goback(self):\r\n apipage.GOTOPAGE(\"init\")\r\n \r\n","sub_path":"easytouch/app_demo/page/zhaoling.py","file_name":"zhaoling.py","file_ext":"py","file_size_in_byte":6604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"387100370","text":"# JiangHao\nimport matplotlib.pyplot as plt\n\n# x_values = [1, 2, 3, 4, 5]\n# y_values = [1, 4, 9, 16, 25]\n\nx_values = list(range(1,1001))\ny_values = [x**2 for x in x_values]\n\n#edgecolors: deleting the color of outline\n# plt.scatter(x_values,y_values,c='red',edgecolors='none',s=50)\n# plt.scatter(x_values,y_values,c=(0, 0, 0.8),edgecolors='none',s=50)\nplt.scatter(x_values,y_values,c=y_values,edgecolors='none',s=50,cmap=plt.cm.Blues) #colormap 颜色映射\n\n\nplt.axis([0, 1100, 0, 1100000])\n\n#title\nplt.title(\"Square Numbers\",fontsize=24)\nplt.xlabel(\"Value\",fontsize=14)\nplt.ylabel(\"Square of Value\",fontsize=14)\n\n#tick mark\nplt.tick_params(axis='both',which='major',labelsize=14)\n\n#If you want to disable both the offset and scientific notaion,\n# you'd use ax.ticklabel_format(useOffset=False, style='plain').\nplt.ticklabel_format(useOffset=False, style='plain')\n\nplt.show()\n\n#save graph, bbox_inches: whether cutting redundant white space\n# plt.savefig('squares_plot.png', bbox_inches='tight')","sub_path":"scatter_squares.py","file_name":"scatter_squares.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"394487977","text":"# coding: utf-8\nfrom flask import render_template,jsonify,Response,g,request\nfrom flask_login import current_user\nimport json\nfrom ..models import Role,User,Article,Tag\nfrom . import api\nfrom .. import db\nfrom guisheng_app.decorators import admin_required\nfrom datetime import datetime\n\ndef add_tags(article, tags, update):\n \"\"\"\n 判断\n 向数据库中添加tag实例\n 向数据库中添加tag和article关系\n \"\"\"\n # add tag\n for tag in tags:\n tag_in_db = Tag.query.filter_by(body=tag).first()\n if tag_in_db:\n if (not update):\n tag_in_db.count += 1\n db.session.add(tag_in_db)\n else:\n add_tag = Tag(body=tag, count=1)\n db.session.add(add_tag)\n db.session.commit()\n # add course & tag\n for tag in tags:\n get_tag = Tag.query.filter_by(body=tag).first()\n post_tags = [t.tag_id for t in article.tag.all()]\n if get_tag.id in post_tags:\n if (not update):\n post_tag = PostTag.query.filter_by(\n tag_id=get_tag.id, article_id=article.id,\n ).first()\n post_tag.count += 1\n db.session.add(post_tag)\n else:\n post_tag = PostTag(\n tag_id=get_tag.id, article_id=article.id, count=1\n )\n db.session.add(post_tag)\n db.session.commit()\n\ndef update_tags(article):\n \"\"\"\n 向数据库中更新tag实例\n 向数据库中更新tag和article关系\n \"\"\"\n tags = request.json.get(\"tags\").split()\n tags_id = [Tag.query.filter_by(body=tag).first().id for tag in tags]\n post_tag_ids = [t.tag_id for t in article.tag.all()]\n # update tag && postTag\n for post_tag_id in post_tag_ids:\n if post_tag_id not in tags_id:\n tag = Tag.query.filter_by(id=post_tag_id).first()\n tag.count -= 1\n db.session.add(tag)\n post_tag = PostTag.query.filter_by(\n tag_id=post_tag_id, article_id=article.id,\n ).first()\n db.session.delete(post_tag)\n db.session.commit()\n\n@api.route('/article//', methods=['GET'])\ndef get_article(id):\n article = Article.query.get_or_404(id)\n like_degree_one = article.light.filter_by(like_degree=0).count()\n like_degree_two = article.light.filter_by(like_degree=1).count()\n like_degree_three = article.light.filter_by(like_degree=2).count()\n user_role = -1 if current_user.is_anonymous else 0\n article.views+=1\n db.session.commit()\n return Response(json.dumps({\n \"kind\":3,\n \"title\":article.title,\n \"img_url\":article.img_url,\n \"author\":User.query.get_or_404(article.author_id).name,\n \"time\":article.time.strftime('%Y-%m-%d'),\n \"body\":article.body,\n \"like_degree\":[like_degree_one,like_degree_two,like_degree_three],\n \"commentCount\":article.comments.filter_by(comment_id=-1).count(),\n \"music\":{\n \"title\":article.music_title,\n \"music_url\":article.music_url,\n },\n \"film\":{\n \"film_url\":article.film_url,\n },\n \"editor\":article.editor,\n \"user_role\":user_role\n }),mimetype='application/json')\n\n@api.route('/article/recommend/',methods=['GET','POST'])\ndef recommend_articles():\n a_id = int(request.get_json().get('article_id'))\n now_a = Article.query.get_or_404(a_id)\n try:\n tag_id = now_a.tag[0].tag_id\n tag = Tag.query.get_or_404(tag_id)\n articles = []\n for _article in tag.articles:\n articles.append(_article.article_id)\n sortlist = sorted(articles,key=lambda id: Article.query.get_or_404(id).views,reverse=True)\n recommend_articles = sortlist[:3] if len(sortlist)>=4 else sortlist\n except:\n recommend_articles=[]\n return Response(json.dumps([{\n \"title\":Article.query.filter_by(id=article_id).first().title,\n \"description\":Article.query.filter_by(id=article_id).first().description,\n \"author\":User.query.get_or_404(Article.query.filter_by(id=article_id).first().author_id).name,\n \"tag\":tag.body,\n \"views\":Article.query.filter_by(id=article_id).first().views\n }for article_id in recommend_articles]\n ),mimetype='application/json')\n\n@api.route('/article/', methods=['GET','POST'])\n@admin_required\ndef add_article():\n if request.method == \"POST\":\n article = Article.from_json(request.get_json())\n db.session.add(article)\n db.session.commit()\n add_tags(article, request.json.get(\"tags\").split(), False)\n return jsonify({\n 'id': article.id\n }), 201\n\n@api.route('/article//', methods=[\"GET\", \"PUT\"])\n@admin_required\ndef update_article(id):\n article = Article.query.get_or_404(id)\n json = request.get_json()\n if request.method == \"PUT\":\n article.title = json.get('title')\n article.img_url = json.get('img_url')\n article.author = json.get('author')\n article.introduction = json.get('introduction')\n article.author = User.query.get_or_404(json.get('author_id'))\n article.music_url = json.get('music_url')\n article.music_title = json.get('music_title')\n article.music_img_url = json.get('music_img_url')\n article.singer = json.get('singer')\n article.film_url = json.get('film_url')\n article.film_img_url = json.get('film_img_url')\n db.session.add(article)\n db.session.commit()\n add_tags(article, request.json.get(\"tags\").split(), True)\n update_tags(article)\n return jsonify({\n 'update': article.id\n }), 200\n\n@api.route('/article//body/', methods=[\"GET\", \"PUT\"])\n@admin_required\ndef update_article_body(id):\n article = Article.query.get_or_404(id)\n if request.method == \"PUT\":\n article.body = request.get_json().get('body')\n db.session.add(article)\n db.session.commit()\n return jsonify({\n 'update': article.id\n }), 200\n\n@api.route('/article//', methods=[\"GET\", \"DELETE\"])\n@admin_required\ndef delete_article(id):\n article = Article.query.get_or_404(id)\n if request.method == \"DELETE\":\n db.session.delete(article)\n db.session.commit()\n return jsonify({\n 'deleted': article.id\n }), 200\n\n","sub_path":"guisheng/guisheng_app/api_1_0/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":6413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"457550597","text":"import pandas as pd\nimport glob\nimport pylab as plt\n\n# 4.23_Seated, Lifeband\n# file_path = 'Lifeband/rawdata/1/*.txt'\n# file_path = 'Sleep_April/rawdata/*/*.txt'\nfile_path = '/Volumes/ZHANGSY/My_Sleep_data/rawdata/*/*.txt'\n\n\ndf = pd.DataFrame()\npaths = glob.glob(file_path)\nprint(paths)\nfor path in paths:\n\tcols = [\"*09\",\"1f\",\"Accel Mag\",\"Activity Count\",\"State\",\"000000000337f980\",\"0660\",\"7fb9\",\"7d50\",\"8323\",\"0000\",\"0000\",\"0000\",\"0000\",\"0000\",\"0000\"]\n\tdf = df.append(pd.read_csv(path, names = cols))#skiprows = lambda x: x[0] != \"*09\", usecols = range(8)))\n # file = open(path)\n # for line in file.readlines():\n # if line[:3] == '*09':\n # new_l = line.split(\",\")\n # next_ = pd.DataFrame(new_l)\n # df = pd.concat([df, next_])\n\ndf = df.loc[df[\"*09\"] == \"*09\"]\n# print(df)\n# print(df.iloc[1, 2])\ndf.iloc[:, 2] = df.iloc[:, 2].astype(float)\n#print(df)\nprint(type(df.iloc[1, 2]))\nplt.scatter(df.index/7200, df.iloc[:,2], s = 10)\nplt.title(\"Accel Mag\")\n# plt.show()\n\nplt.figure(2)\ndf.iloc[:, 3] = df.iloc[:, 3].apply(lambda x: int(x, 16))\nplt.scatter(df.index/7200, df.iloc[:,3], s = 10)\nplt.title(\"Activity Count\")\n\n\nplt.figure(3)\ndf.iloc[:, 4] = df.iloc[:, 4].astype(float)\nplt.scatter(df.index/7200, df.iloc[:,4], s = 10)\nplt.title(\"State\")\nplt.show()\n\n# plt.figure(2)\n# df.iloc[:, 3] = df.iloc[:, 3].apply(lambda x: int(x, 16))\n# plt.scatter(df.index, df.iloc[:,3], s = 10)\n# plt.title(\"Activity Count\")","sub_path":"Abby_code.py","file_name":"Abby_code.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"364922775","text":"import random\n\nclass neuron:\n\n weights = []\n\n def __init__(self, n_weights):\n self.weights = [random.uniform(-5, 5) for x in range(n_weights)]\n\n def sum(self, inputs, type_activation = 1):\n assert len(inputs) == len(self.weights - 1), \"The length of input array \" \\\n \"doens't match with the len of \" \\\n \"weights array\"\n sum = 0\n for i in range(0, len(inputs)):\n sum = sum + inputs[i] * self.weights[i]\n sum = sum + self.weights[len(self.weights)] # BIAS\n\n # activation function\n if type_activation == 1:\n if sum > 1:\n return 1\n else:\n return 0\n else:\n return NotImplementedError\n\n def set_weights(self, w):\n self.weights = w\n\n def get_weights(self):\n return self.weights[:] # this avoid loss of reference\n","sub_path":"codes/neuron.py","file_name":"neuron.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"641152975","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.HomePage.as_view(), name='home'),\n path('about/', views.AboutView.as_view(), name='about'),\n path('blog/detail/', views.BlogDetailView.as_view(), name='blog_detail'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"584458230","text":"from flask import Flask, request, jsonify\nimport db\nfrom db import create_tables\n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n@app.route('/', methods=['GET'])\ndef home():\n return \"

Temperture reading api

This page is a test api and is not ment for public use.

\"\n\n@app.route('/temperture', methods=['GET'])\ndef get_device():\n device = db.get_devices()\n return jsonify(device)\n\n@app.route('/temperture', methods=['POST'])\ndef api_insert_device():\n location = request.args[\"location\"]\n reading = request.args[\"reading\"]\n isEmpty = request.args[\"isEmpty\"]\n result = db.insert_device(location, reading, isEmpty)\n return jsonify(result)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return \"

404

The page could not be found.

\", 404\n\nif __name__ == \"__main__\":\n db.create_tables()\n\n app.run()","sub_path":"api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353203529","text":"from unittest import TestCase\nfrom file_database_api import Files\nfrom webpage_database_api import WebPages\nimport os\nfrom datetime import date\n\n__author__ = 'Gareth Mok'\n\n\nclass TestFiles(TestCase):\n def test_new(self):\n filepath = \"test_last_open.json\"\n self.data = Files(filepath)\n\n self.assertTrue(os.path.isfile(filepath))\n os.remove(filepath)\n\n def test_add_update(self):\n filepath = \"test_last_open.json\"\n data = Files(filepath)\n\n WebPagespath1 = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test1.json')\n test1_WebPages = WebPages(WebPagespath1)\n\n WebPagespath2 = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test2.json')\n test2_WebPages = WebPages(WebPagespath2)\n\n name = \"Test File\"\n data.add_update(name, WebPagespath1, 2)\n self.assertEqual(data.data, {name: {'File': WebPagespath1, 'Delay': 2}, 'Directory': ''})\n\n data.add_update(name, WebPagespath2, 3)\n self.assertEqual(data.data, {name: {'File': WebPagespath2, 'Delay': 3}, 'Directory': ''})\n\n data.add_update(name+\"1\", WebPagespath1, 5)\n self.assertEqual(data.data, {name: {'File': WebPagespath2, 'Delay': 3},\n name+\"1\": {'File': WebPagespath1, 'Delay': 5}, 'Directory': ''})\n\n os.remove(filepath)\n os.remove(WebPagespath1)\n os.remove(WebPagespath2)\n\n def test_remove(self):\n filepath = \"test_last_open.json\"\n data = Files(filepath)\n\n WebPagespath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.json')\n test_WebPages = WebPages(WebPagespath)\n\n name = \"Test File\"\n data.add_update(name, WebPagespath, 4)\n data.remove(name)\n\n self.assertEqual(data.data, {'Directory': ''})\n\n os.remove(filepath)\n os.remove(WebPagespath)\n\n def test_grab(self):\n filepath = \"test_last_open.json\"\n data = Files(filepath)\n\n WebPagespath1 = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test1.json')\n test1_WebPages = WebPages(WebPagespath1)\n\n WebPagespath2 = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test2.json')\n test2_WebPages = WebPages(WebPagespath2)\n\n name = \"Test File\"\n data.add_update(name+\"1\", WebPagespath1, 5)\n data.add_update(name+\"2\", WebPagespath2, 2)\n self.assertEqual(data.grab(), {name+'2': {'File': WebPagespath2, 'Delay': 2},\n name+'1': {'File': WebPagespath1, 'Delay': 5}})\n\n os.remove(filepath)\n os.remove(WebPagespath1)\n os.remove(WebPagespath2)\n\n def test_empty(self):\n filepath = \"test_last_open.json\"\n data = Files(filepath)\n\n self.assertTrue(data.empty())\n\n WebPagespath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.json')\n test_WebPages = WebPages(WebPagespath)\n\n data.add_update(\"Test File\", WebPagespath, 2)\n\n self.assertFalse(data.empty())\n\n os.remove(filepath)\n os.remove(WebPagespath)\n","sub_path":"test_file_database_api.py","file_name":"test_file_database_api.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"100960463","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/utils/word.py\n# Compiled at: 2019-04-04 14:31:30\n# Size of source mod 2**32: 508 bytes\nfrom typing import List\nfrom utils.vectors import Vector\n\nclass Word:\n __doc__ = 'A single word (one line of the input vector embedding file)'\n\n def __init__(self, text: str, vector: Vector, frequency: int) -> None:\n self.text = text\n self.vector = vector\n self.frequency = frequency\n\n def __repr__(self) -> str:\n vector_preview = ', '.join(map(str, self.vector[:2]))\n return f\"{self.text} [{vector_preview}, ...]\"","sub_path":"pycfiles/ETNLP-0.1.1-py3.6/word.cpython-36.py","file_name":"word.cpython-36.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578968765","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='AccountingSystem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('add_date', models.DateTimeField(auto_now_add=True, verbose_name='add date', null=True)),\n ('edit_date', models.DateTimeField(auto_now=True, verbose_name='Last modification date', null=True)),\n ('name', models.CharField(max_length=250)),\n ],\n options={\n 'ordering': ['name'],\n },\n ),\n migrations.CreateModel(\n name='Document',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('add_date', models.DateTimeField(auto_now_add=True, verbose_name='add date', null=True)),\n ('edit_date', models.DateTimeField(auto_now=True, verbose_name='Last modification date', null=True)),\n ('name', models.CharField(max_length=250)),\n ('doc', models.FileField(null=True, upload_to=b'uploads/hedge_admin', blank=True)),\n ],\n options={\n 'ordering': ('add_date',),\n 'abstract': False,\n 'get_latest_by': 'add_date',\n },\n ),\n migrations.CreateModel(\n name='HedgeAdmin',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('add_date', models.DateTimeField(auto_now_add=True, verbose_name='add date', null=True)),\n ('edit_date', models.DateTimeField(auto_now=True, verbose_name='Last modification date', null=True)),\n ('name', models.CharField(max_length=250)),\n ('assets', models.CharField(max_length=250, null=True, verbose_name='Assets Under Administration ', blank=True)),\n ('firm_staff', models.IntegerField(null=True, verbose_name='Number of Staff (Firm)', blank=True)),\n ('is_sas_70_audit_report_review', models.BooleanField(default=False)),\n ('sas_70_review', models.TextField(null=True, blank=True)),\n ('type', models.CharField(blank=True, max_length=10, null=True, choices=[(b'type_1', 'type I'), (b'type_2', 'type II')])),\n ('sas70_coverage_period_from_date', models.DateTimeField(null=True, verbose_name='Sas70 coverage period from', blank=True)),\n ('sas70_coverage_period_to_date', models.DateTimeField(null=True, verbose_name='to', blank=True)),\n ('sas_70_audit_doc', models.FileField(null=True, upload_to=b'uploads/hedge_admin', blank=True)),\n ('firm_note', models.TextField(null=True, verbose_name='Standard Language & General Notes', blank=True)),\n ('firm_memorandum', models.FileField(null=True, upload_to=b'uploads/hedge_admin', blank=True)),\n ('accounting_system', models.ForeignKey(blank=True, to='hedge_admin.AccountingSystem', null=True)),\n ],\n options={\n 'ordering': ('add_date',),\n 'abstract': False,\n 'get_latest_by': 'add_date',\n },\n ),\n migrations.CreateModel(\n name='ShareRegistration',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('add_date', models.DateTimeField(auto_now_add=True, verbose_name='add date', null=True)),\n ('edit_date', models.DateTimeField(auto_now=True, verbose_name='Last modification date', null=True)),\n ('name', models.CharField(max_length=250)),\n ],\n options={\n 'ordering': ['name'],\n },\n ),\n migrations.AddField(\n model_name='hedgeadmin',\n name='share_registration',\n field=models.ForeignKey(verbose_name='Share Registration System', blank=True, to='hedge_admin.ShareRegistration', null=True),\n ),\n migrations.AddField(\n model_name='document',\n name='hedge_admin',\n field=models.ForeignKey(to='hedge_admin.HedgeAdmin'),\n ),\n ]\n","sub_path":"hedge_admin/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"382949568","text":"\"\"\"\nЗадача 3.\nВ соответствии с документацией Python,\ndeque – это обобщение стеков и очередей.\nВот основное правило: если вам нужно что-то быстро дописать или вытащить, используйте deque.\nЕсли вам нужен быстрый случайный доступ, используйте list.\n\nЗадача: создайте простой список (list) и очередь (deque).\nВыполните различные операции с каждым из объектов.\nСделайте замеры и оцените, насколько информация в документации\nсоответствует дейстивтельности.\n\"\"\"\n\nfrom timeit import timeit\nfrom collections import deque\nfrom random import randint\nimport cProfile\n\ns_list = [randint(0, 2000) for _ in range(100)]\ns_deq = deque([randint(0, 2000) for _ in range(100)])\n\n\ndef list_speed_test():\n s_list.append(2)\n s_list.insert(5, 1)\n s_list.pop(5)\n s_list.pop()\n\n\ndef deque_speed_test():\n s_deq.appendleft(1)\n s_deq.append(1)\n s_deq.popleft()\n s_deq.pop()\n\n\nprint(timeit('list_speed_test()', setup='from __main__ import list_speed_test'))\nprint(timeit('deque_speed_test()', setup='from __main__ import deque_speed_test'))\n\nprint(cProfile.run('''def list_speed_test():\n s_list.append(2)\n s_list.insert(5, 1)\n s_list.pop(5)\n s_list.pop()'''))\n\n\nprint(cProfile.run('''def deque_speed_test():\n s_deq.appendleft(1)\n s_deq.append(1)\n s_deq.popleft()\n s_deq.pop()'''))\n\n\n# операции с очередью быстрее и эффективнее по времени\n","sub_path":"Урок 5. Практическое задание/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"81490928","text":"# (c) 2017 Amazon Web Services, Inc., its affiliates, or\n# licensors. All Rights Reserved. This Content is provided subject to\n# the terms of the AWS Customer Agreement available at\n# http://aws.amazon.com/agreement or other written agreement between\n# Customer and Amazon Web Services, Inc.\nimport boto3\n\n\n################################################################################\n# functions: sqs\n################################################################################\nclass RegisterQueue:\n def __init__(self, ru, region, url):\n self.ru = ru\n self.region = region\n self.url = url\n self.sqs_resource = boto3.Session(region_name=region).resource('sqs')\n self.sqs_queue = self.sqs_resource.Queue(url)\n\n def get_hostnames(self, total):\n \"\"\" Get hostnames from SQS queue\n\n :param total: total expected hostnames in the queue\n :return: sorted list of hostnames\n \"\"\"\n hosts_online = set()\n\n while len(hosts_online) < total:\n messages = self.sqs_queue.receive_messages(\n AttributeNames=['All'],\n MaxNumberOfMessages=5,\n VisibilityTimeout=1,\n WaitTimeSeconds=5\n )\n for message in messages:\n hosts_online.add(message.body)\n self.ru.log.info(\"_get_hostnames(): total for {}:{} {}\".format(self.sqs_queue.url.split('/')[-1], len(hosts_online), hosts_online))\n self.ru.loop_sleep(3)\n\n return sorted(hosts_online)\n\n def send_hostname(self, hostname):\n \"\"\" Send hostname to SQS queue for registration\n\n :param sqs_queue: SQS queue object\n :param hostname: hostname to be sent\n :return:\n \"\"\"\n response = self.sqs_queue.send_message(\n MessageBody=hostname,\n DelaySeconds=0\n )\n self.ru.log.info(\"_send_hostname(): sending hostname {} to {}: {}\".format(hostname, self.sqs_queue.url.split('/')[-1], response['ResponseMetadata']['HTTPStatusCode']))\n return response\n\n def process_hosts(self, hosts_s3, hosts_queue):\n \"\"\" Perform logic to discern the state of hosts in the zookeeper ensemble\n\n :param hosts_s3: list of hosts in the S3 connection file\n :param hosts_queue: list of hosts in the SQS queue\n :return: different lists of hosts, based on status\n \"\"\"\n self.ru.log.info(\"_process_hosts(): s3 list: {}\".format(hosts_s3))\n self.ru.log.info(\"_process_hosts(): sqs list: {}\".format(hosts_queue))\n if len(hosts_s3) == 0:\n hosts_existing = sorted(hosts_queue)\n hosts_replaced = []\n hosts_new = hosts_existing\n hosts_final = hosts_existing\n else:\n hosts_existing = sorted(list(set(hosts_s3).intersection(set(hosts_queue))))\n hosts_replaced = sorted(list(set(hosts_s3).difference(set(hosts_queue))))\n hosts_new = sorted(list(set(hosts_queue).difference(set(hosts_s3))))\n hosts_final = list(hosts_s3)\n for host in hosts_replaced:\n index_s3 = hosts_s3.index(host)\n index_replaced = hosts_replaced.index(host)\n replacement = hosts_new[index_replaced]\n self.ru.log.info(\"_process_hosts(): replacing {} at index {} with {}\".format(host, index_s3, replacement))\n hosts_final[index_s3] = replacement\n return hosts_final, hosts_replaced, hosts_existing, hosts_new\n\n","sub_path":"code/register_queue.py","file_name":"register_queue.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5872475","text":"# -*- encoding=utf-8 -*-\nimport socket\n\n# 创建socket对象SOCK_DGRAM表示udp协议。\nrecver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nrecver.bind((\"localhost\", 8888))\nprint(\"启动了udp接受者\")\nwhile True:\n (data, addr) = recver.recvfrom(1024)\n msg = bytes.decode(data);\n\n print(\"接收了 from \" + str(addr[0]) + \":\" + str(addr[1]) + \" : \" + msg)\n\n","sub_path":"Python_Project/mypython-1/UDPReceiver.py","file_name":"UDPReceiver.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"182447803","text":"def Bsearch(arr):\n start = 0\n end = len(arr) - 1\n\n mid = (start + end) // 2\n if len(arr) % 2 != 0:\n return float(arr[mid])\n else:\n median = (arr[mid] + arr[mid + 1]) / 2\n return median\n\n\ndef findMedianSortedArrays(arr1,arr2):\n n = len(arr1)\n\n m = len(arr2)\n\n if m < n:\n arr2 = arr1\n arr1 = arr2\n\n if n == 0:\n if m == 1:\n return float(arr2[0])\n if m == 2:\n return (arr2[0] + arr2[1]) / 2\n else:\n return Bsearch(arr2)\n\n if m == 0:\n if n == 1:\n return float(arr1[0])\n if n == 2:\n return (arr1[0] + arr1[1]) / 2\n else:\n return Bsearch(arr1)\n\n\n\n start1 = 0\n end1 = len(arr1)\n total =(m + n + 1) // 2\n\n while (start1 <= end1):\n\n i1 = (start1 + end1) // 2\n\n i2 = total - i1\n\n max1 = arr1[i1 - 1] if i1 != 0 else -float('inf')\n min1 = arr1[i1] if i1 != n else float('inf')\n max2 = arr2[i2 - 1] if i2 != 0 else -float('inf')\n min2 = arr2[i2] if i2 != m else float('inf')\n\n # if max2 <= min1 and max1 <= min2:\n # if (m + n) % 2 == 0:\n # median = (max(max1, max2) + min(min1, min2)) / 2\n # return median\n # else:\n # median = (max(max1, max2)) / 2\n # return median\n if (max1 > min2):\n end1 = i1 - 1\n\n elif (max2 > min1):\n start1 = i1 + 1\n else:\n\n if (m + n) % 2 == 0:\n median = (max(max1, max2) + min(min1, min2)) / 2\n return median\n else:\n median = (max(max1,max2)) / 2\n return median\n\narr1 = [3]\narr2 = [-2,-1]\nprint(findMedianSortedArrays(arr1,arr2))","sub_path":"SEARCHING AND SORTING/Binary Search/shsh.py","file_name":"shsh.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"529697413","text":"# Convert Embedded.properties into C++ source code to include in Schott\ncount = 0\nsection = 1\nwith open(\"Embedded.cpp\", \"w\") as o:\n\to.write(\"const char *props\" + str(section) + \" = \\n\")\n\tsection += 1\n\twith open(\"Embedded.properties\") as f:\n\t\tfor l in f.readlines():\n\t\t\tif l.endswith('\\n'):\n\t\t\t\tl = l[:-1]\n\t\t\tl = l.replace('\\\\', '\\\\\\\\')\n\t\t\tl = l.replace('\"', '\\\\\"')\n\t\t\tl = '\"' + l + '\\\\n\"\\n'\n\t\t\to.write(l)\n\t\t\tcount += len(l)\n\t\t\t# Visual C++ doesn't allow string literals to be larger than 64K\n\t\t\tif count > 60000:\n\t\t\t\to.write(\";\\n\")\n\t\t\t\to.write(\"const char *props\" + str(section) + \" = \\n\")\n\t\t\t\tsection += 1\n\t\t\t\tcount = 0\n","sub_path":"Schott/Embedify.py","file_name":"Embedify.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"444252874","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport copy\nimport threading\nimport time\n\nfrom six.moves import xrange\n\nfrom echomesh.base import Config\nfrom echomesh.color.LightBank import LightBank\nfrom echomesh.color import ColorTable\nfrom echomesh.util import Log\nfrom echomesh.util.thread import TkThreadRunner\n\nLOGGER = Log.logger(__name__)\nBLACK = '#000000'\nWINDOW_TITLE = 'Lighting visualization window.'\n\ndef _get_dimension(count, columns, rows):\n if not (columns or rows):\n columns = 32\n elif not columns:\n columns = 1 + (count - 1) // columns\n if not rows:\n rows = 1 + (count - 1) // columns\n return columns, rows\n\nclass TkLightBank(LightBank):\n def _before_thread_start(self):\n self.tk_count = 0\n self.light_count = 0\n self.count_difference = 1\n self.last_get = {}\n self.tkwin = None\n self.count = 0\n self.lights = []\n\n super(TkLightBank, self)._before_thread_start()\n TkThreadRunner.run()\n Config.add_client(self)\n\n def destroy(self):\n TkThreadRunner.stop()\n self.tkwin.destroy()\n self.tkwin = None\n\n def _after_thread_pause(self):\n super(TkLightBank, self)._after_thread_pause()\n def destroy():\n TkThreadRunner.stop()\n with self.lock:\n tkwin, self.tkwin = self.tkwin, None\n tkwin.destroy()\n TkThreadRunner.defer(destroy)\n\n def initialize_tk(self):\n with self.lock:\n if self.tkwin:\n import Tkinter\n self.canvas.delete(Tkinter.ALL)\n else:\n import Tkinter\n self.tkwin = Tkinter.Tk()\n self.tkwin.title(WINDOW_TITLE)\n self.canvas = Tkinter.Canvas(self.tkwin,\n width=self.width, height=self.height)\n if 'rectangle'.startswith(self.shape):\n self.method = self.canvas.create_rectangle\n else:\n self.method = self.canvas.create_oval\n self.tkwin.geometry('%dx%d' % (self.width, self.height))\n self.tkwin.configure(background=self.background)\n self.canvas.pack()\n self.lights = [self._make_light(i) for i in xrange(self.count)]\n self.tkwin.update()\n\n def config_update(self, get):\n count = Config.get('light', 'count')\n def _get(*items):\n return get(*(('light', 'visualizer') + items))\n\n last_get = _get()\n if self.last_get == last_get and self.count == count:\n return\n self.last_get = copy.deepcopy(last_get)\n self.count = count\n\n def _color(*items):\n return ColorTable.to_tk(ColorTable.to_color(_get(*items)))\n\n self.border_color = _color('instrument', 'border', 'color')\n self.button_background = _color('instrument', 'background')\n self.background = _color('background')\n self.border_width = _get('instrument', 'border', 'width')\n self.shape = _get('instrument', 'shape')\n self.size = _get('instrument', 'size')\n self.light_padding = _get('instrument', 'padding')\n self.padding = _get('padding')\n self.columns, self.rows = _get_dimension(self.count, *_get('layout'))\n self.width = (self.padding['top'] +\n self.columns * (self.size[0] + self.light_padding[0]) +\n self.padding['right'])\n self.height = (self.padding['top'] +\n self.rows * (self.size[1] + self.light_padding[1]) +\n self.padding['bottom'])\n TkThreadRunner.defer(self.initialize_tk)\n\n def _make_light(self, index):\n column = index % self.columns\n row = index // self.columns\n x = (self.padding['left'] +\n column * (self.size[0] + self.light_padding[0]))\n\n y = (self.padding['top'] +\n row * (self.size[1] + self.light_padding[1]))\n return self.method(x, y, x + self.size[0], y + self.size[1],\n outline=self.border_color)\n\n def clear(self):\n def _clear():\n with self.lock:\n if self.tkwin:\n for i in xrange(self.count):\n self.canvas.itemconfig(self.lights[i], fill=BLACK)\n self.tkwin.update()\n TkThreadRunner.defer(_clear)\n\n def _display_lights(self, lights, brightness):\n light_colors = [ColorTable.to_tk(light, brightness) for light in lights]\n diff = self.count - len(lights)\n if diff > 0:\n light_colors += [BLACK] * diff\n\n def display():\n with self.lock:\n if self.tkwin:\n for i in xrange(self.count):\n self.canvas.itemconfig(self.lights[i], fill=light_colors[i])\n self.tkwin.update()\n self.tk_count += 1\n\n TkThreadRunner.defer(display)\n self.light_count += 1\n\n count_difference = self.light_count - self.tk_count\n if count_difference > self.count_difference:\n if count_difference > 10 and count_difference < 50:\n LOGGER.error('Tk is behind by %s frames - reduce config.light.period',\n count_difference)\n self.count_difference = count_difference\n","sub_path":"code/python/echomesh/color/TkLightBank.py","file_name":"TkLightBank.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"257317427","text":"from datetime import datetime\n\nfrom sqlalchemy import Column, Boolean, BigInteger, String, JSON, TIMESTAMP\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass PromoCode(Base):\n __tablename__ = 'promo_codes'\n _id = Column(\"id\", BigInteger, primary_key=True, autoincrement=True)\n code = Column(String, nullable=False)\n meta = Column(JSON, nullable=False, default='{}')\n valid_from = Column(TIMESTAMP, nullable=False)\n valid_to = Column(TIMESTAMP, nullable=False)\n is_invalid = Column(Boolean, nullable=False, default=False)\n activated_at = Column(TIMESTAMP, nullable=True)\n created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)\n\n def as_dict(self):\n return {\n 'code': self.code,\n 'meta': self.meta,\n 'valid_from': self.valid_from,\n 'valid_to': self.valid_to,\n 'is_invalid': self.is_invalid,\n 'activated_at': self.activated_at,\n 'created_at': self.created_at,\n }\n\n\n","sub_path":"src/db/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408043774","text":"import time\n\nimport serial\ntry:\n import readline\nexcept ImportError:\n pass\n\nimport glob\nimport sys\n\ndef serial_ports():\n \"\"\"Lists serial ports\n :raises EnvironmentError:\n On unsupported or unknown platforms\n :returns:\n A list of available serial ports\n \"\"\"\n if sys.platform.startswith('win'):\n ports = ['COM' + str(i + 1) for i in range(256)]\n\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this is to exclude your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.usb*') + glob.glob('/dev/cu.usb*')\n\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n\ndef main():\n ser = None\n\n try:\n while True:\n ser = None\n if len(sys.argv) > 1:\n try:\n ser = serial.Serial(sys.argv[1])\n except:\n raise OSError()\n\n else:\n \n ser = None\n \n potential_ports = serial_ports()\n\n for c in potential_ports:\n try:\n print(\"Attempting to connect to\", c)\n ser = serial.Serial(c)\n ser.write(b\"cloi hello\\n\")\n time.sleep(1)\n waiting = ser.in_waiting\n print(waiting, \"bytes to read\")\n if waiting > 0:\n data = ser.read(waiting)\n print(\"Received\", data)\n if data == b\"Hello World\\n\":\n break\n else:\n ser.close()\n ser = None\n else:\n ser.close()\n ser = None\n except:\n continue\n\n if not ser:\n raise OSError()\n\n try:\n while True:\n waiting = ser.in_waiting\n if waiting > 0:\n print(str(ser.read(waiting), 'utf-8'), end='')\n ser.write(bytes(input('>>> '), 'utf-8'))\n time.sleep(0.1)\n except OSError:\n print(\"Device disconnected, attempting to reconnect\")\n except (KeyboardInterrupt, EOFError):\n if ser:\n ser.close()\n print(\"\\nProgram exited by user\")\n except (KeyError, OSError):\n print(\"Could not find a device to connect to\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"535260025","text":"import h5py\nimport numpy as np\nimport matplotlib\nimport numpy as np\nfrom glob import glob\nimport imageio\nimport rasterio\nfrom rasterio.transform import Affine\nimport os\nimport shapefile as shp\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt \nimport time\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib import cm\nimport matplotlib.colors as mcolors\nfrom tempfile import NamedTemporaryFile\n\nfname = \"PAAH21.EUOC.270930.967\"\n\nf1 = NamedTemporaryFile()\nf2 = NamedTemporaryFile()\nf3 = NamedTemporaryFile()\ntmpfile1 = f1.name + \".tif\"\ntmpfile2 = f2.name + \".tif\"\ntmpfile3 = f3.name + \".tif\"\n\nhf = h5py.File(fname,'r') \ndata = hf.get('dataset1')\nodata = np.array(data.get(\"data1/data\"), dtype=np.float)\nodata = data.get(\"data1/data\").value\nimport pdb\nnodata = hf.get('/dataset1/what').attrs['nodata']\n\n#h5_png = fname.replace(\"h5\",\"png\")\nh5_png_cosmo = fname + \"-cosmo1.png\"\nh5_png = fname + \".png\"\nimageio.imwrite(tmpfile1, odata)\n\ndef plotShapefile(shape, colour, linewidth=1.0):\n parts = shape.parts\n if parts != 0:\n parts.append(len(shape.points))\n for part in parts[:-1]:\n start = part\n end = parts[parts.index(part)+1]\n x = [i[0] for i in shape.points[start:end]]\n y = [i[1] for i in shape.points[start:end]]\n plt.plot(x,y, color=colour, linewidth=linewidth)\n else:\n x = [i[0] for i in shape.points[:]]\n y = [i[1] for i in shape.points[:]]\n plt.plot(x,y, color=colour, linewidth=linewidth)\n\n# make a color map of fixed colors\ncolours = [\"#000000\", \"#FFFFFF\", \"#E2E2E2\", \"#640064\", \"#AC02AC\", \"#DC02DC\", \"#3232C8\", \"#0064FF\", \"#009696\",\"#01C832\",\"#64FF00\",\"#96FF00\",\"#C8FF32\",\"#FFFF00\",\"#FFC800\",\"#FFA000\",\"#FF7D00\",\"#E11900\"]\ncc = mcolors.ColorConverter().to_rgba\nc16 = [cc(c0, 1.) for c0 in colours]\nc16[0] = cc(colours[0], 0.5)\ncmap16 = mcolors.ListedColormap(c16)\nbounds = [nodata - 1, nodata + 1, 0, 0.16,0.25,0.40,0.63,1.0,1.6,2.5,4.0,6.3,10,16,25,40,63,100]\nnorm = mcolors.BoundaryNorm(bounds, cmap16.N)\n\ndataset = rasterio.open(tmpfile1)\ncrs_data = rasterio.crs.CRS.from_proj4(\"+proj=laea +lat_0=55.0 +lon_0=10.0 +x_0=1950000.0 +y_0=-2100000.0 +units=m +ellps=WGS84\")\n\ndata = dataset.read(1)\nprint(np.histogram(odata, bounds))\n\nres = 2000.0\n\n# the coordinates are the top left coordinates of the odyssey composite,\n# taken from the hdf5 file where they are given in lon/lat and translated\n# in laea\n\n# h5dump -a /where/UL_lat PAAH21.EUOC.270930.967 \n# HDF5 \"PAAH21.EUOC.270930.967\" {\n# ATTRIBUTE \"UL_lat\" {\n# DATATYPE H5T_IEEE_F64LE\n# DATASPACE SCALAR\n# DATA {\n# (0): 67.0228\n# }\n# }\n# }\n# clem@adula:~/Documents/MeteoSwiss/opera-hdf5$ h5dump -a /where/UL_lon PAAH21.EUOC.270930.967 \n# HDF5 \"PAAH21.EUOC.270930.967\" {\n# ATTRIBUTE \"UL_lon\" {\n# DATATYPE H5T_IEEE_F64LE\n# DATASPACE SCALAR\n# DATA {\n# (0): -39.5358\n# }\n# }\n# }\n\n# gdaltransform -s_srs EPSG:4326 -t_srs \"+proj=laea +lat_0=55.00 +lon_0=10.0 +x_0=1950000.0 +y_0=-2100000.0 +ellps=WGS84 +units=m\"\n# -39.5358 67.0228\n# -3.03482991317287 -2.28301597991958 0\n#\n\ntransform = rasterio.transform.from_origin(-2.28301597991958, -3.03482991317287, res, res)\n\nnew_dataset = rasterio.open(\n tmpfile2,\n 'w',\n driver='GTiff',\n height=dataset.shape[0],\n width=dataset.shape[1],\n count=1,\n dtype=data.dtype,\n crs=crs_data,\n transform=transform,\n)\nnew_dataset.write(data, 1)\nnew_dataset.close()\n\nos.system(\"cp \"+ tmpfile2 + \" opera.tif\")\n\n# the coordinates below are the COSMO-1 lower left and upper right corners\n# converted in the laea coordinates system\n# -tr gives the cosmo-1 resolution (approx 1.1 km)\n\nos.system(\"gdalwarp -te 1237149.02666365 -3426195.96337066 2436307.94907839 -2663175.58964395 -tr 1100 1100 -overwrite \" + tmpfile2 + \" \" + tmpfile3)\nos.system(\"cp \"+ tmpfile3 + \" cosmo.tif\")\n\ndataset_opera = rasterio.open(tmpfile2)\ndd = dataset_opera.read(1)\n\nfig = plt.figure(figsize=(dd.shape[1] / 100.0, dd.shape[0] / 100.0), frameon=False)\nax = fig.add_axes([0, 0, 1, 1])\nax.axis('off')\n#fig.patch.set_visible(False)\n\n\nplt.imshow(dd, extent=[-2.283, 3799997.717, -4400003.035, -3.035], cmap=cmap16, norm=norm, aspect='auto')\n\n# ogr2ogr -lco ENCODING=UTF-8 -t_srs \"+proj=laea +lat_0=55.00 +lon_0=10.0 +x_0=1950000.0 +y_0=-2100000.0 +ellps=WGS84 +units=m\" -overwrite opera.shp ne_50m_admin_0_countries.shp\n# projection used, the one given in the odyssey hdf5 file seems to have the wrong ellps parameter\nsf = shp.Reader(\"opera.shp\")\n\nplt.plot()\n\nfor shape in sf.shapeRecords():\n plotShapefile(shape.shape, \"black\", linewidth=1.0)\n\nax.set_ylim([-4400003.035, -3.035])\nax.set_xlim([-2.283, 3799997.717])\n\nax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)\nax.set_aspect(\"equal\")\nax.margins(0)\nplt.axis('off')\nplt.plot()\nplt.savefig(h5_png, dpi=100)\nprint(\"Saved: \"+h5_png)\n\ndataset_cosmo = rasterio.open(tmpfile3)\ndd = dataset_cosmo.read(1)\nfig = plt.figure(figsize=(dd.shape[1] / 100.0, dd.shape[0] / 100.0), frameon=False)\nax = fig.add_axes([0, 0, 1, 1])\nax.axis('off')\n\nplt.imshow(dd, extent=[1237149.02666365, 2436307.94907839, -3426195.96337066, -2663175.58964395], interpolation='bilinear', cmap=cmap16, norm=norm, aspect='auto')\n\nsf = shp.Reader(\"opera.shp\")\nplt.plot()\n\nfor shape in sf.shapeRecords():\n plotShapefile(shape.shape, \"black\", linewidth=1.0)\n\nax.set_ylim([-3426195.96337066, -2663175.58964395])\nax.set_xlim([1237149.02666365, 2436307.94907839])\nax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)\nax.set_aspect(\"equal\")\nax.margins(0)\nplt.axis('off')\nplt.plot()\nplt.savefig(h5_png_cosmo, dpi=100)\nprint(\"Saved: \"+h5_png_cosmo)\n\nos.unlink(tmpfile1)\nos.unlink(tmpfile2)\nos.unlink(tmpfile3)\n","sub_path":"opera-clip.py","file_name":"opera-clip.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"575496647","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport time\r\nimport torch\r\nfrom core.evaluate import accuracy\r\n\r\ndef train(config, train_loader, model, criterion, optimizer, epoch, writer_dict, _print):\r\n batch_time = AverageMeter()\r\n data_time = AverageMeter()\r\n losses = AverageMeter()\r\n accs = AverageMeter()\r\n\r\n # switch to train mode\r\n model.train()\r\n\r\n end = time.time()\r\n for i, (input, target, _, _) in enumerate(train_loader):\r\n # measure data loading time\r\n data_time.update(time.time() - end)\r\n\r\n # 非阻塞允许多个线程同时进入临界区\r\n input = input.cuda(non_blocking=True)\r\n target = target.cuda(non_blocking=True)\r\n\r\n # compute output\r\n output = model(input)\r\n\r\n loss = criterion.facexray_loss(output, target)\r\n loss = loss * 100\r\n\r\n # compute gradient and do update step\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # measure accuracy and record loss\r\n losses.update(loss.item(), input.size(0))\r\n\r\n # 改用语义分割的PA准确率\r\n acc,_ = accuracy(output, target)\r\n\r\n accs.update(acc, input.size(0))\r\n\r\n # measure elapsed time\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n\r\n if i % config.PRINT_FREQ == 0:\r\n msg = 'Epoch: [{0}][{1}/{2}]\\t' \\\r\n 'Time {batch_time.val:.3f}s ({batch_time.avg:.3f}s)\\t' \\\r\n 'Speed {speed:.1f} samples/s\\t' \\\r\n 'Data {data_time.val:.3f}s ({data_time.avg:.3f}s)\\t' \\\r\n 'Loss {loss.val:.5f} ({loss.avg:.5f})\\t' \\\r\n 'Accuracy {accuracy:.4f}\\t'.format(\r\n epoch, i, len(train_loader), batch_time=batch_time,\r\n speed=input.size(0)/batch_time.val,\r\n data_time=data_time, loss=losses, accuracy=acc)\r\n _print(msg)\r\n\r\n if writer_dict:\r\n writer = writer_dict['writer']\r\n global_steps = writer_dict['train_global_steps']\r\n writer.add_scalar('train_loss', losses.val, global_steps)\r\n writer.add_scalar('train_acc', acc, global_steps)\r\n writer_dict['train_global_steps'] = global_steps + 1\r\n\r\ndef validate(config, val_loader, model, criterion, writer_dict, _print):\r\n batch_time = AverageMeter()\r\n losses = AverageMeter()\r\n accs = AverageMeter()\r\n\r\n # switch to evaluate mode\r\n model.eval()\r\n\r\n with torch.no_grad():\r\n end = time.time()\r\n for i, (input, target, _, _) in enumerate(val_loader):\r\n\r\n # 非阻塞允许多个线程同时进入临界区\r\n input = input.cuda(non_blocking=True)\r\n target = target.cuda(non_blocking=True)\r\n\r\n # compute output\r\n output = model(input)\r\n\r\n loss = criterion.facexray_loss(output, target)\r\n\r\n # measure accuracy and record loss\r\n losses.update(loss.item(), input.size(0))\r\n\r\n acc, _ = accuracy(output, target)\r\n\r\n accs.update(acc, input.size(0))\r\n\r\n # measure elapsed time\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n\r\n msg = 'Test: Time {batch_time.avg:.3f}\\t' \\\r\n 'Loss {loss.avg:.4f}\\t' \\\r\n 'Accuracy {accuracy:.4f}\\t'.format(\r\n batch_time=batch_time, loss=losses, accuracy=acc)\r\n _print(msg)\r\n\r\n if writer_dict:\r\n writer = writer_dict['writer']\r\n global_steps = writer_dict['valid_global_steps']\r\n writer.add_scalar('valid_loss', losses.avg, global_steps)\r\n writer.add_scalar('valid_acc', acc, global_steps)\r\n writer_dict['valid_global_steps'] = global_steps + 1\r\n\r\n return accs.val\r\n\r\n\r\n\r\nclass AverageMeter(object):\r\n \"\"\"Computes and stores the average and current value\"\"\"\r\n def __init__(self):\r\n self.reset()\r\n\r\n def reset(self):\r\n self.val = 0\r\n self.avg = 0\r\n self.sum = 0\r\n self.count = 0\r\n\r\n def update(self, val, n=1):\r\n self.val = val\r\n self.sum += val * n\r\n self.count += n\r\n self.avg = self.sum / self.count\r\n","sub_path":"Net_gpuVer3.0/core/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167295321","text":"# Code references:\n# User CrazyGuitar: SQLAlchemy https://github.com/crazyguitar/pysheeet/blob/master/docs/notes/python-sqlalchemy.rst#set-a-database-url\n# Constraints: https://docs.sqlalchemy.org/en/13/core/constraints.html\n# Multiple Constraints: https://gist.github.com/asyd/3cff61ed09eabe187d3fbec2c8a3ee39\n# Flash Messages not displayed: https://stackoverflow.com/questions/49012562/flask-one-flash-message-not-getting-displayed\n# Remove Password: https://dba.stackexchange.com/questions/83164/remove-password-requirement-for-user-postgres\n# Split Flask Models: https://stackoverflow.com/questions/34281873/how-do-i-split-flask-models-out-of-app-py-without-passing-db-object-all-over\n\n#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nimport json\nimport dateutil.parser\nfrom datetime import datetime\nimport babel\nfrom flask import Flask, render_template, request, Response, flash, redirect, url_for\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nimport logging\nfrom logging import Formatter, FileHandler\nfrom flask_wtf import Form\nfrom forms import *\nfrom flask_migrate import Migrate\nimport sys\n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\nmoment = Moment(app)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n#----------------------------------------------------------------------------#\n# Models.\n#----------------------------------------------------------------------------#\n\n# class Venue\n#----------------------------------------------------------------------------#\n\nclass Venue(db.Model):\n __tablename__ = 'Venue'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n address = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n #genres = db.Column(\"genres\", db.ARRAY(db.String()), nullable=False)\n genre_id = db.Column(db.Integer, db.ForeignKey('Genre.id'), nullable=True)\n website = db.Column(db.String(500))\n seeking_talent = db.Column(db.Boolean, default=False)\n seeking_description = db.Column(db.String(120))\n\n shows = db.relationship('Show', backref='venue', lazy=True)\n\n def __repr__(self):\n return f''\n\n# class Artist\n#----------------------------------------------------------------------------#\n\nclass Artist(db.Model):\n __tablename__ = 'Artist'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n #genres = db.Column(\"genres\", db.ARRAY(db.String()), nullable=False)\n genre_id = db.Column(db.Integer, db.ForeignKey('Genre.id'), nullable=True)\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n website = db.Column(db.String(500))\n seeking_venue = db.Column(db.Boolean, default=False)\n seeking_description = db.Column(db.String(120))\n\n shows = db.relationship('Show', backref='artist', lazy=True)\n genres = db.relationship('Genre', backref='artist', lazy=True)\n\n def __repr__(self):\n return f''\n\n# class Show\n#----------------------------------------------------------------------------#\n\nclass Show(db.Model):\n __tablename__ = 'Show'\n\n id = db.Column(db.Integer, primary_key=True)\n artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)\n venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)\n start_time = db.Column(db.DateTime, nullable=False)\n\n def __repr__(self):\n return f''\n\n# class Genre (Didn't use it at the end)\n#----------------------------------------------------------------------------#\nclass Genre(db.Model):\n __tablename__ = 'Genre'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n\n#----------------------------------------------------------------------------#\n# Filters.\n#----------------------------------------------------------------------------#\n\ndef format_datetime(value, format='medium'):\n date = dateutil.parser.parse(value)\n if format == 'full':\n format=\"EEEE MMMM, d, y 'at' h:mma\"\n elif format == 'medium':\n format=\"EE MM, dd, y h:mma\"\n return babel.dates.format_datetime(date, format)\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n@app.route('/')\ndef index():\n return render_template('pages/home.html')\n\n# Venues\n#----------------------------------------------------------------------------#\n# Code ref. Nicholas Pretorius\n\n@app.route('/venues')\ndef venues():\n venue_list = Venue.query.all()\n\n venues_dict = {}\n\n for venue in venue_list:\n key = f'{venue.city}, {venue.state}'\n\n venues_dict.setdefault(key, []).append({\n 'id': venue.id,\n 'name': venue.name,\n 'num_upcoming_shows': len(venue.shows),\n 'city': venue.city,\n 'state': venue.state\n })\n\n data = []\n for value in venues_dict.values():\n data.append({\n 'city': value[0]['city'],\n 'state': value[0]['state'],\n 'venues': value\n }) \n\n return render_template('pages/venues.html', areas=data);\n\n# Venue Search\n#----------------------------------------------------------------------------#\n# Code ref. Ovie Mudi\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n\n search_term = request.form.get('search_term', '')\n venue_search_result = Venue.query.filter(Venue.name.ilike(f'%{search_term}%')).all()\n \n response={\n \"count\": len(venue_search_result),\n \"data\": [] \n }\n\n for result in venue_search_result:\n response[\"data\"].append({\n \"id\": result.id,\n \"name\": result.name,\n \"num_upcoming_shows\": len(result.shows)\n })\n\n return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', ''))\n\n# Venue Show\n#----------------------------------------------------------------------------#\n\n@app.route('/venues/')\ndef show_venue(venue_id):\n \n # Query Artist table (SELECT * FROM Artist FILTER BY id)\n venue = Venue.query.filter_by(id=venue_id).first()\n\n past_shows = []\n upcoming_shows = []\n \n # Create empty lists for past and upcoming shows\n show_attributes = None\n for show in venue.shows:\n show_attributes = {\n \"artist_id\": show.artist.id,\n \"artist_name\": show.artist.name,\n \"artist_image_link\": show.artist.image_link,\n \"start_time\": show.start_time.strftime('%m/%d/%Y, %H:%M:%S')\n }\n\n if show.start_time <= datetime.now():\n past_shows.append(show_attributes)\n else:\n upcoming_shows.append(show_attributes)\n\n venue_dict = {\n \"id\": venue.id,\n \"name\": venue.name,\n \"genres\": venue.genres,\n \"address\": venue.address,\n \"city\": venue.city,\n \"state\": venue.state,\n \"phone\": venue.phone,\n \"website\": venue.website,\n \"facebook_link\": venue.facebook_link,\n \"image_link\": venue.image_link,\n \"seeking_talent\": venue.seeking_talent,\n \"seeking_description\": venue.seeking_description, \n \"past_shows\": past_shows,\n \"upcoming_shows\": upcoming_shows,\n \"past_shows_count\": len(past_shows),\n \"upcoming_shows_count\": len(upcoming_shows)\n }\n\n return render_template('pages/show_venue.html', venue=venue_dict)\n\n# Venue Create\n#----------------------------------------------------------------------------#\n\n@app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n form = VenueForm()\n return render_template('forms/new_venue.html', form=form)\n\n@app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n new_venue = Venue(\n name=request.form['name'],\n city=request.form['city'],\n state=request.form['state'],\n address=request.form['address'],\n phone=request.form['phone'],\n genres=request.form.getlist('genres'),\n facebook_link=request.form['facebook_link'],\n image_link=request.form['image_link']\n )\n\n try:\n db.session.add(new_venue)\n db.session.commit()\n flash('The venue ' + request.form['name'] + ' was successfully listed!')\n\n except:\n flash('An error occurred. Venue ' + new_venue.name + ' could not be listed.', category='error')\n print('exc_info()', exc_info())\n db.session.rollback()\n \n finally:\n db.session.close()\n return redirect(url_for('venues')) \n\n# Venue Delete\n#----------------------------------------------------------------------------#\n\n@app.route('/venues/', methods=['DELETE'])\ndef delete_venue(venue_id):\n #status = False\n try:\n venue = Venue.query.get(venue_id)\n db.session.delete(venue)\n db.session.commit()\n #status = True\n flash('The venue ' + request.form['name'] + ' was successfully deleted!')\n\n except:\n flash('An error occurred. Venue ' + new_venue.name + ' could not be deleted.', category='error')\n print('exc_info()', exc_info())\n db.session.rollback()\n \n finally:\n db.session.close()\n return redirect(url_for('/')) \n\n# Artists\n#----------------------------------------------------------------------------#\n@app.route('/artists')\n\ndef artists():\n data = []\n artists = Artist.query.all()\n\n for artist in artists:\n data.append({\n \"id\": artist.id,\n \"name\": artist.name\n })\n\n return render_template('pages/artists.html', artists=data)\n\n# Artists Search\n#----------------------------------------------------------------------------#\n\n@app.route('/artists/search', methods=['POST'])\ndef search_artists():\n search_term = request.form.get('search_term', '')\n artist_search_result = Artist.query.filter(Artist.name.ilike(f'%{search_term}%')).all()\n response={\n \"count\": len(artist_search_result),\n \"data\": [] \n }\n\n for result in artist_search_result:\n response[\"data\"].append({\n \"id\": result.id,\n \"name\": result.name,\n \"num_upcoming_shows\": len(result.shows)\n })\n\n return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))\n\n# Artist Page Show\n#----------------------------------------------------------------------------#\n\n@app.route('/artists/')\ndef show_artist(artist_id):\n \n# Query Artist table (SELECT * FROM Artist ORDER BY id)\n artist = Artist.query.filter_by(id=artist_id).first()\n\n# Create empty lists for past and upcoming shows\n past_shows = []\n upcoming_shows = []\n\n# Create a dictionary with Show details\n show_details = None\n for show in artist.shows:\n show_details = {\n \"venue_id\": show.venue.id,\n \"venue_name\": show.venue.name,\n \"venue_image_link\": show.venue.image_link,\n \"start_time\": show.start_time.strftime('%m/%d/%Y, %H:%M:%S')\n }\n \n# Populate lists with Show details depending on date \n if show.start_time <= datetime.now():\n past_shows.append(show_details)\n else:\n upcoming_shows.append(show_details)\n\n# Artist data to be displayed\n artist_dict = {\n \"id\": artist.id,\n \"name\": artist.name,\n \"genres\": artist.genres,\n \"city\": artist.city,\n \"state\": artist.state,\n \"phone\": artist.phone,\n \"website\": artist.website,\n \"facebook_link\": artist.facebook_link,\n \"image_link\": artist.image_link,\n \"seeking_venue\": artist.seeking_venue,\n \"seeking_description\": artist.seeking_description, \n \"past_shows\": past_shows,\n \"upcoming_shows\": upcoming_shows,\n \"past_shows_count\": len(past_shows),\n \"upcoming_shows_count\": len(upcoming_shows)\n }\n\n return render_template('pages/show_artist.html', artist=artist_dict)\n\n# Artist Edit\n#----------------------------------------------------------------------------#\n# Code ref. Tune Dev\n\n@app.route('/artists//edit', methods=['GET'])\ndef edit_artist(artist_id):\n form = ArtistForm(request.form)\n artist = Artist.query.filter_by(id=artist_id).first()\n\n form.name.process_data(artist.name)\n form.city.process_data(artist.city)\n form.phone.process_data(artist.phone)\n form.state.process_data(artist.state)\n form.genres.process_data(artist.genres)\n form.facebook_link.process_data(artist.facebook_link)\n form.image_link.process_data(artist.image_link)\n\n return render_template('forms/edit_artist.html', form=form, artist=artist)\n\n@app.route('/artists//edit', methods=['POST'])\ndef edit_artist_submission(artist_id):\n artist = Artist.query.filter_by(id=artist_id).first()\n try:\n artist.name = request.form['name']\n artist.city = request.form['city']\n artist.state = request.form['state']\n artist.phone = request.form['phone']\n artist.genres = request.form.getlist('genres')\n artist.facebook_link = request.form['facebook_link']\n artist.image_link = request.form['image_link']\n\n db.session.commit()\n flash('The artist ' + request.form['name'] + ' was successfully updated!')\n except:\n flash('An error occurred. Artist ' +\n request.form['name'] + ' could not be updated')\n db.session.rollback()\n print(sys.exc_info())\n finally:\n db.session.close()\n return redirect(url_for('show_artist', artist_id=artist_id)) \n\n# Venue Edit\n#----------------------------------------------------------------------------#\n\n@app.route('/venues//edit', methods=['GET'])\ndef edit_venue(venue_id):\n form = VenueForm(request.form)\n venue = Venue.query.filter_by(id=venue_id).first()\n \n form.name.process_data(venue.name)\n form.city.process_data(venue.city)\n form.phone.process_data(venue.phone)\n form.state.process_data(venue.state)\n form.genres.process_data(venue.genres)\n form.facebook_link.process_data(venue.facebook_link)\n form.image_link.process_data(venue.image_link)\n\n return render_template('forms/edit_venue.html', form=form, venue=venue)\n\n@app.route('/venues//edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n venue = Venue.query.filter_by(id=venue_id).first()\n try:\n venue.name = request.form['name']\n venue.city = request.form['city']\n venue.state = request.form['state']\n venue.phone = request.form['phone']\n venue.genres = request.form.getlist('genres')\n venue.facebook_link = request.form['facebook_link']\n venue.image_link = request.form['image_link']\n\n db.session.commit()\n flash('The venue ' + request.form['name'] + ' was successfully updated!')\n except:\n flash('An error occurred. Venue ' +\n request.form['name'] + ' could not be updated')\n db.session.rollback()\n print(sys.exc_info())\n finally:\n db.session.close()\n\n return redirect(url_for('show_venue', venue_id=venue_id))\n\n# Artist Create\n#----------------------------------------------------------------------------#\n\n@app.route('/artists/create', methods=['GET'])\ndef create_artist_form():\n form = ArtistForm()\n return render_template('forms/new_artist.html', form=form)\n\n@app.route('/artists/create', methods=['POST'])\ndef create_artist_submission():\n new_artist = Artist(\n name=request.form['name'],\n city=request.form['city'],\n state=request.form['state'],\n phone=request.form['phone'],\n genres=request.form.getlist('genres'),\n facebook_link=request.form['facebook_link'],\n image_link=request.form['image_link']\n )\n\n try:\n db.session.add(new_artist)\n db.session.commit()\n flash('The artist ' + request.form['name'] + ' was successfully listed!')\n\n except:\n flash('An error occurred. The artist ' + new_artist.name + ' could not be listed.', category='error')\n print('exc_info(): ', exc_info())\n db.session.rollback()\n\n finally:\n db.session.close()\n return redirect(url_for('artists'))\n \n\n# Shows\n#----------------------------------------------------------------------------#\n# Code ref. Ivan Canales\n\n@app.route('/shows')\ndef shows():\n data = []\n show_list = Show.query.all()\n\n for show in show_list:\n data.append({\n \"venue_id\": show.venue_id,\n \"venue_name\": Venue.query.filter_by(id=show.venue_id).first().name,\n \"artist_id\": show.artist_id, \n \"artist_name\": Artist.query.filter_by(id=show.artist_id).first().name,\n \"artist_image_link\": show.artist.image_link, \n 'start_time': show.start_time.strftime('%Y-%m-%d, %H:%M:%S')\n })\n\n return render_template('pages/shows.html', shows=data)\n\n# Shows Create\n#----------------------------------------------------------------------------#\n\n@app.route('/shows/create')\ndef create_shows():\n # renders form. do not touch.\n form = ShowForm()\n return render_template('forms/new_show.html', form=form)\n\n@app.route('/shows/create', methods=['POST'])\ndef create_show_submission():\n new_show = Show(\n artist_id=request.form['artist_id'],\n venue_id=request.form['venue_id'],\n start_time=request.form['start_time']\n )\n \n try:\n db.session.add(new_show)\n db.session.commit()\n flash('The Show at' + request.form['venue_name'] + ' was successfully listed!')\n\n except:\n flash('An error occurred. Artist ' + new_artist.name + ' could not be listed.', category='error')\n print('exc_info(): ', exc_info())\n db.session.rollback()\n\n finally:\n db.session.close()\n return redirect(url_for('shows'))\n\n#----------------------------------------------------------------------------#\n# Errors\n#----------------------------------------------------------------------------#\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\n@app.errorhandler(500)\ndef server_error(error):\n return render_template('errors/500.html'), 500\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","sub_path":"app copy.py","file_name":"app copy.py","file_ext":"py","file_size_in_byte":18897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"522308007","text":"#!/usr/bin/env python3.5\n\nimport glob, os, sys\nimport eos_starter_lib as esl\nfrom concurrent.futures import ThreadPoolExecutor\nimport random\nimport shutil\n\nEXE = \"/user/HS204/m09113/eos/eos_build14/examples/fit-model-multi-alpha-exp\"\n\nLOGNAME = \"fitting.log\"\n\nOUTPUTBASE = \"/vol/vssp/facer2vm/people/Philipp/KF-ITW-prerelease_alpha_experiments/\"\n\nmessage = \"\"\n\nKF_ITW_POSE_FILE = \"/user/HS204/m09113/facer2vm_project_area/data/KF-ITW-prerelease/KF-ITW_pose_DB.csv\"\n\nNUMBER_OF_FITTINGS_PER_EXPERIMENT = 10\n\npose_db=[]\n\nwith open(KF_ITW_POSE_FILE, \"r\") as dbf:\n\tdbf.readline() # header\n\tfor line in dbf:\n\t\tpose_db.append(line.split())\n\n\n\n\nid_folders = glob.glob(\"/user/HS204/m09113/facer2vm_project_area/data/KF-ITW-prerelease/*\")\n#id_folders = os.walk(\"/user/HS204/m09113/facer2vm_project_area/data/KF-ITW-prerelease/\").next()[1]\n\nwith ThreadPoolExecutor(max_workers=30) as executor:\n\tfor n in range(0,len(id_folders)):\n\t\tid_folder = id_folders[n]\n\t\n\t\t# make absolute\n\t\tid_folder = os.path.abspath(id_folder)\t\n\t\n\t\t# check if it's a folder\n\t\tif (not os.path.isdir(id_folder)):\n\t\t\tcontinue;\t\t\n\n\t\tperson_id = id_folder[-2:]\n\t\n\t\texpressions = next(os.walk(id_folder))[1]\n\t\n\t\tfor exp in expressions:\n\n\t\t\texpression = \"/\"+exp+\"/\"\n\t\t\tid_and_expr_folder = id_folder + expression\n\t\t\trandom.seed(exp+person_id)\n\n\n\t\t\tgroup_20_left =[]\n\t\t\tgroup_10_left =[]\n\t\t\tgroup_10_centre =[]\n\t\t\tgroup_10_right =[]\n\t\t\tgroup_20_right =[]\n\n\n\n\t\t\tfor pose_entry in pose_db:\n\t\t\t\tif pose_entry[0]==person_id and pose_entry[1]==exp: #same person and expression\n\t\t\t\t\tyaw = float(pose_entry[3])\n\t\t\t\t\tif yaw < -20:\n\t\t\t\t\t\tgroup_20_left.append(id_and_expr_folder+pose_entry[2]+\".pts\")\n\t\t\t\t\telif yaw < -10 and yaw >-20:\n\t\t\t\t\t\tgroup_10_left.append(id_and_expr_folder+pose_entry[2]+\".pts\")\n\t\t\t\t\telif yaw > -10 and yaw <10:\n\t\t\t\t\t\tgroup_10_centre.append(id_and_expr_folder+pose_entry[2]+\".pts\")\n\t\t\t\t\telif yaw > 10 and yaw <20:\n\t\t\t\t\t\tgroup_10_right.append(id_and_expr_folder+pose_entry[2]+\".pts\")\n\t\t\t\t\telif yaw > 20:\n\t\t\t\t\t\tgroup_20_right.append(id_and_expr_folder+pose_entry[2]+\".pts\")\n\n\t\t\tprint (\"in\",id_and_expr_folder,\"found\",len(group_20_left),len(group_10_left),len(group_10_centre),len(group_10_right),len(group_20_right),)\n\n\t\t\tfor set_iter in range(NUMBER_OF_FITTINGS_PER_EXPERIMENT):\n\n\t\t\t\t# create outpurfolders\n\t\t\t\toutputfolder = OUTPUTBASE + os.path.basename(id_folder)\n\t\t\t\tif (not os.path.exists(outputfolder)):\n\t\t\t\t\tos.mkdir(outputfolder)\t\t\n\n\t\t\t\toutputfolder += \"/\"+exp+\"_only/\"\n\t\t\t\tif (not os.path.exists(outputfolder)):\n\t\t\t\t\tos.mkdir(outputfolder)\t\n\n\t\t\t\tfor experiment_idx in range(9,10):\n\n\t\t\t\t\t#### for each pose experiment\n\t\t\t\t\toutputfolder_experiment = outputfolder + \"pose_exp_\"+format(experiment_idx, '02d')+\"_\"+format(set_iter, '02d')+\"/\"\n\t\t\t\t\tif (not os.path.exists(outputfolder_experiment)):\n\t\t\t\t\t\tos.mkdir(outputfolder_experiment)\n\t\t\t\t\telse:\n\t\t\t\t\t\tshutil.rmtree(outputfolder_experiment)\n\t\t\t\t\t\tos.mkdir(outputfolder_experiment)\n\t\n\n\t\t\t\t\tif experiment_idx==0:\n\t\t\t\t\t\tlms = random.sample(group_20_left,2)+random.sample(group_10_left,2)+random.sample(group_10_centre,2)+random.sample(group_10_right,2)+random.sample(group_20_right,2)\n\t\t\t\t\telif experiment_idx==1:\n\t\t\t\t\t\tlms = random.sample(group_20_left,5)+random.sample(group_20_right,5)\n\t\t\t\t\telif experiment_idx==2:\n\t\t\t\t\t\tlms = random.sample(group_20_left,2)+random.sample(group_10_left,3)+random.sample(group_10_right,3)+random.sample(group_20_right,2)\n\t\t\t\t\telif experiment_idx==3:\n\t\t\t\t\t\tlms = random.sample(group_10_left,4)+random.sample(group_10_centre,2)+random.sample(group_10_right,4)\n\t\t\t\t\telif experiment_idx==4:\n\t\t\t\t\t\tlms = random.sample(group_10_left,2)+random.sample(group_10_centre,6)+random.sample(group_10_right,2)\n\t\t\t\t\telif experiment_idx==5:\n\t\t\t\t\t\tlms = random.sample(group_10_centre,10)\n\t\t\t\t\telif experiment_idx==6:\n\t\t\t\t\t\tlms = random.sample(group_20_left,5)+random.sample(group_10_left,4)+random.sample(group_10_centre,1)\n\t\t\t\t\telif experiment_idx==7:\n\t\t\t\t\t\tlms = random.sample(group_10_centre,1)+random.sample(group_10_right,4)+random.sample(group_20_right,5)\n\t\t\t\t\telif experiment_idx==8:\n\t\t\t\t\t\tlms = random.sample(group_20_left,3)+random.sample(group_10_centre,4)+random.sample(group_20_right,3)\n\t\t\t\t\telif experiment_idx==9:\n\t\t\t\t\t\tlms = random.sample(group_20_left,1)+random.sample(group_10_left,4)+random.sample(group_10_right,4)+random.sample(group_20_right,1)\n\t\t\t\t\timgs = esl.find_imgs_to_lms (lms, \"*.png\")\n\t\n\t\n\t\t\t\t\tmessage = \"id \"+os.path.basename(id_folder) + \" expression \" + exp + \" pose experiment \"+format(experiment_idx, '02d')+\", set \"+str(set_iter)\n\t\t\t\t\t# prepare multi image fit command\n\t\t\t\t\tcmd = esl.assemble_command(EXE, lms, imgs, outputfolder_experiment, regularisation=30.0, iterations=75)\n\t\t\t\t\n\t\t\t\t\t# print id and start cmd\n\t\t\t\t\texecutor.submit(esl.start_and_log,\"multiframe fitting on \"+message, cmd, None, log=outputfolder_experiment+LOGNAME)\n\n\n\n\n\t\n","sub_path":"run_random_multiframe_fit_KF-ITW_different_poses.py","file_name":"run_random_multiframe_fit_KF-ITW_different_poses.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"622749959","text":"from gensim.summarization.summarizer import summarize\nfrom lexrankr import LexRank\nfrom konlpy.tag import Twitter\nfrom collections import Counter\nfrom wordcloud import WordCloud\nfrom mode_pdfconvert import isEnglishOrKorean\nimport urllib.request\nimport json\n\ndef summarize_function(result):\n # 문장 요약 : https://anpigon.github.io/blog/dclick/@anpigon/-textrank-summariser-1540351206980/\n return summarize(result, word_count=50)\n\ndef lexlank_function(result):\n # 참조 : https://wikidocs.net/72820\n # LexRank : https://github.com/theeluwin/lexrankr\n try:\n lexrank = LexRank()\n lexrank.summarize(result)\n \n summarize_data = []\n print(\"요약 진행중!\")\n summaries = lexrank.probe(10)\n for i, summary in enumerate(summaries):\n summarize_data.append(summary)\n\n return summarize_data\n except:\n print(\"요약 내용이 부족합니다.\")\n return []\n\ndef keywords_function(result):\n # 키워드 추출 : https://dalulu.tistory.com/108\n try:\n nlpy = Twitter()\n nouns = nlpy.nouns(result)\n count = Counter(nouns)\n\n tag_count = []\n tags = []\n\n for n, c in count.most_common(200):\n dics = {'tag': n, 'count': c}\n if len(dics['tag']) >= 2 and len(tags) <= 49:\n tag_count.append(dics)\n tags.append((dics['tag'], dics['count']))\n \n return tags\n except:\n return []\n\ndef visualize_function(PDFpathName, summarize_tags):\n try:\n # 사이트 : https://liveyourit.tistory.com/58\n wc = WordCloud(font_path='C:\\\\Windows\\\\Fonts\\\\NanumGothicBold.ttf', \\\n background_color=\"white\", \\\n width=1000, \\\n height=1000, \\\n max_words=100, \\\n max_font_size=300)\n\n wc.generate_from_frequencies(dict(summarize_tags))\n wc.to_file('images/' + PDFpathName + '/wordcloud.png')\n except:\n pass","sub_path":"algorithm/mode_summarize.py","file_name":"mode_summarize.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"248098197","text":"from graia.saya import Saya, Channel\nfrom graia.application import GraiaMiraiApplication\nfrom graia.saya.builtins.broadcast.schema import ListenerSchema\nfrom graia.application.event.messages import GroupMessage, Group\nfrom graia.application.message.parser.literature import Literature\nfrom graia.application.message.elements.internal import MessageChain, Source, Plain\n\nfrom util.RestControl import rest_control\nfrom util.limit import member_limit_check\nfrom util.UserBlock import black_list_block\nfrom util.TextModeration import text_moderation\nfrom config import yaml_data, group_data, sendmsg\n\nfrom .beast import encode, decode\n\n\nsaya = Saya.current()\nchannel = Channel.current()\n\n\n@channel.use(ListenerSchema(listening_events=[GroupMessage],\n inline_dispatchers=[Literature(\"嗷\")],\n headless_decorators=[rest_control(), member_limit_check(15), black_list_block()]))\nasync def main(app: GraiaMiraiApplication, group: Group, message: MessageChain, source: Source):\n\n if yaml_data['Saya']['Beast']['Disabled']:\n return await sendmsg(app=app, group=group)\n elif 'Beast' in group_data[group.id]['DisabledFunc']:\n return await sendmsg(app=app, group=group)\n\n try:\n saying = message.asDisplay().split(\" \", 1)\n msg = encode(saying[1])\n if (len(msg)) < 500:\n await app.sendGroupMessage(group, MessageChain.create([Plain(msg)]), quote=source.id)\n else:\n await app.sendGroupMessage(group, MessageChain.create([Plain(f\"文字过长\")]), quote=source.id)\n except:\n await app.sendGroupMessage(group, MessageChain.create([Plain(\"明文错误``\")]), quote=source.id)\n\n\n@channel.use(ListenerSchema(listening_events=[GroupMessage],\n inline_dispatchers=[Literature(\"呜\")],\n headless_decorators=[rest_control(), member_limit_check(15), black_list_block()]))\nasync def main(app: GraiaMiraiApplication, group: Group, message: MessageChain, source: Source):\n\n if yaml_data['Saya']['Beast']['Disabled']:\n return await sendmsg(app=app, group=group)\n elif 'Beast' in group_data[group.id]['DisabledFunc']:\n return await sendmsg(app=app, group=group)\n\n try:\n saying = message.asDisplay().split(\" \", 1)\n msg = decode(saying[1])\n res = await text_moderation(msg)\n if res['Suggestion'] == \"Pass\":\n await app.sendGroupMessage(group, MessageChain.create([Plain(msg)]), quote=source.id)\n except:\n await app.sendGroupMessage(group, MessageChain.create([Plain(\"密文错误``\")]), quote=source.id)\n","sub_path":"saya/Beast/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"614759802","text":"import threading\nimport timeit\nfrom collections import deque\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom six.moves import cStringIO as io\n\nfrom finex.models import Order, Account\nfrom finex.models import Trade\nfrom finex.orderbook.exceptions import OrderBookException\nfrom finex.orderbook.ordertree import OrderTree\n\n\ndef log_order_book(func):\n def f(self, *args, **kwargs):\n start_time = timeit.default_timer()\n val = func(self, *args, **kwargs)\n elapsed = timeit.default_timer() - start_time\n\n if self.verbose:\n print(self)\n print(\"--- Elapsed({}) ---\\n\".format(elapsed))\n\n return val\n\n return f\n\n\ndef lock_order_book(func):\n def f(self, *args, **kwargs):\n try:\n self.lock.acquire() # pretty shit\n\n return func(self, *args, **kwargs)\n finally:\n self.session = None\n self.lock.release()\n\n return f\n\n\ndef _f_exc_side(func):\n return OrderBookException(\"{} order needs to be either of ['bid', 'ask']\".format(func))\n\n\ndef _f_exc_type(func):\n return OrderBookException(\"{} order_type is neither 'market' or 'limit'\".format(func))\n\n\ndef _f_exc_quant(func):\n return OrderBookException(\"{} order quantity <= 0\".format(func))\n\n\nclass OrderBook(object):\n class OrderType(Enum):\n LIMIT = 1\n MARKET = 2\n\n def __init__(self, order_book_pair=\"BTC/EUR\", session=None):\n self.order_book_pair = order_book_pair\n self.session = None\n self.ticker = deque(maxlen=None)\n self.bids = OrderTree()\n self.asks = OrderTree()\n self.last_tick = None\n self.tick_count = 0\n self.lock = threading.Lock()\n self.verbose = False\n\n\n @log_order_book\n def load(self, orders):\n flag = self.verbose\n self.verbose = False\n for order in orders:\n self.submit(order)\n self.tick_count = 0\n self.last_tick = None\n self.verbose = True\n\n @log_order_book\n @lock_order_book\n def submit(self, submitted_order, session=None):\n\n self.session = session\n self.last_tick = submitted_order\n order_type = submitted_order['type']\n order_in_book = None\n submitted_order['tick'] = self.tick\n\n if submitted_order['quantity'] <= 0:\n raise _f_exc_quant(\"submit()\")\n if order_type == 'market':\n trades = self.process_market_order(submitted_order)\n elif order_type == 'limit':\n submitted_order['price'] = Decimal(submitted_order['price'])\n trades, order_in_book = self.process_limit_order(submitted_order)\n else:\n raise _f_exc_type(\"submit()\")\n\n return trades, order_in_book\n\n @log_order_book\n @lock_order_book\n def delete(self, order_update, session):\n\n def remove_internal(collection):\n if collection.order_exists(order_id):\n collection.remove_order_by_id(order_id)\n\n self.session = session\n order_id = order_update['order_id']\n side = order_update['side']\n\n if side == 'bid':\n remove_internal(self.bids)\n elif side == 'ask':\n remove_internal(self.asks)\n else:\n raise _f_exc_side(\"delete()\")\n\n @log_order_book\n @lock_order_book\n def update(self, order_update, session):\n\n def modify_internal(collection):\n if collection.order_exists(order_id):\n collection.update_order(order_update)\n\n self.session = session\n self.last_tick = order_update\n order_id = order_update['order_id']\n side = order_update['side']\n order_update['tick'] = self.tick\n\n if side == 'bid':\n modify_internal(self.bids)\n elif side == 'ask':\n modify_internal(self.asks)\n else:\n raise _f_exc_side(\"update()\")\n\n @property\n def tick(self):\n self.tick_count += 1\n return self.tick_count\n\n def process_market_order(self, submitted_order):\n trades = []\n quantity_to_trade = submitted_order['quantity']\n side = submitted_order['side']\n if side == 'bid':\n while quantity_to_trade > 0 and self.asks:\n best_price_asks = self.asks.min_price_list()\n quantity_to_trade, new_trades = self.process_order_list(best_price_asks, quantity_to_trade,\n submitted_order)\n trades += new_trades\n elif side == 'ask':\n while quantity_to_trade > 0 and self.bids:\n best_price_bids = self.bids.max_price_list()\n quantity_to_trade, new_trades = self.process_order_list(best_price_bids, quantity_to_trade,\n submitted_order)\n trades += new_trades\n else:\n raise _f_exc_side(\"process_market_order()\")\n return trades\n\n def process_limit_order(self, submitted_order):\n order_in_book = None\n trades = []\n quantity_to_trade = submitted_order['quantity']\n side = submitted_order['side']\n price = submitted_order['price']\n\n if side == 'bid':\n while self.asks and price >= self.asks.min_price() and quantity_to_trade > 0:\n best_price_asks = self.asks.min_price_list()\n quantity_to_trade, new_trades = self.process_order_list(best_price_asks, quantity_to_trade,\n submitted_order)\n trades += new_trades\n # volume remains, insert\n if quantity_to_trade > 0:\n submitted_order['quantity'] = quantity_to_trade\n self.bids.insert_order(submitted_order)\n order_in_book = submitted_order\n elif side == 'ask':\n while self.bids and price <= self.bids.max_price() and quantity_to_trade > 0:\n best_price_bids = self.bids.max_price_list()\n quantity_to_trade, new_trades = self.process_order_list(best_price_bids, quantity_to_trade,\n submitted_order)\n trades += new_trades\n # volume remains, insert\n if quantity_to_trade > 0:\n submitted_order['quantity'] = quantity_to_trade\n self.asks.insert_order(submitted_order)\n order_in_book = submitted_order\n else:\n raise _f_exc_side(\"process_limit_order()\")\n return trades, order_in_book\n\n def process_order_list(self, open_orders, quantity_still_to_trade, submitted_order):\n \"\"\"\n Takes a stack of orders at one price and an incoming order and matches\n appropriate trades given the order's quantity.\n \"\"\"\n\n counter_side = \"bid\" if submitted_order[\"side\"] == \"ask\" else \"ask\"\n counter_collection = self.bids if counter_side == \"bid\" else self.asks\n\n def price():\n return max((submitted_order[\"price\"] if price in submitted_order else -1, head.price))\n\n trades = []\n quantity_to_trade = quantity_still_to_trade\n while len(open_orders) > 0 and quantity_to_trade > 0:\n head = open_orders.head()\n traded_price = price()\n counter_party = head.order_id\n new_book_quantity = None\n\n if quantity_to_trade < head.quantity:\n traded_quantity = quantity_to_trade\n new_book_quantity = head.quantity - quantity_to_trade\n head.update_quantity(new_book_quantity, head.tick)\n quantity_to_trade = 0\n submitted_order[\"closed\"] = True\n head[\"closed\"] = False\n self.modify_orders_and_balances(traded_quantity, traded_price, submitted_order, head)\n elif quantity_to_trade == head.quantity:\n traded_quantity = quantity_to_trade\n counter_collection.remove_order_by_id(head.order_id)\n quantity_to_trade = 0\n submitted_order[\"closed\"] = True\n head[\"closed\"] = True\n self.modify_orders_and_balances(traded_quantity, traded_price, submitted_order, head)\n else: # quantity to trade is larger than the head order\n traded_quantity = head.quantity\n counter_collection.remove_order_by_id(head.order_id)\n quantity_to_trade -= traded_quantity\n submitted_order[\"closed\"] = False\n head[\"closed\"] = True\n self.modify_orders_and_balances(traded_quantity, traded_price, submitted_order, head)\n\n transaction_record = {\n 'tick': self.tick_count,\n 'price': traded_price,\n 'quantity': traded_quantity,\n 'time': self.tick_count,\n 'counter_party_order': [counter_party, counter_side, head.order_id,\n new_book_quantity],\n 'submitted_order': [submitted_order['order_id'], submitted_order['side'], None, None]\n }\n\n self.ticker.append(transaction_record)\n trades.append(transaction_record)\n self.persist_trade(transaction_record)\n\n return quantity_to_trade, trades\n\n def modify_orders_and_balances(self, traded_quantity, traded_price, submitted_order, head):\n if self.session is None:\n return\n bid = submitted_order if submitted_order[\"side\"] == \"bid\" else head\n ask = head if submitted_order[\"side\"] == \"bid\" else submitted_order\n\n for order in [bid, ask]:\n db_order = self.session.query(Order).filter_by(id=order[\"order_id\"]).first()\n db_order.balance -= traded_quantity\n db_order.order_state = Order.State.CLOSED if order[\"closed\"] else Order.State.OPEN\n\n if order == bid:\n account_bid = self.session.query(Account).filter_by(user_id=db_order.user_id,\n account_type=Account.AccountType.BTC).first()\n account_bid.balance += traded_quantity\n\n if order == ask:\n account_ask = self.session.query(Account).filter_by(user_id=db_order.user_id,\n account_type=Account.AccountType.EUR).first()\n account_ask.balance += traded_quantity * traded_price\n\n def persist_trade(self, transaction):\n if self.session is None:\n return\n trade = Trade(order_id=transaction[\"submitted_order\"][0],\n counter_party_order_id=transaction[\"counter_party_order\"][0],\n price=transaction[\"price\"],\n volume=transaction[\"quantity\"], tick=transaction[\"tick\"]\n )\n self.session.add(trade)\n\n def get_volume_at_price(self, side, price):\n price = Decimal(price)\n\n def get_volume(collection):\n volume = 0\n if collection.price_exists(price):\n volume = collection.get_price_list(price).volume\n return volume\n\n if side in (\"bid\", \"ask\"):\n return get_volume(self.bids) if side == 'bid' else get_volume(self.asks)\n else:\n raise _f_exc_side(\"get_volume_at_price()\")\n\n @property\n def best_bid(self):\n return self.bids.max_price()\n\n @property\n def worst_bid(self):\n return self.bids.min_price()\n\n @property\n def best_ask(self):\n return self.asks.min_price()\n\n @property\n def worst_ask(self):\n return self.asks.max_price()\n\n @property\n def depth_bid(self):\n return self.bids.depth\n\n @property\n def depth_ask(self):\n return self.asks.depth\n\n @property\n def bid_items(self):\n for key, price_list in self.bids.price_tree.items(reverse=True):\n for item in price_list:\n yield item.json()\n\n @property\n def ask_items(self):\n for key, price_list in self.asks.price_tree.items():\n for item in price_list:\n yield item.json()\n\n def dump(self, filename, filemode, wipe=False):\n with open(filename, filemode) as file:\n for item in self.ticker:\n file.write('Time: %s, Price: %s, Quantity: %s\\n' % (item['time'], item['price'], item['quantity']))\n if wipe:\n self.ticker = deque(maxlen=None)\n\n def __str__(self):\n buffer = io()\n\n def bids():\n buffer.write(\"--- Bids ---\\n\")\n if self.bids is not None and len(self.bids) > 0:\n for key, value in self.bids.price_tree.items(reverse=True):\n buffer.write('%s' % value)\n\n def asks():\n buffer.write(\"\\n--- Asks ---\\n\")\n if self.asks is not None and len(self.asks) > 0:\n for key, value in list(self.asks.price_tree.items()):\n buffer.write('%s' % value)\n\n def trades():\n buffer.write(\"\\n--- Trades(tick={}) ---\\n\".format(self.tick_count))\n if self.ticker is not None and len(self.ticker) > 0:\n num = 0\n for entry in self.ticker:\n if num < 10: # get last 5 entries\n buffer.write(str(entry['quantity']) + \" @ \" + str(entry['price']) + \" (\" + str(\n entry['tick']) + \") \" + str(entry['counter_party_order'][0]) + \"/\" + str(\n entry['submitted_order'][0]) + \"\\n\")\n num += 1\n else:\n break\n\n bids()\n asks()\n trades()\n buffer.write(\"\\n\")\n return buffer.getvalue()\n","sub_path":"finex/orderbook/orderbook.py","file_name":"orderbook.py","file_ext":"py","file_size_in_byte":13899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"475526613","text":"from flask import Flask, render_template, redirect, request, Blueprint, make_response\nimport base64\nimport hashlib\nlevel4Bp = Blueprint('level4', __name__, url_prefix=\"/level4\")\n# level4CSP = \"script-src-elem 'sha256-l5N3PQZUTfBrAgs6Cd/8DUT5K9Xqti8830NgkUx6TNQ=' 'sha256-1by291HWq0c1xmoYrazFZul7uPqRlwJbhyMQTqWwx2o='\"\n# level4CSP = \"script-src-elem 'sha256-l5N3PQZUTfBrAgs6Cd/8DUT5K9Xqti8830NgkUx6TNQ=' 'sha256-mGkvh1o1NbqhmaNycGqxPAiOdO8oggOM0XPiaSuo7LU='\"\n# level4CSP = \"script-src-elem 'sha256-/90/sYuOXlGCyF2ApZiOOLhVW/5BB6I/37UI9/s0WDM='\"\n\n\n@level4Bp.route(\"/\", methods=['GET', 'POST'])\ndef level4():\n level4CSP = \"script-src 'self'\"\n if not request.args.get('timer'):\n r = make_response(render_template(\"level4.html\"))\n else:\n timer = request.args.get('timer', 1)\n try:\n int(timer)\n except ValueError:\n timer = 1\n script = \"document.getElementById('img').onload = function() {startTimer('\" + timer + \"');}\"\n level4CSP += \" \\'sha256-\" + \\\n base64.b64encode(hashlib.sha256(script.encode(\n 'utf-8')).digest()).decode(\"utf-8\") + \"\\'\"\n r = make_response(render_template(\"level4_timer.html\", timer=timer))\n r.headers['Content-Security-policy'] = level4CSP\n return r\n\n\n'''class MainPage(webapp.RequestHandler):\n \n  def render_template(self, filename, context={}):\n    path = os.path.join(os.path.dirname(__file__), filename)\n    self.response.out.write(template.render(path, context))\n \n  def get(self):\n    # Disable the reflected XSS filter for demonstration purposes\n    self.response.headers.add_header(\"X-XSS-Protection\", \"0\")\n \n    if not self.request.get('timer'):\n      # Show main timer page\n      self.render_template('index.html')\n    else:\n      # Show the results page\n      timer= self.request.get('timer', 0)\n      self.render_template('timer.html', { 'timer' : timer })\n     \n    return\n \napplication = webapp.WSGIApplication([ ('.*', MainPage), ], debug=False)\n'''\n","sub_path":"P2/P2_project/part3 csp2/views/level4.py","file_name":"level4.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"653353737","text":"# You have been given 3 integers - l, r and k. Find how many numbers between l and r (both inclusive) \n# are divisible by k. You do not need to print these numbers, you just have to find their count.\n\n# Input Format\n# The first and only line of input contains 3 space separated integers l, r and k.\n\n# Output Format\n# Print the required answer on a single line.\n\n# Constraints\n\n\n# SAMPLE INPUT \n# 1 10 1\n# SAMPLE OUTPUT \n# 10\n\nm, n, k = map(int, input().split(' '))\ncnt = 0\nfor i in range(m, n+1):\n if(i % k == 0):\n cnt = cnt+1\nprint(cnt)\n","sub_path":"Very easy/Count Divisors.py","file_name":"Count Divisors.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"466777355","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport mysql.connector\r\n\r\nglobal setting\r\nsetting = 0\r\n\r\ndef doctor():\r\n global count\r\n global result\r\n myconn = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Pratham\", database=\"hospital\")\r\n\r\n cur = myconn.cursor()\r\n\r\n try:\r\n cur.execute(\"select*from pharmacy\")\r\n result = cur.fetchall()\r\n count = cur.rowcount\r\n\r\n\r\n except:\r\n myconn.rollback()\r\n myconn.close()\r\n\r\n home = Toplevel()\r\n home.geometry(\"1550x900\")\r\n home.config(bg='snow2')\r\n home.title(\"Pharmacy\")\r\n\r\n def go_back():\r\n home.destroy()\r\n\r\n head_label = Label(home, text=\"Pharmacy\", background=\"turquoise1\", foreground=\"white\",\r\n font=('Times', 50, 'bold'), width=35).place(x=0, y=30)\r\n\r\n back = Button(home, text='Back', fg='black', font=('arial', 16, 'bold'), bg='turquoise1',\r\n relief='raised', bd=10, command=go_back).place(x=1260, y=625)\r\n\r\n id_label = Label(home,text=\"Medicine Id\",bg=\"snow2\",fg = \"black\",font=('Times', 16, 'bold'),relief = \"solid\",padx=5,width=10).place(x=158,y=130)\r\n\r\n id_Name = Label(home, text=\"Medicine Name\", bg=\"snow2\", fg=\"black\", font=('Times', 16, 'bold'), relief=\"solid\", padx=5,\r\n width=27).place(x=290, y=130)\r\n id_quali = Label(home, text=\"In Stock\", bg=\"snow2\", fg=\"black\", font=('Times', 16, 'bold'), relief=\"solid\", padx=5,\r\n width=10).place(x= 626, y=130)\r\n id_specality = Label(home, text=\"Expiry date\", bg=\"snow2\", fg=\"black\", font=('Times', 16, 'bold'), relief=\"solid\", padx=5,\r\n width=15).place(x=758, y=130)\r\n id_exp = Label(home, text=\"Recent Renewal date\", bg=\"snow2\", fg=\"black\", font=('Times', 16, 'bold'), relief=\"solid\", padx=5,\r\n width=18).place(x=950, y=130)\r\n global z\r\n z = 159\r\n global flag\r\n flag =0\r\n for i in range(0,count):\r\n\r\n pharma_id = result[i][0]\r\n pharma_name = result[i][1]\r\n pharma_quantity = result[i][2]\r\n pharama_exp = result[i][3]\r\n pharma_recent = result[i][4]\r\n\r\n\r\n id_label = Label(home, text= pharma_id, bg=\"snow2\", fg=\"black\", font=('Times', 14), relief=\"solid\",\r\n padx=5, width=12).place(x=158,y=z)\r\n\r\n id_Name = Label(home, text= pharma_name, bg=\"snow2\", fg=\"black\", font=('Times', 14), relief=\"solid\", padx=5,\r\n width=33).place(x=290, y=z)\r\n id_quali = Label(home, text= pharma_quantity, bg=\"snow2\", fg=\"black\", font=('Times', 14), relief=\"solid\",\r\n padx=5,width=12).place(x=626, y=z)\r\n id_specality = Label(home, text=pharama_exp, bg=\"snow2\", fg=\"black\", font=('Times', 14), relief=\"solid\",\r\n padx=5,\r\n width=18).place(x=758, y=z)\r\n id_exp = Label(home, text=pharma_recent, bg=\"snow2\", fg=\"black\", font=('Times', 14), relief=\"solid\",\r\n padx=5,\r\n width=21).place(x=950, y=z)\r\n z+=24\r\n\r\n def add():\r\n global z\r\n p_name = StringVar()\r\n p_quantity = IntVar()\r\n p_quantity.set(\"\")\r\n p_exp = StringVar()\r\n p_recent = StringVar()\r\n\r\n def done():\r\n global z\r\n global count\r\n global setting\r\n\r\n pharma_name = p_name.get()\r\n pharma_quantity = p_quantity.get()\r\n pharama_exp = p_exp.get()\r\n pharma_recent = p_recent.get()\r\n\r\n if (pharma_name != \"\" and pharma_quantity != \"\" and pharama_exp != \"\" and pharma_recent != \"\"):\r\n\r\n myconn = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Pratham\", database=\"hospital\")\r\n\r\n cur = myconn.cursor()\r\n\r\n\r\n\r\n try:\r\n\r\n pharma_id = count + 1\r\n sql = \"insert into pharmacy(pharmacy_id, medicine_name,quantity,expiry_date,r_date) values(%s,%s,%s,%s,%s)\"\r\n\r\n val = (pharma_id, pharma_name, pharma_quantity, pharama_exp, pharma_recent)\r\n cur.execute(sql, val)\r\n\r\n myconn.commit()\r\n\r\n except:\r\n print(\"error\")\r\n myconn.rollback()\r\n myconn.close()\r\n messagebox.showinfo(\"Hospital Management System\", \"Details Successfully inserted\")\r\n setting =1\r\n home.destroy()\r\n\r\n else:\r\n messagebox.showinfo(\"Hospital Management System\", \"Fill all the credentials\")\r\n\r\n\r\n\r\n z+=90\r\n add_label = Label(home, text=\"Add Contents\", bg=\"turquoise1\", fg=\"white\", font=('Times', 16,'bold'), padx=5,\r\n width=18, relief='raised').place(x=30, y=z)\r\n\r\n z+=38\r\n id_Name = Label(home, text=\"Medicine Name\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14,'bold'), padx=5,\r\n width=15).place(x=70, y=z)\r\n entry_Name = Entry(home,textvariable = p_name,width= 30,font=('Times', 14,'bold'),bg = \"peachpuff\").place(x=270,y=z)\r\n\r\n submit = Button(home, text='Submit', fg=\"black\", font=('arial', 16, 'bold'), height=3, width=20, padx=5,\r\n bg='turquoise1',\r\n relief='raised', bd=10, command=done).place(x=700, y=z)\r\n\r\n z+=35\r\n\r\n id_qualification = Label(home, text=\"New stock\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'),\r\n padx=5,\r\n width=15).place(x=70, y=z)\r\n entry_qualify = Entry(home, textvariable=p_quantity, width=30, font=('Times', 14, 'bold'),bg = \"peachpuff\").place(x=270, y=z)\r\n\r\n z+=35\r\n\r\n id_specality = Label(home, text=\"Expiry date\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'),\r\n padx=5, width=15).place(x=70, y=z)\r\n entry_specality = Entry(home, textvariable=p_exp, width=30, font=('Times', 14, 'bold'),bg = \"peachpuff\").place(x=270, y=z)\r\n\r\n z+=35\r\n\r\n id_specality = Label(home, text=\"Recent renewal date\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'),\r\n padx=5, width=15).place(x=70, y=z)\r\n entry_specality = Entry(home, textvariable=p_recent, width=30, font=('Times', 14, 'bold'), bg=\"peachpuff\").place(\r\n x=270, y=z)\r\n\r\n z += 35\r\n\r\n def update():\r\n\r\n global count\r\n global result\r\n global z\r\n id_no = IntVar()\r\n id_no.set(\"\")\r\n\r\n def check():\r\n\r\n global z\r\n\r\n ids = id_no.get()\r\n pharma_name = StringVar()\r\n pharama_exp = StringVar()\r\n pharma_recent = StringVar()\r\n pharma_quantity = StringVar()\r\n\r\n flag = 0\r\n for i in range(0, count):\r\n if (ids == result[i][0]):\r\n flag = 1\r\n\r\n if (flag == 1):\r\n def get_new():\r\n p_name = pharma_name.get()\r\n p_exp = pharama_exp.get()\r\n p_recent = pharma_recent.get()\r\n p_quantity = pharma_quantity.get()\r\n\r\n if (p_name == \"\" and p_quantity == \"\" and p_exp == \"\" and p_recent == \"\" ):\r\n messagebox.showinfo(\"Hospital Management System\", \"Enter Contents\")\r\n\r\n else:\r\n myconn = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Pratham\",\r\n database=\"hospital\")\r\n\r\n cur = myconn.cursor()\r\n\r\n try:\r\n cur.execute(\"select*from pharmacy\")\r\n result_w = cur.fetchall()\r\n myconn.commit()\r\n\r\n except:\r\n myconn.rollback()\r\n\r\n if (p_name != \"\"):\r\n try:\r\n\r\n sql = \"update pharmacy set medicine_name = %s where pharmacy_id = %s\"\r\n val = [p_name,ids]\r\n\r\n cur.execute(sql, val)\r\n\r\n myconn.commit()\r\n except:\r\n myconn.rollback()\r\n\r\n if (p_exp != \"\"):\r\n try:\r\n\r\n sql = \"update pharmacy set expiry = %s where pharmacy_id = %s\"\r\n val = [p_recent, ids]\r\n\r\n cur.execute(sql, val)\r\n\r\n myconn.commit()\r\n except:\r\n myconn.rollback()\r\n messagebox.showinfo(\"Hospital Management System\", \"Successfully Inserted Details\")\r\n\r\n if (p_quantity != \"\"):\r\n try:\r\n\r\n sql = \"update pharmacy set quantity = %s where pharmacy_id = %s\"\r\n val = [p_quantity, ids]\r\n\r\n cur.execute(sql, val)\r\n\r\n myconn.commit()\r\n except:\r\n myconn.rollback()\r\n messagebox.showinfo(\"Hospital Management System\", \"Successfully Inserted Details\")\r\n\r\n if (p_recent != \"\"):\r\n try:\r\n\r\n sql = \"update pharmacy set r_date = %s where pharmacy_id = %s\"\r\n val = [p_recent, ids]\r\n\r\n cur.execute(sql, val)\r\n\r\n myconn.commit()\r\n except:\r\n myconn.rollback()\r\n messagebox.showinfo(\"Hospital Management System\", \"Successfully Inserted Details\")\r\n\r\n setting = 1\r\n home.destroy()\r\n messagebox.showinfo(\"Hospital Management System\", \"Successfully Inserted Details\")\r\n\r\n myconn.close()\r\n\r\n id_Name = Label(home, text=\"Medicine Name\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'), padx=5,\r\n width=15).place(x=700, y=z)\r\n entry_Name = Entry(home, textvariable=pharma_name, width=30, font=('Times', 14, 'bold'), bg=\"peachpuff\").place(\r\n x=970,\r\n y=z)\r\n\r\n z += 35\r\n\r\n id_qualification = Label(home, text=\"Quantity\", bg=\"turquoise1\", fg=\"white\",\r\n font=('Times', 14, 'bold'),\r\n padx=5,\r\n width=15).place(x=700, y=z)\r\n entry_qualify = Entry(home, textvariable=pharma_quantity, width=30, font=('Times', 14, 'bold'),\r\n bg=\"peachpuff\").place(x=970,\r\n y=z)\r\n\r\n z += 35\r\n\r\n id_specality = Label(home, text=\"Expiry Date\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'),\r\n padx=5, width=15).place(x=700, y=z)\r\n entry_specality = Entry(home, textvariable=pharama_exp, width=30, font=('Times', 14, 'bold'),\r\n bg=\"peachpuff\").place(x=970, y=z)\r\n\r\n z += 35\r\n\r\n id_exp = Label(home, text=\"Recent Renewal Date\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'),\r\n padx=5, width=15).place(x=700, y=z)\r\n entry_exp = Entry(home, textvariable=pharma_recent, width=30, font=('Times', 14, 'bold'),\r\n bg=\"peachpuff\").place(\r\n x=970, y=z)\r\n\r\n upd_btn = Button(home, text='SUBMIT', fg=\"black\", font=('arial', 16, 'bold'), width=20, padx=5,\r\n bg='turquoise1',\r\n relief='raised', bd=10, command=get_new).place(x=130, y=z)\r\n\r\n z += 35\r\n\r\n else:\r\n messagebox.showinfo(\"Hospital Management System\", \"Invalid Credentials\")\r\n\r\n z+=90\r\n add_label = Label(home, text=\"Updating Contents\", bg=\"turquoise1\", fg=\"white\", font=('Times', 16,'bold'), padx=5,\r\n width=18, relief='raised').place(x=30, y=z)\r\n\r\n z+=38\r\n id = Label(home, text=\"ID No.\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14,'bold'), padx=5,\r\n width=15).place(x=70, y=z)\r\n entry = Entry(home,textvariable =id_no,width= 30,font=('Times', 14,'bold'),bg=\"peachpuff\").place(x=270,y=z)\r\n\r\n\r\n\r\n z+=35\r\n\r\n enter = Button(home, text='Enter', fg=\"black\", font=('arial', 14, 'bold'), width=10, padx=5, bg='turquoise1',\r\n relief='raised', bd=10, command=check).place(x=200, y=z)\r\n\r\n\r\n def delete():\r\n global z\r\n p_id = IntVar()\r\n p_id.set(\"\")\r\n\r\n def gayab():\r\n global count\r\n global result\r\n global setting\r\n\r\n no = p_id.get()\r\n no1 = int(no)\r\n\r\n\r\n flag =0\r\n for i in range(0,count):\r\n if(no1 == result[i][0]):\r\n flag = 1\r\n\r\n if(flag):\r\n myconn = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Pratham\", database=\"hospital\")\r\n\r\n\r\n try:\r\n cur = myconn.cursor()\r\n sql = \"DELETE FROM pharmacy WHERE pharmacy_id = %s\"\r\n\r\n val = [no1]\r\n\r\n cur.execute(sql,val)\r\n myconn.commit()\r\n\r\n except:\r\n print(\"Error\")\r\n myconn.rollback()\r\n\r\n myconn.close()\r\n\r\n messagebox.showinfo(\"Hospital Management System\",\"Deleted Successfully\")\r\n setting = 1\r\n home.destroy()\r\n else:\r\n messagebox.showinfo(\"Hospital Management System\", \"Wrong Credentials\")\r\n p_id.set(\"\")\r\n\r\n\r\n z += 90\r\n add_label = Label(home, text=\"Deleting Contents\", bg=\"turquoise1\", fg=\"white\", font=('Times', 16, 'bold'),\r\n padx=5,\r\n width=18, relief='raised').place(x=30, y=z)\r\n\r\n z += 38\r\n id = Label(home, text=\"ID No.\", bg=\"turquoise1\", fg=\"white\", font=('Times', 14, 'bold'), padx=5,\r\n width=15).place(x=70, y=z)\r\n entry = Entry(home, textvariable=p_id, width=30, font=('Times', 14, 'bold'), bg=\"peachpuff\").place(x=270, y=z)\r\n\r\n z+=35\r\n\r\n del_button = Button(home, text='Delete', fg=\"black\", font=('arial', 14, 'bold'), width=10, padx=5, bg='turquoise1',\r\n relief='raised', bd=10,command = gayab).place(x=200, y=z)\r\n\r\n\r\n z+=30\r\n\r\n add_btn = Button(home, text='ADD To Stock', fg=\"black\", font=('arial', 16, 'bold'),width = 20, padx= 5, bg='turquoise1',\r\n relief='raised', bd=10, command = add).place(x=150, y=z)\r\n del_btn = Button(home, text='Delete Medicine', fg=\"black\", font=('arial', 16, 'bold'), width=20, padx=5, bg='turquoise1',\r\n relief='raised', bd=10,command = delete).place(x=510, y=z)\r\n upd_btn = Button(home, text='Update Details', fg=\"black\", font=('arial', 16, 'bold'), width=20, padx=5, bg='turquoise1',\r\n relief='raised', bd=10, command = update).place(x=870, y=z)\r\n home.mainloop()\r\n\r\nif(setting == 1):\r\n doctor()","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":15824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"534022384","text":"from django.urls import path\n\nfrom accounts.views import RegisterView, LoginViewCustom, AccountDetailsView, AccountEditView, AccountDeleteView\nfrom django.contrib.auth import views\n\nurlpatterns = (\n path('login/', LoginViewCustom.as_view(), name='login'),\n path('logout/', views.LogoutView.as_view(), name='logout'),\n path('register/', RegisterView.as_view(), name='register user'),\n path('details/', AccountDetailsView.as_view(), name='account details'),\n path('edit/', AccountEditView.as_view(), name='account edit'),\n path('delete/', AccountDeleteView.as_view(), name='account delete'),\n\n)\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"272671990","text":"\n# standard\nimport logging\nfrom pathlib import Path\nfrom datetime import datetime\n\n# packages\n\n# internal\nfrom utility import const, env\n\n# find current working path\nCUR_PATH = Path(__file__).parent\n\n# locate config file\nCONFIG_FOLDER = '.config'\nCONFIG_PATH = CUR_PATH/CONFIG_FOLDER\nCONFIG_FILE_PATH = CONFIG_PATH/'config.json'\n\n# if user wants to log to file\nif env.LOG_TO_FILE:\n # locate log file\n LOG_FILE = 'api.log'\n LOG_FILE_PATH = CONFIG_PATH/'logs'\n logging.basicConfig(\n filename=LOG_FILE_PATH/LOG_FILE,\n level=env.LOGGING_LEVEL,\n format='%(asctime)s %(message)s'\n )\n\nelse:\n # otherwise, log to terminal\n logging.basicConfig(\n level=env.LOGGING_LEVEL,\n format='%(asctime)s %(message)s'\n )\n\n_LOGGER = logging.getLogger(__name__)\n\nif __name__ == '__main__':\n\n # init context\n _LOGGER.info('initializing context')\n from context.context import Context\n Context.initialize(CONFIG_FILE_PATH)\n\n # init endpoints\n _LOGGER.info('initializing endpoints')\n from endpoints import Endpoints\n Endpoints.initialize()\n \n # Endpoints.post_transaction(\n # accountID='88efgiTlszS1z2TqSlPj',\n # counterParty='suntrust',\n # transactionType='debit',\n # description='ATM Withdrawal',\n # amount='20'\n # )\n\n # Endpoints.post_transaction(\n # accountID='88efgiTlszS1z2TqSlPj',\n # counterParty='suntrust',\n # transactionType='credit',\n # description='ATM Deposit',\n # amount='100'\n # )\n\n # init connection\n # this init references the conn object\n # because the object stores data in tables\n\n # _LOGGER.info('initializing connection')\n # from connection import conn\n # conn._initialize()\n \n #Endpoints.delete_account('vQOPRQU4YFh80SsjVbyV')\n # Endpoints.delete_account('IYnand5gi92V7mJ9gvZS')\n #res = Endpoints.accounts_by_owner(owner='Anthony')\n\n res = Endpoints.list_accounts()\n\n #res = Endpoints.accounts_by_owner(owner='Steve')\n print('done')\n","sub_path":"scripts/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"23811777","text":"from __future__ import absolute_import\n\nimport argparse\nimport logging\nimport os\n\nimport apache_beam as beam\nfrom apache_beam.io import ReadFromText\nfrom apache_beam.io.avroio import WriteToAvro\n\nfrom dataflow_utils import dataflow_utils\nfrom dataflow_utils.dataflow_utils import get_schema, clean_csv_int, clean_csv_string, generate_args, normalize_address\n\n\nclass ConvertToDicts(beam.DoFn):\n def process(self, datum):\n\n acct_no, name, trade_name, desc_of_business, business_type, address_type, city, state, zip, data_created, \\\n business_start_date_in_pgh, address1, address2 = datum.split(',')\n\n address_full = clean_csv_string(address1) + ' ' + clean_csv_string(address2)\n\n return [{\n 'acct_no': clean_csv_string(acct_no),\n 'name': clean_csv_string(name),\n 'trade_name': clean_csv_string(trade_name),\n 'desc_of_business': clean_csv_string(desc_of_business),\n 'business_type': clean_csv_string(business_type),\n 'address_type': clean_csv_string(address_type),\n 'city': clean_csv_string(city),\n 'state': clean_csv_string(state),\n 'zip': clean_csv_int(zip),\n 'date_created': clean_csv_string(data_created),\n 'business_start_date_in_pgh': clean_csv_string(business_start_date_in_pgh),\n 'address_full': address_full\n }]\n\n\nclass AddNormalizedAddress(beam.DoFn):\n def process(self, datum):\n datum['normalized_address'] = normalize_address(datum['address_full'])\n return datum\n\n\ndef run(argv=None):\n\n known_args, pipeline_options, avro_schema = generate_args(\n job_name='registered-businesses-dataflow',\n bucket='{}_finance'.format(os.environ['GCS_PREFIX']),\n argv=argv,\n schema_name='registered_businesses',\n runner='DataflowRunner'\n )\n\n with beam.Pipeline(options=pipeline_options) as p:\n # Read the text file[pattern] into a PCollection.\n lines = p | ReadFromText(known_args.input, skip_header_lines=1)\n\n load = (\n lines\n | beam.ParDo(ConvertToDicts())\n | beam.ParDo(AddNormalizedAddress())\n | WriteToAvro(known_args.avro_output, schema=avro_schema, file_name_suffix='.avro', use_fastavro=True))\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()\n","sub_path":"dags/dependencies/dataflow_scripts/registered_businesses_dataflow.py","file_name":"registered_businesses_dataflow.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"351722807","text":"#!/usr/bin/python\n\n# https://www.tutorialspoint.com/How-do-we-do-a-file-upload-using-Python-CGI-Programming\n# https://stackoverflow.com/questions/40280267/file-upload-using-python-with-cgi\n\nfrom cgi import FieldStorage\nfrom os.path import basename\n# from os.path import basename\nfrom cgitb import enable\nfrom sys import stderr\n\nenable()\nform = FieldStorage()\nfileitem = form['filename']\n\nif fileitem.filename:\n # Mitigate directory traversal attack\n fn = basename(fileitem.filename)\n open('/home/darren/cgi/cgi-tmp/' + fn, 'wb').write(fileitem.file.read())\n # message = 'The file \"' + fn + '\" was uploaded successfully'\n message = \" '%s' -> '/home/darren/cgi/cgi-tmp/%s'\" % ( fn, fn )\nelse:\n message = 'No file was uploaded'\n\nprint(\"Content-Type: text/plain; charset=utf-8\")\nprint()\n\nprint()\nprint(message)\nprint()\n\nprint(file=stderr)\nprint(message,file=stderr)\nprint(file=stderr)\n\n# for line in stdin:\n# print(line)\n# quit()\n","sub_path":"cgi-bin/03_file.py","file_name":"03_file.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"480691750","text":"import json\nimport numpy as np\nimport torch.utils.data\n\nfrom random import shuffle\n\n# [(ppair_drug, ppair_cmpd), etc.]\ndef train_collate_fn(batch):\n ret_pos = []\n ret_neg = []\n for item in batch: # item is output of __getitem__\n ret_pos.extend(item[0])\n ret_neg.extend(item[1])\n pos_batch = ddi_collate_batch(ret_pos)\n neg_batch = ddi_collate_batch(ret_neg)\n return pos_batch, neg_batch\n\ndef test_collate_fn(batch):\n ret_all, truth = list(zip(*batch))\n return (ddi_collate_batch(map(lambda x: x[0], ret_all)), truth)\n\ndef ddi_collate_batch(batch):\n \"\"\"\n Black-box that does all the stuff she emailed about\n \"\"\"\n drug, cmpd = list(zip(*batch))\n\n ddi_idxs1, ddi_idxs2 = collate_drug_pairs(drug, cmpd)\n drug = (*collate_drugs(drug), *ddi_idxs1)\n cmpd = (*collate_drugs(cmpd), *ddi_idxs2)\n\n return (*drug, *cmpd)\n\n\ndef collate_drug_pairs(drugs1, drugs2):\n n_atom1 = [d['n_atom'] for d in drugs1]\n n_atom2 = [d['n_atom'] for d in drugs2]\n c_atom1 = [sum(n_atom1[:k]) for k in range(len(n_atom1))]\n c_atom2 = [sum(n_atom2[:k]) for k in range(len(n_atom2))]\n\n ddi_seg_i1, ddi_seg_i2, ddi_idx_j1, ddi_idx_j2 = zip(*[\n (i1 + c1, i2 + c2, i2, i1)\n for l1, l2, c1, c2 in zip(n_atom1, n_atom2, c_atom1, c_atom2)\n for i1 in range(l1) for i2 in range(l2)])\n\n ddi_seg_i1 = torch.LongTensor(ddi_seg_i1)\n ddi_idx_j1 = torch.LongTensor(ddi_idx_j1)\n\n ddi_seg_i2 = torch.LongTensor(ddi_seg_i2)\n ddi_idx_j2 = torch.LongTensor(ddi_idx_j2)\n\n return (ddi_seg_i1, ddi_idx_j1), (ddi_seg_i2, ddi_idx_j2)\n\n\ndef collate_drugs(drugs):\n c_atoms = [sum(d['n_atom'] for d in drugs[:k]) for k in range(len(drugs))]\n\n atom_feat = torch.FloatTensor(np.vstack([d['atom_feat'] for d in drugs]))\n atom_type = torch.LongTensor(np.hstack([d['atom_type'] for d in drugs]))\n bond_type = torch.LongTensor(np.hstack([d['bond_type'] for d in drugs]))\n bond_seg_i = torch.LongTensor(np.hstack([\n np.array(d['bond_seg_i']) + c for d, c in zip(drugs, c_atoms)]))\n bond_idx_j = torch.LongTensor(np.hstack([\n np.array(d['bond_idx_j']) + c for d, c in zip(drugs, c_atoms)]))\n batch_seg_m = torch.LongTensor(np.hstack([\n [k] * d['n_atom'] for k, d in enumerate(drugs)]))\n\n return batch_seg_m, atom_type, atom_feat, bond_type, bond_seg_i, bond_idx_j\n\nclass GenericTestDataset(torch.utils.data.Dataset):\n \"\"\"\n Only for predicting single properties from pairs\n\n data: pandas for the intended split\n \"\"\"\n def __init__(self, data, mol_desc_path):\n if len(data) == 0:\n raise ValueError(\"Empty dataset\")\n\n self.pairs = list(map(lambda x: tuple(x[1]), data.iterrows()))\n self.drug_struct = {}\n with open(mol_desc_path) as f:\n for l in f:\n idx, l = l.strip().split('\\t')\n self.drug_struct[idx] = json.loads(l)\n\n def __len__(self):\n return len(self.pairs)\n\n def __getitem__(self, idx):\n pair1, pair2, label = self.pairs[idx]\n cmpds = self.lookup( [(pair1, pair2)] )\n\n return cmpds, label\n\n def lookup(self, data):\n ret = []\n for pair in data:\n ret.append( (self.drug_struct[pair[0]], self.drug_struct[pair[1]]) )\n return ret\n\nclass GenericTrainDataset(GenericTestDataset):\n \"\"\"\n Only for predicting single properties from pairs\n\n data: pandas for the intended split\n \"\"\"\n def __init__(self, data, mol_desc_path, ratioCap=150):\n super().__init__(data, mol_desc_path)\n self.ratioCap = ratioCap\n self.pos_pairs = list(filter(lambda x: x[-1] == 1, self.pairs))\n self.neg_pairs = list(filter(lambda x: x[-1] == 0, self.pairs))\n del self.pairs\n\n if self.neg2pos_ratio() > self.ratioCap:\n self.pos_pairs *= int(len(self.neg_pairs)/self.ratioCap)\n self.shuffle()\n\n def shuffle(self):\n shuffle(self.pos_pairs)\n shuffle(self.neg_pairs)\n\n def neg2pos_ratio(self):\n return 0 if len(self.pos_pairs) == 0 else len(self.neg_pairs)/len(self.pos_pairs)\n\n def __len__(self):\n return len(self.pos_pairs)\n\n def __getitem__(self, idx):\n ratio = int(self.neg2pos_ratio())\n ret_pos = self.lookup( [self.pos_pairs[idx]] )\n\n end_ind = (idx+1)*ratio\n if len(self.neg_pairs) - end_ind < ratio: # make sure to include all data\n end_ind = len(self.neg_pairs)\n ret_neg = self.lookup( self.neg_pairs[idx*ratio:end_ind] )\n return (ret_pos, ret_neg)\n","sub_path":"gen_dataset.py","file_name":"gen_dataset.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"52516648","text":"\"\"\"Example program to demonstrate how to read string-valued markers from LSL.\"\"\"\n\nfrom pylsl import StreamInlet, resolve_stream\n\n\ndef main():\n # first resolve a marker stream on the lab network\n print(\"looking for a marker stream...\")\n streams = resolve_stream('type', 'Markers')\n\n # create a new inlet to read from the stream\n inlet = StreamInlet(streams[0])\n\n while True:\n # get a new sample (you can also omit the timestamp part if you're not\n # interested in it)\n sample, timestamp = inlet.pull_sample()\n print(\"got %s at time %s\" % (sample[0], timestamp))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pylsl/examples/ReceiveStringMarkers.py","file_name":"ReceiveStringMarkers.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"99348087","text":"# classification_report\n\n\n# confusion_matrix(y_true, y_pred)\n# accuracy_score(y_true, y_pred)\n# precision_score(y_true, y_pred)\n# recall_score(y_true, y_pred)\n# fbeta_score(y_true, y_pred, beta)\n# f1_score(y_true, y_pred)\n# classfication_report(y_true, y_pred)\n# roc_curve\n# auc\n\n#----------------------------------\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\n\nX, y = make_classification(n_samples=1000, weights=[0.95, 0.05], random_state=5)\n\nmodel1 = LogisticRegression().fit(X, y)\ny_hat1 = model1.predict(X)\n\nmodel2 = SVC(gamma=0.0001, C=3000, probability=True).fit(X, y)\ny_hat2 = model2.predict(X)\n\n\nfrom sklearn.metrics import confusion_matrix\nprint(confusion_matrix(y, y_hat1))\n\nprint(confusion_matrix(y, y_hat2))\n\n# 두 모형은 분류결과표로 봤을 때는 성능이 같다\n\nfrom sklearn.metrics import classification_report\nprint(classification_report(y, model1.predict(X)))\nprint(classification_report(y, model2.predict(X)))\n\n\n# ROC curve \nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve\nfpr1, tpr1, thresholds1 = roc_curve(y, model1.decision_function(X))\nfpr2, tpr2, thresholds1 = roc_curve(y, model2.decision_function(X))\n\nplt.plot(fpr1, tpr1, 'o-', ms=2, label=\"Logistic Regression\")\nplt.plot(fpr2, tpr2, 'o-', ms=2, label=\"Kernel SVM\")\nplt.legend()\nplt.plot([0, 1], [0, 1], 'k--', label=\"random guess\")\nplt.xlabel('위양성률(Fall-Out)')\nplt.ylabel('재현률(Recall)')\nplt.title('ROC 커브')\nplt.show()\n","sub_path":"day3/classification_report8.py","file_name":"classification_report8.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"315245910","text":"\"\"\"Functions for visulization distributions from seaborn\"\"\"\nfrom __future__ import division\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\n\nfrom ..util import freedman_diaconis_bins, despine\nfrom ..palette import circos, color_palette, blend_palette \n\ndef hist2d(x, y, ax=None, bins=None, norm_hist=False, norm=LogNorm(),\n xlabel=None, ylabel=None, cmap=None,\n **kwargs):\n \"\"\"\n Make a 2D histogram plot.\n\n Parameters\n ----------\n x, y: 1d array-like\n The two input datasets\n ax : matplotlib axis, optional\n Axis to plot on, otherwise uses current axis.\n bins : argument for matplotlib hist(), or None, optional\n Specification of hist bins(integer or array-like), or None to use\n Freedman-Diaconis rule.\n norm_hist : bool, optional\n If True, the histogram height shows a density rather than a count.\n xlabel: string, or None, optional\n Set the x axis label of the current axis.\n ylabel: string, or None, optional\n Set the y axis label of the current axis.\n kwargs : key, value pairings, optional\n Other keyword arguments are passed to ``plt.hist2d()``\n\n Returns\n -------\n ax : matplotlib Axes\n Axes object with the plot.\n\n Examples\n --------\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n\n kwargs.setdefault(\"normed\", norm_hist)\n\n x = x.astype(np.float64)\n y = y.astype(np.float64)\n\n if bins is None:\n x_bins = freedman_diaconis_bins(x)\n y_bins = freedman_diaconis_bins(y)\n bins = min(50, int(np.mean([x_bins, y_bins])))\n \n if cmap is None:\n colors = [circos['meth'+str(100-i)] for i in range(101)]\n cmap = blend_palette(color_palette(colors), as_cmap=True) \n\n ax.hist2d(x, y, bins=bins, norm=LogNorm(), cmap=cmap, **kwargs)\n ax.grid(False)\n\n if xlabel: ax.set_xlabel(xlabel)\n if ylabel: ax.set_ylabel(ylabel)\n\n return ax\n","sub_path":"geneview/baseplot/_distribution.py","file_name":"_distribution.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"602554549","text":"import paho.mqtt.client as mqtt\nimport upload_database\nfrom topics import Topics\n\n\nclass MqttClient:\n # class variables\n amount_of_receptions = 0\n topics = [x.value for x in Topics]\n topics_and_messages = {}\n for topic in topics:\n topics_and_messages[topic] = \"\"\n\n # instance methods\n def __init__(self, host, usr, password):\n self.client = mqtt.Client(client_id=\"5ub5cr1b3r_cl13n7_1d\", protocol=mqtt.MQTTv311, clean_session=False)\n self.client.on_connect = MqttClient.on_connect\n self.client.on_message = MqttClient.on_message\n self.client.on_disconnect = MqttClient.on_disconnect\n self.client.username_pw_set(usr, password)\n self.client.reconnect_delay_set(min_delay=25, max_delay=30)\n self.client.connect(host=host, port=18096, keepalive=60)\n\n self.subscribe_to_topics()\n\n self.client.loop_forever()\n\n def subscribe_to_topics(self):\n for topic in MqttClient.topics:\n (res, mid) = self.client.subscribe(topic, 1)\n print(\"Subscribed to \" + topic + \" with result code \" + str(res))\n\n @staticmethod\n def on_connect(client, userdata, flags, rc):\n if rc == 0:\n print(\"Connected with result code \" + str(rc))\n else:\n print(\"Bad Connection. Result code: \" + str(rc))\n\n @staticmethod\n def on_disconnect(client, userdata, rc):\n if rc != 0:\n print(\"Unexpected disconnection.\")\n\n # with open(\"errors.log\", \"a\") as e:\n # e.write(\"[\" + str(datetime.datetime.now()) + \"]: \" \"Unexpected disconnection.\\n\")\n\n # The callback for when a PUBLISH message is received from the server\n @staticmethod\n def on_message(client, userdata, msg):\n MqttClient.amount_of_receptions = MqttClient.amount_of_receptions + 1\n print(\"Message received: \")\n print(msg.topic, \" \", msg.payload.decode())\n # with open(\"result.txt\", \"a\") as f:\n # f.write(msg.payload.decode())\n print(\"Amount of receptions so far:\", MqttClient.amount_of_receptions)\n if msg.payload.decode() == 'Finish':\n upload_database.upload_to_database(msg.topic, MqttClient.topics_and_messages[msg.topic])\n else:\n MqttClient.topics_and_messages[msg.topic] = MqttClient.topics_and_messages.get(msg.topic) + msg.payload.decode()\n","sub_path":"Suscriber/mqtt_client.py","file_name":"mqtt_client.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"370031566","text":"# TIE-02101 Ohjelmointi 1\n# Konsta Jurvanen, 275552\n# Murtolukulaskin\n\n\nclass Fraction:\n \"\"\" This class represents one single fraction that consists of\n numerator and denominator \"\"\"\n\n def __init__(self, numerator, denominator):\n \"\"\"\n Constructor. Checks that the numerator and denominator are of\n correct type and initializes them.\n\n :param numerator: fraction's numerator\n :param denominator: fraction's denominator\n \"\"\"\n\n if not isinstance(numerator, int) or not isinstance(denominator, int):\n raise TypeError\n elif denominator == 0:\n raise ValueError\n\n self.__numerator = numerator\n self.__denominator = denominator\n\n def return_string(self):\n \"\"\" Returns a string-presentation of the fraction in the format \n numerator/denominator \"\"\"\n\n if self.__numerator * self.__denominator < 0:\n sign = \"-\"\n else:\n sign = \"\"\n return \"{:s}{:d}/{:d}\".format(sign, abs(self.__numerator),\n abs(self.__denominator))\n\n def simplify(self):\n jakaja = greatest_common_divisor(self.__numerator, self.__denominator)\n self.__denominator = int(self.__denominator / jakaja)\n self.__numerator = int(self.__numerator / jakaja)\n sievennetty = Fraction(self.__numerator, self.__denominator)\n return sievennetty\n\n def complement(self):\n\n num = -1 * self.__numerator\n den = self.__denominator\n vastaluku = Fraction(num, den)\n return vastaluku\n\n def reciprocal(self):\n\n num = self.__denominator\n den = self.__numerator\n kaanteisluku = Fraction(num, den)\n return kaanteisluku\n\n def multiply(self, kertoja):\n num = self.__numerator * kertoja.__numerator\n den = self.__denominator * kertoja.__denominator\n tulo = Fraction(num, den)\n return tulo\n\n def divide(self, jakaja):\n num = self.__numerator * jakaja.__denominator\n den = self.__denominator * jakaja.__numerator\n jako = Fraction(num, den)\n return jako\n\n def add(self, summattava):\n num = (self.__numerator * summattava.__denominator\n + summattava.__numerator * self.__denominator)\n den = (self.__denominator * summattava.__denominator)\n summa = Fraction(num, den)\n return summa\n\n def deduct(self, miinus):\n num = (self.__numerator * miinus.__denominator\n - miinus.__numerator * self.__denominator)\n den = (self.__denominator * miinus.__denominator)\n erotus = Fraction(num, den)\n return erotus\n\n def __lt__(self, vert):\n return self.__numerator / self.__denominator < vert.__numerator / vert.__denominator\n\n def __gt__(self, vert):\n return self.__numerator / self.__denominator > vert.__numerator / vert.__denominator\n def __str__(self):\n return self.return_string()\n\n\n\ndef greatest_common_divisor(a, b):\n \"\"\"\n Euclidean algorithm.\n \"\"\"\n\n while b != 0:\n a, b = b, a % b\n return a\n\n\ndef listasievennys():\n\n lukulista = []\n print(\"Enter fractions in the format integer/integer.\")\n print(\"One fraction per line. Stop by entering an empty line.\")\n syote = input()\n while syote != \"\":\n\n [num, den] = syote.split(\"/\")\n murtoluku = Fraction(int(num), int(den))\n lukulista.append(murtoluku)\n syote = input()\n\n print(\"The given fractions in their simplified form:\")\n for luku in lukulista:\n print(f\"{luku} = {luku.simplify()}\")\n\n\ndef main():\n\n murtoluvut = {}\n operaatiot = {\n \"+\": lambda luku1, luku2: luku1.add(luku2),\n \"-\": lambda luku1, luku2: luku1.deduct(luku2),\n \"*\": lambda luku1, luku2: luku1.multiply(luku2),\n \"/\": lambda luku1, luku2: luku1.divide(luku2)\n }\n\n komento = input(\"> \")\n while komento != \"quit\":\n\n if komento in operaatiot:\n luku1 = input(\"1st operand: \")\n if luku1 in murtoluvut:\n luku2 = input(\"2nd operand: \")\n if luku2 in murtoluvut:\n mur1 = murtoluvut[luku1]\n mur2 = murtoluvut[luku2]\n vastaus = operaatiot[komento](mur1, mur2)\n print(f\"{mur1} {komento} {mur2} = {vastaus}\")\n siev = vastaus.simplify()\n print(f\"simplified {siev}\")\n else:\n print(f\"Name {luku2} was not found\")\n else:\n print(f\"Name {luku1} was not found\")\n\n elif komento == \"add\":\n lisattava = input(\"Enter a fraction in the form integer/integer: \")\n nimi = input(\"Enter a name: \")\n [num, den] = lisattava.split(\"/\")\n murtoluku = Fraction(int(num), int(den))\n murtoluvut[nimi] = murtoluku\n\n elif komento == \"print\":\n nimi = input(\"Enter a name: \")\n if nimi in murtoluvut:\n print(f\"{nimi} = {murtoluvut[nimi]}\")\n else:\n print(f\"Name {nimi} was not found\")\n\n elif komento == \"list\":\n for luku in sorted(murtoluvut):\n print(f\"{luku} = {murtoluvut[luku]}\")\n\n elif komento == \"file\":\n try:\n tiedosto = input(\"Enter the name of the file: \")\n lukuja = open(tiedosto, 'r')\n for rivi in lukuja:\n rivi = rivi.rstrip()\n [muuttuja, arvo] = rivi.split(\"=\")\n [nume, denu] = arvo.split(\"/\")\n murtoluvut[muuttuja] = Fraction(int(nume), int(denu))\n lukuja.close()\n except IOError:\n print(\"Error: the file cannot be read.\")\n\n else:\n print(\"Unknown command!\")\n komento = input(\"> \")\n\n print(\"Bye bye!\")\n\n\nmain()\n","sub_path":"fraction.py","file_name":"fraction.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"162823114","text":"#!python3\n\n\"\"\"\n##### Task 3\nWhen shopping, we pay 12% combined GST and PST on many items. Write a program that asks the user to enter in the prices of 4 items that they are buying. Find the total price, the amount of tax and the overall price. Taxes are rounded appropriately\n\nexample:\nEnter the first price: 11.99\nEnter the second price: 14.76\nEnter the third price: 12.99\nEnter the fourth price: 15.98\nEnter the fift price: 7.99\nYour subtotal is $63.71 and your taxes total $7.65 for a total of $71.36\n\n\"\"\"\np1 = float(input(\"Enter the first price: \"))\np2 = float(input(\"Enter the second price: \"))\np3 = float(input(\"Enter the third price: \"))\np4 = float(input(\"Enter the fourth price: \"))\np5 = float(input(\"Enter the fifth price: \"))\nsb = p1 + p2 + p3 + p4 + p5\ntt = sb * .12\nft = sb + tt\nsb2 = str(round(sb, 2))\ntt2 = str(round(tt, 2))\nft2 = str(round(ft, 2))\n\nsb3 = (\"$\" + str(sb2))\ntt3 = (\"$\" + str(tt2))\nft3 = (\"$\" + str(ft2))\n\nprint(\"Your subtotal is\" ,sb3, \"and your taxes total\" ,tt3, \"for a total of\" ,ft3,)\n\n\n","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"474716168","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom scipy.sparse import csr_matrix\nimport random\n\nclass CF_events():\n #k is the number of users using to recommend for current user\n #clicking is a table contain the amount of clicking of user_id for item_id\n #category is the table cotain category of item_id\n #number_of_recommend is a number of item recommend to user\n def __init__(self,events_clicking,events_category,k,number_of_recommend):\n self.k=k\n self.clicking=events_clicking\n self.recommended_items_final=[]\n self.category=events_category\n self.number_of_recommend=number_of_recommend\n \n \n #clean_data has index of each row (item)\n #clean_data1 is numpy type of clean_data\n #clean_data2 do not have index of each row(item) \n #clean_data3 is the total amount of clicking of each item \n # sim is the table compare the cosine similarity each user\n #csr_data use to decrease sparse data\n def preprocessing_data(self):\n try:\n self.clean_data=self.clicking.pivot(index=\"item_id\",columns=\"user_id\",values=\"Clicking\")\n self.clean_data3=self.clean_data.sum(axis=1)\n #standarization data\n \n self.clean_data=(self.clean_data-self.clean_data.mean()+(1e-8))/(self.clean_data.std()+(1e-8))\n \n self.clean_data.fillna(0,inplace=True)\n self.clean_data1=np.array(self.clean_data)\n self.clean_data2=self.clean_data.copy()\n csr_data=csr_matrix(self.clean_data)\n self.clean_data.reset_index(inplace=True)\n self.sim=cosine_similarity(csr_data.T,csr_data.T)\n\n self.delete()\n except:\n pass\n \n \n def pred(self,user_id,item_id):\n #get index of other user clicked to item id, current user, and item\n users_clicked_item_id=self.clicking[self.clicking[\"item_id\"]==item_id][\"user_id\"]\n users_clicked_item_index=[self.clean_data2.columns.get_loc(i) for i in users_clicked_item_id]\n user_index=self.clean_data2.columns.get_loc(user_id)\n item_index=self.clean_data[self.clean_data[\"item_id\"]==item_id].index[0]\n \n #check whether user click item or not, if already click do not recommend\n if self.clean_data1[item_index,user_index]!=0:\n return False\n \n #get sim of current user and other users clicked to item\n #get k users has highest sim to current user\n sim_user=self.sim[user_index,users_clicked_item_index]\n most_similar_index=np.argsort(sim_user)[-self.k:]\n most_similar_user_index=[]\n for i in most_similar_index:\n most_similar_user_index.append(users_clicked_item_index[i])\n\n #the function to predict how much user will click to item\n largest_sim=sim_user[most_similar_index]\n click_value=self.clean_data1[item_index,most_similar_user_index]\n pred=(click_value*largest_sim).sum()/(np.abs(largest_sim).sum()+1e-8)\n return pred\n \n def recommend(self,user_id,item_id):\n recommended_items_final=[]\n recommended_items_CF=[]\n \n #Sort item with pred score\n for item in self.clean_data2.index:\n #Check whether user clicked item or not\n if self.pred(user_id,item)==False:\n continue\n recommended_items_CF.append((item,self.pred(user_id,item)))\n recommended_items_CF.sort(key=lambda x: x[1])\n \n #Choose half item has highest pred score\n recommended_items_CF=recommended_items_CF[-int(self.number_of_recommend/2):]\n \n for item in recommended_items_CF:\n recommended_items_final.append(item[0])\n \n #Sort items with number of category that are the same with current item and total amount of click\n if len(self.category[self.category[\"item_id\"]==item_id])==0:\n item_category=[]\n else: \n item_category=self.category[self.category[\"item_id\"]==item_id].to_numpy()[0][1:]\n \n #Remove nan category \n nan_position=[]\n for i in range(len(item_category)-1,-1,-1):\n if item_category[i]!=item_category[i]:\n nan_position.append(i)\n for i in nan_position:\n item_category=np.delete(item_category,i)\n items_score=[]\n for item in self.category['item_id']:\n #check whether item has already in recommend list\n if item==item_id or item in recommended_items_final:\n continue\n category_score=0\n if len(self.category[self.category['item_id']==item])==0:\n continue\n for i in self.category[self.category[\"item_id\"]==item].to_numpy()[0][1:]:\n #plus 1 to score if have the same category\n if i in item_category:\n category_score+=1\n try:\n clicking_score=self.clean_data3.loc[item]\n except:\n clicking_score=0\n items_score.append((item, category_score, clicking_score))\n \n items_score.sort(key=lambda x: (x[1], x[2]),reverse=True)\n \n \n #choose items until recommended_items_list full \n for i in range(len(items_score)):\n if len(recommended_items_final)==self.number_of_recommend-2:\n items_score=items_score[i:]\n random.shuffle(items_score)\n break\n recommended_items_final.append(items_score[i][0])\n for i in range(len(items_score)):\n if len(recommended_items_final)==self.number_of_recommend:\n break\n recommended_items_final.append(items_score[i][0])\n return recommended_items_final\n\n #update data\n def refresh_data(self,events_clicking,events_category):\n self.clicking=events_clicking\n self.category=events_category\n self.preprocessing_data()\n\n def hottest(self,item_id):\n if len(self.category[self.category[\"item_id\"]==item_id])==0:\n item_category=[]\n else: \n item_category=self.category[self.category[\"item_id\"]==item_id].to_numpy()[0][1:]\n \n #Remove nan category \n nan_position=[]\n for i in range(len(item_category)):\n if item_category[i]!=item_category[i]:\n nan_position.append(i)\n for i in nan_position:\n item_category=np.delete(item_category,i)\n items_score=[]\n for item in self.category['item_id']:\n #check whether item has already in recommend list\n if item==item_id :\n continue\n category_score=0\n if len(self.category[self.category['item_id']==item])==0:\n continue\n for i in self.category[self.category[\"item_id\"]==item].to_numpy()[0][1:]:\n #plus 1 to score if have the same category\n if i in item_category:\n category_score+=1\n try:\n clicking_score=self.clean_data3.loc[item]\n except:\n clicking_score=0\n items_score.append((item, category_score, clicking_score))\n \n items_score.sort(key=lambda x: (x[1], x[2]),reverse=True)\n recommend_list=[]\n for i in range(len(items_score)):\n recommend_list.append(items_score[i][0])\n \n return recommend_list\n \n def welcome_recommend(self,user_id):\n dic={\n 'hottest_events':[],\n 'care_events':[],\n }\n try:\n recommended_items_CF=[]\n #Sort item with pred score\n for item in self.clean_data2.index:\n #Check whether user clicked item or not\n if self.pred(user_id,item)==False:\n continue\n recommended_items_CF.append((item,self.pred(user_id,item)))\n recommended_items_CF.sort(key=lambda x: x[1])\n \n for i in range(len(recommended_items_CF)):\n recommended_items_CF[i]=recommended_items_CF[i][0]\n \n #Choose 10 item with highest pred score \n if len(recommended_items_CF)>10:\n recommended_items_CF=recommended_items_CF[-10:]\n dic['care_events']=recommended_items_CF\n except:\n pass\n #Sort item with highest amount of click \n self.clean_data3=self.clean_data3.sort_values(ascending=False)\n recommended_items_hottest=[]\n count=0\n #Choose 10 hottest item\n items_score=[]\n for item in self.category['item_id']:\n try:\n clicking_score=self.clean_data3.loc[item]\n except:\n clicking_score=0\n items_score.append((item, clicking_score))\n \n items_score.sort(key=lambda x: (x[1]),reverse=True)\n for i in items_score:\n if count==100:\n break\n recommended_items_hottest.append(i[0])\n count+=1\n dic['hottest_events']=recommended_items_hottest\n return dic\n def welcome(self):\n items_score=[]\n self.clean_data3=self.clean_data3.sort_values(ascending=False)\n recommended_items_hottest=[]\n count=0\n dic={\n 'hottest_events':[],\n }\n for item in self.category['item_id']:\n try:\n clicking_score=self.clean_data3.loc[item]\n except:\n clicking_score=0\n items_score.append((item, clicking_score))\n \n items_score.sort(key=lambda x: (x[1]),reverse=True)\n for i in items_score:\n if count==100:\n break\n recommended_items_hottest.append(i[0])\n count+=1\n dic['hottest_events']=recommended_items_hottest\n return dic\n \n def delete(self):\n #delete an event in clicking due to the removal\n total_item= self.category[\"item_id\"]\n clicking_item= self.clicking[\"item_id\"]\n contain=[]\n for i in clicking_item:\n check=False\n for j in total_item:\n if(i==j):\n check=True\n break\n if(check==False):\n contain.append(i)\n for i in contain:\n self.clicking=self.clicking[self.clicking[\"item_id\"]!=i]\n self.clicking.to_csv('database/events_clicking.csv',index=False)\n","sub_path":"collaborative_filtering/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":9288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"153390843","text":"import numpy as np\nfrom GA import *\nimport gym\nimport tensorflow as tf\nimport datetime\nfrom ant_maze_env import *\nimport pickle\n\nTASK_NAME = 'Maze'\nVERSION = '1'\nPOPULATION = 50\nEPISODE_NUMBER = 1000\n\nif TASK_NAME is 'Maze':\n TARGET_GOAL = np.array([0, 16])\nelif TASK_NAME is 'Push':\n TARGET_GOAL = np.array([0, 19])\nelif TASK_NAME is 'Fall':\n TARGET_GOAL = np.array([0, 27])\n\n\n# run the GA with novelty search\n# 2020-2-8\nclass HP:\n def __init__(self, env, seed=1, input_dim=None, output_dim=None, hidden_size=64):\n self.env = env\n self.input_dim = self.env.observation_space.shape[0] if input_dim is None else input_dim\n self.output_dim = self.env.action_space.shape[0] if output_dim is None else output_dim\n self.seed = seed\n self.hidden_size = hidden_size\n np.random.seed(seed)\n tf.set_random_seed(seed)\n self.env.seed(seed)\n self.archive = [] # store the final position of the states\n\n def cal_novelty_v2(self, position):\n # calculate novelty and local competition\n all_data = np.reshape(self.archive, [-1, 2])\n p = np.reshape(position, [-1, 2])\n dist = np.sqrt(np.sum(np.square(p - all_data), axis=1))\n idx = np.argsort(dist)[:15]\n distance_to_goal = [np.sqrt(np.sum(np.square(np.reshape(self.archive[_], [-1, 2]) - TARGET_GOAL), axis=1)) for _\n in idx]\n lc = np.sum(np.array(distance_to_goal) < 1) / 15.0\n return np.mean(np.sort(dist)[:15]), lc\n\n\nclass Policy:\n def __init__(self, hp, params=None):\n # 根据parameter初始化\n self.hp = hp\n self.input_dim, self.output_dim, self.hidden_size = hp.input_dim, hp.output_dim, hp.hidden_size\n self.param_count = hp.input_dim * hp.hidden_size + self.hidden_size + self.hidden_size * self.hidden_size + \\\n self.hidden_size + self.hidden_size * self.output_dim + self.output_dim\n if params is not None:\n assert len(params) == self.param_count\n self.params = params\n\n def set_params(self, params):\n self.params = params\n\n def get_params_count(self):\n return self.param_count\n\n def evaluate_tf(self, state):\n # 得出action值,三层神经网络?用parameter来说\n sess = tf.Session()\n input_state = np.reshape(state, [1, self.input_dim])\n feed_state = tf.placeholder(dtype=tf.float64, shape=[1, self.input_dim])\n param_list = self.get_detail_params()\n l1 = tf.nn.relu(tf.matmul(feed_state, param_list[0]) + param_list[1])\n l2 = tf.nn.relu(tf.matmul(l1, param_list[2])) + param_list[3]\n output_action = tf.nn.tanh(tf.matmul(l2, param_list[4]) + param_list[5]) * 30\n return sess.run(output_action, feed_dict={feed_state: input_state})\n\n def evaluate(self, state):\n input_state = np.reshape(state, [1, self.input_dim])\n param_list = self.get_detail_params()\n l1 = np.maximum(0, input_state.dot(param_list[0]) + param_list[1])\n l2 = np.maximum(0, l1.dot(param_list[2]) + param_list[3])\n return 30 * np.tanh(l2.dot(param_list[4]) + param_list[5])\n\n def get_detail_params(self):\n # 得到w1,b1,w2,b2,w3,b3\n w1 = self.params[:self.input_dim * self.hidden_size]\n b1 = self.params[len(w1):len(w1) + self.hidden_size]\n w2 = self.params[len(w1) + len(b1):len(w1) + len(b1) + self.hidden_size * self.hidden_size]\n b2 = self.params[len(w1) + len(b1) + len(w2):len(w1) + len(b1) + len(w2) + self.hidden_size]\n w3 = self.params[len(w1) + len(w2) + len(b1) + len(b2):len(w1) + len(w2) + len(b1) + len(\n b2) + self.hidden_size * self.output_dim]\n b3 = self.params[-self.output_dim:]\n return [np.reshape(w1, [self.input_dim, self.hidden_size]),\n np.reshape(b1, [self.hidden_size, ]),\n np.reshape(w2, [self.hidden_size, self.hidden_size]),\n np.reshape(b2, [self.hidden_size, ]),\n np.reshape(w3, [self.hidden_size, self.output_dim]),\n np.reshape(b3, [self.output_dim, ])]\n\n def get_fitness(self):\n total_reward = 0\n env = self.hp.env\n obs = env.reset()\n for step in range(500):\n # env.render()\n action = self.evaluate(obs)\n next_obs, reward, done, _ = env.step(action)\n if np.sqrt(np.sum(np.square(next_obs[:2] - TARGET_GOAL))) < 1:\n reward = 1\n else:\n reward = 0\n obs = next_obs\n total_reward += reward\n if done:\n break\n if len(self.hp.archive) > 0:\n novelty, lc = self.hp.cal_novelty_v2(obs[:2])\n else:\n novelty = 0\n lc = 0\n return novelty, lc, obs[:2]\n\n\nenv = AntMazeEnv(maze_id=TASK_NAME)\nRESTART = False\nrestart_file_name = 'novelty_search_final_population'\nepisode_num = EPISODE_NUMBER\nseed = 1\n\nhp = HP(env=env, input_dim=30, output_dim=8, seed=seed)\npolicy = Policy(hp)\nga = GA(num_params=policy.get_params_count(), pop_size=POPULATION, elite_frac=0.1, mut_rate=0.9)\n\nall_data = []\nfinal_pos = []\nfor episode in range(episode_num):\n start_time = datetime.datetime.now()\n if RESTART:\n population = pickle.load(open(restart_file_name, mode='rb'))\n else:\n population = ga.ask()\n lc = []\n novelty = []\n position = []\n for p in population:\n policy.set_params(p)\n n, r, last_position = policy.get_fitness()\n novelty.append(n)\n lc.append(r)\n position.append(last_position)\n fitness = np.array(novelty)+np.array(lc)\n initial_bc = position\n for p in position:\n policy.hp.archive.append(p) # update novelty archive\n ga.tell(population, fitness)\n best_index = np.argmax(fitness)\n all_data.append(\n {'episode': episode, 'best_fitness': fitness[best_index], 'best_reward': lc[best_index],\n 'initial_bc': position, 'novelty': fitness})\n final_pos.append(position[best_index])\n print('######')\n print('Episode ', episode)\n print('Best fitness value: ', fitness[best_index])\n print('Best lc: ', lc[best_index])\n print('Final distance: ', np.sqrt(np.sum(np.square(position[best_index] - TARGET_GOAL))))\n print('Running time:', (datetime.datetime.now() - start_time).seconds)\npickle.dump(all_data, open(TASK_NAME + '_qd_reward_v' + VERSION, mode='wb'))\npickle.dump(final_pos, open(TASK_NAME + '_qd_final_pos_v' + VERSION, mode='wb'))\n# pickle.dump(population, open('ns_final_population_' + str(seed), mode='wb'))\n","sub_path":"quality_diversity.py","file_name":"quality_diversity.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"94287498","text":"'''\nThis contains the dasboards apis\n'''\nfrom django.conf import settings\nfrom django.db import connections\nfrom django.db.models import Sum\nfrom django.db.models.query_utils import Q\nfrom django.http.response import HttpResponse\nfrom tastypie import fields\nfrom tastypie.utils.mime import build_content_type\n\nfrom gladminds.bajaj import models\nfrom gladminds.core.apis.authentication import AccessTokenAuthentication\nfrom gladminds.core.apis.base_apis import CustomBaseResource, CustomApiObject\nfrom gladminds.core.auth_helper import Roles\nfrom gladminds.core.constants import FEED_TYPES, FeedStatus, FEED_SENT_TYPES, \\\n CouponStatus, TicketStatus, FEEDBACK_STATUS\nfrom gladminds.core.core_utils.cache_utils import Cache\nfrom gladminds.core.core_utils.utils import dictfetchall\nfrom gladminds.core.model_fetcher import get_model\n\n\ndef get_vins():\n return models.ProductData.objects.all().count()\n\n\ndef get_customers_count():\n return models.ProductData.objects.filter(purchase_date__isnull=False).count()\n\ndef get_mobile_number_count():\n sum = models.CustomerTempRegistration.objects.filter(mobile_number_update_count__isnull=False).aggregate(Sum('mobile_number_update_count'))\n return sum.values()[0] \n\ndef get_total_sms():\n total_sms = models.SMSLog.objects.filter(Q(action='SENT') | Q(action='RECEIVED')).count()\n return total_sms\n\ndef get_success_and_failure_counts(objects):\n fail = 0\n success = 0\n for data in objects:\n fail = fail + int(data.failed_data_count)\n success = success + int(data.success_data_count)\n return success, fail\n\n\ndef get_set_cache(key, data_func, timeout=15):\n '''\n Used for putting data in cache .. specified on a timeout\n :param key:\n :type string:\n :param data:\n :type queryset result:\n :param timeout:\n :type int:\n '''\n result = Cache.get(key)\n if result is None:\n if data_func is None:\n raise\n if not hasattr(data_func, '__call__'):\n result = data_func\n else:\n result = data_func()\n Cache.set(key, result, timeout)\n return result\n\n_KEYS = [\"id\", \"name\", \"value\"]\n\n\ndef create_dict(values, keys=_KEYS):\n return dict(zip(keys, values))\n\n\n\nclass OverallStatusResource(CustomBaseResource):\n \"\"\"\n It is a preferences resource\n \"\"\"\n id = fields.CharField(attribute=\"id\")\n name = fields.CharField(attribute=\"name\")\n value = fields.CharField(attribute='value', null=True)\n\n class Meta:\n resource_name = 'overall-status'\n authentication = AccessTokenAuthentication()\n object_class = CustomApiObject\n\n def obj_get_list(self, bundle, **kwargs):\n self.is_authenticated(bundle.request)\n vins = get_set_cache('gm_vins', get_vins, timeout=30)\n customers = get_set_cache('gm_customers', get_customers_count, timeout=35)\n coupons_closed = get_set_cache('gm_coupons_closed',\n models.CouponData.objects.closed_count,\n timeout=13)\n coupons_progress = get_set_cache('gm_coupons_progress',\n models.CouponData.objects.inprogress_count,\n timeout=11)\n coupons_expired = get_set_cache('gm_coupons_expired',\n models.CouponData.objects.expired_count,\n timeout=16)\n tickets_raised = get_set_cache('gm_ticket_raised',\n models.Feedback.objects.raised_count)\n tickets_progress = get_set_cache('gm_ticket_progress',\n models.Feedback.objects.inprogress_count)\n dealers = get_set_cache('gm_dealers',\n models.Dealer.objects.count)\n dealers_active = get_set_cache('gm_dealers_active',\n models.Dealer.objects.active_count)\n ascs = get_set_cache('gm_ascs',\n models.AuthorizedServiceCenter.objects.count)\n ascs_active = get_set_cache('gm_ascs_active',\n models.AuthorizedServiceCenter.objects.active_count)\n sas = get_set_cache('gm_sas',\n models.ServiceAdvisor.objects.count)\n sas_active = get_set_cache('gm_sas_active',\n models.ServiceAdvisor.objects.active_count)\n mobile_number_change_count = get_set_cache('gm_mobile_number_change_count',\n get_mobile_number_count,\n timeout=10)\n total_sms = get_set_cache('gm_total_sms', get_total_sms, timeout=12)\n \n \n return map(CustomApiObject, [create_dict([\"1\", \"#of Vins\", vins]),\n create_dict([\"2\", \"Service Coupons Closed\",\n coupons_closed]),\n create_dict([\"3\", \"Service Coupons In Progress\",\n coupons_progress]),\n create_dict([\"4\", \"Service Coupons Expired\",\n coupons_expired]),\n create_dict([\"5\", \"Tickets Raised\",\n tickets_raised]),\n create_dict([\"6\", \"Tickets In Progress\",\n tickets_progress]),\n create_dict([\"7\", \"# of Dealers\",\n dealers]),\n create_dict([\"8\", \"# of Active Dealers\",\n dealers_active]),\n create_dict([\"9\", \"# of ASCs\",\n ascs]),\n create_dict([\"10\", \"# of Active ASCs\",\n ascs_active]),\n create_dict([\"11\", \"# of SAs\",\n sas]),\n create_dict([\"12\", \"# of Active SAs\",\n sas_active]),\n create_dict([\"13\", \"# of Customers\",\n customers]),\n create_dict([\"14\", \"Mobile updated\",\n mobile_number_change_count]),\n create_dict([\"15\", \"Recent Trails\",\n total_sms])\n ]\n )\n\n\n_KEYS_FEED = [\"status\", \"type\", \"success_count\", \"failure_count\"]\n\n\ndef create_feed_dict(values, keys=_KEYS_FEED):\n return dict(zip(keys, values))\n\n\nclass FeedStatusResource(CustomBaseResource):\n \"\"\"\n It is a preferences resource\n \"\"\"\n status = fields.CharField(attribute=\"status\")\n feed_type = fields.CharField(attribute=\"type\")\n success = fields.CharField(attribute=\"success_count\")\n failure = fields.CharField(attribute=\"failure_count\")\n\n class Meta:\n resource_name = 'feeds-status'\n authentication = AccessTokenAuthentication()\n object_class = CustomApiObject\n\n def obj_get_list(self, bundle, **kwargs):\n self.is_authenticated(bundle.request)\n filters = {}\n params = {}\n if hasattr(bundle.request, 'GET'):\n params = bundle.request.GET.copy()\n dtstart = params.get('created_date__gte')\n dtend = params.get('created_date__lte')\n hash_key = \"gm-feeds-status1-\"\n if dtstart:\n filters['created_date__gte'] = dtstart\n hash_key = hash_key + dtstart\n if dtend:\n filters['created_date__lte'] = dtend\n hash_key = hash_key + dtend\n\n data_map = {}\n result = []\n filters['feed_type__in'] = FEED_SENT_TYPES + FEED_TYPES\n\n output = Cache.get(hash_key)\n if output:\n return map(CustomApiObject, output)\n\n objects = models.DataFeedLog.objects.filter(**filters)\n\n for feed_type in FEED_SENT_TYPES + FEED_TYPES:\n data_map[feed_type] = [0, 0]\n for obj in objects:\n feed_counts = data_map[obj.feed_type] \n feed_counts[0] = feed_counts[0] + int(obj.failed_data_count)\n feed_counts[1] = feed_counts[1] + int(obj.success_data_count)\n data_map[obj.feed_type] = feed_counts\n\n for key, value in data_map.items():\n action = FeedStatus.RECEIVED\n if key in FEED_SENT_TYPES:\n action = FeedStatus.SENT\n result.append(create_feed_dict([action,\n key,\n value[1],\n value[0]]))\n Cache.set(hash_key, result, 15*60)\n return map(CustomApiObject, result)\n# data = [] \n# filters['action'] = FeedStatus.RECEIVED\n# for feed_type in FEED_TYPES:\n# filters['feed_type'] = feed_type\n# success_count, failure_count = get_success_and_failure_counts(models.DataFeedLog.objects.filter(**filters))\n# data.append(create_feed_dict([FeedStatus.RECEIVED,\n# feed_type,\n# success_count,\n# failure_count]))\n# filters['action'] = FeedStatus.SENT\n# for feed_type in FEED_SENT_TYPES:\n# filters['feed_type'] = feed_type\n# success_count, failure_count = get_success_and_failure_counts(models.DataFeedLog.objects.filter(**filters))\n# data.append(create_feed_dict([FeedStatus.SENT,\n# feed_type,\n# success_count,\n# failure_count]))\n# return map(CustomApiObject, data)\n\n\nclass SMSReportResource(CustomBaseResource):\n \"\"\"\n It is a preferences resource\n \"\"\"\n date = fields.DateField(attribute=\"date\")\n sent = fields.DecimalField(attribute=\"sent\", default=0)\n received = fields.DecimalField(attribute=\"received\", default=0)\n\n class Meta:\n resource_name = 'sms-report'\n authentication = AccessTokenAuthentication()\n object_class = CustomApiObject\n\n def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):\n \"\"\"\n Extracts the common \"which-format/serialize/return-response\" cycle.\n\n Mostly a useful shortcut/hook.\n \"\"\"\n desired_format = self.determine_format(request)\n data['overall'] = {'sent': self.get_sms_count(FeedStatus.SENT.upper()),\n 'received': self.get_sms_count(FeedStatus.RECEIVED.upper())}\n\n serialized = self.serialize(request, data, desired_format)\n return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)\n\n def get_sms_count(self, action):\n data = self.get_sql_data(\"select count(*) as count from gm_smslog where action=%(action)s\",\n filters={'action': action})\n return data[0]['count']\n\n def get_sql_data(self, query, filters={}):\n conn = connections[settings.BRAND]\n cursor = conn.cursor()\n cursor.execute(query, filters)\n data = dictfetchall(cursor)\n conn.close()\n return data\n\n def obj_get_list(self, bundle, **kwargs):\n self.is_authenticated(bundle.request)\n filters = {}\n params = {}\n if hasattr(bundle.request, 'GET'):\n params = bundle.request.GET.copy()\n dtstart = params.get('created_date__gte')\n dtend = params.get('created_date__lte')\n where_and = \" AND \"\n query = \"select DATE(created_date) as date, action, count(*) as count from gm_smslog where action!='SEND TO QUEUE' \"\n\n if dtstart:\n query = query + where_and + \"DATE(created_date) >= %(dtstart)s \"\n filters['dtstart'] = dtstart\n if dtend:\n query = query + where_and + \"DATE(created_date) <= %(dtend)s \"\n filters['dtend'] = dtend\n\n query = query + \" group by DATE(created_date), action;\"\n\n objs = {}\n all_data = self.get_sql_data(query, filters)\n for data in all_data:\n obj = objs.get(data['date'], {'date': data['date']})\n objs[data['date']] = obj\n objs[data['date']][data['action'].lower()] = data['count']\n return map(CustomApiObject, objs.values())\n\n\nclass CouponReportResource(CustomBaseResource):\n \"\"\"\n It is a preferences resource\n \"\"\"\n date = fields.DateField(attribute=\"date\")\n closed = fields.DecimalField(attribute=\"closed\", default=0)\n inprogress = fields.DecimalField(attribute=\"inprogress\", default=0)\n unused = fields.DecimalField(attribute=\"unused\", default=0)\n exceeds_limit = fields.DecimalField(attribute=\"exceeds\", default=0)\n\n class Meta:\n resource_name = 'coupons-report'\n authentication = AccessTokenAuthentication()\n object_class = CustomApiObject\n\n def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):\n \"\"\"\n Extracts the common \"which-format/serialize/return-response\" cycle.\n\n Mostly a useful shortcut/hook.\n \"\"\"\n desired_format = self.determine_format(request)\n data['overall'] = {'closed': self.get_coupon_count(CouponStatus.CLOSED),\n 'inprogress': self.get_coupon_count(CouponStatus.IN_PROGRESS)}\n\n serialized = self.serialize(request, data, desired_format)\n return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)\n\n def get_coupon_count(self, status):\n status = str(status)\n try:\n return get_set_cache('gm_coupon_counter' + status, None)\n except:\n data = self.get_sql_data(\"select count(*) as count from gm_coupondata where status=%(status)s\",\n filters={'status': status})\n return get_set_cache('gm_coupon_counter' + status, data[0]['count'])\n\n def get_sql_data(self, query, filters={}):\n conn = connections[settings.BRAND]\n cursor = conn.cursor()\n cursor.execute(query, filters)\n data = dictfetchall(cursor)\n conn.close()\n return data\n\n def obj_get_list(self, bundle, **kwargs):\n self.is_authenticated(bundle.request)\n filters = {}\n params = {}\n if hasattr(bundle.request, 'GET'):\n params = bundle.request.GET.copy()\n dtstart = params.get('created_date__gte')\n dtend = params.get('created_date__lte')\n where_and = \" AND \"\n query = \"select c.*, d.date from gm_couponfact c inner join \\\n gm_datedimension d on c.date_id=d.date_id where c.data_type='TOTAL' \";\n if dtstart:\n query = query + where_and + \"DATE(d.date) >= %(dtstart)s \"\n filters['dtstart'] = dtstart\n if dtend:\n query = query + where_and + \"DATE(d.date) <= %(dtend)s \"\n filters['dtend'] = dtend\n\n all_data = self.get_sql_data(query, filters)\n return map(CustomApiObject, all_data)\n\nclass TicketStatusResource(CustomBaseResource):\n \"\"\"\n It is a preferences resource\n \"\"\"\n id = fields.CharField(attribute=\"id\")\n name = fields.CharField(attribute=\"name\")\n value = fields.CharField(attribute='value', null=True)\n\n class Meta:\n resource_name = 'ticket-status'\n authentication = AccessTokenAuthentication()\n object_class = CustomApiObject\n \n def get_ticket_count(self, request):\n if request.user.groups.filter(name=Roles.SDOWNERS):\n assignee_id = get_model('ServiceDeskUser').objects.get(user_profile__user_id=int(request.user.id)).id\n data = self.get_sql_data(\"select status, count(*) as count from gm_feedback where assignee_id=%(assignee_id)s group by status\",\n filters={'assignee_id' : assignee_id})\n \n elif request.user.groups.filter(name__in=[Roles.SDMANAGERS, Roles.DEALERADMIN]):\n data = self.get_sql_data(\"select status, count(*) as count from gm_feedback group by status\")\n \n elif request.user.groups.filter(name=Roles.DEALERS):\n reporter_id = get_model('ServiceDeskUser').objects.get(user_profile__user_id=int(request.user.id)).id\n data = self.get_sql_data(\"select status, count(*) as count from gm_feedback where reporter_id=%(reporter_id)s group by status\",\n filters={'reporter_id' : reporter_id})\n \n return get_set_cache('gm_ticket_count' + str(request.user.id), data, timeout=2)\n \n def get_sql_data(self, query, filters={}):\n conn = connections[settings.BRAND]\n cursor = conn.cursor()\n cursor.execute(query, filters)\n data = dictfetchall(cursor)\n conn.close()\n return data\n \n def obj_get_list(self, bundle, **kwargs):\n self.is_authenticated(bundle.request)\n ticket_count = self.get_ticket_count(bundle.request)\n all_status = []\n status_id = 1\n for status in dict(FEEDBACK_STATUS).keys():\n data = {}\n data['id'] = status_id\n data['value'] = 0\n data['name'] = status\n status_id = status_id+1\n all_status.append(data)\n \n tickets_raised=0\n for data in ticket_count:\n ticket_status = filter(lambda status: status['name'] == data['status'], all_status)\n if ticket_status:\n ticket_status[0]['value'] = data['count']\n tickets_raised = tickets_raised + data['count']\n all_status.append({'id':status_id, 'name':'tickets_raised', 'value':tickets_raised}) \n return map(CustomApiObject, all_status)\n","sub_path":"src/gladminds/core/apis/dashboard_apis.py","file_name":"dashboard_apis.py","file_ext":"py","file_size_in_byte":18280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"238221734","text":"import sys\n#sys.path.append('C:\\\\Jacob\\\\pip')\nimport time\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nimport matplotlib\nmatplotlib.use('TKAgg')\nfrom matplotlib import pyplot\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import auc, roc_curve\nfrom sklearn import metrics, svm\nfrom sklearn.metrics import precision_recall_fscore_support\nimport pandas as pd\nfrom sklearn import preprocessing\nimport warnings\nwarnings.filterwarnings('ignore')\nimport ModelsFinal as m\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.callbacks import TensorBoard\n\n################################################################################\ndef dataProc(X1,y1):\n X1 = pd.DataFrame(X1)\n X1=X1.to_numpy()\n y1 = y1.to_numpy()\n \n \n min_max_scaler = preprocessing.MinMaxScaler()\n X1 = min_max_scaler.fit_transform(X1)\n \n X1, y1 = shuffle(X1, y1, random_state=0)\n return X1,y1\n\ndef plot_history(histories, key='acc'):\n plt.figure(figsize=(16,10))\n\n for name, history in histories:\n val = plt.plot(history.epoch, history.history['val_'+key],\n '--', label=name.title()+' Val')\n plt.plot(history.epoch, history.history[key], color=val[0].get_color(),\n label=name.title()+' Train')\n\n plt.xlabel('Epochs')\n plt.ylabel(key.replace('_',' ').title())\n plt.legend()\n\n plt.xlim([0,max(history.epoch)])\n return plt\n\n##################################################################################\nsysName = \"IEEE14\"\ntestType = \"MainModels\"\nnumEpochs = 100\ncheckpoint_path = \"Saved Models/\"+sysName+\"_models/\"\n\nX1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_40k_lowSparsity\"+\".csv\")\ny1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_40k_lowSparsity\"+\".csv\")\nX2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_40k_midSparsity\"+\".csv\")\ny2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_40k_midSparsity\"+\".csv\")\nX3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_40k_highSparsity\"+\".csv\")\ny3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_40k_highSparsity\"+\".csv\")\n\nXv1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_10k_lowSparsity\"+\".csv\")\nyv1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_10k_lowSparsity\"+\".csv\")\nXv2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_10k_midSparsity\"+\".csv\")\nyv2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_10k_midSparsity\"+\".csv\")\nXv3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_10k_highSparsity\"+\".csv\")\nyv3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_10k_highSparsity\"+\".csv\")\n\nXt1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_4k_lowSparsity\"+\".csv\")\nyt1 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_4k_lowSparsity\"+\".csv\")\nXt2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_4k_midSparsity\"+\".csv\")\nyt2 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_4k_midSparsity\"+\".csv\")\nXt3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Data_4k_highSparsity\"+\".csv\")\nyt3 = pd.read_csv(\"Data/\"+sysName+\"/\"+sysName+\"Labels_4k_highSparsity\"+\".csv\")\n\nX1,y1 = dataProc(X1,y1)\nXv1,yv1 = dataProc(Xv1,yv1)\nXt1,yt1 = dataProc(Xt1,yt1)\nX2,y2 = dataProc(X2,y2)\nXv2,yv2 = dataProc(Xv2,yv2)\nXt2,yt2 = dataProc(Xt2,yt2)\n\nX3,y3 = dataProc(X3,y3)\nXv3,yv3 = dataProc(Xv3,yv3)\nXt3,yt3 = dataProc(Xt3,yt3)\n\nnumFeatures = len(X1[0])\n\nX = np.concatenate((X1, X2, X3), axis=0)\ny = np.concatenate((y1, y2, y3), axis=0)\nXv = np.concatenate((Xv1, Xv2, Xv3), axis=0)\nyv = np.concatenate((yv1, yv2, yv3), axis=0)\nXt = np.concatenate((Xt1, Xt2, Xt3), axis=0)\nyt = np.concatenate((yt1, yt2, yt3), axis=0)\n\nX, y = shuffle(X, y, random_state=0)\nXv, yv = shuffle(Xv, yv, random_state=0)\nXt, yt = shuffle(Xt, yt, random_state=0)\n\n##########################################################################################################\n################################# Deep Learning ##################### \n#PROPOSED MODEL\nmodel1 = m.DLmodel1(numFeatures)\nLOGNAME = \"{}-model1-{}\".format(testType , int(time.time()) )\ntensorboard = TensorBoard(log_dir='logs\\{}'.format(LOGNAME))\nhistory1 = model1.fit(X,y,epochs=numEpochs ,batch_size=32,validation_data=(Xv,yv), callbacks = [tensorboard])\nresults11 = model1.evaluate(Xt1, yt1)\nresults12 = model1.evaluate(Xt2, yt2)\nresults13 = model1.evaluate(Xt3, yt3)\nmodel1.save(checkpoint_path+'model1.h5')\n\n#OTHER MODEL\nmodel2 = m.DLmodel2(numFeatures)\nLOGNAME = \"{}-model2-{}\".format(testType , int(time.time()) )\ntensorboard = TensorBoard(log_dir='logs\\{}'.format(LOGNAME))\nhistory2 = model2.fit(X,y,epochs=numEpochs ,batch_size=32,validation_data=(Xv,yv), callbacks = [tensorboard])\nresults21 = model2.evaluate(Xt1, yt1)\nresults22 = model2.evaluate(Xt2, yt2)\nresults23 = model2.evaluate(Xt3, yt3)\nmodel2.save(checkpoint_path+'model2.h5')\n\n#OTHER MODEL\nmodel3 = m.DLmodel3(numFeatures)\nLOGNAME = \"{}-model3-{}\".format(testType , int(time.time()) )\ntensorboard = TensorBoard(log_dir='logs\\{}'.format(LOGNAME))\nhistory3 = model3.fit(X,y,epochs=numEpochs ,batch_size=32,validation_data=(Xv,yv), callbacks = [tensorboard])\nresults31 = model3.evaluate(Xt1, yt1)\nresults32 = model3.evaluate(Xt2, yt2)\nresults33 = model3.evaluate(Xt3, yt3)\nmodel3.save(checkpoint_path+'model3.h5')\n################################ Final Data Processing #################################\nresults_low = [results11[1], results21[1], results31[1]]\nresults_mid = [results12[1], results22[1], results32[1]]\nresults_high = [results13[1], results23[1], results33[1]]\n\nnames = [ 'Model 1', \n 'Model 2',\n 'Model 3']\n\n################ DATA OUTPUT (Saving in Excel) ###############\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nwriter = pd.ExcelWriter('RESULTS_'+sysName+'_'+testType+'_'+str(numEpochs)+'Epochs.xlsx', engine='xlsxwriter') #CHANGE THE NAME OF THE OUTPUT EXCEL FILE HERE\n\nResults = pd.DataFrame({'Model': names, 'Low': results_low,'Mid': results_mid, 'High': results_high})\n\n# Convert the dataframe to an XlsxWriter Excel object.\nResults.to_excel(writer, sheet_name=sysName)\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n\nprint(\"PROGRAM IS COMPLETE !!!!! \")","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":6305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"298097283","text":"numbers = [1, 1]\nwhile numbers[-1] < 4000000:\n next_number = numbers[-1] + numbers[-2]\n numbers.append(next_number)\n\n\nsum_ = 0\nfor n in numbers:\n if n < 4000000:\n if n % 2 == 0:\n sum_ += n\nprint(sum_)","sub_path":"euler/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"361765156","text":"import sys\nimport io\nfrom htcanalyze import main as ht\n\n\nclass PseudoTTY(object):\n\n def __init__(self, underlying, isset):\n \"\"\"\n\n :param underlying:\n :param isset:\n \"\"\"\n self.__underlying = underlying\n self.__isset = isset\n\n def __getattr__(self, name):\n \"\"\"\n\n :param name:\n :return:\n \"\"\"\n return getattr(self.__underlying, name)\n\n def isatty(self):\n \"\"\"\n\n :return:\n \"\"\"\n return self.__isset\n\n\ncopy_sys_stdout = sys.stdout\ncopy_sys_stdin = sys.stdin\n\n\ndef reset():\n \"\"\"\n Reset sys.stdout and sys.stdin to default.\n\n Does not work with pytest.fixture, as pytest manipulates stdout\n \"\"\"\n sys.stdout = PseudoTTY(copy_sys_stdout, True)\n sys.stdin = PseudoTTY(copy_sys_stdin, True)\n\n\ndef test_no_input_and_no_output():\n reset()\n redirecting_stdout, reading_stdin, std_in = ht.check_for_redirection()\n assert redirecting_stdout is False\n assert reading_stdin is False\n assert std_in is None\n\n\ndef test_input_and_no_output():\n reset()\n normal_log_str = \"tests/test_logs/valid_logs/normal_log.log\"\n sys.stdin = io.StringIO(normal_log_str)\n redirecting_stdout, reading_stdin, std_in = ht.check_for_redirection()\n assert redirecting_stdout is False\n assert reading_stdin is True\n assert std_in == [normal_log_str]\n\n\ndef test_output_and_no_input():\n reset()\n sys.stdout = open('test_output.txt', 'w')\n redirecting_stdout, reading_stdin, std_in = ht.check_for_redirection()\n assert redirecting_stdout is True\n assert reading_stdin is False\n assert std_in is None\n\n\ndef test_input_and_output():\n reset()\n normal_log_str = \"tests/test_logs/valid_logs/normal_log.log\"\n sys.stdin = io.StringIO(normal_log_str)\n sys.stdout = open('test_output.txt', 'w')\n redirecting_stdout, reading_stdin, std_in = ht.check_for_redirection()\n assert redirecting_stdout is True\n assert reading_stdin is True\n assert std_in == [normal_log_str]\n","sub_path":"tests/redirection_test.py","file_name":"redirection_test.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"589143694","text":"import os\nfrom nltk.corpus import stopwords\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom collections import Counter\nimport pandas as pd\nimport numpy as np\nfrom nltk.tokenize import word_tokenize\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom collections import defaultdict\nfrom nltk.corpus import wordnet as nt\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import model_selection, naive_bayes, svm, linear_model\nfrom sklearn.metrics import accuracy_score\nimport pickle\n\ndef model(tk1, tk2, data_m):\n nb = linear_model.LogisticRegression(random_state=0, solver='lbfgs',multi_class='multinomial')\n nb.fit(tk1 ,data_m['Category'])\n pred = nb.predict(tk2)\n print(pred)\n return pred\n \n\ndef tknz(pathToModels,data_st):\n data_s = pd.DataFrame(data_st)\n\n data_m = pd.read_csv(pathToModels+'/Movie/movie_t.csv', encoding = 'utf-8')\n s = data_m['text_final']\n\n nt_arr = defaultdict(lambda : nt.NOUN)\n nt_arr['J'] = nt.ADJ\n nt_arr['V'] = nt.VERB\n nt_arr['R'] = nt.ADV\n\n data_s['Text'] = [entry.lower() for entry in data_s['Text']]\n data_s['Text']= [word_tokenize(entry) for entry in data_s['Text']]\n\n for index,entry in enumerate(data_s['Text']):\n proc_arr = []\n word_Lemmatized = WordNetLemmatizer()\n for word, tag in pos_tag(entry):\n if word not in stopwords.words('english') and word.isalpha():\n word_Final = word_Lemmatized.lemmatize(word,nt_arr[tag[0]])\n proc_arr.append(word_Final)\n s.loc[72] = str(proc_arr)\n\n print(s[72])\n\n Tf = TfidfVectorizer(max_features=5000)\n Tf.fit(data_m['text_final'][0:72])\n Train_X_tf = Tf.transform(data_m['text_final'][0:72])\n Test_X_tf = Tf.transform([s[72]])\n pred = model(Train_X_tf, Test_X_tf, data_m)\n return pred\n \n\ndef cral(pathToModels,bs_ob):\n text = bs_ob\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n dict = {'Text':[]}\n dict['Text'].append(text)\n return tknz(pathToModels,dict)\n\ndef fetch(url):\n brs = webdriver.Firefox()\n brs.get(url)\n resp = brs.page_source\n cral(resp)\n\n#fetch()\n","sub_path":"Compiled/Models_Helper_Server/Movie/movie_model_run.py","file_name":"movie_model_run.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"511780939","text":"# Copyright 2021-2022 NVIDIA Corporation\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# Copyright 2019 Ross Wightman\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\"\"\"\nExponential Moving Average (EMA) of model updates\n\"\"\"\n\nimport logging\nfrom copy import deepcopy\n\nimport torch\nimport torch.nn as nn\n\n_logger = logging.getLogger(__name__)\n\n\nclass ModelEmaV2(nn.Module):\n \"\"\" Model Exponential Moving Average V2\n\n Keep a moving average of everything in the model state_dict (parameters and buffers).\n V2 of this module is simpler, it does not match params/buffers based on name but simply\n iterates in order. It works with torchscript (JIT of full model).\n\n \"\"\"\n\n def __init__(self, model, decay=0.999, device=None):\n super(ModelEmaV2, self).__init__()\n # make a copy of the model for accumulating moving average of weights\n self.module = deepcopy(model)\n self.module.eval()\n self.decay = decay\n self.device = device # perform ema on different device from model if set\n if self.device is not None:\n self.module.to(device=device)\n\n def update(self, model):\n update_fn = lambda ema_v, model_v: self.decay * ema_v + (1.0 - self.decay) * model_v\n with torch.no_grad():\n for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()):\n if self.device is not None:\n model_v = model_v.to(device=self.device)\n ema_v.copy_(update_fn(ema_v, model_v))\n\n def set(self, model):\n with torch.no_grad():\n for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()):\n if self.device is not None:\n model_v = model_v.to(device=self.device)\n ema_v.copy_(model_v)\n\n def forward(self, x):\n return self.module(x)\n","sub_path":"Tools/PyTorch/TimeSeriesPredictionPlatform/training/ema.py","file_name":"ema.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"132135156","text":"import mcp\n\nio = mcp.MCP23017()\n\n# controls some output pins\noutPins = list(range(10,16))\nnextVals = {}\nfor pinNum in outPins:\n\tio.setup(pinNum, mcp.OUT)\n\tnextVals[pinNum] = True\nio.output_pins(nextVals)\n\n# monitors and prints some input pins\ninPins = list(range(0,10))\nfor pinNum in inPins:\n\tio.setup(pinNum, mcp.IN)\nwhile True:\n\tprint(io.input_pins(inPins))\n\t","sub_path":"MicroPython/ESP32/libraries/mcp/testMCP.py","file_name":"testMCP.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"441075006","text":"import logging\nimport math\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_instructions(inp):\n return [(x[0], int(x[1:])) for x in inp.split(\"\\n\")]\n\n\ndef normalize_angle(angle):\n return (angle % 360 + 360) % 360\n\n\ndef get_ship_distance_from_start(inp):\n instructions = parse_instructions(inp)\n position = [0, 0]\n orientation = 0 # East\n\n # First value of the tuple is the coordinate to modify, second value is the factor to multiply by\n basic_actions = {'N': (1, 1), 'S': (1, -1), 'E': (0, 1), 'W': (0, -1)}\n\n for action, value in instructions:\n logger.debug(f\"Action = {action}, value = {value}, current position = {position}, orientation = {orientation}\")\n\n if action in basic_actions:\n position[basic_actions[action][0]] += value * basic_actions[action][1]\n\n elif action == 'L':\n orientation = normalize_angle(orientation + value)\n\n elif action == 'R':\n orientation = normalize_angle(orientation - value)\n\n elif action == 'F':\n position[0] += value * round(math.cos(orientation * math.pi / 180))\n position[1] += value * round(math.sin(orientation * math.pi / 180))\n\n logger.debug(f\"Final position: {position}, final orientation: {orientation}\")\n return abs(position[0]) + abs(position[1])\n\n\ndef get_ship_distance_with_waypoint(inp):\n instructions = parse_instructions(inp)\n position = [0, 0]\n waypoint = [10, 1]\n\n basic_actions = {'N': (1, 1), 'S': (1, -1), 'E': (0, 1), 'W': (0, -1)}\n\n for action, value in instructions:\n logger.debug(f\"Action = {action}, value = {value}, position = {position}, waypoint = {waypoint}\")\n\n if action in basic_actions:\n waypoint[basic_actions[action][0]] += value * basic_actions[action][1]\n\n elif action == 'R':\n value = normalize_angle(value)\n\n if value == 90:\n waypoint = [waypoint[1], -waypoint[0]]\n elif value == 180:\n waypoint = [-waypoint[0], -waypoint[1]]\n elif value == 270:\n waypoint = [-waypoint[1], waypoint[0]]\n\n elif action == 'L':\n value = normalize_angle(value)\n\n if value == 270:\n waypoint = [waypoint[1], -waypoint[0]]\n elif value == 180:\n waypoint = [-waypoint[0], -waypoint[1]]\n elif value == 90:\n waypoint = [-waypoint[1], waypoint[0]]\n\n elif action == 'F':\n position[0] += value * waypoint[0]\n position[1] += value * waypoint[1]\n\n logger.debug(f\"Final position: {position}\")\n return abs(position[0]) + abs(position[1])\n","sub_path":"day12/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"20923870","text":"from res import id as id\nimport os\n\n\n# url\nurl = {\n id.price_action: 'https://api.bitfinex.com/v2/candles/trade:{}:t{}{}/hist?sort=1',\n}\n\n# strategy wise\nthree_black_crow = {\n id.window_size: 14,\n id.wick_percentage: 0.5\n}\n\ndouble_top_double_bottom = {\n id.window_size: 14,\n}\n\n# database\ndatabase = {\n id.db_url: os.getenv('database'),\n}\n\ncoinbase = [\n \"TRX_USD\",\n \"BTC_USD\",\n \"ETH_USD\",\n \"XRP_USD\",\n \"ETH_BTC\",\n \"XRP_BTC\",\n \"TRX_BTC\"\n\n ]\n\n\n\n","sub_path":"res/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"326114384","text":"import os\r\nimport sys\r\n\r\nimport input_gen, system_wrapper\r\nimport filecmp\r\n\r\ndef is_equals(file1_path,file2_path):\r\n with open(file1_path,'r') as file1:\r\n with open(file2_path,'r') as file2:\r\n lines1=file1.readlines()\r\n lines2=file2.readlines()\r\n\r\n if len(lines1)!=len(lines2):\r\n return False\r\n for i in range(len(lines1)):\r\n if lines1[i]!=lines2[i]:\r\n return False\r\n return True\r\n\r\nif __name__ == '__main__':\r\n print(\"Welcome to the automatic tester.\")\r\n NUMBER_OF_FILES = 100\r\n EXE_NAME=\"mtm_ex3.exe\"\r\n print(\"Creating input files.\")\r\n inputs = input_gen.run_input(NUMBER_OF_FILES)\r\n print(\"Input files created.\")\r\n\r\n outputs_valid = [\"io_files\\\\output_valid{}.txt\".format(i + 1) for i in range(NUMBER_OF_FILES)]\r\n outputs_test = [\"io_files\\\\output_test{}.txt\".format(i + 1) for i in range(NUMBER_OF_FILES)]\r\n print(\"Creating output files.\")\r\n\r\n for idx, input in enumerate(inputs):\r\n system_wrapper.run(input, outputs_valid[idx])\r\n os.system(\"{} {} > {}\".format(EXE_NAME,input, outputs_test[idx]))\r\n sys.stdout=sys.__stdout__\r\n print(\"Output files created... Now it the time to go to the bathroom...\")\r\n all_valid=True\r\n print(\"Comparing files - if files won't be equal, they would be printed.\")\r\n for i in range(len(outputs_valid)):\r\n is_valid=is_equals(outputs_valid[i],outputs_test[i])\r\n all_valid=all_valid and is_valid\r\n if (not is_valid):\r\n print(\"{} and {} are equals: {}\".format(outputs_valid[i],outputs_test[i],is_valid))\r\n if all_valid:\r\n print(\"Finished successfully.\")\r\n print(\"NO MORE MATAM FOR YOU! YIHI!\")\r\n print('(: prodk de lo rdrydw od hy prodkv prodkv')","sub_path":"parking_lot_tester/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"633683669","text":"from flask import Blueprint, jsonify, request\nfrom api.models import login_required, User, AccessLevel\nfrom api import mysql\nimport pymysql\n\n# all endpoint under schedule Blueprint share common url root of /schedule\nschedule = Blueprint('schedule', __name__)\n\n\n@schedule.route('/game/', methods = ['POST'])\n@login_required\ndef record_game(current_user):\n\treq = request.json\n\t\n\t#check access level\n\tif current_user.access is not AccessLevel.admin:\n\t\treturn jsonify({'message' : 'Invlaid access level, requires admin token'}), 401\n\tconn = mysql.connect()\n\tcursor = conn.cursor()\n\n\n\t#validate body, check all the games to make sure all the fields have been filled out\n\tfor i in range(0,len(req['games'])):\n\t\tif req['games'][i]['home'] is None:\n\t\t\treturn jsonify({'message' : 'The home team Id must be provided, error at index: ' + str(i)}), 400\n\t\tif req['games'][i]['away'] is None:\n\t\t\treturn jsonify({'message' : 'The away team Id must be provided, error at index: ' + str(i)}), 400\n\t\tif req['games'][i]['date'] is None:\n\t\t\treturn jsonify({'message' : 'The date of the game must be provided, error at index: ' + str(i)}), 400\n\t\tif req['games'][i]['location'] is None:\n\t\t\treturn jsonify({'message' : 'The location Id of the game must be provided, error at index: ' + str(i)}), 400\n\t\tif req['games'][i]['season'] is None:\n\t\t\treturn jsonify({'message' : 'The season Id for the teams must be provided, error at index: ' + str(i)}), 400\n\t\t\n\t#iterate through the games list\n\tfor i in range(0,len(req['games'])):\n\n\t\t#call stored procedure for each game\n\t\ttry:\n\t\t\tcursor.callproc('post_game_schedule',[req['games'][i]['home'], req['games'][i]['away'], req['games'][i]['date'], req['games'][i]['location'], req['games'][i]['season']])\n\t\texcept pymysql.MySQLError as err:\n\t\t\terrno = err.args[0]\n\t\t\tprint(f'Error number: {errno}')\n\t\t\t#get errors for if the body is invalid\n\t\t\tif errno == 1644:\n\t\t\t\treturn jsonify({'message' : err.args[1],\n\t\t\t\t\t\t\t\t'index': i }), 409\n\t\t\t\t\n\treturn jsonify({'message' : 'Updated the game schedule in the Data Base'}), 201\n\n\n@schedule.route('/referee/', methods = ['POST'])\n@login_required\ndef post_ref_schedule(current_user):\n\t# retrieve query string parameters from URL\n\tref_id = current_user.user_id\n\tgame_id = request.args.get('game_id', default = None, type = int)\n\n\t# error check: ensure that both ref_id and game_id are not null\n\tif (ref_id is None or game_id is None):\n\t\treturn jsonify({'message': 'The game_id must be provided'}), 400\n\n\t# error check: ensure that ref_id is indeed a referee\n\tif current_user.access is not AccessLevel.referee:\n\t\treturn jsonify({'message' : 'Invalid access level, needs a referee'}), 401\n\t\t\t\n\t# connects to the database\n\tconn = mysql.connect()\n\tcursor = conn.cursor()\n\n\t# calls for the update_ref_schedule procedure\n\ttry: \n\t\tcursor.callproc('post_ref_schedule',[ref_id, game_id])\n\texcept pymysql.MySQLError as err:\n\t\terrno = err.args[0]\n\t\tprint(f'Error number: {errno}')\n\t\tif errno == 1452: \n\t\t\treturn jsonify ({'message': 'game_id or referee_id does not exist'}), 400\n\t\tif errno == 1062: \n\t\t\treturn jsonify ({'message': 'That referee_id is already scheduled to that game_id'}), 400\n\t\t\n\treturn jsonify({'message': 'Successfully scheduled a referee to a game'}), 201 #created\n\n\n@schedule.route('/league/', methods=['GET'])\ndef get_league_schedule():\n\t# retrieve query string parameters from URL\n\tleague_id = request.args.get('leagueID', default = None, type = int)\n\tseason_id = request.args.get('seasonID', default = None, type = int)\n\t\n\n\t# error check: ensure that league_id is provided\n\tif league_id is None and season_id is None:\n\t\treturn jsonify({'message': 'The leagueID and seasonID must be provided'}), 400 #bad request\n\tif league_id is None:\n\t\treturn jsonify({'message': 'The leagueID must be provided'}), 400\n\tif season_id is None:\n\t\treturn jsonify({'message': 'The seasonID must be provided'}), 400\n\n\t# connect to sql database and call get_player_stat stored procedure\n\tconn = mysql.connect()\n\tcursor = conn.cursor()\n\t\n\t#make sure the request is valid\n\ttry:\n\t\tcursor.callproc('get_league_schedule', [league_id, season_id])\n\texcept pymysql.MySQLError as err:\n\t\terrno = err.args[0]\n\t\tprint(f'Error number: {errno}')\n\t\tif errno == 1644:\n\t\t\treturn jsonify ({'message': err.args[1]}), 400\n\t\tif errno == 1054:\n\t\t\treturn jsonify ({'message': 'No games scheduled for that League and Season'}), 400\n\n\tdata = cursor.fetchall()\n\n\t#make sure data is not empty\n\tif not data:\n\t\treturn jsonify({'message' : 'No games scheduled for that league and season'}), 404 #url not found\n\t\n\tgames_list = []\n\n\t#iterate through data and populate games_list\n\tfor i in range(0, len(data)):\n\t\titems = {\n\t\t\t'date_time':data[i][1],\n\t\t\t'away_team': {\n\t\t\t\t'team_id': data[i][2],\n\t\t\t\t'score': data[i][3]\n\t\t\t},\n\t\t\t'home_team': {\n\t\t\t\t'team_id': data[i][4],\n\t\t\t\t'score': data[i][5]\n\t\t\t},\n\t\t\t'game_id': data[i][6],\n\t\t\t'location': data[i][7]\n\t\t}\n\t\tgames_list.append(items)\n\t\n\t#create dictionary to be jsonified\n\tschedule_dict = {\n\t\t\"league_name\": data[0][0],\n\t\t\"games\": games_list\n\t}\n\t\n\treturn jsonify(schedule_dict), 200\n","sub_path":"api/schedule/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"329309750","text":"\"\"\"\nProblem Statement\nLet's consider an infinite sequence S of non-negative integers defined as follows:\n\nS0 = first;\nS1 = second;\nSi = |Si-2 - Si-1| for all i >= 2.\n\nYou will be given s first and second, representing the 0-th and the 1-st elements of the sequence S,\nand a indices, each element of which represents a non-negative integer without extra leading zeros.\nReturn a containing as many elements as indices, where the i-th element is equal to the indices[i]-th\nelement of the sequence S (index is 0-based). No element of the return should contain extra leading zeros.\n\nDefinition\nClass: AbsSequence\nMethod: getElements\nParameters: string, string, tuple (string)\nReturns: tuple (string)\nMethod signature: def getElements(self, first, second, indices):\nLimits\nTime limit (s): 840.000\nMemory limit (MB): 64\nConstraints\n- first will represent an integer between 0 and 10^18, inclusive, with no extra leading zeros.\n- second will represent an integer between 0 and 10^18, inclusive, with no extra leading zeros.\n- indices will contain between 1 and 50 elements, inclusive.\n- Each element of indices will represent an integer between 0 and 10^18, inclusive, with no extra leading zeros.\n\"\"\"\n\"\"\"\nExamples\n0)\n\"21\"\n\"12\"\n{\"0\", \"1\", \"2\", \"3\", \"4\"}\nReturns: {\"21\", \"12\", \"9\", \"3\", \"6\" }\nHere S0=21 and S1=12. \nThe next three sequence elements are \nS2 = |21 - 12| = 9, \nS3 = |12 - 9| = 3\nS4 = |9 - 3| = 6.\n1)\n\"0\"\n\"0\"\n{\"1000000000000000000\"}\nReturns: {\"0\" }\nHere we get the sequence consisting of only zeros.\n2)\n\"823\"\n\"470\"\n{\"3\",\"1\",\"31\",\"0\",\"8\",\"29\",\"57\",\"75\",\"8\",\"77\"}\ns3 = 823\ns1 = 470\nSi = |Si-2 - Si-1| \ns2 = |s0 - s1|\n\ns3 = s1 - s2 \nReturns: {\"117\", \"470\", \"2\", \"823\", \"115\", \"87\", \"49\", \"25\", \"115\", \"23\" }\n3)\n\"710370\"\n\"177300\"\n{\"5\",\"95\",\"164721\",\"418\",\"3387\",\"710\",\"0\",\"1197\",\"19507\",\"5848\"}\nReturns: {\"178470\", \"108270\", \"90\", \"0\", \"90\", \"90\", \"710370\", \"90\", \"0\", \"0\" }\n\"\"\"\n\n\nclass AbsSequence:\n def getElements(self, first, second, indices):\n s1 = int(first)\n s2 = int(second)\n\n res = []\n if s1 == s2:\n res.append(0)\n\n res.append(s1)\n res.append(s2)\n\n for idx in indices:\n index = int(idx)\n print(\"index = \", index)\n for i in range(len(res), index + 1):\n print(\"i = \", i)\n res.append(abs((int(res[i - 2]) - int(res[i - 1]))))\n idx = res[index]\n return res\n\n\nAS = AbsSequence()\n\ns1 = \"21\"\ns2 = \"12\"\nindices = (\"0\", \"1\", \"2\", \"3\", \"4\")\n\nAS.getElements(s1, s2, indices)\n\n# s1 = \"710370\"\n# s2 = \"177300\"\n# indices = {\"5\",\"95\",\"164721\",\"418\",\"3387\",\"710\",\"0\",\"1197\",\"19507\",\"5848\"}\n\ns1 = \"823\"\ns2 = \"470\"\nindices = {\"3\", \"1\", \"31\", \"0\", \"8\", \"29\", \"57\", \"75\", \"8\", \"77\"}\nprint(AS.getElements(s1, s2, indices))\n","sub_path":"TopCoder/AbcSequence.py","file_name":"AbcSequence.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"587607382","text":"from flask import Blueprint\nfrom flask import abort\nfrom flask import flash\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\n\nfrom application.controllers.form.engineer_form import EngineerForm\nfrom application.controllers.form.engineer_search_form import EngineerSearchForm\nfrom application.domain.model.engineer_skill import EngineerSkill\nfrom application.service.company_service import CompanyService\nfrom application.service.engineer_service import EngineerService\nfrom application.service.skill_service import SkillService\n\nbp = Blueprint('engineer', __name__, url_prefix='/engineer')\nservice = EngineerService()\ncompany_service = CompanyService()\nskill_service = SkillService()\n\n\n@bp.route('/', methods=['GET', 'POST'])\ndef index(page=1):\n form = EngineerSearchForm(request.values)\n form.company_id.choices = company_service.find_all_for_multi_select()\n form.skill_id.choices = skill_service.find_all_for_multi_select()\n\n pagination = service.find(page, form.engineer_name.data, form.company_id.data, form.skill_id.data)\n return render_template('engineer/index.html', pagination=pagination, form=form)\n\n\n@bp.route('/page/', methods=['GET', 'POST'])\ndef engineer_page(page=1):\n return index(page)\n\n\n@bp.route('/detail/', methods=['GET', 'POST'])\ndef detail(engineer_id=None):\n engineer = service.find_by_id(engineer_id)\n\n if engineer is None and engineer_id is not None:\n return abort(404)\n engineer.skill = [h.skill_id for h in engineer.engineer_skills]\n form = EngineerForm(request.form, engineer)\n form.company_id.choices = company_service.find_all_for_select()\n form.skill.choices = skill_service.find_all_for_multi_select()\n\n if form.validate_on_submit():\n engineer.start_date = form.start_date.data\n engineer.end_date = form.end_date.data\n engineer.engineer_name = form.engineer_name.data\n engineer.engineer_name_kana = form.engineer_name_kana.data\n engineer.company_id = form.company_id.data\n engineer.remarks = form.remarks.data\n skills = []\n for skill_id in form.skill.data:\n skills.extend([EngineerSkill(engineer.id, skill_id)])\n engineer.engineer_skills = skills\n\n service.save(engineer)\n flash('保存しました。')\n return redirect(url_for('.detail', engineer_id=engineer.id))\n return render_template('engineer/detail.html', form=form)\n\n\n@bp.route('/create', methods=['GET', 'POST'])\ndef create():\n return detail()\n\n\n@bp.route('/delete/', methods=['GET'])\ndef delete(engineer_id):\n engineer = service.find_by_id(engineer_id)\n if engineer is not None:\n service.destroy(engineer)\n flash('削除しました。')\n return redirect('/engineer')\n","sub_path":"application/controllers/engineer.py","file_name":"engineer.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"575587899","text":"# -*- coding:utf-8 -*-\n\"\"\"\nauthor: lijingxin\n\nCreated on 7:21 PM 3/24/20\n\n\"\"\"\n\nimport time\n#import matplotlib.pyplot as plt\nimport random\nimport math\n# matplotlib inline\n\ndef random_list(l):\n return [[int(1000*random.random()) for i in range(l * n)] for n in range(1, 20)]\n\n\ndef singing_score(values):\n start = time.time()\n small_pos = 0\n for i in range(1, len(values)):\n if values[i] < values[small_pos]:\n small_pos = i\n high_pos = 0\n for i in range(1, len(values)):\n if values[i] > values[high_pos]:\n high_pos = i\n values.remove(values[small_pos])\n values.remove(values[high_pos])\n score = sum(values) // len(values)\n t = time.time()\n return score, len(values), t\n\n\ndef singing_score2(values):\n start = time.time()\n maxx = values[0]\n minn = values[0]\n summ = values[0]\n for i in range(1, len(values)):\n if values[i] < minn:\n minn = values[i]\n if values[i] > minn:\n maxx = values[i]\n summ += values[i]\n\n rst = summ / (len(values) - 2)\n t = time.time() - start\n return rst, len(values), t\n\nvalues = [8,9,5,10,5,8,7,9,9.5]\nv = singing_score(values)\nprint(v)","sub_path":"Algorithm_PY/ch01/01_Ex2_SingContest.py","file_name":"01_Ex2_SingContest.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"92239846","text":"from distutils.core import setup\r\nfrom distutils.errors import DistutilsArgError\r\nfrom distutils.command.install import install\r\nimport os, shutil\r\n\r\npackage_name = 'tobii_calibration'\r\n\r\nclass OverriddenInstallCommand(install):\r\n user_options = install.user_options + [('lang=', None, 'specify the language')]\r\n def initialize_options(self):\r\n install.initialize_options(self)\r\n self.lang = None\r\n def finalize_options(self):\r\n install.finalize_options(self)\r\n if self.lang not in (None, 'hu'):\r\n raise DistutilsArgError(\"Only 'hu' language is allowed.\")\r\n def run(self):\r\n # install localization files\r\n if self.lang == 'hu':\r\n source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"locales\", \"hu\", \"LC_MESSAGES\")\r\n target_dir = os.path.join(self.install_lib, package_name, \"locales\", \"hu\", \"LC_MESSAGES\")\r\n if not os.path.isdir(target_dir):\r\n os.makedirs(target_dir)\r\n shutil.copyfile(os.path.join(source_dir, \"all_strings.mo\"), os.path.join(target_dir, \"all_strings.mo\"))\r\n else:\r\n target_dir = os.path.join(self.install_lib, package_name, \"locales\")\r\n if os.path.isdir(target_dir):\r\n shutil.rmtree(target_dir)\r\n\r\n install.run(self)\r\n\r\nsetup(\r\n name=package_name,\r\n version='0.1',\r\n author='Tamás Zolnai, Olivia Guayasamin',\r\n author_email='zolnaitamas2000@gmail.com, oguayasa@gmail.com',\r\n packages=['tobii_calibration'],\r\n cmdclass={'install': OverriddenInstallCommand},\r\n url='https://github.com/tzolnai/tobii_calibration',\r\n license='LICENSE.txt',\r\n description='Calibration module for Tobii Pro SDK',\r\n long_description='README.md',\r\n install_requires=[\r\n 'numpy',\r\n 'psychopy',\r\n 'pyglet',\r\n 'tobii_research',\r\n ],\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"242353247","text":"# pylint: disable=line-too-long\nimport utils\nimport utils.handlers\n\n\ndef handler(event, context) -> utils.Response:\n \"\"\"lambda entry point\"\"\"\n return utils.handlers.EventHandler(\n name=\"linkedin\",\n event=utils.LambdaEvent(event),\n context=utils.LambdaContext(context),\n action=lambda x: NotImplementedError(\n \"LinkedIn Oauth client credentials (2-legged) flow not available anymore: \"\n \"https://docs.microsoft.com/en-us/linkedin/shared/authentication/client-credentials-flow\")\n ).response\n","sub_path":"lib/stacks/publish_to_social/lambda/services/linkedin.py","file_name":"linkedin.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"340332441","text":"import numpy as np\nfrom mock import Mock\n\nfrom model import Colors\n\n\nclass ColorsT(Colors):\n def __init__(self, vals):\n flatten_list = [item for sublist in vals for item in sublist]\n super(ColorsT, self).__init__(N=max(flatten_list)+1, domain_factory=Mock)\n self._vals = vals\n\n\nclass ColorsTestable:\n good_vals = np.array([[1, 2, 3, 4, 5],\n [2, 3, 4, 5, 1],\n [3, 4, 5, 1, 2],\n [4, 5, 1, 2, 3],\n [5, 1, 2, 3, 4]])\n\n bad_vals = np.array([[1, 3, 5, 2, 4],\n [2, 5, 1, 3, 4],\n [3, 4, 2, 1, 5],\n [5, 1, 4, 2, 3],\n [4, 2, 3, 5, 1]])\n\n simple_vals = np.array([[1, 2],\n [3, 4]])\n\n @classmethod\n def get_color(cls, name):\n colors = ColorsT\n if name == 'correct':\n return colors(cls.good_vals)\n elif name == 'incorrect':\n return colors(cls.bad_vals)\n elif name == 'simple':\n return colors(cls.simple_vals)\n raise ValueError('There is no defined object for {}'.format(name))\n\n","sub_path":"zad_02/tests/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"257258172","text":"import json\n\nimport pytest\n\nfrom rest_framework.test import APIClient, APITestCase\n\nfrom sea_battle import constants\nfrom sea_battle.models import Game, BattleMap\nfrom sea_battle.tests.factories import UserFactory, ActiveGameFactory, GameFactory\n\n\n@pytest.mark.django_db\nclass TestWatchGamesAPIViewSet(APITestCase):\n\n \"\"\"check, if list of active games is provided\n for authenticated users and forbidden for anonymous\"\"\"\n\n def test_list_active_games(self):\n\n test_user = UserFactory()\n client = APIClient()\n\n ActiveGameFactory()\n ActiveGameFactory()\n ActiveGameFactory()\n\n GameFactory()\n\n response = client.get('/rest/games-for-watching/')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n response = client.get('/rest/games-for-watching/')\n\n self.assertEqual(len(response.data), 3)\n assert response.status_code == 200\n\n\nclass TestGamesAPIViewSet(APITestCase):\n\n def test_list(self):\n\n \"\"\"check, if list of available games is provided\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n ActiveGameFactory()\n ActiveGameFactory()\n ActiveGameFactory()\n\n GameFactory()\n\n response = client.get('/rest/games/')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n response = client.get('/rest/games/')\n print(response.data)\n\n self.assertEqual(len(response.data), 1)\n assert response.status_code == 200\n\n def test_create(self):\n\n \"\"\"check, if game can be created\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n data = {\n 'name': 'name',\n 'size': 10,\n 'fleet': [\n [5, 1], [3, 1], [4, 1], [2, 1],\n [4, 4], [3, 4], [3, 6], [3, 8],\n [3, 10], [5, 6], [6, 6], [6, 10],\n [7, 3], [7, 2], [7, 1], [8, 8],\n [7, 8], [9, 5], [9, 3], [9, 4]\n ],\n 'user': test_user.username\n }\n\n response = client.post('/rest/games/', data, format='json')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n response = client.post('/rest/games/', data, format='json')\n self.assertEqual(10, len(BattleMap.objects.get(user=test_user).fleet))\n assert response.status_code == 201\n\n def test_shoot(self):\n\n \"\"\"check, if shoot is being handled properly\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n game = ActiveGameFactory(\n creator=test_user,\n turn=test_user,\n size=10\n )\n enemy_map = BattleMap.objects.get(user=game.joiner, game=game)\n enemy_map.fleet = [\n [[5, 1], [3, 1], [4, 1], [2, 1]],\n [[4, 4], [3, 4]],\n [[3, 6]],\n [[3, 8]],\n [[3, 10]],\n [[5, 6], [6, 6]],\n [[6, 10]],\n [[7, 3], [7, 2], [7, 1]],\n [[8, 8], [7, 8]],\n [[9, 5], [9, 3], [9, 4]]\n ]\n enemy_map.save()\n\n data = {\n 'shoot': [5, 1],\n }\n\n url = '/rest/games/' + str(game.pk) + '/shoot/'\n\n response = client.patch(url, data, format='json')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n\n response = client.patch(url, data, format='json')\n resp_assert = {\n 'state': constants.ACTIVE,\n 'shoot': constants.SHOOT_RESULT_HIT,\n 'dead_zone': [],\n 'dead_ship': []\n }\n self.assertEqual(resp_assert, json.loads(response.content))\n assert response.status_code == 200\n\n def test_join(self):\n\n \"\"\"check, if joining is being handled properly\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n game = GameFactory()\n\n url = '/rest/games/' + str(game.pk) + '/join/'\n\n data = {\n 'game_id': game.pk,\n 'user_id': test_user.id\n }\n\n response = client.post(url, data, format='json')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n\n response = client.post(url, data, format='json')\n self.assertEqual(test_user, Game.objects.get(pk=game.pk).joiner)\n assert response.status_code == 202\n\n url = '/rest/games/' + str(game.pk*2) + '/join/'\n response = client.post(url, data, format='json')\n\n assert response.status_code == 406\n\n def test_join_fleet(self):\n\n \"\"\"check, if joining_fleet is being handled properly\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n game = GameFactory(joiner=test_user)\n\n url = '/rest/games/' + str(game.pk) + '/join_fleet/'\n\n data = {\n 'size': game.size,\n 'fleet': [\n [5, 1], [3, 1], [4, 1], [2, 1],\n [4, 4], [3, 4], [3, 6], [3, 8],\n [3, 10], [5, 6], [6, 6], [6, 10],\n [7, 3], [7, 2], [7, 1], [8, 8],\n [7, 8], [9, 5], [9, 3], [9, 4]\n ]\n }\n\n response = client.post(url, data, format='json')\n assert response.status_code == 401\n\n client.force_authenticate(user=test_user)\n\n response = client.post(url, data, format='json')\n assert response.status_code == 201\n\n def test_state(self):\n\n \"\"\"check, if state is being retrieved\n for authenticated users and forbidden for anonymous\"\"\"\n\n test_user = UserFactory()\n client = APIClient()\n\n game = ActiveGameFactory(joiner=test_user)\n j_battlemap = BattleMap.objects.get(game=game, user=game.joiner)\n j_battlemap.shoots = [[8, 9], [4, 3]]\n c_battlemap = BattleMap.objects.get(game=game, user=game.creator)\n c_battlemap.shoots = [[1, 1], [6, 5]]\n c_battlemap.fleet = [\n [[5, 1], [3, 1], [4, 1], [2, 1]],\n [[4, 4], [3, 4]],\n [[3, 6]],\n [[3, 8]],\n [[3, 10]],\n [[5, 6], [6, 6]],\n [[6, 10]],\n [[7, 3], [7, 2], [7, 1]],\n [[8, 8], [7, 8]],\n [[9, 5], [9, 3], [9, 4]]\n ]\n j_battlemap.fleet = c_battlemap.fleet\n c_battlemap.save()\n j_battlemap.save()\n\n url = '/rest/games/' + str(game.pk) + '/state/'\n\n response = client.get(url)\n assert response.status_code == 401\n\n client.force_authenticate(user=game.creator)\n\n response = client.get(url)\n resp_assert = {\n 'state': constants.ACTIVE,\n 'shoots_of_enemy': [[8, 9, \"miss\"], [4, 3, \"miss\"]],\n \"my_dead_zone\": [],\n \"joiner\": test_user.username,\n \"turn\": game.creator.username,\n }\n self.assertEqual(resp_assert, json.loads(response.content))\n assert response.status_code == 200\n\n\n@pytest.mark.django_db\nclass TestRegisterFormAPIViewSet(APITestCase):\n\n \"\"\"check, if list of active games is provided\n for authenticated users and forbidden for anonymous\"\"\"\n\n def test_create(self):\n\n client = APIClient()\n\n data = json.dumps({\"username\": \"test\", \"password\": \"test123\"})\n\n response = client.post('/rest/signup/', data=data, content_type='application/json')\n\n assert response.status_code == 201\n","sub_path":"sea_battle/api/tests/test_api_views.py","file_name":"test_api_views.py","file_ext":"py","file_size_in_byte":7711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"356439057","text":"import inspect\nimport json\nimport os\nimport pathlib\nimport re\nimport textwrap\nimport time\nimport traceback\n\nfrom copy import deepcopy\nfrom functools import wraps\n\nfrom scitrack import CachingLogger\n\nfrom cogent3 import make_aligned_seqs, make_unaligned_seqs\nfrom cogent3.core.alignment import SequenceCollection\nfrom cogent3.util import parallel as PAR\nfrom cogent3.util import progress_display as UI\nfrom cogent3.util.io import open_\nfrom cogent3.util.misc import (\n extend_docstring_from,\n get_object_provenance,\n in_jupyter,\n)\n\nfrom .data_store import (\n IGNORE,\n OVERWRITE,\n RAISE,\n SKIP,\n DataStoreMember,\n WritableDirectoryDataStore,\n get_data_source,\n)\n\n\n__author__ = \"Gavin Huttley\"\n__copyright__ = \"Copyright 2007-2022, The Cogent Project\"\n__credits__ = [\"Gavin Huttley\"]\n__license__ = \"BSD-3\"\n__version__ = \"2022.8.24a1\"\n__maintainer__ = \"Gavin Huttley\"\n__email__ = \"Gavin.Huttley@anu.edu.au\"\n__status__ = \"Alpha\"\n\nfrom ..util.warning import discontinued\n\n\ndef _make_logfile_name(process):\n text = str(process)\n text = re.split(r\"\\s+\\+\\s+\", text)\n parts = [part[: part.find(\"(\")] for part in text]\n result = \"-\".join(parts)\n pid = os.getpid()\n result = f\"{result}-pid{pid}.log\"\n return result\n\n\ndef _get_origin(origin):\n return origin if type(origin) == str else origin.__class__.__name__\n\n\nclass NotCompleted(int):\n \"\"\"results that failed to complete\"\"\"\n\n def __new__(cls, type, origin, message, source=None):\n \"\"\"\n Parameters\n ----------\n type : str\n examples are 'ERROR', 'FAIL'\n origin\n where the instance was created, can be an instance\n message : str\n descriptive message, succinct traceback\n source : str or instance with .info.source or .source attributes\n the data operated on that led to this result. Can\n \"\"\"\n # todo this approach to caching persistent arguments for reconstruction\n # is fragile. Need an inspect module based approach\n origin = _get_origin(origin)\n source = get_data_source(source)\n d = locals()\n d = {k: v for k, v in d.items() if k != \"cls\"}\n result = int.__new__(cls, False)\n args = tuple(d.pop(v) for v in (\"type\", \"origin\", \"message\"))\n result._persistent = args, d\n\n result.type = type\n result.origin = origin\n result.message = message\n result.source = source\n return result\n\n def __getnewargs_ex__(self, *args, **kw):\n return self._persistent[0], self._persistent[1]\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n name = self.__class__.__name__\n source = self.source or \"Unknown\"\n val = (\n f\"{name}(type={self.type}, origin={self.origin}, \"\n f'source=\"{source}\", message=\"{self.message}\")'\n )\n return val\n\n def to_rich_dict(self):\n \"\"\"returns components for to_json\"\"\"\n return {\n \"type\": get_object_provenance(self),\n \"not_completed_construction\": dict(\n args=self._persistent[0], kwargs=self._persistent[1]\n ),\n \"version\": __version__,\n }\n\n def to_json(self):\n \"\"\"returns json string\"\"\"\n return json.dumps(self.to_rich_dict())\n\n\nALIGNED_TYPE = \"aligned\"\nIDENTIFIER_TYPE = \"identifier\"\nPAIRWISE_DISTANCE_TYPE = \"pairwise_distances\"\nSEQUENCE_TYPE = \"sequences\"\nSERIALISABLE_TYPE = \"serialisable\"\nTABULAR_TYPE = \"tabular\"\nTREE_TYPE = \"tree\"\n\nBOOTSTRAP_RESULT_TYPE = \"bootstrap_result\"\nHYPOTHESIS_RESULT_TYPE = \"hypothesis_result\"\nMODEL_RESULT_TYPE = \"model_result\"\nRESULT_TYPE = \"result\"\nTABULAR_RESULT_TYPE = \"tabular_result\"\n\n\nclass ComposableType:\n _type = None\n\n def __init__(self, input_types=None, output_types=None, data_types=None):\n \"\"\"\n Parameters\n ----------\n input_types : str or collection of str\n Allowed input types\n output_types : str or collection of str\n Types of output\n data_types : str or collection of str\n Allowed data types\n \"\"\"\n from cogent3.util.misc import get_object_provenance\n\n input_types = [] if input_types is None else input_types\n output_types = [] if output_types is None else output_types\n data_types = [] if data_types is None else data_types\n\n if type(input_types) == str:\n input_types = [input_types]\n if type(output_types) == str:\n output_types = [output_types]\n if type(data_types) == str:\n data_types = [data_types]\n\n self._input_types = frozenset(input_types)\n self._output_types = frozenset(output_types)\n self._data_types = frozenset(data_types)\n prov = get_object_provenance(self)\n if not prov.startswith(\"cogent3\"):\n from warnings import catch_warnings, simplefilter\n from warnings import warn as _warn\n\n # we have a 3rd party composable\n msg = (\n \"Defining composable apps by inheriting from Composable is \"\n \"deprecated and will be removed in release 2022.11. This \"\n \"will be a backwards incompatible change! We are moving to a\"\n \" decorator for defining composable apps. For instructions \"\n f\" on porting {prov!r} see\"\n \" https://github.com/cogent3/cogent3/wiki/composable-functions\"\n )\n with catch_warnings():\n simplefilter(\"always\")\n _warn(msg, DeprecationWarning, 1)\n\n def compatible_input(self, other):\n result = other._output_types & self._input_types\n return result != set()\n\n def _validate_data_type(self, data):\n \"\"\"checks data class name matches defined compatible types\"\"\"\n if not self._data_types:\n # not defined\n return True\n\n name = data.__class__.__name__\n valid = name in self._data_types\n if not valid:\n msg = f\"invalid data type, '{name}' not in {', '.join(self._data_types)}\"\n valid = NotCompleted(\"ERROR\", self, message=msg, source=data)\n return valid\n\n\nclass Composable(ComposableType):\n def __init__(self, **kwargs):\n super(Composable, self).__init__(**kwargs)\n # self.func = None # over-ride in subclass\n self._in = None # input rules\n self._out = None # rules receiving output\n # rules operating on result but not part of a chain\n self._checkpointable = False\n self._load_checkpoint = None\n self._formatted = [f\"type='{self._type}'\"]\n\n def __str__(self):\n txt = \"\" if not self.input else str(self.input)\n if txt:\n txt += \" + \"\n txt += f\"{self.__class__.__name__}({', '.join(self._formatted)})\"\n txt = textwrap.fill(\n txt, width=80, break_long_words=False, break_on_hyphens=False\n )\n return txt\n\n def __repr__(self):\n return str(self)\n\n def _formatted_params(self):\n stack = inspect.stack()\n stack.reverse()\n for level in stack:\n args = inspect.getargvalues(level.frame).locals\n klass = args.get(\"__class__\", None)\n if klass and isinstance(self, klass):\n break\n args = inspect.getargvalues(level.frame).locals\n params = inspect.signature(args[\"__class__\"].__init__).parameters\n formatted = []\n for p in params:\n if p == \"self\":\n continue\n try:\n v = args[p]\n except KeyError:\n continue\n try:\n v = v.name\n except AttributeError:\n pass\n\n if in_jupyter():\n if p == \"kwargs\" and v == {\"store_history\": True, \"silent\": False}:\n continue\n formatted.append(f\"{p}={v!r}\")\n self._formatted += formatted\n\n def __add__(self, other):\n if other is self:\n raise ValueError(\"cannot add an app to itself\")\n\n if self.output or other.input:\n # can only be part of a single composable function\n self_name = self.__class__.__name__\n other_name = other.__class__.__name__\n if self.output and other.input:\n msg = (\n f\"{self_name} and {other_name} are already part of a\"\n \" composed function\"\n )\n elif self.output:\n msg = f\"{self_name} already part of composed function\"\n else:\n msg = f\"{other_name} already part of composed function\"\n raise AssertionError(f\"{msg}, use disconnect() to free them up\")\n\n if not other.compatible_input(self):\n msg = '%s() requires input type \"%s\", %s() produces \"%s\"'\n my_name = self.__class__.__name__\n my_output = self._output_types\n their_name = other.__class__.__name__\n their_input = other._input_types\n msg = msg % (their_name, their_input, my_name, my_output)\n raise TypeError(msg)\n self.output = other\n other.input = self\n return other\n\n def _set_checkpoint_loader(self):\n # over-ride in subclasses that are checkpointable\n self._load_checkpoint = None\n\n def _make_output_identifier(self, data):\n # over-ride in subclasses that are checkpointable\n pass\n\n @property\n def checkpointable(self):\n \"\"\"whether this function is checkpointable\"\"\"\n return self._checkpointable\n\n def job_done(self, *args, **kwargs):\n # over-ride in sub classes\n return False\n\n def _trapped_call(self, func, val, *args, **kwargs):\n valid = self._validate_data_type(val)\n if not valid:\n return valid\n try:\n val = func(val, *args, **kwargs)\n except Exception:\n val = NotCompleted(\"ERROR\", self, traceback.format_exc(), source=val)\n return val\n\n def __call__(self, val, *args, **kwargs):\n # initial invocation always transfers call() to first composable\n # element to get input for self\n refobj = kwargs.get(\"identifier\", val)\n if not val:\n return val\n\n if self.checkpointable:\n job_done = self.job_done(refobj)\n if job_done and self.output:\n result = self._load_checkpoint(refobj)\n elif job_done:\n result = self._make_output_identifier(refobj)\n\n if job_done:\n return result\n\n if self.input:\n val = self._in(val, *args, **kwargs)\n\n if not val:\n return val\n result = self._trapped_call(self.func, val, *args, **kwargs)\n if not result and type(result) != NotCompleted:\n msg = (\n f\"The value {result} equates to False. \"\n \"If unexpected, please post this error message along\"\n f\" with the code and data '{val}' as an Issue on the\"\n \" github project page.\"\n )\n origin = str(self)\n result = NotCompleted(\"BUG\", origin, msg, source=val)\n\n return result\n\n @property\n def input(self):\n return self._in\n\n @input.setter\n def input(self, other):\n self._in = other\n\n @property\n def output(self):\n return self._out\n\n @output.setter\n def output(self, other):\n self._out = other\n self._set_checkpoint_loader()\n\n def disconnect(self):\n \"\"\"resets input and output to None\n\n Breaks all connections among members of a composed function.\"\"\"\n input = self.input\n if input:\n input.disconnect()\n\n self._in = None\n self._out = None\n self._load_checkpoint = None\n\n @UI.display_wrap\n def apply_to(\n self,\n dstore,\n parallel=False,\n par_kw=None,\n logger=None,\n cleanup=False,\n ui=None,\n **kwargs,\n ):\n \"\"\"invokes self composable function on the provided data store\n\n Parameters\n ----------\n dstore\n a path, list of paths, or DataStore to which the process will be\n applied.\n parallel : bool\n run in parallel, according to arguments in par_kwargs. If True,\n the last step of the composable function serves as the master\n process, with earlier steps being executed in parallel for each\n member of dstore.\n par_kw\n dict of values for configuring parallel execution.\n logger\n Argument ignored if not an io.writer. If a scitrack logger not provided,\n one is created with a name that defaults to the composable function names\n and the process ID.\n cleanup : bool\n after copying of log files into the data store, it is deleted\n from the original location\n\n Returns\n -------\n Result of the process as a list\n\n Notes\n -----\n If run in parallel, this instance serves as the master object and\n aggregates results.\n \"\"\"\n if \"mininterval\" in kwargs:\n discontinued(\"argument\", \"mininterval\", \"2022.10\", stack_level=1)\n\n if isinstance(dstore, str):\n dstore = [dstore]\n\n dstore = [e for e in dstore if e]\n if not dstore:\n raise ValueError(\"dstore is empty\")\n\n am_writer = hasattr(self, \"data_store\")\n if am_writer:\n start = time.time()\n if logger is None:\n logger = CachingLogger()\n elif not isinstance(logger, CachingLogger):\n raise TypeError(\n f\"logger must be scitrack.CachingLogger, not {type(logger)}\"\n )\n\n if not logger.log_file_path:\n src = pathlib.Path(self.data_store.source)\n logger.log_file_path = str(src.parent / _make_logfile_name(self))\n\n log_file_path = str(logger.log_file_path)\n logger.log_message(str(self), label=\"composable function\")\n logger.log_versions([\"cogent3\"])\n\n results = []\n process = self.input or self\n if self.input:\n # As we will be explicitly calling the input object, we disconnect\n # the two-way interaction between input and self. This means self\n # is not called twice, and self is not unecessarily pickled during\n # parallel execution.\n process.output = None\n self.input = None\n\n # with a tinydb dstore, this also excludes data that failed to complete\n # todo update to consider different database backends\n # we want a dict mapping input member names to their md5 sums so these can\n # be logged\n inputs = {}\n for m in dstore:\n input_id = pathlib.Path(\n m if isinstance(m, DataStoreMember) else get_data_source(m)\n )\n suffixes = input_id.suffixes\n input_id = input_id.name.replace(\"\".join(suffixes), \"\")\n inputs[input_id] = m\n\n if len(inputs) < len(dstore):\n diff = len(dstore) - len(inputs)\n raise ValueError(\n f\"could not construct unique identifiers for {diff} records, \"\n \"avoid using '.' as a delimiter in names.\"\n )\n\n if parallel:\n par_kw = par_kw or {}\n to_do = PAR.as_completed(process, inputs.values(), **par_kw)\n else:\n to_do = map(process, inputs.values())\n\n for result in ui.series(to_do, count=len(inputs)):\n if process is not self and am_writer:\n # if result is NotCompleted, it will be written as incomplete\n # by data store backend. The outcome is just the\n # associated db identifier for tracking steps below we need to\n # know it's NotCompleted.\n # Note: we directly call .write() so NotCompleted's don't\n # get blocked from being written by __call__()\n outcome = self.write(data=result)\n if result and isinstance(outcome, DataStoreMember):\n input_id = outcome.name\n else:\n input_id = get_data_source(result)\n outcome = result\n input_id = pathlib.Path(pathlib.Path(input_id))\n suffixes = input_id.suffixes\n input_id = input_id.name.replace(\"\".join(suffixes), \"\")\n elif process is not self:\n outcome = self(result)\n else:\n outcome = result\n\n results.append(outcome)\n\n if am_writer:\n # now need to search for the source member\n m = inputs[input_id]\n input_md5 = getattr(m, \"md5\", None)\n logger.log_message(input_id, label=\"input\")\n if input_md5:\n logger.log_message(input_md5, label=\"input md5sum\")\n\n if isinstance(outcome, NotCompleted):\n # log error/fail details\n logger.log_message(\n f\"{outcome.origin} : {outcome.message}\", label=outcome.type\n )\n continue\n elif not outcome:\n # other cases where outcome is Falsy (e.g. None)\n logger.log_message(f\"unexpected value {outcome!r}\", label=\"FAIL\")\n continue\n\n logger.log_message(outcome, label=\"output\")\n logger.log_message(outcome.md5, label=\"output md5sum\")\n\n if am_writer:\n finish = time.time()\n taken = finish - start\n\n logger.log_message(f\"{taken}\", label=\"TIME TAKEN\")\n logger.shutdown()\n self.data_store.add_file(log_file_path, cleanup=cleanup, keep_suffix=True)\n self.data_store.close()\n\n # now reconnect input\n if process is not self:\n self = process + self\n\n return results\n\n\nclass ComposableTabular(Composable):\n _type = \"tabular\"\n\n def __init__(self, **kwargs):\n super(ComposableTabular, self).__init__(**kwargs)\n\n\nclass ComposableSeq(Composable):\n\n _type = \"sequences\"\n\n def __init__(self, **kwargs):\n super(ComposableSeq, self).__init__(**kwargs)\n\n\nclass ComposableAligned(Composable):\n _type = \"aligned\"\n\n def __init__(self, **kwargs):\n super(ComposableAligned, self).__init__(**kwargs)\n\n\nclass ComposableTree(Composable):\n _type = \"tree\"\n\n def __init__(self, **kwargs):\n super(ComposableTree, self).__init__(**kwargs)\n\n\nclass ComposableModel(Composable):\n _type = \"model\"\n\n def __init__(self, **kwargs):\n super(ComposableModel, self).__init__(**kwargs)\n\n\nclass ComposableHypothesis(Composable):\n _type = \"hypothesis\"\n\n def __init__(self, **kwargs):\n super(ComposableHypothesis, self).__init__(**kwargs)\n\n\nclass ComposableDistance(Composable):\n _type = \"distance\"\n\n def __init__(self, **kwargs):\n super(ComposableDistance, self).__init__(**kwargs)\n\n\nclass _seq_loader:\n def load(self, data):\n \"\"\"returns sequences\n\n Parameters\n ----------\n data\n file path or cogent3 sequence collection / alignment\n \"\"\"\n if type(data) == str:\n with open_(data) as infile:\n data = dict(record for record in self._parser(infile))\n seqs = self.klass(data=data, moltype=self.moltype)\n seqs.info.path = data\n elif not isinstance(data, SequenceCollection):\n if self.aligned:\n seqs = make_aligned_seqs(data, moltype=self.moltype)\n else:\n seqs = make_unaligned_seqs(data, moltype=self.moltype)\n\n if not (self._output_types & {\"aligned\"}):\n seqs = seqs.degap()\n\n return seqs\n\n\nclass _checkpointable(Composable):\n def __init__(\n self,\n data_path,\n name_callback=None,\n create=False,\n if_exists=SKIP,\n suffix=None,\n writer_class=None,\n **kwargs,\n ):\n \"\"\"\n Parameters\n ----------\n data_path\n path to write output\n name_callback\n function that takes the data object and returns a base\n file name\n create : bool\n whether to create the data_path reference\n if_exists : str\n behaviour if output exists. Either 'skip', 'raise' (raises an\n exception), 'overwrite', 'ignore'\n writer_class : type\n constructor for writer\n \"\"\"\n super(_checkpointable, self).__init__(**kwargs)\n self._formatted_params()\n\n data_path = str(data_path)\n\n if data_path.endswith(\".tinydb\") and not self.__class__.__name__.endswith(\"db\"):\n raise ValueError(\"tinydb suffix reserved for write_db\")\n\n self._checkpointable = True\n if_exists = if_exists.lower()\n assert if_exists in (\n SKIP,\n IGNORE,\n RAISE,\n OVERWRITE,\n ), \"invalid value for if_exists\"\n self._if_exists = if_exists\n\n klass = writer_class or WritableDirectoryDataStore\n self.data_store = klass(\n data_path, suffix=suffix, create=create, if_exists=if_exists\n )\n self._callback = name_callback\n self.func = self.write\n\n # override the following in subclasses\n self._format = None\n self._formatter = None\n self._load_checkpoint = None\n\n def _make_output_identifier(self, data):\n if self._callback:\n data = self._callback(data)\n\n return self.data_store.make_absolute_identifier(data)\n\n def job_done(self, data):\n identifier = self._make_output_identifier(data)\n exists = identifier in self.data_store\n if exists and self._if_exists == RAISE:\n msg = f\"'{identifier}' already exists\"\n raise RuntimeError(msg)\n\n if self._if_exists == OVERWRITE:\n exists = False\n return exists\n\n def write(self, data) -> DataStoreMember:\n # over-ride in subclass\n raise NotImplementedError\n\n\nclass user_function(Composable):\n \"\"\"wrapper class for user specified function\"\"\"\n\n _type = \"function\"\n\n @extend_docstring_from(ComposableType.__init__, pre=False)\n def __init__(\n self, func, input_types, output_types, *args, data_types=None, **kwargs\n ):\n \"\"\"\n func : callable\n user specified function\n *args\n positional arguments to append to incoming values prior to calling\n func\n **kwargs\n keyword arguments to include when calling func\n\n Notes\n -----\n Known types are defined as constants in ``cogent3.app.composable``, e.g.\n ALIGNED_TYPE, SERIALISABLE_TYPE, RESULT_TYPE.\n\n If you create a function ``foo(arg1, arg2, kwarg1=False)``. You can\n turn this into a user function, e.g.\n\n >>> ufunc = user_function(foo, in_types, out_types, arg1val, kwarg1=True)\n\n Then\n\n >>> ufunc(arg2val) == foo(arg1val, arg2val, kwarg1=True)\n \"\"\"\n super(user_function, self).__init__(\n input_types=input_types, output_types=output_types, data_types=data_types\n )\n self._user_func = func\n self._args = args\n self._kwargs = kwargs\n\n def func(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n args\n self._args + args are passed to the user function\n kwargs\n a deep copy of self._kwargs is updated by kwargs and passed to the\n user function\n\n Returns\n -------\n the result of the user function\n \"\"\"\n args = self._args + args\n kwargs_ = deepcopy(self._kwargs)\n kwargs_.update(kwargs)\n # the following enables a decorated user function (via @appify())\n # or directly passed user function\n func = getattr(self._user_func, \"__wrapped__\", self._user_func)\n return func(*args, **kwargs_)\n\n def __str__(self):\n txt = \"\" if not self.input else str(self.input)\n if txt:\n txt += \" + \"\n txt += f\"user_function(name='{self._user_func.__name__}', module='{self._user_func.__module__}')\"\n txt = textwrap.fill(\n txt, width=80, break_long_words=False, break_on_hyphens=False\n )\n return txt\n\n def __repr__(self):\n return str(self)\n\n\n@extend_docstring_from(ComposableType.__init__, pre=True)\ndef appify(input_types, output_types, data_types=None):\n \"\"\"function decorator for generating user apps. Simplifies creation of\n user_function() instances, e.g.\n\n >>> @appify(SEQUENCE_TYPE, SEQUENCE_TYPE, data_types=\"SequenceCollection\")\n ... def omit_seqs(seqs, quantile=None, gap_fraction=1, moltype=\"dna\"):\n ... return seqs.omit_bad_seqs(quantile=quantile, gap_fraction=gap_fraction, moltype=\"dna\")\n ...\n\n ``omit_seqs()`` is now an app factory, allowing creating variants of the app.\n\n >>> omit_bad = omit_seqs(quantile=0.95)\n\n ``omit_bad`` is now a composable ``user_function`` app. Calling with different\n args/kwargs values returns a variant app, as per the behaviour of builtin\n apps.\n\n \"\"\"\n # the 3 nested functions are required to allow setting decorator arguments\n # to allow using functools.wraps so the decorated function has the correct\n # docstring, name etc... And, the final inner one gets to pass the\n # reference to the wrapped function (wrapped_ref) to user_function. This\n # latter is required to enable pickling of the user_function instance.\n def enclosed(func):\n @wraps(func)\n def maker(*args, **kwargs):\n # construct the user_function app\n return user_function(\n wrapped_ref,\n input_types,\n output_types,\n *args,\n data_types=data_types,\n **kwargs,\n )\n\n wrapped_ref = maker\n\n return maker\n\n return enclosed\n","sub_path":"src/cogent3/app/composable.py","file_name":"composable.py","file_ext":"py","file_size_in_byte":26340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"78801018","text":"# @oj: atcoder\n# @id: hitwanyang\n# @email: 296866643@qq.com\n# @date: 2020-05-19 17:18\n# @url:https://atcoder.jp/contests/abc135/tasks/abc135_d\nimport sys,os\nfrom io import BytesIO, IOBase\nimport collections,itertools,bisect,heapq,math,string\n# region fastio\n\nBUFSIZE = 8192\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n newlines = 0\n\n def __init__(self, file):\n self._fd = file.fileno()\n self.buffer = BytesIO()\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n while True:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n if not b:\n break\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines = 0\n return self.buffer.read()\n\n def readline(self):\n while self.newlines == 0:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n self.newlines = b.count(b\"\\n\") + (not b)\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines -= 1\n return self.buffer.readline()\n\n def flush(self):\n if self.writable:\n os.write(self._fd, self.buffer.getvalue())\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\nclass IOWrapper(IOBase):\n def __init__(self, file):\n self.buffer = FastIO(file)\n self.flush = self.buffer.flush\n self.writable = self.buffer.writable\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n# ------------------------------\ndef main():\n # python取模注意每次都需要取模,否则可能会导致tle\n # 大数取模的运算通常可以分解为每个位置的权重进行取模运算,然后求和再取模的,例如:\n # 1993%mod=(1000%mod+900%mod+90%mod+3%mod)%mod\n # 利用模运算的基本性质:\n # 加法:19%3=(10%3+9%3)%3 (a+b)%mod=(a%mod+b%mod)%mod\n # 乘法:27%4=(9%4*3%4)%4 (a*b)%mod=(a%mod*b%mod)%mod\n s=str(input())\n S=s[::-1]\n dp=[[0]*13 for i in range(len(S))]\n mod=10**9+7\n p=1 # 每位的权重10的幂次\n for i in range(len(S)):\n if i==0:\n if S[i]!='?':\n t=p*int(S[i])%13\n dp[i][t]+=1\n else:\n for j in range(10):\n dp[i][j]+=1\n else:\n if S[i]!='?':\n t=p*int(S[i])%13\n for j in range(13):\n dp[i][(t+j)%13]=dp[i-1][j]%mod\n else:\n for j in range(10):\n for k in range(13):\n temp=(p*j%13+k)%13\n dp[i][temp]=(dp[i][temp]+dp[i-1][k])%mod\n # 权重取模\n p=(p%13*10%13)%13\n # print (dp)\n print (dp[len(S)-1][5])\nif __name__ == \"__main__\":\n main()","sub_path":"Python_codes/p02960/s646668497.py","file_name":"s646668497.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"433834380","text":"import csv\nfrom os import close\n\n#Leo el archivo csv, lo recorro y guardo la info en diccionarios \n#dentro de una lista que retorno.\ndef read_csv() -> list:\n lista =[]\n with open('usuarios.csv') as f:\n reader = csv.DictReader(f)\n for row in reader:\n lista.append(row)\n \n return lista\n\ndef calculating_average(list):\n userss = list\n hotmail = 0\n gmail = 0\n outlook = 0\n count_hotm = 0\n count_gmail = 0\n count_outl = 0\n #print(userss)\n\n #Recorro la lista de diccionarios y guardo el valor de los puntos \n #dependiendo de la terminación del correo.\n for i in userss:\n \n a = i[\"correo\"].split(\"@\")\n \n if a[1] == \"hotmail.com\":\n hotmail += float(i[\"puntos\"])\n count_hotm += 1\n \n if a[1] == \"gmail.com\":\n gmail += float(i[\"puntos\"])\n count_gmail += 1\n\n if a[1] == \"outlook.com\":\n outlook += float(i[\"puntos\"])\n count_outl += 1\n\n return \"hotmail \"+ str(hotmail/count_hotm)+\"\\n\" \"gmail \"+ str(gmail/count_gmail)+\"\\n\"+ \"outlook \"+ str(outlook/count_outl)\n\nif __name__ == \"__main__\":\n #Guardo en una variable la lista con la info\n data = read_csv()\n\n #Mandamos los datos a calcular e imprimimos\n print(calculating_average(data))","sub_path":"ago-dic-2020/Juan Arnoldo Chavez Munoz/Practicas/Practica_4/Practica_4.py","file_name":"Practica_4.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"446521735","text":"\"\"\"Postprocessing Pipeline Workflow Builder and Distributer.\n\nBased on user input, builds and runs a postprocessing pipeline for a set \nof subjects, distributing the workload across a cluster if requested.\n\"\"\"\n\nimport sys\nimport os\nimport warnings\nimport json\nimport time\nfrom pathlib import Path\n\nfrom .bids import (\n get_bids,\n get_confounds,\n get_images_to_process,\n get_mask,\n get_mixing_file,\n get_noise_file,\n get_subjects,\n get_tr,\n validate_subject_exists,\n)\n\nimport pydantic\n\n# This hides a pybids future warning\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n from bids import BIDSLayout\n from bids.layout import BIDSFile\n\nfrom .config_json_parser import ClpipeConfigParser\nfrom .config.postprocessing2 import DEFAULT_PROCESSING_STREAM\nfrom .batch_manager import BatchManager, Job\nfrom .postprocutils.workflows import (\n build_image_postprocessing_workflow,\n build_postprocessing_workflow,\n)\nfrom .postprocutils.confounds_workflows import build_confounds_processing_workflow\nfrom .postprocutils.utils import draw_graph\nfrom .utils import add_file_handler, get_logger, resolve_fmriprep_dir\nfrom .errors import *\n\nSTEP_NAME = \"postprocess2\"\nPROCESSING_DESCRIPTION_FILE_NAME = \"processing_description.json\"\nIMAGE_TIME_DIMENSION_INDEX = 3\nIMAGE_SUBMISSION_STRING_TEMPLATE = (\n \"postprocess_image {config_file} \"\n \"{image_path} {bids_dir} {fmriprep_dir} {pybids_db_path} {out_dir} \"\n \"{subject_out_dir} {processing_stream} {subject_working_dir} {log_dir} \"\n \"{debug}\"\n)\nSUBJECT_SUBMISSION_STRING_TEMPLATE = (\n \"postprocess_subject {subject_id} {bids_dir} {fmriprep_dir} {output_dir} \"\n \"{processing_stream} {config_file} {index_dir} {log_dir} {batch} {submit} \"\n \"{debug}\"\n)\n\n\ndef postprocess_subjects(\n subjects=None,\n config_file=None,\n bids_dir=None,\n fmriprep_dir=None,\n output_dir=None,\n processing_stream=DEFAULT_PROCESSING_STREAM,\n batch=False,\n submit=False,\n log_dir=None,\n pybids_db_path=None,\n refresh_index=False,\n debug=False,\n cache=True,\n):\n \"\"\"\n Parse configuration and sanitize inputs in preparation for\n subject job distribution.\n \"\"\"\n\n config = _parse_config(config_file)\n config_file = Path(config_file)\n\n project_dir = config[\"ProjectDirectory\"]\n project_dir = Path(project_dir)\n\n # Setup Logging\n clpipe_logs = project_dir / \"logs\"\n logger = get_logger(STEP_NAME, debug=debug)\n add_file_handler(clpipe_logs)\n\n if not fmriprep_dir:\n # Look for a target dir configuration - if empty or not present,\n # assume the fmriprep dir\n default_path = resolve_fmriprep_dir(\n config[\"FMRIPrepOptions\"][\"OutputDirectory\"]\n )\n try:\n fmriprep_dir = config[\"PostProcessingOptions2\"][\"TargetDirectory\"]\n if fmriprep_dir == \"\":\n fmriprep_dir = default_path\n except KeyError:\n fmriprep_dir = default_path\n fmriprep_dir = Path(fmriprep_dir)\n logger.info(f\"Preparing postprocessing job targeting: {str(fmriprep_dir)}\")\n time.sleep(0.5)\n\n if not bids_dir:\n bids_dir = Path(config[\"FMRIPrepOptions\"][\"BIDSDirectory\"])\n bids_dir = Path(bids_dir)\n\n if not output_dir:\n default_path = Path(project_dir) / \"data_postproc2\"\n try:\n output_dir = config[\"PostProcessingOptions2\"][\"OutputDirectory\"]\n if output_dir == \"\":\n output_dir = default_path\n except KeyError:\n output_dir = default_path\n\n output_dir = Path(output_dir)\n logger.info(f\"Output directory: {output_dir}\")\n\n working_dir = config[\"PostProcessingOptions2\"][\"WorkingDirectory\"]\n if working_dir == \"\":\n logger.warn(\"Working directory not set, defaulting to output directory.\")\n else:\n logger.info(f\"Using working directory: {working_dir}\")\n\n stream_output_dir = output_dir / processing_stream\n if not stream_output_dir.exists():\n stream_output_dir.mkdir(parents=True)\n\n if not log_dir:\n log_dir = Path(project_dir) / \"logs\" / \"postproc2_logs\"\n log_dir = Path(log_dir)\n logger.debug(f\"Using log directory: {log_dir}\")\n\n if not pybids_db_path:\n pybids_db_path = Path(project_dir) / \"bids_index\"\n pybids_db_path = Path(pybids_db_path)\n\n # Setup batch jobs if indicated\n batch_manager = None\n if batch:\n slurm_log_dir = log_dir / \"distributor\"\n if not slurm_log_dir.exists():\n logger.info(f\"Creating slurm log directory: {slurm_log_dir}\")\n slurm_log_dir.mkdir(exist_ok=True, parents=True)\n batch_manager = _setup_batch_manager(config, slurm_log_dir, non_processing=True)\n\n # Create jobs based on subjects given for processing\n # TODO: PYBIDS_DB_PATH should have config arg\n try:\n bids: BIDSLayout = get_bids(\n bids_dir,\n database_path=pybids_db_path,\n logger=logger,\n fmriprep_dir=fmriprep_dir,\n refresh=refresh_index,\n )\n\n subjects_to_process = get_subjects(bids, subjects)\n logger.info(\n f\"Processing requested for subject(s): {','.join(subjects_to_process)}\"\n )\n time.sleep(0.5)\n\n logger.info(\"Creating submission string(s)\")\n submission_strings = {}\n time.sleep(0.5)\n\n batch_flag = \"\" if batch_manager else \"-no-batch\"\n submit_flag = \"-submit\" if submit else \"\"\n debug_flag = \"-debug\" if debug else \"\"\n\n for subject in subjects_to_process:\n key = \"Postprocessing_sub-\" + subject\n submission_strings[key] = SUBJECT_SUBMISSION_STRING_TEMPLATE.format(\n subject_id=subject,\n bids_dir=bids_dir,\n fmriprep_dir=fmriprep_dir,\n config_file=config_file,\n index_dir=pybids_db_path,\n output_dir=output_dir,\n processing_stream=processing_stream,\n log_dir=log_dir,\n batch=batch_flag,\n submit=submit_flag,\n debug=debug_flag,\n )\n\n _submit_jobs(batch_manager, submission_strings, logger, submit=submit)\n except NoSubjectsFoundError as nsfe:\n logger.error(nsfe)\n sys.exit()\n except FileNotFoundError as fnfe:\n logger.error(fnfe)\n sys.exit()\n\n sys.exit()\n\n\ndef postprocess_subject(\n subject_id,\n bids_dir,\n fmriprep_dir,\n output_dir,\n config_file,\n index_dir,\n batch,\n submit,\n log_dir,\n processing_stream=DEFAULT_PROCESSING_STREAM,\n debug=False,\n):\n \"\"\"\n Parse configuration and (TODO) sanitize inputs for image job distribution.\n \"\"\"\n\n logger = get_logger(\"postprocess_subject\", debug=debug)\n logger.info(f\"Processing subject: {subject_id}\")\n\n # Create a postprocessing logging directory for this subject,\n # if it doesn't exist\n log_dir = Path(log_dir)\n log_dir = log_dir / (\"sub-\" + subject_id)\n\n config = _parse_config(config_file)\n config_file = Path(config_file)\n\n output_dir = Path(output_dir)\n\n stream_output_dir = output_dir / processing_stream\n postprocessing_config = _fetch_postprocessing_stream_config(\n config, stream_output_dir, processing_stream=processing_stream\n )\n\n batch_manager = None\n if batch:\n batch_manager = _setup_batch_manager(config, log_dir)\n\n try:\n bids: BIDSLayout = get_bids(\n bids_dir, database_path=index_dir, fmriprep_dir=fmriprep_dir\n )\n validate_subject_exists(bids, subject_id, logger)\n\n image_space = postprocessing_config[\"TargetImageSpace\"]\n try:\n tasks = postprocessing_config[\"TargetTasks\"]\n except KeyError:\n logger.warn(\n (\n \"Postprocessing configuration setting 'TargetTasks' not set. \"\n \"Defaulting to all tasks.\"\n )\n )\n tasks = None\n try:\n acquisitions = postprocessing_config[\"TargetAcquisitions\"]\n except KeyError:\n logger.warn(\n (\n \"Postprocessing configuration setting 'TargetAcquisitions' \"\n \"not set. Defaulting to all acquisitions.\"\n )\n )\n acquisitions = None\n\n images_to_process = get_images_to_process(\n subject_id,\n image_space,\n bids,\n logger,\n tasks=tasks,\n acquisitions=acquisitions,\n )\n\n subject_out_dir = output_dir / processing_stream / (\"sub-\" + subject_id)\n\n working_dir = postprocessing_config[\"WorkingDirectory\"]\n subject_working_dir = _get_subject_working_dir(\n working_dir, output_dir, subject_id, processing_stream\n )\n\n if not subject_out_dir.exists():\n logger.info(f\"Creating subject directory: {subject_out_dir}\")\n subject_out_dir.mkdir(parents=True)\n\n if not subject_working_dir.exists():\n logger.info(f\"Creating subject working directory: {subject_working_dir}\")\n subject_working_dir.mkdir(parents=True, exist_ok=False)\n\n submission_strings = _create_image_submission_strings(\n images_to_process,\n bids_dir,\n fmriprep_dir,\n index_dir,\n output_dir,\n subject_out_dir,\n processing_stream,\n subject_working_dir,\n config_file,\n log_dir,\n debug,\n logger,\n )\n\n _submit_jobs(batch_manager, submission_strings, logger, submit=submit)\n except SubjectNotFoundError as snfe:\n logger.error(snfe)\n sys.exit()\n except ValueError as ve:\n logger.error(ve)\n sys.exit()\n except FileNotFoundError as fnfe:\n logger.error(fnfe)\n sys.exit()\n\n sys.exit()\n\n\ndef postprocess_image(\n config_file,\n image_path,\n bids_dir,\n fmriprep_dir,\n pybids_db_path,\n out_dir,\n subject_out_dir,\n subject_working_dir,\n log_dir,\n processing_stream=DEFAULT_PROCESSING_STREAM,\n confounds_only=False,\n debug=False,\n):\n \"\"\"\n Setup the workflows specified in the postprocessing configuration.\n \"\"\"\n\n logger = get_logger(\"postprocess_image\", debug=debug)\n logger.info(f\"Processing image: {image_path}\")\n\n config = _parse_config(config_file)\n config_file = Path(config_file)\n\n stream_output_dir = Path(out_dir) / processing_stream\n postprocessing_config = _fetch_postprocessing_stream_config(\n config, stream_output_dir, processing_stream=processing_stream\n )\n\n image_path = Path(image_path)\n subject_working_dir = Path(subject_working_dir)\n log_dir = Path(log_dir)\n subject_out_dir = Path(subject_out_dir)\n\n # Grab only the image file name in a way that works\n # on both .nii and .nii.gz\n file_name_no_extensions = Path(\n str(image_path).rstrip(\"\".join(image_path.suffixes))\n ).stem\n # Remove modality to shorten necessary pipeline name\n file_name_no_modality = file_name_no_extensions.replace(\"_desc-preproc_bold\", \"\")\n # Remove hyphens to allow use as a pipeline name\n pipeline_name = file_name_no_modality.replace(\"-\", \"_\")\n\n bids: BIDSLayout = get_bids(\n bids_dir, database_path=pybids_db_path, fmriprep_dir=fmriprep_dir\n )\n # Lookup the BIDSFile with the image path\n bids_image: BIDSFile = bids.get_file(image_path)\n # Fetch the image's entities\n image_entities = bids_image.get_entities()\n # Create a sub dict of the entities we will need to query on\n query_params = {\n k: image_entities[k]\n for k in image_entities.keys()\n & {\"session\", \"subject\", \"task\", \"run\", \"acquisition\", \"space\"}\n }\n # Create a specific dict for searching non-image files\n non_image_query_params = query_params.copy()\n non_image_query_params.pop(\"space\")\n\n mixing_file, noise_file = None, None\n if \"AROMARegression\" in postprocessing_config[\"ProcessingSteps\"]:\n try:\n # TODO: update these for image entities\n mixing_file = get_mixing_file(bids, non_image_query_params, logger)\n noise_file = get_noise_file(bids, non_image_query_params, logger)\n except MixingFileNotFoundError as mfnfe:\n logger.error(mfnfe)\n # TODO: this should raise the error for the controller to handle\n sys.exit(1)\n except NoiseFileNotFoundError as nfnfe:\n logger.error(nfnfe)\n sys.exit(1)\n\n mask_image = get_mask(bids, query_params, logger)\n tr = get_tr(bids, query_params, logger)\n confounds_path = get_confounds(bids, non_image_query_params, logger)\n\n image_wf = None\n confounds_wf = None\n\n if confounds_path is not None:\n try:\n confounds_export_path = build_export_path(\n confounds_path, query_params[\"subject\"], fmriprep_dir, subject_out_dir\n )\n\n confounds_wf = _setup_confounds_wf(\n postprocessing_config,\n pipeline_name,\n tr,\n confounds_export_path,\n subject_working_dir,\n log_dir,\n logger,\n mixing_file=mixing_file,\n noise_file=noise_file,\n )\n\n except ValueError as ve:\n logger.warn(ve)\n logger.warn(\"Skipping confounds processing\")\n\n if not confounds_only:\n image_export_path = build_export_path(\n image_path, query_params[\"subject\"], fmriprep_dir, subject_out_dir\n )\n\n image_wf = _setup_image_workflow(\n postprocessing_config,\n pipeline_name,\n tr,\n image_export_path,\n subject_working_dir,\n log_dir,\n logger,\n mask_image=mask_image,\n confounds=confounds_export_path,\n mixing_file=mixing_file,\n noise_file=noise_file,\n )\n\n postproc_wf = build_postprocessing_workflow(\n image_wf=image_wf,\n confounds_wf=confounds_wf,\n name=f\"{pipeline_name}_wf\",\n postprocessing_config=postprocessing_config,\n base_dir=subject_working_dir,\n crashdump_dir=log_dir,\n )\n\n if postprocessing_config[\"WriteProcessGraph\"]:\n draw_graph(postproc_wf, \"processing_graph\", stream_output_dir, logger=logger)\n\n postproc_wf.inputs.inputnode.in_file = image_path\n postproc_wf.inputs.inputnode.confounds_file = confounds_path\n\n postproc_wf.run()\n sys.exit(0)\n\n\ndef _setup_image_workflow(\n postprocessing_config,\n pipeline_name,\n tr,\n export_path,\n working_dir,\n log_dir,\n logger,\n mask_image=None,\n confounds=None,\n mixing_file=None,\n noise_file=None,\n):\n logger.info(f\"Building postprocessing workflow for: {pipeline_name}\")\n wf = build_image_postprocessing_workflow(\n postprocessing_config,\n export_path=export_path,\n name=f\"image_wf\",\n mask_file=mask_image,\n confounds_file=confounds,\n mixing_file=mixing_file,\n noise_file=noise_file,\n tr=tr,\n base_dir=working_dir,\n crashdump_dir=log_dir,\n )\n\n return wf\n\n\ndef build_export_path(\n image_path: os.PathLike,\n subject_id: str,\n fmriprep_dir: os.PathLike,\n subject_out_dir: os.PathLike,\n) -> Path:\n \"\"\"Builds a new name for a processed image.\n\n Args:\n image_path (os.PathLike): The path to the original image file.\n subject_out_dir (os.PathLike): The destination directory.\n\n Returns:\n os.PathLike: Save path for an image file.\n \"\"\"\n # Copy the directory structure following the subject-id\n # from the fmriprep dir\n out_path = Path(image_path).relative_to(Path(fmriprep_dir) / (\"sub-\" + subject_id))\n export_path = Path(subject_out_dir) / str(out_path)\n export_folder = export_path.parent\n\n # Create the output folder if it doesn't exist\n if not export_folder.exists():\n export_folder.mkdir(parents=True, exist_ok=True)\n\n export_path = Path(subject_out_dir) / str(out_path).replace(\"preproc\", \"postproc\")\n print(f\"Export path: {export_path}\")\n\n return export_path\n\n\ndef _setup_confounds_wf(\n postprocessing_config,\n pipeline_name,\n tr,\n export_file,\n working_dir,\n log_dir,\n logger,\n mixing_file=None,\n noise_file=None,\n):\n # TODO: Run this async or batch\n logger.info(f\"Building confounds workflow for {pipeline_name}\")\n\n logger.info(f\"Postprocessed confound out file: {export_file}\")\n\n confounds_wf = build_confounds_processing_workflow(\n postprocessing_config,\n export_file=export_file,\n tr=tr,\n name=f\"confounds_wf\",\n mixing_file=mixing_file,\n noise_file=noise_file,\n base_dir=working_dir,\n crashdump_dir=log_dir,\n )\n\n return confounds_wf\n\n\ndef _fetch_postprocessing_stream_config(\n config: dict,\n stream_output_dir: os.PathLike,\n processing_stream: str = DEFAULT_PROCESSING_STREAM,\n):\n \"\"\"\n The postprocessing stream config is a subset of the main\n configuration's postprocessing config, based on\n selections made in the processing streams config.\n\n This stream postprocessing config is saved as a seperate configuration\n file at the level of the output folder / stream folder and\n is referred to by the workflow builders.\n \"\"\"\n\n postprocessing_description_file = (\n Path(stream_output_dir) / PROCESSING_DESCRIPTION_FILE_NAME\n )\n postprocessing_config = _postprocessing_config_apply_processing_stream(\n config, processing_stream=processing_stream\n )\n _write_processing_description_file(\n postprocessing_config, postprocessing_description_file\n )\n\n return postprocessing_config\n\n\ndef _list_available_streams(postprocessing_config: dict):\n return postprocessing_config.keys()\n\n\ndef _write_processing_description_file(\n postprocessing_config: dict, processing_description_file: os.PathLike\n):\n processing_steps = postprocessing_config[\"ProcessingSteps\"]\n processing_step_options = postprocessing_config[\"ProcessingStepOptions\"]\n processing_step_options_reference = processing_step_options.copy()\n confound_options = postprocessing_config[\"ConfoundOptions\"]\n\n # Remove processing options not used\n for step_option in processing_step_options_reference.keys():\n if step_option not in processing_steps:\n processing_step_options.pop(step_option)\n\n # Write the processing file\n with open(processing_description_file, \"w\") as file_to_write:\n json.dump(postprocessing_config, file_to_write, indent=4)\n\n\ndef _postprocessing_config_apply_processing_stream(\n config: dict, processing_stream: str = DEFAULT_PROCESSING_STREAM\n):\n postprocessing_config = _get_postprocessing_config(config)\n processing_streams = _get_processing_streams(config)\n\n # If using the default stream, no need to update postprocessing config\n if processing_stream == DEFAULT_PROCESSING_STREAM:\n return postprocessing_config\n\n # Iterate through the available processing streams and see\n # if one matches the one requested\n # The default processing stream name won't be in this list -\n # it refers to the base PostProcessingOptions\n for stream in processing_streams:\n stream_options = stream[\"PostProcessingOptions\"]\n\n if stream[\"ProcessingStream\"] == processing_stream:\n # Use deep update to impart the processing stream options\n # into the postprocessing config\n postprocessing_config = pydantic.utils.deep_update(\n postprocessing_config, stream_options\n )\n return postprocessing_config\n\n raise ValueError(f\"No stream found in configuration with name: {processing_stream}\")\n\n\ndef _get_postprocessing_config(config: dict):\n return config[\"PostProcessingOptions2\"]\n\n\ndef _get_processing_streams(config: dict):\n return config[\"ProcessingStreams\"]\n\n\ndef _submit_jobs(batch_manager, submission_strings, logger, submit=True):\n num_jobs = len(submission_strings)\n\n if batch_manager:\n _populate_batch_manager(batch_manager, submission_strings, logger)\n if submit:\n batch_manager.submit_jobs()\n else:\n batch_manager.print_jobs()\n else:\n if submit:\n for key in submission_strings.keys():\n os.system(submission_strings[key])\n else:\n for key in submission_strings.keys():\n print(submission_strings[key])\n\n\ndef _create_image_submission_strings(\n images_to_process,\n bids_dir,\n fmriprep_dir,\n pybids_db_path,\n out_dir,\n subject_out_dir,\n processing_stream,\n subject_working_dir,\n config_file,\n log_dir,\n debug,\n logger,\n):\n logger.info(f\"Building image job submission strings\")\n submission_strings = {}\n\n debug_flag = \"\"\n if debug:\n debug_flag = \"-debug\"\n\n logger.info(\"Creating submission string(s)\")\n for image in images_to_process:\n key = f\"{str(Path(image.path).stem)}\"\n\n submission_strings[key] = IMAGE_SUBMISSION_STRING_TEMPLATE.format(\n config_file=config_file,\n image_path=image.path,\n bids_dir=bids_dir,\n fmriprep_dir=fmriprep_dir,\n pybids_db_path=pybids_db_path,\n out_dir=out_dir,\n subject_out_dir=subject_out_dir,\n processing_stream=processing_stream,\n subject_working_dir=subject_working_dir,\n log_dir=log_dir,\n debug=debug_flag,\n )\n logger.debug(submission_strings[key])\n return submission_strings\n\n\ndef _parse_config(config_file):\n # Get postprocessing configuration from general config\n if not config_file:\n raise ValueError(\"No config file provided\")\n\n configParser = ClpipeConfigParser()\n configParser.config_updater(config_file)\n config = configParser.config\n\n return config\n\n\ndef _populate_batch_manager(batch_manager, submission_strings, logger):\n logger.info(\"Setting up batch manager with jobs to run.\")\n\n for key in submission_strings.keys():\n batch_manager.addjob(Job(key, submission_strings[key]))\n\n batch_manager.createsubmissionhead()\n batch_manager.compilejobstrings()\n\n\ndef _setup_batch_manager(config, log_dir, non_processing=False):\n batch_manager = BatchManager(config[\"BatchConfig\"], log_dir)\n batch_manager.update_mem_usage(\n config[\"PostProcessingOptions2\"][\"BatchOptions\"][\"MemoryUsage\"]\n )\n batch_manager.update_time(\n config[\"PostProcessingOptions2\"][\"BatchOptions\"][\"TimeUsage\"]\n )\n batch_manager.update_nthreads(\n config[\"PostProcessingOptions2\"][\"BatchOptions\"][\"NThreads\"]\n )\n batch_manager.update_email(config[\"EmailAddress\"])\n\n if non_processing:\n batch_manager.update_mem_usage(2000)\n batch_manager.update_nthreads(1)\n batch_manager.update_time(\"0:30:0\")\n\n return batch_manager\n\n\ndef _get_subject_working_dir(working_dir, out_dir, subject_id, processing_stream):\n # If no top-level working directory is provided, make one in the out_dir\n if not working_dir:\n subject_working_dir = (\n out_dir / \"working\" / processing_stream / (\"sub-\" + subject_id)\n )\n # Otherwise, use the provided top-level directory as a base,\n # and name working directory after the subject\n else:\n subject_working_dir = (\n Path(working_dir) / processing_stream / (\"sub-\" + subject_id)\n )\n\n return subject_working_dir\n","sub_path":"clpipe/fmri_postprocess2.py","file_name":"fmri_postprocess2.py","file_ext":"py","file_size_in_byte":23674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"371856093","text":"#Problem 1:\n\n# Create a function that will ask the user for a number. \n# Use the function to get two numbers from the user, \n# then pass the two numbers to a function. Add, subtract, multiple, and divide the numbers.\n\ndef twoNum():\n num1 = int(input('enter number')) # !! : add some formatting (space after string)\n num2 = int(input('enter number'))\n add(num1, num2)\n\n\ndef add(num1, num2): # !! : not a great function name\n print(num1 + num2)\n print(num1 - num2)\n print(num1 * num2)\n print(num1 / num2)\n \ntwoNum()","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"503019943","text":"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nfrom __future__ import absolute_import\n\nimport awkward as ak\nfrom awkward._v2.index import Index\nfrom awkward._v2.contents.content import Content, NestedIndexError\nfrom awkward._v2.forms.bytemaskedform import ByteMaskedForm\n\nnp = ak.nplike.NumpyMetadata.instance()\n\n\nclass ByteMaskedArray(Content):\n def __init__(self, mask, content, valid_when, identifier=None, parameters=None):\n if not (isinstance(mask, Index) and mask.dtype == np.dtype(np.int8)):\n raise TypeError(\n \"{0} 'mask' must be an Index with dtype=int8, not {1}\".format(\n type(self).__name__, repr(mask)\n )\n )\n if not isinstance(content, Content):\n raise TypeError(\n \"{0} 'content' must be a Content subtype, not {1}\".format(\n type(self).__name__, repr(content)\n )\n )\n if not isinstance(valid_when, bool):\n raise TypeError(\n \"{0} 'valid_when' must be boolean, not {1}\".format(\n type(self).__name__, repr(valid_when)\n )\n )\n if not len(mask) <= len(content):\n raise ValueError(\n \"{0} len(mask) ({1}) must be <= len(content) ({2})\".format(\n type(self).__name__, len(mask), len(content)\n )\n )\n\n self._mask = mask\n self._content = content\n self._valid_when = valid_when\n self._init(identifier, parameters)\n\n @property\n def mask(self):\n return self._mask\n\n @property\n def content(self):\n return self._content\n\n @property\n def valid_when(self):\n return self._valid_when\n\n @property\n def nplike(self):\n return self._mask.nplike\n\n Form = ByteMaskedForm\n\n @property\n def form(self):\n return self.Form(\n self._mask.form,\n self._content.form,\n self._valid_when,\n has_identifier=self._identifier is not None,\n parameters=self._parameters,\n form_key=None,\n )\n\n def __len__(self):\n return len(self._mask)\n\n def __repr__(self):\n return self._repr(\"\", \"\", \"\")\n\n def _repr(self, indent, pre, post):\n out = [indent, pre, \"\\n\")\n out.append(self._mask._repr(indent + \" \", \"\", \"\\n\"))\n out.append(self._content._repr(indent + \" \", \"\", \"\\n\"))\n out.append(indent)\n out.append(\"\")\n out.append(post)\n return \"\".join(out)\n\n def _getitem_nothing(self):\n return self._content._getitem_range(slice(0, 0))\n\n def _getitem_at(self, where):\n if where < 0:\n where += len(self)\n if not (0 <= where < len(self)):\n raise NestedIndexError(self, where)\n if self._mask[where] == self._valid_when:\n return self._content._getitem_at(where)\n else:\n return None\n\n def _getitem_range(self, where):\n start, stop, step = where.indices(len(self))\n assert step == 1\n return ByteMaskedArray(\n self._mask[start:stop],\n self._content._getitem_range(slice(start, stop)),\n self._valid_when,\n self._range_identifier(start, stop),\n self._parameters,\n )\n\n def _getitem_field(self, where, only_fields=()):\n return ByteMaskedArray(\n self._mask,\n self._content._getitem_field(where, only_fields),\n self._valid_when,\n self._field_identifier(where),\n None,\n )\n\n def _getitem_fields(self, where, only_fields=()):\n return ByteMaskedArray(\n self._mask,\n self._content._getitem_fields(where, only_fields),\n self._valid_when,\n self._fields_identifier(where),\n None,\n )\n\n def _carry(self, carry, allow_lazy, exception):\n assert isinstance(carry, ak._v2.index.Index)\n\n try:\n nextmask = self._mask[carry.data]\n except IndexError as err:\n if issubclass(exception, NestedIndexError):\n raise exception(self, carry.data, str(err))\n else:\n raise exception(str(err))\n\n return ByteMaskedArray(\n nextmask,\n self._content._carry(carry, allow_lazy, exception),\n self._valid_when,\n self._carry_identifier(carry, exception),\n self._parameters,\n )\n\n def nextcarry_outindex(self, numnull):\n nplike = self.nplike\n self._handle_error(\n nplike[\n \"awkward_ByteMaskedArray_numnull\",\n numnull.dtype.type,\n self._mask.dtype.type,\n ](\n numnull.to(nplike),\n self._mask.to(nplike),\n len(self._mask),\n self._valid_when,\n )\n )\n nextcarry = ak._v2.index.Index64.empty(len(self) - numnull[0], nplike)\n outindex = ak._v2.index.Index64.empty(len(self), nplike)\n self._handle_error(\n nplike[\n \"awkward_ByteMaskedArray_getitem_nextcarry_outindex\",\n nextcarry.dtype.type,\n outindex.dtype.type,\n self._mask.dtype.type,\n ](\n nextcarry.to(nplike),\n outindex.to(nplike),\n self._mask.to(nplike),\n len(self._mask),\n self._valid_when,\n )\n )\n return nextcarry, outindex\n\n def _getitem_next(self, head, tail, advanced):\n nplike = self.nplike # noqa: F841\n\n if head == ():\n return self\n\n elif isinstance(head, (int, slice, ak._v2.index.Index64)):\n nexthead, nexttail = self._headtail(tail)\n numnull = ak._v2.index.Index64.empty(1, nplike)\n nextcarry, outindex = self.nextcarry_outindex(numnull)\n\n next = self._content._carry(nextcarry, True, NestedIndexError)\n out = next._getitem_next(head, tail, advanced)\n out2 = ak._v2.contents.indexedoptionarray.IndexedOptionArray(\n outindex,\n out,\n self._identifier,\n self._parameters,\n )\n return out2._simplify_optiontype()\n\n elif ak._util.isstr(head):\n return self._getitem_next_field(head, tail, advanced)\n\n elif isinstance(head, list):\n return self._getitem_next_fields(head, tail, advanced)\n\n elif head is np.newaxis:\n return self._getitem_next_newaxis(tail, advanced)\n\n elif head is Ellipsis:\n return self._getitem_next_ellipsis(tail, advanced)\n\n elif isinstance(head, ak._v2.contents.ListOffsetArray):\n raise NotImplementedError\n\n elif isinstance(head, ak._v2.contents.IndexedOptionArray):\n raise NotImplementedError\n\n else:\n raise AssertionError(repr(head))\n\n def _localindex(self, axis, depth):\n posaxis = self._axis_wrap_if_negative(axis)\n if posaxis == depth:\n return self._localindex_axis0()\n else:\n numnull = ak._v2.index.Index64.empty(1, self.nplike)\n nextcarry, outindex = self.nextcarry_outindex(numnull)\n\n next = self.content._carry(nextcarry, False, NestedIndexError)\n out = next._localindex(posaxis, depth)\n out2 = ak._v2.contents.indexedoptionarray.IndexedOptionArray(\n outindex,\n out,\n self._identifier,\n self._parameters,\n )\n return out2._simplify_optiontype()\n","sub_path":"src/awkward/_v2/contents/bytemaskedarray.py","file_name":"bytemaskedarray.py","file_ext":"py","file_size_in_byte":7959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"504958444","text":"import doctest\n\n\ndef how_many_days(seconds):\n \"\"\"\n Calculate how many days are comprised in the time provided.\n\n :param seconds: int\n :precondition: argument is an integer >= 0\n :postcondition: number of days comprised by the argument\n :return: int\n\n >>> how_many_days(86401)\n 1\n \"\"\"\n\n return seconds // 86400\n\n\ndef how_many_hours(seconds):\n \"\"\"\n Calculate how many hours are comprised in the time provided.\n\n :param seconds: int\n :precondition: argument is an integer >= 0\n :postcondition: number of hours comprised by the argument\n :return: int\n\n >>> how_many_hours(7200)\n 2\n \"\"\"\n\n return seconds // 3600\n\n\ndef how_many_minutes(seconds):\n \"\"\"\n Calculate how many minutes are comprised in the time provided.\n\n :param seconds: int\n :precondition: argument is an integer >= 0\n :postcondition: number of minutes comprised by the argument\n :return: int\n\n >>> how_many_minutes(180)\n 3\n \"\"\"\n\n return seconds // 60\n\n\ndef time_calculator(seconds):\n \"\"\"\n Convert seconds into respective days, hours and minutes.\n\n :param seconds: integer\n :precondition: argument is an integer >= 0\n :postcondition: argument value converted to days, hours, seconds\n :return: string\n\n >>> time_calculator(980)\n We have 0 days, 0 hours, 16 minutes and 20 seconds\n \"\"\"\n # 60 seconds in a minute\n # 3600 seconds in an hour\n # 86 400 seconds in a day\n\n hours = 0\n minutes = 0\n\n days = how_many_days(seconds)\n\n if days == 0:\n time_remaining = seconds\n else:\n time_remaining = seconds % 86400\n\n if time_remaining >= 3600: # ie. there is at least 1 hour\n hours = how_many_hours(time_remaining)\n time_remaining = time_remaining % 3600\n\n if time_remaining >= 60:\n minutes = how_many_minutes(time_remaining)\n\n seconds = time_remaining % 60\n\n print(\"We have %d days, %d hours, %d minutes and %d seconds\" % (days, hours, minutes, seconds))\n\n\ndef main():\n # print(\"TEST 60 (1 min)\")\n # time_calculator(60)\n # print(\"TEST 3600 (1 hour)\")\n # time_calculator(3600)\n # print(\"TEST 86400 (1 day)\")\n # time_calculator(86400)\n # print(\"TEST \")\n # time_calculator(980)\n\n doctest.testmod()\n\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\nComponents of computational thinking (decomposition, pattern matching, abstraction, algorithms) used in this script:\nDecomposition occurs in the separating out of the how_many_X functions.\nThe methodology behind determining how many of each unit of time (day, hour, minute, second) is an example of\n algorithmic thinking.\n\n\"\"\"\n","sub_path":"A1/time_calculator.py","file_name":"time_calculator.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"494740710","text":"\"\"\"\ngithub3.orgs\n============\n\nThis module contains all of the classes related to organizations.\n\n\"\"\"\n\nfrom json import dumps\nfrom github3.events import Event\nfrom github3.models import BaseAccount, GitHubCore\nfrom github3.repos import Repository\nfrom github3.users import User\nfrom github3.decorators import requires_auth\n\n\nclass Team(GitHubCore):\n def __init__(self, team, session=None):\n super(Team, self).__init__(team, session)\n self._api = team.get('url', '')\n #: This team's name.\n self.name = team.get('name')\n #: Unique ID of the team.\n self.id = team.get('id')\n #: Permission leve of the group\n self.permission = team.get('permission')\n #: Number of members in this team.\n self.members_count = team.get('members_count')\n #: Number of repos owned by this team.\n self.repos_count = team.get('repos_count')\n\n def __repr__(self):\n return ''.format(self.name)\n\n def _update_(self, team):\n self.__init__(team, self._session)\n\n @requires_auth\n def add_member(self, login):\n \"\"\"Add ``login`` to this team.\n\n :returns: bool\n \"\"\"\n url = self._build_url('members', login, base_url=self._api)\n return self._boolean(self._put(url), 204, 404)\n\n @requires_auth\n def add_repo(self, repo):\n \"\"\"Add ``repo`` to this team.\n\n :param str repo: (required), form: 'user/repo'\n :returns: bool\n \"\"\"\n url = self._build_url('repos', repo, base_url=self._api)\n return self._boolean(self._put(url), 204, 404)\n\n @requires_auth\n def delete(self):\n \"\"\"Delete this team.\n\n :returns: bool\n \"\"\"\n return self._boolean(self._delete(self._api), 204, 404)\n\n @requires_auth\n def edit(self, name, permission=''):\n \"\"\"Edit this team.\n\n :param str name: (required)\n :param str permission: (optional), ('pull', 'push', 'admin')\n :returns: bool\n \"\"\"\n if name:\n data = dumps({'name': name, 'permission': permission})\n json = self._json(self._patch(self._api, data=data), 200)\n if json:\n self._update_(json)\n return True\n return False\n\n def has_repo(self, repo):\n \"\"\"Checks if this team has access to ``repo``\n\n :param str repo: (required), form: 'user/repo'\n :returns: bool\n \"\"\"\n url = self._build_url('repos', repo, base_url=self._api)\n return self._boolean(self._get(url), 204, 404)\n\n def is_member(self, login):\n \"\"\"Check if ``login`` is a member of this team.\n\n :param str login: (required), login name of the user\n :returns: bool\n \"\"\"\n url = self._build_url('members', login, base_url=self._api)\n return self._boolean(self._get(url), 204, 404)\n\n def iter_members(self, number=-1):\n \"\"\"Iterate over the members of this team.\n\n :param int number: (optional), number of users to iterate over.\n Default: -1 iterates over all values\n :returns: generator of :class:`User `\\ s\n \"\"\"\n url = self._build_url('members', base_url=self._api)\n return self._iter(int(number), url, User)\n\n def list_members(self):\n \"\"\"List the members of this team.\n\n :returns: list of :class:`User `\\ s\n \"\"\"\n url = self._build_url('members', base_url=self._api)\n json = self._json(self._get(url), 200)\n return [User(m, self) for m in json]\n\n def iter_repos(self, number=-1):\n \"\"\"Iterate over the repositories this team has access to.\n\n :param int number: (optional), number of repos to iterate over.\n Default: -1 iterates over all values\n :returns: generator of :class:`Repository `\n objects\n \"\"\"\n url = self._build_url('repos', base_url=self._api)\n return self._iter(int(number), url, Repository)\n\n def list_repos(self):\n \"\"\"List the repositories this team has access to.\n\n :returns: list of :class:`Repository `\n objects\n \"\"\"\n url = self._build_url('repos', base_url=self._api)\n json = self._json(self._get(url), 200)\n return [Repository(r, self) for r in json]\n\n @requires_auth\n def remove_member(self, login):\n \"\"\"Remove ``login`` from this team.\n\n :param str login: (required), login of the member to remove\n :returns: bool\n \"\"\"\n url = self._build_url('members', login, base_url=self._api)\n return self._boolean(self._delete(url), 204, 404)\n\n @requires_auth\n def remove_repo(self, repo):\n \"\"\"Remove ``repo`` from this team.\n\n :param str repo: (required), form: 'user/repo'\n :returns: bool\n \"\"\"\n url = self._build_url('repos', repo, base_url=self._api)\n return self._boolean(self._delete(url), 204, 404)\n\n\nclass Organization(BaseAccount):\n \"\"\"The :class:`Organization ` object.\"\"\"\n def __init__(self, org, session=None):\n super(Organization, self).__init__(org, session)\n if not self.type:\n self.type = 'Organization'\n\n #: Number of private repositories.\n self.private_repos = org.get('private_repos', 0)\n\n def __repr__(self):\n return ''.format(self.login, self.name)\n\n def _list_members(self, tail):\n \"\"\"List members of this organization.\"\"\"\n url = self._api + tail\n json = self._json(self._get(url), 200)\n return [User(memb, self) for memb in json]\n\n @requires_auth\n def add_member(self, login, team):\n \"\"\"Add ``login`` to ``team`` and thereby to this organization.\n\n Any user that is to be added to an organization, must be added\n to a team as per the GitHub api.\n\n :param str login: (required), login name of the user to be added\n :param str team: (required), team name\n :returns: bool\n \"\"\"\n teams = self.list_teams()\n for t in teams:\n if team == t.name:\n return t.add_member(login)\n return False\n\n @requires_auth\n def add_repo(self, repo, team):\n \"\"\"Add ``repo`` to ``team``.\n\n :param str repo: (required), form: 'user/repo'\n :param str team: (required)\n \"\"\"\n teams = self.list_teams()\n for t in teams:\n if team == t.name:\n return t.add_repo(repo)\n return False\n\n @requires_auth\n def create_repo(self,\n name,\n description='',\n homepage='',\n private=False,\n has_issues=True,\n has_wiki=True,\n has_downloads=True,\n team_id=0,\n auto_init=False,\n gitignore_template=''):\n \"\"\"Create a repository for this organization if the authenticated user\n is a member.\n\n :param str name: (required), name of the repository\n :param str description: (optional)\n :param str homepage: (optional)\n :param bool private: (optional), If ``True``, create a private\n repository. API default: ``False``\n :param bool has_issues: (optional), If ``True``, enable issues for\n this repository. API default: ``True``\n :param bool has_wiki: (optional), If ``True``, enable the wiki for\n this repository. API default: ``True``\n :param bool has_downloads: (optional), If ``True``, enable downloads\n for this repository. API default: ``True``\n :param int team_id: (optional), id of the team that will be granted\n access to this repository\n :param bool auto_init: (optional), auto initialize the repository.\n :param str gitignore_template: (optional), name of the template; this\n is ignored if auto_int = False.\n :returns: :class:`Repository `\n\n .. warning: ``name`` should be no longer than 100 characters\n \"\"\"\n url = self._build_url('repos', base_url=self._api)\n data = {'name': name, 'description': description,\n 'homepage': homepage, 'private': private,\n 'has_issues': has_issues, 'has_wiki': has_wiki,\n 'has_downloads': has_downloads, 'auto_init': auto_init,\n 'gitignore_template': gitignore_template}\n if team_id > 0:\n data.update({'team_id': team_id})\n json = self._json(self._post(url, dumps(data)), 201)\n return Repository(json, self) if json else None\n\n @requires_auth\n def conceal_member(self, login):\n \"\"\"Conceal ``login``'s membership in this organization.\n\n :returns: bool\n \"\"\"\n url = self._build_url('public_members', login, base_url=self._api)\n return self._boolean(self._delete(url), 204, 404)\n\n @requires_auth\n def create_team(self, name, repo_names=[], permissions=''):\n \"\"\"Assuming the authenticated user owns this organization,\n create and return a new team.\n\n :param str name: (required), name to be given to the team\n :param list repo_names: (optional) repositories, e.g.\n ['github/dotfiles']\n :param str permissions: (optional), options:\n\n - ``pull`` -- (default) members can not push or administer\n repositories accessible by this team\n - ``push`` -- members can push and pull but not administer\n repositories accessible by this team\n - ``admin`` -- members can push, pull and administer\n repositories accessible by this team\n\n :returns: :class:`Team `\n \"\"\"\n data = dumps({'name': name, 'repo_names': repo_names,\n 'permissions': permissions})\n url = self._build_url('teams', base_url=self._api)\n json = self._json(self._post(url, data), 201)\n return Team(json, self._session) if json else None\n\n @requires_auth\n def edit(self,\n billing_email=None,\n company=None,\n email=None,\n location=None,\n name=None):\n \"\"\"Edit this organization.\n\n :param str billing_email: (optional) Billing email address (private)\n :param str company: (optional)\n :param str email: (optional) Public email address\n :param str location: (optional)\n :param str name: (optional)\n :returns: bool\n \"\"\"\n json = None\n data = {'billing_email': billing_email, 'company': company,\n 'email': email, 'location': location, 'name': name}\n for (k, v) in data.items():\n if v is None:\n del data[k]\n\n if data:\n json = self._json(self._patch(self._api, data=dumps(data)), 200)\n\n if json:\n self._update_(json)\n return True\n return False\n\n def is_member(self, login):\n \"\"\"Check if the user with login ``login`` is a member.\n\n :returns: bool\n \"\"\"\n url = self._build_url('members', login, base_url=self._api)\n return self._boolean(self._get(url), 204, 404)\n\n def is_public_member(self, login):\n \"\"\"Check if the user with login ``login`` is a public member.\n\n :returns: bool\n \"\"\"\n url = self._build_url('public_members', login, base_url=self._api)\n return self._boolean(self._get(url), 204, 404)\n\n def iter_events(self, number=-1):\n \"\"\"Iterate over events for this org.\n\n :param int number: (optional), number of events to return. Default: -1\n iterates over all events available.\n :returns: generator of :class:`Event `\\ s\n \"\"\"\n url = self._build_url('events', base_url=self._api)\n return self._iter(int(number), url, Event)\n\n def list_events(self):\n \"\"\"List events for this org.\n\n :returns: list of :class:`Event `\\ s\n \"\"\"\n url = self._build_url('events', base_url=self._api)\n json = self._json(self._get(url), 200)\n return [Event(e, self._session) for e in json]\n\n def iter_members(self, number=-1):\n \"\"\"Iterate over members of this organization.\n\n :param int number: (optional), number of members to return. Default:\n -1 will return all available.\n :returns: generator of :class:`User `\\ s\n \"\"\"\n url = self._build_url('members', base_url=self._api)\n return self._iter(int(number), url, User)\n\n def list_members(self):\n \"\"\"List members of this organization.\n\n :returns: list of :class:`User `\\ s\n \"\"\"\n return self._list_members('/members')\n\n def iter_public_members(self, number=-1):\n \"\"\"Iterate over public members of this organization.\n\n :param int number: (optional), number of members to return. Default:\n -1 will return all available.\n :returns: generator of :class:`User `\\ s\n \"\"\"\n url = self._build_url('public_members', base_url=self._api)\n return self._iter(int(number), url, User)\n\n def list_public_members(self):\n \"\"\"List public members of this organization.\n\n :returns: list of :class:`User `\\ s\n \"\"\"\n return self._list_members('/public_members')\n\n def iter_repos(self, type='', number=-1):\n \"\"\"Iterate over repos for this organization.\n\n :param str type: (optional), accepted values:\n ('all', 'public', 'member', 'private'), API default: 'all'\n :param int number: (optional), number of members to return. Default:\n -1 will return all available.\n :returns: generator of :class:`Repository `\n \"\"\"\n url = self._build_url('repos', base_url=self._api)\n if type in ('all', 'public', 'member', 'private'):\n url = '{0}?type={1}'.format(url, type)\n return self._iter(int(number), url, Repository)\n\n def list_repos(self, type=''):\n \"\"\"List repos for this organization.\n\n :param str type: (optional), accepted values:\n ('all', 'public', 'member', 'private'), API default: 'all'\n :returns: list of :class:`Repository `\n objects\n \"\"\"\n url = self._build_url('repos', base_url=self._api)\n params = {}\n if type in ('all', 'public', 'member', 'private'):\n params['type'] = type\n json = self._json(self._get(url, params=params), 200)\n return [Repository(r, self) for r in json]\n\n @requires_auth\n def iter_teams(self, number=-1):\n \"\"\"Iterate over teams that are part of this organization.\n\n :param int number: (optional), number of teams to return. Default: -1\n returns all available teams.\n :returns: generator of :class:`Team `\\ s\n \"\"\"\n url = self._build_url('teams', base_url=self._api)\n return self._iter(int(number), url, Team)\n\n @requires_auth\n def list_teams(self):\n \"\"\"List teams that are part of this organization.\n\n :returns: list of :class:`Team `\\ s\n \"\"\"\n url = self._build_url('teams', base_url=self._api)\n json = self._json(self._get(url), 200)\n return [Team(team, self) for team in json]\n\n @requires_auth\n def publicize_member(self, login):\n \"\"\"Make ``login``'s membership in this organization public.\n\n :returns: bool\n \"\"\"\n url = self._build_url('public_members', login, base_url=self._api)\n return self._boolean(self._put(url), 204, 404)\n\n @requires_auth\n def remove_member(self, login):\n \"\"\"Remove the user with login ``login`` from this\n organization.\n\n :returns: bool\n \"\"\"\n url = self._build_url('members', login, base_url=self._api)\n return self._boolean(self._delete(url), 204, 404)\n\n @requires_auth\n def remove_repo(self, repo, team):\n \"\"\"Remove ``repo`` from ``team``.\n\n :param str repo: (required), form: 'user/repo'\n :param str team: (required)\n :returns: bool\n \"\"\"\n teams = self.list_teams()\n for t in teams:\n if team == t.name:\n return t.remove_repo(repo)\n return False\n\n @requires_auth\n def team(self, team_id):\n \"\"\"Returns Team object with information about team specified by\n ``team_id``.\n\n :param int team_id: (required), unique id for the team\n :returns: :class:`Team `\n \"\"\"\n json = None\n if int(team_id) > 0:\n url = self._build_url('teams', str(team_id))\n json = self._json(self._get(url), 200)\n return Team(json, self._session) if json else None\n","sub_path":"github3/orgs.py","file_name":"orgs.py","file_ext":"py","file_size_in_byte":17008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"329647157","text":"from flask import (Flask, request, g)\nfrom flask_autodoc import Autodoc\nfrom flask_restful import Api\nfrom mynextbus.common.util import (output_both, output_json, output_xml)\nfrom mynextbus.resources.agencies import Agencies\nfrom mynextbus.resources.favicon import Favicon\nfrom mynextbus.resources.inactiveroutes import InActiveRoutes\nfrom mynextbus.resources.predictions import Predictions\nfrom mynextbus.resources.routeconfig import RouteConfig\nfrom mynextbus.resources.routemessages import RouteMessages\nfrom mynextbus.resources.routes import Routes\nfrom mynextbus.resources.routeschedule import RouteSchedule\nfrom mynextbus.resources.vehiclelocations import VehicleLocations\nfrom operator import itemgetter\nfrom os import environ\nfrom sys import version_info\nfrom time import time\nfrom xml.sax.saxutils import escape\nfrom flask_restful import Resource\n\n\n# WARNING! These two variables are being used as globals in non thread safe manner.\nslow_queries = []\nendpoint_counter = dict()\n\n\napp = Flask(__name__)\napi = Api(app)\nauto = Autodoc(app)\n\n\n#\n# Config\n#\napp.config.from_object('mynextbus.config')\n\n# Allow overriding the default config via the MYNEXTBUS_CONFIG environment variable:\nif 'MYNEXTBUS_CONFIG' in environ:\n app.config.from_envvar('MYNEXTBUS_CONFIG')\n\n\n#\n# Request statistics\n#\n@app.before_request\ndef before_request():\n global endpoint_counter\n\n g.time_started = time()\n if request.url_rule is not None:\n endpoint = request.url_rule.rule\n if endpoint in endpoint_counter:\n endpoint_counter[endpoint] += 1\n else:\n endpoint_counter[endpoint] = 1\n\n\n@app.after_request\ndef after_request(response):\n global slow_queries\n g.time_stopped = time()\n g.time_taken = g.time_stopped - g.time_started\n if g.time_taken >= app.config['NEXTBUS_SLOW_REQUEST_THRESHOLD']:\n slow_queries.append((request.path, g.time_taken))\n slow_queries.sort(key=itemgetter(1), reverse=True)\n if len(slow_queries) > app.config['NEXTBUS_SLOW_REQUESTS_LIST_SIZE']:\n slow_queries = slow_queries[:app.config['NEXTBUS_SLOW_REQUESTS_LIST_SIZE']]\n return response\n\n\nclass SlowQueries(Resource):\n \"\"\"A list of slow requests.\"\"\"\n def get(self):\n global slow_queries\n\n data = ''\n\n if slow_queries is not None:\n for endpoint, time_taken in slow_queries:\n data += '' + escape(endpoint) + '' + str(\n time_taken) + ''\n\n data += ''\n code = 200\n return data, code\n\n\nclass TotalQueries(Resource):\n \"\"\"The total number of queries made to each of the endpoints.\"\"\"\n def get(self):\n global endpoint_counter\n\n data = ''\n\n if endpoint_counter is not None:\n if version_info > (3, 0):\n for endpoint, count in endpoint_counter.items():\n data += '' + escape(endpoint) + '' + str(\n count) + ''\n else:\n for endpoint, count in endpoint_counter.iteritems():\n data += '' + escape(endpoint) + '' + str(\n count) + ''\n\n data += ''\n code = 200\n return data, code\n\n\n#\n# Representations\n#\napi.representations['application/json'] = output_json\napi.representations['application/x-xml'] = output_xml\napi.representations['application/xml'] = output_xml\napi.representations['misc/both'] = output_both\napi.representations['text/xml'] = output_xml\n\n\n#\n# Resources\n#\napi.add_resource(Agencies, '/agencies')\napi.add_resource(Favicon, '/favicon.ico')\napi.add_resource(InActiveRoutes, '/inactiveroutes//')\napi.add_resource(Predictions,\n '/predictions///',\n '/predictions////',\n '/predictions////',\n '/predictions///')\napi.add_resource(RouteConfig, '/routeconfig//')\napi.add_resource(RouteMessages, '/messages//', '/messages//')\napi.add_resource(RouteSchedule, '/schedule//')\napi.add_resource(Routes, '/routes/')\napi.add_resource(VehicleLocations, '/vehiclelocations///')\napi.add_resource(TotalQueries, '/totalqueries')\napi.add_resource(SlowQueries, '/slowqueries')\n\n\n\n\n# Decorate all endpoints with Autodoc.doc():\nif version_info > (3, 0):\n for endpoint, function in app.view_functions.items():\n app.view_functions[endpoint] = auto.doc()(function)\nelse:\n for endpoint, function in app.view_functions.iteritems():\n app.view_functions[endpoint] = auto.doc()(function)\n\n\n@app.route('/')\ndef doc():\n return auto.html(title='MyNextBus API', template=\"autodoc_custom.html\")\n","sub_path":"mynextbus/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"21594332","text":"import importlib\nimport os\nimport pkgutil\nfrom cmd import Cmd\nfrom lib.utils import *\nfrom lib.workplace import WorkPlace\nimport importlib\n\n\nclass CMDLine(Cmd):\n module_list = [\"BASE\"]\n prompt_f = green(\"{}{}{} \") #prompt format\n prompt = \"\" #prompt string\n options = None\n module = None\n base = \"BASE/\" #where the module base of path\n file = None\n record_file = None #use to record the command history\n current_workplace = None # current working place\n module_name = \"\" # name like Web.PHP.mt_seed\n completions = dict() #tab completion dict\n\n def prompt_format(self, module='', prompt=\"fuck\", workplace='None'):\n self.prompt = self.prompt_f.format(blue(module), green(prompt), blue(\"(\") + red(workplace) + blue(\")\"))\n\n def init(self):\n self.prompt_format()\n self.record_file = config_read(\"header\",\"record_file\")\n # for autocompletion of use module\n self.completions[\"use\"] = list()\n\n def _get_modules(name):\n m = None\n for _, module, _ in pkgutil.iter_modules([name]):\n m = module\n _get_modules(name + module + \"/\")\n else:\n if m != None:\n _ = name + m\n self.completions[\"use\"].append(_.replace(\"/\", \".\")[5:])\n\n _get_modules(\"BASE/\")\n\n def __init__(self):\n Cmd.__init__(self)\n print(blue(\"initializing...\"))\n self.init()\n print(blue('done'))\n\n def emptyline(self):\n pass\n\n '''\n \n '''\n\n def do_use(self, arg):\n try:\n self.module = importlib.import_module(\"BASE.\" + arg)\n self.module = self.module.Module()\n self.prompt_format(module=(\"[\" + arg + \"]\"), workplace=self.current_workplace.workplace_name\n if self.current_workplace != None else 'None')\n self.module_name = arg\n self.completions[\"set\"] = list(self.module.getOptions().keys())\n except Exception as e:\n print_error(e)\n\n '''\n ls: list the modules\n '''\n\n def do_ls(self, arg):\n for _, module, _ in pkgutil.iter_modules([\"BASE/\" + arg.replace('.', '/')]):\n print(module)\n\n def do_options(self, arg):\n print_options(self.module.getOptions())\n\n def do_info(self, arg):\n print_info(self.module.getInfo())\n\n def do_set(self, arg: str):\n try:\n key = arg[:arg.find(\" \")]\n value = arg[arg.find(\" \") + 1:]\n self.module.setOption(key, value)\n\n except:\n pass\n\n def do_workplace(self, arg: str):\n try:\n args = arg.split(\" \")\n if args[0] == \"create\":\n args[1] = args[1].strip()\n if args[1].strip() == \"\":\n workplace = WorkPlace(os.getcwd())\n self.current_workplace = workplace\n return\n workplace = WorkPlace(args[1])\n self.current_workplace = workplace\n self.prompt_format(module=self.module_name, workplace=self.current_workplace.workplace_name\n if self.current_workplace != None else 'None')\n elif args[0] == \"use\":\n args[1] = args[1].strip()\n if args[1] == \"\":\n print_warning(\"Must select your workplace\")\n return\n workplace = WorkPlace(args[1])\n self.current_workplace = workplace\n self.prompt_format(module=self.module_name, workplace=self.current_workplace.workplace_name\n if self.current_workplace != None else 'None')\n\n except Exception as e:\n print(e)\n\n def do_shell(self, args):\n try:\n os.system(args)\n except Exception as e:\n print_error(e)\n\n def do_run(self, arg):\n try:\n cache = self.module.run()\n if arg.strip() == \"-save\":\n self.current_workplace.save(cache, self.module_name)\n except KeyboardInterrupt:\n pass\n except Exception as e:\n print(e)\n\n def do_exit(self, arg):\n exit(0)\n\n def do_record(self):\n self.file = open(self.record_file, \"w\")\n\n def close(self):\n if self.file:\n self.file.close()\n self.file = None\n\n def do_playback(self):\n self.close()\n with open(self.record_file) as f:\n self.cmdqueue.extend(f.read().splitlines())\n\n def complete_set(self, text, line, begidx, endidx):\n mline = line.partition(' ')[2]\n offs = len(line) - len(text)\n lines = []\n for s in self.completions[line.partition(' ')[0]]:\n if s.startswith(mline):\n lines.append(s)\n return lines\n\n def complete_use(self, text, line, begidx, endidx):\n mline = line.partition(' ')[2]\n return [s for s in self.completions[\"use\"] if s.startswith(mline)]\n\n\ndef main():\n banner()\n importlib.import_module(\"BASE\")\n parse = CMDLine()\n parse.cmdloop()\n\n\nif __name__ == '__main__':\n try:\n main()\n except:\n pass\n","sub_path":"lib/command/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372714435","text":"#!/usr/bin/env python\n\nimport subprocess\n\np = subprocess.Popen(['sac'], \n stdout = subprocess.PIPE, \n stdin = subprocess.PIPE, \n stderr = subprocess.STDOUT )\n\nout = p.communicate('''\nfg seismo\nlh columns 2\nquit\n'''.encode('ascii'))\n\nprint(out[0].decode())\n\n\n\n","sub_path":"examples/script/sac_script.py","file_name":"sac_script.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353715856","text":"'''\r\nUn robottino deve muoversi su di una scacchiera di 15 x 15 celle con celle bianche e nere ciascuna di lato 40. \r\nPer rendere il percorso accidentato alcune delle celle della scacchiera contengono ostacoli (queste celle sono colorate di rosso).\r\n\r\nUn esempio di scacchiera con ostacoli e' dato dall'immagine 'I1.png'\r\n\r\nPer caricare e salvare immagini PNG usate le funzioni load e save che abbiamo preparato nel modulo immagini.py .\r\n\r\nAl'inizio il robottino e' posizionato sulla prima cella in altro a sinistra della scacchiera ed e' rivolto verso destra (x crescente). \r\nAd ogni step tenta di ragiungere una delle celle adiacenti in orizzontale o verticale. \r\nLe regole di movimento del robottino sono le seguenti: \r\n- al generico step, si sposta sulla cella che ha di fronte se questa e' libera da ostacoli e non ci e' gia transitato in passato. \r\n- se invece la cella risulta occupata o e' una cella su cui ha gia transitato, ruota di 90 gradi in senso orario ed aspetta lo step successivo. \r\n- dopo aver ruotato di 360 gradi senza essere riuscito a spostarsi si ferma. \r\n\r\nProgettare la funzione percorso(fname, fname1) che presi in input:\r\n- il percorso di un file (fname) contenente l'immagine in formato .png di una scacchiera con ostacoli\r\n- il percorso di un file di tipo .png (fname1) da creare\r\nlegge l'immagine della scacchiera in fname, colora di verde le celle della scacchiera percorse dal robottino prima di fermarsi, \r\ncolora di blu la cella in cui il robottino si ferma e registra l'immagine ricolorata nel file fname1. \r\nInoltre restituisce una stringa dove in sequanza sono codificati i passi effettuati dal robottino prima di fermarsi. \r\nLa codifica e' a seguente: \r\n '0' per un passo verso destra (x crescenti)\r\n '1' per un passo verso il basso (y crescenti)\r\n '2' per un passo verso sinistra (x decrescenti)\r\n '3' per un passo verso l'alto (y decrescenti)\r\n\r\nSi puo' assumere che la cella in alto a sinistra sia priva di ostacoli. \r\n\r\nPer esempi di scacchiere con ostacoli e relativi cammini vedere il file grade02.txt \r\n\r\nNOTA: il timeout per la esecuzione del grader e' fissato a 10*N secondi (per N test eseguiti dal grader)\r\n'''\r\n\r\nfrom immagini import *\r\n\r\ndef cammino(fname, fname1):\r\n immagine = load(fname)\r\n direzione = 'destra'\r\n x=0\r\n y=0\r\n counter = 0\r\n percorso = \"\"\r\n while True:\r\n info = checkOstacolo(immagine,direzione,x,y)\r\n direzione = info[3] #direzione nuova presa da info!\r\n if info[0] == False: \r\n if direzione == \"destra\":\r\n percorso += \"0\"\r\n elif direzione == \"giu\":\r\n percorso += \"1\"\r\n elif direzione == \"sinistra\":\r\n percorso += \"2\"\r\n else:\r\n percorso += \"3\"\r\n counter = 0 #il counter conta quante volte cambio la mia direzione dalla posizione in cui sono !Nel momento in cui arriva a 4 vuol dire che non posso piu muovermi e il quadrato lo devo quindi colorare di blu!\r\n immagine = coloraDiVerde(immagine,x,y)\r\n x = info[1]\r\n y = info[2]\r\n else:\r\n counter += 1\r\n if counter == 4:\r\n immagine = coloraDiBlu(immagine,x,y)\r\n break\r\n save(immagine,fname1)\r\n return percorso\r\ndef checkOstacolo(immagine,direzione,x,y):\r\n direzione_da_ritornare = \"\"\r\n x_da_ritornare = x\r\n y_da_ritornare = y\r\n ostacolo = False #all'inizio assumo che non ho ostacolo,solo nel momento in cui mi si verifica che il pixel è rosso ne avrò uno !\r\n if direzione=='destra':\r\n x_temporanea= x+40\r\n if inside(immagine,x+40,y): #se il pixel del quadrato verso destra successivo è rosso allora cambio direzione e dirò che ho un ostacolo\r\n if immagine[y][x_temporanea]== (255,0,0) or immagine[y][x_temporanea] == (0,255,0):\r\n direzione_da_ritornare = \"giu\"\r\n ostacolo = True\r\n else:\r\n x_da_ritornare += 40 #siccome non ho un ostacolo mi sposto avanti di 40 pixel nella stessa direzione in cui ho iniziato (destra)\r\n direzione_da_ritornare = direzione\r\n else:\r\n direzione_da_ritornare = \"giu\"\r\n ostacolo = True\r\n if direzione == 'giu':\r\n y_temporanea= y+40\r\n if inside(immagine,x,y+40):\r\n if immagine[y_temporanea][x]==(255,0,0) or immagine[y_temporanea][x] == (0,255,0):\r\n direzione_da_ritornare='sinistra'\r\n ostacolo = True\r\n else:\r\n y_da_ritornare += 40\r\n direzione_da_ritornare=direzione\r\n else:\r\n direzione_da_ritornare='sinistra'\r\n ostacolo = True\r\n if direzione =='sinistra':\r\n x_temporanea=x-40\r\n if inside(immagine,x-40,y):\r\n if immagine[y][x_temporanea]==(255,0,0) or immagine[y][x_temporanea] == (0,255,0):\r\n direzione_da_ritornare='su'\r\n ostacolo = True\r\n else:\r\n x_da_ritornare -= 40\r\n direzione_da_ritornare=direzione\r\n else:\r\n direzione_da_ritornare='su'\r\n ostacolo = True\r\n if direzione=='su':\r\n y_temporanea=y-40\r\n if inside(immagine,x,y-40):\r\n if immagine[y_temporanea][x]==(255,0,0) or immagine[y_temporanea][x] == (0,255,0):\r\n direzione_da_ritornare='destra'\r\n ostacolo = True\r\n else:\r\n y_da_ritornare -= 40\r\n direzione_da_ritornare=direzione\r\n else:\r\n direzione_da_ritornare='destra'\r\n ostacolo = True\r\n return (ostacolo,x_da_ritornare,y_da_ritornare,direzione_da_ritornare) \r\n \r\n \r\ndef coloraDiBlu(immagine,x,y):\r\n for i in range(40):\r\n for j in range(40):\r\n immagine[i+y][j+x] = (0,0,255)\r\n return immagine \r\n \r\n \r\ndef coloraDiVerde(immagine,x,y):\r\n for i in range(40):\r\n for j in range(40):\r\n immagine[i+y][j+x] = (0,255,0)\r\n return immagine \r\n\r\n\r\n\r\n\r\ndef inside(immagine,x,y):\r\n if x < 0 or x >= len(immagine[0]) or y < 0 or y >= len(immagine):\r\n return False\r\n return True \r\n","sub_path":"students/1750888/homework03/program02.py","file_name":"program02.py","file_ext":"py","file_size_in_byte":6409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"341236602","text":"from django.urls import path\nfrom login_app import views\n\napp_name = \"login_app\"\n\nurlpatterns = [\n path('signup/', views.sign_up, name='signup'),\n path('login/', views.login_sys, name='login'),\n path('logout/', views.logout_sys, name='logout'),\n path('profile/', views.user_profile, name='profile'),\n]","sub_path":"ecommerce_project/login_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"203380688","text":"import sys, logging, json\nfrom scipy.sparse import hstack, csr_matrix\nimport os\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.preprocessing import StandardScaler\nroot_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(root_dir)\n\nfrom util.DataStreamer import DataStreamer\nfrom features.extractors import *\nfrom util.common import save_sparse_csr, load_sparse_csr\n\nimport argparse\n\nparser = argparse.ArgumentParser(description = 'does hyperparameter tuning')\nparser.add_argument('trainExamplesZip', type = str, help = 'bz2 file for training examples')\nparser.add_argument('trainLabels', type = str, help = 'labels file for training pipeline')\nparser.add_argument('testExamplesZip', type = str, help = 'bz2 file for test examples')\nparser.add_argument('out_file', help='where to store the X matrices')\nargs = parser.parse_args()\n\nfeature_extractor = FeatureUnion([\n ('title', Pipeline([\n ('counts', TitleNgramsExtractor(binary=True)),\n ('tfidf', TfidfTransformer(norm='l2', use_idf=True)),\n ('kbest', SelectKBest(chi2, k=100)),\n ])),\n ('body', Pipeline([\n ('counts', BodyNgramsExtractor(binary=False)),\n ('tfidf', TfidfTransformer(use_idf=True, norm='l2')),\n ('kbest', SelectKBest(chi2, k=1000)),\n ])),\n #('code', Pipeline([\n # ('counts', CodeNgramsExtractor()),\n # ('tfidf', TfidfTransformer()),\n # ('kbest', SelectKBest(chi2)),\n #])),\n ('pygment', Pipeline([\n ('counts', PygmentExtractor(binary=True)),\n ('tfidf', TfidfTransformer(use_idf=True)),\n ('kbest', SelectKBest(chi2, k=100)),\n ])),\n ('label', Pipeline([\n ('counts', LabelCountsExtractor(binary=True)),\n ('tfidf', TfidfTransformer(use_idf=True)),\n ])),\n ('bernoulli', Pipeline([\n ('counts', ManualBernoulliExtractor(candidates=['c:', 'd:', '/*', '//', '#!', '\\\\'], code_only=False)),\n ])),\n ('multinomial', Pipeline([\n ('counts', ManualBernoulliExtractor(candidates=[\n '<', '>', '<', '>', '/>'\n '.net',\n '.h',\n 'public static',\n '<page', '<grid', '<bool',\n 'windows.', 'system.', 'bing.',\n '@implementation', '@class', '@property', '@interface', '@end', '@',\n 'class=', 'id=', 'class =', 'id =', 'vb.net', 'hkey_current', '.exe', \n '#import', 'foundation.h',\n 'nsobject', 'nsstring'], code_only=False)),\n ('tfidf', TfidfTransformer(use_idf=True, norm='l2')),\n ])),\n])\n\nexamples = [e for e in DataStreamer.load_from_bz2(args.trainExamplesZip)]\nY = load_sparse_csr(args.trainLabels)\nX = feature_extractor.fit_transform(examples, Y)\nsave_sparse_csr(args.out_file + '.train.X', csr_matrix(X))\n\nexamples = [e for e in DataStreamer.load_from_bz2(args.testExamplesZip)]\nX = feature_extractor.transform(examples)\nif 'val' in args.testExamplesZip:\n save_sparse_csr(args.out_file + '.val.X', csr_matrix(X))\nelse:\n save_sparse_csr(args.out_file + '.test.X', csr_matrix(X))\n","sub_path":"util/extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"509285787","text":"\"\"\"Test OS API.\"\"\"\nfrom pathlib import Path\n\nimport pytest\n\nfrom supervisor.coresys import CoreSys\nfrom supervisor.hardware.data import Device\n\n# pylint: disable=protected-access\n\n\n@pytest.mark.asyncio\nasync def test_api_os_info(api_client):\n \"\"\"Test docker info api.\"\"\"\n resp = await api_client.get(\"/os/info\")\n result = await resp.json()\n\n for attr in (\n \"version\",\n \"version_latest\",\n \"update_available\",\n \"board\",\n \"boot\",\n \"data_disk\",\n ):\n assert attr in result[\"data\"]\n\n\n@pytest.mark.asyncio\nasync def test_api_os_info_with_agent(api_client, coresys: CoreSys):\n \"\"\"Test docker info api.\"\"\"\n await coresys.dbus.agent.connect()\n await coresys.dbus.agent.update()\n\n resp = await api_client.get(\"/os/info\")\n result = await resp.json()\n\n assert result[\"data\"][\"data_disk\"] == \"/dev/sda\"\n\n\n@pytest.mark.asyncio\nasync def test_api_os_datadisk_move(api_client, coresys: CoreSys):\n \"\"\"Test datadisk move without exists disk.\"\"\"\n await coresys.dbus.agent.connect()\n await coresys.dbus.agent.update()\n coresys.os._available = True\n\n resp = await api_client.post(\"/os/datadisk/move\", json={\"device\": \"/dev/sdaaaa\"})\n result = await resp.json()\n\n assert result[\"message\"] == \"'/dev/sdaaaa' don't exists on the host!\"\n\n\n@pytest.mark.asyncio\nasync def test_api_os_datadisk_list(api_client, coresys: CoreSys):\n \"\"\"Test datadisk list function.\"\"\"\n await coresys.dbus.agent.connect()\n await coresys.dbus.agent.update()\n\n coresys.hardware.update_device(\n Device(\n \"sda\",\n Path(\"/dev/sda\"),\n Path(\"/sys/bus/usb/000\"),\n \"block\",\n None,\n [Path(\"/dev/serial/by-id/test\")],\n {\"ID_NAME\": \"xy\", \"MINOR\": \"0\", \"DEVTYPE\": \"disk\"},\n [],\n )\n )\n coresys.hardware.update_device(\n Device(\n \"sda1\",\n Path(\"/dev/sda1\"),\n Path(\"/sys/bus/usb/000/1\"),\n \"block\",\n None,\n [Path(\"/dev/serial/by-id/test1\")],\n {\"ID_NAME\": \"xy\", \"MINOR\": \"1\", \"DEVTYPE\": \"partition\"},\n [],\n )\n )\n\n resp = await api_client.get(\"/os/datadisk/list\")\n result = await resp.json()\n\n assert result[\"data\"][\"devices\"] == [\"/dev/sda\"]\n","sub_path":"tests/api/test_os.py","file_name":"test_os.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"510033062","text":"import numpy as np\nimport matplotlib.pyplot as pyplot\n\nmenMeans = (20, 35, 30, 35, 27)\nmenStd = (2, 3, 4, 1, 2)\nwomenMeans = (25, 32, 34, 20, 25)\nwomenStd = (3, 5, 2, 3, 3)\nmen1Means = (20, 35, 30, 35, 27)\nmen1Std = (2, 3, 4, 1, 2)\nwomen1Means = (25, 32, 34, 20, 25)\nwomen1Std = (3, 5, 2, 3, 3)\n\n\n\nN = len(menMeans) # number of data entries\nind = np.arange(N) # the x locations for the groups\nwidth = 0.35 # bar width\nfig, ax = pyplot.subplots()\nrects1 = ax.bar(ind, menMeans, # data\n width, # bar width\n color='MediumSlateBlue', # bar colour\n yerr=menStd, # data for error bars\n error_kw={'ecolor':'Tomato', # error-bars colour\n 'linewidth':2}) # error-bar width\n\nrects2 = ax.bar(ind + width, womenMeans, \n width, \n color='Tomato', \n yerr=womenStd, \n error_kw={'ecolor':'MediumSlateBlue',\n 'linewidth':2})\nrects3 = ax.bar(ind, men1Means, # data\n width, # bar width\n color='MediumSlateBlue', # bar colour\n yerr=men1Std, # data for error bars\n error_kw={'ecolor':'Tomato', # error-bars colour\n 'linewidth':2}) # error-bar width\n\nrects4 = ax.bar(ind + width, women1Means, \n width, \n color='Tomato', \n yerr=women1Std, \n error_kw={'ecolor':'MediumSlateBlue',\n 'linewidth':2})\n\naxes = pyplot.gca()\naxes.set_ylim([0, 41]) # y-axis bounds\n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,\n '%d' % int(height),\n ha='center', # vertical alignment\n va='bottom' # horizontal alignment\n )\n\nautolabel(rects1)\nautolabel(rects2)\n\npyplot.show() # render the plot","sub_path":"Evaluation/graphGen/newFile.py","file_name":"newFile.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"304618245","text":"import cv2\nimport os\nimport voc_utils as vu\nimport voc_config as vc\n\n#将VOC文件内的图片规整到指定大小,分割的class和object也相应的指定并one-hot\ndef crop_jpeg(origin_path,save_path,imgL):\n for name in os.listdir(origin_path):\n print(name)\n oneOrigin_path = os.path.join(origin_path, name)\n oneSave_path = os.path.join(save_path, name)\n img = cv2.imread(oneOrigin_path)\n img = vu.resize_image_with_crop_or_pad(img,(imgL,imgL))\n cv2.imwrite(oneSave_path,img)\n print('end')\n\ndef crop_seg(origin_path,save_path,imgL,classes):\n for name in os.listdir(origin_path):\n print(name)\n oneOrigin_path = os.path.join(origin_path, name)\n save_name = name.split('.')[0] + '.plk'\n oneSave_path = os.path.join(save_path, save_name)\n plk = vu.segImg2oneHot(oneOrigin_path,imgL,classes)\n vu.save_plk(plk,oneSave_path)\n print('end')\n\n#mode可以是'get'或者是'show'\nmode = 'get'\norigin_path = 'C:/Users/huang/.keras/datasets/VOC2012/VOCdevkit/VOC2012'\nsave_path = 'D:/myVOC2012'\n\nif mode == 'get':\n crop_jpeg(origin_path+'/JPEGImages',save_path+'/JPEGImages',vc.imgL)\n crop_seg(origin_path+'/SegmentationClass',save_path+'/SegmentationClass',vc.imgL,vc.classes)\n crop_seg(origin_path+'/SegmentationObject',save_path+'/SegmentationObject',vc.imgL,None)\nelse:\n for name in os.listdir(save_path+'/SegmentationObject'):\n print(name)\n img_name = name.split('.')[0] + '.jpg'\n one_imgPath = os.path.join(save_path+'/JPEGImages', img_name)\n one_classPath = os.path.join(save_path+'/SegmentationClass', name)\n one_objectPath = os.path.join(save_path + '/SegmentationObject', name)\n print('当前显示一张原图')\n one_img = cv2.imread(one_imgPath)\n vu.imshow(one_img)\n print('当前显示object')\n one_object = vu.load_plk(one_objectPath)\n vu.plkshow(one_object)\n print('当前显示class')\n one_class = vu.load_plk(one_classPath)\n vu.plkshow(one_class)\n","sub_path":"1_voc_crop.py","file_name":"1_voc_crop.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"157207297","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 17 09:16:29 2016\n\n@author: oplab\n\n\"\"\"\nimport lib_aula as aula\n\n#%%\nimagePlot = True\nmappingSwath = 2.0\nstartXMeter = 0\nendXMeter = startXMeter + mappingSwath\nstartYMeter = 0\nendYMeter = mappingSwath\n\n#%%\n\nposX,posY,posZ = aula.loadAndPlotPoints('G:/Cruise/Borneo/DTMBES/20111219/Processoutputs/bathy_points_ply.asc',imagePlot)\nangX,angY,angZ = aula.calcRotateAngles(posX,posY,posZ)\nrotX,rotY,rotZ = aula.rotateAdjustPointsAndPlot(angX,posX,posY,posZ,imagePlot)\n\n\nmeshX,meshY,meshZ = aula.meshBlockPoints(rotX,rotY,rotZ,startXMeter,endXMeter,startYMeter,endYMeter)\n","sub_path":"imageProcessing/maincode.py","file_name":"maincode.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"643359605","text":"#!/usr/bin/env python\n\n'''Usage: server.py [-p PORT] [-d DIRECTORY] [-l FILE]\n\n-h --help show this\n-p --port PORT specify port [default: 8080]\n-d --docroot DIRECTORY specify directory of files [default: ./]\n-l --logfile file specify file for logs to printed to [default: standard output]\n\n'''\n\nfrom docopt import docopt\nimport socket\n\ndef main():\n\n # get values of arguments\n docroot = arguments.get('--docroot')\n port = int(arguments.get('--port'))\n log_file = arguments.get('--logfile')\n\n # create log file if one specified\n if log_file == 'standard output':\n log_file = False\n else:\n log_file = open(log_file, 'w')\n\n # create server\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.setblocking(0)\n server.bind(('localhost', port))\n server.listen(5)\n\nif __name__ == '__main__':\n arguments = docopt(__doc__)\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"590001886","text":"import numpy as np\nimport logging\n\nclass Perceptron:\n def __init__(self,eta,epochs):\n self.weights = np.random.randn(3) * 1e-4 # Randomly Initialize weights\n logging.info(f'Initial weights before training: {self.weights}')\n self.eta = eta\n self.epochs = epochs\n\n def activationFunction(self,input,weights):\n z = np.dot(input, weights)\n return(np.where(z > 0, 1, 0))\n\n def fit(self,X,y):\n self.X = X\n self.y = y\n\n X_with_bias = np.c_[self.X, -np.ones((len(self.X),1))]\n\n for epoch in range(1,self.epochs + 1):\n logging.info('--'*10)\n logging.info(f'For epoch: {epoch}')\n logging.info('--'*10)\n y_hat = self.activationFunction(X_with_bias, self.weights) # Forward Propagation\n logging.info(f'Predicted value after forward pass: {y_hat}')\n self.error = self.y - y_hat\n logging.info(f'Error: \\n{self.error}')\n self.weights = self.weights + self.eta * np.dot(X_with_bias.T, self.error) # Backward Propagation\n logging.info(f'Update weights after epoch: {epoch}/{self.epochs} : {self.weights}')\n self.total_loss()\n logging.info('####'*10)\n\n def predict(self,X):\n X_with_bias = np.c_[X, -np.ones((len(X),1))]\n return(self.activationFunction(X_with_bias, self.weights))\n\n def total_loss(self):\n total_loss = np.sum(self.error) \n logging.info(f'Total Loss: {total_loss}')\n return(total_loss)","sub_path":"src/Perceptron/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"329991948","text":"\"\"\"\nSklearn: query for (cached) nearest neighbors\n\"\"\"\n\nimport numpy as np \nfrom sklearn.neighbors import KDTree \nfrom sklearn.datasets import load_boston \n \nX, y = load_boston(return_X_y=True) \n \nkdt = KDTree(X, leaf_size=2, metric='euclidean') \ndistances, indices = kdt.query(X[0:1], k=5) \n \nprint(\"distances:\", distances) \nprint(\"indices:\", indices) \n\nradius = 50\nindices = kdt.query_radius(X[:1], r=radius)\nprint(len(indices[0]), \"neighbors within distance\", radius)\n\n\"\"\"\nOutput:\ndistances: [[ 0. 16.0970999 16.99995447 18.40100218 18.73017253]]\nindices: [[ 0 241 62 81 60]]\n139 neighbors within distance 50\n\"\"\"\n\n","sub_path":"sklearn_kdtree_basic.py","file_name":"sklearn_kdtree_basic.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"609341852","text":"from datetime import date\r\nimport os\r\n\r\n\r\ndef create_dirs():\r\n os.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n d = date.today()\r\n\r\n for _ in range(12):\r\n create_month_dir_for(d)\r\n if d.month == 1:\r\n d = date(d.year - 1, 12, 1)\r\n else:\r\n d = date(d.year, d.month - 1, 1)\r\n\r\n\r\ndef create_month_dir_for(d):\r\n print(d.strftime('%Y-%m'))\r\n dir = os.path.join(os.getcwd(), d.strftime('%Y-%m'))\r\n if not os.path.exists(dir):\r\n os.mkdir(dir)\r\n else:\r\n print(f'Path {dir} exists. Nothing to do.')\r\n\r\ncreate_dirs()","sub_path":"Python/misc/month_dirs/create-month-dirs.py","file_name":"create-month-dirs.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"215764056","text":"from requests.auth import AuthBase\nimport time\nimport hashlib\nimport hmac\nimport requests\nimport json\n#from swagger_client.api_client import ApiClient\n#import swagger_client\n#from swagger_client.rest import ApiException\nfrom collections import namedtuple\nfrom future.builtins import bytes\nfrom future.standard_library import hooks\nwith hooks(): # Python 2/3 compat\n from urllib.parse import urlparse\nbitmex_api_key = 'K_OIF_xO4hSYdVKGevQejyN2'\nbitmex_api_secret = '5V2rEFVp1fre3PbsXllE8fkH9J_mjuauUScHb3PE4ZF987a7'\ncurrency = namedtuple(\"currency\",[\"Symbol\"])\nclass BitmexDefault(AuthBase):\n def __init__(self, apiKey, apiSecret):\n self.apiKey = apiKey\n self.apiSecret = apiSecret\n #self.url = 'https://www.bitmex.com'\n self.url = 'https://testnet.bitmex.com'\n def Get(self, endpoint, query = None):\n path = '/api/v1' + endpoint\n if query is not None:\n query = json.dumps(query)\n else:\n query = \"\"\n head = self.Header('GET', path, query)\n r = requests.get(self.url + path , data = query , headers=head)\n return json.loads(r.text)\n\n def Delete(self,endpoint,query = None):\n path = '/api/v1' + endpoint\n if query is not None:\n query = json.dumps(query)\n else:\n query = \"\"\n head = self.Header('DELETE', path , query)\n r = requests.delete(self.url + path , data = query , headers=head)\n return json.loads(r.text)\n\n def Post(self,endpoint,query):\n path = '/api/v1' + endpoint\n query = json.dumps(query)\n head = self.Header('POST', path, query)\n r = requests.post(self.url + path , data = query , headers=head)\n print ('bitmex.py/Post:',r.text)\n return json.loads(r.text)\n\n def Header(self, verb, endpoint, data):\n signature = self.generate_signature(verb, endpoint, data)\n headers = {\n 'api-expires': str(self.generate_expires()),\n 'api-key': self.apiKey,\n 'api-signature': signature,\n 'Content-Type':\"application/json\",\n 'Connection': 'close'\n }\n return headers\n\n def generate_expires(self):\n return int(time.time() + 3600)\n\n def generate_signature(self, verb, endpoint, data):\n expires = self.generate_expires()\n message = verb + endpoint + str(expires) + data\n signature = hmac.new(bytes(self.apiSecret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()\n return signature\n\nclass Bitmex():\n def __init__(self,apiKey,apiSecret):\n self.bit = BitmexDefault(apiKey,apiSecret)\n def GetOrder(self,market = None, status = None): # get the newest or more than one ?\n result = []\n endpoint = \"/order\"\n data = {'reverse':'true'}\n if market is not None:\n data['symbol'] = market\n allOrder = self.bit.Get(endpoint,data)\n for order in allOrder:\n print (order)\n ap={}\n ap[\"orderid\"] = order[\"orderID\"]\n ap[\"side\"] = order[\"side\"]\n ap['ordertime'] = order['transactTime']\n ap['orderstatus'] = order['ordStatus']\n ap['price'] = order['price']\n ap['volume'] = order['orderQty']\n ap['ordertype'] = order['ordType']\n ap['market'] = order['symbol']\n if(status is not None and order['ordStatus'] == status):\n result.append(ap)\n elif(status is None):\n result.append(ap)\n return result,len(allOrder)\n def Members_me(self):\n endpoint = \"/user\"\n return self.bit.Get(endpoint)\n def Account(self):\n result = {}\n endpoint = \"/user/walletSummary\"\n allWallet = self.bit.Get(endpoint,'')\n for wallet in allWallet:\n amount = wallet['amount']\n if (float(amount) > 0):\n result[wallet['currency'].lower()] = wallet['amount']\n return result\n def OrderBook(self,symbol):\n endpoint = '/orderBook/L2'\n return self.bit.Get(endpoint,'?symbol=' + symbol)\n def GetTrade(self): #param?\n endpoint = '/trade'\n return self.bit.Get(endpoint,'')\n def GetOrderInfor(self,order):\n result = {}\n print('get order infor :',order)\n orderStatus = order[0]\n result['exchange'] = orderStatus['exDestination']\n result['price'] = orderStatus['price']\n currencyA = currency(order[1])\n currencyB = currency(order[2])\n result['side'] = orderStatus['side']\n result['avgPrice'] = orderStatus['avgPx']\n result['amount'] = orderStatus['orderQty']\n result['pair'] = order[1]+\"_\"+order[2]\n result['Currency'] = {\"CurrencyA\":dict(currencyA._asdict()), \"CurrencyB\":dict(currencyB._asdict())}\n result['orderID2'] = str(orders[0]['orderid'])\n result['ordertime'] = orderStatus['transactTime']\n return result\n \n def Post_orders(self, market,orderside, volume, price, ordertype):\n data = {}\n pairA = market[0:3]\n pairB = market[3:]\n data['symbol'] = pairA + pairB\n data['orderQty'] = volume\n if price is not None:\n data['price'] = price\n if ordertype is not None:\n data['ordType'] = ordertype\n if orderside is not None:\n data['side'] = orderside\n endpoint = '/order'\n order = self.bit.Post(endpoint,data),pairA,pairB\n try:\n infor = self.GetOrderInfor(order)\n except:\n infor = order\n #print (infor)\n return infor\n \n def DeleteOrder(self, orderID = None):\n endpoint = '/order'\n data = {}\n if orderID is not None:\n data['orderID'] = orderID\n print (data)\n order = self.bit.Delete(endpoint,data)\n return order\n\n def DeleteAllOrder(self,pair = None):\n endpoint = '/order/all'\n data ={}\n if pair is not None:\n data = {'symbol': pair}\n order = self.bit.Delete(endpoint,data)\n return order\n\n\ntest = Bitmex(bitmex_api_key,bitmex_api_secret)\n#print (test.GetOrder('new'))\n#market,orderside, volume, price, ordertype\n#print (test.Post_orders('XBTUSD','Buy',3,3000,'limit'))\n#print (test.Post_orders('XBT','USD',orderside='Sell',price=123.0))\n#print (test.GetOrder('XBTUSD'))\n#print (test.Members_me())\n#rint (test.DeleteOrder(orderID='4ea64203-dc50-9e7c-6d9a-a4fe45268ff7'))\n#print (test.GetOrder('ETHUSD'))\n#a = currency()\n#print a\n#print (test.DeleteAllOrder())\n#print (test.GetOrder())\n","sub_path":"bitmex.py","file_name":"bitmex.py","file_ext":"py","file_size_in_byte":6598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"125067448","text":"\"\"\"\nHealth Check Web Controller\n\"\"\"\n\n# Third Party Library\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom django.utils.translation import gettext as _\n\n# Local Library\nfrom app.modules.core.health import Health\nfrom app.modules.util.helpers import Helpers\nfrom app.modules.core.response import Response\n\n\nclass HealthCheck(View):\n\n __response = None\n __correlation_id = None\n __health = None\n __helpers = None\n __logger = None\n\n def get(self, request):\n\n self.__correlation_id = request.META[\"X-Correlation-ID\"] if \"X-Correlation-ID\" in request.META else \"\"\n self.__response = Response()\n self.__health = Health()\n self.__helpers = Helpers()\n self.__logger = self.__helpers.get_logger(__name__)\n\n status = Health.OK\n errors = []\n errors.extend(self.__health.check_db())\n errors.extend(self.__health.check_io())\n errors.extend(self.__health.check_workers())\n\n if len(errors) > 0:\n status = Health.NOT_OK\n self.__logger.error(_(\"Health Check Result: %(status)s %(errors)s {'correlationId':'%(correlationId)s'}\") % {\n \"status\": status,\n \"errors\": self.__helpers.json_dumps(errors),\n \"correlationId\": self.__correlation_id\n })\n else:\n self.__logger.debug(_(\"Health Check Result: %(status)s %(errors)s {'correlationId':'%(correlationId)s'}\") % {\n \"status\": status,\n \"errors\": self.__helpers.json_dumps(errors),\n \"correlationId\": self.__correlation_id\n })\n\n return JsonResponse(self.__response.send({\n \"status\": status\n }, self.__correlation_id), status=200 if status == Health.OK else 503)\n","sub_path":"app/controllers/web/health_check.py","file_name":"health_check.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"37621666","text":"import tensorflow as tf\nfrom tensorflow.keras import layers\n\n\ndef get_architecture_op(num_nodes=512):\n def architecture_op(ranking_features):\n first_dense = layers.Dense(num_nodes, activation=\"relu\", name=\"first_dense\")(\n ranking_features\n )\n first_dropout = layers.Dropout(rate=0.3, name=\"first_dropout\")(first_dense)\n final_dense = layers.Dense(64, activation=\"relu\", name=\"final_dense\")(first_dropout)\n # _ = tf.keras.layers.Dropout(rate=0.1g)(_)\n scores = layers.Dense(1, name=\"scores\")(final_dense)\n\n # Collapse extra dimensions\n scores = tf.squeeze(scores, axis=-1)\n\n return scores\n\n return architecture_op\n","sub_path":"python/ml4ir/model/architectures/dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408390273","text":"\"\"\"Usage:\n\nThis script should be placed with runexp.py.\nI recommend to copy two files (this and runexp.py) in each directory where experiments are done.\n\n### Usage 1: Low-level management of QusbWorkflow\n\n# First, define the template qsub file for your experiment.\n# In this template, __XXX__ is a placeholder, which will be filled by variable `xxx` given to `new_env` argument later.\ntemplate = '''#!/bin/bash\n\n#$-l __MACHINE__=1\n#$-l h_rt=__TIME__\n#$-j y\n#$-cwd\n# you can add more preambles here.\n\nsource /etc/profile.d/modules.sh\nsource __VENV__/bin/activate # __VENV__ is filled by some value if `venv` argument is given (see below).\n# conda activate __CONDA__ # In this case, variable `conda` will replace __CONDA__.\n\ncd __DIR__ # __DIR__ is automatically replaced with the current directory.\n\n__CMD__\n'''\n\n# When dry_run=True, the command will not be executed (similar to dry_run in make).\nwith QsubWorkflow(template=template, qsub_dir='qsubs', dry_run=True) as workflow:\n with workflow.new_env(time='5:00', venv='/path/venv', delete_qsub=False) as env:\n env.add_task('echo a > a.txt', tgt='a.txt') # this will regist new qsub script (which will be created in `qsub_dir` directory, and deleted if `delete_qsub` is True).\n env.add_task('echo b > b.txt', tgt='b.txt')\n with workflow.new_env(time='3:00', venv='/path/venv') as env:\n env.add_task('echo c > c.txt', tgt='c.txt')\n workflow.run() # wrap exp.run()\n\n\n### Usage 2: using run_qsub to avoid managing QusbWorkflow by yourself.\n\ntemplate = '''#!/bin/bash\n\n#$-l __MACHINE__=1\n#$-l h_rt=__TIME__\n#$-j y\n#$-cwd\n# you can add more preambles here.\n\nsource /etc/profile.d/modules.sh\nsource __VENV__/bin/activate # __VENV__ is filled by some value if `venv` argument is given (see below).\n# conda activate __CONDA__ # In this case, variable `conda` will replace __CONDA__.\n\ncd __DIR__ # __DIR__ is automatically replaced with the current directory.\n\n__CMD__\n'''\n\ndef add_task_fn_gen(chars):\n def add_task(env):\n for x in chars:\n cmd = 'echo {} > {}.txt'.format(x, x)\n env.add_task(cmd, tgt='{}.txt'.format(x))\n return add_task\n\nadd_task_fns = [add_task_fn_gen(['a', 'b', 'c'])] # A list of functions to add a task to `env`.\n\nrun_qsub(add_task_fns, template, venv='/path/venv')\n\n\"\"\"\n\nfrom hashlib import md5\nimport logging\nimport numpy as np\nimport os\nimport itertools\nfrom pathlib import Path\nfrom runexp import Workflow\nimport signal\nfrom subprocess import Popen\nimport sys\n\nlogging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO,\n)\nlogger = logging.getLogger(__name__)\n\ndef run_qsub(add_task_fns, template, dry_run=False, num_jobs=128, time='5:00:00', group='gac50547',\n sync=True, machine='rt_G.small', keep_going=True, delete_qsub=False,\n qsub_dir='qsub', **env_args):\n \"\"\"A wrapper of QusbWorkflow, which regists all tasks created by functions in `add_task_fns`.\n\n Parameters\n ----------\n add_task_fns : list\n A list of functions, each of which receives `env` variable and call `add_task`\n (regist a new task). `env` is an instance of `QsubEnv` and `add_task` has\n three arguments:\n `add_task(self, cmd, src=None, tgt=None).`\n `cmd` is a shell command to be executed (e.g., train or evaluate a model).\n `src` and `tgt` is source and target files, which define the order of execusion\n of tasks. The order is determined so that all `src`s in any task should be\n created before execusion (i.e., in typological order of a graph defined by source\n and targets). `src` and `tgt` can be a str, or a list of str, if multiple files\n are source or target.\n template : str\n A template qsub file. __XXX__ is a placeholder that can be filled by custom variables\n (see also **env_args).\n dry_run : bool\n If True, do not run the command and just simulate the execusion.\n num_jobs : int\n Number of parallel qsub jobs.\n time : str\n The time in the format of qsub.\n group : str\n Your ABCI group.\n sync : bool\n If False, the tasks are executed asynchronously, and just finish after calling all\n qsub tasks. This should be `True` when there is a dependence between different tasks\n (by src and tgt). Setting this to `False` is useful when you want to avoid to remain\n the process (of this function) due to some reason, e.g., to avoid to occupy a process\n in Jupyter.\n machine : str\n The machine name of ABCI.\n keep_going : bool\n If False, all qsub commands are killed when there is an error in some command.\n delete_qsub : bool\n Before calling a qusb command, all qsub script will be stored in `qsub_dir` directory.\n These files are deleted when this is True.\n qsub_dir : str\n The directory in which all qsub files are stored.\n **env_args\n Additional arguments to be used to fill placeholders in `template`. For example,\n when the template contains the following line:\n `conda activate __CONDA__`,\n by run_qsub(..., conda='torch-1.7'), this __CONDA__ will be filled by `torch-1.7`.\n \"\"\"\n if not isinstance(add_task_fns, list):\n add_task_fns = [add_task_fns]\n with QsubWorkflow(template=template, dry_run=dry_run, num_jobs=num_jobs, keep_going=keep_going,\n qsub_dir=qsub_dir) as workflow:\n with workflow.new_env(machine=machine, time=time, delete_qsub=delete_qsub,\n sync=sync, group=group, **env_args) as env:\n for add_task_fn in add_task_fns:\n add_task_fn(env)\n workflow.run()\n\nclass QsubTask:\n def __init__(self, env, cmd, src, tgt):\n self.env = env\n self.cmd = cmd\n self.src = src or []\n self.tgt = tgt or []\n\nclass QsubEnv:\n\n def __init__(self,\n workflow,\n time='5:00:00',\n group='gac50428',\n machine='rt_G.small',\n workdir='./',\n delete_qsub=True,\n sync=True,\n **template_args):\n self.workflow = workflow\n self.time = time\n self.group = group\n self.machine = machine\n self.workdir = workdir\n self.delete_qsub = delete_qsub\n self.sync = 'y' if sync else 'n'\n self.template_args = dict([('__{}__'.format(k.upper()), v) for k, v in template_args.items()])\n\n def add_task(self, cmd, src=None, tgt=None):\n self.workflow.add_task(QsubTask(self, cmd, src, tgt))\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n\nclass QsubWorkflow:\n\n def __init__(self, qsub_dir = \"./\", template = None, **args):\n self.tasks = []\n self.qsub_paths = []\n self.qsub_dir = Path(qsub_dir)\n\n self.exp = Workflow(args=[])\n self.exp.set_options(**args)\n\n self.template = template or '''\n#!/bin/bash\n\n#$-l __MACHINE__=1\n#$-l h_rt=__TIME__\n#$-j y\n#$-cwd\n\nsource /etc/profile.d/modules.sh\nsource __CUDA_MODULE__\n. /home/aaa10317sm/anaconda3/etc/profile.d/conda.sh\nconda activate __CONDA__\n\ncd __DIR__\n\n__CMD__'''\n\n def new_env(self, **args):\n env = QsubEnv(self, **args)\n return env\n\n def add_task(self, task):\n qsub_content = self._mk_qsub_content(task)\n code = md5(qsub_content.encode('utf-8')).hexdigest()\n\n if not self.qsub_dir.exists():\n self.qsub_dir.mkdir()\n qsub_path = self.qsub_dir / 'qsub-{}.sh'.format(code)\n with qsub_path.open('wt') as f:\n f.write(qsub_content)\n\n self.tasks.append(task)\n self.qsub_paths.append(qsub_path)\n\n self.exp(name = task.tgt, source=task.src, target=task.tgt,\n rule='qsub -g {} -sync {} {}'.format(\n task.env.group, task.env.sync, qsub_path))\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n for task, qsub_path in zip(self.tasks, self.qsub_paths):\n if task.env.delete_qsub and qsub_path.exists():\n qsub_path.unlink()\n\n def run(self):\n self.exp.run()\n\n def _mk_qsub_content(self, task):\n env = task.env\n workdir = Path(os.getcwd()) / env.workdir\n replace_dict = {\n **env.template_args,\n **{'__MACHINE__': env.machine,\n '__TIME__': env.time,\n '__DIR__': workdir,\n '__CMD__': task.cmd,\n }}\n template = self.template\n for k, v in replace_dict.items():\n template = template.replace(str(k), str(v))\n return template\n\n\nclass ParamSet:\n\n def __init__(self):\n self.params = []\n\n def add_list(self, params = []):\n self.params.extend(params)\n\n def add_grid_search(self, parameters = {}):\n self.params.extend(self._product(parameters))\n\n def add_random_samples(self, param_to_generator, num_samples):\n for i in range(num_samples):\n param = dict([(k, param_to_generator[k]()) for k in param_to_generator])\n self.params.append(param)\n\n def sorted_params(self):\n return [sorted(p.items()) for p in self.params]\n\n def _product(self, parameters):\n '''\n >>> product({'x': [0, 1, 2], 'y': [1, 3, 5]})\n [{'x': 0, 'y': 1}, {'x': 0, 'y': 3}, {'x': 0, 'y': 5},\n {'x': 1, 'y': 1}, {'x': 1, 'y': 3}, {'x': 1, 'y': 5},\n {'x': 2, 'y': 1}, {'x': 2, 'y': 3}, {'x': 2, 'y': 5}]\n '''\n keys = sorted(parameters)\n values = [parameters[key] for key in keys]\n values_product = itertools.product(*values)\n return [dict(zip(keys, vals)) for vals in values_product]\n\n\nclass RandGen:\n\n @staticmethod\n def categorical(choices=[]):\n return lambda: np.random.choice(choices)\n\n @staticmethod\n def uniform(low, high, precision=10):\n \"\"\"los <= x < high\"\"\"\n return lambda: round(np.random.uniform(low, high), precision)\n\n @staticmethod\n def loguniform(low, high, precision=10):\n return lambda: round(np.exp(np.random.uniform(np.log(low), np.log(high))), precision)\n\n @staticmethod\n def uniform_int(low, high):\n \"\"\"low <= x < high\"\"\"\n return lambda: np.random.randint(low, high)\n\n @staticmethod\n def store_true():\n return categorical(['store_true_yes', 'store_true_no'])\n\n\nclass QsubJob:\n\n def __init__(self,\n cmd,\n time='5:00:00',\n conda='torch-1.7',\n group='gac50428',\n cuda_module='~/load_cuda_moduels.sh',\n machine='rt_G.small',\n delete_qsub=True,\n sync=True,\n dry_run=False):\n self.cmd = cmd\n self.time = time\n self.conda = conda\n self.group = group\n self.cuda_module = cuda_module\n self.machine = machine\n self.delete_qsub = delete_qsub\n self.sync = 'y' if sync else 'n'\n self.dry_run = dry_run\n\n self.qsub_path = None\n\n def run(self):\n assert self.qsub_path is not None\n cmd = 'qsub -g {} -sync {} {}'.format(self.group, self.sync, self.qsub_path)\n logger.info('Run: {} ({})'.format(cmd, self.cmd))\n if not self.dry_run:\n try:\n proc = Popen(cmd, shell=True, close_fds=True, preexec_fn=os.setpgrp)\n ret = proc.wait()\n except KeyboardInterrupt as e:\n logger.info('Terminating the running task...')\n os.killpg(proc.pid, signal.SIGTERM)\n return 1\n except Exception as e:\n logger.info('ExecCommand: Unknown error raised')\n os.killpg(proc.pid, signal.SIGTERM)\n return 1\n return ret\n\n def __enter__(self):\n qsub_content = self._mk_content()\n code = md5(qsub_content.encode('utf-8')).hexdigest()\n qsub_path = 'qsub-{}.sh'.format(code)\n with Path(qsub_path).open('wt') as f:\n f.write(qsub_content)\n self.qsub_path = qsub_path\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.delete_qsub and Path(self.qsub_path).exists():\n Path(self.qsub_path).unlink()\n self.qsub_path is None\n\n def _mk_content(self):\n return '''#!/bin/bash\n\n#$-l {}=1\n#$-l h_rt={}\n#$-j y\n#$-cwd\n\nsource /etc/profile.d/modules.sh\nsource {}\n. /home/aaa10317sm/anaconda3/etc/profile.d/conda.sh\nconda activate {}\n\ncd {}\n\n{}\n'''.format(self.machine, self.time, self.cuda_module, self.conda, os.getcwd(), self.cmd)\n\ndef run_command(cmd, **args):\n with QsubJob(cmd, **args) as j:\n j.run()\n\nif __name__ == '__main__':\n\n env_args = {'conda': 'torch-1.7', 'cuda_module': '~/load_cuda_moduels.sh'}\n with QsubWorkflow(dry_run=True, keep_going=True, num_jobs=1) as workflow:\n with workflow.new_env(machine='rt_C.small', **env_args, delete_qsub=False) as env:\n env.add_task('ls -alh > ls1.txt', tgt='ls1.txt')\n env.add_task('ls -al > ls2.txt', tgt='ls2.txt')\n with workflow.new_env(time='0:10:00', **env_args) as env:\n env.add_task('ls > ls3.txt', tgt='ls3.txt')\n\n workflow.run()\n\n\n template = '''#!/bin/bash\n\n#$-l __MACHINE__=1\n#$-l h_rt=__TIME__\n#$-j y\n#$-cwd\n# you can add more preambles here.\n\nsource /etc/profile.d/modules.sh\nsource ~/load_cuda_moduels.sh\n. /home/aaa10317sm/anaconda3/etc/profile.d/conda.sh\nconda activate __CONDA__\n\ncd __DIR__\n\n__CMD__\n'''\n def add_task_fn_gen(chars):\n def add_task(env):\n for x in chars:\n cmd = 'echo {} > {}.txt'.format(x, x)\n env.add_task(cmd, tgt='{}.txt'.format(x))\n return add_task\n\n add_task_fns = [add_task_fn_gen(['a', 'b', 'c'])] # A list of functions to add a task to `env`.\n\n run_qsub(add_task_fns, template, dry_run=False, conda='torch-1.7')\n\n","sub_path":"qsub_manager.py","file_name":"qsub_manager.py","file_ext":"py","file_size_in_byte":14097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"230785255","text":"from django.shortcuts import render\nfrom budgetApp.models import Stuff\nfrom budgetApp.forms import NewCategory\n\n\n\n# Create your views here.\ndef index(request):\n form = NewCategory()\n budget_list = Stuff.objects.order_by('top_name')\n amount_budgeted = 0\n amount_spent = 0\n income = 0\n for i in budget_list:\n amount_budgeted += i.budgeted\n amount_spent += i.actual\n budgeted_saved = income - amount_budgeted\n amount_saved = (amount_budgeted-amount_spent)\n\n\n if request.method == \"POST\":\n\n #postData = request.POST\n #return render(request,'budgetApp/test.html', {'postData': postData})\n\n if 'newExpense' in request.POST:\n category = request.POST[\"Add\"]#category you want to add the expense to\n amount_spent = int(request.POST[\"newExpense\"])\n category_info = Stuff.objects.get(top_name=category)\n current_spent = int(category_info.actual)\n current_spent += amount_spent\n category_info.actual = current_spent\n category_info.save()\n form = NewCategory()\n budget_list = Stuff.objects.order_by('top_name')\n amount_budgeted = 0\n amount_spent = 0\n for i in budget_list:\n amount_budgeted += i.budgeted\n amount_spent += i.actual\n budgeted_saved = income - amount_budgeted\n amount_saved = (income-amount_spent)\n return render(request,'budgetApp/index.html', {'stuff': budget_list, 'form':form, 'budgeted_saved':int(budgeted_saved),'amount_budgeted':int(amount_budgeted), 'amount_spent':int(amount_spent), 'amount_saved':int(amount_saved)})\n #old method of testing below\n #postData = category_info\n #return render(request,'budgetApp/test.html', {'postData': postData})\n\n if \"newCategory\" in request.POST:\n form = NewCategory(request.POST)\n if form.is_valid():\n form.save(commit=True)\n form = NewCategory()\n budget_list = Stuff.objects.order_by('top_name')\n amount_budgeted = 0\n amount_spent = 0\n for i in budget_list:\n amount_budgeted += i.budgeted\n amount_spent += i.actual\n budgeted_saved = income - amount_budgeted\n amount_saved = (income-amount_spent)\n return render(request,'budgetApp/index.html', {'stuff': budget_list, 'form':form, 'budgeted_saved':int(budgeted_saved),'amount_budgeted':int(amount_budgeted), 'amount_spent':int(amount_spent), 'amount_saved':int(amount_saved)})\n else:\n print ('error form is invalid')\n return render(request,'budgetApp/index.html', {'stuff': budget_list, 'form':form, 'budgeted_saved':int(budgeted_saved),'amount_budgeted':int(amount_budgeted), 'amount_spent':int(amount_spent), 'amount_saved':int(amount_saved)})\n\ndef test(request):\n budget_list = Stuff.objects.order_by('top_name')\n postData = []\n for i in budget_list:\n postData.append(i.budgeted)\n return render(request,'budgetApp/test.html', {'postData': postData})\n","sub_path":"budgetApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"168577108","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport dataset\nfrom sklearn.tree import DecisionTreeClassifier # , plot_tree\nfrom sklearn.model_selection import train_test_split\n\nN = 50 # number of points per class, namely number of students\nD = 7 # dimensionality of work choice factors\nK = 8 # number of classes of work type\n\n# X, y = dataset.get_data(N, D, K)\nX = np.loadtxt('ReplacedData.txt')\ny = np.loadtxt('work_choice.txt')\nx = []\nfrom itertools import chain\n\nfor i in range(int(len(X) / K)):\n tmp = X[i * K:(i + 1) * K]\n x.append(list(chain.from_iterable(tmp)))\n\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\n\nmodel = LogisticRegression(penalty='l2', dual=False, tol=1e-4, C=1.0,\n fit_intercept=True, intercept_scaling=1, class_weight=None,\n random_state=None, solver='liblinear', max_iter=100,\n multi_class='ovr', verbose=0, warm_start=False, n_jobs=1)\n# model = SGDClassifier()\n# for i in range(1000000):\n# x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=np.random.randint(0, 100000),\n# shuffle=True)\n# model.fit(x_train, y_train)\n# prediction = model.predict(x_test)\n# acc = sum(int(prediction[i] == y_test[i]) for i in range(len(y_test)))\n# print('the number of accurate work in all 10 test samples is:', acc)\n# if acc >= 8:\n# x_train_best, x_test_best, y_train_best, y_test_best = x_train, x_test, y_train, y_test\n# np.savetxt('x_train_best.txt', x_train_best)\n# np.savetxt('x_test_best.txt', x_test_best)\n# np.savetxt('y_train_best.txt', y_train_best)\n# np.savetxt('y_test_best.txt', y_test_best)\n# model_best = model\n# break\n\nx_train_best, x_test_best = np.loadtxt('x_train_best.txt'), np.loadtxt('x_test_best.txt')\ny_train_best, y_test_best = np.loadtxt('y_train_best.txt'), np.loadtxt('y_test_best.txt')\nmodel.fit(x_train_best, y_train_best)\nprediction = model.predict(x_test_best)\nprint(prediction)\nprint(y_test_best)\nacc = sum(int(prediction[i] == y_test_best[i]) for i in range(len(y_test_best)))\nprint(acc)\nnp.savetxt('W_matrix.txt', model.coef_)\nprint('love world')\nprint('hello world')\n","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"254205268","text":"from tensorlib.research.resnet_v1_beta.resnet_v1_beta import ResNet_V1_beta_block, ResNet_V1_small_beta_block\nimport tensorlib as lib\nimport tensorflow as tf\nfrom collections import namedtuple\n\n\nBLOCKS = {'bottleneck': ResNet_V1_beta_block,\n 'lite_bottleneck': ResNet_V1_small_beta_block}\n\n\nclass HRStage(namedtuple('HRStage', ['scope', 'module_fn', 'args'])):\n pass\n\n\ndef stack_stages(net, stages):\n nets = [net]\n for i, stage in enumerate(stages):\n with tf.name_scope(stage.scope, 'stage', nets):\n for j, module in enumerate(stage.args):\n point_name = 'module_%d' % (j + 1)\n nets = stage.module_fn(nets, **dict(module, name=point_name))\n if i + 1 < len(stages):\n block_type = stages[i + 1].args[0]['block_type']\n expansion = 4 if block_type == 'bottleneck' else 1\n depths = [depth * expansion for depth in stages[i + 1].args[0]['depths']]\n nets = fusion_block(nets, depths=depths)\n return nets\n\n\ndef fusion_block(nets, depths, fuse_method='sum', name='fusion'):\n \"\"\"\n Exchange information between different spatial feature maps\n Implementation better show in graph: for e.g. (3 nets, 4 depths)\n prepare net vector [None, None, None]\n i is iterator of nets in [0, 1, 2], j is iterator of depths in [0, 1, 2, 3]\n set nets = [x, y, z], ↑: up sample, ↓: down sample\n iteration procedure:\n iter 0: net vector = [x, y↑, z↑] -> do fusion\n iter 1: net vector = [x↓, y, z↑] -> do fusion\n iter 2: net vector = [x↓↓, y↓, z] -> do fusion\n iter 3: net vector = [x↓↓↓, y↓↓, z↓] -> do fusion\n we can find an rule: original tensors in diagonal\n down sample tensors below diagonal, and k+1 iter's tensors only need\n down sample one time using k iter's tensors\n up sample tensors upon diagonal\n In this way, we can reuse previous iteration's down sample results\n and only in O(n^2) cost\n \"\"\"\n assert len(depths) - len(nets) == 1, \\\n \"num of depths({:d}) - num of nets({:d}) must be 1\".format(len(depths), len(nets))\n with tf.name_scope(name, values=nets):\n spatial = [lib.engine.int_shape(net)[1:-1] for net in nets]\n net_vector = [None] * len(nets)\n outputs = []\n # Due to python's lazy evaluation mechanism,\n # we can not pass a spatial[i] with a variable i into lambda.\n # lambda only remembers the last value of i, instead of the value\n # when it was passed to lambda, so we need to make it to be a local\n # variable of lambda, it can be done in two ways\n # 1. currying, exactly the way we do in the below codes\n # 2. use 'lambda x, size=spatial[i]: ....'\n resize_fn = lambda size: lambda x: tf.image.resize_bilinear(\n x, size=size, align_corners=True)\n for i, depth in enumerate(depths):\n for j in range(len(nets)):\n num = i - j\n if num == 0:\n net_vector[j] = nets[j]\n elif num < 0:\n net_vector[j] = lib.layers.Lambda(\n resize_fn(spatial[i]),\n name='upsample')(nets[j])\n net_vector[j] = lib.contrib.Conv2D(\n out_channels=depth, kernel_size=1,\n name='c_reduce')(net_vector[j])\n else:\n net_vector[j] = lib.contrib.Conv2D(\n out_channels=depth, kernel_size=3,\n stride=2, name='downsample')(net_vector[j])\n if len(net_vector) > 1:\n if fuse_method == 'sum':\n outputs.append(lib.layers.Lambda(lambda x: tf.add_n(x), name='sum_fusion')(*net_vector))\n else:\n outputs.append(lib.layers.concat(*net_vector, axis=-1))\n else:\n outputs.append(net_vector[0])\n return outputs\n\n\ndef hrnet_arg_scope(\n weight_decay=0.0001,\n batch_norm_decay=0.997,\n batch_norm_epsilon=1e-5,\n activation_fn='relu',\n use_batch_norm=True,\n use_weight_standardization=False):\n batch_norm_params = {\n 'decay': batch_norm_decay,\n 'epsilon': batch_norm_epsilon,\n }\n\n with lib.engine.arg_scope(\n [lib.contrib.WSConv2D],\n kernel_regularizer=lib.regularizers.l2(weight_decay),\n kernel_initializer='truncated_normal',\n activation_fn=activation_fn,\n normalizer_fn=lib.layers.BatchNorm if use_batch_norm else None,\n use_weight_standardization=use_weight_standardization):\n with lib.engine.arg_scope([lib.layers.BatchNorm], **batch_norm_params) as arg_sc:\n return arg_sc\n","sub_path":"tensorlib/research/hrnet/hrnet_utils.py","file_name":"hrnet_utils.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"33548225","text":"import random,sys,os\nimport numpy as np\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\ntf_version = int((tf.__version__)[0])\n\nfrom tensorflow.python.client import device_lib\nfrom keras.models import Sequential,Model\nfrom keras.layers import Dense,Dropout,Input,BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\nfrom mpi4py import MPI\nimport random, math\nimport time\n \nif __name__ == \"__main__\":\n\n start = time.time()\n comm = MPI.COMM_WORLD\n rank = comm.rank\n size = comm.size\n \n num_cores = os.cpu_count()\n num_CPU = os.cpu_count()\n num_GPU = 0\n\n if tf_version < 2:\n gpu_names = [x.name for x in device_lib.list_local_devices() if x.device_type == 'GPU']\n if rank==0 and len(gpu_names)>0:\n num_cores = 1\n num_CPU = 1\n num_GPU = len(gpu_names)\n config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,\n inter_op_parallelism_threads=num_cores, \n allow_soft_placement=True,\n log_device_placement=True,\n device_count = {'CPU' : num_CPU,\n 'GPU' : num_GPU})\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n set_session(sess)\n elif tf_version >= 2:\n '''\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.compat.v1.Session(config=config)\n tf.compat.v1.keras.backend.set_session(sess)\n '''\n tf.debugging.set_log_device_placement(True)\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if gpus:\n try:\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n '''\n # Restrict TensorFlow to only allocate MEM_LIMIT amount of memory\n MEM_LIMIT = 16000 / self.size\n for devIdx in np.arange(len(gpus)):\n tf.config.experimental.set_virtual_device_configuration(\n gpus[devIdx],\n [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=MEM_LIMIT)])\n '''\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n except RuntimeError as e:\n print(e)\n\n ITERS = 5 \n matsize = 10\n if rank==0:\n print('Perform TF MATMUL on every process using square matrix size of ', matsize, ' for ', ITERS, ' iterations.')\n \n arr = np.ones((matsize,matsize))\n tften = tf.constant(arr)\n for e in (range(ITERS)):\n #tfout = tf.matmul(tften, tften)\n time.sleep(10)\n\n elapse = time.time() - start \n sum_elapse = comm.reduce(elapse, op=MPI.SUM, root=0)\n if rank==0:\n print(\" Average elapsed time per iteration = \", sum_elapse/(size*(ITERS if ITERS else 1)))\n","sub_path":"tfinit.py","file_name":"tfinit.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"301730637","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/synctools/stacks/reconstruction/lamino.py\n# Compiled at: 2020-03-06 02:01:31\n# Size of source mod 2**32: 7697 bytes\n__author__ = [\n 'H. Payno']\n__license__ = 'MIT'\n__date__ = '01/10/2018'\nfrom queue import Queue\nfrom silx.gui import qt\nfrom tomwer.core.log import TomwerLogger\nfrom tomwer.core.scan.scanbase import TomoBase\nfrom tomwer.core.process.reconstruction.lamino.tofu import _tofu_lamino_reconstruction\nimport copy\nfrom tomwer.core.process.reconstruction.lamino.tofu import LaminoReconstruction\nfrom tomwer.core.utils.Singleton import singleton\nfrom tomwer.web.client import OWClient\nlogger = TomwerLogger(__name__)\n\n@singleton\nclass LaminoReconstructionStack(qt.QObject, Queue, OWClient):\n __doc__ = '\\n Manage a stack of lamino (tofu) reconstruction\\n '\n sigReconsFinished = qt.Signal(TomoBase)\n sigReconsFailed = qt.Signal(TomoBase)\n sigReconsMissParams = qt.Signal(TomoBase)\n sigReconsStarted = qt.Signal(TomoBase)\n\n def __init__(self):\n qt.QObject.__init__(self)\n Queue.__init__(self)\n OWClient.__init__(self, logger)\n self.reconsThread = _LaminoReconsThread()\n self.reconsThread.sigThReconsFinished.connect(self._dealWithFinishedRecons)\n self.reconsThread.sigThReconsFailed.connect(self._dealWithFailedRecons)\n self.reconsThread.sigThMissingParams.connect(self._dealWithThMissingParams)\n self._forceSync = False\n\n def add(self, recons_obj, recons_params, additional_opts, scan_id, remove_existing, callback):\n \"\"\"\n add a reconstruction and will run it as soon as possible\n\n :param recons_obj: reconstructor, keeping trace of preprocess flat field\n correction for example.\n :type recons_obj: LaminoReconstruction\n :param dict reconsParams: parameters of the reconstruction\n :param dict additional_opts: not managed directly by the gui\n :param scan_id: the folder of the acquisition to reconstruct\n :type: TomoBase\n :param bool remove_existing: if True then remove output dir before\n reconstruction\n :param callback: function to call after the reconstruction execution\n \"\"\"\n assert isinstance(recons_obj, LaminoReconstruction)\n Queue.put(self, (recons_obj, recons_params, additional_opts, scan_id, remove_existing, callback))\n if self.canExecNext():\n self.execNext()\n\n def execNext(self):\n \"\"\"\n Launch the next reconstruction if any\n \"\"\"\n if Queue.empty(self):\n return\n assert not self.reconsThread.isRunning()\n recons_obj, recons_params, additional_opts, scan, remove_existing, callback = Queue.get(self)\n self.sigReconsStarted.emit(scan)\n self.reconsThread.init(recons_obj=recons_obj, recons_params=recons_params,\n additional_opts=additional_opts,\n scan_id=scan,\n remove_existing=remove_existing)\n self.reconsThread.sigThReconsFinished.connect(callback)\n self.reconsThread.start()\n if self._forceSync is True:\n self.reconsThread.wait()\n\n def canExecNext(self):\n \"\"\"\n Can we launch an ftserie reconstruction.\n Reconstruction can't be runned in parallel\n\n :return: True if no reconstruction is actually running\n \"\"\"\n return not self.reconsThread.isRunning()\n\n def _dealWithFinishedRecons(self, scan):\n assert isinstance(scan, TomoBase)\n info = 'reconstruction %s is finished' % scan.path\n logger.info(info)\n self.sigReconsFinished.emit(scan)\n self.execNext()\n\n def _dealWithThMissingParams(self, scan):\n assert isinstance(scan, TomoBase)\n self.sigReconsMissParams.emit(scan)\n self.execNext()\n\n def _dealWithFailedRecons(self, scan):\n assert isinstance(scan, TomoBase)\n self.sigReconsFailed.emit(scan)\n self.execNext()\n\n def setMockMode(self, b):\n self.reconsThread.setMockMode(b)\n self.execNext()\n\n def setForceSync(self, b=True):\n self._forceSync = b\n\n\nclass _LaminoReconsThread(qt.QThread):\n __doc__ = 'Thread used for running lamino reconstrucion using Tofu'\n sigThReconsFinished = qt.Signal(TomoBase)\n sigThReconsFailed = qt.Signal(TomoBase)\n sigThMissingParams = qt.Signal(TomoBase)\n\n def __init__(self):\n qt.QThread.__init__(self)\n self.scan = None\n self.recons_params = None\n self.additional_opts = None\n self.callback = None\n self.remove_existing = False\n\n def init(self, recons_obj, recons_params, additional_opts, remove_existing, scan_id):\n assert isinstance(recons_obj, LaminoReconstruction)\n self.recons_obj = recons_obj\n self.recons_params = recons_params\n self.additional_opts = additional_opts\n self.remove_existing = remove_existing\n self.scan = scan_id\n\n def run(self):\n recons_obj = copy.deepcopy(self.recons_obj)\n recons_obj.reconstruction_parameters = self.recons_params\n recons_obj.additional_reco_options = self.additional_opts\n try:\n recons_obj.process(scan=(self.scan))\n except ValueError as error:\n try:\n logger.warning(error)\n self.sigThMissingParams.emit('Some parameters are missing or are incoherent')\n finally:\n error = None\n del error\n\n except Exception as error:\n try:\n logger.error('fail to run lamino reconstruction for %s reason is %s' % (\n self.scan, error))\n self.sigThReconsFailed.emit('fail to run reconstruction %s' % self.scan.path)\n finally:\n error = None\n del error\n\n else:\n self.sigThReconsFinished.emit(self.scan)","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/lamino.cpython-37.py","file_name":"lamino.cpython-37.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539740942","text":"r\"\"\"Vision models run inference using trained checkpoint\"\"\"\n\nfrom absl import app\nfrom absl import flags\nimport tensorflow as tf\n\nfrom official.vision.beta.serving import run_lib\nfrom official.common import flags as tfm_flags\n\nFLAGS = flags.FLAGS\n\ntf.config.experimental.set_memory_growth(tf.config.list_physical_devices('GPU')[0], True)\n\n\ndef main(_):\n \n export_module = run_lib.get_export_module(experiment=FLAGS.experiment,\n batch_size=FLAGS.batch_size,\n config_files=FLAGS.config_file)\n \n ckpt = tf.train.Checkpoint(model=export_module.model)\n ckpt_dir_or_file = FLAGS.model_dir\n if tf.io.gfile.isdir(ckpt_dir_or_file):\n ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)\n status = ckpt.restore(ckpt_dir_or_file).expect_partial()\n\n def inference_fn(images):\n outputs = export_module.serve(images)\n return [v for k, v in outputs.items()]\n \n export_module.run_on_image_dir(image_path_glob=FLAGS.image_path_glob, \n output_dir=FLAGS.output_dir,\n preprocess_fn=None,\n inference_fn=inference_fn, \n visualise=FLAGS.visualise, \n stitch_original=FLAGS.stitch_original,\n class_names_path=FLAGS.class_names_path,\n save_logits_bin=FLAGS.save_logits_bin)\n\n\nif __name__ == '__main__':\n tfm_flags.define_flags()\n run_lib.define_flags()\n app.run(main)\n","sub_path":"official/vision/beta/serving/run_model.py","file_name":"run_model.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"493274961","text":"\"\"\"Unit tests for command line tools\"\"\"\n\nimport unittest\nimport platform\nimport os\nimport tempfile\n\nimport sciunit\n\nclass CommandLineTestCase(unittest.TestCase):\n \"\"\"Unit tests for command line tools\"\"\"\n\n def setUp(self):\n from sciunit.__main__ import main\n \n self.main = main\n path = os.path.abspath(sciunit.__path__[0])\n SCIDASH_HOME = os.path.dirname(os.path.dirname(path))\n self.cosmosuite_path = os.path.join(SCIDASH_HOME,'scidash')\n\n def test_sciunit_1create(self):\n try:\n self.main('--directory',self.cosmosuite_path,'create')\n except Exception as e:\n if 'There is already a configuration file' not in str(e):\n raise e\n else:\n temp_path = tempfile.mkdtemp()\n self.main('--directory',temp_path,'create')\n\n def test_sciunit_2check(self):\n self.main('--directory',self.cosmosuite_path,'check')\n \n def test_sciunit_3run(self):\n self.main('--directory',self.cosmosuite_path,'run')\n\n def test_sciunit_4make_nb(self):\n self.main('--directory',self.cosmosuite_path,'make-nb')\n\n # Skip for python versions that don't have importlib.machinery\n @unittest.skipIf(platform.python_version()<'3.3',\n \"run-nb not supported on Python < 3.3\")\n def test_sciunit_5run_nb(self):\n self.main('--directory',self.cosmosuite_path,'run-nb')","sub_path":"sciunit/unit_test/command_line_tests.py","file_name":"command_line_tests.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"100458998","text":"'''\nFaça um programa que peça o tamanho de um arquivo para download (em MB)\ne a velocidade de um link de Internet (em Mbps),\ncalcule e informe o tempo aproximado de download do arquivo usando este link (em minutos).\n'''\ntamanho_arquivo = float(input('Qual o tamanho do arquivo para download (em Mb)? '))\nvelocidade_internet = int(input('Qual a velocidade do link de Internet (em Mbps)? '))\n\ntempo_download = (tamanho_arquivo / velocidade_internet) / 60\nminutos = int(tempo_download)\nsegundos = round((tempo_download % 1) * 60)\nprint('Tempo aproximado de download do arquivo usando este link (em minutos): {}m{}' . format(minutos, segundos))","sub_path":"Maratona Data Science Brazil/Semana#01 - Python/01-estruturas-sequenciais/exercicio-18.py","file_name":"exercicio-18.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"41690322","text":"from paramiko import SSHClient, AutoAddPolicy\nfrom threading import Thread\n\nimport logging\nlogging.basicConfig(filename=\"run_bc.log\")\nlog = logging.getLogger(\"paramiko\")\nlog.setLevel(logging.DEBUG)\n\nclient = SSHClient()\nclient.set_missing_host_key_policy(AutoAddPolicy())\n\n\n\nclient.connect('192.168.56.105', username='root', password='welcome')\nstdin, stdout, stderr = client.exec_command('python')\n\ndef send_command(out):\n while True:\n line = input(\"Enter command: \")\n out.write(line + \"\\n\")\n\ndef get_result(instream):\n for line in instream:\n print(line, flush=True)\n\n\nt1 = Thread(target=send_command, args=(stdin,))\nt2 = Thread(target=get_result, args=(stdout,))\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\nclient.close()\n","sub_path":"Learning/Network_process_WA/Day1/2020_Jul23/paramiko/run_python_interact.py","file_name":"run_python_interact.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408009743","text":"#!/usr/bin/python\n\nimport pymongo\nfrom datetime import datetime, timedelta\nimport os\nfrom ConfigParser import RawConfigParser\n\nconfig = RawConfigParser()\nconfig_paths = ['jira.cfg', '../jira.cfg']\nconfig.read([os.path.join(os.getcwd(), path) for path in config_paths])\n\nconn = pymongo.MongoClient(config.get('Mongo', 'uri'))\nmetrics = conn.metrics\n\ndef MakeHTML():\n cursor = metrics.catalog.find({'type': 'weekly'})\n cursor.sort([('date', pymongo.DESCENDING)])\n\n yield('Support Metrics Index')\n yield('

Support Metrics Index

')\n yield('TODO: make this page less of a Spartan eyesore.')\n yield('

Metrics for week ending:')\n yield('

')\n\ndef Main():\n directory = os.path.join(os.getcwd(), 'html')\n if not os.path.exists(directory): os.mkdir(directory)\n fh = open(os.path.join(directory, 'index.html'), mode=\"w\")\n for x in MakeHTML():\n fh.write(x)\n fh.close()\n\nMain()\n\n","sub_path":"metrics/make_html.py","file_name":"make_html.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"405778021","text":"import requests, json\nfrom requests.auth import HTTPBasicAuth\nfrom github import Github\nfrom pprint import pprint\n\n\ndef PR_stats(stats=None):\n stats = stats or {}\n\n core_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core\"\n core_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:open\"\n core_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:merged\"\n core_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:closed\"\n\n org_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI\"\n org_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:open\"\n org_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:merged\"\n org_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:closed\"\n\n jarbas_core_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20author:jarbasai\"\n jarbas_core_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:open%20author:jarbasai\"\n jarbas_core_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:merged%20author:jarbasai\"\n jarbas_core_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:closed%20author:jarbasai\"\n\n jarbas_org_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20author:jarbasai\"\n jarbas_org_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:open%20author:jarbasai\"\n jarbas_org_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:merged%20author:jarbasai\"\n jarbas_org_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:closed%20author:jarbasai\"\n\n jarbas2_core_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20author:jarbasal\"\n jarbas2_core_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:open%20author:jarbasal\"\n jarbas2_core_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:merged%20author:jarbasal\"\n jarbas2_core_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20repo:MycroftAI/mycroft-core%20is:closed%20author:jarbasal\"\n\n jarbas2_org_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20author:jarbasal\"\n jarbas2_org_open_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:open%20author:jarbasal\"\n jarbas2_org_merged_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:merged%20author:jarbasal\"\n jarbas2_org_closed_prs_url = \"https://api.github.com/search/issues?q=type:pr%20org:MycroftAI%20is:closed%20author:jarbasal\"\n\n def get_number(url):\n try:\n n = requests.get(url, auth=HTTPBasicAuth('jarbasal', 'e8f036bf2af2d8fc458eadfc5d7aa6965207fdc2')).json()[\n \"total_count\"]\n return n\n except:\n return 1\n\n # org\n stats[\"mycroftAI\"] = {}\n stats[\"mycroftAI\"][\"prs\"] = get_number(org_prs_url)\n stats[\"mycroftAI\"][\"merged_prs\"] = get_number(org_merged_prs_url)\n stats[\"mycroftAI\"][\"closed_prs\"] = get_number(org_closed_prs_url) - stats[\"mycroftAI\"][\"merged_prs\"]\n stats[\"mycroftAI\"][\"open_prs\"] = get_number(org_open_prs_url)\n\n stats[\"mycroftAI\"][\"jarbas_prs\"] = get_number(jarbas_org_prs_url) + get_number(jarbas2_org_prs_url)\n stats[\"mycroftAI\"][\"jarbas_open_prs\"] = get_number(jarbas_org_open_prs_url) + get_number(\n jarbas2_org_open_prs_url) # 10 + 8\n stats[\"mycroftAI\"][\"jarbas_merged_prs\"] = get_number(jarbas_org_merged_prs_url) + get_number(\n jarbas2_org_merged_prs_url) # 21 + 28\n stats[\"mycroftAI\"][\"jarbas_closed_prs\"] = get_number(jarbas_org_closed_prs_url) + \\\n get_number(jarbas2_org_closed_prs_url) - stats[\"mycroftAI\"][\n \"jarbas_merged_prs\"]\n\n stats[\"mycroftAI\"][\"jarbas_percent\"] = round(100 * stats[\"mycroftAI\"][\"jarbas_prs\"] / stats[\"mycroftAI\"][\"prs\"], 1)\n stats[\"mycroftAI\"][\"jarbas_open_percent\"] = round(\n 100 * stats[\"mycroftAI\"][\"jarbas_open_prs\"] / stats[\"mycroftAI\"][\"open_prs\"], 1)\n stats[\"mycroftAI\"][\"jarbas_closed_percent\"] = round(\n 100 * stats[\"mycroftAI\"][\"jarbas_closed_prs\"] / stats[\"mycroftAI\"][\n \"closed_prs\"], 1)\n stats[\"mycroftAI\"][\"jarbas_merged_percent\"] = round(\n 100 * stats[\"mycroftAI\"][\"jarbas_merged_prs\"] / stats[\"mycroftAI\"][\n \"merged_prs\"], 1)\n\n # core\n stats[\"mycroft-core\"] = {}\n stats[\"mycroft-core\"][\"prs\"] = get_number(core_prs_url) #\n stats[\"mycroft-core\"][\"merged_prs\"] = get_number(core_merged_prs_url)\n stats[\"mycroft-core\"][\"closed_prs\"] = get_number(core_closed_prs_url) - stats[\"mycroft-core\"][\"merged_prs\"]\n stats[\"mycroft-core\"][\"open_prs\"] = get_number(core_open_prs_url)\n\n stats[\"mycroft-core\"][\"jarbas_prs\"] = get_number(jarbas_core_prs_url) + get_number(jarbas2_core_prs_url)\n stats[\"mycroft-core\"][\"jarbas_open_prs\"] = get_number(jarbas_core_open_prs_url) + get_number(\n jarbas2_core_open_prs_url)\n stats[\"mycroft-core\"][\"jarbas_merged_prs\"] = get_number(jarbas_core_merged_prs_url) + get_number(\n jarbas2_core_merged_prs_url)\n stats[\"mycroft-core\"][\"jarbas_closed_prs\"] = get_number(jarbas_core_closed_prs_url) + get_number(\n jarbas2_core_closed_prs_url) - \\\n stats[\"mycroft-core\"][\"jarbas_merged_prs\"]\n\n stats[\"mycroft-core\"][\"jarbas_percent\"] = round(\n 100 * stats[\"mycroft-core\"][\"jarbas_prs\"] / stats[\"mycroft-core\"][\"prs\"], 1)\n stats[\"mycroft-core\"][\"jarbas_open_percent\"] = round(\n 100 * stats[\"mycroft-core\"][\"jarbas_open_prs\"] / stats[\"mycroft-core\"][\n \"open_prs\"], 1)\n stats[\"mycroft-core\"][\"jarbas_closed_percent\"] = round(\n 100 * stats[\"mycroft-core\"][\"jarbas_closed_prs\"] / stats[\"mycroft-core\"][\n \"closed_prs\"], 1)\n stats[\"mycroft-core\"][\"jarbas_merged_percent\"] = round(\n 100 * stats[\"mycroft-core\"][\"jarbas_merged_prs\"] / stats[\"mycroft-core\"][\n \"merged_prs\"], 1)\n return stats\n\n\ndef github_stats(stats=None):\n stats = stats or {}\n # First create a Github instance:\n # using an access token\n g = Github(\"e8f036bf2af2d8fc458eadfc5d7aa6965207fdc2\")\n\n # Then play with your Github objects:\n user = g.get_user(\"jarbasai\")\n repos = user.get_repos()\n total_repos = 0\n total_skills = 0\n total_stars = 0\n total_watchers = 0\n total_archived = 0\n followers = user.followers\n for repo in repos:\n total_stars += repo.stargazers_count\n total_watchers += repo.watchers_count\n total_repos += 1\n if \"skill\" in repo.name.lower() or \"fallback\" in repo.name.lower():\n total_skills += 1\n if repo.archived:\n total_archived += 1\n\n user = g.get_user(\"jarbasal\")\n stats[\"avatar\"] = user.avatar_url\n stats[\"email\"] = user.email\n followers += user.followers\n repos = user.get_repos()\n for repo in repos:\n total_stars += repo.stargazers_count\n total_watchers += repo.watchers_count\n total_repos += 1\n if repo.archived:\n total_archived += 1\n if \"skill\" in repo.name.lower() or \"fallback\" in repo.name.lower():\n total_skills += 1\n\n stats[\"total_followers\"] = followers\n stats[\"total_stars\"] = total_stars\n stats[\"total_repos\"] = total_repos\n stats[\"total_skills\"] = total_skills\n stats[\"total_archived\"] = total_archived\n stats[\"total_watchers\"] = total_watchers\n return stats\n\n\nstats = {'avatar': 'https://avatars0.githubusercontent.com/u/33701864?v=4',\n 'email': 'jarbasai@mailfence.com',\n 'mycroft-core': {'closed_prs': 183,\n 'jarbas_closed_percent': 0.15846994535519127,\n 'jarbas_closed_prs': 29,\n 'jarbas_merged_percent': 0.040042149631190724,\n 'jarbas_merged_prs': 38,\n 'jarbas_open_percent': 0.6,\n 'jarbas_open_prs': 15,\n 'jarbas_percent': 0.07087294727744166,\n 'jarbas_prs': 82,\n 'merged_prs': 949,\n 'open_prs': 25,\n 'prs': 1157},\n 'mycroftAI': {'closed_prs': 447,\n 'jarbas_closed_percent': 0.08053691275167785,\n 'jarbas_closed_prs': 36,\n 'jarbas_merged_percent': 0.022272727272727274,\n 'jarbas_merged_prs': 49,\n 'jarbas_open_percent': 0.1782178217821782,\n 'jarbas_open_prs': 18,\n 'jarbas_percent': 0.03748180494905386,\n 'jarbas_prs': 103,\n 'merged_prs': 2200,\n 'open_prs': 101,\n 'prs': 2748},\n 'total_archived': 49,\n 'total_followers': 46,\n 'total_repos': 113,\n 'total_skills': 83,\n 'total_stars': 174,\n 'total_watchers': 174\n }\n\nstats = PR_stats(stats)\nstats = github_stats(stats)\nstats[\"email\"] = \"jarbasai@mailfence.com\"\nwith open(\"stats.json\", \"w\") as f:\n f.write(json.dumps(stats))\n\npprint(stats)\n","sub_path":"_data/scrap_stats.py","file_name":"scrap_stats.py","file_ext":"py","file_size_in_byte":9741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"117024901","text":"N, A, B = map(int, input().split())\nS = [int(input()) for _ in range(N)]\n\nmaxi = max(S)\nmini = min(S)\n\nif maxi==mini:\n print(-1)\n exit()\n \nP = B/(maxi-mini)\n\nfor i in range(N):\n S[i] = S[i]*P\n\nmean = sum(S)/N\nQ = A - mean\n\nprint(P, Q)","sub_path":"atcoder/2015/ARC/0815_arc043/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"57550872","text":"import scipy.io\nimport pylab\nimport numpy as np\nfrom random import randint\nfrom random import random\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\n\n# Load input data\nDATA = scipy.io.loadmat('./test.mat') # MATLAB data\nINPUT = DATA['input'] # [x,y,q,r]\nOUTPUT = DATA['output'] # [L or G]\nTRIALS = len(DATA) - 1 # Number of trials -1 cause it starts from 0\nEPISODES = 500 # Number of training episodes\n\n\n#Normalize input\nx_max = np.max(INPUT[:,0]);\nx_min = np.min(INPUT[:,0]);\ny_max = np.max(INPUT[:,1]);\ny_min = np.min(INPUT[:,1]);\nq_max = np.max(INPUT[:,2]);\nq_min = np.min(INPUT[:,2]);\nr_max = np.max(INPUT[:,3]);\nr_min = np.min(INPUT[:,3]);\n\nfor i in range(INPUT.shape[0]) :\n INPUT[i][0] = (INPUT[i][0] - x_min)/(x_max-x_min + 0.0001);\n INPUT[i][1] = (INPUT[i][1] - y_min)/(y_max-y_min + 0.0001);\n INPUT[i][2] = (INPUT[i][2] - q_min)/(q_max-q_min + 0.0001);\n INPUT[i][3] = (INPUT[i][3] - r_min)/(r_max-r_min + 0.0001);\n\nreplay_buffer = list();\n\n# Uncertainty-Value Model (Proposed Model)\nclass UVModel:\n def __init__(self, state_size, action_size):\n self.load_model = False # Load saved model\n\n # Initialize the state size & action size\n self.state_size = state_size\n self.action_size = action_size\n self.value_size = 1\n\n # Hyperparameter setting\n self.discount_factor = 1\n self.actor_lr = 0.001\n self.critic_lr = 0.001\n\n # Build Actor & Critic\n self.actor = self.build_actor()\n self.critic = self.build_critic()\n self.actor_updater = self.actor_optimizer()\n self.critic_updater = self.critic_optimizer()\n\n # Load saved model for test\n if self.load_model:\n self.actor.load_weights(\"./Uncertainty_Value_model_Actor.h5\")\n self.critic.load_weights(\"./Uncertainty_Value_model_Critic.h5\")\n\n # actor: computes the probability of actions (softmax)\n def build_actor(self):\n actor = Sequential()\n actor.add(Dense(24, input_dim=self.state_size, activation='relu',\n kernel_initializer='he_uniform'))\n actor.add(Dense(self.action_size, activation='softmax',\n kernel_initializer='he_uniform'))\n actor.summary()\n return actor\n\n # critic: computes the value of actions\n def build_critic(self):\n critic = Sequential()\n critic.add(Dense(24, input_dim=self.state_size, activation='relu',\n kernel_initializer='he_uniform'))\n critic.add(Dense(self.value_size, activation='linear',\n kernel_initializer='he_uniform'))\n critic.summary()\n return critic\n\n # Choose action\n def get_action(self, state, eps):\n policy = self.actor.predict(state, batch_size=1).flatten()\n\n # random choice with epsilon degree;\n\n if random() < eps :\n return np.random.choice(self.action_size, 1, p= [0.5, 0.5])[0];\n else :\n return np.random.choice(self.action_size, 1, p=policy)[0]\n\n\n # Updates policy\n def actor_optimizer(self):\n action = K.placeholder(shape=[None, self.action_size])\n advantage = K.placeholder(shape=[None, ])\n\n action_prob = K.sum(action * self.actor.output, axis=1)\n cross_entropy = K.log(action_prob) * advantage\n loss = -K.sum(cross_entropy)\n\n optimizer = Adam(lr=self.actor_lr)\n updates = optimizer.get_updates(self.actor.trainable_weights, [], loss)\n train = K.function([self.actor.input, action, advantage], [],\n updates=updates)\n\n return train\n\n # Updates value\n def critic_optimizer(self):\n target = K.placeholder(shape=[None, ])\n\n\n loss = K.mean(K.square(target - self.critic.output))\n\n optimizer = Adam(lr=self.critic_lr)\n updates = optimizer.get_updates(self.critic.trainable_weights, [], loss)\n train = K.function([self.critic.input, target], [], updates=updates)\n\n return train\n\n # Update Actor & Critic at every time step\n def train_model(self, state, action, reward, next_state, done):\n\n value = self.critic.predict(state)\n next_value = self.critic.predict(next_state)\n # print(\"value:\", value, \" next_vale\", next_value)\n\n act = np.zeros([action.shape[0], self.action_size])\n advan_list = list();\n target_list= list();\n for ii in range(action.shape[0]) :\n act[ii][int(action[ii])] = 1;\n\n # Update using Bellman equation\n if done[ii]:\n advantage = reward[ii] - value[ii]\n target = [reward[ii]]\n else:\n advantage = (reward[ii] + self.discount_factor * next_value[ii]) - value[ii]\n target = reward[ii] + self.discount_factor * next_value[ii]\n advan_list.append(advantage);\n target_list.append(target);\n\n # print(\"advantage:\", advantage, \" target:\", target)\n\n self.actor_updater([state, act, np.squeeze(np.stack(advan_list))])\n\n self.critic_updater([state, np.squeeze(np.stack(target_list))])\n\ndef sample_from_replay(size, batch_size=10) :\n\n sampled_idx = np.zeros(shape=(batch_size,), dtype=int);\n for i in range(batch_size) :\n sampled_idx[i] = randint(0,size-1);\n return sampled_idx;\n\nif __name__ == \"__main__\":\n state_size = 4 # state = [x,y,q,r]\n action_size = 2 # action = [G or L]\n epsilon_start_value = 0.99;\n\n\n # Build Actor-Critic agent\n agent = UVModel(state_size, action_size)\n\n # Initialize scores and trials\n scores, trials = [], []\n\n count = 0 # number for plotting\n epsilon = epsilon_start_value;\n # Training\n for e in range(EPISODES):\n print(\"===================== Episode: \", e, \" ===========================\")\n done = False\n score = 0\n\n for t in range(TRIALS):\n\n state = INPUT[t]\n state = np.reshape(state, [1, state_size])\n epsilon = epsilon*0.99; ########################################################################################\n action = agent.get_action(state, epsilon)\n\n next_state = INPUT[t + 1]\n next_state = np.reshape(next_state, [1, state_size])\n\n answer = OUTPUT[t+1]\n if answer == action:\n reward = 1\n else:\n reward = -1\n next_state = [0.0, 0.0, 0.0, 0.0]; ######################################################################\n done = True;\n\n\n #done = False\n\n if len(replay_buffer) < 50 : ######################################################################\n replay_buffer.append([state, action, reward, next_state, done])\n else :\n replay_buffer.pop(0);\n replay_buffer.append([state, action, reward, next_state, done])\n\n\n idx = sample_from_replay(len(replay_buffer), batch_size = 2); ######################################################################\n # randomly shuffle replay buffer\n replay_state = np.zeros(shape=(idx.shape[0], state.shape[1]));\n replay_action = np.zeros(shape=(idx.shape[0], ));\n replay_reward = np.zeros(shape=(idx.shape[0], ));\n replay_next_state = np.zeros(shape=(idx.shape[0], state.shape[1]));\n replay_done = np.zeros(shape=(idx.shape[0], ));\n\n for dat_idx in range(idx.shape[0]) :\n replay_state[dat_idx] = replay_buffer[idx[dat_idx]][0];\n replay_action[dat_idx] = replay_buffer[idx[dat_idx]][1];\n replay_reward[dat_idx] = replay_buffer[idx[dat_idx]][2];\n replay_next_state[dat_idx] = replay_buffer[idx[dat_idx]][3];\n replay_done[dat_idx] = replay_buffer[idx[dat_idx]][4];\n\n agent.train_model(replay_state, replay_action, replay_reward , replay_next_state, replay_done);\n\n score = reward\n state = next_state\n\n # Print results\n scores.append(score)\n trials.append(count)\n count += 1\n print(\"trial:\", count, \" score:\", score, \" action prediction:\", action, \" output:\", answer)\n if done == True :\n break;\n\n # agent.actor.save_weights(\"./Uncertainty_Value_model_Actor.h5\")\n # agent.critic.save_weights(\"./Uncertainty_Value_model_Critic.h5\")\n # sys.exit()\n\n pylab.plot(trials, scores, 'b')\n pylab.savefig(\"./Uncertainty_Value_Model.png\")\n","sub_path":"simulation_code/simulation/simul_model.py","file_name":"simul_model.py","file_ext":"py","file_size_in_byte":8849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244177596","text":"from grdb.database.v1_1_0.models import (\n Sample,\n PreparationStep,\n Recipe,\n Properties,\n RamanSet,\n RamanFile,\n RamanSpectrum,\n SemFile,\n Author,\n Software,\n)\n\n# from gresq.recipe import Recipe\nfrom sqlalchemy import String, Integer, Float\nfrom gresq.util.box_adaptor import BoxAdaptor\nimport uuid\nimport pandas as pd\nimport os\nimport sys\nfrom datetime import date\n\npar = os.path.abspath(os.path.pardir)\nsys.path.append(os.path.join(par, \"src\", \"gresq\", \"dashboard\", \"gsaraman\", \"src\"))\nfrom gsaraman.gsaraman import auto_fitting\nfrom gresq.dashboard.submit.util import get_or_add_software_row\nfrom gresq import __version__ as GRESQ_VERSION\nfrom gsaimage import __version__ as GSAIMAGE_VERSION\nfrom gsaraman import __version__ as GSARAMAN_VERSION\n\nsample_key = {\"experiment_date\": \"DATE\"}\nproperties_key = {\n \"average_thickness_of_growth\": \"PROPERTY: Average Thickness of Growth (nm)\",\n \"standard_deviation_of_growth\": \"PROPERTY: Standard Deviation of Growth (nm)\",\n \"number_of_layers\": \"PROPERTY: Number of Layers\",\n \"growth_coverage\": \"PROPERTY: Growth Coverage (%)\",\n}\nrecipe_key = {\n \"sample_surface_area\": r\"PROPERTY: Sample Surface Area (mm$\\^2$)\",\n \"thickness\": r\"PROPERTY: Thickness ($\\mu$m)\",\n \"tube_diameter\": \"ALL CONDITION: Tube Diameter (mm)\",\n \"tube_length\": \"ALL CONDITION: Tube Length (mm)\",\n \"catalyst\": \"ALL CONDITION: Catalyst\",\n \"cross_sectional_area\": \"ALL CONDITION: Cross Sectional Area (mm^2)\",\n \"base_pressure\": \"ALL CONDITION: Base Pressure (mTorr)\",\n}\npreparation_step_key = {\n \"duration\": \"PREPARATION STEP DETAIL: Timestamp\",\n \"furnace_temperature\": \"PREPARATION STEP DETAIL: Furnace Temperature\",\n \"furnace_pressure\": \"PREPARATION STEP DETAIL: Furnace Pressure\",\n \"sample_location\": \"PREPARATION STEP DETAIL: Sample Location\",\n \"helium_flow_rate\": \"PREPARATION STEP DETAIL: Helium Flow Rate\", ## l/s vs sccm\n \"hydrogen_flow_rate\": \"PREPARATION STEP DETAIL: Hydrogen Flow Rate\",\n \"carbon_source\": \"PREPARATION STEP DETAIL: Carbon Source\",\n \"carbon_source_flow_rate\": \"PREPARATION STEP DETAIL: Carbon Source Flow Rate\",\n \"argon_flow_rate\": \"PREPARATION STEP DETAIL: Argon Flow Rate\",\n}\n\nsql_validator = {\n \"int\": lambda x: isinstance(x.property.columns[0].type, Integer),\n \"float\": lambda x: isinstance(x.property.columns[0].type, Float),\n \"str\": lambda x: isinstance(x.property.columns[0].type, String),\n}\n\n\ndef convert(value, field, header=None):\n if sql_validator[\"int\"](field):\n return int(value)\n elif sql_validator[\"float\"](field):\n value = float(value)\n if \"mTorr\" in header:\n value /= 1000\n return value\n else:\n return str(value)\n\n\ndef upload_file(\n box_adaptor,\n file_path,\n folder_name=None,\n box_config_path=\"/Users/Joshua_Schiller/Dropbox/GSAMain/src/box_config.json\",\n):\n upload_folder = box_adaptor.create_upload_folder(folder_name=folder_name)\n box_file = box_adaptor.upload_file(upload_folder, file_path, str(uuid.uuid4()))\n\n return box_file.get_shared_link_download_url(access=\"open\")\n\n\ndef get_filepaths(reference_id, folder_path=\"./\"):\n contents = os.listdir(os.path.join(folder_path, reference_id))\n raman = []\n sem = []\n for f in contents:\n if f.split(\".\")[-1] == \"txt\":\n raman.append(f)\n elif f.split(\".\")[-1] == \"tif\":\n sem.append(f)\n return raman, sem\n\n\ndef convert_date(d):\n words = d.split(\"/\")\n month = int(words[0])\n day = int(words[1])\n year = int(\"20\" + words[2])\n return date(year, month, day)\n\n\ndef convert_db(data):\n columns = data.columns\n for i in range(data.shape[0]):\n # for c, col in enumerate(columns):\n for col in enumerate(columns):\n if \"Torr l/s\" in col:\n value = data[col][i]\n if pd.isnull(value) == False:\n value = float(value)\n new_col = col.replace(\"Torr l/s\", \"sccm\")\n if pd.isnull(data[new_col][i]):\n data[new_col][i] = value / 0.01270903\n new_cols = [col for col in columns if \"Torr l/s\" not in col]\n data = data[new_cols].copy()\n\n return data\n\n\ndef build_db(session, filepath, sem_raman_path=None, nrun=None, box_config_path=None):\n data = pd.read_csv(os.path.join(filepath, \"recipe_2019-08-27.csv\"))\n data = convert_db(data)\n box_adaptor = BoxAdaptor(box_config_path)\n\n name_idxs = []\n cooling_idx = None\n for c, col in enumerate(data.columns):\n if \"PREPARATION STEP NAME\" in col:\n name_idxs.append(c)\n elif \"Cooling Rate\" in col:\n cooling_idx = c\n\n annealing_df = data.iloc[:, name_idxs[0] + 1 : name_idxs[1]].copy()\n growing_df = data.iloc[:, name_idxs[1] + 1 : name_idxs[2]].copy()\n cooling_df = data.iloc[:, cooling_idx + 1 :].copy()\n cooling_rate = data.iloc[:, cooling_idx].copy()\n box_folder = data[\"BOX FOLDER\"].copy()\n author_column = data[\"CONTRIBUTOR\"].copy()\n\n # Check software versions\n gresq_soft = get_or_add_software_row(session, \"gresq\", GRESQ_VERSION)\n gsaimage_soft = get_or_add_software_row(session, \"gsaimage\", GSAIMAGE_VERSION)\n gsaraman_soft = get_or_add_software_row(session, \"gsaraman\", GSARAMAN_VERSION)\n\n if nrun == None:\n nrun = data.shape[0]\n\n for i in range(nrun):\n if \"Kaihao\" in author_column[i]:\n\n s = Sample(\n software_name=gresq_soft.name, software_version=gresq_soft.version\n )\n s.material_name = \"Graphene\"\n s.validated = True\n date_string = data[sample_key[\"experiment_date\"]][i]\n if pd.isnull(date_string) == False:\n s.experiment_date = convert_date(date_string)\n\n session.add(s)\n session.flush()\n\n pr = Properties()\n pr.sample_id = s.id\n for key, header in properties_key.items():\n value = data[header][i]\n if pd.isnull(value) == False:\n value = convert(value, getattr(Properties, key), header=header)\n setattr(pr, key, value)\n\n r = Recipe()\n r.sample_id = s.id\n for key, header in recipe_key.items():\n value = data[header][i]\n if pd.isnull(value) == False:\n value = convert(value, getattr(Recipe, key), header=header)\n setattr(r, key, value)\n session.add(pr)\n session.add(r)\n session.commit()\n\n total_steps = 0\n\n for j in range(0, annealing_df.shape[1], 9):\n prep_df = annealing_df.iloc[:, j : j + 9].copy()\n\n # initial_cols = prep_df.columns\n for col in prep_df.columns:\n for key, value in preparation_step_key.items():\n if (\n value in col\n and preparation_step_key[\"carbon_source_flow_rate\"]\n not in col\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n elif (\n value in col\n and value == preparation_step_key[\"carbon_source_flow_rate\"]\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n prep = PreparationStep()\n prep.name = \"Annealing\"\n prep.recipe_id = r.id\n for key, header in preparation_step_key.items():\n try:\n value = prep_df[header][i]\n if pd.isnull(value) == False:\n value = convert(\n value, getattr(PreparationStep, key), header=header\n )\n setattr(prep, key, value)\n except Exception as e:\n print(\"###################\")\n print(\"%s Row %s Column %s\" % (prep.name, i, j))\n print(\"Header: '%s'\" % header)\n print(e)\n if prep.duration != None:\n prep.step = total_steps\n total_steps += 1\n session.add(prep)\n session.commit()\n\n for j in range(0, growing_df.shape[1], 9):\n prep_df = growing_df.iloc[:, j : j + 9].copy()\n\n for col in prep_df.columns:\n for key, value in preparation_step_key.items():\n if (\n value in col\n and preparation_step_key[\"carbon_source_flow_rate\"]\n not in col\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n elif (\n value in col\n and value == preparation_step_key[\"carbon_source_flow_rate\"]\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n prep = PreparationStep()\n prep.name = \"Growing\"\n prep.recipe_id = r.id\n for key, header in preparation_step_key.items():\n try:\n value = prep_df[header][i]\n if pd.isnull(value) == False:\n value = convert(\n value, getattr(PreparationStep, key), header=header\n )\n setattr(prep, key, value)\n except Exception as e:\n print(\"###################\")\n print(\"%s Row %s Column %s\" % (prep.name, i, j))\n print(\"Header: '%s'\" % header)\n print(e)\n if prep.duration != None:\n prep.step = total_steps\n total_steps += 1\n session.add(prep)\n session.commit()\n\n for j in range(0, cooling_df.shape[1], 9):\n prep_df = cooling_df.iloc[:, j : j + 9].copy()\n if prep_df.shape[1] < 9:\n break\n for col in prep_df.columns:\n for key, value in preparation_step_key.items():\n if (\n value in col\n and preparation_step_key[\"carbon_source_flow_rate\"]\n not in col\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n elif (\n value in col\n and value == preparation_step_key[\"carbon_source_flow_rate\"]\n ):\n prep_df.rename(columns={col: value}, inplace=True)\n prep = PreparationStep()\n prep.name = \"Cooling\"\n prep.recipe_id = r.id\n cooling_value = cooling_rate[i]\n if pd.isnull(cooling_value) == False:\n prep.cooling_rate = cooling_value\n\n for key, header in preparation_step_key.items():\n try:\n value = prep_df[header][i]\n if pd.isnull(value) == False:\n value = convert(\n value, getattr(PreparationStep, key), header=header\n )\n setattr(prep, key, value)\n except Exception as e:\n print(\"###################\")\n print(\"%s Row %s Column %s\" % (prep.name, i, j))\n print(\"Header: '%s'\" % header)\n print(e)\n if prep.duration != None:\n prep.step = total_steps\n total_steps += 1\n session.add(prep)\n session.commit()\n\n ### RAMAN IS A SEPARATE DATASET FROM SAMPLE ###\n rs = RamanSet()\n rs.sample_id = s.id\n rs.experiment_date = s.experiment_date\n session.add(rs)\n session.flush()\n\n reference_id = str(box_folder[i])\n if os.path.isdir(os.path.join(sem_raman_path, reference_id)):\n files = os.listdir(os.path.join(sem_raman_path, reference_id))\n files_response = {\n \"Raman Files\": [],\n \"SEM Image Files\": [],\n \"Raman Wavelength\": 532,\n }\n for f in files:\n if f.split(\".\")[-1] == \"txt\":\n files_response[\"Raman Files\"].append(\n os.path.join(sem_raman_path, reference_id, f)\n )\n elif f.split(\".\")[-1] == \"tif\":\n files_response[\"SEM Image Files\"].append(\n os.path.join(sem_raman_path, reference_id, f)\n )\n\n if len(files_response[\"Raman Files\"]) > 0:\n files_response[\"Characteristic Percentage\"] = [\n 100 / len(files_response[\"Raman Files\"])\n ] * len(files_response[\"Raman Files\"])\n for ri, ram in enumerate(files_response[\"Raman Files\"]):\n rf = RamanFile()\n rf.filename = os.path.basename(ram)\n rf.sample_id = s.id\n rf.url = upload_file(\n box_adaptor, ram, box_config_path=box_config_path\n )\n if files_response[\"Raman Wavelength\"] != None:\n rf.wavelength = files_response[\"Raman Wavelength\"]\n session.add(rf)\n session.flush()\n\n params = auto_fitting(ram)\n r = RamanSpectrum(\n software_name=gsaraman_soft.name,\n software_version=gsaraman_soft.version,\n )\n r.raman_file_id = rf.id\n r.set_id = rs.id\n if files_response[\"Characteristic Percentage\"] != None:\n r.percent = float(\n files_response[\"Characteristic Percentage\"][ri]\n )\n else:\n r.percent = 0.0\n for peak in params.keys():\n for v in params[peak].keys():\n key = \"%s_%s\" % (peak, v)\n setattr(r, key, float(params[peak][v]))\n session.add(r)\n session.flush()\n\n rs_fields = [\n \"d_peak_shift\",\n \"d_peak_amplitude\",\n \"d_fwhm\",\n \"g_peak_shift\",\n \"g_peak_amplitude\",\n \"g_fwhm\",\n \"g_prime_peak_shift\",\n \"g_prime_peak_amplitude\",\n \"g_prime_fwhm\",\n ]\n for field in rs_fields:\n setattr(\n rs,\n field,\n sum(\n [\n getattr(spect, field)\n * getattr(spect, \"percent\")\n / 100.0\n for spect in rs.raman_spectra\n ]\n ),\n )\n rs.d_to_g = sum(\n [\n getattr(spect, \"d_peak_amplitude\")\n / getattr(spect, \"g_peak_amplitude\")\n * getattr(spect, \"percent\")\n / 100.0\n for spect in rs.raman_spectra\n ]\n )\n rs.gp_to_g = sum(\n [\n getattr(spect, \"g_prime_peak_amplitude\")\n / getattr(spect, \"g_peak_amplitude\")\n * getattr(spect, \"percent\")\n / 100.0\n for spect in rs.raman_spectra\n ]\n )\n session.flush()\n\n if len(files_response[\"SEM Image Files\"]) > 0:\n for f in files_response[\"SEM Image Files\"]:\n sf = SemFile()\n sf.sample_id = s.id\n sf.filename = os.path.basename(f)\n sf.url = upload_file(\n box_adaptor, f, box_config_path=box_config_path\n )\n session.add(sf)\n session.flush()\n\n auth = Author()\n auth.first_name = \"Kaihao\"\n auth.last_name = \"Zhang\"\n auth.institution = \"University of Illinois at Urbana-Champaign\"\n\n if \"Kaihao\" in author_column[i]:\n auth.sample_id = s.id\n auth.raman_id = rs.id\n session.add(auth)\n\n session.commit()\n","sub_path":"src/gsaraman/util/csv2db3.py","file_name":"csv2db3.py","file_ext":"py","file_size_in_byte":17738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"380573819","text":"#!/usr/bin/python\n\nimport sys\nimport struct\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom read_psrfits import *\n\n\ndef convert_samples(a, nbits):\n\tif nbits == 8:\n\t\treturn a\n\telif nbits == 4:\n\t\tr = np.empty(len(a)*2, np.uint8)\n\t\tr[0::2] = np.right_shift(a, 4)\n\t\tr[1::2] = np.bitwise_and(a, 0b1111)\n\t\treturn r\n\telif nbits == 2:\n\t\tr = np.empty(len(a)*4, np.uint8)\n\t\tr[0::4] = np.right_shift(a, 6)\n\t\tr[1::4] = np.bitwise_and(np.right_shift(a, 4), 0b11)\n\t\tr[2::4] = np.bitwise_and(np.right_shift(a, 2), 0b11)\n\t\tr[3::4] = np.bitwise_and(a, 0b11)\n\t\treturn r\n\telse:\n\t\tprint('unknown sample bits: %d' % nbits)\n\n\ndef psrfits_plot_subint(f, hdr, tmpl):\n\tfor i in range(len(tmpl)):\n\t\t#print(\"%s %d\" % (tmpl[i].form, format_length(tmpl[i].form)))\n\t\tlength = format_length(tmpl[i].form)\n\t\tbytes = f.read(length)\n\t\tif len(bytes) < length:\n\t\t\tprint('only %d bytes read while expect %d, EOF?' % (len(bytes), length))\n\t\t\treturn False\n\t\tif tmpl[i].type != 'DATA':\n\t\t\tval = struct.unpack('>'+tmpl[i].form, bytes)\n\t\t\tprint('%8s ' % tmpl[i].type),\n\t\t\tif len(val) == 1:\n\t\t\t\tprint(val[0])\n\t\t\telif len(val) < 10:\n\t\t\t\tprint(val)\n\t\t\telse:\n\t\t\t\tprint(val[0:10]),\n\t\t\t\tprint('......')\n\t\telse:\n\t\t\tnbits = int(fits_hdu_get_value(hdr, 'NBITS'))\n\t\t\tnchan = int(fits_hdu_get_value(hdr, 'NCHAN'))\n\t\t\tnpol = int(fits_hdu_get_value(hdr, 'NPOL'))\n\t\t\tnsblk = int(fits_hdu_get_value(hdr, 'NSBLK'))\n\t\t\t# read in samples in 1-D array\n\t\t\ts = convert_samples(np.frombuffer(bytes, dtype=np.uint8), nbits)\n\t\t\tprint(s)\n\t\t\tif npol == 1:\n\t\t\t\tt = np.reshape(s, (nsblk, nchan))\n\t\t\t\tplt.subplot(111)\n\t\t\t\tplt.imshow(np.transpose(t))\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.show()\n\t\t\telif npol == 2:\n\t\t\t\t# construct 2-D array for display\n\t\t\t\tt = np.reshape(s, (nsblk, npol, nchan))\n\t\t\t\tpol0 = t[:,0]\n\t\t\t\tpol1 = t[:,1]\n\t\t\t\tplt.subplot(211)\n\t\t\t\tplt.imshow(np.transpose(pol0), aspect=3)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.subplot(212)\n\t\t\t\tplt.imshow(np.transpose(pol1), aspect=3)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.show()\n\t\t\telif npol == 4:\n\t\t\t\tt = np.reshape(s, (nsblk, npol, nchan))\n\t\t\t\tplt.subplot(411)\n\t\t\t\tplt.imshow(np.transpose(t[:,0]), aspect=5)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.subplot(412)\n\t\t\t\tplt.imshow(np.transpose(t[:,1]), aspect=5)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.subplot(413)\n\t\t\t\tplt.imshow(np.transpose(t[:,2]), aspect=5)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.subplot(414)\n\t\t\t\tplt.imshow(np.transpose(t[:,3]), aspect=5)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.show()\n\t\t\telse:\n\t\t\t\tprint('unknown polarization number: %d' % npol)\n\treturn True\n\n\nif __name__ == '__main__':\n\t\n\tif len(sys.argv) != 2:\n\t\tprint('Usage: %s ' % sys.argv[0])\n\t\texit(1)\n\n\tfile = sys.argv[1]\n\twith open(file, 'rb') as f:\n\t\thdr = fits_read_hdu(f)\n\t\tfits_show_hdu(hdr)\n\t\tfits_next_table(f, hdr)\n\t\t# skip to subint table\n\t\twhile True:\n\t\t\thdr = fits_read_hdu(f)\n\t\t\textname = fits_hdu_get_value(hdr, 'EXTNAME')\n\t\t\tif extname == 'SUBINT':\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tfits_next_table(f, hdr)\n\t\tsubint = hdr\n\t\tfits_show_hdu(subint)\n\t\tnrows = int(fits_hdu_get_value(subint, 'NAXIS2'))\n\t\tfits_file_align(f)\n\t\ttmpl = psrfits_get_subint_template(subint)\n\t\tfor i in range(0, nrows):\n\t\t\tprint('\\n')\n\t\t\tprint('*' * 18)\n\t\t\tprint(' SUBINT %d' % i)\n\t\t\tprint('*' * 18)\n\t\t\tpsrfits_plot_subint(f, hdr, tmpl)\n\n","sub_path":"roach_related/psrspec_roach2/plot_psrfits.py","file_name":"plot_psrfits.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"18593788","text":"from django.core.management import BaseCommand\n\nfrom custom.gitlab_getter import get_gitlab\n\n\nclass Command(BaseCommand):\n def handle(self, *_, **__):\n to_delete = []\n for user in get_gitlab().users.list():\n if not user.is_admin:\n print(\"Deleting user\", user.username, user.name)\n to_delete.append(user)\n if input(\"Are you sure you want to do this? This will delete everything (y/n)\") == 'y':\n [user.delete() for user in to_delete]\n","sub_path":"custom/management/commands/gitlab_cleanup.py","file_name":"gitlab_cleanup.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"34701827","text":"# -*- coding:utf-8 -*-\nimport string\nimport os\nimport shutil\nimport uuid\nfrom captcha.image import ImageCaptcha\nimport numpy as np\n\nimport itertools\n\nNUMBER_PER_IMAGE = 5\nNUMBER_PER_PERMUTATION = 1\nIMAGE_HEIGHT = 100\nIMAGE_WIDTH = 40 + 20 * NUMBER_PER_IMAGE \nBASE_PATH = './datasets'\nTEST_SET_SIZE_RATIO = 0.2\n\ndef create_captcha_image(image, subpath, captcha_set):\n\tcreate_path = os.path.join(BASE_PATH, subpath)\n\tif not os.path.exists(create_path):\n\t\tos.makedirs(create_path)\n\n\tcaptcha = ''.join(str(x) for x in captcha_set)\n\tfn = os.path.join(create_path, '%s_%s.png' % (captcha, uuid.uuid4()))\n\timage.write(captcha, fn)\n\ndef gen_captcha():\n\tif os.path.exists(BASE_PATH):\n\t\tshutil.rmtree(BASE_PATH)\n\tos.makedirs(BASE_PATH)\n\timage = ImageCaptcha(width=IMAGE_WIDTH, height=IMAGE_HEIGHT)\n\n\tgenerated_image_count = 0\n\n\t## training set\n\tfor n in range(NUMBER_PER_PERMUTATION):\n\t\tfor i in itertools.permutations(range(10), NUMBER_PER_IMAGE):\n\t\t\tcreate_captcha_image(image, 'train', i)\n\t\t\tgenerated_image_count += 1\n\n\t## test set\n\tfor n in range(int(generated_image_count * TEST_SET_SIZE_RATIO)):\n\t\trandom_set = np.random.randint(10, size=NUMBER_PER_IMAGE)\n\t\tcreate_captcha_image(image, 'test', random_set)\n\n\n\nif __name__ == '__main__':\n\tgen_captcha()","sub_path":"gen_captcha.py","file_name":"gen_captcha.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"178795729","text":"import queue\r\n\r\n\r\ndef main():\r\n board = []\r\n bfs = queue.Queue()\r\n almacenados = avltree()\r\n index = -1\r\n RESPUESTA = \"0123456789\"\r\n\r\n # se llena el tablero con los datos\r\n for i in range(9):\r\n board.insert(i, int(input()))\r\n if board[i] == 0:\r\n index = i\r\n\r\n print(index)\r\n # se agrega el primer tableto a la cola\r\n bfs.put(board)\r\n\r\n while True:\r\n board1 = bfs.get()\r\n\r\n # Revisamos si es la respuesta\r\n if board1 == RESPUESTA:\r\n break\r\n\r\n element = selector_de_ramas(board1)\r\n\r\n # se revisa que no estuviera ya en la cola\r\n for i in element:\r\n aux = len(almacenados.inorder_traverse())\r\n # esto es para convertir la lista en str\r\n almacenados.insert(''.join(map(str, element)))\r\n if len(almacenados.inorder_traverse()) != aux:\r\n bfs.put(element[i])\r\n\r\n\r\n# me devuelve los posibles tableros segun la posicion donde este el cero\r\ndef selector_de_ramas(board):\r\n aux = []\r\n result = []\r\n index = -1\r\n for i in board:\r\n aux[i] = board[i]\r\n if board[i] == 0:\r\n index = i\r\n if index == 0:\r\n aux[0] = board[1]\r\n aux[1] = board[0]\r\n result[0] = aux\r\n aux[1] = board[1]\r\n aux[0] = board[3]\r\n aux[3] = board[0]\r\n result[1] = aux\r\n return result\r\n elif index == 1:\r\n aux[1] = board[0]\r\n aux[0] = board[1]\r\n result[0] = aux\r\n aux[0] = board[0]\r\n aux[1] = board[2]\r\n aux[2] = board[1]\r\n result[1] = aux\r\n aux[2] = board[2]\r\n aux[1] = board[4]\r\n aux[4] = board[1]\r\n result[2] = aux\r\n return result\r\n elif index == 2:\r\n aux[2] = board[1]\r\n aux[1] = board[2]\r\n result[0] = aux\r\n aux[1] = board[1]\r\n aux[2] = board[5]\r\n aux[5] = board[2]\r\n result[1] = aux\r\n return result\r\n elif index == 3:\r\n aux[3] = board[0]\r\n aux[0] = board[3]\r\n result[0] = aux\r\n aux[0] = board[0]\r\n aux[3] = board[4]\r\n aux[4] = board[3]\r\n result[1] = aux\r\n aux[4] = board[4]\r\n aux[3] = board[6]\r\n aux[6] = board[3]\r\n result[2] = aux\r\n return result\r\n elif index == 4:\r\n aux[4] = board[3]\r\n aux[3] = board[4]\r\n result[0] = aux\r\n aux[3] = board[3]\r\n aux[4] = board[1]\r\n aux[1] = board[4]\r\n result[1] = aux\r\n aux[1] = board[1]\r\n aux[4] = board[5]\r\n aux[5] = board[4]\r\n result[2] = aux\r\n aux[5] = board[5]\r\n aux[4] = board[7]\r\n aux[7] = board[4]\r\n result[3] = aux\r\n return result\r\n elif index == 5:\r\n aux[5] = board[2]\r\n aux[2] = board[5]\r\n result[0] = aux\r\n aux[2] = board[2]\r\n aux[5] = board[4]\r\n aux[4] = board[5]\r\n result[1] = aux\r\n aux[4] = board[4]\r\n aux[5] = board[8]\r\n aux[8] = board[5]\r\n result[2] = aux\r\n return result\r\n elif index == 6:\r\n aux[6] = board[3]\r\n aux[3] = board[6]\r\n result[0] = aux\r\n aux[3] = board[3]\r\n aux[6] = board[7]\r\n aux[7] = board[6]\r\n result[1] = aux\r\n return result\r\n elif index==7:\r\n aux[7] = board[6]\r\n aux[6] = board[7]\r\n result[0] = aux\r\n aux[6] = board[6]\r\n aux[7] = board[4]\r\n aux[4] = board[7]\r\n result[1] = aux\r\n aux[4] = board[4]\r\n aux[7] = board[8]\r\n aux[8] = board[7]\r\n result[2] = aux\r\n return result\r\n elif index==8:\r\n aux[8] = board[7]\r\n aux[7] = board[8]\r\n result[0] = aux\r\n aux[7] = board[7]\r\n aux[8] = board[5]\r\n aux[5] = board[8]\r\n result[1] = aux\r\n return result\r\n\r\n\r\n# Sacado de: http://blog.coder.si/2014/02/how-to-implement-avl-tree-in-python.html\r\nclass avlnode(object):\r\n def __init__(self, key):\r\n self.key = key\r\n self.left = None\r\n self.right = None\r\n\r\n def __str__(self):\r\n return str(self.key)\r\n\r\n def __repr__(self):\r\n return str(self.key)\r\n\r\n\r\nclass avltree(object):\r\n def __init__(self):\r\n\r\n self.node = None\r\n self.height = -1\r\n self.balance = 0\r\n\r\n def insert(self, key):\r\n n = avlnode(key)\r\n\r\n if not self.node:\r\n self.node = n\r\n self.node.left = avltree()\r\n self.node.right = avltree()\r\n elif key < self.node.key:\r\n self.node.left.insert(key)\r\n elif key > self.node.key:\r\n self.node.right.insert(key)\r\n\r\n self.rebalance()\r\n\r\n def rebalance(self):\r\n self.update_heights(recursive=False)\r\n self.update_balances(False)\r\n while self.balance < -1 or self.balance > 1:\r\n if self.balance > 1:\r\n\r\n if self.node.left.balance < 0:\r\n self.node.left.rotate_left()\r\n self.update_heights()\r\n self.update_balances()\r\n self.rotate_right()\r\n self.update_heights()\r\n self.update_balances()\r\n\r\n if self.balance < -1:\r\n\r\n if self.node.right.balance > 0:\r\n self.node.right.rotate_right() # we're in case III\r\n self.update_heights()\r\n self.update_balances()\r\n self.rotate_left()\r\n self.update_heights()\r\n self.update_balances()\r\n\r\n def update_heights(self, recursive=True):\r\n if self.node:\r\n if recursive:\r\n if self.node.left:\r\n self.node.left.update_heights()\r\n if self.node.right:\r\n self.node.right.update_heights()\r\n\r\n self.height = 1 + max(self.node.left.height, self.node.right.height)\r\n else:\r\n self.height = -1\r\n\r\n def update_balances(self, recursive=True):\r\n if self.node:\r\n if recursive:\r\n if self.node.left:\r\n self.node.left.update_balances()\r\n if self.node.right:\r\n self.node.right.update_balances()\r\n\r\n self.balance = self.node.left.height - self.node.right.height\r\n else:\r\n self.balance = 0\r\n\r\n def rotate_right(self):\r\n new_root = self.node.left.node\r\n new_left_sub = new_root.right.node\r\n old_root = self.node\r\n\r\n self.node = new_root\r\n old_root.left.node = new_left_sub\r\n new_root.right.node = old_root\r\n\r\n def rotate_left(self):\r\n new_root = self.node.right.node\r\n new_left_sub = new_root.left.node\r\n old_root = self.node\r\n\r\n self.node = new_root\r\n old_root.right.node = new_left_sub\r\n new_root.left.node = old_root\r\n\r\n def delete(self, key):\r\n if self.node is not None:\r\n if self.node.key == key:\r\n if not self.node.left.node and not self.node.right.node:\r\n self.node = None\r\n elif not self.node.left.node:\r\n self.node = self.node.right.node\r\n elif not self.node.right.node:\r\n self.node = self.node.left.node\r\n else:\r\n successor = self.node.right.node\r\n while successor and successor.left.node:\r\n successor = successor.left.node\r\n\r\n if successor:\r\n self.node.key = successor.key\r\n\r\n self.node.right.delete(successor.key)\r\n\r\n elif key < self.node.key:\r\n self.node.left.delete(key)\r\n\r\n elif key > self.node.key:\r\n self.node.right.delete(key)\r\n\r\n self.rebalance()\r\n\r\n def inorder_traverse(self):\r\n\r\n result = []\r\n\r\n if not self.node:\r\n return result\r\n\r\n result.extend(self.node.left.inorder_traverse())\r\n result.append(self.node.key)\r\n result.extend(self.node.right.inorder_traverse())\r\n\r\n return result\r\n\r\n def display(self, node=None, level=0):\r\n if not node:\r\n node = self.node\r\n\r\n if node.right.node:\r\n self.display(node.right.node, level + 1)\r\n print('\\t' * level), ' /'\r\n\r\n print('\\t' * level), node\r\n\r\n if node.left.node:\r\n print('\\t' * level), ' \\\\'\r\n self.display(node.left.node, level + 1)\r\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":8567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"344362943","text":"from Classes import Card, Pile, Deck, Player, Center, Ai, MCTS\nimport os\nimport copy\nimport time\nimport pandas as pd\nimport argparse\n\n# # Encode the game state from the perspective of a player\n# def encodeHistory(player,center):\n# # There is a 52-D vector, 0 if that card is not in hand, 1 if that card is in hand\n# cards = [0 for i in range(52)]\n# for card in player.hand:\n# cards[13*card.suit + card.value - 1] = 1\n# # There is a 13-D vector representing the spades, 0 if that card has not been seen, 1 \n\ntimeForMCTS = 1000000\n\ndef playGame():\n humanScoreHistory = []\n computerScoreHistory = []\n gameHistory = []\n center = Center.Center()\n deck = Deck.Deck()\n human = Ai.Ai(0)\n computer = Player.Player(1)\n human.addOpponent(computer)\n\n validBidHand = False\n while not(validBidHand):\n deck = Deck.Deck()\n human = Ai.Ai(0)\n computer = Player.Player(1)\n human.addOpponent(computer)\n for i in range(4):\n human.addCardsToHand([deck.dealCard()])\n computer.addCardsToHand([deck.dealCard()])\n if max([c.value for c in human.hand]) >= 9:\n validBidHand = True\n\n print(\"Entering the Bidding Stage\")\n print(\"Human Hand\")\n print(human.hand)\n # bidValue = int(input(\"Choose a Bid From Your Hand. -1 To Reshuffle\\n\"))\n bidValue = human.chooseBid() # random bid\n print(\"BID VALUE IS\",bidValue)\n for i in range(4):\n card = deck.dealCard()\n human.cardHistory[card.suit][card.value - 1] = 1\n computer.cardHistory[card.suit][card.value - 1] = 1\n center.addNewPile(Pile.Pile(card.value,[card]),True)\n\n print(center)\n move = human.makeMove(center,True,bidValue)\n humanScoreHistory.append(human.calculateScore())\n computer.evaluateOpponentMove(move)\n #human.makeMove(center,True,bidValue)\n for i in range(8):\n human.addCardsToHand([deck.dealCard()])\n computer.addCardsToHand([deck.dealCard()])\n #print(\"COMPUTERS HAND\")\n print(center)\n print(\"Computer Hand\",computer.hand)\n move = MCTS.MCTS(center,computer,human,True,timeForMCTS,roundForMCTS).run_simulation()\n computer.doMove(move,center)\n computerScoreHistory.append(computer.calculateScore())\n human.evaluateOpponentMove(move)\n\n while len(computer.hand) > 0:\n # print(\"HUMANS MOVE IS:\")\n # human.makeMove(center)\n print(center)\n print(human.hand)\n # move = human.HumanChooseMove(center,False)\n move = human.makeMove(center)\n humanScoreHistory.append(human.calculateScore())\n computer.evaluateOpponentMove(move)\n print(center)\n print(computer.hand)\n print(\"COMPUTERS MOVE IS:\")\n # move = computer.makeMove(center)\n move = MCTS.MCTS(center,computer,human,True,timeForMCTS,roundForMCTS).run_simulation()\n computer.doMove(move,center)\n computerScoreHistory.append(computer.calculateScore())\n human.evaluateOpponentMove(move)\n\n print(\"HALF WAY SCORES\")\n print(\"Human Score\",human.calculateScore())\n print(\"Computer Score\",computer.calculateScore())\n\n for i in range(12):\n human.addCardsToHand([deck.dealCard()])\n computer.addCardsToHand([deck.dealCard()])\n\n while len(computer.hand) > 0:\n # print(\"HUMANS MOVE IS:\")\n # human.makeMove(center)\n print(center)\n print(human.hand)\n # move = human.HumanChooseMove(center,False)\n move = human.makeMove(center)\n humanScoreHistory.append(human.calculateScore())\n computer.evaluateOpponentMove(move)\n print(center)\n print(computer.hand)\n print(\"COMPUTERS MOVE IS:\")\n move = MCTS.MCTS(center,computer,human,False,timeForMCTS,roundForMCTS).run_simulation()\n computer.doMove(move,center)\n computerScoreHistory.append(computer.calculateScore())\n human.evaluateOpponentMove(move)\n\n \n # print(\"FINAL CENTER\")\n # print(center)\n print(\"ALL THE CENTER PILES ARE GOING TO \",center.lastPickUp)\n print(\"SCORES BEFORE CLEANING UP\")\n print(\"Human Score\",human.calculateScore())\n print(\"Computer Score\",computer.calculateScore())\n center.finalCleanUp(computer if center.lastPickUp == 0 else human)\n print(\"FINAL SCORE\")\n print(\"Human Score\",human.calculateScore())\n print(\"Computer Score\",computer.calculateScore())\n return (gameHistory, human.calculateScore(), computer.calculateScore(), humanScoreHistory, computerScoreHistory)\n\n# playGame()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-d1\", help='Depth in expectimax', required=True, type=int)\nparser.add_argument(\"-d2\", help='Depth in minimax', required=True, type=int)\nparser.add_argument('-l', nargs=4, help='Weights in evaluation function', required=True, type=int)\nparser.add_argument(\"-r\", help='Round in MCTS', required=True, type=int)\nparser.add_argument(\"-c\", help='Current gameplay', required=True, type=int)\nparser.add_argument(\"-m\", help='Maximun gameplay', required=True, type=int)\nparser.add_argument(\"-d\", help='Results directory', required=True, type=str)\nargs = parser.parse_args()\n# print(args.d1)\nAi.depth1 = args.d1\nAi.depth2 = args.d2\nAi.weights = args.l\nroundForMCTS = args.r\ncurrentGame = args.c\nmaxGameplay = args.m\nresultDir = args.d\ngameStatDir = 'gameResult/'\nscoresFile = 'scores.csv'\ngameFile = 'gameplay'\n\nif __name__ == \"__main__\":\n try:\n scoresDf = pd.read_csv(resultDir+scoresFile, index_col=0)\n except pd.io.common.EmptyDataError and FileNotFoundError:\n print(\"WARMING:\",resultDir+scoresFile, \"is empty\")\n scoresDf = pd.DataFrame(columns=['MCTS', 'Expectiminimax'])\n while currentGame < maxGameplay:\n print('Game', currentGame)\n Ai.scoresHistory = []\n MCTS.winRateHistory = []\n start_time = time.time()\n history, hmScore, aiScore, hmScoreHis, aiScoreHis = playGame()\n newScore = pd.Series({'MCTS':hmScore, 'Expectiminimax':aiScore},name=currentGame)\n scoresDf = scoresDf.append(newScore)\n scoresDf.to_csv(resultDir+scoresFile)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n # print(len(Ai.scoresHistory))\n # print(len(MCTS.winRateHistory))\n gameStat = pd.DataFrame({'Expectiminimax scores':Ai.scoresHistory, 'Expectiminimax game scores':hmScoreHis, 'MCTS win rates':MCTS.winRateHistory, 'MCTS game scores':aiScoreHis})\n gameStat.to_csv(resultDir+gameStatDir+gameFile+str(currentGame)+'.csv')\n currentGame+=1\n","sub_path":"minimaxGame.py","file_name":"minimaxGame.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"288102058","text":"# -*- coding:utf-8 -*-\n# /usr/bin/env python\n\"\"\"\nDate: 2020/4/6 20:37\nDesc: 中国期货市场监控中心-指数\nhttp://index.cfmmc.com/index/views/index.html\n\"\"\"\nimport requests\nimport pandas as pd\nfrom io import BytesIO\nfrom bs4 import BeautifulSoup\n\n\ndef futures_index_dict():\n \"\"\"\n name and code map\n :return: name to code\n :rtype: dict\n index_code\n 商品期货指数 CCFI\n 农产品期货指数 CAFI\n 油脂油料期货指数 OOFI\n 谷物期货指数 CRFI\n 油脂期货指数 OIFI\n 粮食期货指数 GRFI\n 软商品期货指数 SOFI\n 饲料期货指数 FEFI\n 工业品期货指数 CIFI\n 钢铁期货指数 STFI\n 建材期货指数 BMFI\n 能化期货指数 ECFI\n 商品综合指数 CCCI\n 林木综合指数 FWCI\n 能化综合指数 ECCI\n 金属综合指数 MECI\n 农畜综合指数 ALCI\n \"\"\"\n url = \"http://index.cfmmc.com/index/views/index.html\"\n r = requests.get(url)\n soup = BeautifulSoup(r.text, \"lxml\")\n name_list = [item.text.strip() for item in soup.find(attrs={\"class\": \"down_box\"}).find_all(\"b\")[1:]]\n code_list = [item[\"indexcode\"] for item in soup.find(attrs={\"class\": \"down_box\"}).find_all(\"b\")[1:]]\n return dict(zip(name_list, code_list))\n\n\ndef futures_index_cfmmc(index_name=\"商品综合指数\", start_date=\"2010-01-01\", end_date=\"2020-04-06\"):\n \"\"\"\n 中国期货市场监控中心-各类指数数据\n http://index.cfmmc.com/index/views/index.html\n :param index_name: 指数名称 大类 {\"商品期货指数\", \"农产品期货指数\", \"商品期货指数\", \"工业品期货指数\", \"商品综合指数\"}, refer futures_index_dict\n :type index_name: str\n :param start_date: default \"2010-01-01\"\n :type start_date: str\n :param end_date: default \"2020-04-06\"\n :type end_date: str\n :return: index data frame\n :rtype: pandas.DataFrame\n \"\"\"\n futures_index_map = futures_index_dict()\n url = \"http://index.cfmmc.com/servlet/indexAction\"\n params = {\n \"function\": \"DowladIndex\",\n \"start\": start_date,\n \"end\": end_date,\n \"code\": futures_index_map[index_name],\n \"codeName\": index_name,\n }\n r = requests.get(url, params=params)\n temp_df = pd.read_excel(BytesIO(r.content))\n return temp_df\n\n\nif __name__ == '__main__':\n futures_index_dict_temp = futures_index_dict()\n futures_index_df = pd.DataFrame.from_dict(futures_index_dict_temp, orient=\"index\", columns=[\"index_code\"])\n print(futures_index_df)\n futures_index_cfmmc_df = futures_index_cfmmc(index_name=\"林木综合指数\", start_date=\"2010-01-01\", end_date=\"2020-04-06\")\n print(futures_index_cfmmc_df)\n","sub_path":"akshare/futures/futures_cfmmc.py","file_name":"futures_cfmmc.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"506585182","text":"# 20K1026 日比野将己\n# 第1回 レポート課題プログラム\n# --------------------------\n# プログラム名: 20K1026-日比野将己-R01.py\n\nfrom tkinter import *\nfrom dataclasses import dataclass\nimport random\nimport time\n\n# 初期状態の設定\nSPEEDS = [-2, -1, 1, 2] # ボールのx方向初速選択肢\nBLOCKS_X = [150, 250, 350, 400] # ブロックのx座標のリスト\nrandom.shuffle(BLOCKS_X)\nBLOCKS_Y = [100, 200, 300, 350] # ブロックのy座標のリスト\nrandom.shuffle(BLOCKS_Y)\nBLOCKS_W = [40, 40, 40, 40] # ブロックの幅のリスト\nBLOCKS_H = [20, 20, 20, 20] # ブロックの高さのリスト\nDURATION = 0.01 # 描画間隔(秒)\nBALL_X0 = 470 # ボールの初期位置(x)\nBALL_Y0 = 550 # ボールの初期位置(y)\nPADDLE_X0 = 350 # パドルの初期位置(x)\nPADDLE_Y0 = 500 # パドルの初期位置(y)\nPADDLE_VX = 5 # パドルの速度\nWALL_X0 = 100 # 外枠のx座標\nWALL_Y0 = 80 # 外枠のy座標\nWALL_W = 400 # 外枠の幅\nWALL_H = 500 # 外枠の高さ\n\nBALL_VX = random.choice(SPEEDS) # ボールのx方向初速\nBALL_VY = -10 # ボールのy方向初速\n\nGRAVITY = 0.12 # 重力加速度\nREACTION = 1 # 反発係数\n\ncount1 = 0 # ブロックのx座標を判定する count\ncount2 = 0 # ブロックのy座標を判定する count\ncount3 = 0 # スタート画面制御\ncount4 = 0 # db からダウンロード\n\nplay = 0 # ゲーム前か後か\nscore = 0 # スコアの初期化\nselect_x = 150 # 以下4つ、初めから続きからの選択の四角\nselect_y = 170\nselect_w = 300\nselect_h = 80\nc = 0 # パドルの色\n\n# 変える色を用意する。\nCOLORS = [\"#1f0000\", \"#3f0000\", \"#5f0000\", \"#7f0000\", \"#9f0000\", \"#bf0000\", \"#df0000\", \"#ff0000\"] # だんだん赤\n\n\n# -------------------------\n@dataclass\nclass Ball:\n id: int\n x: int\n y: int\n vx: int\n vy: int\n d: int\n c: str\n\n\n@dataclass\nclass Paddle:\n id: int\n x: int\n y: int\n w: int\n h: int\n vx: int\n c: str\n\n\n@dataclass\nclass Wall:\n x: int\n y: int\n w: int\n h: int\n\n\n@dataclass\nclass Block:\n id: int\n x: int\n y: int\n w: int\n h: int\n c: str\n\n\n@dataclass\nclass Point:\n id: int\n x: int\n y: int\n score: int\n\n\n@dataclass\nclass Select:\n id: int\n y: int\n\n\n# -------------------------\n\ndef make_wall(wall): # 外枠を作る関数\n global canvas\n canvas.create_rectangle(wall.x, wall.y, wall.x + wall.w, wall.y + wall.h, width=10, outline=\"white\") # 外枠\n canvas.create_line(wall.x + wall.w - 50, wall.y + 150, wall.x + wall.w - 50, wall.y + wall.h, width=10,\n fill=\"white\") # 縦線\n canvas.create_line(wall.x + wall.w - 100, wall.y, wall.x + wall.w, wall.y + 50, width=10, fill=\"white\") # 右上斜め\n canvas.create_line(wall.x, paddle.y - 50, wall.x + 80, paddle.y, width=10, fill=\"white\") # 左下斜め\n canvas.create_line(wall.x + wall.w - 130, paddle.y, wall.x + wall.w - 50, paddle.y - 50, width=10,\n fill=\"white\") # 右下斜め\n\n\n# ブロックの描画\ndef make_block(x, y, w, h, c=\"blue\"): # ブロックを作成する関数\n global canvas\n id = canvas.create_rectangle(x, y, x + w, y + h, fill=c, outline=\"white\") # id に保存\n return Block(id, x, y, w, h, c) # 生成クラスを返す\n\n\n# ブロックの消去\ndef delete_block(block): # ブロックを消す関数\n global blocks\n canvas.delete(block.id) # ブロックのidを消す\n blocks.remove(block) # ブロック自体を消す\n\n\n# ブロックをまとめて描画\ndef make_blocks(x, y, w, h):\n blocks = [] # ブロックのリスト\n for i in range(len(x)): # 4回繰り返す\n blocks.append(make_block(x[i], y[i], w[i], h[i])) # ブロックを生成してリストに追加\n return blocks # リストを返す\n\n\ndef block_judge(block): # ブロックに当たったかを判定する関数\n global canvas, count1, count2, score\n if ball.x + ball.d > block.x and ball.x < block.x + block.w: # もしブロックの上か下にボールがあれば\n count1 = 1 # count1 を1にする\n else:\n count1 = 0 # その他は 0\n if ball.y + ball.d > block.y and ball.y < block.y + block.h and count1 == 1: # count1 が1で、ボールがブロックの上か下に当たれば\n ball.vy = -ball.vy # y方向に反射させる\n count1 = 2\n\n if ball.x <= block.x <= ball.x + ball.d and ball.y >= block.y and ball.y + ball.d <= block.y + block.h:\n # もし左横からぶつかれば\n ball.vx = -ball.vx # x方向に反射させる\n count2 = 1\n elif ball.x <= block.x + block.w <= ball.x + ball.d and ball.y >= block.y and ball.y + ball.d <= block.y + block.h: # もし右横からぶつかれば\n ball.vx = -ball.vx # x方向に反射させる\n count2 = 1\n else:\n count2 = 0\n\n if count1 == 2 or count2 == 1: # ブロックに当たれば\n delete_block(block) # ブロックを消す\n score += 10 # スコアを加算する\n redraw_point() # ポイントを書き換える\n # このようにそれぞれを完全に独立しておかないとお互い競合して vx と vy が両方変わって、当たったほうに戻っちゃう\n\n\n# ball\n# ボールの描画・登録\ndef make_ball(x, y, vx, vy, d=3, c=\"white\"): # ボールを作る関数\n global canvas\n id = canvas.create_oval(x, y, x + d, y + d,\n fill=c, outline=c) # 初期位置を id として保存\n return Ball(id, x, y, vx, vy, d, c) # Ballクラスに id を加えて返す\n\n\n# ボールの移動\ndef move_ball(ball): # ボールの移動関数\n ball.x += ball.vx # x 座標を vx 分移動させる\n ball.vy += GRAVITY # vy に重力加速度を付加\n ball.y += ball.vy # y 座標を vy 分移動させる\n\n\n# ボールの再描画\ndef redraw_ball(ball): # ボール再描写関数\n canvas.coords(ball.id, ball.x, ball.y,\n ball.x + ball.d, ball.y + ball.d) # id の値を書き換える\n\n\n# -------------------------\n# paddle\n# パドルの描画・登録\ndef make_paddle(x, y, w=100, h=10, c=\"white\"): # パドルを作る関数\n id = canvas.create_rectangle(x, y, x + w, y + h,\n fill=c, outline=\"white\") # id に初期値を保存\n return Paddle(id, x, y, w, h, 0, c) # パドルクラスに id をいれて返す\n\n\n# パドルの移動(左右)\ndef move_paddle(pad): # パドルの移動関数\n pad.x += pad.vx # x 座標を vx 分移動させる\n\n\n# パドルの色を変える\ndef change_paddle_color(pad, c): # パドルの色を変える関数\n canvas.itemconfigure(pad.id, fill=c) # id の fill を c にする\n canvas.itemconfigure(pad.id, outline=\"white\") # id の outline を c にする\n redraw_paddle(pad) # パドルを再描写する\n\n\n# パドルの再描画\ndef redraw_paddle(pad): # パドルの再描写関数\n global canvas\n canvas.coords(pad.id, pad.x, pad.y, pad.x + pad.w, pad.y + pad.h) # id の値を書き換える\n\n\n# -------------------------\n# パドル操作のイベントハンドラ\ndef left_paddle(event): # 速度を左向き(マイナス)に設定(左押された用)\n paddle.vx = -PADDLE_VX # パドルを左に移動させる\n\n\ndef right_paddle(event): # 速度を右向き(マイナス)に設定(右押された用)\n paddle.vx = PADDLE_VX # パドルを右に移動させる\n\n\ndef stop_paddle(event): # 速度をゼロに設定(何も押さない用)\n paddle.vx = 0 # パドルを止める\n\n\ndef play_start(event):\n global play, count3\n if count3 == 0: # 1回目\n canvas.delete(start_rect, start_text) # 最初の画面を削除\n count3 = 1\n elif count3 == 1: # 2回目\n canvas.delete(select_rect1, select_rect2, select_text1, select_text2) # 選択画面を削除\n count3 = 2\n else: # 3回目\n play = 1 # ゲームスタート\n\n\ndef select_up(event): # 上押したら\n select.y = 170 # y を170に\n redraw_select(select) # 四角形再描写\n\n\ndef select_down(event): # 下押したら\n global select_y\n select.y = 260 # y を260に\n redraw_select(select) # 四角形再描写\n select_y = select.y # y 座標を変数に代入\n\n\n# -------------------------\n# その他\ndef draw_point(score): # スコアを表示する関数\n global canvas, point\n canvas.create_rectangle(20, 20, 150, 50, width=3, fill=\"lightgrey\") # 枠作成\n id = canvas.create_text(75, 38, text=f\"score:{score}\", font=(\"\", 15, \"bold\")) # 文字idに保存\n return id # id を返す\n\n\ndef redraw_point(): # スコアの更新関数\n global canvas, point\n canvas.delete(point) # スコアの描写を消す\n point = canvas.create_text(75, 38, text=f\"score:{score}\", font=(\"\", 15, \"bold\")) # 新しいスコアを描写する  # coords は座標しか変えれない\n\n\ndef start(): # スタート画面作成関数\n global canvas, start_rect, start_text\n start_rect = canvas.create_rectangle(40, 150, 560, 350, fill=\"lightgrey\", width=2) # 枠作成\n start_text = canvas.create_text(300, 250, text=\"START\\n(space)\", font=(\"\", 50, \"bold\")) # 文字作成\n\n\ndef select_score(y): # 選択画面作成関数\n global canvas, select_rect1, select_rect2, select_text1, select_text2\n select_rect1 = canvas.create_rectangle(40, 150, 560, 350, fill=\"lightgrey\", width=2) # 外枠\n select_rect2 = canvas.create_rectangle(150, y, 150 + 300, y + 80, width=5) # 選択枠\n select_text1 = canvas.create_text(300, 210, text=\"最初から\", font=(\"\", 50, \"bold\")) # 最初から\n select_text2 = canvas.create_text(300, 300, text=\"続きから\", font=(\"\", 50, \"bold\")) # 続きから\n return Select(select_rect2, y) # 選択枠を返す\n\n\ndef redraw_select(select): # 選択枠再描写関数\n global canvas\n canvas.coords(select.id, 150, select.y, 150 + 300, select.y + 80) # id の値を書き換える\n\n\ndef finish(): # 終了関数\n global canvas\n if ball.y + ball.d + ball.vy >= wall.y + wall.h or len(blocks) == 0 or c == 8: # ボールが下枠を越えるか、ブロックが無くなるか、8回当たったら\n if select_y == 260: # もし選択が「続きから」なら\n with open(r\"db.txt\", mode=\"w\") as file: # ファイルに書き込む\n file.write(str(score))\n if len(blocks) == 0: # もしブロックが無くなったら\n canvas.create_text(300, 300, text=\"CLEAR!!\", font=(\"\", 50, \"bold\"), fill=\"green\") # クリアと表示\n else:\n canvas.create_text(300, 300, text=\"~GAME OVER~\", font=(\"\", 50, \"bold\"), fill=\"red\") # ゲームオーバーと表示\n\n\n# =================================================\ntk = Tk()\ntk.title(\"Game\") # 左上のタイトルを書ける\n\ncanvas = Canvas(tk, width=600, height=700, bg=\"black\", highlightthickness=0)\ncanvas.pack()\ntk.update()\n\n# -----------------\n# 描画アイテムを準備する。\npaddle = make_paddle(PADDLE_X0, PADDLE_Y0) # パドル作成\nball = make_ball(BALL_X0, BALL_Y0, BALL_VX, BALL_VY, 10) # ボール作成\nwall = Wall(WALL_X0, WALL_Y0, WALL_W, WALL_H) # 外枠作成\nmake_wall(wall) # 実際に外枠作成\nblocks = make_blocks(BLOCKS_X, BLOCKS_Y, BLOCKS_W, BLOCKS_H) # ブロック作成\npoint = draw_point(score) # スコアの描写\nselect = select_score(select_y) # 選択枠の描写\nstart() # スタート画面の制御\n\n# イベントと、イベントハンドラを連結する。\ncanvas.bind_all('', left_paddle) # Left 押したら left_paddle 実行\ncanvas.bind_all('', right_paddle) # Right 押したら right_paddle 実行\ncanvas.bind_all('', stop_paddle) # Left 離したら stop_paddle 実行\ncanvas.bind_all('', stop_paddle) # Right 離したら stop_paddle 実行\ncanvas.bind_all('', play_start) # Space 押したら play_start 実行\ncanvas.bind_all('', select_up) # Up 押したら select_up 実行\ncanvas.bind_all('', select_down) # Down 押したら select_down 実行\n\n# -------------------------\n# プログラムのメインループ\nwhile True:\n move_paddle(paddle) # パドルの移動\n if paddle.x <= wall.x: # パドルが左横の棒に当たったら\n paddle.x = wall.x # パドルをその場に止める\n if paddle.x + paddle.w >= wall.x + wall.w - 50: # パドルが右横の棒に当たったら\n paddle.x = wall.x + wall.w - 50 - paddle.w # パドルをその場に止める\n\n if play == 0:\n redraw_paddle(paddle) # パドルの再描画\n tk.update() # 描画が画面に反映される。\n time.sleep(DURATION) # 次に描画するまで、sleep する。\n continue\n\n if select_y == 260 and count4 == 0: # 下選んで一回目なら\n with open(r\"db.txt\") as file: # ファイルを読み込む\n score = int(file.readline()) # score に代入\n redraw_point() # スコア表示\n count4 = 1 # 1にする\n\n move_ball(ball) # ボールの移動\n if ball.x + ball.vx <= wall.x: # ボールが左枠を越えたら\n ball.vx = -ball.vx # ボールを反射させる\n if ball.x + ball.d + ball.vx >= wall.x + wall.w: # ボールが右枠を越えたら\n ball.vx = -ball.vx # ボールを反射させる\n if ball.y + ball.vy <= wall.y: # ボールが上枠を越えたら\n ball.vy = -ball.vy # ボールを反射させる\n if wall.x + wall.w - 50 >= ball.x >= wall.x + wall.w - 52 and ball.y >= wall.y + 150: # 縦線で跳ね返る\n ball.vx = -ball.vx\n if wall.x + wall.w - 100 <= ball.x <= wall.x + wall.w and wall.y <= ball.y <= wall.y + 50 and ball.y <= (\n 1 / 2) * ball.x - 120: # 右上斜めで跳ね返る\n ball.vy = -ball.vy # y方向に跳ね返る\n ball.vx = -abs(ball.vx) # 絶対マイナス方向\n if wall.x <= ball.x <= wall.x + 80 and paddle.y - 50 <= ball.y + ball.d <= paddle.y and (\n 5 / 8) * ball.x + 387.5 <= ball.y + ball.d: # 左下斜めで跳ね返る\n ball.vy = -ball.vy # y 方向に跳ね返る\n ball.y = (5 / 8) * ball.x + 387.5 - ball.d # 線上にする\n\n if wall.x + wall.w - 130 <= ball.x + ball.d <= wall.x + wall.w - 50 and paddle.y - 50 <= ball.y + ball.d <= paddle.y \\\n and ball.y + ball.d >= -(5 / 8) * ball.x + ball.d + 731.25: # 右下斜めで跳ね返る\n ball.vy = -ball.vy # y 方向に跳ね返る\n ball.y = -(5 / 8) * ball.x + ball.d + 731.25 - ball.d # 線上にする\n\n if ball.y + ball.d + ball.vy >= wall.y + wall.h or len(blocks) == 0 or c == 8: # ボールが下枠を越えたら\n if select_y == 260: # もし「続きから」なら\n with open(r\"db.txt\", mode=\"w\") as file: # ファイルに保存する\n file.write(str(score))\n finish() # 文字表示\n break # while を抜ける(終了)\n\n # ボールの下側がパドルの上面に届き、横位置がパドルと重なる\n if (paddle.y <= ball.y + ball.d <= paddle.y + paddle.h \\\n and paddle.x <= ball.x + ball.d / 2 <= paddle.x + paddle.w): # パドルにボールが当たったら\n change_paddle_color(paddle, COLORS[c]) # だんだん赤くなる\n c += 1 # インデックスを+!\n ball.vy = -ball.vy * REACTION # ボールの移動方向が変わる(反射が大きくなる)\n ball.y = paddle.y - ball.d # 線上にする\n\n if ball.x <= wall.x + 50 and ball.y + ball.d >= paddle.y \\\n or ball.x >= wall.x + wall.w - 100 and ball.y + ball.d >= paddle.y: # ボールが左の棒か右の棒に当たったら\n ball.vy = -ball.vy # ボールを反射させる\n ball.y = paddle.y - ball.d # 線上にする\n\n for block in blocks: # 4 回繰り返す(今回は4つ作るから)\n block_judge(block) # ボールがブロックに当たったら跳ね返す\n\n redraw_paddle(paddle) # パドルの再描画\n redraw_ball(ball) # ボールの再描画\n tk.update() # 描画が画面に反映される。\n time.sleep(DURATION) # 次に描画するまで、sleep する。\n\ntk.mainloop()\n","sub_path":"08/前回.py","file_name":"前回.py","file_ext":"py","file_size_in_byte":16398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"448043387","text":"from django.conf.urls import url\n\nfrom cake import views\n\nurlpatterns = [\n # 首页\n url(r'^$', views.index, name='index'),\n # 蛋糕\n url(r'^cake/$', views.cake, name='cake'),\n # 面包\n url(r'^bread/$', views.bread, name='bread'),\n # 冰激凌\n url(r'^ice/$', views.ice, name='ice'),\n # 咖啡下午茶\n url(r'^coffee/$', views.coffee, name='coffee'),\n # 常温蛋糕\n url(r'^normal_cake/$', views.normal_cake, name='normal_cake'),\n # 设计师礼品\n url(r'^design/$', views.design, name='design'),\n # 全国送\n url(r'^country/$', views.country, name='country'),\n # 企业专区\n url(r'^company/$', views.company, name='company'),\n # 通知\n url(r'^inform/$', views.inform, name='inform'),\n # 物流\n url(r'^wuliu/$', views.wuliu, name='wuliu'),\n # 购物车\n url(r'^gouwu/$', views.gouwu, name='gouwu'),\n # pay\n url(r'^go_jiesuan/$', views.go_jiesuan, name='go_jiesuan'),\n # 结算\n url(r'^jiesuan/$', views.jiesuan, name='jiesuan'),\n # 商品详情\n url(r'^detail/$', views.detail, name='detail'),\n # 我的订单\n url(r'^orderlist/$', views.orderlist, name='orderlist'),\n # 未完成订单\n url(r'^unfinish/$', views.unfinish, name='unfinish'),\n # 我的订单为空\n url(r'^none_orderlist/$', views.none_orderlist, name='none_orderlist'),\n\n # 注册\n url(r'^register/$', views.register, name='register'),\n # 登录\n url(r'^user_login/$', views.user_login, name='user_login'),\n # 退出登录\n url(r'^user_logout/$', views.user_logout, name='user_logout'),\n # 21客会员协议\n url(r'^agreement/$', views.agreement, name='agreement'),\n # 隐私保护协议\n url(r'^secret/$', views.secret, name='secret'),\n # 获取验证码\n url(r'^yzm/$', views.yzm, name='yzm'),\n # 个人中心\n url(r'^personal/$', views.personal, name='personal'),\n\n # 生日\n url(r'^birthday/$', views.birthday, name='birthday'),\n # 儿童\n url(r'^child/$', views.child, name='child'),\n\n # 支付\n url(r'^pay/$', views.pay, name='pay'),\n # 取消订单\n url(r'^cancel/$', views.cancel, name='cancel'),\n # 删除订单\n url(r'^delete_order/$', views.delete_order, name='delete_order'),\n\n # 编辑个人资料\n url(r'^edit_permsg/$', views.edit_permsg, name='edit_permsg'),\n # 修改密码\n url(r'^xiugaipass/$', views.xiugaipass, name='xiugaipass'),\n]\n","sub_path":"cake_project/cake/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45930333","text":"# Create your views here.\nimport csv\nimport json\nfrom bson.objectid import ObjectId\nfrom datetime import datetime\nfrom backend.models import Client\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.contrib.auth.models import User, Group\nfrom django.http import Http404\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.http import HttpResponseRedirect\nfrom django.template.defaultfilters import slugify\nfrom django.views.generic.list import ListView\nfrom django.shortcuts import render\nfrom django.core.urlresolvers import reverse\n\nfrom dvutils.decorators import super_user_required\nfrom dvutils.replica_set import fetch_replica_db\nfrom waybill.forms import WaybillForm, WaybillClientForm, WaybillFormBD\nfrom waybill.app_settings import *\nfrom waybill.forms import BarcodeGenerateForm\nfrom waybill.models import WaybillDocument, connection\nfrom waybill.models import find_by_id\nfrom waybill.utils import get_form, dynamic_load_form\nfrom dvutils.utils import api_request\nfrom package.models import Package\nfrom package.app_settings import BARCODE_NSL_CODE\n\n@login_required\ndef waybill_lots(request, client):\n \"\"\"list of all active lots that belong to the input client\"\"\"\n waybill_lots = WaybillLot.objects.filter(active=True)\n if not client == 'all':\n waybill_lots = waybill_lots.filter(client__name=client)\n\n # fetch client names - in single query\n waybill_lots = waybill_lots.select_related('client__name')\n\n # fetch only the fields that we will be displaying\n waybill_lots = waybill_lots.only(\n 'client', 'series', 'count', 'waybill_consumed', 'created_on')\n\n return ListView(request,\n queryset=waybill_lots.order_by('client', '-created_on'),\n extra_context={'client': client})\n\n\n@login_required\ndef waybill_download(request, lot_id):\n \"\"\"generates csv dump of all waybills that belong to the input lot\"\"\"\n try:\n l = WaybillLot.objects.get(id=lot_id)\n except WaybillLot.DoesNotExist:\n raise Http404\n\n filename = '%d_%s_%s_%d_%s.csv' % (\n l.id, slugify(l.client.name), slugify(l.get_series_display()),\n l.count, datetime.strftime(l.created_on, '%Y%m%d'))\n\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n\n writer = csv.writer(response)\n writer.writerow(['Waybill'])\n\n qs = Waybill.objects.filter(lot=l)\n for w in qs.iterator():\n writer.writerow([w.waybill])\n\n return response\n\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_edit_wdoc'))\ndef edit(request, wid=None):\n '''\n :param request:\n :param wid: waybill lot id\n :return: Response\n Add or edit a waybill lot on the basis of wid\n '''\n #get respective form acording the user group\n form_name=get_form(request.user)\n #dayanamically load the form class from form name\n form_level=dynamic_load_form(form_name)\n if wid:\n wdoc = find_by_id(wid)\n form = form_level(wdoc)\n else:\n wdoc = connection.WaybillDocument()\n form = form_level()\n if request.method == \"POST\":\n form = form_level(request.POST)\n if form.is_valid():\n exclude = [x.name for x in form.hidden_fields()]\n for i, v in form.cleaned_data.items():\n if not i in exclude:\n wdoc[i] = WaybillDocument.structure[i](v)\n\n # save and be done!\n wdoc._u = u'%s' % request.user\n wdoc.save()\n return HttpResponseRedirect(\n reverse('waybill.views.listing', args=[wdoc.cl]))\n\n return render(request, 'waybill_edit.html',\n {'form': form, 'wdoc': wdoc, 'wid': wid},\n content_type=\"text/html\")\n\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_delete_wdoc'))\ndef delete(request, wid):\n \"\"\"\n deletes the waybill and redirects to the listing page for that client\n \"\"\"\n wdoc = find_by_id(wid)\n cl = wdoc.cl\n wdoc.delete()\n return HttpResponseRedirect(\n reverse('waybill.views.listing', args=[cl]))\n\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_view_wdoc'))\ndef csv_download(request, wid):\n \"\"\"generates csv dump of all waybills that belong to the input id\"\"\"\n wb = find_by_id(wid)\n\n filename = '%s_%s_%d_%s.csv' % (\n slugify(wb.cl), slugify(wb.t),\n wb.count, datetime.strftime(wb.cd, '%Y%m%dT%H%M'))\n\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n\n writer = csv.writer(response)\n writer.writerow(['Waybill'])\n\n for w in wb.asgn:\n writer.writerow([w])\n\n return response\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_create_wdoc'))\ndef generate_waybill_csv(request):\n \"\"\"generates csv dump of all waybills that belong to the input id\"\"\"\n form = WaybillClientForm()\n error = \"\"\n if request.method == \"POST\":\n form = WaybillClientForm(request.POST)\n if form.is_valid():\n count = int(request.POST.get('count', None))\n cl = request.POST.get('cl', None)\n\n wb = api_request('GET', '/waybill/api/bulk/json/',\n {\"cl\": \"%s\" % cl, \"count\": count})\n\n if wb[1][1] != 'OK':\n return render(request, 'generate_waybills.html',\n {'form': form,\n 'error': \"Invalid client or count selected\"},\n content_type=\"text/html\")\n\n # Generating CSV to download\n filename = '%s_%d_%s.csv' % (\n slugify(cl), count,\n datetime.now().strftime('%Y%m%dT%H%M'))\n\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n\n writer = csv.writer(response)\n writer.writerow(['Waybill'])\n\n for w in wb[0].split(\",\"):\n writer.writerow([w])\n\n return response\n return render(request, 'generate_waybills.html',\n {'form': form, 'error': error},\n content_type=\"text/html\")\n\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_view_wdoc'))\ndef listing(request, client=None):\n cl = None\n waybills = None\n if not client:\n # display the list of clients\n cl = Client.active.all().order_by('name')\n else:\n find_criteria = dict()\n find_criteria['cl'] = u'%s' % client\n find_criteria['a'] = True\n\n waybills = connection.WaybillDocument.find(\n find_criteria, sort=[('meta.e', -1)])\n\n return render(request, 'listing.html',\n {'waybills': waybills, 'cl': cl, 'client': client},\n content_type=\"text/html\")\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_activate_wdoc'))\ndef activate(request, wid):\n \"\"\"\n activate and deactivate the waybill doc\n \"\"\"\n wdoc = find_by_id(wid)\n if wdoc:\n wdoc.a = not wdoc.a\n wdoc.save()\n return HttpResponseRedirect(\n reverse('waybill.views.csv_download', args=[wid]))\n\n@user_passes_test(lambda u: u.has_perm('waybill.can_generate_barcode'))\ndef generate_barcode(request):\n '''\n This view is used to generate barcode corresponding to the waybills\n provided. It first checks for the validity of the waybills.\n also it adds nsl to the packages\n '''\n location = request.session.get('center')\n form = BarcodeGenerateForm(location, initial={'location':location})\n if request.method=='POST':\n form = BarcodeGenerateForm(location=location, data=request.POST)\n if form.is_valid():\n if request.is_ajax():\n ref_nums = form.cleaned_data['ref_nums']\n print_type = form.cleaned_data['print_type']\n pkgs = fetch_replica_db()['packages'].find({'wbn':{'$in':ref_nums}})\n\n # To print on single-sided page or two-sided\n single_sided = True\n if print_type==u'2':\n single_sided = False\n\n for pkg in pkgs:\n kwargs = {\n 'u' : request.user,\n 'nsl_code' : BARCODE_NSL_CODE,\n 'st' : pkg.get('cs', {}).get('st'),\n 'sd' : datetime.now()}\n Package(pkg)._add_status(**kwargs)\n return render(request, 'waybill_barcode.html',\n {'ref_nums': ref_nums, 'single_sided': single_sided})\n else:\n return HttpResponseBadRequest(form.errors.get('__all__'))\n return render(request, 'generate_barcode.html', {'form':form})\n","sub_path":"waybill/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"165101448","text":"import gym\nimport numpy as np\nfrom gym import wrappers\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nimport tensorflow_probability as tfp\nimport os\nimport tensorflow.keras as keras\nfrom tensorflow.keras.layers import Dense\nimport matplotlib.pyplot as plt\n\nclass Agent:\n def __init__(self, alpha=0.0003, gamma=0.92, n_actions=2, n_outputs=1):\n self.gamma = gamma\n self.n_actions = n_actions\n self.action = None\n self.log_probs = None\n self.n_outputs = n_outputs\n self.actor_critic = ActorCriticNetwork(n_actions=n_actions)\n self.actor_critic.compile(optimizer=Adam(learning_rate=alpha))\n\n def choose_action(self, observation):\n state = tf.convert_to_tensor([observation])\n v,pi = self.actor_critic(state)\n mu, sigma = pi[0]\n sigma = tf.math.exp(sigma)\n\n action_probabilities = tfp.distributions.Normal(mu, sigma)\n action = action_probabilities.sample(sample_shape=(4,))\n log_prob = action_probabilities.log_prob(action)\n action = tf.math.tanh(action)\n self.action=action\n return action.numpy()\n\n def save_models(self):\n self.actor_critic.save_weights(self.actor_critic.checkpoint_file)\n print(\"Model Saved\")\n\n def load_models(self):\n self.actor_critic.load_weights(self.actor_critic.checkpoint_file)\n print(\"Loaded Models\")\n\n def learn(self, state, reward, state_, done):\n state = tf.convert_to_tensor([state],dtype=tf.float32)\n state_ = tf.convert_to_tensor([state_],dtype=tf.float32)\n reward = tf.convert_to_tensor(reward,dtype=tf.float32)\n with tf.GradientTape() as tape:\n state_value, probs = self.actor_critic(state)\n state_value_, _ = self.actor_critic(state_)\n state_value = tf.squeeze(state_value)\n state_value_ = tf.squeeze(state_value_)\n action_probs = tfp.distributions.Categorical(probs=probs)\n log_prob = action_probs.log_prob(self.action)\n delta = reward + self.gamma*state_value_*(1-int(done)) - state_value\n actor_loss = -log_prob*delta\n critic_loss = delta**2\n total_loss = actor_loss + critic_loss\n gradient = tape.gradient(total_loss, self.actor_critic.trainable_variables)\n self.actor_critic.optimizer.apply_gradients(zip(\n gradient, self.actor_critic.trainable_variables))\n\n\nclass ActorCriticNetwork(keras.Model):\n def __init__(self, n_actions=2, fc1_dims=1024, fc2_dims=512, name='ActorCritic', chkpt_dir='tmp/ActorCritic'):\n super(ActorCriticNetwork, self).__init__()\n self.fc1_dims = fc1_dims\n self.fc2_dims = fc2_dims\n self.n_actions = n_actions\n self.model_name = name\n self.checkpoint_dir = chkpt_dir\n self.checkpoint_file = os.path.join(self.checkpoint_dir, name)\n self.fc1 = Dense(self.fc1_dims, activation='relu')\n self.fc2 = Dense(self.fc2_dims, activation='relu')\n self.v = Dense(1, activation='relu')\n self.pi = Dense(self.n_actions, activation='relu')\n\n def call(self, state):\n value = self.fc1(state)\n value = self.fc2(value)\n v = self.v(value)\n pi = self.pi(value)\n return v, pi\n\ndef plot_learning_curve(x, scores, figure_file):\n running_avg = np.zeros(len(scores))\n for i in range(len(running_avg)):\n running_avg[i] = np.mean(scores[max(0, i-100):(i+1)])\n plt.plot(x, running_avg)\n plt.title('Running average of previous 100 scores')\n plt.savefig(figure_file)\n\nenv = gym.make('BipedalWalker-v3')\nagent = Agent(alpha=1e-5)\nn_games = 50\nfilename = 'BipedalWalker_Graph.png'\nfigure_file = 'plots/' + filename\nbest_score = env.reward_range[0]\nscore_history = []\nload_checkpoint = False\nif load_checkpoint:\n agent.load_models()\nfor i in range(n_games):\n observation = env.reset()\n done = False\n score = 0\n while not done:\n action = agent.choose_action(observation)\n observation_, reward, done, info = env.step(action)\n score += reward\n if not load_checkpoint:\n agent.learn(observation, reward, observation_, done)\n observation = observation_\n score_history.append(score)\n avg_score = np.mean(score_history[-100:])\n if avg_score > best_score:\n best_score = avg_score\n if not load_checkpoint:\n agent.save_models()\n print(\"Episode\", i, \"with score of\",score, \"and average score of\", avg_score)\nif not load_checkpoint:\n x = [i+1 for i in range(n_games)]\n plot_learning_curve(x, score_history, figure_file)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193383091","text":"'''\nDBSCAN\n 1. creates clusters based on nearest (and most numerous) neighbors\n'''\n\n\nimport sklearn\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy.spatial import distance\nimport timeit\nfrom metrics import DaviesBouldin\n\nstart = timeit.default_timer()\nfile = open('ex_data.csv')\ndf = pd.read_csv(file, sep = ',', index_col = 0, header = 0) #another important note: make sure the sep is set to a comma (',') since you are reading from a comma separated value file (csv)\ndata_matrix = df.as_matrix()\n\n# Compute DBSCAN\ndb = DBSCAN(eps=0.95, min_samples=10).fit(data_matrix) #will have to modify tge eps and the min_samples?\n\ncore_samples_mask = np.zeros_like(db.labels_, dtype=bool)\ncore_samples_mask[db.core_sample_indices_] = True\nlabels = db.labels_\ndbi = DaviesBouldin(X, labels)\n\n\n##############################################################################\n#metrics\nlabels_true = []\nf = open('labels_true.txt') #puts my labels true into a list so its comparable to labels pred\nl = f.readlines()\nfor line in l:\n x = line.split('\\t')\n labels_true.append(int(x[1].strip()))\n\nprint(len(labels_true))\nprint(len(labels))\nprint(\"Davies Bouldin Index: %0.3f\" % dbi)\nprint( \"Homogeneity: %0.3f\" % metrics.homogeneity_score(labels_true, labels))\nprint( \"Completeness: %0.3f\" % metrics.completeness_score(labels_true, labels))\nprint( \"V-measure: %0.3f\" % metrics.v_measure_score(labels_true, labels))\nprint( \"Adjusted Rand Index: %0.3f\" % metrics.adjusted_rand_score(labels_true, labels))\n\nstop = timeit.default_timer()\nprint(stop - start, \" seconds\")\n\n#==============================================================================\nresults = pd.DataFrame([df.index,labels]).T\nresults = results.rename(columns={0 : 'Gene', 1 : 'DBSCAN'})\nresults.to_csv('DBSCAN_results.txt', index=False, header=True,sep=\"\\t\")\n#==============================================================================\n","sub_path":"scripts/DBSCAN_clust_proj.py","file_name":"DBSCAN_clust_proj.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"95779374","text":"# 350. Intersection of Two Arrays II\n# Given two arrays, write a function to compute their intersection.\n\n# Example 1:\n\n# Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]\n# Output: [2, 2]\n# Example 2:\n\n# Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]\n# Output: [4, 9]\n# Note:\n\n# Each element in the result should appear as many times as it shows in both arrays.\n# The result can be in any order.\n# Follow up:\n\n# What if the given array is already sorted? How would you optimize your algorithm?\n# What if nums1's size is small compared to nums2's size? Which algorithm is better?\n# What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?\nfrom collections import Counter\n\n\ndef intersect(nums1, nums2):\n\n nums1 = Counter(nums1)\n nums2 = Counter(nums2)\n res = []\n # nums 1 is larger\n if len(nums1) > len(nums2):\n for k, v in nums1.items():\n if k in nums2.keys():\n while nums1[k] and nums2[k]:\n nums2[k] -= 1\n nums1[k] -= 1\n res.append(k)\n\n else:\n for k, v in nums2.items():\n if k in nums1.keys():\n while nums1[k] and nums2[k]:\n nums2[k] -= 1\n nums1[k] -= 1\n res.append(k)\n return res\n\n\ndef intersect(nums1, nums2):\n\n counts = collections.Counter(nums1)\n res = []\n\n for num in nums2:\n if counts[num] > 0:\n res += num,\n counts[num] -= 1\n\n return res\n\n\nprint(intersect([1, 2, 2, 1], [2, 2])) # [2,2]\nprint(intersect([4, 9, 5], [9, 4, 9, 8, 4])) # [4,9]\n","sub_path":"LeetCode/IntersectionofTwoArraysII.py","file_name":"IntersectionofTwoArraysII.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"568421960","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom flask import Flask,request,render_template,abort\nimport flask\nimport os\nimport sys\nimport pandas as pd\nimport xlrd\nsys.path.append('/home/shopify/shopifyLive')\napp = Flask(__name__)\nfrom shopifyOper import *\n@app.route('/')\ndef test():\n return shopApi()\n\n\n#. 上传页面\n@app.route('/upload-file')\ndef form():\n return \"\"\"\n \n \n

Transform a file demo

\n\n
\n \n \n
\n \n \n \"\"\"\n\n\n\n#. 处理上传文件\n@app.route('/transform',methods=['post','get'])\ndef transform():\n if request.method == 'POST':\n file = request.files['data_file']\n if not file:\n return internal_server_error(500)\n check = check_file_type(file.filename)\n if check == 'csv':\n data = pd.read_csv(file)\n datas = pd.DataFrame(data)\n for x in range(len(datas)):\n row = datas[x:x + 1]\n order_id = row['order_id'][x]\n tracking_number = row['tracking_number'][x]\n store = row['store_id'][x]\n dictData = {'order_id': order_id, 'tracking_number': tracking_number, 'store': store}\n shopifyOper().uploadTracking(dictData)\n elif check in ['xls', 'xlsx']:\n data = pd.read_excel(file)\n resList = []\n db, storeObj = shopifyOper.loadStore([])\n for j in data.index.values:\n df_line = data.loc[j, ['order_id','tracking_number','tracking_url','tracking_company','store_id']].to_dict()\n order_id = df_line['order_id']\n tracking_number = df_line['tracking_number']\n tracking_url = df_line['tracking_url']\n tracking_company = df_line['tracking_company']\n store = df_line['store_id']\n dictData = {'order_id': order_id, 'tracking_number': tracking_number, 'store': store,'tracking_url':tracking_url,'tracking_company':tracking_company}\n result = shopifyOper().uploadTracking(dictData,db,storeObj)\n if not result:\n msg = '失败'\n else:\n msg = '成功'\n resList.append(msg)\n else:\n return '文件类型不正确'\n return '上传状态:' + \"\\r\\n\".join(resList)\n\n\n\n\n\n\n#. 判断文件类型\ndef check_file_type(filename):\n file_type = ['xls','xlsx','csv']\n # 获取文件后缀\n ext = filename.split('.')[1]\n # 判断文件是否是允许上传得类型\n if ext in file_type:\n return ext\n else:\n return False\n\n\n@app.route('/uoload',methods=['post'])\ndef upload():\n if request.method == 'POST':\n try:\n files = request.files['action']\n if not files:\n return internal_server_error(500)\n data = pd.read_csv(files)\n datas = pd.DataFrame(data)\n for x in range(len(datas)):\n row = datas[x:x + 1]\n order_id = row['order_id'][x]\n tracking_number = row['tracking_number'][x]\n dictData = {'order_id': order_id, 'tracking_number': tracking_number}\n shopifyOper().uploadTracking(dictData)\n except Exception as e:\n raise e\n # return internal_server_error(500)\n return '上传成功'\n\n@app.errorhandler(400)\ndef internal_server_error(e):\n return '系统错误'\n\ndef shopApi():\n s = shopifyOper()\n s.pullOrder()\n return '成功'\n\nif __name__ == '__main__':\n app.debug = True # 设置调试模式,生产模式的时候要关掉debug\n app.run(host='0.0.0.0',port=5000)\n","sub_path":"live/shopifyLive/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102171476","text":"import numpy as np\nfrom scipy import stats as stats\n\nimport mne\nfrom mne import (io, spatio_temporal_tris_connectivity, spatial_tris_connectivity, compute_morph_matrix, grade_to_tris)\nfrom mne.stats import (spatio_temporal_cluster_1samp_test, summarize_clusters_stc)\n\nfrom Modelling import *\n\n\ndef obtain_statistical_data(data_cursor, data_robot, subject_to_process, method, vector, trans, src, bem):\n \"\"\"Obtains the data required to perform statistics.\n\n :param data_cursor: -\n :param data_robot: -\n :param subject_to_process: The subject list to process\n :param method: Method to perform modelling ('sLORETA' etc.)\n :param vector: Specify to show in vector form (True or False)\n :param trans: Model obtained from get_FS_data function\n :param src: Model obtained from get_FS_data function\n :param bem: Model obtained from get_FS_data function\n :return: data_array, parameters_cache\n \"\"\"\n # Perform modelling for 1 subject\n model_data, model_cache = perform_modelling(data_cursor['s02'], method, trans, src, bem)\n n_vertices, n_vecs, n_times = model_data['contrast_stc_vec'].shape\n\n # Initialization the empty arrays\n contrast_cursor_array = np.array([]).reshape(n_vertices, n_times, 0)\n contrast_robot_array = np.array([]).reshape(n_vertices, n_times, 0)\n\n contrast_vec_cursor_array = np.array([]).reshape(n_vertices, n_vecs, n_times, 0)\n contrast_vec_robot_array = np.array([]).reshape(n_vertices, n_vecs, n_times, 0)\n\n for i in range(len(subject_to_process)):\n\n # Perform modelling for single subject\n single_subject = subject_to_process[i]\n print('\\nProcessing for subject: ' + single_subject + '\\n')\n\n modelling_data_cursor, model_cache_cursor = perform_modelling(data_cursor[single_subject], method, trans, src,\n bem)\n modelling_data_robot, model_cache_robot = perform_modelling(data_robot[single_subject], method, trans, src, bem)\n\n if vector is False:\n\n # Load the data\n contrast_cursor = modelling_data_cursor['contrast_stc'].data ### Shape is (20484, 257)\n contrast_robot = modelling_data_robot['contrast_stc'].data\n\n # Concatenate the data for all subjects\n contrast_cursor_array = np.concatenate((contrast_cursor_array, contrast_cursor[:, :, np.newaxis]), axis=2)\n contrast_robot_array = np.concatenate((contrast_robot_array, contrast_robot[:, :, np.newaxis]), axis=2)\n\n else:\n\n # Load the data\n contrast_vec_cursor = modelling_data_cursor['contrast_stc_vec'].shape\n contrast_vec_robot = modelling_data_robot['contrast_stc_vec'].shape\n\n # Concatenate the data for all subjects\n contrast_vec_cursor_array = np.concatenate(\n (contrast_vec_cursor_array, contrast_vec_cursor[:, :, :, np.newaxis]), axis=3)\n contrast_vec_robot_array = np.concatenate(\n (contrast_vec_robot_array, contrast_vec_robot[:, :, :, np.newaxis]), axis=3)\n\n if vector is False:\n\n # Concatenate the data for cursor and robot\n data_array = np.concatenate(\n (contrast_cursor_array[:, :, :, np.newaxis], contrast_robot_array[:, :, :, np.newaxis]), axis=3)\n\n # Delete unnecessary data\n del contrast_cursor_array, contrast_robot_array\n\n # Unpack the inverse operator\n inverse_operator = model_cache_cursor['inv']\n subject_vertices = [s['vertno'] for s in inverse_operator['src']]\n\n # Total number of subjects\n n_subjects = len(subject_to_process)\n\n # Cache the parameters in dictionary (for 1 subject, which is representative of both cursor and robot)\n t_step = modelling_data_cursor['contrast_stc'].tstep\n n_vertices, n_times = modelling_data_cursor['contrast_stc'].data.shape\n parameters_cache = {'t_step': t_step, 'n_vertices': n_vertices, 'n_times': n_times, 'n_subjects': n_subjects,\n 'subject_vertices': subject_vertices}\n\n else:\n # Concatenate the data for cursor and robot\n data_array = np.concatenate(\n (contrast_vec_cursor_array[:, :, :, :, np.newaxis], contrast_vec_robot_array[:, :, :, :, np.newaxis]),\n axis=4)\n\n # Delete unnecessary data\n del contrast_vec_cursor_array, contrast_vec_robot_array\n\n # Unpack the inverse operator\n inverse_operator = model_cache['inv']\n subject_vertices = [s['vertno'] for s in inverse_operator['src']]\n\n # Total number of subjects\n n_subjects = len(subject_to_process)\n\n # Cache the parameters in dictionary (for 1 subject, which is representative of both cursor and robot)\n t_step = modelling_data_cursor['contrast_stc_vec'].step\n n_vertices, n_vec, n_times = modelling_data_cursor['contrast_stc_vec'].data.shape\n parameters_cache = {'t_step': t_step, 'n_vertices': n_vertices, 'n_vec': n_vec, 'n_times': n_times,\n 'n_subjects': n_subjects, 'subject_vertices': subject_vertices}\n return data_array, parameters_cache\n\n\ndef morph_data(data_array, parameters_cache, vector, subjects_dir):\n \"\"\"Morphs the subject brains to fs_average brain.\n\n :param data_array: Statistical data obtained from obtain_statistical_data function\n :param parameters_cache: Statistical parameters cache obtained from obtain_statistical_data function\n :param vector: Method to perform modelling ('sLORETA' etc.)\n :param subjects_dir: Directory to the brain model\n :return: (morphed brain data array)\n \"\"\"\n # Unpack parameter cache dictionary\n n_vertices = parameters_cache['n_vertices']\n n_times = parameters_cache['n_times']\n n_subjects = parameters_cache['n_subjects']\n subject_vertices = parameters_cache['subject_vertices']\n\n if vector is True:\n n_vec = parameters_cache['n_vec']\n\n # Create the fs average vertices\n fs_ave_vertices = [np.arange(10242), np.arange(10242)]\n\n # Add in fs_ave_vertices to parameter_cache\n parameters_cache['fs_ave_vertices'] = fs_ave_vertices\n\n # Compute the morph matrix\n smooth_int = 20\n morph_mat = compute_morph_matrix('subjects', 'fsaverage', subject_vertices, fs_ave_vertices, smooth_int,\n subjects_dir)\n n_vertices_fs_ave = morph_mat.shape[0]\n # morph_mat shape is (20484, 20484)\n\n # Reshape in order for dot() to work properly\n if vector is False:\n X = data_array.reshape(n_vertices, n_times * n_subjects * 2) # Shape is (20484, 257*12*2)\n else:\n X = data_array.reshape(n_vertices * n_vec,\n n_times * n_subjects * 2) # Shape is (20484*3, 257*12*2) ##### TO DOUBLE CHECK #####\n\n print('Morphing data...')\n\n X = morph_mat.dot(X) # morph_mat is a sparse matrix\n\n # Reshape into (vertices, times, subjects and conditions)\n if vector is False:\n X = X.reshape(n_vertices_fs_ave, n_times, n_subjects, 2) # Shape is (20484, 257, 12, 2)\n # Reshape into (vertices, vecs, times, subjects and conditions)\n else:\n X = X.reshape(n_vertices, n_vec, n_times, n_subjects, 2) # Shape is (20484, 3, 257, 12, 2)\n return X, parameters_cache\n\n\ndef perform_statistics(morphed_data, parameter_cache, vector, p_value=None):\n \"\"\"Performs the statistical analysis using spatial_tris_connectivity.\n\n :param morphed_data: Morphed data obtained from morph_data function\n :param parameter_cache: Morphed parameter cache obtained from morph_data function.\n :param vector: Method to perform modelling ('sLORETA' etc.)\n :param p_value: Statistical p-value\n :return: clu, good_cluster_inds\n \"\"\"\n # Unpack parameter cache dictionary\n n_subjects = parameter_cache['n_subjects']\n n_times = parameter_cache['n_times']\n\n # Take on the absolute\n X = np.abs(morphed_data)\n\n # Obtain the paired contrast\n if vector is False:\n X = X[:, :, :, 0] - X[:, :, :, 1] # Dimension is (space, time, subjects)\n else:\n X = X[:, :, :, :, 0] - X[:, :, :, :, 1] # Dimension is (space, vector, time, subjects)\n\n print('Computing connectivity... ')\n connectivity = spatial_tris_connectivity(grade_to_tris(5))\n\n # Note that X needs to be a multi-dimensional array of shape [samples (subjects) x time x space]\n if vector is False:\n X = np.transpose(X, [2, 1, 0])\n else:\n X = np.transpose(X, [3, 2, 1, 0]) ##### TO DOUBLE CHECK #####\n\n # Perform the clustering\n p_threshold = p_value # 0.001\n t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)\n\n print('Clustering... ')\n T_obs, clusters, cluster_p_values, H0 = spatio_temporal_cluster_1samp_test(X, connectivity=connectivity, n_jobs=1,\n threshold=t_threshold)\n\n # Pack the outputs into tuple\n clu = (T_obs, clusters, cluster_p_values, H0)\n\n # Select the clusters that are sig. at p < p_value (Note this value is multiple-comparisons corrected)\n good_cluster_inds = np.where(cluster_p_values < p_value)[0]\n return clu, good_cluster_inds\n\n\ndef perform_statistics_2(morphed_data, parameter_cache, vector, p_value=None):\n \"\"\"Performs the statistical analysis using spatial_tris_connectivity.\n\n :param morphed_data: Morphed data obtained from morph_data function\n :param parameter_cache: Morphed parameter cache obtained from morph_data function.\n :param vector: Method to perform modelling ('sLORETA' etc.)\n :param p_value: Statistical p-value\n :return: clu, good_cluster_inds\n \"\"\"\n # Unpack parameter cache dictionary\n n_subjects = parameter_cache['n_subjects']\n n_times = parameter_cache['n_times']\n\n # Take on the absolute\n X = np.abs(morphed_data)\n\n # Obtain the paired contrast\n if vector is False:\n X = X[:, :, :, 0] - X[:, :, :, 1] # Dimension is (space, time, subjects)\n else:\n X = X[:, :, :, :, 0] - X[:, :, :, :, 1] # Dimension is (space, vector, time, subjects)\n\n print('Computing connectivity... ')\n connectivity_2 = mne.spatio_temporal_tris_connectivity(grade_to_tris(5), n_times)\n\n # Note that X needs to be a multi-dimensional array of shape [samples (subjects) x time x space]\n if vector is False:\n X = np.transpose(X, [2, 1, 0])\n else:\n X = np.transpose(X, [3, 2, 1, 0]) ##### TO DOUBLE CHECK #####\n\n # Perform the clustering\n p_threshold = p_value # 0.001\n t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)\n\n print('Clustering... ')\n T_obs, clusters, cluster_p_values, H0 = spatio_temporal_cluster_1samp_test(X, connectivity=connectivity_2, n_jobs=1,\n threshold=t_threshold)\n\n # Pack the outputs into tuple\n clu = (T_obs, clusters, cluster_p_values, H0)\n\n # Select the clusters that are sig. at p < p_value (Note this value is multiple-comparisons corrected)\n good_cluster_inds = np.where(cluster_p_values < p_value)[0]\n return clu, good_cluster_inds","sub_path":"Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":11156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"24627513","text":"#!/usr/bin/python3\nimport Quandl ## Install Quandl direct in script folder\nimport pandas as pd\nimport os\nimport time\n\nauth_tok = open(\"Auth.txt\",\"r\").read() ## read the Token\n## Now get data directly from the site\n##data = Quandl.get(\"WIKI/KO\",trim_start = \"2000-12-12\",trim_end = \"2014-12-12\",authtoken=auth_tok)\n##print(data[\"Adj. Close\"])\n\npath = \"/home/vagner/Documents/acerta/intraQuarter\"\n### Get the data from the internet and store local\ndef Stock_Prices():\n df = pd.DataFrame()\n statspath = path + \"/_KeyStats\"\n stock_list = [x[0] for x in os.walk(statspath)]\n #print(stock_list)\n\n for each_dir in stock_list[1:]:\n try:\n ticker = each_dir.split(\"/\")[-1]\n print(ticker)\n name = \"WIKI/\"+ticker.upper()\n data = Quandl.get(name,\n trim_start=\"2000-12-12\",\n trim_end=\"2015-03-03\",\n authtoken=auth_tok)\n data[ticker.upper()] = data[\"Adj. Close\"]\n df = pd.concat([df, data[ticker.upper()]], axis = 1)\n except Exception as e:\n print(str(e))\n time.sleep(10) ## Stop for 10 seconds and try again\n try:\n ticker = each_dir.split(\"/\")[1]\n print(ticker)\n name = \"WIKI/\"+ticker.upper()\n data = Quandl.get(name,\n trim_start=\"2000-12-12\",\n trim_end=\"2015-03-03\",\n authtoken=auth_tok)\n data[ticker.upper()] = data[\"Adj. Close\"]\n df = pd.concat([df, data[ticker.upper()]], axis = 1)\n except Exception as e:\n print(str(e))\n\n df.to_csv(\"stock_prices.csv\")\n\nStock_Prices()","sub_path":"AI11.py","file_name":"AI11.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"629600816","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 23 23:00:47 2018\n\n@author: meganporter\n\"\"\"\n\n\"\"\"This is a boolean look at whether I should go hiking or not and whether I will draw in my \nnature journal or keep a photographic record. I won't go if it's below 45F or above 80F. I\nalso won't go if I don't have a ride or haven't reserved a rental car in time. \n\nI like to keep records of hikes. Either I take photos on my phone to print out at a drugstore\nor I bring my dedicated nature journal and draw with an archival pen. I'll rely on my phone\nif it is downpouring or windy. Wind causes too much disturbance and if the rain is too heavy\nmy phone will be in danger. However, it's works okay to protect my phone from drizzle with\nmy sleeve and dry pockets stuffed with knitted gloves.\"\"\"\n\n#Is it below 45 degrees F?\nbelow_45 = False\n#Is it above 80 degrees F?\nabove_80 = False\n#Is it sunny?\nsunny = False\n#Is it drizzling?\ndrizzling = True\n#Is it downpouring?\ndownpour = False\n#Is it windy?\nwindy = False\n#Do I have a ride?\nride = False\n#Have I reserved a rental car in time?\nrental = True\n\nyes_go = not(below_45 or above_80) and (ride or rental)\njournal = sunny and not (windy or downpour) and yes_go\nphone_photos = (sunny or drizzling) and not (downpour or journal) and yes_go\nprint(yes_go, journal, phone_photos)\n","sub_path":"ShouldIGoHiking.py","file_name":"ShouldIGoHiking.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615913464","text":"import ROOT\nROOT.gROOT.SetBatch(1)\nimport ctypes\n\ndef filldiff(up,down, diffgraph):\n n = up.GetN()\n i = 0\n xup = ctypes.c_double(-9.9)\n yup = ctypes.c_double(-9.9)\n xlo = ctypes.c_double(-9.9)\n ylo = ctypes.c_double(-9.9)\n while i threshold:\n goingUp = False\n crossings = crossings + 1\n else:\n if not goingUp and current_sample < threshold:\n goingUp = True\n crossings = crossings + 1\n \n # Calculate the beats per minute.\n time_to_get_samples = (1/fs) * signal.size\n \n return ((crossings/2) * 60) / time_to_get_samples\n\n def normalize_signal(self, signal):\n \n #find min of signal\n minimum = np.min(signal)\n \n #subtract the minimum so the minimum of the signal is zero\n signal = signal - minimum\n #find the new maximum of the signal\n maximum = np.max(signal)\n \n #divide the signal by the new maximum so the maximum becomes 1\n signal = signal / maximum\n \n return signal\n\n def linear_map(self, a1, a2, b1, b2, s):\n return b1 + (((s - a1) * (b2 - b1))/(a2 - a1))\n\n def save_to_file(self, data_array, file_name = \"foo.csv\"):\n np.savetxt(file_name, data_array, delimiter=\",\")\n\n def load_from_file(self, file_name):\n return np.genfromtxt(file_name, delimiter=',')","sub_path":"src/Python/Libraries/HR.py","file_name":"HR.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"562581183","text":"# :coding: utf-8\n# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips\n# :license: See LICENSE.txt.\n\nimport os\nimport operator\n\nimport pytest\n\nimport lucidity\n\n\nTEST_TEMPLATE_PATH = os.path.join(\n os.path.dirname(__file__), '..', 'fixture', 'template'\n)\n\nTEST_SCHEMA_ROOT = os.path.join(\n os.path.dirname(__file__), '..', 'fixture', 'schema'\n)\n\n@pytest.fixture\ndef templates():\n '''Return candidate templates.'''\n return [\n lucidity.Template('model', '/jobs/{job.code}/assets/model/{lod}'),\n lucidity.Template('rig', '/jobs/{job.code}/assets/rig/{rig_type}')\n ]\n\n\ndef test_schema():\n '''Valid initializing.'''\n schema = lucidity.Schema(templates())\n assert isinstance(schema, lucidity.Schema)\n\n\ndef test_schema_from_yaml_simple():\n '''Valid initializing from yaml without nesting'''\n schema = lucidity.Schema.from_yaml(os.path.join(TEST_SCHEMA_ROOT, 'schema_simple.yaml'))\n\n\n@pytest.mark.parametrize(('template_id', 'data', 'expected'), [\n ('optional1', # #1 (1/1 optionals)\n {'project': {'name': 'foobar'}, 'variation': 'evil'},\n 'foobar/art/var_evil/concept'),\n ('optional1', # #1 (0/1 optionals)\n {'project': {'name': 'foobar'}},\n 'foobar/art/concept'),\n ('optional2', # #2 (0/2 optionals)\n {'project': {'name': 'swag'}, 'asset': {'name': 'dude'}, 'version': 1912},\n 'swag/model/dude_v1912.mb'),\n ('optional2', # #2 (1/2 optionals)\n {'project': {'name': 'transformers'}, 'asset': {'name': 'lolly'}, 'version': 471, 'variation': 'blue'},\n 'transformers/model/lolly_blue_v0471.mb'),\n ('optional2', # #2 (2/2 optionals)\n {'project': {'name': 'foobar'}, 'asset': {'name': 'johny'}, 'date': '20150601', 'version': 5, 'variation': 'red'},\n 'foobar/model/johny_20150601_red_v0005.mb'),\n ], ids=[\n '#1 (1/1 optionals)',\n '#1 (0/1 optionals)',\n '#2 (0/2 optionals)',\n '#2 (1/2 optionals)',\n '#2 (2/2 optionals)'\n ])\ndef test_schema_from_yaml_optional(template_id, data, expected):\n '''Valid initializing from yaml'''\n schema = lucidity.Schema.from_yaml(os.path.join(TEST_SCHEMA_ROOT, 'schema_optional.yaml'))\n\n template = schema.get_template(template_id)\n path = template.format(data)\n assert path == expected\n\n\n@pytest.mark.parametrize(('template_id', 'data', 'expected'), [\n ('doc.notes',\n {'project': {'name': 'foobar'}},\n 'foobar/documents/notes'),\n ('doc.contracts',\n {'project': {'name': 'transformers'}},\n 'transformers/documents/contracts'),\n ('extensive',\n {'project': {'name': 'swag'}, 'code': 'abc'},\n 'abc/swag/documents/backup/swag/documents/contracts'),\n ('deepnest',\n {'project': {'name': 'a'}, 'code': 'b'},\n 'b/a/documents/backup/a/documents/contracts/a/documents/a/documents/notes'),\n ('nest',\n {'project': {'name': 'abc'}},\n 'abc/documents')\n ], ids=[\n 'doc.contracts (1 nested)',\n 'doc.notes (1 nested)',\n 'extensive (2 nested)',\n 'deepnest (3 nested, long)',\n 'nest (only 1 nest)'\n ])\ndef test_schema_from_yaml_referenced(template_id, data, expected):\n '''Valid initializing from yaml'''\n schema = lucidity.Schema.from_yaml(os.path.join(TEST_SCHEMA_ROOT, 'schema_referenced.yaml'))\n\n template = schema.get_template(template_id)\n path = template.format(data)\n assert path == expected","sub_path":"test/unit/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"493926392","text":"import imutils\nfrom keras.applications import imagenet_utils\n\n\ndef sliding_window(image, step, window):\n for y in range(0, image.shape[0] - window[1], step):\n for x in range(0, image.shape[1] - window[0], step):\n yield (x, y, image[y: y + window[1], x: x + window[0]])\n\n\ndef image_pyramid(image, scale=1.5, min_size=(224, 224)):\n yield image\n\n while True:\n # Compute the dimensions of the next image in the pyramid.\n w = int(image.shape[1] / scale)\n image = imutils.resize(image, width=w)\n\n # If the resized image does not meet the supplied minimum size, then stop the process.\n if image.shape[0] < min_size[1] or image.shape[1] < min_size[0]:\n break\n\n yield image\n\n\ndef classify_batch(model, batch_rois, batch_locations, labels, min_prob=0.5, top=10, dimension=(224, 224)):\n # Pass our batch ROIs through our network and decode the predictions\n predictions = model.predict(batch_rois)\n P = imagenet_utils.decode_predictions(predictions, top=top)\n\n for i in range(0, len(P)):\n for (_, label, prob) in P[i]:\n if prob > min_prob:\n (p_x, p_y) = batch_locations[i]\n box = (p_x, p_y, p_x + dimension[0], p_y + dimension[1])\n\n L = labels.get(label, [])\n L.append((box, prob))\n labels[label] = L\n\n return labels\n","sub_path":"utils/simple_object_detector.py","file_name":"simple_object_detector.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627626690","text":"\"\"\"Wrap a node along with its relative coordinates within its DOM.\"\"\"\nfrom typing import Any\n\nfrom yamlpath import YAMLPath\n\nclass NodeCoords:\n \"\"\"\n Initialize a new NodeCoords.\n\n A node's coordinates track these properties:\n 1. Reference-to-the-Node-Itself,\n 2. Immediate-Parent-Node-of-the-Node,\n 3. Index-or-Key-of-the-Node-Within-Its-Immediate-Parent\n \"\"\"\n\n def __init__(\n self, node: Any, parent: Any, parentref: Any, path: YAMLPath = None\n ) -> None:\n \"\"\"\n Initialize a new NodeCoords.\n\n Positional Parameters:\n 1. node (Any) Reference to the ruamel.yaml DOM data element\n 2. parent (Any) Reference to `node`'s immediate DOM parent\n 3. parentref (Any) The `list` index or `dict` key which indicates where\n within `parent` the `node` is located\n 4. path (YAMLPath) The YAML Path for this node, as reported by its\n creator process\n\n Returns: N/A\n\n Raises: N/A\n \"\"\"\n self.node = node\n self.parent = parent\n self.parentref = parentref\n self.path = path\n\n def __str__(self) -> str:\n \"\"\"Get a String representation of this object.\"\"\"\n return str(self.node)\n\n def __repr__(self) -> str:\n \"\"\"\n Generate an eval()-safe representation of this object.\n\n Assumes all of the ruamel.yaml components are similarly safe.\n \"\"\"\n return (\"{}('{}', '{}', '{}')\".format(\n self.__class__.__name__, self.node, self.parent,\n self.parentref))\n\n @staticmethod\n def unwrap_node_coords(data: Any) -> Any:\n \"\"\"\n Recursively strips all DOM tracking data off of a NodeCoords wrapper.\n\n Parameters:\n 1. data (Any) the source data to strip.\n\n Returns: (Any) the stripped data.\n \"\"\"\n if isinstance(data, NodeCoords):\n return NodeCoords.unwrap_node_coords(data.node)\n\n if isinstance(data, list):\n stripped_nodes = []\n for ele in data:\n stripped_nodes.append(NodeCoords.unwrap_node_coords(ele))\n return stripped_nodes\n\n return data\n","sub_path":"yamlpath/wrappers/nodecoords.py","file_name":"nodecoords.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"610875062","text":"# Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n\nfrom pyspark.sql import SparkSession\nimport os\n\ncontroller = os.getenv(\"PRAVEGA_CONTROLLER_URI\", \"tcp://127.0.0.1:9090\")\nscope = os.getenv(\"PRAVEGA_SCOPE\", \"examples\")\nallowCreateScope = os.getenv(\"PROJECT_NAME\") is None\ncheckPointLocation = os.getenv(\"CHECKPOINT_DIR\", \"/tmp/spark-checkpoints-stream_generated_data_to_pravega\")\n\nspark = (SparkSession\n .builder\n .getOrCreate()\n )\n\n(spark \n .readStream \n .format(\"rate\") \n .load() \n .selectExpr(\"cast(timestamp as string) as event\", \"cast(value as string) as routing_key\") \n .writeStream \n .trigger(processingTime=\"3 seconds\") \n .outputMode(\"append\") \n .format(\"pravega\") \n .option(\"allow_create_scope\", allowCreateScope)\n .option(\"controller\", controller)\n .option(\"scope\", scope) \n .option(\"stream\", \"streamprocessing1\") \n .option(\"checkpointLocation\", checkPointLocation)\n .start() \n .awaitTermination()\n )\n","sub_path":"spark-connector-examples/src/main/python/stream_generated_data_to_pravega.py","file_name":"stream_generated_data_to_pravega.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"4472147","text":"import datetime\nimport json\nimport logging\nimport uuid\n\nfrom flask import Flask, request, Response\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import joinedload\n\nfrom src.model.eeg_recording import EEGRecording\nfrom src.model.eeg_recording_label import EEGRecordingLabel\nfrom src.service.transfer_manager import TransferManager\nfrom src.service.base import connection_str\n\napp = Flask(__name__)\n\ntransfer_manager = TransferManager()\n\n\ndef api_error(message):\n return Response(json.dumps({'message': message}), status=500)\n\n\n@app.route('/api/record', methods=['POST'])\ndef upload_recording():\n \"\"\"\n accepts file uploads to server. maximum limit of the file imposed by postgresql is 1GB\n operation is transactional\n :return: success response after the succssful upload, internal server error after failure\n \"\"\"\n if 'file' not in request.files:\n return api_error('file required')\n\n file = request.files['file']\n\n if not file:\n return api_error('file is empty')\n\n recording = EEGRecording(recording_file=file.read(), filename=file.filename)\n\n try:\n transfer_manager.save(recording)\n print(str(recording.id))\n except:\n return api_error(\"couldn't save the file\")\n\n return Response(json.dumps(recording.as_dict()))\n\n\n@app.route('/api/record/', methods=['GET'])\ndef download_recording(recording_id):\n if not transfer_manager.find_recording(recording_id):\n return api_error(f'file with id {recording_id} was not found')\n\n recording: EEGRecording = transfer_manager.session \\\n .query(EEGRecording) \\\n .filter(EEGRecording.id == uuid.UUID(recording_id)) \\\n .first()\n\n return api_error(f'file {recording_id} could not be found') if recording is None \\\n else Response(recording.recording_file, headers={\"Content-disposition\": \"attachment; filename=\" + recording.filename})\n\n\n@app.route('/api/label/', methods=['POST'])\ndef mark_metadata(recording_id):\n if not transfer_manager.find_recording(recording_id):\n return api_error(f'file with id {recording_id} was not found')\n\n content = request.json\n\n recording_uuid = uuid.UUID(recording_id)\n\n metadata = EEGRecordingLabel(int(content['subject_id']),\n int(content['paradigm_id']),\n datetime.datetime.now(),\n str(content['comment']),\n str(content['recorded_by']),\n bool(content['with_feedback']),\n recording_uuid)\n\n transfer_manager.session.query(EEGRecordingLabel) \\\n .filter(EEGRecordingLabel.recording == recording_uuid) \\\n .delete()\n\n transfer_manager.session.add(metadata)\n transfer_manager.session.commit()\n\n transfer_manager.session.refresh(metadata)\n print(str(content))\n\n return json.dumps({'uuid': recording_id})\n\n\n@app.route('/api/recordings', methods=['GET'])\ndef find_recordings():\n query = transfer_manager.build_query(subject_id=request.args.get('subject_id'),\n paradigm_id=request.args.get('paradigm_id'),\n recorded_by=request.args.get('recorded_by'))\n\n try:\n result = query.all()\n return Response(json.dumps([row.as_dict() for row in result]), mimetype='application/json')\n except:\n logging.exception('')\n\n return api_error('failed to retrieve recordings')\n\n\n@app.route('/api/verify', methods=['GET'])\ndef verify_connection():\n verify_engine = create_engine(connection_str)\n engine_connection = verify_engine.connect()\n\n\n # List all tables\n tables = verify_engine.table_names()\n engine_connection.close()\n\n return Response(json.dumps({'tables': tables}), mimetype='application/json')\n\n\ndef main(args=None):\n bind_to = {'hostname': \"0.0.0.0\", 'port': 9888}\n app.run(port=9888, host='0.0.0.0', debug=True)\n\n\nif __name__ == '__main__':\n main(['-h'])\n","sub_path":"cybathlon-recordings-server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"293963453","text":"\"\"\"empty message\n\nRevision ID: e12a9d8f1ef2\nRevises: 1da382943019\nCreate Date: 2019-03-17 22:58:06.830512\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e12a9d8f1ef2'\ndown_revision = '1da382943019'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('like', 'recipe_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n op.alter_column('like', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('like', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.alter_column('like', 'recipe_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e12a9d8f1ef2_.py","file_name":"e12a9d8f1ef2_.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537176072","text":"from setuptools import setup, find_packages\nimport os\nimport re\n\nPACKAGE=\"django-wfs\"\n\nMYDIR = os.path.dirname(__file__)\n\ndef read_version():\n fn = os.path.join(os.path.join(MYDIR,\"debian-unix\"),\"changelog\")\n with open(fn) as fd:\n line = fd.readline() \n version,n = re.subn('^'+PACKAGE+'\\\\s*\\\\(([^-]*)-[^)]\\\\).*\\n','\\\\1',line)\n if n != 1:\n raise SyntaxError(\"debian changelog line [%s] is malformatted\"%line.substring[:-1])\n return version\n\nsetup(\n name=PACKAGE,\n packages=find_packages(),\n include_package_data=True,\n package_dir={'wfs': 'wfs'},\n version=read_version(),\n install_requires = ['sqlparse>=0.2.2'],\n description='A WFS (web feature service) implementation as a Django application.',\n author='Vasco Pinho',\n author_email='vascogpinho@gmail.com',\n url='https://github.com/vascop/django-wfs',\n download_url='https://github.com/vascop/django-wfs/tarball/master',\n long_description=open('README.md', 'r').read(),\n license='Apache 2.0',\n keywords=['wfs', 'geo', 'django'],\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167530416","text":"\"\"\"Trains a simple convnet on the MNIST dataset.\nGets to 99.25% test accuracy after 12 epochs\n(there is still a lot of margin for parameter tuning).\n16 seconds per epoch on a GRID K520 GPU.\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\n# batch_size 每个批次跑的样本数量,样本太小会导致训练慢,过拟合。太大会导致欠拟合,如果样本数量是60000,那么一个\n# 迭代跑的批次就是60000/128\nbatch_size = 256\n\n# 0-9手写数字一个有10个类别\nnum_classes = 10\n\n# 12次完整迭代\nepochs = 2\n\n# 输入图像的大小\nimg_rows, img_cols = 28, 28\n\n# 导入数据\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# 数据有的是颜色通道数在前,有的是在后\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\n# 数据变成浮点更精确\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\n# 数据正则化\nx_train /= 255\nx_test /= 255\n\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# 把数字0-9的类别变成二进制,方便训练\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n# 构建模型\nmodel = Sequential()\n\n# 添加第一个2D卷积层,32个滤波器,滤波器/卷积核大小为3X3\n# 激活函数选用relu\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\n\n# 添加第二个2D积卷层,64个滤波器,滤波器/卷积核大小为3X3\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\n\n# 添加第一个池化层/采样层,用MaxPolling函数,采样大小为2X2\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# 对池化层/采样层,采用0.25的比例的丢弃率\nmodel.add(Dropout(0.25))\n\n# 展平层,展平所有像素,从[28*28]->[748]\nmodel.add(Flatten())\n\n# 添加第一个全连接层,128个神经元(也就是输出为128个),激活函数使用relu\nmodel.add(Dense(128, activation='relu'))\n\n# 对全连接层,采用0.5的比例的丢弃率\nmodel.add(Dropout(0.5))\n\n# 添加第二个全连接层,10个神经元(也就是输出为10个),激活函数使用softmax\nmodel.add(Dense(num_classes, activation='softmax'))\n\n# 编译模型,使用的损失函数为cross entropy,使用的梯度下降算法为Ada delta\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\ntbCallBack = keras.callbacks.TensorBoard(log_dir='./Graph2', histogram_freq=0, write_graph=True, write_images=True)\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n# 开始培训/优化模型,设置跑12次迭代, 每个迭代跑128个样本\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test),\n callbacks=[tbCallBack])\n\n# 用测试数据看看预测的精度是多少?\nscore = model.evaluate(x_test, y_test, verbose=0)\n\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","sub_path":"src/keras/mnist_cnn_solution.py","file_name":"mnist_cnn_solution.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"425931098","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport argparse\n\nfrom WPBackupTool import WPBackupTool\nfrom WPBackupTool.Library.Config import Config\nfrom WPBackupTool.Utils import Logger\n\n\ndef main():\n # parse args\n parser = argparse.ArgumentParser(description='Create a backup of your wordpress site!')\n parser.add_argument('--config', required=True, type=str, help='Path to the json-config-file')\n parser.add_argument('--skip_db', action='store_true', help='Skip db-backup?')\n parser.add_argument('--skip_ftp', action='store_true', help='Skip ftp-backup?')\n parser.add_argument('--multithreading', action='store_true', help='Do all Backups in parrallel?')\n parser.add_argument('--logging', action='store_true', help='Write logs?')\n\n args = parser.parse_args()\n\n config_file = args.config\n\n config = Config.from_config_file(config_file)\n\n Logger.LOGGING = args.logging\n\n wordpressBackup = WPBackupTool(config, args.skip_db, args.skip_ftp, args.multithreading)\n\n wordpressBackup.start_job()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DoWordpressBackup.py","file_name":"DoWordpressBackup.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"644668245","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\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: E:\\Programmer\\PYTHON\\cqrcode\\app\\make_qrcode\\alpha2bit.py\n# Compiled at: 2020-04-07 07:47:23\n# Size of source mod 2**32: 2606 bytes\n__doc__ = '\\n@File : alpha2bit.py\\n@Author : jiaming\\n@Modify Time: 2020/4/2 20:28\\n@Contact : https://blog.csdn.net/weixin_39541632\\n@Version : 1.0\\n@Desciption : 集合了字符编码解码函数调用\\n 只能对于 Alphanumeric_mode_table 中的字符进行编码\\n'\nfrom cqrcode.static._static_data import number_of_bits_in_character_count, alphanumeric_mode_table, version_bit_length\nimport random\n\ndef data_encode(alpha='', version_bit=''):\n \"\"\"\n 对传入原生字符串进行检查并编码为一份标准填充比特流。\n :param alpha: Alphanumeric_mode_table 表中的字符\n :return: 原生字符对应的填充比特流\n \"\"\"\n if len(version_bit) > version_bit_length:\n raise RuntimeError('版本号比特长度错误!')\n alpha = alpha.upper()\n alpha_group = ''\n results = ''\n for i in range(0, len(alpha) - 1, 2):\n alpha_group += alpha[i] + alpha[(i + 1)] + ' '\n number = alphanumeric_mode_table[alpha[i]] * 45 + alphanumeric_mode_table[alpha[(i + 1)]]\n bits = ''.join(list(bin(number))[2:])\n if len(bits) < 11:\n bits = '0' * (11 - len(bits)) + bits\n results += bits + ' '\n\n if len(alpha) % 2 != 0:\n alpha_group += alpha[(-1)]\n number = alphanumeric_mode_table[alpha[(-1)]]\n bits = ''.join(list(bin(number))[2:])\n if len(bits) < 6:\n bits = '0' * (6 - len(bits)) + bits\n results += bits + ' '\n number_of_bits = ''.join(list(bin(len(alpha)))[2:])\n if len(number_of_bits) < number_of_bits_in_character_count:\n number_of_bits = '0' * (number_of_bits_in_character_count - len(number_of_bits)) + number_of_bits\n print('消除空格前编码后数据: ', version_bit + ' ' + number_of_bits + ' ' + results + '0000')\n data_bits = (version_bit + ' ' + number_of_bits + ' ' + results + '0000').replace(' ', '')\n print('消除空格后编码后数据: ', data_bits)\n return data_bits\n\n\ndef random_bit(length=-1):\n \"\"\"\n 返回 length 长度的比特流\n :param length:\n :return:\n \"\"\"\n return ''.join([random.choice(['1', '0']) for i in range(length)])\n\n\nif __name__ == '__main__':\n print(random_bit(10))","sub_path":"pycfiles/cqrs-1.1.0.tar/alpha2bit.cpython-35.py","file_name":"alpha2bit.cpython-35.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"637149684","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom collections import deque\nclass Solution:\n def findTarget(self, root: TreeNode, k: int) -> bool:\n treeSum = 0\n nums = set()\n queue =deque()\n queue.append(root)\n while queue:\n node = queue.popleft()\n if k - node.val in nums:\n return True\n else:\n nums.add(node.val)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return False ","sub_path":"bfs/easy/twoSumBST.py","file_name":"twoSumBST.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"207907947","text":"from collections import OrderedDict\nfrom .file import FilenameHandler\n\ndef get_files_contents(session):\n \"\"\" Generator that returns file contents from session info. \"\"\"\n for fileinfo in session['files']:\n file_handler = FilenameHandler(**fileinfo)\n filename = file_handler.get_full_path()\n with open(filename, 'r', encoding='utf-8') as f:\n buf = f.read()\n yield file_handler, buf\n\ndef save_in_session(session, info):\n if not 'files' in session:\n session['files'] = []\n session['files'].append(info)\n session.modified = True\n","sub_path":"default/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"256576636","text":"import os\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom IPython.core.debugger import Tracer\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport copy\nfrom torch.autograd import grad\nimport time\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport copy\nimport matplotlib\nimport operator\n\nfrom BNN_Util import *\nfrom BNN_Q_D import *\nfrom BNN_Model_def import *\nfrom BNN_Sampler import *\nfrom BNN_training_func import *\nfrom BNN_Dataloader import *\n\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\ntotal_run=10\nrandom_seed=[15,25,35,40,45,50,55,60,65,70]\n\n\n\ntrain_loader = datasets.MNIST('./BNN_MNIST/data/', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\ntest_loader = datasets.MNIST('./BNN_MNIST/data/', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n\ntrain_X,train_Y,test_X,test_Y=SelectImage_All(train_loader,test_loader)\ntrain_class=NewMNISTLoader(train_X,train_Y,flag_train=True)\ntest_class=NewMNISTLoader(test_X,test_Y,flag_train=False)\n\ntrain_loader=DataLoader(train_class, batch_size=500,\n shuffle=True)\ntest_loader=DataLoader(test_class,batch_size=500,shuffle=True)\n\n\n\n# #############################################################################################################################\n##### Set which sampler to run #######\nflag_nnsghmc=True\nflag_SGLD=False\n\n\nif flag_nnsghmc==True:\n print('NNSGHMC')\nelif flag_SGLD==True:\n print('SGLD')\nelse:\n print('SGHMC')\nif flag_nnsghmc==False:\n \n\n for total_idx in range(total_run):\n print('Current total:%s'%(total_idx+1))\n torch.manual_seed(random_seed[total_idx])\n\n num_chain=20\n MLP_mnist=BNN(dim=784,hidden=40,layer_num=3,dim_out=10)\n total_dim=MLP_mnist.get_total_dim()\n data_N=60000.\n C=50\n B=0.\n\n SGHMC_obj=SGHMC(total_dim,MLP_mnist)\n A=Variable(torch.Tensor([1.1]))\n\n weight_init=Variable(0.01*torch.randn(num_chain,total_dim),requires_grad=True)\n if flag_SGLD==True:\n eps=0.2/data_N\n else:\n eps=0.01/data_N # this is the learning rate, in original paper this = eps_true**2=gamma/data_N (gamma is the per sampler lr)\n if flag_SGLD==False:\n alpha=0.01 # this is eps_true*C \n else:\n alpha=1.\n \n total_step=100\n sigma=1.\n\n state_mom_init=Variable(0*torch.randn(num_chain,total_dim),requires_grad=True)\n st=time.time()\n if flag_SGLD==True:\n state_list_SGLD,_,energy_list,time_list_SGLD=SGHMC_obj.parallel_sample(weight_init,state_mom_init,train_loader,data_N,num_chain=num_chain,eps=eps,alpha=alpha,beta=0,sigma=sigma,interval=100,mom_resample=100000,total_step=total_step,flag_SGLD=True,test_loader=test_loader)\n else:\n state_list_sghmc,_,energy_list,time_list_sghmc=SGHMC_obj.parallel_sample(weight_init,state_mom_init,train_loader,data_N,num_chain=num_chain,eps=eps,alpha=alpha,beta=0,sigma=sigma,interval=100,mom_resample=100000,total_step=total_step,flag_SGLD=False,test_loader=test_loader)\n ed=time.time()-st\n # Store the samples\n if flag_SGLD==True:\n tensor_state_list_sgld=torch.stack(tuple(state_list_SGLD),dim=0)\n torch.save(tensor_state_list_sgld,'./ReLU_Generalization_Long_Run/Test_long_run_sgld_%s_0.2'%(total_idx+1))\n\n draw_list_SGLD=draw_samples(state_list_SGLD,burn_in=0,interval=1,draw_method='Cross')\n Acc,NLL=Test_accuracy(test_loader,MLP_mnist,draw_list_SGLD[-1],data_number=10000.)\n Result=np.concatenate(([Acc],[NLL.cpu().data.numpy()],[ed]))\n np.savetxt('./ReLU_Generalization_Long_Run/Test_long_run_sgld_%s_0.2'%(total_idx+1),Result)\n else:\n tensor_state_list_sghmc=torch.stack(tuple(state_list_sghmc),dim=0)\n torch.save(tensor_state_list_sghmc,'./ReLU_Generalization_Long_Run/Test_long_run_sghmc_%s'%(total_idx+1))\n\n draw_list_sghmc=draw_samples(state_list_sghmc,burn_in=0,interval=1,draw_method='Cross')\n Acc,NLL=Test_accuracy(test_loader,MLP_mnist,draw_list_sghmc[-1],data_number=10000.)\n Result=np.concatenate(([Acc],[NLL.cpu().data.numpy()],[ed]))\n np.savetxt('./ReLU_Generalization_Long_Run/Test_long_run_sghmc_%s_result'%(total_idx+1),Result)\nelse:\n for total_idx in range(total_run):\n \n print('Current total:%s'%(total_idx+1))\n \n torch.manual_seed(random_seed[total_idx])\n \n num_chain=20\n MLP_mnist=BNN(dim=784,hidden=40,layer_num=3,dim_out=10)\n Q_MLP=MLP(input_dim=2,hidden=10,out_size=1)\n D_MLP=Positive_MLP(input_dim=3,hidden=10,out_size=1)\n \n \n # load the trained sampler \n Q_MLP.load_state_dict(torch.load('./Q_state_batch_500_baseline_50D_70G_step_0.007_40ep_broad_0.2'))\n D_MLP.load_state_dict(torch.load('./D_state_batch_500_baseline_50D_70G_step_0.007_40ep_broad_0.2'))\n \n total_dim=MLP_mnist.get_total_dim()\n data_N=60000.\n #Tracer()()\n B=Variable(torch.Tensor([0]))\n Q=parallel_Q_eff(total_dim,Q_MLP,MLP_mnist,num_chain,clamp=5,dim_pen=1.,dim_pen_p=1,sqrt=False)\n D=parallel_D_eff(total_dim,D_MLP,MLP_mnist,num_chain,clamp_min=0,clamp_max=1000,dim_pen=1.,dim_pen_p=1,dim_pen_g=1,sqrt=False)\n Gamma=parallel_Gamma_eff(total_dim,Q_NN=Q_MLP,D_NN=D_MLP)\n\n\n NNSGHMC_obj=NN_SGHMC(total_dim,MLP_mnist,D,Q,Gamma)\n\n\n eps=float(np.sqrt(0.0085/data_N))\n eps2=float(np.sqrt(0.018/data_N))\n sigma=1.\n const_Q=0.\n const_D=float(0.01/eps)\n\n coef=15910./total_dim\n\n total_step=100\n\n\n weight_init=Variable(0.01*torch.randn(num_chain,total_dim),requires_grad=True)\n\n state_mom_init=Variable(0*torch.randn(num_chain,total_dim),requires_grad=True)\n\n\n st=time.time()\n \n ##### This is to run meta without finite difference ######\n# state_list_nnsghmc,state_mom_list,energy_list,_,_,A_list,time_list_nnsghmc=NNSGHMC_obj.parallel_sample(weight_init,\n# state_mom_init,B,train_loader,coef=coef,num_chain=num_chain,data_N=data_N,sigma=sigma,\n# total_step=total_step,limit_step=100,eps=eps,eps2=eps2,TBPTT_step=10,sample_interval=100,mom_resample=2000000,mom_scale=1.,mode_train=False,const_Q=const_Q,const_D=const_D,flag_finite=False,test_loader=test_loader)\n################ Finite difference \n state_list_nnsghmc,time_list_nnsghmc=NNSGHMC_obj.parallel_sample_FD(weight_init,state_mom_init,B,train_loader,data_N=data_N,sigma=sigma,num_chain=num_chain,total_step=total_step,eps=eps,eps2=eps2,coef=coef,sample_interval=100,const_Q=const_Q,const_D=const_D,test_loader=test_loader)\n ed=time.time()-st\n \n tensor_state_list_nnsghmc=torch.stack(tuple(state_list_nnsghmc),dim=0)\n torch.save(tensor_state_list_nnsghmc,'./ReLU_Generalization_Long_Run/Test_long_run_nnsghmc_%s_fd_0.18'%(total_idx+1))\n\n draw_list_nnsghmc=draw_samples(state_list_nnsghmc,burn_in=0,interval=1,draw_method='Cross')\n Acc,NLL=Test_accuracy(test_loader,MLP_mnist,draw_list_nnsghmc[-1],data_number=10000.)\n Result=np.concatenate(([Acc],[NLL.cpu().data.numpy()],[ed]))\n np.savetxt('./ReLU_Generalization_Long_Run/Test_long_run_nnsghmc_%s_result_fd_0.018'%(total_idx+1),Result)\n \n\n \n\n ","sub_path":"BNN_MNIST/NetworkTopologyGeneralization.py","file_name":"NetworkTopologyGeneralization.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"152296101","text":"class Solution:\n def findMinHeightTrees(self, n, edges):\n if n == 1: return [0]\n adj = [set() for _ in range(n)]\n for i, j in edges:\n adj[i].add(j)\n adj[j].add(i)\n\n leaves = [i for i in range(n) if len(adj[i]) == 1]\n\n while n > 2:\n n -= len(leaves)\n newLeaves = []\n for i in leaves:\n j = adj[i].pop()\n adj[j].remove(i)\n if len(adj[j]) == 1: newLeaves.append(j)\n leaves = newLeaves\n return leaves\n\n\nif __name__ == '__main__':\n s = Solution()\n n = 6\n edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]\n print(s.findMinHeightTrees(n, edges=edges))\n","sub_path":"0310-Minimum Height Trees.py","file_name":"0310-Minimum Height Trees.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"43435869","text":"# (c) Copyright 2014-2016 Hewlett-Packard Development Company, L.P.\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 logging\n\nfrom cliff import command\nfrom cliff import lister\nfrom cliff import show\n\nfrom freezerclient import exceptions\nfrom freezerclient import utils\n\n\nlogging = logging.getLogger(__name__)\n\n\nclass ActionShow(show.ShowOne):\n \"\"\"Show a single action \"\"\"\n def get_parser(self, prog_name):\n parser = super(ActionShow, self).get_parser(prog_name)\n parser.add_argument(dest='action_id',\n help='ID of the action')\n return parser\n\n def take_action(self, parsed_args):\n action = self.app.client.actions.get(parsed_args.action_id)\n\n if not action:\n raise exceptions.ApiClientException('Action not found')\n\n column = (\n 'Action ID',\n 'Name',\n 'Action',\n 'Mode',\n 'Path to Backup or Restore',\n 'Storage',\n 'Snapshot'\n )\n\n data = (\n action.get('action_id'),\n action.get('freezer_action', {}).get('backup_name', ''),\n action.get('freezer_action', {}).get('action', 'backup'),\n action.get('freezer_action', {}).get('mode', 'fs'),\n action.get('freezer_action', {}).get('path_to_backup', ''),\n action.get('freezer_action', {}).get('storage', 'swift'),\n action.get('freezer_action', {}).get('snapshot', 'False'),\n )\n\n return column, data\n\n\nclass ActionList(lister.Lister):\n \"\"\"List all actions for your user\"\"\"\n def get_parser(self, prog_name):\n parser = super(ActionList, self).get_parser(prog_name)\n\n parser.add_argument(\n '--limit',\n dest='limit',\n default=100,\n help='Specify a limit for search query',\n )\n\n parser.add_argument(\n '--offset',\n dest='offset',\n default=0,\n help='',\n )\n\n parser.add_argument(\n '--search',\n dest='search',\n default='',\n help='Define a filter for the query',\n )\n return parser\n\n def take_action(self, parsed_args):\n search = utils.prepare_search(parsed_args.search)\n\n actions = self.app.client.actions.list(\n limit=parsed_args.limit,\n offset=parsed_args.offset,\n search=search\n )\n\n columns = ('Action ID', 'Name', 'Action',\n 'Path to Backup or Restore', 'Mode', 'Storage', 'snapshot')\n\n # Print empty table if no actions found\n if not actions:\n actions = [{}]\n data = ((action.get('action-id', ''),\n action.get('freezer_action', {}).get('backup_name', ''),\n action.get('freezer_action', {}).get('action', ''),\n action.get('freezer_action', {}).get(\n 'path_to_backup', ''),\n action.get('freezer_action', {}).get('mode', ''),\n action.get('freezer_action', {}).get('storage', ''),\n action.get('freezer_action', {}).get('snapshot', '')\n ) for action in actions)\n else:\n data = ((action.get('action_id'),\n action.get('freezer_action', {}).get('backup_name', ''),\n action.get('freezer_action', {}).get('action', 'backup'),\n action.get('freezer_action', {}).get(\n 'path_to_backup', ''),\n action.get('freezer_action', {}).get('mode', 'fs'),\n action.get('freezer_action', {}).get('storage', 'swift'),\n action.get('freezer_action', {}).get('snapshot', 'False')\n ) for action in actions)\n\n return columns, data\n\n\nclass ActionDelete(command.Command):\n \"\"\"Delete an action from the api\"\"\"\n def get_parser(self, prog_name):\n parser = super(ActionDelete, self).get_parser(prog_name)\n parser.add_argument(dest='action_id',\n help='ID of the action')\n return parser\n\n def take_action(self, parsed_args):\n self.app.client.actions.delete(parsed_args.action_id)\n logging.info('Action {0} deleted'.format(parsed_args.action_id))\n\n\nclass ActionCreate(command.Command):\n \"\"\"Create an action from a file\"\"\"\n def get_parser(self, prog_name):\n parser = super(ActionCreate, self).get_parser(prog_name)\n parser.add_argument('--file',\n dest='file',\n required=True,\n help='Path to json file with the action')\n return parser\n\n def take_action(self, parsed_args):\n action = utils.doc_from_json_file(parsed_args.file)\n action_id = self.app.client.actions.create(action)\n logging.info('Action {0} created'.format(action_id))\n\n\nclass ActionUpdate(command.Command):\n \"\"\"Update an action from a file\"\"\"\n def get_parser(self, prog_name):\n parser = super(ActionUpdate, self).get_parser(prog_name)\n parser.add_argument(dest='action_id',\n help='ID of the session')\n\n parser.add_argument(dest='file',\n help='Path to json file with the action')\n return parser\n\n def take_action(self, parsed_args):\n action = utils.doc_from_json_file(parsed_args.file)\n self.app.client.actions.update(parsed_args.action_id, action)\n logging.info('Action {0} updated'.format(parsed_args.action_id))\n","sub_path":"python-freezerclient-1.3.1/freezerclient/v1/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"407519558","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCBSD CLASS OBJECT FILE\n\"\"\"\n\nclass CBSD:\n\t\"\"\"\n\tGrant - Array of DeregistrationResponsedata objects.\n\t\tEach DeregistrationResponse data object represents a deregistrationresponse to a deregistration request of a CBSD\n\t\n\tAttributes\n\t----------\n\tcbsdId : string (conditional)\n\t\tThis parameter is included if and only if the cbsdId parameter in the DeregistrationRequestobject contains a valid CBSD identity.\n\t\tIf included, the SAS shall set this parameterto the value of the cbsdIdparameter in the corresponding DeregistrationRequest object.\n\tresponse : object Response (required)\n\t\tThis parameter includes information on whether the corresponding CBSD request is approved or disapproved for a reason. See Table 14: ResponseObject Definition\n\t\"\"\"\n\tdef __init__(self, id, trustLevel, fccId, name=None, longitude=None, latitude=None, IPAddress=None, \\\n\t\tminFreq=None, maxFreq=None, minSR=None, maxSR=None, type=None, mobility=False, status=None, \\\n\t\t\t comment=None, cbsdSerialNumber=None, callSign=None, cbsdCategory=\"A\", cbsdInfo=\"\", airInterface=None, \\\n\t\t\t\tinstallationParam=None, measCapability=None, groupingParam=None, fullyTrusted=False):\n\t\tself.id = id\n\t\tself.name = name\n\t\tself.latitude = latitude\n\t\tself.longitude = longitude\n\t\tself.trustLevel = trustLevel\n\t\tself.longitude = longitude\n\t\tself.latitude = latitude\n\t\tself.trustLevel = trustLevel\n\t\tself.IPAddress = IPAddress\n\t\tself.minFrequency = minFreq\n\t\tself.maxFrequency = maxFreq\n\t\tself.minSampleRate = minSR\n\t\tself.maxSampleRate = maxSR\n\t\tself.nodeType = type\n\t\tself.mobility = mobility\n\t\tself.status = status\n\t\tself.comment = comment\n\t\tself.fccId = fccId\n\t\tself.cbsdSerialNumber = cbsdSerialNumber\n\t\tself.callSign = callSign\n\t\tself.cbsdCategroy = cbsdCategory\n\t\tself.cbsdInfo = cbsdInfo\n\t\tself.airInterface = airInterface\n\t\tself.installationParam = installationParam\n\t\tself.measCapability = measCapability\n\t\tself.groupingParam = groupingParam\n\t\tself.fullyTrusted = fullyTrusted\n\n\tdef asdict(self):\n\t\treturn_dict = {}\n\t\tif(self.id):\n\t\t\treturn_dict[\"id\"] = self.id\n\t\tif(self.name):\n\t\t\treturn_dict[\"name\"] = self.name\n\t\tif(self.latitude):\n\t\t\treturn_dict[\"latitude\"] = self.latitude\n\t\tif(self.longitude):\n\t\t\treturn_dict[\"longitude\"] = self.longitude\n\t\tif(self.trustLevel):\n\t\t\treturn_dict[\"trustLevel\"] = self.trustLevel\n\t\tif(self.longitude):\n\t\t\treturn_dict[\"longitude\"] = self.longitude\n\t\tif(self.latitude):\n\t\t\treturn_dict[\"latitude\"] = self.latitude\n\t\tif(self.trustLevel):\n\t\t\treturn_dict[\"trustLevel\"] = self.trustLevel\n\t\tif(self.IPAddress):\n\t\t\treturn_dict[\"IPAddress\"] = self.IPAddress\n\t\tif(self.minFrequency):\n\t\t\treturn_dict[\"minFrequency\"] = self.minFrequency\n\t\tif(self.maxFrequency):\n\t\t\treturn_dict[\"maxFrequency\"] = self.maxFrequency\n\t\tif(self.minSampleRate):\n\t\t\treturn_dict[\"minSampleRate\"] = self.minSampleRate\n\t\tif(self.maxSampleRate):\n\t\t\treturn_dict[\"maxSampleRate\"] = self.maxSampleRate\n\t\tif(self.nodeType):\n\t\t\treturn_dict[\"nodeType\"] = self.nodeType\n\t\tif(self.mobility):\n\t\t\treturn_dict[\"mobility\"] = self.mobility\n\t\tif(self.status):\n\t\t\treturn_dict[\"status\"] = self.status\n\t\tif(self.comment):\n\t\t\treturn_dict[\"comment\"] = self.comment\n\t\tif(self.fccId):\n\t\t\treturn_dict[\"fccId\"] = self.fccId\n\t\tif(self.cbsdSerialNumber):\n\t\t\treturn_dict[\"cbsdSerialNumber\"] = self.cbsdSerialNumber\n\t\tif(self.callSign):\n\t\t\treturn_dict[\"callSign\"] = self.callSign\n\t\tif(self.cbsdCategroy):\n\t\t\treturn_dict[\"cbsdCategroy\"] = self.cbsdCategroy\n\t\tif(self.cbsdInfo):\n\t\t\treturn_dict[\"cbsdInfo\"] = self.cbsdInfo\n\t\tif(self.airInterface):\n\t\t\treturn_dict[\"airInterface\"] = self.airInterface\n\t\tif(self.installationParam):\n\t\t\treturn_dict[\"installationParam\"] = self.installationParam\n\t\tif(self.measCapability):\n\t\t\treturn_dict[\"measCapability\"] = self.measCapability\n\t\tif(self.groupingParam):\n\t\t\treturn_dict[\"groupingParam\"] = self.groupingParam\n\t\tif(self.fullyTrusted):\n\t\t\treturn_dict[\"fullyTrusted\"] = self.fullyTrusted\n\t\treturn return_dict","sub_path":"Core/CBSD.py","file_name":"CBSD.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"186292351","text":"import sys\nimport os\nimport json\nsys.path.append(\"..\") # comment out if importing from pip module\n\nimport dash\nfrom finishline import FinishLine\nimport dash_html_components as html\nimport dash_core_components as dcc\n\napp = dash.Dash(suppress_callback_exceptions=True)\napp.config.suppress_callback_exceptions = True\napp.scripts.config.serve_locally = True\napp.title = \"Dash FinishLine\"\nserver = app.server\ndata = {}\n\nfrom plugins.callbacks import finalize1\n\n\ndef generate_layout(**kwargs):\n story_id = kwargs.get(\"path_name\")\n if not story_id:\n return html.Div(\n [dcc.Location(id=\"url\", refresh=False), html.Div(id=\"page-content\")]\n )\n fl = FinishLine(app=app, data=data, debug=False, debug_path=None, name=story_id)\n # fl.load_plugins()\n\n json_path = story_id.replace(\"/\",\"\") + \"-v2.json\"\n layouts = {}\n children = []\n page_header = []\n\n try:\n if os.path.isfile(json_path):\n with open(json_path, \"r\") as openfile:\n obj = json.load(openfile)\n children = obj[\"grid-layout-children\"]\n layouts = obj[\"grid-layout\"]\n page_header = obj[\"filters\"]\n except:\n pass\n\n layouts = fl.generate_layout(layouts=layouts)\n layouts.children[1].children = children\n if page_header:\n layouts.children[0].children = page_header\n\n\n\n return layouts\n# Update the index\n@app.callback(\n dash.dependencies.Output(\"page-content\", \"children\"),\n [dash.dependencies.Input(\"url\", \"pathname\")],\n)\ndef display_page(pathname):\n if pathname != \"/\":\n return generate_layout(path_name=pathname)\n else:\n return \"Welcome, Please add /{datasourceID} to url\"\n # You could also return a 404 \"URL not found\" page here\n\napp.layout = generate_layout\nfinalize1(app, data, None)\n\n\nif __name__ == \"__main__\":\n app.run_server(debug=True, port=5000, host=\"0.0.0.0\")\n","sub_path":"example/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"97013910","text":"import pytest\r\nimport yaml\r\n\r\nfrom Calculator import Calculator\r\n\r\n\"\"\"\r\n类里面的(setup/teardown)运行在调用方法的前后,setup_method/teardown_method的简写\r\n方法级(setup_method/teardown_method)运行在调用方法的前后\r\n类级(setup_class/teardown_class) 只在类中前后运行一次\r\n函数级(setup_function/teardown_function) 只对函数用例生效(不在类中)\r\n模块级(setup_module/teardown_module) 模块始末,全局的(优先最高)\r\n\"\"\"\r\n\r\ndef get_datas(name,type='int'):\r\n with open(\"./datas/calc.yaml\") as f:\r\n # safe_load 将 yaml 数据流转换为 python 对象\r\n # safe_dump 将 python 对象转换为 yaml 数据流\r\n all_datas=yaml.safe_load(f)\r\n datas = all_datas[name][type][\"datas\"]\r\n ids = all_datas[name][type][\"ids\"]\r\n return (datas,ids)\r\n\r\nclass TestCalc:\r\n # 变量后加:类型提示作用\r\n # datas:list = get_datas()\r\n add_int_data = get_datas(\"add\",\"int\")\r\n add_float_data = get_datas(\"add\", \"float\")\r\n div_int_data = get_datas(\"div\",\"int\")\r\n div_zero_data = get_datas(\"div\", \"zero\")\r\n\r\n # 前置条件\r\n def setup(self):\r\n print(\"开始计算\")\r\n # 实例变量\r\n self.calc = Calculator()\r\n\r\n def teardown(self):\r\n print(\"结束计算\")\r\n\r\n @pytest.mark.add_normal\r\n # 参数化每一条用例是独立的,某一条失败不影响其他条\r\n @pytest.mark.parametrize(\"a,b,result\",add_int_data[0],ids=add_int_data[1])\r\n def test_add(self,a,b,result):\r\n print(a,b,result)\r\n assert result==self.calc.add(a,b)\r\n\r\n @pytest.mark.add_float\r\n @pytest.mark.parametrize(\"a,b,result\",add_float_data[0],ids=add_float_data[1])\r\n def test_add_float(self,a,b,result):\r\n assert result == round(self.calc.add(a,b),2)\r\n\r\n\r\n @pytest.mark.div\r\n @pytest.mark.parametrize(\"a,b,result\",div_int_data[0],ids=div_int_data[1])\r\n def test_div(self,a,b,result):\r\n assert result==self.calc.div(a,b)\r\n\r\n @pytest.mark.div_zero\r\n @pytest.mark.parametrize(\"a,b,result\", div_zero_data[0], ids=div_zero_data[1])\r\n def test_div(self, a, b, result):\r\n with pytest.raises(ZeroDivisionError):\r\n result = a / b\r\n\r\n\r\n\r\n","sub_path":"test_lab/test_pytest/test_calculator.py","file_name":"test_calculator.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"288863557","text":"# -*- coding: utf-8 -*-\nfrom datetime import date, datetime\nimport sqlalchemy as sa\n\nfrom sqlalchemy_defaults import Column\nfrom tests import TestCase\n\n\nclass TestDateTimeDefaults(TestCase):\n column_options = {}\n\n def create_models(self, **options):\n class User(self.Model):\n __tablename__ = 'user'\n __lazy_options__ = options\n\n id = Column(sa.Integer, primary_key=True)\n created_at = Column(sa.DateTime, auto_now=True)\n fav_day = Column(\n sa.Date, min=date(2000, 1, 1), max=date(2099, 1, 1)\n )\n\n self.User = User\n\n def test_autonow(self):\n column = self.User.created_at\n assert isinstance(column.default.arg(column), datetime)\n assert (\n column.server_default.arg.__class__ == sa.func.now().__class__\n )\n","sub_path":"tests/test_datetime_defaults.py","file_name":"test_datetime_defaults.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"588168392","text":"#!/usr/bin/env python\n\n\"\"\"\nsetup.py file for SWIG example\n\"\"\"\n\nfrom distutils.core import setup, Extension\n\n\nkernels_module = Extension('_kernels',\n sources=['kernels_wrap.cxx', 'kernels.cpp'],\n )\n\nsetup (name = 'kernels',\n version = '0.1',\n author = \"Yongjoo Park\",\n description = \"\"\"Kernel computation for Gaussian Process\"\"\",\n ext_modules = [kernels_module],\n py_modules = [\"kernels\"],\n )\n","sub_path":"code_backup/py/gp/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"294679759","text":"\"\"\"\nThis module implements training and evaluation of a multi-layer perceptron in NumPy.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport numpy as np\nimport os\nimport mlp_numpy\nimport cifar10_utils\n\n# Default constants\nLEARNING_RATE_DEFAULT = 2e-3\nWEIGHT_REGULARIZER_STRENGTH_DEFAULT = 0.\nWEIGHT_INITIALIZATION_SCALE_DEFAULT = 1e-4\nBATCH_SIZE_DEFAULT = 200\nMAX_STEPS_DEFAULT = 1500\nDNN_HIDDEN_UNITS_DEFAULT = '100'\n\n# Directory in which cifar data is saved\nDATA_DIR_DEFAULT = './cifar10/cifar-10-batches-py'\n\nFLAGS = None\n\ndef train():\n \"\"\"\n Performs training and evaluation of MLP model. Evaluate your model on the whole test set each 100 iterations.\n \"\"\"\n ### DO NOT CHANGE SEEDS!\n # Set the random seeds for reproducibility\n np.random.seed(42)\n\n ## Prepare all functions\n # Get number of units in each hidden layer specified in the string such as 100,100\n if FLAGS.dnn_hidden_units:\n dnn_hidden_units = FLAGS.dnn_hidden_units.split(\",\")\n dnn_hidden_units = [int(dnn_hidden_unit_) for dnn_hidden_unit_ in dnn_hidden_units]\n else:\n dnn_hidden_units = []\n\n ########################\n # PUT YOUR CODE HERE #\n #######################\n batch_size = FLAGS.batch_size\n # Get cifar data\n print('Get cifar data')\n cifar10 = cifar10_utils.get_cifar10('cifar10/cifar-10-batches-py')\n x, y = cifar10.train.next_batch(batch_size)\n #x = x.flatten()\n x = x.reshape(batch_size, -1)\n input_dimensions = x.shape[1]\n n_classes = y.shape[1]\n print('Data obtained')\n\n # Initialize MLP instance\n MLP = mlp_numpy.MLP(dnn_hidden_units, n_classes, input_dimensions, batch_size, FLAGS.weight_reg_strength, FLAGS.weight_init_scale)\n\n # Train\n #FLAGS.max_steps = 7\n for step in range(FLAGS.max_steps):\n logits = MLP.inference(x)\n #print(logits)\n loss, logits = MLP.loss(logits, y)\n #print(logits)\n MLP.train_step(loss, FLAGS, logits, y)\n \n if step%10 == 0:\n # Calculate accuracy\n print(str(step) + \": \" + str(MLP.accuracy(logits,y)) + \",\\tloss: \" + str(loss))\n\n x, y = cifar10.train.next_batch(batch_size)\n x = x.reshape(batch_size, -1)\n \n if (step + 1) == FLAGS.max_steps:\n # Load test data\n test_x, test_y = cifar10.test.images, cifar10.test.labels\n test_x = test_x.reshape(test_x.shape[0], -1)\n logits = MLP.inference(test_x)\n print(\"Accuracy on test data: \" + str(MLP.accuracy(logits,test_y)))\n\n #raise NotImplementedError\n ########################\n # END OF YOUR CODE #\n #######################\n\ndef print_flags():\n \"\"\"\n Prints all entries in FLAGS variable.\n \"\"\"\n for key, value in vars(FLAGS).items():\n print(key + ' : ' + str(value))\n\ndef main():\n \"\"\"\n Main function\n \"\"\"\n # Print all Flags to confirm parameter settings\n print_flags()\n\n if not os.path.exists(FLAGS.data_dir):\n os.makedirs(FLAGS.data_dir)\n\n # Run the training operation\n train()\n\nif __name__ == '__main__':\n # Command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--dnn_hidden_units', type = str, default = DNN_HIDDEN_UNITS_DEFAULT,\n help='Comma separated list of number of units in each hidden layer')\n parser.add_argument('--learning_rate', type = float, default = LEARNING_RATE_DEFAULT,\n help='Learning rate')\n parser.add_argument('--max_steps', type = int, default = MAX_STEPS_DEFAULT,\n help='Number of steps to run trainer.')\n parser.add_argument('--batch_size', type = int, default = BATCH_SIZE_DEFAULT,\n help='Batch size to run trainer.')\n parser.add_argument('--weight_init_scale', type = float, default = WEIGHT_INITIALIZATION_SCALE_DEFAULT,\n help='Weight initialization scale (e.g. std of a Gaussian).')\n parser.add_argument('--weight_reg_strength', type = float, default = WEIGHT_REGULARIZER_STRENGTH_DEFAULT,\n help='Regularizer strength for weights of fully-connected layers.')\n parser.add_argument('--data_dir', type = str, default = DATA_DIR_DEFAULT,\n help='Directory for storing input data')\n FLAGS, unparsed = parser.parse_known_args()\n\n main()\n","sub_path":"assignment_1/train_mlp_numpy.py","file_name":"train_mlp_numpy.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39145911","text":"\"\"\" Sandpiles Test\"\"\"\n\nimport itertools\nfrom sandpile import *\n\n\ndef main():\n try:\n # find maxgroup\n maxgroup = {}\n m = Sandpile(2, 2, \"3333\")\n temp = Sandpile(2, 2)\n\n perm = itertools.product(range(4), repeat=m.dimx * m.dimy)\n\n n = 0\n for p in perm:\n n += 1\n temp.setgrid(p)\n temp.add(m)\n key = temp.getgrid()\n maxgroup[key] = maxgroup.get(key, 0) + 1\n print(maxgroup)\n print(len(maxgroup))\n print(n)\n\n except ValueError as x:\n print('Program failed: ', x)\n\n\n# Standard boilerplate to call the main() function to begin\n# the program.\nif __name__ == '__main__':\n main()\n","sub_path":"puzzles/sandpiles/sandpilestest.py","file_name":"sandpilestest.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"59127765","text":"import spacy\nimport nltk\nfrom spacy import displacy\nfrom spacy.lang.pt.stop_words import STOP_WORDS\n\npln = spacy.load('pt')\n\ndocumento = pln('Estou aprendendo processamento de linguagem natural, curso em Curitiba')\nfor token in documento:\n print(token.text, token.pos_)\n\nfor token in documento:\n print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,\n token.shape_, token.is_alpha, token.is_stop)\n\nfor token in documento:\n if token.pos_ == 'PROPN':\n print(token.text)\n\n\n\nfor token in documento:\n print(token.text, token.lemma_)\n\ndoc = pln('encontrei encontraram encontrarão encontrariam')\n[token.lemma_ for token in doc]\n\nnltk.download('rslp')\n\nstemmer = nltk.stem.RSLPStemmer()\nstemmer.stem('aprendendo')\n\nfor token in documento:\n print(token.text, token.lemma_, stemmer.stem(token.text))\n\n\ntexto = 'A IBM é uma empresa dos Estados Unidos voltada para a área de informática. Sua sede no Brasil fica em São Paulo e a receita em 2018 foi de aproximadamente 320 bilhões de reais'\ndocumento = pln(texto)\n\nfor entidade in documento.ents:\n print(entidade.text, entidade.label_)\n\ndisplacy.render(documento, style = 'ent', jupyter= True)\n\ntexto = 'Bill Gates nasceu em Seattle em 28/10/1955 e foi o criador da Microsoft'\ndocumento = pln(texto)\nfor entidade in documento.ents:\n print(entidade.text, entidade.label_)\n\nfor entidade in documento.ents:\n if entidade.label_ == 'PER':\n print(entidade.text)\n\nprint(STOP_WORDS)\nlen(STOP_WORDS)\npln.vocab['ir'].is_stop\npln.vocab['caminhar'].is_stop\n\ndocumento = pln('Estou aprendendo processamento de linguagem natural, curso em Curitiba')\nfor token in documento:\n if not pln.vocab[token.text].is_stop:\n print(token.text)\n\n\n\ndocumento = pln('reserve uma passagem saindo de Guarulhos e chegando em Curitiba')\norigem = documento[5]\ndestino = documento[9]\norigem, destino\n\nlist(origem.ancestors)\nlist(destino.ancestors)\n\ndocumento[0].is_ancestor(documento[2])\n\n\ndocumento = pln('Reserva de uma mesa para o restaurante e de um táxi para o hotel')\ntarefas = documento[3], documento[10]\nlocais = documento[6], documento[13]\nfor local in locais:\n for objeto in local.ancestors:\n if objeto in tarefas:\n print(\"reserva de {} é para o {}\". format(objeto, local))\n break\n\nlist(documento[6].children)\n\ndisplacy.serve(documento, style='dep')\ndisplacy.render(documento, style='dep', jupyter=False, options={'distance':90})\n\nlist(documento[3].ancestors)\nlist(documento[3].children)\n\ndocumento = pln('Que locais podemos visitar em Curitiba e para ficar em Guarulhos?')\nlugares = [token for token in documento if token.pos_ == 'PROPN']\nacoes = [token for token in documento if token.pos_ == 'VERB']\n\nfor local in lugares:\n for acao in local.ancestors:\n if acao in acoes:\n print(\"{} para {}\".format(local, acao))\n break\n\ndisplacy.render(documento, style='dep', jupyter=True, options={'distance':90})\n\n\n\n\np1 = pln('olá')\np2 = pln('oi')\np3 = pln('ou')\n\np1.similarity(p2)\np2.similarity(p1)\np1.similarity(p3)\np2.similarity(p3)\n\n\ntexto1 = pln('Quando será lançado o novo filme?')\ntexto2 = pln('O novo filme será lançado mês que vem')\ntexto3 = pln('Qual a cor do carro?')\n\ntexto1.similarity(texto2)\ntexto1.similarity(texto3)\n\n\ntexto = pln('gato cachorro cavalo pessoa')\nfor texto1 in texto:\n #print('-----', texto1)\n for texto2 in texto:\n #print(texto2)\n similaridade = int(texto1.similarity(texto2) * 100)\n print(\"{} é {} similar a {}\".format(texto1, similaridade, texto2))\n\n\n\ndocumento = pln('Estou aprendendo processamento de linguagem natural, curso em Curitiba')\ndocumento1 = 'Estou aprendendo processamento de linguagem natural, curso em Curitiba'\ndocumento1.split(' ')\nfor token in documento:\n print(token)\n\n\n\n\n\n\n","sub_path":"introducao ao spacy.py","file_name":"introducao ao spacy.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"586714710","text":"# Tu pišite svoje funkcije:\r\n\r\nfrom math import *\r\n\r\ndef koordinate(ime, kraji):\r\n for kraj, x, y in kraji:\r\n if ime == kraj:\r\n return x, y\r\n return None\r\n\r\ndef razdalja_koordinat(x1, y1, x2, y2):\r\n z = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\r\n return z\r\n\r\ndef razdalja(ime1, ime2, kraji):\r\n x1, y1 = koordinate(ime1, kraji)\r\n x2, y2 = koordinate(ime2, kraji)\r\n\r\n return razdalja_koordinat(x1, y1, x2, y2)\r\n\r\ndef v_dometu(ime, domet, kraji):\r\n s = []\r\n for kraj, x, y in kraji:\r\n if ime == kraj:\r\n x0, y0 = x, y\r\n break\r\n\r\n for kraj, x, y in kraji:\r\n r = sqrt((x - x0) ** 2 + (y - y0) ** 2)\r\n if r <= domet and kraj != ime:\r\n s.append(kraj)\r\n return s\r\n\r\ndef najbolj_oddaljeni(ime, imena, kraji):\r\n r = 0\r\n for kraj, x, y in kraji:\r\n if ime == kraj:\r\n x0, y0 = x, y\r\n break\r\n\r\n for kraj, x, y in kraji:\r\n if kraj in imena:\r\n z = sqrt((x - x0) ** 2 + (y - y0) ** 2)\r\n if z > r:\r\n r = z\r\n naj = kraj\r\n return naj\r\n\r\ndef zalijemo(ime, domet, kraji):\r\n r = 0\r\n for kraj, x, y in kraji:\r\n if ime == kraj:\r\n x0, y0 = x, y\r\n\r\n for kraj, x, y in kraji:\r\n z = sqrt((x - x0) ** 2 + (y - y0) ** 2)\r\n if r < z <= domet:\r\n r = z\r\n naj = kraj\r\n\r\n return naj\r\n\r\ndef presek(s1, s2):\r\n s3 = []\r\n for i in s1:\r\n if i in s2:\r\n s3.append(i)\r\n return(s3)\r\n\r\ndef skupno_zalivanje(ime1, ime2, domet, kraji):\r\n s1 = v_dometu(ime1, domet, kraji)\r\n s2 = v_dometu(ime2, domet, kraji)\r\n return presek(s1, s2)\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN4-M-194.py","file_name":"DN4-M-194.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"447951574","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 15 20:46:19 2020\n\n@author: Touzari\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport statistics\nfrom scipy.stats import norm\n\ndef methode_hist(coord,grid):\n cpt=0\n res=[]\n f=False\n N=len(coord)\n x=sorted(list(set([i[0] for i in grid]))) #2\n y=sorted(list(set([i[1] for i in grid])))\n \n for i1 in range(len(x)-1):\n for i2 in range(len(y)-1):\n cpt=0\n for j in coord:\n if((x[i1]<=j[1]) and (j[1] 0:\n chris(n-1)\n else:\n print('----------')\n print(n)\n\nchris(3)\n\n'''''\n\n# person_list=['alex','wupeiqi','linhaifeng','zsc']\n# def ask_way(person_list):\n# print('-'*60)\n# if len(person_list) == 0:\n# return '根本没人知道'\n# person=person_list.pop(0)\n# if person == 'linhaifeng':\n# return '%s说:我知道,老男孩就在沙河汇德商厦,下地铁就是' %person\n#\n# print('hi 美男[%s],敢问路在何方' % person)\n# print('%s回答道:我不知道,但念��慧眼识猪,你等着,我帮你问问%s...' % (person, person_list))\n#\n# res=ask_way(person_list)\n#\n#\n# print('%s问的结果是: %res' %(person,res))\n# return res\n#\n# res=ask_way(person_list)\n# print(res)\n\n\n# jishubu = ['李铁峰', '王瑞涛', '严岳','陈亮']\n# def wenlu(jishubu):\n# if len(jishubu) == 0:\n# return '没有人知道'\n# ren = jishubu.pop(0)\n# if ren == '王瑞涛':\n# return '左边'\n#\n# print('%s, 你知道怎么去厕所嘛' %ren)\n# print('%s说我帮你问问 %s' %(ren, jishubu))\n#\n# res = wenlu(jishubu)\n# print('%s问的结果是: %res' %(ren,res))\n# return res\n# res = wenlu(jishubu)\n# print(res)\n\n\n# name = 'chris'\n# def foo():\n# if name != 'chris':\n# return 'wo shi shuaige'\n# else:\n# return 'laji'\n\n# name = 'jdlskajf'\n# def chris(name):\n# return name+'_sb'\n#\n# print(chris(name))\n\n\n# name = 'chris'\n#\n# def foo():\n# name = 'fish'\n# def bar():\n# name = 'micheal'\n# def tt():\n# print(name)\n# return tt\n# return bar\n# ln = foo()()()\n# print(ln)\n\n\n# name = 'chris'\n# sj = lambda x : name+'_shuaqi'\n# print(sj(name))\n\n'''''\ndef cal(x):\n return 2*x+1\n\nprint(cal(5))\n\n'''''\n\n# def foo(n): #n=bar\n# print(n)\n#\n# def bar(name):\n# print('my name is %s' %name)\n#\n# # foo(bar)\n# # foo(bar())\n# # foo(bar('alex'))\n\n\nnum = [1, 2, 10, 5, 3, 7]\nnum2 = [1, 22, 10, 5, 3, 7]\n\n# chris = []\n# for i in num:\n# chris.append(i**2)\n# print(chris)\n\n#\n# def pf(shuzu):\n# chris = []\n# for i in num2:\n# chris.append(i**2)\n# return chris\n#\n# print(pf(num2))\n\n# def map_test(func,array):\n# ret=[]\n# for i in num_l:\n# res=func(i) #add_one(i)\n# ret.append(res)\n# return ret\n#\n# print(map_test(add_one,num))\n\n\n# num=[1,2,10,5,3,7]\n\n\n# li = []\n# # for i in num:\n# # li.append(i**2)\n# # print(li)\n#\n# def pingfang(zhi):\n# for i in zhi:\n# li.append(i**2)\n# return li\n# print(pingfang(num))\n#\n# print(list(map(lambda x:x**2, num)))\n\n# peo=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']\n\n# li = []\n# for i in peo:\n# if not i.endswith('sb'):\n# li.append(i)\n# print(li)\n#\n# def chris(fangfa, zhi):\n# li = []\n# for i in zhi:\n# if not fangfa(i):\n# li.append(i)\n# return li\n#\n# res = chris(lambda x:x.endswith('sb'), peo)\n# print(res)\n\n#\n#\n# print(list(filter(lambda x:not x.endswith('sb'), peo)))\n\n\nli = [1, 2, 3, 100]\n\n#\n# ret = 0\n# for i in li:\n# ret += i\n# print(ret)\n\n\n# def chris(zhi):\n# ret = 0\n# for i in zhi:\n# ret += i\n# return ret\n# print(chris(li))\n\n# def xiangjia(x,y):\n# return x+y\n#\n# def chris(func, array):\n# res = 0\n# for i in array:\n# res += i\n# return res\n# print(chris(xiangjia, li))\n# print(reduce(lambda x,y:x+y,li))\n\n\n#\n#\n# num_l=[1,2,3,100]\n# def reduce_test(func,array,init=None):\n# if init is None:\n# res=array.pop(0)\n# else:\n# res=init\n# for num in array:\n# res=func(res,num)\n# return res\n# print(reduce_test(lambda x,y:x+y,num_l))\n\n\n# name='你好'\n# print(bytes(name,encoding='utf-8').decode('utf-8'))\n\n\n# age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30}\n#\n#\n# print(list(max(zip(age_dic.values(),age_dic.keys()))))\n\n\n# print(max(age_dic.values()))\n#\n# #默认比较的是字典的key\n# # print(max(age_dic))\n#\n# for item in zip(age_dic.values(),age_dic.keys()): #[(18,'alex_age') (20,'wupeiqi_age') () () ()]\n# print(item)\n# #\n# print('=======>',list(max(zip(age_dic.values(),age_dic.keys()))))\n\n# l=[\n# (5,'e'),\n# (1,'b'),\n# (3,'a'),\n# (4,'d'),\n# ]\n# # l1=['a10','b12','c10',100] #不同类型之间不能进行比较\n# l1=['a10','a2','a10'] #不同类型之间不能进行比较\n# print(list(max(l)))\n# print('--->',list(max(l1)))\n\n\n# l=[1,3,100,-1,2]\n# print(max(l))\n# dic={'age1':18,'age2':10}\n# print(max(dic)) #比较的是key\n# print(max(dic.values())) #比较的是key,但是不知道是那个key对应的\n#\n# print(max(zip(dic.values(),dic.keys()))) #结合zip使用\n#\n\n# people=[\n# {'name':'alex','age':1000},\n# {'name':'wupei','age':10000},\n# {'name':'yuanhao','age':9000},\n# {'name':'linhaifeng','age':18},\n# ]\n#\n# age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30}\n#\n# # ret = []\n# # for i in people:\n# # ret.append(i['age'])\n# # print(ret)\n#\n# print(sorted(people, key=lambda x:x['age']))\n\n\n# chris = open('eop.py', 'r')\n# data = chris.readlines()\n# fish = open('eop.py', 'w')\n# fish.write(data[0])\n# chris.close()\n# fish.close()\n\n# f = open('日志文件', 'rb')\n#\n# for i in f:\n# offs=-3\n# n=0\n# while True:\n# f.seek(offs,2)\n# data=f.readlines()\n# if len(data) > 1:\n# print('最后一行%s' %(data[-1].decode('utf-8')))\n# break\n# offs*=2\n\n\n# l=[1,3,100,-1,2]\n# res = l.__iter__()\n# print(res)\n# print(res.__next__())\n# print(next(res))\n# print(next(res))\n\n\n# egglist = []\n# for i in range(10):\n# egglist.append('鸡蛋%s'%i)\n# print(egglist)\n#\n# l = ['鸡蛋%s' %i for i in range(10)] # 列表解析\n# print(l)\n\n# laomuji = ('鸡蛋%s' % i for i in range(3)) # 生成器表达式,生成器表达式比列表解析更省内存\n# print(laomuji)\n# print(next(laomuji))\n# print(next(laomuji))\n#\n\n# print(sum(i for i in range(10)))\n\n\n# def xiadan():\n# ret = []\n# for i in range(10):\n# ret.append('鸡蛋%s' %i)\n# return ret\n# print(xiadan())\n#\n#\n# x = ['鸡蛋%s' %i for i in range(100)]\n# print(x)\n#\n# y = ('鸡蛋%s' %i for i in range(100))\n# print(next(y))\n# print(next(y))\n# print(next(y))\n# print(next(y))\n# print(next(y))\n# print(next(y))\n\n# def xiadan():\n# for i in range(10):\n# yield '鸡蛋%s' %i\n# chris = xiadan()\n# print(next(chris))\n# print(next(chris))\n# print(next(chris))\n# print(next(chris))\n\n# def chris():\n# ret = []\n# with open('renkou.py', 'w') as f:\n# for i in f:\n# ret.append(i)\n# return ret\n# print(chris())\n\n\n'''''\n\ndef get_popu():\n with open('renkou.py', 'r') as f:\n for i in f:\n yield i\n\ng = get_popu() # g是一个生成器,Python的生成器是一个返回可以迭代对象的函数\ns1 = eval(g.__next__()) # eval函数就是实现list、dict、tuple与str之间的转化\nprint (type(s1))\nprint (s1['num'])\n# res = 0\n# for p in g:\n# p_dic = eval(p)\n# print (p_dic['num'])\n# res += p_dic['num']\n# print (res)\n\nall_pop = sum(eval(i)['num'] for i in g)\nprint (all_pop)\n\n\nfor p in g:\n print (eval)\n\n'''''\n\n'''''\ndef test():\n print('开始')\n first = yield 99\n print('第一次', first)\n second = yield 2\n print('第二次',second)\n yield 3\n\nt = test()\nres = t.__next__()\nprint(res)\nt.send(55)\nt.send(88)\n\n'''''\n\n'''''\n\nimport time\n\nlist = ['roubaozi', 'caibaozi', 'jiucaibaozi','niuroubaozi','23']\ndef ren(name):\n print('我是%s 等着吃包子' %name)\n while True:\n baozi = yield\n time.sleep(2)\n print('这个%s包子是我%s最爱吃的' %(baozi,name))\ndef bao():\n l1 = ren('chris')\n l2 = ren('mc')\n l1.__next__()\n l2.__next__()\n for i in list:\n l1.send(i)\n l2.send(i)\nbao()\n\n'''''\n\n'''''\n\ndef func(start, end, a = 0, b = 0):\n if start == end:\n return a,b\n if start %3 == 0 and start %7 == 0:\n a += 1\n b += start\n ret = func(start+1, end, a, b)\n return ret\nres = func(1, 300)\nprint(res)\n\n'''''\n\n'''''\n\ndef func(zifu1):\n a=0\n b=0\n c=0\n for i in zifu1:\n if i.isupper():\n a+=1\n elif i.islower():\n b+=1\n elif i.isdigit():\n c+=1\n return ({'daxie':a,'xiaoxie':b,'shuzi':c})\nzifu1 = ('aaa111AAA')\nprint(func(zifu1))\n\n\n\n'''''\n\n'''''\n\n\n\n\n\nfun1(a,b,c) \nfun2(a=1,b=2,c=3) \nfun3(*args) \nfun4(**kargs)\n\n四种中最常见是前两种,基本上一般点的教程都会涉及,后两种一般很少单独出现,常用在混合模式中\n第一种 fun1(a,b,c)是直接将实参赋予行参,根据位置做匹配,即严格要求实参的数量与行参的数量位置相等,比较一般,大多数语言常用这种方式。\n\n第二种 fun2(a=1,b=2,c=3)根据键值对的形式做实参与行参的匹配,通过这种式就可以忽略了参数的位置关系,直接根据关键字来进行赋值,\n同时该种传参方式还有个好处就是可以在调用函数的时候作为个别选填项,不要求数量上的相等,即可以fun5(3,4)来调用fun2函数,\n这里关键就是前面的3,4覆盖了原来a、b两个行参的值,但c还是不变采用原来的默认值3,这种模式相较第一种更加灵活,\n不仅可以通过fun6(c=5,a=2,b=7)来打乱行参的位置,而且可以在但没有对应行参传递的时候常用定义函数时的默认值。\n\n第三种 fun3(*args),这传参方式是可以传入任意个参数,这些若干参数都被放到了tuple元组中赋值给行参args,之后要在函数中使用这些行参,\n直接操作args这个tuple元组就可以了,这样的好处是在参数的数量上没有了限制,但是因为是tuple,其本身还是有次序的,\n这就仍然存在一定的束缚,在对参数操作上也会有一些不便\n\n第四种 fun4(**kargs)最为灵活,其是以键值对字典的形式向函数传参,含有第二种位置的灵活的同时具有第三种方式的数量上的无限制。\n此外第三四种函数声明的方式前的'*',与c里面的指针声明一样,这里仅做声明标识之用\n最后要强调的是四种传递方式混合使用(大多数情况是这种),fun7(a,b,*c,**d),但四种方式混用时要遵守:\n\n\n ● args = 须在args之后\n ● *args须在args=value之后\n ● **kargs须在*args之��\n赋值过程为:\n 1. 按顺序把传给args的实参赋值给对应的行参\n 2. args = value 形式的实参赋值给行参\n 3. 将多余出的即键值对行后的零 散实参打包组成一个tuple传递给*args\n 4. 将多余的key=value形式的实参打包正一个dicrionary传递给**kargs\n举例\n定义\ndef test(x,y=5,*,**b): \n>>>>print x,y,a,b\n调用结果\ntest(1) ===> 1 5 () {} \ntest(1,2) ===> 1 2 () {} \ntest(1,2,3) ===> 1 2 (3,) {} \ntest(1,2,3,4) ===> 1 2 (3,4) \ntest(x=1) ===> 1 5 () {} \ntest(x=1,y=1) ===> 1 1 () {} \ntest(x=1,y=1,a=1) ===> 1 1 () {'a':1} test(x=1,y=1,a=1,b=1) ===> 1 1 () {'a':1,'b':1} \ntest(1,y=1) ===> 1 1 () {} \ntest(1,2,y=1) ===> 出错,说y给赋了多个值\ntest(1,2,3,4,a=1) ===> 1 2 (3,4) {'a':1} \ntest(1,2,3,4,k=1,t=2,o=3) ===> 1 2 (3,4) {'k':1,'t':2,'o':3}\n\n\n'''''\n\n'''''\n#默认参数\nprint('\\n以下是默认参数传值\\n')\ndef stu_info(name,age,major,country = 'CN'): # country设为了默认参数,必须放在位置参数之后,否则会出错\n print('--------学生信息-------')\n print('姓名:',name)\n print('年龄:',age)\n print('专业:',major)\n print('国籍:',country)\n\n# stu1 = stu_info('Jack',21,'Chinese') # 此处未传对应的值,但形参中已经定义了,所以不用担心找不家了!\n# stu2 = stu_info('Frank',20,'JP')   # 你也是的\nstu3 = stu_info('Rose',19,'Art','UK')# 既然你已经传参了,就随你了。\n\n\n'''''\n\n\n# def func(a):\n# return a+100\n# func = lambda a:a+200\n# ret = func(10)\n# print(ret)\n\n\n# str = '老男孩'\n# print(str.encode('utf-8'))\n# print(bytes('老男孩', encoding='utf-8'))\n# print(bytes('老男孩', 'utf-8'))\n\n\n# def test(arg):\n# a=1\n# b=2\n# data_dict = {}\n# print(locals())\n# print(globals())\n#\n#\n# if __name__ == '__main__':\n# test(3)\n\n\n# 内置函数zip\n#\n# l1=['alex',1]\n# l2=['alex22',1]\n# l3=['alex33',1]\n#\n# print('_'.join(list(zip(l1,l2,l3))[0]))\n\n\n# a=[1,2]\n# def ss():\n# a.append(456)\n# ss()\n# print(a)\n\n\n# name = 'root'\n#\n# def func():\n# name = \"seven\"\n# def outer():\n# name = \"eric\"\n# def inner():\n# global name\n# name = \"蒙逼了吧...\"\n# print(name)\n# print(name)\n#\n# ret = func()\n# print(ret)\n# print(name)\n\n\n#\n# import time\n#\n# def shijian(func):\n# def tongji(*args, **kwargs):\n# starttime = time.time()\n# res = func(*args,**kwargs)\n# endtime = time.time()\n# print(endtime-starttime)\n# return res\n# return tongji\n#\n#\n# # @shijian\n# # def test(name, age):\n# # time.sleep(1)\n# # print('test函数运行完毕,名字是%s,年龄是%s' %(name, age))\n# # return 'test的返回值'\n# # res = test('linhaifeng',18)\n# # print(res)\n#\n#\n# @shijian\n# def test1(name, age, gender):\n# time.sleep(1)\n# print('test函数运行完毕,名字是%s,年龄是%s,性别%s' %(name, age, gender))\n# return 'test的返回值'\n# res = test1('linhaifeng',18, 'man')\n# print(res)\n#\n# # res = shijian(test)\n# # res()\n\n# # a,b,c = {1,2,3}\n# a,b,c = 'hec'\n# print(a)\n# print(b)\n# print(c)\n\n\n#\n# l = [1,2,3,4,5,6,7,8,9] #取列表的第一个和最后一个值\n# # a,d = l[0], l[-1]\n# # print(a)\n# # print(d)\n#\n# a,*_,d=l\n# print(a)\n# print(d)\n\n#\n# user_list=[\n# {'name':'alex','passwd':'123'},\n# {'name':'linhaifeng','passwd':'123'},\n# {'name':'wupeiqi','passwd':'123'},\n# {'name':'yuanhao','passwd':'123'},\n# ]\n#\n# type = {'username':None, 'login':False}\n#\n#\n#\n# def auth(auth_type='filedb'):\n# def auth_func(func):\n# def wapper(*args,**kwargs):\n# print('认证类型是', auth_type)\n# if auth_type == 'filedb':\n# if type['username'] and type['login']:\n# res = func(*args, **kwargs)\n# return res\n# else:\n# username = input('please input').strip()\n# password = input('please input').strip()\n# for use_dic in user_list:\n# if username == use_dic['name'] and password == use_dic['passwd']:\n# type['username'] = username\n# type['login'] = True\n# res = func(*args,**kwargs)\n# return res\n# else:\n# print('1111111111')\n# elif auth_type == 'ldap':\n# print('sm gui')\n# return wapper\n# return auth_func\n#\n#\n#\n# @auth(auth_type='filedb') #auth_func = auth(auth_type='filedb')---->>>@auth_func\n# def index():\n# print('welcome to home')\n#\n# @auth(auth_type='ldap')\n# def home(name):\n# print('lets go, %s' %name)\n#\n# @auth(auth_type='filedb')\n# def shopping_car(name):\n# print('%s , %s , %s in your shoppingcar' %(name,'macbook','iphone'))\n#\n# index()\n# home('project manager')\n# shopping_car('monkey')\n\n\ndef fetch(data):\n print('This is fetch')\n print('user data is', data)\n backend_data = 'backend %s' % data\n with open('haproxy.conf', 'r') as read_f:\n tag = False\n ret = []\n for read_line in read_f:\n if read_line.strip() == backend_data:\n tag = True\n continue\n if tag and read_line.startswith('backend'):\n break\n if tag:\n print(read_line,end='')\n ret.append(read_line.strip())\n return ret\n\n\n\n\ndef add():\n pass\n\n\ndef change(data):\n print('This is change')\n print('user Transmitted data is', data)\n data[0]['backend'] #文件当中的一条记录\n res = fetch(backend)\n print(res)\n\ndef delete():\n pass\n\n\nif __name__ == '__main__':\n msg = '''\n 1: 查询\n 2: 添加\n 3: 修改\n 4: 删除\n 5: 退出\n '''\n\n msg_dic = {\n '1': fetch,\n '2': add,\n '3': change,\n '4': delete,\n }\n\n while True:\n print(msg)\n choice = input('please iput:').strip()\n if not choice: continue\n if choice == '5': break\n\n data = input('please insert your data:').strip()\n if choice != 1:\n data = eval(data)\n res = msg_dic[choice](data)\n print(res)\n","sub_path":"CHRIS.py","file_name":"CHRIS.py","file_ext":"py","file_size_in_byte":24710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"457186760","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def isSameTree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype: bool\n \"\"\"\n\n #if Both are null then return True\n\n if(p == None and q == None):\n return True\n # if one of them is null then of course tree are not same hence return False\n if(p == None or q == None):\n return False\n # Classic case of preOrder Traversal, check curr values and then go left check and then go right check \n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n\n\ndef main():\n Tree1 = TreeNode([1,2,2,3,4,None,4])\n\n Tree2 = TreeNode([1,2,2,3,4,None,4])\n\n solution = Solution()\n print(solution.isSameTree(Tree1,Tree2))\n\nmain()\n\n","sub_path":"source/LeetCode/Code/100.py","file_name":"100.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"176767068","text":"import numpy as np\nimport math\n\nimport NeuralNet as skNN\n\n'''\nTry to use neural for curve fitting\nHere we will set input as sine wave\n\n'''\n## input of network\np=np.linspace(-1,1,100)\np=np.mat(p)\nindexSampleP=1 # 0=Sample in row, 1=Sample in column\n\n# target of network\n# target=np.matrix('0; 0; 0; 1')\ntarget=np.sin(p)\ntarget=np.mat(target)\nindexSampleTarget=1 # 0=Sample in row, 1=Sample in column\n\n# network structure\n# nHidLayer=1\nnNodeInEachHid=np.array([5])\nnHidLayer=len(nNodeInEachHid)\n# if len(nNodeInEachHid) != nHidLayer:\n# print('You must set the no. of neural in each hidden layer !')\n\n# array of transfer function that related with no. of hidden layer\n# dim=len(nNeuronArr)-2 (set transfer funciton only neuron in each hidden layer)\ntransfNetwork=['purelin']\n\n# print('\\ninput=')\n# print(p)\n#\n# print('\\ntarget=')\n# print(target)\n# singleNN=nn()\n# singleNN.inAndOut(p,1,target,0,[2,1,1],['hardlim'])\n\n# Build the network\nnnFitSin=skNN.MLP()\nnnFitSin.build(p,indexSampleP,target,indexSampleTarget,nNodeInEachHid,transfNetwork)\n","sub_path":"Neural network/02_MultiPerceptron.py","file_name":"02_MultiPerceptron.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102684814","text":"f = open('27-11b.txt')\nn = int(f.readline())\nsum_max = 0\nost = [10001] * 8\nz = [0] * 3\nfor _ in range(n):\n a, b, c = map(int, f.readline().split())\n z[0] = a\n z[1] = b\n z[2] = c\n ost1 = ost.copy()\n z.sort()\n sum_max += z[2]\n for j in range(2):\n d = z[2] - z[j]\n r = d%8\n if r != 0:\n for i in range(1, 8):\n r1 = (r+i)%8\n ost1[r1] = min(ost1[r1], d + ost[i])\n ost1[r] = min(ost1[r], d)\n ost = ost1.copy()\nif sum_max % 8 == 0:\n print(sum_max)\nelse:\n print(sum_max - ost[sum_max%8])","sub_path":"Щелчок/27_поляков/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"484827076","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nd = webdriver.Chrome()\nd.implicitly_wait(10)\nd.maximize_window()\nd.get('http://www.baidu.com')\ne1 = d.find_element_by_xpath('//*[@id=\"s-usersetting-top\"]')\n\n#生成对象,传入driver\naction=ActionChains(d)\n#传入要悬停的元素\naction.move_to_element(e1).perform()\n\n","sub_path":"sss/shop/鼠标悬停.py","file_name":"鼠标悬停.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439221939","text":"import numpy as np\nimport pandas as pd\nfrom pandas_datareader import data as wb\nimport matplotlib.pyplot as plt\n\nTickerA='ITSA4.SA'\nTickerB='FLRY3.SA'\nTickerC='LREN3.SA'\nTickerD='PRIO3.SA'\nTickerE='BPAN4.SA'\nTickerF='LWSA3.SA'\n\nprices=pd.DataFrame()\ntickers = [TickerA, TickerB, TickerC, TickerD, TickerE, TickerF]\nfor t in tickers:\n prices[t]=wb.DataReader(t, data_source='yahoo', start='2019-1-1')['Adj Close']\n\n(prices/prices.iloc[0]*100).plot(figsize=(15,5))\nplt.ylabel('NORMALIZED PRICES')\nplt.xlabel('DATE')\nplt.show()","sub_path":"grafico-de-acoes.py","file_name":"grafico-de-acoes.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"308897571","text":"#work on python2 only\nimport nmap\nimport optparse\ndef nmapscan(tgthost, tgtport):\n scann=nmap.PortScanner()\n scann.scan(tgthost, tgtport)\n state=scann[tgthost]['tcp'][int(tgtport)]['state']\n print((\"[*]\"+tgthost+\"tcp/\"+tgtport+\":::\"+state))\n\n\ndef main():\n\n parser = optparse.OptionParser(\"usage %prog \"+\"-H -P \")\n parser.add_option('-H', dest='tgthost', type='string',help='specify target host')\n parser.add_option('-P', dest='tgtport', type='string',help='specify target port[s] separated by comma')\n (options, args) = parser.parse_args()\n tgthost = options.tgthost\n tgtports = str(options.tgtport).split(\",\")\n if (tgthost == None) | (tgtports[0] == None):\n print('[-] You must specify a target host and port[s].')\n exit(0)\n for tgtport in tgtports:\n nmapscan(tgthost, tgtport)\nif __name__ == '__main__':\n main()","sub_path":"nmap_scanner.py","file_name":"nmap_scanner.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"348076999","text":"'''\nCreated on 31.05.2014\n\n@author: Ulrichstandard\n'''\nimport pygame\nimport tempfile\nimport os\nimport util.random\nimport wx\nclass Button:\n def __init__(self, parent, text=\"\", cords=(0, 0), action=\"\", backingFile=None):\n pygame.init()\n pygame.font.init()\n self.text = text\n self.parent = parent\n self.cords = cords\n self.action = action\n self.rect = None\n self.backingfile = backingFile\n self.surface = None\n self.button_padding = 10\n self.bitmap = None\n self.font_file = os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"ressources\", \"LiberationMono-Regular.ttf\")\n self.render()\n \n def render(self):\n font_format = pygame.font.Font(self.font_file, 30, bold=False, italic=False)\n rendered_text = font_format.render(self.text, True, (0, 0, 0))\n font_width = rendered_text.get_rect().width\n font_height = rendered_text.get_rect().height\n box_width = font_width + self.button_padding + self.button_padding\n box_height = font_height + self.button_padding + self.button_padding\n \n \n if len(self.cords) >= 4:\n box_width = self.cords[2]\n box_height = self.cords[3]\n \n centerX = box_width / 2 - (font_width / 2)\n centerY = box_height / 2 - (font_height / 2)\n \n background = pygame.image.load(self.backingfile)\n background = pygame.transform.smoothscale(background, (box_width, box_height))\n background.blit(rendered_text, (centerX, centerY))\n self.surface = background\n self.renderBitmap()\n \n def renderBitmap(self, format='png'):\n if os.name == \"nt\":\n path = os.environ[\"APPDATA\"]\n else:\n path = os.path.expanduser('~')\n \n # Funktioniert nicht, keine Ahnung wieso\n # f = tempfile.NamedTemporaryFile(suffix=format)\n path = os.path.join(path, util.random.uniqid('image-') + \".png\")\n pygame.image.save(self.surface, path)\n self.bitmap = wx.Image(path, wx.BITMAP_TYPE_ANY).ConvertToBitmap()\n os.unlink(path)\n \n def getBitmap(self):\n return self.bitmap\n","sub_path":"src/controller/pygame/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650379689","text":"# Copyright (c) 2021, NVIDIA CORPORATION.\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 cudf\nimport cugraph\nimport numpy as np\nfrom .convert_matrix import from_cudf_edgelist\nfrom .graph_components import (\n annotate_nodes,\n annotate_edges,\n category_to_color\n)\n\n\ndef make_synthetic_dataset(**kwargs):\n import pandas as pd\n import datetime as dt\n kwargs.update(direct=True)\n df = cudf.DataFrame.from_pandas(pd.DataFrame({\n \"src\": [0, 1, 2, 3],\n \"dst\": [1, 2, 3, 0],\n \"colors\": [1, 1, 2, 2],\n \"bool\": [True, False, True, True],\n \"char\": [\"a\", \"b\", \"c\", \"d\"],\n \"str\": [\"a\", \"b\", \"c\", \"d\"],\n \"ustr\": [u\"a\", u\"b\", u\"c\", u\"d\"],\n \"emoji\": [\"😋\", \"😋😋\", \"😋\", \"😋\"],\n \"int\": [0, 1, 2, 3],\n \"num\": [0.5, 1.5, 2.5, 3.5],\n \"date_str\": [\n \"2018-01-01 00:00:00\",\n \"2018-01-02 00:00:00\",\n \"2018-01-03 00:00:00\",\n \"2018-01-05 00:00:00\",\n ],\n \"date\": [\n dt.datetime(2018, 1, 1),\n dt.datetime(2018, 1, 1),\n dt.datetime(2018, 1, 1),\n dt.datetime(2018, 1, 1),\n ],\n \"time\": [\n pd.Timestamp(\"2018-01-05\"),\n pd.Timestamp(\"2018-01-05\"),\n pd.Timestamp(\"2018-01-05\"),\n pd.Timestamp(\"2018-01-05\"),\n ],\n }))\n return make_and_shape_hypergraph(df, **kwargs)\n\n\ndef make_and_shape_hypergraph(df, **kwargs):\n hyper = cugraph.hypergraph(df, **kwargs)\n del hyper[\"events\"]\n del hyper[\"entities\"]\n SOURCE = kwargs.get(\"SOURCE\", \"src\")\n TARGET = kwargs.get(\"TARGET\", \"dst\")\n NODEID = kwargs.get(\"NODEID\", \"node_id\")\n EVENTID = kwargs.get(\"EVENTID\", \"event_id\")\n CATEGORY = kwargs.get(\"CATEGORY\", \"category\")\n nodes = hyper[\"nodes\"][[NODEID, CATEGORY]]\n edges = hyper[\"edges\"][[SOURCE, TARGET]]\n # Create graph\n graph, nodes, edges = from_cudf_edgelist(edges, SOURCE, TARGET)\n nodes[\"name\"] = nodes[\"node\"]\n # Add vis components \n nodes = annotate_nodes(graph, nodes, edges)\n edges = annotate_edges(graph, nodes, edges)\n return graph, nodes, edges\n\n\ndef make_capwin_dataset(**kwargs):\n\n def drop_index(df):\n return df.reset_index(drop=True)\n\n def smoosh(df):\n size = sum([df[x].dtype.itemsize for x in df])\n data = drop_index(drop_index(df).stack()).data\n dtype = cudf.utils.dtypes.min_unsigned_type(0, size*8)\n return cudf.core.column.NumericalColumn(data, dtype=dtype)\n\n def add_edge_colors(edges, category):\n colors = drop_index(category_to_color(edges[category], color_palette=[\n # ADDRESS AUTH KEYS CREDENTIALS EMAIL FALSE\n 4294967091, 4294410687, 4293138972, 4281827000, 33554431\n ]).astype(np.uint32))\n return edges.assign(color=smoosh(cudf.DataFrame({\n \"src\": drop_index(colors), \"dst\": drop_index(colors)\n })).astype(np.uint64), src_color=colors)\n \n df = cudf.read_csv(\"data/pii_sample_for_viz.csv\")\n df = df[[\"src_ip\", \"dest_ip\", \"pii\", \"timestamp\"]]\n df[\"timestamp\"] = cudf.to_datetime(df[\"timestamp\"], format=\"%m/%d/%y %H:%M\")\n # Create graph\n graph, nodes, edges = from_cudf_edgelist(df, \"src_ip\", \"dest_ip\")\n # Add vis components \n nodes = nodes.rename({\"node\": \"name\"}, axis=1, copy=False)\n nodes = annotate_nodes(graph, nodes, edges)\n # add edge colors\n edges = add_edge_colors(edges, \"pii\")\n print(edges.query(\"src_color != 33554431\")[\"src\"].value_counts())\n print(edges.query(\"src_color != 33554431\")[\"dst\"].value_counts())\n # add edge names\n edges[\"name\"] = edges[\"src_ip\"] + \" -> \" + edges[\"dest_ip\"] + \\\n (\"\\nPII: \" + edges[\"pii\"]).replace(\"\\nPII: FALSE\", \"\")\n return graph, nodes, edges\n","sub_path":"modules/demo/graph/python/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430894283","text":"\"\"\"\ntemplate_demo.py - Simplified version of string.Template's metaclass from Chapter 2\n\"\"\"\n\nimport re\n\nclass TemplateMetaclass(type):\n default_pattern = 'example' # complex regular expression pattern\n\n def __init__(cls, name, bases, cls_attrs):\n super().__init__(name, bases, cls_attrs)\n if 'pattern' in cls_attrs:\n pattern = cls.pattern\n else:\n pattern = TemplateMetaclass.default_pattern\n cls.pattern = re.compile(pattern)\n\n\nclass Template(metaclass=TemplateMetaclass):\n \"\"\"A string class for supporting $-substitutions.\"\"\"\n\nclass MyTemplate(Template):\n pattern = 'This is my template pattern'\n\nmy_template = MyTemplate()\nprint(MyTemplate.pattern)\n","sub_path":"examples/ch02_examples/template_demo.py","file_name":"template_demo.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"589614995","text":"from collections import defaultdict\nfrom itertools import product\n\nfrom fuzzconfig import FuzzConfig\nimport interconnect\nimport nets\nimport pytrellis\nimport re\nimport argparse\n\nimport isptcl\nimport mk_nets\n\nspan1_re = re.compile(r'R\\d+C\\d+_[VH]01[NESWTLBR]\\d{4}')\njofx_re = re.compile(r'R\\d+C\\d+_JOFX\\d')\ndef nn_filter(net, netnames):\n \"\"\" Match nets that are: in the tile according to Tcl, global nets, or span-1 nets that are accidentally\n left out by Tcl\"\"\"\n return net in netnames or nets.machxo2.is_global(net) or span1_re.match(net)\n\n# JOFX source connections are conjectured to not go to anything.\n# Also ignore edge connections.\n# TODO: We should probably ignore KEEP connections too, but right now am unsure.\ndef fc_filter(arc, netnames):\n return not jofx_re.match(arc[0]) and not (nets.general_routing_re.match(arc[0]) and nets.general_routing_re.match(arc[1]))\n\n# Bank of None means that the I/O connections are in another tile.\njobs = [\n {\n \"pos\" : (12, 18),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEB\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PB18:PIC_B0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"B\",\n },\n {\n \"pos\" : (8, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEL\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PL8:PIC_L0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n # Probably the same thing as PIC_L0 plus some additional fixed connections?\n {\n \"pos\" : (11, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELLC0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PL11:LLC0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n {\n \"pos\" : (10, 22),\n \"cfg\" : FuzzConfig(job=\"PIOROUTER\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PR10:PIC_R0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n # 4\n {\n \"pos\" : (0, 16),\n \"cfg\" : FuzzConfig(job=\"PIOROUTET\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PT16:PIC_T0\"]),\n \"missing_nets\" : None,\n \"nn_filter\" : lambda x, nets: x.startswith(\"R0C16\"),\n \"bank\" : \"T\",\n },\n\n {\n \"pos\" : (9, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELS0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PL9:PIC_LS0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"LS\",\n },\n\n {\n \"pos\" : (3, 22),\n \"cfg\" : FuzzConfig(job=\"PIOROUTERS0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PR3:PIC_RS0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"RS\",\n },\n\n {\n \"pos\" : (10, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEL\", family=\"MachXO3\", device=\"LCMXO3LF-6900C\", ncl=\"pioroute_6900.ncl\",\n tiles=[\"PL10:PIC_L2\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n # 8\n # Probably the same thing as PIC_L2 plus some additional fixed connections?\n {\n \"pos\" : (26, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELLC2\", family=\"MachXO3\", device=\"LCMXO3LF-6900C\", ncl=\"pioroute_6900.ncl\",\n tiles=[\"PL26:LLC2\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n {\n \"pos\" : (25, 41),\n \"cfg\" : FuzzConfig(job=\"PIOROUTER\", family=\"MachXO3\", device=\"LCMXO3LF-6900C\", ncl=\"pioroute_6900.ncl\",\n tiles=[\"PR25:PIC_R1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n\n {\n \"pos\" : (10, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEL\", family=\"MachXO3\", device=\"LCMXO3LF-2100C\", ncl=\"pioroute_2100.ncl\",\n tiles=[\"PL10:PIC_L3\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n {\n \"pos\" : (14, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEL\", family=\"MachXO3\", device=\"LCMXO3LF-4300C\", ncl=\"pioroute_4300.ncl\",\n tiles=[\"PL14:PIC_L1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n # 12\n {\n \"pos\" : (21, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELLC1\", family=\"MachXO3\", device=\"LCMXO3LF-4300C\", ncl=\"pioroute_4300.ncl\",\n tiles=[\"PL21:LLC1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n\n {\n \"pos\" : (11, 22),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELRC0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PR11:LRC0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n\n {\n \"pos\" : (21, 32),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELRC1\", family=\"MachXO3\", device=\"LCMXO3LF-4300C\", ncl=\"pioroute_4300.ncl\",\n tiles=[\"PR21:LRC1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n\n {\n \"pos\" : (14, 26),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELRC1PIC2\", family=\"MachXO3\", device=\"LCMXO3LF-2100C\", ncl=\"pioroute_2100.ncl\",\n tiles=[\"PR14:LRC1PIC2\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n #16\n {\n \"pos\" : (1, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEULC1\", family=\"MachXO3\", device=\"LCMXO3LF-4300C\", ncl=\"pioroute_4300.ncl\",\n tiles=[\"PL1:ULC1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (1, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEULC2\", family=\"MachXO3\", device=\"LCMXO3LF-6900C\", ncl=\"pioroute_6900.ncl\",\n tiles=[\"PL1:ULC2\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (1, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEULC3PIC\", family=\"MachXO3\", device=\"LCMXO3LF-2100C\", ncl=\"pioroute_2100.ncl\",\n tiles=[\"PL1:ULC3PIC\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (1, 26),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEURC1PIC\", family=\"MachXO3\", device=\"LCMXO3LF-2100C\", ncl=\"pioroute_2100.ncl\",\n tiles=[\"PR1:URC1PIC\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n #20\n {\n \"pos\" : (30, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELLC0PIC_VREF3\", family=\"MachXO3\", device=\"LCMXO3LF-9400C\", ncl=\"pioroute_9400.ncl\",\n tiles=[\"PL30:LLC0PIC_VREF3\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (14, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTELLC1PIC_VREF3\", family=\"MachXO3\", device=\"LCMXO3LF-2100C\", ncl=\"pioroute_2100.ncl\",\n tiles=[\"PL14:LLC3PIC_VREF3\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (1, 1),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEULC0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PL1:ULC0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"L\"\n },\n {\n \"pos\" : (11, 11),\n \"cfg\" : FuzzConfig(job=\"CIBPICB0ROUTE\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"CIB_R11C11:CIB_PIC_B0\"]),\n # A bug in the span1 fix prevents span1 nets from being included.\n # Just fuzz manually for now.\n \"missing_nets\" : [\"R10C11_V01N0001\", \"R10C11_V01N0101\"],\n \"nn_filter\": nn_filter,\n \"bank\" : None,\n },\n #24\n {\n \"pos\" : (1, 10),\n \"cfg\" : FuzzConfig(job=\"CIBPICT0ROUTE\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"CIB_R1C10:CIB_PIC_T0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : None,\n },\n {\n \"pos\" : (1, 22),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEURC0\", family=\"MachXO3\", device=\"LCMXO3LF-1300E\", ncl=\"pioroute_1300.ncl\",\n tiles=[\"PR1:URC0\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n {\n \"pos\" : (1, 32),\n \"cfg\" : FuzzConfig(job=\"PIOROUTEURC0\", family=\"MachXO3\", device=\"LCMXO3LF-4300C\", ncl=\"pioroute_4300.ncl\",\n tiles=[\"PR1:URC1\"]),\n \"missing_nets\" : None,\n \"nn_filter\": nn_filter,\n \"bank\" : \"R\"\n },\n]\n\ndef main(args):\n pytrellis.load_database(\"../../../database\")\n for job in [jobs[i] for i in args.ids]:\n cfg = job[\"cfg\"]\n cfg.setup()\n\n if args.i:\n # Fuzz basic routing, ignore fixed connections to/from I/O pads.\n interconnect.fuzz_interconnect(config=cfg, location=job[\"pos\"],\n netname_predicate=job[\"nn_filter\"],\n netdir_override=defaultdict(lambda : str(\"ignore\")),\n fc_predicate=fc_filter,\n netname_filter_union=False,\n enable_span1_fix=True)\n\n if args.m and job[\"missing_nets\"]:\n interconnect.fuzz_interconnect_with_netnames(config=cfg,\n netnames=job[\"missing_nets\"],\n fc_predicate=fc_filter,\n netname_filter_union=False,\n bidir=True,\n netdir_override=defaultdict(lambda : str(\"ignore\")))\n\n\n if args.p and job[\"bank\"]:\n # I/O connections in the left/right tiles exist as-if a column \"0\"\n # or one past maximum is physically present.\n if job[\"bank\"].startswith(\"R\"):\n ab_only = job[\"bank\"].endswith(\"S\")\n io_nets = mk_nets.io_conns((job[\"pos\"][0], job[\"pos\"][1] + 1), job[\"bank\"], ab_only)\n elif job[\"bank\"].startswith(\"L\"):\n ab_only = job[\"bank\"].endswith(\"S\")\n io_nets = mk_nets.io_conns((job[\"pos\"][0], job[\"pos\"][1] - 1), job[\"bank\"], ab_only)\n else:\n io_nets = mk_nets.io_conns((job[\"pos\"][0], job[\"pos\"][1]), job[\"bank\"])\n\n io_list = [io[0] for io in io_nets]\n override_dict = {io[0]: io[1] for io in io_nets}\n print(override_dict)\n\n interconnect.fuzz_interconnect_with_netnames(config=cfg,\n netnames=io_list,\n fc_predicate=fc_filter,\n netname_filter_union=False,\n bidir=True,\n netdir_override=override_dict)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"PIO Routing Fuzzer.\")\n parser.add_argument(\"-i\", action=\"store_true\", help=\"Fuzz interconnect.\")\n parser.add_argument(\"-m\", action=\"store_true\", help=\"Fuzz missing nets.\")\n parser.add_argument(\"-p\", action=\"store_true\", help=\"Fuzz I/O pad connections.\")\n parser.add_argument(dest=\"ids\", metavar=\"N\", type=int, nargs=\"*\",\n default=range(0, len(jobs)), help=\"Job (indices) to run.\")\n args = parser.parse_args()\n main(args)\n","sub_path":"fuzzers/machxo3/050-pio_routing/fuzzer.py","file_name":"fuzzer.py","file_ext":"py","file_size_in_byte":13087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"216283690","text":"\n\nfrom xai.brain.wordbase.verbs._annex import _ANNEX\n\n#calss header\nclass _ANNEXED(_ANNEX, ):\n\tdef __init__(self,): \n\t\t_ANNEX.__init__(self)\n\t\tself.name = \"ANNEXED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"annex\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_annexed.py","file_name":"_annexed.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"565753858","text":"#!/usr/bin/python3\n\n# *****************************************************************************\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# ******************************************************************************\n\nimport argparse\nimport os\nfrom datalab.actions_lib import *\nfrom fabric import *\nfrom datalab.logger import logging\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--keyfile', type=str, default='')\nparser.add_argument('--notebook_ip', type=str, default='')\nparser.add_argument('--os_user', type=str, default='')\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n global conn\n conn = datalab.fab.init_datalab_connection(args.notebook_ip, args.os_user, args.keyfile)\n\n bucket_name = ('{0}-{1}-{2}-bucket'.format(os.environ['conf_service_base_name'], os.environ['project_name'],\n os.environ['endpoint_name'])).lower().replace('_', '-')\n gitlab_certfile = os.environ['conf_gitlab_certfile']\n if GCPActions().get_gitlab_cert(bucket_name, gitlab_certfile):\n conn.put(gitlab_certfile, gitlab_certfile)\n conn.sudo('chown root:root {}'.format(gitlab_certfile))\n logging.info('{} has been downloaded'.format(gitlab_certfile))\n else:\n logging.info('There is no {} to download'.format(gitlab_certfile))\n\n conn.close()","sub_path":"infrastructure-provisioning/src/general/scripts/gcp/common_download_git_certfile.py","file_name":"common_download_git_certfile.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"130092014","text":"import math\ndef correct_float(string):\n while True:\n try:\n point = float(input(\"{}\".format(string)))\n except ValueError:\n print(\"Value error! Try again!\\n\")\n else:\n if(point > 0):\n return point\n print(\"Range error! Try again!\")\n\nweight = correct_float(\"Введiть вагу зернятка в кг:\\t\")\nsum = 0\nfor i in range(0, 64):\n cell = int(math.pow(2, i))\n sum += cell\n print(f\"На клiтинцi {i+1} – {cell} зерен\")\nweight *= sum\nprint(f\"Всього:\\t{sum}\\nВага:\\t{weight} кг\")","sub_path":"python/Lab3/Lab3_5.py","file_name":"Lab3_5.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"460450632","text":"from tkinter import *\nfrom tkinter import messagebox\n\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef scrape():\n if (messagebox.askyesno(\"Wait?\", \"This could take a few seconds. Wait?\") == False):\n return\n if site.status_code is 200:\n content = BeautifulSoup(site.content, 'html.parser') \n totalpts = 0\n for myplayer in lst: # loop to check my players\n dTag = content.find(attrs={\"csk\": myplayer})\n parent = dTag.findParent('tr')\n playerpts = int(parent.contents[8].text) # 8th tag is total points\n print(myplayer + \" \" + str(playerpts))\n totalpts = totalpts + playerpts \n mypts.configure(text=totalpts)\n \ndef updatelab():\n lstprint = \"\"\n for item in lst:\n lstprint = lstprint + item + \"\\n\"\n mylab.configure(text=lstprint) \n\ndef addItem():\n item = entry.get()\n if (lst.count != 0):\n lst.append(item)\n entry.delete(0, END) \n updatelab() \n \ndef remItem():\n item = entry.get()\n if (len(lst) != 0):\n lst.remove(item)\n entry.delete(0, END) \n updatelab()\n \ndef saveList():\n myfile = open(\"myplayers.txt\",\"w\")\n for player in lst:\n myfile.write(player + \"\\n\")\n myfile.close()\n messagebox.showinfo(\"myplayers.txt\", \"Players saved to disk\")\n\nlst = []\nlstprint = \"\"\ntotalpts = 0\nprint(\"Downloading hockey data\")\nsite = requests.get('https://www.hockey-reference.com/leagues/NHL_2019_skaters.html')\n\nroot = Tk()\nroot.geometry(\"300x400+0+900\")\nroot.title(\"hockey pool\")\n\ninstlab = Label(root,text=\"Input (e.g., McDavid,Connor): \")\ninstlab.pack() \n\nentry = Entry(root) \nentry.pack()\n\naddbutton = Button(root, text=\"Add\", command=addItem)\naddbutton.pack()\n\nrembutton = Button(root, text=\"Remove\", command=remItem)\nrembutton.pack()\n\nsavebutton = Button(root, text=\"Save\", command=saveList)\nsavebutton.pack()\n\nmylab = Label(root,text=lstprint,anchor=W,justify=LEFT)\nmylab.pack()\n\nptsbutton = Button(root,text=\"Check pts\", command=scrape)\nptsbutton.pack()\n\nmypts = Label(root,text=totalpts)\nmypts.pack()\n\nmainloop()\n","sub_path":"pool.py","file_name":"pool.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"355477122","text":"\"\"\"\nSensor and Switch for Bayernluefter\n\"\"\"\nimport logging\n\nimport voluptuous as vol\nfrom homeassistant.helpers.discovery import async_load_platform\n\nfrom homeassistant.const import (\n CONF_RESOURCE,\n CONF_PASSWORD,\n CONF_SCAN_INTERVAL,\n TEMP_CELSIUS,\n)\nfrom homeassistant.helpers.event import async_track_time_interval\nfrom datetime import timedelta\nfrom datetime import datetime\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers import aiohttp_client\n\nfrom pyernluefter import Bayernluefter\n\n_LOGGER = logging.getLogger(__name__)\n\nDOMAIN = \"bayernluefter\"\n\n# scan every 30 seconds per default\nDEFAULT_SCAN_INTERVAL = 30\n\nUNIT = {\"analog\": TEMP_CELSIUS, \"speed\": \"rpm\", \"power\": \"kW\", \"energy\": \"kWh\"}\nICON = {\n \"analog\": \"mdi:thermometer\",\n \"speed\": \"mdi:speedometer\",\n \"power\": \"mdi:power-plug\",\n \"energy\": \"mdi:power-plug\",\n}\n\nCONFIG_SCHEMA = vol.Schema(\n {\n DOMAIN: vol.Schema(\n {\n vol.Required(CONF_RESOURCE): cv.url,\n vol.Optional(\n CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL\n ): cv.positive_int,\n }\n ),\n },\n extra=vol.ALLOW_EXTRA,\n)\n\n\nasync def async_setup(hass, config):\n \"\"\"Set up the BLNET component\"\"\"\n\n config = config[DOMAIN]\n resource = config.get(CONF_RESOURCE)\n scan_interval = config.get(CONF_SCAN_INTERVAL)\n session = aiohttp_client.async_get_clientsession(hass)\n\n # Initialize the BL-NET sensor\n try:\n blnet = Bayernluefter(resource, session)\n except (ValueError, AssertionError) as ex:\n if isinstance(ex, ValueError):\n _LOGGER.error(\"No Bayernluefter reached at {}\".format(resource))\n else:\n _LOGGER.error(\"Configuration invalid: {}\".format(ex))\n return False\n\n # set the communication entity\n hass.data[\"DATA_{}\".format(DOMAIN)] = blnet\n\n # make sure the communication device gets updated once in a while\n async def fetch_data(*_):\n return await blnet.update()\n\n # Get the latest data from REST API and load\n # sensors and switches accordingly\n disc_info = {\n \"domain\": DOMAIN,\n }\n await async_load_platform(hass, \"sensor\", DOMAIN, disc_info, config)\n await async_load_platform(hass, \"switch\", DOMAIN, disc_info, config)\n await async_load_platform(hass, \"fan\", DOMAIN, disc_info, config)\n\n # Repeat if data fetching fails at first\n async_track_time_interval(hass, fetch_data, timedelta(seconds=scan_interval))\n\n # Fetch method takes care of adding dicovered sensors\n return True\n","sub_path":"custom_components/bayernluefter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"93373800","text":"from matplotlib import pyplot as plt\nfrom matplotlib.dates import date2num\nfrom Data_Cleaning import Data_Cleaner\n\nobj = Data_Cleaner()\nplot_data = obj.Get_Plot_Data_Tweet_VS_Date('clean_gold.csv')\n#print plot_data\n\nx = [date2num(date) for (date, value) in plot_data]\ny = [value for (date, value) in plot_data]\n\nfig = plt.figure()\ngraph = fig.add_subplot(111)\ngraph.set_xlabel('Date')\ngraph.xaxis.label.set_color('blue')\ngraph.set_ylabel('Number of tweets')\ngraph.yaxis.label.set_color('blue')\n\n# Plot the data as a red line with round markers\ngraph.plot(x,y,'r--o')\n# Set the xtick locations to correspond to just the dates you entered.\ngraph.set_xticks(x)\n# Set the xtick labels to correspond to just the dates you entered.\ngraph.set_xticklabels(\n [date.strftime(\"%d-%m-%Y\") for (date, value) in plot_data]\n )\ntitle_obj = plt.title('Date vs Number of tweets') #get the title property handler\nplt.getp(title_obj) #print out the properties of title\nplt.getp(title_obj, 'text') #print out the 'text' property for title\nplt.setp(title_obj, color='b')\nplt.show()\nplt.show()\n","sub_path":"Data_Cleaning Projects/no_of_tweets_vs_date.py","file_name":"no_of_tweets_vs_date.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221221756","text":"import math\n\ndef score (dicReq, dicDoc):\n\tscore=0\n\tfor motR in dicReq:\n\t\tfor motD in dicDoc:\n\t\t\tif (motR==motD):\n\t\t\t\tscore+=float(dicReq[motR])*float(dicDoc[motD])\n\n\t#Calcul norme Requete\n\tnormeReq=0\n\tfor motR in dicReq:\n\t\tnormeReq += pow(float(dicReq[motR]),2)\n\tnormeReq=math.sqrt(normeReq)\n\n\t#Calcul norme Document\n\tnormeDoc=0\n\tfor motD in dicDoc:\n\t\tnormeDoc += pow(float(dicDoc[motD]),2)\n\tnormeDoc=math.sqrt(normeDoc)\n\n\t#calcul score final\n\treturn score/(normeDoc*normeReq)\n\n\ndicDocs = dict()\ndicReqs = dict()\n\n#Ouverture des documents\ndataDoc = open(\"indexDoc.txt\").readlines()\nfor line in dataDoc:\n\tcol = line.split()\n\tdicDocs[col[0]]=dict()\n\tfor i in range(1,len(col),2):\n\t\tdicDocs[col[0]][col[i]]=col[i+1]\n\n#Ouverture des requetes\ndataReq = open(\"indexReq.txt\").readlines()\nfor line in dataReq:\n\tcol = line.split()\n\tdicReqs[col[0]]=dict()\n\tfor i in range(1,len(col),2):\n\t\tdicReqs[col[0]][col[i]]=col[i+1]\n\n#Traitement des requetes\nresultat = dict()\nfor requete in dicReqs:\n\tresultat[requete] = dict()\n\tfor document in dicDocs:\n\t\tdist = score(dicReqs[requete], dicDocs[document]) #Calcul du score du document pour la requete\n\t\tresultat[requete][document]=dist #ajout du document au dico\n\n#Ecriture du fichier resultat\ndoc = open(\"resultat.txt\", \"w\")\nfor requete in resultat:\n\tfor document in resultat[requete]:\n\t\tif resultat[requete][document] > 0.1 :\n\t\t\tdoc.write(\"%s %s %f \\n\" %(requete,document,resultat[requete][document]))\n \n\ndoc.close()\n\t\t\n","sub_path":"Projet/Tf-Idf.py","file_name":"Tf-Idf.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"285039600","text":"# %%\nimport pandas as pd\nimport tensorflow as tf\nimport keras\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import TensorDataset, DataLoader\nimport numpy as np\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout\nfrom tensorflow.keras.models import load_model, Model\nfrom attention import Attention\n\n# %%\n# torch.cuda.is_available() checks and returns a Boolean True if a GPU is available, else it'll return False\nis_cuda = torch.cuda.is_available()\n\n# If we have a GPU available, we'll set our device to GPU. We'll use this device variable later in our code. \"gpu\"/\"tpu\"\nif is_cuda:\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\n\n# %%\npath = r\"/Users/taanhtuan/Desktop/ids-2018-demo/combined_data.csv\"\n\n# %%\ndf = pd.read_csv(path)\n\n# %%\ndf\n\n# %%\nfor col in df.columns:\n print(col, \": \", df.iloc[0][col])\n\n# %%\nfor col in df.columns:\n num_of_samples = len(df)\n unique_values = df[col].value_counts()\n unique_values = unique_values.reset_index()\n for value in unique_values.iterrows():\n percentage = float((value[1][col]*100/num_of_samples))\n if percentage > 99:\n print(\"Col: \", col)\n print(\"the percentage of \", value[1]['index'], \" occupied\", percentage)\n else:\n break;\n# print(\"and some values with trivial percentage\")\n\n# %%\nnum_of_samples = len(df)\nunique_values = df[\"Dst Port\"].value_counts()\nunique_values = unique_values.reset_index()\nfor value in unique_values.iterrows():\n percentage = float((value[1][\"Dst Port\"]*100/num_of_samples))\n if percentage > 0.01:\n print(\"the percentage of \", value[1]['index'], \" occupied\", percentage)\nprint(\"and some values with trivial percentage\")\n\n# %%\ndf.sort_values(by=[\"Dst Port\", \"Timestamp\"])\n\n# %%\ndropped_columns = [\"Timestamp\", \"Bwd PSH Flags\", \"Bwd URG Flags\", \"FIN Flag Cnt\", \"CWE Flag Count\", \"Fwd Byts/b Avg\",\n \"Fwd Pkts/b Avg\", \"Fwd Blk Rate Avg\", \"Bwd Byts/b Avg\", \"Bwd Pkts/b Avg\", \"Bwd Blk Rate Avg\"]\ndf = df.drop(dropped_columns, axis=1)\n\n# %%\nX = df.iloc[:, df.columns != 'Label']\nY = df.iloc[:, df.columns == 'Label']\n\n# %%\nY = df.iloc[:, df.columns == 'Label']\nunique_values = Y[\"Label\"].value_counts()\nprint(unique_values)\n\n# %%\nord_enc = OrdinalEncoder()\nY = ord_enc.fit_transform(Y)\n\n# %%\nY = Y.ravel()\n\n# %%\nY.shape\n\n# %%\nX\n\n# %%\nX = X.replace([np.inf, -np.inf], np.nan)\nX = X.dropna()\n\n# %%\nheig = len(X.columns)\nDst_list = []\nX_uniq_vals = X[\"Dst Port\"].value_counts()\nX_uniq_vals = X_uniq_vals.reset_index()\n\nleng = X_uniq_vals.iloc[0]['Dst Port']\n\nprint(\"leng: \", leng)\nprint(\"heig: \", heig)\n\n# %%\ninputs = np.zeros((1050000 ,20,68))\nnum_of_inputs = 0\nnum_of_inputsVal = 0\n\nhis_record = 20\nnum_of_feat = 68\n \nfor value in X_uniq_vals.iterrows():\n num_of_inputsVal = 0\n print(\"value index: \", value[1]['index'])\n \n mask = X['Dst Port'] == value[1]['index']\n dfX = X[mask].to_numpy()\n print(type(dfX))\n dfX = dfX.transpose()\n \n extra_df = np.zeros((num_of_feat, his_record))\n count = 0;\n \n new_df = np.concatenate((extra_df, dfX), axis=1)\n new_df = new_df.transpose()\n \n df_leng = new_df.shape[0]\n \n print(extra_df.shape)\n print(dfX.shape)\n print(new_df.shape)\n print(new_df[0].shape)\n print(df_leng)\n \n for i in range(his_record,df_leng):\n print(\"num_of_inputs: \", num_of_inputs)\n inputs[num_of_inputs] = new_df[i-his_record:i][:]\n num_of_inputs += 1\n num_of_inputsVal += 1\n if(num_of_inputsVal == 10000):\n break;\n\n# if value[1]['index'] == 53:\n# break;\n# arr = torch.from_numpy(arr).float(\n\n# %%\ninputs = inputs[:num_of_inputs]\n\n# %%\nlabels = Y[:num_of_inputs]\n\n# %%\nprint(type(labels))\nprint(type(inputs))\nprint()\nprint(labels.shape)\nprint(inputs.shape)\n\n# %%\nx_train, x_test, y_train, y_test = train_test_split(inputs, labels,test_size=0.15, random_state=42)\n# x_train, x_val, y_train, y_val = train_test_split(x_train, y_train,test_size=0.2, random_state=42)\n\n# %%\nprint(x_train.shape)\nprint(y_train.shape)\nprint(x_test.shape)\nprint(y_test.shape)\n\n# %%\nnumofclass = np.unique(labels, return_inverse=False)\nprint(numofclass)\n\n# %%\n# Dummy data. There is nothing to learn in this example.\nnum_samples = 193721\n\ntime_steps = 20\ninput_dim = 68\n\noutput_dim = 1\n\nprint(\"size: \", num_samples, \" \", time_steps, \" \", input_dim)\n\ndata_x = x_train\ndata_y = y_train\n\n# %%\nprint(\"ABC\")\n\n# Define/compile the model.\nmodel_input = Input(shape=(time_steps, input_dim))\nprint(\"model_input: \", model_input.shape) # input(None, 20, 78)\nx = LSTM(64, return_sequences=True)(model_input)\nprint(x.shape) # outputLSTM(None, 20, 64)\nx = Dropout(0.5)(x)\nprint(x.shape) # outputDropout(None, 20, 64)\nx = Attention(32)(x)\nprint(x.shape) # outputAttention(None, 32)\ninitializer = tf.keras.initializers.GlorotUniform(seed=42)\nactivation = None\nx = Dense(3, kernel_initializer=initializer, activation=activation)(x)\nprint(x.shape) # output(None, 1)\n\nmodel = Model(model_input, x)\nmodel.compile(optimizer=keras.optimizers.Adam(),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), # default from_logits=False\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n\n\n# %%\nprint(model.summary())\n\n# train.\nmodel.fit(data_x, data_y, epochs=10)\n\n# test save/reload model.\npred1 = model.predict(data_x)\nmodel.save('test_model.h5')\n\n\n# %%\nimport numpy as np\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout\nfrom tensorflow.keras.models import load_model, Model\n\nfrom attention import Attention\n\ntime_steps = 20\ninput_dim = 68\n\n# Define/compile the model.\nmodel_input = Input(shape=(time_steps, input_dim))\nx = LSTM(64, return_sequences=True)(model_input)\nx = Dropout(0.5)(x)\nx = Attention(32)(x)\nx = Dense(3)(x)\n\n\nmodel = Model(model_input, x)\nmodel.compile(loss='bce', optimizer='adam')\nprint(model.summary())\n\nmodel_h5 = load_model('test_model.h5')\npred_muilt = model_h5.predict(x_test)\n \n\n# %%\nprint(pred_muilt.shape)\npreTest = np.zeros(32999)\nfor i in range(pred_muilt.shape[0]):\n preTest[i] = np.argmax(pred_muilt[i], axis=0)\n\nnumCorrect = 0\nprint(preTest.shape)\nprint(y_test.shape)\nfor i in range(preTest.shape[0]):\n if y_test[i] == preTest[i]:\n numCorrect += 1\nprint(\"Accuracy: \", numCorrect/preTest.shape[0])\n\n# %%\n","sub_path":"LSTM-Attention.py","file_name":"LSTM-Attention.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"633519166","text":"# -*- coding: utf-8 -*-\n\nfrom keras.models import model_from_json\nfrom sentence_to_numbers import convert_sentence_to_number\nfrom keras.preprocessing import sequence\n\n# load json and create model\njson_file = open('model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"model.h5\")\nprint(\"Loaded model from disk\")\n\nsentence = u'Утре ще вали ли навън?'\n\nmax_length = 80\n\nX = [convert_sentence_to_number(sentence)]\n\nX = sequence.pad_sequences(X, maxlen=max_length)\n\nprint(loaded_model.predict(X))\n","sub_path":"data_processing/predict_new.py","file_name":"predict_new.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"293772879","text":"# explanation: ソケット通信用のパッケージ\n# creator:R Suzuki\n# date:2020.12.26\n# coding: UTF-8\n# \n# ソケット通信の基礎\n# https://qiita.com/megadreams14/items/32a3eed4661e55419e1c\n# \n# ソケット通信 python公式ドキュメント\n# https://docs.python.org/ja/3.6/howto/sockets.html\n\nimport socket\n\nCRLF = \"\\r\\n\"\n\ndef request_attitude():\n ip_adr = \"127.0.0.1\"\n port = 50007\n message = \"attitude\"\n\n try:\n # AF_INET: IPv4, SOCK_STREAM: TCP/IP\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((ip_adr, port)) # サーバを指定\n message = message.encode()\n s.sendall(message) # サーバにメッセージを送る\n print(\"send: \", repr(message))\n data = s.recv(1024) # ネットワークのバッファサイズは1024。サーバからの文字列を取得する\n print(\"receive: \", data.decode().split(CRLF))\n except:\n raise\n finally:\n s.close()\n \n return data\n\ndef attitude_server():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(('127.0.0.1', 50007)) # IPアドレスとポートを指定\n s.listen(1) # 並列処理数\n try:\n while True:\n conn, addr = s.accept() # 誰かがアクセスしてきたら、コネクションとアドレスを入れる\n with conn:\n while True:\n data = conn.recv(1024) # データを受け取る\n if not data:\n break\n print('data : {}, addr: {}'.format(data, addr))\n \n if data == b'attitude': # attitudeリクエストの場合の処理\n x = 12.13523452345\n y = -235342.2342345\n z = 29384.2452345\n message = (str(x)+CRLF+str(y)+CRLF+str(z)).encode()\n conn.sendall(message)\n except:\n raise\n finally:\n print(\"server close\")\n s.close()\n\nif __name__ == \"__main__\":\n request_attitude()\n # attitude_server()","sub_path":"sckcomm.py","file_name":"sckcomm.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"343951793","text":"'''\r\n\r\nNew Integration Test for create vm with iscsi 6 volumes and detach 6 volumes and reboot vm and attach one volumes .\r\n\r\n@author: ye.tian 2018-12-12\r\n'''\r\n\r\nimport zstackwoodpecker.test_util as test_util\r\nimport os\r\nimport zstackwoodpecker.test_lib as test_lib\r\nimport zstackwoodpecker.test_state as test_state\r\nimport zstackwoodpecker.operations.host_operations as host_ops\r\nimport zstackwoodpecker.operations.resource_operations as res_ops\r\nimport zstackwoodpecker.operations.vm_operations as vm_ops\r\nimport zstackwoodpecker.operations.volume_operations as vol_ops\r\nimport zstackwoodpecker.operations.account_operations as acc_ops\r\nimport zstackwoodpecker.operations.tag_operations as tag_ops\r\n\r\n\r\n_config_ = {\r\n 'timeout' : 2000,\r\n 'noparallel' : True\r\n }\r\n\r\ntest_stub = test_lib.lib_get_test_stub()\r\ntest_obj_dict = test_state.TestStateDict()\r\nall_volume_offering_uuid = None\r\nrw_volume_offering_uuid = None\r\ninstance_offering_uuid = None\r\n\r\nvm = None\r\n\r\ndef test():\r\n global vm, all_volume_offering_uuid, rw_volume_offering_uuid, all_volume_uuid, rw_volume_uuid, volume_offering_3, volume_offering_4, volume_offering_5, volume_offering_6 \r\n global instance_offering_uuid, volume_uuid_3, volume_uuid_4, volume_uuid_5, volume_uuid_6\r\n \r\n #create disk offering\r\n test_util.test_dsc('create disk offering')\r\n name_all = 'all_disk_offering'\t\r\n volume_bandwidth = 30*1024*1024\r\n all_volume_offering = test_lib.lib_create_disk_offering(name = name_all, volume_bandwidth = volume_bandwidth)\r\n all_volume_offering_uuid = all_volume_offering.uuid\r\n\r\n name_rw = 'rw_disk_offering'\t\r\n volume_read_bandwidth = 90*1024*1024\r\n volume_write_bandwidth = 100*1024*1024\r\n rw_volume_offering = test_lib.lib_create_disk_offering(name = name_rw, read_bandwidth = volume_read_bandwidth, write_bandwidth = volume_write_bandwidth)\r\n rw_volume_offering_uuid = rw_volume_offering.uuid\r\n \r\n volume_offering_3 = test_lib.lib_create_disk_offering(name = \"volume_offering_3\")\r\n volume_offering_4 = test_lib.lib_create_disk_offering(name = \"volume_offering_4\")\r\n volume_offering_5 = test_lib.lib_create_disk_offering(name = \"volume_offering_5\")\r\n volume_offering_6 = test_lib.lib_create_disk_offering(name = \"volume_offering_6\")\r\n\r\n #create instance offering \r\n test_util.test_dsc('create instance offering')\r\n read_bandwidth = 50*1024*1024\r\n write_bandwidth = 60*1024*1024\r\n net_outbound_bandwidth = 70*1024*1024\r\n net_inbound_bandwidth = 80*1024*1024\r\n new_instance_offering = test_lib.lib_create_instance_offering(read_bandwidth = read_bandwidth, write_bandwidth=write_bandwidth, net_outbound_bandwidth = net_outbound_bandwidth, net_inbound_bandwidth = net_inbound_bandwidth)\r\n instance_offering_uuid = new_instance_offering.uuid\r\n\r\n #create vm with 2 data volumes\r\n test_util.test_dsc('create vm with volumes qos by normal account a')\r\n l3net_uuid = res_ops.get_resource(res_ops.L3_NETWORK)[0].uuid\r\n cond = res_ops.gen_query_conditions('platform', '=', 'Linux')\r\n image_uuid = res_ops.query_resource(res_ops.IMAGE, cond)[0].uuid\r\n vm_creation_option = test_util.VmOption()\r\n vm_creation_option.set_instance_offering_uuid(instance_offering_uuid)\r\n vm_creation_option.set_image_uuid(image_uuid)\r\n vm_creation_option.set_l3_uuids([l3net_uuid])\r\n\r\n vm = test_stub.create_vm_with_volume(vm_creation_option = vm_creation_option, data_volume_uuids = [all_volume_offering_uuid, rw_volume_offering_uuid, volume_offering_3.uuid, volume_offering_4.uuid, volume_offering_5.uuid, volume_offering_6.uuid])\r\n vm_inv = vm.get_vm()\r\n\r\n\r\n # get the volume uuid\r\n test_util.test_dsc('get the vm data volumes')\r\n cond1 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', all_volume_offering_uuid)\r\n cond2 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', rw_volume_offering_uuid)\r\n cond3 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', volume_offering_3.uuid)\r\n cond4 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', volume_offering_4.uuid)\r\n cond5 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', volume_offering_5.uuid)\r\n cond6 = res_ops.gen_query_conditions(\"diskOfferingUuid\", '=', volume_offering_6.uuid)\r\n all_volume_uuid = res_ops.query_resource(res_ops.VOLUME, cond1)[0].uuid\r\n rw_volume_uuid = res_ops.query_resource(res_ops.VOLUME, cond2)[0].uuid\r\n volume_uuid_3 = res_ops.query_resource(res_ops.VOLUME, cond3)[0].uuid\r\n volume_uuid_4 = res_ops.query_resource(res_ops.VOLUME, cond4)[0].uuid\r\n volume_uuid_5 = res_ops.query_resource(res_ops.VOLUME, cond5)[0].uuid\r\n volume_uuid_6 = res_ops.query_resource(res_ops.VOLUME, cond6)[0].uuid\r\n\r\n tag_ops.create_system_tag('VolumeVO', all_volume_uuid, \"capability::virtio-scsi\")\r\n tag_ops.create_system_tag('VolumeVO', rw_volume_uuid, \"capability::virtio-scsi\")\r\n tag_ops.create_system_tag('VolumeVO', volume_uuid_3, \"capability::virtio-scsi\")\r\n tag_ops.create_system_tag('VolumeVO', volume_uuid_4, \"capability::virtio-scsi\")\r\n tag_ops.create_system_tag('VolumeVO', volume_uuid_5, \"capability::virtio-scsi\")\r\n tag_ops.create_system_tag('VolumeVO', volume_uuid_6, \"capability::virtio-scsi\")\r\n\r\n vm.check()\r\n vm.reboot()\r\n\r\n vol_ops.detach_volume(all_volume_uuid, vm_inv.uuid)\r\n vol_ops.detach_volume(rw_volume_uuid, vm_inv.uuid)\r\n vol_ops.detach_volume(volume_uuid_3, vm_inv.uuid)\r\n vol_ops.detach_volume(volume_uuid_4, vm_inv.uuid)\r\n vol_ops.detach_volume(volume_uuid_5, vm_inv.uuid)\r\n vol_ops.detach_volume(volume_uuid_6, vm_inv.uuid)\r\n \r\n vm.check()\r\n \r\n vol_ops.attach_volume(all_volume_uuid, vm_inv.uuid)\r\n vol_ops.attach_volume(rw_volume_uuid, vm_inv.uuid)\r\n vol_ops.attach_volume(volume_uuid_3, vm_inv.uuid)\r\n vol_ops.attach_volume(volume_uuid_4, vm_inv.uuid)\r\n vol_ops.attach_volume(volume_uuid_5, vm_inv.uuid)\r\n vol_ops.attach_volume(volume_uuid_6, vm_inv.uuid)\r\n\r\n vm.reboot()\r\n vm.check()\r\n \r\n vol_ops.detach_volume(all_volume_uuid, vm_inv.uuid)\r\n vm.check()\r\n\r\n vol_ops.attach_volume(all_volume_uuid, vm_inv.uuid)\r\n\r\n vm.destroy()\r\n vm.check()\r\n\r\n vol_ops.delete_disk_offering(all_volume_offering_uuid)\r\n vol_ops.delete_disk_offering(rw_volume_offering_uuid)\r\n vol_ops.delete_disk_offering(volume_offering_3.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_4.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_5.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_6.uuid)\r\n vol_ops.delete_volume(all_volume_uuid)\r\n vol_ops.delete_volume(rw_volume_uuid)\r\n vol_ops.delete_volume(volume_uuid_3)\r\n vol_ops.delete_volume(volume_uuid_4)\r\n vol_ops.delete_volume(volume_uuid_5)\r\n vol_ops.delete_volume(volume_uuid_6)\r\n vm_ops.delete_instance_offering(instance_offering_uuid)\r\n test_util.test_pass('Create VM with volumes and detach/attach and after reboot and detach/attach Test Success')\r\n\r\n#Will be called only if exception happens in test().\r\ndef error_cleanup():\r\n global vm, all_volume_offering_uuid, rw_volume_offering_uuid, all_volume_uuid, rw_volume_uuid, volume_offering_3, volume_offering_4, volume_offering_5, volume_offering_6 \r\n global instance_offering_uuid, volume_uuid_3, volume_uuid_4, volume_uuid_5, volume_uuid_6\r\n if vm:\r\n vm.destroy()\r\n vol_ops.delete_disk_offering(all_volume_offering_uuid)\r\n vol_ops.delete_disk_offering(rw_volume_offering_uuid)\r\n vol_ops.delete_disk_offering(volume_offering_3.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_4.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_5.uuid)\r\n vol_ops.delete_disk_offering(volume_offering_6.uuid)\r\n vol_ops.delete_volume(all_volume_uuid)\r\n vol_ops.delete_volume(rw_volume_uuid)\r\n vol_ops.delete_volume(volume_uuid_3)\r\n vol_ops.delete_volume(volume_uuid_4)\r\n vol_ops.delete_volume(volume_uuid_5)\r\n vol_ops.delete_volume(volume_uuid_6)\r\n vm_ops.delete_instance_offering(instance_offering_uuid)\r\n","sub_path":"integrationtest/vm/basic/test_crt_vm_with_volumes_and_detach_attach_reboot_detach_attach_volume.py","file_name":"test_crt_vm_with_volumes_and_detach_attach_reboot_detach_attach_volume.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"317489287","text":"from argparse import ArgumentParser\nimport json\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Collection\n\nfrom coupledmodeldriver.configure import ModelJSON\nfrom coupledmodeldriver.generate.adcirc.base import ADCIRCJSON\nfrom coupledmodeldriver.generate.adcirc.check import (\n check_adcirc_completion,\n collect_adcirc_errors,\n CompletionStatus,\n)\nfrom coupledmodeldriver.utilities import convert_value\n\nMODELS = {model.name.lower(): model for model in ModelJSON.__subclasses__()}\n\n\ndef parse_check_completion_arguments():\n argument_parser = ArgumentParser()\n argument_parser.add_argument(\n 'directory',\n nargs='*',\n default=Path.cwd(),\n help='directory containing model run configuration',\n )\n argument_parser.add_argument('--model', help='model that is running, one of: `ADCIRC`')\n argument_parser.add_argument(\n '--verbose', action='store_true', help='list all errors and problems with runs'\n )\n\n arguments = argument_parser.parse_args()\n\n model = arguments.model\n if model is not None:\n model = MODELS[model.lower()]\n\n directory = convert_value(arguments.directory, [Path])\n if len(directory) == 1:\n directory = directory[0]\n\n return {\n 'directory': directory,\n 'model': model,\n 'verbose': arguments.verbose,\n }\n\n\ndef check_completion(\n directory: PathLike = None, model: ModelJSON = None, verbose: bool = False\n):\n if directory is None:\n directory = Path.cwd()\n elif not isinstance(directory, Path) and (\n not isinstance(directory, Collection) or isinstance(directory, str)\n ):\n directory = Path(directory)\n\n if model is None:\n model = ADCIRCJSON\n\n completion_status = {}\n\n if isinstance(directory, Collection):\n for subdirectory in directory:\n completion_status[subdirectory.name] = check_completion(\n directory=subdirectory, model=model, verbose=verbose\n )\n elif isinstance(directory, Path):\n subdirectories = [member.name for member in directory.iterdir()]\n if 'spinup' in subdirectories:\n completion_status.update(\n check_completion(directory=directory / 'spinup', model=model, verbose=verbose)\n )\n if 'runs' in subdirectories:\n completion_status['runs'] = {}\n for run_directory in (directory / 'runs').iterdir():\n completion_status['runs'].update(\n check_completion(directory=run_directory, model=model, verbose=verbose)\n )\n else:\n if model == ADCIRCJSON:\n if verbose:\n completion = collect_adcirc_errors(directory=directory)\n percentage = completion['completion_percentage']\n else:\n completion, percentage = check_adcirc_completion(directory=directory)\n\n if isinstance(completion, CompletionStatus):\n completion = f'{completion.value} - {percentage}%'\n\n completion_status[directory.name] = completion\n\n return completion_status\n\n\ndef main():\n completion_status = check_completion(**parse_check_completion_arguments())\n print(json.dumps(completion_status, indent=4))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"coupledmodeldriver/client/check_completion.py","file_name":"check_completion.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"66398047","text":"# Reproduce Table 4 from Neely, Rapach, Zhou (2011)\n#\n# Larry Takeuchi\n# first version: 12/02/2015\n#\n# Note: uses simple equity premium (not log equity premium)\n\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport numpy as np\nimport statsmodels.formula.api as smf\nfrom IPython.display import display, HTML\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n#from oos_forecast import oos_forecast\nfrom perform_cw_test import perform_cw_test\nfrom perform_asset_allocation import perform_asset_allocation\nfrom oos_pc_forecast import oos_pc_forecast\n\n# -----------------------------------------------------------------------------\n# Set parameters\n\n# set date range (Initial: 1950-12 to 1965-12, OOS: 1966-01 to 2011-12 for NRZ)\nbeg_date_init = '1950-12'\nbeg_date_oos = '1966-01'\nend_date_oos = '2011-12'\n#end_date_oos = '2014-12'\n\n# Risk aversion paramter\ngamma_MV = 5\n\n# transactions cost in basis points\nc_bp = 50\n\n# size of rolling window for vol forecast\nwindow_size = 5 * 12\n\n\n# -----------------------------------------------------------------------------\n# Load data\npath_name = '/Users/ltakeuchi/Python/stockpredict/data/'\nfile_name = 'nrz_fundamentals_monthly.pkl'\n#file_name = 'fundamentals_monthly.pkl'\ndf = pd.read_pickle(path_name + file_name)\n\n# load NBER recession indicator\nnber = pd.read_pickle(path_name + 'nber_monthly.pkl')\n\n# add recession dummies to df\ndf = pd.concat([df, nber], axis=1)\n\nfile_name = 'nrz_technical_variables.pkl'\ntech = pd.read_pickle(path_name + file_name)\ndf = pd.concat([df, tech], axis=1)\n\n# change sign so that expected slope coefficents are positive as in NRZ\nfor i in ['ntis', 'tbl', 'lty', 'infl']:\n df[i] = df[i] * -1\n\necon_var = ['dp', 'dy', 'ep', 'de', 'rvol', 'bm', 'ntis', 'tbl', 'lty', 'ltr',\n 'tms','dfy','dfr','infl']\ntech_var = ['ma_1_9', 'ma_1_12', 'ma_2_9', 'ma_2_12', 'ma_3_9', 'ma_3_12',\n 'mom_9', 'mom_12', 'vol_1_9', 'vol_1_12', 'vol_2_9', 'vol_2_12',\n 'vol_3_9', 'vol_3_12']\nall_var = econ_var + tech_var\n\n\n# get data for specified date range\ndf_sub = df[beg_date_init:end_date_oos]\n\n# Expanding window historical average forecast for equity premium\ndf['ha_mean'] = Series(pd.expanding_mean(df_sub['equity_premium']/100,\n min_periods = window_size).shift(1), index = df_sub.index)\n\n# Rolling window historical average forecast for equity premium variance\n# note degree of freedom adjusted to match NRZ\ndf['ha_var'] = Series(pd.rolling_var(df_sub['equity_premium']/100, window_size,\n min_periods = window_size, ddof = 0).shift(1), index = df_sub.index)\n\n\n# Perform asset allocation using historical average forecasts using c_bp = 0\n# all months\ndf_sub = df[beg_date_oos:end_date_oos] \nha_results = perform_asset_allocation(df_sub['equity_premium']/100, df_sub['Rfree'],\n\t df_sub['ha_mean'], df_sub['ha_var'], gamma_MV, 0)\n# expansion months\ndf_exp = df_sub[df_sub['recession']==0]\nha_results_exp = perform_asset_allocation(df_exp['equity_premium']/100, df_exp['Rfree'],\n\t df_exp['ha_mean'], df_exp['ha_var'], gamma_MV, 0)\n# expansion months\ndf_rec = df_sub[df_sub['recession']==1]\nha_results_rec = perform_asset_allocation(df_rec['equity_premium']/100, df_rec['Rfree'],\n\t df_rec['ha_mean'], df_rec['ha_var'], gamma_MV, 0)\n\n\n# create table of results for historical average forecast\nha = {}\nfor i in ['CER', 'CER_exp', 'CER_rec', 'Sharpe ratio', 'turnover (%)']:\n ha[i] = []\nha['CER'] = ha_results['avg_utility'] * 1200\nha['CER_exp'] = ha_results_exp['avg_utility'] * 1200\nha['CER_rec'] = ha_results_rec['avg_utility'] * 1200\nha['Sharpe ratio'] = ha_results['SR']\nha['turnover (%)'] = ha_results['avg_turnover'] * 100\n\npd.options.display.float_format = '{:.4f}'.format\ntable4 = DataFrame(ha, index=['HA'])\ntable4 = table4[['CER', 'CER_exp', 'CER_rec', 'Sharpe ratio', 'turnover (%)']]\ndisplay(table4)\n\n\n# Perform asset allocation using bivariate regression forecasts\n\n# initialize dictionary of lists\nd = {}\nfor i in ['CER', 'CER_exp', 'CER_rec', 'Sharpe ratio', 'rel turnover',\n 'CER w/tc', 'Sharpe w/tc']:\n d[i] = []\n\n# lag the x variables\ndf[all_var] = df[all_var].shift(1)\n\n#______________________________________________________________________________\n# to match NRZ, increment beg_date_init by one month (since we lag the X vars)\nbeg_date_init = '1951-01' \n\n\nfor var_list in ['pc_econ', 'pc_tech', 'pc_all']:\n if var_list == 'pc_econ':\n max_k = 3\n prediction = oos_pc_forecast('equity_premium', econ_var, df, max_k, beg_date_init,\n beg_date_oos, end_date_oos)\n elif var_list == 'pc_tech':\n max_k = 1\n prediction = oos_pc_forecast('equity_premium', tech_var, df, max_k, beg_date_init,\n beg_date_oos, end_date_oos)\n elif var_list == 'pc_all':\n max_k = 4\n prediction = oos_pc_forecast('equity_premium', all_var, df, max_k, beg_date_init,\n beg_date_oos, end_date_oos)\n\n results = perform_asset_allocation(df_sub['equity_premium']/100, df_sub['Rfree'],\n prediction['y_forecast']/100, df_sub['ha_var'], gamma_MV, 0)\n d['CER'].append((results['avg_utility'] - ha_results['avg_utility']) * 1200)\n d['Sharpe ratio'].append(results['SR'])\n d['rel turnover'].append(results['avg_turnover'] / ha_results['avg_turnover'])\n\n results_exp = perform_asset_allocation(df_exp['equity_premium']/100, df_exp['Rfree'],\n prediction['y_forecast'][df_sub['recession']==0]/100, df_exp['ha_var'], gamma_MV, 0)\n d['CER_exp'].append((results_exp['avg_utility'] - ha_results_exp['avg_utility']) * 1200)\n\n results_rec = perform_asset_allocation(df_rec['equity_premium']/100, df_rec['Rfree'],\n prediction['y_forecast'][df_sub['recession']==1]/100, df_rec['ha_var'], gamma_MV, 0)\n d['CER_rec'].append((results_rec['avg_utility'] - ha_results_rec['avg_utility']) * 1200)\n\n # with transactions costs\n results_tc = perform_asset_allocation(df_sub['equity_premium']/100, df_sub['Rfree'],\n prediction['y_forecast']/100, df_sub['ha_var'], gamma_MV, c_bp)\n ha_results_tc = perform_asset_allocation(df_sub['equity_premium']/100, df_sub['Rfree'],\n df_sub['ha_mean'], df_sub['ha_var'], gamma_MV, c_bp)\n d['CER w/tc'].append((results_tc['avg_utility'] - ha_results_tc['avg_utility']) * 1200)\n d['Sharpe w/tc'].append(results_tc['SR'])\n\n\n# create and display Table 4, panels B and C\ntable4a = DataFrame(d, index=['pc_econ', 'pc_tech', 'pc_all'])\ntable4a = table4a[['CER', 'CER_exp', 'CER_rec', 'Sharpe ratio', 'rel turnover',\n 'CER w/tc', 'Sharpe w/tc']]\ndisplay(table4a)\n\n\n\n\n\n","sub_path":"create_table4_pc.py","file_name":"create_table4_pc.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"336348419","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom django.db import connection\n\n\nclass GetData(object):\n def dictfetchall(self, cursor):\n desc = cursor.description\n return [\n dict(zip([col[0] for col in desc], row))\n for row in cursor.fetchall()\n ]\n\n def get_subisidy(self, pref_name=None, city_name=None, num=5):\n \"\"\"\n 助成金情報を取得する\n :param pref_name:\n :param city_name:\n :return:\n \"\"\"\n cursor = connection.cursor()\n # cursor.execute(\n # \"SELECT * FROM subsidy WHERE pref_name = '\" + pref_name + \"' AND city = '\" + city_name + \"'\")\n cursor.execute(\n \"SELECT subsidy::int, content, url FROM subsidy WHERE pref_name = '\" + pref_name + \"' LIMIT \" + str(\n num) + \"\")\n return list(self.dictfetchall(cursor))\n\n def get_sarary(self, pref_name=None):\n \"\"\"\n 都道府県ごとの平均給料を取得する\n :param pref_name:\n :return:\n \"\"\"\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM sarary\")\n return pd.DataFrame(list(self.dictfetchall(cursor)))\n\n def get_main_content(self):\n \"\"\"\n メインコンテンツ\n :return:\n \"\"\"\n cursor = connection.cursor()\n cursor.execute(\"SELECT id, main_title, main_text, main_picture, content.pref_name,pref_code, content.city_name, city_code FROM content INNER JOIN resas_code ON content.pref_name=resas_code.pref_name and content.city_name = resas_code.city_name\")\n return list(self.dictfetchall(cursor))\n\n def get_detail_content(self, id):\n \"\"\"\n 詳細コンテンツ\n :return:\n \"\"\"\n id = str(id)\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM content WHERE id= \" + id + \"\")\n return list(self.dictfetchall(cursor))\n","sub_path":"main/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"574851625","text":"from keras.models import load_model\r\nfrom keras.utils import np_utils\r\nimport os\r\nimport pickle\r\n\r\n\"\"\"\r\n测试模型精度\r\n\"\"\"\r\nif __name__ == '__main__':\r\n model = load_model('./CIFAR10_normal/CIFAR10_model.h5')\r\n\r\n cwd = os.getcwd()\r\n datafile = cwd + '/CIFAR_10_normal.pkl' # 标准化后\r\n # datafile = cwd + '/CIFAR_10_mean.pkl' #零均值化后\r\n (X_train, y_train), (X_test, y_test) = pickle.load(open(datafile, \"rb\"))\r\n print(model.metrics_names)\r\n y_test = np_utils.to_categorical(y_test, 10 )\r\n test = model.evaluate(x=X_test,y=y_test,batch_size=128)\r\n print(test[0]) #loss\r\n print(test[1]) #acc","sub_path":"testModel.py","file_name":"testModel.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"466093573","text":"#Importing modules\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import ensemble\nfrom sklearn.metrics import mean_absolute_error\n\n# Step-2 Importing dataset\n#df = pd.read_csv(\"E:\\VSCODE\\Python\\ML\\Proj1\\Melbourne_housing_FULL.csv\\Melbourne_housing_FULL.csv\")\ndf = pd.read_csv(\"C:\\\\Users\\\\n0278588\\Desktop\\\\Melbourne_housing_FULL.csv\")\n#print(df.columns)\n\n# Step-3 Scrubbing\n# As part of scrubbing here w eare deleting unwanted columns\ndel df[\"Address\"]\ndel df[\"Method\"]\ndel df[\"SellerG\"]\ndel df[\"Date\"]\ndel df[\"Postcode\"]\ndel df[\"Lattitude\"]\ndel df[\"Longtitude\"]\ndel df[\"Regionname\"]\ndel df[\"Propertycount\"]\n\n##Next scrubbing is do remove the missing values\ndf.dropna(axis=0, how=\"any\", thresh=None, subset=None, inplace=True)\n\n##Converting Non-Numeric into Nuemeric using Hot-Encoding\nfeatures_df = pd.get_dummies(df, columns=[\"Suburb\", \"CouncilArea\", \"Type\"])\n\n##Remove the Proce column bcz its going to be our Target(y) and\n##currenlty its with our feature(X)\ndel features_df[\"Price\"]\n\n##Now create X and y arrays from the dataset using .values\nX = features_df.values\ny = df[\"Price\"].values\n\n#Step-4 Split the Dataset\n##We are splitting with standard 70/30 splitting ratio\n\n#X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,shuffle=True) #Shuffle will not work with scikit-leanr 0.18\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)\n\n#Step-5 Select ALgorithm and configure hyperparametes\nmodel = ensemble.GradientBoostingRegressor(\n n_estimators= 150,\n learning_rate= 0.1,\n max_depth= 30,\n min_samples_split= 4,\n min_samples_leaf= 6,\n max_features= 0.6,\n loss= 'huber'\n\n)\n\n##Train the model by using the Fit command\nprint(\"Data modelling in progress..\")\nmodel.fit(X_train,y_train)\n\n#Step-6 Evalute the Results\n##We are using MAE for evaluting the errors in prediction\nmse = mean_absolute_error(y_train,model.predict(X_train))\nprint(f\"Training Set Mean Absolute Error: {mse}\")\n\n##MAE with test Data\nmse = mean_absolute_error(y_test,model.predict(X_test))\nprint(f\"Test Set Mean Absolute Error: {mse}\")\n\nprint(\"\\nModelling Completed\")\n\n\n","sub_path":"ClassicalML/Proj1-GradientBoosting-MelbourneHousingPrice/gradientBoosting.py","file_name":"gradientBoosting.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"472067405","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 27 18:08:44 2015\n\nAuthor: David Evans\n\nExample Usage of LakeModel in lake\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom lake import LakeModel, LakeModelAgent, LakeModel_Equilibrium\nimport pandas as pd\n#Use Matplotlib to Adjust style#\nimport matplotlib\nmatplotlib.style.use('ggplot')\n\n#Initialize Parameters\nalpha = 0.013\nlamb = 0.283#0.2486\nb = 0.0124\nd = 0.00822\ng = b-d\nN0 = 150.\ne0 = 0.92\nu0 = 1-e0\nT = 50\n\nLM = LakeModel(lamb,alpha,b,d)\n\n#Find steady state\nxbar = LM.find_steady_state()\n\n#simulate stocks for T periods\nE0 = e0*N0\nU0 = u0*N0\nX_path = np.vstack( LM.simulate_stock_path([E0,U0],T) )\nplt.figure(figsize=[10,9])\nplt.subplot(3,1,1)\nplt.plot(X_path[:,0])\nplt.title(r'Employment')\nplt.subplot(3,1,2)\nplt.plot(X_path[:,1])\nplt.title(r'Unemployment')\nplt.subplot(3,1,3)\nplt.plot(X_path.sum(1))\nplt.title(r'Labor Force')\nplt.tight_layout()\nplt.savefig('example_stock_path.png')\n\n#simulate rates for T periods\n\nx_path = np.vstack( LM.simulate_rate_path([e0,u0],T) )\nplt.figure(figsize=[10,6])\nplt.subplot(2,1,1)\nplt.plot(x_path[:,0])\nplt.hlines(xbar[0],0,T,'r','--')\nplt.title(r'Employment Rate')\nplt.subplot(2,1,2)\nplt.plot(x_path[:,1])\nplt.hlines(xbar[1],0,T,'r','--')\nplt.title(r'Unemployment Rate')\nplt.tight_layout()\nplt.savefig('example_rate_path.png')\n\n\n#Simulate a single agent\nT = 5000\n\nA = LakeModelAgent(lamb,alpha)\npi_bar = A.compute_ergodic().flatten()\n\nsHist = np.hstack(A.simulate(1,T))\n\npi_u = np.cumsum(sHist)/(np.arange(T) + 1.) # time spent in unemployment after T periods\npi_e = 1- pi_u #time spent employed\n\nplt.figure(figsize=[10,6])\nplt.subplot(2,1,1)\nplt.plot(range(50,T),pi_e[50:])\nplt.hlines(pi_bar[0],0,T,'r','--')\nplt.title('Percent of Time Employed')\nplt.subplot(2,1,2)\nplt.plot(range(50,T),pi_u[50:])\nplt.hlines(pi_bar[1],0,T,'r','--')\nplt.xlabel('Time')\nplt.title('Percent of Time Unemployed')\nplt.tight_layout()\nplt.savefig('example_averages.png')\n\n\n#==============================================================================\n# Now add McCall Search Model\n#==============================================================================\nfrom scipy.stats import norm\n\n#using quaterly data\nalpha_q = (1-(1-alpha)**3) # alpha is monthly and alpha_q is quarterly\ngamma = 1.\n\nlogw_dist = norm(np.log(20.),1)\nw = np.linspace(0.,175,201)# wage grid\n\n#compute probability of each wage level\ncdf = logw_dist.cdf(np.log(w))\npdf = cdf[1:]-cdf[:-1]\npdf /= pdf.sum()\nw = (w[1:] + w[:-1])/2\n\n#Find the quilibirum\nLME = LakeModel_Equilibrium(alpha_q,gamma,0.99,2.00,pdf,w)\n\n#possible levels of unemployment insurance\ncvec = np.linspace(1.,75,25)\nT,W,U,EV,pi = map(np.vstack,zip(* [LME.find_steady_state_tax(c) for c in cvec]))\nW= W[:]\nT = T[:]\nU = U[:]\nEV = EV[:]\ni_max = np.argmax(W)\n\nplt.figure(figsize=[10,6])\nplt.subplot(221)\nplt.plot(cvec,W)\nplt.xlabel(r'$c$')\nplt.title(r'Welfare' )\naxes = plt.gca()\nplt.vlines(cvec[i_max],axes.get_ylim()[0],max(W),'k','-.')\n\nplt.subplot(222)\nplt.plot(cvec,T)\naxes = plt.gca()\nplt.vlines(cvec[i_max],axes.get_ylim()[0],T[i_max],'k','-.')\nplt.xlabel(r'$c$')\nplt.title(r'Taxes' )\n\n\nplt.subplot(223)\nplt.plot(cvec,pi[:,0])\naxes = plt.gca()\nplt.vlines(cvec[i_max],axes.get_ylim()[0],pi[i_max,0],'k','-.')\nplt.xlabel(r'$c$')\nplt.title(r'Employment Rate' )\n\n\nplt.subplot(224)\nplt.plot(cvec,pi[:,1])\naxes = plt.gca()\nplt.vlines(cvec[i_max],axes.get_ylim()[0],pi[i_max,1],'k','-.')\nplt.xlabel(r'$c$')\nplt.title(r'Unemployment Rate' )\nplt.tight_layout()\nplt.savefig('welfare_plot.png')\n","sub_path":"sub/lake_model/lakemodel_example.py","file_name":"lakemodel_example.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"455429426","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\nColumbia's COMS W4111.003 Introduction to Databases\nExample Webserver\n\nTo run locally:\n\n python server.py\n\nGo to http://localhost:8111 in your browser.\n\nA debugger such as \"pdb\" may be helpful for debugging.\nRead about it online.\n\"\"\"\n\nimport os\nfrom sqlalchemy import *\nfrom sqlalchemy.pool import NullPool\nfrom flask import Flask, request, render_template, g, redirect, Response\ntmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')\nPIC_FOLDER = os.path.join('static','pic')\napp = Flask(__name__, template_folder=tmpl_dir)\napp.config ['UPLOAD_FOLDER'] = PIC_FOLDER\n#\n# The following is a dummy URI that does not connect to a valid database. You will need to modify it to connect to your Part 2 database in order to use the data.\n#\n# XXX: The URI should be in the format of: \n#\n# postgresql://USER:PASSWORD@104.196.152.219/proj1part2\n#\n# For example, if you had username biliris and password foobar, then the following line would be:\n#\n# DATABASEURI = \"postgresql://biliris:foobar@104.196.152.219/proj1part2\"\n#\nDATABASEURI = \"postgresql://zd2263:123456@35.196.73.133/proj1part2\"\n\n\n#\n# This line creates a database engine that knows how to connect to the URI above.\n#\nengine = create_engine(DATABASEURI)\n\n#\n# Example of running queries in your database\n# Note that this will probably not work if you already have a table named 'test' in your database, containing meaningful data. This is only an example showing you how to run queries in your database using SQLAlchemy.\n#\n\n\n@app.before_request\ndef before_request():\n \"\"\"\n This function is run at the beginning of every web request \n (every time you enter an address in the web browser).\n We use it to setup a database connection that can be used throughout the request.\n\n The variable g is globally accessible.\n \"\"\"\n try:\n g.conn = engine.connect()\n except:\n print (\"uh oh, problem connecting to database\")\n import traceback; traceback.print_exc()\n g.conn = None\n\n@app.teardown_request\ndef teardown_request(exception):\n \"\"\"\n At the end of the web request, this makes sure to close the database connection.\n If you don't, the database could run out of memory!\n \"\"\"\n try:\n g.conn.close()\n except Exception as e:\n pass\n\n\n#\n# @app.route is a decorator around index() that means:\n# run index() whenever the user tries to access the \"/\" path using a GET request\n#\n# If you wanted the user to go to, for example, localhost:8111/foobar/ with POST or GET then you could use:\n#\n# @app.route(\"/foobar/\", methods=[\"POST\", \"GET\"])\n#\n# PROTIP: (the trailing / in the path is important)\n# \n# see for routing: http://flask.pocoo.org/docs/0.10/quickstart/#routing\n# see for decorators: http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/\n#\n@app.route('/',methods=['GET', 'POST'])\ndef index():\n \"\"\"\n request is a special object that Flask provides to access web request information:\n\n request.method: \"GET\" or \"POST\"\n request.form: if the browser submitted a form, this contains the data in the form\n request.args: dictionary of URL arguments, e.g., {a:1, b:2} for http://localhost?a=1&b=2\n\n See its API: http://flask.pocoo.org/docs/0.10/api/#incoming-request-data\n \"\"\"\n # DEBUG: this is debugging code to see what request looks like\n print (request.args)\n # Flask uses Jinja templates, which is an extension to HTML where you can\n # pass data to a template and dynamically generate HTML based on the data\n # (you can think of it as simple PHP)\n # documentation: https://realpython.com/blog/python/primer-on-jinja-templating/\n full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'genshin.jpg')\n if request.method == 'GET':\n return render_template('index.html', Login_image=full_filename)\n else:\n uid = request.form.get('uid')\n uname = request.form.get('uname')\n submit = request.form.get('login')\n if submit == 'login':\n if uid == '' or uname == '':\n return render_template('index.html', Login_image=full_filename, wrong='Please input both uid and uname')\n if not uid.isdigit():\n return render_template('index.html', Login_image=full_filename, wrong='UID must be integer')\n if len(uid) > 5:\n wrongdigit = \"The input number's length has to be smaller than 6\"\n return render_template('index.html', wrong=wrongdigit, Login_image=full_filename)\n cursor = g.conn.execute(\"SELECT * from Users where uid=%s and uname=%s\", (uid, uname))\n check = cursor.fetchall()\n cursor.close()\n if len(check) == 1:\n return redirect('/search')\n else:\n return render_template('index.html', Login_image=full_filename, wrong='Wrong login information')\n\n\n@app.route('/search',methods=['GET', 'POST'])\ndef search():\n print(request.args)\n full_filename = os.path.join(app.config['UPLOAD_FOLDER'],'Liyue.jpg')\n return render_template('search.html',Liyue_image = full_filename)\n\n@app.route('/characters',methods=['GET', 'POST'])\ndef characters():\n print (request.args)\n if request.method == 'GET':\n cursor = g.conn.execute(\"SELECT * from Characters C INNER JOIN Nations N on C.nid=N.nid limit 5\")\n characters = []\n for result in cursor:\n characters.append(result) # can also be accessed using result\n context = dict(data=characters)\n cursor.close()\n return render_template(\"characters.html\",**context)\n else:\n getcol=[]\n getcol.append(request.form.get('cname'))\n getcol.append(request.form.getlist('elements'))\n getcol.append(request.form.getlist('character_rarity'))\n getcol.append(request.form.getlist('weapon_type'))\n getcol.append(request.form.get('birthday'))\n getcol.append(request.form.getlist('nid'))\n submit = request.form.get('search')\n if submit == 'search':\n cols = ['cname', 'elements','character_rarity','weapon_type','birthday','nation_name']\n dic = {}\n i=1\n for col in cols:\n if getcol[i-1]!='' and getcol[i-1]!=[]:\n dic[col]=getcol[i-1]\n i+=1\n sql = 'SELECT * from Characters C INNER JOIN Nations N on C.nid=N.nid'\n if len(dic) > 0:\n sql = sql + ' where '\n data = []\n para = []\n for col in dic:\n if (col=='cname' or col=='birthday'):\n data.append(col + '=' + '%s')\n para.append(dic[col])\n else:\n part= []\n for n in dic[col]:\n part.append(col + '=' + '%s')\n para.append(n)\n data.append('(' + ' or '.join(part) + ')')\n sql = sql + ' and '.join(data)\n cursor = g.conn.execute(sql,para)\n characters = []\n for result in cursor:\n characters.append(result) # can also be accessed using result[0]\n context = dict(data=characters)\n cursor.close()\n return render_template('characters.html',**context)\n\n@app.route('/weapons',methods=['GET', 'POST'])\ndef weapons():\n print(request.args)\n if request.method == 'GET':\n sql=\"SELECT wname,weapon_rarity,type,weapon_base_attack,extra_attribute,value,\"+\\\n \"case when extra_attribute='Elemental Mastery' or cast(value as varchar)='0' then cast(value as varchar) else (cast(value as varchar)||'%%') end AS valuenew \"+\\\n \"from Weapons W limit 5\"\n cursor = g.conn.execute(sql)\n characters = []\n for result in cursor:\n characters.append(result) # can also be accessed using result\n context = dict(data=characters)\n cursor.close()\n return render_template(\"weapons.html\", **context)\n else:\n getcol = []\n getcol.append(request.form.get('wname'))\n getcol.append(request.form.getlist('rarity'))\n getcol.append(request.form.getlist('weapon_type'))\n getcol.append(request.form.getlist('extra_attribute'))\n submit = request.form.get('search')\n if submit == 'search':\n cols = ['wname', 'weapon_rarity', 'type', 'extra_attribute']\n dic = {}\n i = 1\n for col in cols:\n if getcol[i - 1] != '' and getcol[i - 1] != []:\n dic[col] = getcol[i - 1]\n i += 1\n sql = \"SELECT wname,weapon_rarity,type,weapon_base_attack,extra_attribute,value,\" + \\\n \"case when extra_attribute='Elemental Mastery' or cast(value as varchar)='0' then cast(value as varchar) else (cast(value as varchar)||'%%') end AS valuenew \" + \\\n \"from Weapons W \"\n if len(dic) > 0:\n sql = sql + ' where '\n data = []\n para = []\n for col in dic:\n if (col == 'wname'):\n data.append(col + '=' + '%s')\n para.append(dic[col])\n else:\n part = []\n for n in dic[col]:\n part.append(col + '=' + '%s')\n para.append(n)\n data.append('(' + ' or '.join(part) + ')')\n sql = sql + ' and '.join(data)\n cursor = g.conn.execute(sql, para)\n weapons = []\n for result in cursor:\n weapons.append(result)\n context = dict(data=weapons)\n cursor.close()\n return render_template('weapons.html', **context)\n\n@app.route('/users',methods=['GET', 'POST'])\ndef users():\n print(request.args)\n if request.method == 'GET':\n cursor = g.conn.execute(\"SELECT * from Users limit 5\")\n users = []\n for result in cursor:\n users.append(result) # can also be accessed using result\n context = dict(data=users)\n cursor.close()\n return render_template(\"users.html\", **context)\n else:\n getcol = []\n inuid=request.form.get('uid')\n getcol.append(inuid)\n getcol.append(request.form.get('uname'))\n inulevel=request.form.get('ulevel')\n getcol.append(inulevel)\n inday=request.form.get('activate_day')\n getcol.append(inday)\n inachievements=request.form.get('number_of_achievements')\n getcol.append(inachievements)\n getcol.append(request.form.get('deep_spiral'))\n submit = request.form.get('search')\n ints = [len(inuid), len(inulevel), len(inday), len(inachievements)]\n if submit == 'search':\n if not (inuid.isdigit() or inuid == ''):\n context = dict(data=[])\n return render_template('users.html', wrongu='must input integer', **context)\n if not (inulevel.isdigit() or inulevel==''):\n context = dict(data=[])\n return render_template('users.html', wrongl='must input integer', **context)\n if not (inday.isdigit() or inday==''):\n context = dict(data=[])\n return render_template('users.html', wrongd='must input integer', **context)\n if not (inachievements.isdigit() or inachievements == ''):\n context = dict(data=[])\n return render_template('users.html', wronga='must input integer', **context)\n if max(ints) > 5:\n wrongdigit = \"The input number's length has to be smaller than 6\"\n return render_template('users.html', wrongdigit=wrongdigit, data=[])\n else:\n cols = ['uid','uname', 'ulevel', 'activate_day', 'number_of_achievements','deep_spiral']\n dic = {}\n i = 1\n for col in cols:\n if getcol[i - 1] != '':\n dic[col] = getcol[i - 1]\n i += 1\n sql = 'SELECT * from Users'\n if len(dic) > 0:\n sql = sql + ' where '\n data = []\n para = []\n for col in dic:\n data.append(col + '=' + '%s')\n if col!='deep_spiral':\n para.append(dic[col])\n else:\n para.append(' '+dic[col])\n sql = sql + ' and '.join(data)\n cursor = g.conn.execute(sql, para)\n weapons = []\n for result in cursor:\n weapons.append(result)\n context = dict(data=weapons)\n cursor.close()\n return render_template('users.html', **context)\n\n@app.route('/owning',methods=['GET', 'POST'])\ndef owning():\n print(request.args)\n if request.method == 'GET':\n cursor = g.conn.execute(\"SELECT O.uid,uname,cname,elements,character_rarity,clevel,friendship,constellation from Owning O, Users U, Characters C where O.uid=U.uid and O.cid=C.cid limit 5\")\n characters = []\n for result in cursor:\n characters.append(result) # can also be accessed using result\n context = dict(data=characters)\n cursor.close()\n return render_template(\"owning.html\", **context)\n else:\n getcol = []\n inuid = request.form.get('uid')\n getcol.append(inuid)\n getcol.append(request.form.get('uname'))\n getcol.append(request.form.get('cname'))\n getcol.append(request.form.getlist('elements'))\n getcol.append(request.form.getlist('character_rarity'))\n inclevel = request.form.get('clevel')\n getcol.append(inclevel)\n infrd = request.form.get('friendship')\n getcol.append(infrd)\n incon = request.form.get('constellation')\n getcol.append(incon)\n submit = request.form.get('search')\n ints = [len(inuid), len(inclevel), len(infrd), len(incon)]\n if submit == 'search':\n if not (inuid.isdigit() or inuid == ''):\n context = dict(data=[])\n return render_template('owning.html', wrongu='must input integer', **context)\n if not (inclevel.isdigit() or inclevel == ''):\n context = dict(data=[])\n return render_template('owning.html', wrongl='must input integer', **context)\n if not (infrd.isdigit() or infrd == ''):\n context = dict(data=[])\n return render_template('owning.html', wrongf='must input integer', **context)\n if not (incon.isdigit() or incon == ''):\n context = dict(data=[])\n return render_template('owning.html', wrongc='must input integer', **context)\n if max(ints) > 5:\n wrongdigit = \"The input number's length has to be smaller than 6\"\n return render_template('owning.html', wrongdigit=wrongdigit, data=[])\n else:\n cols = ['O.uid', 'uname', 'cname', 'elements', 'character_rarity', 'clevel', 'friendship', 'constellation']\n dic = {}\n i = 1\n for col in cols:\n if getcol[i - 1] != '' and getcol[i - 1] != []:\n dic[col] = getcol[i - 1]\n i += 1\n sql = 'SELECT O.uid,uname,cname,elements,character_rarity,clevel,friendship,constellation'\\\n +' from Owning O, Users U, Characters C where O.uid=U.uid and O.cid=C.cid'\n if len(dic) > 0:\n sql = sql + ' and '\n data = []\n para = []\n for col in dic:\n if (col == 'elements' or col == 'character_rarity'):\n part = []\n for n in dic[col]:\n part.append(col + '=' + '%s')\n para.append(n)\n data.append('(' + ' or '.join(part) + ')')\n else:\n data.append(col + '=' + '%s')\n para.append(dic[col])\n sql = sql + ' and '.join(data)\n cursor = g.conn.execute(sql, para)\n users = []\n for result in cursor:\n users.append(result)\n context = dict(data=users)\n cursor.close()\n return render_template('owning.html', **context)\n\n@app.route('/materials',methods=['GET', 'POST'])\ndef materials():\n print(request.args)\n if request.method == 'GET':\n sql=\"SELECT mname,location,nation_name,'Loc_materials' AS type \"+\\\n \",string_agg(cname,',') AS used_by_characters \"+\\\n \"from Materials M, Nations N, Locate L,Loc_materials Loc,Characters C, Level_up U \"+\\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"+\\\n \"Group by Loc.mid,mname,location,nation_name \"+\\\n \"limit 5\"\n cursor = g.conn.execute(sql)\n characters = []\n for result in cursor:\n characters.append(result)\n cursor.close()\n sql = \"SELECT mname,location,nation_name,'Talent_level_up_materials' AS type,open_day \"+\\\n \",string_agg(cname,',') AS used_by_characters \"+\\\n \"from Materials M, Nations N, Locate L,Talent_level_up_materials Loc,Characters C, Level_up U \"+\\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"+\\\n \"Group by Loc.mid,mname,location,nation_name,open_day \"+\\\n \"limit 5\"\n cursor = g.conn.execute(sql)\n characters2 = []\n for result in cursor:\n characters2.append(result)\n cursor.close()\n return render_template(\"materials.html\", data_l=characters, data_t=characters2)\n else:\n getcol = []\n getcol.append(request.form.get('mname'))\n getcol.append(request.form.get('location'))\n getcol.append(request.form.getlist('nid'))\n intype = request.form.getlist('type')\n days=request.form.getlist('open_day')\n getcol.append(days)\n getcol.append(request.form.get('cname'))\n submit = request.form.get('search')\n if submit == 'search':\n cols = ['mname', 'location', 'nation_name', 'open_day', 'cname']\n dic = {}\n i = 1\n for col in cols:\n if getcol[i - 1] != '' and getcol[i - 1] != []:\n dic[col] = getcol[i - 1]\n i += 1\n if (intype == []) or ('Loc_materials' in intype):\n if 'cname' not in dic:\n sql1 = \"SELECT mname,location,nation_name,'Loc_materials' AS type \" + \\\n \",string_agg(cname,',') AS used_by_characters \" + \\\n \"from Materials M, Nations N, Locate L,Loc_materials Loc,Characters C, Level_up U \" + \\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"\n para = []\n else:\n sql1 =\"SELECT mname,location,nation_name,'Loc_materials' AS type \" + \\\n \",%s AS used_by_characters \" + \\\n \"from Materials M, Nations N, Locate L,Loc_materials Loc,Characters C, Level_up U \" + \\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"\n para = [dic['cname']]\n if (len(dic) > 1) or (('open_day' not in dic) and len(dic) > 0):\n sql1 = sql1 + ' and '\n data = []\n for col in dic:\n if (col!='open_day'):\n if (col == 'nation_name'):\n part = []\n for n in dic[col]:\n part.append(col + '=' + '%s')\n para.append(n)\n data.append('(' + ' or '.join(part) + ')')\n else:\n data.append(col + '=' + '%s')\n para.append(dic[col])\n sql1 = sql1 + ' and '.join(data)+ 'Group by Loc.mid,mname,location,nation_name'\n cursor1 = g.conn.execute(sql1, para)\n Loc = []\n for result in cursor1:\n Loc.append(result)\n context_l = Loc\n cursor1.close()\n if (intype != []) and ('Loc_materials' not in intype):\n context_l = []\n if (intype == []) or ('Talent_level_up_materials' in intype):\n if 'cname' not in dic:\n sql2 = \"SELECT mname,location,nation_name,'Talent_level_up_materials' AS type,open_day \" + \\\n \",string_agg(cname,',') AS used_by_characters \" + \\\n \"from Materials M, Nations N, Locate L,Talent_level_up_materials Loc,Characters C, Level_up U \" + \\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"\n para = []\n else:\n sql2 =\"SELECT mname,location,nation_name,'Talent_level_up_materials' AS type,open_day \" + \\\n \",%s AS used_by_characters \" + \\\n \"from Materials M, Nations N, Locate L,Talent_level_up_materials Loc,Characters C, Level_up U \" + \\\n \"where N.nid=L.nid and Loc.mid=M.mid and Loc.mid=L.mid and C.cid=U.cid and Loc.mid=U.mid \"\n para = [dic['cname']]\n if (len(dic) > 0):\n sql2 = sql2 + ' and '\n data = []\n for col in dic:\n if (col == 'nation_name'):\n part = []\n for n in dic[col]:\n part.append(col + '=' + '%s')\n para.append(n)\n data.append('(' + ' or '.join(part) + ')')\n elif (col == 'open_day'):\n part = []\n if '1' in dic[col]:\n part.append(col + \" like '%%1%%' \")\n if '2' in dic[col]:\n part.append(col + \" like '%%2%%' \")\n if '3' in dic[col]:\n part.append(col + \" like '%%3%%' \")\n if '4' in dic[col]:\n part.append(col + \" like '%%4%%' \")\n if '5' in dic[col]:\n part.append(col + \" like '%%5%%' \")\n if '6' in dic[col]:\n part.append(col + \" like '%%6%%' \")\n if '7' in dic[col]:\n part.append(col + \" like '%%7%%' \")\n data.append('(' + ' and '.join(part) + ')')\n else:\n data.append(col + '=' + '%s')\n para.append(dic[col])\n sql2 = sql2 + ' and '.join(data) + ' Group by Loc.mid,mname,location,nation_name,open_day'\n cursor2 = g.conn.execute(sql2, para)\n Talent= []\n for result in cursor2:\n Talent.append(result)\n context_t = Talent\n cursor2.close()\n if (intype != []) and ('Talent_level_up_materials' not in intype):\n context_t = []\n return render_template('materials.html', data_l=context_l, data_t=context_t)\n\n@app.route('/special',methods=['GET', 'POST'])\ndef special():\n def type_get(u_order, c_order, num_row=5):\n sql_1 = \"SELECT O.uid, uname, ulevel, activate_day, number_of_achievements, COUNT(*) AS owning_character_number, \" \\\n \"AVG(O.clevel) AS average_character_level, AVG(O.friendship) AS average_character_friendship \"+\\\n \"from Owning O, Users U, Characters C where O.uid=U.uid and O.cid=C.cid \" \\\n \"GROUP BY O.uid, uname, ulevel, activate_day, number_of_achievements\" \\\n +\" ORDER BY {} DESC\".format(u_order)\n if num_row != 'All':\n sql_1 += \" limit {}\".format(num_row)\n cursor_u = g.conn.execute(sql_1)\n users = []\n for result in cursor_u:\n users.append(result)\n context_1 = users\n cursor_u.close()\n sql_2 = \"SELECT cname, C.elements, C.character_rarity, COUNT(*) AS number_of_user_owing, \" \\\n \" AVG(O.clevel) AS average_character_level, AVG(O.friendship) AS average_character_friendship \" + \\\n \"from Owning O, Users U, Characters C where O.uid=U.uid and O.cid=C.cid \" \\\n \"GROUP BY O.cid, cname, C.elements, C.character_rarity\" \\\n + \" ORDER BY {} DESC\".format(c_order)\n if num_row != 'All':\n sql_2 += \" limit {}\".format(num_row)\n cursor_c = g.conn.execute(sql_2)\n characters = []\n for result in cursor_c:\n characters.append(result)\n context_2 = characters\n cursor_u.close()\n return context_1, context_2\n\n if request.method == 'GET':\n context_1, context_2 = type_get(u_order='O.uid', c_order='cname')\n return render_template('special.html', data_u=context_1, data_c=context_2)\n else:\n number_rows = request.form.getlist('num_row')\n print(\"number_rows\", number_rows)\n if 'All' in number_rows:\n num_rows = 'All'\n elif '10' in number_rows:\n num_rows = 10\n else:\n num_rows = 5\n order_target = request.form.get('order')\n if order_target == None:\n c1 = []\n c2 = []\n return render_template('special.html', data_u=c1, data_c=c2, wrong='Please choose one order target!')\n if 'Both' in order_target:\n order = 'All'\n elif 'User' in order_target:\n order = 'User'\n else:\n order = 'Character'\n order_type = []\n orderu = request.form.get('orderu')\n order_type.append(orderu)\n orderb = request.form.get('orderb')\n order_type.append(orderb)\n submit = request.form.get('search')\n cols_char = ['owning_number', 'average_character_level', 'average_character_friendship']\n if submit == 'search':\n if orderu != None and orderb!= None:\n c1, c2 = [], []\n return render_template('special.html', wrong='Please match order target and order type '\n 'and only choose one order type!', data_u=c1, data_c=c2)\n if orderu == None and orderb == None:\n c1 = []\n c2 = []\n return render_template('special.html', wrong='Please at least choose one order type', data_u=c1, data_c=c2)\n if (('Both' in order_target) or ('Character' in order_target)) and orderb == None:\n c1 = []\n c2 = []\n return render_template('special.html', wrong='Please match order target and order type!', data_u=c1, data_c=c2)\n '''if ('User' in order_target) and orderu == None:\n c1 = []\n c2 = []\n return render_template('special.html', wrong='Please match order target and order type!', data_u=c1, data_c=c2)'''\n if orderu != None and order == 'All':\n c1 = []\n c2 = []\n return render_template('special.html', wrong='Please match order target and order type!', data_u=c1, data_c=c2)\n tmp = []\n for col in order_type:\n if col != None:\n tmp.append(col)\n def get_two_order(order_type, order):\n if order_type == 'owning_number':\n if order == 'All':\n return 'owning_character_number', 'number_of_user_owing'\n elif order == 'User':\n return 'owning_character_number', 'cname'\n else:\n return 'O.uid', 'number_of_user_owing'\n if len(tmp) == 1:\n if order == 'All':\n if tmp[0] in cols_char:\n if tmp[0] == 'owning_number':\n u_order, c_order = get_two_order(tmp[0], order)\n else:\n u_order, c_order = tmp[0], tmp[0]\n context_1, context_2 = type_get(u_order=u_order, c_order=c_order, num_row=num_rows)\n else:\n context_1, context_2 = type_get(u_order=tmp[0], c_order='cname', num_row=num_rows)\n elif order == 'User':\n if tmp[0] == 'owning_number':\n u_order, c_order = get_two_order(tmp[0], order)\n else:\n u_order, c_order = tmp[0], 'cname'\n context_1, context_2 = type_get(u_order=u_order, c_order=c_order, num_row=num_rows)\n context_2 =[]\n else:\n if tmp[0] in cols_char:\n if tmp[0] == 'owning_number':\n u_order, c_order = get_two_order(tmp[0], order)\n else:\n u_order, c_order = 'O.uid', tmp[0]\n context_1, context_2 = type_get(u_order=u_order, c_order=c_order, num_row=num_rows)\n else:\n context_1, context_2 = type_get(u_order='O.uid', c_order='cname', num_row=num_rows)\n context_1=[]\n else:\n context_1, context_2 = type_get(u_order='O.uid', c_order='cname', num_row=num_rows)\n return render_template('special.html', data_u=context_1, data_c=context_2)\n\n\ndef this_is_never_executed():\n print('***')\n pass\n\n\n@app.route('/login')\ndef login():\n os.abort(401)\n this_is_never_executed()\n\n\nif __name__ == \"__main__\":\n import click\n\n @click.command()\n @click.option('--debug', is_flag=True)\n @click.option('--threaded', is_flag=True)\n @click.argument('HOST', default='0.0.0.0')\n @click.argument('PORT', default=8111, type=int)\n def run(debug, threaded, host, port):\n \"\"\"\n This function handles command line parameters.\n Run the server using:\n\n python server.py\n\n Show the help text using:\n\n python server.py --help\n\n \"\"\"\n\n HOST, PORT = host, port\n print (\"running on %s:%d\"% (HOST, PORT))\n app.run(host=HOST, port=PORT, debug=debug, threaded=threaded)\n\n\n run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":27375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"3370489","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/gianluca/Pubblici/GIThub/MASTER/Videomass/videomass3/vdms_dialogs/popup.py\n# Compiled at: 2020-05-11 07:27:34\n# Size of source mod 2**32: 3499 bytes\nimport wx\nfrom pubsub import pub\n\nclass PopupDialog(wx.Dialog):\n __doc__ = '\\n A pop-up dialog box for temporary user messages that tell the user\\n the load in progress (required for large files).\\n\\n Usage:\\n loadDlg = PopupDialog(None, (\"Videomass - Loading\"),\\n (\"\\nWait....\\nwork in progress.\\n\")\\n )\\n loadDlg.ShowModal()\\n loadDlg.Destroy()\\n '\n\n def __init__(self, parent, title, msg):\n wx.Dialog.__init__(self, parent, (-1), title, size=(350, 150), style=(wx.CAPTION))\n box = wx.BoxSizer(wx.VERTICAL)\n box2 = wx.BoxSizer(wx.HORIZONTAL)\n bitmap = wx.Bitmap(32, 32)\n bitmap = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_MESSAGE_BOX, (32,\n 32))\n graphic = wx.StaticBitmap(self, -1, bitmap)\n box2.Add(graphic, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, 10)\n message = wx.StaticText(self, -1, msg)\n box2.Add(message, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 10)\n box.Add(box2, 0, wx.EXPAND)\n self.SetAutoLayout(True)\n self.SetSizer(box)\n self.Fit()\n self.Layout()\n pub.subscribe(self.getMessage, 'RESULT_EVT')\n\n def getMessage(self, status):\n \"\"\"\n Riceive msg and status from thread.\n All'inizio usavo self.Destroy() per chiudere il dialogo modale\n (con modeless ritornava dati None), ma dava warning e critical\n e su OsX non chiudeva affatto. Con EndModal ho risolto tutti\n i problemi e funziona bene. Ma devi ricordarti di eseguire\n Destroy() dopo ShowModal() nel chiamante.\n vedi: https://github.com/wxWidgets/Phoenix/issues/672\n Penso sia fattibile anche implementare un'interfaccia GetValue\n su questo dialogo, ma si perderebbe un po' di portabilità.\n \"\"\"\n self.EndModal(1)","sub_path":"pycfiles/videomass-2.1.7-py3-none-any/popup.cpython-37.py","file_name":"popup.cpython-37.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"322430045","text":"import numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n#from sklearn.metrics import mean_squared_error\r\nimport os\r\n\r\n\r\ndef ChooseAndShuffle(C1,C2):\r\n firstC=C1\r\n secondC=C2\r\n train=\"True\"\r\n File = open(\"IrisData.txt\")\r\n Lines = File.readlines()\r\n i = 0\r\n ListOfRecords = list()\r\n firstThirty=0\r\n for EachLine in Lines:\r\n if i == 0:\r\n i = i + 1\r\n else:\r\n X1 = (EachLine.split(','))[0]\r\n X2 = (EachLine.split(','))[1]\r\n X3 = (EachLine.split(','))[2]\r\n X4 = (EachLine.split(','))[3]\r\n Label = (EachLine.split(','))[4]\r\n if Label == 'Iris-setosa\\n':\r\n Cluster = \"C1\"\r\n if Label == 'Iris-versicolor\\n':\r\n Cluster = 'C2'\r\n if Label == 'Iris-virginica\\n':\r\n Cluster = 'C3'\r\n\r\n Record = dict(X1=X1, X2=X2, X3=X3, X4=X4, Label=Cluster, Index=i)\r\n ListOfRecords.append(Record)\r\n mod=i%50\r\n i = i + 1\r\n Line=Record[\"X1\"]+','+ Record[\"X2\"]+','+ Record[\"X3\"]+','+ Record[\"X4\"]+','+ Record[\"Label\"]+'\\n'# to change the format of the dict\r\n if ((mod <31 and mod !=0 )and (Cluster==firstC or Cluster==secondC)):\r\n with open(\"TrainFile.txt\", \"a\") as f:\r\n f.writelines(Line)\r\n elif((mod >=31 or mod ==0 ) and (Cluster==firstC or Cluster==secondC)):\r\n with open(\"TestFile.txt\", \"a\") as f:\r\n f.writelines(Line)\r\n with open(\"TrainFile.txt\") as f:\r\n lines = f.readlines()\r\n random.shuffle(lines)\r\n with open(\"TrainFile.txt\", \"w\") as f:\r\n f.writelines(lines)\r\n # with open(\"TestFile.txt\") as f:\r\n # lines = f.readlines()\r\n # random.shuffle(lines)\r\n # with open(\"TestFile.txt\", \"w\") as f:\r\n # f.writelines(lines)\r\n\r\ndef ChooseFeatures (F1,F2,class1,class2,Filename):\r\n FirstFeatureList=list()\r\n SecodFeatureList=list()\r\n LabelList=list()\r\n ThisnewLabel=list()\r\n # File = open(\"TrainFile.txt\")\r\n File=open(Filename)\r\n Lines = File.readlines()\r\n for eachline in Lines:\r\n X1 = (eachline.split(','))[0]\r\n X2 = (eachline.split(','))[1]\r\n X3 = (eachline.split(','))[2]\r\n X4 = (eachline.split(','))[3]\r\n ThisLabel=(eachline.split(','))[4]\r\n if ThisLabel==class1 + \"\\n\":\r\n ThisnewLabel=1 ##############################333 -1 wnfs el klam el test ############ n2as 7war ino a7tfz bel class dah nfso\r\n elif ThisLabel==class2 + \"\\n\":\r\n ThisnewLabel=-1\r\n\r\n if (F1 == \"X1\"):\r\n FirstFeatureList.append(float(X1))\r\n if (F1 == \"X2\"):\r\n FirstFeatureList.append(float(X2))\r\n if (F1 == \"X3\"):\r\n FirstFeatureList.append(float(X3))\r\n if (F1 == \"X4\"):\r\n FirstFeatureList.append(float(X4))\r\n if (F2 == \"X1\"):\r\n SecodFeatureList.append(float(X1))\r\n if (F2 == \"X2\"):\r\n SecodFeatureList.append(float(X2))\r\n if (F2 == \"X3\"):\r\n SecodFeatureList.append(float(X3))\r\n if (F2 == \"X4\"):\r\n SecodFeatureList.append(float(X4))\r\n #print (ThisLabel)\r\n LabelList.append(ThisnewLabel)\r\n return (FirstFeatureList,SecodFeatureList,LabelList)\r\n\r\ndef InputMatrixConstructor(F1,F2,BooleanBias):\r\n Input_Matrix=np.empty([60,3],dtype=float)\r\n if BooleanBias == True:\r\n Bias = 1\r\n elif BooleanBias == False:\r\n Bias=0\r\n for i in range(0,60):\r\n Input_Matrix[i][0] =Bias\r\n Input_Matrix[i][1]=F1[i]\r\n Input_Matrix[i][2]=F2[i]\r\n\r\n return Input_Matrix\r\n#def WeightMatrixConstructor(Bias):\r\ndef WeightMatrixConstructor():\r\n WeightMatrix=np.empty([3,1],dtype=float)\r\n # Weight1=np.random.rand(1,1)\r\n # Weight2=np.random.rand(1,1)\r\n weight=np.random.rand(3,1)\r\n for i in range (0,3):\r\n WeightMatrix[i]=weight[i]\r\n # WeightMatrix[0][i] = Bias###############################################################\r\n # WeightMatrix[1][i] = Weight1[0][i]\r\n # WeightMatrix[2][i] = Weight2[0][i]\r\n\r\n return WeightMatrix\r\n\r\ndef Signum(NetMatrixResult):\r\n if(NetMatrixResult>0):\r\n NetMatrixResult=1\r\n elif(NetMatrixResult==0):\r\n NetMatrixResult=1\r\n else:\r\n NetMatrixResult=-1\r\n return NetMatrixResult #############\r\n\r\n\r\ndef SingleLayerPers(InputMatrix,WeightMatrix,TargetList,Epochs,LR):\r\n # Epochs=10\r\n # LR=10\r\n for E in range(0, Epochs):\r\n for i in range(0, 60):\r\n InputRecordMat = np.empty([1, 3])\r\n InputRecordMat[0][0] = InputMatrix[i][0]\r\n InputRecordMat[0][1] = InputMatrix[i][1]\r\n InputRecordMat[0][2] = InputMatrix[i][2]\r\n\r\n NetMatrix = np.dot(InputRecordMat, WeightMatrix)\r\n NormaizedVal=Signum(NetMatrix)\r\n\r\n if (NormaizedVal != TargetList):\r\n Loss=TargetList[i]-NormaizedVal\r\n Term=np.dot(LR,Loss)\r\n WeightMatrix[0][0] = WeightMatrix[0][0]+(np.dot(Term,InputRecordMat[0][0]))\r\n WeightMatrix[1][0] = WeightMatrix[1][0]+(np.dot(Term,InputRecordMat[0][1]))\r\n WeightMatrix[2][0] = WeightMatrix[2][0]+(np.dot(Term,InputRecordMat[0][2]))\r\n\r\n return WeightMatrix\r\n\r\n#second task algo adaline\r\ndef Adaline(InputMatrix,WeightMatrix,TargetList,Epochs,LR,mse):\r\n # Epochs=10\r\n # LR=10\r\n x=100000000000\r\n epoch=0\r\n loss2=0\r\n while (x > mse):##############################\r\n for i in range(0, 60):\r\n InputRecordMat = np.empty([1, 3])\r\n InputRecordMat[0][0] = InputMatrix[i][0]\r\n InputRecordMat[0][1] = InputMatrix[i][1]\r\n InputRecordMat[0][2] = InputMatrix[i][2]\r\n\r\n NetMatrix = np.dot(InputRecordMat, WeightMatrix)\r\n\r\n\r\n #if (NetMatrix != TargetList):\r\n Loss=TargetList[i]-NetMatrix\r\n Term=np.dot(LR,Loss)\r\n WeightMatrix[0][0] = WeightMatrix[0][0]+(np.dot(Term,InputRecordMat[0][0]))\r\n WeightMatrix[1][0] = WeightMatrix[1][0]+(np.dot(Term,InputRecordMat[0][1]))\r\n WeightMatrix[2][0] = WeightMatrix[2][0]+(np.dot(Term,InputRecordMat[0][2]))\r\n ###losss mean square\r\n\r\n #to calculae the mse\r\n for i in range(0, 60):\r\n InputRecordMat = np.empty([1, 3])\r\n InputRecordMat[0][0] = InputMatrix[i][0]\r\n InputRecordMat[0][1] = InputMatrix[i][1]\r\n InputRecordMat[0][2] = InputMatrix[i][2]\r\n\r\n NetMatrix = np.dot(InputRecordMat, WeightMatrix)\r\n\r\n\r\n # if (NetMatrix != TargetList):\r\n loss2+=np.nan_to_num(((TargetList[i]-NetMatrix)*(TargetList[i]-NetMatrix)/2))\r\n x=(loss2/60)\r\n epoch += 1\r\n loss2=0\r\n print(x)\r\n print(\"Epochs is: \",epoch)\r\n\r\n\r\n return WeightMatrix\r\n\r\n\r\ndef AnotherInputMatrixConstructor(F1,F2,BooleanBias):\r\n AnotherInputMatrix=np.empty([40,3],dtype=float)\r\n if BooleanBias == True:\r\n Bias = 1\r\n elif BooleanBias == False:\r\n Bias=0\r\n for i in range(0,40):\r\n AnotherInputMatrix[i][0] =Bias\r\n AnotherInputMatrix[i][1]=F1[i]\r\n AnotherInputMatrix[i][2]=F2[i]\r\n return AnotherInputMatrix\r\n\r\ndef test(AnotherInputMatrix,WeightMatrix,TargetList):\r\n Accuracy=0\r\n c1true=0\r\n c2true=0\r\n c1false=0\r\n c2false=0\r\n confMat=np.empty([2,2])\r\n for i in range(0, 40):\r\n InputRecordMat2 = np.empty([1, 3])\r\n InputRecordMat2[0][0] = AnotherInputMatrix[i][0]\r\n InputRecordMat2[0][1] = AnotherInputMatrix[i][1]\r\n InputRecordMat2[0][2] = AnotherInputMatrix[i][2]\r\n NetMatrix2 = np.dot(InputRecordMat2, WeightMatrix)\r\n NormaizedVal2=Signum(NetMatrix2)\r\n if(TargetList[i]==NormaizedVal2 and TargetList[i]==1):\r\n c1true+=1\r\n Accuracy+=1\r\n elif(TargetList[i]==NormaizedVal2 and TargetList[i]==-1):\r\n c2true+=1\r\n Accuracy+=1\r\n elif(TargetList[i]!=NormaizedVal2 and TargetList[i]==1):\r\n c1false+=1\r\n elif(TargetList[i]!=NormaizedVal2 and TargetList[i]==-1):\r\n c2false+=1\r\n confMat[0][0]=c1true\r\n confMat[0][1]=c2false\r\n confMat[1][0]=c1false\r\n confMat[1][1]=c2true\r\n\r\n return ((Accuracy/40)*100),confMat\r\n\r\ndef draw_line(F1,F2,LabelList,Updatedweight):\r\n\r\n FirstFeatureFirstClass=list()\r\n FirstFeatureSecondClass=list()\r\n SecondFeatureFirstClass=list()\r\n SecondFeatureSecondClass=list()\r\n for i in range(0,40):\r\n if(LabelList[i]==1):\r\n FirstFeatureFirstClass.append(F1[i])\r\n SecondFeatureFirstClass.append(F2[i])\r\n elif(LabelList[i]==-1):\r\n FirstFeatureSecondClass.append(F1[i])\r\n SecondFeatureSecondClass.append(F2[i])\r\n plt.figure('fig1')\r\n plt.scatter(FirstFeatureFirstClass,SecondFeatureFirstClass)\r\n plt.scatter(FirstFeatureSecondClass,SecondFeatureSecondClass)\r\n point1=-Updatedweight[0]/Updatedweight[2]\r\n point2=-Updatedweight[0]/Updatedweight[1]\r\n minx=min(F1)\r\n maxx=max(F1)\r\n miny=(-(Updatedweight[1]*minx)-Updatedweight[0])/Updatedweight[2]\r\n maxy=(-(Updatedweight[1]*maxx)-Updatedweight[0])/Updatedweight[2]\r\n\r\n plt.plot((minx,maxx),(miny,maxy))\r\n plt.xlabel('Feature1')\r\n plt.ylabel('Feature2')\r\n plt.show()\r\n\r\n\r\n\r\ndef main(Feature1,Feature2,Class1,Class2,Bias,Epochs,LearningRate,mse):\r\n\r\n\r\n # Epochs=10############################################################## update this!!!!!\r\n open(\"TrainFile.txt\",'w').close()\r\n open(\"TestFile.txt\", 'w').close()\r\n # DefaultBias=np.random.rand(1,1)\r\n ChooseAndShuffle(Class1, Class2)\r\n F1,F2,LabelList=ChooseFeatures(Feature1,Feature2,Class1,Class2,\"TrainFile.txt\")\r\n F1 = np.array(F1)\r\n F2 = np.array(F2)\r\n F1=F1.reshape(60,1)\r\n F2=F2.reshape(60,1)\r\n InputMatrix=InputMatrixConstructor(F1,F2,Bias)\r\n # WeightMatrix=WeightMatrixConstructor(DefaultBias)\r\n WeightMatrix=WeightMatrixConstructor()\r\n #UpdatedWeightMatrix=SingleLayerPers(InputMatrix,WeightMatrix,LabelList,Epochs,LearningRate)\r\n UpdatedWeightMatrix=Adaline(InputMatrix,WeightMatrix,LabelList,Epochs,LearningRate,mse)\r\n\r\n #for test\r\n F1T,F2T,LabelListtest=ChooseFeatures(Feature1,Feature2,Class1,Class2,\"TestFile.txt\")\r\n AnotherInputMatrix=AnotherInputMatrixConstructor(F1T,F2T,Bias)\r\n acuuracy,confusionMatrix=test(AnotherInputMatrix,UpdatedWeightMatrix,LabelListtest)\r\n print('Accuracy=', int(acuuracy),'%','\\n','Confusion Matrix is:\\n',confusionMatrix,'\\n')\r\n\r\n #for drawing line\r\n draw_line(F1T,F2T,LabelListtest,UpdatedWeightMatrix)\r\n\r\nmain(\"X1\",\"X4\",\"C1\",\"C2\",True,10,0.005,0.05)\r\n\r\n\r\n","sub_path":"NN_Algo.py","file_name":"NN_Algo.py","file_ext":"py","file_size_in_byte":10803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"275169482","text":"''' Hello, world!\n'''\nimport glob\nimport os\nimport json\nimport sqlite3\nimport hashlib\n\nfrom functools import wraps\nfrom flask import Flask, jsonify, request, Response, redirect, url_for, flash, render_template, session, Markup\nfrom flask_orator import Orator\n\nfrom orator import Model, SoftDeletes\nfrom orator.orm import belongs_to, has_many, has_one, belongs_to_many, morph_to, morph_many, morph_one\nfrom orator.exceptions.query import QueryException\n\nfrom flask_humanize import Humanize\n\napp = Flask(__name__)\n\napp.config['ORATOR_DATABASES'] = {\n 'development': {\n 'driver': 'sqlite',\n 'database': 'test.db'\n },\n 'production': {\n 'driver': 'mysql',\n 'host': 'localhost',\n 'database': 'manuhub',\n 'user': 'root',\n 'password': 'secret'\n }\n}\n\napp.config['SESSION_TYPE'] = 'filesystem'\napp.config['HUMANIZE_USE_UTC'] = True\n\nhumanize = Humanize(app)\ndb = Orator(app)\n\n# Decorators\ndef authenticate():\n if 'user_id' in session:\n session.pop('user_id')\n if 'admin' in session:\n session.pop('admin')\n if 'username' in session:\n session.pop('username')\n \n return redirect('login')\n\ndef home():\n return redirect('/')\n\ndef requires_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if 'user_id' not in session or User.find(session['user_id']) is None or 'username' not in session or 'admin' not in session:\n return authenticate()\n\n return f(*args, **kwargs)\n return decorated\n\ndef requires_zero(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if 'user_id' not in session or User.find(session['user_id']) is None:\n return authenticate()\n if User.find(session['user_id']).user_role > 0:\n abort(404)\n \n return f(*args, **kwargs)\n return decorated\n\ndef requires_one(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if 'user_id' not in session or User.find(session['user_id']) is None:\n return authenticate()\n if User.find(session['user_id']).user_role > 1:\n abort(404)\n \n return f(*args, **kwargs)\n return decorated\n\ndef requires_not_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if 'user_id' in session:\n return home()\n return f(*args, **kwargs)\n return decorated\n\n# Set Up Classes\nclass User(db.Model, SoftDeletes):\n ''' Represents the \"user\" object within the system.\n Users are the staff who have access to the application. A user is uniquely identified\n by both a user id (id) and a username (username). Authentication further requires a \n password (password), and both a first name (first_name) and last name (last_name) are provided\n for context. The permissions a user have are dictated on a scale (user_role)\n TODO: Extract this away to an additional Roles table/object\n 0: Admin - Full Access to Everything\n 1: Sales - Full Create Access; Limited Delete Access\n ...\n 100: Invalid - Generic Placeholder for an Invalid user_role\n Users leverage soft deletes. \n '''\n __guarded__ = []\n __dates__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.name\n\n @has_many\n def customers(self):\n return Customer\n\n @has_many\n def opportunities(self):\n return Opportunity\n\nclass Customer(db.Model, SoftDeletes):\n ''' Represents the \"customer\" object within the system.\n Customers are any clients, leads, or other external parties with whom a business relationship\n is intended. A customer is uniquely identified by a customer id (id) and an email (email). In \n addition, the name (first_name, last_name), company (company), and information on contact info and \n addresses (phone, address_1, address_2, city, zip, country, state) are included.\n A customer belongs to the user (user_id) which created it; this user is the exclusive non-admin \n part that can remove the record.\n Customers leverage soft deletes'''\n __guarded__ = []\n __dates__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.email\n\n @belongs_to\n def user(self):\n return User\n \n @belongs_to_many\n def opportunities(self):\n return Opportunity\n\n @belongs_to\n def country(self):\n return Country\n\n @belongs_to\n def region(self):\n return Region\n\n\nclass Opportunity(db.Model, SoftDeletes):\n ''' Represents the \"opportunities\" within the system.\n An opportunity is any attempted sale, from initial contact, through to delivery of goods. The \n opportunity is the record which houses all of the other documentation regarding the order process\n (i.e. Quotes, Work Orders, Change Orders, etc.). \n An opportunity is uniquely identified by an id (id), and has a title (title), and phase (phase).\n The phase is an integer which specifies the id of the current phase on the order.\n The Opportunity belongs to a user (user_id), who is the only non-admin able to remove it or its children.\n Opporunities leverage soft deletes'''\n __guarded__ = []\n __fillable__ = ['title', 'phase_id', 'user_id']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.title\n \n @belongs_to\n def user(self):\n return User\n\n @belongs_to\n def phase(self):\n return Phase\n \n @belongs_to_many\n def customers(self):\n return Customer\n\n @has_many\n def quotes(self):\n return Quote\n\n @has_many\n def work_orders(self):\n return WorkOrder\n\nclass Phase(db.Model, SoftDeletes):\n ''' # TODO: Fill out this description\n BY DEFAULT\n 0: \"Lead\" - Initial Contact is Made;\n 1: \"Discussion\" - In active conversation, with no firm agreements;\n 2: \"Negotation\" - Discussions of Specifics; Quote Iterations;\n 3: \"Agreement\" - The quote has been agreed upon; waiting for signatures, etc.;\n 4: \"In Progress\"- The work order is generated and work has started;\n 5: \"Delivery\" - The order is in transit to the client;\n 6: \"Follow-up\" - The truck has arrived, customer support is in full swing, ask for reviews/links\n 7: \"Maintenance\" - The relationship has 'ended'; everything is maintained for future information\n '''\n __guarded__ = []\n __fillable__ = ['phase_name', 'description', 'order']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.phase_name\n\n # @has_many\n # def opportunities(self):\n # return Opportunity\n\nclass Item(db.Model, SoftDeletes):\n ''' Represents any \"item\" within the system.\n An item is the representation of: (1) any piece of inventory; (2) any line that can appear on a quote or\n in a work, purchase, or change order; (3) otherwise needs to be tracked by the system.\n An item is uniquely identified by an item id (id).\n There are then variables to represent the item name (name), item description (description), and \n then a category (category_type) field. The category field can take on values of:\n TODO: Extract this away to an additional ItemCategory table/object\n 0: \"product\" - This represents any distinct product that will have a corresponding inventory record\n 1: \"line_item\" - This is an item that can appear on 2 or more report types, but is not a product\n 2: \"quote_item\" - This represents any item on a quote, which is not a product, and does not appear on other report types\n 3: \"work_order_item\" - This represents any item on a work order, which is not a product, and does not appear on other report types\n 4: \"change_order_item\" - This represents any item on a change order, which is not a product, and does not appear on other report types\n 5: \"purchase_order_item\" - This represents any item on a purchase order, which is not a product, and does not appear on other request types\n 6: \"cost_breakdown_item\" - This repesents any item which is not directly a product, but contributes to a products cost\n In addition to the category, there is a category_id field. This will correspond to a polymorphic relationship, in that line_items and products are\n sepearate objects, with their own properties, and that an item can belong to them. \n The Item does not belong to any created entity, though only admins can create/destroy them.\n Item leverages soft deletes'''\n __guarded__ = []\n __fillable__ = ['name', 'description', 'category_type', 'category_id']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.name\n\n @morph_to\n def category(self):\n return\n\nclass Product(db.Model, SoftDeletes):\n ''' Represents any \"product\" within the system.\n This corresponds to the inventory record for the any Item with category_type = 0. These products are intended to be items which are either \n (1) available directly on the quote sent to a customer; (2) available directly on the work order sent to production; (3) available directly\n on a purchase order sent to a vendor; or (4) available directly on a change order, assigned to an Opportunity.\n The Product is uniquely identified by an ID and a system id (system_id). The system id represents internal\n inventory ID numbers for anything stored in inventory, external numbers for items which are purchased from a vendor, etc.\n Additionally, there is a product category (category) and sub-category (subcategory), which are IDs corresponding to the Category and Sub-Category\n of the product. There is a stock level (stock), a customer Price (customer_price) in CAD, an order price (purchase_price). There is a markup (markup) field\n which defaults to 20%. If only one price is specified then there is an added markup of (markup)% on the customer_price. \n The Product does not belong to any created entity, though only admins can create/destroy them.\n Product leverages soft deletes.'''\n __guarded__ = []\n __fillable__ = ['system_id', 'category_id', 'subcategory_id', 'stock', 'customer_price', 'purchase_price', 'markup']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.system_id\n\n @morph_one('category')\n def item(self):\n return Item\n \n @has_one\n def cost_breakdown(self):\n return CostBreakdown\n\n @belongs_to_many\n def quotes(self):\n return Quote\n\n @morph_one('item')\n def quote_item(self):\n return QuoteItem\n\n @belongs_to\n def category(self):\n return Category\n\n @belongs_to\n def subcategory(self):\n return Subcategory\n\nclass LineItem(db.Model, SoftDeletes):\n ''' '''\n __guarded__ = []\n __fillable__ = ['category', 'subcategory']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.id\n\n @morph_one('category')\n def item(self):\n return Item\n \n @belongs_to_many\n def quotes(self):\n return Quote\n\n @morph_one('item')\n def quote_item(self):\n return QuoteItem\n\nclass QuoteLineItem(db.Model, SoftDeletes):\n ''' '''\n __guarded__ = []\n __fillable__ = ['category', 'subcategory', 'customer_price']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.id\n\n @morph_one('category')\n def item(self):\n return Item\n \n @belongs_to_many\n def quotes(self):\n return Quote\n\n @morph_one('item')\n def quote_item(self):\n return QuoteItem\n\nclass CostBreakdown(db.Model, SoftDeletes):\n ''' Represents a \"cost breakdown\" in the system.\n A cost breakdown is an optional addition to a product. This allows the customer/purchase price of a product to have \n a line-by-line breakdown explaining the total cost. \n A CostBreakdown is uniquely identified by an id. There is a product ID (product_id) to associate it with the specified\n product. \n CostBreakdowns are not assocaited with any created entity, though only admins can create/destroy them.\n CostBreakdown leverages soft deletes'''\n __guarded__ = []\n __fillable__ = ['product_id']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.product_id\n \n @belongs_to\n def product(self):\n return Product\n\n @has_many\n def cost_breakdown_items(self):\n return CostBreakdownItem\n\nclass CostBreakdownItem(db.Model, SoftDeletes):\n ''' Represents an item for a cost breakdown.\n The CostBreakdownItem is uniquely identified with an id (id). Additionally, there is a price (customer_price) field\n and a cost breakdown ID (cost_breakdown_id). Each cost breakdown item is associated with a standard Item which has a\n category of cost_breakdown_item assigned to it.\n CostBreakdownItems leverage soft deletes'''\n __guarded__ = []\n __fillable__ = ['customer_price', 'cost_breakdown_id']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.id\n \n @belongs_to\n def cost_breakdown(self):\n return CostBreakdown\n \n @morph_one('category')\n def item(self):\n return Item\n\n\nclass Quote(db.Model, SoftDeletes):\n ''' Represents a quote in teh system.\n The Quote is uniquely identified with an id and a quote number (quote_number) which is an alphanumeric (numeric by default)\n representation. A Quote also has an opportunity ID (opportunity_id) corresponding to the opportunity it is related to\n and a user id (user_id) for the user who created the specific quote. Additionally, a currency (currency), an exchange rate\n (exchange_rate), and a tax rate (tax_rate) are all specified. The exchange rate is quoted in CAD (i.e. 1.25 means 1.25CAD=1CUR).\n Quotes leverage soft deletes. '''\n \n __guarded__ = []\n __fillable__ = ['quote_number', 'opportunity_id', 'user_id', 'currency_id', 'exchange_rate', 'tax_rate']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.quote_number\n \n @belongs_to\n def user(self):\n return User\n \n @belongs_to\n def opportunity(self):\n return Opportunity\n\n @has_many\n def quote_items(self):\n return QuoteItem\n\n @belongs_to\n def currency(self):\n return Currency\n\nclass QuoteItem(db.Model, SoftDeletes):\n __guarded__ = []\n __fillable__ = ['quote_id', 'order', 'item_type', 'item_id', 'quantity']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.id\n \n # Item Type: product, quote_item, line_item\n @belongs_to\n def quote(self):\n return Quote\n \n @morph_to\n def item(self):\n return\n\nclass WorkOrder(db.Model, SoftDeletes):\n ''' '''\n \n __guarded__ = []\n __fillable__ = ['work_order_number', 'opportunity_id', 'user_id']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.work_order_number\n \n @belongs_to\n def user(self):\n return User\n \n @belongs_to\n def opportunity(self):\n return Opportunity\n\n @has_many\n def work_order_items(self):\n return WorkOrderItem\n\nclass WorkOrderItem(db.Model, SoftDeletes):\n __guarded__ = []\n __fillable__ = ['work_order_id', 'order', 'item_type', 'item_id', 'quantity']\n __data__ = ['deleted_at']\n\n def __repr__(self):\n return '' % self.id\n \n @belongs_to\n def work_order(self):\n return WorkOrder\n \n # Item Type: product, work_order_line_item, line_item\n @morph_to\n def item(self):\n return\n\nclass Currency(db.Model):\n ''' Represents a Currency that is Accepted\n '''\n __guarded__ = []\n __fillable__ = ['currency_code']\n\n def __repr__(self):\n return '' % self.currency_code\n\n @has_one\n def exchange_rate(self):\n return ExchangeRate\n\n @belongs_to\n def country(self):\n return Country\n\nclass ExchangeRate(db.Model):\n ''' Represents the conversion of any Currency into CAD; I.e $X CAD = 1 Currency\n '''\n\n __guarded__ = []\n __fillable__ = ['currency_id', 'exchange_rate']\n\n def __repr__(self):\n return '' % self.currency_id \n\n @belongs_to\n def currency(self):\n return Currency\n\nclass Country(db.Model):\n ''' Represents a country within the system\n '''\n __guarded__ = []\n __fillable__ = ['country_name', 'country_code']\n\n def __repr__(self):\n return '' % self.country_name\n\n @has_one\n def currency(self):\n return Currency\n \n @has_many\n def regions(self):\n return Region\n\nclass Region(db.Model):\n ''' Represents a region (state or province) within the system \n '''\n\n __guarded__ = []\n __fillable__ = ['country_id', 'region_name']\n\n def __repr__(self):\n return '' % self.region_name\n\n @belongs_to\n def country(self):\n return Country\n\n @has_one\n def tax_rate(self):\n return TaxRate\n\nclass TaxRate(db.Model):\n ''' Stores a regions tax rate within the system\n '''\n\n __guarded__ = []\n __fillable__ = ['region_id', 'tax_rate']\n\n def __repr__(self):\n return '' % self.id\n\n @belongs_to\n def region(self):\n return Region\n\nclass Category(db.Model):\n ''' Stores a Product or Line Item Category\n '''\n\n __guarded__ = []\n __fillable__ = ['category_name']\n\n def __repr__(self):\n return '' % self.category_name\n\n @has_many\n def subcategories(self):\n return Subcategory\n\n @has_many\n def products(self):\n return Product\n\nclass Subcategory(db.Model):\n ''' Stores a subcategory for a Product or Line Item\n '''\n\n __guarded__ = []\n __fillable__ = ['subcategory_name', 'category_id']\n\n def __repr__(self):\n return '' % self.subcategory_name\n\n @belongs_to\n def category(self):\n return Category\n\n @has_many\n def products(self):\n return Product\n\n# class WorkOrder(db.Model, SoftDeletes):\n# ''' Stores the Main WorkOrder Record\n# ''' \n\n# __guaded__ = []\n# __fillable__ = ['user_id', 'opportunity_id', 'quote_id']\n# __data__ = ['deleted_at']\n\n# def __repr__(self):\n# return \"\" % self.id\n\n# @belongs_to\n# def opportunity(self):\n# return Opportunity\n\n# @belongs_to\n# def quote(self):\n# return Quote\n\n# class WorkOrderItem(db.Model, SoftDeletes):\n# ''' Stores the Items attributed to a WorkOrder\n# ''' \n\n# __guaded__ = []\n# __fillable__ = ['work_order_id', 'quantity', 'item_id', 'item_type', 'completed']\n# __data__ = ['deleted_at']\n\n# def __repr__(self):\n# return '' % self.id\n\n# @belongs_to\n# def work_order(self):\n# return WorkOrder\n\n# Standard API Routes\n@app.route('/search')\ndef search():\n query = request.args.get('query', '')\n search_type = request.args.get('search_type', '')\n return_data = {}\n\n if query == \"\":\n return jsonify({})\n\n if search_type == \"\" or search_type == \"customers\":\n # Select Customers\n customers = Customer.where('first_name', 'like', '%'+query+'%')\\\n .or_where('last_name', 'like', '%'+query+'%')\\\n .or_where('email', 'like', '%'+query+'%')\\\n .or_where('company', 'like', '%'+query+'%')\\\n .or_where('id', '=', query).get()\n return_data['customers'] = customers.serialize()\n\n if search_type == \"\" or search_type == \"opportunities\":\n # Select Opportunities\n opportunities = Opportunity.where('title', 'like', '%'+query+'%')\\\n .or_where('id', '=', query).get()\n return_data['opportunities'] = opportunities.serialize()\n\n if search_type == \"\" or search_type == \"users\":\n # Select Users\n users = User.where('first_name', 'like', '%'+query+'%')\\\n .or_where('last_name', 'like', '%'+query+'%')\\\n .or_where('username', 'like', '%'+query+'%')\\\n .or_where('id', '=', query).get()\n return_data['users'] = users.serialize()\n\n return jsonify(return_data)\n\n# API Routes (No Views)\n@app.route('/api/opportunity-financials/')\n@requires_auth\ndef opportunity_tax_rate(opportunity_id = None):\n if opportunity_id is None:\n return jsonify({'tax_rate': 0.00, 'currency_id': 1})\n\n opportunity = Opportunity.find(opportunity_id)\n\n if opportunity is None:\n return jsonify({'tax_rate': 0.00, 'currency_id': 1})\n\n customers = opportunity.customers\n\n if customers is None:\n return jsonify({'tax_rate': 0.00, 'currency_id': 1})\n\n for customer in customers:\n if customer.region and customer.region is not None and type(customer.region) is not None:\n if customer.region.tax_rate is not None:\n print(\"...\")\n return jsonify({'tax_rate': customer.region.tax_rate.tax_rate, 'currency_id': customer.country.currency.id})\n\n return jsonify({'tax_rate': 0.00, 'currency_id': customer.country.currency.id})\n\n@app.route('/api/get-region/')\n@requires_auth\ndef return_regions_from_country(country_id = None):\n if country_id is None:\n return jsonify({'regions': []})\n\n country = Country.find(country_id)\n\n if country is None:\n return jsonify({'regions': []})\n\n return jsonify({'regions': country.regions.serialize()})\n\n@app.route('/api/currency-exchange/')\n@requires_auth\ndef return_exchange_rate_from_currency_id(currency_id = None):\n if currency_id is None:\n return jsonify({'exchange_rate': 1.00})\n\n currency = Currency.find(currency_id)\n\n if currency is None:\n return jsonify({'exchange_rate': 1.00})\n\n return jsonify({'exchange_rate': currency.exchange_rate.exchange_rate}) \n\n@app.route('/api/users/sales-funnel')\n@requires_auth\ndef return_sales_funnel_users():\n opportunities = Opportunity.all()\n data = [{'label': \"Lead\", 'value': 10},\n {'label': \"Discussion\", 'value': 20},\n {'label': \"Negotiation\", 'value': 5},\n {'label': \"Agreement\", 'value': 2},\n {'label': \"In Progress\", 'value': 5},\n {'label': \"Delivery\", 'value': 1},\n {'label': \"Follow-up\", 'value': 10},\n {'label': \"Maintenance\", 'value': 50}]\n #0: \"Lead\" - Initial Contact is Made;\n # 1: \"Discussion\" - In active conversation, with no firm agreements;\n # 2: \"Negotation\" - Discussions of Specifics; Quote Iterations;\n # 3: \"Agreement\" - The quote has been agreed upon; waiting for signatures, etc.;\n # 4: \"In Progress\"- The work order is generated and work has started;\n # 5: \"Delivery\" - The order is in transit to the client;\n # 6: \"Follow-up\" - The truck has arrived, customer support is in full swing, ask for reviews/links\n # 7: \"Maintenance\" - The relationship has 'ended'; everything is maintained for future information\n return jsonify(data)\n\n\n# Render the Home Page\n@app.route('/')\n@requires_auth\ndef main_page():\n if User.find(session['user_id']).user_role == 0:\n return render_template('home/admin.html')\n return render_template('index.html')\n\n# Render the Login Page\n@app.route('/login', methods=['GET', 'POST'])\n@requires_not_auth\ndef login_page():\n if request.method == 'GET':\n return render_template('login.html')\n \n # Attempt to Validate the Login\n if \"username\" not in request.form or len(request.form['username']) <= 0:\n flash(\"Please enter a username\", 'danger')\n return redirect('login')\n\n elif \"password\" not in request.form or len(request.form['password']) <= 0:\n flash(\"Please enter a password\", 'danger')\n return redirect('login')\n \n password = hashlib.sha256(request.form['password'].encode('utf8')).hexdigest()\n\n login = User.where('username', request.form['username']).where('password', password).first()\n\n if login is None:\n flash(\"Incorrect Username or Password\", 'danger')\n return redirect('login')\n \n session['user_id'] = login.id\n session['admin'] = login.user_role == 0\n session['username'] = login.username\n\n return redirect('/')\n\n# User Routes\n@app.route('/user')\n@requires_auth\ndef users_index():\n users = User.all()\n\n return render_template('users/index.html', users=users)\n\n@app.route('/logout')\n@requires_auth\ndef user_logout():\n if 'user_id' in session:\n session.pop('user_id')\n if 'admin' in session:\n session.pop('admin')\n if 'username' in session:\n session.pop('username')\n \n return redirect('/')\n \n\n@app.route('/user/')\ndef user_index(user_id = None):\n if user_id is None:\n flash(\"No user was specified.\", \"danger\")\n return redirect('user')\n \n user = User.find(user_id)\n\n if user is None:\n flash(\"No such user exists.\", \"danger\")\n return redirect('user')\n\n return render_template('users/individual.html', user=user)\n\n@app.route('/user/create', methods=['GET', 'POST'])\n@requires_zero\ndef user_create():\n if request.method == 'GET':\n return render_template('users/add.html')\n \n if \"username\" not in request.form or len(request.form['username']) <= 0:\n flash(\"Please enter a username\", 'danger')\n return redirect('/users/create')\n elif \"password\" not in request.form or len(request.form['password']) <= 0:\n flash(\"Please enter a password\", 'danger')\n return redirect('/users/create')\n elif \"first_name\" not in request.form or len(request.form['first_name']) <= 0:\n flash(\"Please enter a First Name\", 'danger')\n return redirect('/users/create')\n elif \"last_name\" not in request.form or len(request.form['last_name']) <= 0:\n flash(\"Please enter a Last Name\", 'danger')\n return redirect('/users/create')\n elif \"user_role\" not in request.form or len(request.form['user_role']) <= 0:\n flash(\"Please enter a User Role\", 'danger')\n return redirect('/users/create')\n \n # Everything has been submitted\n username = \"\" if request.form['username'] is None else request.form['username']\n password = \"\" if request.form['password'] is None else hashlib.sha256(request.form['password'].encode('utf8')).hexdigest()\n first_name = \"\" if request.form['first_name'] is None else request.form['first_name']\n last_name = \"\" if request.form['last_name'] is None else request.form['last_name']\n user_role = 100 if request.form['user_role'] is None else int(request.form['user_role'])\n\n try:\n new_user = User.create(username=username, password=password, first_name=first_name, last_name=last_name, user_role=user_role)\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A user with that username already exists. Please choose a different one.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('user')\n\n flash(new_user.username+\" Successfully added.\", 'success')\n return redirect('user')\n\n@app.route('/user/update/', methods=['GET', 'POST'])\n@requires_zero\ndef user_update(user_id=None):\n if user_id is None:\n flash(\"No user was specified.\", 'danger')\n return redirect('user'), 404\n \n user = User.find(user_id)\n\n if user is None:\n flash(\"That user does not exist.\", 'danger')\n return redirect('user'), 404\n\n if request.method == 'GET':\n return render_template('users/edit.html', user=user)\n\n username = \"\" if request.form['username'] is None else request.form['username']\n first_name = \"\" if request.form['first_name'] is None else request.form['first_name']\n last_name = \"\" if request.form['last_name'] is None else request.form['last_name']\n user_role = 100 if request.form['user_role'] is None else int(request.form['user_role'])\n\n user.username = username\n user.first_name = first_name\n user.last_name = last_name\n user.user_role = user_role\n\n if request.form['password'] is not None and request.form['password'] != \"\":\n user.password = hashlib.sha256(request.form['password'].encode('utf8')).hexdigest()\n try:\n user.save()\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A user with that username already exists. Please choose a different one.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('user/update/'+str(user.id))\n\n flash(\"Successfully updated \"+user.username, 'success')\n return redirect('user/'+str(user.id)) \n\n@app.route('/user/remove/')\n@requires_zero\ndef user_remove(user_id=None):\n if user_id is None:\n flash(\"Cannot remove a user that does not exist!\", 'danger')\n return redirect('user')\n \n user = User.find(user_id)\n\n if user is None:\n flash(\"Cannot remove a user that does not exist!\", 'danger')\n return redirect('user')\n\n user.delete()\n\n flash(\"Succesfully removed \"+user.username, 'warning')\n return redirect('user')\n\n# Customer Routes\n@app.route('/customer')\n@requires_auth\ndef customers_index():\n customers = Customer.all()\n\n return render_template('customers/index.html', customers=customers)\n\n@app.route('/customer/')\n@requires_auth\ndef customer_index(customer_id=None):\n if customer_id is None:\n flash(\"No customer ID provided.\", \"danger\")\n return redirect('customer')\n\n customer = Customer.find(customer_id)\n\n if customer is None:\n flash(\"No customer exists with that ID.\", \"danger\")\n return redirect('customer')\n \n return render_template('customers/individual.html', customer=customer)\n\n@app.route('/customer/create', methods=['GET', 'POST'])\n@requires_one\ndef customer_create():\n if request.method == 'GET':\n countries = Country.all()\n return render_template('customers/add.html', countries=countries.serialize())\n \n if \"first_name\" not in request.form or len(request.form['first_name']) <= 0:\n flash(\"Please enter a first name.\", 'danger')\n return redirect('/customer/create')\n elif \"last_name\" not in request.form or len(request.form['last_name']) <= 0:\n flash(\"Please enter a last name.\", 'danger')\n return redirect('/customer/create')\n elif \"email\" not in request.form or len(request.form['email']) <= 0:\n flash(\"Please enter an email.\", 'danger')\n return redirect('/customer/create') \n elif \"country_id\" not in request.form or len(request.form['country_id']) <= 0:\n flash(\"Please enter a country.\", 'danger')\n return redirect('/customer/create')\n\n # Set Variables\n first_name = \"\" if request.form['first_name'] is None else request.form['first_name']\n last_name = \"\" if request.form['last_name'] is None else request.form['last_name']\n email = \"\" if request.form['email'] is None else request.form['email']\n phone = \"\" if request.form['phone'] is None else request.form['phone']\n company = \"\" if request.form['company'] is None else request.form['company']\n address_1 = \"\" if request.form['address_1'] is None else request.form['address_1']\n address_2 = \"\" if request.form['address_2'] is None else request.form['address_2']\n city = \"\" if request.form['city'] is None else request.form['city']\n zip_c = \"\" if request.form['zip'] is None else request.form['zip']\n country_id = -1 if request.form['country_id'] is None or len(request.form['country_id']) <= 0 else int(request.form['country_id'])\n region_id = -1 if \"region_id\" not in request.form or request.form['region_id'] is None or len(request.form['region_id']) <= 0 else int(request.form['region_id'])\n user = session['user_id']\n\n try:\n customer = Customer.create(first_name=first_name, last_name=last_name, email=email, phone=phone, company=company, address_1=address_1, address_2=address_2, city=city, country_id=country_id, region_id=region_id, zip=zip_c, user_id=user) \n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A customer with that email already exists.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('customer')\n\n\n flash(\"Successfully added \"+customer.first_name + \" \" + customer.last_name + \" (\" + customer.email + \")\", 'success')\n return redirect('customer')\n\n@app.route('/customer/update/', methods=['GET', 'POST'])\n@requires_one\ndef customer_update(customer_id=None):\n if customer_id is None:\n flash(\"No customer was specified.\", 'danger')\n return redirect('customer'), 404\n \n customer = Customer.find(customer_id)\n\n if customer is None:\n flash(\"No such customer exists\", 'danger')\n return redirect('customer'), 404\n\n if request.method == 'GET':\n countries = Country.all()\n return render_template('customers/edit.html', customer=customer, countries=countries)\n\n # Set Variables\n customer.first_name = customer.first_name if request.form['first_name'] is None else request.form['first_name']\n customer.last_name = customer.last_name if request.form['last_name'] is None else request.form['last_name']\n customer.email = customer.email if request.form['email'] is None else request.form['email']\n customer.phone = customer.phone if request.form['phone'] is None else request.form['phone']\n customer.company = customer.company if request.form['company'] is None else request.form['company']\n customer.address_1 = customer.address_1 if request.form['address_1'] is None else request.form['address_1']\n customer.address_2 = customer.address_2 if request.form['address_2'] is None else request.form['address_2']\n customer.city = customer.city if request.form['city'] is None else request.form['city']\n customer.zip = customer.zip if request.form['zip'] is None else request.form['zip']\n customer.country_id = customer.country_id if request.form['country_id'] is None else request.form['country_id']\n customer.region_id = customer.region_id if request.form['region_id'] is None else request.form['region_id']\n customer.user_id = session['user_id']\n\n try:\n customer.save()\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A customer with that email already exists. Could not update.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('customer/update/'+str(customer.id))\n \n\n flash(\"Successfully updated \"+customer.first_name + \" \" + customer.last_name + \" (\" + customer.email + \")\", \"success\")\n return redirect('customer/'+str(customer.id))\n\n@app.route('/customer/remove/')\n@requires_auth\ndef customer_remove(customer_id=None):\n if customer_id is None:\n flash(\"No customer was specified.\", 'danger')\n return redirect('customer')\n \n customer = Customer.find(customer_id)\n\n if customer is None:\n flash(\"No customer matched the specified ID.\", 'danger')\n return redirect('customer')\n\n # Validate that the Customer Can be Deleted\n if customer.user_id != session['user_id'] and User.find(session['user_id']).user_role != 0:\n flash(\"You do not have permission to remove that customer.\", 'warning')\n return redirect('customer')\n\n customer.delete()\n\n flash(\"Successfully removed \"+customer.first_name+\" \"+customer.last_name+\" (\"+customer.email+\")\", 'warning')\n return redirect('customer')\n\n# Opportunities Routes\n@app.route('/opportunity')\n@requires_auth\ndef opportunities_index():\n if request.args.get('filter_phase') is not None:\n opportunities = Opportunity.where('phase_id', int(request.args.get('filter_phase'))).get()\n else:\n opportunities = Opportunity.all()\n phases = Phase.all()\n\n return render_template('opportunities/index.html', opportunities=opportunities, phases=phases)\n\n@app.route('/opportunity/')\n@requires_auth\ndef opportunity_index(opportunity_id = None):\n if opportunity_id is None:\n flash(\"No Opportunity ID Provided\", \"danger\")\n return redirect('/opportunity')\n \n opportunity = Opportunity.find(opportunity_id)\n\n if opportunity is None:\n flash(\"That Opportunity does not Exist\", \"danger\")\n return redirect('/opportunity')\n\n return render_template('opportunities/individual.html', opportunity=opportunity)\n\n@app.route('/opportunity/create', methods=[\"GET\", \"POST\"])\n@requires_one\ndef opportunity_create():\n if request.method == \"GET\":\n return render_template('opportunities/add.html')\n\n if \"title\" not in request.form or request.form[\"title\"] is None or len(request.form[\"title\"]) <= 0:\n flash(\"Please provide a title for the opportunity.\", \"danger\")\n return redirect('/opportunity/create')\n \n try:\n opportunity = Opportunity.create(title=request.form[\"title\"], phase_id=1, user_id=session['user_id'])\n except QueryException as e:\n print(e)\n flash(\"The opportunity could not be added at the moment. Please try again!\", \"danger\")\n return redirect('/opportunity/create') \n\n if \"customer_id\" in request.form and len(request.form.getlist('customer_id')) > 0:\n # Try to match customer\n for customer_id in request.form.getlist('customer_id'):\n customer = Customer.find(customer_id)\n if customer is not None:\n opportunity.customers().attach(customer)\n else:\n flash(\"The Customer ID was Invalid; the Opportunity is Still Being Created, you can add a Customer after.\", \"warning\")\n\n try:\n opportunity.save()\n except QueryException as e:\n print(e)\n flash(\"The opportunity could not be added at the moment. Please try again!\", \"danger\")\n return redirect('/opportunity/create')\n\n flash(\"Successfully added the Opportunity!\", \"success\")\n return redirect('/opportunity/'+str(opportunity.id))\n\n# Product Routes\n@app.route('/product/')\n@requires_auth\ndef product_index(product_id = None):\n if product_id is None:\n flash(\"No product ID entered\", \"danger\")\n return redirect('/product')\n \n product = Product.find(product_id)\n\n if product is None:\n flash(\"That is not a valid product ID.\", \"danger\")\n return redirect('/product')\n \n return render_template('products/individual.html', product=product)\n\n@app.route('/product')\n@requires_auth\ndef products_index():\n products = Product.all()\n return render_template('products/index.html', products=products)\n\n@app.route('/product/create', methods=['GET', 'POST'])\n@requires_zero\ndef product_create():\n\n categories = Category.all()\n\n if request.method == 'GET':\n return render_template('products/add.html', categories=categories)\n\n # Validate All Required Fields\n if \"name\" not in request.form or len(request.form[\"name\"]) <= 0:\n flash(\"A name must be provided.\", \"danger\")\n return redirect('/product/create')\n if \"category\" not in request.form or len(request.form[\"category\"]) <= 0:\n flash(\"A product category must be specified.\", \"danger\")\n return redirect('/product/create')\n if \"customer_price\" not in request.form or len(request.form[\"customer_price\"]) <= 0:\n flash(\"A customer price must be specified.\", \"danger\")\n return redirect('/product/create')\n \n\n # Define all Variables\n name = \"\" if request.form[\"name\"] is None else request.form[\"name\"]\n description = \"\" if request.form[\"description\"] is None else request.form[\"description\"]\n system_id = \"\" if request.form[\"system_id\"] is None else request.form[\"system_id\"]\n category_id = 0 if request.form[\"category\"] is None else request.form[\"category\"]\n subcategory_id = \"\" if request.form[\"subcategory\"] is None else request.form[\"subcategory\"]\n stock = 0 if request.form[\"stock\"] is None or request.form[\"stock\"] == \"\" else request.form[\"stock\"]\n customer_price = 0.00 if request.form[\"customer_price\"] is None or request.form[\"customer_price\"] == \"\" else float(request.form[\"customer_price\"].replace(',',''))\n purchase_price = 0.00 if request.form[\"purchase_price\"] is None or request.form[\"purchase_price\"] == \"\" else float(request.form[\"purchase_price\"].replace(',',''))\n markup = None if request.form[\"markup\"] is None or request.form[\"markup\"] == \"\" else request.form[\"markup\"]\n\n # Create Item\n # ~~TODO: Proper Error Handling in this Route~~\n item = Item(name=name, description=description, category_type='products', category_id=-1)\n try:\n item.save()\n except Exception as e:\n flash(\"Something went wrong. Please try again. If this persists, report: \"+str(e)+\" to the administrator.\", \"danger\")\n return redirect('/product/create')\n \n # Create Product\n if system_id == \"\":\n system_id = str(item.id)\n \n if markup is None and purchase_price != 0.00:\n markup = round(customer_price/purchase_price - 1,4)\n\n try:\n product = Product.create(system_id=system_id, category_id=category_id, subcategory_id=subcategory_id, stock=stock, customer_price=customer_price, purchase_price=purchase_price, markup=markup)\n except Exception as e:\n print(e)\n return \"Something went so very wrong...\"\n \n item.category_id = product.id\n try:\n item.save()\n except Exception as e:\n print(e)\n return \"Something went so very wrong\"\n\n return redirect('/product/'+str(product.id))\n\n\n@app.route('/product/update/', methods=['GET', 'POST'])\n@requires_zero\ndef product_update(product_id = None):\n if product_id is None:\n flash(\"No Product ID was Provided\", \"danger\")\n return redirect('/product')\n \n product = Product.find(product_id)\n item = product.item\n\n if product is None or item is None:\n flash(\"Invalid Product ID\", \"danger\")\n return redirect('/product')\n\n if request.method == 'GET':\n categories = Category.all()\n return render_template('products/update.html', product=product, categories=categories)\n \n # Define all Variables\n item.name = item.name if request.form[\"name\"] is None else request.form[\"name\"]\n item.description = item.description if request.form[\"description\"] is None else request.form[\"description\"]\n product.system_id = product.system_id if request.form[\"system_id\"] is None else request.form[\"system_id\"]\n product.category_id = product.category if request.form[\"category\"] is None else request.form[\"category\"]\n product.subcategory_id = product.subcategory_id if request.form[\"subcategory\"] is None else request.form[\"subcategory\"]\n product.stock = product.stock if request.form[\"stock\"] is None or request.form[\"stock\"] == \"\" else request.form[\"stock\"]\n product.customer_price = product.customer_price if request.form[\"customer_price\"] is None or request.form[\"customer_price\"] == \"\" else float(request.form[\"customer_price\"])\n product.purchase_price = product.purchase_price if request.form[\"purchase_price\"] is None or request.form[\"purchase_price\"] == \"\" else float(request.form[\"purchase_price\"])\n markup = None if request.form[\"markup\"] is None or request.form[\"markup\"] == \"\" else request.form[\"markup\"]\n\n # Create Item\n # ~~TODO: Proper Error Handling in this Route~~\n try:\n item.save()\n except Exception as e:\n flash(\"Something went wrong. Please try again. If this persists, report: \"+str(e)+\" to the administrator.\", \"danger\")\n return redirect('/product')\n \n if markup is None and product.purchase_price != 0.00:\n product.markup = round(product.customer_price/product.purchase_price - 1,4)\n\n try:\n product.save()\n except Exception as e:\n print(e)\n return \"Something went so very wrong\"\n\n return redirect('/product/'+str(product.id))\n\n@app.route('/product//add-cost-breakdown')\n@requires_zero\ndef add_cost_breakdown_to_product(product_id = None):\n if product_id is None:\n flash(\"No product ID specified\", \"danger\")\n return redirect(\"/product\")\n \n product = Product.find(product_id)\n\n if product is None:\n flash(\"The specified product ID is not valid\", \"danger\")\n return redirect(\"/product\")\n \n # ~~TODO: Implement Proper Error Catching~~\n try:\n cost_breakdown = CostBreakdown.create(product_id=product.id)\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A costbreakdown for that product already exists. Please choose a different one.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('/cost-breakdown/create')\n\n return redirect('/cost-breakdown/'+str(cost_breakdown.id)+'/add')\n\n# Cost Breakdown Routes\n@app.route('/cost-breakdown/create', methods=['GET', 'POST'])\n@requires_zero\ndef cost_breakdown_create():\n if request.method == 'GET':\n return render_template('cost_breakdowns/add.html')\n \n # Validate Input\n if \"product_id\" not in request.form or len(request.form[\"product_id\"]) <= 0:\n flash(\"No product ID was provided\", \"danger\")\n return redirect('/cost-breakdown/create')\n \n product = Product.find(request.form[\"product_id\"])\n\n if product is None:\n flash(\"The product ID was not valid\", \"danger\")\n return redirect('/cost-breakdown/create')\n \n # ~~TODO: Implement Proper Error Catching~~\n try:\n cost_breakdown = CostBreakdown.create(product_id=int(request.form[\"product_id\"]))\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A costbreakdown for that product already exists. Please choose a different one.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('/cost-breakdown/create')\n\n return redirect('/cost-breakdown/'+str(cost_breakdown.id)+'/add')\n\n@app.route('/cost-breakdown//add', methods=['GET', 'POST'])\n@requires_zero\ndef cost_breakdown_add(cost_breakdown_id=None):\n if cost_breakdown_id is None:\n flash(\"No Cost Breakdown ID Specified\", \"danger\")\n return redirect('/cost-breakdown/create')\n \n cost_breakdown = CostBreakdown.find(cost_breakdown_id)\n\n if cost_breakdown is None:\n flash(\"Invalid cost breakdown ID specified.\", \"danger\")\n return redirect('/cost-breakdown/create')\n \n if request.method == \"GET\":\n return render_template('cost_breakdowns/breakdown_items.html', cost_breakdown=cost_breakdown)\n \n if \"name\" not in request.form:\n flash(\"At least one name must be provided\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n if \"description\" not in request.form:\n flash(\"An error occurred; no descriptions were found!\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n if \"cost\" not in request.form:\n flash(\"No prices were detected.\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n \n names = request.form.getlist('name')\n descriptions = request.form.getlist('description')\n costs = request.form.getlist('cost')\n\n if names is None or descriptions is None or costs is None:\n flash(\"Could not find names, descriptions, and costs for every line item.\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n \n if len(names) != len(descriptions) or len(descriptions) != len(costs):\n flash(\"Could not find names, descriptions, and costs for every line item.\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n\n items = []\n cost_breakdown_items = []\n\n for cbi in cost_breakdown.cost_breakdown_items:\n cbi.delete()\n\n for i, name in enumerate(names):\n # Create an Item:\n # Name + Description > Set category_id = -1\n # ~~TODO: Proper Error Validation~~\n try:\n items.append(Item.create(name=name, description=descriptions[i], category_id=-1, category_type=\"cost_breakdown_items\"))\n except Exception as e:\n flash(\"Something went wrong. Please try again. If the problem persists, please send the following: \"+str(e)+\" to the administrator.\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n \n try:\n # Create a CostBreakdownItem\n # Cost + Cost_Breakdown.id\n cost_breakdown_items.append(CostBreakdownItem.create(cost_breakdown_id=cost_breakdown.id, customer_price=float(costs[i])))\n # Grab ID from CostBreakdownItem and assign\n # to category ID \n items[i].category_id = cost_breakdown_items[i].id\n items[i].save()\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A costbreakdown for that product already exists. Please choose a different one.\", \"danger\")\n else:\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('/cost-breakdown/'+str(cost_breakdown_id)+'/add')\n return redirect('/product/'+str(cost_breakdown.product.id))\n\n# Inventory Routes\n@app.route('/inventory')\n@requires_auth\ndef inventory_index():\n products = Product.all()\n return render_template(\"inventory/index.html\", products=products)\n\n# Quote Routes\n@app.route('/quote')\n@requires_auth\ndef quotes_index():\n quotes = Quote.all()\n return render_template('quotes/index.html', quotes=quotes)\n\n@app.route('/quote/create', methods=['GET', 'POST'])\n@requires_one\ndef quote_create():\n print(\"WTF\")\n max_quote = Quote.order_by('id', 'desc').first()\n currencies = Currency.all()\n if max_quote is None:\n max_quote = 1\n else:\n max_quote = max_quote.id\n\n if request.method == \"GET\":\n opportunity = None\n if request.args.get('opportunity'):\n opportunity = Opportunity.find(request.args.get('opportunity'))\n if opportunity is not None:\n opportunity = opportunity.serialize()\n return render_template('quotes/add.html', max_quote=max_quote, currencies=currencies, opportunity=opportunity)\n \n # Validate Input\n if \"opportunity_id\" not in request.form or len(request.form[\"opportunity_id\"]) <= 0:\n flash(\"An opportunity must be specified.\", \"danger\")\n return redirect('/quote/create')\n \n opportunity = Opportunity.find(request.form[\"opportunity_id\"])\n\n if opportunity is None:\n flash(\"The opportunity ID is invalid.\", \"danger\")\n return redirect('/quote/create')\n \n\n quote_number = \"\" if request.form[\"quote_number\"] is None else request.form[\"quote_number\"]\n\n if quote_number == \"\":\n quote_number = str(max_quote.id + 999)\n\n opportunity_id = opportunity.id\n user_id = session['user_id']\n currency = \"CAD\" if request.form[\"currency\"] is None or len(request.form[\"currency\"]) <= 0 else request.form[\"currency\"]\n exchange_rate = 1.00 if request.form[\"exchange_rate\"] is None or len(request.form[\"exchange_rate\"]) <= 0 else request.form[\"exchange_rate\"]\n tax_rate = 0.00 if request.form[\"tax_rate\"] is None or len(request.form[\"tax_rate\"]) <= 0 else request.form[\"tax_rate\"]\n\n # ~~TODO: Fix this error checking~~\n try:\n quote = Quote.create(quote_number=quote_number, opportunity_id=opportunity_id, user_id=user_id, currency_id=currency, exchange_rate=exchange_rate, tax_rate=tax_rate)\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n flash(\"A quote with that number already exists. Please choose a different one.\", \"danger\")\n else:\n print(e)\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('/quote/create')\n\n return redirect('/quote/'+str(quote.id)+'/add')\n\n@app.route('/quote//add', methods=['GET', 'POST'])\n@requires_one\ndef quote_add_items(quote_id = None):\n if quote_id is None:\n flash(\"No quote ID was provided.\", \"danger\")\n return redirect('/quote')\n quote = Quote.find(quote_id)\n products = Product.all()\n\n print(quote)\n if quote is None:\n flash(\"The quote ID is not valid.\", \"danger\")\n return redirect('/quote')\n\n if request.method == \"GET\":\n return render_template(\"quotes/add_items.html\", quote=quote, products=products)\n \n if \"quote_id\" not in request.form or len(request.form[\"quote_id\"]) <= 0:\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"No quote ID was provided.\"}), 400\n flash(\"No quote ID was provided.\", \"danger\")\n return redirect('/quote')\n if \"price\" not in request.form or len(request.form[\"price\"]) <= 0:\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"No price was provided.\"}), 400\n flash(\"No price was provided.\", \"danger\")\n return redirect('/quote')\n if \"item_id\" not in request.form or len(request.form[\"item_id\"]) <= 0:\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"No item ID was provided.\"}), 400\n flash(\"No item ID was provided.\", \"danger\")\n return redirect('/quote/'+str(quote_id)+\"/add\")\n if \"item_type\" not in request.form or len(request.form[\"item_id\"]) <= 0:\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"No item type was provided.\"}), 400\n flash(\"No item type was provided.\", \"danger\")\n return redirect('/quote/'+str(quote_id)+\"/add\")\n \n quote_item = QuoteItem()\n\n quote_item.quote_id = request.form[\"quote_id\"]\n quote_item.item_id = request.form[\"item_id\"]\n quote_item.item_type = request.form[\"item_type\"]\n quote_item.price = request.form[\"price\"]\n quote_item.quantity = 1 if request.form[\"quantity\"] is None or len(request.form[\"quantity\"]) <= 0 else request.form[\"quantity\"]\n quote_item.order = 0 if request.form[\"order\"] is None or len(request.form[\"order\"]) <= 0 else request.form[\"order\"]\n \n # ~~TODO: Proper Error Checking~~\n try:\n quote_item.save()\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"A quote with that number already exists. Please choose a different one.\"}), 400\n flash(\"A quote with that number already exists. Please choose a different one.\", \"danger\")\n else:\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"Something went wrong! Please try again.\"}), 400\n flash(\"Something went wrong! Please try again.\", \"danger\")\n if \"ajax_request\" in request.form:\n return jsonify({\"message\", \"Successfully added the quote item!\"}), 200\n return redirect('/quote/'+str(quote_id)+\"/add\")\n\n# Quote Routes\n@app.route('/phase')\n@requires_zero\ndef manage_phases():\n phases = Phase.order_by(\"order\", \"asc\").get()\n return render_template(\"phase/index.html\", phases=phases)\n\n@app.route('/phase/create', methods=['POST'])\n@requires_zero\ndef phase_add_item():\n max_order = Phase.order_by(\"order\", \"desc\").limit(1).get()\n\n if max_order is None:\n max_order = 0\n else:\n max_order = max_order[0].order\n \n\n if \"phase_name\" not in request.form or len(request.form[\"phase_name\"]) <= 0:\n flash(\"No Phase Name was Provided\", \"danger\")\n return redirect('/phase')\n\n phase_name = \"\" if request.form[\"phase_name\"] is None else request.form[\"phase_name\"]\n description = \"\" if \"description\" not in request.form or len(request.form[\"description\"]) <= 0 else request.form[\"description\"]\n order = -1 if \"order\" not in request.form or len(request.form[\"order\"]) <= 0 or request.form['order'] is None else int(request.form[\"order\"])\n\n if order == -1 or order > max_order + 1 or order is None:\n order = max_order + 1\n elif order <= max_order:\n i = max_order \n while i >= order:\n phase = Phase.where(\"order\", i).limit(1).get()\n phase[0].order = i + 1\n try:\n phase[0].save()\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\": \n flash(\"We could not reorder the phases automatically. Sorry.\", \"danger\")\n else:\n flash(\"Something failed when trying to re-order phases! Please try again.\", \"danger\")\n \n return redirect('/phase')\n i -= 1\n\n try:\n phase = Phase.create(phase_name=phase_name, description=description, order=order)\n except QueryException as e:\n if str(e)[0:24] == \"UNIQUE constraint failed\":\n print(e)\n flash(\"A phase with that name already exists. Please choose a different one.\", \"danger\")\n elif str(e)[0:26] == \"NOT NULL constraint failed\":\n flash(\"The phase was tried to be created without an order. An order must be provided.\", \"danger\")\n print(order)\n else:\n print (str(e))\n flash(\"Something went wrong! Please try again.\", \"danger\")\n return redirect('/phase')\n\n return redirect('/phase')\n\n# Category Routes\n@app.route('/categories/manage', methods=['GET', 'POST'])\n@requires_zero\ndef manage_categories():\n categories = Category.all()\n return render_template('categories/manage.html', categories=categories)\n\n# Work Order Routes\n@app.route('/workorder/create-from-quote/')\n@requires_one\ndef create_workorder(quote_id = None):\n if quote_id is None:\n flash(\"No quote ID provided for the workorder.\", \"danger\")\n return redirect(\"/quote\")\n \n quote = Quote.find(quote_id)\n\n if quote is None:\n flash(\"An invalid quote ID was provided for the workorder.\", \"danger\")\n return redirect(\"quote\")\n \n # Add the Work Order Itself;\n work_order = WorkOrder.create(user_id=session['user_id'], \n opportunity_id=quote.opportunity.id, \n work_order_number=quote.quote_number)\n\n # Add the Work Order Items;\n for item in quote.quote_items:\n if item.item_type == 'products' or item.item_type == 'line_items':\n WorkOrderItem.create(work_order_id=work_order.id,\n quantity=item.quantity,\n order=item.order,\n item_id=item.item_id,\n item_type=item.item_type,\n completed=0)\n\n # Redirect to the Work Order;\n flash(\"Successfully added the work order.\", \"success\")\n return redirect('/workorder/'+str(work_order.id))\n\n@app.route('/workorder/')\n@requires_auth\ndef work_order_index(work_order_id=None):\n if work_order_id is None:\n flash(\"No work order ID was provided.\", \"danger\")\n return redirect(\"/\")\n\n work_order = WorkOrder.find(work_order_id)\n\n if work_order is None:\n flash(\"An invalid work order ID was provided.\", \"danger\")\n return redirect(\"/\")\n\n return render_template('workorders/index.html', work_order=work_order)\n\n# TODO: Proper Item Search / Add on Quote Id;\n# TODO: Proper Item / Product Display on Quote Add;\n# TODO: Add Detection of Price When Using Line Items; Offer \"extras\" line if over specified, \"discount\" line if under specified, or to set as total cost.\n# TODO: Add Product Categories; Implement with Search Functionality on Product Add Page\n# TODO: Allow for the Editing of Cost Breakdowns\n# TODO: Allow for the Deletion of Products\n# TODO: Add Customers to Opportunities; Edit Opportunity Titles\n# TODO: jQuery-ify the Customer Price / Purchase Price / Markup to not allow all three to be specified separately\n# TODO: Create Opportunity from Customer Directly\n\nport = os.getenv('PORT', '5000')\n\nif __name__ == \"__main__\":\n app.jinja_env.auto_reload = True\n app.config['TEMPLATES_AUTO_RELOAD'] = True\n app.run(host='0.0.0.0', port=int(port), debug=True)","sub_path":"build/lib/manuhub/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":60973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"487758217","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDjango settings for Django / Webpack Base project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nimport environ\n\nROOT_DIR = environ.Path(__file__) - 3\nAPPS_DIR = ROOT_DIR.path(\"demo\")\n\nenv = environ.Env()\n\n\n# -------------------------------------\n# APP CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\n\nDJANGO_APPS = (\n \"utils\",\n # Default Django apps:\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.sites\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n\n # Useful template tags:\n # 'django.contrib.humanize',\n\n # Admin\n \"django.contrib.admin\",\n)\n\nTHIRD_PARTY_APPS = (\n \"django_extensions\",\n \"webpack_loader\",\n \"rest_framework\",\n)\n\nLOCAL_APPS = (\n # Your stuff: custom apps go here\n \"demo\",\n \"demo.home.apps.DemoHomeConfig\"\n)\n\nINSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS\n\n# -------------------------------------\n# MIDDLEWARE CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes\n\nMIDDLEWARE_CLASSES = (\n \"django.middleware.security.SecurityMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.locale.LocaleMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n)\n\n# -------------------------------------\n# DEBUG CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\n\nDEBUG = env.bool(\"DJANGO_DEBUG\", False)\n\n# -------------------------------------\n# FIXTURE CONFIGURATION\n# -------------------------------------\n# See:\n# https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\n\nFIXTURE_DIRS = (\n str(APPS_DIR.path(\"fixtures\")),\n)\n\n# -------------------------------------\n# EMAIL CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\n\nEMAIL_BACKEND = env(\"DJANGO_EMAIL_BACKEND\",\n default=\"django.core.mail.backends.smtp.EmailBackend\")\n\n# -------------------------------------\n# MANAGER CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\n\nADMINS = (\n (\"admin\", \"admin@admin.com\"),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n\n# -------------------------------------\n# DATABASE CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\n\nDATABASES = {\n # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ\n \"default\": env.db(\"DATABASE_URL\",\n default=\"postgres://vagrant:vagrant@postgres/vagrant\"),\n}\n\n# -------------------------------------\n# GENERAL CONFIGURATION\n# -------------------------------------\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\n\nTIME_ZONE = \"America/Los_Angeles\"\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = \"en\"\n\nLANGUAGES = [\n (\"en\", \"English\"),\n (\"de\", \"German\")\n]\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n\n# -------------------------------------\n# TEMPLATE CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates\n\nTEMPLATES = [\n {\n # See:\n # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n\n # See:\n # https://docs.djangoproject.com/en/dev/ref/settings/#dirs\n \"DIRS\": [\n str(APPS_DIR.path(\"templates\")),\n ],\n\n # See:\n # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-OPTIONS\n \"OPTIONS\": {\n # See:\n # https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\n \"debug\": DEBUG,\n\n # See:\n # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types\n \"loaders\": [\n \"django.template.loaders.filesystem.Loader\",\n \"django.template.loaders.app_directories.Loader\",\n ],\n\n # See:\n # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n # Your stuff: custom template context processors go here\n ],\n },\n },\n]\n\n# -------------------------------------\n# STATIC FILE CONFIGURATION\n# -------------------------------------\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = str(ROOT_DIR(\"staticfiles\"))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = \"/static/\"\n\n# See:\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n str(APPS_DIR.path(\"static\")),\n)\n\n# See:\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = (\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n)\n\n# -------------------------------------\n# MEDIA CONFIGURATION\n# -------------------------------------\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = str(APPS_DIR(\"media\"))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = \"/media/\"\n\n# -------------------------------------\n# URL CONFIGURATION\n# -------------------------------------\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = \"config.urls\"\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = \"config.wsgi.application\"\n\n# -------------------------------------\n# AUTHENTICATION CONFIGURATION\n# -------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#auth\n\nAUTHENTICATION_BACKENDS = (\n \"django.contrib.auth.backends.ModelBackend\",\n)\nACCOUNT_AUTHENTICATION_METHOD = \"username\"\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = \"mandatory\"\nACCOUNT_ALLOW_REGISTRATION = env.bool(\n \"DJANGO_ACCOUNT_ALLOW_REGISTRATION\", True)\n\n\n# -------------------------------------\n# ADMIN CONFIGURATION\n# -------------------------------------\n\n# Location of root django.contrib.admin URL, use {% raw %}{% url\n# \"admin:index\" %}{% endraw %}\nADMIN_URL = r\"^admin/\"\n\n# -------------------------------------\n# WEBPACK CONFIGURATION\n# -------------------------------------\n# See: https://github.com/owais/django-webpack-loader\n\nSTATS_FILE = ROOT_DIR(\"webpack-stats.json\")\nWEBPACK_LOADER = {\n \"DEFAULT\": {\n \"STATS_FILE\": STATS_FILE,\n \"BUNDLE_DIR_NAME\": \"/\"\n }\n}\n\n# -------------------------------------\n# DJANGO REST CONFIGURATION\n# -------------------------------------\n# See: http://www.django-rest-framework.org/\n\nREST_FRAMEWORK = {\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.IsAdminUser\",),\n \"PAGE_SIZE\": 10\n}\n\n# -------------------------------------\n# AUTO-SLUG CONFIGURATION\n# -------------------------------------\n# See: http://pythonhosted.org/django-autoslug/\n\nAUTOSLUG_SLUGIFY_FUNCTION = \"slugify.slugify\"\n\n# -------------------------------------\n# PROJECT CONFIGURATION\n# -------------------------------------\n","sub_path":"django/config/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"173013195","text":"# coding:utf-8\n\ndef fab(n):\n F = [0, 1] # F[0] = 0, F[1] = 1\n if n == 0:\n return F[0]\n if n == 1:\n return F[1]\n for i in range(2, n+1):\n F.append(0)\n F[i] = F[i-1] + F[i-2]\n return F\n\ndef main():\n n = 20\n result = fab(n)\n print(result)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DP/Fibonacci_Series.py","file_name":"Fibonacci_Series.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600899468","text":"import os\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom torchvision import transforms\n\nfrom PIL import Image\nimport numpy as np\n\nimage_dir = 'dogs-vs-cats/train'\n\nimages = os.listdir(image_dir)\n# images = images[:100]\n\ntraining_transformer = transforms.Compose([\n transforms.Resize((320, 320)),\n transforms.ColorJitter(brightness=0.125, contrast=0.125, saturation=0.125),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n\nclass HADataset(data.Dataset):\n def __init__(self, split):\n split_index = 4*len(images)//5\n if split == 'train':\n self.images = images[:split_index]\n else:\n self.images = images[split_index:]\n self.transformer = training_transformer\n print(type(self.transformer))\n def __getitem__(self, i):\n image = self.images[i]\n\n # label = 0 -> dog\n # label = 1 -> cat\n if 'cat' in image:\n label = 1\n else:\n label = 0\n \n image = Image.open(os.path.join(image_dir, image))\n # image = np.array(image)\n image = self.transformer(image)\n return torch.Tensor(image), label\n \n def __len__(self):\n return len(self.images)","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"355471354","text":"import json\nimport logging\nimport unittest\nfrom unittest.mock import call, MagicMock, sentinel\n\nfrom tg import Tg\n\n\nclass BaseRelayTest(unittest.TestCase):\n\n def setUp(self):\n self.bot = Tg(sentinel.token, sentinel.connection)\n self.mock_request = MagicMock()\n self.bot.bot._api_request = self.mock_request\n\n def assert_messages(self, chat_id, messages):\n calls = [call('sendMessage',\n {'chat_id': chat_id, 'text': message})\n for message in messages]\n self.assertEqual(self.mock_request.call_args_list, calls)\n\n\nclass StompRelayTest(BaseRelayTest):\n def test_mock(self):\n self.bot.bot.sendMessage(sentinel.chat_id, sentinel.msg)\n\n self.assert_messages(sentinel.chat_id, (sentinel.msg,))\n\n def test_stomp_single_message(self):\n self.bot.on_message(None, json.dumps({\"to\": {\"chat_id\": \"chat\"},\n \"text\": \"hello, world\"}))\n\n self.assert_messages(\"chat\", (\"hello, world\",))\n\n def test_stomp_multiple_messages_at_once(self):\n self.bot.on_message(None, json.dumps({\"to\": {\"chat_id\": \"chat\"},\n \"text\": [\"hello\", \"world\"]}))\n\n self.assert_messages(\"chat\", (\"hello\", \"world\"))\n\n def test_stomp_error(self):\n with self.assertLogs(\"tg\", logging.DEBUG) as cm:\n self.bot.on_error(None, \"error message\")\n self.assertEqual(cm.output, [f\"ERROR:tg:received an error: error message\"])\n\n\nclass MalformedMessagesTest(BaseRelayTest):\n def test_no_to(self):\n msg = json.dumps({\"text\": \"hello, world\"})\n with self.assertLogs(\"tg\", logging.DEBUG) as cm:\n self.bot.on_message(None, msg)\n\n self.assertEqual(cm.output, [f\"DEBUG:tg:received a message: {msg}\",\n f\"ERROR:tg:Malformed message: {msg}\"])\n self.assert_messages(None, ())\n\n def test_no_chat_id(self):\n msg = json.dumps({\"to\": {}, \"text\": \"hello, world\"})\n with self.assertLogs(\"tg\", logging.DEBUG) as cm:\n self.bot.on_message(None, msg)\n\n self.assertEqual(cm.output, [f\"DEBUG:tg:received a message: {msg}\",\n f\"ERROR:tg:Malformed message: {msg}\"])\n self.assert_messages(None, ())\n\n def test_no_message(self):\n msg = json.dumps({\"to\": {\"chat_id\": \"1234\"}})\n with self.assertLogs(\"tg\", logging.DEBUG) as cm:\n self.bot.on_message(None, msg)\n\n self.assertEqual(cm.output, [f\"DEBUG:tg:received a message: {msg}\",\n f\"ERROR:tg:Malformed message: {msg}\"])\n self.assert_messages(None, ())\n","sub_path":"tests/test_relay.py","file_name":"test_relay.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"57220910","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 12 2021\n\n@author: Enrique Benavides\n\"\"\"\n## Librerias ##\nimport serial\nimport time\nimport sys\nfrom aruco_camera import Camera, ArucoTracker\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport funciones as fx\n\n### Diccionarios ###\nrobots = dict(ram01 = \"COM9\", \n ram02 = \"COM11\", \n ram03 = \"COM14\", \n ram04 = \"COM16\", \n ram05 = \"COM17\",\n ram = \"COM4\")\nARUCO_DICT = {\n \t\"DICT_4X4_50\": cv2.aruco.DICT_4X4_50,\n \t\"DICT_4X4_100\": cv2.aruco.DICT_4X4_100,\n \t\"DICT_4X4_250\": cv2.aruco.DICT_4X4_250,\n \t\"DICT_4X4_1000\": cv2.aruco.DICT_4X4_1000,\n \t\"DICT_5X5_50\": cv2.aruco.DICT_5X5_50,\n \t\"DICT_5X5_100\": cv2.aruco.DICT_5X5_100,\n \t\"DICT_5X5_250\": cv2.aruco.DICT_5X5_250,\n \t\"DICT_5X5_1000\": cv2.aruco.DICT_5X5_1000,\n \t\"DICT_6X6_50\": cv2.aruco.DICT_6X6_50,\n \t\"DICT_6X6_100\": cv2.aruco.DICT_6X6_100,\n \t\"DICT_6X6_250\": cv2.aruco.DICT_6X6_250,\n \t\"DICT_6X6_1000\": cv2.aruco.DICT_6X6_1000,\n \t\"DICT_7X7_50\": cv2.aruco.DICT_7X7_50,\n \t\"DICT_7X7_100\": cv2.aruco.DICT_7X7_100,\n \t\"DICT_7X7_250\": cv2.aruco.DICT_7X7_250,\n \t\"DICT_7X7_1000\": cv2.aruco.DICT_7X7_1000,\n \t\"DICT_ARUCO_ORIGINAL\": cv2.aruco.DICT_ARUCO_ORIGINAL,\n \t\"DICT_APRILTAG_16h5\": cv2.aruco.DICT_APRILTAG_16h5,\n \t\"DICT_APRILTAG_25h9\": cv2.aruco.DICT_APRILTAG_25h9,\n \t\"DICT_APRILTAG_36h10\": cv2.aruco.DICT_APRILTAG_36h10,\n \t\"DICT_APRILTAG_36h11\": cv2.aruco.DICT_APRILTAG_36h11\n }\n### Diccionarios ###\n\n### Funciones ###\n\ndef main():\n print(\"Iniciando Programa\")\n tracker_top = ArucoTracker()\n tracker_bottom = ArucoTracker()\n ##### Variables Fijas #####\n #### Variables de movimiento ####\n V0 = 0.15; # Velocidad lineal m/s\n rho0 = 0.4 # Radio de giro \n w0 = V0/rho0; # Frecuencia natural\n \n #### Partículas en el plano ####\n N = 2;\n M = N;\n R0 = 0 + 0*1j;\n kappa = w0;\n A = np.ones([N,N]);\n \n #### Variables del robot ####\n r_llanta = 0.032/2\n L = 0.085\n # Ks = np.array([[0.005,0.1,0.005,0.5,0.1,0.5]]) # [Cx,Cxk,Cxi,Cy,Cyk,K]\n Ks = np.array([[0.015,0.1,0.005,1.5,0.1,0.5]]) # [Cx,Cxk,Cxi,Cy,Cyk,K]\n Ks = np.array([[0.005,0.1,0.005,0.5,0.1,0.5]]) # [Cx,Cxk,Cxi,Cy,Cyk,K]\n \n #### Variables de tiempo ####\n tf = 30\n dt = 0.1\n tact = 0; tant = 0\n \n #####\n #### Conexión con Robots ####\n tag1 = '1'\n tag2 = '2'\n try:\n print('RAM01')\n RAM01 = serial.Serial(robots['ram01'],9600)\n time.sleep(1.0)\n except:\n sys.exit()\n print(\"Error Comunicación RAM01\")\n \n try:\n print('RAM02')\n RAM02 = serial.Serial(robots['ram03'],9600)\n time.sleep(1.0)\n except:\n sys.exit()\n print(\"Error Comunicación RAM03\")\n \n \n #### Conexión con cámara ####\n camera_top = Camera(src = 2).start()\n camera_bottom = Camera(src = 1).start()\n \n #### Variables para graficar ####\n x_par = np.zeros((1,N)); y_par = np.zeros((1,N)); xi_par = np.zeros((1,N))\n x = np.zeros((1,N)); y = np.zeros((1,N)); xi = np.zeros((1,N))\n \n Xr = np.zeros((1,N)); Yr = np.zeros((1,N)); Xir = np.zeros((1,N))\n err_x = np.zeros((1,N)); err_y = np.zeros((1,N)); err_xi = np.zeros((1,N))\n v = np.zeros((1,N)); w = np.zeros((1,N))\n r = np.zeros((1,N),dtype=complex); theta = np.zeros((1,N))\n t = []; t2 = []\n \n #### Condiciones iniciales ####\n X0 = np.zeros((1,N)); Y0 = np.zeros((1,N)); Xi0 = np.zeros((1,N))\n cal = False;\n adjust_cs = False\n while cal == False:\n frame_bottom = camera_bottom.read()\n frame_top = camera_top.read()\n \n frame_top = cv2.cvtColor(frame_top, cv2.COLOR_BGR2GRAY)\n ret3_top,frame_top = cv2.threshold(frame_top,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n \n frame_bottom = cv2.cvtColor(frame_bottom, cv2.COLOR_BGR2GRAY)\n ret3_bottom,frame_bottom = cv2.threshold(frame_bottom,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\n tag_poses = tracker_top.aruco_pose(frame_top) # returns dictionary with values 'x', 'y', 'theta'\n tracker_bottom.calibrated = True\n tracker_bottom.scale = tracker_top.scale\n \n tag_poses2 = tracker_bottom.aruco_pose(frame_bottom)\n if not adjust_cs :\n tracker_bottom.cs['y'] -= 0.04\n tag_poses2 = tracker_bottom.aruco_pose(frame_bottom)\n adjust_cs = True\n\n tag_poses.update(tag_poses2)\n \n try:\n X0[0,0] = tag_poses[tag1]['x']; Y0[0,0] = tag_poses[tag1]['y']; Xi0[0,0] = -tag_poses[tag1]['theta']\n X0[0,1] = tag_poses[tag2]['x']; Y0[0,1] = tag_poses[tag2]['y']; Xi0[0,1] = -tag_poses[tag2]['theta']\n cal = True\n except:\n print(\"no tag\")\n \n print(\"5s\")\n time.sleep(1)\n print(\"4s\")\n time.sleep(1)\n print(\"3s\")\n time.sleep(1)\n print(\"2s\")\n time.sleep(1)\n print(\"1s\")\n time.sleep(1)\n \n #### Prealocación de variables ####\n r0 = X0 + Y0*1j\n theta0 = Xi0 + np.pi/2\n t0 = time.time()\n \n tant_a = 0\n t = np.append(t,tact)\n t2 = np.append(t2,tact)\n \n r_ant = np.zeros((1,N),dtype = complex)\n theta_ant = np.zeros((1,N))\n r_ant[0,:] = r0\n theta_ant[0,:] = theta0\n r[0,:] = r0\n theta[0,:] = theta0\n \n x[0,:] = X0; y[0,:] = Y0; xi[0,:] = Xi0\n Xr[0,:] = X0; Yr[0,:] = Y0; Xir[0,:] = Xi0\n \n v_par = np.zeros((1,N))\n w_par = np.zeros((1,N))\n \n print(\"Iniciando ciclo\")\n while tact <= tf:\n tact = time.time() - t0\n tact_a = tact\n \n if (tact_a - tant_a) >= dt/5:\n \n ## Obtener posición y orientación\n frame_bottom = camera_bottom.read()\n frame_top = camera_top.read()\n \n frame_top = cv2.cvtColor(frame_top, cv2.COLOR_BGR2GRAY)\n ret3_top,frame_top = cv2.threshold(frame_top,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n \n frame_bottom = cv2.cvtColor(frame_bottom, cv2.COLOR_BGR2GRAY)\n ret3_bottom,frame_bottom = cv2.threshold(frame_bottom,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\n tag_poses = tracker_top.aruco_pose(frame_top) # returns dictionary with values 'x', 'y', 'theta'\n tag_poses2 = tracker_bottom.aruco_pose(frame_bottom)\n\n tag_poses.update(tag_poses2)\n \n try:\n x_par[0,0] = tag_poses[tag1]['x']; y_par[0,0] = tag_poses[tag1]['y']; xi_par[0,0] = -tag_poses[tag1]['theta']\n x_par[0,1] = tag_poses[tag2]['x']; y_par[0,1] = tag_poses[tag2]['y']; xi_par[0,1] = -tag_poses[tag2]['theta']\n t = np.append(t,tact_a)\n x = np.append(x,x_par)\n y = np.append(y,y_par)\n xi = np.append(xi,xi_par)\n except:\n # x_par = x_par + v_par*np.cos(xi_par)*(tact_a - tant_a)\n # y_par = y_par + v_par*np.sin(xi_par)*(tact_a - tant_a)\n # xi_par = xi_par + w_par*(tact_a - tant_a)\n print(\"no tag\")\n \n tag_poses.clear()\n tag_poses2.clear()\n tant_a = tact_a\n \n if tact - tant >= dt:\n dtt = tact - tant\n #### Partículas en el plano ####\n u_par = fx.steeringControl(V0,w0,r_ant,theta_ant,R0,kappa,N,M,A)\n # u_par = np.array([w0,w0])\n # u_par = np.array([0,0])\n [r_act,theta_act] = fx.particlesPlane(V0,r_ant,theta_ant,u_par,dtt)\n \n r = np.append(r,r_act)\n theta = np.append(theta,theta_act)\n \n #### Referencias ####\n Xr_par = r_act.real\n Yr_par = r_act.imag\n Xir_par = theta_act\n # print(Xir_par)\n Xir_par = np.mod(Xir_par,(2*np.pi)) - np.pi/2\n for i in range(N):\n if Xir_par[0,i] > np.pi:\n Xir_par[0,i] -= 2*np.pi\n \n t2 = np.append(t2,tact)\n Xr = np.append(Xr,Xr_par)\n Yr = np.append(Yr,Yr_par)\n Xir = np.append(Xir,Xir_par)\n \n #### Errores ####\n err_xi_par = Xir_par - xi_par\n for i in range(N):\n if np.abs(err_xi_par[0,i]) > np.pi:\n err_xi_par[0,i] = err_xi_par[0,i] - np.sign(err_xi_par[0,i])*2*np.pi\n \n err_x_par = np.cos(xi_par)*(Xr_par - x_par) + np.sin(xi_par)*(Yr_par - y_par);\n err_y_par = -np.sin(xi_par)*(Xr_par - x_par) + np.cos(xi_par)*(Yr_par - y_par);\n \n err_xi = np.append(err_xi,err_xi_par)\n err_x = np.append(err_x,err_x_par)\n err_y = np.append(err_y,err_y_par)\n \n #### Control Uniciclo ####\n \n [v_par,w_par] = fx.trackingControl(V0,fx.etheta(theta_act,V0),u_par,err_xi_par,err_x_par,err_y_par,Ks,A)\n \n for i in range(N):\n if v_par[i] < 0:\n v_par[i] = 0\n \n v = np.append(v,v_par)\n w = np.append(w,w_par)\n \n #### Calcular velocidades de llanta #### Giro estático\n # vd = (2*V0 + w0*L)/(2*r_llanta)\n # vi = (2*V0 - w0*L)/(2*r_llanta)\n \n #### Calcular velocidades de llanta #### Giro control de posición\n vd = (2*v_par + w_par*L)/(2*r_llanta)\n vi = (2*v_par - w_par*L)/(2*r_llanta)\n \n #### Enviar datos a uniciclo ####\n \n cad = \"@W\" + str(round(vd[0],1)) + \"D\" + str(round(vi[0],1)) + \"I#\"\n # print(cad)\n RAM01.write(cad.encode('ascii'))\n cad = \"@W\" + str(round(vd[1],1)) + \"D\" + str(round(vi[1],1)) + \"I#\"\n # print(cad)\n RAM02.write(cad.encode('ascii'))\n \n theta_ant = theta_act\n r_ant = r_act\n tant = tact\n print(tact)\n \n \n cad = \"@W0D0I#\"\n RAM01.write(cad.encode('ascii'))\n RAM02.write(cad.encode('ascii'))\n \n RAM01.close()\n RAM02.close()\n \n camera_top.stop()\n camera_bottom.stop()\n \n \n #### Impresión de variables ####\n x = x.reshape((-1,N))\n y = y.reshape((-1,N))\n xi = xi.reshape((-1,N))\n \n err_x = err_x.reshape((-1,N))\n err_y = err_y.reshape((-1,N))\n err_xi = err_xi.reshape((-1,N))\n \n v = v.reshape((-1,N))\n w = w.reshape((-1,N))\n \n Xr = Xr.reshape((-1,N))\n Yr = Yr.reshape((-1,N))\n Xir = Xir.reshape((-1,N))\n \n #### Impresión de variables ####\n labels = [\"RAM01\",\"RAM02\"]\n labels_r = [\"RAM01r\",\"RAM02r\"]\n color = ['r','g']\n color_r = ['r--','g--']\n plt.close('all')\n\n fig, axs = plt.subplots(3,figsize=(15,10))\n fig.suptitle('Estados')\n axs[0].grid()\n axs[1].grid()\n axs[2].grid()\n \n for k in range(N):\n axs[0].plot(t,x[:,k], color[k])\n axs[0].plot(t2,Xr[:,k], color_r[k])\n axs[1].plot(t,y[:,k], color[k])\n axs[1].plot(t2,Yr[:,k], color_r[k])\n axs[2].plot(t,xi[:,k], color[k], label = labels[k])\n axs[2].plot(t2,Xir[:,k], color_r[k], label = labels_r[k])\n \n axs[0].set(xlabel = \"t [s]\", ylabel = \"x [m]\")\n axs[1].set(xlabel = \"t [s]\", ylabel = \"y [m]\")\n axs[2].set(xlabel = \"t [s]\", ylabel = \"xi [rad]\")\n axs[2].legend(bbox_to_anchor = (0.5,0), loc = \"lower center\", bbox_transform = fig.transFigure, ncol = N)\n \n ##### Errores #####\n fig, axs = plt.subplots(3,figsize=(15,10))\n fig.suptitle('Errores')\n axs[0].grid()\n axs[1].grid()\n axs[2].grid()\n \n for k in range(N):\n axs[0].plot(t2,err_x[:,k], color[k])\n axs[1].plot(t2,err_y[:,k], color[k])\n axs[2].plot(t2,err_xi[:,k], color[k], label = labels[k])\n\n axs[0].set(xlabel = \"t [s]\", ylabel = \"error x [m]\")\n axs[1].set(xlabel = \"t [s]\", ylabel = \"error y [m]\")\n axs[2].set(xlabel = \"t [s]\", ylabel = \"error xi [rad]\")\n axs[2].legend(bbox_to_anchor = (0.5,0), loc = \"lower center\", bbox_transform = fig.transFigure, ncol = N)\n \n ##### Salidas #####\n fig, axs = plt.subplots(2,figsize = (15,10))\n fig.suptitle('Salidas')\n axs[0].grid()\n axs[1].grid()\n axs[0].set_title(\"Velocidad lineal\")\n axs[1].set_title(\"Velocidad angular\")\n\n for k in range(N):\n axs[0].plot(t2,v[:,k], color[k])\n axs[1].plot(t2,w[:,k], color[k], label = labels[k])\n\n axs[0].set(xlabel = \"t [s]\", ylabel = \"[m/s]\")\n axs[1].set(xlabel = \"t [s]\", ylabel = \"[rad/s]\")\n axs[1].legend(bbox_to_anchor = (0.5,0), loc = \"lower center\", bbox_transform = fig.transFigure, ncol = N)\n \n ##### Plano Fase #####\n fig = plt.figure(figsize=(10,10))\n plt.grid()\n plt.title('Plano Fase')\n\n for k in range(N):\n plt.plot(Xr[:,k],Yr[:,k], color[k], label = labels_r[k])\n plt.plot(x[:,k],y[:,k], color_r[k], label = labels[k])\n\n plt.xlabel(\"X [m]\")\n plt.ylabel(\"Y [m]\")\n plt.legend(bbox_to_anchor = (0.5,0), loc = \"lower center\", bbox_transform = fig.transFigure, ncol = N)\n \n np.savez('DATA/data2',robots=N,tiempo=t,tiempo2=t2,Xref=Xr,Yref=Yr,Xiref=Xir,xest=x,yest=y,xiest=xi,errx=err_x,erry=err_y,errxi=err_xi,vellin=v,velang=w) #,veleva=v_eva\n\n########## Programa ##########\nif __name__ == '__main__':\n main()","sub_path":"CONDA/Experimental/PRUEBA_2Robot_CloseLoop.py","file_name":"PRUEBA_2Robot_CloseLoop.py","file_ext":"py","file_size_in_byte":13449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"541924827","text":"from flask import Flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.security import SQLAlchemyUserDatastore, Security\nfrom flask.ext.security.utils import encrypt_password\n\napp = Flask(__name__)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\n\nfrom .models import User, Role\nfrom .forms import HICRegisterForm\n\n# Setup Flask-Security\nuser_datastore = SQLAlchemyUserDatastore(db, User, Role)\nsecurity = Security(app, user_datastore, register_form=HICRegisterForm)\n\nfrom app import views, models\n\n# Create a user to test with\n@app.before_first_request\ndef init_app():\n db.create_all()\n setup_roles()\n setup_users()\n\n\ndef setup_users():\n if not User.query.first():\n user = user_datastore.create_user(\n email='ajay.ranipeta@yale.edu',\n password=encrypt_password('password'),\n name='Ajay Ranipeta')\n\n role = user_datastore.find_role('HIC_ADMIN')\n user_datastore.add_role_to_user(user, role)\n db.session.commit()\n\n\ndef setup_roles():\n if not Role.query.first():\n user_datastore.find_or_create_role(\n name='HIC_ADMIN',\n description='HIC administrator'\n )\n user_datastore.find_or_create_role(\n name='HIC_DATA_MANAGER',\n description='HIC data manager'\n )\n user_datastore.find_or_create_role(\n name='HIC_VALIDATOR',\n description='HIC data validator'\n )\n user_datastore.find_or_create_role(\n name='HIC_USER',\n description='General HIC user'\n )\n\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"466897059","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 18-7-13\n\n@author: Suspext\n\"\"\"\nimport xgboost as xgb\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nxgb_params = { # default\n 'booster': 'gbtree', # gbtree\n 'silent': 0, # 0\n 'nthread': -1, # max thread\n\n 'eta': 0.4, # 0.3\n 'min_child_weight': 1, # 1\n 'max_depth': 6, # 6\n 'gamma': 1.55, # 0\n 'max_delta_step': 10, # 0\n 'subsample': 1, # 1\n 'colsample_bytree': 0.6, # 1\n 'colsample_bylevel': 1, # 1\n 'lambda': 1, # 1\n 'alpha': 1, # 1\n 'scale_pos_weight': 1, # 1\n\n 'objective': 'binary:logistic', # reg:linear\n 'eval_metric': 'error', # reg:'rmse',cls\"'error'\n 'n_estimators': 200,\n 'verbose': True,\n 'early_stop': 100,\n}\n\n\ndef classifier(X_train, y_train, X_val, y_val, params,\n metric=None, verbose=False, early_stop=None):\n if metric is None:\n metric = params['eval_metric']\n if early_stop is None:\n early_stop = params['early_stop']\n\n model = xgb.XGBClassifier(**params)\n model.fit(X_train, y_train,\n eval_set=[(X_val, y_val)],\n eval_metric=metric,\n verbose=verbose,\n early_stopping_rounds=early_stop)\n y_pred = model.predict(X_val)\n return y_pred\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"Model/ML/xgboost.py","file_name":"xgboost.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"646520260","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 21 09:15:11 2018\n\n@author: Stian\n\"\"\"\n\n\nfrom tkinter import *\nfrom PIL import Image,ImageFilter\nfrom PIL import ImageTk\nimport Bj_3\nimport time\nimport chipModule as cm\n\n\npmove = 0\ndmove = 0\ncmove = 0\n\n\nroot = Tk()\nroot.geometry('1280x780')\nroot.configure(bg='green')\n\nroot.grid_rowconfigure(1, weight=1)\nroot.grid_columnconfigure(1, weight=1)\n\nmyFrame = Frame(root,bg='red',width=1280, height=780)\n#Create Canvas\ncanvas = Canvas(root,width=1280,height=700,bg='GRAY',highlightthickness=0)\n#Title of application\nroot.title('BJ Boys')\n\n\nbjlogo2 = Image.open('assets/bjlogo.png')\npilImage = Image.open(\"assets/bjtable.png\")\nbjlogo = Image.open('assets/bjlogo.png')\n\nrez = pilImage.resize((1280,750))\nrezbjlogo = bjlogo.resize((250,175))\n\nimagebjbg = ImageTk.PhotoImage(rez,master=root)\nimagebjlogo = ImageTk.PhotoImage(rezbjlogo,master=root)\n\ncardPath = Image.open('assets/cards/s13.png')\nresCard = cardPath.resize((100,100))\nCardVar = ImageTk.PhotoImage(resCard,master=root)\n\n\n#slider\nw = Scale(myFrame, from_=0, to=50,orient=HORIZONTAL,tickinterval=10,length=600)\nw.grid(sticky='nw',row=1, column=1)\n\n\n#___________________put an image on main canvas________________________________\ncardList=[]\ndef createImg(x,y,inputImage,anc):\n global newCard\n global cardList\n cardList.append(inputImage)\n imagesprite = canvas.create_image(x,y,image=cardList[-1],anchor=anc)\n#_______________________draw card in correct position__________________________\n\n \ncreateImg(0,0,imagebjbg,NW)\ncreateImg(0,-45,imagebjlogo,NW)\n \ndef civ(plyr, key): #create image variables\n global cardPath\n global resCard\n global CardVar\n global pmove\n global dmove\n global cmove\n import Bj_3\n \n getDict=str(key[0])\n card_value = key[:0] + key[1:]\n card_value = int(card_value)-1\n newKey = getDict + str(card_value)\n \n \n cardPath = Image.open('assets/cards/%s.png' %(newKey))\n resCard = cardPath.resize((100,100))\n CardVar = ImageTk.PhotoImage(resCard,master=root)\n if plyr[0].lower() == 'p':\n createImg(600+pmove,500,CardVar,CENTER)\n pmove = pmove + 75\n elif plyr[0].lower() == 'd':\n createImg(600+dmove,210,CardVar,CENTER)\n dmove = dmove + 75\n\n else:\n print('broken inside civ() couldnt find plyr')\n \ndef chipCreate(num):\n global cmove\n chipPath = Image.open('assets/chip.png')\n resChip = chipPath.resize((65,65))\n chipImg = ImageTk.PhotoImage(resChip,master=root)\n x=0\n while x < num:\n createImg(516+(cmove/5),547 - cmove,chipImg,CENTER)\n cmove = cmove + 5\n x = x + 1\n \ndef obank():\n import bank as bk\n bank = Tk()\n bank.geometry('428x378')\n \n loginFrame = Frame(bank,width=628,height=678)\n \n entry1 = Entry(loginFrame)\n entry2 = Entry(loginFrame)\n entry3 = Entry(loginFrame)\n \n \n Label(loginFrame, text=\"user name\").grid(row=1,column=2)\n Label(loginFrame, text=\"password\").grid(row=3,column=2)\n Label(loginFrame, text=\"password\").grid(row=3,column=2)\n\n T = Text(bank, height=2, width=30)\n T.pack()\n\n enBtn = Button(loginFrame, text='login', command=lambda: T.insert(CURRENT,bk.login_output(entry1.get(),entry2.get()))) \n enBtn.config(fg='black',height=4,width=7)\n enBtn.grid(sticky='nW',row=2,column=3)\n \n enBtn_2 = Button(loginFrame, text='get saldo', command=lambda: T.insert(CURRENT,str(bk.get_saldo_output()+'\\n'))) \n enBtn_2.config(fg='black',height=4,width=7)\n enBtn_2.grid(sticky='nW',row=2,column=4,rowspan=2)\n \n enBtn_3 = Button(loginFrame, text='Buy chips', command=lambda: T.insert(CURRENT,bk.buychips(bk.current_user,int(entry3.get())))) \n enBtn_3.config(fg='black',height=4,width=7)\n enBtn_3.grid(sticky='nW',row=13,column=2)\n \n enBtn_4 = Button(loginFrame, text='Sell chips', command=lambda: T.insert(CURRENT,bk.cashInChips(bk.current_user,int(entry3.get())))) \n enBtn_4.config(fg='black',height=4,width=7)\n enBtn_4.grid(sticky='nW',row=13,column=3)\n \n entry1.grid(row=2,column=2)\n entry2.grid(row=4,column=2)\n entry3.grid(row=14,column=2)\n loginFrame.pack(side=\"top\",fill=\"both\",expand=True)\n bank.mainloop()\n \nglobal chipsOnTable \nchipsOnTable = 0 \n \n#____________________________Calling start in Bj_3________________________________\ndef startBJ():\n import Bj_3\n import chipModule as cm\n print('starting BJ')\n tcommand('place your bet\\n')\n tcommand('Chips: %d\\n' %(cm.ChipWallet()) )\n betBtn.config(state=\"normal\")\n startBtn.configure(state=\"disabled\")\n hitBtn.config(state=\"normal\")\n standBtn.config(state=\"normal\")\n resetBtn.configure(state='disabled')\n Bj_3.start()\n \n#__________________________Draws text to table on canvas_______________________ \ntextList = [0]\n\ndef drawText(person,txt):\n try:\n print('drawText(): deleted: %d' %(textList[0]))\n canvas.delete(textList[0])\n textList.pop()\n except IndexError:\n print('list was empty did not pop')\n finally:\n if person[0].lower() == 'd':\n a = canvas.create_text(625,130,fill=\"black\",font=\"Arial 25\",text=txt)\n textList.append(a)\n \n#__________________________Draws text to table on canvas_______________________ \ntextList = [0]\n\ndef drawText(person,txt):\n try:\n canvas.delete(textList[0])\n textList.pop()\n except IndexError:\n print('list was empty did not pop')\n finally:\n if person[0].lower() == 'd':\n a = canvas.create_text(625,130,fill=\"black\",font=\"Arial 25\",text=txt)\n textList.append(a)\n\n\n \n#______________________________________________________________________________\n\n#________________hit or stand function_________________________________________\ndef hors(choice):\n import Bj_3\n if choice == 'hit': #player wants to hit, get a new card\n Bj_3.drawCard('player','hit')\n elif choice == 'stand': #player does not want to hit, dealer hits\n Bj_3.drawCard('player','stand')\n else:\n print('broke inside hors() function')\n#__________________resets table and game_______________________________________ \ndef reset():\n print('\\n\\n\\n RESETTING \\n\\n\\n')\n global pmove\n global dmove\n global cmove\n global cardList\n hitBtn.config(state=\"normal\")\n for i in cardList:\n cardList.pop()\n canvas.delete(\"all\")\n createImg(0,0,imagebjbg,NW)\n createImg(0,-45,imagebjlogo,NW)\n startBtn.config(state='normal')\n betBtn.config(state='normal')\n hitBtn.config(state='disabled')\n standBtn.config(state='disabled')\n resetBtn.config(state='disabled')\n \n pmove = 0\n dmove = 0\n cmove = 0\n import Bj_3\n Bj_3.reset()\n#___________________Closes application_________________________________________\ndef closeApp():\n root.destroy()\n \ndef callback(event):\n print('X: %d, Y: %d' %(event.x,event.y) )\n drawText('Dealer','mullar krekar 123 fire fem')\n \ncanvas.bind(\"\", callback) \n \n \n \n#___________________creates buttons____________________________________________ \n\ndef command(count):\n tbox.insert(CURRENT,'Player score: %d\\n'%(count))\ndef tcommand(tekst):\n tbox.insert(CURRENT,str(tekst))\n\n\n\ndef bjWin():\n global chipsOnTable\n print('called bjWin')\n tcommand('you won: %d chips\\n' %(chipsOnTable))\n cm.getChips(chipsOnTable)\n tcommand('you have: %d chips\\n' %(cm.ChipWallet()))\n chipsOnTable = 0\n standBtn.configure(state='disabled')\n resetBtn.configure(state='normal')\n \ndef bjLoose():\n global chipsOnTable\n print('called bjLoose')\n tcommand('you lost: %d chips\\n' %(chipsOnTable))\n cm.removeChips(chipsOnTable)\n tcommand('you have: %d chips\\n' %(cm.ChipWallet()))\n chipsOnTable = 0\n resetBtn.configure(state='normal')\n standBtn.configure(state='disabled')\n\n\n\ndef bet():\n import chipModule as cm\n global chipsOnTable\n betBtn.configure(state='disabled')\n bs = w.get()\n chipsOnTable = bs\n w.set(1)\n chipCreate(chipsOnTable)\n totalChips = cm.ChipWallet() - chipsOnTable\n cm.removeChips(bs)\n tcommand('betted %d, %d left\\n' %(chipsOnTable,totalChips))\n return bs\n\n#buttons\nbetBtn = Button(myFrame, text='bet',command=lambda: bet())\nbetBtn.config(fg='black',height=4,width=7,state=\"disabled\")\nbetBtn.grid(sticky='nW',row=1,column=2,rowspan=5)\n\nbankBtn = Button(myFrame, text='Bank', command=lambda: obank())\nbankBtn.config(fg='black',height=4,width=7)\nbankBtn.grid(sticky='sW',row=1,column=3,rowspan=5)\n\n\nhitBtn = Button(myFrame, text='Hit',command=lambda: hors('hit'))\nhitBtn.config(fg='black',height=4,width=7,state=\"disabled\")\nhitBtn.grid(sticky='sW',row=1,column=4,rowspan=5)\n\nstandBtn = Button(myFrame, text='Stand',command=lambda: hors('stand'))\nstandBtn.config(fg='black',height=4,width=7,state=\"disabled\")\nstandBtn.grid(sticky='sW',row=1,column=5,rowspan=5)\n\n\nstartBtn = Button(myFrame, text='Start',command=lambda: startBJ())\nstartBtn.config(fg='black',height=4,width=6)\nstartBtn.grid(sticky='se',row=1,column=8,rowspan=5)\n\nresetBtn = Button(myFrame, text='Reset',command=lambda: reset())\nresetBtn.config(fg='black',height=4,width=6,state=\"disabled\")\nresetBtn.grid(sticky='se',row=1,column=9,rowspan=5)\n\nendBtn = Button(myFrame, text='Exit', command=lambda: closeApp())\nendBtn.config(fg='black',height=4,width=6, highlightbackground='#3E4149')\nendBtn.grid(sticky='se',row=1,column=10,rowspan=5)\n\ntbox = Text(myFrame, height=4, width=20)\ntbox.grid(sticky='se',row=1,column=20,rowspan=5)\n\nwbox = Text(myFrame, height=4, width=12)\nwbox.configure(bg='lightgray')\nwbox.grid(sticky='se',row=1,column=19,rowspan=5)\ncanvas.pack(side=\"top\", fill=\"both\", expand=True)\nmyFrame.pack(side=\"top\", fill=\"both\", expand=True)\nroot.mainloop()\n\n\n\n","sub_path":"BlackJackProject/blackJackGUI.py","file_name":"blackJackGUI.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"159280955","text":"# This file has two main purposes\n# 1) To be run on a raspberry pi long term to gather\n# test images to the output_dir. The goal is simply\n# to look for motion, save the image, and sort them\n# later for feeding into a machine learning system\n#\n# 2) To serve as a debug platform to evaluate various\n# motion capture and/or machine learning algorithms\n#\n# It is still somewhat crude...\n\nimport numpy as np\nimport cv2\nimport time\nimport imutils\nimport datetime\nimport os\nimport argparse\nfrom CameraStream import CameraStream\nimport json\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-v\", \"--video\", help=\"path to video\")\nargs = vars(ap.parse_args())\n\nconf = json.load(open(\"conf.json\"))\n\ncam = CameraStream(resolution=tuple(conf[\"resolution\"])).start()\ntime.sleep(2.0)\n\n#fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()\n#fgbg = cv2.bgsegm.createBackgroundSubtractorCNT()\nfgbg = cv2.bgsegm.createBackgroundSubtractorMOG()\n\nmovement_detected = False\n\nif conf[\"save_capture_files\"]:\n try:\n os.makedirs('output_dir')\n except OSError:\n pass\n\nmark_time = datetime.datetime.now()\nframe_number = 0\nframe_writes = 0\n\nwhile True:\n\n if (datetime.datetime.now() - mark_time).seconds >= 10:\n fps = frame_number / float(((datetime.datetime.now() - mark_time).seconds))\n print(\"frames per second: \" + str(fps) + \" writes: \" + str(frame_writes))\n mark_time = datetime.datetime.now()\n frame_number = 0\n frame_writes = 0\n\n frame_number = frame_number + 1\n\n frame_orrig = cam.read()\n\n if( datetime.datetime.now().hour < conf[\"start_hour\"]):\n continue\n elif( datetime.datetime.now().hour >= conf[\"stop_hour\"]):\n continue\n\n #sizing stuff\n frame = imutils.resize(frame_orrig, width=(conf[\"resize_width\"]))\n\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #gray = cv2.GaussianBlur(gray, (21,21), 0)\n\n fgmask = fgbg.apply(frame)\n\n thresh = cv2.threshold(fgmask, 25, 255, cv2.THRESH_BINARY)[1]\n #dilate the threshold image to fill in holes, then find contours\n #on the threshold image\n thresh = cv2.dilate(thresh, None, iterations=2)\n _, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n #loop over the contours\n movement_detected = False\n biggest_area = 0\n height, width, channels = frame.shape\n for c in cnts:\n if cv2.contourArea(c) < (conf[\"movement_ratio_min\"]*height*width):\n continue\n if cv2.contourArea(c) > (conf[\"movement_ratio_max\"] * height * width):\n continue\n if cv2.contourArea(c) > biggest_area:\n biggest_area = cv2.contourArea(c)\n (x, y, w, h) = cv2.boundingRect(c)\n movement_detected = True\n cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2 )\n\n\n if movement_detected:\n biggest_ratio = (float(biggest_area) / (height * width))\n cv2.putText(frame, \"biggest:\" + str(biggest_area) + \" R: \" + str(biggest_ratio), (10, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n if conf[\"show_video\"]:\n cv2.imshow('frame', frame)\n if conf[\"show_motion_mask\"]:\n cv2.imshow('mask', fgmask)\n if((movement_detected == True) and (conf[\"save_capture_files\"])):\n dt = datetime.datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S_%f\")\n cv2.imwrite('output_dir/'+dt+'_hint.png', frame)\n cv2.imwrite('output_dir/'+dt+'_full.png', frame_orrig)\n frame_writes = frame_writes + 1\n key = cv2.waitKey(1) & 0xFF\n\n if key == ord(\"q\"):\n break\n\ncam.stop()\ncv2.destroyAllWindows()\n\n","sub_path":"security_cam.py","file_name":"security_cam.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"54052861","text":"#create two seperate word vector embeddings instead, one that only focuses on order and another that does not\n\nimport numpy as np\nimport csv\nimport json\nimport pandas as pd\nimport pickle\n\ncorrect = 0\nLENGTH = 20\n\ndef lev(s1, s2):\n if len(s1) < len(s2):\n return lev(s2, s1)\n\n # len(s1) >= len(s2)\n if len(s2) == 0:\n return len(s1)\n\n previous_row = range(len(s2) + 1)\n for i, c1 in enumerate(s1):\n current_row = [i + 1]\n for j, c2 in enumerate(s2):\n insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer\n deletions = current_row[j] + 1 # than s2\n substitutions = previous_row[j] + (c1 != c2)\n current_row.append(min(insertions, deletions, substitutions))\n previous_row = current_row\n\n return previous_row[-1]\n\ndef distance(word1, word2):\n return cosDistance(word1['vec'], word2['vec']) + lengthMatch(len(word1),len(word2))\n\ndef lengthMatch(w1, w2):\n return (1 - (np.absolute(w1-w2)/max(w1,w2))) * LENGTH\n\ndef cosDistance(vec1, vec2):\n if len(vec1) < len(vec2):\n vec1 = np.lib.pad(vec1, (0,len(vec2) - len(vec1)) , 'constant',constant_values=0)\n elif len(vec2) < len(vec1):\n vec2 = np.lib.pad(vec2, (0,len(vec1) - len(vec2) ), 'constant',constant_values=0)\n elif np.linalg.norm(vec1) * np.linalg.norm(vec2) == 0:\n return 0\n return np.inner(vec1,vec2)/(np.linalg.norm(vec1) * np.linalg.norm(vec2))\n\ndef bestMatch(internal,external):\n global counter\n global correct\n counter = 0\n inn = []\n out = []\n for inVec in internal[0:700]:\n minVal = np.argmax(np.array([distance(inVec,extVec) for extVec in external]))\n inn.append(inVec['name'])\n out.append(external[minVal]['name'])\n if inVec['id'] != external[minVal]['id']:\n print(\"internal\", inVec['name'])\n print(\"external\", external[minVal]['name'])\n print(\"internal\", inVec['id'])\n print(\"external\", external[minVal]['id'])\n correct += 1\n counter = counter + 1\n return zip(inn,out)\n\ninternal = pickle.load(open(\"realWord.p\", \"rb\"))\nexternal = pickle.load(open(\"distortWord.p\", \"rb\"))\n\nfinalMatches1 = (bestMatch(internal, external))\n\n#average levenshtein distance of results\nprint(\"Original Levenshtein Distance:\", sum([lev(inn['name'], out['name']) for inn,out in zip(internal, external)]) * (1/counter))\nprint(\"Average Levenstein Distance:\", sum([lev(inn,out) for inn,out in finalMatches1]) * (1/counter))\nprint(\"Correct Match Percentage\", 1 - correct/counter)\n","sub_path":"stringmatching/wordvectors1.py","file_name":"wordvectors1.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513092729","text":"import random\nimport numpy as np\nfrom collections import defaultdict, deque\nfrom game import Board, Game\nfrom mcts_alphaZero import MCTSPlayer\nfrom policy_value_net import PolicyValueNet # Theano and Lasagne\nfrom datetime import datetime\nimport pickle\nimport sys\nsys.setrecursionlimit(10**8)\n\nclass TrainPipeline():\n def __init__(self):\n # 게임(오목)에 대한 변수들\n self.board_width, self.board_height = 9, 9\n self.n_in_row = 5\n self.board = Board(width=self.board_width, height=self.board_height, n_in_row=self.n_in_row)\n self.game = Game(self.board)\n \n # 학습에 대한 변수들\n self.learn_rate = 2e-3\n self.lr_multiplier = 1.0 # KL에 기반하여 학습 계수를 적응적으로 조정\n self.temp = 1.0 # the temperature param\n self.n_playout = 400 # num of simulations for each move\n self.c_puct = 5\n self.buffer_size = 10000\n self.data_buffer = deque(maxlen=self.buffer_size)\n self.batch_size = 512 # mini-batch size : 버퍼 안의 데이터 중 512개를 추출\n self.play_batch_size = 1\n self.epochs = 5 # num of train_steps for each update\n self.kl_targ = 0.02\n self.check_freq = 500 # 지정 횟수마다 모델을 체크하고 저장. 원래는 100이었음.\n self.game_batch_num = 3000 # 최대 학습 횟수\n self.train_num = 0 # 현재 학습 횟수\n \n # policy-value net에서 학습 시작\n self.policy_value_net = PolicyValueNet(self.board_width, self.board_height)\n \n self.mcts_player = MCTSPlayer(self.policy_value_net.policy_value_fn, c_puct=self.c_puct, n_playout=self.n_playout, is_selfplay=1)\n\n def get_equi_data(self, play_data):\n \"\"\"\n 회전 및 뒤집기로 데이터set 확대\n play_data: [(state, mcts_prob, winner_z), ..., ...]\n \"\"\"\n extend_data = []\n for state, mcts_porb, winner in play_data:\n for i in [1, 2, 3, 4]:\n # 반시계 방향으로 회전\n equi_state = np.array([np.rot90(s, i) for s in state])\n equi_mcts_prob = np.rot90(np.flipud(mcts_porb.reshape(self.board_height, self.board_width)), i)\n extend_data.append((equi_state, np.flipud(equi_mcts_prob).flatten(), winner))\n # 수평으로 뒤집기\n equi_state = np.array([np.fliplr(s) for s in equi_state])\n equi_mcts_prob = np.fliplr(equi_mcts_prob)\n extend_data.append((equi_state, np.flipud(equi_mcts_prob).flatten(), winner))\n \n return extend_data\n\n def collect_selfplay_data(self, n_games=1):\n \"\"\"collect self-play data for training\"\"\"\n for i in range(n_games):\n winner, play_data = self.game.start_self_play(self.mcts_player, temp=self.temp)\n play_data = list(play_data)[:]\n self.episode_len = len(play_data)\n # 데이터를 확대\n play_data = self.get_equi_data(play_data)\n self.data_buffer.extend(play_data) # deque의 오른쪽(마지막)에 삽입\n\n def policy_update(self):\n \"\"\"update the policy-value net\"\"\"\n mini_batch = random.sample(self.data_buffer, self.batch_size)\n state_batch = [data[0] for data in mini_batch]\n mcts_probs_batch = [data[1] for data in mini_batch]\n winner_batch = [data[2] for data in mini_batch]\n old_probs, old_v = self.policy_value_net.policy_value(state_batch)\n for i in range(self.epochs):\n loss, entropy = self.policy_value_net.train_step(state_batch, mcts_probs_batch, winner_batch, self.learn_rate*self.lr_multiplier)\n new_probs, new_v = self.policy_value_net.policy_value(state_batch)\n kl = np.mean(np.sum(old_probs * (np.log(old_probs + 1e-10) - np.log(new_probs + 1e-10)), axis=1))\n \n # D_KL diverges 가 나쁘면 빠른 중지\n if kl > self.kl_targ * 4 : break\n \n # learning rate를 적응적으로 조절\n if kl > self.kl_targ * 2 and self.lr_multiplier > 0.1 : self.lr_multiplier /= 1.5\n elif kl < self.kl_targ / 2 and self.lr_multiplier < 10 : self.lr_multiplier *= 1.5\n\n explained_var_old = (1 - np.var(np.array(winner_batch) - old_v.flatten()) / np.var(np.array(winner_batch)))\n explained_var_new = (1 - np.var(np.array(winner_batch) - new_v.flatten()) / np.var(np.array(winner_batch)))\n\n print(f\"kl:{kl:5f}, lr_multiplier:{self.lr_multiplier:3f}, loss:{loss}, entropy:{entropy}, explained_var_old:{explained_var_old:3f}, explained_var_new:{explained_var_new:3f}\")\n\n return loss, entropy\n\n def run(self):\n for i in range(self.game_batch_num):\n self.collect_selfplay_data(self.play_batch_size)\n self.train_num += 1\n print(f\"batch i:{self.train_num}, episode_len:{self.episode_len}\")\n\n if len(self.data_buffer) > self.batch_size : loss, entropy = self.policy_update()\n\n # 현재 model의 성능을 체크, 모델 속성을 저장\n if (i+1) % self.check_freq == 0:\n print(f\"★ {self.train_num}번째 batch에서 모델 저장 : {datetime.now()}\")\n self.policy_value_net.save_model(f'{model_path}/policy_9_{self.train_num}.model')\n pickle.dump(self, open(f'{train_path}/train_9_{self.train_num}.pickle', 'wb'), protocol=2)\n\nif __name__ == '__main__':\n print(\"9x9 환경에서 학습을 진행합니다.\")\n train_path = f\"./save/train_9\"\n model_path = f\"./save/model_9\"\n \n init_num = int(input('현재까지 저장된 모델의 학습 수 : '))\n if init_num == 0 or init_num == None : training_pipeline = TrainPipeline()\n else : training_pipeline = pickle.load(open(f'{train_path}/train_9_{init_num}.pickle', 'rb'))\n\n print(f\"★ 학습시작 : {datetime.now()}\")\n training_pipeline.run()\n ","sub_path":"train_local.py","file_name":"train_local.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"518401374","text":"\nimport pygame\nfrom game import constants\nimport random\nfrom game import sounds\n\nclass Laser:\n def __init__(self, x, y, img):\n self.x = x\n self.y = y\n self.img = img\n self.mask = pygame.mask.from_surface(self.img)\n \n def collide(self, obj1, obj2):\n offset_x = obj2.x - obj1.x\n offset_y = obj2.y - obj1.y\n return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None\n\n def draw(self, window):\n window.blit(self.img, (self.x, self.y))\n\n def move(self, vel):\n self.y += vel\n\n def off_screen(self, height):\n return not(self.y <= height and self.y >= 0)\n\n def collision(self, obj):\n return self.collide(self, obj)\n\n\nclass Ship:\n COOLDOWN = 30\n\n def __init__(self, x, y, health=100):\n self.x = x\n self.y = y\n self.health = health\n self.ship_img = None\n self.laser_img = None\n self.lasers = []\n self.cool_down_counter = 0\n\n def draw(self, window):\n window.blit(self.ship_img, (self.x, self.y))\n for laser in self.lasers:\n laser.draw(window)\n\n def move_lasers(self, vel, obj):\n self.cooldown()\n for laser in self.lasers:\n laser.move(vel)\n if laser.off_screen(constants.HEIGHT):\n self.lasers.remove(laser)\n elif laser.collision(obj):\n obj.health -= 10\n self.lasers.remove(laser)\n sounds.get_collition_sound()\n\n def cooldown(self):\n if self.cool_down_counter >= self.COOLDOWN:\n self.cool_down_counter = 0\n elif self.cool_down_counter > 0:\n self.cool_down_counter += 1\n\n def shoot(self):\n if self.cool_down_counter == 0:\n laser = Laser(self.x, self.y, self.laser_img)\n self.lasers.append(laser)\n self.cool_down_counter = 1\n\n def get_width(self):\n return self.ship_img.get_width()\n\n def get_height(self):\n return self.ship_img.get_height()\n\n\nclass Player(Ship):\n def __init__(self, x, y, health=100):\n super().__init__(x, y, health)\n self.ship_img = constants.YELLOW_SPACE_SHIP\n self.laser_img = constants.Mask\n self.mask = pygame.mask.from_surface(self.ship_img)\n self.max_health = health\n self.collision_enemy = 0\n\n def move_lasers(self, vel, objs):\n self.cooldown()\n self.throw_random()\n for laser in self.lasers:\n laser.move(vel)\n if laser.off_screen(constants.HEIGHT):\n self.lasers.remove(laser)\n else:\n for obj in objs:\n if laser.collision(obj):\n objs.remove(obj)\n self.collision_enemy += 1\n sounds.get_pop_enemy_sound()\n if laser in self.lasers:\n self.lasers.remove(laser)\n \n def get_collision_enemy(self):\n return self.collision_enemy\n\n def draw(self, window):\n super().draw(window)\n self.healthbar(window)\n \n def throw_random(self):\n x = random.randint(0,11)\n if x % 2 == 0:\n self.laser_img = constants.Syringe\n else:\n self.laser_img = constants.Mask\n\n def healthbar(self, window):\n pygame.draw.rect(window, (255,0,0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width(), 10))\n pygame.draw.rect(window, (0,255,0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width() * (self.health/self.max_health), 10))\n\n\nclass Enemy(Ship):\n COLOR_MAP = {\n \"red\": (constants.RED_SPACE_SHIP, constants.RED_LASER),\n \"green\": (constants.GREEN_SPACE_SHIP, constants.GREEN_LASER),\n \"blue\": (constants.BLUE_SPACE_SHIP, constants.BLUE_LASER)\n }\n\n def __init__(self, x, y, color, health=100):\n super().__init__(x, y, health)\n self.ship_img, self.laser_img = self.COLOR_MAP[color]\n self.mask = pygame.mask.from_surface(self.ship_img)\n\n def move(self, vel):\n self.y += vel\n\n def shoot(self):\n if self.cool_down_counter == 0:\n laser = Laser(self.x-20, self.y, self.laser_img)\n self.lasers.append(laser)\n self.cool_down_counter = 1","sub_path":"Covid_Space_Shooter/game/sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"146016228","text":"import os\nimport sys\nimport numpy as np\nsys.path.append('/home/harper/optking/optking')\nimport optking.addIntcos\nimport optking.intcosMisc\nimport optking.displace\nimport optking.linearAlgebra\nimport optparams as op\nimport xml.etree.ElementTree as ET\nfrom sys import argv\nimport scipy\nfrom scipy.optimize import minimize\n\nscript, filename, small_eta, small_method, small_basis, big_eta, big_method, big_basis = argv\nsystem_name = filename.replace(\".cml\",\"\")\nPtable = {\n\t\t\"H\" : 1,\n\t\t\"He\" : 2,\n\t\t\"Li\" : 3,\n\t\t\"Be\" : 4,\n\t\t\"B\" : 5,\n\t\t\"C\" : 6,\n \"N\" : 7,\n \"O\" : 8,\n \"F\" : 9,\n \"Ne\" : 10\n\t}\n\nempty_python_dict = {}\nop.Params = op.optParams(empty_python_dict)\n\ndef Get_Cartesians():\n tree = ET.parse(filename)\n root = tree.getroot()\n geom = []\n for atom in root[0]:\n geom.append(np.array([float(atom.attrib['x3']),float(atom.attrib['y3']),float(atom.attrib['z3'])]))\n geom = np.array(geom)\n return geom\n\ndef Get_Intcos(geom, atomic_nos, intcos):\n intcos = []\n C = optking.addIntcos.connectivityFromDistances(geom, atomic_nos)\n optking.addIntcos.addIntcosFromConnectivity(C, intcos, geom)\n q = optking.intcosMisc.qValues(intcos,geom)\n return intcos\n\ndef Get_Energy(internals):\n\tcartesians = Get_Cartesians()\n\t'''\n\tgradient = Get_Grad()\n\tfq = optking.intcosMisc.qForces(intcos, cartesians, gradient)\n\tdq = -.0001*fq\n\toptking.displace.displace(intcos, cartesians, dq, fq)\n '''\n\tUpdate_CML(cartesians)\n\tos.system(\"python real_mim_shady.py \"+str(system_name)+\" \"+str(small_eta)+\" \"+str(small_method)+\" \"+str(small_basis)+\" \"+str(big_eta)+\" \"+str(big_method)+\" \"+str(big_basis))\n\tefile = open(\"final_energy\",\"r\")\n\tenergy = float(efile.read())\n\tprint (str(energy))\n\treturn float(energy)\n\ndef Get_Atom_Nos(filename):\n tree = ET.parse(filename)\n root = tree.getroot()\n a_nos = []\n for atom in root[0]:\n a_nos.append(int(Ptable.get(atom.attrib['elementType'])))\n a_nos = np.array(a_nos)\n return a_nos\n\ndef Get_Grad():\n gradient = []\n os.system(\"python real_mim_grady.py \"+str(system_name)+\" \"+str(small_eta)+\" \"+str(small_method)+\" \"+str(small_basis)+\" \"+str(big_eta)+\" \"+str(big_method)+\" \"+str(big_basis))\n gradient_file = open(\"final_grad\",\"r\")\n line_no = 0\n for line in gradient_file.readlines():\n line = line.replace(\"\\n\",\"\")\n line = line.split(\" \")\n gradient.append(float(line[0]))\n gradient.append(float(line[1]))\n gradient.append(float(line[2]))\n gradient = np.array(gradient)\n return gradient\n\ndef Cartesian_Geom_to_Internal_Numbers(geom, atomic_nos, intcos):\n intcos = []\n C = optking.addIntcos.connectivityFromDistances(geom, atomic_nos)\n optking.addIntcos.addIntcosFromConnectivity(C, intcos, geom)\n q = optking.intcosMisc.qValues(intcos,geom)\n return q\n\ndef Update_CML(cartesians):\n tree = ET.parse(filename)\n root = tree.getroot()\n for atom in range(0, len(root[0])):\n root[0][atom].attrib['x3']=str(cartesians[atom][0])\n root[0][atom].attrib['y3']=str(cartesians[atom][1])\n root[0][atom].attrib['z3']=str(cartesians[atom][2])\n tree.write(filename)\n\ndef Internal_Step(internals):\n cartesians = Get_Cartesians()\n gradient = Get_Grad()\n print (gradient)\n for j in range(0, len(gradient)):\n if abs(gradient[j])<1e-4:\n gradient[j] = 0\n fq = optking.intcosMisc.qForces(intcos, cartesians, gradient)\n '''\n for i in range(0, len(fq)):\n if abs(fq[i])<1e-4:\n fq[i] = 0\n '''\n dq = -.0001*fq\n internal_jac = optking.displace.displace(intcos, cartesians, dq, fq)\n Update_CML(cartesians)\n return dq\n\nintcos = []\ncartesians = Get_Cartesians()\natomic_nos = Get_Atom_Nos(filename)\nintcos = Get_Intcos(cartesians, atomic_nos, intcos)\ninitial_internals = Cartesian_Geom_to_Internal_Numbers(cartesians, atomic_nos, intcos)\nscipy.optimize.minimize(Get_Energy, initial_internals, method='BFGS', jac=Internal_Step, options={'gtol': 1e-5})\nprint(str(Get_Energy(initial_internals)))\n","sub_path":"GeOp.py","file_name":"GeOp.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"294215960","text":"def BinarySearch(list1, key):\n\tlow = 0\n\thigh = len(list1)-1\n\tFound = False\n\n\twhile low<=high and not Found:\n\t\tmid = (low + high) // 2\n\t\tif key == list1[mid]:\n\t\t\tFound = True\n\t\telif key > list1[mid]:\n\t\t\tlow = mid + 1\n\t\telse:\n\t\t\thigh = mid - 1\n\n\tif Found:\n\t\tprint(\"Key is found \")\n\telse:\n\t\tprint(\"Key is not found\")\n\n\n\n\nnum = int(input(\"Enter the list length: \"))\nlist1 = [int(input()) for i in range(num)]\n\nlist1.sort()\nprint(list1)\nkey = int(input(\"Enter the Key: \"))\n\nBinarySearch(list1, key)\n","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"192622049","text":"#-*- coding:utf-8 -*-\nimport maya.cmds as cmd\ndef chcentra():\n select = cmd.ls(dag=True,v=True,long=True,typ='transform')\n select.sort(key=len, reverse=True)\n chcentral_total=[]\n for i in select:\n index = select.index(i)\n childrens = cmd.listRelatives(i, children=True,f=True) or [i]\n #print childrens\n if len(childrens) == 1:\n objectType = cmd.objectType(childrens)\n #print objectType\n else:\n objectType = cmd.objectType(i)\n #print short,objectType\n if objectType=='transform' or objectType=='mesh':\n central=cmd.xform('%s.rotatePivot'%select[index],q=True,t=True)\n if not central==[0,0,0]:\n chcentral_total.append(childrens)\n #print childrens,central\n del select[0:]\n #print chcentral_total\n return chcentral_total\n # if len(chcentral_total) > 0:\n # print '有物体或者组的中心轴被改动', chcentral_total\n # for j in chcentral_total:\n # cmd.select(j, add=True)\n # else:\n # print '没有物体或者组的中心轴被改动'\n","sub_path":"total_model/change_central_two.py","file_name":"change_central_two.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"465405894","text":"import pytest\nfrom galaxy.api.errors import AuthenticationRequired\nfrom galaxy.api.types import Achievement\n\nfrom backend import OriginBackendClient, ProductInfo\nfrom plugin import AchievementsImportContext\n\nOWNED_GAMES_SIMPLE_SIMPLE_ACHIEVEMENTS = {\n \"DR:119971300\": ProductInfo(\"DR:119971300\", \"Need For Speed™ Shift\", \"54856\", None),\n \"OFB-EAST:109552409\": ProductInfo(\"OFB-EAST:109552409\", \"The Sims™ 4\", \"55482\", None),\n \"OFB-EAST:48217\": ProductInfo(\"OFB-EAST:48217\", \"Plants vs. Zombies™ Game of the Year Edition\", \"180975\", None),\n \"OFB-EAST:50885\": ProductInfo(\"OFB-EAST:50885\", \"Dead Space™ 3\", \"52657\", \"50563_52657_50844\"),\n \"Origin.OFR.50.0001672\": ProductInfo(\"Origin.OFR.50.0001672\", \"THE WITCHER® 3: WILD HUNT\", \"192492\", \"50318_194188_50844\"),\n \"Origin.OFR.50.0001452\": ProductInfo(\"Origin.OFR.50.0001452\", \"Titanfall® 2\", \"192492\", \"193634_192492_50844\")\n}\n\nOWNED_GAME_SPECIAL_ACHIEVEMENTS = {\"DR:225064100\": ProductInfo(\"DR:225064100\", \"Battlefield 3™\", \"50182\", \"BF_BF3_PC\")}\n\nOWNED_GAMES = {**OWNED_GAMES_SIMPLE_SIMPLE_ACHIEVEMENTS, **OWNED_GAME_SPECIAL_ACHIEVEMENTS}\n\nACHIEVEMENTS = {\n \"DR:119971300\": [],\n \"OFB-EAST:109552409\": [],\n \"OFB-EAST:48217\": [],\n \"Origin.OFR.50.0001672\": [],\n \"OFB-EAST:50885\": [\n Achievement(1376676315, \"1\", \"Stranger in a Strange Land\"),\n Achievement(1376684053, \"2\", \"Space Odyssey\"),\n Achievement(1377464844, \"3\", \"Critical Mass\"),\n Achievement(1377467003, \"4\", \"Snow Crash\"),\n Achievement(1383078508, \"5\", \"Intestinal Fortitude\"),\n Achievement(1403554953, \"31\", \"Full House\"),\n Achievement(1377897989, \"34\", \"From the Jaws\"),\n Achievement(1377459297, \"50\", \"Overpowered Healing\")\n ],\n \"DR:225064100\": [\n Achievement(1371064136, \"XP2ACH02_00\", \"Man of Calibre\"),\n Achievement(1362857404, \"ACH36_00\", \"M.I.A\"),\n Achievement(1371066037, \"XP2ACH01_00\", \"Dominator\"),\n Achievement(1362857404, \"ACH33_00\", \"Support Efficiency\"),\n ],\n \"Origin.OFR.50.0001452\": [\n Achievement(1480870347, \"1\", \"The Student...\"),\n Achievement(1480870977, \"3\", \"The Graduate\"),\n Achievement(1483373394, \"50\", \"Free Association\")\n ]\n}\n\nMULTIPLE_ACHIEVEMENTS_SETS_BACKEND_RESPONSE = {\n \"50318_194188_50844\": {\n \"achievements\": {},\n \"name\": \"THE WITCHER® 3: WILD HUNT\"\n },\n \"50563_52657_50844\": {\n \"achievements\": {\n \"1\": {\n \"complete\": True,\n \"u\": 1376676315,\n \"name\": \"Stranger in a Strange Land\",\n },\n \"2\": {\n \"complete\": True,\n \"u\": 1376684053,\n \"name\": \"Space Odyssey\",\n },\n \"3\": {\n \"complete\": True,\n \"u\": 1377464844,\n \"name\": \"Critical Mass\",\n },\n \"4\": {\n \"complete\": True,\n \"u\": 1377467003,\n \"name\": \"Snow Crash\",\n },\n \"5\": {\n \"complete\": True,\n \"u\": 1383078508,\n \"name\": \"Intestinal Fortitude\",\n },\n \"31\": {\n \"complete\": True,\n \"u\": 1403554953,\n \"name\": \"Full House\",\n },\n \"34\": {\n \"complete\": True,\n \"u\": 1377897989,\n \"name\": \"From the Jaws\",\n },\n \"50\": {\n \"complete\": True,\n \"u\": 1377459297,\n \"name\": \"Overpowered Healing\",\n }\n },\n \"name\": \"Dead Space™ 3\"\n },\n \"193634_192492_50844\": {\n \"achievements\": {\n \"1\": {\n \"complete\": True,\n \"u\": 1480870347,\n \"name\": \"The Student...\",\n },\n \"3\": {\n \"complete\": True,\n \"u\": 1480870977,\n \"name\": \"The Graduate\",\n },\n \"50\": {\n \"complete\": True,\n \"u\": 1483373394,\n \"name\": \"Free Association\",\n }\n },\n \"name\": \"Titanfall® 2\"\n }\n}\n\nMULTIPLE_ACHIEVEMENTS_SETS_BACKEND_PARSED = {\n \"50318_194188_50844\": ACHIEVEMENTS[\"Origin.OFR.50.0001672\"],\n \"50563_52657_50844\": ACHIEVEMENTS[\"OFB-EAST:50885\"],\n \"193634_192492_50844\": ACHIEVEMENTS[\"Origin.OFR.50.0001452\"]\n}\n\nSINGLE_ACHIEVEMENTS_SET_BACKEND_RESPONSE = {\n \"XP2ACH02_00\": {\n \"complete\": True,\n \"u\": 1371064136,\n \"name\": \"Man of Calibre\",\n },\n \"ACH36_00\": {\n \"complete\": True,\n \"u\": 1362857404,\n \"name\": \"M.I.A\",\n },\n \"XP2ACH01_00\": {\n \"complete\": True,\n \"u\": 1371066037,\n \"name\": \"Dominator\",\n },\n \"ACH33_00\": {\n \"complete\": True,\n \"u\": 1362857404,\n \"name\": \"Support Efficiency\",\n }\n}\n\nSINGLE_ACHIEVEMENTS_SET_BACKEND_PARSED = {\n \"BF_BF3_PC\": ACHIEVEMENTS[\"DR:225064100\"]\n}\n\n@pytest.mark.asyncio\nasync def test_not_authenticated(plugin, http_client):\n http_client.is_authenticated.return_value = False\n\n with pytest.raises(AuthenticationRequired):\n await plugin.prepare_achievements_context(OWNED_GAMES.keys())\n\n\n@pytest.mark.asyncio\nasync def test_achievements_context_preparation(\n authenticated_plugin,\n user_id,\n persona_id,\n backend_client\n):\n await authenticated_plugin.prepare_achievements_context(OWNED_GAMES.keys())\n\n backend_client.get_owned_games.assert_called_once_with(user_id)\n backend_client.get_achievements.assert_called_once_with(persona_id)\n\n\n@pytest.mark.asyncio\nasync def test_get_unlocked_achievements_simple(\n authenticated_plugin,\n backend_client,\n user_id\n):\n for game_id in OWNED_GAMES_SIMPLE_SIMPLE_ACHIEVEMENTS.keys():\n assert ACHIEVEMENTS[game_id] == await authenticated_plugin.get_unlocked_achievements(\n game_id,\n context=AchievementsImportContext(\n owned_games=OWNED_GAMES_SIMPLE_SIMPLE_ACHIEVEMENTS,\n achievements=MULTIPLE_ACHIEVEMENTS_SETS_BACKEND_PARSED\n )\n )\n\n backend_client.get_achievements.assert_not_called()\n\n\n@pytest.mark.asyncio\nasync def test_get_unlocked_achievements_explicit_call(\n authenticated_plugin,\n backend_client,\n persona_id\n):\n backend_client.get_achievements.return_value = SINGLE_ACHIEVEMENTS_SET_BACKEND_PARSED\n\n for game_id in OWNED_GAMES.keys():\n assert ACHIEVEMENTS[game_id] == await authenticated_plugin.get_unlocked_achievements(\n game_id,\n context=AchievementsImportContext(\n owned_games=OWNED_GAMES,\n achievements=MULTIPLE_ACHIEVEMENTS_SETS_BACKEND_PARSED\n )\n )\n\n backend_client.get_achievements.assert_called_once_with(persona_id, \"BF_BF3_PC\")\n\n\nBACKEND_GAMES_RESPONSE = \"\"\"\n\n \n OFB-EAST:48217\n Plants vs. Zombies™ Game of the Year Edition\n 180975\n Normal Game\n \n \n DR:119971300\n Need For Speed™ Shift\n 54856\n \n \n OFB-EAST:109552409\n The Sims™ 4\n 55482\n Normal Game\n \n \n DR:225064100\n Battlefield 3™\n \n \n BF_BF3_PC\n \n \n 50182\n Normal Game\n \n \n OFB-EAST:50885\n Dead Space™ 3\n \n \n 50563_52657_50844\n \n \n 52657\n Normal Game\n \n \n Origin.OFR.50.0001452\n Titanfall® 2\n \n \n 193634_192492_50844\n \n \n 192492\n Normal Game\n \n \n Origin.OFR.50.0001672\n THE WITCHER® 3: WILD HUNT\n \n \n 50318_194188_50844\n \n \n 192492\n Normal Game\n \n\n\"\"\"\n\n\n@pytest.mark.asyncio\nasync def test_owned_games_parsing(persona_id, http_client, create_xml_response):\n http_client.get.return_value = create_xml_response(BACKEND_GAMES_RESPONSE)\n\n assert OWNED_GAMES == await OriginBackendClient(http_client).get_owned_games(persona_id)\n\n http_client.get.assert_called_once()\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"backend_response, parsed, explicit_set\", [\n ({}, {}, None),\n (MULTIPLE_ACHIEVEMENTS_SETS_BACKEND_RESPONSE, MULTIPLE_ACHIEVEMENTS_SETS_BACKEND_PARSED, None),\n (SINGLE_ACHIEVEMENTS_SET_BACKEND_RESPONSE, SINGLE_ACHIEVEMENTS_SET_BACKEND_PARSED, \"BF_BF3_PC\"),\n])\nasync def test_achievements_parsing(\n backend_response,\n parsed,\n explicit_set,\n http_client,\n user_id,\n create_json_response\n):\n http_client.get.return_value = create_json_response(backend_response)\n\n assert parsed == await OriginBackendClient(http_client).get_achievements(user_id, explicit_set)\n\n http_client.get.assert_called_once_with(\n \"https://achievements.gameservices.ea.com/achievements/personas/{user_id}{specific_set}/all\".format(\n user_id=user_id, specific_set=\"/\" + explicit_set if explicit_set else \"\"\n ),\n params={'lang': 'en_US', 'metadata': 'true'}\n )\n","sub_path":"tests/test_achievements.py","file_name":"test_achievements.py","file_ext":"py","file_size_in_byte":10890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563678066","text":"def hash(data):\n result = 0\n for c in data:\n result += ord(c)\n return result\ndef hash_insert(table, key, value):\n table[\"current\"] += 1\n if table[\"current\"]/len(table[\"content\"]) > 0.75:\n new_content = [[] for x in range(2*len(table[\"content\"]))]\n for old in table[\"content\"]:\n for old_key, old_value in old:\n index = hash(old_key)%len(new_content)\n new_content[index].append((old_key, old_value))\n table[\"content\"] = new_content\n index = hash(key)%len(table[\"content\"])\n table[\"content\"][index].append((key, value))\ndef hash_get(table, key):\n index = hash(key)%len(table[\"content\"])\n bucket = table[\"content\"][index]\n for k in bucket:\n if k[0] == key:\n return k[1]\n return None\ntable = {\"content\": [[],[]], \"current\":0}\nhash_insert(table, \"a\", 1)\nhash_insert(table, \"b\", 2)\nhash_insert(table, \"c\", 3)\nhash_insert(table, \"d\", 4)\nhash_insert(table, \"e\", 5)\nprint(hash_get(table, \"a\"))\nprint(hash_get(table, \"b\"))\nprint(hash_get(table, \"c\"))\nprint(hash_get(table, \"d\"))\nprint(hash_get(table, \"e\"))","sub_path":"data structures and algs/hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"404428729","text":"import data\nfrom data.json import stream_json\nfrom data_extraction import content_export\nfrom data_extraction import taxonomy_query\nfrom lib import plek\nfrom lib.helpers import dig\nimport functools\nimport progressbar\nfrom multiprocessing import Pool\nimport gzip\nimport json\nimport os\nimport sys\nimport ijson\n\n\nconfig_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'config', 'data_export_fields.json')\n\nwith open(config_path) as json_data_file:\n configuration = json.load(json_data_file)\n\ndef notty_progress_bar():\n def process(data):\n count = 0\n for x in data:\n yield x\n count += 1\n if (count % 1000) == 0:\n print(\"Processed {} items\".format(count))\n\n print(\"Finished processing {} items\".format(count))\n\n return process\n\ndef jenkins_compatible_progress_bar(*args, **kwargs):\n if sys.stdout.isatty():\n return progressbar.ProgressBar(*args, **kwargs)\n else:\n return notty_progress_bar()\n\ndef __transform_content(input_filename=\"data/content.json.gz\",\n output_filename=\"data/filtered_content.json.gz\",\n transform_function=lambda x: x):\n with gzip.open(input_filename, mode='rt') as input_file:\n with gzip.open(output_filename, mode='wt') as output_file:\n content_generator = ijson.items(input_file, prefix='item')\n stream_json(output_file, transform_function(content_generator))\n\n\ndef __get_all_content(blacklist_document_types=[]):\n get_content = functools.partial(\n content_export.get_content,\n content_store_url=plek.find('content-store')\n )\n\n progress_bar = jenkins_compatible_progress_bar()\n\n content_links_list = list(\n progress_bar(\n content_export.content_links_generator(\n blacklist_document_types=blacklist_document_types\n )\n )\n )\n\n content_links_set = set(content_links_list)\n duplicate_links = len(content_links_list) - len(content_links_set)\n\n if duplicate_links > 0:\n print(\"{} duplicate links from Rummager\".format(duplicate_links))\n\n pool = Pool(4)\n return pool.imap(get_content, content_links_set), len(content_links_set)\n\n\ndef export_content(output_filename=\"data/content.json.gz\"):\n blacklist_document_types = data.document_types_excluded_from_the_topic_taxonomy()\n seen_content_ids = set()\n duplicate_content_ids = []\n blacklisted_content = []\n\n def filter_content(content):\n # This can happen a few ways, for example, if the request to\n # get the content resulted in a redirect.\n if not content:\n return False\n\n content_id = content['content_id']\n\n if content_id in seen_content_ids:\n duplicate_content_ids.append(content_id)\n return False\n\n if content.get('document_type') in blacklist_document_types:\n blacklisted_content.append(content)\n return False\n\n seen_content_ids.add(content_id)\n return True\n\n content_iterator, count = __get_all_content(blacklist_document_types=blacklist_document_types)\n content = filter(filter_content, content_iterator)\n\n progress_bar = jenkins_compatible_progress_bar(max_value=count)\n\n with gzip.open(output_filename, 'wt') as output_file:\n stream_json(output_file, progress_bar(content))\n\n duplicate_content_ids_count = len(set(duplicate_content_ids))\n print(\"Seen {} duplicate content ids\".format(\n duplicate_content_ids_count\n ))\n\n print(\"Blacklisted content: \")\n for bc in blacklisted_content:\n print(\"content_id: %s : document_type: %s\" % (bc['content_id'], bc['document_type']))\n\n\ndef export_filtered_content(input_filename=\"data/content.json.gz\", output_filename=\"data/filtered_content.json.gz\"):\n slicer = functools.partial(content_export.content_dict_slicer,\n base_fields=configuration['base_fields'],\n taxon_fields=configuration['taxon_fields'],\n ppo_fields=configuration['ppo_fields'])\n\n __transform_content(input_filename=input_filename,\n output_filename=output_filename,\n transform_function=lambda iterator: map(slicer, iterator))\n\n\ndef export_untagged_content(input_filename=\"data/content.json.gz\", output_filename=\"data/untagged_content.json.gz\"):\n def __filter_tagged(dict_in):\n return dig(dict_in, 'links', 'taxons') is None\n\n untagged_dict_slicer = functools.partial(content_export.untagged_dict_slicer,\n base_fields=configuration['untagged_content_fields'],\n ppo_fields=configuration['ppo_fields'])\n\n __transform_content(input_filename=input_filename,\n output_filename=output_filename,\n transform_function=lambda iterator: map(untagged_dict_slicer, filter(__filter_tagged, iterator)))\n\n\ndef export_taxons(output_filename=\"data/taxons.json.gz\"):\n def __taxonomy():\n query = taxonomy_query.TaxonomyQuery()\n level_one_taxons = query.level_one_taxons()\n children = [taxon\n for level_one_taxon in level_one_taxons\n for taxon in query.child_taxons(level_one_taxon['base_path'])]\n return iter(level_one_taxons + children)\n\n with gzip.open(output_filename, 'wt') as output_file:\n stream_json(output_file, __taxonomy())\n","sub_path":"python/data_extraction/export_data.py","file_name":"export_data.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"164631521","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nfor tc in range(1, int(input())+1):\n N, M = map(int, input().split())\n t = [int(input()) for _ in range(N)]\n l, r = 1, max(t)*M\n while l < r:\n s, m = 0, (l+r)//2\n for i in range(N): s += m//t[i]\n if s < M: l = m+1\n else: r = m\n print('#{} {}'.format(tc, l))","sub_path":"swea/D4/3074.py","file_name":"3074.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"548068597","text":"from sys import stdin\n\ndef trian(n): return (n*(n+1))//2\ndef bytwo(n): return 2*n\n\ndef binsearch(f, lo, hi, k):\n ans = None\n if(lo < hi):\n while(lo+1 < hi):\n mid = (hi+lo)//2\n if(k >= f(mid)):\n lo = mid\n else:\n hi = mid\n\n ans = lo\n return ans\n\n\ndef main():\n N, first = int(stdin.readline()), True\n for case in range(N):\n if(not first): print(\"\")\n first = False\n stdin.readline()\n k = abs(int(stdin.readline()))\n\n n = binsearch(trian, 1, 45000, k)\n if(trian(n) < k): n += 1\n \n dif = trian(n)-k\n \n if(dif%2 == 0): print(n)\n else:\n dif = trian(n+1)-k\n ans = binsearch(bytwo, 1, n+1, dif)\n if(ans*2==dif):\n print(n+1)\n else:print(n+2)\n \n\n\nmain()","sub_path":"10025.py","file_name":"10025.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"246704582","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n# Copyright 2021 Dell (www.dell.com)\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 unittest\nfrom qiskit import QuantumCircuit, execute, transpile\nfrom dell_runtime import BackendProvider\nfrom qiskit.providers import JobStatus\nfrom time import sleep\n\nclass ProviderTest(unittest.TestCase):\n def test_job_submission(self):\n provider = BackendProvider()\n self.assertIsNotNone(provider)\n \n backend = provider.get_backend(name=\"aer_simulator\")\n self.assertIsNotNone(backend)\n\n qc = QuantumCircuit(2, 2)\n qc.h(0)\n qc.cx(0, 1)\n qc.measure([0, 1], [0, 1])\n job = backend.run(qc, shots=1) \n self.assertIsNotNone(job)\n # self.assertNotEqual(JobStatus.DONE, job.status())\n \n count = 0\n # 5 second\n max = 50 \n while count < max and job.status() != JobStatus.DONE:\n count += 1\n sleep(0.1)\n self.assertEqual(JobStatus.DONE, job.status())\n\n job.result()\n\n\n def test_execute(self):\n provider = BackendProvider()\n self.assertIsNotNone(provider)\n \n backend = provider.get_backend(name=\"aer_simulator\")\n self.assertIsNotNone(backend)\n\n qc = QuantumCircuit(2, 2)\n qc.h(0)\n qc.cx(0, 1)\n qc.measure([0, 1], [0, 1])\n job = execute(qc, backend, shots=2)\n self.assertIsNotNone(job)\n\n count = 0\n # 5 second\n max = 50 \n while count < max and job.status() != JobStatus.DONE:\n count += 1\n sleep(0.1)\n self.assertEqual(JobStatus.DONE, job.status())\n\n def test_get_counts(self):\n provider = BackendProvider()\n self.assertIsNotNone(provider)\n \n backend = provider.get_backend(name=\"aer_simulator\")\n self.assertIsNotNone(backend)\n\n circ = QuantumCircuit(2)\n circ.h(0)\n circ.cx(0, 1)\n circ.measure_all()\n\n # Transpile for simulator\n circ = transpile(circ, backend)\n\n # Run and get counts\n result = backend.run(circ).result()\n counts = result.get_counts(circ)\n total = counts.get('11') + counts.get('00')\n self.assertEqual(total, 1024)\n\n","sub_path":"tests/test_emulator_job.py","file_name":"test_emulator_job.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"397600589","text":"from pyspark import SparkContext,SparkConf\nconf=SparkConf().setMaster(\"local\").setAppName(\"Most Popular Superhero\")\nsc=SparkContext().getOrCreate(conf=conf)\n\ndef names_mapper(line):\n data=line.split(\"\\\"\")\n return (int(data[0]),data[1])\n\nsuper_hero_names_data=sc.textFile(\"Marvel-Names.txt\")\nsuper_hero_names=super_hero_names_data.map(names_mapper)\ndef graph_mapper(line):\n fields=line.split()\n return (int(fields[0]),len(fields)-1)\n\nsuper_hero_graph_data=sc.textFile(\"Marvel-Graph.txt\")\nsuper_hero_graph=super_hero_graph_data.map(graph_mapper)\nsuper_hero_popularity=super_hero_graph.reduceByKey(lambda x,y:x+y).map(lambda x:(x[1],x[0]))\n\nmost_popular_hero=super_hero_popularity.max()\n\nmost_popular_hero_name=super_hero_names.lookup(int(most_popular_hero[1]))\n\n\nprint(\"{a} is the most popular hero. \".format(a=most_popular_hero_name[0]))\n\n","sub_path":"src/most_popular_super_hero.py","file_name":"most_popular_super_hero.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96717366","text":"from torch.utils.data import Dataset\nimport numpy as np\nimport torch\nimport random\nimport json\nimport copy\nimport tqdm\nfrom dataset import BPE\n\nclass TreeBERTDataset(Dataset):\n def __init__(self, vocab, path_num, node_num, code_len, dataset_save_path, is_dataset_processed=True, \n test_source_path=None, test_target_path=None, corpus_lines=None, is_test=False,is_fine_tune=False):\n self.vocab = vocab\n self.path_num = path_num\n self.node_num = node_num\n self.code_len = code_len\n self.is_fine_tune = is_fine_tune\n self.encoder_input = []\n self.decoder_input = []\n self.label = []\n self.is_path_order = []\n ASTs = []\n codes = []\n\n if(is_test):\n dataset_save_path = dataset_save_path + \"/TestDataset.json\"\n else:\n dataset_save_path = dataset_save_path + \"/TrainDataset.json\"\n\n if(is_dataset_processed == False):\n\n if(test_source_path != None and test_target_path != None):\n with open(test_source_path, \"r\", encoding='utf-8') as f: \n for paths in tqdm.tqdm(f, desc=\"Loading Source Dataset\"):\n path = paths.split(\"\\t\")\n path_list = []\n for nodes in path:\n node_list = []\n for tmp in nodes.replace(\"|\", \" \").replace(\"\\/?\", \"\").replace(\"/\", \" / \").split():\n tmp = tmp + ''\n node_list.append(tmp)\n node_list = BPE.encode(vocab.vocab_tokenization,vocab.tokenize_word,vocab.sorted_tokens,texts=node_list)\n if(len(node_list) > 2):\n path_list.append(node_list)\n ASTs.append(path_list)\n\n with open(test_target_path, \"r\", encoding='utf-8') as f:\n for code in tqdm.tqdm(f, desc=\"Loading Dataset\"):\n tmp_tokens = []\n for tmp in code.split():\n tmp = tmp + ''\n tmp_tokens.append(tmp)\n\n code = BPE.encode(vocab.vocab_tokenization,vocab.tokenize_word,vocab.sorted_tokens,texts=tmp_tokens)\n codes.append(code)\n else:\n ASTs = vocab.ASTs\n codes = vocab.codes\n\n # Temporary save to file\n with open(dataset_save_path, \"w\", encoding=\"utf-8\") as f:\n for index, AST in enumerate(ASTs):\n t, is_path_order = self.change_node(ASTs[index])\n AST, code, token_list = self.PMLM(t, codes[index])\n self.encoder_input.append(AST)\n self.decoder_input.append(code)\n self.label.append(token_list)\n self.is_path_order.append(is_path_order)\n \n output = {\"encoder_input\": AST,\n \"decoder_input\": code,\n \"label\": token_list,\n \"is_path_order\": is_path_order}\n f.write(json.dumps(output))\n f.write(\"\\n\")\n\n else:\n # If the dataset has already been processed, read the file directly.\n with open(dataset_save_path, \"r\", encoding=\"utf-8\") as f:\n for data in tqdm.tqdm(f, desc=\"Loading Processed Dataset\", total=corpus_lines):\n data = json.loads(data)\n self.encoder_input.append(data[\"encoder_input\"])\n self.decoder_input.append(data[\"decoder_input\"])\n self.label.append(data[\"label\"])\n self.is_path_order.append(data[\"is_path_order\"])\n \n\n self.source_corpus_lines = len(self.encoder_input)\n self.target_corpus_lines = len(self.decoder_input) \n\n def __len__(self):\n return self.target_corpus_lines\n\n def __getitem__(self, item):\n code = [self.vocab.sos_index] + self.decoder_input[item] + [self.vocab.eos_index]\n token_list = [self.vocab.sos_index] + self.label[item] + [self.vocab.eos_index]\n\n # padding \n AST = self.encoder_input[item][:self.path_num]\n if(len(AST) < self.path_num):\n tmp = [self.vocab.pad_index for _ in range(self.node_num)]\n padding = [tmp for _ in range(self.path_num - len(AST))]\n AST.extend(padding)\n # padding number of AST Paths\n for index, path in enumerate(AST):\n if(len(path) >= self.node_num):\n AST[index] = path[:self.node_num]\n else:\n padding = [self.vocab.pad_index for _ in range(self.node_num - len(path))]\n AST[index].extend(padding)\n\n # padding length of decoder inputs and outputs\n code = code[:self.code_len]\n if(len(code) < self.code_len):\n padding = [self.vocab.pad_index for _ in range(self.code_len - len(code))]\n code.extend(padding)\n\n token_list = token_list[:self.code_len]\n if(len(token_list) < self.code_len):\n padding = [self.vocab.pad_index for _ in range(self.code_len - len(token_list))]\n token_list.extend(padding)\n\n if(self.is_fine_tune == False):\n output = {\"encoder_input\": AST,\n \"decoder_input\": code,\n \"label\": token_list,\n \"is_path_order\": self.is_path_order[item]}\n else:\n output = {\"encoder_input\": AST,\n \"label\": token_list}\n \n return {key: torch.tensor(value) for key, value in output.items()}\n\n def PMLM(self, AST, code):\n mask_node = []\n if(self.is_fine_tune == False):\n # AST path disrupted, up to mask 0.15 nodes\n max_mask_num = len(AST) * len(AST[0]) * 0.15\n random.shuffle(AST)\n for path in AST:\n d = len(path)\n tmp = np.array(range(d))\n select_node_prob_dis = np.exp(tmp-d) / np.sum(np.exp(tmp-d))\n\n for index, node in enumerate(path):\n prob = random.random()\n if (prob < select_node_prob_dis[index]) and (len(mask_node) < max_mask_num):\n mask_node.append(path[index])\n path[index] = \"\"\n \n # Decoder Inputs and Outputs\n token_list = []\n for m, token in enumerate(code):\n token_list.append(self.vocab.stoi.get(token, self.vocab.unk_index))\n if(self.is_fine_tune == False):\n if (token not in mask_node):\n code[m] = self.vocab.mask_index\n else:\n code[m] = self.vocab.stoi.get(token, self.vocab.unk_index)\n\n # Encoder Inputs\n for m, path in enumerate(AST):\n for n, node in enumerate(path):\n AST[m][n] = self.vocab.stoi.get(node, self.vocab.unk_index)\n \n return AST, code, token_list\n\n def change_node(self, AST):\n t = copy.deepcopy(AST) \n\n # output_text, label(disorder:0, order:1)\n # AST has 0.5 probability of exchanging nodes\n if(self.is_fine_tune == False):\n if random.random() > 0.5:\n return t, 1\n else:\n # Randomly select a path\n path = t[random.randint(0, len(t)-1)]\n path = t[random.randint(0, len(t)-1)]\n position = random.sample(range(0,len(path)-1), 2)\n path[position[0]], path[position[1]] = path[position[1]], path[position[0]]\n return t, 0\n return t, 0","sub_path":"dataset/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"396211350","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\nimport scipy.io as sio\nimport tensorflow as tf\nimport numpy as np\n\nimport resnet_model\n\nparser = argparse.ArgumentParser()\n\n# Basic model parameters.\nparser.add_argument('--data_dir', type=str, default=os.path.join(os.path.dirname(__file__), '../datasets'),\n help='The path to the SVHN data directory.')\n\nparser.add_argument('--model_dir', type=str, default='/tmp/svhn_resnet_model',\n help='The directory where the model will be stored.')\n\nparser.add_argument('--resnet_size', type=int, default=32,\n help='The size of the ResNet model to use.')\n\nparser.add_argument('--train_epochs', type=int, default=160,\n help='The number of epochs to train.')\n\nparser.add_argument('--epochs_per_eval', type=int, default=1,\n help='The number of epochs to run in between evaluations.')\n\nparser.add_argument('--batch_size', type=int, default=128,\n help='The number of images per batch.')\n\nparser.add_argument('--activation', type=str, default='relu',\n help='activation function swish,relu,lrelu,tanh,elu')\n\nparser.add_argument(\n '--data_format', type=str, default=None,\n choices=['channels_first', 'channels_last'],\n help='A flag to override the data format used in the model. channels_first '\n 'provides a performance boost on GPU but is not always compatible '\n 'with CPU. If left unspecified, the data format will be chosen '\n 'automatically based on whether TensorFlow was built for CPU or GPU.')\n\n_HEIGHT = 32\n_WIDTH = 32\n_DEPTH = 3\n_NUM_IMAGES = {'train': 73257, 'test': 26032}\n_NUM_CLASSES = 10\n_WEIGHT_DECAY = 2e-4\n_MOMENTUM = 0.9\n\ndef get_data(is_training, data_dir):\n \"\"\"Read the .mat file, do data conversions, and return\n TF dataset\n \"\"\"\n if is_training:\n filename = 'train_32x32.mat'\n else:\n filename = 'test_32x32.mat'\n\n filepath = os.path.join(data_dir, filename)\n assert (os.path.exists(filepath))\n \n #roll the image# axis backwards to be the first axis\n data = sio.loadmat(filepath)\n X = np.rollaxis(data['X'], 3)\n y = data['y'].reshape((X.shape[0], 1))\n\n num_images = _NUM_IMAGES['train'] if is_training else _NUM_IMAGES['test']\n assert(X.shape[0] == num_images)\n\n dataset = tf.data.Dataset.from_tensor_slices((X, y))\n dataset = dataset.map(\n lambda image, label: (tf.cast(image, tf.float32), \n tf.squeeze(\n tf.one_hot(tf.cast(label, tf.int32), _NUM_CLASSES)\n )))\n \n return dataset\n\ndef preprocess_image(is_training, image):\n if is_training:\n image = tf.image.resize_image_with_crop_or_pad(\n image, _HEIGHT + 8, _WIDTH + 8)\n \n image = tf.random_crop(image, [_HEIGHT, _WIDTH, _DEPTH])\n image = tf.image.random_flip_left_right(image)\n \n image = tf.image.per_image_standardization(image)\n \n return image\n\ndef input_fn(is_training, data_dir, batch_size, num_epochs=1):\n \"\"\"input function to the network\"\"\"\n dataset = get_data(is_training, data_dir)\n\n if is_training:\n dataset = dataset.shuffle(buffer_size = _NUM_IMAGES['train'])\n\n dataset = dataset.map(\n lambda image, label: (preprocess_image(is_training, image), label))\n \n dataset = dataset.prefetch(2 * batch_size)\n #Repeat the dataset N epochs before evaluation\n dataset = dataset.repeat(num_epochs)\n\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n images, labels = iterator.get_next()\n\n return images, labels\n\ndef svhn_model_fn(features, labels, mode, params):\n tf.summary.image('images', features, max_outputs=6)\n network = resnet_model.cifar10_resnet_v2_generator(\n params['resnet_size'], _NUM_CLASSES, params['data_format'], FLAGS.activation)\n \n inputs = tf.reshape(features, [-1, _HEIGHT, _WIDTH, _DEPTH])\n logits = network(inputs, mode == tf.estimator.ModeKeys.TRAIN)\n \n predictions = {\n 'classes': tf.argmax(logits, axis=1),\n 'probabilities': tf.nn.softmax(logits, name='softmax_tensor')\n }\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n #calculate loss\n cross_entropy = tf.losses.softmax_cross_entropy(\n logits=logits, onehot_labels=labels)\n\n #logging cross entropy\n tf.identity(cross_entropy, name='cross_entropy')\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n #Add weight decay to the loss\n loss = cross_entropy + _WEIGHT_DECAY * tf.add_n(\n [tf.nn.l2_loss(v) for v in tf.trainable_variables()])\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n # Scale the learning rate linearly with the batch size. When the batch size\n # is 128, the learning rate should be 0.1.\n initial_learning_rate = 0.1 * params['batch_size'] / 128\n batches_per_epoch = _NUM_IMAGES['train'] / params['batch_size']\n global_step = tf.train.get_or_create_global_step()\n\n # Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.\n boundaries = [int(batches_per_epoch * epoch) for epoch in [80, 120]]\n values = [initial_learning_rate * decay for decay in [1, 0.1, 0.01]]\n learning_rate = tf.train.piecewise_constant(\n tf.cast(global_step, tf.int32), boundaries, values)\n\n # Create a tensor named learning_rate for logging purposes\n tf.identity(learning_rate, name='learning_rate')\n tf.summary.scalar('learning_rate', learning_rate)\n\n optimizer = tf.train.MomentumOptimizer(\n learning_rate=learning_rate,\n momentum=_MOMENTUM)\n\n # Batch norm requires update ops to be added as a dependency to the train_op\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss, global_step)\n else:\n train_op = None\n\n accuracy = tf.metrics.accuracy(\n tf.argmax(labels, axis=1), predictions['classes'])\n metrics = {'accuracy': accuracy}\n\n # Create a tensor named train_accuracy for logging purposes\n tf.identity(accuracy[1], name='train_accuracy')\n tf.summary.scalar('train_accuracy', accuracy[1])\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=metrics)\n\ndef main(unused_argv):\n # Using the Winograd non-fused algorithms provides a small performance boost.\n os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n # Set up a RunConfig to only save checkpoints once per training cycle.\n run_config = tf.estimator.RunConfig().replace(save_checkpoints_secs=1e9)\n svhn_classifier = tf.estimator.Estimator(\n model_fn=svhn_model_fn, model_dir=FLAGS.model_dir, config=run_config,\n params={\n 'resnet_size': FLAGS.resnet_size,\n 'data_format': FLAGS.data_format,\n 'batch_size': FLAGS.batch_size,\n })\n\n for _ in range(FLAGS.train_epochs // FLAGS.epochs_per_eval):\n tensors_to_log = {\n 'learning_rate': 'learning_rate',\n 'cross_entropy': 'cross_entropy',\n 'train_accuracy': 'train_accuracy'\n }\n\n logging_hook = tf.train.LoggingTensorHook(\n tensors=tensors_to_log, every_n_iter=100)\n\n svhn_classifier.train(\n input_fn=lambda: input_fn(\n True, FLAGS.data_dir, FLAGS.batch_size, FLAGS.epochs_per_eval),\n hooks=[logging_hook])\n\n # Evaluate the model and print results\n eval_results = svhn_classifier.evaluate(\n input_fn=lambda: input_fn(False, FLAGS.data_dir, FLAGS.batch_size))\n print(eval_results)\n\n\nif __name__ == \"__main__\":\n tf.logging.set_verbosity(tf.logging.INFO)\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(argv=[sys.argv[0]] + unparsed)\n\n","sub_path":"resnet/svhn_main_test.py","file_name":"svhn_main_test.py","file_ext":"py","file_size_in_byte":7725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245928843","text":"import torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport tensorflow as tf\n\nclass BACH_Net(nn.Module):\n \n #网络的基本结构较简单,3个有300个隐藏层的LSTM,然后加两个线性层,最后是一个激活层和归一化层\n #LSTM非双向,双向做下来效果和单向差不多,但时间增加了,不划算\n #损失函数是带有mask的交叉熵函数\n \n def __init__(self, input_size, hidden_size, output_size, num_layers, max_length, lengths=[]):\n super(BACH_Net,self).__init__()\n self.lstm_layer = nn.LSTM(input_size,hidden_size,num_layers) #这里一定要搞清楚输入输出是什么,很重要\n self.Softmax = nn.Softmax(dim=3) #在Pytorch的0.4.0版本及其之后的版本,Softmax必须指定维度\n self.Sigmoid = nn.Sigmoid() #Sigmoid层\n self.Linearmiddle = nn.Linear(hidden_size,hidden_size) #第一个线性层\n self.Linearnote = nn.Linear(hidden_size,3*(output_size-1)) #第二个线性层中的音符层\n self.Linearchangenote = nn.Linear(hidden_size,3*1) #第二个线性层中的换音层\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.lengths = lengths #长度为5个,与batch数一致\n self.max_length = max_length #是batch最大长度,不是序列padding后的,padding后长度都一样\n \n def forward(self,x):\n #下面其实就做了一件事,根据batch做动态rnn输入\n #tensorflow里面只要调用dynamic_rnn就可以,但Pytorch不行\n #注意Pytorch的pack_padded_sequence函数默认序列长度递减输入\n #################################################################################\n _, idx_sort = torch.sort(self.lengths, dim=0, descending=True)\n _, idx_unsort = torch.sort(idx_sort, dim=0)\n length = torch.tensor(list(self.lengths[idx_sort])) #降序排列\n x = x[:,:length[0]]\n x_zeros = torch.zeros(5,self.max_length-length[0],self.hidden_size) #padding的长度\n x = x.index_select(0, idx_sort)\n x_packed = nn.utils.rnn.pack_padded_sequence(x,length,batch_first=True)\n x_packed,_ = self.lstm_layer(x_packed) #pack后的序列再输入lstm网络\n x_padded = nn.utils.rnn.pad_packed_sequence(x_packed,batch_first=True)\n x = x_padded[0].index_select(0, idx_unsort) #还原顺序\n if self.max_length-length[0]!=0:\n if torch.cuda.is_available():\n x = torch.cat((x.cuda(),x_zeros.cuda()),1)\n else:\n x = torch.cat((x,x_zeros),1) #将原始序列与padding的0拼接起来\n #################################################################################\n x = torch.reshape(x, [-1,self.hidden_size]) #准备转入线性层\n x = self.Linearmiddle(x) #传入第一层线性层\n \n notes = self.Linearnote(x)\n #下面需要注意shape要匹配好\n notes = self.Softmax(torch.reshape(notes,[5,self.max_length,3,(self.output_size-1)]))\n changenote = self.Linearchangenote(x)\n #changenote最后是一维,和note不一样\n changenote = self.Sigmoid(torch.reshape(changenote,[5, self.max_length,3,1]))\n \n x = torch.cat((notes, changenote),3) #在最后一个维度进行拼接\n\n return x\n\nclass LossFunction(nn.Module):\n \n def __init__(self):\n super(LossFunction, self).__init__()\n\n def forward(self,p,t):\n \n #此处为交叉熵函数,定义很简单,但必须利用torch内置函数,才能自动求导反向传播\n #比如在tensorflow中有clip截断函数,但torch中只能自己用数学方法凑出来,如下是我想的一个办法\n c_e = t*torch.log(1e-10*(1-p>1e-10).float()+p.mul((p>1e-10).float()).mul((p<1.0).float())+\\\n 1.0*(1-(p<1.0).float()).float())+ (1-t)*torch.log(1e-10*(1-(1-p)>1e-10).float()+\\\n (1-p).mul(((1-p)>1e-10).float()).mul(((1-p)<1.0).float())+1.0*(1-((1-p)<1.0).float()).float())\n c_e = -torch.sum(torch.sum(c_e,3),2) #此步为止为交叉熵定义,但此处需要有mask作用,避免padding值也算入误差\n mask = torch.sign(torch.max(torch.max(torch.abs(t),3)[0],2)[0]) #此处维度需要看清楚,在哪一个维加\n c_e*= mask #套上mask\n c_e = torch.sum(c_e,1)\n c_e/= torch.sum(mask,1) #输出列表\n\n return torch.mean(c_e.float()) #输出实数\n","sub_path":"Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205518840","text":"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nfrom __future__ import absolute_import\n\ntry:\n from collections.abc import Iterable\nexcept ImportError:\n from collections import Iterable\n\nfrom awkward._v2.forms.form import Form\n\n\nclass RecordForm(Form):\n def __init__(\n self,\n contents,\n keys,\n has_identifier=False,\n parameters=None,\n form_key=None,\n ):\n if not isinstance(contents, Iterable):\n raise TypeError(\n \"{0} 'contents' must be iterable, not {1}\".format(\n type(self).__name__, repr(contents)\n )\n )\n for content in contents:\n if not isinstance(content, Form):\n raise TypeError(\n \"{0} all 'contents' must be Form subclasses, not {1}\".format(\n type(self).__name__, repr(content)\n )\n )\n if keys is not None and not isinstance(keys, Iterable):\n raise TypeError(\n \"{0} 'keys' must be iterable, not {1}\".format(\n type(self).__name__, repr(contents)\n )\n )\n\n self._keys = keys\n self._contents = list(contents)\n self._init(has_identifier, parameters, form_key)\n\n @property\n def contents(self):\n return self._contents\n\n def __repr__(self):\n args = [repr(self._contents), repr(self._keys)] + self._repr_args()\n return \"{0}({1})\".format(type(self).__name__, \", \".join(args))\n\n def _tolist_part(self, verbose, toplevel):\n out = {\"class\": \"RecordArray\"}\n\n contents_tolist = [\n content._tolist_part(verbose, toplevel=False) for content in self._contents\n ]\n if self._keys is not None:\n out[\"contents\"] = dict(zip(self._keys, contents_tolist))\n else:\n out[\"contents\"] = contents_tolist\n\n return self._tolist_extra(out, verbose)\n\n @property\n def purelist_isregular(self):\n return True\n\n @property\n def purelist_depth(self):\n return 1\n\n @property\n def minmax_depth(self):\n if len(self._contents) == 0:\n return (0, 0)\n mins, maxs = [], []\n for content in self._contents:\n mindepth, maxdepth = content.minmax_depth\n mins.append(mindepth)\n maxs.append(maxdepth)\n return (min(mins), max(maxs))\n\n @property\n def branch_depth(self):\n if len(self._contents) == 0:\n return (False, 1)\n anybranch = False\n mindepth = None\n for content in self._contents:\n branch, depth = content.branch_depth\n if mindepth is None:\n mindepth = depth\n if branch or mindepth != depth:\n anybranch = True\n if mindepth > depth:\n mindepth = depth\n return (anybranch, mindepth)\n\n @property\n def keys(self):\n return self._keys\n","sub_path":"src/awkward/_v2/forms/recordform.py","file_name":"recordform.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"556517452","text":"import time\nimport logging\nfrom mysql.connector import MySQLConnection, Error\nfrom selenium import webdriver\nfrom selenium.common.exceptions import *\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\ndb_bd = \"hardware\"\ndb_user = \"root\"\ndb_password = \"\"\ndb_host = \"localhost\"\n\nlist_database_product = None\nchange_list_database = True\ncount_add = 0\ncount_no_add = 0\nlist_many_optimization = []\ncount_many_optimization = 0\n\nall = []\nid_brenchmark_gpu = \"\"\nid_brenchmark_cpu = \"\"\n\ngpus = []\n\nlog = logging.getLogger(__name__)\nformat = '%(asctime)s %(levelname)s:%(message)s'\nlogging.basicConfig(format=format, level=logging.INFO)\ncount_cpu = 0\ncount_zero = 0\nurl_main = [\"https://gfxbench.com/result.jsp?benchmark=gfx40\"]\n\ndef select_database(sql, data):\n try:\n conn = MySQLConnection(user = db_user, password = db_password, host = db_host, database = db_bd)\n conn.autocommit = True\n cursor = conn.cursor()\n cursor.execute(sql, data)\n rows = cursor.fetchall()\n cursor.close()\n conn.close()\n return rows\n except Error as e:\n print(\"Ошибка:\", e)\n exit(0)\n\ndef insert_database(sql, data):\n try:\n conn = MySQLConnection(user = db_user, password = db_password, host = db_host, database = db_bd)\n conn.autocommit = True\n cursor = conn.cursor()\n cursor.execute(sql, data)\n lastrowid = cursor.lastrowid\n cursor.close()\n conn.close()\n return lastrowid\n except Error as e:\n print(\"Ошибка:\", e)\n\ndef get_gpu_benchmark_id(source_name, test_name, score_name):\n sql_query = \"SELECT gpu_benchmark_id FROM gpu_benchmarks WHERE source_name = %s and test_name = %s and score_name = %s\"\n data = (source_name, test_name, score_name)\n rows = select_database(sql_query, data)\n if(len(rows)==1):\n return rows[0][0]\n else:\n print(\"Отсутствует Id бенчмаркета в таблице.\")\n exit(0)\n\ndef get_product_database(type):\n global id_brenchmark_gpu\n if(type == \"gpu\"):\n sql_query = \"SELECT gpu.id, gpu.name from gpu LEFT JOIN gpu_benchmarks_values ON gpu.id = gpu_benchmarks_values.gpu_id WHERE gpu_benchmarks_values.gpu_benchmark_id != %s OR gpu_benchmarks_values.gpu_benchmark_id is null\"\n data = (id_brenchmark_gpu,)\n rows = select_database(sql_query, data)\n return rows\n\n\ndef get_product_id(name, type):\n global list_database_product\n name_text = name\n if(type == \"cpu\"):\n sql_query = \"SELECT id FROM gpu WHERE name = %s\"\n else:\n if(type == \"gpu\"):\n sql_query = \"SELECT id FROM gpu WHERE name = %s\"\n\n data = (name_text,)\n rows = select_database(sql_query, data)\n if(len(rows) == 1):\n return rows[0][0]\n\ndef add_gpu_benchmark(gpu_id, id_benchmark, mark):\n\n sql_query = \"SELECT row_id FROM gpu_benchmarks_values WHERE gpu_id = %s and gpu_benchmark_id = %s and value = %s\"\n data = (gpu_id, id_benchmark, mark)\n rows = select_database(sql_query, data)\n if(len(rows) == 1):\n return rows[0][0]\n else:\n if(len(rows) == 0):\n sql_query = \"INSERT INTO gpu_benchmarks_values (gpu_id, gpu_benchmark_id, value) VALUES (%s, %s, %s)\"\n return insert_database(sql_query, data)\n\n\ndef optimization(item):\n # if (item.find(\"APU\") != -1):\n # item = item.replace(\"APU\", \"\")\n # text = re.search(\"IGP$\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n # text = re.search(\"[a-zA-Z]{3,}-Core\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n # text = re.search(\"^Mobile\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n #\n # text = re.search(\"SOC$\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n #\n # text = re.search(\"Athlon Dual Core [0-9]{4}[a-zA-Z]\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n # text = re.search(\"[+]$\", item)\n # if (text != None):\n # item = item.replace(text.group(0), \"\")\n # if (item.find(\"Mobility Pro Graphics\") != -1):\n # item = item.replace(\"Mobility Pro Graphics\", \"\")\n # if (item.find(\"FireGL V\") != -1):\n # item = item.replace(\"FireGL V\", \"\")\n # if (item.find(\"(TM)\") != -1):\n # item = item.replace(\"(TM)\", \"\")\n # if (item.find(\"(R)\") != -1):\n # item = item.replace(\"(R)\", \"\")\n # if (item.find(\"Black Edition\") != -1):\n # item = item.replace(\"Black Edition\", \"BE\")\n # if (item.find(\"V-Series\") != -1):\n # item = item.replace(\"V-Series\", \"\")\n if (item.find(\",\") != -1):\n item = item.replace(\",\", \"\")\n if (item.find(\"Adapter\") != -1):\n item = item.replace(\"Adapter\", \"\")\n if (item.find(\"(FireGL)\") != -1):\n item = item.replace(\"(FireGL)\", \"\")\n #\n # #cpu\n if (item.find(\"Processor\") != -1):\n item = item.replace(\"Processor\", \"\")\n if (item.find(\"Compute Engine\") != -1):\n item = item.replace(\"Compute Engine\", \"\") ##\n if (item.find(\"(Desktop)\") != -1):\n item = item.replace(\"(Desktop)\", \"\")\n if (item.find(\"Design\") != -1):\n item = item.replace(\"Design\", \"\") #?\n # if (item.find(\"ATI\") != -1):\n # item = item.replace(\"ATI\", \"\") #?\n if (item.find(\"Graphics\") != -1):\n item = item.replace(\"Graphics\", \"\") #?\n # if (item.find(\"GMA\") != -1):\n # item = item.replace(\"GMA\", \"\") #?\n if (item.find(\"®\") != -1):\n item = item.replace(\"®\", \"\")\n if (item.find(\"™\") != -1):\n item = item.replace(\"™\", \"\")\n if (item.find(\"CPU\") != -1):\n item = item.replace(\"CPU\", \"\")\n if (item.find(\"-\") != -1):\n item = item.replace(\"-\", \"\") #?\n if (item.find(\" \") != -1):\n item = item.replace(\" \", \"\")\n if (item.find(\"(\") != -1):\n item = item.replace(\"(\", \"\")\n if (item.find(\")\") != -1):\n item = item.replace(\")\", \"\")\n if (item.find(\"+\") != -1):\n item = item.replace(\"+\", \"\")\n\n item = item.lower()\n if (item.find(\"series\") != -1):\n item = item.replace(\"series\", \"\")\n if (item.find(\"gtx\") != -1):\n item = item.replace(\"gtx\", \"\")\n if (item.find(\"nvidia\") != -1):\n item = item.replace(\"nvidia\", \"\")\n if (item.find(\"amd\") != -1):\n item = item.replace(\"amd\", \"\")\n if (item.find(\"intel\") != -1):\n item = item.replace(\"intel\", \"\")\n if (item.find(\"radeon\") != -1):\n item = item.replace(\"radeon\", \"\")\n if (item.find(\"ati\") != -1):\n item = item.replace(\"ati\", \"\")\n\n return item\n\ndef search_best_conformity(product, type):\n global list_many_optimization\n global change_list_database, list_database_product\n # if(change_list_database):\n list_database_product = get_product_database(type)\n change_list_database = False\n\n name_product_list = [i[1] for i in list_database_product]\n index_product_list = [i[0] for i in list_database_product]\n list_new = []\n for name in name_product_list:\n list_new.append(optimization(name))\n new_product = optimization(product)\n count_optimization = 0\n memory_index = -1\n many_optimization = []\n for index, new in enumerate(list_new):\n # print(new,\"---\", new_product)\n if(new == new_product):\n many_optimization.append(name_product_list[index])\n count_optimization += 1\n memory_index = index\n if(count_optimization == 1):\n print(\"Оптимизировалось:\", name_product_list[memory_index], index_product_list[memory_index])\n change_list_database = True\n return index_product_list[memory_index]\n if(count_optimization > 0):\n global count_many_optimization\n count_many_optimization+= 1\n list_many_optimization.append(many_optimization)\n\n\n\n\ndef init_driver():\n ff = \"../install/chromedriver.exe\"\n chrome_option = webdriver.ChromeOptions()\n chrome_option.add_argument(\"headless\")\n prefs = {\"profile.managed_default_content_settings.images\": 2}\n chrome_option.add_experimental_option(\"prefs\", prefs)\n\n\n try:\n # driver = webdriver.Firefox(executable_path=ff)\n driver = webdriver.Chrome(executable_path=ff, chrome_options=chrome_option)\n # driver = webdriver.Chrome(executable_path=ff, chrome_options=chrome_option, service_args=service_args)\n except SessionNotCreatedException:\n print(\"Ошибка инициализации браузера. Скорее всего у вас не установлен браузер. Пожалуйста обратитесь к разработчику парсера\")\n\n return driver\n\n\n\ndef parse(url):\n source_name = \"GFXBench 4.0\"\n selected = [\"Car Chase Offscreen\", \"Manhattan\", \"T-Rex\"]\n global count_cpu, count_add, count_no_add\n print(\"Запуск браузера\")\n driver = init_driver()\n print(\"Переход на страницу:\", url)\n driver.get(url)\n\n tickets_per_page_top_control_selectSelectBoxIt = driver.find_element_by_css_selector(\n '#tickets-per-page-top-control-selectSelectBoxIt').click()\n tickets_per_page_top_control_selectSelectBoxItOptions = WebDriverWait(driver, 30).until(\n EC.visibility_of_element_located((By.CSS_SELECTOR, \"#tickets-per-page-top-control-selectSelectBoxItOptions\")))\n lis = tickets_per_page_top_control_selectSelectBoxItOptions.find_elements_by_css_selector('li')\n for li in lis:\n if (li.find_element_by_css_selector('a').text == \"Show all\"):\n li.click()\n break\n\n for select in selected:\n id_brenchmark_gpu_frames = get_gpu_benchmark_id(source_name, select, \"Frames\")\n id_brenchmark_gpu_fps = get_gpu_benchmark_id(source_name, select, \"Fps\")\n # window_result = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"div.results-list\")))\n testSelectBoxItContainer = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#testSelectBoxItContainer'))).click()\n testSelectBoxItOptions = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"#testSelectBoxItOptions\")))\n lis = testSelectBoxItOptions.find_elements_by_css_selector('li')\n for li in lis:\n text = li.find_element_by_css_selector('a').text\n if(text == select):\n li.click()\n break\n div_results_list = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"div.results-list\")))\n items = div_results_list.find_elements_by_css_selector(\"#result-list-container>a>ul\")\n print(len(items))\n for index, item in enumerate(items):\n lis = item.find_elements_by_css_selector(\"li\")\n name = lis[1].text\n value = lis[5].find_element_by_css_selector('span.value').text\n if(value == \"Failed / Not supported\"):\n value = None\n fps = lis[5].find_element_by_css_selector('span.fps').text\n if(fps == \"Failed / Not supported\"):\n fps = None\n if(fps.find(\")\") != -1):\n fps = fps.replace(\")\", \"\")\n if (fps.find(\"(\") != -1):\n fps = fps.replace(\"(\", \"\")\n fps = fps[:-3]\n\n\n id_product = get_product_id(name, \"gpu\")\n if (id_product != None):\n add_gpu_benchmark(id_product, id_brenchmark_gpu_frames, value)\n add_gpu_benchmark(id_product, id_brenchmark_gpu_fps, fps)\n count_add += 1\n print(\"Добавлен в БД:\", [id_product, id_brenchmark_gpu_frames, value])\n print(\"Добавлен в БД:\", [id_product, id_brenchmark_gpu_fps, fps])\n else:\n id_product = search_best_conformity(name, \"gpu\")\n if (id_product != None):\n add_gpu_benchmark(id_product, id_brenchmark_gpu_frames, value)\n add_gpu_benchmark(id_product, id_brenchmark_gpu_fps, fps)\n count_add += 1\n print(\"Добавлен в БД:\", [id_product, id_brenchmark_gpu_frames, value])\n print(\"Добавлен в БД:\", [id_product, id_brenchmark_gpu_fps, fps])\n else:\n count_no_add += 1\n gpus.append([name])\n print(\"Добавлен в список недобавленных:\", [name, value])\n\n\ndef main():\n global gpus, id_brenchmark_gpu, list_many_optimization, count_many_optimization, count_add, count_no_add, change_list_database\n start_time = time.time()\n for url in url_main:\n change_list_database = True\n parse(url)\n\n #\n # for list_many_optimization in list_many_optimization:\n # print(list_many_optimization)\n\n print(\"------------------------Недобавленные GPUS-----------------------------\")\n for gpu in gpus:\n print(gpu)\n print(\"Количество add:\", count_add)\n print(\"Количество no_add:\", count_no_add)\n print(\"Количество 2 и более значений:\", count_many_optimization)\n print(\"Время работы:\", time.time() - start_time)\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"compubench.com_gfxbench.com/gfxbench.com.py","file_name":"gfxbench.com.py","file_ext":"py","file_size_in_byte":13470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98706151","text":"import random\n\n\ndef main():\n # Block 1\n\n count = list()\n for i in range(10):\n count.append(0)\n\n # Block 2\n\n num = 100000\n\n inp = input(\"Number of random intengers: \")\n\n if inp.isdigit():\n num = int(inp)\n else:\n print(\"** Invalid input. Assuming 100000. **\")\n\n for n in range(num):\n i = random.randint(0, 9)\n count[i] += 1\n\n # Block 3\n\n for i in range(10):\n print(\"\\t\" + str(i) + \":\", '{:>7}'.format(count[i]))\n\n\nmain()\n","sub_path":"CSE-231/lab07/lab07.partd.py","file_name":"lab07.partd.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376203101","text":"import logging\n\n\ndef init_log(args):\n raw_log_level = 2 + (args.verbose or 0) - (args.quiet or 0)\n if raw_log_level <= 0:\n log_level = logging.CRITICAL\n elif raw_log_level == 1:\n log_level = logging.ERROR\n elif raw_log_level == 2: # default\n log_level = logging.WARNING\n elif raw_log_level == 3:\n log_level = logging.INFO\n else:\n log_level = logging.DEBUG\n\n if log_level == logging.DEBUG:\n FORMAT = '%(levelname).1s %(asctime)-15s ' \\\n '%(filename)s:%(lineno)d %(message)s'\n else:\n FORMAT = '%(levelname).1s %(asctime)-15s %(message)s'\n\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(log_level)\n stream_handler.setFormatter(logging.Formatter(\n FORMAT,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n ))\n\n handlers = [stream_handler]\n\n if args.outputfilename_log:\n file_handler = logging.FileHandler(args.outputfilename_log)\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(logging.Formatter(\n FORMAT,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n ))\n handlers.append(file_handler)\n\n logging.basicConfig(\n level=logging.DEBUG,\n )\n\n logging.getLogger('').handlers = handlers\n","sub_path":"smbcrawler/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"330550201","text":"import numpy as np\nimport random\n\nfrom sklearn.cluster import DBSCAN\n\n\nclass TSProcessor:\n def __init__(self, points_in_template: int, max_template_spread: int):\n\n # максимальное расстояние между соседними зубчиками шаблона\n self._max_template_spread = max_template_spread\n\n self.x_dim: int = max_template_spread ** (points_in_template - 1) # сколько у нас всего шаблонов\n self.z_dim: int = points_in_template # сколько зубчиков в каждом шаблоне\n\n # сами шаблоны\n templates = (np.repeat(0, self.x_dim).reshape(-1, 1), )\n\n # непонятный код, который заполняет шаблоны нужными значениями. Пытаться вникнуть бесполезно.\n for i in range(1, points_in_template):\n col = (np.repeat(\n np.arange(1, max_template_spread + 1, dtype=int), max_template_spread ** (points_in_template - (i + 1))\n ) + templates[i - 1][::max_template_spread ** (points_in_template - i)]).reshape(-1, 1)\n\n templates += (col, ) # don't touch\n\n self._templates: np.ndarray = np.hstack(templates)\n\n # формы шаблонов, т.е. [1, 1, 1], [1, 1, 2] и т.д.\n self._template_shapes: np.ndarray = self._templates[:, 1:] - self._templates[:, :-1]\n\n def fit(self, time_series: np.ndarray) -> None:\n '''Обучить класс на конкретном ряду.'''\n\n self._time_series = time_series\n self.y_dim = self._time_series.size - self._templates[0][-1]\n self._original_size = self._time_series.size\n\n # создать обучающее множество\n # Его можно представить как куб, где по оси X идут шаблоны, по оси Y - вектора,\n # а по оси Z - индивидуальные точки векторов.\n # Чтобы получить точку A вектора B шаблона C - делаем self._training_vectors[C, B, A].\n # Вектора идут в хронологическом порядке \"протаскивания\" конкретного шаблона по ряду,\n # шаблоны - по порядку от [1, 1, ... , 1], [1, 1, ..., 2] до [n, n, ..., n].\n self._training_vectors: np.ndarray = \\\n np.full(shape=(self.x_dim, self.y_dim, self.z_dim), fill_value=np.inf, dtype=float)\n\n # тащим шаблон по ряду\n for i in range(self.x_dim):\n template_data = (\n self._time_series[self._templates[i]\n + np.arange(self._time_series.size - self._templates[i][-1])[:, None]]\n )\n\n self._training_vectors[i, :template_data.shape[0]] = (\n self._time_series[self._templates[i]\n + np.arange(self._time_series.size - self._templates[i][-1])[:, None]]\n )\n\n def pull(self, steps: int, eps: float, n_trajectories: int, noise_amp: float) -> np.ndarray:\n '''\n Основной метод пулла, который использовался в статье.\n\n Parameters\n ----------\n steps : int\n На сколько шагов прогнозируем.\n eps : float\n Минимальное Евклидово расстояние от соответствующего шаблона, в пределах которого должны находиться\n вектора наблюдений, чтобы считаться \"достаточно похожими\".\n n_trajectories : int\n Сколько траекторий использовать. Чем больше, тем дольше время работы и потенциально точнее результат.\n noise_amp : float\n Максимальная амплитуда шума, используемая при расчете траекторий.\n\n Возвращает матрицу размером steps x n_trajectories, где по горизонтали идут шаги, а по вертикали - прогнозы\n каждой из траекторий на этом шаге.\n '''\n\n # прибавляем к тренировочному датасету steps пустых векторов, которые будем заполнять значениями на ходу\n self._training_vectors = np.hstack([self._training_vectors,\n np.full([self.x_dim, steps, self.z_dim], fill_value=np.inf)])\n\n # удлиняем изначальый ряд на значение steps\n self._time_series = np.resize(self._time_series, self._original_size + steps)\n self._time_series[-steps:] = np.nan\n\n # сеты прогнозных значений для каждой точки, в которой будем делать прогноз\n forecast_sets = np.full((steps, n_trajectories), np.nan)\n\n for i in range(n_trajectories):\n for j in range(steps):\n\n # тестовые вектора, которые будем сравнивать с тренировочными\n last_vectors = (self._time_series[:self._original_size + j]\n [np.cumsum(-self._template_shapes[:, ::-1], axis=1)[:, ::-1]])\n\n distance_matrix = self._calc_distance_matrix(last_vectors, np.repeat(True, self.x_dim), steps)\n\n # последние точки тренировочных векторов, оказавшихся в пределах eps\n points = self._training_vectors[distance_matrix < eps][:, -1]\n\n # теперь нужно выбрать финальное прогнозное значение из возможных\n # я выбираю самое часто встречающееся значение, но тут уже можно на свое усмотрение\n forecast_point = self._freeze_point(points, 'mf') \\\n + random.uniform(-noise_amp, noise_amp)\n forecast_sets[j, i] = forecast_point\n self._time_series[self._original_size + j] = forecast_point\n\n # у нас появилась новая точка в ряду, последние вектора обновились, добавим их в обучающие\n new_training_vectors = (\n self._time_series[:self._original_size + 1 + j]\n [np.hstack((np.cumsum(-self._template_shapes[:, ::-1], axis=1)[:, ::-1]\n - 1, np.repeat(-1, self.x_dim).reshape(-1, 1)))]\n )\n\n self._training_vectors[:, self.y_dim + j, :] = new_training_vectors\n\n # честно говоря, я не помню, зачем нужен код дальше\n\n # delete added vectors after each run\n self._training_vectors[:, self.y_dim:] = np.inf\n\n # delete added points after each run\n self._time_series[-steps:] = np.nan\n\n return forecast_sets\n\n def cluster_sets(self, forecast_sets: np.ndarray, dbs_eps: float, dbs_min_samples: int):\n '''\n Скластеризировать полученные в результате пулла множества прогнозных значений.\n Возвращает центр самого большого кластера на каждом шаге.\n '''\n\n predictions = np.full(shape=[forecast_sets.shape[0], ], fill_value=np.nan)\n dbs = DBSCAN(eps=dbs_eps, min_samples=dbs_min_samples)\n\n for i in range(len(forecast_sets)):\n curr_set = forecast_sets[i]\n dbs.fit(curr_set.reshape(-1, 1))\n\n cluster_labels, cluster_sizes = np.unique(dbs.labels_[dbs.labels_ > -1], return_counts=True)\n\n if cluster_labels.size > 0:\n biggest_cluster_center = curr_set[dbs.labels_ == cluster_labels[cluster_sizes.argmax()]].mean()\n predictions[i] = biggest_cluster_center\n\n return predictions\n\n def _calc_distance_matrix(self, test_vectors: np.ndarray, mask: np.ndarray, steps: int) -> np.ndarray:\n '''\n По необъяснимым причинам считать матрицу расстояний между тестовыми векторами и тренировочными быстрее вот так.\n '''\n\n distance_matrix = ((self._training_vectors[mask, :, 0] - np.repeat(test_vectors[:, 0], self.y_dim + steps)\n .reshape(-1, self.y_dim + steps)) ** 2\n + (self._training_vectors[mask, :, 1] - np.repeat(test_vectors[:, 1], self.y_dim + steps)\n .reshape(-1, self.y_dim + steps)) ** 2\n + (self._training_vectors[mask, :, 2] - np.repeat(test_vectors[:, 2], self.y_dim + steps)\n .reshape(-1, self.y_dim + steps)) ** 2) ** 0.5\n\n return distance_matrix\n\n def _freeze_point(self, points_pool: np.ndarray, how: str, dbs_eps: float = 0.0, dbs_min_samples: int = 0) -> float:\n '''\n Выбрать финальный прогноз в данной точке из множества прогнозных значений.\n\n \"How\" варианты:\n \"mean\" = \"mean\"\n \"mf\" = \"most frequent\"\n \"cl\" = \"cluster\", нужны dbs_eps и dbs_min_samples\n '''\n\n if points_pool.size == 0:\n result = np.nan\n else:\n if how == 'mean':\n result = float(points_pool.mean())\n\n elif how == 'mf':\n points, counts = np.unique(points_pool, return_counts=True)\n result = points[counts.argmax()]\n\n elif how == 'cl':\n dbs = DBSCAN(eps=dbs_eps, min_samples=dbs_min_samples)\n dbs.fit(points_pool.reshape(-1, 1))\n\n cluster_labels, cluster_sizes = np.unique(dbs.labels_[dbs.labels_ > -1], return_counts=True)\n\n if (cluster_labels.size > 0\n and np.count_nonzero(((cluster_sizes / cluster_sizes.max()).round(2) > 0.8)) == 1):\n biggest_cluster_center = points_pool[dbs.labels_ == cluster_labels[cluster_sizes.argmax()]].mean()\n result = biggest_cluster_center\n else:\n result = np.nan\n\n return result\n\n def _fish(self, steps: int, eps: float, current_step: int) -> list:\n '''\n \"Закидываем удочку\". Из текущей точки закидываем все шаблоны вперед, насколько позволяет их длина, и сохраняем\n последние точки соответствующих обучающих векторов в массив points, которые затем аггрегируем в \"общий\" список\n forecasted_points.\n '''\n\n forecasted_points = []\n\n # длина удочки = максимальное расстояние между соседними зубчиками в шаблоне\n for i in range(min(self._max_template_spread, steps - current_step)):\n\n # вектора, последняя точка которых \"висит в воздухе\"\n last_vectors = (\n self._time_series[:self._original_size + current_step]\n [np.cumsum(-self._template_shapes[:, ::-1], axis=1)[:, ::-1]\n + (self._template_shapes[:, -1] - 1).reshape(-1, 1)]\n )\n\n # отсеиваем \"недостаточно длинные\" шаблоны\n length_mask = self._template_shapes[:, -1] > i\n\n # убираем вектора, в которые попадают непрогнозируемые точки\n non_nan_mask = ~np.isnan(last_vectors).any(axis=1)\n\n total_mask = length_mask & non_nan_mask\n\n last_vectors = last_vectors[total_mask]\n distance_matrix = self._calc_distance_matrix(last_vectors, total_mask, steps)\n\n points = self._training_vectors[total_mask][distance_matrix < eps, -1]\n forecasted_points.append(points)\n\n return forecasted_points\n\n def push(self, steps, eps, dbs_eps, dbs_min_samples):\n self._training_vectors = np.hstack([self._training_vectors,\n np.full([self.x_dim, steps, self.z_dim], fill_value=np.inf)])\n self._time_series = np.resize(self._time_series, self._original_size + steps)\n self._time_series[-steps:] = np.nan\n point_pools = [[] for _ in range(steps)]\n\n for back_point in range(steps): # двигаем задний порог\n front_point = back_point\n\n # двигаем передний порог\n while front_point < min(front_point + self._max_template_spread, steps):\n if np.isnan(self._time_series[self._original_size - 1 + front_point]):\n front_point += 1\n continue\n\n forecasted_points = self._fish(steps, eps, front_point)\n\n for i in range(len(forecasted_points)):\n point_pools[front_point + i].extend(forecasted_points[i])\n\n self._time_series[self._original_size + front_point + i] =\\\n self._freeze_point(np.array(forecasted_points[i]), 'cl', dbs_eps, dbs_min_samples)\n\n front_point += 1\n\n # добавляем только что полученные новые вектора к обучающим\n self._training_vectors[:, -steps] = self._time_series[:self._original_size + 1][\n np.hstack([\n np.cumsum(-self._template_shapes[:, ::-1], axis=1)[:, ::-1] - 1,\n np.repeat(-1, self.x_dim).reshape(-1, 1)\n ])\n ]\n\n back_point += 1\n\n return self._time_series[-steps:], point_pools\n","sub_path":"TSProcessor.py","file_name":"TSProcessor.py","file_ext":"py","file_size_in_byte":14629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"177038585","text":"import math\r\narr1 = [-5,1,2,3,6]\r\nexpected_result = [0,-1,1,2,3,-5]\r\narr2 =[0,1,2,3]\r\n\r\ndef abs(a):\r\n return -a if a<0 else a\r\ndef re_sort(arr):\r\n if not arr:\r\n return\r\n arr_length = len(arr)\r\n if arr[0] > 0:\r\n return arr\r\n if arr[arr_length-1]<0:\r\n return reverse(arr)\r\n result = [0] * arr_length\r\n pivot = re_sort_helper(arr)\r\n position = 0\r\n result[position] = arr[pivot]\r\n position += 1\r\n start = pivot-1\r\n end = pivot +1\r\n while start>=0 or end < arr_length:\r\n if start < 0:\r\n temp_start = arr[0]\r\n else:\r\n temp_start = arr[start]\r\n if end >= arr_length:\r\n temp_end = arr[arr_length-1]\r\n else:\r\n temp_end = arr[end]\r\n if abs(temp_start) <= abs(temp_end):\r\n result[position] = temp_start\r\n start -=1\r\n else:\r\n result[position] = temp_end\r\n end += 1\r\n position += 1\r\n return result\r\n\r\n","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"187762727","text":"from math import factorial\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom progress.bar import Bar\n\nimport torch\nimport torch.nn.functional as F\nimport albumentations as A\n\nfrom utils.utils import *\nfrom net.mtcnn import *\n\n\nclass Bridge:\n def __init__(self, mode='train', net_dataset='onet'):\n self.mode = mode\n self.net = net_dataset\n\n self.pnet = torch.load('/home/grey/Documents/mtcnn_model_saving/pnet/91-pnet-0.911.pth')\n self.rnet = torch.load('/home/grey/Documents/mtcnn_model_saving/rnet/111-rnet-0.910.pth')\n # self.onet = torch.load('/home/grey/Documents/mtcnn_model_saving/onet/104-onet-0.910.pth')\n\n # self.pnet = PNet().cuda()\n # weights = torch.load('/home/grey/Documents/mtcnn_model_saving/pnet_timesler.pt')\n # self.pnet.load_state_dict(weights)\n\n self.img_path = f'/data/grey/WIDER_FACE/WIDER_{mode}/images'\n self.label_path = f'/data/grey/WIDER_FACE/WIDER_{mode}/labels'\n self.save_path = f'/data/grey/WIDER_FACE/{self.net}_{mode}set/'\n\n self.mean = [0.45650857, 0.39260386, 0.36109988]\n self.std = [0.27675595, 0.26248012, 0.26266556]\n \n self.norm = A.Normalize(mean=self.mean, std=self.std, p=1)\n\n self.faces_count = 1\n self.pos_count = 1\n self.par_count = 1\n self.neg_count = 1\n\n self.labels = []\n\n def generate_dataset(self, face_thres=[0.6, 0.7, 0.8], nms_thres=[0.7, 0.7, 0.7]):\n cate_list = os.listdir(self.img_path)\n bar = Bar(f'generating {self.net}\\'s {self.mode}set:', max=99999)\n\n for cate in cate_list:\n img_list = os.listdir(os.path.join(self.img_path, cate))\n\n for img_file in img_list:\n label_file = img_file.replace('jpg', 'npy')\n img = np.array(Image.open(os.path.join(self.img_path, cate, img_file)))\n gts = np.load(os.path.join(self.label_path, cate, label_file))[:4]\n\n bboxes = self.pnet_output(img, face_thres[0], nms_thres[0])\n if self.net == 'onet':\n bboxes = self.rnet_output(bboxes, img, face_thres[1], nms_thres[1])\n\n self.save_net_set(bboxes, img, gts, bar, self.net)\n\n np.save(os.path.join(self.save_path, 'label_list_net'), self.labels)\n bar.finish()\n\n def pnet_output(self, img, face_threshold, nms_threshold):\n img_w, img_h = img.shape[0], img.shape[1]\n scale_pyramid = image_pyramid(img)\n\n bboxes = []\n\n for scale in scale_pyramid:\n img_scale = scale_image(img, scale, img_w, img_h)\n img_ = self._img2normalize_tensor(img_scale)\n\n with torch.no_grad():\n [pred_cls, bbox_reg] = self.pnet(img_)\n # [bbox_reg, pred_cls] = self.pnet(img_)\n\n dets = self._scale_img_boxes(pred_cls, bbox_reg, scale, face_threshold)\n bboxes.append(dets)\n\n bboxes = np.vstack(bboxes)\n keep = nms(bboxes, nms_threshold)\n\n return bboxes[keep]\n\n def rnet_output(self, bboxes, img, face_threshold, nms_threshold):\n img_w, img_h = img.shape[0], img.shape[1]\n\n faces = torch.zeros((bboxes.shape[0], 3, 24, 24)).cuda()\n for idx, bbox in enumerate(bboxes):\n face, _ = self.generate_face(img, bbox, img_w, img_h, (24, 24))\n faces[idx] = self._img2normalize_tensor(face)\n \n with torch.no_grad():\n [pred_cls, bbox_reg] = self.rnet(faces)\n\n pred_cls = F.softmax(pred_cls.cpu(), dim=1)\n bboxes = bboxes[np.where(pred_cls[:, 1] > face_threshold)]\n\n bbox_reg = np.array(bbox_reg.cpu())[np.where(pred_cls[:, 1] > face_threshold)]\n bboxes = self.fine_tuning(bboxes, bbox_reg)\n\n keep = nms(bboxes, nms_threshold)\n\n return bboxes[keep]\n\n def onet_output(self, bboxes, img, face_threshold, nms_threshold):\n img_w, img_h = img.shape[0], img.shape[1]\n\n faces = torch.zeros((bboxes.shape[0], 3, 48, 48)).cuda()\n for idx, bbox in enumerate(bboxes):\n face, _ = self.generate_face(img, bbox, img_w, img_h, (48, 48))\n faces[idx] = self._img2normalize_tensor(face)\n \n with torch.no_grad():\n [pred_cls, bbox_reg] = self.onet(faces)\n\n pred_cls = F.softmax(pred_cls.cpu(), dim=1)\n bboxes = bboxes[np.where(pred_cls[:, 1] > face_threshold)]\n\n bbox_reg = np.array(bbox_reg.cpu())[np.where(pred_cls[:, 1] > face_threshold)]\n bboxes = self.fine_tuning(bboxes, bbox_reg)\n\n keep = nms(bboxes, nms_threshold)\n return bboxes[keep]\n\n def _img2normalize_tensor(self, img):\n img = self.norm(image=img)['image']\n img = np.expand_dims(img.transpose(2, 0, 1), 0)\n img_ = torch.tensor(img).cuda()\n return img_\n\n def _scale_img_boxes(self, pred_cls, bbox_reg, scale, thres):\n pred_cls = pred_cls.squeeze(0).cpu()\n pred_cls = F.softmax(pred_cls, dim=0)\n\n bbox_reg = np.squeeze(bbox_reg.cpu().numpy().transpose(2, 3, 0, 1), axis=2)\n bbox_reg = bbox_reg[np.where(pred_cls[1] > thres)]\n\n y, x = np.array(np.where(pred_cls[1] > thres)) * 2\n w, h = np.ones(y.shape) * 12, np.ones(x.shape) * 12\n score = pred_cls[1][pred_cls[1] > thres].flatten()\n\n dets = np.vstack([x, y, w, h, score]).transpose()\n keep = nms(dets, 0.5)\n\n dets = dets[keep]\n bbox_reg = bbox_reg[keep]\n\n dets = self.fine_tuning(dets, bbox_reg)\n dets[:, :4] = dets[:, :4] / scale\n\n return dets\n\n def fine_tuning(self, dets, bbox_reg):\n dets[:, 0] = dets[:, 0] + bbox_reg[:, 0] * dets[:, 2]\n dets[:, 1] = dets[:, 1] + bbox_reg[:, 1] * dets[:, 3]\n dets[:, 2] = dets[:, 2] * np.exp(bbox_reg[:, 2])\n dets[:, 3] = dets[:, 3] * np.exp(bbox_reg[:, 3])\n return dets\n\n def save_net_set(self, bboxes, img, gts, bar, net):\n img_w, img_h = img.shape[0], img.shape[1]\n size = (24, 24) if net == 'rnet' else (48, 48)\n img_size = '24x24' if net == 'rnet' else '48x48'\n\n for bbox in bboxes:\n face, label = self.generate_img_and_label(img, gts, bbox, img_w, img_h, size)\n\n if self.neg_count > self.pos_count * 2 and label[-1] == 0:\n continue\n if self.par_count > self.pos_count and label[-1] == -1:\n continue\n\n make_sure_path_exists(os.path.join(self.save_path, f'img{img_size}'))\n np.save(os.path.join(self.save_path, f'img{img_size}', f'{self.faces_count}'), face)\n\n self.labels.append(label)\n\n if label[-1] == 0:\n self.neg_count += 1\n elif label[-1] == 1:\n self.pos_count += 1\n elif label[-1] == -1:\n self.par_count += 1\n\n bar.suffix = f'{self.faces_count} / unknown'\n bar.next()\n\n self.faces_count += 1\n\n def generate_img_and_label(self, img, gts, bbox, img_w, img_h, size):\n face, bbox = self.generate_face(img, bbox, img_w, img_h, size)\n\n bbox_ = bbox.reshape(-1, 5)\n ious = iou(bbox_, gts)\n\n # negitive sample\n label = np.zeros(5)\n\n # positive sample\n idx = np.where(ious > 0.6)[0]\n if len(idx):\n gt = gts[idx][0]\n label[-1] = 1\n\n label[0] = (gt[0] - bbox[0]) / bbox[2]\n label[1] = (gt[1] - bbox[1]) / bbox[3]\n label[2] = np.log(gt[2] / bbox[2])\n label[3] = np.log(gt[3] / bbox[3])\n\n # part sample\n elif len(np.where(ious > 0.3)[0]):\n idx = np.where(ious > 0.3)[0]\n\n gt = gts[idx][0]\n label[-1] = -1\n\n label[0] = (gt[0] - bbox[0]) / bbox[2]\n label[1] = (gt[1] - bbox[1]) / bbox[3]\n label[2] = np.log(gt[2] / bbox[2])\n label[3] = np.log(gt[3] / bbox[3])\n\n return face, label\n\n def generate_face(self, img, bbox, img_w, img_h, size):\n bbox = bbox.astype('int')\n\n side = max(bbox[2], bbox[3])\n bbox[2], bbox[3] = side, side\n\n face = img[max(bbox[1], 0):min(bbox[1] + bbox[2], img_w), max(bbox[0], 0):min(bbox[0] + bbox[3], img_h)]\n\n if 0 > bbox[1]:\n face = np.pad(face, ((-bbox[1], 0), (0, 0), (0, 0)), 'constant')\n if 0 > bbox[0]:\n face = np.pad(face, ((0, 0), (-bbox[0], 0), (0, 0)), 'constant')\n if bbox[1] + bbox[2] > img_w:\n face = np.pad(face, ((0, bbox[1] + bbox[2] - img_w), (0, 0), (0, 0)), 'constant')\n if bbox[0] + bbox[3] > img_h:\n face = np.pad(face, ((0, 0), (0, bbox[0] + bbox[3] - img_h), (0, 0)), 'constant')\n\n face = Image.fromarray(face)\n face = np.array(face.resize(size))\n return face, bbox\n\ndef resize_img(img_path, save_path, size=(12, 12)):\n file_list = os.listdir(img_path)\n num_imgs = len(file_list)\n bar = Bar('resizing images:', max=num_imgs)\n\n for idx, file in enumerate(file_list):\n img = np.array(Image.open(os.path.join(img_path, file)))\n img = cv2.resize(img, size, interpolation=cv2.INTER_LINEAR)\n img = Image.fromarray(img)\n img.save(os.path.join(save_path, file))\n bar.suffix = f'{idx + 1} / {num_imgs}'\n bar.next()\n bar.finish()\n\n\ndef detector(img, face_thres=[0.6, 0.7, 0.8], nms_thres=[0.7, 0.7, 0.2]):\n bridge = Bridge()\n bboxes = bridge.pnet_output(img, face_thres[0], nms_thres[0])\n bboxes = bridge.rnet_output(bboxes, img, face_thres[1], nms_thres[1])\n bboxes = bridge.onet_output(bboxes, img, face_thres[2], nms_thres[2])\n return bboxes\n\n\nif __name__ == '__main__':\n model = 'onet'\n dataset_type = 'val'\n\n bridge = Bridge(mode=dataset_type, net_dataset=model)\n bridge.generate_dataset()\n\n# img_path = f'/data/grey/WIDER_FACE/{model}_{dataset_type}set/img'\n# save_path = f'/data/grey/WIDER_FACE/{model}_{dataset_type}set/img24x24'\n# resize_img(img_path, save_path, (24, 24))","sub_path":"bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":9961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"287970354","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport random\nimport datetime\n\nfrom flask import (request, jsonify, Response)\nfrom flask import Blueprint\napi = Blueprint('api', __name__)\n\n\nfile_path = os.path.dirname(\n os.path.abspath(__file__)) + '/static/upload/'\n\n\n@api.route('/upload/img', methods=['POST'])\ndef upload_img():\n def allowed_file(name):\n ALLOWED_EXTENSIONS = [\n 'jpeg', 'jif', 'png', 'jpg', 'bmp']\n return True\n return name.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\n if 'logo' in request.files.keys():\n files = request.files['logo']\n\n if files and allowed_file(files.filename):\n imgtype = files.filename.rsplit('.', 1)[1]\n filename = datetime.datetime.now().strftime(\n '%Y%m%d%H%M') + '%s.%s' % (random.randint(1000, 9999), imgtype)\n\n files.save(os.path.join(file_path, filename))\n url = '/api/show/tmp/' + filename\n url = '/static/upload/' + filename\n\n data = {'status': '2', 'url': url}\n return Response(json.dumps(data))\n\n data = {'status': '0', 'error': 'error'}\n return Response(json.dumps(data))\n\n\n@api.route('/show/tmp/')\ndef show_img(filename):\n import mimetypes\n img = None\n mimetype, encoding = mimetypes.guess_type(filename)\n if not img:\n with open(file_path + filename) as img:\n data = img.read()\n return Response(data, mimetype=mimetype)\n\n return Response(img, mimetype=mimetype)\n","sub_path":"staticserver/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"381366201","text":"import numpy as np\nfrom math import sqrt\nfrom time import time, sleep\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nfrom threading import Thread\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom deepstream import get, post\nimport geopy\nfrom geopy.distance import VincentyDistance\n\n\"\"\"\n\n# given lat1, lon1, b = bearing in degrees, d = distance in kilometers\norigin = geopy.Point(lat,lon)\ndestination = VincentyDistance(kilometers=d).destination(origin, b)\nlat2, lon2 = destination.latitude, destination.longitude\n\n\"\"\"\n\n\nimport cv2\n\nlookForTennisBall = False\nlocation = [ 0.0, 0.0 ]\n\n#cap = cv2.VideoCapture(\"/dev/v4l/by-id/usb-HD_Camera_Manufacturer_USB_2.0_Camera-video-index0\")\ncap = cv2.VideoCapture(0)\n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"..\")\n\n\n# ## Object detection imports\n# Here are the imports from the object detection module.\n\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util\n\n# What model to download.\nMODEL_NAME = '../output'\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('data', 'label_map.pbtxt')\n\nNUM_CLASSES = 1\n\ntBallInMM = 0.654\n\n\n# ## Load a (frozen) Tensorflow model into memory.\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n# ## Loading label map\n# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\nedgeOfCameraIndegrees = 40\ndef offSet(b):\n if b >= 0.5:\n return edgeOfCameraIndegrees*2*(b-0.5)\n else:\n return (edgeOfCameraIndegrees*2*b)-edgeOfCameraIndegrees\n\n\ndef runImageProcessing():\n global lookForTennisBall, location\n listLengths = 40\n offsetList = []\n pixelDistanceList = []\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True:\n t = time()\n ret, image_np = cap.read()\n mask = 200 if lookForTennisBall else 480\n image_np[:mask] = np.uint8(0) # block out the top 50 pixels from top of image\n #print(ret, image_np)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n #print(detection_graph.get_collection())\n #image_tensor = detection_graph.get_tensor_by_name('final_result:0')\n #print(image_tensor)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected. \n \n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n #print(scores)\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n #print(sess.run(classes))\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n # Actual detection.s\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n \n if scores[0][0] > 0.75:\n try:\n #print(\"object:\", [category_index.get(i) for i in classes[0]][0][\"name\"] + \",\", \"elapsed:\", \"{:1.4f}\".format(time() - t) + \",\", \"epochTime:\", \"{:.0f}\".format(time()))\n pass\n except:\n pass\n yPosition = (boxes[0][0][3] + boxes[0][0][1]) / 2\n degreesOffset = offSet(yPosition)\n #print('YPosition', yPosition)\n #print('degreesOffset:', degreesOffset)\n avePxWidth= int((( ( (boxes[0][0][2] - boxes[0][0][0]) * 415) + ((boxes[0][0][3] - boxes[0][0][1]) * 415) )))\n dist = (0.016 * 650 * 480) / (avePxWidth * 82) * 100 \n #print(\"pixel width\", avePxWidth)\n #print(\"pixel distance:\", int(dist), \"cm\")\n if lookForTennisBall and len(offsetList) < listLengths and len(pixelDistanceList) < listLengths:\n offsetList.append(degreesOffset)\n pixelDistanceList.append(int(dist))\n elif len(offsetList) == listLengths and lookForTennisBall:\n pxDistAverage = round(np.mean(pixelDistanceList), 2)\n offsetAverage = round(np.mean(offsetList), 2)\n print(\"POSTING VALUES TO DEEPSTREAM:\")\n print(\" pxDist:\", pxDistAverage, \" offset:\", offsetAverage)\n if len(location) == 2:\n #if location[0] != 0 and location[1] != 0:\n origin = geopy.Point(location[0],location[1])\n destination = VincentyDistance(kilometers=pxDistAverage/100000).destination(origin, offsetAverage)\n lat2, lon2 = round(destination.latitude, 16), round(destination.longitude, 16) \n print('Projected Lat:', '{:.18f}'.format(lat2), 'Lon:', '{:.18f}'.format(lon2))\n pointPayload = {\"Tball\":[ lat2, lon2 ]}\n post(pointPayload, 'Tball', 'localhost')\n print(pointPayload)\n offsetList.append(1)\n pixelDistanceList.append(1)\n pass\n \n if not lookForTennisBall:\n offsetList = []\n pixelDistanceList = []\n \n #print('score:', scores[0][0])\n\n\n #if len(distArr) < 10:\n # distArr.append(int(dist))\n # timeArr.append(int(time() - lastSeen))\n #elif len(distArr) == 10:\n #distArr[int(time()) % 10] = int(dist)\n #timeArr[int(time()) % 10] = time() - lastSeen\n #print(\"Average distance:\", np.mean(distArr))\n #print(\"DistArr:\", distArr)\n #print(\"TimeArr:\", timeArr)\n #print(\"Average Time Distance:\", np.mean(timeArr))\n #print(\"Dist:\", pow( pow((1 - radius), 0.9) / 0.01, 2.16))\n #print(\"pixel average\", radius * 800)\n\n\n \n cv2.imshow('object detection', cv2.resize(image_np, (800,600)))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\ndef inRangeOfTBall():\n global lookForTennisBall, location\n while True:\n try:\n l = get('startLooking', 'localhost')\n if type(l) is dict:\n if 'startLooking' in l:\n if l['startLooking'] == True:\n lookForTennisBall = True\n else:\n lookForTennisBall = False\n except:\n print('not connecting to deepstream')\n pass\n sleep(0.06)\n try:\n h = get('reach', 'localhost')\n if type(h) == dict:\n if 'lat' in h and 'lon' in h:\n location = (h['lat'], h['lon'])\n except:\n pass\n sleep(.06)\n\n\nt1 = Thread(target=runImageProcessing)\nt2 = Thread(target=inRangeOfTBall)\nt1.start()\nt2.start()\n\n\n","sub_path":"object_detection/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":8331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"80020563","text":"\"\"\"General utilities to get and process data from the database\"\"\"\n\n# All the usual imports for data analysis\nimport pandas as pd\nimport pandas.io.sql as pysql\nimport pymssql as py\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport v7_integrator_3 as v7\nimport zmq\nimport sys\n\n\ndef GetData(pv, mk, cd, d2, s1):\n\n # Set up the database connection . . .\n conn = py.connect(server='VM-Database', database='Autotrader')\n cursor = conn.cursor()\n\n # Set the parameters to get the raw data to import\n provider = pv\n marketname = mk\n candleduration = cd\n date2 = d2\n span1 = s1\n\n # Construct the query string and execute against the connection defined\n # above (sooo much better than Mathematica!)\n query = \"exec V7CandleView '\" + provider + \"', '\" + marketname + \"', '\" + str(candleduration) \\\n + \"', '\" + date2 + \"', '\" + span1 + \"'\"\n dataf = pysql.read_sql_query(query, conn, index_col='TimeCandle')\n query = \"select [NominalSpread] from [MarketWatchlist] where [MarketName] = '\" + \\\n marketname + \"'\"\n cursor.execute(query)\n spd = float(cursor.fetchone()[0])\n\n # Output summary data\n print()\n print(\"Number of records =\", len(dataf), \" Number of days =\", len(dataf.groupby(dataf.index.date).last()),\n \" Market =\", marketname, \" Spread =\", spd)\n\n # Plot the basic time series data\n ax = dataf.Close.plot(figsize=(16, 8)) # , style=\"darkblue\"\n ax.set_ylabel(\"Price\")\n\n # Return the initial dataset, the spread, and array version of the dataset\n return dataf, spd\n\n\n\n\ndef ConvertToArray(df1):\n \"\"\"Function to convert input dataframe to numpy array\"\"\"\n\n # Create a recarray with all the fields required for the iteration\n z = np.recarray(len(df1), dtype=[('DateNo', ' 0) & (z['TimeInt'] == 1) & (\n # z['DOK'] == 1) & np.isfinite(z['PrvC'])] = 1\n\n return z\n\n\ndef SingleDaySimulate(dataf1, sprd, mode, candur, tsth, tw, init_stop, trail_stop):\n\n # convert the passed in mode string to numeric for use in algorithm\n if mode == \"SHORT\" :\n mode = -1\n\n else:\n mode = 1\n\n # Convert input dataframe to array for fast processing in Cython\n r = ConvertToArray(dataf1)\n\n # Call the Cython routine that does single sweep of dataframe\n #v7.simulate_trade(r, mode, tsth, tw, stop, candur, sprd)\n v7.simulate_trade(r, sprd, mode, candur, tsth, tw, init_stop, trail_stop)\n\n\n # Convert the processed array back to a dataframe\n dataf2 = (pd.DataFrame.from_records(r, index=dataf1.index))\n\n # Produce required output for single day sweep - firstly a textual summary\n print()\n print(\" Date =\", dataf2.index.date[0],\n \" Total profit =\", '{:5.2f}'.format(\n dataf2.Topft[len(dataf2) - 1]),\n \" Number of trades =\", '{:0d}'.format(dataf2.Tonum[len(dataf2) - 1]))\n\n # Plot the graph\n ax = dataf2.Attpr.plot(figsize=(12, 8) , style=\"blue\" )\n dataf2.Defpr.plot(style='red')\n dataf2.Ssll.plot(style=\"orange\", ax=ax)\n #dataf2.Stplvl.plot(style=\"red\")\n ax.set_ylabel(\"Price\")\n\n return dataf2\n\n\ndef MultiDaySimulate(dataf1, sprd, mode, candur, tsth, tw, init_stop, trail_stop):\n\n # convert the passed in mode string to numeric for use in algorithm\n if mode == \"SHORT\" :\n mode = -1\n\n else:\n mode = 1\n\n # Convert input dataframe to array for fast processing in Cython\n r = ConvertToArray(dataf1)\n\n # Call the Cython routine that does single sweep of dataframe\n v7.simulate_trade(r, sprd, mode, candur, tsth, tw, init_stop, trail_stop)\n\n # Convert the processed array back to a dataframe\n dataf2 = (pd.DataFrame.from_records(r, index=dataf1.index))\n\n # Produce required output for single day sweep - firstly a textual summary\n print()\n print(\" Date =\", dataf2.index.date[0],\n \" Total profit =\", '{:5.2f}'.format(\n dataf2.Topft[len(dataf2) - 1]),\n \" Number of trades =\", '{:0d}'.format(dataf2.Tonum[len(dataf2) - 1]))\n\n # Plot the graph of profit by day, and cumulative profit, by points\n s = dataf2.groupby(dataf2.index.date)['Dapft', 'Danum'].last()\n s['Runpft'] = s.Dapft.cumsum()\n\n fig, axes = plt.subplots(nrows=3, ncols=1)\n s['Runpft'].plot(\n kind='line', ax=axes[0], figsize=(16, 12), title=\"Running performance\")\n s['Dapft'].plot(\n kind='bar', ax=axes[1], figsize=(16, 12), title=\"Daily profit\")\n s['Danum'].plot(kind='bar', ax=axes[2], figsize=(\n 16, 12), title=\"Number of trades\", color=\"green\")\n\n return dataf2\n\n\ndef MultiDaySimulate(dataf1, sprd, mode, candur, tsth, tw, init_stop, trail_stop):\n\n # convert the passed in mode string to numeric for use in algorithm\n if mode == \"SHORT\" :\n mode = -1\n\n else:\n mode = 1\n\n # Convert input dataframe to array for fast processing in Cython\n r = ConvertToArray(dataf1)\n\n # Call the Cython routine that does single sweep of dataframe\n v7.simulate_trade(r, sprd, mode, candur, tsth, tw, init_stop, trail_stop)\n\n # Convert the processed array back to a dataframe\n dataf2 = (pd.DataFrame.from_records(r, index=dataf1.index))\n\n # Produce required output for single day sweep - firstly a textual summary\n print()\n print(\" Date =\", dataf2.index.date[0],\n \" Total profit =\", '{:5.2f}'.format(\n dataf2.Topft[len(dataf2) - 1]),\n \" Number of trades =\", '{:0d}'.format(dataf2.Tonum[len(dataf2) - 1]))\n\n # Plot the graph of profit by day, and cumulative profit, by points\n s = dataf2.groupby(dataf2.index.date)['Dapft', 'Danum'].last()\n s['Runpft'] = s.Dapft.cumsum()\n\n fig, axes = plt.subplots(nrows=3, ncols=1)\n s['Runpft'].plot(\n kind='line', ax=axes[0], figsize=(16, 12), title=\"Running performance\")\n s['Dapft'].plot(\n kind='bar', ax=axes[1], figsize=(16, 12), title=\"Daily profit\")\n s['Danum'].plot(kind='bar', ax=axes[2], figsize=(\n 16, 12), title=\"Number of trades\", color=\"green\")\n\n return dataf2\n\n\ndef SweepSimulate(dataf1, sprd, mode, candur, tsth, tw, init_stop, trail_stop):\n # convert the passed in mode string to numeric for use in algorithm\n if mode == \"SHORT\" :\n mode = -1\n\n else:\n mode = 1\n\n # Convert input dataframe to array for fast processing in Cython\n r = ConvertToArray(dataf1)\n lastr = r.shape[0] - 1\n\n tsth_List = np.linspace(tsth[0], tsth[1], tsth[2])\n tw_List = np.linspace(tw[0], tw[1], tw[2])\n init_stop_List = np.linspace(init_stop[0], init_stop[1], init_stop[2])\n trail_stop_List = np.linspace(trail_stop[0], trail_stop[1], trail_stop[2])\n\n # Create a recarray with all the fields required to hold results of sweep\n y = np.recarray((len(tsth_List) * len(tw_List) * len(init_stop_List) * len(trail_stop_List) ) , \n dtype=[('Tsth', ' 0 else None\n })\n\n return result[:8]\n","sub_path":"jetbrains/project_parser.py","file_name":"project_parser.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625507868","text":"import os \nimport re\nimport cv2\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt\n\nbase_path = os.getcwd()\ndata = pd.read_csv(base_path+'/10_round_results.csv')\nimage = cv2.imread((base_path+'/dataset/trainset/faces/face00001.png'),cv2.IMREAD_GRAYSCALE)\nfeature_names = pd.read_csv(base_path+'/features_names.csv')\nfor k in range(len((data.J_values)[:])):\n image_with_feature = image.copy()\n string_temp = (feature_names.iloc[(data.J_values)[k]])[0]\n [w,h,i,j] = (re.findall('\\d+', string_temp))\n [w,h,i,j] = list(map(int, [w,h,i,j]))\n \n if ((data.J_values).iloc[k] <= 7440):\n #type2\n a = 255*np.array([1]*h*w + [0]*h*w)\n a.resize(h,2*w)\n image_with_feature[i:i+h,j:j+w*2] = a\n elif ( (data.J_values).iloc[k] <= 14880 ):\n #type 1\n a = 255*np.array([1]*h*w + [0]*h*w)\n a.resize(2*h,w)\n image_with_feature[i:i+h*2,j:w+j] = a\n elif ( (data.J_values).iloc[k] <= 18352 ):\n #type 3\n a = 255*np.array([0]*h*w + [1]*2*h*w + [0]*h*w)\n a.resize(4*h,w)\n image_with_feature[i:i+h*4,j:j+w] = a\n elif ( (data.J_values).iloc[k] <= 21824 ):\n #type 4\n a = 255*np.array([0]*h*w + [1]*2*h*w + [0]*h*w)\n a.resize(h,4*w)\n image_with_feature[i:i+h,j:4*w+j] = a\n else:\n #type 5\n a = 255*np.array([1]*h*w + [0]*h*w + [0]*h*w + [1]*h*w)\n a.resize(2*h,2*w)\n image_with_feature[i:i+2*h,j:2*w+j] = a\n \n fig = plt.imshow(image_with_feature,cmap=(plt.cm).gray)\n plt.show(fig)","sub_path":"Displaying_features.py","file_name":"Displaying_features.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214392813","text":"# Sets the Camera sensor to RGB565\ndef sensorRGB(sensor):\n sensor.reset()\n sensor.set_pixformat(sensor.RGB565)\n sensor.set_framesize(sensor.QVGA)\n sensor.skip_frames(time = 2000)\n sensor.set_auto_gain(False) # must be turned off for color tracking\n sensor.set_auto_whitebal(False) # must be turned off for color tracking\n return sensor\n\n# Sets the Camera sensor to GrayScale\ndef sensorGrayscale(sensor):\n sensor.reset()\n sensor.set_pixformat(sensor.GRAYSCALE)\n sensor.set_framesize(sensor.VGA)\n sensor.set_windowing((640//2 - 200//2, 480//2 -200//2, 200, 200))\n sensor.skip_frames(10)\n sensor.set_auto_gain(False)\n clock = time.clock()\n\n# LED function to indicate to user\ndef led_indicate():\n for i in range(0,5):\n red_led.on()\n pyb.delay(200)\n red_led.off()\n blue_led.on()\n pyb.delay(200)\n blue_led.off()\n\n# Formula to calculate the distance to an object in mm.\ndef distCalc(b):\n return int(((lens_mm * box_height_mm * image_height_pixels) / (b[3] * sensor_h_mm)) - offset_mm)\n\n# Normalize the distance and the color together. Must be 5 chars\ndef normalize_feedback(dist, color):\n dist = str(dist)\n if len(dist) > 4:\n # Distance is only good up to 3000mm (~10ft).\n mic_str == \"n9999\"\n elif len(dist) == 4:\n mic_str = color + dist\n elif len(dist) == 3:\n mic_str = color + \"0\" + dist\n return mic_str\n\n\n\n# Obtain and transfer QR code to microcontroller, then return.\ndef QR_code():\n print('test')\n # Begin looking for QR code\n while(True):\n clock.tick()\n img = sensor.snapshot()\n img.lens_corr(1.0)\n for code in img.find_qrcodes():\n img.draw_rectangle(code.rect(), color = (255, 0, 0))\n myArray = \"\\0\" * 24\n myArray = code.payload()\n #break array into three gps coordinates\n str = myArray[7:]\n qr1 = str[1:25]\n qr2 = str[27:52]\n qr3 = str[54:80]\n\n message = 'N'\n\n while message != '0':\n uart.write(qr1)\n print(qr1)\n message = uart.read(1)\n\n while message != '1':\n uart.write(qr2)\n print(qr2)\n message = uart.read(1)\n\n while message != '2':\n uart.write(qr3)\n print(qr3)\n message = uart.read(1)\n #if microcontroller sends f, return to mani loop\n if uart.read(1) == 'f':\n return;\n\n\n# Blob detection that also calls distance function and returns to microcontroller.\ndef objectDetection(uart, cam, curr_threshold, color):\n '''\n Purple box - clear day - 10am\n threshold[0][0-3]\n [28, 37, 18, 35, -18, -3] - Facing south\n [43, 50, 26, 36, -44, -34] - facing North\n [81, 88, 24, 34, -27, -17] - facing west\n [44, 63, 18, 32, -40, -28] - facing east\n red box - clear day - 10am\n threshold[0][4-7]\n [34, 38, 47, 53, 13, 29] - facing south\n [43, 68, 17, 72, 24, 47] - facing north\n [67, 69, 41, 45, 34, 50] - facing west\n [42, 57, 36, 47, -4, 13] - facing east\n '''\n\n # Begin looking for blobs/boxes. It will never exit this while loop.\n while(True):\n clock.tick()\n img = sensor.snapshot()\n cam.add_frame(img)\n # Possibly need to add square after testing, and change pixel/area threshold.\n for blob in img.find_blobs(curr_threshold, area_threshold=300, merge=True, margin=10):\n # Draw rect and cross to identify blob currently being tracked.\n img.draw_rectangle(blob.rect())\n img.draw_cross(blob.cx(), blob.cy())\n\n '''\n # Obtain statistics based on blob, to be able to tell what color blob is.\n perc = img.get_statistics(roi=blob.rect())\n # Reset color, incase none is detected\n color = \"n\"\n # Check if color is within threshold for.\n if (perc[20] in range(threshold[1][5], threshold[0][5] +1)): # Purple\n color = \"p\"\n elif (perc[20] in range(threshold[7][5], threshold[6][5] +1)): # Red\n color = \"r\"\n print(perc[20])\n '''\n\n\n # Obtain distance.\n distance = distCalc(blob)\n\n # Normalize values and return to microcontroller.\n mic_str = normalize_feedback(distance, color)\n uart.write(mic_str)\n print(mic_str) # Can be removed in final implementation\n\n # Check if micro doesn't need to check for this box anymore\n message = uart.read(1)\n if message == \"1\":\n led_indicate() # Flip LEDs to indicate succesful run\n return # Go back to 'main' to continue code\n\n'''\n MAIN MAIN MAIN MAIN MAIN\n'''\n# Import packages\nimport sensor, image, time, mjpeg\nfrom pyb import UART\nimport pyb\nclock = time.clock()\n\n# Variables needed for distance calculations. Almost all values are correctly set for wide angle lens.\nlens_mm = 1.7 # Wide angle lens value\nbox_height_mm = 355.6 # 14\" to mm\nimage_height_pixels = 240.0 # QVGA # Currently runs on QVGA, 120x160\nsensor_h_mm = 2.952 # For OV7725 sensor - see datasheet.\noffset_mm = -60.0 # Offset fix... Think this is a correction + b\n\n# Set up LEDs for better understanding of what the camera is doing\nred_led = pyb.LED(1)\ngreen_led = pyb.LED(2)\nblue_led = pyb.LED(3)\nred_led.off()\ngreen_led.off()\nblue_led.off()\n\n# Create the UART object\nuart = UART(3, 9600)\n\n\n# Set thresholds, need to be set before every run\nred_threshold = [(69, 74, 4, 12, 38, 57)]\npurple_threshold = [(69, 72, -23, -16, -27, -19)]\n\n#Set sensor to grayscale for QR_code, and obtain QR code\nsensorGrayscale(sensor)\nprint(\"getting qr codes\")\nQR_code()\n\n# Set sensor for blob detection and send to blob detection.\nsensorRGB(sensor)\n\n# Create camera object\n#cam = mjpeg.Mjpeg('demonstration.mp4')\n\nwhile (message != '1'): # While we do not have an end command from the micro controller..\n objectDetection(uart, cam, red_threshold, 'r')\n objectDetection(uart, cam, purple_threshold, 'p')\n objectDetection(uart, cam, purple_threshold, 'p')\n\ncam.close()\n","sub_path":"OpenMV/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280169898","text":"\"\"\"Well then, how can we calculate a more accurate\nfixed monthly payment than we did in Problem 2 without\nrunning into the problem of slow code?\n What is a good upper bound? Imagine the\n instead of paying monthly, we paid off the\n entire balance at the end of the year. What we\n ultimately pay must be greater than what we\n would've paid in monthly installments, because\n the interest was compounded on the balance\n we didn't pay off each month. So a good upper\n bound for the monthly payment would be one-twelfth of the balance, after having its\n interest compounded monthly for an entire year.\"\"\"\ndef payingdebt_offinayear(balance, annual_interestrate):\n \"\"\"\n A function to calculate the lowest payment\n \"\"\"\n def bal_d(balance, pay, annual_interestrate):\n \"\"\"A function \"\"\"\n balan_d = balance\n for _ in range(1, 13):\n unpaid_bal = balan_d - pay\n balan_d = unpaid_bal*(1 + (annual_interestrate/12.0))\n return balan_d\n payment_low = balance/12.0\n monthly_interestrate = annual_interestrate/12.0\n payment_high = (balance*((1 + monthly_interestrate)**12))/12.0\n payment = (payment_high + payment_low)/2.0\n epsilon = 0.05556\n\n while True:\n if bal_d(balance, payment, annual_interestrate) > epsilon:\n payment_low = payment\n elif bal_d(balance, payment, annual_interestrate) < -epsilon:\n payment_high = payment\n else:\n return round(payment, 2)\n payment = (payment_high + payment_low)/2.0\ndef main():\n \"\"\"An output\"\"\"\n data = input()\n data = data.split(' ')\n data = list(map(float, data))\n print(\"Lowest Payment: \" + str(payingdebt_offinayear(data[0], data[1])))\nif __name__ == \"__main__\":\n main()\n","sub_path":"M7/p3/Functions - Assignment-3/assignment3.py","file_name":"assignment3.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"595418890","text":"import re as regex\nimport nltk\nimport pandas as pd\n\n\nclass DataCleaner:\n def __init__(self, is_testing):\n self.is_testing = is_testing\n\n words = set(nltk.corpus.words.words())\n\n def iterate(self):\n for cleanup_method in [self.remove_duplicates,\n self.remove_noneng_rssfeeds,\n self.remove_urls,\n self.clean_text,\n self.remove_special_chars,\n self.processHashtags,\n self.processHandles,\n self.processUrls,\n self.processRepeatings\n ]:\n yield cleanup_method\n\n\n @staticmethod\n def remove_by_regex(rssfeeds, regexp):\n rssfeeds.loc[:, \"summary\"].replace(regexp, \"\", inplace=True)\n return rssfeeds\n\n def remove_duplicates(self, tweets):\n print(\"removing duplicate tweets\")\n tweets.drop_duplicates(subset=[\"summary\"], inplace=True)\n print(\"Number of tweets after removing duplicates: \",tweets.shape)\n return tweets\n\n def clean_text(self, rssfeeds):\n print(\"removing unwanted text\")\n print(rssfeeds.head())\n for index,rssfeed in rssfeeds[1:].iterrows():\n rssfeed[\"author\"] = regex.sub('\\/u/', '', rssfeed.author)\n rssfeed.title = regex.sub('\\/u/.*$', '', rssfeed.title)\n rssfeed.summary = regex.sub('\\/u/.*$', '', rssfeed.summary)\n if \"submitted by\" in rssfeed[\"summary\"]:\n rssfeed[\"summary\"] = rssfeed[\"title\"]\n if \"submitted by\" in rssfeed[\"title\"]:\n rssfeed[\"title\"] = rssfeed[\"author\"]\n print(\"after cleaning data: \", rssfeeds.head())\n print(\"Number of rssfeeds after removing duplicates: \", rssfeeds.shape)\n return rssfeeds\n\n\n def remove_noneng_rssfeeds(self, rssfeeds):\n rssfeeds_text=[]\n print(\"removing non english rssfeeds\")\n print(\"filtered rssfeed\")\n\n try:\n for i in range(len(rssfeeds)):\n rssfeeds_text.append(\" \".join(w for w in nltk.wordpunct_tokenize(str(rssfeeds[\"summary\"][i])) if w.lower() in self.words or w.isalpha()))\n rssfeeds[\"summary\"]=rssfeeds_text\n except Exception as e:\n print(\"exception: \",e)\n return rssfeeds\n\n def remove_urls(self, rssfeeds):\n print(\"removing urls\")\n return self.remove_by_regex(rssfeeds, regex.compile(r\"http.?://[^\\s]+[\\s]?\"))\n\n # def remove_na(self, rssfeeds):\n # print(\"removing NA values\")\n # return rssfeeds[rssfeeds[\"summary\"] != \"Not Available\"]\n\n def remove_special_chars(self, rssfeeds): # it unrolls the hashtags to normal words\n print(\"removing special characters\")\n for remove in map(lambda r: regex.compile(regex.escape(r)), [\",\", \":\", \"\\\"\", \"=\", \"&\", \";\", \"%\", \"$\",\n \"@\", \"%\", \"^\", \"*\", \"(\", \")\", \"{\", \"}\",\n \"[\", \"]\", \"|\", \"/\", \"\\\\\", \">\", \"<\", \"-\",\n \"!\", \"?\", \".\", \"'\",\n \"--\", \"---\", \"#\"]):\n rssfeeds.loc[:, \"summary\"].replace(remove, \"\", inplace=True)\n return rssfeeds\n\n # def process_usernames(self, rssfeeds):\n # print(\"processing user names\")\n # rssfeeds.author = rssfeeds.author[3:]\n # # print(rssfeeds.head())\n # return rssfeeds\n\n # def remove_numbers(self, rssfeeds):\n # print(\"removing numbers\")\n # return self.remove_by_regex(rssfeeds, regex.compile(r\"\\s?[0-9]+\\.?[0-9]*\"))\n\n # Hashtags\n hash_regex = regex.compile(r\"#(\\w+)\")\n\n def hash_repl(self,match):\n return '__HASH_' + match.group(1).upper()\n\n # Handels\n hndl_regex = regex.compile(r\"@(\\w+)\")\n\n def hndl_repl(self,match):\n return '__HNDL' # _'+match.group(1).upper()\n\n # URLs\n url_regex = regex.compile(r\"(http|https|ftp)://[a-zA-Z0-9\\./]+\")\n\n # Spliting by word boundaries\n word_bound_regex = regex.compile(r\"\\W+\")\n\n # Repeating words like hurrrryyyyyy\n rpt_regex = regex.compile(r\"(.)\\1{1,}\", regex.IGNORECASE);\n\n def rpt_repl(self,match):\n return match.group(1) + match.group(1)\n\n def processHashtags(self, rssfeeds):\n # print(\"head: \", rssfeeds.head())\n for index,rssfeed in rssfeeds[1:].iterrows():\n rssfeed[\"summary\"] = regex.sub(self.hash_regex, self.hash_repl, rssfeed[\"summary\"])\n return rssfeeds\n\n def processHandles( self, rssfeeds):\n for index,rssfeed in rssfeeds[1:].iterrows():\n rssfeed[\"summary\"] = regex.sub(self.hndl_regex, self.hndl_repl, rssfeed[\"summary\"])\n return rssfeeds\n\n def processUrls( self, rssfeeds):\n for index,rssfeed in rssfeeds[1:].iterrows():\n rssfeed[\"summary\"] = regex.sub( self.url_regex, ' __URL ', rssfeed[\"summary\"])\n return rssfeeds\n\n\n def processRepeatings( \tself, rssfeeds):\n for index, rssfeed in rssfeeds[1:].iterrows():\n rssfeed[\"summary\"] = regex.sub(self.rpt_regex, self.rpt_repl, rssfeed[\"summary\"])\n # print(\"rssfeeds columns in process repearing: \\n******************\\n\", rssfeeds.columns, \"\\n******************\\n\")\n # print(rssfeeds.head())\n return rssfeeds\n\n\n\n","sub_path":"rssfeed_analysis/data_cleaner.py","file_name":"data_cleaner.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"525455680","text":"import tensorflow as tf\n\nfrom modelv4 import yolov4\nfrom utils.misc_utils import parse_anchors, load_weights\n\nnum_class = 80\nimg_size = 608\nweight_path = './data/darknet_weights_v4/yolov4.weights'\nsave_path = './data/darknet_weights_v4/yolov4.ckpt'\nanchors = parse_anchors('./data/yolo_anchors.txt')\n\nmodel = yolov4(80, anchors)\nwith tf.Session() as sess:\n inputs = tf.placeholder(tf.float32, [1, img_size, img_size, 3])\n\n with tf.variable_scope('yolov4'):\n feature_map = model.forward(inputs)\n\n saver = tf.train.Saver(var_list=tf.global_variables(scope='yolov4'))\n\n load_ops = load_weights(tf.global_variables(scope='yolov4'), weight_path)\n sess.run(load_ops)\n saver.save(sess, save_path=save_path)\n print('TensorFlow model checkpoint has been saved to {}'.format(save_path))\n","sub_path":"convert_weight_v4.py","file_name":"convert_weight_v4.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"429708933","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n\n#create 100 point data\nX = 2 * np.random.rand(100, 1)\ny = 4 + 3*X + np.random.rand(100, 1)\n\nX_b = np.c_[np.ones((100, 1)), X]\n\ntheta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)\n\n#test\nX_new = np.array([[0], [2]])\nX_new_ = np.c_[np.ones((2, 1)), X_new]\n\ny_pre = X_new_.dot(theta)\n\nprint(\"Theta = {}\".format(theta))\n\n\nplt.plot(X_new, y_pre, 'b-')\nplt.plot(X, y, 'r.')\nplt.axis([0, 2, 0, 15])\nplt.show()\n\n\n#Su dung thuat toan LinearRegression() de kiem tra ket qua\nln = LinearRegression()\nln.fit(X, y)\n\nW, b = ln.coef_, ln.intercept_\n\nprint(\"W = {} \\n b = {}\".format(W, b))\n","sub_path":"gradientDescent/example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"265741440","text":"#! /usr/bin/env python3\nfrom ch07ex01 import Person as Person\n\nclass Family:\n \n def __init__(self, mother, father, *kids):\n self.mother = mother\n self.father = father\n self.kids = []\n for i in kids:\n self.kids.append(i)\n\n def add(self, kid):\n self.kids.append(kid)\n\n def __str__(self):\n family = \"Parents \\n\" + str(self.mother) + \" \" + str(self.father) + \"\\nChildren\"\n for i in self.kids:\n family += \"\\n\" + str(i)\n return family\nmother = Person(\"Mom\", 45, \"F\")\nfather = Person(\"Dad\", 45, \"M\")\nkid1 = Person(\"Johnie\", 2, \"M\")\nkid2 = Person(\"Janie\", 3, \"F\")\nmyFamily = Family(mother, father, kid1, kid2)\nkid3 = Person(\"Paulie\", 1, \"M\")\nmyFamily.add(kid3)\nprint(myFamily)\n","sub_path":"ch07ex02fam.py","file_name":"ch07ex02fam.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167419024","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 4 08:56:23 2018\n\n@author: florefe\n\"\"\"\n\nimport Predictor as pr\nimport pandas as pd\nimport numpy as np\n\nnum_files_training_with = 4\npredictor = pr.Predictor()\npredictor.load_trainers(1,num_files_training_with)\n#test_data = [[29.99254335, -95.42296647, '12/8/2017 1:33']]\n\ninputs = pd.read_csv('../data/notification_submission_dest_coords.csv')\n\n#predict arrival at current spot and store as delta\ntest_data = []\nfor i in range(0,6):\n test_data.append([[inputs['lat'][i], inputs['lng'][i],\n inputs['route_begin'][i], inputs['timestamp'][i],\n inputs['dest_lat'][i],\n inputs['dest_lng'][i]]])\n\ndelta =[]\n\nfor test in test_data:\n for t in test:\n delta.append(predictor.predict(t[0], t[1], t[2], t[3]))\nprint (delta)\n#get prediction for destination\npredictions = []\nfor test in test_data:\n for t in test:\n predictions.append(predictor.predict(t[4], t[5], t[2], t[3]))\n#subtract delta\nfor i in range(0,6):\n predictions[i] = predictions[i]-delta[i]\nprint (predictions)\n\n","sub_path":"rsgtpg/PredictorTest.py","file_name":"PredictorTest.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"77197756","text":"import os,sys\nimport csv\nimport shutil\nfrom xlrd import *\nfrom xlutils.copy import copy\n\ndef results_xl_file():\n\tfile = copy(open_workbook('..\\\\results\\\\final_results.xls'))\n\t#file.sheet_name('ETC Power Data Transfer Measurements')\n\treturn file\n\t\ndef results_file_name(test_condition):\n\t#CSV file name creation\n\tfile_name ='stc'\n\tfor i in range(len(test_condition)):\n\t\tfile_name += '_'+test_condition[i]\n\treturn file_name\n\n \ndef results_modification(row_no,current_mode,test_condition,result_folder,result_file):\n\tg_path = '-0001-generatorportresults.csv'\n\ta_path = '-0002-analyzerportresults.csv'\n\tr_path = '-0003-rxstreamsummaryresults.csv'\n\tt_path = '-0004-txstreamresults.csv'\n\t\n\tdata_folder = os.getcwd() + '\\\\' + current_mode\n\tos.chdir(data_folder)\n\n\t#CSV file name creation\n\tcsv_file_name = results_file_name(test_condition)+'.csv'\n\t\n\tgf = open((current_mode + g_path),'rb')\n\taf = open((current_mode + a_path),'rb')\n\trf = open((current_mode + r_path),'rb')\n\ttf = open((current_mode + t_path),'rb')\n\n\tcsv_result = open(csv_file_name,'wb')\n\twriter = csv.writer(csv_result)\n\t\n\t#Creating a Sheet in the Workbook\n\tres_sheet = result_file.get_sheet(0)\n\tres_sheet.row(row_no).write(0,row_no)\n\t\n\tfor i in range(4):\n\t\tres_sheet.row(row_no).write((i+1),test_condition[i])\n \n\t'''\n\t#Updating CSV result with Link Speed\n\twriter.writerows([['ETC Port Link Parameters',],''])\n\twriter.writerows([['PortNo','Firmware Version','Link Speed'],])\n\tfor i in range(5):\n\t\tif bin(int(Link[1][i],16))[-2:] == '10':\n\t\t\twriter.writerows([['GPHY'+str(i),Link[0][i],'1000mb'],])\n\t\telif bin(int(Link[1][i],16))[-2:] == '01':\t\n\t\t\twriter.writerows([['GPHY'+str(i),Link[0][i],'100mb'],])\n\t\telif bin(int(Link[1][i],16))[-2:] == '00':\t\n\t\t\twriter.writerows([['GPHY'+str(i),Link[0][i],'10mb'],])\n '''\n\t#Adding Generator Port Results\n\twriter.writerows(['',['Generator_Results'],''])\n\tgf_reader = csv.reader(gf)\n\tgenerator_crc = list(gf_reader)[-8:]\n\tfor i in range(6):\n\t\tres_sheet.row(row_no).write((i+11),generator_crc[i+2][20])\n\twriter.writerows(generator_crc)\n\n\t#Adding Analyzing Results\n\twriter.writerows(['',['Analyzer_Results'],''])\n\taf_reader = csv.reader(af)\n\twriter.writerows(list(af_reader)[-8:])\n\n\t#Adding RX Stream Results\n\twriter.writerows(['',['RxStream_Results'],''])\n\trf_reader = csv.reader(rf)\n\tdropped_frame_count = list(rf_reader)[-8:]\n\tfor i in range(6):\n\t\tres_sheet.row(row_no).write((i+5),dropped_frame_count[i+2][9])\n\twriter.writerows(dropped_frame_count)\n\n\t#Adding TX Stream Results\n\twriter.writerows(['',['TxStream_Results'],''])\n\ttf_reader = csv.reader(tf)\n\twriter.writerows(list(tf_reader)[-8:])\n\t\n\tcsv_result.close()\n\t\n\t#Transfering the result \n\tdestin_file = '..\\\\'+result_folder+'\\\\'+csv_file_name\n\tshutil.copy(csv_file_name,destin_file)\n\tos.chdir('..//')","sub_path":"Python_Practice/Power_On_Off/source_code/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430717829","text":"# Adapted and modified from:\n# https://stackoverflow.com/questions/51851198/opencv-set-camera-resolution-windows-vrs-linux\n# https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html\n# https://stackoverflow.com/questions/33311153/python-extracting-and-saving-video-frames\n\nimport cv2\nfrom imagePrep import process_image_file\nimport numpy as np\nimport time\n\ninput = 0 # webcam input being used\nvidcap = cv2.VideoCapture(input + cv2.CAP_DSHOW)\nsuccess,image = vidcap.read()\ncount = 0\npathOutFrames = 'C:\\\\Users\\\\Maria Medina\\\\Desktop\\\\Cam_images\\\\' # folder where output frames will be stored\npathOutModFrames = 'C:\\\\Users\\\\Maria Medina\\\\Desktop\\\\Mod_Cam_images\\\\' # folder where output modified frames will be stored\ntimeWait = 0 # time to wait before capturing a new frame\n\nwhile success:\n\n # generic storage location for the output frames\n frame_location = pathOutFrames + \"frame%d.jpg\" % count\n mod_frame_location = pathOutModFrames + \"frame%d.jpg\" % count\n\n #cv2.imwrite(pathOutFrames + \"frame%d.jpg\" % count, image) # save frame as JPEG file\n cv2.imwrite(frame_location, image) # save frame as JPEG file\n\n # Process the frame as it is being read in\n label_class = process_image_file(frame_location)\n\n # writing on an image before saving it\n mod_image = cv2.imread(frame_location, cv2.IMREAD_COLOR)\n height, width, channels = mod_image.shape\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(mod_image, label_class, (0,450), font, 4, (255,255,155), 13, cv2.LINE_AA)\n\n # save a modified version of the image in another folder with text on it\n cv2.imwrite(mod_frame_location, mod_image) # save modified image in it's own folder\n\n # Display the original resulting frame\n cv2.imshow('frame', image)\n\n # Moved above: Process the frame as it is being read in\n # process_image_file(frame_location)\n\n time.sleep(timeWait)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n success,image = vidcap.read()\n print('Read a new frame: ', success)\n count += 1\n\n# When everything done, release the capture\nvidcap.release()\ncv2.destroyAllWindows()","sub_path":"SW/Initial Boil Detection/webCamCapture.py","file_name":"webCamCapture.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"307214365","text":"import os\nimport nstrace\nimport matplotlib.pyplot as plt\nimport random\n\ndef ping_parser(file_name):\n t1 = []\n v1 = []\n\n t2 = []\n v2 = []\n\n f = open(file_name, 'r')\n Lines = f.readlines()\n\n for i in range(len([line for line in Lines]) - 1):\n try:\n lne1 = Lines[i].split()\n lne2 = Lines[i+1].split()\n \n if lne1[0] == \"node\":\n source_node = int(lne1[1])\n time = float(lne2[2])\n ping = float(lne2[8])\n\n if source_node == 0:\n t1.append(time)\n v1.append(ping)\n elif source_node == 1:\n t2.append(time)\n v2.append(ping)\n\n else:\n pass\n except:\n pass\n return t1, v1, t2, v2\n\n\ndef find_index(t, sec):\n for i in range(len(t)):\n if i > sec:\n return i - 1\n return int(i)\n\nfilename = 'main.tcl'\nagents = ['Agent/TCP', 'Agent/TCP/Newreno', 'Agent/TCP/Vegas']\nftr_name = 'ping.txt'\nfnm_name = 'test.nam'\nmany = 5\n\nplt.figure(figsize=(20, 20))\n\nfor agent in agents:\n\n t0s = []\n v0s = []\n t1s = []\n v1s = []\n for i in range(many):\n n23_d = str(int(random.uniform(5, 25))) + 'ms'\n n46_d = str(int(random.uniform(5, 25))) + 'ms'\n\n os.system(f'ns {filename} {agent} {n23_d} {n46_d} {ftr_name} {fnm_name}')\n t0, v0, t1, v1 = ping_parser(ftr_name)\n t0s.append(t0)\n t1s.append(t1)\n v0s.append(v0)\n v1s.append(v1)\n\n T0, V0, T1, V1 = [], [], [], []\n \n max_time = -1\n for i in t0s:\n max_time = max(max_time, int(max(i)))\n \n for sec in range(max_time): \n T0.append(sec)\n v0 = 0\n for times in range(many):\n index = find_index(t0s[times], sec)\n v0 += v0s[times][index]\n V0.append(v0 / many)\n\n for sec in range(max_time): \n T1.append(sec)\n v1 = 0\n for times in range(many):\n index = find_index(t1s[times], sec)\n v1 += v1s[times][index]\n V1.append(v1 / many)\n\n\n plt.plot(T0, V0, label=f'flow0 :: {agent}')\n plt.plot(T1, V1, label=f'flow1 :: {agent}')\n\nplt.title(f'PING(avg on {many} times)')\nplt.grid()\nplt.legend()\nplt.xlabel('time(s)')\nplt.ylabel('avg ping')\nplt.show()\n\n\n# import os\n# import nstrace\n# import matplotlib.pyplot as plt\n# import random\n\n# def only_vars(file_name, v_name):\n# t1 = []\n# v1 = []\n\n# t2 = []\n# v2 = []\n\n# nstrace.nsopen(file_name)\n# while not nstrace.isEOF():\n# if nstrace.isVar():\n# (time, src_node, src_flow, dst_node, dst_flow, var_name, var_value)=\\\n# nstrace.getVar()\n# if v_name == var_name:\n# if src_node == 0:\n# t1.append(time)\n# v1.append(var_value)\n# elif src_node == 1:\n# t2.append(time)\n# v2.append(var_value)\n# else:\n# nstrace.skipline()\n# nstrace.nsclose()\n# return t1, v1, t2, v2\n\n\n# def all_done(ptrs, txs):\n# for i in range(len(ptrs)):\n# if not ptrs[i] == (len(txs[i])-1):\n# return False\n# return True\n\n# def arg_min(txs, ptrs):\n# mn = float('inf')\n# mn_idx = -1\n# for i in range(len(ptrs)):\n# if (txs[i][ptrs[i]] < mn) and (not ptrs[i] == len(txs[i])-1):\n# mn = txs[i][ptrs[i]]\n# mn_idx = i\n# return mn_idx, mn\n\n# def inc(txs, ptrs, mn):\n# for i in range(len(ptrs)):\n# if txs[i][ptrs[i]] == mn:\n# if not ptrs[i]==len(txs[i])-1:\n# ptrs[i] += 1\n\n# def avg(txs, ptrs):\n# sum = 0\n# for i in range(len(ptrs)):\n# if ptrs[i] == 0 or ptrs[i] == len(txs[i])-1:\n# sum += txs[i][ptrs[i]]\n# else:\n# sum += txs[i][ptrs[i]-1]\n# return sum/len(ptrs)\n\n# filename = 'main.tcl'\n# agents = ['Agent/TCP', 'Agent/TCP/Newreno', 'Agent/TCP/Vegas']\n# ftr_name = 'test.tr'\n# fnm_name = 'test.nam'\n# many = 1\n# step = 1\n\n\n# plt.figure(figsize=(20, 20))\n\n# for agent in agents:\n\n# t0s = []\n# v0s = []\n# t1s = []\n# v1s = []\n# for i in range(many):\n# n23_d = str(int(random.uniform(5, 25))) + 'ms'\n# n46_d = str(int(random.uniform(5, 25))) + 'ms'\n\n# os.system(f'ns {filename} {agent} {n23_d} {n46_d} {ftr_name} {fnm_name}')\n# t0, v0, t1, v1 = only_vars(ftr_name, 'rtt_')\n# t0s.append(t0)\n# t1s.append(t1)\n# v0s.append(v0)\n# v1s.append(v1)\n \n# print(t0s, v0s)\n# T0, V0, T1, V1 = [], [], [], []\n# ptrs = [0 for i in range(many)]\n\n# while(not all_done(ptrs, t0s)):\n# mn_idx , mn = arg_min(t0s, ptrs)\n# T0.append(mn)\n# V0.append(avg(v0s, ptrs))\n# inc(t0s, ptrs, mn)\n\n# ptrs = [0 for i in range(many)]\n\n# while(not all_done(ptrs, t1s)):\n# mn_idx , mn = arg_min(t1s, ptrs)\n# T1.append(mn)\n# V1.append(avg(v1s, ptrs))\n# inc(t1s, ptrs, mn)\n\n# plt.plot(T0[::step], V0[::step], label=f'flow0 :: {agent}')\n# plt.plot(T1[::step], V1[::step], label=f'flow1 :: {agent}')\n\n# plt.title(f'RTT(avg on {many} times)')\n# plt.grid()\n# plt.legend()\n# plt.xlabel('time(s)')\n# plt.ylabel('avg rtt_')\n# plt.show()","sub_path":"codes/ping_graph.py","file_name":"ping_graph.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"7531072","text":"# 02.5\n# Armazenando frase\nmessage1 = 'Albert Einstein certa vez disse: “Uma pessoa que nunca c' \\\n 'ometeu um erro jamais tentou nada novo.”'\nprint(message1)\n\n# 02.6\nfamous_person = \"Albert Einstein\"\nmessage2 = famous_person +\" certa vez disse: “Uma pessoa que nunca cometeu \" \\\n \"um erro jamais tentou nada novo.”\"\nprint(message2)","sub_path":"Chapter 02/02.5 e 02.6 - Citação famosa.py","file_name":"02.5 e 02.6 - Citação famosa.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"384556492","text":"from gst.equality_check import equality_check_using\n\n\"\"\" This is a utility module for getting matches from text and pattern \"\"\"\n\n\ndef get_matches(p, t, p_mask, t_mask, pattern, text):\n\n \"\"\" Args:\n p -> current pattern index\n t -> current text index\n p_mask -> pattern mask array\n t_mask -> text mask array\n pattern -> the pattern array\n text -> the text\n\n returns:\n j -> an integer representing match length\n\n This function takes p and t, which are the current positions in the\n pattern and text arrays. j is a slider which increments if the current\n elements match, and is returned when match ends. This (j) is how match\n length is tracked.\n \"\"\"\n\n j = 0\n while p + j < len(pattern) and t + j < len(text) and equality_check_using(\n pattern[p + j],\n text[t + j]) and p_mask[p + j] is False and t_mask[t + j] is False:\n\n j += 1\n\n return j\n","sub_path":"gst/get_matches.py","file_name":"get_matches.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"49649291","text":"from flask_restx import Namespace, fields, reqparse\r\nfrom ..helpers.markdown import md\r\nfrom ..helpers.apimodel import data_response, error_response, default_error\r\n# -------------------------------------------------\r\n\r\n# - API Namespace ---------------------------------\r\nns = Namespace('Accounts', description=md(\"docs/sessions\"))\r\n# -------------------------------------------------\r\n\r\n\r\nsession_field = ns.model(\"Session\",\r\n{\r\n \"id\": fields.String(description=\"Session id.\"),\r\n \"token\": fields.String(description=\"JWT session token.\"),\r\n \"blacklisted\":fields.DateTime(description=\"Invalidation date.\"),\r\n \"created\": fields.DateTime(description=\"Token creation date.\"),\r\n \"expires\": fields.DateTime(description=\"Token expiring date.\"),\r\n \"platform\": fields.String(description=\"Operative system.\"),\r\n \"device\": fields.String(description=\"Application or browser sending request.\"),\r\n \"version\": fields.String(description=\"Application version.\"),\r\n \"language\": fields.String(description=\"Current device language.\"),\r\n \"address\": fields.String(description=\"Source IP address.\")\r\n})\r\n\r\nsession_params = reqparse.RequestParser()\r\nsession_params.add_argument('tokens', location=\"query\", type=bool , help=\"Set to true if you **need** to have tokens for all sessions.\")\r\n\r\nlogin_parser = reqparse.RequestParser()\r\nlogin_parser.add_argument('email', location=\"form\", required=True, help=\"The email of a valid registered user.\")\r\nlogin_parser.add_argument('password', location=\"form\", required=True, help=\"The password associated to the specified user.\")\r\nlogin_parser.add_argument('confirmation', location=\"form\", required=False, help=\"Token sent to the mail, **required** if first login.\")\r\n\r\n\r\n# - Default response layout -----------------------\r\nerror_message = ns.model('Error', default_error())\r\nerror_response = ns.model('Error response', error_response(error_message))\r\nsessions_response = ns.model('Sessions', data_response(session_field))\r\nlogin_response = ns.model('Token',\r\n{\r\n 'jwt': fields.String(description=\"The access token for all user apis\")\r\n})\r\n# -------------------------------------------------\r\n\r\n# - Modules\r\nfrom .sessions import Sessions\r\n","sub_path":"server/rest/session/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"361212729","text":"#!python3\r\nimport pyperclip\r\nimport time\r\nimport ctypes\r\nimport sympy\r\n\r\nctypes.windll.kernel32.SetConsoleTitleA(b\"Copypaste calculator\")\r\n\r\nmathproof = [\"+\", \"-\", \"*\", \"/\", \"=\"]\r\nparsedict = {\"×\": \"*\",\r\n \"÷\": \"/\",\r\n \"^\": \"**\"}\r\n\r\ndef stringparse(string):\r\n string = string.replace(\" \", \"\")\r\n for i in string:\r\n if i in parsedict.keys():\r\n string = string.replace(i, parsedict[i])\r\n print(string)\r\n return string\r\n\r\ndef solver(string_exp):\r\n #string_exp = stringparse(string_exp)\r\n x = sympy.Symbol('x')\r\n y = sympy.S(string_exp)\r\n y = sympy.simplify(y)\r\n print(y)\r\n z = sympy.solve(y)\r\n if len(z) > 1:\r\n z = [str(i) for i in z]\r\n pyperclip.copy(\", \".join([str(i) for i in z]))\r\n return \"Possible solutions: x={0} or {1} when y=0.\".format(\", \".join(z[0:-1]), z[-1])\r\n else:\r\n pyperclip.copy(str(z[0]))\r\n return \"Solution: x is {0}.\".format(z[0])\r\n\r\ndef init():\r\n current = pyperclip.paste()\r\n new = current\r\n main(current, new)\r\n\r\ndef main(current, new):\r\n print(\"Calculate the answer of a copied symbolic expression, \\nand paste it on the clipboard.\")\r\n while True:\r\n new = pyperclip.paste()\r\n if new != current:\r\n print(solver(new))\r\n pass\r\n else:\r\n time.sleep(1.0)\r\n pass\r\n current = new\r\n\r\nif __name__ == \"__main__\":\r\n init()","sub_path":"PyCalc.py","file_name":"PyCalc.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"550278221","text":"s = 'aba'\nn = int(input(f'Number of times to repeat {s}: '))\n\n''' my original function\n s *= n\n new_s = s[:n + 1]\n a = new_s.count('a')\n return a\n'''\n\n# calculation to avoid memory error | got this on hackerrank discussions\n\ndef repeatedString(n, s):\n a = s.count('a')\n num = n // len(s) # integer division of the number of times the string should be repeated by the length of the string\n mod = n % len(s) # division rest of the number of times the string should be repeated by the length of the string\n count = a * num + s[:mod].count('a')\n return count \n\nprint(repeatedString(n, s))","sub_path":"Python/hacker-rank/repeated-strings.py","file_name":"repeated-strings.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"468598444","text":"from django.conf import settings\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import gettext_lazy as _, gettext\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\nfrom business_register.filters import FopFilterSet\nfrom business_register.models.fop_models import Fop\nfrom business_register.serializers.fop_serializers import FopSerializer\nfrom data_converter.pagination import CachedCountPagination\nfrom data_ocean.filters import FullWordSearchFilter\nfrom data_ocean.permissions import IsAuthenticatedAndPaidSubscription\nfrom data_ocean.tasks import export_to_s3\nfrom data_ocean.views import CachedViewSetMixin, RegisterViewMixin\n\n\n@method_decorator(name='retrieve', decorator=swagger_auto_schema(tags=['business register']))\n@method_decorator(name='list', decorator=swagger_auto_schema(tags=['business register']))\nclass FopViewSet(RegisterViewMixin,\n CachedViewSetMixin,\n viewsets.ReadOnlyModelViewSet):\n pagination_class = CachedCountPagination\n queryset = Fop.objects.select_related(\n 'status', 'authority'\n ).prefetch_related(\n 'kveds', 'exchange_data'\n ).all()\n filter_backends = (DjangoFilterBackend, FullWordSearchFilter)\n serializer_class = FopSerializer\n filterset_class = FopFilterSet\n search_fields = ('fullname', 'address', 'status__name')\n\n @action(detail=False, url_path='xlsx', schema=None, permission_classes=[IsAuthenticatedAndPaidSubscription])\n def export_to_xlsx(self, request):\n queryset = self.filter_queryset(self.get_queryset())\n if queryset.count() > settings.FOP_TO_XLSX_LIMIT:\n return Response(\n {\"detail\": _(\"Too many results for export in .xlsx. Try reduce filter conditions.\")},\n status=416\n )\n export_dict = {\n 'ID': ['id', 9],\n gettext('Full Name'): ['fullname', 30],\n gettext('Status'): ['status', 14],\n gettext('Address'): ['address', 33],\n gettext('Registration Date'): ['registration_date', 18],\n gettext('Termination Date'): ['termination_date', 18],\n gettext('Created Date'): ['created_at', 19],\n gettext('Updated Date'): ['updated_at', 19],\n gettext('Authority'): ['authority', 36]\n }\n export_to_s3.delay(\n request.GET,\n export_dict,\n 'business_register.Fop',\n 'business_register.filters.FopFilterSet',\n 'business_register.views.fop_views.FopViewSet',\n request.user.id)\n return Response(\n {\"detail\": _(\"Generation of .xlsx file has begin. Expect an email with downloading link.\")},\n status=200\n )\n","sub_path":"business_register/views/fop_views.py","file_name":"fop_views.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"619650027","text":"#!/usr/bin/python\n\nimport csv\nimport codecs\nimport sys\n\ndef unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):\n csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)\n for row in csv_reader:\n yield [unicode(cell, 'utf-8') for cell in row]\n\nif __name__ == '__main__':\n authors_got_file_name = 'authors_got.csv'\n individuals_file_name = 'individuals.csv'\n missing_file_name = 'missing.csv'\n\n try:\n individuals_reader = unicode_csv_reader(open(individuals_file_name))\n except:\n sys.exit('Erro ao abrir o arquivo '+individuals_file_name)\n try:\n authors_got_reader = unicode_csv_reader(open(authors_got_file_name))\n except:\n sys.exit('Erro ao abrir o arquivo '+authors_got_file_name)\n\n individuals_list = []\n for row in individuals_reader:\n individuals_list.append(row[0])\n\n authors_got_list = []\n for row in authors_got_reader:\n authors_got_list.append(row[0].lower().replace(' ','').replace('.',''))\n\n missing_list = [] \n for author in individuals_list:\n if not author.lower().replace(' ','').replace('.','') in authors_got_list:\n with open(missing_file_name, 'a') as missing_file:\n missing_file.write('\"'+author.encode('utf-8')+'\"\\n')","sub_path":"dac/authors/missing.py","file_name":"missing.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"62324690","text":"from bilmo.scripts.config import Config\nimport logging\nimport pickle\nimport numpy as np\nimport pandas as pd\nconf = Config.conf\nlog = logging.getLogger(\"cafa-logger\")\n\ndef prepare_training_binary(df):\n selected_class = conf['binary']['selected_class']\n def find_go(row):\n if selected_class in row.go:\n res = selected_class\n else:\n res = 'others'\n return res\n df['selected_class'] = df.apply(find_go, axis=1)\n available_T = (df['selected_class'] == selected_class).sum()\n available_F = len(df) - available_T\n log.debug('number of rows that has ' + selected_class + 'is: ' + str(available_T))\n\n df_F = df[df['selected_class'] == 'others']\n df_T = df[df['selected_class'] == selected_class]\n\n valid_len_T = int(available_T * conf['valid_split_percentage'])\n train_len_T = available_T - valid_len_T\n train_len_F = train_len_T\n valid_len_F = available_F - train_len_F\n log.debug('train_len_T ' + str(train_len_T) + ' train_len_F ' + str(train_len_F) + ' valid_len_T ' +\n str(valid_len_T) + ' valid_len_F ' + str(valid_len_F))\n idx_T = np.random.permutation(range(available_T))\n idx_F = np.random.permutation(range(available_F))\n\n train_T = df_T.iloc[idx_T][:train_len_T]\n valid_T = df_T.iloc[idx_T][train_len_T:]\n\n train_F = df_F.iloc[idx_F][:train_len_F]\n valid_F = df_F.iloc[idx_F][train_len_F:]\n\n df_train = pd.concat([train_T, train_F])\n df_valid = pd.concat([valid_T, valid_F])\n return df_train, df_valid\n\n\n\ndef prepare_training_multiclass(df):\n pass\n # old code, should be updated!! we also need df_valid\n selected_classes = conf['multiclass']['selected_classes']\n selected_class = selected_classes[0]\n selected_class2 = selected_classes[1]\n def find_go(row, go_id=selected_class):\n if go_id in row.go:\n res = 'is_' + selected_class\n else:\n res = 'not_' + selected_class\n return res\n df['selected_class'] = df.apply(find_go, axis=1, go_id=selected_class)\n df['selected_class2'] = df.apply(find_go, axis=1, go_id=selected_class2)\n available_T1 = (df['selected_class'] == 'is_' + selected_class).sum()\n available_T2 = (df['selected_class2'] == 'is_' + selected_class2).sum()\n\n log.debug('number of rows that has ' + selected_class + 'is: ' + str(available_T1))\n log.debug('number of rows that has ' + selected_class + 'is: ' + str(available_T2))\n\n df_undersampled_1 = df[df['selected_class'] == 'is_' + selected_class &\n df['selected_class2'] == 'not_' + selected_class2].copy()\n df_undersampled_2 = df[df['selected_class_2'] == 'is_' +\n selected_class2 & df['selected_class'] == 'not_' + selected_class].copy()\n df_undersampled = pd.concat(\n [df_undersampled_1, df_undersampled_2])\n log.debug('len of undersampled train_df ' + str(len(df_undersampled)))\n return df_undersampled\n\ndef prepare_training_multilabel(df):\n df[conf['class_col_name']] = df.apply(lambda r: \" \".join(r.go), axis=1)\n df = df.iloc[np.random.permutation(len(df))]\n cut = int(conf['valid_split_percentage'] * len(df)) + 1\n train_df, valid_df = df[cut:], df[:cut]\n return train_df, valid_df\n\n\ndef prepare_training_df(df):\n df = df.dropna(subset=[conf['sequence_col_name']]).copy()\n log.info('total number of training rows after removing NaN ' + str(len(df)))\n if conf['classificiation_type'] == 'binary':\n return prepare_training_binary(df)\n elif conf['classificiation_type'] == 'multiclass':\n return prepare_training_multiclass(df)\n elif conf['classificiation_type'] == 'multilabel':\n return prepare_training_multilabel(df)\n else:\n raise BaseException(\"classificiation_type not exist\")\n\n\ndef load_data_train():\n if conf['training_dataframe_path'] == None:\n raise BaseException(\"training_dataframe_path not set in config file\")\n df = pickle.load(open(conf['training_dataframe_path'], 'rb'))\n log.debug(df.columns)\n log.info('total number of training rows ' + str(len(df)))\n df_train, df_valid = prepare_training_df(df)\n if conf['smaller_train_df'] is not None:\n df_train, df_valid = df_train[:conf[\n 'smaller_train_df']], df_valid[:conf['smaller_train_df']]\n return df_train, df_valid\n\ndef load_data_test():\n if not conf['test_on_cafa3_testset']:\n return None\n df_test = pd.read_csv(conf['data_path'] +\n 'cafa3/targets.csv')\n\n # Important Note:\n # because the number of targets are 130K and it takes a long time to predict\n # for all of them, we just create the prediction for the proteins that are\n # expected to be assessed. This should be ok for the protein centeric evaluation\n # but I guess it's not ok to do this for the term centeric evaluation\n\n if conf['predict_only_final_targets']:\n df_targets_final_BPO = pd.read_csv(\n conf['data_path'] +\n 'cafa3/CAFA 3 Benchmarks/benchmark20171115/groundtruth/leafonly_BPO.txt',\n sep='\\t',\n names=['uniq_id', 'go_id'],\n header=None)\n\n df_targets_final_CCO = pd.read_csv(\n conf['data_path'] +\n 'cafa3/CAFA 3 Benchmarks/benchmark20171115/groundtruth/leafonly_CCO.txt',\n sep='\\t',\n names=['uniq_id', 'go_id'],\n header=None)\n\n df_targets_final_MFO = pd.read_csv(\n conf['data_path'] +\n 'cafa3/CAFA 3 Benchmarks/benchmark20171115/groundtruth/leafonly_MFO.txt',\n sep='\\t',\n names=['uniq_id', 'go_id'],\n header=None)\n\n df_targets_final = pd.concat(\n [df_targets_final_BPO, df_targets_final_CCO, df_targets_final_MFO])\n\n df_test = df_test.loc[df_test['uniq_id'].isin(\n df_targets_final.uniq_id.unique())]\n\n\n return df_test\n","sub_path":"bilmo/dataset/prepare_datasets_dataframe.py","file_name":"prepare_datasets_dataframe.py","file_ext":"py","file_size_in_byte":5896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"348504021","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom models import Config, Model\nimport math\n\nXAVIER_INIT = tf.contrib.layers.xavier_initializer\n\n\nclass RecurrentCNNConfig(Config):\n\n\tdef __init__(self):\n\t\tself.batch_size = 64\n\t\tself.lr = 1e-3\n\t\tself.l2_lambda = 0.0000001\n\t\tself.hidden_size = 512\n\t\tself.num_epochs = 50\n\t\tself.num_layers = 3\n\t\tself.num_classes = 4 # Mean vector of size 4\n\t\tself.features_shape = (100,100,3) #TO FIX!!!!\n\t\tself.targets_shape = (4,)\n\t\tself.init_loc_size = (4,)\n\t\tself.max_norm = 10\n\t\tself.keep_prob = 0.8\n\t\tself.init_state_out_size = 128\n\t\tself.cnn_out_shape = 128\n\t\tself.variance = 1e-1\n\t\tself.num_samples = 5\n\n\nclass RecurrentCNN(Model):\n\n\tdef __init__(self, features_shape, num_classes, cell_type='lstm', seq_len=8, reuse=False, add_bn=False,\n\t\t\t\tadd_reg=False, deeper = False, loss_type = 'negative_l1_dist', cum_sum=False, scope='RCNN'):\n\t\tself.config = RecurrentCNNConfig()\n\t\tself.config.features_shape = features_shape\n\t\tself.config.num_classes = num_classes\n\t\tself.reuse = reuse\n\t\tself.inputs_placeholder = tf.placeholder(tf.float32, shape=tuple((None,None,)+ self.config.features_shape ))\n\t\tself.init_loc = tf.placeholder(tf.float32, shape=tuple((None,)+ self.config.init_loc_size))\n\t\tself.targets_placeholder = tf.placeholder(tf.float32, shape=tuple((None,None,) + self.config.targets_shape))\n\t\tself.config.seq_len = seq_len\n\t\tself.seq_len_placeholder = tf.placeholder(tf.int32, shape=tuple((None,) ))\n\t\tself.deeper = deeper\n\t\tself.loss_type = loss_type\n\t\tself.cumsum = cum_sum\n\n\t\tself.scope = scope\n\t\tif add_bn:\n\t\t\tself.norm_fn = tf.contrib.layers.batch_norm\n\t\telse:\n\t\t\tself.norm_fn = None\n\n\t\tif add_reg:\n\t\t\tself.reg_fn = tf.nn.l2_loss\n\t\telse:\n\t\t\tself.reg_fn = None\n\n\t\tif cell_type == 'rnn':\n\t\t\tself.cell = tf.contrib.rnn.RNNCell\n\t\telif cell_type == 'gru':\n\t\t\tself.cell = tf.contrib.rnn.GRUCell\n\t\telif cell_type == 'lstm':\n\t\t\tself.cell = tf.contrib.rnn.LSTMCell\n\t\telse:\n\t\t\traise ValueError('Input correct cell type')\n\n\tdef conv_layer(self, inputs, outputs, kernel_size, stride, reuse, scope):\n\t\treturn tf.contrib.layers.conv2d(inputs=inputs, num_outputs=outputs, kernel_size=kernel_size,\n\t\t\t\t\t\t\t\tstride=stride,padding='SAME',rate=1,activation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\treuse = reuse, scope=scope, trainable=True)\n\n\n\tdef build_cnn(self, cur_inputs, reuse=False, scope=None):\n\t\twith tf.variable_scope(scope):\n\t\t\tconv_out1 = self.conv_layer(cur_inputs, 32, [3,3], [1,1], reuse, 'conv1')\n\t\t\tconv_out2 = self.conv_layer(conv_out1, 32, [3,3], [1,1], reuse, 'conv2')\n\n\t\t\tmax_pool1 = tf.contrib.layers.max_pool2d(inputs=conv_out2, kernel_size=[3,3],stride=[2,2],\n\t\t\t\t\t\t\t\tscope='maxpool1', padding='SAME')\n\t\t\tconv_out3 = self.conv_layer(max_pool1, 32, [3,3], [1,1], reuse, 'conv3')\n\t\t\tconv_out4 = self.conv_layer(conv_out3, 32, [3,3], [1,1], reuse, 'conv4')\n\n\t\t\tmax_pool2 = tf.contrib.layers.max_pool2d(inputs=conv_out4, kernel_size=[3,3],stride=[2,2],\n\t\t\t\t\t\t\t\t\t\tscope='maxpool1',padding='SAME')\n\t\t\tflatten_out = tf.contrib.layers.flatten(max_pool2,scope='flatten')\n\n\t\t\tfc1 = tf.contrib.layers.fully_connected(inputs=flatten_out, num_outputs=self.config.cnn_out_shape,activation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse,scope='fc1',trainable=True)\n\t\t\tfc2 = tf.contrib.layers.fully_connected(inputs=fc1, num_outputs=self.config.cnn_out_shape,activation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse,scope='fc2',trainable=True)\n\n\t\tcnn_out = fc2\n\t\treturn cnn_out\n\n\tdef build_deeper_cnn(self, cur_inputs, reuse=False, scope=None):\n\t\twith tf.variable_scope(scope):\n\t\t\tconv_out1 = self.conv_layer(cur_inputs, 32, [3,3], [1,1], reuse, 'conv1')\n\t\t\tconv_out2 = self.conv_layer(conv_out1, 32, [3,3], [1,1], reuse, 'conv2')\n\n\t\t\tmax_pool1 = tf.contrib.layers.max_pool2d(inputs=conv_out2, kernel_size=[3,3],stride=[1,1],\n\t\t\t\t\t\t\t\tscope='maxpool1', padding='SAME')\n\t\t\tconv_out3 = self.conv_layer(max_pool1, 32, [3,3], [1,1], reuse, 'conv3')\n\t\t\tconv_out4 = self.conv_layer(conv_out3, 32, [3,3], [1,1], reuse, 'conv4')\n\n\t\t\tmax_pool2 = tf.contrib.layers.max_pool2d(inputs=conv_out4, kernel_size=[3,3],stride=[2,2],\n\t\t\t\t\t\t\t\t\t\tscope='maxpool2',padding='SAME')\n\n\t\t\tconv_out5 = self.conv_layer(max_pool2, 32, [3,3], [1,1], reuse, 'conv5')\n\t\t\tconv_out6 = self.conv_layer(conv_out5, 32, [3,3], [1,1], reuse, 'conv6')\n\n\t\t\tmax_pool3 = tf.contrib.layers.max_pool2d(inputs=conv_out6, kernel_size=[3,3],stride=[1,1],\n\t\t\t\t\t\t\t\t\t\tscope='maxpool3',padding='SAME')\n\n\t\t\tconv_out7 = self.conv_layer(max_pool3, 32, [3,3], [1,1], reuse, 'conv7')\n\t\t\tconv_out8 = self.conv_layer(conv_out7, 32, [3,3], [1,1], reuse, 'conv8')\n\n\t\t\tmax_pool4 = tf.contrib.layers.max_pool2d(inputs=conv_out8, kernel_size=[3,3],stride=[2,2],\n\t\t\t\t\t\t\t\t\t\tscope='maxpool4',padding='SAME')\n\n\t\t\tflatten_out = tf.contrib.layers.flatten(max_pool4,scope='flatten')\n\n\t\t\tfc1 = tf.contrib.layers.fully_connected(inputs=flatten_out, num_outputs=self.config.cnn_out_shape,activation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse,scope='fc1',trainable=True)\n\t\t\tfc2 = tf.contrib.layers.fully_connected(inputs=fc1, num_outputs=self.config.cnn_out_shape,activation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse,scope='fc2',trainable=True)\n\n\t\tcnn_out = fc2\n\t\treturn cnn_out\n\n\tdef build_rnn(self, rnn_inputs):\n\t\tW = tf.get_variable(\"Weights\", shape=[self.config.hidden_size, self.config.num_classes],\n\t\t\t\t\t\t\tinitializer=XAVIER_INIT(uniform=True))\n\t\tb = tf.get_variable(\"Bias\", shape=[self.config.num_classes])\n\n\t\trnnNet = tf.contrib.rnn.MultiRNNCell([self.cell(num_units = self.config.hidden_size) for _ in\n\t\t\t\t\t\t\t\t\trange(self.config.num_layers)], state_is_tuple=True)\n\t\t(rnnNet_out, rnnNet_state) = tf.nn.dynamic_rnn(cell = rnnNet, inputs=rnn_inputs,\n\t\t sequence_length=self.seq_len_placeholder,dtype=tf.float32)\n\n\t\tcur_shape = tf.shape(rnnNet_out)\n\t\trnnOut_2d = tf.reshape(rnnNet_out, [-1, cur_shape[2]])\n\n\t\tlogits_2d = tf.matmul(rnnOut_2d, W) + b\n\t\trnn_out = tf.reshape(logits_2d,[cur_shape[0], cur_shape[1], self.config.num_classes])\n\n\t\treturn rnn_out\n\n\tdef build_initial_state(self, loc_inputs, reuse=False, scope=None):\n\t\twith tf.variable_scope(scope):\n\t\t\tfc1 = tf.contrib.layers.fully_connected(inputs=loc_inputs, num_outputs=self.config.init_state_out_size,\n\t\t\t\t\t\t\t\t\tactivation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse, scope='fc1', trainable=True)\n\n\t\t\tfc2 = tf.contrib.layers.fully_connected(inputs=fc1, num_outputs=self.config.init_state_out_size,\n\t\t\t\t\t\t\t\t\tactivation_fn=tf.nn.relu,\n\t\t\t\t\t\t\t\t\tnormalizer_fn=self.norm_fn,\tweights_initializer=XAVIER_INIT(uniform=True) ,\n\t\t\t\t\t\t\t\t\tweights_regularizer=self.reg_fn , biases_regularizer=self.reg_fn ,\n\t\t\t\t\t\t\t\t\treuse = reuse,scope='fc2',trainable=True)\n\n\n\n\t\tinit_state_out = fc2\n\t\treturn init_state_out\n\n\n\n\tdef build_model(self):\n\t\tself.cnn_scope = 'CNN'\n\t\tself.fc_scope = 'FC'\n\t\tself.rnn_scope = 'RNN'\n\n\t\tobs_outputs = []\n\t\treuse = False\n\t\twith tf.variable_scope(self.scope):\n\t\t\tfor t in xrange(self.config.seq_len):\n\t\t\t\tprint(\"Current iteration: {0}\".format(t))\n\t\t\t\tx = tf.placeholder(tf.float32, shape=[None, self.config.init_state_out_size])\n\t\t\t\tst_state = tf.zeros_like(x)\n\t\t\t\tif t == 0:\n\t\t\t\t\treuse = False\n\t\t\t\t\tst_state = self.build_initial_state(tf.zeros_like(self.init_loc), reuse, self.fc_scope)\n\t\t\t\tif t > 0:\n\t\t\t\t\t# tf.get_variable_scope().reuse_variables()\n\t\t\t\t\treuse = True\n\t\t\t\t\tst_state = self.build_initial_state(tf.zeros_like(self.init_loc), reuse, self.fc_scope)\n\n\t\t\t\tif not self.deeper:\n\t\t\t\t\tconcat_result = tf.concat([self.build_cnn(self.inputs_placeholder[:,t,:,:,:], reuse, self.cnn_scope),st_state],\n\t\t\t\t\t\t\t\t\t\t\t axis=1)\n\t\t\t\t\tobs_outputs.append(concat_result)\n\t\t\t\telse:\n\t\t\t\t\tconcat_result = tf.concat([self.build_deeper_cnn(self.inputs_placeholder[:,t,:,:,:], reuse, self.cnn_scope),st_state],\n\t\t\t\t\t\t\t\t\t\t\t axis=1)\n\t\t\t\t\tobs_outputs.append(concat_result)\n\n\t\t\tobs_outputs = tf.stack(obs_outputs, axis=1)\n\n\t\t\trnn_output = None\n\t\t\twith tf.variable_scope(self.rnn_scope):\n\t\t\t\trnn_output = self.build_rnn(obs_outputs)\n\n\t\t\tself.logits = tf.nn.sigmoid(rnn_output)\n\t\t# self.logits = rnn_output\n\n\n\tdef get_iou_loss(self):\n\t\tp_left = self.location_samples[:, :, :, 1]\n\t\tg_left = self.targets_placeholder[:, :, 1]\n\t\tleft = tf.maximum(p_left, g_left)\n\t\tp_right = self.location_samples[:, :, :, 1] + self.location_samples[:, :, :, 3]\n\t\tg_right = self.targets_placeholder[:, :, 1] + self.targets_placeholder[:, :, 3]\n\t\tright = tf.minimum(p_right, g_right)\n\t\tp_top = self.location_samples[:, :, :, 0]\n\t\tg_top = self.targets_placeholder[:, :, 0]\n\t\ttop = tf.maximum(p_top, g_top)\n\t\tp_bottom = self.location_samples[:, :, :, 0] + self.location_samples[:, :, :, 2]\n\t\tg_bottom = self.targets_placeholder[:, :, 0] + self.targets_placeholder[:, :, 2]\n\t\tbottom = tf.minimum(p_bottom, g_bottom)\n\t\tintersection = tf.maximum((right - left), 0) * tf.maximum((bottom - top), 0)\n\t\tp_area = self.location_samples[:, :, :, 3] * self.location_samples[:, :, :, 2]\n\t\tg_area = self.targets_placeholder[:, :, 3] * self.targets_placeholder[:, :, 2]\n\t\tunion = p_area + g_area - intersection\n\n\t\treturn intersection/union\n\n\n\tdef add_loss_op(self, loss_type='negative_l1_dist'):\n\t\tself.loss_type = loss_type\n\t\tlogits_shape = tf.shape(self.logits)\n\t\tlogits_flat = tf.reshape(self.logits, [-1])\n\t\tlocation_dist = tf.contrib.distributions.MultivariateNormalDiag(mu=logits_flat,\n\t\t\t\t\t\t\t\t\tdiag_stdev=self.config.variance*tf.ones_like(logits_flat))\n\t\tlocation_samples = location_dist.sample([self.config.num_samples])\n\n\t\tnew_logits_shape = tf.concat([[self.config.num_samples,] , logits_shape], axis=0)\n\t\tlocation_samples = tf.reshape(location_samples, new_logits_shape)\n\t\tself.location_samples = location_samples\n\n\t\tif self.loss_type == 'negative_l1_dist':\n\t\t\trewards = -tf.reduce_mean(tf.abs(location_samples - tf.cast(self.targets_placeholder,tf.float32)),axis=3,keep_dims=True) - \\\n\t\t\t\t\ttf.reduce_max(tf.abs(location_samples - tf.cast(self.targets_placeholder,tf.float32)), axis=3,keep_dims=True)\n\t\telif self.loss_type == 'iou':\n\t\t\trewards = self.get_iou_loss()\n\t\t\trewards = tf.expand_dims(rewards,axis=-1)\n\n\t\ttimestep_rewards = tf.reduce_mean(rewards, axis=0, keep_dims=True)\n\t\tself.timestep_rewards = timestep_rewards\n\n\t\tif self.cumsum:\n\t\t\ttot_cum_rewards = tf.cumsum(rewards, axis=2, reverse=True)\n\t\telse:\n\t\t\ttot_cum_rewards = tf.tile(tf.reduce_sum(rewards, axis=2, keep_dims = True),multiples=[1,1,self.config.seq_len, 1])\n\n\t\tself.tot_cum_rewards = tot_cum_rewards\n\n\t\ttimestep_rewards_grad_op = tf.stop_gradient(timestep_rewards)\n\t\trewards_grad_op = tf.stop_gradient(rewards)\n\t\tlocation_samples_op = tf.stop_gradient(location_samples)\n\t\ttot_cum_rewards_op = tf.stop_gradient(tot_cum_rewards)\n\n\n\t\tconst1 = 1.0 / (np.sqrt(2.0 * math.pi) * self.config.variance)\n\t\tconst2 = 2.0 * self.config.variance**2\n\t\tsquared_diff = tf.square(self.targets_placeholder - self.logits)\n\n\t\tdensity_func = tf.log(const1 * tf.exp(-squared_diff / const2))\n\t\tself.density_func = density_func\n\n\t\tself.loss = tf.reduce_mean(tf.reduce_sum(density_func*(tot_cum_rewards_op - timestep_rewards_grad_op), axis=2),\n\t\t\t\t\t\t\t\t\t\t\taxis=[1, 0])\n\t\tself.total_rewards = tf.reduce_mean(tf.reduce_sum(timestep_rewards, axis=2), axis=1)\n\t\ttf.summary.scalar('Total Rewards', self.total_rewards[0][0])\n\n\n\tdef add_optimizer_op(self):\n\t\ttvars = tf.trainable_variables()\n\t\tgrads = tf.gradients(self.loss, tvars)\n\t\toptimizer = tf.train.AdamOptimizer(self.config.lr)\n\t\tself.train_op = optimizer.apply_gradients(zip(grads, tvars))\n\n\n\n\tdef add_error_op(self):\n\t\t# VOT metrics (MOT only makes sense for multiple object)\n \t\t# Accuracy:\n\t\t# intersection / union\n \t\t# Robustness\n \t\t# average count of number of resets (0 overlap in predicted and actual)\n\n\t\t# y, x, height, width\n\t\t# left = x\n\t\t# right = x + width\n\t\t# top = y\n\t\t# bottom = y + height\n\n\t\t# IoU Metric calculation\n\t\tp_left = self.logits[:, :, 1]\n\t\tg_left = self.targets_placeholder[:, :, 1]\n\t\tleft = tf.maximum(p_left, g_left)\n\t\tself.left = left\n\n\t\tp_right = self.logits[:, :, 1] + self.logits[:, :, 3]\n\t\tg_right = self.targets_placeholder[:, :, 1] + self.targets_placeholder[:, :, 3]\n\t\tright = tf.minimum(p_right, g_right)\n\t\tself.right = right\n\n\t\tp_top = self.logits[:, :, 0]\n\t\tg_top = self.targets_placeholder[:, :, 0]\n\t\ttop = tf.maximum(p_top, g_top)\n\t\tself.top = top\n\n\t\tp_bottom = self.logits[:, :, 0] + self.logits[:, :, 2]\n\t\tg_bottom = self.targets_placeholder[:, :, 0] + self.targets_placeholder[:, :, 2]\n\t\tbottom = tf.minimum(p_bottom, g_bottom)\n\t\tself.bottom = bottom\n\n\t\tintersection = tf.maximum((right - left), 0) * tf.maximum((bottom - top), 0)\n\t\tself.intersection = intersection\n\t\tp_area = self.logits[:, :, 3] * self.logits[:, :, 2]\n\t\tg_area = self.targets_placeholder[:, :, 3] * self.targets_placeholder[:, :, 2]\n\t\tunion = p_area + g_area - intersection\n\t\tself.union = union\n\n\t\tself.area_accuracy = tf.reduce_mean(intersection / union)\n\t\ttf.summary.scalar('IOU Area Accuracy', self.area_accuracy)\n\n\t\t# Bounding box summaries\n\t\tp_seq_image_bboxes = []\n\t\tg_seq_image_bboxes = []\n\t\tfor i in xrange(self.config.seq_len):\n\t\t\tp_left_i = self.logits[:, i, 1]\n\t\t\tg_left_i = self.targets_placeholder[:, i, 1]\n\t\t\tp_right_i = self.logits[:, i, 1] + self.logits[:, i, 3]\n\t\t\tg_right_i = self.targets_placeholder[:, i, 1] + self.targets_placeholder[:, i, 3]\n\t\t\tp_top_i = self.logits[:, i, 0]\n\t\t\tg_top_i = self.targets_placeholder[:, i, 0]\n\t\t\tp_bottom_i = self.logits[:, i, 0] + self.logits[:, i, 2]\n\t\t\tg_bottom_i = self.targets_placeholder[:, i, 0] + self.targets_placeholder[:, i, 2]\n\n\t\t\tp_top_i = tf.expand_dims(p_top_i, axis=-1)\n\t\t\tp_left_i = tf.expand_dims(p_left_i, axis=-1)\n\t\t\tp_bottom_i = tf.expand_dims(p_bottom_i, axis=-1)\n\t\t\tp_right_i = tf.expand_dims(p_right_i, axis=-1)\n\n\t\t\tg_top_i = tf.expand_dims(g_top_i, axis=-1)\n\t\t\tg_left_i = tf.expand_dims(g_left_i, axis=-1)\n\t\t\tg_bottom_i = tf.expand_dims(g_bottom_i, axis=-1)\n\t\t\tg_right_i = tf.expand_dims(g_right_i, axis=-1)\n\n\t\t\tp_bboxes_i = tf.expand_dims(tf.concat([p_top_i, p_left_i, p_bottom_i, p_right_i], axis=-1), axis=1)\n\t\t\tg_bboxes_i = tf.expand_dims(tf.concat([g_top_i, g_left_i, g_bottom_i, g_right_i], axis=-1), axis=1)\n\n\t\t\t# squeezed_seq_input = tf.squeeze(self.inputs_placeholder[:, i, :, :, :], axis=1)\n\t\t\t# print p_bboxes_i.get_shape().as_list()\n\t\t\t# print g_bboxes_i.get_shape().as_list()\n\t\t\tp_image_bboxes = tf.image.draw_bounding_boxes(self.inputs_placeholder[:, i, :, :, :], p_bboxes_i)\n\t\t\tg_image_bboxes = tf.image.draw_bounding_boxes(self.inputs_placeholder[:, i, :, :, :], g_bboxes_i)\n\t\t\tp_seq_image_bboxes.append(p_image_bboxes)\n\t\t\tg_seq_image_bboxes.append(g_image_bboxes)\n\n\t\tp_image_bboxes = tf.concat(p_seq_image_bboxes, axis=2)\n\t\tg_image_bboxes = tf.concat(g_seq_image_bboxes, axis=2)\n\t\tbbox_summary = tf.concat([p_image_bboxes, g_image_bboxes], axis=1)\n\t\ttf.summary.image('bounding boxes', bbox_summary, max_outputs=10)\n\n\n\tdef add_summary_op(self):\n\t\tself.summary_op = tf.summary.merge_all()\n\n\n\tdef add_feed_dict(self, input_batch, target_batch, seq_len_batch , init_locations_batch):\n\t\tfeed_dict = {self.inputs_placeholder:input_batch, self.targets_placeholder:target_batch,\n\t\t\t\t\t\tself.init_loc:init_locations_batch, self.seq_len_placeholder:seq_len_batch}\n\t\treturn feed_dict\n\n\n\tdef train_one_batch(self, session, input_batch, target_batch, seq_len_batch , init_locations_batch):\n\t\tfeed_dict = self.add_feed_dict(input_batch, target_batch, seq_len_batch , init_locations_batch)\n\n\t\t_, loss, summary, density_func, total_rewards, area_accuracy = session.run([\n\t\t\t\tself.train_op,\n\t\t\t\tself.loss,\n\t\t\t\tself.summary_op,\n\t\t\t\tself.density_func,\n\t\t\t\tself.total_rewards,\n\t\t\t\tself.area_accuracy],\n\t\t\t\tfeed_dict)\n\n\n\t\treturn summary, loss, total_rewards[0][0], area_accuracy\n\n\n\tdef test_one_batch(self, session, input_batch, target_batch, seq_len_batch , init_locations_batch):\n\t\tfeed_dict = self.add_feed_dict(input_batch, target_batch, init_locations)\n\t\t# Accuracy\n\t\tloss, summary, rewards, area_accuracy = session.run([self.loss, self.summary_op, self.total_rewards, self.area_accuracy], feed_dict)\n\n\t\treturn summary, loss, rewards, area_accuracy\n\n\n\tdef run_one_batch(self, args, session, input_batch, target_batch, seq_len_batch , init_locations_batch):\n\t\tif args.train == 'train':\n\t\t\tsummary, loss, rewards, area_accuracy = self.train_one_batch(session, input_batch, target_batch, seq_len_batch , init_locations_batch)\n\t\telse:\n\t\t\tsummary, loss, rewards, area_accuracy = self.test_one_batch(session, input_batch, target_batch, seq_len_batch , init_locations_batch)\n\t\treturn summary, loss, rewards, area_accuracy\n\n\n\tdef get_config(self):\n\t\treturn self.config\n\n\tdef add_update_weights_op(self, input_model, gamma):\n\t\tq_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=input_model.scope)\n\t\ttarget_q_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope)\n\n\t\tupdate_ops = []\n\t\tfor targ, orig in zip(target_q_vars, q_vars):\n\t\t\tnew_targ = tf.assign(targ, gamma*orig + (1-gamma)*targ)\n\t\t\tupdate_ops.append(new_targ)\n\n\t\tself.update_target_op = tf.group(*update_ops)\n\n\tdef update_weights(self, session):\n\t\tsession.run(self.update_target_op)\n","sub_path":"RecurrentCNN.py","file_name":"RecurrentCNN.py","file_ext":"py","file_size_in_byte":17785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"503546085","text":"# Modified version of my script for cross-platform use.\n# Pat Findley 17 Apr 2021\n# Copied to picycle on 13 Aug 2023 for raspberry pi\n# To get Firefox to open pages in the same tab, you have to make these changes in about:config:\n# browser.link.open_newwindow.restriction = 0\n# browser.link.open_newwindow = 1\n# browser.cache.memory.limit < - set to something realistic or it will eat all your rams.\n# Remember to go into options and enable autoplay audio and video if using Youtube links\n #from selenium import webdriver\n #driver = webdriver.Chrome()\n #driver.get(link1)\n#import random\n\n#All this is commented out and it uses the default browser.\n#Opening in the same tab only works in Firefox (new=0), and only if you make the changes above.\n#firefox_path = \"C:\\Program Files\\Mozilla Firefox\\firefox.exe %s\"\n#webbrowser.register('firefox', None, webbrowser.BackgroundBrowser(firefox_path))\n#IF Linux, we need this and change webbrowser.open to firefox.open\n#firefox = webbrowser.get('Firefox')\n\nimport webbrowser\nimport time\nimport subprocess\nrestart = 1\n\nVAR_CYCLE = 1\nwhile VAR_CYCLE > 0:\n\n if restart == 24:\n command = 'pkill firefox'\n command = 'firefox-esr --kiosk http://magicmirror.findley.cc:8080 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(240)\n command = 'kill %1'\n\n command = 'firefox-esr --kiosk https://www.pollen.com/forecast/current/pollen/63132 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(30)\n\n command = 'firefox-esr --kiosk http://en.blitzortung.org/live_lightning_maps.php?map=30 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(60)\n\n command = 'firefox-esr --kiosk https://www.wunderground.com/wundermap?lat=37.7&lon=-92.7&zoom=4&radar=1&wxstn=0 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(60)\n\n command = 'firefox-esr --kiosk http://magicmirror.findley.cc:8080 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(210)\n\n command = 'firefox-esr --kiosk https://radar.weather.gov/?settings=v1_eyJhZ2VuZGEiOnsiaWQiOiJ3ZWF0aGVyIiwiY2VudGV &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(60)\n\n command = 'firefox-esr --kiosk https://www.wunderground.com/wundermap &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(60)\n\n command = 'firefox-esr --kiosk https://www.wunderground.com/dashboard/pws/KMOSTLOU477 &'\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n time.sleep(60)\n \n restart += 1","sub_path":"pibrowser.py","file_name":"pibrowser.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"544021869","text":"import sys\n\n\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n if n <= 0:\n return 0\n res = [1]\n p2, p3, p5 = 0, 0, 0\n\n for i in range(1, n):\n r2 = res[p2] * 2\n r3 = res[p3] * 3\n r5 = res[p5] * 5\n\n res.append(min(r2, r3, r5))\n\n if (res[i] == res[p2] * 2): p2 += 1\n if (res[i] == res[p3] * 3): p3 += 1\n if (res[i] == res[p5] * 5): p5 += 1\n\n return res[-1]\n\n\nans = Solution( )\nxx = ans.nthUglyNumber(10)\n","sub_path":"小工具/ugly.py","file_name":"ugly.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"366854037","text":"from django.forms.formsets import formset_factory, BaseFormSet\nfrom django.forms.widgets import Select, CheckboxInput\n\n__author__ = 'john.back'\n\nfrom django import forms\nfrom django.forms.util import ErrorList\nfrom content.models import Content, Collection, ContentImage\n\nclass ContentForm(forms.ModelForm):\n class Meta:\n model = Content\n fields = ('title', 'description', 'body', 'url', 'display_date')\n\n\nclass ContentFormForMyPosts(forms.ModelForm):\n publish = forms.BooleanField(required=False, widget=CheckboxInput(attrs={'class': 'custom-checkbox publish-post-checkbox'}))\n id = forms.CharField(widget=forms.HiddenInput())\n url = forms.CharField(widget=forms.HiddenInput())\n display_score = forms.CharField(widget=forms.HiddenInput())\n main_image = forms.ModelChoiceField(queryset=ContentImage.objects.all(), empty_label=None, required=False)\n collection = forms.ModelChoiceField(queryset=Collection.objects.all().order_by('name'), empty_label=\"All topics\", required=False,\n widget=Select(attrs={'class': 'posts-list-select-cat custom-dropdown'}))\n\n def __init__(self, *args, **kwargs):\n if 'content' in kwargs.get('initial', {}):\n self.content = kwargs['initial'].pop('content')\n \n super(ContentFormForMyPosts, self).__init__(*args, **kwargs)\n\n if self.initial:\n self.fields['main_image'].queryset = ContentImage.objects.filter(user = self.content.owner, content=self.content)\n\n class Meta:\n model = Content\n fields = ('id', 'title')\n widgets = {\n 'title': forms.HiddenInput(),\n }\n\n def clean_id(self):\n id = self.cleaned_data['id']\n self.content = Content.objects.get(id=id)\n self.fields['main_image'].queryset = ContentImage.objects.filter(user = self.content.owner, content=self.content)\n return id\n\n def save(self):\n changed = False\n if self.content.active != self.cleaned_data['publish']:\n self.content.active = self.cleaned_data['publish']\n changed =True\n if self.content.collection != self.cleaned_data['collection']:\n self.content.collection = self.cleaned_data['collection']\n changed = True\n \n if changed:\n self.content.save()\n\n self.content.cache_revalidate()\n\n\nclass ErrorFormat(ErrorList):\n\n def as_divs(self):\n if not self: return u''\n\n return u'
%s
' % ''.join([u'
'\n u'%s
' % e for e in self])\n\n def __unicode__(self):\n\n return self.as_divs()\n\n\nclass SearchForm(forms.Form):\n word_key = forms.CharField(widget=forms.TextInput(attrs={\n 'class': 'side-search-box brdr-box', 'type': 'text'\n }), required=True, min_length=2)\n\n","sub_path":"content/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"84399884","text":"# time complexity: O (m+n) - total number of elements in both lists\r\n# space complexity: O (1) - list initialization with 2 nodes\r\n\r\n\r\nclass SLNode(object):\r\n\r\n def __init__(self, data=None, next=None):\r\n self.data = data\r\n self.next = next\r\n\r\n def __str__(self):\r\n return str(self.data)\r\n\r\n\r\nclass SLList(object):\r\n\r\n def __init__(self, head=None):\r\n self.head = head\r\n\r\n def __str__(self):\r\n if self.head:\r\n index = self.head\r\n indexes = [str(index)]\r\n while index.next:\r\n index = index.next\r\n indexes.append(str(index))\r\n return 'Single Linked List: ' + ' --> '.join(indexes)\r\n return 'Single Linked List: []'\r\n\r\n\r\ndef merge_lists(head1, head2):\r\n if head1 and head2:\r\n if head1.data < head2.data:\r\n head1.next = merge_lists(head1.next, head2)\r\n return head1\r\n head2.next = merge_lists(head1, head2.next)\r\n return head2\r\n elif head1:\r\n return head1\r\n return head2\r\n\r\ne = SLNode(31)\r\nd = SLNode(15, e)\r\nc = SLNode(7, d)\r\nb = SLNode(3, c)\r\na = SLNode(1, b)\r\n\r\ni = SLNode(16)\r\nh = SLNode(8, i)\r\ng = SLNode(4, h)\r\nf = SLNode(2, g)\r\n\r\nprint(SLList(a))\r\nprint(SLList(f))\r\nprint(SLList(merge_lists(a, f)))","sub_path":"task32.py","file_name":"task32.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"554265928","text":"#!/usr/bin/python\n# -*- coding: UTF-8 _*_\nimport hashlib\nimport os\nimport sys\nimport threading\nimport time\nimport pytest\n\nfrom common.Request import RequestsHandler\nimport allure\nfrom common import Assert\nfrom common.Retrun_Response import dict_style\n\nfrom common.Yaml_Data import HandleYaml\nfrom run_all_case import logger\n\nAPI_dir_cnf = os.path.dirname(os.path.abspath('.')) + '\\\\Auto_Test'\nhandleyaml = HandleYaml(API_dir_cnf + '\\\\test_data\\\\test_yaml_data.yaml')\nyamldict = handleyaml.get_data()\n\ndef_name = sys._getframe().f_code.co_name\n\n\n@pytest.mark.run(order=1)\n@allure.severity(\"blocker\")\n@allure.description(\"测试http://123.133.28.226:60011接口\")\n@allure.testcase(\"http://123.133.28.226:60011\", \"测试用例地址 👇\")\ndef test_api_per():\n logger.info(\"开始执行脚本%s:\\n\", def_name)\n timer = threading.Timer(1, fun_ApiTimeLoop)\n timer.start()\n time.sleep(30) # n秒后停止定时器\n timer.cancel()\n\n\ndef fun_ApiTimeLoop():\n # 优化格式化化版本\n timeNow = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))\n appid = 'cjt'\n checkcode = 'cjt' + timeNow + 'e14b7c06-f127-4f7c-86f0-eec9bbcdc8d6'\n m = hashlib.md5()\n m.update(checkcode.encode('utf-8'))\n\n opera_url = \"http://123.133.28.226:60011/gpl/webservice/security/getToken?appid=\" + appid + \"×tamp=\" + timeNow + \"&checkcode=\" + m.hexdigest()\n opera_result = RequestsHandler().post_Req(url=opera_url, params='')\n sting_response = opera_result.content.decode()\n json_response = dict_style(sting_response)\n token = json_response.get(\"token\")\n if token is None:\n print('ERROR,Token没拿到')\n print(json_response)\n global timer\n timer = threading.Timer(1, fun_ApiTimeLoop)\n timer.start()\n","sub_path":"Auto_Test/test_case/test_Api_demo/test_api_per.py","file_name":"test_api_per.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"59846308","text":"'''\n\tCodes for PCA/ICA methods described in Detecting cell assemblies in large neuronal populations, Lopes-dos-Santos et al (2013).\n\t\t\t\t\t\t\t\t\t\t\thttps://doi.org/10.1016/j.jneumeth.2013.04.010\n\tThis implementation was written in Feb 2019.\n\tPlease e-mail me if you have comments, doubts, bug reports or criticism (Vítor, vtlsantos@gmail.com / vitor.lopesdossantos@pharm.ox.ac.uk).\n'''\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.impute import SimpleImputer\nfrom scipy import stats\nimport numpy as np\nimport numpy.matlib\nimport matplotlib.pyplot as plt\n\n#### Custom imports start here ####\nimport CaImaging.Miniscope\nfrom CaImaging.Miniscope import open_minian, get_transient_timestamps\nfrom CaImaging import util\nfrom itertools import zip_longest\nimport warnings\nfrom tqdm import tqdm\n\n\nfrom CaImaging.CellReg import CellRegObj, trim_map, rearrange_neurons, get_cellreg_path\nfrom scipy.ndimage import gaussian_filter1d\n\n\n__author__ = \"Vítor Lopes dos Santos\"\n__version__ = \"2019.1\"\n\n\ndef toyExample(assemblies, nneurons=10, nbins=1000, rate=1.):\n np.random.seed()\n\n actmat = np.random.poisson(rate, nneurons * nbins).reshape(nneurons, nbins)\n assemblies.actbins = [None] * len(assemblies.membership)\n for (ai, members) in enumerate(assemblies.membership):\n members = np.array(members)\n nact = int(nbins * assemblies.actrate[ai])\n actstrength_ = rate * assemblies.actstrength[ai]\n\n actbins = np.argsort(np.random.rand(nbins))[0:nact]\n\n actmat[members.reshape(-1, 1), actbins] = \\\n np.ones((len(members), nact)) + actstrength_\n\n assemblies.actbins[ai] = np.sort(actbins)\n\n return actmat\n\n\nclass toyassemblies:\n\n def __init__(self, membership, actrate, actstrength):\n self.membership = membership\n self.actrate = actrate\n self.actstrength = actstrength\n\n\ndef marcenkopastur(significance):\n nbins = significance.nbins\n nneurons = significance.nneurons\n tracywidom = significance.tracywidom\n\n # calculates statistical threshold from Marcenko-Pastur distribution\n q = float(nbins) / float(nneurons) # note that silent neurons are counted too\n lambdaMax = pow((1 + np.sqrt(1 / q)), 2)\n lambdaMax += tracywidom * pow(nneurons, -2. / 3) # Tracy-Widom correction\n\n return lambdaMax\n\n\ndef getlambdacontrol(zactmat_):\n significance_ = PCA()\n significance_.fit(zactmat_.T)\n lambdamax_ = np.max(significance_.explained_variance_)\n\n return lambdamax_\n\n\ndef binshuffling(zactmat, significance):\n np.random.seed()\n\n lambdamax_ = np.zeros(significance.nshu)\n for shui in range(significance.nshu):\n zactmat_ = np.copy(zactmat)\n for (neuroni, activity) in enumerate(zactmat_):\n randomorder = np.argsort(np.random.rand(significance.nbins))\n zactmat_[neuroni, :] = activity[randomorder]\n lambdamax_[shui] = getlambdacontrol(zactmat_)\n\n lambdaMax = np.percentile(lambdamax_, significance.percentile)\n\n return lambdaMax\n\n\ndef circshuffling(zactmat, significance):\n np.random.seed()\n\n lambdamax_ = np.zeros(significance.nshu)\n for shui in tqdm(range(significance.nshu)):\n zactmat_ = np.copy(zactmat)\n for (neuroni, activity) in enumerate(zactmat_):\n cut = int(np.random.randint(significance.nbins * 2))\n zactmat_[neuroni, :] = np.roll(activity, cut)\n lambdamax_[shui] = getlambdacontrol(zactmat_)\n\n lambdaMax = np.percentile(lambdamax_, significance.percentile)\n\n return lambdaMax\n\n\ndef runSignificance(zactmat, significance):\n if significance.nullhyp == 'mp':\n lambdaMax = marcenkopastur(significance)\n elif significance.nullhyp == 'bin':\n lambdaMax = binshuffling(zactmat, significance)\n elif significance.nullhyp == 'circ':\n lambdaMax = circshuffling(zactmat, significance)\n else:\n print('ERROR !')\n print(' nyll hypothesis method ' + str(nullhyp) + ' not understood')\n significance.nassemblies = np.nan\n\n nassemblies = np.sum(significance.explained_variance_ > lambdaMax)\n significance.nassemblies = nassemblies\n\n return significance\n\n\ndef extractPatterns(actmat, significance, method):\n nassemblies = significance.nassemblies\n\n if method == 'pca':\n idxs = np.argsort(-significance.explained_variance_)[0:nassemblies]\n patterns = significance.components_[idxs, :]\n elif method == 'ica':\n from sklearn.decomposition import FastICA\n ica = FastICA(n_components=nassemblies)\n ica.fit(actmat.T)\n patterns = ica.components_\n else:\n print('ERROR !')\n print(' assembly extraction method ' + str(method) + ' not understood')\n patterns = np.nan\n\n if patterns is not np.nan:\n patterns = patterns.reshape(nassemblies, -1)\n\n # sets norm of assembly vectors to 1\n norms = np.linalg.norm(patterns, axis=1)\n patterns /= np.matlib.repmat(norms, np.size(patterns, 1), 1).T\n\n return patterns\n\n\ndef runPatterns(zactmat, method='ica', nullhyp='circ', nshu=1000,\n percentile=99, tracywidom=False):\n '''\n INPUTS\n\n zactmat: activity matrix - numpy array (neurons, time bins)\n should already be z-scored\n\n nullhyp: defines how to generate statistical threshold for assembly detection.\n 'bin' - bin shuffling, will shuffle time bins of each neuron independently\n 'circ' - circular shuffling, will shift time bins of each neuron independently\n obs: mantains (virtually) autocorrelations\n 'mp' - Marcenko-Pastur distribution - analytical threshold\n\n nshu: defines how many shuffling controls will be done (n/a if nullhyp is 'mp')\n\n percentile: defines which percentile to be used use when shuffling methods are employed.\n (n/a if nullhyp is 'mp')\n\n tracywidow: determines if Tracy-Widom is used. See Peyrache et al 2010.\n (n/a if nullhyp is NOT 'mp')\n\n OUTPUTS\n\n patterns: co-activation patterns (assemblies) - numpy array (assemblies, neurons)\n significance: object containing general information about significance tests\n zactmat: returns zactmat\n\n '''\n\n nneurons = np.size(zactmat, 0)\n nbins = np.size(zactmat, 1)\n\n silentneurons = np.var(zactmat, axis=1) == 0\n if any(silentneurons):\n warnings.warn(f'Silent neurons detected: '\n f'{np.where(silentneurons)[0].tolist()}')\n actmat_didspike = zactmat[~silentneurons, :]\n\n # # z-scoring activity matrix\n # actmat_ = stats.zscore(actmat_, axis=1)\n #\n # # Impute missing values.\n # imp = SimpleImputer(missing_values=np.nan, strategy='constant',\n # fill_value=0)\n # actmat_ = imp.fit_transform(actmat_.T).T\n\n # running significance (estimating number of assemblies)\n significance = PCA()\n significance.fit(actmat_didspike.T)\n significance.nneurons = nneurons\n significance.nbins = nbins\n significance.nshu = nshu\n significance.percentile = percentile\n significance.tracywidom = tracywidom\n significance.nullhyp = nullhyp\n significance = runSignificance(actmat_didspike, significance)\n if np.isnan(significance.nassemblies):\n return\n\n if significance.nassemblies < 1:\n print('WARNING !')\n print(' no assembly detected!')\n patterns = []\n else:\n # extracting co-activation patterns\n patterns_ = extractPatterns(actmat_didspike, significance, method)\n if patterns_ is np.nan:\n return\n\n # putting eventual silent neurons back (their assembly weights are defined as zero)\n patterns = np.zeros((np.size(patterns_, 0), nneurons))\n patterns[:, ~silentneurons] = patterns_\n # zactmat = np.copy(actmat)\n # zactmat[~silentneurons, :] = actmat_didspike\n\n\n return patterns, significance, zactmat\n\n\ndef computeAssemblyActivity(patterns, zactmat, zerodiag=True):\n nassemblies = len(patterns)\n nbins = np.size(zactmat, 1)\n\n assemblyAct = np.zeros((nassemblies, nbins))\n for (assemblyi, pattern) in enumerate(patterns):\n projMat = np.outer(pattern, pattern)\n projMat -= zerodiag * np.diag(np.diag(projMat))\n for bini in range(nbins):\n assemblyAct[assemblyi, bini] = \\\n np.dot(np.dot(zactmat[:, bini], projMat), zactmat[:, bini])\n\n return assemblyAct\n\n################### Will's code starts here ##################\n\ndef find_assemblies(neural_data, method='ica', nullhyp='mp',\n n_shuffles=1000, percentile=99, tracywidow=False,\n compute_activity=True, use_bool=False, plot=True):\n \"\"\"\n Gets patterns and assembly activations in one go.\n\n :parameters\n ---\n neural_data: (neuron, time) array\n Neural activity (e.g., S).\n\n method: str\n 'ica' or 'pca'. 'ica' is recommended.\n\n nullhyp: str\n defines how to generate statistical threshold for assembly detection.\n 'bin' - bin shuffling, will shuffle time bins of each neuron independently\n 'circ' - circular shuffling, will shift time bins of each neuron independently\n obs: maintains (virtually) autocorrelations\n 'mp' - Marcenko-Pastur distribution - analytical threshold\n\n nshu: float\n defines how many shuffling controls will be done (n/a if nullhyp is 'mp')\n\n percentile: float\n defines which percentile to be used use when shuffling methods are employed.\n (n/a if nullhyp is 'mp')\n\n tracywidow: bool\n determines if Tracy-Widom is used. See Peyrache et al 2010.\n (n/a if nullhyp is NOT 'mp')\n\n \"\"\"\n spiking, _, bool_arr = get_transient_timestamps(neural_data,\n thresh_type='eps')\n if use_bool:\n actmat = bool_arr\n else:\n actmat = stats.zscore(neural_data, axis=1)\n\n # Replace NaNs.\n imp = SimpleImputer(missing_values=np.nan, strategy='constant',\n fill_value=0)\n actmat = imp.fit_transform(actmat.T).T\n\n patterns, significance, z_data = \\\n runPatterns(actmat, method=method, nullhyp=nullhyp,\n nshu=n_shuffles, percentile=percentile,\n tracywidom=tracywidow)\n\n if compute_activity:\n activations = computeAssemblyActivity(patterns, actmat)\n\n if plot:\n sorted_spiking, sorted_colors = membership_sort(patterns, spiking)\n plot_assemblies(activations, sorted_spiking, colors=sorted_colors)\n else:\n activations = None\n\n assembly_dict = {'patterns': patterns,\n 'significance': significance,\n 'z_data': z_data,\n 'orig_data': neural_data,\n 'activations': activations,\n }\n\n return assembly_dict\n\n\ndef membership_sort(patterns, neural_data, sort_duplicates=True):\n \"\"\"\n Sorts neurons by their contributions to each pattern.\n\n :param patterns:\n :param neural_data:\n :return:\n \"\"\"\n high_weights = get_important_neurons(patterns)\n colors = util.distinct_colors(patterns.shape[0])\n\n do_not_sort, sorted_data, sorted_colors = [], [], []\n for color, pattern in zip(colors, high_weights):\n for neuron in pattern:\n if neuron not in do_not_sort:\n sorted_data.append(neural_data[neuron])\n sorted_colors.append(color)\n\n if not sort_duplicates:\n do_not_sort.append(neuron)\n\n return sorted_data, sorted_colors\n\n\ndef preprocess_multiple_sessions(S_list, smooth_factor=0,\n neurons=None, use_bool=True,\n z_method='global'):\n # Store original data.\n data = {'orig_S_list': S_list.copy()}\n\n # Keep certain neurons here. If None, keep all.\n if neurons is not None:\n S_list = [S[neurons] for S in S_list]\n\n # Get event timestamps.\n spike_times, rates, bool_arr_list, new_S = [], [], [], []\n for S in S_list:\n # Handle missing data.\n S = np.asarray(S, dtype=float)\n imp = SimpleImputer(missing_values=np.nan, strategy='constant',\n fill_value=0)\n S = imp.fit_transform(S.T).T\n\n # Get spiking timestamps.\n temp_s, temp_r, temp_bool = \\\n get_transient_timestamps(S, thresh_type='eps',\n do_zscore=False)\n spike_times.append(temp_s)\n rates.append(temp_r)\n bool_arr_list.append(temp_bool)\n new_S.append(S)\n S_list = new_S\n\n # Smooth if desired.\n if smooth_factor > 0:\n S_list = [util.smooth_array(S, smooth_factor)\n for S in S_list]\n bool_arr_list = [util.smooth_array(spikes, smooth_factor)\n for spikes in bool_arr_list]\n\n # Make sure to z-score. Either globally or locally.\n # If global, take into account activity from all sessions that got\n # passed through this function. If local, just z-score within\n # session.\n if z_method == 'global':\n S_list = util.zscore_list(S_list)\n bool_arr_list = util.zscore_list(bool_arr_list)\n\n elif z_method == 'local':\n S_list = [stats.zscore(S, axis=1) for S in S_list]\n bool_arr_list = [stats.zscore(spikes, axis=1) for spikes in bool_arr_list]\n\n data['S'] = S_list\n data['spike_times'] = spike_times\n data['spike_rates'] = rates\n data['bool_arrs'] = bool_arr_list\n\n if use_bool:\n data['processed'] = bool_arr_list\n else:\n data['processed'] = S_list\n\n return data\n\ndef lapsed_activation(act_list, nullhyp='circ', n_shuffles=1000,\n percentile=99):\n \"\"\"\n Computes activity of ensembles based on data from another day.\n\n :parameters\n ---\n S_list: list of (neurons, time) arrays. The first entry will be\n considered the template AND all arrays must be sorted by row\n (neuron) in the same order.\n Neural activity from all sessions.\n\n method: str\n 'ica' or 'pca'. 'ica' is recommended.\n\n nullhyp: str\n defines how to generate statistical threshold for assembly detection.\n 'bin' - bin shuffling, will shuffle time bins of each neuron independently\n 'circ' - circular shuffling, will shift time bins of each neuron independently\n obs: maintains (virtually) autocorrelations\n 'mp' - Marcenko-Pastur distribution - analytical threshold\n\n n_shuffles: float\n defines how many shuffling controls will be done (n/a if nullhyp is 'mp')\n\n percentile: float\n defines which percentile to be used use when shuffling methods are employed.\n (n/a if nullhyp is 'mp')\n \"\"\"\n # Get patterns.\n patterns, significance, _= runPatterns(act_list[0],\n nullhyp=nullhyp,\n nshu=n_shuffles,\n percentile=percentile)\n\n if significance.nassemblies < 1:\n raise ValueError('No assemblies detected.')\n\n # Find assembly activations for the template session then the lapsed ones.\n activations = []\n for actmat in act_list:\n # Get activations.\n activations.append(computeAssemblyActivity(patterns, actmat))\n\n assemblies = {'activations': activations,\n 'patterns': patterns,\n 'significance': significance}\n\n return assemblies\n\n\n# DEPRECATED. Maybe integrate into plot_assemblies\n# def plot_assemblies():\n# # Sort neurons based on membership (weights) in different patterns.\n# sorted_spikes, color_list = [], []\n# for session in spike_times:\n# session_sorted_spikes, colors_sorted = \\\n# membership_sort(patterns, session)\n#\n# # Do this for each session.\n# color_list.append(colors_sorted)\n# sorted_spikes.append(session_sorted_spikes)\n#\n# # Plot assembly activations.\n# if show_plot:\n# fig, axes = plot_assemblies(activations, sorted_spikes,\n# colors=color_list)\n#\n# plt.tight_layout()\n# plt.show()\n#\n#\n# # Compile data.\n# assemblies = dict(activations=activations,\n# patterns=patterns,\n# sorted_spike_times=sorted_spikes)\n#\n# spikes = dict(S_normalized=S_mats,\n# bool_arr=bool_arr,\n# spike_times=spike_times,\n# smooth_actmat=smooth_actmat)\n#\n# return assemblies, spikes\n\n\ndef plot_assemblies(assembly_act, spiking, do_zscore=True, colors=None):\n \"\"\"\n Plots assembly activations with S overlaid.\n\n :parameters\n ---\n assembly_act: list of (patterns, time) arrays\n Assembly activations.\n\n spiking: (sessions,) list of (neurons,) lists\n The inner lists should contain timestamps of spiking activity (e.g., from S).\n\n do_zscore: bool\n Flag to z-score assembly_act.\n\n colors: (sessions,) list of (neurons,) lists\n The inner lists should contain colors for each neuron.\n\n \"\"\"\n\n # Handles cases where you only want to plot one session's assembly.\n if not isinstance(assembly_act, list):\n assembly_act = [assembly_act]\n\n # If colors are not specified, use defaults.\n if colors is None:\n colors = util.distinct_colors(assembly_act[0])\n\n # spiking should already be a list. Let's also check that it's a list\n # that's the same size as assembly_act. If not, it's probably a list\n # of a single session so package it into a list.\n if len(spiking) != len(assembly_act):\n spiking = [spiking]\n colors = [colors]\n\n # Get color for each assembly.\n uniq_colors = util.ordered_unique(colors[0])\n\n # Build the figure.\n n_sessions = len(assembly_act)\n fig, axes = plt.subplots(n_sessions, 1)\n if n_sessions == 1:\n axes = [axes] # For iteration purposes.\n\n # For each session, plot each assembly.\n for n, (ax, act, spikes, c) in \\\n enumerate(zip_longest(axes, assembly_act, spiking, colors,\n fillvalue='k')):\n if do_zscore:\n act = stats.zscore(act, axis=1)\n\n # Plot assembly activation.\n for activation, assembly_color in zip(act, uniq_colors):\n ax.plot(activation, color=assembly_color, alpha=0.7)\n ax2 = ax.twinx()\n ax2.invert_yaxis()\n\n # Plot S.\n ax2.eventplot(spikes, colors=c)\n ax.set_ylim(bottom=0)\n ax2.set_ylim(bottom=0)\n ax.set_ylabel('Ensemble activation [a.u.]')\n ax.set_xlabel('Time [frame]')\n ax2.set_ylabel('Neurons grouped by ensembles', rotation=-90)\n ax2.set_yticks([0, len(spikes)])\n\n return fig, axes\n\n\ndef get_important_neurons(patterns, mode='raw', n=10):\n \"\"\"\n Gets the most highly contributing neurons from each pattern.\n\n :parameters\n ---\n patterns: (patterns, neurons) array\n Weights for each neuron.\n\n mode: 'raw' or 'percentile'\n Determines whether to interpret n as a percentile or the raw number.\n\n n: float\n Percentile or number of neurons to extract from pattern weightings.\n\n :return\n ---\n inds: (patterns,) list of (n,) arrays\n Neuron indices.\n\n \"\"\"\n if mode == 'percentile':\n n = (100-n) * patterns.shape[1]\n\n inds = []\n for pattern in np.abs(patterns):\n inds.append(np.argpartition(pattern, -n)[-n:])\n\n return inds\n\nif __name__ == '__main__':\n # s1 = 0\n # s2 = 2\n # mouse = 'G132'\n # dict_list = util.dir_dict()\n # entries = util.filter_sessions(dict_list, **{'Animal': mouse})\n # cellregpath = get_cellreg_path(mouse)\n #\n # minian_outputs = []\n # for entry in entries:\n # minian_outputs.append(open_minian(entry['DataPath']))\n #\n # C = CellRegObj(cellregpath)\n #\n #\n # # cell_map = trim_map(C.cell_map, [0,1], was_detected_everyday=True)\n # # template = np.asarray(minian1.S)\n # # lapsed = rearrange_neurons(cell_map[:,1], [np.asarray(minian2.S)])\n # # template = rearrange_neurons(cell_map[:,0], [template])\n # #\n # # lapsed_activation(template[0], [lapsed])\n #\n # map = trim_map(C.map, [s1,s2], detected='either_day')\n # template = np.asarray(minian_outputs[s1].S)\n # lapsed = rearrange_neurons(map[:,1], [np.asarray(minian_outputs[s2].S)])\n # template = rearrange_neurons(map[:,0], [template])\n #\n # lapsed_activation(template[0], lapsed)\n #find_assemblies(template[0])\n # Make toy datasets.\n toy = toyassemblies(membership=[[0, 1, 2, 3]],\n actrate=[0.05],\n actstrength=[10])\n act1 = stats.zscore(toyExample(toy, nbins=500), axis=1)\n\n toy = toyassemblies(membership=[[6, 7, 8, 9]],\n actrate=[0.05],\n actstrength=[10])\n act2 = stats.zscore(toyExample(toy, nbins=500), axis=1)\n acts = [act1, act2]\n\n toy = toyassemblies(membership=[[2, 3, 4, 5]],\n actrate=[0.05],\n actstrength=[10])\n act3 = stats.zscore(toyExample(toy, nbins=500), axis=1)\n acts = [act1, act2, act3]\n\n # Get patterns from first dataset.\n patterns = runPatterns(act1)[0]\n\n # Get activation strengths from all datasets.\n assemblyActs = []\n for act in acts:\n assemblyActs.append(computeAssemblyActivity(patterns, act))\n\n fig, axs = plt.subplots(len(acts), 2, sharey='col')\n for act, assemblyAct, ax in zip(acts,\n assemblyActs,\n axs):\n # Spikes and ensemble activation.\n ax[0].plot(assemblyAct.T, color='b', alpha=0.3)\n ax[0].set_ylabel('Activation strength')\n spike_ax = ax[0].twinx()\n spks = spike_ax.imshow(act, cmap='Reds')\n spike_ax.axis('tight')\n ax[0].set_zorder(spike_ax.get_zorder() + 1)\n ax[0].patch.set_visible(False)\n\n # Correlation matrix.\n r = ax[1].imshow(np.corrcoef(act))\n fig.colorbar(spks, ax=spike_ax)\n fig.colorbar(r, ax=ax[1])\n\n plt.tight_layout()\n axs[0,1].set_title('Correlations')\n plt.show()\n","sub_path":"CaImaging/Assemblies.py","file_name":"Assemblies.py","file_ext":"py","file_size_in_byte":22522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"168667886","text":"from datetime import timedelta\nfrom provider.utils import get_dom, skip_empty_lines, days_lower, on_workdays, pattern_slice\n\nURL_ROOT = \"http://stexhaz.hu/index.php/hu/etl/deli-ajanlat\"\n\n\n@on_workdays\ndef get_menu(today):\n dom = get_dom(URL_ROOT)\n menu = dom.xpath(\"/html/body//article//text()\")\n menu = pattern_slice(menu, [days_lower[today.weekday()]], days_lower + ['ára', 'előfizetés', 'ajánlat'], inclusive=False)\n return list(skip_empty_lines(menu))\n\nmenu = {\n 'name': 'Stex',\n 'id': \"st\",\n 'url': URL_ROOT,\n 'get': get_menu,\n 'ttl': timedelta(minutes=100),\n 'cards': ['szep', 'erzs']\n}\n","sub_path":"provider/stex.py","file_name":"stex.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"69108582","text":"#Import other classes and declare global variables\r\n#Raheem\r\nimport GameState as gs\r\nfrom Tile import Tile\r\n#Create begining game board\r\ngameState = gs.newGame()\r\n\r\ndef setup():\r\n size(1000,800)\r\n textAlign(CENTER)\r\n rectMode(CENTER)\r\n\r\ndef draw():\r\n background(150)\r\n gs.interfaceUpdate()\r\n #Use the global gameState variable\r\n global gameState\r\n #Display all items in gameState\r\n grey = True\r\n for x in range(8):\r\n grey = not grey\r\n for y in range(8):\r\n grey = not grey\r\n gameState[x][y].display(grey)\r\n\r\ndef mouseClicked():\r\n #Use the global gameState variable\r\n global gameState\r\n #Buttons\r\n x = int((mouseX)/100)\r\n y = int((mouseY)/100)\r\n if x < 8 and y < 8:\r\n gameState[x][y].clicked(gameState)\r\n","sub_path":"Chess/Chess.pyde","file_name":"Chess.pyde","file_ext":"pyde","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"561009740","text":"# Imports\nimport time\nimport os\nimport RPi.GPIO as GPIO\nimport datetime\nimport DAQ\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n# Constants\nambientSensorPin = 4\nfilename = 'Data'\nfilenameSuffix = '.txt'\nmoistureSensorQuantity = 8\ndataPointsPerHour = 60.0 # Up to 120 per hour (minimum of 30 second delay before reading data)\ndelayBeforeReadingData = 10 # Seconds\nsecondsPerPoint = 60.0*60.0/float(dataPointsPerHour)\n\n# Create new data file \nfilename = DAQ.safeFilename(filename, filenameSuffix)\nheaderString = 'Date and Time, Nominal Minutes, Temp [C], Humidity, Brick1, Brick2, Brick3, Brick4, Brick5, Brick6, Brick7, Brick8'\nDAQ.safeWriteTextToFile(filename, headerString)\nprint(headerString)\n\n# Initialize time and date\nstartDate = datetime.datetime.today()\nDAQ.initializeADC()\n# Loop and collect the data\nshouldContinue = True\nisEven = False\nnominalTestMinutes = 0\n\nwhile shouldContinue == True:\n nominalTestMinutes = nominalTestMinutes + 60.0/dataPointsPerHour\n dataPointStartDateTime = datetime.datetime.today()\n nextDataPointTime = dataPointStartDateTime + datetime.timedelta(seconds=secondsPerPoint)\n \n if isEven == True:\n isEven = False\n else:\n isEven = True\n #print(\"Getting ambient data\")\n (temperature, humidity) = DAQ.getEnvironmentData(ambientSensorPin)\n #print(\"Getting moisture data\")\n moistureSensorValues = DAQ.getMoistureData(isEven,moistureSensorQuantity, delayBeforeReadingData) \n \n currentdatetime = datetime.datetime.today()\n timeSinceStarting = currentdatetime - startDate\n\n dateTimeString = currentdatetime.isoformat(' ')\n\n dataString = dateTimeString + ', ' + repr(nominalTestMinutes) + ', ' + repr(temperature) + ', ' + repr(humidity)\n for i in range(moistureSensorQuantity):\n dataString = dataString + ', ' + repr(moistureSensorValues[i])\n\n DAQ.safeWriteTextToFile(filename, dataString)\n print(dataString)\n dataString = \"\"\n \n if isEven == True:\n isEven = False\n else:\n isEven = True\n \n # Reverse polarity on the sensors for euqal duration to minimize galvanic corrosion\n DAQ.getMoistureData(isEven,moistureSensorQuantity, delayBeforeReadingData) \n\n now = datetime.datetime.today()\n\n #print(\"About to wait for next data point\")\n while now < nextDataPointTime:\n now = datetime.datetime.today()\n #print(\"About to start new data point\")\n","sub_path":"DryingDataLogger.py","file_name":"DryingDataLogger.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"257699331","text":"import numpy as np\nimport cv2\nimport collections\nimport heapq\n\n\n'''\nWhy use heap?\nThe heap implementation ensures time complexity is logarithmic. Thus push/pop operations are\nproportional to the base-2 Logarithm of number of elements.\nImplementation is through a binary tree (Just like a sieve!)\nHeap property: Value of node is always smaller than both of its children unlike a binary search tree.\n'''\nimport queue\nimport time\nimport pandas as pd\n \n'''\nWhy Priority Queue?\nBecause here we have to decide the priority. So what if we had a queue that adjusts the priority for us!\nEarlier attempt was to use a list/collection of nodes and find out the minimum. But the time complexity increases in that case.\n'''\n#Appendix:\n#Diagonal Distance=1\n#Dijkstra=2\n#Euclidean=3\n#H1=4 ...A non-admissible Heuristic.\n#Manhattan=5\n\n\n#Appendix:\nchoice=3 # Heuristic_type\nchoice2=2 # Travel_selection\n''' \nChoice2=1 means diagonal movement allowed\nChoice2=2 means diagonal movement not allowed\n'''\nchoice3=1 # Cost_selection\n'''\nChoice3=1 means normal given cost\nChoice3=2 valid for only Choice2=2\nIt is a cost method developed assuming that a bot takes some time to turn.\nIt is designed so that the bot will prefer to go straight (According to the path along which it has entered the current node)\n'''\n\nheuristic=['Diagonal Distance','Dijkstra','Euclidean','H1','Manhattan']\n#For documentation\nwrite_path='a a astar.txt'\n#Read Image Path\nimg_path='C:/Research Group/Dilation_1.jpg'\n#img_path='sample_for_Astar.png'\n\n#Write Image Path\nimg_write_path='AStar_'+str(choice)+'_'+heuristic[choice-1]+'_'+'Case-'+str(choice2)\nif(choice2==2 and choice3==2):\n img_write_path=img_write_path+'_2'\nimg_write_path=img_write_path+'.png'\n\n#Written as variables so that making changes in code according to the need become easy \n\nwait=10000\n#Define color parameters\nob_color = [255,255,255]\nnp_color =[0,0,0]\npath_pointer=[255,255,0]\nstart=(139,60)\nend=(141,420)\n\n\n#Read Image\nimg = cv2.imread(img_path,cv2.IMREAD_COLOR)\n#Calculate image size before search\nh,w,c = img.shape\n\n\n#Calculate Heuristic Func\ndef calcHeuristic(point1,point2=None,startpt=None,endpt=None):\n\n '''\n Calculates Heuristic Function according to the global choice selected.\\n\n Calculates the Heuristic between points point1 and point2\n choice==1 Diagonal Distance\\n\n returns max(abs(point1[0] - point2[0]),abs(point1[1] - point2[1]))\\n\n choice==2 Dijkstra\\n\n returns 0 (No Heuristic)\\n\n Choice==3 Euclidean=3\\n\n returns ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)**0.5\\n\n Can delete **0.5 according to need\\n\n Choice==4 H1 ...A non-admissible Heuristic.\\n\n H1 is a non-Admissible Heuristic.\\n Based on distance between point and a line.\\nWorks well with no obstacles\\n\n Choice==5 Manhattan\\n\n returns abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])\\n\n @param startpt and endpt required for H1\\n\n '''\n if(choice==1):\n return max(abs(point1[0] - point2[0]),abs(point1[1] - point2[1]))\n\n if(choice==2):\n return 0\n\n if(choice==3):\n return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)**0.5 \n\n if(choice==4):\n a=start[1]-end[1]\n b=end[0]-start[0]\n c=start[0]*end[1]-start[1]*end[0]\n if(a*point1[0]+b*point1[1]+c==0):\n return -10\n return abs(a*point1[0]+b*point1[1]+c) \n\n if(choice==5):\n return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])\n\n\n\n\ndef calcCost(point1,point2):\n ''' \n Calculates cost\n '''\n if(abs(point1[0]-point2[0])==1 and abs(point1[1]-point2[1])==0):\n return 1.0\n if(abs(point1[0]-point2[0])==1 and abs(point1[1]-point2[1])==1):\n return 1.41421356237 #define square root of 2\n if(abs(point1[0]-point2[0])==0 and abs(point1[1]-point2[1])==1):\n return 1.0\n if(abs(point1[0]-point2[0])==0 and abs(point1[1]-point2[1])==0):\n return 0.0\n else:\n return np.inf\n\n\n\n\ndef calcCost2(child,current,start,parent=None): \n '''\n Special cost function\\n\n based on real runtime situation.\\n\n Accounts time taken for turning by the bot\\n\n '''\n point1=child.position\n point2=current.position\n start_point=start.position\n if not (point2[0]==start_point[0] and point2[1]==start_point[1]):\n parent_point=parent.position\n if(float(point2[0])==(point1[0]+parent_point[0])/2 and float(point2[1])==(point1[1]+parent_point[1])/2 ):\n return 1\n if(parent_point[0]==point1[0] and parent_point[1]==point1[1]):\n return 3\n if(point1[0]==point2[0] and point1[1]==point2[1]):\n return 0\n else:\n return 2\n else:\n if(abs(point1[0]-point2[0])==1 and abs(point1[1]-point2[1])==0):\n return 1\n if(abs(point1[0]-point2[0])==0 and abs(point1[1]-point2[1])==1):\n return 1\n if(abs(point1[0]-point2[0])==0 and abs(point1[1]-point2[1])==0):\n return 0\n\n\n\n\n#check for navigation path\ndef isinrange(img,position):\n '''\n Returns False if given node is not accessible\n \\nElse returns True\n '''\n b=False\n x=position[0]\n y=position[1]\n ob_color = [255,255,255]\n if(x>=0 and x=0 and y (chk parameter=cost)\n '''\n return self.f>other.f\n\n\n\n\n\n#get neighbourhood according to choice2\ndef get_nbd(current):\n '''\n returns list of neighbourhood positions\n \\nchoice is made based on choice2\n '''\n l=[]\n\n if(choice2==1):\n for i in range(-1,2):\n for j in range(-1,2):\n position=(current.position[0]+i,current.position[1]+j)\n if (isinrange(img,position)==True):\n l.append(position) \n\n if(choice2==2):\n for i in range(-1,2):\n position=(current.position[0]+i,current.position[1])\n if (isinrange(img,position)==True):\n l.append(position)\n for j in range(-1,2):\n if(j==0): #skip repetition\n continue\n position=(current.position[0],current.position[1]+j)\n if (isinrange(img,position)==True):\n l.append(position) \n \n return l\n\n\n# create a matrix/dict of objects\nnode_matrix=np.empty((h,w),dtype=object)\n#node_matrix=collections.defaultdict(node)\nfor i in range(h):\n for j in range(w):\n node_matrix[i,j]=node()\n node_matrix[i,j].position=(i,j)\n\n\n\n#main function\ndef main_func(img,startpt,endpt):\n '''\n The main traversing function\\n\n returns time taken for traversing\n '''\n #create lists \n visited=[]\n path=[]\n\n h,w,c=img.shape\n\n #create priority queue \n pt_list=PriorityQueue()\n \n #Initialise start node\n start=node(startpt)\n start.g=0\n start.f=start.h=calcHeuristic(start.position,endpt)\n start.isvisted=True\n node_matrix[startpt]=start\n pt_list.put(start)\n\n #Start Traversing\n beg=time.time()\n\n\n while(not pt_list.isempty()):\n\n #while the list is not empty obtain the node with smallest f\n\n current=pt_list.get()\n\n #Now that current node is not in the list change the corresponding chkpts\n\n current.is_in_list=False\n current.is_current=True\n\n #Now to preserve the node use the matrix\n\n node_matrix[current.position]=current\n\n #break condition\n\n if(current.position==endpt):\n break\n\n #get the neighbourhood points\n\n nbd_list=get_nbd(current)\n\n # searching operation \n\n for pos in nbd_list:\n # earlier attempt was to use a list of objects. But finally dealing with position.\n\n nbd=node_matrix[pos]\n\n #get the temp_cost \n\n if(choice2==2 and choice3==2):\n g_temp=current.g+calcCost2(nbd,current,start,current.parent)\n else:\n g_temp=current.g+calcCost(pos,current.position)\n \n # if this newly calculated cost< the stored cost-\n if(g_temp 1048576: #1 MB is the current limit\n return False, 'large_doc_upload'\n \n resume_dir = user.resume_dir\n if not resume_dir:\n #if user.resume_dir is null, we need to fill it up\n resume_dir = getResumeDir()\n user.resume_dir = resume_dir\n\n resume_filename = user.username + '-' + dataplus.getUniqueId()\n resume_path = resume_dir + '/' + resume_filename + ext\n try:\n resume_file = open(resume_path, 'wb')\n resume_file.write(filecontent)\n resume_file.close()\n except:\n logError('Writing uploaded resume file failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n call(['rm',resume_path])\n return False, 'unknown'#'cannot_write_document'\n \n html_created, html_formatter = convertToXHtml(user, resume_path, resume_dir, ext)\n if not html_created:\n call(['rm',resume_path])\n return False, 'cannot_create_html'\n \n else:\n call(['mv',resume_dir + '/' + resume_filename + '.html', resume_dir + '/' + user.username + '.html'])\n call(['mv',resume_path, resume_dir + '/' + user.username + ext])\n \n html_body, html_style = extractBodyAndStyle(resume_dir + '/' + user.username + '.html', html_formatter)\n \n if html_formatter == 'abiword':\n #abiword has an unwanted style 'awml' :)\n html_body = re.sub('awml\\:style=\".*\"','', html_body)\n \n save_result = saveResume(user, html_body, html_style, html_formatter, False)\n \n if save_result:\n format = ext[1:]\n settings = models.UserSettings.objects.get(user=user)\n settings.original_resume_format = format\n settings.available_resume_download_formats = 'html'\n if not settings.resume_download_format_set:\n if format == 'doc':\n settings.preferred_resume_download_format = 'doc'\n elif format == 'odt':\n settings.preferred_resume_download_format = 'pdf'\n settings.save()\n \n return True, 'ok'\n else:\n return False, 'unknown'\n except:\n logError('Save resume doc failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False, 'unknown'\n\ndef saveResume(user, resume_text, resume_html_style='', resume_html_formatter='', original=True):\n try:\n #safety first, filter the html\n if original:\n resume_text = hotmetal.filter(resume_text)\n \n resume_dir = user.resume_dir\n if not resume_dir:\n #if user.resume_dir is null, we need to fill it up\n resume_dir = getResumeDir()\n user.resume_dir = resume_dir\n \n success, resume_html_body, masked_html_body = saveResumeHtml(user, resume_dir, resume_text, resume_html_style, resume_html_formatter)\n if not success:\n return False\n \n #Writing to plain text resume file\n #beautiful-soup gives unicode, dammit! :) need to u => ascii\n html_text = html2text.html2text(resume_html_body) \n update_success = updatePlainTextResume(user, html_text)\n if not update_success:\n return False\n \n cleaned_up_preview_text = cleanUpPreviewText(html2text.html2text(masked_html_body))\n \n #store stuff in hilite and small_desc\n if dataplus.isNullOrEmpty(user.personal_desc):\n user.hilite = dataplus.getPreviewText(cleaned_up_preview_text, 512)\n user.small_desc = dataplus.getPreviewText(cleaned_up_preview_text, 256)\n \n if original:\n settings = models.UserSettings.objects.get(user=user)\n if settings.original_resume_format != 'doc':\n call(['rm',resume_dir + '/' + user.username + '.doc'])\n call(['rm',resume_dir + '/' + user.username + '-masked.doc'])\n \n settings.original_resume_format = 'html'\n settings.available_resume_download_formats = 'html'\n if not settings.resume_download_format_set:\n settings.preferred_resume_download_format = 'pdf'\n settings.save()\n \n user.resume_update_time = datetime.utcnow()\n user.save() \n \n return True\n except:\n logError('Save resume failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False\n\ndef saveResumeHtml(user, resume_dir, resume_text, resume_html_style, resume_html_formatter):\n resume_prefix = u'\\r\\n' + \\\n '\\r\\n' + \\\n '\\r\\n' + \\\n '\\t\\r\\n' + \\\n '\\t' + user.name + '_resume\\r\\n'\n \n resume_prefix += resume_html_style\n \n resume_prefix += '\\r\\n' + \\\n '\\r\\n'\n resume_suffix = u'\\r\\n'\n \n resume_html = resume_prefix + resume_text + resume_suffix\n \n try:\n #some html might need fixing...\n soup = BeautifulSoup(resume_html)\n resume_html = soup.prettify() \n except:\n pass\n \n resume_html += '\\n'\n \n resume_filepath = resume_dir + '/' + user.username + '.html'\n try:\n html_file = open(resume_filepath, 'w')\n html_file.write(resume_html)\n except:\n logError('Writing Html file failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False, None, None\n finally: \n html_file.close()\n \n #create a masked html file too..\n masked_text = getMaskedHtml(resume_text)\n masked_resume_filepath = resume_dir + '/' + user.username + '-masked.html'\n masked_html = resume_prefix + masked_text + resume_suffix\n try:\n masked_html_file = open(masked_resume_filepath, 'w')\n masked_html_file.write(masked_html) \n except:\n logError('Writing Masked Html file failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False, None, None\n finally: \n masked_html_file.close()\n \n #save to DB as well.\n user.resume_contents.text = resume_text\n user.resume_contents.masked_text = masked_text\n user.resume_contents.html_style = resume_html_style\n user.resume_contents.html_formatter = resume_html_formatter\n user.resume_contents.save()\n \n return True, resume_text, masked_text\n \ndef updatePlainTextResume(user, html_text=None):\n try:\n if not user.resume_dir:\n #if user.resume_dir is null, we need to fill it up\n user.resume_dir = getResumeDir()\n \n textfile_path = user.resume_dir + '/' + user.username + '.txt'\n \n if not html_text:\n soup = BeautifulSoup('' + user.resume_contents.text + '')\n resume_html = soup.prettify()\n \n #beautiful-soup gives unicode, dammit! :) need to u => ascii\n html_text = html2text.html2text(resume_html)\n \n resume_plaintext = 'User: ' + user.username + ', Name: ' + user.name + ' - ' + html_text\n if not dataplus.isNullOrEmpty(user.personal_desc):\n try:\n #TODO:fixme: this bombs when non-ascii chars live in user.personal_desc\n resume_plaintext += '\\n' + user.personal_desc \n except:\n pass\n \n resume_plaintext = dataplus.toAscii(resume_plaintext)\n try:\n textfile = open(textfile_path, 'w')\n textfile.write(resume_plaintext)\n except:\n logError('Writing Plain text resume file failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False\n finally:\n textfile.close()\n \n return True\n except:\n logError('Update plain text failed for user:' + user.username + ': ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))\n return False\n \ndef cleanUpPreviewText(resume_text):\n email_pat = re.compile('(?<=[^\\w])\\w+([-+.\\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*(?=[^\\w])')\n preview_text = email_pat.sub(' ', resume_text)\n \n keyword_pat = re.compile('(Email|E-mail|Phone|Mobile)',re.IGNORECASE)\n preview_text = keyword_pat.sub(' ', preview_text)\n \n preview_text = re.sub('[^\\w\\s:\\-\\,;\\.\\'\\(\\)\\+\\#]+',' ', preview_text) \n preview_text = re.sub('[\\s]{2,}',' ',preview_text)\n \n if len(preview_text) > 500:\n m = re.search('.*?[\\.|\\n]', preview_text[100:])\n if m:\n preview_text = preview_text[100:].replace(m.group(0), '')\n \n return preview_text\n \ndef getMaskedHtml(html_frag):\n masked_html = html_frag\n pat1 = re.compile('(?<=[^\\d])[\\d]{3}[\\s|-]{1}[\\d]{4}(?=[^\\d])')\n matches = pat1.findall(masked_html)\n pat2 = re.compile('(?<=[^\\d])[\\d]{4}[\\s|-]{1}[\\d]{4}(?=[^\\d])')\n tmp_matches2 = pat2.findall(masked_html)\n for match2 in tmp_matches2:\n if re.match('^(19|20).*$', match2) is None:\n matches.append(match2)\n pat3 = re.compile('(?<=[^\\d])[\\d]{5,14}(?=[^\\d])')\n matches += pat3.findall(masked_html)\n for match in matches:\n masked_html = masked_html.replace(match, re.sub('\\d','*', match))\n \n return masked_html\n \ndef extractBodyAndStyle(html_file_path, html_formatter):\n html_file = open(html_file_path, 'r')\n resume_text = string.join(html_file.readlines(), '')\n #Abiword encodes as utf-8\n resume_text = dataplus.decode(resume_text, 'ascii')\n html_file.close()\n \n body_start = resume_text.index('>',resume_text.index('')]\n \n html_style = ''\n if html_formatter == 'openoffice':\n try:\n html_style = resume_text[ resume_text.index('')]\n html_style = '\\n'\n except:\n pass\n \n return html_body, html_style\n \ndef convertToXHtml(user, resume_path, resume_dir, ext): \n #Converting to html \n html_created = False\n html_formatter = 'MSWord'\n \n shutil.copy(resume_path, temp_file_path + '/' + user.username + ext)\n files = docserve_client.command('convert_file', user.username + ext + ',html')\n if not files.startswith('error:'):\n shutil.copy(temp_file_path + '/' + user.username + '.html', resume_dir + '/' + user.username + '.html')\n html_created = True\n \n return html_created, html_formatter\n \ndef getResumeDir():\n resume_dir = config.resume_base_path + '/' + strftime(\"%d%m%Y\", gmtime())\n \n #if the folder is not created yet, create it\n if not os.path.exists(resume_dir):\n os.mkdir(resume_dir)\n return resume_dir\n \ndef getIndustryCategoriesHtml(user):\n if user.industry_category:\n selected_cat = user.industry_category.name\n else:\n selected_cat = ''\n\n industry_cats = models.IndustryCategory.objects.all().order_by('id')\n industry_cats_html = hotmetal.elemSelect([('Select', '')], industry_cats,\n lambda x:x.name, lambda x:x.name, selected_cat, 'name=\"industry_category\" id=\"industry_category\" style=\"width:260px\"') \n return industry_cats_html\n\ndef getResumeText(user, masked=False):\n if masked:\n return user.resume_contents.masked_text\n else:\n return user.resume_contents.text\n\ndef getResumeStyleSheet(user):\n return user.resume_contents.html_style\n\ndef getResumeFilePath(user, pref=None, masked=False):\n masked_suffix = ''\n if masked:\n masked_suffix = '-masked'\n resume_path = user.resume_dir + '/' + user.username + masked_suffix + '.pdf'\n if os.path.exists(resume_path):\n return resume_path\n else:\n return user.resume_dir + '/' + user.username + masked_suffix + '.html'\n \n if pref:\n resume_path = user.resume_dir + '/' + user.username + '.' + pref\n if os.path.exists(resume_path):\n return resume_path\n else:\n return None\n \n settings = models.UserSettings.objects.get(user=user)\n if settings.available_resume_download_formats:\n available_formats = settings.available_resume_download_formats.split(',')\n \n if settings.preferred_resume_download_format in available_formats:\n return user.resume_dir + '/' + user.username + '.' + settings.preferred_resume_download_format\n \n return user.resume_dir + '/' + user.username + '.html'\n\ndef logError(err):\n file = open(log_filepath, 'a')\n try:\n file.write(str(datetime.utcnow()) + '\\t' + err + '\\n')\n except:\n pass\n finally:\n if file is not None: file.close()\n \ndef getSalaryRanges(country_code):\n country = models.Country.objects.get(code=country_code)\n salary_brackets = dataplus.stringToList(country.salary_brackets)\n if not salary_brackets: return []\n \n list = []\n list.append(('0-' + salary_brackets[0].replace(',',''), 'upto ' + salary_brackets[0]))\n for i in range(0, len(salary_brackets) -1):\n list.append((salary_brackets[i].replace(',','') + '-' + salary_brackets[i+1].replace(',',''), salary_brackets[i] + '-' + salary_brackets[i+1]))\n list.append((salary_brackets[len(salary_brackets)-1].replace(',','') + '-1000000000', 'more than ' + salary_brackets[len(salary_brackets)-1]))\n \n return list","sub_path":"website/bigfoot/utils/codejar_resume.py","file_name":"codejar_resume.py","file_ext":"py","file_size_in_byte":14814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563142391","text":"#010 - Multiplicação Entre Matrizes\n\nA = []\nB = []\nM = []\n\nLin = int(input('Linha: '))\nCol = int(input('Coluna: '))\nL = int(input('Linha: '))\nC = int(input('Coluna: '))\n\nif Lin == C:\n for l in range(1, Lin+1):\n aux = []\n for c in range(1, Col+1):\n valor = int(input('Valor: '))\n aux.append(valor)\n A.append(aux)\n\n for lin in range(1, L+1):\n aux2 = []\n for col in range(1, C+1):\n V = int(input('Valor: '))\n aux2.append(V)\n B.append(aux2)\n\n\n for a in range(len(A)):\n multi = []\n for b in range(len(B[0])):\n K = 0\n for t in range(len(A[0])):\n K += A[a][t]*B[t][b]\n multi.append(K)\n M.append(multi)\n\n for r in M:\n for s in r:\n print(s, end=' ')\n print()\n\nelse:\n print('Inválida!')\n\n\n\n\n","sub_path":"Revisões - UFRPE/Lista #3 - Listas/010 - Multiplicação Entre Matrizes.py","file_name":"010 - Multiplicação Entre Matrizes.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"476080209","text":"# encoding: utf-8\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\n\nfrom yolox.exp import Exp as MyExp\nfrom yolox.data import get_yolox_datadir\n\nclass Exp(MyExp):\n def __init__(self):\n super(Exp, self).__init__()\n self.num_classes = 3\n self.depth = 1.33\n self.width = 1.25\n# ---------------- dataloader config ---------------- #\n # set worker to 4 for shorter dataloader init time\n self.data_num_workers = 4\n self.input_size = (256, 512) # (height, width)\n # Actual multiscale ranges: [640-5*32, 640+5*32].\n # To disable multiscale training, set the\n # self.multiscale_range to 0.\n self.multiscale_range = 0\n self.train_path = '/data/AIGC_3rd_2021/GIST_tr2_veryhard5000_all_tr2'\n self.val_path = '/data/AIGC_3rd_2021/tr2_set_01_tune'\n self.train_ann = \"label_coco_bbox.json\"\n self.val_ann = \"label_coco_bbox.json\"\n\n # --------------- transform config ----------------- #\n self.mosaic_prob = 0.0\n self.mixup_prob = 0.2\n self.hsv_prob = 0.0\n self.flip_prob = 0.0\n self.degrees = 0.0\n self.translate = 0.0\n self.mosaic_scale = (0.5, 1.5)\n self.mixup_scale = (0.5, 1.5)\n self.shear = 0.0\n self.perspective = 0.0\n self.enable_mixup = True\n\n # -------------- training config --------------------- #\n self.warmup_epochs = 1\n self.max_epoch = 200\n self.warmup_lr = 0\n self.basic_lr_per_img = 0.01 / 64.0\n self.scheduler = \"yoloxwarmcos\"\n self.no_aug_epochs = 15\n self.min_lr_ratio = 0.05\n self.ema = True\n\n self.weight_decay = 5e-4\n self.momentum = 0.9\n self.print_interval = 10\n self.eval_interval = 10\n self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n\n # ----------------- testing config ------------------ #\n self.test_size = (256, 512)\n self.test_conf = 0.01\n self.nmsthre = 0.65\n\n def get_data_loader(self, batch_size, is_distributed, no_aug=False, cache_img=False):\n from yolox.data.datasets.intflow import INTFLOWDataset\n from yolox.data.datasets.mosaicdetection import MosaicDetection\n from yolox.data.data_augment import TrainTransform\n from yolox.data.dataloading import DataLoader\n from yolox.data.samplers import InfiniteSampler, YoloBatchSampler\n import torch.distributed as dist\n\n dataset = INTFLOWDataset(\n data_dir=self.train_path,\n json_file=self.train_ann,\n name=\"img\",\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=10,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n rotation=False,\n compatible_coco=True,\n cache=cache_img,\n )\n\n dataset = MosaicDetection(\n dataset,\n mosaic=not no_aug,\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=20,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n degrees=self.degrees,\n translate=self.translate,\n mosaic_scale=self.mosaic_scale,\n mixup_scale=self.mixup_scale,\n shear=self.shear,\n perspective=self.perspective,\n enable_mixup=self.enable_mixup,\n mosaic_prob=self.mosaic_prob,\n mixup_prob=self.mixup_prob,\n )\n\n self.dataset = dataset\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n sampler = InfiniteSampler(len(self.dataset), seed=self.seed if self.seed else 0)\n\n batch_sampler = YoloBatchSampler(\n sampler=sampler,\n batch_size=batch_size,\n drop_last=False,\n mosaic=not no_aug\n )\n\n dataloader_kwargs = {\"num_workers\": self.data_num_workers, \"pin_memory\": True}\n dataloader_kwargs[\"batch_sampler\"] = batch_sampler\n\n train_loader = DataLoader(self.dataset, **dataloader_kwargs)\n\n return train_loader\n\n def get_eval_loader(self, batch_size, is_distributed, testdev=False):\n from yolox.data import INTFLOWDataset, ValTransform\n\n valdataset = INTFLOWDataset(\n data_dir=self.val_path,\n json_file=self.val_ann,\n name=\"img\",\n img_size=self.input_size,\n preproc=ValTransform(),\n compatible_coco=True,\n rotation=False,\n )\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n sampler = torch.utils.data.distributed.DistributedSampler(\n valdataset, shuffle=False\n )\n else:\n sampler = torch.utils.data.SequentialSampler(valdataset)\n\n dataloader_kwargs = {\n \"num_workers\": self.data_num_workers,\n \"pin_memory\": True,\n \"sampler\": sampler,\n }\n dataloader_kwargs[\"batch_size\"] = batch_size\n val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)\n\n return val_loader\n\n def get_evaluator(self, batch_size, is_distributed, testdev=False):\n from yolox.evaluators import INTFLOWEvaluator\n\n val_loader = self.get_eval_loader(batch_size, is_distributed, testdev)\n evaluator = INTFLOWEvaluator(\n dataloader=val_loader,\n img_size=self.test_size,\n confthre=self.test_conf,\n nmsthre=self.nmsthre,\n num_classes=self.num_classes,\n testdev=testdev,\n )\n return evaluator\n\n def eval(self, model, evaluator, is_distributed, half=False):\n return evaluator.evaluate(model, is_distributed, half)\n","sub_path":"exps/yolox_audio__tr2/yolox_x.py","file_name":"yolox_x.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"447047892","text":"import click\nimport yaml\n\nfrom pipeline_generator import DagGenerator, Downloader\n\nfrom .config_generator import ConfigGenerator\nfrom .requirements_manager import RequirementsManager\nfrom .task_generator import TaskGenerator\nfrom .yaml_file import YamlFile\n\n\nclass Executor(object):\n def execute(self, file: str) -> None:\n with open(file, 'r') as stream:\n data = yaml.load(stream)\n app_name = data['app_name']\n dag_name = data['dag_name']\n Downloader().download_framework(app_name)\n\n generators = [\n TaskGenerator,\n DagGenerator,\n ConfigGenerator,\n RequirementsManager\n ]\n for generator in generators:\n generator(data).execute()\n\n YamlFile().move_to_app_directory(app_name)\n click.echo('Completed!')\n click.echo(\n \"Your application '{}' is created under current directory.\".format(\n app_name))\n click.echo(\n \"Sample DAG file is created at '{}/airflow/dags/{}.py'.\".format(\n app_name, dag_name))\n","sub_path":"pipeline_generator/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"49562672","text":"import os\nfrom lib.util.config import CONFIG\nfrom selenium import webdriver\nfrom Mash import Mash\n\ndef before_all(context):\n context.config = Mash(CONFIG)\n\ndef before_scenario(context, scenario):\n behave_driver = os.environ.get('BHV_DRIVER', 'chrome')\n if behave_driver == 'firefox':\n context.driver = webdriver.Firefox()\n else:\n context.driver = webdriver.Chrome()\n\n if \"frontend\" in context.feature.tags:\n context.driver.get(context.config.front_end.url)\n else:\n context.driver.get(context.config.back_end.url)\n context.driver.maximize_window()\n\ndef after_scenario(context, scenario):\n context.driver.quit()\n","sub_path":"features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"184842677","text":"# Crie um programa que leia vários números inteiros pelo teclado.\n# O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.\n# No final, mostre quantos números foram digitados e qual foi a soma entre eles (deconsiderando o flag 999).\nnum = soma = c = 0\nnum = int(input('Digite um numero [999 para parar]: '))\nwhile num != 999:\n soma += num\n c += 1\n num = int(input('Digite um numero [999 para parar]: '))\nprint(f'Você digitou {c} numeros e a soma entre eles foi {soma}')\n\n'''num = int(input('Digite um numero: '))\nsoma = 0\nc = 0\nwhile num != 999:\n soma += num\n c += 1\n num = int(input('Digite outro: '))\nprint(f'Você digitou {c} numeros e a soma deles é {soma}')'''","sub_path":"CEV/ex064.py","file_name":"ex064.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"371304360","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright Kitware Inc.\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 mako\nimport json\nimport os\nimport requests\nimport cherrypy\nfrom base64 import b64encode\nfrom girder import constants, events\nfrom girder.utility.model_importer import ModelImporter\n\nfrom girder.plugins.minerva.rest import \\\n analysis, dataset, s3_dataset, session, shapefile, geocode, source, \\\n wms_dataset, wms_source\nfrom girder.plugins.minerva.constants import PluginSettings\n\n\nclass CustomAppRoot(object):\n \"\"\"\n The webroot endpoint simply serves the main index HTML file of minerva.\n \"\"\"\n exposed = True\n\n indexHtml = None\n\n vars = {\n 'plugins': [],\n 'apiRoot': '/api/v1',\n 'staticRoot': '/static',\n 'title': 'Minerva'\n }\n\n template = r\"\"\"\n \n \n \n ${title}\n \n \n \n \n \n \n \n % for plugin in pluginCss:\n \n % endfor\n \n \n \n \n \n \n
${apiRoot}
\n
${staticRoot}
\n \n \n \n \n \n \n % for plugin in pluginJs:\n \n % endfor\n \n\n\n \n \n \n \n \n\n \n \n \"\"\"\n\n def GET(self):\n if self.indexHtml is None:\n self.vars['pluginCss'] = []\n self.vars['pluginJs'] = []\n builtDir = os.path.join(constants.STATIC_ROOT_DIR, 'clients',\n 'web', 'static', 'built', 'plugins')\n # it would be nice to get the activated plugins from girder's\n # settings # but we need to reproduce this functionality in the\n # Gruntfile, so pull these from the plugin.json\n minervaPluginDir = os.path.dirname(os.path.realpath(__file__))\n pluginJson = os.path.join(minervaPluginDir, '..', 'plugin.json')\n with open(pluginJson, 'r') as pluginJsonData:\n pluginConfig = json.load(pluginJsonData)\n self.vars['plugins'] = pluginConfig['dependencies']\n for plugin in self.vars['plugins']:\n if os.path.exists(os.path.join(builtDir, plugin,\n 'plugin.min.css')):\n self.vars['pluginCss'].append(plugin)\n if os.path.exists(os.path.join(builtDir, plugin,\n 'plugin.min.js')):\n self.vars['pluginJs'].append(plugin)\n self.indexHtml = mako.template.Template(self.template).render(\n **self.vars)\n\n return self.indexHtml\n\n\nclass WmsProxy(object):\n exposed = True\n\n def GET(self, url, credentials, **params):\n from cryptography.fernet import Fernet\n key = PluginSettings.CRYPTO_KEY\n f = Fernet(key)\n credentials = 'Basic ' + b64encode(f.decrypt(bytes(credentials)))\n headers = {'Authorization': credentials}\n r = requests.get(url, params=params, headers=headers)\n cherrypy.response.headers['Content-Type'] = r.headers['content-type']\n return r.content\n\n\ndef validate_settings(event):\n \"\"\"Validate minerva specific settings.\"\"\"\n key = event.info['key']\n val = event.info['value']\n\n if key == 'minerva.geonames_folder':\n ModelImporter.model('folder').load(val, exc=True, force=True)\n event.preventDefault().stopPropagation()\n\n\ndef load(info):\n # Move girder app to /girder, serve minerva app from /\n info['serverRoot'], info['serverRoot'].girder = (CustomAppRoot(),\n info['serverRoot'])\n info['serverRoot'].api = info['serverRoot'].girder.api\n\n shapefileREST = shapefile.Shapefile()\n info['apiRoot'].item.route('POST', (':id', 'geojson'),\n shapefileREST.createGeoJson)\n info['apiRoot'].item.route('GET', (':id', 'geojson'),\n shapefileREST.findGeoJson)\n\n # Admin endpoint for initializing the geonames database\n info['apiRoot'].geonames = geocodeREST = geocode.Geonames()\n info['apiRoot'].geonames.route('POST', ('setup',),\n geocodeREST.setup)\n info['apiRoot'].geonames.route('GET', ('geocode',),\n geocodeREST.geocode)\n events.bind('model.setting.validate', 'minerva', validate_settings)\n\n info['apiRoot'].minerva_dataset = dataset.Dataset()\n info['apiRoot'].minerva_analysis = analysis.Analysis()\n info['apiRoot'].minerva_session = session.Session()\n info['apiRoot'].minerva_dataset_s3 = s3_dataset.S3Dataset()\n info['apiRoot'].minerva_source = source.Source()\n info['apiRoot'].minerva_source_wms = wms_source.WmsSource()\n info['apiRoot'].minerva_dataset_wms = wms_dataset.WmsDataset()\n info['serverRoot'].wms_proxy = WmsProxy()\n","sub_path":"server/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459152582","text":"from math import exp\nfrom random import random\n\ndef categorical_draw(probs):\n z = random()\n cum_prob = 0.0\n for i in range(len(probs)):\n prob = probs[i]\n cum_prob += prob\n if cum_prob > z:\n return i\n \n return len(probs) - 1\n\nclass Hedge(object):\n def __init__(self, eta, counts, values):\n self.eta = eta\n self.counts = counts\n self.values = values\n return\n \n def initialize(self, n_arms):\n self.counts = [0 for col in range(n_arms)]\n self.values = [0.0 for col in range(n_arms)]\n return\n \n def select_arm(self):\n zz = [exp(v / self.eta) for v in self.values]\n z = sum(zz)\n probs = [ i/z for i in zz]\n return categorical_draw(probs)\n \n def update(self, chosen_arm, reward):\n self.counts[chosen_arm] = self.counts[chosen_arm] + 1\n \n value = self.values[chosen_arm]\n self.values[chosen_arm] = value + reward\n return\n","sub_path":"python/algorithms/hedge.py","file_name":"hedge.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411020249","text":"#!/home/chwang/anaconda2/envs/tensorflow/bin/python\n\n#/eecs/research/asr/mingbin/python-workspace/hopeless/bin/python\nimport numpy, logging, time, copy, os, cPickle\n\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n# from CoNLL2003eval import evaluation\nfrom gigaword2feature import * \nfrom LinkingUtil import *\n\nfrom tqdm import tqdm\nfrom itertools import ifilter, izip, imap\nfrom random import choice\n\nlogger = logging.getLogger( __name__ )\n\n########################################################################\n\ndef load_word_embedding( filename ):\n \"\"\"\n Parameters\n ----------\n filename : str\n path to the word embedding binary file (trained by skipgram-train.py)\n\n Returns\n -------\n embedding : ndarray\n 2D matrix where each row is a word vector\n \"\"\"\n with open( filename, 'rb' ) as fp:\n shape = numpy.fromfile( fp, dtype = numpy.int32, count = 2 )\n embedding = numpy.fromfile( fp, dtype = numpy.float32 ).reshape( shape )\n return embedding\n\n########################################################################\n\n\nclass mention_config( object ):\n def __init__( self, args = None ):\n # default config\n self.word_embedding = 'word2vec/reuters128'\n self.data_path = 'processed-data'\n self.n_char_embedding = 64\n self.n_char = 128\n self.n_batch_size = 512\n self.learning_rate = 0.1024\n self.momentum = 0.9\n self.layer_size = '512,512,512'\n self.max_iter = 64\n self.feature_choice = 511\n self.overlap_rate = 0.08\n self.disjoint_rate = 0.016\n self.dropout = True\n self.n_ner_embedding = 32\n self.char_alpha = 0.8\n self.word_alpha = 0.5\n self.n_window = 7\n self.strictly_one_hot = True\n self.hope_out = 0\n self.n_label_type = 7\n self.kernel_height = range(2, 10)\n self.kernel_depth = [16] * 8\n self.enable_distant_supervision = False\n self.initialize_method = 'uniform'\n self.kernel_depth = ','.join( ['16'] * 8 )\n self.kernel_height = '2,3,4,5,6,7,8,9'\n self.l1 = 0\n self.l2 = 0\n self.n_pattern = 0\n\n # KBP-specific config\n self.language = 'eng'\n self.average = False\n self.is_2nd_pass = False\n\n if args is not None:\n self.__dict__.update( args.__dict__ )\n\n self.kernel_depth = [ int(d) for d in self.kernel_depth.split(',') ]\n self.kernel_height = [ int(h) for h in self.kernel_height.split(',') ]\n \n # these parameters are not decided by the input to the program\n # I put some placeholders here; they will be eventually modified\n self.algorithm = 1 # highest first, decided by training\n self.threshold = 0.5 # decided by training\n self.drop_rate = 0.4096 if self.dropout else 0\n self.n_word1 = 100000 # decided by self.word_embedding\n self.n_word2 = 100000 # decided by self.word_embedding\n self.n_word_embedding1 = 256 # decided by self.word_embedding\n self.n_word_embedding2 = 256 # decided by self.word_embedding\n self.customized_threshold = None # not used any more\n assert len( self.kernel_height ) == len( self.kernel_depth )\n\n\n########################################################################\n\n\nclass multi_fofe_mention_net( object ):\n\n def __init__( self, config = None, gpu_option = 0.96 ):\n \"\"\"\n Parameters\n ----------\n config : mention_config\n \"\"\"\n\n # most code is lengacy, let's put some alias here\n word_embedding = config.word_embedding\n data_path = config.data_path\n n_char_embedding = config.n_char_embedding\n n_char = config.n_char\n n_batch_size = config.n_batch_size\n learning_rate = config.learning_rate\n momentum = config.momentum\n layer_size = config.layer_size\n feature_choice = config.feature_choice\n overlap_rate = config.overlap_rate\n disjoint_rate = config.disjoint_rate\n dropout = config.dropout\n n_ner_embedding = config.n_ner_embedding\n char_alpha = config.char_alpha\n word_alpha = config.word_alpha\n n_window = config.n_window\n hope_out = config.hope_out\n n_label_type = config.n_label_type\n kernel_height = config.kernel_height\n kernel_depth = config.kernel_depth\n enable_distant_supervision = config.enable_distant_supervision\n initialize_method = config.initialize_method\n n_pattern = config.n_pattern\n \n # if config is not None:\n # self.config = copy.deepcopy( config )\n # else:\n # self.config = mention_config()\n\n self.config = mention_config()\n if config is not None:\n self.config.__dict__.update( config.__dict__ )\n\n self.graph = tf.Graph()\n\n # TODO: create a graph instead of using default graph\n # otherwise, we cannot instantiate multiple fofe_mention_nets\n # tf.reset_default_graph()\n\n if gpu_option is not None:\n gpu_option = tf.GPUOptions( per_process_gpu_memory_fraction = gpu_option )\n configg = tf.ConfigProto(gpu_options = gpu_option )\n configg.gpu_options.allow_growth = True\n self.session = tf.Session( config = configg,\n # log_device_placement = True ),\n graph = self.graph )\n\n else:\n self.session = tf.Session( graph = self.graph )\n\n # NON-CHINESE WORD EMBEDDINGS\n if os.path.exists( self.config.word_embedding + '-case-insensitive.word2vec' ) \\\n and os.path.exists( self.config.word_embedding + '-case-sensitive.word2vec' ):\n\n # Matrix with row word vectors for insensitive case\n projection1 = load_word_embedding( self.config.word_embedding + \\\n '-case-insensitive.word2vec' )\n\n # Matrix with row word vectors for sensitive case\n projection2 = load_word_embedding( self.config.word_embedding + \\\n '-case-sensitive.word2vec' )\n\n # Number of words in insensitive case\n self.n_word1 = projection1.shape[0]\n\n # Number of words in sensitive case\n self.n_word2 = projection2.shape[0]\n\n # Number of words in insensitive case\n n_word1 = projection1.shape[0]\n # Number of words in sensitive case\n n_word2 = projection2.shape[0]\n\n # Length of the word embedding for insensitive case\n n_word_embedding1 = projection1.shape[1]\n\n # Length of the word embedding for sensitive case\n n_word_embedding2 = projection2.shape[1]\n\n # Update the configuation\n self.config.n_word1 = self.n_word1\n self.config.n_word2 = self.n_word2\n self.config.n_word_embedding1 = n_word_embedding1\n self.config.n_word_embedding2 = n_word_embedding2\n logger.info( 'non-Chinese embeddings loaded' )\n\n # CHINESE CHARACTER EMBEDDINGS\n elif os.path.exists( self.config.word_embedding + '-char.word2vec' ) \\\n and os.path.exists( self.config.word_embedding + '-word.word2vec' ):\n\n projection1 = load_word_embedding( self.config.word_embedding + \\\n '-char.word2vec' )\n projection2 = load_word_embedding( self.config.word_embedding + \\\n ('-avg.word2vec' if self.config.average else '-word.word2vec') )\n\n self.n_word1 = projection1.shape[0]\n self.n_word2 = projection2.shape[0]\n\n n_word_embedding1 = projection1.shape[1]\n n_word_embedding2 = projection2.shape[1]\n\n self.config.n_word1 = self.n_word1\n self.config.n_word2 = self.n_word2\n self.config.n_word_embedding1 = n_word_embedding1\n self.config.n_word_embedding2 = n_word_embedding2\n logger.info( 'Chinese embeddings loaded' )\n\n else:\n self.n_word1 = self.config.n_word1\n self.n_word2 = self.config.n_word2\n n_word_embedding1 = self.config.n_word_embedding1\n n_word_embedding2 = self.config.n_word_embedding2\n\n projection1 = numpy.random.uniform( -1, 1, \n (self.n_word1, n_word_embedding1) ).astype( numpy.float32 )\n projection2 = numpy.random.uniform( -1, 1, \n (self.n_word2, n_word_embedding2) ).astype( numpy.float32 )\n logger.info( 'embedding is randomly initialized' )\n\n if config.is_2nd_pass:\n logger.info( 'In 2nd pass, substitute the last few entries with label types.' )\n projection1[-1 - n_label_type: -1, :] = \\\n numpy.random.uniform( \n projection1.min(), projection1.max(),\n (n_label_type, n_word_embedding1) \n ).astype( numpy.float32 )\n sub = numpy.random.uniform( \n projection2.min(), projection2.max(),\n (n_label_type, n_word_embedding2) \n ).astype( numpy.float32 )\n if self.config.language == 'cmn':\n projection2[-1 - n_label_type: -1, :] = sub\n else:\n projection2[-2 - n_label_type: -2, :] = sub\n\n # dimension of x in the HOPE paper\n hope_in = 0\n for ith, name in enumerate( ['case-insensitive bidirectional-context-with-focus', \\\n 'case-insensitive bidirectional-context-without-focus', \\\n 'case-insensitive focus-bow', \\\n 'case-sensitive bidirectional-context-with-focus', \\\n 'case-sensitive bidirectional-context-without-focus', \\\n 'case-sensitive focus-bow', \\\n 'left-char & right-char', 'left-initial & right-initial', \\\n 'gazetteer', 'char-conv', 'char-bigram' ] ):\n if (1 << ith) & self.config.feature_choice > 0: \n logger.info( '%s used' % name )\n if ith in [0, 1]:\n hope_in += n_word_embedding1 * 2\n elif ith in [3, 4]:\n hope_in += n_word_embedding2 * 2\n elif ith == 2:\n hope_in += n_word_embedding1\n elif ith == 5:\n hope_in += n_word_embedding1\n elif ith in [6, 7]:\n hope_in += n_char_embedding * 2\n elif ith == 8: \n hope_in += n_ner_embedding\n elif ith == 9:\n hope_in += sum( kernel_depth )\n elif ith == 10:\n hope_in += n_char_embedding * 2\n\n CONLL_N_LABELS = 4\n ONTONOTES_N_LABELS = 18\n KBP_N_LABELS = 10\n\n # add a U matrix between projected feature and fully-connected layers\n\n n_in_shared = [ hope_out if hope_out > 0 else hope_in ] + [ int(s) for s in layer_size.split(',') ]*4\n n_out_shared = n_in_shared[1:] + [n_in_shared[-1]]\n\n n_in_conll = n_out_shared[-4:]\n n_out_conll = n_in_conll[1:] + [ CONLL_N_LABELS + 1 ]\n\n n_in_ontonotes = n_out_shared[-4:]\n n_out_ontonotes = n_in_ontonotes[1:] + [ ONTONOTES_N_LABELS + 1 ]\n\n n_in_kbp = n_out_shared[-4:]\n n_out_kbp = n_in_kbp[1:] + [KBP_N_LABELS + 1]\n\n logger.info( 'n_in_shared: ' + str(n_in_shared) )\n logger.info( 'n_out_shared: ' + str(n_out_shared) )\n logger.info( 'n_in_ontonotes: ' + str(n_in_ontonotes) )\n logger.info( 'n_out_ontonotes: ' + str(n_out_ontonotes) )\n logger.info( 'n_in_conll: ' + str(n_in_conll) )\n logger.info( 'n_out_conll: ' + str(n_out_conll) )\n logger.info( 'n_in_kbp' + str(n_in_kbp))\n logger.info( 'n_out_kbp'+ str(n_out_kbp))\n\n with self.graph.as_default():\n\n ###########################\n ### WORD-LEVEL FEATURES ###\n ###########################\n\n # CASE INSENSITIVE\n # ----------------\n\n # case insensitive excluding fragment\n self.lw1_values = tf.placeholder( dtype = tf.float32, shape = [None], \n name = 'left-context-values' )\n self.lw1_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'left-context-indices' )\n\n # case insensitive excluding fragment\n self.rw1_values = tf.placeholder( tf.float32, [None], \n name = 'right-context-values' )\n self.rw1_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'right-context-indices' )\n\n # case insensitive including fragment\n self.lw2_values = tf.placeholder( tf.float32, [None], \n name = 'left-context-values' )\n self.lw2_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'left-context-indices' )\n\n # case insensitive including fragment\n self.rw2_values = tf.placeholder( tf.float32, [None], \n name = 'right-context-values' )\n self.rw2_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'right-context-indices' )\n\n # case insensitive bow fragment\n self.bow1_values = tf.placeholder( tf.float32, [None], \n name = 'bow-values' )\n self.bow1_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'bow-indices' )\n\n # CASE SENSITIVE\n # --------------\n # value vectors in FOFE code\n\n # case sensitive excluding fragment\n self.lw3_values = tf.placeholder( tf.float32, [None], \n name = 'left-context-values' )\n self.lw3_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'left-context-indices' )\n\n # case sensitive excluding fragment\n self.rw3_values = tf.placeholder( tf.float32, [None], \n name = 'right-context-values' )\n self.rw3_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'right-context-indices' )\n\n # case sensitive including fragment\n self.lw4_values = tf.placeholder( tf.float32, [None], \n name = 'left-context-values' )\n self.lw4_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'left-context-indices' )\n\n # case sensitive including fragment\n self.rw4_values = tf.placeholder( tf.float32, [None], \n name = 'right-context-values' )\n self.rw4_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'right-context-indices' )\n\n # case sensitive bow fragment\n self.bow2_values = tf.placeholder( tf.float32, [None], \n name = 'bow-values' )\n self.bow2_indices = tf.placeholder( tf.int64, [None, 2], \n name = 'bow-indices' )\n\n # Shape of the index matrices\n # ===========================\n # case insensitive bow shape, vector of size 2\n # first value # of rows and second value # of cols\n self.shape1 = tf.placeholder( tf.int64, [2], name = 'bow-shape1' )\n # case sensitive\n self.shape2 = tf.placeholder( tf.int64, [2], name = 'bow-shape2' )\n\n\n ################################\n ### CHARACTER-LEVEL FEATURES ###\n ################################\n\n self.lc_fofe = tf.placeholder( tf.float32, [None, n_char], name = 'left-char' )\n self.rc_fofe = tf.placeholder( tf.float32, [None, n_char], name = 'right-char' )\n\n self.li_fofe = tf.placeholder( tf.float32, [None, n_char], name = 'left-initial' )\n self.ri_fofe = tf.placeholder( tf.float32, [None, n_char], name = 'right-initial' )\n\n ################################################################################\n # A grid like matrix where each row represents a token, and a 0/1 in a particular\n # column means that the token is a mention with entity type corresponding to \n # column number:\n self.ner_cls_match_conll = tf.placeholder( tf.float32, [None, CONLL_N_LABELS + 1], name = 'gazetteer_conll' )\n self.ner_cls_match_ontonotes = tf.placeholder( tf.float32, [None, ONTONOTES_N_LABELS + 1], name = 'gazetteer_ontonotes' )\n self.ner_cls_match_kbp = tf.placeholder(tf.float32, [None, KBP_N_LABELS + 1], name = 'gazetteer_kbp')\n\n # Each entity type is associated with a label\n self.label = tf.placeholder( tf.int64, [None], 'label' )\n\n # A constant value\n self.lr = tf.placeholder( tf.float32, [], 'learning-rate' )\n\n # 1 - dropout rate\n self.keep_prob = tf.placeholder( tf.float32, [], 'keep-prob' )\n \n self.char_idx = tf.placeholder( tf.int32, [None, None], name = 'char-idx' )\n\n # Bigrams\n # left context character level\n self.lbc_values = tf.placeholder( tf.float32, [None], name = 'bigram-values' )\n self.lbc_indices = tf.placeholder( tf.int64, [None, 2], name = 'bigram-indices' )\n\n # right context character level\n self.rbc_values = tf.placeholder( tf.float32, [None], name = 'bigram-values' )\n self.rbc_indices = tf.placeholder( tf.int64, [None, 2], name = 'bigram-indices' )\n\n ################################################################################\n\n self.shape3 = tf.placeholder( tf.int64, [2], name = 'shape3' )\n\n logger.info( 'placeholder defined' )\n #################### model parameters ##########################################\n ################################################################################\n\n # projection1 and projection2 are one-hot word vectors (?)\n self.word_embedding_1 = tf.Variable( projection1 )\n self.word_embedding_2 = tf.Variable( projection2 )\n del projection1, projection2\n\n # weights & bias of fully-connected layers\n # self.W contains weight matrices for each layer\n self.shared_layer_weights = []\n self.ontonotes_layer_weights = []\n self.conll_layer_weights = []\n self.kbp_layer_weights = []\n\n # Bias\n self.shared_layer_b = [] \n self.ontonotes_layer_b = []\n self.conll_layer_b = []\n self.param = []\n self.kbp_layer_b = []\n\n # network weights are randomly initialized based on the uniform distribution\n if initialize_method == 'uniform':\n # Character-level network weights initialization\n val_rng = numpy.float32(2.5 / numpy.sqrt(n_char + n_char_embedding))\n self.char_embedding = tf.Variable( tf.random_uniform( \n [n_char, n_char_embedding], minval = -val_rng, maxval = val_rng ) )\n \n self.conv_embedding = tf.Variable( tf.random_uniform( \n [n_char, n_char_embedding], minval = -val_rng, maxval = val_rng ) )\n\n # Word-level network weights initialization\n # value range\n val_rng_conll = numpy.float32(2.5 / numpy.sqrt(CONLL_N_LABELS + n_ner_embedding + 1))\n val_rng_ontonotes = numpy.float32(2.5 / numpy.sqrt(ONTONOTES_N_LABELS + n_ner_embedding + 1))\n var_rng_kbp = numpy.float32(2.5 / numpy.sqrt(KBP_N_LABELS + n_ner_embedding + 1))\n\n # random initialization of word embeddings\n self.ner_embedding_conll = tf.Variable( tf.random_uniform( \n [CONLL_N_LABELS + 1 , n_ner_embedding], minval = -val_rng_conll, maxval = val_rng_conll ) )\n\n self.ner_embedding_ontonotes = tf.Variable( tf.random_uniform( \n [ONTONOTES_N_LABELS + 1 ,n_ner_embedding], minval = -val_rng_ontonotes, maxval = val_rng_ontonotes ) )\n\n self.ner_embedding_kbp = tf.Variable( tf.random_uniform( \n [KBP_N_LABELS + 1 ,n_ner_embedding], minval = -var_rng_kbp, maxval = var_rng_kbp ) )\n \n val_rng = numpy.float32(2.5 / numpy.sqrt(96 * 96 + n_char_embedding))\n self.bigram_embedding = tf.Variable( tf.random_uniform( \n [96 * 96, n_char_embedding], minval = -val_rng, maxval = val_rng ) )\n\n self.kernels = [ tf.Variable( tf.random_uniform( \n [h, n_char_embedding, 1, d], \n minval = -2.5 / numpy.sqrt(1 + h * n_char_embedding * d), \n maxval = 2.5 / numpy.sqrt(1 + h * n_char_embedding * d) ) ) for \\\n (h, d) in zip( kernel_height, kernel_depth ) ]\n\n self.kernel_bias = [ tf.Variable( tf.zeros( [d] ) ) for d in kernel_depth ]\n\n if hope_out > 0:\n val_rng = 2.5 / numpy.sqrt( hope_in + hope_out )\n u_matrix = numpy.random.uniform( -val_rng, val_rng, \n [hope_in, hope_out] ).astype( numpy.float32 )\n u_matrix = u_matrix / (u_matrix ** 2).sum( 0 )\n self.U = tf.Variable( u_matrix )\n del u_matrix\n\n # Initialize the weights of each module using uniform\n for i, o in zip( n_in_shared, n_out_shared ):\n val_rng = numpy.float32(2.5 / numpy.sqrt(i + o))\n # random_uniform : Returns a tensor of the specified shape filled with random uniform values.\n self.shared_layer_weights.append( tf.Variable( tf.random_uniform( [i, o], minval = -val_rng, maxval = val_rng ) ) )\n self.shared_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_ontonotes, n_out_ontonotes ):\n val_rng = numpy.float32(2.5 / numpy.sqrt(i + o))\n\n self.ontonotes_layer_weights.append( tf.Variable( tf.random_uniform( [i, o], minval = -val_rng, maxval = val_rng ) ) )\n self.ontonotes_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_conll, n_out_conll ):\n val_rng = numpy.float32(2.5 / numpy.sqrt(i + o))\n\n self.conll_layer_weights.append( tf.Variable( tf.random_uniform( [i, o], minval = -val_rng, maxval = val_rng ) ) )\n self.conll_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_kbp, n_out_kbp ):\n val_rng = numpy.float32(2.5 / numpy.sqrt(i + o))\n\n self.kbp_layer_weights.append( tf.Variable( tf.random_uniform( [i, o], minval = -val_rng, maxval = val_rng ) ) )\n self.kbp_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n\n if n_pattern > 0:\n # case-insensitive patterns\n val_rng = numpy.sqrt(3)\n\n # val_rng = numpy.float32(2.5 / numpy.sqrt(n_pattern + n_word1)) \n self.pattern1 = []\n self.pattern1_bias = []\n for _ in xrange(4):\n self.pattern1.append(\n tf.Variable(\n tf.random_uniform( [n_pattern, n_word1],\n minval = -val_rng, maxval = val_rng )\n )\n )\n self.pattern1_bias.append(\n tf.Variable(\n tf.random_uniform( [n_pattern],\n minval = -val_rng, maxval = val_rng )\n )\n )\n\n # case-sensitive patterns\n # val_rng = numpy.float32(2.5 / numpy.sqrt(n_pattern + n_word2))\n self.pattern2 = []\n self.pattern2_bias = []\n for _ in xrange(4):\n self.pattern2.append(\n tf.Variable(\n tf.random_uniform( [n_pattern, n_word2],\n minval = -val_rng, maxval = val_rng )\n )\n )\n self.pattern2_bias.append(\n tf.Variable(\n tf.random_uniform( [n_pattern],\n minval = -val_rng, maxval = val_rng )\n )\n )\n\n del val_rng\n \n else:\n self.char_embedding = tf.Variable( tf.truncated_normal( [n_char, n_char_embedding], \n stddev = numpy.sqrt(2./(n_char * n_char_embedding)) ) )\n \n self.conv_embedding = tf.Variable( tf.truncated_normal( [n_char, n_char_embedding], \n stddev = numpy.sqrt(2./(n_char * n_char_embedding)) ) )\n\n self.ner_embedding = tf.Variable( tf.truncated_normal( [n_label_type + 1, n_ner_embedding], \n stddev = numpy.sqrt(2./(n_label_type * n_ner_embedding)) ) )\n\n self.bigram_embedding = tf.Variable( tf.truncated_normal( [96 * 96, n_char_embedding],\n stddev = numpy.sqrt(2./(96 * 96 * n_char_embedding)) ) )\n\n self.kernels = [ tf.Variable( tf.truncated_normal( [h, n_char_embedding, 1, d], \n stddev = numpy.sqrt(2./(h * n_char_embedding * d)) ) ) for \\\n (h, d) in zip( kernel_height, kernel_depth ) ]\n\n self.kernel_bias = [ tf.Variable( tf.zeros( [d] ) ) for d in kernel_depth ]\n\n # the U matrix in the HOPE paper\n if hope_out > 0:\n self.U = tf.Variable( tf.truncated_normal( [hope_in, hope_out],\n stddev = numpy.sqrt(2./(hope_in * hope_out)) ) )\n\n for i, o in zip( n_in_shared, n_out_shared ):\n self.shared_layer_weights.append( tf.Variable( tf.truncated_normal( [i, o], stddev = numpy.sqrt(2./(i * o)) ) ) )\n self.shared_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_ontonotes, n_out_ontonotes ):\n self.ontonotes_layer_weights.append( tf.Variable( tf.truncated_normal( [i, o], stddev = numpy.sqrt(2./(i * o)) ) ) )\n self.ontonotes_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_conll, n_out_conll ):\n self.conll_layer_weights.append( tf.Variable( tf.truncated_normal( [i, o], stddev = numpy.sqrt(2./(i * o)) ) ) )\n self.conll_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n for i, o in zip( n_in_kbp, n_out_kbp ):\n self.kbp_layer_weights.append( tf.Variable( tf.truncated_normal( [i, o], stddev = numpy.sqrt(2./(i * o)) ) ) )\n self.kbp_layer_b.append( tf.Variable( tf.zeros( [o] ) ) )\n\n if n_pattern > 0:\n # case-insensitive patterns\n # stddev = numpy.sqrt(2./(n_pattern * n_word1))\n stddev = numpy.sqrt(2./n_word1 )\n self.pattern1 = []\n self.pattern1_bias = []\n for _ in xrange(4):\n self.pattern1.append(\n tf.Variable(\n tf.truncated_normal( [n_pattern, n_word1], stddev = stddev )\n )\n )\n self.pattern1_bias.append(\n tf.Variable(\n tf.truncated_normal( [n_pattern], stddev = stddev )\n )\n )\n\n # case-sensitive patterns\n # stddev = numpy.sqrt(2./(n_pattern * n_word2))\n stddev = numpy.sqrt(2./n_word2)\n self.pattern2 = []\n self.pattern2_bias = []\n for _ in xrange(4):\n self.pattern2.append(\n tf.Variable(\n tf.truncated_normal( [n_pattern, n_word2], stddev = stddev )\n )\n )\n self.pattern2_bias.append(\n tf.Variable(\n tf.truncated_normal( [n_pattern], stddev = stddev )\n )\n )\n\n del stddev\n\n # parameters that need calculation for the cost function\n if hope_out > 0:\n self.param.append( self.U )\n self.param.append( self.char_embedding )\n self.param.append( self.conv_embedding )\n self.param.append( self.bigram_embedding )\n self.param.extend( self.kernels )\n self.param.extend( self.kernel_bias )\n self.param.extend( self.shared_layer_weights )\n self.param.extend( self.shared_layer_b )\n\n if n_pattern > 0:\n self.param.extend( self.pattern1 )\n self.param.extend( self.pattern2 )\n self.param.extend( self.pattern1_bias )\n self.param.extend( self.pattern2_bias )\n\n self.ontonotes_param = self.param[:]\n self.conll_param = self.param[:]\n self.kbp_param = self.param[:]\n\n self.conll_param.append( self.ner_embedding_conll )\n self.conll_param.extend(self.conll_layer_weights)\n self.conll_param.extend(self.conll_layer_b)\n\n self.ontonotes_param.append( self.ner_embedding_ontonotes )\n self.ontonotes_param.extend(self.ontonotes_layer_weights)\n self.ontonotes_param.extend(self.ontonotes_layer_b)\n\n self.kbp_param.append( self.ner_embedding_kbp )\n self.kbp_param.extend(self.kbp_layer_weights)\n self.kbp_param.extend(self.kbp_layer_b)\n \n # add KBP later\n\n logger.info( 'variable defined' )\n\n ################################################################################\n\n char_cube = tf.expand_dims( tf.gather( self.conv_embedding, self.char_idx ), 3 )\n\n # char-level CNN\n char_conv = [ tf.reduce_max( tf.nn.tanh( tf.nn.conv2d( char_cube, \n kk, \n [1, 1, 1, 1], \n 'VALID' ) + bb ),\n reduction_indices = [1, 2] ) \\\n for kk,bb in zip( self.kernels, self.kernel_bias) ]\n\n ###########################\n ### WORD-LEVEL FEATURES ###\n ###########################\n\n # case insensitive excluding fragment\n lw1 = tf.SparseTensor( self.lw1_indices, self.lw1_values, self.shape1 )\n rw1 = tf.SparseTensor( self.rw1_indices, self.rw1_values, self.shape1 )\n\n # case insensitive including fragment\n lw2 = tf.SparseTensor( self.lw2_indices, self.lw2_values, self.shape1 )\n rw2 = tf.SparseTensor( self.rw2_indices, self.rw2_values, self.shape1 )\n\n # case insensitive bow fragment\n bow1 = tf.SparseTensor( self.bow1_indices, self.bow1_values, self.shape1 )\n\n # CASE SENSITIVE\n # --------------\n # case sensitive excluding fragment\n lw3 = tf.SparseTensor( self.lw3_indices, self.lw3_values, self.shape2 )\n rw3 = tf.SparseTensor( self.rw3_indices, self.rw3_values, self.shape2 )\n\n # case sensitive including fragment\n lw4 = tf.SparseTensor( self.lw4_indices, self.lw4_values, self.shape2 )\n rw4 = tf.SparseTensor( self.rw4_indices, self.rw4_values, self.shape2 )\n\n # case sensitive bow fragment\n bow2 = tf.SparseTensor( self.bow2_indices, self.bow2_values, self.shape2 )\n\n # left and right bigram context\n lbc = tf.SparseTensor( self.lbc_indices, self.lbc_values, self.shape3 )\n rbc = tf.SparseTensor( self.rbc_indices, self.rbc_values, self.shape3 )\n\n if n_pattern > 0:\n def sparse_fofe( fofe, pattern, pattern_bias ):\n indices_f32 = tf.to_float( fofe.indices )\n # n_pattern * n_example\n sp_w = tf.transpose(\n # tf.nn.relu( \n tf.nn.softmax(\n tf.sparse_tensor_dense_matmul( \n fofe, pattern, adjoint_b = True,\n name = 'sparse-weight' )\n + pattern_bias\n )\n )\n # replicate the indices\n indices_rep = tf.tile( indices_f32, [n_pattern, 1] )\n # add n_pattern as highest dimension\n nnz = tf.to_int64( tf.shape(fofe.indices)[0] )\n indices_high = tf.to_float(\n tf.reshape(\n tf.range( n_pattern * nnz) / nnz,\n [-1, 1]\n )\n )\n # effectively n_pattern * n_example * n_word\n indices_ext = tf.concat( [ indices_high, indices_rep ], 1 )\n # pattern * fofe\n values_ext = tf.multiply( \n tf.tile( fofe.values, [n_pattern] ),\n tf.gather_nd( \n pattern,\n tf.to_int64(\n tf.concat( [ indices_ext[:,0:1], indices_ext[:,2:3] ], 1 )\n )\n )\n )\n # re-weight by pattern importance\n values_ext_2d = tf.multiply(\n values_ext,\n tf.gather_nd( sp_w, tf.to_int64(indices_ext[:,0:2]) )\n )\n values_att = tf.reduce_sum( tf.reshape( values_ext_2d, [n_pattern, -1] ), 0 )\n # re-group it as a SparseTensor\n return tf.SparseTensor( fofe.indices, values_att, fofe.dense_shape )\n\n lw1 = sparse_fofe( lw1, self.pattern1[0], self.pattern1_bias[0] )\n rw1 = sparse_fofe( rw1, self.pattern1[1], self.pattern1_bias[1] )\n lw2 = sparse_fofe( lw2, self.pattern1[2], self.pattern2_bias[2] )\n rw2 = sparse_fofe( rw2, self.pattern1[3], self.pattern2_bias[3] )\n\n lw3 = sparse_fofe( lw3, self.pattern2[0], self.pattern2_bias[0] )\n rw3 = sparse_fofe( rw3, self.pattern2[1], self.pattern2_bias[1] )\n lw4 = sparse_fofe( lw4, self.pattern2[2], self.pattern2_bias[2] )\n rw4 = sparse_fofe( rw4, self.pattern2[3], self.pattern2_bias[3] )\n\n # all sparse feature after projection\n\n # case-insensitive in English / word embedding in Chinese\n # case-insensitive bfofe with candidate word(s)\n\n # 1st layer: word embedding, char embedding, ner embedding\n lwp1 = tf.sparse_tensor_dense_matmul( lw1, self.word_embedding_1,\n name = 'emb1-left-fofe-excl-proj' )\n rwp1 = tf.sparse_tensor_dense_matmul( rw1, self.word_embedding_1,\n name = 'emb1-right-fofe-excl-proj' )\n\n # case-insensitive bfofe without candidate word(s)\n lwp2 = tf.sparse_tensor_dense_matmul( lw2, self.word_embedding_1,\n name = 'emb1-left-fofe-incl-proj' )\n rwp2 = tf.sparse_tensor_dense_matmul( rw2, self.word_embedding_1,\n name = 'emb1-right-fofe-incl-proj' )\n\n # case-insensitive bag-of-words\n bowp1 = tf.sparse_tensor_dense_matmul( bow1, self.word_embedding_1 )\n\n # case-sensitive in English / character embedding in Chinese\n # case-sensitive bfofe with candidate word(s)\n lwp3 = tf.sparse_tensor_dense_matmul( lw3, self.word_embedding_2,\n name = 'emb2-left-fofe-excl-proj' )\n rwp3 = tf.sparse_tensor_dense_matmul( rw3, self.word_embedding_2,\n name = 'emb2-right-fofe-excl-proj' )\n\n # case-sensitive bfofe without candidate word(s)\n lwp4 = tf.sparse_tensor_dense_matmul( lw4, self.word_embedding_2,\n name = 'emb2-left-fofe-incl-proj' )\n rwp4 = tf.sparse_tensor_dense_matmul( rw4, self.word_embedding_2,\n name = 'emb2-right-fofe-incl-proj' )\n\n # case-sensitive bag-of-words\n bowp2 = tf.sparse_tensor_dense_matmul( bow2, self.word_embedding_2 )\n\n # dense features after projection\n # char-level bfofe of candidate word(s)\n lcp = tf.matmul( self.lc_fofe, self.char_embedding )\n rcp = tf.matmul( self.rc_fofe, self.char_embedding )\n \n lip = tf.matmul( self.li_fofe, self.char_embedding )\n rip = tf.matmul( self.ri_fofe, self.char_embedding )\n\n # bigram char-fofe\n lbcp = tf.sparse_tensor_dense_matmul( lbc, self.bigram_embedding )\n rbcp = tf.sparse_tensor_dense_matmul( rbc, self.bigram_embedding )\n\n ner_projection_conll = tf.matmul( self.ner_cls_match_conll, self.ner_embedding_conll )\n ner_projection_ontonotes = tf.matmul( self.ner_cls_match_ontonotes, self.ner_embedding_ontonotes )\n ner_projection_kbp = tf.matmul(self.ner_cls_match_kbp, self.ner_embedding_kbp)\n\n # all possible features\n feature_list = [ [lwp1, rwp1], [lwp2, rwp2], [bowp1],\n [lwp3, rwp3], [lwp4, rwp4], [bowp2],\n [lcp, rcp], [lip, rip], [ner_projection_conll, ner_projection_ontonotes, ner_projection_kbp],\n char_conv, [lbcp, rbcp] ]\n\n # divide up the used and unused features\n used, not_used = [], [] \n\n # decide what feature to use\n for ith, f in enumerate( feature_list ):\n if (1 << ith) & feature_choice > 0: \n used.extend( f )\n else:\n not_used.extend( f )\n\n # only use the features requested for use\n feature_list = used #+ not_used\n\n # a tensor containing all the feature vectors\n # 2nd layer: concatenate\n feature = tf.concat( feature_list, 1 )\n\n if hope_out > 0:\n hope = tf.matmul( feature, self.U )\n shared_layer_output = [ hope ]\n else:\n # layer 1 and 2\n shared_layer_output = [ tf.nn.dropout( feature, self.keep_prob ) ]\n\n #=======================\n #==== Shared layers ====\n #=======================\n\n # calculate the output by multiplying the input by the weights\n # use ReLU as an activation function\n # 3rd layer to 11th layer: linear, relu, dropout\n for i in xrange( len(self.shared_layer_weights) ):\n # linear layer (also 12th layer: linear)\n shared_layer_output.append( tf.matmul( shared_layer_output[-1], self.shared_layer_weights[i] ) + self.shared_layer_b[i] )\n # ReLU layer\n shared_layer_output[-1] = tf.nn.relu(shared_layer_output[-1] )\n # Dropout layer\n shared_layer_output[-1] = tf.nn.dropout(shared_layer_output[-1], self.keep_prob )\n\n conll_layer_output = [shared_layer_output[-1]]\n ontonotes_layer_output = [shared_layer_output[-1]]\n kbp_layer_output = [shared_layer_output[-1]]\n\n #============================\n #==== OntoNotes layers ======\n #============================\n\n for i in xrange(len(self.ontonotes_layer_weights)):\n ontonotes_layer_output.append( tf.matmul( ontonotes_layer_output[-1], self.ontonotes_layer_weights[i] ) + self.ontonotes_layer_b[i] )\n if i < len(self.ontonotes_layer_weights) - 1:\n # ReLU layer\n ontonotes_layer_output[-1] = tf.nn.relu(ontonotes_layer_output[-1] )\n if i < len(self.ontonotes_layer_weights) - 2:\n # Dropout layer\n ontonotes_layer_output[-1] = tf.nn.dropout(ontonotes_layer_output[-1], self.keep_prob )\n\n #=============================\n #==== CoNLL 2003 layers ======\n #=============================\n\n for i in xrange(len(self.conll_layer_weights)):\n conll_layer_output.append( tf.matmul(conll_layer_output[-1], self.conll_layer_weights[i] ) + self.conll_layer_b[i] )\n if i < len(self.conll_layer_weights) - 1:\n # ReLU layer\n conll_layer_output[-1] = tf.nn.relu(conll_layer_output[-1] )\n if i < len(self.conll_layer_weights) - 2:\n # Dropout layer\n conll_layer_output[-1] = tf.nn.dropout(conll_layer_output[-1], self.keep_prob )\n\n #===========================\n #==== KBP 2003 layers ======\n #===========================\n\n for i in xrange(len(self.kbp_layer_weights)):\n kbp_layer_output.append(tf.matmul(kbp_layer_output[-1], self.kbp_layer_weights[i]) + self.kbp_layer_b[i])\n # ReLU layer\n if i < len(self.kbp_layer_weights) - 1:\n kbp_layer_output[-1] = tf.nn.relu(kbp_layer_output[-1])\n # Dropout layer\n if i < len(self.kbp_layer_weights) - 2:\n kbp_layer_output[-1] = tf.nn.dropout(kbp_layer_output[-1], self.keep_prob)\n\n #===========================\n\n # 13th layer: log_softmax\n self.ontonotes_xent = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( \n logits = ontonotes_layer_output[-1], labels = self.label ) )\n\n self.conll_xent = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( \n logits = conll_layer_output[-1], labels = self.label ) )\n\n self.kbp_xent = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( \n logits = kbp_layer_output[-1], labels = self.label ) )\n\n if config.l1 > 0:\n # self.param contains weights, bias, character conv embedding variables etc\n for param in self.ontonotes_param:\n self.ontonotes_xent = self.ontonotes_xent + config.l1 * tf.reduce_sum( tf.abs( param ) )\n\n for param in self.conll_param:\n self.conll_xent = self.conll_xent + config.l1 * tf.reduce_sum( tf.abs( param ) )\n\n for param in self.kbp_param:\n self.kbp_xent = self.kbp_xent + config.l1 * tf.reduce_sum( tf.abs( param ) )\n\n if config.l2 > 0:\n for param in self.ontonotes_param:\n self.ontonotes_xent = self.ontonotes_xent + config.l2 * tf.nn.l2_loss( param )\n\n for param in self.conll_param:\n self.conll_xent = self.conll_xent + config.l2 * tf.nn.l2_loss( param )\n\n for param in self.kbp_param:\n self.kbp_xent = self.kbp_xent + config.l2 * tf.nn.l2_loss( param )\n\n self.ontonotes_predicted_values = tf.nn.softmax( ontonotes_layer_output[-1] )\n _, top_ontonotes_indices = tf.nn.top_k( self.ontonotes_predicted_values )\n self.ontonotes_predicted_indices = tf.reshape( top_ontonotes_indices, [-1] )\n\n self.conll_predicted_values = tf.nn.softmax( conll_layer_output[-1] )\n _, top_conll_indices = tf.nn.top_k( self.conll_predicted_values )\n self.conll_predicted_indices = tf.reshape( top_conll_indices, [-1] )\n\n self.kbp_predicted_values = tf.nn.softmax( kbp_layer_output[-1] )\n _, top_kbp_indices = tf.nn.top_k( self.kbp_predicted_values )\n self.kbp_predicted_indices = tf.reshape( top_kbp_indices, [-1] )\n\n varlist = self.shared_layer_weights + self.shared_layer_b\n # add KBP later\n\n # fully connected layers are must-trained layers\n # Want to change the weights and bias terms only for minimization of cross entropy \n # cost function\n ontonotes_varlist = varlist + self.ontonotes_layer_weights + self.ontonotes_layer_b\n ontonotes_fully_connected_train_step = tf.train.MomentumOptimizer( self.lr, \n self.config.momentum, \n use_locking = False ) \\\n .minimize(self.ontonotes_xent, var_list = ontonotes_varlist)\n\n conll_varlist = varlist + self.conll_layer_weights + self.conll_layer_b\n conll_fully_connected_train_step = tf.train.MomentumOptimizer(self.lr,\n self.config.momentum,\n use_locking = False) \\\n .minimize(self.conll_xent, var_list = conll_varlist)\n\n kbp_varlist = varlist + self.kbp_layer_weights + self.kbp_layer_b\n kbp_fully_connected_train_step = tf.train.MomentumOptimizer(self.lr,\n self.config.momentum,\n use_locking = False) \\\n .minimize(self.kbp_xent, var_list = kbp_varlist)\n\n\n # a list of things to train\n self.conll_train_step = [ conll_fully_connected_train_step ]\n self.ontonotes_train_step = [ ontonotes_fully_connected_train_step ]\n self.kbp_train_step = [kbp_fully_connected_train_step]\n if n_pattern > 0:\n __lambda = 0.001\n self.xentPlusSparse = self.xent\n # L1-norm, not working\n # for i in xrange(4):\n # self.xentPlusSparse += __lambda * tf.reduce_sum( tf.abs( self.pattern1[i] ) )\n # self.xentPlusSparse += __lambda * tf.reduce_sum( tf.abs( self.pattern2[i] ) )\n \n # orthogonality\n for p in self.pattern1 + self.pattern2:\n self.xentPlusSparse += tf.reduce_sum(\n tf.abs(\n tf.matmul( p, p, \n transpose_a = False,\n transpose_b = True ) \n - tf.eye( n_pattern )\n )\n ) * __lambda\n sparse_fofe_step = tf.train.GradientDescentOptimizer(\n self.lr,\n use_locking = True\n ).minimize( \n self.xentPlusSparse,\n var_list = self.pattern1 + self.pattern2 +\n self.pattern1_bias +\n self.pattern2_bias\n )\n self.train_step.append( sparse_fofe_step )\n\n # train the word embedding for insensitive case\n if feature_choice & 0b111 > 0:\n # returns an Operation that updates the variables in var_list.\n conll_insensitive_train_step = tf.train.GradientDescentOptimizer( self.lr / 4, \n use_locking = True ) \\\n .minimize( self.conll_xent, var_list = [ self.word_embedding_1 ] )\n ontonotes_insensitive_train_step = tf.train.GradientDescentOptimizer( self.lr / 4, \n use_locking = True ) \\\n .minimize( self.ontonotes_xent, var_list = [ self.word_embedding_1 ] )\n\n kbp_insensitive_train_step = tf.train.GradientDescentOptimizer( self.lr / 4, \n use_locking = True ) \\\n .minimize( self.kbp_xent, var_list = [ self.word_embedding_1 ] )\n\n self.conll_train_step.append( conll_insensitive_train_step )\n self.ontonotes_train_step.append( ontonotes_insensitive_train_step )\n self.kbp_train_step.append( kbp_insensitive_train_step )\n\n # train the word embedding for sensitive case\n if feature_choice & (0b111 << 3) > 0:\n conll_sensitive_train_step = tf.train.GradientDescentOptimizer( self.lr / 4, \n use_locking = True ) \\\n .minimize( self.conll_xent, var_list = [ self.word_embedding_2 ] )\n ontonotes_sensitive_train_step = tf.train.GradientDescentOptimizer( self.lr / 4, \n use_locking = True ) \\\n .minimize( self.ontonotes_xent, var_list = [ self.word_embedding_2 ] )\n\n kbp_sensitive_train_step = tf.train.GradientDescentOptimizer(self.lr / 4, \n use_locking = True) \\\n .minimize( self.kbp_xent, var_list = [ self.word_embedding_2 ] )\n\n self.conll_train_step.append( conll_sensitive_train_step )\n self.ontonotes_train_step.append( ontonotes_sensitive_train_step )\n self.kbp_train_step.append(kbp_sensitive_train_step)\n\n # train the char embedding for insensitive case\n if feature_choice & (0b11 << 6) > 0:\n conll_char_embedding_train_step = tf.train.GradientDescentOptimizer( self.lr / 2, \n use_locking = True ) \\\n .minimize( self.conll_xent, var_list = [ self.char_embedding ] )\n ontonotes_char_embedding_train_step = tf.train.GradientDescentOptimizer( self.lr / 2, \n use_locking = True ) \\\n .minimize( self.ontonotes_xent, var_list = [ self.char_embedding ] )\n kbp_char_embedding_train_step = tf.train.GradientDescentOptimizer(self.lr / 2,\n use_locking = True) \\\n .minimize(self.kbp_xent, var_list = [self.char_embedding])\n\n self.conll_train_step.append( conll_char_embedding_train_step )\n self.ontonotes_train_step.append( ontonotes_char_embedding_train_step )\n self.kbp_train_step.append(kbp_char_embedding_train_step)\n\n # train the NER embedding\n if feature_choice & (1 << 8) > 0:\n conll_ner_embedding_train_step = tf.train.GradientDescentOptimizer( self.lr, \n use_locking = True ) \\\n .minimize( self.conll_xent, var_list = [ self.ner_embedding_conll ] )\n ontonotes_ner_embedding_train_step = tf.train.GradientDescentOptimizer( self.lr, \n use_locking = True ) \\\n .minimize( self.ontonotes_xent, var_list = [ self.ner_embedding_ontonotes ] )\n kbp_ner_embedding_train_step = tf.train.GradientDescentOptimizer(self.lr,\n use_locking = True) \\\n .minimize(self.kbp_xent, var_list = [self.ner_embedding_kbp])\n\n self.conll_train_step.append( conll_ner_embedding_train_step )\n self.ontonotes_train_step.append( ontonotes_ner_embedding_train_step )\n self.kbp_train_step.append(kbp_ner_embedding_train_step)\n\n if feature_choice & (1 << 9) > 0:\n conll_char_conv_train_step = tf.train.MomentumOptimizer( self.lr, momentum )\\\n .minimize( self.conll_xent, \n var_list = [ self.conv_embedding ] + \\\n self.kernels + self.kernel_bias )\n ontonotes_char_conv_train_step = tf.train.MomentumOptimizer( self.lr, momentum )\\\n .minimize( self.ontonotes_xent, \n var_list = [ self.conv_embedding ] + \\\n self.kernels + self.kernel_bias )\n kbp_char_conv_train_step = tf.train.MomentumOptimizer(self.lr, momentum) \\\n .minimize(self.kbp_xent, var_list = [self.conv_embedding] + \\\n self.kernels + self.kernel_bias)\n\n self.conll_train_step.append( conll_char_conv_train_step )\n self.ontonotes_train_step.append( ontonotes_char_conv_train_step )\n self.kbp_train_step.append(kbp_char_conv_train_step)\n\n if feature_choice & (1 << 10) > 0:\n conll_bigram_train_step = tf.train.GradientDescentOptimizer( self.lr / 2, use_locking = True )\\\n .minimize( self.conll_xent, var_list = [ self.bigram_embedding ] )\n ontonotes_bigram_train_step = tf.train.GradientDescentOptimizer( self.lr / 2, use_locking = True )\\\n .minimize( self.ontonotes_xent, var_list = [ self.bigram_embedding ] )\n kbp_bigram_train_step = tf.train.GradientDescentOptimizer(self.lr / 2, use_locking = True) \\\n .minimize(self.kbp_xent, var_list = [self.bigram_embedding])\n self.conll_train_step.append( conll_bigram_train_step )\n self.ontonotes_train_step.append( ontonotes_bigram_train_step )\n self.kbp_train_step.append(kbp_bigram_train_step)\n\n if hope_out > 0:\n __lambda = 0.001\n orthogonal_penalty = tf.reduce_sum(\n tf.abs(\n tf.matmul( self.U, self.U, transpose_a = True ) - tf.eye(hope_out)\n ) \n ) * __lambda\n U_train_step_1 = tf.train.GradientDescentOptimizer(self.lr, use_locking = True) \\\n .minimize( orthogonal_penalty , var_list = [ self.U ] )\n U_train_step_2 = tf.train.MomentumOptimizer( self.lr, momentum, use_locking = True ) \\\n .minimize( self.xent, var_list = [ self.U ] )\n self.train_step.append( U_train_step_1 )\n self.train_step.append( U_train_step_2 )\n\n logger.info( 'computational graph built\\n' )\n\n with self.graph.as_default():\n self.session.run( tf.global_variables_initializer() )\n # self.session.run( tf.variables_initializer( self.param ) )\n self.saver = tf.train.Saver()\n\n\n def train( self, mini_batch, curr_task, profile = False ):\n \"\"\"\n Parameters\n ----------\n mini_batch : tuple\n dataset: 0 - CoNLL2003 \n 1 - OntoNotes \n 2 - KBP\n\n Returns\n -------\n c : float\n \"\"\" \n l1_values, r1_values, l1_indices, r1_indices, \\\n l2_values, r2_values, l2_indices, r2_indices, \\\n bow1i, \\\n l3_values, r3_values, l3_indices, r3_indices, \\\n l4_values, r4_values, l4_indices, r4_indices, \\\n bow2i, \\\n dense_feature,\\\n conv_idx,\\\n l5_values, l5_indices, r5_values, r5_indices, \\\n target = mini_batch\n\n if not self.config.strictly_one_hot:\n dense_feature[:,-1] = 0\n\n if profile:\n options = tf.RunOptions( trace_level = tf.RunOptions.FULL_TRACE )\n run_metadata = tf.RunMetadata()\n else:\n options, run_metadata = None, None\n\n if curr_task.batch_num == 0:\n train = self.conll_train_step + [self.conll_xent]\n ner_cls_match_conll = dense_feature[:,512:]\n ner_cls_match_ontonotes = numpy.zeros((512, 19))\n ner_cls_match_kbp = numpy.zeros((512, 11))\n elif curr_task.batch_num == 1:\n train = self.ontonotes_train_step + [self.ontonotes_xent]\n ner_cls_match_conll = numpy.zeros((512, 5))\n ner_cls_match_ontonotes = dense_feature[:,512:]\n ner_cls_match_kbp = numpy.zeros((512, 11))\n else: \n train = self.kbp_train_step + [self.kbp_xent]\n ner_cls_match_conll = numpy.zeros((512, 5))\n ner_cls_match_ontonotes = numpy.zeros((512, 19))\n ner_cls_match_kbp = dense_feature[:,512:]\n\n c = self.session.run( \n train,\n feed_dict = { self.lw1_values: l1_values,\n self.lw1_indices: l1_indices,\n self.rw1_values: r1_values,\n self.rw1_indices: r1_indices,\n self.lw2_values: l2_values,\n self.lw2_indices: l2_indices,\n self.rw2_values: r2_values,\n self.rw2_indices: r2_indices,\n self.bow1_indices: bow1i,\n self.bow1_values: numpy.ones( bow1i.shape[0], dtype = numpy.float32 ),\n self.lw3_values: l3_values,\n self.lw3_indices: l3_indices,\n self.rw3_values: r3_values,\n self.rw3_indices: r3_indices,\n self.lw4_values: l4_values,\n self.lw4_indices: l4_indices,\n self.rw4_values: r4_values,\n self.rw4_indices: r4_indices,\n self.bow2_indices: bow2i,\n self.bow2_values: numpy.ones( bow2i.shape[0], dtype = numpy.float32 ),\n self.shape1: (target.shape[0], self.n_word1),\n self.shape2: (target.shape[0], self.n_word2),\n self.lc_fofe: dense_feature[:,:128],\n self.rc_fofe: dense_feature[:,128:256],\n self.li_fofe: dense_feature[:,256:384],\n self.ri_fofe: dense_feature[:,384:512],\n self.ner_cls_match_conll: ner_cls_match_conll,\n self.ner_cls_match_ontonotes: ner_cls_match_ontonotes,\n self.ner_cls_match_kbp: ner_cls_match_kbp,\n self.char_idx: conv_idx,\n self.lbc_values : l5_values,\n self.lbc_indices : l5_indices,\n self.rbc_values : r5_values,\n self.rbc_indices : r5_indices,\n self.shape3 : (target.shape[0], 96 * 96),\n self.label: target,\n self.lr: curr_task.lr,\n self.keep_prob: 1 - self.config.drop_rate },\n options = options, \n run_metadata = run_metadata\n )[-1]\n\n if profile:\n tf.contrib.tfprof.model_analyzer.print_model_analysis(\n self.graph,\n run_meta = run_metadata,\n tfprof_options = tf.contrib.tfprof.model_analyzer.PRINT_ALL_TIMING_MEMORY\n )\n\n return c\n \n\n def eval( self, mini_batch, curr_task ):\n \"\"\"\n Parameters\n ----------\n mini_batch : tuple\n\n Returns:\n c : float\n pi : numpy.ndarray\n pv : numpy.ndarray\n \"\"\"\n l1_values, r1_values, l1_indices, r1_indices, \\\n l2_values, r2_values, l2_indices, r2_indices, \\\n bow1i, \\\n l3_values, r3_values, l3_indices, r3_indices, \\\n l4_values, r4_values, l4_indices, r4_indices, \\\n bow2i, \\\n dense_feature,\\\n conv_idx,\\\n l5_values, l5_indices, r5_values, r5_indices, \\\n target = mini_batch\n\n if not self.config.strictly_one_hot:\n dense_feature[:,-1] = 0\n\n if curr_task.batch_num == 0:\n train = [self.conll_xent, self.conll_predicted_indices, self.conll_predicted_values]\n ner_cls_match_conll = dense_feature[:,512:]\n ner_cls_match_ontonotes = numpy.zeros((512, 19))\n ner_cls_match_kbp = numpy.zeros((512, 11))\n elif curr_task.batch_num == 1:\n train = [self.ontonotes_xent, self.ontonotes_predicted_indices, self.ontonotes_predicted_values]\n ner_cls_match_conll = numpy.zeros((512, 5))\n ner_cls_match_ontonotes = dense_feature[:,512:]\n ner_cls_match_kbp = numpy.zeros((512, 11))\n else:\n train = [self.kbp_xent, self.kbp_predicted_indices, self.kbp_predicted_values]\n ner_cls_match_conll = numpy.zeros((512, 5))\n ner_cls_match_ontonotes = numpy.zeros((512, 19))\n ner_cls_match_kbp = dense_feature[:,512:]\n\n\n c, pi, pv = self.session.run( train, \n feed_dict = { self.lw1_values: l1_values,\n self.lw1_indices: l1_indices,\n self.rw1_values: r1_values,\n self.rw1_indices: r1_indices,\n self.lw2_values: l2_values,\n self.lw2_indices: l2_indices,\n self.rw2_values: r2_values,\n self.rw2_indices: r2_indices,\n self.bow1_indices: bow1i,\n self.bow1_values: numpy.ones( bow1i.shape[0], dtype = numpy.float32 ),\n self.lw3_values: l3_values,\n self.lw3_indices: l3_indices,\n self.rw3_values: r3_values,\n self.rw3_indices: r3_indices,\n self.lw4_values: l4_values,\n self.lw4_indices: l4_indices,\n self.rw4_values: r4_values,\n self.rw4_indices: r4_indices,\n self.bow2_indices: bow2i,\n self.bow2_values: numpy.ones( bow2i.shape[0], dtype = numpy.float32 ),\n self.shape1: (target.shape[0], self.n_word1),\n self.shape2: (target.shape[0], self.n_word2),\n self.lc_fofe: dense_feature[:,:128],\n self.rc_fofe: dense_feature[:,128:256],\n self.li_fofe: dense_feature[:,256:384],\n self.ri_fofe: dense_feature[:,384:512],\n self.ner_cls_match_conll: ner_cls_match_conll,\n self.ner_cls_match_ontonotes: ner_cls_match_ontonotes,\n self.ner_cls_match_kbp : ner_cls_match_kbp,\n self.char_idx: conv_idx,\n self.lbc_values : l5_values,\n self.lbc_indices : l5_indices,\n self.rbc_values : r5_values,\n self.rbc_indices : r5_indices,\n self.shape3 : (target.shape[0], 96 * 96),\n self.label: target,\n self.keep_prob: 1 } ) \n\n return c, pi, pv\n\n def tofile( self, filename ):\n \"\"\"\n Parameters\n ----------\n filename : str\n The current model will be stored in basename.{tf,config}\n \"\"\"\n self.saver.save( self.session, filename )\n with open( filename + '.config', 'wb' ) as fp:\n cPickle.dump( self.config, fp )\n\n\n def fromfile( self, filename ):\n \"\"\"\n filename : str\n The current model will be restored from basename.{tf,config}\n \"\"\"\n self.saver.restore( self.session, filename )\n\n\n def __del__( self ):\n self.session.close()\n\n########################################################################\n\n","sub_path":"multi_fofe_mention_net.py","file_name":"multi_fofe_mention_net.py","file_ext":"py","file_size_in_byte":69121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"423150409","text":"##############################################################################\n# Assignment: Homework #06 (Exercise 4)\n# Class Section: Wednesday, 6:30, ARMS 1010\n# Description: This program accepts 10 numbers from the user to store in a list\n# and determines the statistics of minimum, maximum, total, and average of the numbers\n# Programmers: Oluwatosin Ogunjobi oogunjob@purdue.edu\n#############################################################################\n\nimport statistics # imports statistics library to use the mean function\n\ndef findTotal(numbers):\n total = 0 # initializes total as 0\n \n # finds the sum of the list\n for count in range(len(numbers)):\n total += numbers[count]\n \n return total # returns the total of the list\n\ndef main():\n numbers = [0] * 10 # initializes list of numbers\n \n # loop that allows user to enter the numbers\n for count in range(len(numbers)):\n numbers[count] = float(input(\"Enter number %d of 10: \" % (count + 1)))\n \n print() # prints space between input and output\n \n minimum = min(numbers) # finds minimum number in list\n maximum = max(numbers) # finds maximum number in list\n \n print(\"Lowest number: %.2f\" % minimum)\n print(\"Highest number: %.2f\" % maximum)\n \n total = findTotal(numbers) # finds total amount from the list\n \n print(\"Total: %.2f\" % total)\n \n average = statistics.mean(numbers) # finds the average of the list\n\n print(\"Average: %.2f\" % average)\n\nmain()\n","sub_path":"week6/hw06_4.py","file_name":"hw06_4.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"258934131","text":"from django.conf.urls import patterns, url\n\nfrom .views import IndexView, CreateView, AddRuleView, DetailView, DeleteRuleView\n\nurlpatterns = patterns('',\n url(r'^$', IndexView.as_view(), name='index'),\n url(r'^create/$', CreateView.as_view(), name='create'),\n url(r'^(?P[^/]+)/add_rule/$', \n AddRuleView.as_view(),name='add_rule'),\n url(r'^(?P[^/]+)$',\n DetailView.as_view(),name='detail'),\n url(r'^(?P[^/]+)/delete_rule/$', DeleteRuleView.as_view(),\n name='delete_rule'),\n )\n\n","sub_path":"amazon/securitygroups/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"414781991","text":"\"\"\"Repeating a beat in a loop.\"\"\"\n\n__author__ = \"730240245\"\n\n\n# Begin your solution here... \ncounter: int = 0 \nrepeat: str = input(\"What beat do you want to repeat? \")\nmaximum: int = int(input(\"How many times do you want to repeat it? \"))\nwhile maximum > counter:\n times: str = (str(\" \" + repeat) * (maximum - 1))\n print(repeat + times)\n counter = maximum\nif maximum <= 0: \n print(\"No beat...\")\n\n\n ","sub_path":"exercises/ex02/repeat_beat.py","file_name":"repeat_beat.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"532996340","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.validators import RegexValidator\n\n\nREGEX_ONLY_LETTERS = '^[a-zA-Z ]+$'\nONLY_LETTERS_MESSAGE = 'Solo se permiten caracteres en este campo'\n\n\nclass UserCreate(models.Model):\n \"\"\"Creator.\"\"\"\n\n user_create = models.ForeignKey(User, help_text='Usuario que crea el registro', on_delete=models.PROTECT)\n\n class Meta:\n abstract = True\n\n\nclass TimeStamp(models.Model):\n \"\"\"Basic data.\"\"\"\n\n created = models.DateTimeField(auto_now_add=True, null=True, help_text=\"Fecha de creacion\")\n modified = models.DateTimeField(auto_now=True, null=True, help_text=\"Fecha de modificacion\")\n\n class Meta:\n abstract = True\n\n\nclass Active(models.Model):\n \"\"\"Status of the record\"\"\"\n\n active = models.BooleanField(default=True)\n\n class Meta:\n abstract = True\n\n\nclass Person(models.Model):\n \"\"\"Person Basic data.\"\"\"\n\n first_name = models.CharField(max_length=50, help_text=\"Nombre de la persona\",\n validators=[\n RegexValidator(\n regex = REGEX_ONLY_LETTERS,\n message = ONLY_LETTERS_MESSAGE\n )\n \n ])\n last_name = models.CharField(max_length=50, help_text=\"Apellido de la persona\",\n validators=[\n RegexValidator(\n regex = REGEX_ONLY_LETTERS,\n message = ONLY_LETTERS_MESSAGE\n )\n \n ])\n email = models.EmailField(help_text=\"Email de la persona\")\n\n\n class Meta:\n abstract = True\n\n\n","sub_path":"apps/help/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"556513694","text":"# coding: utf-8\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nimport numpy as np\nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\n\n##############################\n# 指定した複数銘柄の決算情報を取得する\n##############################\ndef get_financial_infos(codes):\n \"\"\" 指定した複数銘柄の決算情報を取得する。\n \n Args:\n codes (dict) : 証券コードと名称のディクショナリ\n (ex){'JR東日本':9020, 'JR西日本': 9021}\n Returns:\n DataFrame : 取得した情報を格納したDataFrame\n \"\"\"\n \n whole_df = None\n for name in codes.keys():\n \n # 指定した証券コードの決算情報を取得する。\n code = codes[name]\n df = get_financial_info(code)\n \n # 名称を追加し、MultiIndexにする。\n df['名称'] = name\n df = df.set_index('名称', append=True)\n \n if whole_df is None:\n whole_df = df\n else:\n whole_df = whole_df.append(df)\n \n # 1秒ディレイ\n time.sleep(1)\n \n # indexを入れ替える\n whole_df = whole_df.swaplevel('名称', '決算期').sort_index()\n \n return whole_df\n \n##############################\n# 指定した銘柄の決算情報を取得する\n##############################\ndef get_financial_info(code):\n \"\"\" 指定した銘柄の決算情報を取得する。\n \n Args:\n code (int) : 証券コード\n\n Returns:\n DataFrame : 決算情報を格納したDataFrame\n \"\"\"\n \n # 指定URLのHTMLデータを取得\n url = \"https://minkabu.jp/stock/{0:d}/settlement\".format(code)\n html = requests.get(url)\n \n # BeautifulSoupのHTMLパーサーを生成\n soup = BeautifulSoup(html.content, \"html.parser\")\n \n # 決算情報テーブルを取得する\n fin_df1 = get_financial_table(soup, '決算情報')\n \n # 決算情報から不要データを削る。\n fin_df1 = trim_unnecessary_from_dataframe(fin_df1)\n \n # 財務情報テーブルを取得する\n fin_df2 = get_financial_table(soup, '財務情報')\n \n # 財務情報から不要データを削る。\n fin_df2 = trim_unnecessary_from_dataframe(fin_df2)\n \n # キャッシュフロー情報から不要データを削る。\n cf_df = get_cf_table(soup)\n \n # キャッシュフロー情報から不要データを削る。\n cf_df = trim_unnecessary_from_dataframe(cf_df)\n \n # DataFrameを結合する \n df = pd.concat([fin_df1, fin_df2, cf_df], axis=1)\n \n return df\n \n##############################\n# 指定した名称の要素のデータを抽出する\n##############################\ndef get_financial_table(bs, table_name):\n \"\"\" 指定した名称の
要素のデータを抽出する\n \n Args:\n bs (BeautifulSoup) : 抽出対象HTMLのBeautifulSoupオブジェクト\n table_name (string) : 抽出対象テーブルの名称\n\n Returns:\n DataFrame :
要素を格納したDataFrame\n \"\"\"\n \n # 全
要素を抽出\n table_all = bs.find_all('table')\n \n # 決算情報の
要素を検索する。\n fin_table1 = None\n for table in table_all:\n \n #
要素を取得\n caption = table.find('caption')\n if caption is None:\n continue\n \n # 要素の文字列が目的のものと一致したら終了\n if caption.text == table_name:\n fin_table1 = table\n break\n \n # 要素内のヘッダ情報を取得する。\n headers = []\n thead_th = fin_table1.find('thead').find_all('th')\n for th in thead_th:\n headers.append(th.text)\n \n #
要素内のデータを取得する。\n rows = []\n tbody_tr = fin_table1.find('tbody').find_all('tr')\n for tr in tbody_tr:\n \n # 1行内の全データを格納するためのリスト\n row = []\n \n # 要素内の要素内の
要素を取得する。\n th = tr.find('th')\n row.append(th.text)\n \n #
要素を取得する。\n td_all = tr.find_all('td')\n for td in td_all:\n row.append(td.text)\n \n # 1行のデータを格納したリストを、リストに格納\n rows.append(row)\n \n # DataFrameを生成する\n df = pd.DataFrame(rows, columns=headers)\n df = df.set_index(headers[0]) # 先頭の列(決算期)をインデックスに指定する\n \n return df\n \n##############################\n# キャッシュフロー情報を抽出する\n##############################\ndef get_cf_table(bs):\n \"\"\" キャッシュフロー情報を抽出する\n \n Args:\n bs (BeautifulSoup) : 抽出対象HTMLのBeautifulSoupオブジェクト\n\n Returns:\n DataFrame : 要素を格納したDataFrame\n \"\"\"\n \n # 全
要素を抽出\n table_all = bs.find_all('table')\n \n # キャッシュフロー情報の
要素を検索する。\n cf_table = None\n for table in table_all:\n \n # 要素を取得\n thead = table.find('thead')\n if thead is None:\n continue\n \n # 内の全
要素を取得\n thead_th = thead.find_all('th')\n for th in thead_th:\n if th.text == '営業CF':\n cf_table = table\n break\n \n # 要素内のヘッダ情報を取得する。\n headers = []\n thead_th = cf_table.find('thead').find_all('th')\n for th in thead_th:\n headers.append(th.text)\n \n #
要素内のデータを取得する。\n rows = []\n tbody_tr = cf_table.find('tbody').find('tr').find_all('tr')\n for tr in tbody_tr:\n \n # 1行内の全データを格納するためのリスト\n row = []\n \n # 要素内の要素内の
要素を取得する。\n th = tr.find('th')\n row.append(th.text)\n \n #
要素を取得する。\n td_all = tr.find_all('td')\n for td in td_all:\n row.append(td.text)\n \n # 1行のデータを格納したリストを、リストに格納\n rows.append(row)\n\n # DataFrameを生成する\n df = pd.DataFrame(rows, columns=headers)\n df = df.set_index(headers[0]) # 先頭の列(決算期)をインデックスに指定する\n \n return df\n \n##############################\n# DataFrameから不要なデータを削る。\n##############################\ndef trim_unnecessary_from_dataframe(df):\n \"\"\" DataFrameから不要なデータを削る。\n \n Args:\n df (DataFrame) : データフレーム\n\n Returns:\n DataFrame : 不要データ削除後のDataFrame\n \"\"\"\n \n # 数値のカンマを削除する関数\n def trim_camma(x):\n # 2,946,639.3のようなカンマ区切り、小数点有りの数値か否か確認する\n comma_re = re.search(r\"([+-]?\\d{1,3}(,\\d{3})*(\\.\\d+){0,1})\", x)\n if comma_re:\n value = comma_re.group(1)\n value = value.replace(',', '') # カンマを削除\n return np.float64(value) # 数値に変換\n \n return x\n \n # 各列に対して、trim_cammaを適用する\n new_df = df.copy()\n for col in df.columns:\n new_df[col] = df[col].map(lambda v : trim_camma(v))\n \n # 括弧内の文字列を削除する関数(括弧自体も削除する)\n def remove_inparentheses(s):\n \n # インデックス(決算情報)の括弧内要素を削除する。\n # ex) 決算期(決算発表)\n result = re.search(r\"(.+)(\\(.+\\))\", s)\n if result:\n str = result.group(1)\n return str\n \n return s\n \n # インデックス(決算情報)の括弧内要素を削除する。\n new_df.index.name = remove_inparentheses(new_df.index.name)\n new_df.index = new_df.index.map(lambda s : remove_inparentheses(s))\n \n return new_df\n \n##############################\n# 複数銘柄の決算情報を整形する\n##############################\ndef reshape_financial_info(df):\n \"\"\" 複数銘柄の決算情報を整形する。\n \n Args:\n df (DataFrame) : 複数銘柄の決算情報が格納されたデータフレーム\n\n Returns:\n DataFrame : 整形後のDataFrame\n \"\"\"\n \n # 各銘柄のデータと統計量を結合する。\n new_df = df.copy()\n \n # 売上高(百万円) -> 売上高(十億円)\n # 営業利益(百万円) -> 営業利益(十億円)\n # 経常利益(百万円) -> 経常利益(十億円)\n # 純利益(百万円) -> 純利益(十億円)\n # 総資産(百万円) -> 総資産(十億円)\n # 純資産(百万円) -> 純資産(十億円)\n # 営業CF(百万円) -> 営業CF(十億円)\n # 投資CF(百万円) -> 投資CF(十億円)\n # 財務CF(百万円) -> 財務CF(十億円)\n # 現金期末残高(百万円) -> 現金期末残高(十億円)\n # フリーCF(百万円) -> フリーCF(十億円)\n new_df['売上高'] = new_df['売上高'] / 1.0e+3\n new_df['営業利益'] = new_df['営業利益'] / 1.0e+3\n new_df['経常利益'] = new_df['経常利益'] / 1.0e+3\n new_df['純利益'] = new_df['純利益'] / 1.0e+3\n new_df['総資産'] = new_df['総資産'] / 1.0e+3\n new_df['純資産'] = new_df['純資産'] / 1.0e+3\n new_df['営業CF'] = new_df['営業CF'] / 1.0e+3\n new_df['投資CF'] = new_df['投資CF'] / 1.0e+3\n new_df['財務CF'] = new_df['財務CF'] / 1.0e+3\n new_df['現金期末残高'] = new_df['現金期末残高'] / 1.0e+3\n new_df['フリーCF'] = new_df['フリーCF'] / 1.0e+3\n new_df = new_df.rename(columns={\n '売上高' : '売上高(十億円)', \n '営業利益' : '営業利益(十億円)',\n '経常利益' : '経常利益(十億円)',\n '純利益' : '純利益(十億円)',\n '1株益' : '1株益(円)',\n '1株純資産' : '1株純資産(円)',\n '総資産' : '総資産(十億円)',\n '純資産' : '純資産(十億円)',\n '営業CF' : '営業CF(十億円)',\n '投資CF' : '投資CF(十億円)',\n '財務CF' : '財務CF(十億円)',\n '現金期末残高' : '現金期末残高(十億円)',\n 'フリーCF' : 'フリーCF(十億円)',\n })\n \n return new_df\n \n##################################################\n# 決算情報のうち指定したデータを棒グラフで可視化する\n##################################################\ndef visualize_financial_info_in_bar(df, data_name, filepath):\n \"\"\" 決算情報のうち指定したデータを棒グラフで可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n data_name (string) : 可視化する列名\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # FigureとAxesを取得\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n \n##################################################\n# 決算情報のうち指定した複数データを\n# 折れ線グラフで可視化する\n##################################################\ndef visualize_financial_infos_in_line(df, data_names, filepath, from_zero=False):\n \"\"\" 決算情報のうち指定した複数データを折れ線グラフで可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n data_names (list) : 可視化する列名のリスト\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n data_num = len(data_names)\n \n # サブプロットの行数・列数を決定\n if data_num == 1:\n rows, cols = (1, 1)\n figsize=(6, 4)\n elif data_num == 2:\n rows, cols = (1, 2)\n figsize=(10, 4)\n elif data_num == 3:\n rows, cols = (1, 3)\n figsize=(15, 4)\n elif data_num == 4:\n rows, cols = (2, 2)\n figsize=(10, 8)\n elif data_num <= 6:\n rows, cols = (2, 3)\n figsize=(15, 8)\n elif data_num <= 9:\n rows, cols = (3, 3)\n figsize=(15, 12)\n else:\n rows, cols = (4, 4)\n figsize=(20, 16)\n \n # Figurを取得\n fig = plt.figure(figsize=figsize)\n #fig = plt.figure()\n \n # 指定した全データをデータ別に折れ線グラフで表示する\n for i in range(data_num):\n \n # Axesを取得\n ax = fig.add_subplot(rows, cols, i+1)\n \n # データ名\n data_name = data_names[i]\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # Y軸の表示範囲を設定\n if from_zero:\n ax.set_ylim(ymin=0)\n \n # 不要な余白を削る\n plt.tight_layout()\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n\n##############################\n# 決算情報のうちROEとROAを可視化する\n##############################\ndef visualize_roe_roa(df, filepath):\n \"\"\" 決算情報のうち指定した複数データを可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # 可視化するデータ\n data_names = ['ROE', 'ROA']\n\n # Figurを取得\n fig = plt.figure(figsize=(10, 4))\n\n # 指定した全データをデータ別に折れ線グラフで表示する\n for i, data_name in enumerate(data_names):\n \n # Axesを取得\n ax = fig.add_subplot(1, 2, i+1)\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # 不要な余白を削る\n plt.tight_layout()\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n\n##################################################\n# 決算情報のうち指定した1銘柄の指定データを可視化する\n##################################################\ndef visualize_financial_info_for_specified_brand(df, brand_name, bar_datas, line_datas=None, filepath=None):\n \"\"\" 決算情報のうち指定した1銘柄の指定データを可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n brand_name (string) : 可視化する銘柄の名称\n bar_datas (list) : 棒グラフで可視化する列名のリスト\n line_datas (list) : 折れ線グラフで可視化する列名のリスト\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # 可視化するデータを抽出\n brand_df = df.loc[(brand_name,)] # 指定した銘柄\n fiscal_year = brand_df.index.values # 決��期\n \n # データ数を取得\n num_year = len(fiscal_year) # 可視化する決算期の数\n num_bar_data = len(bar_datas) # 棒グラフで可視化するデータ数\n \n # FigureとAxesを取得\n fig = plt.figure()\n ax1 = fig.add_subplot(1,1,1)\n \n # 色\n color_count = 0\n colors = plt.get_cmap('tab10')\n \n ########################################\n # 棒グラフの可視化処理\n ########################################\n \n # 棒グラフを横並びで表示するためのパラメータ\n width = 0.8 / num_bar_data # 棒グラフの幅\n xpos = np.arange(num_year) # X軸上の位置\n \n # 可視化するデータ数分ループ\n for i, data_name in enumerate(bar_datas):\n \n x = xpos + width * i\n y = brand_df[data_name]\n \n # 棒グラフを表示\n ax1.bar(x, y, width=width, align='center', label=data_name, color=colors(color_count))\n color_count += 1\n \n # X軸の目盛位置を調整し、銘柄名を表示\n offset = width / 2 * (num_bar_data - 1)\n ax1.set(xticks=xpos+offset, xticklabels=fiscal_year)\n \n # Y軸の表示範囲を設定\n ymin, ymax = get_yminmax_financial_info(brand_df, bar_datas)\n ax1.set_ylim(ymin=ymin*1.5, ymax=ymax*1.5)\n \n ########################################\n # 折れ線グラフの可視化処理\n ########################################\n if line_datas is not None:\n \n # 右軸のAxesを取得\n ax2 = ax1.twinx()\n \n # 可視化するデータ数分ループ\n for i, data_name in enumerate(line_datas):\n \n # 折れ線グラフ表示\n y = brand_df[data_name]\n ax2.plot(xpos+offset, y, marker='o', label=data_name, color=colors(color_count))\n color_count += 1\n \n # Y軸の表示範囲を設定\n ymin, ymax = get_yminmax_financial_info(brand_df, line_datas)\n ax2.set_ylim(ymin=ymin*1.3, ymax=ymax*1.3)\n\n # 補助線を描画\n ax1.grid(axis='y', color='gray', ls='--')\n \n # 凡例を表示\n h1, l1 = ax1.get_legend_handles_labels()\n if line_datas is None:\n ax1.legend(h1, l1, loc='upper right')\n else:\n h2, l2 = ax2.get_legend_handles_labels()\n ax1.legend(h1+h2, l1+l2, loc='upper right')\n \n # グラフのタイトルを追加\n plt.title(brand_name)\n\n # グラフを表示\n fig.show()\n \n # グラフをファイルに出力\n if filepath is not None:\n fig.savefig(filepath) \n \n \n##################################################\n# 指定した列を可視化する際のY軸の表示範囲を取得する\n##################################################\ndef get_yminmax_financial_info(df, columns):\n \"\"\" 指定した列を可視化する際のY軸の表示範囲を取得する\n \n Args:\n df (DataFrame) : 複数銘柄の決算情報が格納されたデータフレーム\n columns (list) : 可視化する列\n \n Returns:\n tuple : Y軸の表示範囲を(ymin, ymax)の形で返す\n \"\"\"\n \n # 最大値・最小値を取得\n ymax = df[columns].max().max() \n ymin = df[columns].min().min()\n \n if ymin >= 0:\n return(0, ymax)\n else:\n abs_max = max([abs(ymin), ymax])\n return(-abs_max, abs_max)\n ","sub_path":"01.stock_investment/01.corporate_analysis/stinfo/financial_info.py","file_name":"financial_info.py","file_ext":"py","file_size_in_byte":20897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"195212101","text":"# Данный класс унаследован от класса Player, и отличается тем,\n# что после каждой проверки на выигрыш комбинация игрока\n# меняется, для этого переопределен метод cap_calc базового класса\n# с сохранением прежнего функционала и с добавлением нового\n\nimport player\nclass Change_Player(player.Player):\n def __init__(self,capital,set_player,name,n1,k1,k2):\n super().__init__(capital,set_player,name)\n self.__n1=n1\n self.__k1=k1\n self.__k2=k2\n def cap_calc(self,exset):\n super().cap_calc(exset)\n super().init_random(self.__n1,self.__k1,self.__k2)\n \n","sub_path":"change_player.py","file_name":"change_player.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"12284444","text":"# Copyright (c) 2019 The Boule Developers.\n# Distributed under the terms of the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# This code is part of the Fatiando a Terra project (https://www.fatiando.org)\n#\nr\"\"\"\n.. _normal_gravity:\n\nNormal Gravity\n==============\n\nOne of the main uses for ellipsoids in geodesy and geophysics is the\ncomputation of *normal gravity* (usually represented by :math:`\\gamma`):\n\n Normal gravity is the magnitude of the gradient of the gravity potential\n (gravitational + centrifugal) generated by the ellipsoid.\n\nThe calculation is performed by the :meth:`boule.Ellipsoid.normal_gravity`\nmethod.\nIt implements the closed-form formula of [LiGotze2001]_ which can calculate\nnormal gravity at any latitude and (geometric) height.\n\nAs an example, lets calculate a profile of normal gravity from pole to pole\nat a height of 1000 m using the :ref:`WGS84 ` ellipsoid.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport boule as bl\n\n\nlatitude = np.linspace(-90, 90, 100)\ngamma = bl.WGS84.normal_gravity(latitude, height=1000)\n\nplt.figure(figsize=(8, 5))\nplt.plot(latitude, gamma, \"-k\")\nplt.title(\"WGS84 normal gravity\")\nplt.xlabel(\"latitude\")\nplt.ylabel(\"normal gravity (mGal)\")\nplt.show()\n\n###############################################################################\n# This calculation can be performed for any ellipsoid. For example, here is the\n# normal gravity of the :ref:`Martian ellipsoid `:\n\ngamma_mars = bl.MARS.normal_gravity(latitude, height=1000)\n\nplt.figure(figsize=(8, 5))\nplt.plot(latitude, gamma_mars, \"-k\")\nplt.title(\"Mars normal gravity\")\nplt.xlabel(\"latitude\")\nplt.ylabel(\"normal gravity (mGal)\")\nplt.show()\n\n\n###############################################################################\n# Notice that the overall trend is the same as for the Earth (the Martian\n# ellipsoid is also oblate) but the range of values is different. The mean\n# gravity on Mars is much weaker than on the Earth: around 370,000 mGal or 3.7\n# m/s² when compared to 970,000 mGal or 9.7 m/s².\n","sub_path":"tutorials/normal_gravity.py","file_name":"normal_gravity.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"490206856","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 12 17:14:09 2017\r\n\r\n@author: HP\r\n\"\"\"\r\nimport re\r\nimport hindi_stemmer as hs\r\nimport string\r\nfrom collections import defaultdict\r\n\r\nexclude1 = set([u'।',u'-',u',',u'ॽ',u'॥',u'(',u')',u'.',u'…', u'…', u'०', u'१', u'२', u'३', u'४', u'५', u'६', u'७', u'८', u'९'])\r\nexclude2 = set(string.punctuation)\r\nstopwords=[]\r\nhindi_stop_words = open('hindi_stopwords.txt','r')\r\nfor line in hindi_stop_words:\r\n stopwords.append(line.decode('utf-8').strip('\\n'))\r\n \r\nstopwords = set(stopwords)\r\n\r\nemoji_pattern = re.compile(\r\n u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\r\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\r\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\r\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\r\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\r\n \"+\", flags=re.UNICODE)\r\n\r\n\r\ndef clean_tweet(tweet):\r\n \r\n tweet_new = Remove_AlphaNumeric(tweet)\r\n \r\n \r\n \r\n tweet_new = Remove_Punctuation(tweet_new)\r\n\r\n tweet_new = Remove_stopwords(tweet_new)\r\n \r\n tweet_new = Remove_stem(tweet_new)\r\n\r\n tweet_new = Remove_Emoji(tweet_new)\r\n \r\n return tweet_new\r\n\r\n\r\ndef Remove_AlphaNumeric(tweet):\r\n\r\n tweet_new = re.sub(\"[a-zA-Z0-9@]\",\"\",tweet)\r\n tweet_new = re.sub(\"[\\nEOF]\",\" \",tweet_new)\r\n \r\n return tweet_new\r\n\r\ndef Remove_Emoji(data):\r\n \r\n\r\n if not data:\r\n return data\r\n if not isinstance(data, basestring):\r\n return data\r\n try:\r\n # UCS-4\r\n patt = re.compile(u'([\\U00002600-\\U000027BF])|([\\U0001f300-\\U0001f64F])|([\\U0001f680-\\U0001f6FF])')\r\n except re.error:\r\n # UCS-2\r\n patt = re.compile(u'([\\u2600-\\u27BF])|([\\uD83C][\\uDF00-\\uDFFF])|([\\uD83D][\\uDC00-\\uDE4F])|([\\uD83D][\\uDE80-\\uDEFF])')\r\n return patt.sub('', data)\r\n #remove_emoji(tweet)\r\n\r\n\r\ndef Remove_Punctuation(tweet):\r\n ### Removing punctuations\r\n tweet_new = ''.join(ch for ch in tweet if ch not in exclude1)\r\n tweet_new = ''.join(ch for ch in tweet_new if ch not in exclude2)\r\n return tweet_new\r\n \r\ndef Remove_stopwords(tweet):\r\n tweet_new = \" \".join([i for i in tweet.split() if i not in stopwords])\r\n return tweet_new\r\n\r\ndef Remove_stem(tweet):\r\n tweet_list = tweet.split()\r\n tweet_list = [hs.hi_stem(word) for word in tweet_list]\r\n tweet_new = \" \".join(tweet_list)\r\n return tweet_new \r\n\r\ndef clean_tweet_by_frequency(tweet_file_name, processed_tweets_file_name):\r\n \r\n frequency = defaultdict(int)\r\n tweet_file = open(tweet_file_name,'r')\r\n new_tweet_file = open(processed_tweets_file_name,'w')\r\n \r\n for tweet in tweet_file:\r\n for token in tweet.split():\r\n frequency[token] += 1\r\n \r\n tweet_file.seek(0)\r\n \r\n \r\n for tweet in tweet_file:\r\n text = [token for token in tweet.split() if frequency[token]>1]\r\n if text is not None:\r\n new_tweet_file.write(\" \".join(text)+\"\\n\")\r\n \r\n \r\n tweet_file.close()\r\n new_tweet_file.close() \r\n\r\n\r\n#for ch in str:\r\n# print ch\r\n","sub_path":"tweet_clean.py","file_name":"tweet_clean.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167775156","text":"#Basic dictionary\r\nalien_0 = {'color' : 'green', 'points': 5}\r\n\r\nprint(alien_0['color'])\r\nprint(alien_0['points'])\r\n\"\"\"\r\nalien_0 딕셔너리는 외계인 색과 점수를 저장한다 두 print문은 정보에 접근하고\r\nprint(alien_0['color']) 는 green을 출력하게 되고, print(alien_0['points'])는\r\n5를 출력하게 된다 dictionary는 처음 배울 때는 익숙치 않으니 연습이 필요하다\r\n\"\"\"\r\n# use dictionary\r\n\"\"\"\r\n파이썬 딕셔너리는 키-값 쌍의 모음이다 각 키는 값에 연결되며, 키에 연결된 값에\r\n접근할 때도 키를 사용한다. 키의 값은 숫자, 문자열, 리스트, 심지어\r\n다른 딕셔셔너리도 가능하다\r\n\"\"\"\r\n# contact dictionary value\r\nalien_0 = {'color' : 'green'}\r\nprint(alien_0['color'])\r\n# 딕셔너리에 쓸 수 있는 키-값 쌍의 숫자에는 제한이 없다\r\nalien_0 = {'color' : 'green', 'points': 5}\r\n\r\nnew_points = alien_0['points']\r\nprint(\"You just earned \" +str(new_points) + \" points!\")\r\n\"\"\"\r\nnew_points는 딕셔너리에서 키'points'의 값을 가져온다 그리고\r\n그 값을 new_points 변수에 저장한다 str()은 정수 값을 문자열로 바꿔서 플레이어가\r\n몇 점을 얻었는지 출력한다\r\n\"\"\"\r\n# 새 키-값 쌍 추가하기\r\nprint('\\n' + str(alien_0))\r\n\r\nalien_0['x_position'] = 0\r\nalien_0['y_position'] = 25\r\nprint(alien_0)\r\n\"\"\"\r\n딕셔너리는 문자열이 아니라 str을 통해 문자열로 바꿔줬다\r\n그리고 마지막 버전에서 키-값 쌍이 네 개 생겼다 원래 두 땃응ㄴ 색과 점수르 저장하고\r\n추가한 두 쌍은 외계인 위치를 저장했다. 키-값이 표시되는 순서는 추가한 순서와\r\n일치하지 않는다 파이썬은 각 키-값 쌍을 저장한 순서는 신경 쓰지 않고 각 키와 값의 연결\r\n만 중시한다\r\n\"\"\"\r\n# start empty dictionary\r\nalien_0 = {}\r\n\r\nalien_0['color'] = 'green'\r\nalien_0['points'] = 5\r\n\r\nprint(\"\\n\" + str(alien_0))\r\n\"\"\"\r\n때로는 빈 딕셔너리로 시작하고 새 항목을 추가하는 방법이 더 간편하거나 필요할 때도\r\n있다 빈 딕셔너리로 시작하려면 빈 중괄호로 딕셔너리를 정의하고 다른 행에서 키-값 쌍을\r\n추가한다\r\n\"\"\"\r\n# modify value of dictionary\r\nalien_0 = {'color' : 'green'}\r\nprint(\"\\nThe alien is \" + alien_0['color'] + \".\")\r\n\r\nalien_0['color'] = 'yellow'\r\nprint(\"The alien is \" + alien_0['color'] + \".\")\r\n\"\"\"\r\n딕셔너리의 값을 수정할 때는 딕셔너리 이름 다음에 대괄호 속에 키를 쓰고 그 키에 연결할\r\n새 값을 지정한다.\r\n\"\"\"\r\nalien_0 = {'x_position' : 0, 'y_position' : 25, 'speed' : 'medium',}\r\nprint(\"Original x-position: \" + str(alien_0['x_position']))\r\n\r\n# 외계인을 오른쪽으로 움직인다\r\n# 현재 속도를 기준으로 외계인이 얼마나 빨리 움직이는지 판단한다\r\n\r\nif alien_0['speed'] == 'slow':\r\n x_increment = 1\r\nelif alien_0['speed'] == 'medium':\r\n x_increment = 2\r\nelse:\r\n # 이 외계인을 빠른놈이다\r\n x_increment = 3\r\n\r\n# 새 위치는 이전 위치에 증가분을 더한 값이다\r\nalien_0['x_position'] = alien_0['x_position'] + x_increment\r\nprint(\"New x-position: \" + str(alien_0['x_position']))\r\n\"\"\"\r\n먼저 외계인의 첫 x 위치와 y 위치, 'medium' 속도를 지정했다 단순하게 보이려고 색과\r\n점수는 생략했지만, 색과 점수가 있더라도 똑같이 작동한다 외계인이 오른쪽으로 얼마나\r\n빨리 움직이는 보기 위해 x_position의 원래 값도 출력했다\r\nif-elif-else 문을 써서 외계인이 오른쪽으로 얼마나 빨리 움직이는지 판단하고\r\n그 값을 x_increment 변수에 저장했다 외계인의 속도가 'slow'이면 한 칸을, 속도가\r\n'medium'이면 두 칸을, 'fast'이면 세 칸을 오른쪽으로 움직인다. 이동거리를\r\nx_position 값에 더하고 그 결과를 딕셔너리의 x_position에 저장했다 이 외계인은\r\n중간 속도이므로 오른쪽으로 두 칸 이동했다\r\n만약 중간 속도 외게인을 빠른 속도로 바꾸고싶다면 if문 위에 alien_0['speed'] = 'fast'\r\n코드를 추가하면 x_increment에 더 큰 값을 할당한다\r\n\"\"\"\r\n# 키-값 쌍 제거하기\r\nalien_0 = {'color' : 'green','points': 5}\r\nprint(alien_0)\r\n\r\ndel alien_0['points']\r\nprint(alien_0)\r\n\"\"\"\r\n딕셔너리에 저장된 정보가 더 이상 필요 없다면 del 문을 써서 완벽히 제거할 수 있다\r\ndel 문에는 디겻너리 이름과 제거할 키만 필요하다\r\n\"\"\"\r\n","sub_path":"dictionary/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"454094529","text":"import argparse\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter\n\nfrom proto_mdd.dataloader.samplers import CategoriesSampler, CategoriesSamplerOurs\nfrom proto_mdd.models.proto import proto_net\nfrom proto_mdd.models.proto_attention import proto_attention_net\nfrom proto_mdd.models.mdd import MDDNet, mdd_loss\nfrom proto_mdd.utils import pprint, set_gpu, ensure_path, Averager, Timer, count_acc, euclidean_metric, compute_confidence_interval, log, setup_seed\n\nfrom baseline_data.datamgr import SimpleDataManager, SetDataManager\n\n\nsetup_seed(666)\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--max_epoch', type=int, default=600)\n parser.add_argument('--train_way', type=int, default=5) \n parser.add_argument('--val_way', type=int, default=5)\n parser.add_argument('--shot', type=int, default=5)\n parser.add_argument('--query', type=int, default=15)\n parser.add_argument('--lr', type=float, default=0.0001)\n parser.add_argument('--lr_mul', type=float, default=10) # lr is the basic learning rate, while lr * lr_mul is the lr for other parts \n parser.add_argument('--temperature', type=float, default=128) \n parser.add_argument('--step_size', type=int, default=10)\n parser.add_argument('--gamma', type=float, default=0.5)\n parser.add_argument('--class_num', default=64, type=int)\n parser.add_argument('--srcweight', default=-1, type=int)\n parser.add_argument('--lambda_pre_fsl_loss', default= 1, type=float)\n parser.add_argument('--lambda_da', default=1, type=float) \n parser.add_argument('--lambda_new_fsl_loss', default = 1, type=float) \n parser.add_argument('--proto_attention', default = 0, type = int) \n parser.add_argument('--model_type', type=str, default='ResNet18', choices=['ConvNet', 'ResNet', 'ResNet18'])\n parser.add_argument('--dataset', type=str, default='cross', choices=['MiniImageNet', 'CUB', 'TieredImageNet','cross'])\n parser.add_argument('--init_weights', type = str, default= None) \n parser.add_argument('--head', type=int, default=1)\n parser.add_argument('--gpu', default='0,1')\n parser.add_argument('--print_i_mdd', default=0, type= int)\n parser.add_argument('--num_train_episodes', default = 100, type = int)\n args = parser.parse_args() \n\n if args.dataset == 'MiniImageNet':\n args.class_num = 64\n args.width = 1024\n args.srcweight = 4\n is_cen = False\n elif args.dataset == 'TieredImageNet':\n args.class_num = 351\n args.width = 1024\n args.srcweight = 4\n args.num_train_episodes = 1000\n is_cen = False\n elif args.dataset == 'CUB':\n args.class_num = 100\n args.width = 1024\n args.srcweight = 4\n is_cen = False\n elif args.dataset == 'cross':\n args.class_num = 100\n args.width = 1024\n args.srcweight = 4\n args.lr = 0.01\n args.lr_mul = 0.1\n is_cen = False\n\n else:\n print('Dataset not supported!')\n exit()\n \n\n set_gpu(args.gpu)\n if args.proto_attention:\n save_path1 = '-'.join([args.dataset, args.model_type, 'proto_atten', str(args.shot), str(args.train_way)])\n else:\n save_path1 = '-'.join([args.dataset, args.model_type, 'proto', str(args.shot), str(args.train_way)])\n save_path2 = '_'.join([str(args.lr),str(args.temperature), str(args.lambda_pre_fsl_loss), str(args.lambda_da), str(args.lambda_new_fsl_loss)])\n\n args.save_path = osp.join(save_path1, save_path2)\n ensure_path(save_path1, remove=False)\n ensure_path(args.save_path)\n train_log_file_path = os.path.join(args.save_path, 'train_log.txt') \n val_log_file_path = os.path.join(args.save_path, 'val_log.txt')\n log(train_log_file_path, str(vars(args)))\n log(val_log_file_path, str(vars(args)))\n\n\n if args.dataset == 'MiniImageNet': \n from proto_mdd.dataloader.mini_imagenet import MiniImageNet as Dataset\n elif args.dataset == 'CUB':\n from proto_mdd.dataloader.cub import CUB as Dataset\n elif args.dataset == 'TieredImageNet':\n from proto_mdd.dataloader.tiered_imagenet import tieredImageNet as Dataset\n elif args.dataset == 'cross':\n from proto_mdd.dataloader.mini_imagenet_pre import MiniImageNet as Dataset_mini\n from proto_mdd.dataloader.cub import CUB as Dataset_cub\n else:\n raise ValueError('Non-supported Dataset.')\n \n if args.dataset == 'cross': \n train_file = '~/filelists/miniImagenet/all.json'\n val_file = '~/filelists/CUB/val.json'\n image_size = 224\n base_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.train_way * 2, n_support = args.shot)\n train_loader = base_datamgr.get_data_loader( train_file , aug = True) \n val_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.val_way, n_support = args.shot)\n val_loader = val_datamgr.get_data_loader( val_file, aug = False) \n else:\n trainset = Dataset('train', args)\n train_sampler = CategoriesSamplerOurs(trainset.label, args.num_train_episodes, args.train_way, args.shot + args.query)\n train_loader = DataLoader(dataset=trainset, batch_sampler=train_sampler, num_workers=8, pin_memory=True)\n valset = Dataset('val', args)\n val_sampler = CategoriesSampler(valset.label, 600, args.val_way, args.shot + args.query)\n val_loader = DataLoader(dataset=valset, batch_sampler=val_sampler, num_workers=8, pin_memory=True)\n \n if args.proto_attention:\n base_net = proto_attention_net(args, dropout = 0.5) \n else:\n base_net = proto_net(args, dropout = 0.5)\n\n mdd_net = MDDNet(base_net=args.model_type, use_bottleneck=True,\n bottleneck_dim=args.width, width=args.width,\n class_num=args.class_num).cuda()\n\n\n # parameter list to optimize\n base_net_param_list = [{'params': base_net.encoder.parameters()}]\n if args.proto_attention:\n base_net_param_list = base_net_param_list + [{'params': base_net.slf_attn.parameters(), 'lr': args.lr * args.lr_mul}]\n \n mdd_net_param_list = mdd_net.get_parameter_list()\n mdd_net_param_list = [{'params':x['params'], 'lr': x['lr'] * args.lr * args.lr_mul} for x in mdd_net_param_list] \n\n parameter_list = base_net_param_list + mdd_net_param_list\n\n if args.model_type == 'ConvNet':\n optimizer = torch.optim.Adam(parameter_list, lr=args.lr)\n elif args.model_type == 'ResNet' or args.model_type == \"ResNet18\":\n optimizer = torch.optim.SGD(parameter_list, lr=args.lr, momentum=0.9, nesterov=True, weight_decay=0.0005)\n else:\n raise ValueError('No Such Encoder')\n \n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma) \n \n # load pre-trained model (no FC weights)\n base_net_dict = base_net.state_dict()\n if args.init_weights is not None:\n pretrained_dict = torch.load(args.init_weights)['state_dict']\n # remove weights for FC\n # pretrained_dict = {k[7:]: v for k, v in pretrained_dict.items()} # for cross-domain setting\n pretrained_dict = {'encoder.' + k[7:]: v for k, v in pretrained_dict.items()}\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in base_net_dict and base_net_dict[k].shape == pretrained_dict[k].shape}\n print(pretrained_dict.keys())\n base_net_dict.update(pretrained_dict) \n base_net.load_state_dict(base_net_dict, False) \n \n if args.train_way >= 10:\n \tbase_net.encoder = torch.nn.DataParallel(base_net.encoder, device_ids = [0,1]).cuda()\n \tbase_net = base_net.cuda()\n else:\n \tbase_net = base_net.cuda()\n \n def save_model(name):\n torch.save(dict(params=base_net.state_dict()), osp.join(args.save_path, name + '.pth'))\n torch.save(dict(params=mdd_net.state_dict()), osp.join(args.save_path, name + '_mdd.pth'))\n \n trlog = {}\n trlog['args'] = vars(args)\n trlog['train_loss'] = []\n trlog['val_loss'] = []\n trlog['train_acc'] = []\n trlog['val_acc'] = []\n trlog['max_acc'] = 0.0\n trlog['max_acc_epoch'] = 0\n \n timer = Timer()\n global_count = 0 \n \n label = torch.arange(args.train_way, dtype=torch.int8).repeat(args.query).type(torch.LongTensor) \n if torch.cuda.is_available():\n label = label.cuda() \n \n for epoch in range(1, args.max_epoch + 1):\n if args.dataset != 'cross':\n lr_scheduler.step()\n base_net.train()\n mdd_net.train()\n tl = Averager()\n ta = Averager()\n \n for i, batch in enumerate(train_loader, 1):\n args.print_i_mdd = i\n global_count = global_count + 1\n\n n_imgs = args.train_way * (args.shot + args.query) # 5*(5+15) = 100 \n data, index_label = batch[0].cuda(), batch[1].cuda()\n data_1 = data[:args.train_way]\n data_2 = data[args.train_way:]\n index_label_1 = index_label[:args.train_way]\n index_label_2 = index_label[args.train_way:]\n data_1 = data_1.permute(1,0,2,3,4)\n data_2 = data_2.permute(1,0,2,3,4)\n data_1 = data_1.reshape([-1] + list(data_1.shape[-3:]))\n data_2 = data_2.reshape([-1] + list(data_2.shape[-3:]))\n index_label_1 = index_label_1.permute(1,0)\n index_label_2 = index_label_2.permute(1,0)\n index_label_1 = index_label_1.reshape([-1])\n index_label_2 = index_label_2.reshape([-1])\n data = torch.cat([data_1, data_2], dim = 0)\n index_label = torch.cat([index_label_1, index_label_2]) \n # print(index_label)\n # prototypical network part\n # the first FSL loss i.e. (2 * N)-train_way K-shot learning\n \n pre_data_src = data[:n_imgs]\n pre_data_tgt = data[n_imgs:]\n\n p = args.shot * args.train_way\n pre_data_src_shot = pre_data_src[:p]\n pre_data_src_query = pre_data_src[p:]\n pre_data_tgt_shot = pre_data_tgt[:p]\n pre_data_tgt_query = pre_data_tgt[p:]\n pre_data_shot = torch.cat([pre_data_src_shot, pre_data_tgt_shot], dim = 0)\n pre_data_query = torch.cat([pre_data_src_query, pre_data_tgt_query], dim = 0)\n pre_fea_shot, pre_fea_query, pre_logits = base_net(pre_data_shot, pre_data_query)\n\n pre_label_fsl_s = torch.arange(args.train_way).repeat(args.query)\n pre_label_fsl_t = torch.arange(args.train_way, 2 * args.train_way).repeat(args.query)\n pre_label_fsl = torch.cat([pre_label_fsl_s, pre_label_fsl_t], dim = 0)\n pre_label_fsl = pre_label_fsl.type(torch.cuda.LongTensor)\n\n pre_fsl_loss = F.cross_entropy(pre_logits, pre_label_fsl) \n pre_fsl_acc = count_acc(pre_logits, pre_label_fsl)\n\n # rearrange the feature index\n pre_fea_src_shot = pre_fea_shot[:p]\n pre_fea_tgt_shot = pre_fea_shot[p:]\n pre_fea_src_query = pre_fea_query[:(n_imgs-p)]\n pre_fea_tgt_query = pre_fea_query[(n_imgs-p):]\n pre_src_features = torch.cat([pre_fea_src_shot, pre_fea_src_query], dim = 0)\n pre_tgt_features = torch.cat([pre_fea_tgt_shot, pre_fea_tgt_query], dim = 0)\n\n # domain adaptation part\n # the second FSL loss i.e. N-train_way K-shot learning\n pre_features = torch.cat([pre_src_features, pre_tgt_features], dim = 0)\n new_features, outputs, outputs_adv = mdd_net(pre_features)\n\n new_fea_s = new_features[:n_imgs]\n new_fea_t = new_features[n_imgs:]\n \n new_fea_shot_s, new_fea_query_s = new_fea_s[:p], new_fea_s[p:]\n new_fea_shot_t, new_fea_query_t = new_fea_t[:p], new_fea_t[p:]\n new_logits_s = base_net(new_fea_shot_s, new_fea_query_s, input_type = \"feature\")\n new_logits_t = base_net(new_fea_shot_t, new_fea_query_t, input_type = \"feature\")\n new_label_fsl = torch.arange(args.train_way).repeat(args.query)\n new_label_fsl = new_label_fsl.type(torch.cuda.LongTensor) \n new_fsl_loss_s = F.cross_entropy(new_logits_s, new_label_fsl)\n new_fsl_loss_t = F.cross_entropy(new_logits_t, new_label_fsl)\n new_fsl_loss = new_fsl_loss_s + new_fsl_loss_t\n\n new_fsl_acc_s = count_acc(new_logits_s, new_label_fsl)\n new_fsl_acc_t = count_acc(new_logits_t, new_label_fsl)\n\n # domain adaptation loss \n src_idx = list(range(n_imgs))\n tgt_idx = list(range(n_imgs, (2 * n_imgs)))\n # src_support_num = args.train_way * args.shot\n # tgt_support_num = args.train_way * args.query\n # src_idx = list(range(src_support_num))\n # tgt_idx = list(range((2 * n_imgs - tgt_support_num), (2 * n_imgs)))\n\n transfer_loss = mdd_loss(args, new_features, outputs, outputs_adv, index_label, src_idx, tgt_idx)\n if torch.isnan(transfer_loss):\n print(index_label[src_idx])\n print(index_label[tgt_idx])\n transfer_loss = pre_fsl_loss\n\n \n # total loss\n total_loss = args.lambda_pre_fsl_loss * pre_fsl_loss + args.lambda_new_fsl_loss * new_fsl_loss + args.lambda_da * transfer_loss\n\n if i % 25 == 0:\n \tlog(train_log_file_path, \"epoch: {} iter: {} transfer_loss: {:.4f} pre_fsl_loss: {:.4f} new_fsl_loss: {:.4f} total_fsl_loss: {:.4f}\".format\\\n \t\t(epoch, i, transfer_loss.item(), pre_fsl_loss.item(), new_fsl_loss.item(), total_loss.item()))\n \tlog(train_log_file_path, \"epoch: {} iter: {} fsl_acc_s: {:.4f} fsl_acc_t: {:.4f} pre_fsl_acc: {:.4f}\".format\\\n \t\t(epoch, i, new_fsl_acc_s, new_fsl_acc_t, pre_fsl_acc))\n \tif i% 100 == 0:\n \t\tlog(train_log_file_path, \"\\n\") \n \n tl.add(total_loss.item())\n ta.add(pre_fsl_acc)\n\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n\n tl = tl.item()\n ta = ta.item()\n\n base_net.eval()\n mdd_net.eval()\n\n vl = Averager()\n va = Averager()\n\n label_val = torch.arange(args.val_way).repeat(args.query)\n label_val = label_val.type(torch.cuda.LongTensor)\n \n with torch.no_grad():\n for i, batch in enumerate(val_loader, 1): \n data, _ = [_.cuda() for _ in batch]\n data = data.permute(1, 0, 2, 3, 4)\n data = data.reshape([-1] + list(data.shape[-3:])) \n p = args.shot * args.val_way\n data_shot, data_query = data[:p], data[p:]\n _, _, logits = base_net(data_shot, data_query)\n loss = F.cross_entropy(logits, label_val)\n acc = count_acc(logits, label_val) \n vl.add(loss.item())\n va.add(acc)\n\n vl = vl.item()\n va = va.item() \n log(val_log_file_path,'epoch {}, val, loss={:.4f} acc={:.4f}'.format(epoch, vl, va) \\\n \t+ ' *** best epoch and acc: {} {:.4f}'.format(trlog['max_acc_epoch'], trlog['max_acc']))\n\n if va >= trlog['max_acc']:\n trlog['max_acc'] = va\n trlog['max_acc_epoch'] = epoch\n save_model('max_acc') \n \n trlog['train_loss'].append(tl)\n trlog['train_acc'].append(ta)\n trlog['val_loss'].append(vl)\n trlog['val_acc'].append(va)\n\n torch.save(trlog, osp.join(args.save_path, 'trlog'))\n\n save_model('epoch-{}'.format(epoch))\n\n print('ETA:{}/{}'.format(timer.measure(), timer.measure(epoch / args.max_epoch))) \n\n # Test Phase\n trlog = torch.load(osp.join(args.save_path, 'trlog'))\n if args.dataset == \"cross\":\n # test_set = Dataset_cub('test', args)\n # sampler = CategoriesSampler(test_set.label, 10000, args.val_way, args.shot + args.query)\n # loader = DataLoader(test_set, batch_sampler=sampler, num_workers=8, pin_memory=True) \n test_file = '~/filelists/CUB/novel.json'\n image_size = 224 \n test_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.val_way, n_support = args.shot)\n test_loader = test_datamgr.get_data_loader( test_file, aug = False) \n else:\n test_set = Dataset('test', args)\n sampler = CategoriesSampler(test_set.label, 2000, args.val_way, args.shot + args.query)\n test_loader = DataLoader(test_set, batch_sampler=sampler, num_workers=8, pin_memory=True)\n\n if args.dataset == 'cross':\n \ttest_acc_record = np.zeros((len(test_loader),))\n else:\n \ttest_acc_record = np.zeros((2000,))\n\n base_net.load_state_dict(torch.load(osp.join(args.save_path, 'max_acc' + '.pth'))['params'])\n base_net.eval()\n\n ave_acc = Averager()\n label_val = torch.arange(args.val_way).repeat(args.query)\n label_val = label_val.type(torch.cuda.LongTensor) \n\n with torch.no_grad():\n for i, batch in enumerate(test_loader, 1): \n data, _ = [_.cuda() for _ in batch]\n data = data.permute(1, 0, 2, 3, 4) \n data = data.reshape([-1] + list(data.shape[-3:])) \n k = args.val_way * args.shot\n data_shot, data_query = data[:k], data[k:]\n _, _, logits = base_net(data_shot, data_query)\n acc = count_acc(logits, label_val)\n ave_acc.add(acc)\n test_acc_record[i-1] = acc\n if i % 100 == 0:\n \tprint('batch {}: {:.2f}({:.2f})'.format(i, ave_acc.item() * 100, acc * 100))\n \n m, pm = compute_confidence_interval(test_acc_record)\n log(val_log_file_path, 'Val Best Epoch {}, Acc {:.4f}, Test Acc {:.4f}'.format(trlog['max_acc_epoch'], trlog['max_acc'], ave_acc.item()))\n log(val_log_file_path, 'Test Acc {:.6f} + {:.6f}'.format(m, pm)) ","sub_path":"cross_domain_train.py","file_name":"cross_domain_train.py","file_ext":"py","file_size_in_byte":18364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"212476430","text":"from nbodykit.lab import *\nfrom nbodykit.cosmology.correlation import pk_to_xi, xi_to_pk\nimport mcfit\nfrom mcfit import P2xi, xi2P\n\nfrom scipy.integrate import quad, cumtrapz\nfrom scipy.special import spherical_jn\nfrom scipy.interpolate import interp1d\nfrom sympy.physics.wigner import wigner_3j\n\nclass model_4PCF(object):\n \n def __init__(self, meta_data, do_rsd=False, r_in=None, xi_in=None, verbose=False):\n\n '''\n lls is a list specifies the angular momentum\n e.g.\n \n ['000',\n '011',\n '022',\n '033']\n '''\n \n self.meta_data = meta_data\n self.lls = meta_data.ell_gaussian\n self.verbose = verbose\n self.do_rsd = do_rsd\n self.k_in = meta_data.k_in\n if r_in is None:\n self.r_in = meta_data.rbins_1d\n else:\n self.r_in = r_in\n self.redshift = meta_data.redshift\n \n if hasattr(self.meta_data, 'bias'):\n self.bias = self.meta_data.bias\n else:\n self.bias = 1\n \n if not self.do_rsd:\n if hasattr(self.meta_data, 'pk_in'):\n self.Pr = self.meta_data.pk_in\n else:\n self.Pr = None\n if hasattr(self.meta_data, 'twopcf_mean'):\n self.xir = self.meta_data.twopcf_mean\n else:\n self.xir = None\n \n elif self.do_rsd:\n if hasattr(self.meta_data, 'pk_in'):\n print(\"load existing Pr\")\n self.Pr = meta_data.pk_in\n else:\n self.Pr = None\n self.pk_ell = {}\n self.xi_ell = {}\n for ii in [0, 2, 4]:\n if hasattr(self.meta_data, 'pk_zs_mean'):\n try:\n # print(\"load existing Pk%s\"%ii)\n self.pk_ell[ii] = self.meta_data.pk_zs_mean[ii]\n except:\n pass\n if hasattr(self.meta_data, 'xi_zs_mean'):\n self.xi_ell[ii] = self.meta_data.xi_zs_mean[ii] \n \n def run(self):\n \n self.init_arrs()\n self.init_2stat()\n self.get_jnbar()\n self.get_zeta_model()\n \n def init_arrs(self):\n \n kbin_min= 1e-3\n kbin_max= 5\n nbink = 1000\n if self.r_in is None:\n sbin_min= 8.5\n sbin_max = 170\n dsbin = 17\n self.rr= numpy.arange(sbin_min, sbin_max, dsbin)\n else:\n self.rr = self.r_in.copy()\n self.nbins = len(self.rr)\n self.kk = numpy.linspace(kbin_min, kbin_max, nbink)\n self.kk_log = numpy.logspace(numpy.log10(kbin_min), numpy.log10(kbin_max), nbink)\n self.dkk = self.kk[1]-self.kk[0]\n self.rrv, self.kkv = numpy.meshgrid(self.rr, self.kk)\n \n def init_cosmo(self):\n h = 0.676\n Omega_nu = 0.00140971\n Omega0_m = 0.31\n Omega0_b = 0.022/h**2\n Omega0_cdm = Omega0_m - Omega0_b - Omega_nu\n n_s = 0.96\n sigma8 = 0.824\n self.cosmo = cosmology.Cosmology(h=h, Omega0_b=Omega0_b, \n Omega0_cdm=Omega0_cdm, n_s=n_s)\n self.cosmo.match(sigma8=sigma8)\n \n def init_2stat(self):\n \n if not self.do_rsd:\n if self.Pr is not None:\n print(\"load existing Pk\")\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk)\n if self.xir is not None:\n print(\"load existing xi\")\n self.r = self.r_in.copy()\n self.xi_interp = interp1d(self.r_in, self.xir, kind='cubic', fill_value='extrapolate')\n else:\n print(\"FT xi from existing Pk\")\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n\n elif self.Pkr is None:\n print(\"calculate linear Pk\")\n print(\"FT xi from linear theory Pk\")\n self.init_cosmo()\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n Pk_log = Plin(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate') \n \n elif self.do_rsd:\n self.xi_ell_interp = {}\n if (not bool(self.pk_ell)) or (not bool(self.xi_ell)) or (len(self.pk_ell)<3):\n if not hasattr(self, 'cosmo'):\n print(\"init cosmo\")\n self.init_cosmo()\n growth_rate = self.cosmo.scale_independent_growth_rate(0.57)\n beta = growth_rate/self.bias\n kaiser_fac = {}\n kaiser_fac[0] = (1 + 2*beta/3 + beta**2/5) * self.bias**2\n kaiser_fac[2] = (4*beta/3 + 4*beta**2/7) * self.bias**2\n kaiser_fac[4] = (8*beta**2/35) * self.bias**2\n \n if not bool(self.pk_ell):\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n if self.Pr is None:\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n print(\"linear Pk for ell=[0,2,4]\")\n else:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk)\n print(\"lieanr Kaiser + input Pr for ell=[0,2,4]\")\n for ii in [0, 2, 4]:\n if ii not in self.Pk_ell.keys():\n self.Pk_ell[ii] = self.Pk * kaiser_fac[ii]\n elif len(self.pk_ell)==3:\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n for ii in [0, 2, 4]:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n self.Pk_ell[ii] = pk_interp(self.kk) \n print(\"load existing pk_%s\"%ii)\n elif len(self.pk_ell)<3:\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n for ii in [0, 2, 4]:\n try:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n self.Pk_ell[ii] = pk_interp(self.kk) \n print(\"load existing pk_%s\"%ii)\n except:\n if self.Pr is None:\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n print(\"linear Pk%s\"%ii)\n else:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk) \n print(\"lieanr Kaiser + input Pr for ell=%s\"%ii)\n self.Pk_ell[ii] = self.Pk * kaiser_fac[ii] \n \n if not bool(self.xi_ell): \n if self.Pr is not None:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n self.get_xibar()\n for ii in [0, 2, 4]:\n print(\"linear xi%s\"%ii)\n xi = self.xi_interp(self.r) \n if ii == 2:\n xi -= self.xi_bar\n elif ii == 4:\n xi -= self.xi_bar_bar\n self.xi_ell_interp[ii] = interp1d(self.r, xi * kaiser_fac[ii], kind='cubic', fill_value='extrapolate')\n if hasattr(self.meta_data, 'pk_zs_mean'):\n print(\"FT pk_zs_mean to xi_ell\")\n for ii in [0, 2, 4]:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_ell_interp[ii] = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n \n else:\n self.r = self.r_in.copy()\n for ii in [0, 2, 4]:\n print(\"load existing xi%s\"%ii)\n self.xi_ell_interp[ii] = interp1d(self.r, self.xi_ell[ii], kind='cubic', fill_value='extrapolate')\n for ii in [1, 3, 5]:\n self.xi_ell_interp[ii] = interp1d(self.r, numpy.zeros_like(self.r), kind='cubic', fill_value='extrapolate')\n\n \n def get_xibar(self):\n ss = numpy.linspace(1e-2, 200, 1e3)\n ds = numpy.average(ss[1:]-ss[:-1])\n self.xi_bar = numpy.zeros(len(self.r))\n self.xi_bar_bar = numpy.zeros(len(self.r))\n for ii in range(len(self.r)):\n si = ss[ss < self.r[ii]]\n self.xi_bar[ii] = numpy.sum(self.xi_interp(si)*ds*si**2)/self.r[ii]**3*3\n self.xi_bar_bar[ii] = numpy.sum(self.xi_interp(si)*ds*si**4)/self.r[ii]**5*5\n \n def get_jnbar(self):\n\n self.jn_bar = {}\n nkbins = len(self.kk)\n half_width = (self.rr[1] - self.rr[0])*0.49\n\n for l in range(0,6):\n self.jn_bar[l] = numpy.zeros([len(self.rr), nkbins])\n \n for ii, ir in enumerate(self.rr):\n u = numpy.linspace(ir-half_width, ir+half_width, 100)\n du = u[1] - u[0]\n uv, kv = numpy.meshgrid(u, self.kk, indexing='ij')\n norm = numpy.sum(uv*uv, axis=0)*du\n for l in range(0,6):\n ans = numpy.sum(uv*uv*spherical_jn(l, uv*kv), axis=0)*du\n ans /= norm\n self.jn_bar[l][ii,:] = ans\n \n def get_flll(self, ells, a, b, c, verbose=False):\n \n ells = numpy.array(ells)\n if not self.do_rsd:\n if len(set(ells)) > 1:\n ells_unit = numpy.ones_like(ells)\n ells_unit[ells==0] = 0\n ans = (self.Pk * \n (self.jn_bar[ells[0]][a])**ells_unit[0] *\n (self.jn_bar[ells[1]][b])**ells_unit[1] *\n (self.jn_bar[ells[2]][c])**ells_unit[2] *\n self.kk**2) \n else:\n ans = (self.Pk * \n (self.jn_bar[ells[0]][a])**ells[0] *\n (self.jn_bar[ells[1]][b]) *\n (self.jn_bar[ells[2]][c]) *\n self.kk**2)\n elif self.do_rsd:\n ans = (self.Pk_ell[ells[0]] * \n (self.jn_bar[ells[1]][a]) *\n (self.jn_bar[ells[2]][b]) *\n self.kk**2) \n \n if verbose:\n try:\n print(\"ells_unit\", ells_unit)\n except:\n pass\n\n return ans\n\n def get_zeta_model(self):\n \n self.zetas_dict = {}\n self.zetas_dict_1d = {}\n \n for il in self.lls:\n self.zetas_dict[il] = numpy.zeros([self.nbins, self.nbins, self.nbins])\n\n for il in self.lls:\n ells = numpy.array([int(i) for i in il])\n for ii, ir1 in enumerate(self.rr):\n for jj, ir2 in enumerate(self.rr):\n for mm, ir3 in enumerate(self.rr):\n if not self.do_rsd:\n y_int = numpy.sum(self.get_flll(ells, ii, jj, mm))*self.dkk/2./numpy.pi**2\n rs = numpy.array([ir1, ir2, ir3])\n if len(set(ells)) > 1:\n self.zetas_dict[il][ii, jj, mm] = self.xi_interp(rs[ells==0])*y_int\n else:\n self.zetas_dict[il][ii, jj, mm] = 0\n y_int = numpy.sum(self.get_flll(ells, ii, jj, mm))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir1)*y_int \n y_int = numpy.sum(self.get_flll(ells, jj, mm, ii))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir2)*y_int \n y_int = numpy.sum(self.get_flll(ells, mm, ii, jj))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir3)*y_int \n elif self.do_rsd:\n ells_perm = [ells[0], ells[1], ells[2]]\n y_int1 = numpy.sum(self.get_flll(ells_perm, jj, mm, 0))*self.dkk/2./numpy.pi**2\n y_int1 *= (self.xi_ell_interp[ells_perm[0]](ir1) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n ells_perm = [ells[1], ells[0], ells[2]]\n y_int2 = numpy.sum(self.get_flll(ells_perm, ii, mm, 0))*self.dkk/2./numpy.pi**2\n y_int2 *= (self.xi_ell_interp[ells_perm[0]](ir2) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n ells_perm = [ells[2], ells[0], ells[1]]\n y_int3 = numpy.sum(self.get_flll(ells_perm, ii, jj, 0))*self.dkk/2./numpy.pi**2\n y_int3 *= (self.xi_ell_interp[ells_perm[0]](ir3) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n self.zetas_dict[il][ii, jj, mm] = (y_int1 + y_int2 + y_int3) # il is ell combo, ii, jj, mm is bin index\n\n if not self.do_rsd:\n phase = (4*numpy.pi)**1.5*(-1)**max(ells)*numpy.sqrt(2*max(ells)+1)\n elif self.do_rsd:\n threej = numpy.float64(wigner_3j(ells[0],ells[1],ells[2],0,0,0))\n phase = (4*numpy.pi)**1.5*numpy.sqrt((2*ells[0]+1)*(2*ells[1]+1)*(2*ells[2]+1))*threej\n #print(ells, max(ells))\n self.zetas_dict[il] *= phase\n\n self.zetas_1d = []\n bin_idx = []\n self.rbin_3d = []\n for ii in range(self.nbins):\n for jj in range(ii+1, self.nbins):\n for mm in range(jj+1, self.nbins):\n bin_idx.append([ii, jj, mm])\n self.rbin_3d.append([self.rr[ii], self.rr[jj], self.rr[mm]])\n self.zetas_1d.append(self.zetas_dict[il][ii, jj, mm])\n\n self.zetas_dict_1d[il] = numpy.array(self.zetas_1d)","sub_path":"Testing/model_4PCF_Gaussian_isotropic_basis.py","file_name":"model_4PCF_Gaussian_isotropic_basis.py","file_ext":"py","file_size_in_byte":15479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"69492969","text":"from datetime import datetime, timedelta\n\nfrom django.urls import reverse\n\nfrom general_test import ProjectViewsTestGeneral\nfrom students.models import Application, StudentFile\n\n\nclass StudentsViewsTest(ProjectViewsTestGeneral):\n def setUp(self):\n self.app = 'students'\n super(StudentsViewsTest, self).setUp()\n # self.debug=True\n self.f = StudentFile(\n Caption='testfiletype',\n Distribution=self.dist,\n )\n self.f.save()\n\n def test_view_status(self):\n \"\"\"\n Test pages related to applications\n\n :return:\n \"\"\"\n # Track for the project, with trackhead t-h\n s = self\n # General pages\n code_general = [\n [['list_applications', None], [s.p_student_only]],\n [['addfile', {'dist': self.dist.pk}], [s.p_student_dist]],\n [['editfile', {'dist': self.dist.pk, 'file': self.f.pk}], [s.p_student_dist]],\n [['files', {'dist': self.dist.pk}], [s.p_all_this_dist]],\n ]\n # Status: 1 2 3 notpublic 3public 3+exec 3+finished\n # For projects that can be applied to via marketplace\n code_project_apply = [\n [['apply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_student_only, s.p_student_only, s.p_forbidden]],\n [['confirmapply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_student_only, s.p_student_only, s.p_forbidden]],\n ]\n # For projects that cannot be applied using marketplace\n code_project_notapply = [\n [['apply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden]],\n [['confirmapply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden]],\n ]\n code_application_none = [\n [['retractapplication', {'application_id': 0}], [s.p_student404]],\n # [['prioUp', {'application_id': 0}], [student404]],\n # [['prioDown', {'application_id': 0}], [student404]]\n ]\n\n self.status = 1\n # info object with debug info if assertion fails\n info = {}\n # Test general page (not project specific)\n if self.debug:\n print(\"Testing general\")\n info['type'] = 'general'\n if self.debug:\n print('General 1')\n self.loop_code_user(code_general)\n\n # Project specific\n if self.debug:\n print(\"Testing project apply\")\n info['type'] = 'apply system'\n self.project.Apply = 'system'\n self.project.save()\n self.loop_code_user(code_project_apply)\n\n # Project specific, not apply\n if self.debug:\n print(\"Testing project apply for contacting supervisor\")\n info['type'] = 'apply supervisor'\n self.project.Apply = 'supervisor'\n self.project.save()\n self.loop_code_user(code_project_notapply)\n\n # application pages\n if self.debug:\n print(\"Testing project apply for applications student only\")\n info['type'] = 'apply general'\n self.project.Status = 3\n self.project.EndDate = datetime.now().date() + timedelta(days=2)\n self.project.Progress = None\n self.project.save()\n a = Application(Student=self.users.get('r-s'), Project=self.project)\n a.save()\n self.loop_code_user(code_application_none)\n\n self.assertListEqual(self.allurls, [], msg=\"Not all URLs of this app are tested!\")\n\n def test_apply_retract(self):\n \"\"\"\n Test apply retract pages in status 3\n\n :return:\n \"\"\"\n self.project.Status = 3\n self.project.EndDate = datetime.now().date() + timedelta(days=2)\n self.project.Progress = None\n self.project.Apply = 'system'\n self.project.save()\n\n # student\n s = self.users.get('r-s')\n\n # Test apply\n view = \"students:apply\"\n self.client.force_login(s)\n response = self.client.get(reverse(view, kwargs={\"pk\": self.p}))\n self.assertEqual(response.status_code, 200, msg=\"Student cannot apply to project!\")\n self.assertTrue(Application.objects.exists(), msg=\"Application is not made!\")\n\n # Test retract\n view = \"students:retractapplication\"\n app = Application.objects.get(Student=s)\n response = self.client.get(reverse(view, kwargs={\"application_id\": app.id}))\n self.assertEqual(response.status_code, 200, msg=\"Student cannot retract application!\")\n self.assertFalse(Application.objects.exists(), msg=\"Application is not retracted!\")\n\n self.client.logout()\n","sub_path":"students/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"477463504","text":"import os\nimport platform\nfrom ..Task import Task, TaskError\n\nclass LinkTaskTargetDirectoryError(TaskError):\n \"\"\"Link Target Directory Error.\"\"\"\n\nclass LinkTask(Task):\n \"\"\"\n Links (hardlink or symlink) a file to the target file path.\n \"\"\"\n\n __defaultLinkType = \"hardlink\"\n __kernelDll = None\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Create a Link task.\n \"\"\"\n super(LinkTask, self).__init__(*args, **kwargs)\n\n self.setOption('type', self.__defaultLinkType)\n self.setMetadata('dispatch.split', True)\n self.setMetadata('dispatch.splitSize', 20)\n\n def _perform(self):\n \"\"\"\n Perform the task.\n \"\"\"\n assert self.option('type') in ('hardlink', 'symlink'), \"Invalid link type {}\".format(self.option())\n\n for crawler in self.crawlers():\n filePath = self.target(crawler)\n\n # trying to create the directory automatically in case it does not exist\n try:\n os.makedirs(os.path.dirname(filePath))\n except OSError:\n pass\n\n # linking the file to the new target\n sourceFilePath = crawler.var('filePath')\n targetFilePath = filePath\n\n # Check if the target path already exists, if it is file remove it else raise an exception\n if os.path.isfile(targetFilePath):\n os.remove(targetFilePath)\n elif os.path.isdir(targetFilePath):\n raise LinkTaskTargetDirectoryError(\n 'Target directory already exists {}'.format(targetFilePath)\n )\n\n # linking\n if platform.system() == \"Windows\":\n self.__linkOnWindows(\n sourceFilePath,\n targetFilePath\n )\n else:\n self.__linkOnUnix(\n sourceFilePath,\n targetFilePath\n )\n\n # default result based on the target filePath\n return super(LinkTask, self)._perform()\n\n def __linkOnWindows(self, sourceFilePath, targetFilePath):\n \"\"\"\n Create a link on windows.\n \"\"\"\n # loading the kernel dll when necessary\n if self.__kernelDll is None:\n import ctypes\n self.__kernelDll = ctypes.windll.LoadLibrary(\"kernel32.dll\")\n\n sourceFilePath = os.path.normpath(sourceFilePath)\n targetFilePath = os.path.normpath(targetFilePath)\n\n # NOTE: creating a symlinks on windows requires additional permissions\n if self.option('type') == \"symlink\":\n createSymboliclink = ctypes.windll.kernel32.CreateSymbolicLinkW\n createSymboliclink.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n createSymboliclink.restype = ctypes.c_ubyte\n flags = int(os.path.isdir(sourceFilePath))\n if createSymboliclink(targetFilePath, sourceFilePath, flags) == 0:\n raise ctypes.WinError()\n\n elif self.option('type') == \"hardlink\":\n createHardlink = ctypes.windll.kernel32.CreateHardLinkW\n createHardlink.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n createHardlink.restype = ctypes.c_ubyte\n flags = 0\n if createHardlink(targetFilePath, sourceFilePath, flags) == 0:\n raise ctypes.WinError()\n\n def __linkOnUnix(self, sourceFilePath, targetFilePath):\n \"\"\"\n Create a link on unix.\n \"\"\"\n if self.option('type') == \"symlink\":\n os.symlink(\n sourceFilePath,\n targetFilePath\n )\n elif self.option('type') == \"hardlink\":\n os.link(\n sourceFilePath,\n targetFilePath\n )\n\n\n# registering task\nTask.register(\n 'link',\n LinkTask\n)\n","sub_path":"src/lib/kombi/Task/Fs/LinkTask.py","file_name":"LinkTask.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"481650719","text":"from flask import Flask\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restplus import Api\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True, max_age=86400)\napp.config.from_object('config')\napi = Api(app=app,\n catch_all_404s=True,\n title=\"2017 OMS API\",\n description=\"2017년도 한양대학교 주문관리시스템 API description page\",\n contact=\"한양대학교 한기훈\",\n contact_email=\"kordreamfollower@gmail.com\",\n prefix=\"/api\")\n\ndb = None\ndb_engine = None\nif db is None and db_engine is None:\n db = SQLAlchemy(app)\n db_engine = db.create_engine(app.config['SQLALCHEMY_DATABASE_URI'],\n encoding='utf-8',\n connect_args=app.config['DATABASE_CONNECT_OPTIONS'],\n pool_size=20, max_overflow=0)\n\nfrom app.modules import helper\napp.before_request(helper.before_request)\n\nfrom app.resources import *\napi.add_resource(user.User, '/user')\napi.add_resource(group.Group, '/group')\napi.add_resource(group.GroupEach, '/group/')\napi.add_resource(member.Member, '/member')\napi.add_resource(menu.Menu, '/menu')\napi.add_resource(menu.MenuEach, '/menu/')\napi.add_resource(setmenu.Setmenu, '/setmenu')\napi.add_resource(setmenu.SetmenuEach, '/setmenu/')\napi.add_resource(order.Order, '/order')\napi.add_resource(order.OrderEach, '/order/')\napi.add_resource(queue.Queue, '/queue')\napi.add_resource(statistics.Statistics, '/statistics')\napi.add_resource(download.Download, '/download')\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"566319171","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import View\nfrom main.forms import UserForm, UserProfileForm\n\n\nclass IndexView(View):\n def get(self, request):\n return render(request, 'main/index.html', {\n })\n\n\nclass RegisterView(View):\n def get(self, request):\n uform = UserForm()\n pform = UserProfileForm()\n return render(request, 'main/register.html', {\n 'uform': uform,\n 'pform': pform,\n })\n\n def post(self, request):\n uform = UserForm(data=request.POST)\n pform = UserProfileForm(data=request.POST)\n if uform.is_valid() and pform.is_valid():\n user = uform.save(commit=False)\n user.set_password(user.password)\n user.save()\n profile = pform.save(commit=False)\n profile.user = user\n profile.save()\n return redirect('/')\n return render(request, 'main/register.html', {\n 'uform': uform,\n 'pform': pform,\n })\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"68826183","text":"\"\"\"\n-------------------------------------------------------------------------------------------------------------------\n\n Project: Web Application, supporting search by keywords.\n Databases:\n 1. World:\n consists of country, city and countrylanguage of World database\n @https://dev.mysql.com/doc/world-setup/en/\n 2. FilmsActors:\n consists of film, film_actor, language and actor of Sakila database\n @https://dev.mysql.com/doc/sakila/en/\n 3. CustomersOrder:\n consists of products, orderdetails, productlines, orders and customers of classicmodels database\n @https://www.mysqltutorial.org/mysql-sample-database.aspx\n\n\n Execution Format:\n $ python import.py \n\n e.g.\n $ python import.py World World\n $ python import.py FilmsActors FilmsActors\n $ python import.py CustomersOrder CustomersOrder\n\n-------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nimport mysql.connector\nfrom mysql.connector import errorcode\nimport json\nimport decimal\nimport datetime\nimport sys\nimport requests\nimport re\n\n\ndef _build_connector(project_metadata):\n \"\"\"\n This function builds the connector instance to a database, with handling the exception.\n \"\"\"\n try:\n # Creates connector to database\n cnx = mysql.connector.connect(host='localhost', user='inf551', password='inf551',\n database=project_metadata['database'])\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Wrong username or password!\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist!\")\n else:\n print(err)\n return cnx\n\n\ndef _read_database(db_name, project_metadata):\n \"\"\"\n This function transforms the database in MySQL server to JSON serializable Object.\n \"\"\"\n cnx = _build_connector(project_metadata)\n\n result = _query_data(cnx, project_metadata)\n\n cnx.close()\n return result\n\n\ndef _query_data(cnx, project_metadata):\n \"\"\"\n This function queries the data in the database, and transforms the data into JSON.\n\n e.g.\n project_metadata = {'database': 'World', 'tables': ['city', 'country', 'countrylanguage']}\n\n ===>\n\n {'city': {'1': {'CountryCode': 'AFG',\n 'District': 'Kabol',\n 'ID': 1,\n 'Name': 'Kabul',\n 'Population': 1780000},\n ...\n 'country': {'ABW': {'Capital': 129,\n 'Code': 'ABW',\n 'Code2': 'AW',\n 'Continent': 'North America',\n 'GNP': '828.00',\n ...\n 'SurfaceArea': '193.00'},\n ...\n }\n\n 'countrylanguage': {'ABWDutch': {'CountryCode': 'ABW',\n 'IsOfficial': 'T',\n 'Language': 'Dutch',\n 'Percentage': '5.3'},\n ...\n }\n }\n \"\"\"\n\n data = dict()\n for table in project_metadata['tables']: # iterate tables chosen.\n data[table] = dict()\n # https://stackoverflow.com/questions/29772337/python-mysql-connector-unread-result-found-when-using-fetchone\n cursor = cnx.cursor(buffered=True)\n\n \"\"\"\n 1. Query the primary keys\n \"\"\"\n primaryKey = _retrieve_primary_key(table, project_metadata)\n\n \"\"\"\n 2. Query the data\n \"\"\"\n columns = _retrieve_columns(table, project_metadata)\n cursor.execute(\"SELECT {} FROM {}\".format(', '.join(columns), table))\n table_values = cursor.fetchall()\n for row_values in table_values:\n tmp = dict()\n # Handle the values that are not JSON serializable.\n for attr_name, row_value in zip(columns, row_values):\n if not isinstance(row_value, (set, decimal.Decimal, datetime.date)):\n tmp[attr_name] = row_value\n elif isinstance(row_value, set):\n tmp[attr_name] = list(row_value)\n elif isinstance(row_value, (datetime.date, decimal.Decimal)):\n tmp[attr_name] = str(row_value)\n attr_pk = _normalize_primaryKey('&'.join([str(tmp[pk]) for pk in primaryKey])) # normalize key\n data[table][attr_pk] = tmp\n cursor.close()\n\n return data\n\n\ndef _retrieve_primary_key(table, project_metadata):\n \"\"\"\n This function returns a list of column(s), which is the primary key(s) of .\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT kcu.COLUMN_NAME \" \\\n \"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \" \\\n \"USING(CONSTRAINT_NAME,TABLE_SCHEMA,TABLE_NAME) \" \\\n \"WHERE tc.TABLE_SCHEMA='{}' AND tc.TABLE_NAME='{}' \" \\\n \"AND tc.CONSTRAINT_TYPE='PRIMARY KEY';\".format(project_metadata['database'], table)\n cursor.execute(query)\n metadata_cnx.close()\n return [i[0] for i in cursor.fetchall()]\n\n\ndef _retrieve_columns(table, project_metadata):\n \"\"\"\n This function returns column(s) of
.\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA=\\'{}\\' AND TABLE_NAME=\\'{}\\'\"\\\n .format(project_metadata['database'], table)\n cursor.execute(query)\n metadata_cnx.close()\n return [i[0] for i in cursor.fetchall()]\n\n\ndef _normalize_primaryKey(string):\n \"\"\"\n Normalizes the string.\n\n e.g.\n 'North America' -> ['north', america']\n 'Washington.DC' -> ['woshingtondc']\n ...\n \"\"\"\n return re.sub(r'[^A-Za-z0-9 ]+', '', string) # only keeps english letter\n\n\ndef _normalize_index(value):\n \"\"\"\n Normalize the string and split string if needed.\n e.g.\n 'North America' -> ['north', america']\n 'Washington.DC' -> ['woshingtondc']\n ...\n \"\"\"\n # lower the value, and only keep letters, numbers and spaces in the value.\n\n string = str(value)\n _ = re.sub(r'[^A-Za-z0-9 ]+', '', string.lower()).strip() # only keeps english letter\n # _ = re.sub(r'[^\\w\\s]+', '', string.lower()).strip()\n\n # split the value by space(s)\n _ = re.split(r'\\s+', _)\n return _\n\n\ndef _patch_data_to_firebase(data, node):\n \"\"\"\n Patches data to firebase.\n \"\"\"\n URL = 'https://inf551-project-msl-wqd.firebaseio.com/{}.json'.format(node)\n print('Patching data to {}...'.format(URL))\n requests.patch(URL, json.dumps(data))\n\n\ndef _save_json(json_content, json_path):\n \"\"\"\n Save to local.\n \"\"\"\n with open(json_path, 'w') as file:\n file.write(json.dumps(json_content, indent=4))\n\n\ndef _project_metadata(db_name):\n \"\"\"\n Typically, it is solid to use information_schema.tables to query the tables for each database.\n \n However, as we planned in the project proposal, only a subset of tables is chosen for each database,\n so we have to give EXPLICIT table names.\n \"\"\"\n if db_name not in {'World', 'FilmsActors', 'CustomersOrder'}:\n print(\"The {} database is not available. Please choose database from 'World', 'FilmsActors' \"\n \"or 'CustomersOrder'\".format(db_name))\n exit(0)\n\n if db_name == 'World':\n return {'database': 'World',\n 'tables': ['city', 'country', 'countrylanguage']}\n elif db_name == 'FilmsActors':\n return {'database': 'sakila',\n 'tables': ['film', 'film_actor', 'language', 'actor']}\n else:\n return {'database': 'classicmodels',\n 'tables': ['products', 'orderdetails', 'productlines', 'orders', 'customers']}\n\n\ndef _build_index(data):\n \"\"\"\n This function builds inverted index for every word inside data,\n storing mapping from word to its location in table.\n\n\n e.g. the index of \"davidson\" in the CustomersOrder database\n \"davidson\":\n [\n {\n \"TABLE\": \"products\",\n \"PRIMARYKEY\": \"S101678\",\n \"COLUMN\": \"productName\"\n },\n\n ...\n\n {\n \"TABLE\": \"productlines\",\n \"PRIMARYKEY\": \"Motorcycles\",\n \"COLUMN\": \"textDescription\"\n }\n ]\n \"\"\"\n index = dict()\n for table_name, table_data in data.items():\n for primary_key, row_data in table_data.items():\n for column_name, value in row_data.items():\n words_list = _normalize_index(value)\n for word in words_list:\n try:\n int(word)\n continue\n except ValueError:\n index[word] = index.get(word, []) + \\\n [{'TABLE': table_name, 'PRIMARYKEY': primary_key, 'COLUMN': column_name}]\n if '' in index:\n del index['']\n return index\n\n\ndef _retrieve_schema(project_metadata):\n \"\"\"\n e.g.\n project_metadata = {'database': 'World', 'tables': ['city', 'country', 'countrylanguage']}\n\n result:\n {\n \"city\": {\n \"columns\": [\n \"CountryCode\",\n \"District\",\n \"ID\",\n \"Name\",\n \"Population\"\n ],\n \"foreign_key\": {\n \"CountryCode\": {\n \"referenced_table\": \"country\",\n \"referenced_column\": \"Code\"\n }\n }\n },\n \"country\": {\n ...\n },\n \"countrylanguage\": {\n ...\n }\n }\n \"\"\"\n schema = dict()\n for table in project_metadata['tables']:\n schema[table] = dict()\n schema[table]['columns'] = _retrieve_columns(table, project_metadata)\n schema[table]['foreign_key'] = _retrieve_foreign_key_constraints(project_metadata, table)\n return schema\n\n\ndef _retrieve_foreign_key_constraints(project_metadata, table):\n \"\"\"\n This function connects to INFORMATION_SCHEMA of MySQL DBMS, returns foreign keys constraint.\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME \" \\\n \"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \" \\\n \"USING(CONSTRAINT_NAME,TABLE_SCHEMA,TABLE_NAME) \" \\\n \"WHERE tc.TABLE_SCHEMA='{}' AND tc.TABLE_NAME='{}' \" \\\n \"AND tc.CONSTRAINT_TYPE='FOREIGN KEY'\".format(project_metadata['database'], table)\n\n fk_cons = dict()\n cursor.execute(query)\n for cons in cursor.fetchall():\n if cons[1] in project_metadata['tables']:\n fk_cons[cons[0]] = {'referenced_table': cons[1], 'referenced_column': cons[2]}\n metadata_cnx.close()\n\n return fk_cons\n\n\nif __name__ == '__main__':\n database_name = sys.argv[1]\n firebase_node = sys.argv[2]\n\n _project_metadata = _project_metadata(database_name)\n\n print('\\nRetrieving schema...')\n _schema = _retrieve_schema(_project_metadata)\n # _save_json(_schema, '{}_schema.json'.format(database_name))\n _patch_data_to_firebase(_schema, '{}_schema'.format(firebase_node))\n\n print('\\nRetrieving data...')\n results = _read_database(database_name, _project_metadata)\n # _save_json(results, '{}.json'.format(database_name))\n _patch_data_to_firebase(results, database_name)\n\n print('\\nBuilding indices...')\n inverted_index = _build_index(results)\n # _save_json(inverted_index, '{}_index.json'.format(firebase_node))\n _patch_data_to_firebase(inverted_index, '{}_index'.format(firebase_node))\n\n print('\\nDone!')\n\n","sub_path":"Coding_for_once/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":12218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"453153350","text":"# -*- coding: UTF-8 -*-\n'''\nAuthor: Jaime Rivera\nFile: 3ddist_exec.py\nDate: 2019.01.06\nRevision: 2019.01.06\nCopyright: Copyright Jaime Rivera 2019 | www.jaimervq.com\n The program(s) herein may be used, modified and/or distributed in accordance with the terms and conditions\n stipulated in the Creative Commons license under which the program(s) have been registered. (CC BY-SA 4.0)\n\nBrief: Executable file that lets the user calculate distances between Nuke 3D objects (cameras, geometries...)\n\n'''\n\n__author__ = 'Jaime Rivera '\n__copyright__ = 'Copyright 2019, Jaime Rivera'\n__credits__ = []\n__license__ = 'Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)'\n__maintainer__ = 'Jaime Rivera'\n__email__ = 'jaime.rvq@gmail.com'\n__status__ = 'Testing'\n\nimport nuke\n\n# NUKE FLAGS USED\n# ---------------\n# STARTLINE = 0x00001000\n# SLIDER = 0x00000002\n# READ_ONLY = 0x10000000\n# NO_ANIMATION = 0x00000100\n# INVISIBLE = 0x00000400\n\n\n# -------------------------------- NUMBER INPUT -------------------------------- #\n\ntotal_objects = None\n\nwhile total_objects is None:\n try:\n input_count = nuke.getInput(\"Enter number of 3D objects to compare\", '')\n total_objects = int(2.0 * round(abs(float(input_count)) / 2.0))\n except ValueError:\n nuke.message('Not a valid number')\n pass\n\n\n# -------------------------------- NODE CREATION -------------------------------- #\n\nsticky_note = nuke.nodes.StickyNote(name='Distances',\n label='3D distances',\n note_font='Arial Bold',\n note_font_size=35,\n tile_color=2566914303)\n\n# Knobs creation\nfor i in range(1, total_objects + 1):\n\n source = nuke.String_Knob('source_row_{}'.format(i), 'Source'.format(i))\n sticky_note.addKnob(source)\n\n button_code_source = \"if len(nuke.selectedNodes())==1:\" \\\n \"\\n if 'translate' in nuke.selectedNode().knobs().keys():\" \\\n \"\\n nuke.thisNode()['source_row_{0}'].setValue(nuke.selectedNode()['name'].value())\" \\\n \"\\n else:\" \\\n \"\\n nuke.thisNode()['source_row_{0}'].setValue('')\" \\\n \"\\nelif len(nuke.selectedNodes())>1:\" \\\n \"\\n nuke.message('Please select only one node')\" \\\n \"\\nelse:\" \\\n \"\\n nuke.message('Please select a node')\".format(i)\n source_button = nuke.PyScript_Knob('source_button_row_{}'.format(i), 'Select', button_code_source)\n source_button.setTooltip(\"Select a 3D object and press this button to add it to the field on the left (Source)\"\n \"\\nYou can also type any node's name into these fields\".format(i))\n sticky_note.addKnob(source_button)\n\n target = nuke.String_Knob('target_row_{}'.format(i), ' Target '.format(i))\n sticky_note.addKnob(target)\n target.clearFlag(0x00001000)\n\n button_code_target = \"if len(nuke.selectedNodes())==1:\" \\\n \"\\n if 'translate' in nuke.selectedNode().knobs().keys():\" \\\n \"\\n nuke.thisNode()['target_row_{0}'].setValue(nuke.selectedNode()['name'].value())\" \\\n \"\\n else:\" \\\n \"\\n nuke.thisNode()['target_row_{0}'].setValue('')\" \\\n \"\\nelif len(nuke.selectedNodes())>1:\" \\\n \"\\n nuke.message('Please select only one node')\" \\\n \"\\nelse:\" \\\n \"\\n nuke.message('Please select a node')\".format(i)\n target_button = nuke.PyScript_Knob('target_button_row_{}'.format(i), 'Select', button_code_target)\n target_button.setTooltip(\n \"Select a 3D object and press this button to add it to the field on the left (Target)\\nYou can also type any node's name into these fields\".format(\n i))\n sticky_note.addKnob(target_button)\n\n\n result = nuke.Double_Knob('result_row_{}'.format(i), ' DIST')\n result.setExpression(\"sqrt((pow2([value source_row_{0}].translate.x-[value target_row_{0}].translate.x))+\"\n \"(pow2([value source_row_{0}].translate.y-[value target_row_{0}].translate.y))+\"\n \"(pow2([value source_row_{0}].translate.z - [value target_row_{0}].translate.z)))\".format(i))\n sticky_note.addKnob(result)\n result.clearFlag(0x00001000)\n result.clearFlag(0x00000002)\n result.setFlag(0x10000000)\n result.setFlag(0x10000000)\n\n\nreset_code = \"for knob in nuke.thisNode().allKnobs():\"\\\n \"\\n if 'target_' in knob.name() or 'source_' in knob.name():\" \\\n \"\\n if 'button' not in knob.name():\" \\\n \"\\n knob.setValue('')\"\nreset_knob = nuke.PyScript_Knob('reset', 'RESET ALL', reset_code)\nsticky_note.addKnob(reset_knob)\nreset_knob.setFlag(0x00001000)\n\n\nformat_knob = nuke.Int_Knob('format', '')\nformat_knob.setExpression(\"[python -execlocal {if not nuke.selectedNode()['result_row_1'].getFlag(0x10000000):\"\n \"\\n for knob in nuke.thisNode().allKnobs():\"\n \"\\n if 'result_' in knob.name():\"\n \"\\n knob.clearFlag(0x00000002)\"\n \"\\n knob.setFlag(0x10000000)\"\n \"\\n knob.setFlag(0x10000000)\"\n \"\\nret=0}]\")\nsticky_note.addKnob(format_knob)\nformat_knob.setFlag(0x00000400)\n\n\nformat3_knob = nuke.Int_Knob('format3', '')\nformat3_knob.setExpression(\"[python -execlocal {for knob in nuke.thisNode().allKnobs():\"\n \"\\n if 'source_row_' in knob.name() and nuke.toNode(knob.value()) is not None:\"\n \"\\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():\"\n \"\\n knob.setValue('')\"\n \"\\n if 'target_row_' in knob.name() and nuke.toNode(knob.value()) is not None:\"\n \"\\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():\"\n \"\\n knob.setValue('')\"\n \"\\nret=0}]\")\nsticky_note.addKnob(format3_knob)\nformat3_knob.setFlag(0x00000400)\n\n\n# -------------------------------- FRAMING -------------------------------- #\n\nsticky_note.setSelected(True)\nnuke.show(sticky_note)\nnuke.zoomToFitSelected()\nfor n in nuke.allNodes():\n n.setSelected(False)","sub_path":"3ddist_exec.py","file_name":"3ddist_exec.py","file_ext":"py","file_size_in_byte":6699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"219591644","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport subprocess\nimport distutils.cmd\nimport distutils.log\nfrom distutils.errors import DistutilsPlatformError\nfrom distutils.dir_util import copy_tree\nimport glob\nimport re\nimport shlex\n\n\ndef compileJava(self, coverage):\n target_version = \"1.7\"\n srcs = glob.glob('native/java/**/*.java', recursive=True)\n src1 = [i for i in srcs if \"JPypeClassLoader\" in i]\n src2 = [i for i in srcs if not \"JPypeClassLoader\" in i]\n cmd1 = shlex.split('javac -d build/lib -g:none -source %s -target %s' %\n (target_version, target_version))\n cmd1.extend(src1)\n debug = \"-g:none\"\n if coverage:\n debug = \"-g:lines,vars,source\"\n cmd2 = shlex.split('javac -d build/classes %s -source %s -target %s -cp build/lib' %\n (debug, target_version, target_version))\n cmd2.extend(src2)\n os.makedirs(\"build/lib\", exist_ok=True)\n os.makedirs(\"build/classes\", exist_ok=True)\n self.announce(\" %s\" % \" \".join(cmd1), level=distutils.log.INFO)\n subprocess.check_call(cmd1)\n self.announce(\" %s\" % \" \".join(cmd2), level=distutils.log.INFO)\n subprocess.check_call(cmd2)\n cmd3 = shlex.split(\n 'jar cvf build/lib/org.jpype.jar -C build/classes/ .')\n self.announce(\" %s\" % \" \".join(cmd3), level=distutils.log.INFO)\n subprocess.check_call(cmd3)\n\n\nclass BuildJavaCommand(distutils.cmd.Command):\n \"\"\"A custom command to create jar file during build.\"\"\"\n\n description = 'build jpype jar'\n user_options = []\n\n def initialize_options(self):\n \"\"\"Set default values for options.\"\"\"\n pass\n\n def finalize_options(self):\n \"\"\"Post-process options.\"\"\"\n pass\n\n def run(self):\n \"\"\"Run command.\"\"\"\n java = self.distribution.enable_build_jar\n\n # Try to use the cach if we are not requested build\n if not java:\n src = os.path.join('native', 'jars')\n dest = os.path.join('build', 'lib')\n if os.path.exists(src):\n distutils.log.info(\"Using Jar cache\")\n copy_tree(src, dest)\n return\n\n distutils.log.info(\n \"Jar cache is missing, using --enable-build-jar to recreate it.\")\n\n coverage = self.distribution.enable_coverage\n\n # build the jar\n try:\n compileJava(self, coverage)\n except subprocess.CalledProcessError as exc:\n distutils.log.error(exc.output)\n raise DistutilsPlatformError(\"Error executing {}\".format(exc.cmd))\n","sub_path":"setupext/build_java.py","file_name":"build_java.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"652611660","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 17 23:33:03 2019\n\n\"\"\"\n\n\"\"\"\n Peer review comments:\n This looks like a good solution to the problems, I just have a couple of comments:\n - It is generally good style to import modules at the top of the file rather than where you use them\n - I would advise when you have a (value, flag) return style that you alwyas return a number\n as the first value instead of '_' in case someone tries to use the result before they check the flag.\n This would cause a crash if you return a string\n\"\"\"\n\n\ndef lp_apply(p, i):\n \"\"\"Applies a permutation p, given as a linear order, to a point i.\"\"\"\n n = len(p)\n if 0 <= i and i < n:\n return p[i]\n\n\ndef lp_orbit(p, i):\n \"\"\"Computes the orbit of i under p\"\"\"\n n = len(p)\n if 0 <= i and i < n:\n rv = [i]\n k = lp_apply(p, i)\n while k != i:\n rv.append(k)\n k = lp_apply(p, k)\n return rv\n\n\ndef lp_moves_to(p, i, j):\n n = len(lp_orbit(p, i))\n \"\"\"If j is not in the orbit of p under i then there is no k for which\"\"\"\n \"\"\"p**k(i)=j; test for membership and then work out position in orbit\"\"\"\n if j in lp_orbit(p, i):\n for l in range(n):\n if j == lp_orbit(p, i)[l]:\n flag = True\n if l == 0:\n \"\"\"Don't want value of k=0 returned\"\"\"\n return (n, flag)\n else:\n return (l, flag)\n else:\n flag = False\n return ('_', flag)\n\n\nfrom nose.tools import ok_\n\nok_((2, True) == lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 3))\n_, flag = lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 7)\nok_(not flag)\n\nok_((1, True) == lp_moves_to([4, 2, 5, 1, 3, 0], 3, 1))\nok_((4, True) == lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 6))\n\n\ndef lp_times(p, q):\n \"\"\"Computes the product of two permutations p and q, given as linear orders.\"\"\"\n n, m = len(p), len(q)\n if n == m:\n pq = n * [None]\n for i in range(n):\n pq[i] = lp_apply(p, lp_apply(q, i))\n return pq\n\n\ndef lp_inv(p):\n \"\"\"Computes the inverse of a permutation p, given as a linear order\"\"\"\n n = len(p)\n pinv = n * [None]\n for i in range(n):\n pinv[p[i]] = i\n return pinv\n\n\ndef lp_orbits(p):\n \"\"\"Partitions [0, ..., n - 1] by orbits of p.\n nb. Returns them sorted by length\n \"\"\"\n n = len(p)\n seen = set()\n orbits = []\n for i in range(n):\n if i not in seen:\n o = lp_orbit(p, i)\n seen |= set(o) # add multiple elements to seen\n orbits.append(o)\n orbits.sort(key=len)\n return orbits\n\n\ndef flat(p):\n \"\"\"Flattens the list\"\"\"\n x = []\n for a in p:\n for b in a:\n x.append(b)\n return x\n\n\ndef check_conj(p, q):\n \"\"\"Checks if p and q can be conjugate\"\"\"\n porbits, qorbits = lp_orbits(p), lp_orbits(q)\n m, n = len(porbits), len(qorbits)\n if m == n:\n for i in range(m):\n if len(porbits[i]) == len(qorbits[i]):\n return True\n else:\n return False\n\n\ndef lp_isconj(p, q):\n \"\"\"Finds function t\"\"\"\n rv = []\n x = flat(lp_orbits(p))\n y = flat(lp_orbits(q))\n if check_conj(p, q) == True:\n for i in range(len(x)):\n s = y.index(i)\n rv.append(x[s])\n t = rv\n return (t, True)\n else:\n return ('t', False)\n\n\n\"\"\"Tests\"\"\"\n\nfrom nose.tools import ok_\n\nt, flag = lp_isconj([7, 3, 6, 2, 0, 5, 1, 4], [3, 6, 2, 7, 5, 1, 4, 0])\nok_(flag and [7, 3, 6, 2, 0, 5, 1, 4] == lp_times(lp_times(t, [3, 6, 2, 7, 5, 1, 4, 0]), lp_inv(t)))\n\nu, flag = lp_isconj([0, 1, 2, 3, 4, 5, 6, 7], [3, 6, 2, 7, 5, 1, 4, 0])\nok_(not flag)\n\nok_('t', False == lp_isconj([1, 0, 2], [2, 0, 1])) \n\n","sub_path":"Peer Feedback/18th Feb.py","file_name":"18th Feb.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"546841684","text":"from abc import ABC, abstractmethod\nimport tensorflow as tf \nimport tensorflow.compat.v1 as v1\n\nclass BaseModel(ABC):\n \"\"\"\n Abstract base class for TensorFlow dataset.\n To create a subclass, you need to implement at least these functions:\n -- <__init__>: initialize the class\n -- : parse/pre-process model input\n -- : main function to build computation graph\n -- : (optionally) add dataset-specific options, called in base_options.py\n \"\"\"\n def __init__(self, opt):\n self.opt = opt\n\n @staticmethod\n def modify_commandline_options(parser):\n return parser\n \n @abstractmethod\n def set_input(self, model_input):\n raise NotImplementedError\n\n @abstractmethod\n def build_graph(self):\n raise NotImplementedError\n\nclass VideoPredictionModel(BaseModel):\n \"\"\"\n Generic model class for video prediction task.\n The driver scripts (train.py and test.py) will use function to build computational graph, like\n doing forward pass, computing losses/metrics/gradients, optimizing parameters and adding summaries. \n \"\"\"\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n\n @staticmethod\n def modify_commandline_options(parser):\n BaseModel.modify_commandline_options(parser)\n return parser\n\n def build_graph(self, isTrain=True):\n \"\"\"\n Function for building computational graph.\n Parameters:\n isTrain (bool) -- identify train/val process and test process\n Return:\n ret_fetch (dict) -- dictionary of tensorflow tensors\n \"\"\"\n # get global step #\n self.global_step = v1.train.get_or_create_global_step()\n\n # get learning rate and other step dependent properties #\n self.get_learning_rate()\n self.get_kl_weight()\n \n # forward function #\n input_dict = {}\n input_dict[\"image_seq\"] = self.image_seq\n try:\n if self.action is not None:\n input_dict[\"action\"] = self.action\n except AttributeError:\n pass\n try:\n if self.state is not None:\n input_dict[\"state\"] = self.state\n except AttributeError:\n pass\n \n if isTrain:\n self.outputs = self.forward(input_dict, training=True, _reuse=None)\n self.eval_outputs = self.forward(input_dict, training=False, _reuse=True)\n else:\n # in test mode, use only eval_output\n # self.outputs is used to initialize graph\n self.outputs = self.forward(input_dict, training=True, _reuse=None)\n self.eval_outputs = self.forward(input_dict, training=False, _reuse=True)\n\n # compute loss #\n if isTrain:\n self.losses = self.compute_losses(self.image_seq, self.outputs)\n self.eval_losses = self.compute_losses(self.image_seq, self.eval_outputs)\n else:\n self.losses = None\n self.eval_losses = self.compute_losses(self.image_seq, self.eval_outputs)\n\n # compute metrics #\n if isTrain:\n # since we compute l1 loss use posterior, use prior here\n self.metrics = self.compute_metrics(self.image_seq, self.outputs[\"gen_images_prior\"])\n self.eval_metrics = self.compute_metrics(self.image_seq, self.eval_outputs[\"gen_images_prior\"])\n else:\n self.metrics = None\n self.eval_metrics = self.compute_metrics(self.image_seq, self.eval_outputs[\"gen_images_prior\"])\n\n # optimizer routine only in train mode #\n if isTrain:\n train_op = self.optimize_parameters(self.losses[\"d_loss\"], self.losses[\"g_loss\"])\n \n # add summaries #\n if isTrain:\n image_sum_op, scalar_sum_op, hist_sum_op = self.create_summaries(prefix=\"train\")\n eval_image_sum_op, eval_scalar_sum_op, eval_hist_sum_op = self.create_summaries(prefix=\"eval\")\n\n # store mode-specific fetches # \n ret_fetch = {}\n # train operation\n if isTrain:\n ret_fetch[\"train_op\"] = train_op\n # global steps \n if isTrain:\n ret_fetch[\"global_step\"] = self.global_step\n # losses dict\n if self.losses:\n ret_fetch[\"losses\"] = self.losses \n ret_fetch[\"eval_losses\"] = self.eval_losses\n # metrics dict\n if self.metrics:\n ret_fetch[\"metrics\"] = self.metrics\n ret_fetch[\"eval_metrics\"] = self.eval_metrics\n # other scalars\n ret_fetch[\"batch_size\"] = tf.constant(self.image_seq.get_shape().as_list()[0], dtype=tf.float32)\n if isTrain:\n ret_fetch[\"learning_rate\"] = self.learning_rate\n ret_fetch[\"kl_weight\"] = self.kl_weight\n # summary ops\n if isTrain:\n ret_fetch[\"scalar_sum_op\"] = scalar_sum_op\n ret_fetch[\"image_sum_op\"] = image_sum_op\n ret_fetch[\"hist_sum_op\"] = hist_sum_op\n ret_fetch[\"eval_scalar_sum_op\"] = eval_scalar_sum_op\n ret_fetch[\"eval_image_sum_op\"] = eval_image_sum_op\n ret_fetch[\"eval_hist_sum_op\"] = eval_hist_sum_op\n # saved images \n ret_fetch[\"target_images\"] = self.image_seq\n ret_fetch[\"eval_gen_images\"] = self.eval_outputs[\"gen_images_prior\"]\n return ret_fetch","sub_path":"video_prediction/models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"302527059","text":"class Node: \n def __init__(self, data): \n self.data = data \n self.next = None\n\nclass LinkedList: \n def __init__(self): \n self.head = None\n\n def pairSwap(self): \n temp = self.head \n if temp is None: \n return\n while(temp is not None and temp.next is not None): \n if(temp.data == temp.next.data): \n temp = temp.next.next\n else: \n temp.data, temp.next.data = temp.next.data, temp.data \n temp = temp.next.next\n\n def push(self, new_data): \n new_node = Node(new_data) \n new_node.next = self.head \n self.head = new_node \n\n def printList(self): \n temp = self.head \n while(temp): \n print(temp.data) \n temp = temp.next\n\nll = LinkedList() \nll.push(5) \nll.push(4) \nll.push(3) \nll.push(11) \nll.push(27) \nll.pairSwap() \nll.printList()\n","sub_path":"Day 28 - Pair Swap Linked List.py","file_name":"Day 28 - Pair Swap Linked List.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"226132651","text":"from collections import defaultdict\n\n\nclass TimeMap:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.dict1 = {}\n self.dict2 = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.dict1[(key, timestamp)] = value\n self.dict2[key].append(timestamp)\n\n def get(self, key: str, timestamp: int) -> str:\n arr = self.dict2[key]\n p1, p2 = 0, len(arr) - 1\n\n while p1 <= p2:\n m = p1 + (p2 - p1) // 2\n if arr[m] == timestamp:\n return self.dict1[(key, arr[m])]\n elif arr[m] < timestamp:\n p1 = m + 1\n elif arr[m] > timestamp:\n p2 = m - 1\n if p1 == 0:\n return \"\"\n return self.dict1[(key, arr[p1 - 1])]","sub_path":"leetcode/p0981_time_based_key_value_store/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"84225356","text":"\"\"\"\nHelper functions for financial computations.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom main import database_manager\nfrom typing import Tuple\nfrom abc import ABC, abstractmethod\n\n\nLOOKBACK_PERIOD_ANNUAL = 252\n\n\nclass TimeVaryingPortfolioStrategy(object):\n \"\"\"\n Example Usage:\n st_1 = main.portfolio_strategy.ConstantVolatilityStrategy(dbm, df, 0.4)\n res_1 = st_1.compute_strategy()\n\n st_2 = main.portfolio_strategy.TSMOMStrategy(dbm, df, 0.4)\n res_2 = st_2.compute_strategy()\n \"\"\"\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target: float):\n self.dbm = dbm\n self.data = data\n self.n_t = None\n self.aggregated_assets = None\n self.table_in_assets = []\n self.sigma_target = sigma_target\n\n def __aggregate_assets(self):\n \"\"\"\n Joins PX_LAST of all assets.\n \"\"\"\n agg_assets, _ = self.dbm.get_table(self.data.index[0])\n\n agg_assets['PX_LAST_' + self.data.index[0]] = agg_assets['PX_LAST']\n agg_assets['PX_LAST_' + self.data.index[0]].fillna(method='ffill', inplace=True)\n agg_assets = agg_assets[['PX_LAST_' + self.data.index[0]]]\n\n table_present = np.zeros(self.data.shape[0])\n table_present[0] = 1\n i = 1\n\n for t in range(1, self.data.shape[0]):\n # if self.verbose:\n # print('Progress: {0:.2f}%'.format(i / self.data.shape[0]))\n\n tbl_name = self.data.index[t]\n df_curr, _ = self.dbm.get_table(tbl_name)\n\n if df_curr is not None:\n if df_curr.shape[0] < LOOKBACK_PERIOD_ANNUAL + 1:\n i += 1\n continue\n\n table_present[i] = 1\n\n df_curr['PX_LAST_' + tbl_name] = df_curr['PX_LAST']\n df_curr = df_curr[['PX_LAST_' + tbl_name]]\n\n agg_assets = agg_assets.join(df_curr, on='Dates', how='outer', sort=True)\n agg_assets.fillna(method='ffill', inplace=True)\n\n i += 1\n\n self.n_t = agg_assets.notna().sum(axis=1)\n self.aggregated_assets = agg_assets\n self.table_in_assets = table_present\n\n def __compute_annualized_returns(self, sd_window) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Computes annualized return and rolling standard deviation for lookback period.\n :return: tuple of daily return, annual return and rolling standard deviation of all assets. \n \"\"\"\n daily_ret = self.aggregated_assets.pct_change()\n annual_ret = self.aggregated_assets.pct_change(periods=LOOKBACK_PERIOD_ANNUAL)\n rolling_std = daily_ret.rolling(sd_window).std() * np.sqrt(LOOKBACK_PERIOD_ANNUAL)\n rolling_std[rolling_std < self.sigma_target / 10.0] = self.sigma_target / 10.0\n\n return daily_ret, annual_ret, rolling_std\n\n def pre_strategy(self, sd_window) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Prepares & computes the necessary variables needed before computating the strategy. \n :return: \n \"\"\"\n self.__aggregate_assets()\n daily_ret, annual_ret, rolling_std = self.__compute_annualized_returns(sd_window)\n\n return daily_ret, annual_ret, rolling_std\n\n @abstractmethod\n def compute_strategy(self, sd_window):\n pass\n\n\nclass ConstantVolatilityStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n asset_weight = self.sigma_target / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t, axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n\n\nclass TSMOMStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n annual_ret = annual_ret > 0\n annual_ret = (annual_ret * 2) - 1\n\n asset_weight = self.sigma_target * annual_ret / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t, axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n\n\nclass CorrAdjustedTSMOMStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n annual_ret_signed = (annual_ret > 0)\n annual_ret_signed = (annual_ret_signed * 2) - 1\n\n cf_list = []\n\n for t in range(annual_ret.shape[0]):\n curr_date = annual_ret.index[t]\n annual_ret_upto_curr = annual_ret[annual_ret.index <= curr_date]\n\n assets_present = annual_ret.columns[annual_ret.iloc[t].notnull()]\n\n if t % 100 == 0:\n print('Progress: {0:.2f}%'.format(int(t * 100 / self.n_t.shape[0])))\n\n annual_ret_upto_curr_assets = annual_ret_upto_curr[assets_present]\n annual_ret_upto_curr_assets = annual_ret_upto_curr_assets.dropna(how='all')\n\n if annual_ret_upto_curr_assets.shape[0] < 2 or annual_ret_upto_curr_assets.shape[1] < 2:\n cf_list.append(1)\n continue\n\n annual_ret_upto_curr_assets_signed = annual_ret_upto_curr_assets > 0\n annual_ret_upto_curr_assets_signed *= 2\n annual_ret_upto_curr_assets_signed -= 1\n\n asset_corr = annual_ret_upto_curr_assets.corr().values\n\n co_sign = np.eye(*asset_corr.shape)\n\n for i in range(co_sign.shape[0]):\n for j in range(i + 1, co_sign.shape[1]):\n temp = annual_ret_upto_curr_assets_signed.iloc[-1].values\n co_sign[i, j] = temp[i] * temp[j]\n co_sign[j, i] = temp[i] * temp[j]\n\n # N = self.n_t[t]\n N = asset_corr.shape[0]\n rho_bar = ((asset_corr * co_sign).sum() - asset_corr.shape[0]) / (N * (N - 1))\n temp = N / (1 + ((N - 1) * rho_bar))\n\n if temp < 0:\n print('Warning: negative value encountered for taking square root.')\n cf_list.append(1)\n continue\n\n cf_t = np.sqrt(temp)\n cf_list.append(cf_t)\n\n asset_weight = self.sigma_target * annual_ret_signed / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.mul(np.array(cf_list), axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t * np.array(cf_list), axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n","sub_path":"main/portfolio_strategy.py","file_name":"portfolio_strategy.py","file_ext":"py","file_size_in_byte":7462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"165142206","text":"import subprocess\nimport shlex\n\ndef run(**args):\n f_result = '../natypi/data/nmap_scan_result.txt'\n #command = 'nmap -T4 -A 192.168.0.1/24'\n command = 'nc -v 10.0.0.12 22'\n \n command = shlex.split(command)\n process = subprocess.Popen(command, stdout=subprocess.PIPE)\n output, err = process.communicate()\n result = '********** [ STDOUT ] **********\\n%s********** [ STDERR ] **********\\n%s' % (output, err)\n with open(f_result, 'w') as f:\n f.write(result)\n return result\n","sub_path":"modules/shell_cmd_nmap.py","file_name":"shell_cmd_nmap.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"629032054","text":"\"\"\" This rule checks for any unused security groups in AWS account.\n\"\"\"\n__version__ = '0.6.2'\n__author__ = 'Bhupender Kumar'\nimport boto3\nimport craws\nimport datetime\n\ndef handler(event, context):\n logger = craws.get_logger(name='UnusedSecurityGroups', level='DEBUG')\n logger.debug('Unused Security Groups check started')\n\n sts = boto3.client('sts')\n \n for account in craws.accounts:\n try:\n # Check if this rule has already been executed today for this account\n response = sts.assume_role(RoleArn='arn:aws:iam::926760075421:role/crawsExecution', RoleSessionName='GenerateReports')\n s3_client = boto3.client('s3', aws_access_key_id=response['Credentials']['AccessKeyId'], \n aws_secret_access_key=response['Credentials']['SecretAccessKey'], \n aws_session_token=response['Credentials']['SessionToken'])\n today = str(datetime.datetime.now().date())\n response = s3_client.head_object(Bucket = craws.bucket, Key = today+'/'+account['account_id']+'/UnusedSecurityGroups.json')\n logger.info('Account ' + account['account_id'] + ' already checked. Skipping.')\n except Exception:\n # This rule has not been executed today for this account, go ahead and execute\n results = {'Rule Name': 'Unused Custom Security Groups'}\n results['Area'] = 'EC2'\n results['Description'] = 'This rule checks the unused and dangling custom security groups in the AWS account. Security ' +\\\n 'groups that are not attached to any resource should be deleted to minimize the surface of attack.'\n details = []\n try:\n response = sts.assume_role(RoleArn=account['role_arn'], RoleSessionName='unused_SG')\n except Exception as e:\n logger.error(e)\n continue\n credentials = response['Credentials']\n regions = craws.get_region_descriptions()\n green_count = red_count = orange_count = yellow_count = grey_count = 0\n\n for region in regions:\n ec2_client = boto3.client('ec2', region_name=region['Id'],\n aws_access_key_id=credentials['AccessKeyId'], \n aws_secret_access_key=credentials['SecretAccessKey'], \n aws_session_token=credentials['SessionToken'])\n cloudtrail_client = boto3.client('cloudtrail', region_name=region['Id'],\n aws_access_key_id=credentials['AccessKeyId'], \n aws_secret_access_key=credentials['SecretAccessKey'], \n aws_session_token=credentials['SessionToken'])\n try:\n result = []\n sgrps = ec2_client.describe_security_groups()\n default_sgrps = set([sg['GroupId'] for sg in sgrps['SecurityGroups'] if \n sg['Description'] == 'default VPC security group' and sg['GroupName'] == 'default'])\n all_sgrps = set([sg['GroupId'] for sg in sgrps['SecurityGroups']])\n cstm_sgrps = set()\n cstm_sgrps = all_sgrps - default_sgrps\n used_sgrps = set()\n net_interface = ec2_client.describe_network_interfaces()\n for interface in net_interface['NetworkInterfaces']:\n for grp in interface['Groups']:\n used_sgrps.add(grp['GroupId'])\n green_count += len(list(used_sgrps))\n \n unused_sgs = cstm_sgrps - used_sgrps\n for unused_sec_grp in list(unused_sgs):\n # Some issues found, mark it as Red/Orange/Yellow depending on this check's risk level\n #details.append({'Status': craws.status['Red'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n orange_count += 1\n unused_sec_grp = craws.get_cloudtrail_data(lookup_value=unused_sec_grp, \n cloudtrail_client=cloudtrail_client, region_id=region['Id'])\n result.append({'Security Group Id': unused_sec_grp})\n \n except Exception as e:\n logger.error(e)\n # Exception occured, mark it as Grey (not checked)\n details.append({'Status': craws.status['Grey'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n grey_count += 1\n \n if len(result) == 0:\n # All good, mark it as Green\n #details.append({'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Status': craws.status['Green'], 'Result': result})\n details.append({'Status': craws.status['Green'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n else:\n # Some issues found, mark it as Red/Orange/Yellow depending on this check's risk level\n details.append({'Status': craws.status['Orange'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n\n results['Details'] = details\n results['GreenCount'] = green_count\n results['RedCount'] = red_count\n results['OrangeCount'] = orange_count\n results['YellowCount'] = yellow_count\n results['GreyCount'] = grey_count\n craws.upload_result_json(results, 'UnusedSecurityGroups.json', account['account_id'])\n logger.info('Results for account %s uploaded to s3', account['account_id'])\n\n logger.debug('Unused Security Groups check finished')\n\n","sub_path":"unused_security_groups.py","file_name":"unused_security_groups.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"383272556","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = []\r\nfor i in range(31):\r\n name = 'New_experiments/Q_learning_'+str(i+1)+'_all.csv'\r\n df = pd.read_csv(name)\r\n avg_roll = df['Reward']\r\n data.append(avg_roll)\r\n\r\ndata = np.array(data)\r\ndata_avg = data.mean(axis = 0)\r\ndata_std = data.std(axis = 0)\r\ndict = {'Average_data': data_avg}\r\ndf = pd.DataFrame(dict)\r\ndf['roll'] = df['Average_data'].rolling(window = 500).mean()\r\nvar = df['Average_data'].rolling(window = 500).std()\r\nx = np.arange(1, 100001, 1)\r\n\r\ndata = []\r\nfor i in range(31):\r\n name = 'New_experiments/Q_learning_'+str(i+1)+'.csv'\r\n df = pd.read_csv(name)\r\n avg_roll = df['Avg_rewards']\r\n data.append(avg_roll)\r\n\r\ndata = np.array(data)\r\ndata_avg = data.mean(axis = 0)\r\ndata_std = data.std(axis = 0)\r\ndict = {'Average_data': data_avg}\r\ndf1 = pd.DataFrame(dict)\r\ndf1['roll'] = df1['Average_data'].rolling(window = 200).mean()\r\nvar1 = df1['Average_data'].rolling(window = 200).std()\r\nx1 = np.arange(1, 100001, 10)\r\n\r\nplt.plot(x, df['rolling'], c = 'blue')\r\nplt.fill_between(x, df['rolling']-var, df['rolling']+var, facecolor = 'blue', alpha = 0.2)\r\nplt.plot(x, df1['rolling'], c = 'red')\r\nplt.fill_between(x, df1['rolling']-var1, df1['rolling']+var1, facecolor = 'red', alpha = 0.2)\r\nplt.show()\r\n","sub_path":"Transfer/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"617260575","text":"from decimal import Decimal\nfrom datetime import timedelta, datetime\nfrom model_mommy import mommy\nfrom django.test import TestCase\nfrom callcenter.models import CallRecord, Bill, PriceRule\n\n\nclass CallRecordTest(TestCase):\n def setUp(self):\n self.call_record = mommy.make(\n CallRecord, pk=10, type=1, timestamp='2018-11-25 08:08:08',\n call_id=50, source='11986091154', destination='11988888888'\n )\n\n def test_call_record_creation(self):\n self.assertTrue(isinstance(self.call_record, CallRecord))\n self.assertEquals(self.call_record.type, 1)\n self.assertEquals(self.call_record.call_id, 50)\n self.assertEquals(self.call_record.timestamp, '2018-11-25 08:08:08')\n self.assertEquals(self.call_record.source, '11986091154')\n self.assertEquals(self.call_record.destination, '11988888888')\n self.assertEquals(self.call_record.__str__(), '11986091154')\n\n\nclass BillTest(TestCase):\n def setUp(self):\n self.call_record_start_one = mommy.make(\n CallRecord, pk=1, type=1, timestamp='2018-10-31 23:55:00',\n call_id=1, source='11999998888', destination='11982223454'\n )\n\n self.call_record_end_one = mommy.make(\n CallRecord, pk=2, type=2, timestamp='2018-11-2 00:01:08',\n call_id=1, source='', destination=''\n )\n\n def test_create(self):\n bill_instance = Bill()\n bill_data_to_save = {\n 'call': CallRecord.objects.get(id=2),\n 'cost': 12.76,\n 'call_duration': timedelta(hours=24, minutes=6, seconds=8),\n 'call_start': datetime(2018, 10, 31, 23, 55, 00),\n 'call_end': datetime(2018, 11, 2, 00, 1, 8),\n 'month': 11,\n 'year': 2018\n }\n\n bill_instance.create(bill_data=bill_data_to_save)\n\n def test_call_record_creation_exception(self):\n bill_instance = Bill()\n bill_data_to_save = {\n 'call': CallRecord.objects.get(id=2),\n 'cost': 12.76,\n 'call_duration': timedelta(hours=24, minutes=6, seconds=8),\n 'call_start': datetime(2018, 10, 31, 23, 55, 00),\n 'call_end': timedelta(hours=10),\n 'month': 11,\n 'year': 2018\n }\n\n expected = (\n '[\"\\'10:00:00\\' value has an invalid format. It must '\n 'be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.\"]'\n )\n\n actual = bill_instance.create(bill_data=bill_data_to_save)\n\n self.assertEqual(actual, expected)\n\n\nclass PriceRuleTest(TestCase):\n def setUp(self):\n self.price_rule = mommy.make(\n PriceRule, pk=1, rule_type=1, fixed_charge=Decimal('0.36'),\n call_charge=Decimal('0.09'),\n start_period=datetime(2018, 7, 10, 22, 0, 0).time(),\n end_period=datetime(2018, 7, 10, 6, 0, 0).time()\n )\n\n def test_price_rule_create(self):\n price_rule_one = PriceRule.objects.get(id=1)\n\n self.assertEqual(\n self.price_rule.rule_type,\n price_rule_one.rule_type\n )\n self.assertEqual(\n self.price_rule.fixed_charge,\n price_rule_one.fixed_charge\n )\n self.assertEqual(\n self.price_rule.call_charge,\n price_rule_one.call_charge\n )\n self.assertEqual(\n self.price_rule.start_period,\n price_rule_one.start_period\n )\n self.assertEqual(\n self.price_rule.end_period,\n price_rule_one.end_period\n )\n","sub_path":"callcenter/tests/tests_models.py","file_name":"tests_models.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"21037305","text":"def swapingFileData():\n file1=input(\"Give Original File: \")\n file2=input(\"Give the file to be swapped:\")\n\n with open(file1, 'r') as a:\n data_a=a.read()\n with open(file2, 'r') as b:\n data_b=b.read()\n\n with open(file1, 'w+') as a:\n a.write(data_a)\n with open(file2, 'w+') as b:\n b.write(data_b)\n\nswapingFileData()\n\n \n","sub_path":"swapingFile.py","file_name":"swapingFile.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"290828025","text":"\"\"\"validate prosper.test_utils.schema_utils\"\"\"\nimport datetime\nimport json\nimport jsonschema\nimport pathlib\nfrom plumbum import local\n\nimport pytest\nimport helpers\n\nimport prosper.test_utils.schema_utils as schema_utils\nimport prosper.test_utils.exceptions as exceptions\nimport prosper.test_utils._version as _version\n\n@pytest.fixture\ndef mongo_fixture(tmpdir):\n \"\"\"helper for making testmode mongo context managers\n\n Args:\n tmpdir: PyTest magic\n\n Returns:\n schema_utils.MongoContextManager: in tinydb mode\n\n \"\"\"\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n _testmode_filepath=tmpdir,\n _testmode=True,\n )\n return mongo_context\n\n\nclass TestMongoContextManager:\n \"\"\"validate expected behavior for MongoContextManager\"\"\"\n demo_data = [\n {'butts': True, 'many': 10},\n {'butts': False, 'many': 100},\n ]\n def test_mongo_context_testmode(self, tmpdir):\n \"\"\"test with _testmode enabled\"\"\"\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n _testmode=True,\n _testmode_filepath=tmpdir,\n )\n\n with mongo_context as t_mongo:\n t_mongo['test_collection'].insert(self.demo_data)\n\n with mongo_context as t_mongo:\n data = t_mongo['test_collection'].find_one({'butts': True})\n\n assert data['many'] == 10\n\n def test_mongo_context_prodmode(self):\n \"\"\"test against real mongo\"\"\"\n if not helpers.can_connect_to_mongo(helpers.TEST_CONFIG):\n pytest.xfail('no mongo credentials')\n\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n )\n\n with mongo_context as mongo:\n mongo['test_collection'].insert(self.demo_data)\n\n with mongo_context as _:\n data = mongo['test_collection'].find_one({'butts': True})\n\n assert data['many'] == 10\n\n\nclass TestFetchLatestSchema:\n \"\"\"validate expected behavior for fetch_latest_schema()\"\"\"\n fake_schema_table = [\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.0.0',\n 'schema':{'result':'NOPE'}},\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.1.0',\n 'schema':{'result':'NOPE'}},\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.1.1',\n 'schema':{'result':'YUP'}},\n {'schema_group':'not_test', 'schema_name':'fake.schema', 'version':'1.1.2',\n 'schema':{'result':'NOPE'}},\n ]\n def test_fetch_latest_version(self, mongo_fixture):\n \"\"\"try to find latest schema\"\"\"\n collection_name = 'fake_schema_table'\n\n with mongo_fixture as t_mongo:\n t_mongo[collection_name].insert(self.fake_schema_table)\n\n with mongo_fixture as t_mongo:\n latest_schema = schema_utils.fetch_latest_schema(\n 'fake.schema',\n 'test',\n t_mongo[collection_name]\n )\n\n assert latest_schema['schema'] == {'result': 'YUP'}\n assert latest_schema['version'] == '1.1.1'\n\n def test_fetch_latest_version_empty(self, mongo_fixture):\n \"\"\"make sure function returns expected for no content\"\"\"\n collection_name = 'blank_schema_table'\n\n with pytest.warns(exceptions.FirstRunWarning):\n with mongo_fixture as t_mongo:\n latest_schema = schema_utils.fetch_latest_schema(\n 'fake.schema',\n 'test',\n t_mongo[collection_name]\n )\n\n assert latest_schema['schema'] == {}\n assert latest_schema['version'] == '1.0.0'\n\n\nclass TestCompareSchemas:\n \"\"\"validate expected behavior for compare_schemas()\"\"\"\n base_schema = helpers.load_schema_from_file('base_schema.json')\n minor_change = helpers.load_schema_from_file('minor_schema_change.json')\n major_removed_value = helpers.load_schema_from_file('major_items_removed.json')\n #major_values_changed = helpers.load_schema_from_file('major_values_changed.json')\n unhandled_diff = set(helpers.load_schema_from_file('unhandled_diff.json'))\n\n def test_compare_schemas_happypath(self):\n \"\"\"make sure equivalence works as expected\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.base_schema\n )\n\n assert status == schema_utils.Update.no_update\n\n def test_compare_schemas_minor(self):\n \"\"\"make sure minor updates are tagged as such\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.minor_change\n )\n\n assert status == schema_utils.Update.minor\n\n def test_compare_schemas_major(self):\n \"\"\"make sure major updates are tagged as such\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.major_removed_value\n )\n\n assert status == schema_utils.Update.major\n\n\n def test_compare_schemas_empty(self):\n \"\"\"make sure empty case signals first-run\"\"\"\n status = schema_utils.compare_schemas(\n {},\n self.base_schema,\n )\n\n assert status == schema_utils.Update.first_run\n\n def test_compare_schemas_error(self):\n \"\"\"make sure raises for really screwed up case\"\"\"\n pytest.xfail('compare_schemas raise case not working yet')\n with pytest.raises(exceptions.UnhandledDiff):\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.unhandled_diff\n )\n\n\nclass TestBuildMetadata:\n \"\"\"validate expected behavior for build_metadata()\"\"\"\n fake_metadata = {\n 'schema_group': 'fake_group',\n 'schema_name': 'fake_name',\n 'update': datetime.datetime.utcnow().isoformat(),\n 'version': '1.2.1',\n 'schema': {'type': 'DONTCARE'},\n }\n dummy_schema = {'fake': 'DONTCARE'}\n\n def test_build_schema_no_update(self):\n \"\"\"assert behavior for no_update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.no_update,\n )\n assert metadata == self.fake_metadata\n\n def test_build_schema_first_run(self):\n \"\"\"assert behavior for first_run\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.first_run,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == self.fake_metadata['version']\n\n def test_build_schema_minor(self):\n \"\"\"assert behavior for minor update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.minor,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == '1.2.2'\n\n def test_build_schema_major(self):\n \"\"\"assert behavior for major update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.major,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == '1.3.0'\n\n def test_build_schema_badschema(self):\n \"\"\"assert behavior for bad schema\"\"\"\n dummy_meta = {\n 'schema': '',\n 'version': '1.0.0',\n 'update': datetime.datetime.utcnow().isoformat(),\n }\n\n with pytest.raises(jsonschema.exceptions.ValidationError):\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n dummy_meta,\n schema_utils.Update.first_run\n )\n\n\nclass TestDumpMajorUpdate:\n \"\"\"validate expected behavior for dump_major_update()\"\"\"\n\n dummy_metadata1 = {'butts': 'yes'}\n dummy_metadata2 = {'butts': 'no'}\n def test_dump_major_udpate_empty(self, tmpdir):\n \"\"\"validate system doesn't raise for empty data\"\"\"\n filename = tmpdir / 'empty.json'\n schema_utils.dump_major_update(\n self.dummy_metadata1,\n filename,\n )\n\n with open(str(filename), 'r') as tmp_fh:\n saved_data = json.load(tmp_fh)\n\n assert saved_data[0] == self.dummy_metadata1\n\n\n def test_dump_major_update_exists(self, tmpdir):\n \"\"\"validate system appends new metadata to report\"\"\"\n filename = tmpdir / 'exists.json'\n with open(str(filename), 'w') as tmp_fh:\n json.dump([self.dummy_metadata1], tmp_fh)\n\n schema_utils.dump_major_update(\n self.dummy_metadata2,\n filename,\n )\n\n with open(str(filename), 'r') as tmp_fh:\n saved_data = json.load(tmp_fh)\n\n assert saved_data[1] == self.dummy_metadata2\n\n\nclass TestSchemaHelper:\n \"\"\"validate expected behavior for schema_helper()\"\"\"\n base_sample = helpers.load_schema_from_file('base_sample.json')\n minor_sample = helpers.load_schema_from_file('minor_sample.json')\n major_sample = helpers.load_schema_from_file('major_sample.json')\n\n name = 'dummy_name'\n group = 'dummy_group'\n collection = 'TESTSCHEMA_'\n\n def do_the_thing(self, mongo_fixture, data, collection):\n \"\"\"helper: run schema_utils.schema_helper\"\"\"\n schema_utils.schema_helper(\n data=data,\n data_source='DONTCARE',\n schema_name=self.name,\n schema_group=self.group,\n config=helpers.TEST_CONFIG,\n _collection_name=collection,\n _testmode=True,\n _dump_filepath=str(mongo_fixture._testmode_filepath),\n )\n\n def test_schema_helper_blank(self, mongo_fixture):\n \"\"\"exercise first_run path\"\"\"\n collection = self.collection + __name__\n with pytest.warns(exceptions.FirstRunWarning):\n self.do_the_thing(\n mongo_fixture, self.base_sample, self.collection + __name__)\n\n with mongo_fixture as t_mongo:\n results = list(t_mongo[collection].find({}))\n\n assert results[0]['version'] == '1.0.0'\n\n def test_schema_helper_no_update(self, mongo_fixture):\n \"\"\"exercise no_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n self.do_the_thing(\n mongo_fixture, self.base_sample, collection\n )\n\n with mongo_fixture as t_mongo:\n results = list(t_mongo[collection].find({}))\n\n assert results[0] == written_metadata\n\n def test_schema_helper_minor_update(self, mongo_fixture):\n \"\"\"exercise minor_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n self.do_the_thing(\n mongo_fixture, self.minor_sample, collection\n )\n\n with mongo_fixture as t_mongo:\n updated_metadata = schema_utils.fetch_latest_schema(\n self.name, self.group, t_mongo[collection]\n )\n\n #sanitize outputs\n written_metadata.pop('_id', None)\n updated_metadata.pop('_id', None)\n\n assert updated_metadata != written_metadata\n assert updated_metadata['version'] == '1.1.1'\n\n def test_schema_helper_major_update(self, mongo_fixture):\n \"\"\"exercise major_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n with pytest.raises(exceptions.MajorSchemaUpdate) as e:\n self.do_the_thing(\n mongo_fixture, self.major_sample, collection\n )\n with open(str(e.value), 'r') as major_fh:\n major_update_list = json.load(major_fh)\n\n todo_metadata = major_update_list[0]\n assert todo_metadata['version'] == '1.2.0'\n\n with mongo_fixture as t_mongo:\n updated_metadata = schema_utils.fetch_latest_schema(\n self.name, self.group, t_mongo[collection]\n )\n\n #sanitize outputs\n written_metadata.pop('_id', None)\n updated_metadata.pop('_id', None)\n\n assert updated_metadata['version'] == '1.1.0'\n\nclass TestCLI:\n \"\"\"validate update-prosper-schemas behavior\"\"\"\n CLI_name = 'update-prosper-schemas'\n update_command = local['update-prosper-schemas']\n update_path = pathlib.Path(helpers.HERE) / 'dummy-schema-update.json'\n\n def test_cli_help(self):\n \"\"\"make sure help command works\"\"\"\n output = self.update_command('-h')\n\n def test_cli_name(self):\n \"\"\"make sure --version command works\"\"\"\n output = self.update_command('--version').strip()\n\n assert output == '{cli_name} {version}'.format(\n cli_name=self.CLI_name, version=_version.__version__\n )\n\n def test_cli_happypath(self, tmpdir):\n \"\"\"dry-run CLI\"\"\"\n collection_name = 'TESTDUMMY'\n output = self.update_command(\n self.update_path,\n '--verbose',\n '--debug',\n '--local-dir={}'.format(tmpdir),\n '--collection={}'.format(collection_name),\n )\n\n mongo_context = schema_utils.MongoContextManager(\n config=helpers.ROOT_CONFIG,\n _testmode=True,\n _testmode_filepath=tmpdir,\n )\n mongo_context.database = 'TESTprosper'\n with mongo_context as t_mongo:\n results = t_mongo[collection_name].find_one({})\n\n with open(str(self.update_path), 'r') as update_fh:\n expected_results = json.load(update_fh)\n\n results.pop('_id')\n print(expected_results[0])\n print(results)\n assert results == expected_results[0]\n","sub_path":"tests/test_schema_utils.py","file_name":"test_schema_utils.py","file_ext":"py","file_size_in_byte":14715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"232528997","text":"import os \n\nfrom requests import post, codes\nfrom flask import jsonify, request, session\nfrom json import dumps\nfrom random import randint\nfrom pubnub_client import send_message\n\nfrom defaults import (CHILD_MDN,\n ACTION_URL,\n FOUNDRY_AUTH_URL)\n\n\nfrom subscription_manager import create_subscription\n\ndef create_routes(app):\n @app.route('/')\n def hello_world():\n return 'Hello World!'\n \n @app.route(\"/auth\", methods=[\"POST\"])\n def auth():\n \"\"\"\n 1. Creates an auth token that gets stored in the session itself.\n 2. Creates a call direciton subscription for a hardcoded mdn\n\n Return 401 if it can't create an auth\n Return 200 if the auth token was created and a subscription already existed for the mdn\n Return 201 if the auth token was created and a subscription was created for the mdn\n \"\"\"\n payload = {\n \"client_id\": app.config['CONSUMER_KEY'],\n \"client_secret\": app.config['CONSUMER_SECRET']\n }\n\n # This doesn't have to have content-type json because the OAuth Token request\n # expects a content type of \"Content-Type: application/x-www-form-urlencoded\",\n # aka the default behavior of requests.\n result = post(url=FOUNDRY_AUTH_URL, data=payload)\n\n if result.status_code != codes.ok:\n return \"Unable to create auth token\", codes.UNAUTHORIZED\n\n app.config[\"AUTH_TOKEN\"] = result.json()[\"access_token\"]\n app.logger.debug(\"Created an auth token: \" + app.config[\"AUTH_TOKEN\"])\n\n return create_subscription(app, CHILD_MDN)\n\n @app.route(\"/auth\", methods=[\"GET\"])\n def get_auth_token():\n if not \"auth_token\" in session:\n return \"No auth token found\", codes.NOT_FOUND\n\n return session[\"auth_token\"], codes.OK\n \n\n @app.route(\"/callback\", methods=[\"POST\"])\n def callback():\n \"\"\"\n Each subscription has a unique callback url. For now, \n use a common callback url endpoint that will defer all calls.\n \"\"\"\n\n caller = request.json['eventNotification']['callingParticipant']\n\n # We have the ability to maintain a record of the request to defer\n # via a unique decision id. For now, we'll just use the caller and a \n # random int\n decision_id = caller + str(randint(0, 10000))\n app.config[\"DECISION_ID\"] = decision_id\n\n send_message(app, request.json)\n\n callback_response = {\n \"actionToPerform\": \"Deferred\",\n \"routingAddress\": decision_id + \";display=originator\",\n \"decisionId\": decision_id\n }\n\n return jsonify(action=callback_response)\n\n @app.route(\"/action\", methods=[\"POST\"])\n def action():\n \"\"\"\n Based on the deferred decision id and the subscription id, make a decision on the call.\n ACTIONS: EndCall, Route, Continue\n \"\"\"\n subscription_id = app.config[\"SUB_ID\"]\n decision_id = app.config[\"DECISION_ID\"]\n action = request.json[\"action\"]\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(app.config[\"AUTH_TOKEN\"]),\n }\n\n decision_url = ACTION_URL.format(subscription_id, decision_id, action)\n\n if action == \"Route\":\n headers[\"Content-Type\"] = \"application/json\"\n route_addr = request.json['routeAddress']\n decision_url += \"?routeAddr={route_addr}\".format(route_addr=route_addr)\n app.logger.debug(\"Routing call to: \" + decision_url)\n result = post(url=decision_url,\n headers=headers,\n data=dumps({\"display\": \"originator\"}))\n else:\n headers[\"Content-Length\"] = 0\n result = post(url=decision_url,\n headers=headers)\n\n return result.text, result.status_code\n\n\n","sub_path":"controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"339928373","text":"#-----------------------------------------------------------\n# Licensed under the terms of GNU GPL 2\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#---------------------------------------------------------------------\n# Tim Hancock/Matthias Kuhn 2017\n\nfrom qgis.PyQt.QtCore import (\n QObject,\n QDate,\n pyqtSignal\n)\n\nfrom qgis.PyQt.QtWidgets import (\n QMessageBox,\n QAction\n)\n\nfrom qgis.core import (\n QgsMessageLog, QgsFeature, QgsGeometry,\n QgsFeatureRequest,\n QgsRectangle, QgsExpression\n)\n\nfrom ..proposalTypeUtilsClass import ProposalTypeUtilsMixin\n\n#from .TOMsProposalElement import *\nfrom ..core.TOMsProposal import (TOMsProposal)\n\nfrom ..constants import (\n ProposalStatus,\n RestrictionAction\n)\n\nclass TOMsTile(QObject):\n def __init__(self, proposalsManager, tileNr=None):\n QObject.__init__(self)\n\n self.proposalsManager = proposalsManager\n self.tableNames = self.proposalsManager.tableNames\n\n self.setTilesLayer()\n\n if tileNr is not None:\n self.setTile(tileNr)\n\n def setTilesLayer(self):\n self.tilesLayer = self.tableNames.setLayer(\"MapGrid\")\n if self.tilesLayer is None:\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer. tilesLayer layer NOT set !!!\", tag=\"TOMs panel\")\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer... \", tag=\"TOMs panel\")\n\n self.tilesInAcceptedProposalsLayer = self.tableNames.setLayer(\"TilesInAcceptedProposals\")\n if self.tilesLayer is None:\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer. tilesInAcceptedProposalsLayer layer NOT set !!!\", tag=\"TOMs panel\")\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer... tilesInAcceptedProposalsLayer \", tag=\"TOMs panel\")\n\n def setTile(self, tileNr):\n\n self.thisTileNr = tileNr\n self.setTilesLayer()\n\n if (tileNr is not None):\n query = '\\\"tileNr\\\" = {tileNr}'.format(proposalID=tileNr)\n request = QgsFeatureRequest().setFilterExpression(query)\n for tile in self.tilesLayer.getFeatures(request):\n self.thisTile = tile # make assumption that only one row\n return True\n\n return False # either not found or 0\n\n def tile(self):\n return self\n\n def tileNr(self):\n return self.thisTileNr\n\n def revisionNr(self):\n return self.thisTile.attribute(\"RevisionNr\")\n\n def setRevisionNr(self, value):\n return self.thisTile.setAttribute(\"RevisionNr\", value)\n\n def lastRevisionDate(self):\n return self.thisTile.attribute(\"LastRevisionDate\")\n\n def setLastRevisionDate(self, value):\n return self.thisTile.setAttribute(\"LastRevisionDate\", value)\n\n def getTileRevisionNrAtDate(self, filterDate=None):\n\n QgsMessageLog.logMessage(\"In TOMsTile:getTileRevisionNrAtDate.\", tag=\"TOMs panel\")\n\n if filterDate is None:\n filterDate = self.proposalsManager.date()\n\n #query2 = '\"tile\" = \\'{tileid}\\''.format(tileid=currTile)\n\n queryString = \"\\\"TileNr\\\" = \" + str(self.thisTileNr)\n\n QgsMessageLog.logMessage(\"In getTileRevisionNrAtDate: queryString: \" + str(queryString), tag=\"TOMs panel\")\n\n expr = QgsExpression(queryString)\n\n # Grab the results from the layer\n features = self.tilesInAcceptedProposalsLayer.getFeatures(QgsFeatureRequest(expr))\n tileProposal = TOMsProposal(self)\n\n for feature in sorted(features, key=lambda f: f[2], reverse=True):\n lastProposalID = feature[\"ProposalID\"]\n lastRevisionNr = feature[\"RevisionNr\"]\n\n tileProposal.setProposal(lastProposalID)\n\n #lastProposalOpendate = self.proposalsManager.getProposalOpenDate(lastProposalID)\n lastProposalOpendate = tileProposal.getProposalOpenDate()\n\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: last Proposal: \" + str(lastProposalID) + \"; \" + str(lastRevisionNr),\n tag=\"TOMs panel\")\n\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: last Proposal open date: \" + str(lastProposalOpendate) + \"; filter date: \" + str(filterDate),\n tag=\"TOMs panel\")\n\n if lastProposalOpendate <= filterDate:\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: using Proposal: \" + str(lastProposalID) + \"; \" + str(lastRevisionNr),\n tag=\"TOMs panel\")\n return lastRevisionNr, lastProposalOpendate\n\n return 0, None\n\n def updateTileRevisionNr(self):\n\n QgsMessageLog.logMessage(\n \"In TOMsTile:updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" currRevNr: \", tag=\"TOMs panel\")\n\n # This will update the revision numberwithin \"Tiles\" and add a record to \"TilesWithinAcceptedProposals\"\n\n currProposal = self.proposalsManager.currentProposalObject()\n\n # check that there are no revisions beyond this date\n if self.lastRevisionDate < currProposal.getProposalOpenDate():\n QgsMessageLog.logMessage(\n \"In updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" revision numbers are out of sync\",\n tag=\"TOMs panel\")\n QMessageBox.information(self.iface.mainWindow(), \"ERROR\", (\"In updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" revision numbers are out of sync\"))\n return False\n\n if self.revisionNr() is None:\n newRevisionNr = 1\n else:\n newRevisionNr = self.revisionNr() + 1\n\n self.setRevisionNr(newRevisionNr)\n self.setLastRevisionDate(currProposal.getProposalOpenDate())\n\n # Now need to add the details of this tile to \"TilesWithinAcceptedProposals\" (including revision numbers at time of acceptance)\n\n newRecord = QgsFeature(self.tilesInAcceptedProposalsLayer.fields())\n\n idxProposalID = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"ProposalID\")\n idxTileNr = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"TileNr\")\n idxRevisionNr = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"RevisionNr\")\n\n newRecord[idxProposalID] = currProposal.getProposalNr()\n newRecord[idxTileNr] = self.thisTileNr\n newRecord[idxRevisionNr] = newRevisionNr\n newRecord.setGeometry(QgsGeometry())\n\n status = self.tilesInAcceptedProposalsLayer.addFeature(newRecord)\n\n return status\n\n\n","sub_path":"core/TOMsTile.py","file_name":"TOMsTile.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224998346","text":"\r\nfrom PyQt4 import QtCore, QtGui, Qt\r\nfrom PyQt4.QtCore import *\r\nfrom PyQt4.QtGui import *\r\nimport ImageWindow\r\nimport NewMapWindow\r\n\r\n\r\nclass ToolBox(QtGui.QFrame):\r\n def __init__(self, parent=None):\r\n super(ToolBox, self).__init__(parent)\r\n \r\n self.newMap = QPushButton(\"new map\")\r\n self.newMap.clicked.connect(self.newMapDialog)\r\n \r\n self.loadImage = QPushButton(\"load image\")\r\n self.loadImage.clicked.connect(self.loadImageDialog)\r\n \r\n self.loadMap = QPushButton(\"load map\")\r\n self.loadMap.clicked.connect(self.loadMapDialog)\r\n \r\n self.saveMap = QPushButton(\"save map\")\r\n self.saveMap.clicked.connect(self.saveMapDialog)\r\n \r\n self.mapGrid = QCheckBox(\"grid on map\")\r\n self.mapGrid.stateChanged.connect(self.toggleMapGrid)\r\n \r\n self.imageGrid = QCheckBox(\"grid on image\")\r\n self.imageGrid.stateChanged.connect(self.toggleImageGrid)\r\n \r\n self.layerSpinBox = QSpinBox()\r\n self.layerSpinBox.setRange(0, 2)\r\n self.layerSpinBox.valueChanged.connect(self.layerChanged)\r\n \r\n self.bgColor = QPushButton(\"background\")\r\n self.bgColor.clicked.connect(self.setBgColor)\r\n \r\n self.editCollision = QCheckBox(\"edit collision\")\r\n self.editCollision.stateChanged.connect(self.toggleEditCollision)\r\n \r\n self.imageWindow = ImageWindow.ImageWindow()\r\n \r\n buttonLayout = QtGui.QGridLayout()\r\n buttonLayout.addWidget(self.newMap, 0, 0)\r\n buttonLayout.addWidget(self.loadImage, 1, 0)\r\n buttonLayout.addWidget(self.loadMap, 0, 1)\r\n buttonLayout.addWidget(self.saveMap, 1, 1)\r\n \r\n gridLayout = QtGui.QHBoxLayout()\r\n gridLayout.addWidget(self.mapGrid)\r\n gridLayout.addWidget(self.imageGrid)\r\n \r\n layerLayout = QtGui.QHBoxLayout()\r\n layerLayout.addWidget(self.layerSpinBox)\r\n layerLayout.addWidget(self.bgColor)\r\n \r\n \r\n mainLayout = QtGui.QVBoxLayout()\r\n mainLayout.addLayout(buttonLayout)\r\n mainLayout.addWidget(self.imageWindow)\r\n mainLayout.addLayout(gridLayout)\r\n mainLayout.addLayout(layerLayout)\r\n mainLayout.addWidget(self.editCollision)\r\n \r\n self.setLayout(mainLayout)\r\n \r\n def loadImageDialog(self):\r\n file = QFileDialog.getOpenFileName(None, \"open image\", QString(), \"Images (*.png *.jpg *.gif)\")\r\n self.imageWindow.loadImage(file)\r\n \r\n def loadMapDialog(self):\r\n file = QFileDialog.getOpenFileName(None, \"open map\", QString(), \"Map (*.txt)\")\r\n if file == '' or file is None:\r\n return\r\n self.mapWindow.loadMap(file)\r\n \r\n \r\n def saveMapDialog(self):\r\n file = QFileDialog.getSaveFileName(None, \"save map\", QString(), \"Map (*.txt)\")\r\n if file == '' or file is None:\r\n return\r\n self.mapWindow.saveMap(file)\r\n \r\n def newMapDialog(self):\r\n d = NewMapWindow.NewMapDialog(self)\r\n if d.exec_() == QDialog.Accepted:\r\n \r\n self.mapWindow.mapArea.mapWidth = d.widthLine.value()\r\n self.mapWindow.mapArea.mapHeight = d.heightLine.value()\r\n self.mapWindow.mapArea.gridSize = d.gridSizeLine.value()\r\n self.mapWindow.mapArea.create()\r\n self.imageWindow.imageArea.gridsize = d.gridSizeLine.value()\r\n \r\n def toggleMapGrid(self, e):\r\n if e == Qt.Unchecked:\r\n self.mapWindow.mapArea.drawGrid = False\r\n elif e == Qt.Checked:\r\n self.mapWindow.mapArea.drawGrid = True\r\n self.mapWindow.mapArea.update()\r\n \r\n def toggleImageGrid(self, e):\r\n if e == Qt.Unchecked:\r\n self.imageWindow.imageArea.drawGrid = False\r\n elif e == Qt.Checked:\r\n self.imageWindow.imageArea.drawGrid = True\r\n self.imageWindow.imageArea.update()\r\n \r\n def layerChanged(self, val):\r\n self.mapWindow.mapArea.layer = val\r\n \r\n def setBgColor(self):\r\n color = QColorDialog.getColor(self.mapWindow.mapArea.bgColor)\r\n self.mapWindow.mapArea.bgColor = color\r\n self.mapWindow.mapArea.update()\r\n \r\n def toggleEditCollision(self, e):\r\n if e == Qt.Unchecked:\r\n self.mapWindow.mapArea.editCollision = False\r\n elif e == Qt.Checked:\r\n self.mapWindow.mapArea.editCollision = True\r\n self.mapWindow.mapArea.update()\r\n \r\n ","sub_path":"ToolBox.py","file_name":"ToolBox.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"135421425","text":"class Solution:\n \"\"\"\n @param n: The integer n\n @param k: The integer k\n @return: Return the combination\n \"\"\"\n def getCombination(self, n, k):\n comb = [[-1 for j in range(n//2 + 1)] for i in range(n+1)]\n def get_comb(n, m):\n if comb[n][m] != -1: return comb[n][m]\n if m == 0 or n == m:\n comb[n][m] = 1\n else:\n comb[n][m] = get_comb(n-1, m-1) + get_comb(n-1, m)\n return comb[n][m]\n\n ans = [-1] * (n//2)\n pos = -1\n for i in range(n//2):\n cnt = 0\n for j in range(pos+1, n):\n v = get_comb(n-j-1, n//2-i-1)\n if k-v <= 0:\n pos = j\n break\n k -= v\n\n ans[i] = pos+1\n\n return ans\n\n\nsol = Solution()\nprint(sol.getCombination(18, 3014))\n","sub_path":"lint/1500/1464.py","file_name":"1464.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224531666","text":"## License: Apache 2.0. See LICENSE file in root directory.\n## Copyright(c) 2017 Intel Corporation. All Rights Reserved.\n\n#####################################################\n## Align Depth to Color ##\n#####################################################\nimport sys\n\nsy_root = '/home/nvidia/realsense/librealsense-master/build/wrappers/python'\nsys.path.insert(0, sy_root)\n# First import the library\n#import pyrealsense2 as rs\n# Import Numpy for easy array manipulation\nimport numpy as np\n# Import OpenCV for easy image rendering\nimport cv2\nimport numpy as np\nimport time\n\ndef hough(picture):\n img=cv2.cvtColor(picture, cv2.COLOR_RGB2GRAY)\n #uu=rgb2gray(picture)\n cv2.imshow(\"gray\", img)\n #gradX = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx = 1, dy = 0, ksize = -1)\n #gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)\n\n #cv2.imshow(\"gradX\", gradX)\n #x=cv2.waitKey(1)& 0xFF\n #cv2.imshow(\"gradY\", gradY)\n #x=cv2.waitKey(1)\n # subtract the y-gradient from the x-gradient\n #gradient = cv2.subtract(gradX, gradY)\n #img = cv2.convertScaleAbs(gradient)\n img = cv2.blur(img, (3, 3))\n edges = cv2.Canny(img, 50, 150, apertureSize=3)\n cv2.imshow('cannyuu',edges)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 118) # 这里对最后一个参数使用了经验型的值\n result = img.copy()\n shuipingx=[]\n if(lines is not None):\n for lop in range(int(lines.size/2)):\n for line in lines[lop]:\n rho = line[0] # 第一个元素是距离rho\n theta = line[1] # 第二个元素是角度theta\n print(rho)\n print(theta)\n if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): # 垂直直线\n # 该直线与第一行的交点\n pt1 = (int(rho / np.cos(theta)), 0)\n # 该直线与最后一行的焦点\n pt2 = (int((rho - result.shape[0] * np.sin(theta)) / np.cos(theta)), result.shape[0])\n # 绘制一条白线\n cv2.line(result, pt1, pt2,0,1)\n else: # 水平直线\n # 该直线与第一列的交点\n pt1 = (0, int(rho / np.sin(theta)))\n # 该直线与最后一列的交点\n pt2 = (result.shape[1], int((rho - result.shape[1] * np.cos(theta)) / np.sin(theta)))\n # 绘制一条直线\n if(pt2[0]-pt1[0]>0):\n cv2.line(result, pt1, pt2,0, 1)\n shuipingx.append(pt1[1])\n print(('pt2=',pt2,'pt1 =',pt1))\n #if shuipingx>0:\n # break\n return result, shuipingx\ndef imgread(picture,imgcutxia, r, g, b):\n x = (imgcutxia[:, :, 0] > r)\n y = (imgcutxia[:, :, 1] > g)\n z = (imgcutxia[:, :, 2] > b)\n imgcutxia[(x & y & z), :] = 0\n x = (imgcutxia[:, :, 0] < 8)\n y = (imgcutxia[:, :, 1] < 8)\n z = (imgcutxia[:, :, 2] < 8)\n imgcutxia[(x & y & z), :] = 0\n \"\"\"\n NpKernel = np.uint8(np.zeros((3, 3)))\n for i in range(3):\n NpKernel[2, i] = 1 # 感谢chenpingjun1990的提醒,现在是正确的\n NpKernel[i, 2] = 1\n imgcutxia = cv2.erode(imgcutxia, NpKernel)\n \"\"\"\n x = (imgcutxia[:, :, 0] > 10)\n y = (imgcutxia[:, :, 1] > 10)\n z = (imgcutxia[:, :, 2] > 10)\n\n p = np.sum((x & y & z))\n return p\n\n\ndef huojia(picture, pix, r, g, b):\n shang=0\n xia=0\n img = cv2.imread(picture)\n imgcutshang = img[140:300, 150:550]\n _,shuipingx=hough(imgcutshang)\n max1=max(shuipingx)\n min2=min(shuipingx)\n print('shuipilllllllllllllllllllllllllllllllllllllllllllllllllllllngx',max1,min2)\n #imgcutshang = img[(140+max1-130):(140+max1+4), 150:550]\n imgcutshang = img[(140 + max1 - 130):(140 + max1 -15), 200:480]\n cv2.imwrite('%s_yuanshang.jpg' % (picture), imgcutshang)\n #imgcutxia= img[140+max1+70:480, 150:550]\n imgcutxia = img[140 + max1 + 70:480, 200:480]\n cv2.imwrite('%s_yuanxia.jpg' % (picture), imgcutxia)\n\n # cv2.imwrite('%s_yuanxia.jpg' % (picture), imgcutxia)\n p1 = imgread(picture + 'shang', imgcutshang, r, g, b)\n print(picture, 'shang has ', p1)\n if (p1 > pix):\n print(picture, 'shang is you')\n shang = 1\n else:\n print((picture, 'shang is wu'))\n p2 = imgread(picture + 'xia', imgcutxia, r, g, b)\n print(picture, 'xia has ', p2)\n if (p2 > pix):\n print(picture, 'xia is you')\n xia = 1\n else:\n print((picture, 'xia is wu'))\n cv2.imwrite('%s_shang.jpg' % (picture), imgcutshang)\n cv2.imwrite('%s_xia.jpg' % (picture), imgcutxia)\n cv2.imwrite('maskshang.jpg', imgcutshang)\n cv2.imwrite('maskxia.jpg', imgcutxia)\n return shang, xia, p1, p2\n\n\n# Streaming loop\ndef picture():\n pipeline = rs.pipeline()\n\n # Create a config and configure the pipeline to stream\n # different resolutions of color and depth streams\n config = rs.config()\n config.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\n\n # Start streaming\n profile = pipeline.start(config)\n\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_sensor = profile.get_device().first_depth_sensor()\n depth_scale = depth_sensor.get_depth_scale()\n print\n \"Depth Scale is: \", depth_scale\n\n # We will be removing the background of objects more than\n # clipping_distance_in_meters meters away\n clipping_distance_in_meters = 0.65 # 1 meter\n clipping_distance = clipping_distance_in_meters / depth_scale\n\n # Create an align object\n # rs.align allows us to perform alignment of depth frames to others frames\n # The \"align_to\" is the stream type to which we plan to align depth frames.\n align_to = rs.stream.color\n align = rs.align(align_to)\n\n print(' start ')\n\n while True:\n # Get frameset of color and depth\n frames = pipeline.wait_for_frames()\n # frames.get_depth_frame() is a 640x360 depth image\n # Align the depth frame to color frame\n aligned_frames = align.proccess(frames)\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n # Validate that both frames are valid\n if not aligned_depth_frame or not color_frame:\n continue\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n # Remove background - Set pixels further than clipping_distance to grey\n grey_color = 0\n depth_image_3d = np.dstack(\n (depth_image, depth_image, depth_image)) # depth image is 1 channel, color is 3 channels\n bg_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), grey_color, color_image)\n # Render images\n # depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.09), cv2.COLORMAP_JET)\n # images = np.hstack((bg_removed, depth_colormap))\n cv2.namedWindow('Align Example', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('Align Example', bg_removed)\n key = cv2.waitKey(110)\n # print key\n picname = 6\n for lm in range(picname + 1):\n if key == ord('%d' % (lm)):\n cv2.imwrite('picture/%d.jpg' % (lm), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (lm), color_image)\n\n if key == ord('s'):\n print('kjkk')\n pipeline.stop()\n break\n \"\"\"\n\n\n # Get frameset of color and depth\n\n frames = pipeline.wait_for_frames()\n # frames.get_depth_frame() is a 640x360 depth image\n\n # Align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n\n # Validate that both frames are valid\n #if not aligned_depth_frame or not color_frame:\n # continue\n\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n # Remove background - Set pixels further than clipping_distance to grey\n grey_color = 0\n depth_image_3d = np.dstack((depth_image,depth_image,depth_image)) #depth image is 1 channel, color is 3 channels\n bg_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), grey_color, color_image)\n # Render images\n #depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.09), cv2.COLORMAP_JET)\n #images = np.hstack((bg_removed, depth_colormap))\n #cv2.namedWindow('Align Example', cv2.WINDOW_AUTOSIZE)\n #cv2.imshow('Align Example', bg_removed)\n key = cv2.waitKey(12)\n #print key\n cv2.imwrite('picture/%d.jpg' % (1), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (2), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (3), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (4), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (5), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (6), bg_removed)\n if key ==ord('1'):\n cv2.imwrite('picture/%d.jpg'%(1),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (1),color_image)\n if key ==ord('2'):\n cv2.imwrite('picture/_%d.jpg'%(2),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (2), color_image)\n if key ==ord('3'):\n cv2.imwrite('picture/_%d.jpg'%(3),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (3), color_image)\n if key == ord('4'):\n cv2.imwrite('picture/%d.jpg' % (4), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (4), color_image)\n if key == ord('5'):\n cv2.imwrite('picture/%d.jpg' % (5), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (5), color_image)\n if key == ord('6'):\n cv2.imwrite('picture/%d.jpg' % (6), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (6), color_image)\n if key == ord('s'):\n print('kjkk')\n print('true is pp')\n time.sleep(5)\n cv2.destroyAllWindows()\n pipeline.stop()\n \"\"\"\n\n\ndef huop():\n # alist1=[]\n # alist2=[]\n pix1 = []\n pix2 = []\n pix3 = []\n #picture()\n start = time.clock()\n for kl in range(1, 7):\n shang, xia, p1, p2 = huojia('picture/%d.jpg' % (kl), pix=800, r=70, g=70, b=75)\n # alist1.append([shang])\n # alist2.append([xia])\n pix3.append(p1)\n pix3.append(p2)\n pix1.append(p1)\n pix2.append(p2)\n # alist=alist2+alist1\n pixt = pix1 + pix2\n pix3.sort()\n # print(alist)\n print(pixt)\n print((pix3))\n for xpo in pixt:\n if xpo == pix3[0] or xpo == pix3[1] or xpo == pix3[2]:\n pixt[pixt.index(xpo)] = 0\n else:\n pixt[pixt.index(xpo)] = 1\n\n # print(alist)\n print(pixt)\n last_tiem = [[pixt[0], pixt[1], pixt[2], pixt[3], pixt[4], pixt[5]],\n [pixt[6], pixt[7], pixt[8], pixt[9], pixt[10], pixt[11]\n ]]\n # print(' last item',last_tiem)\n end = time.clock()\n print('cost time is', end - start)\n return last_tiem\n\n\nif __name__ == \"__main__\":\n \"\"\"\n cap = cv2.VideoCapture(3)\n cap.set(3, 1920)\n cap.set(4, 1080)\n time.sleep(2)\n ret, frame = cap.read()\n print(frame.shape)\n cv2.imshow('hhhh', frame)\n cv2.waitKey(110)\n time.sleep(0.74)\n cv2.imwrite('ggggg.jpg', frame)\n print('has done ')\n cap.release()\n cv2.destroyAllWindows()\n \"\"\"\n last_tiem = huop()\n print(' last item', last_tiem)\n","sub_path":"pic_for_car.py","file_name":"pic_for_car.py","file_ext":"py","file_size_in_byte":11853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"138953449","text":"#!/usr/bin/env python\n\n# (c) David Sykes 2013\n# One more time, for the kids!\n\nimport sys\nimport os\nfrom Parameters import Parameters, ParamError\nfrom CompileEngine import CompileEngine\nfrom CompileError import CompileError\nfrom TokenParser import TokenParser\nfrom VariableEngine import VariableEngine\nfrom ScriptEngine import ScriptEngine\nfrom NullFileWrapper import NullFileWrapper\n\ndef Useage(mess = None):\n\tprint('Useage: ' + sys.argv[0] + \" {script file} -variables {variable file} -functions {functions file}\")\n\tprint(\"Options: -lst : Ouptut debug information\")\n\tif mess:\n\t\tprint()\n\t\tprint(mess)\n\t\tsys.exit(-1)\n\tsys.exit(0)\n\ndef Quit(mess):\n\tprint(mess)\n\tsys.exit(-1)\n\ndef fetch_output_folder(parameters):\n\treturn p.GetOption('output')\n\ndef make_output_script_path(script_path, output_folder):\n\t(full_path, extension) = os.path.splitext(script)\n\t(folder, file_name) = os.path.split(full_path)\n\tif output_folder:\n\t\treturn os.path.join(output_folder, file_name)\n\treturn full_path\n\ndef get_list_file(path, create_list_file_path_flag):\n\tif create_list_file_path_flag:\n\t\treturn open(output_script_path + '.lst', 'w')\n\ntry:\n\tp = Parameters(['test','lst'],'[variables,functions,output]','[undefined]', sys.argv[1:])\nexcept ParamError as e:\n\tUseage('Param error: ' + e.value )\n\nif p.GetSwitch('test'):\n\tsys.path.append('./Tests')\n\tfrom Tests import RunTests\n\tRunTests()\n\tsys.exit(0)\n\nif len(p.GetParameters()) < 1:\n\tUseage('No script to compile')\n\nif p.GetOption('variables') == None and p.GetOption('functions') == None:\n\tUseage('No variable or functions file specified')\n\noutput_folder = fetch_output_folder(p)\n\nvariableengine = VariableEngine()\ntry:\n\tif p.GetOption('variables') != None:\n\t\tvariableengine.LoadXml(p.GetOption('variables'))\n\tif p.GetOption('functions') != None:\n\t\tvariableengine.LoadXml(p.GetOption('functions'))\nexcept CompileError as e:\n\tQuit(''.join([p.GetOption('variables'), ': ', e.value]))\n\nscriptengine = ScriptEngine()\n\nfor script in p.GetParameters():\n\ttry:\n\t\tfiledata = open(script).read()\n\texcept IOError as e:\n\t\tUseage(e)\n\ttokenparser = TokenParser(filedata)\n\te = CompileEngine(tokenparser, variableengine, scriptengine)\n\ttry:\n\t\te.Process()\n\t\ttry:\n\t\t\toutput_script_path = make_output_script_path(script, output_folder)\n\t\t\ttarget = output_script_path + '.bytes'\n\t\t\tobjf = open(target, 'wb')\n\t\t\tlistFile = NullFileWrapper(get_list_file(output_script_path, p.GetSwitch('lst')))\n\t\t\tscriptengine.Write(objf, listFile)\n\t\texcept IOError as e:\n\t\t\tUseage(e)\n\texcept CompileError as e:\n\t\tQuit(''.join(['Error:', script, '(', str(e.line), '): ', e.value]))\n","sub_path":"Compiler/CompileScript.py","file_name":"CompileScript.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"261776198","text":"from django.shortcuts import render,render_to_response\nfrom django.http import HttpResponse\nfrom models import Category,Service,Comment,UserAQL\nfrom django.template import RequestContext, loader\nfrom django.template import RequestContext as RC\nfrom django.utils import timezone\n# Create your views here.\ndef Categories (request):\n\tcategory_list = {'Category':Category.objects.all()}\n\treturn render(request,'CategoriasDjango.html',category_list)\ndef Cat (request,Name):\n\tif request.method == 'GET':\n\t\t\"\"\"return render(request,'categoriaDjango.html',suppliers_list)\"\"\"\n\t\t\"\"\"return render_to_response('categoriaDjango.html', {'suppliers':Supplier.objects.all().filter(category_id=supplier).order_by('-calificacion')},context_instance = RC( request, {} ),)\"\"\"\n\t\treturn render_to_response('CategoriaDjango.html', {'Services':Service.objects.all().filter(Category=Name).order_by('-Calification')},context_instance = RC( request, {} ),)\ndef Serv(request,Name,NameService):\n\tif request.method == 'GET':\n\t\ttheService = Service.objects.get(NameService=NameService)\n\t\trealComment = dict()\n\t\tcomments = Comment.objects.filter(Service=theService)\n\t\trealComments = list() \n\t\tfor c in comments:\n\t\t\trealComment = dict()\n\t\t\trealComment['User'] = c.User\n\t\t\trealComment['Opinion'] = c.Opinion\n\t\t\trealComment['Image'] = realComment['User'].Image\n\t\t\trealComments.append(realComment)\n\t\trealComments.reverse()\n\t\treturn render_to_response('Service.html', {'Service': theService,'Comments':realComments},context_instance = RC( request, {} ),)\ndef All(request):\n\tif request.method == 'GET':\n\t\treturn render_to_response('AllCategories.html', {'Services':Service.objects.all().order_by('-Calification')},context_instance = RC( request, {} ),)\ndef New(request):\n\tif request.method == 'GET':\n\t\tallServices = Service.objects.all()\n\t\ttoday = timezone.now()\n\t\tnewServices = list() \n\t\tfor a in allServices:\n\t\t\tif a.CreationDate.month == today.month:\n\t\t\t\tnewServices.append(a)\n\t\tnewServices = reversed(newServices)\n\t\treturn render_to_response('NewService.html', {'Services':newServices},context_instance = RC( request, {} ),)","sub_path":"aquienllamo9.0/Service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"416218159","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect, get_object_or_404, get_list_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import SupplierForm, NewIndustryForm, NewProductCategoryForm, SupplierQueryForm, ContactUsForm\nfrom .models import Supplier, Industry, ProductCategory\nfrom django.core.mail import send_mail, BadHeaderError\n\nfrom django.views.generic import ListView, CreateView\nfrom django.urls import reverse_lazy\n#construir view da página de buscas. Método GET vai retornar\n#sem nenhum parâmetro, método POST vai retornar com query\n\ndef homePage(request):\n contact_email = \"contato@mysupplier.com.br\"\n if request.method == \"POST\":\n form = ContactUsForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n from_email = form.cleaned_data['email']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n try:\n send_mail(subject, message, from_email, [contact_email])\n except BadHeaderError:\n return HttpResponse(\"Header inválido encontrado\")\n return redirect(\"success_message\")\n else:\n form = ContactUsForm()\n industries = Industry.objects.all()\n return render(request, \"home.html\", {\"form\" : form, \"industries\" : industries})\n\n\ndef successMessage(request):\n return render(request, \"message_success.html\")\n\n#formulários internos (administração) para criar novas industrias\n#e categorias de produtos\ndef newIndustry(request):\n if request.method == \"POST\":\n form = NewIndustryForm(request.POST, request.FILES)\n if form.is_valid():\n form.save(commit=True)\n return redirect(\"new_category\")\n else:\n form = NewIndustryForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\ndef newCategory(request):\n if request.method == \"POST\":\n form = NewProductCategoryForm(request.POST)\n if form.is_valid():\n category = form.save(commit=True)\n return redirect(\"new_category\")\n else:\n form = NewProductCategoryForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\n\n#view do usuário, para criação de novos anúncios\n@login_required\ndef newSupplier(request):\n if request.method == \"POST\":\n form = SupplierForm(request.POST)\n if form.is_valid():\n #create object with correct parameters\n #use commit=false to add extra infor before saving to DB\n supplier = form.save(commit=False)\n supplier.owner = request.user\n supplier.save()\n\n return redirect(\"query_supplier_list\")\n else:\n form = SupplierForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\n#View para realizar buscas no BD de forncedores\ndef querySupplierList(request):\n if request.method == \"POST\":\n form = SupplierQueryForm(request.POST)\n if form.is_valid():\n category = form.cleaned_data['category']\n suppliers = Supplier.objects.filter(category__name=category)\n\n form = SupplierQueryForm()\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n form = SupplierQueryForm()\n suppliers = Supplier.objects.all()\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n\n\n#later substitute 404 for page showing no results and askinjg for new query\ndef queryAllSuppliers(request, industry, category):\n if request.method == \"GET\":\n suppliers = get_list_or_404(Supplier.objects.filter(category__rel_industry=industry))\n\n if category != 0:\n pass\n #suppliers = get_list_or_404(suppliers.filter(category=category))\n form = SupplierQueryForm()\n\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n","sub_path":"project_django/mysupplier/suppliers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"253154474","text":"import numpy as np\nimport numba as nb\nimport awkward as awk\nimport operator\nfrom cachetools import cachedmethod\nfrom cachetools.keys import hashkey\nfrom functools import partial\n\nfrom utils.Geometry import RadToCart2D, CartToRad2D\n\n@nb.njit\ndef pt_shift_numba(pt, nsig, up, down):\n return pt*(1 + (nsig>=0)*nsig*up - (nsig<0)*nsig*down)\n\ndef jet_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fjet_pt_shift'))\n def fjet_pt_shift(ev, evidx, nsig, source):\n nominal = ev.Jet.pt\n try:\n up = getattr(ev.Jet, 'JEC{}Up'.format(source)).content\n down = getattr(ev.Jet, 'JEC{}Down'.format(source)).content\n except AttributeError:\n up = 0.\n down = 0.\n return awk.JaggedArray(nominal.starts, nominal.stops, pt_shift_numba(\n nominal.content, nsig, up, down,\n ))\n\n def return_jet_pt_shift(ev):\n source = ev.source if ev.source in ev.attribute_variation_sources else ''\n return fjet_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return return_jet_pt_shift\n\ndef muon_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fmuon_pt_shift'))\n def fmuon_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"muonPtScale\")*ev.Muon.ptErr.content/ev.Muon.pt.content\n return awk.JaggedArray(ev.Muon.pt.starts, ev.Muon.pt.stops, pt_shift_numba(\n ev.Muon.pt.content, nsig, shift, -1.*shift\n ))\n\n def ret_func(ev):\n source = ev.source if ev.source == \"muonPtScale\" else ''\n return fmuon_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef ele_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fele_pt_shift'))\n def fele_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"eleEnergyScale\")*ev.Electron_energyErr.content/ev.Electron.pt.content\n return awk.JaggedArray(ev.Electron.pt.starts, ev.Electron.pt.stops, pt_shift_numba(\n ev.Electron.pt.content, nsig, shift, -shift\n ))\n\n def ret_func(ev):\n source = ev.source if ev.source == \"eleEnergyScale\" else \"\"\n return fele_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef photon_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fphoton_pt_shift'))\n def fphoton_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"photonEnergyScale\")*ev.Photon_energyErr.content/ev.Photon.pt.content\n result = awk.JaggedArray(ev.Photon.pt.starts, ev.Photon.pt.stops, pt_shift_numba(\n ev.Photon.pt.content, nsig, shift, -shift\n ))\n result.content[np.isnan(result).content] = 0.\n return result\n\n def ret_func(ev):\n source = ev.source if ev.source == \"photonEnergyScale\" else \"\"\n return fphoton_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef met_shift(arg, unclust_energy):\n @nb.njit\n def met_shift_numba(\n met, mephi, jpt, jptcorr, jphi, jstarts, jstops, metuncx, metuncy, nsig,\n ):\n jpx_old, jpy_old = RadToCart2D(jpt, jphi)\n jpx_new, jpy_new = RadToCart2D(jptcorr, jphi)\n\n mex, mey = RadToCart2D(met, mephi)\n for iev, (start, stop) in enumerate(zip(jstarts, jstops)):\n for iob in range(start, stop):\n if jpt[iob] > unclust_energy:\n mex[iev] += jpx_old[iob]\n mey[iev] += jpy_old[iob]\n if jptcorr[iob] > unclust_energy:\n mex[iev] -= jpx_new[iob]\n mey[iev] -= jpy_new[iob]\n\n mex += nsig*metuncx\n mey += nsig*metuncy\n\n return CartToRad2D(mex, mey)\n\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fmet_shift'))\n def fmet_shift(ev, evidx, nsig, source, arg_):\n return met_shift_numba(\n ev.MET_pt, ev.MET_phi, ev.Jet_pt.content,\n ev.Jet_ptShift(ev).content, ev.Jet_phi.content,\n ev.Jet_pt.starts, ev.Jet_pt.stops,\n (source==\"unclust\")*ev.MET_MetUnclustEnUpDeltaX,\n (source==\"unclust\")*ev.MET_MetUnclustEnUpDeltaY,\n nsig,\n )[arg_]\n\n return lambda ev: fmet_shift(ev, ev.iblock, ev.nsig, ev.source, arg)\n\ndef obj_selection(objname, selection, xclean=False):\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fobj_selection'))\n def fobj_selection(ev, evidx, nsig, source, objname_, selection_, xclean_, attr):\n mask = getattr(ev, \"{}_{}Mask\".format(objname_, selection_))(ev)\n if xclean_:\n mask = mask & getattr(ev, \"{}_XCleanMask\".format(objname_))(ev)\n\n obj = getattr(ev, \"{}_{}\".format(objname_, attr))\n if callable(obj):\n obj = obj(ev)\n\n return obj[mask]\n\n def return_obj_selection(ev, attr):\n source = ev.source if ev.source in ev.attribute_variation_sources else ''\n return fobj_selection(\n ev, ev.iblock, ev.nsig, source, objname, selection, xclean, attr,\n )\n\n return return_obj_selection\n\nclass ObjectFunctions(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n def begin(self, event):\n event.Jet_ptShift = jet_pt_shift()\n event.Muon_ptShift = muon_pt_shift()\n event.Electron_ptShift = ele_pt_shift()\n event.Photon_ptShift = photon_pt_shift()\n event.Tau_ptShift = lambda ev: ev.Tau_pt\n event.MET_ptShift = met_shift(0, self.unclust_threshold)\n event.MET_phiShift = met_shift(1, self.unclust_threshold)\n\n for objname, selection, xclean in self.selections:\n if xclean:\n setattr(event, selection+\"NoXClean\", obj_selection(objname, selection))\n setattr(event, selection, obj_selection(objname, selection, xclean=True))\n else:\n setattr(event, selection, obj_selection(objname, selection))\n","sub_path":"sequence/Readers/ObjectFunctions.py","file_name":"ObjectFunctions.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"476844250","text":"from .. import IrisCommand\nfrom .. import state_types as t\nfrom .. import state_machine as sm\nfrom .. import util as util\nfrom .. import iris_objects\n\nclass Mean(IrisCommand):\n title = \"take mean of {dataframe}\"\n examples = [\n \"mean of {dataframe} of numbers\",\n \"mean {dataframe}\",\n \"average of {dataframe}\",\n \"average value of {dataframe}\",\n ]\n help_text = [\n \"This computes the average values of an array of numbers\"\n ]\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe would you like to analyze?\"),\n \"selector\": t.DataframeSelector(\"What are the columns you'd like to transform?\", dataframe=\"dataframe\")\n }\n def command(self, dataframe, selector):\n import numpy as np\n return np.average(selector.to_matrix().flatten())\n def explanation(self, val):\n return \"The mean is {}\".format(round(val, 6))\n\nmean = Mean()\n\nclass LogTransform(IrisCommand):\n title = \"log-transform {dataframe}\"\n examples = [\n \"log-transform {dataframe} of numbers\",\n \"log {dataframe}\",\n \"log of {dataframe}\",\n \"log value of {dataframe}\",\n ]\n help_text = [\n \"This computes the log values of an array of numbers\"\n ]\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe would you like to analyze?\"),\n \"selector\": t.DataframeSelector(\"What are the columns you'd like to transform?\", dataframe=\"dataframe\")\n }\n def command(self, dataframe, selector):\n import numpy as np\n data = selector.to_matrix()\n data_out = []\n for col in range(0,data.shape[1]):\n data_out.append(np.log(data[:,col]))\n data_out = np.array(data_out).T\n return iris_objects.IrisDataframe(column_names=selector.column_names, column_types=selector.column_types, data=data_out)\n\nlog = LogTransform()\n\nclass PearsonCorrelation(IrisCommand):\n title = \"compute pearson correlation: {x} and {y}\"\n examples = [ \"pearson correlation between {x} and {y}\",\n \"pearson correlation {x} {y}\",\n \"how are {x} and {y} correlated\" ]\n help_text = [\n \"A pearson correlation coefficient is a measure of linear dependence between two variables.\",\n \"A coefficient greater than 0 indicates a positive linear relationship\",\n \"A coefficient less than 0 indicates a negative relationship\",\n \"And a coefficient near 0 indicates the absence of any relationship.\",\n \"This command returns a coefficient and a p-value that measures the degree of confidence in its significance.\"\n ]\n argument_help = {\n \"x\": \"The x value should be an array from the current environment\",\n \"y\": \"The y value should be an array from the current environment\",\n }\n def command(self, x : t.Array(\"What is the first array?\"), y : t.Array(\"The second array?\")):\n from scipy.stats import pearsonr\n return pearsonr(x,y)\n def explanation(self, corr_pval):\n corr = round(corr_pval[0],4)\n pval = round(corr_pval[1],4)\n return \"Correlation of {} with p-value of {}\".format(corr, pval)\n\npearsonCorrelation = PearsonCorrelation()\n\nclass FindQuartiles(IrisCommand):\n title = \"find quartiles {array}\"\n expamples = [\"quartiles {array}\", \"Q1 Q2 Q3 Q4 {array}\"]\n argument_types ={\n \"array\": t.Array(\"What array do you want to use?\")\n }\n def command(self, array):\n import numpy as np\n min_, max_ = min(array), max(array)\n q25, q50, q75 = np.percentile(array, [25, 50, 75])\n return (min_, q25, q50, q75, max_)\n def explanation(self, results):\n out_s = \"Q1 is from {} to {}, Q2 is from {} to {}, Q3 is from {} to {}, and Q4 is from {} to {}\"\n return out_s.format(results[0], results[1], results[1], results[2], results[2], results[3], results[3], results[4])\n\nfindQuartiles = FindQuartiles()\n\nclass StatisticalTestDataframe(IrisCommand):\n title = \"two-sample statistical test {stats_test} on columns in {data1} and {data2}\"\n examples = [\"two-sample {stats_test} on columns in {data1} {data2}\"]\n argument_types = {\n \"stats_test\": t.Select(options={\n \"Mann-Whitney U test (does not assume data is normally distributed)\": \"mann_whitney\",\n \"Welch's t-test (assumes normal distibution, not equal variance)\": \"welch\",\n \"Student's t-test (assumes normal distribution and equal variance)\": \"student_t\"\n }),\n \"data1\": t.Dataframe(\"What data for first population?\"),\n \"data2\": t.Dataframe(\"What data for second population?\")\n }\n def command(self, stats_test, data1, data2):\n from scipy.stats import ttest_ind, mannwhitneyu\n from collections import namedtuple\n import numpy as np\n if stats_test == \"mann_whitney\":\n ttest = mannwhitneyu\n elif stats_test == \"welch\":\n ttest = lambda x,y: ttest_ind(x,y,equal_var=False)\n else:\n ttest = ttest_ind\n data1M, data2M = [data.to_matrix() for data in [data1, data2]]\n results = []\n Statistic = namedtuple('Statistic', ['stat', 'p_val', 'odds'])\n for i in range(0, data1M.shape[1]):\n stat_val = ttest(data1M[:,i], data2M[:,i])\n results.append(Statistic(stat_val[0], stat_val[1], np.average(data1M[:,i].flatten())/np.average(data2M[:,i].flatten())))\n results = np.array(results).reshape(1, data1M.shape[1], 3)\n df = iris_objects.IrisDataframe(column_names=list(data1.column_names), column_types=[], data=results)\n df.pops = [data1.name, data2.name]\n return df\n\nstatisticalTestDataframe = StatisticalTestDataframe()\n\nclass BonferroniCorrection(IrisCommand):\n title = \"apply bonferroni correction to {data}\"\n examples = [ \"bonferroni {data}\" ]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n import numpy as np\n dataM = data.to_matrix()\n num_tests = dataM.shape[1]\n new_data = np.copy(dataM)\n for i in range(0, num_tests):\n new_data[0,i,1] = new_data[0,i,1] * num_tests\n df = iris_objects.IrisDataframe(column_names=list(data.column_names), column_types=[], data=new_data)\n df.pops = list(data.pops)\n return df\n\nbonferroniCorrection = BonferroniCorrection()\n\nclass HolmCorrection(IrisCommand):\n title = \"apply holm correction to {data}\"\n examples = [ \"holm {data}\" ]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n import numpy as np\n dataM = data.to_matrix()\n num_tests = dataM.shape[1]\n new_data = np.copy(dataM)\n pvals = sorted([(i, new_data[0,i,1]) for i in range(0, num_tests)], key=lambda x: x[1])\n p2i = {k[0]:i for i,k in enumerate(pvals)}\n for i in range(0, num_tests):\n new_data[0,i,1] = new_data[0,i,1] * (num_tests-p2i[i]+1)\n df = iris_objects.IrisDataframe(column_names=list(data.column_names), column_types=[], data=new_data)\n df.pops = list(data.pops)\n return df\n\nholmesCorrection = HolmCorrection()\n\nclass ShowSignificantValues(IrisCommand):\n title = \"show significant values for {data}\"\n examples = [ \"significant values {data}\"]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n dmatrix = data.to_matrix()\n pvals = [dmatrix[0, i, 1] for i in range(0, dmatrix.shape[1])]\n odds = [dmatrix[0, i, 2] for i in range(0, dmatrix.shape[1])]\n results = [(p_val, odds[i], data.column_names[i]) for i, p_val in enumerate(pvals) if p_val < 0.05]\n return (results, data.pops)\n def explanation(self, results):\n stats, pops = results\n new_results = []\n for r in stats:\n if r[1] < 1:\n direction = \"{} more likely in \\\"{}\\\"\".format(round(1.0/r[1],6), pops[1])\n else:\n direction = \"{} more likely in \\\"{}\\\"\".format(round(r[1],6), pops[0])\n new_results.append(\"\\\"{}\\\" with p-value of {} is {}\".format(r[2], round(r[0],6), direction))\n return new_results\n\nshowSignificantValues = ShowSignificantValues()\n\nclass StudentTTest(IrisCommand):\n title = \"student t-test on {dataframe}\"\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe contains the data?\"),\n \"pop1\": t.DataframeSelector(\"What is the first population to analyze?\", dataframe=\"dataframe\"),\n \"pop2\": t.DataframeSelector(\"What is the second population to analyze?\", dataframe=\"dataframe\"),\n }\n def command(self, dataframe, pop1, pop2):\n from scipy.stats import ttest_ind\n data_pop1 = pop1.to_matrix().flatten() # TODO: in future, force single column selection\n data_pop2 = pop2.to_matrix().flatten()\n return ttest_ind(data_pop1, data_pop2)\n def explanation(self, results):\n return \"The p-value is {:.2e} and t-statistic is {}.\".format(results[1], round(results[0],6))\n\nstudentTTest = StudentTTest()\n\n# class StudentTTest(IrisCommand):\n# title = \"calculate two sample Student t-test on {x} and {y}\"\n# examples = [\n# \"Student t-test on {x} {y}\",\n# \"statistical test\",\n# \"two sample statistical test\",\n# \"test statistic\"\n# ]\n# help_text = [\n# \"This test determines whether two independent samples are significantly different from one another.\",\n# \"It assumes that both samples are normally distributed with equal variance.\"\n# ]\n# def command(self, x : t.Array(), y : t.Array()):\n# from scipy.stats import ttest_ind\n# return ttest_ind(x,y)\n# def explanation(self, results):\n# pval = round(results[1], 4)\n# if pval < 0.05:\n# return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n# else:\n# return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n#\n# studentTTest = StudentTTest()\n\nclass WelchTTest(IrisCommand):\n title = \"calculate Welch t-test on {x} and {y}\"\n examples = [\n \"Welch t-test on {x} and {y}\",\n \"statistical test\",\n \"two sample statistical test\",\n \"statistical\"\n ]\n help_text = [\n \"This test determines whether two independent samples are significantly different from one another.\",\n \"It assumes that both samples are normally distributed, but does not assume they have equal variance.\"\n ]\n def command(self, x : t.Array(), y : t.Array()):\n from scipy.stats import ttest_ind\n return ttest_ind(x,y, equal_var=False)\n def explanation(self, results):\n pval = round(results[1], 4)\n if pval < 0.05:\n return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n else:\n return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n\nwelchTTest = WelchTTest()\n\nclass MannWhitney(IrisCommand):\n title = \"calculate Mann-Whitney U test on {x} and {y}\"\n examples = [\n \"Mann-Whitney U test on {x} and {y}\",\n \"statistical test\",\n \"two sample statistical test\"\n ]\n help_text = [\n \"This test determines whether two independent samples are significantly different from one another.\",\n \"It does not assume that both samples are normally distributed.\"\n ]\n def command(self, x : t.Array(), y : t.Array()):\n from scipy.stats import mannwhitneyu\n return mannwhitneyu(x,y)\n def explanation(self, results):\n pval = round(results[1], 4)\n if pval < 0.05:\n return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n else:\n return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n\nmannWhitney = MannWhitney()\n\nclass TTestHelp(IrisCommand):\n title = \"help me run a t-test\"\n example = [\n \"which t-test should I use?\"\n ]\n help_text = [\n \"This command walks you through choosing a t-test\"\n ]\n argument_types = {\n \"choice\": t.YesNo(\"Is your data normally distributed?\",\n yes=t.YesNo(\"Do your samples have equal variance?\",\n yes=\"use student's t-test\",\n no=\"use welch's t-test\"\n ),\n no=\"use mann-whitney u test\"\n )\n }\n def command(self, choice):\n return choice\n\ntTestHelp = TTestHelp()\n","sub_path":"backend/iris/stdlib/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":12607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"429050028","text":"from __init__ import *\n\nimport sys\nimport os.path\nfrom PIL import Image\nimport numpy as np\nfrom arg_parser import parse_args\n\nfrom printer import print_header, print_usage, print_line\n\nsys.path.insert(0, ROOT)\nfrom utils import *\n\ndef init_images(app_data):\n print(\"[init.py] : initializing images...\")\n\n app_args = app_data['app_args']\n rows = 2048\n cols = 2048\n\n # input image:\n img_path1 = app_args.img_file1\n img1 = np.array(Image.open(img_path1))\n\n img_path2 = app_args.img_file2\n img2 = np.array(Image.open(img_path2))\n\n if img1.shape != img2.shape:\n app_data['error'] = 1\n return \n\n R = img1.shape[0]\n C = img1.shape[1]\n\n off_left = 31\n total_pad = 60\n\n # convert input image to floating point\n image1_f = np.float32(img1) / 255.0\n image2_f = np.float32(img2) / 255.0\n\n # create ghost zone and copy image roi\n\n # Image 1:\n image1_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32)\n image1_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \\\n np.array(img1[0:rows, 0:cols, 0:3], np.float32)\n # clamp the boundary portions\n image_clamp(img1, image1_ghost, rows, cols, 3,\n np.float32, 1, off_left, total_pad)\n\n # Image 2\n image2_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32)\n image2_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \\\n np.array(img2[0:rows, 0:cols, 0:3], np.float32)\n # clamp the boundary portions\n image_clamp(img2, image2_ghost, rows, cols, 3,\n np.float32, 1, off_left, total_pad)\n\n # create a simple mask of size (rows+total_pad) x (cols+total_pad)\n maskRow = 820\n half1 = np.zeros((maskRow, cols+total_pad), np.float32)\n half2 = np.ones((rows+total_pad-maskRow, cols+total_pad), np.float32)\n\n mask_ghost = np.vstack((half1, half2))\n\n # move colour dimension outside\n image1_f_flip = np.rollaxis(image1_ghost, 2).ravel()\n image2_f_flip = np.rollaxis(image2_ghost, 2).ravel()\n\n # result array\n OUT = np.empty((3, rows, cols), np.float32) \n\n img_data = {}\n img_data['IN1'] = image1_f_flip\n img_data['IN2'] = image2_f_flip\n img_data['OUT'] = OUT\n img_data['mask_ghost'] = mask_ghost\n\n app_data['img_data'] = img_data\n app_data['rows'] = rows\n app_data['cols'] = cols\n app_data['total_pad'] = 60\n return\n\ndef get_input(app_data):\n # parse the command-line arguments\n app_args = parse_args()\n app_data['app_args'] = app_args\n\n app_data['mode'] = app_args.mode\n app_data['runs'] = int(app_args.runs)\n app_data['graph_gen'] = bool(app_args.graph_gen)\n app_data['timer'] = app_args.timer\n\n # storage optimization\n app_data['optimize_storage'] = bool(app_args.optimize_storage)\n # early freeing of allocated arrays\n app_data['early_free'] = bool(app_args.early_free)\n # pool allocate option\n app_data['pool_alloc'] = bool(app_args.pool_alloc)\n\n return\n\ndef init_all(app_data):\n pipe_data = {}\n app_data['pipe_data'] = pipe_data\n\n get_input(app_data)\n\n init_images(app_data)\n\n return\n\n","sub_path":"sandbox/apps/python/img_proc/pyramid_blend/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"536154207","text":"\"\"\"Test for the ui element TimePicker\"\"\"\nimport os, unittest\n\nfrom mock import patch, Mock\n\ntry:\n\tfrom ui import TimePicker\nexcept ImportError:\n\tprint(\"Absolute imports failed, trying relative imports\")\n\tos.sys.path.append(os.path.dirname(os.path.abspath('.')))\n\t# Store original __import__\n\torig_import = __import__\n\n\tdef import_mock(name, *args):\n\t\tif name in ['helpers']:\n\t\t\treturn Mock()\n\t\telif name == 'ui.utils':\n\t\t\timport utils\n\t\t\treturn utils\n\t\treturn orig_import(name, *args)\n\n\twith patch('__builtin__.__import__', side_effect=import_mock):\n\t\tfrom time_picker import TimePicker\n\ndef get_mock_input():\n\treturn Mock()\n\ndef get_mock_output(width=128, height=64, mode=\"1\"):\n m = Mock()\n m.configure_mock(width=width, height=height, device_mode=mode, type=[\"b&w\"])\n return m\n\ntp_name = \"Test TimePicker\"\n\nclass TestDatePicker(unittest.TestCase):\n\t\"\"\"Tests TimePicker\"\"\"\n\n\tdef test_constructor(self):\n\t\t\"\"\"Tests constructor\"\"\"\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\tself.assertIsNotNone(tp)\n\n\tdef test_keymap(self):\n\t\t\"\"\"Tests keymap\"\"\"\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\tself.assertIsNotNone(tp)\n\t\tfor key_name, callback in tp.keymap.iteritems():\n\t\t\tself.assertIsNotNone(callback)\n\n\t# Test whether it returns None when deactivating it\n\tdef test_left_key_returns_none(self):\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\ttp.refresh = lambda *args, **kwargs: None\n\n\t\t# Checking at start\n\t\tdef scenario():\n\t\t\ttp.deactivate()\n\t\t\tassert not tp.in_foreground\n\n\t\twith patch.object(tp, 'idle_loop', side_effect=scenario) as t:\n\t\t\treturn_value = tp.activate()\n\t\tassert return_value is None\n\n\t\t# Chechking after changing the numbers a little\n\t\tdef scenario():\n\t\t\tfor i in range(3):\n\t\t\t\ttp.decrease_one()\n\t\t\t\ttp.move_right()\n\t\t\t\ttp.increase_one()\n\t\t\ttp.deactivate()\n\t\t\tassert not tp.in_foreground\n\n\t\twith patch.object(tp, 'idle_loop', side_effect=scenario) as t:\n\t\t\treturn_value = tp.activate()\n\t\tassert return_value is None\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"ui/tests/test_time_picker.py","file_name":"test_time_picker.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"628655637","text":"import re\r\nfile=input(\"Enter the file name: \")\r\ntry:\r\n fh=open(file)\r\nexcept:\r\n print(\"Invalid File name:\",file)\r\n quit()\r\nnumlist=list()\r\nfor line in fh:\r\n line=line.strip()\r\n splitspace=line.split()\r\n if len(splitspace)<1: #Removing Blank Lines\r\n continue\r\n for item in splitspace:\r\n numbers=re.findall('[0-9]+',item) \r\n if item==\"http://www.py4e.com/code3/\":\r\n num1=item.split('/')\r\n for item2 in num1:\r\n numbers2=re.findall('[0-9]+',item2)\r\n #numlist.append(numbers2) #Creates list within list, since the re has already o/ps list\r\n numlist=numlist+numbers2 #to avoid list within list, also doesn't adds blank values.\r\n elif len(numbers)!=0:\r\n #numlist.append(numbers)\r\n numlist=numlist+numbers\r\n\r\n \r\nprint(numlist,'\\n')\r\nintlist=list()\r\nfor stringitem in numlist:\r\n intitem=int(stringitem) #Converting the list items in the string format to integer format\r\n intlist.append(intitem)\r\nprint(\"The number of items in the list is: \",len(intlist))\r\nprint('\\nThe total of the number of the items in the list is: ',sum(intlist))","sub_path":"asample_11.py","file_name":"asample_11.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"131448187","text":"import cv2\nimport numpy as np\n\nfrom helpers import *\n\nimg = cv2.imread('data/stone1.jpg', cv2.IMREAD_COLOR)\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ngray = np.float32(gray)\ndst = cv2.cornerHarris(gray, 2, 1, 0.04)\n# result is dilated for marking the corners, not important\ndst = cv2.dilate(dst, None)\n# Threshold for an optimal value, it may vary depending on the image.\nimg[dst > 0.01 * dst.max()] = [0, 0, 255]\n\ncv2.imshow('edge', img)\ncv2.waitKey(0)\n","sub_path":"src/CornerHarris.py","file_name":"CornerHarris.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398672700","text":"# function for reshaping two categorical columns\n# to create a matrix for heatmap\ndef category_matrix(dataframe, col1, col2):\n ''' Takes two categorical columns and regroup them and return dict of dicts\n Input: dataframe, header_string1, header_string2\n Output: Nested Dictionary >>> {col1_val1: {col2_val1: num_intersect}, ..., col1_valX : {col2_valX: num_intersect}}\n '''\n # get list of unique values from provided columns\n val_list1 = dataframe[col1].unique()\n val_list2 = dataframe[col2].unique()\n\n # create condition dict for first column\n condition = {}\n for i, val1 in enumerate(val_list1):\n condition[i] = (dataframe[col1] == val1)\n\n reshaped_dataframe = {} # empty dict for storing reshaped dataframe\n\n for i, val1 in enumerate(val_list1):\n # get unique intersection of val2 for each val 1 in dataframe\n val2_per_val1 = dataframe.loc[condition[i]][col2].unique()\n reshaped_dataframe[val1] = {}\n for j, val2 in enumerate(val2_per_val1):\n try:\n reshaped_dataframe[val1][val2] = (\n dataframe.loc[condition[i]][col2] == val2).value_counts()[1]\n except KeyError:\n reshaped_dataframe[val1][val2] = 0\n return reshaped_dataframe\n","sub_path":"helpers/category_matrix.py","file_name":"category_matrix.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"557743528","text":"from jinja2 import Template\nfrom markdown import markdown\nimport json\nfrom os import path, makedirs\n\n\nTEMPLATES_DIR = 'templates'\nOUTPUT_DIR = 'output'\n\n\ndef load_config(filepath):\n with open(filepath, 'r') as config:\n return json.load(config)\n\n\ndef create_dir(directory):\n if not path.exists(directory):\n makedirs(directory)\n\n\ndef get_index_page(config):\n template = get_template('index.html')\n for article in config['articles']:\n article['article_url'] = get_article_url(article['source'])\n output_filepath = '{0}/{1}'.format(OUTPUT_DIR, 'index.html')\n render_page(config, output_filepath, template)\n\n\ndef get_article_page(config):\n template = get_template('article.html')\n for article in config['articles']:\n article_info = {'title': article['title'],\n 'text': convert_md_to_html(article['source']),\n }\n filepath = path.dirname(article['source'])\n article_url = get_article_url(article['source'])\n create_dir('{0}/{1}'.format(OUTPUT_DIR, filepath))\n render_page(article_info, '{0}/{1}'.format(OUTPUT_DIR, article_url), template)\n\n\ndef get_article_url(source):\n source = replace_spesial_symbols(source)\n output_source = '{0}.{1}'.format(source, 'html')\n return output_source\n\n\ndef replace_spesial_symbols(source):\n symbols = ['&', '<', '>', ' ']\n source = path.splitext(source)[0]\n for symbol in symbols:\n if symbol in source:\n source = source.replace(symbol, '_')\n return source\n\ndef get_template(template_name):\n template_filepath = '{0}/{1}'.format(TEMPLATES_DIR, template_name)\n pattern = open(template_filepath).read()\n template = Template(pattern)\n return template\n\n\ndef render_page(data, filepath, template):\n with open(filepath, 'w', encoding='utf-8') as file:\n file.write(template.render(info=data))\n\n\ndef convert_md_to_html(filepath):\n filepath = '{0}/{1}'.format('articles', filepath)\n with open(filepath, 'r', encoding='utf-8') as data:\n return markdown(data.read(), extensions=['codehilite', 'fenced_code'])\n\n\nif __name__ == '__main__':\n config = load_config('config.json')\n create_dir(OUTPUT_DIR)\n get_index_page(config)\n get_article_page(config)\n","sub_path":"site_generator.py","file_name":"site_generator.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"29469397","text":"import math\nimport operator\nimport pygame\nimport random\n\ndef distance(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n dx = x1 - x2\n dy = y1 - y2\n return math.sqrt(dx * dx + dy * dy)\n\ndef is_exit_event(event):\n if event.type == pygame.QUIT:\n return True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n return True\n elif event.key == pygame.K_F4 and event.mod & pygame.KMOD_ALT:\n return True\n return False\n\ndef ab(attr, rect, inside):\n \"\"\"\n Find the a, b arguments for random.\n \"\"\"\n assert attr in 'wh' or attr in ['width', 'height']\n\n if attr.startswith('w'):\n attr = 'right'\n other = 'x'\n else:\n attr = 'bottom'\n other = 'y'\n\n a = getattr(inside, other)\n b = getattr(inside, attr) - getattr(rect, attr)\n\n return (a, b)\n\ndef randomize(rect, inside, nocollide):\n \"\"\"\n Randomly place rect inside another, until it doesn't collide.\n :param rect: rect to place\n :param inside: container\n :param nocollide: list of rect to avoid\n \"\"\"\n a, b = ab('width', rect, inside)\n c, d = ab('height', rect, inside)\n while True:\n rect.x = random.randint(a, b)\n rect.y = random.randint(c, d)\n if rect.collidelist(nocollide) == -1:\n break\n\npointsgetter = operator.attrgetter('topleft', 'topright', 'bottomright', 'bottomleft')\n\ndef rect2points(rect):\n for point in pointsgetter(rect):\n yield point\n\ndef calculate_direction(origin, target):\n \"\"\"\n :param origin: position calculate from\n :param target: position calculate to\n \"\"\"\n cx, cy = origin\n sx, sy = target\n\n cy = -cy\n sy = -sy\n\n theta_radians = math.atan2(sy - cy, sx - cx)\n\n return theta_radians\n\ndirection = calculate_direction\n\ndef rect_sweep_polygon(origin, destination):\n # ( (x1, y1), (x2, y2) )\n l1 = (origin.topleft, destination.topleft)\n l2 = (origin.bottomright, destination.bottomright)\n\n return (l1, l2)\n\ndef make_explosion_from_rect(rect, time_to_live):\n pixels = [ (x, y) for x in xrange(rect.left, rect.right)\n for y in xrange(rect.top, rect.bottom) ]\n centers = random.sample(pixels, 100)\n for center in centers:\n for spark in make_explosion(center, time_to_live, 1):\n yield spark\n\n# want only upwardly flying sparks\n# remember coordinates are upside down\nANGLES = range(225, 315)\n\nFORCES = [n/1000000.0 for n in range(500, 750)]\n\nfrom .sprites.spark import VerletSpark as Spark\n\ndef make_explosion(center, time_to_live, n=10):\n for _ in xrange(n):\n angle = math.radians(random.choice(ANGLES))\n force = random.choice(FORCES)\n velocity = (0.0, 0.0)\n acceleration = (math.cos(angle) * force, math.sin(angle) * force)\n spark = Spark(center, velocity, acceleration, time_to_live)\n yield spark\n","sub_path":"01-dodger/dodger1/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45256527","text":"\"\"\"\nAdd Two Numbers II\nYou are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nFollow up:\nWhat if you cannot modify the input lists? In other words, reversing the lists is not allowed.\n\nExample:\n\nInput: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 8 -> 0 -> 7\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n # Solution 1 - 68 ms\n \"\"\"\n st1, st2 = [], []\n while l1:\n st1.append(l1.val)\n l1 = l1.next\n\n while l2:\n st2.append(l2.val)\n l2 = l2.next\n\n carry, head = 0, None\n\n while st1 or st2 or carry:\n d1, d2 = 0, 0\n d1 = st1.pop() if st1 else 0\n d2 = st2.pop() if st2 else 0\n carry, digit = divmod(d1 + d2 + carry, 10)\n head_new = ListNode(digit)\n head_new.next = head\n head = head_new\n\n return head\n \"\"\"\n # Solution 2 - 48 ms\n a = 0\n b = 0\n head1, head2 = l1, l2\n while head1:\n a = a * 10 + head1.val\n head1 = head1.next\n while head2:\n b = b * 10 + head2.val\n head2 = head2.next\n res = a + b\n new_head = None\n if res == 0:\n node = ListNode(0)\n node.next = new_head\n new_head = node\n return new_head\n while res:\n val = res % 10\n res = res // 10\n node = ListNode(val)\n node.next = new_head\n new_head = node\n return new_head\n\n def printList(self, node):\n temp = node\n while (temp):\n print(temp.val)\n temp = temp.next\n\n\n# Main Call\nnode = ListNode(7)\nnode.next = ListNode(2)\nnode.next.next = ListNode(4)\nnode.next.next.next = ListNode(3)\n\nnode_2 = ListNode(5)\nnode_2.next = ListNode(6)\nnode_2.next.next = ListNode(4)\n\nsolution = Solution()\nsum_node = solution.addTwoNumbers(node, node_2)\nsolution.printList(sum_node)\n","sub_path":"src/linkedLists/addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"453239213","text":"import pandas as pd\nimport numpy as np\nimport re\nimport json\nfrom sklearn.linear_model import LinearRegression\n\ndf = pd.read_csv('/Users/keinobaird/Desktop/labspt15-cityspire-g-ds/notebooks/data/population2010-2019/metropop_2010_2019.csv')\n\ndef explode_str(df, col='Metro-Area', sep='-'):\n s = df[col]\n i = np.arange(len(s)).repeat(s.str.count(sep) +1)\n return df.iloc[i].assign(**{col: sep.join(s).split(sep)})\n\nnew_df = explode_str(df)\n\ndef metro_lists_gen(new_df):\n new_df.rename(columns={\"Metro-Area\": 'metro_area'}, inplace=True)\n new_df['metro_area'] = new_df['metro_area'].apply(lambda row: row.lower())\n lists = new_df['metro_area'].unique().tolist()\n with open('metro_list.json', 'w', encoding='utf-8') as f:\n json.dump(lists, f, ensure_ascii=False, indent=4)\n return lists, new_df\n\n\ndef selecting_metro(df, metro):\n df = df.loc[df['metro_area'] == metro]\n df.drop(['metro_area', 'State', 'Census', 'Estimate Base'], axis=1, inplace=True)\n df = df.T\n df.dropna(inplace=True)\n df = df.reset_index()\n return df\n\ndef prediction_model(df):\n x = df.iloc[:, 0].values.reshape(-1, 1)\n y = df.iloc[:, 1].values.reshape(-1, 1)\n model = LinearRegression().fit(x,y)\n return model\n\ndef prediction(model, year):\n return int(model.coef_[0][0] * year + model.intercept_[0])\n\ndef main():\n metro = input('Please input the metro area: ').lower()\n year = int(input('Pleae enter the year to predict: '))\n df = new_df\n lists, df = metro_lists_gen(df)\n if metro in lists:\n df = selecting_metro(df, metro)\n model = prediction_model(df)\n result = prediction(model, year)\n print(f'\\n Result: {metro.upper()} population in {year} will be {result:,d}')\n else:\n print(\"Kindly check available metro anmes and spelling from metro_list.json\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"notebooks/datasets/data/population2010-2019/population_prediction.py","file_name":"population_prediction.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"297081615","text":"############### import module ###############\nimport pygame\nimport os\nfrom math import floor\n\n############### import my module ###############\nimport function_main as func\n\n############### class player ###############\nclass Player(object):\n \n def __init__(self,x,y,width,height,velocity,stand_right_path,stand_left_path,move_right_path,move_left_path,dash_right_path,dash_left_path,dead_down_path,dash_gauge_path):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.velocity = velocity\n self.hitbox = (self.x,self.y,self.x+self.width,self.y+self.height)\n self.is_jumping = False\n self.jump_power = func.CHARACTER_JUMP\n self.status = 'STAND'\n self.facing = 'RIGHT'\n self.is_dead = False\n self.image = ''\n self.dash_gauge = 0\n\n self.health = 30 \n self.median = (self.x+self.width/2,self.y+self.height/2)\n \n self.stand_right_path = stand_right_path\n self.stand_right_list = os.listdir(self.stand_right_path)\n self.stand_right_index = 0\n \n self.stand_left_path = stand_left_path\n self.stand_left_list = os.listdir(self.stand_left_path)\n self.stand_left_index = 0\n\n self.move_right_path = move_right_path\n self.move_right_list = os.listdir(self.move_right_path)\n self.move_right_index = 0\n\n self.move_left_path = move_left_path\n self.move_left_list = os.listdir(self.move_left_path)\n self.move_left_index = 0\n\n self.dash_right_path = dash_right_path\n self.dash_right_list = os.listdir(self.dash_right_path)\n self.dash_right_index = 0\n\n self.dash_left_path = dash_left_path\n self.dash_left_list = os.listdir(self.dash_left_path)\n self.dash_left_index = 0\n\n self.dead_down_path = dead_down_path\n self.dead_down_list = os.listdir(self.dead_down_path)\n self.dead_down_index = 0\n\n self.dash_gauge_path = dash_gauge_path\n self.dash_gauge_list = os.listdir(self.dash_gauge_path)\n\n def key_continuous_input(self,screen):\n pygame.event.pump() # initialize key press\n keys = pygame.key.get_pressed() # key press\n\n if 1 not in keys:\n self.status = 'STAND'\n\n if keys[pygame.K_RIGHT]:\n self.facing = 'RIGHT'\n self.status = 'MOVE'\n self.dash_gauge += 1\n self.x += self.velocity\n\n if keys[pygame.K_LEFT]:\n self.facing = 'LEFT'\n self.status = 'MOVE'\n self.dash_gauge += 1\n self.x -= self.velocity\n \n if keys[pygame.K_RIGHT] and keys[pygame.K_a] and self.dash_gauge >= 260:\n self.facing = 'RIGHT'\n self.status = 'DASH'\n self.dash_gauge = 0\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[0])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 10\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[1])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 5\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[2])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 2.5\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[3])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 1.25\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[4])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 0.625\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[5])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 0.3125\n \n if keys[pygame.K_LEFT] and keys[pygame.K_a] and self.dash_gauge >= 260:\n self.facing = 'LEFT'\n self.status = 'DASH'\n self.dash_gauge = 0\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[0])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 10\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[1])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 5\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[2])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 2.5\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[3])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 1.25\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[4])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 0.625\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[5])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 0.3125\n \n if keys[pygame.K_RIGHT] and keys[pygame.K_s]:\n self.facing = 'RIGHT'\n self.status = 'ATTACK'\n\n if keys[pygame.K_LEFT] and keys[pygame.K_s]:\n self.facing = 'LEFT'\n self.status = 'ATTACK'\n\n if not self.is_jumping:\n if keys[pygame.K_UP]:\n self.is_jumping = True\n else:\n if self.jump_power >= -1*func.CHARACTER_JUMP:\n neg = 1\n if self.jump_power < 0:\n neg = -1\n \n self.y -= (self.jump_power ** 2) * 0.5 * neg \n self.jump_power -= 1\n \n else:\n self.is_jumping = False\n\n self.jump_power = func.CHARACTER_JUMP\n\n def character_district(self):\n if self.x < 0: self.x = 0\n if self.x > func.WINDOW_WIDTH - self.width : self.x = func.WINDOW_WIDTH - self.width\n \n def hit(self,other):\n self.hitbox = (self.x,self.y,self.x+self.width,self.y+self.height) # declare more for initialize player's hitbox\n if (other.median[0] < self.hitbox[2]) and (other.median[0] > self.hitbox[0]) and (other.median[1] < self.hitbox[3]) and (other.median[1] > self.hitbox[1]) and self.status != 'DASH': # if monster's median touches player's hitbox\n self.health -= 1\n\n if self.health >= 30:\n self.image = pygame.image.load('./image/healthbar/RedHP3.png')\n self.image = pygame.transform.scale(self.image,(200,20))\n func.screen.blit(self.image,(self.x+80, self.y+30))\n elif self.health >= 20 and self.health < 30:\n self.image = pygame.image.load('./image/healthbar/RedHP2.png')\n self.image = pygame.transform.scale(self.image,(200,20))\n func.screen.blit(self.image,(self.x+80, self.y+30)) \n elif self.health > 0:\n self.image = pygame.image.load('./image/healthbar/RedHP1.png')\n self.image = pygame.transform.scale(self.image,(200,20)) \n func.screen.blit(self.image,(self.x+80, self.y+30)) \n\n return True if self.health == 0 else False\n\n def draw_components(self,screen):\n \n if not self.is_dead:\n if self.status == 'STAND' and self.facing == 'RIGHT':\n self.stand_right(screen)\n if self.status == 'STAND' and self.facing == 'LEFT':\n self.stand_left(screen)\n if self.status == 'MOVE' and self.facing == 'RIGHT':\n self.move_right(screen)\n if self.status == 'MOVE' and self.facing == 'LEFT':\n self.move_left(screen)\n '''\n if self.status == 'DASH' and self.facing == 'RIGHT':\n self.dash_right(screen)\n if self.status == 'DASH' and self.facing == 'LEFT':\n self.dash_left(screen)\n '''\n\n if self.dash_gauge < 20:\n self.draw_dash_gauge(screen,0)\n elif self.dash_gauge < 40:\n self.draw_dash_gauge(screen,1)\n elif self.dash_gauge < 60:\n self.draw_dash_gauge(screen,2)\n elif self.dash_gauge < 80:\n self.draw_dash_gauge(screen,3)\n elif self.dash_gauge < 100:\n self.draw_dash_gauge(screen,4)\n elif self.dash_gauge < 120:\n self.draw_dash_gauge(screen,5)\n elif self.dash_gauge < 140:\n self.draw_dash_gauge(screen,6)\n elif self.dash_gauge < 160:\n self.draw_dash_gauge(screen,7)\n elif self.dash_gauge < 180:\n self.draw_dash_gauge(screen,8)\n elif self.dash_gauge < 200:\n self.draw_dash_gauge(screen,9)\n elif self.dash_gauge < 220:\n self.draw_dash_gauge(screen,10)\n elif self.dash_gauge < 240:\n self.draw_dash_gauge(screen,11)\n else:\n self.draw_dash_gauge(screen,12)\n \n def draw_dash_gauge(self,screen,index):\n self.image = pygame.image.load(self.dash_gauge_path+'/'+self.dash_gauge_list[index])\n self.image = pygame.transform.scale(self.image,(250,50))\n screen.blit(self.image,(func.WINDOW_WIDTH-290,30))\n\n def stand_right(self,screen):\n self.stand_right_list = os.listdir(self.stand_right_path)\n self.image = pygame.image.load(self.stand_right_path+'/'+self.stand_right_list[floor(self.stand_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.stand_right_index += 0.05\n if self.stand_right_index >= len(self.stand_right_list)-1: self.stand_right_index = 0\n\n def stand_left(self,screen):\n self.stand_left_list = os.listdir(self.stand_left_path)\n self.image = pygame.image.load(self.stand_left_path+'/'+self.stand_left_list[floor(self.stand_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.stand_left_index += 0.05\n if self.stand_left_index >= len(self.stand_left_list)-1: self.stand_left_index = 0\n \n def move_right(self,screen):\n self.move_right_list = os.listdir(self.move_right_path)\n self.image = pygame.image.load(self.move_right_path+'/'+self.move_right_list[floor(self.move_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.move_right_index += 0.1\n if self.move_right_index >= len(self.move_right_list)-1: self.move_right_index = 0\n \n def move_left(self,screen):\n self.move_left_list = os.listdir(self.move_left_path)\n self.image = pygame.image.load(self.move_left_path+'/'+self.move_left_list[floor(self.move_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.move_left_index += 0.1\n if self.move_left_index >= len(self.move_left_list)-1: self.move_left_index = 0\n '''\n def dash_right(self,screen):\n self.dash_right_list = os.listdir(self.dash_right_path)\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[floor(self.dash_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.dash_right_index += 0.01\n if self.dash_right_index >= len(self.dash_right_list)-1: self.dash_right_index = 0\n \n def dash_left(self,screen):\n self.dash_left_list = os.listdir(self.dash_left_path)\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[floor(self.dash_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.dash_left_index += 0.01\n if self.dash_left_index >= len(self.dash_left_list)-1: self.dash_left_index = 0\n '''\n def dead_down(self,screen):\n self.dead_down_list = os.listdir(self.dead_down_path)\n self.image = pygame.image.load(self.dead_down_path+'/'+self.dead_down_list[floor(self.dead_down_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n if self.dead_down_index < len(self.dead_down_list)-0.1:\n self.dead_down_index += 0.1\n \n \n","sub_path":"class_player.py","file_name":"class_player.py","file_ext":"py","file_size_in_byte":14117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"20542844","text":"#!/usr/bin/env python3.7\n\nfrom openpyxl import load_workbook\n\nworkbook = load_workbook(filename=\"sample.xlsx\")\nsheet = workbook.active\n\nfor value in sheet.iter_rows(min_row=1,\n max_row=2,\n min_col=1,\n max_col=3,\n values_only=False):\n print(value)\n\n","sub_path":"openpyxl/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"341889014","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n path ('register',views.register,name = \"register\"),# when user wants to signup\n path ('report',views.report,name = \"report\"),# showing report page\n path('result',views.result, name=\"result\"),# when submit button is clicked\n url(r'find',views.find,name=\"find\"),#when submit to doctor button is clicked\n path('home',views.home,name=\"home\"),#main page where info is entered\n path('signup',views.signup,name=\"signup\"),# when signup is clicked\n path('login',views.login,name=\"login\"),# when login is clicked\n path('searching',views.searching,name=\"searching\"),\n path('enter',views.enter,name=\"enter\"),#starting page showing login\n path('submit',views.submit,name=\"submit\"),\n path('logout',views.logout,name=\"logout\"),\n path('',views.welcome,name=\"welcome\"),\n \n]\n","sub_path":"pred/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142199231","text":"#!/usr/bin/python\nimport sys\nimport re\nfrom seq import Sequence\nfrom seq import ResidueError\n\nclass AlignedSequence(Sequence):\n\tdef __init__(self, fn1=None, ssq1=None):\n\t\tsuper().__init__(fn1, ssq1)\n\t\tif not self.is_dna():\n\t\t\tself.is_protein()\n\tdef __getitem__(self,i):\n\t\treturn self.seq_[i]\n\tdef is_gap(self,pos):\n\t\treturn self.seq_[pos]==\"-\"\n\tdef is_dna(self):\n\t\tnot re.search(r\"[^ATGC-]\",self.seq_)\n\tdef is_protein(self):\n\t\tif self.is_dna():\n\t\t\treturn False\n\t\telse:\n\t\t\tfor i in self.seq_:\n\t\t\t\tif i not in ['G','A','V','L','I','P','F','Y','W','S','T','C','M','N','Q','K','R','H','D','E','-','X','Z','B']: #'X' a feature where the identity of the amino acid is unknown (an X is shown at this position in the sequence) and the only information concerning the modification is that the N-terminus is blocked: P80979 (Blocked amino end (Xaa))\n#Note: Pyro-Glu is often indicated in papers as ‘pGlu’ and sometimes, in one-letter code as “U”, although this is now used for selenocysteine. In figures of publications, it may be cited as Z, pQ or E\n\t\t\t\t\traise ResidueError(\"Residue '%s' cannot be identified as either a nucleotide or amino acid for sequence %s.\"%(i, self.name_))\n\t\t\treturn True \n\t#Given aligned position returns the actual sequece position \n\tdef aligned_to_sequence_position(self, apos):\n\t\tspos=0\n\t\ti=0\n\t\twhile i < apos:\n\t\t\tif self.seq_[i] != \"-\":\n\t\t\t\tspos=spos+1\n\t\t\ti=i+1\n\t\treturn spos\n\t#Given actual sequence position returns the aligned position\n\tdef sequence_to_aligned_position(self,spos):\n\t\tapos=0\n\t\ti=0\n\t\twhile spos > 0:\n\t\t\tif not self.is_gap(i):\n\t\t\t\tapos = apos+1\n\t\t\t\tspos=spos-1\n\t\t\t\ti=i+1\n\t\t\telse:\n\t\t\t\tapos= apos+1\n\t\t\t\ti=i+1\n\t\treturn apos\n","sub_path":"src/alignedseq.py","file_name":"alignedseq.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"274924978","text":"def get_eig_Jacobian(pars, fp):\n \"\"\"\n Simulate the Wilson-Cowan equations \n \n Args:\n pars : Parameter dictionary\n fp : fixed point (E, I), array\n \n Returns:\n evals : 2x1 vector of eigenvalues of the Jacobian matrix\n \"\"\"\n \n #get the parameters\n tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars['theta_E']\n tau_I, a_I, theta_I = pars['tau_I'], pars['a_I'], pars['theta_I']\n wEE, wEI = pars['wEE'], pars['wEI'] \n wIE, wII = pars['wIE'], pars['wII']\n I_ext_E, I_ext_I = pars['I_ext_E'], pars['I_ext_I']\n\n #initialization\n E = fp[0]\n I = fp[1]\n J = np.zeros((2,2))\n \n #Jacobian matrix\n J[0,0] = (-1 + wEE*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dE\n J[0,1] = (-wEI*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dI\n J[1,0] = (wIE*dF(wIE*E-wII*I+I_ext_I,a_I,theta_I))/tau_I #dGI_dE\n J[1,1] = (-1 - wII*dF(wIE*E-wII*I,a_I+I_ext_I,theta_I))/tau_I #dGI_dI \n \n # Eigenvalues\n evals = np.linalg.eig(J)[0]\n \n return evals\n\neig_1 = get_eig_Jacobian(pars, x_fp_1)\neig_2 = get_eig_Jacobian(pars, x_fp_2)\neig_3 = get_eig_Jacobian(pars, x_fp_3)\nprint(eig_1, 'Stable point')\nprint(eig_2, 'Unstable point')\nprint(eig_3, 'Stable point')","sub_path":"tutorials/W3D2_DynamicNetworks/solutions/W3D2_Tutorial2_Solution_0349af2c.py","file_name":"W3D2_Tutorial2_Solution_0349af2c.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"94880513","text":"# Log analyzer script using pandas\nimport pandas as pd\nimport os, logging, sys, re, argparse, json\n\nconfig = {\n \"REPORT_SIZE\": 1000,\n \"REPORT_DIR\": \"./reports\",\n \"LOG_DIR\": \"./log\"\n}\nnames = ['remote_addr', 'remote_user', 'empty_1', 'http_x_real_ip', 'time_local', 'timezone', 'request', 'status', 'body_bytes_sent',\n 'http_referer', \"http_user_agent\", \"http_x_forwarded_for\", \"http_X_REQUEST_ID\", \"http_X_RB_USER\", 'request_time']\nres_names = ['url', 'count', 'count_perc', 'time_sum', 'time_perc', 'time_avg', 'time_max', 'time_med']\n\ndef get_log_file_name(log_dir=config['LOG_DIR']):\n log_files = {re.findall('nginx-access-ui.log-([^\\.]+)', f)[0]: f for f in os.listdir('.'+log_dir) if re.match(r'nginx-access-ui.log-', f)}\n return log_files[max(log_files, key=int)]\n\ndef parse_command_line_arguments(config):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--config', type=argparse.FileType('r'),\n help='Configuration json file'\n )\n args = parser.parse_args()\n defaults = config\n if args.config:\n try:\n defaults = json.load(args.config)\n except ValueError:\n print('Error: Could not parse config file', sys.stderr.write())\n finally:\n args.config.close()\n return defaults\n\ndef read_log_name(config):\n actual_log_file_name, actual_date = get_log_file_name(), re.findall('log-([^\\.]+)', get_log_file_name())[0]\n report_file = '.' + config['REPORT_DIR'] + '/report-' + actual_date[:4] + '.' + actual_date[4:6] + '.' + actual_date[6:] + '.html'\n print('Last actual log date is ' + actual_date + ', loading...')\n return actual_log_file_name, actual_date, report_file\n\ndef load_log(actual_log_file_name, names, config):\n return pd.read_table('.' + config['LOG_DIR'] + '/' + actual_log_file_name, sep=' ', names=names, index_col=False)\n\ndef process_log(actual_log_file_name, actual_date, report_file, df, res_names):\n print('Processing report for ' + actual_date + '...')\n url_regexp = '([^\\s]+)\\sHTTP'\n df['url'] = df['request'].str.extract(url_regexp, expand=False)\n res = df.groupby(['url']).agg({'request_time':['count', 'sum', 'mean', 'max', 'median']}).reset_index()\n res.columns = res.columns.droplevel(0)\n res['time_perc'], res['count_perc'] = 100 * res['sum'] / res['sum'].sum(), 100 * res['count'] / res['count'].sum()\n res.columns = ['url', 'count', 'time_sum', 'time_avg', 'time_max', 'time_med', 'time_perc', 'count_perc']\n return res[res_names].sort_values('time_sum', ascending=False).reset_index(drop=True)\n\ndef write_report(res, report_file, actual_date):\n path = os.path.dirname(report_file)\n if not os.path.exists(path):\n try:\n os.makedirs(path)\n except OSError:\n print (\"Creation of the directory %s failed\" % path)\n else:\n print (\"Successfully created the directory %s \" % path)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.max_colwidth',100)\n pd.set_option('display.float_format', lambda x: '%.3f' % x)\n res.to_html(report_file, index=False)\n print('Report done for ' + actual_date)\n\ndef main():\n # Reading config\n actual_config = parse_command_line_arguments(config)\n\n # Reading log\n actual_log_file_name, actual_date, report_file = read_log_name(config=actual_config)\n\n # Check_if_report_exists\n if os.path.isfile(report_file):\n print('!!! Last actual date report file already exists !!!')\n sys.exit()\n\n # Loading log file\n df = load_log(actual_log_file_name, names, config=actual_config)\n\n # Processing log\n res = process_log(actual_log_file_name, actual_date, report_file, df, res_names)\n\n # Writing html report\n write_report(res, report_file, actual_date)\n\n# main\nif __name__ == \"__main__\":\n main()\n","sub_path":"01_advanced_basics/log_analyzer/src/log_analyzer_pandas.py","file_name":"log_analyzer_pandas.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"151908308","text":"import abc\nfrom collections import OrderedDict, deque\nimport time\n\nimport gtimer as gt\nfrom tqdm import trange\nimport numpy as np\nimport torch\n\nfrom utils.logging import logger\nimport utils.pytorch_util as ptu\nimport ray\n\n\nclass BatchMetaRLAlgorithm(metaclass=abc.ABCMeta):\n def __init__(\n self,\n trainer,\n path_collector,\n train_buffer,\n train_goals,\n wd_goals,\n ood_goals,\n num_epochs,\n num_train_loops_per_epoch,\n num_tasks,\n num_workers,\n ):\n super().__init__()\n\n self.train_buffer = train_buffer\n self.num_epochs = num_epochs\n self.num_train_loops_per_epoch = num_train_loops_per_epoch\n self.path_collector = path_collector\n self.num_tasks = num_tasks\n self.num_workers = num_workers\n self.train_goals = [goal for goal in train_goals]\n self.wd_goals = [goal for goal in wd_goals]\n self.ood_goals = [goal for goal in ood_goals]\n\n self.trainer = trainer\n\n self.avg_train_episode_returns = []\n self.final_train_achieved = []\n self.train_avg_returns = 0.\n\n self.avg_wd_episode_returns = []\n self.final_wd_achieved = []\n self.wd_avg_returns = 0.\n\n self.avg_ood_episode_returns = []\n self.final_ood_achieved = []\n self.ood_avg_returns = 0.\n\n self._start_epoch = 0\n\n def train(self, start_epoch=0):\n self._start_epoch = start_epoch\n self._train()\n\n def _train(self):\n\n batch_idxes = np.arange(self.num_tasks)\n\n gt.start()\n\n for epoch in gt.timed_for(\n trange(self._start_epoch, self.num_epochs),\n save_itrs=True,\n ): \n # Distribute the evaluation. We ship the \n # params of each needed network to the \n # remote path collector\n params_list = []\n for net in self.trainer.networks:\n params_list.append(ptu.state_dict_cpu(net))\n\n self.path_collector.set_network_params(params_list)\n\n gt.stamp('ship_params_to_evaluate', unique=False)\n\n evaluation_train_obj_id_list = []\n count = 0\n while count < len(self.train_goals) :\n if len(self.train_goals) - count < self.num_workers:\n evaluation_obj_id = self.path_collector.async_evaluate(self.train_goals[count:])\n count = len(self.train_goals)\n else:\n evaluation_obj_id = self.path_collector.async_evaluate(self.train_goals[count:count + self.num_workers])\n count += self.num_workers\n evaluation_train_obj_id_list.extend(evaluation_obj_id)\n\n assert len(evaluation_train_obj_id_list) == len(self.train_goals)\n\n evaluation_wd_obj_id_list = []\n count = 0\n while count < len(self.wd_goals) :\n if len(self.wd_goals) - count < self.num_workers:\n evaluation_obj_id = self.path_collector.async_evaluate(self.wd_goals[count:])\n count = len(self.wd_goals)\n else:\n evaluation_obj_id = self.path_collector.async_evaluate(self.wd_goals[count:count + self.num_workers])\n count += self.num_workers\n evaluation_wd_obj_id_list.extend(evaluation_obj_id)\n\n assert len(evaluation_wd_obj_id_list) == len(self.wd_goals)\n\n # evaluation_ood_obj_id_list = []\n # count = 0\n # while count < len(self.ood_goals) :\n # if len(self.ood_goals) - count < self.num_workers:\n # evaluation_obj_id = self.path_collector.async_evaluate(self.ood_goals[count:])\n # count = len(self.ood_goals)\n # else:\n # evaluation_obj_id = self.path_collector.async_evaluate(self.ood_goals[count:count + self.num_workers])\n # count += self.num_workers\n # evaluation_ood_obj_id_list.extend(evaluation_obj_id)\n\n # assert len(evaluation_ood_obj_id_list) == len(self.ood_goals)\n\n gt.stamp('set_up_evaluation', unique=False)\n\n # Sample meta training tasks. And transfer the\n # transitions sampling job to each remote replay buffer.\n train_batch_obj_id = self.train_buffer.sample_training_data(batch_idxes)\n\n for it in range(self.num_train_loops_per_epoch):\n train_raw_batch = ray.get(train_batch_obj_id)\n gt.stamp('sample_training_data', unique=False)\n\n # In this way, we can start the data sampling job for the\n # next training while doing training for the current loop.\n train_batch_obj_id = self.train_buffer.sample_training_data(batch_idxes)\n gt.stamp('set_up_sampling', unique=False)\n\n train_data = self.construct_training_batch(train_raw_batch)\n gt.stamp('construct_training_batch', unique=False)\n\n self.trainer.train(train_data, batch_idxes)\n\n if (it + 1) % 100 == 0:\n print(it)\n\n eval_train_returns = ray.get(evaluation_train_obj_id_list)\n\n self.avg_train_episode_returns = [item[0] for item in eval_train_returns]\n self.final_train_achieved = [item[1] for item in eval_train_returns]\n self.train_avg_returns = np.mean(self.avg_train_episode_returns)\n \n eval_wd_returns = ray.get(evaluation_wd_obj_id_list)\n\n self.avg_wd_episode_returns = [item[0] for item in eval_wd_returns]\n self.final_wd_achieved = [item[1] for item in eval_wd_returns]\n self.wd_avg_returns = np.mean(self.avg_wd_episode_returns)\n\n # eval_ood_returns = ray.get(evaluation_ood_obj_id_list)\n\n # self.avg_ood_episode_returns = [item[0] for item in eval_ood_returns]\n # self.final_ood_achieved = [item[1] for item in eval_ood_returns]\n # self.ood_avg_returns = np.mean(self.avg_ood_episode_returns)\n\n gt.stamp('evaluation', unique=False)\n\n self._end_epoch(epoch)\n\n def construct_training_batch(self, raw_batch):\n ''' Construct training batch from raw batch'''\n # obs = np.concatenate([rb[0] for rb in raw_batch], axis=0)\n # actions = np.concatenate([rb[2] for rb in raw_batch], axis=0)\n # contexts = np.concatenate([rb[4] for rb in raw_batch], axis=0)\n # rewards = np.concatenate([rb[3] for rb in raw_batch], axis=0)\n # next_obs = np.concatenate([rb[1] for rb in raw_batch], axis=0)\n\n obs = torch.cat(tuple(\n ptu.elem_or_tuple_to_variable(rb[0]) for rb in raw_batch\n ), dim=0)\n actions = torch.cat(tuple(\n ptu.elem_or_tuple_to_variable(rb[2]) for rb in raw_batch\n ), dim=0)\n\n # contexts: list of contexts from each tasks: \n # (num_candidate_context, num_trans_context, context_dim)\n contexts = [ptu.elem_or_tuple_to_variable(rb[4]) for rb in raw_batch]\n\n return {\n 'obs': obs,\n 'actions': actions,\n 'contexts': contexts,\n }\n \n def get_evaluation_diagnostics(self):\n eval = OrderedDict()\n\n eval['avg_train_episode_returns'] = self.avg_train_episode_returns\n eval['final_train_achieved'] = self.final_train_achieved\n eval['train_avg_returns'] = self.train_avg_returns\n\n eval['avg_wd_episode_returns'] = self.avg_wd_episode_returns\n eval['final_wd_achieved'] = self.final_wd_achieved\n eval['wd_avg_returns'] = self.wd_avg_returns\n\n eval['avg_ood_episode_returns'] = self.avg_ood_episode_returns\n eval['final_ood_achieved'] = self.final_ood_achieved\n eval['ood_avg_returns'] = self.ood_avg_returns\n return eval\n\n def _end_epoch(self, epoch):\n\n self._log_stats(epoch)\n if epoch > 0:\n snapshot = self._get_snapshot(epoch)\n logger.save_itr_params(epoch + 1, snapshot)\n gt.stamp('saving', unique=False)\n\n self.trainer.end_epoch(epoch)\n self.path_collector.end_epoch(epoch)\n self.train_buffer.end_epoch(epoch)\n\n logger.record_dict(_get_epoch_timings())\n logger.record_tabular('Epoch', epoch)\n\n write_header = True if epoch == 0 else False\n logger.dump_tabular(with_prefix=False, with_timestamp=False,\n write_header=write_header)\n\n def _get_snapshot(self, epoch):\n ''''\n Currently we do not need to get snapt shot\n '''\n snapshot = dict(\n trainer=self.trainer.get_snapshot(),\n )\n\n # What epoch indicates is that at the end of this epoch,\n # The state of the program is snapshot\n # Not to be confused with at the beginning of the epoch\n snapshot['epoch'] = epoch\n\n # Save the state of various rng\n snapshot['global_pkg_rng_state'] = get_global_pkg_rng_state()\n\n return snapshot\n\n def _log_stats(self, epoch):\n logger.log(\"Epoch {} finished\".format(epoch), with_timestamp=True)\n\n \"\"\"\n Trainer\n \"\"\"\n logger.record_dict(self.trainer.get_diagnostics(), prefix='trainer/')\n\n \"\"\"\n Evaluation\n \"\"\"\n logger.record_dict(self.get_evaluation_diagnostics(), prefix='eval/')\n \"\"\"\n Misc\n \"\"\"\n gt.stamp('logging')\n\n def to(self, device):\n for net in self.trainer.networks:\n net.to(device)\n\n\ndef _get_epoch_timings():\n times_itrs = gt.get_times().stamps.itrs\n times = OrderedDict()\n epoch_time = 0\n for key in sorted(times_itrs):\n time = times_itrs[key][-1]\n epoch_time += time\n times['time/{} (s)'.format(key)] = time\n times['time/epoch (s)'] = epoch_time\n times['time/total (s)'] = gt.get_times().total\n return times\n\ndef get_global_pkg_rng_state():\n\n rng = dict()\n\n rng['np_rng_state'] = np.random.get_state()\n rng['t_cpu_rng_state'] = torch.get_rng_state()\n\n if torch.cuda.is_available():\n rng['t_gpu_rng_state'] = torch.cuda.get_rng_state_all()\n\n return rng","sub_path":"no_transition_relabelling/rl_algorithm.py","file_name":"rl_algorithm.py","file_ext":"py","file_size_in_byte":10266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"198695723","text":"from subprocess import check_call, CalledProcessError\n\ndef findSolution(lpFile, solutionFile):\n '''\n Launch the command in windows shell to find the solution of the lp file\n\n :param lpFile: \n :param solutionFile:\n\n :type lpFile:\n :type solutionFile:\n\n :return solutionFile: the file of the solution\n '''\n try:\n check_call([\"glpsol\", \"--cpxlp\", lpFile , \"-o\", solutionFile])\n except CalledProcessError:\n print(\"\\n/!\\ Impossible de lancer la commande pour résoudre le fichier lp /!\\ \\n\")\n exit()\n \n return solutionFile\n\nif __name__ == \"__main__\":\n findSolution(\"test4\", \"soltion8\")","sub_path":"Other files/findSolution.py","file_name":"findSolution.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"604065791","text":"#!/usr/bin/env python3\n\nactual_date_raw = str(input()).split(\" \")\nexpected_date_raw = str(input()).split(\" \")\n\nexpected_date = {'day': int(expected_date_raw[0]), 'month': int(expected_date_raw[1]), 'year': int(expected_date_raw[2])}\nactual_date = {'day': int(actual_date_raw[0]), 'month': int(actual_date_raw[1]), 'year': int(actual_date_raw[2])}\n\nday_diff = actual_date['day'] - expected_date['day']\nmonth_diff = actual_date['month'] - expected_date['month']\nyear_diff = actual_date['year'] - expected_date['year']\n\nif year_diff >= 1:\n print(10000)\nelif year_diff < 0:\n print(0)\nelif month_diff >= 1:\n fine = 500 * month_diff\n print(fine)\nelif day_diff >= 1:\n fine = 15 * day_diff\n print(fine)\nelse:\n print(0)","sub_path":"30-days-of-code-hr-2/day-26/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"436044199","text":"\"\"\"Madgrad optimizer implementation.\"\"\"\nimport tensorflow as tf\n\n\n@tf.keras.utils.register_keras_serializable(package=\"MadGrad\", name=\"MadGrad\")\nclass MadGrad(tf.keras.optimizers.Optimizer):\n r\"\"\"Optimizer that implements the MADGRAD algorithm.\n Args:\n learning_rate: A Tensor or a floating point value. The learning rate.\n momentum: A float value or a constant float tensor. Accelerates in the\n direction of gradient descent and dampens oscillations\n weight_decay: A float value or a constant float tensor. Factor by which\n the weights are decayed\n epsilon: A small constant for numerical stability.\n name: Optional name for the operations created when applying gradients.\n Defaults to `\"Madgrad\"`.\n **kwargs: Keyword arguments. Allowed to be one of\n `\"clipnorm\"` or `\"clipvalue\"`.\n `\"clipnorm\"` (float) clips gradients by norm; `\"clipvalue\"` (float) clips\n gradients by value.\n Usage Example:\n # >>> opt = MadGrad(learning_rate=0.2)\n # >>> var1 = tf.Variable(10.0)\n # >>> loss = lambda: (var1 ** 2) / 2.0\n # >>> step_count = opt.minimize(loss, [var1]).numpy()\n # >>> \"{:.1f}\".format(var1.numpy())\n 9.3\n Reference:\n - [Aaron Defazio and Samy Jelassi, 2021](https://arxiv.org/abs/2101.11075).\n \"\"\"\n\n _HAS_AGGREGATE_GRAD = True\n\n def __init__(\n self,\n learning_rate=0.01,\n momentum=0.9,\n weight_decay=0,\n epsilon=1e-6,\n name=\"MadGrad\",\n **kwargs\n ):\n learning_rate = kwargs.get(\"lr\", learning_rate)\n super(MadGrad, self).__init__(name, **kwargs)\n self._set_hyper(\"learning_rate\", kwargs.get(\"lr\", learning_rate))\n self._set_hyper(\"decay\", self._initial_decay)\n self._set_hyper(\"momentum\", momentum)\n self._set_hyper(\"weight_decay\", weight_decay)\n self.epsilon = epsilon if epsilon is not None else tf.keras.backend.epsilon()\n self._first_step = True\n\n def _create_slots(self, var_list):\n for var in var_list:\n self.add_slot(var, \"vk\")\n for var in var_list:\n self.add_slot(var, \"sk\")\n for var in var_list:\n self.add_slot(var, \"x_0\")\n\n def _prepare_local(self, var_device, var_dtype, apply_state):\n momentum = tf.identity(self._get_hyper(\"momentum\", var_dtype))\n weight_decay = tf.identity(self._get_hyper(\"weight_decay\", var_dtype))\n\n apply_state[(var_device, var_dtype)] = dict(\n epsilon=tf.convert_to_tensor(self.epsilon, var_dtype),\n momentum=momentum,\n weight_decay=weight_decay,\n )\n\n def _resource_apply_dense(self, grad, var, apply_state=None):\n return var.assign(\n self._compute_update(self, grad, var, apply_state),\n use_locking=self._use_locking,\n ).op\n\n def _resource_apply_sparse(self, grad, var, apply_state, indices):\n return var.assign(\n self._compute_update(self, grad, var, apply_state, indices),\n use_locking=self._use_locking,\n ).op\n\n def _compute_update(self, grad, var, apply_state, indices=[]):\n var_device, var_dtype = var.device, var.dtype.base_dtype\n device_pair = (var_device, var_dtype)\n coefficients = (apply_state or {}).get(\n device_pair\n ) or self._fallback_apply_state(var_device, var_dtype)\n\n eps = coefficients[\"epsilon\"]\n rho = coefficients[\"momentum\"]\n vk = self.get_slot(var, \"vk\")\n sk = self.get_slot(var, \"sk\")\n x0 = self.get_slot(var, \"x_0\")\n\n lr_t = self._decayed_lr(var_dtype)\n i = tf.cast(self.iterations + 1, var_dtype)\n lbda = lr_t * tf.math.sqrt(i)\n damp = tf.cast(self._get_hyper(\"weight_decay\"), var_dtype)\n grad = tf.cond(\n tf.greater(damp, 0),\n lambda: grad + damp * var,\n lambda: grad,\n )\n if self._first_step:\n x0 = x0.assign(var, use_locking=self._use_locking)\n self._first_step = False\n\n sparse = tf.rank(indices) > 0\n s = tf.cond(\n sparse,\n lambda: self._resource_scatter_add(sk, indices, lbda * grad),\n lambda: sk.assign_add(lbda * grad, use_locking=self._use_locking),\n )\n nu = tf.cond(\n sparse,\n lambda: self._resource_scatter_add(vk, indices, lbda * grad ** 2),\n lambda: vk.assign_add(lbda * grad ** 2, use_locking=self._use_locking),\n )\n inv = tf.pow(nu, (1.0 / 3.0)) + eps\n inv_safe = tf.where(inv >= 0)\n inv_safe = tf.where(inv_safe, inv, tf.ones(inv))\n z = x0 - s / inv_safe\n x = (1 - rho) * var + (rho * z)\n return x\n\n def get_config(self):\n config = super(MadGrad, self).get_config()\n config.update(\n {\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n \"weight_decay\": self._serialize_hyperparameter(\"weight_decay\"),\n \"epsilon\": self.epsilon,\n }\n )\n return config\n","sub_path":"madgrad/madgrad.py","file_name":"madgrad.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"377057030","text":"from unittest.mock import MagicMock\n\nfrom s3mesh.forwarder import MeshToS3Forwarder\n\n\ndef build_forwarder(**kwargs):\n mock_mesh_inbox = kwargs.get(\"mesh_inbox\", MagicMock())\n mock_s3_uploader = kwargs.get(\"s3_uploader\", MagicMock())\n mock_probe = kwargs.get(\"probe\", MagicMock())\n mock_mesh_inbox.read_messages.return_value = kwargs.get(\"incoming_messages\", [])\n mock_mesh_inbox.read_messages.side_effect = kwargs.get(\"read_error\", None)\n mock_mesh_inbox.count_messages.side_effect = kwargs.get(\"count_error\", None)\n mock_mesh_inbox.count_messages.return_value = kwargs.get(\"inbox_message_count\", 0)\n\n return MeshToS3Forwarder(mock_mesh_inbox, mock_s3_uploader, mock_probe)\n","sub_path":"tests/builders/forwarder.py","file_name":"forwarder.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"197641859","text":"# Author: Ivica Nikolic (cube444@gmail.com)\n\nimport argparse\nimport sys\nsys.path.append('./metaheuristics')\nfrom simulated_annealing import *\nfrom genetic_algorithm import *\n\n\n\n# Check dependencies\ntry:\n\timport gurobipy\nexcept:\n\tprint( 'The fitness function for SKINNY is implemented as ILP.\\nThe code uses Intels Gurobi to solve ILP, however, gurobipy library cannot be imported. \\nInstall Gurobi to proceed.\\nExiting...')\n\texit(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--search\", help=\"Print debug info\", action='store')\n\nargs = parser.parse_args()\nif args.search:\n\n\tif int(args.search) == 1:\n\t\tsimmulated_annealing()\n\telif int(args.search) == 2:\n\t\tgenetic_algorithm()\n\telse:\n\t\tprint('Syntax: \\n\\tpython main.py --search METHOD\\nwhere \\nMETHOD=1 for simulated annealing, \\nMETHOD=2 for genetic algorithm')\t\t\t\n\nelse:\n\tprint('Syntax: \\n\\tpython main.py --search METHOD\\nwhere \\nMETHOD=1 for simulated annealing, \\nMETHOD=2 for genetic algorithm')\t\t\t\n\n","sub_path":"skinny/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"1547943","text":"\"\"\"Tests for user authentication in order to access my API\"\"\"\n\nAPI_PATH_NO_KEY = \"/api/v1/%s\"\nAPI_PATH_WITH_KEY = \"/api/v1/%s?api_key=not_the_right_key\"\nAPI_ENDPOINTS = ['states', 'executive', 'legislator', 'committee']\n\n\ndef test_api_key_is_required(client):\n for i in API_ENDPOINTS:\n res = client.get(API_PATH_NO_KEY % i)\n assert res.status_code == 401\n assert 'Submit an API Key' in res.data\n\n\ndef test_api_key_is_not_authorized(client):\n for i in API_ENDPOINTS:\n res = client.get(API_PATH_WITH_KEY % i)\n assert res.status_code == 401\n assert 'Not Authorized' in res.data\n","sub_path":"tests/test_api_key.py","file_name":"test_api_key.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"464393065","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom convolution import convolution\n\ndef sobel_edge_detection(image, filter):\n new_image_x = convolution(image, filter)\n\n new_image_y = convolution(image, np.flip(filter.T, axis=0))\n\n gradient_magnitude = np.sqrt(np.square(new_image_x) + np.square(new_image_y))\n\n gradient_magnitude *= 255.0 / gradient_magnitude.max()\n\n gradient_direction = np.arctan2(new_image_y, new_image_x)\n\n gradient_direction = np.rad2deg(gradient_direction)\n gradient_direction += 180\n\n return gradient_magnitude, gradient_direction\n","sub_path":"Canny_Edge_Detection_Raspberry/sobel.py","file_name":"sobel.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"85866225","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport os\n\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import url_for\nfrom flask_jwt_extended import create_access_token\n\nfrom app.config.config import DevelopmentConfig\nfrom app.models.users import User\nfrom app.utils import responses as resp\nfrom app.utils.responses import response_with\nfrom app.utils.token import generate_verification_token, confirm_verification_token\n\nuser_routes = Blueprint(\"user_routes\", __name__)\n\n\n@user_routes.route('///', methods=['POST'])\ndef create_user():\n try:\n data = request.get_json()\n if User.find_by_email(data['email']) is not None or User.find_by_username(data['username']) is not None:\n return response_with(resp.INVALID_INPUT_422)\n data['password'] = User.generate_hash(data['password'])\n token = generate_verification_token(data['email'])\n verification_email = url_for('user_routes.verify_email', token=token, _external=True)\n result = {'db_insert': str(User.create(data)), 'verification_email': verification_email}\n return response_with(resp.SUCCESS_201, value={'result': result})\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n\n\n@user_routes.route('/confirm//', methods=['GET'])\ndef verify_email(token):\n try:\n email = confirm_verification_token(token)\n except Exception as e:\n return response_with(resp.UNAUTHORIZED_401)\n user = User.find_by_email(email=email)\n if user['is_verified']:\n return response_with(resp.INVALID_INPUT_422)\n else:\n user['is_verified'] = True\n User.update_field(user, 'is_verified', True)\n return response_with(resp.SUCCESS_200, value={'message': 'E-mail verified, you can proceed to login now.'})\n\n\n@user_routes.route('/dev-login/', methods=['POST'])\ndef authenticate_dev_user():\n try:\n data = request.get_json()\n current_user = {}\n if data.get('email'):\n current_user = User.find_by_email(data['email'])\n elif data.get('username'):\n current_user = User.find_by_username(data['username'])\n if not current_user:\n return response_with(resp.SERVER_ERROR_404)\n if current_user and not current_user['is_verified']:\n return response_with(resp.BAD_REQUEST_400)\n if User.verify_hash(data['password'], current_user['password']):\n # JWT_ACCESS_TOKEN_EXPIRES en desarrollo el token no expira.\n access_token = create_access_token(identity=current_user['username'], expires_delta=False)\n return response_with(resp.SUCCESS_200,\n value={'message': 'Logged in as admin', \"access_token\": access_token})\n else:\n return response_with(resp.UNAUTHORIZED_401)\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n\n\n@user_routes.route('/login/', methods=['POST'])\ndef authenticate_user():\n try:\n data = request.get_json()\n current_user = {}\n if data.get('email'):\n current_user = User.find_by_email(data['email'])\n elif data.get('username'):\n current_user = User.find_by_username(data['username'])\n if not current_user:\n return response_with(resp.SERVER_ERROR_404)\n if current_user and not current_user['is_verified']:\n return response_with(resp.BAD_REQUEST_400)\n if User.verify_hash(data['password'], current_user['password']):\n # JWT_ACCESS_TOKEN_EXPIRES = 15 minutos por defecto\n expires = datetime.timedelta(\n minutes=int(os.environ.get('JWT_ACCESS_TOKEN_EXPIRES', DevelopmentConfig.JWT_ACCESS_TOKEN_EXPIRES)))\n access_token = create_access_token(identity=current_user['username'], expires_delta=expires)\n return response_with(resp.SUCCESS_200,\n value={'message': 'Logged in as admin', \"access_token\": access_token})\n else:\n return response_with(resp.UNAUTHORIZED_401)\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n","sub_path":"app/routes/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"514091261","text":"#!/usr/bin/python\n\n###################################################################################################\n#\n# pyral.query_builder - module to build Rally WSAPI compliant query clause\n#\n###################################################################################################\n\n__version__ = (1, 5, 2)\n\nimport re\nimport types\nimport six\nfrom six.moves.urllib.parse import quote\n\n###################################################################################################\n\nclass RallyUrlBuilder(object):\n \"\"\"\n An instance of this class is used to collect information needed to construct a\n valid URL that can be issued in a REST Request to Rally.\n The sequence of use is to obtain a RallyUrlBuilder for a named entity, \n provide qualifying criteria, augments, scoping criteria and any provision \n for a pretty response, and then call build to return the resulting resource URL.\n An instance can be re-used (for the same entity) by simply re-calling the \n specification methods with differing values and then re-calling the build method.\n \"\"\"\n parts = ['fetch', 'query', 'order', \n 'workspace', 'project', 'projectScopeUp', 'projectScopeDown', \n 'pagesize', 'start', 'pretty'\n ]\n\n def __init__(self, entity):\n self.entity = entity\n\n def qualify(self, fetch, query, order, pagesize, startIndex):\n self.fetch = fetch\n self.query = query\n self.order = order\n self.pagesize = pagesize\n self.startIndex = startIndex\n self.workspace = None\n self.project = None\n self.scopeUp = None\n self.scopeDown = None\n self.pretty = False\n \n\n def build(self, pretty=None):\n if pretty:\n self.pretty = True\n \n resource = \"{0}?\".format(self.entity)\n\n qualifiers = ['fetch=%s' % self.fetch]\n if self.query:\n##\n## print(\"RallyQueryFormatter raw query: %s\" % self.query)\n##\n query_string = RallyQueryFormatter.parenGroups(self.query)\n##\n## print(\"query_string: |query=(%s)|\" % query_string)\n##\n qualifiers.append(\"query=(%s)\" % query_string)\n if self.order:\n qualifiers.append(\"order=%s\" % quote(self.order))\n if self.workspace:\n qualifiers.append(self.workspace)\n if self.project:\n qualifiers.append(self.project)\n if self.scopeUp:\n qualifiers.append(self.scopeUp)\n if self.scopeDown:\n qualifiers.append(self.scopeDown)\n\n qualifiers.append('pagesize=%s' % self.pagesize)\n qualifiers.append('start=%s' % self.startIndex)\n\n if self.pretty:\n qualifiers.append('pretty=true')\n\n resource += \"&\".join(qualifiers)\n##\n## print(\"RallyUrlBuilder.build: resource= %s\" % resource)\n##\n return resource\n\n def augmentWorkspace(self, augments, workspace_ref):\n wksp_augment = [aug for aug in augments if aug.startswith('workspace=')]\n self.workspace = \"workspace=%s\" % workspace_ref\n if wksp_augment:\n self.workspace = wksp_augment[0]\n\n def augmentProject(self, augments, project_ref):\n proj_augment = [aug for aug in augments if aug.startswith('project=')]\n self.project = \"project=%s\" % project_ref\n if proj_augment:\n self.project = proj_augment[0]\n\n def augmentScoping(self, augments):\n scopeUp = [aug for aug in augments if aug.startswith('projectScopeUp=')]\n if scopeUp:\n self.scopeUp = scopeUp[0]\n scopeDown = [aug for aug in augments if aug.startswith('projectScopeDown=')]\n if scopeDown:\n self.scopeDown = scopeDown[0]\n\n def beautifyResponse(self):\n self.pretty = True\n\n##################################################################################################\n\nclass RallyQueryFormatter(object):\n CONJUNCTIONS = ['and', 'AND', 'or', 'OR']\n CONJUNCTION_PATT = re.compile(r'\\s+(AND|OR)\\s+', re.I | re.M)\n ATTR_IDENTIFIER = r'[\\w\\.]+[a-zA-Z0-9]' # gotta be word-like possibly separated by '.' chars\n RELATIONSHIP = r'=|!=|>|<|>=|<=|contains|!contains'\n ATTR_VALUE = r'\"[^\"]+\"|[^ ]+' # double quoted value or has no leading, embedded or trailing spaces\n QUERY_CRITERIA_PATTERN = re.compile(r'^(%s) (%s) (%s)$' % (ATTR_IDENTIFIER, RELATIONSHIP, ATTR_VALUE), re.M)\n\n @staticmethod\n def parenGroups(criteria):\n \"\"\"\n Keep in mind that Rally WSAPI only supports a binary expression of (x) op (y)\n as in \"(foo) and (bar)\"\n or (foo) and ((bar) and (egg)) \n Note that Rally doesn't handle (x and y and z) directly.\n Look at the criteria to see if there are any parens other than begin and end \n if the only parens are at begin and end, strip them and subject the criteria to our\n clause grouper and binary expression confabulator. \n Otherwise, we'll naively assume the caller knows what they are doing, ie., they are \n aware of the binary expression requirement.\n \"\"\"\n def _encode(condition):\n \"\"\"\n if cond has pattern of 'thing relation value', then urllib.quote it and return it\n if cond has pattern of '(thing relation value)', then urllib.quote content inside parens\n then pass that result enclosed in parens back to the caller\n \"\"\"\n first_last = \"%s%s\" % (condition[0], condition[-1])\n if first_last == \"()\":\n url_encoded = quote(condition)\n else:\n url_encoded = '(%s)' % quote(condition)\n\n # replace the %xx encodings for '=', '(', ')', '!', and double quote characters\n readable_encoded = url_encoded.replace(\"%3D\", '=')\n readable_encoded = readable_encoded.replace(\"%22\", '\"')\n readable_encoded = readable_encoded.replace(\"%28\", '(')\n readable_encoded = readable_encoded.replace(\"%29\", ')')\n readable_encoded = readable_encoded.replace(\"%21\", '!')\n return readable_encoded\n##\n## print(\"RallyQueryFormatter.parenGroups criteria parm: |%s|\" % repr(criteria))\n##\n \n if type(criteria) in [list, tuple]:\n # by fiat (and until requested by a paying customer), we assume the criteria expressions are AND'ed\n #conditions = [_encode(expression) for expression in criteria] \n conditions = [expression for expression in criteria] \n criteria = \" AND \".join(conditions)\n##\n## print(\"RallyQueryFormatter: criteria is sequence type resulting in |%s|\" % criteria)\n##\n\n if type(criteria) == dict: \n expressions = []\n for field, value in list(criteria.items()):\n # have to enclose string value in double quotes, otherwise turn whatever the value is into a string\n tval = '\"%s\"' % value if type(value) == bytes else '%s' % value\n expression = ('%s = %s' % (field, tval))\n if len(criteria) == 1:\n return expression.replace(' ', '%20')\n expressions.append(expression)\n criteria = \" AND \".join(expressions)\n\n # if the caller has a simple query in the form \"(something relation a_value)\"\n # then return the query as is (after stripping off the surrounding parens)\n if criteria.count('(') == 1 and criteria.count(')') == 1 and \\\n criteria.strip()[0] == '(' and criteria.strip()[-1] == ')':\n return criteria.strip()[1:-1].replace(' ', '%20')\n \n # if caller has more than one opening paren, summarily return the query \n # after stripping off the opening paren at the start of the string and the \n # closing parent at the end of the string\n # The assumption is that the caller has correctly done the parenthesized grouping\n # to end up in a binary form but we strip off the enclosing parens because the \n # caller (RallyUrlBuilder) will be immediately supplying them after the return from here.\n if criteria.count('(') > 1:\n stripped_and_plugged = criteria.strip()[1:-1].replace(' ', '%20')\n return stripped_and_plugged\n\n # commented out following substitution for 1.5.0, as later a call to quote(criteria ...)\n # ends up url-encoding the %26 resulting a a value of %2526 which goofs things up on the back-end in Rally\n #criteria = criteria.replace('&', '%26')\n parts = RallyQueryFormatter.CONJUNCTION_PATT.split(criteria.strip())\n # adjust parts for range condition presence, coalesce parts components that have a sequence of\n # 'foo between value1', 'and', 'value2' into 'foo between value1 and value2',\n adjusted_parts = []\n temp = parts[:]\n while temp:\n if len(temp) > 2:\n if 'between ' in temp[0].lower() and temp[1].lower() == 'and' and temp[2] and ' ' not in temp[2]:\n range_part = f'{temp[0]} {temp[1]} {temp[2]}'\n adjusted_parts.append(range_part)\n conj = temp[1][:]\n temp = temp[3:] if len(temp) > 3 else []\n # and take out 1 'and' or 'AND' conjunction from conjunctions\n continue\n adjusted_parts.append(temp.pop(0))\n parts = adjusted_parts\n\n##\n## print(\"RallyQueryFormatter parts: %s\" % repr(parts))\n##\n # if no CONJUNCTION is in parts, use the condition as is (simple case)\n # OR if the criteria looks like subset query or a range query\n conjunctions = [p for p in parts if p in RallyQueryFormatter.CONJUNCTIONS]\n #if not conjunctions or re.search(r'!?between .+\\s+and\\s+', criteria, flags=re.I):\n if not conjunctions and re.search(r'^[\\w\\.0-9]+\\s+!?between .+\\s+and\\s+.+$', criteria, flags=re.I):\n attr_ident = r'[\\w\\.]+[a-zA-Z0-9]'\n # Is this a subset expression, foo in baz,korn or foo !in burgers,fries,toast\n mo = re.search(r'^(%s)\\s+(!?in)\\s+(.+)$' % attr_ident, criteria, flags=re.I)\n if mo:\n attr_name, cond, values = mo.group(1), mo.group(2), mo.group(3)\n # Rally WSAPI supports attr_name in value1,value2,... directly but not so with !in\n if cond.lower() == '!in': # we must construct an OR'ed express with != for each listed value\n # Rally WSAPI supports attr_name in value1,value2,... directly but not so with !in\n criteria = RallyQueryFormatter.constructSubsetExpression(attr_name, cond, values)\n else:\n # Is this a range expression, someDate between today and nextYear\n mo = re.search(r'^(%s)\\s+(!?between)\\s+(.+)\\s+and\\s+(.+)$' % attr_ident, criteria, flags=re.I)\n if mo:\n attr_name, cond, lesser, greater = mo.group(1), mo.group(2), mo.group(3), mo.group(4)\n criteria = RallyQueryFormatter.constructRangefulExpression(attr_name, cond, lesser, greater)\n\n expression = quote(criteria.strip()).replace('%28', '(').replace('%29', ')')\n return expression\n\n parts = RallyQueryFormatter.validatePartsSyntax(parts)\n binary_expression = quote(parts.pop())\n while parts:\n item = parts.pop()\n if item in RallyQueryFormatter.CONJUNCTIONS:\n conj = item\n binary_expression = \"%s (%s)\" % (conj, binary_expression)\n else:\n cond = quote(item)\n binary_expression = \"(%s) %s\" % (cond, binary_expression)\n\n encoded_parened_expression = binary_expression.replace('%28', '(').replace('%29', ')')\n##\n## print(\"RallyQueryFormatter.encoded_parened_expression: |{0}|\".format(encoded_parened_expression))\n## print(\"=============================================================\")\n##\n final_expression = encoded_parened_expression.replace(' ', '%20')\n return final_expression\n\n @staticmethod\n def validatePartsSyntax(parts):\n attr_ident = r'[\\w\\.]+[a-zA-Z0-9]'\n relationship = r'=|!=|>|<|>=|<=|contains|!contains'\n attr_value = r'\"[^\"]+\"|[^\" ]+'\n criteria_pattern = re.compile(r'^(%s) (%s) (%s)$' % (attr_ident, relationship, attr_value))\n quoted_value_pattern = re.compile(r'^(%s) (%s) (\"[^\"]+\")$' % (attr_ident, relationship))\n unquoted_value_pattern = re.compile(r'^(%s) (%s) ([^\"].+[^\"])$' % (attr_ident, relationship))\n subset_pattern = re.compile(r'^(%s)\\s+(!?in)\\s+(.+)$' % attr_ident, flags=re.I)\n range_pattern = re.compile(r'^(%s)\\s+(!?between)\\s+(.+)\\s+and\\s+(.+)$' % attr_ident, flags=re.I)\n\n valid_parts = []\n front = \"\"\n while parts:\n part = \"%s%s\" % (front, parts.pop(0))\n\n mo = subset_pattern.match(part)\n if mo:\n attr_name, cond, values = mo.group(1), mo.group(2), mo.group(3)\n # Rally WSAPI supports attr_name in value1,value2,... directly, but not so with !in\n if cond.lower() == 'in':\n valid_parts.append(part)\n else: # we must construct an OR'ed express with != for each listed value\n criteria = RallyQueryFormatter.constructSubsetExpression(attr_name, cond, values)\n valid_parts.append(criteria)\n continue\n\n mo = range_pattern.match(part)\n if mo:\n attr_name, cond, lesser, greater = mo.group(1), mo.group(2), mo.group(3), mo.group(4)\n criteria = RallyQueryFormatter.constructRangefulExpression(attr_name, cond, lesser, greater)\n valid_parts.append(criteria)\n continue\n\n if criteria_pattern.match(part):\n valid_parts.append(part)\n elif quoted_value_pattern.match(part):\n valid_parts.append(part)\n elif unquoted_value_pattern.match(part):\n wordles = part.split(' ', 2)\n recast_part = '%s %s \"%s\"' % tuple(wordles)\n valid_parts.append(recast_part)\n else:\n if re.match(r'^(AND|OR)$', part, re.I):\n valid_parts.append(part)\n else:\n front = part + \" \"\n\n if not valid_parts:\n raise Exception(\"Invalid query expression syntax in: %s\" % (\" \".join(parts)))\n \n return valid_parts\n\n #\n # subset and range related ops for building queries\n #\n @staticmethod\n def constructSubsetExpression(field, relation, values):\n \"\"\"\n intended for use when a subset operator (in or !in) is in play\n State in Defined, Accepted, Relased\n needs an ORed expression ((f = D OR f = A) OR ((f = R)))\n State !in Working, Fixed, Testing\n needs an ANDed expression ((f != W AND f != F) AND ((f != T)))\n \"\"\"\n operator, conjunction = \"=\", 'OR'\n if relation.lower() == '!in':\n operator = \"!=\"\n conjunction = 'AND'\n if isinstance(values, str):\n if values.count(',') == 0: # no commas equal only 1 value considered, put it in a list\n values = [values]\n else:\n values = [item.lstrip().rstrip() for item in values.split(',')]\n if len(values) == 1:\n return f'{field} {operator} \"{values[0]}\"'\n val1, val2 = values[:2]\n binary_expression = f'({field} {operator} \"{val1}\") {conjunction} ({field} {operator} \"{val2}\")'\n for value in values[2:]:\n binary_expression = f'({binary_expression}) {conjunction} ({field} {operator} \"{value}\")'\n return binary_expression\n\n @staticmethod\n def constructRangefulExpression(attr_name, cond, lesser, greater):\n \"\"\"\n intended for use when a range operator (between or !between) is in play\n DevPhase between 2021-05-23 and 2021-07-09\n needs a single ANDed expression ((dp >= d1) AND (dp <= d1)))\n DevPhase !between 2021-12-19 and 2022-01-03\n needs a single ORed expression ((dp < d1) OR (dp > d1)))\n \"\"\"\n rlns = ['>=', '<='] if cond.lower() == 'between' else ['<', '>']\n conjunction= 'AND' if cond.lower() == 'between' else 'OR'\n lcond = '%s %s %s' % (attr_name, rlns[0], lesser)\n gcond = '%s %s %s' % (attr_name, rlns[1], greater)\n expression = \"(%s) %s (%s)\" % (lcond, conjunction, gcond)\n return expression\n\n##################################################################################################\n","sub_path":"pyral/query_builder.py","file_name":"query_builder.py","file_ext":"py","file_size_in_byte":16918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"570784061","text":"from django.shortcuts import render, redirect\nfrom django.core.mail import send_mail\nfrom django.views import View\nfrom product.models import Category\nfrom cart.models import *\nfrom order.models import Order\n\ncart = {}\n\n\nclass CartController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n quantity = 0\n try:\n cart = request.session['cart']\n\n for key, value in cart.items():\n quantity += int(value['quantity'])\n\n total = 0\n if len(cart) > 0:\n for key, value in cart.items():\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n return render(request, 'cart.html', {\n 'category': category,\n 'cart_quantity': quantity,\n 'total': total,\n })\n else:\n return render(request, 'empty_cart.html', {\n 'category': category,\n 'cart_quantity': quantity\n })\n except:\n return render(request, 'empty_cart.html', {\n 'category': category,\n 'cart_quantity': quantity\n })\n\n def add_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n num = request.POST['quantity']\n product = Product.objects.get(id=id)\n if id in cart.keys():\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': int(cart[id]['quantity']) + int(num)\n }\n else:\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': num\n }\n\n cart[id] = item\n\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n def update_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n num = request.POST['quantity']\n product = Product.objects.get(id=id)\n if id in cart.keys():\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': num\n }\n\n cart[id] = item\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n def remove_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n if id in cart.keys():\n del cart[id]\n\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n\nclass CheckoutController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n return render(request, 'checkout.html', {\n 'category': category\n })\n\n\nclass PaymentController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n\n quantity = 0\n total = 0\n for key, value in cart.items():\n quantity += int(value['quantity'])\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n\n return render(request, 'payment.html', {\n 'category': category,\n 'cart_quantity': quantity,\n 'total': total\n })\n\n def post(request):\n name = request.POST['Name']\n address = request.POST['Address']\n email = request.POST['Email']\n note = request.POST['Note']\n\n lst = []\n\n c = Cart()\n total = 0\n for key, value in cart.items():\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n lst.append(value['name'] + ' - ' + str(value['quantity']))\n\n c.user = name\n c.total = total\n c.save()\n\n i = Cart.objects.last()\n for key, value in cart.items():\n item = CartItem()\n item.title = i.user\n item.product_id = int(key)\n item.quantity = value['quantity']\n if int(value['sale']) > 0:\n\n item.price = int(value['sale'])\n else:\n item.price = int(value['price'])\n item.save()\n\n order = Order()\n order.user = i.user\n order.product = lst\n order.ship_address = address\n order.description = note\n order.save()\n\n\n message = 'Xin chào {0}, đơn hàng của bạn đã được đặt thành công.\\nCác món bạn đã đặt là {1}.\\nTổng giá trị đơn hàng là {2} vnđ (chưa bao gồm phí vận chuyển).\\nĐịa chỉ giao hàng: {3}.\\nCảm ơn quí khách đã sử dụng dịch vụ.'.format(name, lst, total, address)\n\n send_mail(\n 'New Coffee',\n message,\n 'newcoffee138hadac@gmail.com',\n [email]\n )\n\n cart.clear()\n request.session['cart'] = cart\n\n return redirect('home:index')\n\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"302879392","text":"\ndef findEndPoint(num, dict):\n halt = False\n orig = num\n while not halt:\n if num == 1:\n dict[orig] = num\n return 1\n if num == 89:\n dict[orig] = num\n return 89\n if num in dict:\n dict[orig] = dict[num]\n return dict[num]\n \n temp = 0\n for ch in str(num):\n temp += int(ch)**2\n num = temp\n\ndef main():\n dict = {}\n\n answer = 0\n for num in range(1,10000000):\n check = findEndPoint(num, dict)\n if check == 89:\n answer +=1\n\n print(answer)\n\nmain()\n\n","sub_path":"Python/euler92/euler92/euler92.py","file_name":"euler92.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"162337725","text":"from app1.models import *\nfrom app1.util.utils import *\n\ndef updateTeachPlan(request):\n '''\n get:\n http://127.0.0.1:8000/app1/updateTeachPlan?tpno=001&credit=7.0&teach_date=2011-08-22&evaluation_method=考查\n post:\n http://127.0.0.1:8000/app1/updateTeachPlan\n '''\n try:\n if(request.method=='POST'):\n teadata=json.loads(request.body)\n data=teadata[\"data\"]\n for item in data:\n # tpid=request.GET.get(\"tpno\")\n # cr=request.GET.get(\"credit\")\n # te=request.GET.get(\"teach_date\")\n # ev=request.GET.get(\"evaluation_method\")\n\n tpid=item[\"tpno\"]\n cr=item[\"credit\"]\n te=item[\"teach_date\"]\n ev=item[\"evaluation_method\"]\n\n result=TeachPlan.objects.filter(tpno=tpid).update(credit=cr,teach_date=te,evaluation_method=ev)\n\n result=TeachPlan.objects.all().values(\"tpno\",\"credit\",\"teach_date\",\"evaluation_method\",\"department__dno\",\"department__dname\",\"course__cno\",\"course__cname\",\"teacher__tno\",\"teacher__tname\")\n return showJsonresult(result)\n except Exception as e:\n response={}\n response['msg']=str(e)\n response['err_num']=1\n return showJsonerror(response) ","sub_path":"day08/django/app1/dateview/updateTeachPlan.py","file_name":"updateTeachPlan.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"314745005","text":"# Copyright (c) 2009-2019 The Regents of the University of Michigan\n# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\nR\"\"\" Pair potentials.\n\nGenerally, pair forces are short range and are summed over all non-bonded particles\nwithin a certain cutoff radius of each particle. Any number of pair forces\ncan be defined in a single simulation. The net force on each particle due to\nall types of pair forces is summed.\n\nPair forces require that parameters be set for each unique type pair. Coefficients\nare set through the aid of the :py:class:`coeff` class. To set these coefficients, specify\na pair force and save it in a variable::\n\n my_force = pair.some_pair_force(arguments...)\n\nThen the coefficients can be set using the saved variable::\n\n my_force.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n my_force.pair_coeff.set('A', 'B', epsilon=1.0, sigma=2.0)\n my_force.pair_coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n\nThis example set the parameters *epsilon* and *sigma*\n(which are used in :py:class:`lj`). Different pair forces require that different\ncoefficients are set. Check the documentation of each to see the definition\nof the coefficients.\n\"\"\"\n\nfrom hoomd import _hoomd\nfrom hoomd.md import _md\nfrom hoomd.md import force;\nfrom hoomd.md import nlist as nl # to avoid naming conflicts\nimport hoomd;\n\nimport math;\nimport sys;\nimport json;\nfrom collections import OrderedDict\n\nclass coeff:\n R\"\"\" Define pair coefficients\n\n All pair forces use :py:class:`coeff` to specify the coefficients between different\n pairs of particles indexed by type. The set of pair coefficients is a symmetric\n matrix defined over all possible pairs of particle types.\n\n There are two ways to set the coefficients for a particular pair force.\n The first way is to save the pair force in a variable and call :py:meth:`set()` directly.\n\n The second method is to build the :py:class:`coeff` class first and then assign it to the\n pair force. There are some advantages to this method in that you could specify a\n complicated set of pair coefficients in a separate python file and import it into\n your job script.\n\n Example (**force_field.py**)::\n\n from hoomd import md\n my_coeffs = md.pair.coeff();\n my_force.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n my_force.pair_coeff.set('A', 'B', epsilon=1.0, sigma=2.0)\n my_force.pair_coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n\n Example job script::\n\n from hoomd import md\n import force_field\n\n .....\n my_force = md.pair.some_pair_force(arguments...)\n my_force.pair_coeff = force_field.my_coeffs\n\n \"\"\"\n\n ## \\internal\n # \\brief Initializes the class\n # \\details\n # The main task to be performed during initialization is just to init some variables\n # \\param self Python required class instance variable\n def __init__(self):\n self.values = {};\n self.default_coeff = {}\n\n ## \\internal\n # \\brief Return a compact representation of the pair coefficients\n def get_metadata(self):\n # return list for easy serialization\n l = []\n for (a,b) in self.values:\n item = OrderedDict()\n item['typei'] = a\n item['typej'] = b\n for coeff in self.values[(a,b)]:\n item[coeff] = self.values[(a,b)][coeff]\n l.append(item)\n return l\n\n ## \\var values\n # \\internal\n # \\brief Contains the matrix of set values in a dictionary\n\n ## \\var default_coeff\n # \\internal\n # \\brief default_coeff['coeff'] lists the default value for \\a coeff, if it is set\n\n ## \\internal\n # \\brief Sets a default value for a given coefficient\n # \\details\n # \\param name Name of the coefficient to for which to set the default\n # \\param value Default value to set\n #\n # Some coefficients have reasonable default values and the user should not be burdened with typing them in\n # all the time. set_default_coeff() sets\n def set_default_coeff(self, name, value):\n self.default_coeff[name] = value;\n\n def set(self, a, b, **coeffs):\n R\"\"\" Sets parameters for one type pair.\n\n Args:\n a (str): First particle type in the pair (or a list of type names)\n b (str): Second particle type in the pair (or a list of type names)\n coeffs: Named coefficients (see below for examples)\n\n Calling :py:meth:`set()` results in one or more parameters being set for a single type pair\n or set of type pairs.\n Particle types are identified by name, and parameters are also added by name.\n Which parameters you need to specify depends on the pair force you are setting\n these coefficients for, see the corresponding documentation.\n\n All possible type pairs as defined in the simulation box must be specified before\n executing :py:class:`hoomd.run()`. You will receive an error if you fail to do so. It is not an error,\n however, to specify coefficients for particle types that do not exist in the simulation.\n This can be useful in defining a force field for many different types of particles even\n when some simulations only include a subset.\n\n There is no need to specify coefficients for both pairs 'A', 'B' and 'B', 'A'. Specifying\n only one is sufficient.\n\n To set the same coefficients between many particle types, provide a list of type names instead of a single\n one. All pairs between the two lists will be set to the same parameters.\n\n Examples::\n\n coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n coeff.set('A', 'B', epsilon=1.5, sigma=1.0)\n coeff.set(['A', 'B', 'C', 'D'], 'F', epsilon=2.0)\n coeff.set(['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], epsilon=1.0)\n\n system = init.read_xml('init.xml')\n coeff.set(system.particles.types, system.particles.types, epsilon=2.0)\n coeff.set('A', system.particles.types, epsilon=1.2)\n\n Note:\n Single parameters can be updated. If both epsilon and sigma have already been\n set for a type pair, then executing ``coeff.set('A', 'B', epsilon=1.1)`` will update\n the value of epsilon and leave sigma as it was previously set.\n\n Some pair potentials assign default values to certain parameters. If the default setting for a given coefficient\n (as documented in the respective pair command) is not set explicitly, the default will be used.\n\n \"\"\"\n hoomd.util.print_status_line();\n\n # listify the inputs\n a = hoomd.util.listify(a)\n b = hoomd.util.listify(b)\n\n for ai in a:\n for bi in b:\n self.set_single(ai, bi, coeffs);\n\n ## \\internal\n # \\brief Sets a single parameter\n def set_single(self, a, b, coeffs):\n a = str(a);\n b = str(b);\n\n # create the pair if it hasn't been created it\n if (not (a,b) in self.values) and (not (b,a) in self.values):\n self.values[(a,b)] = {};\n\n # Find the pair to update\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n hoomd.context.msg.error(\"Bug detected in pair.coeff. Please report\\n\");\n raise RuntimeError(\"Error setting pair coeff\");\n\n # update each of the values provided\n if len(coeffs) == 0:\n hoomd.context.msg.error(\"No coefficients specified\\n\");\n for name, val in coeffs.items():\n self.values[cur_pair][name] = val;\n\n # set the default values\n for name, val in self.default_coeff.items():\n # don't override a coeff if it is already set\n if not name in self.values[cur_pair]:\n self.values[cur_pair][name] = val;\n\n ## \\internal\n # \\brief Verifies set parameters form a full matrix with all values set\n # \\details\n # \\param self Python required self variable\n # \\param required_coeffs list of required variables\n #\n # This can only be run after the system has been initialized\n def verify(self, required_coeffs):\n # first, check that the system has been initialized\n if not hoomd.init.is_initialized():\n hoomd.context.msg.error(\"Cannot verify pair coefficients before initialization\\n\");\n raise RuntimeError('Error verifying pair coefficients');\n\n # get a list of types from the particle data\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n valid = True;\n # loop over all possible pairs and verify that all required variables are set\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n a = type_list[i];\n b = type_list[j];\n\n # find which half of the pair is set\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n hoomd.context.msg.error(\"Type pair \" + str((a,b)) + \" not found in pair coeff\\n\");\n valid = False;\n continue;\n\n # verify that all required values are set by counting the matches\n count = 0;\n for coeff_name in self.values[cur_pair].keys():\n if not coeff_name in required_coeffs:\n hoomd.context.msg.notice(2, \"Notice: Possible typo? Pair coeff \" + str(coeff_name) + \" is specified for pair \" + str((a,b)) + \\\n \", but is not used by the pair force\\n\");\n else:\n count += 1;\n\n if count != len(required_coeffs):\n hoomd.context.msg.error(\"Type pair \" + str((a,b)) + \" is missing required coefficients\\n\");\n valid = False;\n\n\n return valid;\n\n ## \\internal\n # \\brief Try to get whether a single pair coefficient\n # \\detail\n # \\param a First name in the type pair\n # \\param b Second name in the type pair\n # \\param coeff_name Coefficient to get\n def get(self,a,b,coeff_name):\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n return None;\n\n if coeff_name in self.values[cur_pair]:\n return self.values[cur_pair][coeff_name];\n else:\n return None;\n\nclass pair(force._force):\n R\"\"\" Common pair potential documentation.\n\n Users should not invoke :py:class:`pair` directly. It is a base command that provides common\n features to all standard pair forces. Common documentation for all pair potentials is documented here.\n\n All pair force commands specify that a given potential energy and force be computed on all non-excluded particle\n pairs in the system within a short range cutoff distance :math:`r_{\\mathrm{cut}}`.\n\n The force :math:`\\vec{F}` applied between each pair of particles is:\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n \\vec{F} = & -\\nabla V(r) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\vec{r}` is the vector pointing from one particle to the other in the pair, and :math:`V(r)` is\n chosen by a mode switch (see :py:meth:`set_params()`):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & V_{\\mathrm{pair}}(r) & \\mathrm{mode\\ is\\ no\\_shift} \\\\\n = & V_{\\mathrm{pair}}(r) - V_{\\mathrm{pair}}(r_{\\mathrm{cut}}) & \\mathrm{mode\\ is\\ shift} \\\\\n = & S(r) \\cdot V_{\\mathrm{pair}}(r) & \\mathrm{mode\\ is\\ xplor\\ and\\ } r_{\\mathrm{on}} < r_{\\mathrm{cut}} \\\\\n = & V_{\\mathrm{pair}}(r) - V_{\\mathrm{pair}}(r_{\\mathrm{cut}}) & \\mathrm{mode\\ is\\ xplor\\ and\\ } r_{\\mathrm{on}} \\ge r_{\\mathrm{cut}}\n \\end{eqnarray*}\n\n :math:`S(r)` is the XPLOR smoothing function:\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n S(r) = & 1 & r < r_{\\mathrm{on}} \\\\\n = & \\frac{(r_{\\mathrm{cut}}^2 - r^2)^2 \\cdot (r_{\\mathrm{cut}}^2 + 2r^2 -\n 3r_{\\mathrm{on}}^2)}{(r_{\\mathrm{cut}}^2 - r_{\\mathrm{on}}^2)^3}\n & r_{\\mathrm{on}} \\le r \\le r_{\\mathrm{cut}} \\\\\n = & 0 & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n and :math:`V_{\\mathrm{pair}}(r)` is the specific pair potential chosen by the respective command.\n\n Enabling the XPLOR smoothing function :math:`S(r)` results in both the potential energy and the force going smoothly\n to 0 at :math:`r = r_{\\mathrm{cut}}`, reducing the rate of energy drift in long simulations.\n :math:`r_{\\mathrm{on}}` controls the point at which the smoothing starts, so it can be set to only slightly modify\n the tail of the potential. It is suggested that you plot your potentials with various values of\n :math:`r_{\\mathrm{on}}` in order to find a good balance between a smooth potential function and minimal modification\n of the original :math:`V_{\\mathrm{pair}}(r)`. A good value for the LJ potential is\n :math:`r_{\\mathrm{on}} = 2 \\cdot \\sigma`.\n\n The split smoothing / shifting of the potential when the mode is ``xplor`` is designed for use in mixed WCA / LJ\n systems. The WCA potential and it's first derivative already go smoothly to 0 at the cutoff, so there is no need\n to apply the smoothing function. In such mixed systems, set :math:`r_{\\mathrm{on}}` to a value greater than\n :math:`r_{\\mathrm{cut}}` for those pairs that interact via WCA in order to enable shifting of the WCA potential\n to 0 at the cutoff.\n\n The following coefficients must be set per unique pair of particle types. See :py:mod:`hoomd.md.pair` for information\n on how to set coefficients:\n\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n When :math:`r_{\\mathrm{cut}} \\le 0` or is set to False, the particle type pair interaction is excluded from the neighbor\n list. This mechanism can be used in conjunction with multiple neighbor lists to make efficient calculations in systems\n with large size disparity. Functionally, this is equivalent to setting :math:`r_{\\mathrm{cut}} = 0` in the pair force\n because negative :math:`r_{\\mathrm{cut}}` has no physical meaning.\n \"\"\"\n\n ## \\internal\n # \\brief Initialize the pair force\n # \\details\n # The derived class must set\n # - self.cpp_class (the pair class to instantiate)\n # - self.required_coeffs (a list of the coeff names the derived class needs)\n # - self.process_coeffs() (a method that takes in the coeffs and spits out a param struct to use in\n # self.cpp_force.set_params())\n def __init__(self, r_cut, nlist, name=None):\n # initialize the base class\n force._force.__init__(self, name);\n\n # convert r_cut False to a floating point type\n if r_cut is False:\n r_cut = -1.0\n self.global_r_cut = r_cut;\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n self.pair_coeff.set_default_coeff('r_cut', self.global_r_cut);\n self.pair_coeff.set_default_coeff('r_on', self.global_r_cut);\n\n # setup the neighbor list\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n def set_params(self, mode=None):\n R\"\"\" Set parameters controlling the way forces are computed.\n\n Args:\n mode (str): (if set) Set the mode with which potentials are handled at the cutoff.\n\n Valid values for *mode* are: \"none\" (the default), \"shift\", and \"xplor\":\n\n - **none** - No shifting is performed and potentials are abruptly cut off\n - **shift** - A constant shift is applied to the entire potential so that it is 0 at the cutoff\n - **xplor** - A smoothing function is applied to gradually decrease both the force and potential to 0 at the\n cutoff when ron < rcut, and shifts the potential to 0 at the cutoff when ron >= rcut.\n\n See :py:class:`pair` for the equations.\n\n Examples::\n\n mypair.set_params(mode=\"shift\")\n mypair.set_params(mode=\"no_shift\")\n mypair.set_params(mode=\"xplor\")\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode is not None:\n if mode == \"no_shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.no_shift)\n elif mode == \"shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.shift)\n elif mode == \"xplor\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.xplor)\n else:\n hoomd.context.msg.error(\"Invalid mode\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n def process_coeff(self, coeff):\n hoomd.context.msg.error(\"Bug in hoomd, please report\\n\");\n raise RuntimeError(\"Error processing coefficients\");\n\n def update_coeffs(self):\n coeff_list = self.required_coeffs + [\"r_cut\", \"r_on\"];\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify(coeff_list):\n hoomd.context.msg.error(\"Not all pair coefficients are set\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # build a dict of the coeffs to pass to process_coeff\n coeff_dict = {};\n for name in coeff_list:\n coeff_dict[name] = self.pair_coeff.get(type_list[i], type_list[j], name);\n\n param = self.process_coeff(coeff_dict);\n self.cpp_force.setParams(i, j, param);\n\n # rcut can now have \"invalid\" C++ values, which we round up to zero\n self.cpp_force.setRcut(i, j, max(coeff_dict['r_cut'], 0.0));\n self.cpp_force.setRon(i, j, max(coeff_dict['r_on'], 0.0));\n\n ## \\internal\n # \\brief Get the maximum r_cut value set for any type pair\n # \\pre update_coeffs must be called before get_max_rcut to verify that the coeffs are set\n def get_max_rcut(self):\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # find the maximum r_cut\n max_rcut = 0.0;\n\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n r_cut = self.pair_coeff.get(type_list[i], type_list[j], 'r_cut');\n max_rcut = max(max_rcut, r_cut);\n\n return max_rcut;\n\n ## \\internal\n # \\brief Get the r_cut pair dictionary\n # \\returns The rcut(i,j) dict if logging is on, and None if logging is off\n def get_rcut(self):\n if not self.log:\n return None\n\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # update the rcut by pair type\n r_cut_dict = nl.rcut();\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n r_cut = self.pair_coeff.get(type_list[i], type_list[j], 'r_cut');\n\n if r_cut is not None: # use the defined value\n if r_cut is False: # interaction is turned off\n r_cut_dict.set_pair(type_list[i],type_list[j], -1.0);\n else:\n r_cut_dict.set_pair(type_list[i],type_list[j], r_cut);\n else: # use the global default\n r_cut_dict.set_pair(type_list[i],type_list[j],self.global_r_cut);\n\n return r_cut_dict;\n\n ## \\internal\n # \\brief Return metadata for this pair potential\n def get_metadata(self):\n data = force._force.get_metadata(self)\n\n # make sure all coefficients are set\n self.update_coeffs()\n\n data['pair_coeff'] = self.pair_coeff\n return data\n\n def compute_energy(self, tags1, tags2):\n R\"\"\" Compute the energy between two sets of particles.\n\n Args:\n tags1 (``ndarray``): a numpy array of particle tags in the first group\n tags2 (``ndarray``): a numpy array of particle tags in the second group\n\n .. math::\n\n U = \\sum_{i \\in \\mathrm{tags1}, j \\in \\mathrm{tags2}} V_{ij}(r)\n\n where :math:`V_{ij}(r)` is the pairwise energy between two particles :math:`i` and :math:`j`.\n\n Assumed properties of the sets *tags1* and *tags2* are:\n\n - *tags1* and *tags2* are disjoint\n - all elements in *tags1* and *tags2* are unique\n - *tags1* and *tags2* are contiguous numpy arrays of dtype int32\n\n None of these properties are validated.\n\n Examples::\n\n tags=numpy.linspace(0,N-1,1, dtype=numpy.int32)\n # computes the energy between even and odd particles\n U = mypair.compute_energy(tags1=numpy.array(tags[0:N:2]), tags2=numpy.array(tags[1:N:2]))\n\n \"\"\"\n # future versions could use np functions to test the assumptions above and raise an error if they occur.\n return self.cpp_force.computeEnergyBetweenSets(tags1, tags2);\n\n def _connect_gsd_shape_spec(self, gsd):\n # This is an internal method, and should not be called directly. See gsd.dump_shape() instead\n if isinstance(gsd, hoomd.dump.gsd) and hasattr(self.cpp_force, \"connectGSDShapeSpec\"):\n self.cpp_force.connectGSDShapeSpec(gsd.cpp_analyzer);\n else:\n raise NotImplementedError(\"GSD Schema is not implemented for {}\".format(self.__class__.__name__));\n\n def get_type_shapes(self):\n \"\"\"Get all the types of shapes in the current simulation.\n\n Since this behaves differently for different types of shapes, the\n default behavior just raises an exception. Subclasses can override this\n to properly return.\n \"\"\"\n raise NotImplementedError(\n \"You are using a shape type that is not implemented! \"\n \"If you want it, please modify the \"\n \"hoomd.hpmc.integrate.mode_hpmc.get_type_shapes function.\")\n\n def _return_type_shapes(self):\n type_shapes = self.cpp_force.getTypeShapesPy();\n ret = [ json.loads(json_string) for json_string in type_shapes ];\n return ret;\n\nclass lj(pair):\n R\"\"\" Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`lj` specifies that a Lennard-Jones pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n lj = pair.lj(r_cut=3.0, nlist=nl)\n lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n lj.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, alpha=0.5, r_cut=3.0, r_on=2.0);\n lj.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n lj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass gauss(pair):\n R\"\"\" Gaussian pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`gauss` specifies that a Gaussian pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{gauss}}(r) = & \\varepsilon \\exp \\left[ -\\frac{1}{2}\\left( \\frac{r}{\\sigma} \\right)^2 \\right]\n & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n gauss = pair.gauss(r_cut=3.0, nlist=nl)\n gauss.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n gauss.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, r_cut=3.0, r_on=2.0);\n gauss.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=3.0, sigma=0.5)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairGauss(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairGauss;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairGaussGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairGaussGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n\n return _hoomd.make_scalar2(epsilon, sigma);\n\nclass slj(pair):\n R\"\"\" Shifted Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n d_max (float): Maximum diameter particles in the simulation will have (in distance units)\n\n :py:class:`slj` specifies that a shifted Lennard-Jones type pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{SLJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r - \\Delta} \\right)^{12} -\n \\left( \\frac{\\sigma}{r - \\Delta} \\right)^{6} \\right] & r < (r_{\\mathrm{cut}} + \\Delta) \\\\\n = & 0 & r \\ge (r_{\\mathrm{cut}} + \\Delta) \\\\\n \\end{eqnarray*}\n\n where :math:`\\Delta = (d_i + d_j)/2 - 1` and :math:`d_i` is the diameter of particle :math:`i`.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. attention::\n Due to the way that pair.slj modifies the cutoff criteria, a shift_mode of *xplor* is not supported.\n\n The actual cutoff radius for pair.slj is shifted by the diameter of two particles interacting. Thus to determine\n the maximum possible actual r_cut in simulation\n pair.slj must know the maximum diameter of all the particles over the entire run, *d_max* .\n This value is either determined automatically from the initialization or can be set by the user and can be\n modified between runs with :py:meth:`hoomd.md.nlist.nlist.set_params()`. In most cases, the correct value can be\n identified automatically.\n\n The specified value of *d_max* will be used to properly determine the neighbor lists during the following\n :py:func:`hoomd.run()` commands. If not specified, :py:class:`slj` will set d_max to the largest diameter\n in particle data at the time it is initialized.\n\n If particle diameters change after initialization, it is **imperative** that *d_max* be the largest\n diameter that any particle will attain at any time during the following :py:func:`hoomd.run()` commands.\n If *d_max* is smaller than it should be, some particles will effectively have a smaller value of *r_cut*\n then was set and the simulation will be incorrect. *d_max* can be changed between runs by calling\n :py:meth:`hoomd.md.nlist.nlist.set_params()`.\n\n Example::\n\n nl = nlist.cell()\n slj = pair.slj(r_cut=3.0, nlist=nl, d_max = 2.0)\n slj.pair_coeff.set('A', 'A', epsilon=1.0)\n slj.pair_coeff.set('A', 'B', epsilon=2.0, r_cut=3.0);\n slj.pair_coeff.set('B', 'B', epsilon=1.0, r_cut=2**(1.0/6.0));\n slj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, d_max=None, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # update the neighbor list\n if d_max is None :\n sysdef = hoomd.context.current.system_definition;\n d_max = sysdef.getParticleData().getMaxDiameter()\n hoomd.context.msg.notice(2, \"Notice: slj set d_max=\" + str(d_max) + \"\\n\");\n\n # SLJ requires diameter shifting to be on\n self.nlist.cpp_nlist.setDiameterShift(True);\n self.nlist.cpp_nlist.setMaximumDiameter(d_max);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairSLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairSLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairSLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairSLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\n def set_params(self, mode=None):\n R\"\"\" Set parameters controlling the way forces are computed.\n\n See :py:meth:`pair.set_params()`.\n\n Note:\n **xplor** is not a valid setting for :py:class:`slj`.\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode == \"xplor\":\n hoomd.context.msg.error(\"XPLOR is smoothing is not supported with slj\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n pair.set_params(self, mode=mode);\n\nclass yukawa(pair):\n R\"\"\" Yukawa pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`yukawa` specifies that a Yukawa pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{yukawa}}(r) = & \\varepsilon \\frac{ \\exp \\left( -\\kappa r \\right) }{r} & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\kappa` - *kappa* (in units of 1/distance)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n yukawa = pair.lj(r_cut=3.0, nlist=nl)\n yukawa.pair_coeff.set('A', 'A', epsilon=1.0, kappa=1.0)\n yukawa.pair_coeff.set('A', 'B', epsilon=2.0, kappa=0.5, r_cut=3.0, r_on=2.0);\n yukawa.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=0.5, kappa=3.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairYukawa(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairYukawa;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairYukawaGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairYukawaGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'kappa'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n kappa = coeff['kappa'];\n\n return _hoomd.make_scalar2(epsilon, kappa);\n\nclass ewald(pair):\n R\"\"\" Ewald pair potential.\n\n :py:class:`ewald` specifies that a Ewald pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{ewald}}(r) = & q_i q_j \\left[\\mathrm{erfc}\\left(\\kappa r + \\frac{\\alpha}{2\\kappa}\\right) \\exp(\\alpha r)+\n \\mathrm{erfc}\\left(\\kappa r - \\frac{\\alpha}{2 \\kappa}\\right) \\exp(-\\alpha r)\\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n The Ewald potential is designed to be used in conjunction with :py:class:`hoomd.md.charge.pppm`.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\kappa` - *kappa* (Splitting parameter, in 1/distance units)\n - :math:`\\alpha` - *alpha* (Debye screening length, in 1/distance units)\n .. versionadded:: 2.1\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n\n Example::\n\n nl = nlist.cell()\n ewald = pair.ewald(r_cut=3.0, nlist=nl)\n ewald.pair_coeff.set('A', 'A', kappa=1.0)\n ewald.pair_coeff.set('A', 'A', kappa=1.0, alpha=1.5)\n ewald.pair_coeff.set('A', 'B', kappa=1.0, r_cut=3.0, r_on=2.0);\n\n Warning:\n **DO NOT** use in conjunction with :py:class:`hoomd.md.charge.pppm`. It automatically creates and configures\n :py:class:`ewald` for you.\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairEwald(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairEwald;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairEwaldGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairEwaldGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['kappa','alpha'];\n self.pair_coeff.set_default_coeff('alpha', 0.0);\n\n def process_coeff(self, coeff):\n kappa = coeff['kappa'];\n alpha = coeff['alpha'];\n\n return _hoomd.make_scalar2(kappa, alpha)\n\n def set_params(self, coeff):\n \"\"\" :py:class:`ewald` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\ndef _table_eval(r, rmin, rmax, V, F, width):\n dr = (rmax - rmin) / float(width-1);\n i = int(round((r - rmin)/dr))\n return (V[i], F[i])\n\nclass table(force._force):\n R\"\"\" Tabulated pair potential.\n\n Args:\n width (int): Number of points to use to interpolate V and F.\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list (default of None automatically creates a global cell-list based neighbor list)\n name (str): Name of the force instance\n\n :py:class:`table` specifies that a tabulated pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n The force :math:`\\vec{F}` is (in force units):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n \\vec{F}(\\vec{r}) = & 0 & r < r_{\\mathrm{min}} \\\\\n = & F_{\\mathrm{user}}(r)\\hat{r} & r_{\\mathrm{min}} \\le r < r_{\\mathrm{max}} \\\\\n = & 0 & r \\ge r_{\\mathrm{max}} \\\\\n \\end{eqnarray*}\n\n and the potential :math:`V(r)` is (in energy units)\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & 0 & r < r_{\\mathrm{min}} \\\\\n = & V_{\\mathrm{user}}(r) & r_{\\mathrm{min}} \\le r < r_{\\mathrm{max}} \\\\\n = & 0 & r \\ge r_{\\mathrm{max}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\vec{r}` is the vector pointing from one particle to the other in the pair.\n\n :math:`F_{\\mathrm{user}}(r)` and :math:`V_{\\mathrm{user}}(r)` are evaluated on *width* grid points between\n :math:`r_{\\mathrm{min}}` and :math:`r_{\\mathrm{max}}`. Values are interpolated linearly between grid points.\n For correctness, you must specify the force defined by: :math:`F = -\\frac{\\partial V}{\\partial r}`.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`V_{\\mathrm{user}}(r)` and :math:`F_{\\mathrm{user}}(r)` - evaluated by ``func`` (see example)\n - coefficients passed to ``func`` - *coeff* (see example)\n - :math:`_{\\mathrm{min}}` - *rmin* (in distance units)\n - :math:`_{\\mathrm{max}}` - *rmax* (in distance units)\n\n .. rubric:: Set table from a given function\n\n When you have a functional form for V and F, you can enter that\n directly into python. :py:class:`table` will evaluate the given function over *width* points between\n *rmin* and *rmax* and use the resulting values in the table::\n\n def lj(r, rmin, rmax, epsilon, sigma):\n V = 4 * epsilon * ( (sigma / r)**12 - (sigma / r)**6);\n F = 4 * epsilon / r * ( 12 * (sigma / r)**12 - 6 * (sigma / r)**6);\n return (V, F)\n\n nl = nlist.cell()\n table = pair.table(width=1000, nlist=nl)\n table.pair_coeff.set('A', 'A', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=1.5, sigma=1.0))\n table.pair_coeff.set('A', 'B', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=2.0, sigma=1.2))\n table.pair_coeff.set('B', 'B', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=0.5, sigma=1.0))\n\n .. rubric:: Set a table from a file\n\n When you have no function for for *V* or *F*, or you otherwise have the data listed in a file,\n :py:class:`table` can use the given values directly. You must first specify the number of rows\n in your tables when initializing pair.table. Then use :py:meth:`set_from_file()` to read the file::\n\n nl = nlist.cell()\n table = pair.table(width=1000, nlist=nl)\n table.set_from_file('A', 'A', filename='table_AA.dat')\n table.set_from_file('A', 'B', filename='table_AB.dat')\n table.set_from_file('B', 'B', filename='table_BB.dat')\n\n Note:\n For potentials that diverge near r=0, make sure to set *rmin* to a reasonable value. If a potential does\n not diverge near r=0, then a setting of *rmin=0* is valid.\n\n \"\"\"\n def __init__(self, width, nlist, name=None):\n hoomd.util.print_status_line();\n\n # initialize the base class\n force._force.__init__(self, name);\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.TablePotential(hoomd.context.current.system_definition, self.nlist.cpp_nlist, int(width), self.name);\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.TablePotentialGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, int(width), self.name);\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # stash the width for later use\n self.width = width;\n\n def update_pair_table(self, typei, typej, func, rmin, rmax, coeff):\n # allocate arrays to store V and F\n Vtable = _hoomd.std_vector_scalar();\n Ftable = _hoomd.std_vector_scalar();\n\n # calculate dr\n dr = (rmax - rmin) / float(self.width-1);\n\n # evaluate each point of the function\n for i in range(0, self.width):\n r = rmin + dr * i;\n (V,F) = func(r, rmin, rmax, **coeff);\n\n # fill out the tables\n Vtable.append(V);\n Ftable.append(F);\n\n # pass the tables on to the underlying cpp compute\n self.cpp_force.setTable(typei, typej, Vtable, Ftable, rmin, rmax);\n\n ## \\internal\n # \\brief Get the r_cut pair dictionary\n # \\returns rcut(i,j) dict if logging is on, and None otherwise\n def get_rcut(self):\n if not self.log:\n return None\n\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # update the rcut by pair type\n r_cut_dict = nl.rcut();\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n rmax = self.pair_coeff.get(type_list[i], type_list[j], 'rmax');\n r_cut_dict.set_pair(type_list[i],type_list[j], rmax);\n\n return r_cut_dict;\n\n def get_max_rcut(self):\n # loop only over current particle types\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # find the maximum rmax to update the neighbor list with\n maxrmax = 0.0;\n\n # loop through all of the unique type pairs and find the maximum rmax\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n rmax = self.pair_coeff.get(type_list[i], type_list[j], \"rmax\");\n maxrmax = max(maxrmax, rmax);\n\n return maxrmax;\n\n def update_coeffs(self):\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify([\"func\", \"rmin\", \"rmax\", \"coeff\"]):\n hoomd.context.msg.error(\"Not all pair coefficients are set for pair.table\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # loop through all of the unique type pairs and evaluate the table\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n func = self.pair_coeff.get(type_list[i], type_list[j], \"func\");\n rmin = self.pair_coeff.get(type_list[i], type_list[j], \"rmin\");\n rmax = self.pair_coeff.get(type_list[i], type_list[j], \"rmax\");\n coeff = self.pair_coeff.get(type_list[i], type_list[j], \"coeff\");\n\n self.update_pair_table(i, j, func, rmin, rmax, coeff);\n\n def set_from_file(self, a, b, filename):\n R\"\"\" Set a pair interaction from a file.\n\n Args:\n a (str): Name of type A in pair\n b (str): Name of type B in pair\n filename (str): Name of the file to read\n\n The provided file specifies V and F at equally spaced r values.\n\n Example::\n\n #r V F\n 1.0 2.0 -3.0\n 1.1 3.0 -4.0\n 1.2 2.0 -3.0\n 1.3 1.0 -2.0\n 1.4 0.0 -1.0\n 1.5 -1.0 0.0\n\n The first r value sets *rmin*, the last sets *rmax*. Any line with # as the first non-whitespace character is\n is treated as a comment. The *r* values must monotonically increase and be equally spaced. The table is read\n directly into the grid points used to evaluate :math:`F_{\\mathrm{user}}(r)` and :math:`_{\\mathrm{user}}(r)`.\n \"\"\"\n hoomd.util.print_status_line();\n\n # open the file\n f = open(filename);\n\n r_table = [];\n V_table = [];\n F_table = [];\n\n # read in lines from the file\n for line in f.readlines():\n line = line.strip();\n\n # skip comment lines\n if line[0] == '#':\n continue;\n\n # split out the columns\n cols = line.split();\n values = [float(f) for f in cols];\n\n # validate the input\n if len(values) != 3:\n hoomd.context.msg.error(\"pair.table: file must have exactly 3 columns\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n # append to the tables\n r_table.append(values[0]);\n V_table.append(values[1]);\n F_table.append(values[2]);\n\n # validate input\n if self.width != len(r_table):\n hoomd.context.msg.error(\"pair.table: file must have exactly \" + str(self.width) + \" rows\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n # extract rmin and rmax\n rmin_table = r_table[0];\n rmax_table = r_table[-1];\n\n # check for even spacing\n dr = (rmax_table - rmin_table) / float(self.width-1);\n for i in range(0,self.width):\n r = rmin_table + dr * i;\n if math.fabs(r - r_table[i]) > 1e-3:\n hoomd.context.msg.error(\"pair.table: r must be monotonically increasing and evenly spaced\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n hoomd.util.quiet_status();\n self.pair_coeff.set(a, b, func=_table_eval, rmin=rmin_table, rmax=rmax_table, coeff=dict(V=V_table, F=F_table, width=self.width))\n hoomd.util.unquiet_status();\n\nclass morse(pair):\n R\"\"\" Morse pair potential.\n\n :py:class:`morse` specifies that a Morse pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{morse}}(r) = & D_0 \\left[ \\exp \\left(-2\\alpha\\left(r-r_0\\right)\\right) -2\\exp \\left(-\\alpha\\left(r-r_0\\right)\\right) \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`D_0` - *D0*, depth of the potential at its minimum (in energy units)\n - :math:`\\alpha` - *alpha*, controls the width of the potential well (in units of 1/distance)\n - :math:`r_0` - *r0*, position of the minimum (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n morse = pair.morse(r_cut=3.0, nlist=nl)\n morse.pair_coeff.set('A', 'A', D0=1.0, alpha=3.0, r0=1.0)\n morse.pair_coeff.set('A', 'B', D0=1.0, alpha=3.0, r0=1.0, r_cut=3.0, r_on=2.0);\n morse.pair_coeff.set(['A', 'B'], ['C', 'D'], D0=1.0, alpha=3.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMorse(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMorse;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMorseGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMorseGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['D0', 'alpha', 'r0'];\n\n def process_coeff(self, coeff):\n D0 = coeff['D0'];\n alpha = coeff['alpha'];\n r0 = coeff['r0']\n\n return _hoomd.make_scalar4(D0, alpha, r0, 0.0);\n\nclass dpd(pair):\n R\"\"\" Dissipative Particle Dynamics.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n seed (int): seed for the PRNG in the DPD thermostat.\n name (str): Name of the force instance.\n\n :py:class:`dpd` specifies that a DPD pair force should be applied between every\n non-excluded particle pair in the simulation, including an interaction potential,\n pairwise drag force, and pairwise random force. See `Groot and Warren 1997 `_.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F = F_{\\mathrm{C}}(r) + F_{\\mathrm{R,ij}}(r_{ij}) + F_{\\mathrm{D,ij}}(v_{ij}) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F_{\\mathrm{C}}(r) = & A \\cdot w(r_{ij}) \\\\\n F_{\\mathrm{R, ij}}(r_{ij}) = & - \\theta_{ij}\\sqrt{3} \\sqrt{\\frac{2k_b\\gamma T}{\\Delta t}}\\cdot w(r_{ij}) \\\\\n F_{\\mathrm{D, ij}}(r_{ij}) = & - \\gamma w^2(r_{ij})\\left( \\hat r_{ij} \\circ v_{ij} \\right) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n w(r_{ij}) = &\\left( 1 - r/r_{\\mathrm{cut}} \\right) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\hat r_{ij}` is a normalized vector from particle i to particle j, :math:`v_{ij} = v_i - v_j`,\n and :math:`\\theta_{ij}` is a uniformly distributed random number in the range [-1, 1].\n\n :py:class:`dpd` generates random numbers by hashing together the particle tags in the pair, the user seed,\n and the current time step index.\n\n .. attention::\n\n Change the seed if you reset the simulation time step to 0. If you keep the same seed, the simulation\n will continue with the same sequence of random numbers used previously and may cause unphysical correlations.\n\n For MPI runs: all ranks other than 0 ignore the seed input and use the value of rank 0.\n\n `C. L. Phillips et. al. 2011 `_ describes the DPD implementation\n details in HOOMD-blue. Cite it if you utilize the DPD functionality in your work.\n\n :py:class:`dpd` does not implement and energy shift / smoothing modes due to the function of the force.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in force units)\n - :math:`\\gamma` - *gamma* (in units of force/velocity)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n To use the DPD thermostat, an :py:class:`hoomd.md.integrate.nve` integrator must be applied to the system and\n the user must specify a temperature. Use of the dpd thermostat pair force with other integrators will result\n in unphysical behavior. To use pair.dpd with a different conservative potential than :math:`F_C`,\n set A to zero and define the conservative pair potential separately. Note that DPD thermostats\n are often defined in terms of :math:`\\sigma` where :math:`\\sigma = \\sqrt{2k_b\\gamma T}`.\n\n Example::\n\n nl = nlist.cell()\n dpd = pair.dpd(r_cut=1.0, nlist=nl, kT=1.0, seed=0)\n dpd.pair_coeff.set('A', 'A', A=25.0, gamma = 4.5)\n dpd.pair_coeff.set('A', 'B', A=40.0, gamma = 4.5)\n dpd.pair_coeff.set('B', 'B', A=25.0, gamma = 4.5)\n dpd.pair_coeff.set(['A', 'B'], ['C', 'D'], A=12.0, gamma = 1.2)\n dpd.set_params(kT = 1.0)\n integrate.mode_standard(dt=0.02)\n integrate.nve(group=group.all())\n\n \"\"\"\n def __init__(self, r_cut, nlist, kT, seed, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPDThermoDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDThermoDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDThermoDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDThermoDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A', 'gamma'];\n\n # set the seed for dpd thermostat\n self.cpp_force.setSeed(seed);\n\n # set the temperature\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def set_params(self, kT=None):\n R\"\"\" Changes parameters.\n\n Args:\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n\n Example::\n\n dpd.set_params(kT=2.0)\n \"\"\"\n hoomd.util.print_status_line();\n self.check_initialization();\n\n # change the parameters\n if kT is not None:\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def process_coeff(self, coeff):\n a = coeff['A'];\n gamma = coeff['gamma'];\n return _hoomd.make_scalar2(a, gamma);\n\nclass dpd_conservative(pair):\n R\"\"\" DPD Conservative pair force.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`dpd_conservative` specifies the conservative part of the DPD pair potential should be applied between\n every non-excluded particle pair in the simulation. No thermostat (e.g. Drag Force and Random Force) is applied,\n as is in :py:class:`dpd`.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{DPD-C}}(r) = & A \\cdot \\left( r_{\\mathrm{cut}} - r \\right)\n - \\frac{1}{2} \\cdot \\frac{A}{r_{\\mathrm{cut}}} \\cdot \\left(r_{\\mathrm{cut}}^2 - r^2 \\right)\n & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n\n :py:class:`dpd_conservative` does not implement and energy shift / smoothing modes due to the function of the force.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in force units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n dpdc = pair.dpd_conservative(r_cut=3.0, nlist=nl)\n dpdc.pair_coeff.set('A', 'A', A=1.0)\n dpdc.pair_coeff.set('A', 'B', A=2.0, r_cut = 1.0)\n dpdc.pair_coeff.set('B', 'B', A=1.0)\n dpdc.pair_coeff.set(['A', 'B'], ['C', 'D'], A=5.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A'];\n\n\n def process_coeff(self, coeff):\n a = coeff['A'];\n gamma = 0;\n return _hoomd.make_scalar2(a, gamma);\n\n def set_params(self, coeff):\n \"\"\" :py:class:`dpd_conservative` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\nclass dpdlj(pair):\n R\"\"\" Dissipative Particle Dynamics with a LJ conservative force\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n seed (int): seed for the PRNG in the DPD thermostat.\n name (str): Name of the force instance.\n\n :py:class:`dpdlj` specifies that a DPD thermostat and a Lennard-Jones pair potential should be applied between\n every non-excluded particle pair in the simulation.\n\n `C. L. Phillips et. al. 2011 `_ describes the DPD implementation\n details in HOOMD-blue. Cite it if you utilize the DPD functionality in your work.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F = F_{\\mathrm{C}}(r) + F_{\\mathrm{R,ij}}(r_{ij}) + F_{\\mathrm{D,ij}}(v_{ij}) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F_{\\mathrm{C}}(r) = & \\partial V_{\\mathrm{LJ}} / \\partial r \\\\\n F_{\\mathrm{R, ij}}(r_{ij}) = & - \\theta_{ij}\\sqrt{3} \\sqrt{\\frac{2k_b\\gamma T}{\\Delta t}}\\cdot w(r_{ij}) \\\\\n F_{\\mathrm{D, ij}}(r_{ij}) = & - \\gamma w^2(r_{ij})\\left( \\hat r_{ij} \\circ v_{ij} \\right) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n w(r_{ij}) = &\\left( 1 - r/r_{\\mathrm{cut}} \\right) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\hat r_{ij}` is a normalized vector from particle i to particle j, :math:`v_{ij} = v_i - v_j`,\n and :math:`\\theta_{ij}` is a uniformly distributed random number in the range [-1, 1].\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless)\n - *optional*: defaults to 1.0\n - :math:`\\gamma` - *gamma* (in units of force/velocity)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n To use the DPD thermostat, an :py:class:`hoomd.md.integrate.nve` integrator must be applied to the system and\n the user must specify a temperature. Use of the dpd thermostat pair force with other integrators will result\n in unphysical behavior.\n\n Example::\n\n nl = nlist.cell()\n dpdlj = pair.dpdlj(r_cut=2.5, nlist=nl, kT=1.0, seed=0)\n dpdlj.pair_coeff.set('A', 'A', epsilon=1.0, sigma = 1.0, gamma = 4.5)\n dpdlj.pair_coeff.set('A', 'B', epsilon=0.0, sigma = 1.0 gamma = 4.5)\n dpdlj.pair_coeff.set('B', 'B', epsilon=1.0, sigma = 1.0 gamma = 4.5, r_cut = 2.0**(1.0/6.0))\n dpdlj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon = 3.0,sigma=1.0, gamma = 1.2)\n dpdlj.set_params(T = 1.0)\n integrate.mode_standard(dt=0.005)\n integrate.nve(group=group.all())\n\n \"\"\"\n\n def __init__(self, r_cut, nlist, kT, seed, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPDLJThermoDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDLJThermoDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDLJThermoDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDLJThermoDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon','sigma', 'alpha', 'gamma'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n\n # set the seed for dpdlj thermostat\n self.cpp_force.setSeed(seed);\n\n # set the temperature\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def set_params(self, kT=None, mode=None):\n R\"\"\" Changes parameters.\n\n Args:\n T (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature (if set) (in energy units)\n mode (str): energy shift/smoothing mode (default noshift).\n\n Examples::\n\n dpdlj.set_params(kT=variant.linear_interp(points = [(0, 1.0), (1e5, 2.0)]))\n dpdlj.set_params(kT=2.0, mode=\"shift\")\n\n \"\"\"\n hoomd.util.print_status_line();\n self.check_initialization();\n\n # change the parameters\n if kT is not None:\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n if mode is not None:\n if mode == \"xplor\":\n hoomd.context.msg.error(\"XPLOR is smoothing is not supported with pair.dpdlj\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n #use the inherited set_params\n pair.set_params(self, mode=mode)\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n gamma = coeff['gamma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar4(lj1, lj2, gamma, 0.0);\n\nclass force_shifted_lj(pair):\n R\"\"\" Force-shifted Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`force_shifted_lj` specifies that a modified Lennard-Jones pair force should be applied between\n non-excluded particle pair in the simulation. The force differs from the one calculated by :py:class:`lj`\n by the subtraction of the value of the force at :math:`r_{\\mathrm{cut}}`, such that the force smoothly goes\n to zero at the cut-off. The potential is modified by a linear function. This potential can be used as a substitute\n for :py:class:`lj`, when the exact analytical form of the latter is not required but a smaller cut-off radius is\n desired for computational efficiency. See `Toxvaerd et. al. 2011 `_\n for a discussion of this potential.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] + \\Delta V(r) & r < r_{\\mathrm{cut}}\\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n\n \\Delta V(r) = -(r - r_{\\mathrm{cut}}) \\frac{\\partial V_{\\mathrm{LJ}}}{\\partial r}(r_{\\mathrm{cut}})\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n fslj = pair.force_shifted_lj(r_cut=1.5, nlist=nl)\n fslj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairForceShiftedLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairForceShiftedLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairForceShiftedLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairForceShiftedLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass moliere(pair):\n R\"\"\" Moliere pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`moliere` specifies that a Moliere type pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Moliere}}(r) = & \\frac{Z_i Z_j e^2}{4 \\pi \\epsilon_0 r_{ij}} \\left[ 0.35 \\exp \\left( -0.3 \\frac{r_{ij}}{a_F} \\right) + 0.55 \\exp \\left( -1.2 \\frac{r_{ij}}{a_F} \\right) + 0.10 \\exp \\left( -6.0 \\frac{r_{ij}}{a_F} \\right) \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`Z_i` - *Z_i* - Atomic number of species i (unitless)\n - :math:`Z_j` - *Z_j* - Atomic number of species j (unitless)\n - :math:`e` - *elementary_charge* - The elementary charge (in charge units)\n - :math:`a_0` - *a_0* - The Bohr radius (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n moliere = pair.moliere(r_cut = 3.0, nlist=nl)\n moliere.pair_coeff.set('A', 'B', Z_i = 54.0, Z_j = 7.0, elementary_charge = 1.0, a_0 = 1.0);\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMoliere(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMoliere;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMoliereGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMoliereGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['Z_i', 'Z_j', 'elementary_charge', 'a_0'];\n self.pair_coeff.set_default_coeff('elementary_charge', 1.0);\n self.pair_coeff.set_default_coeff('a_0', 1.0);\n\n def process_coeff(self, coeff):\n Z_i = coeff['Z_i'];\n Z_j = coeff['Z_j'];\n elementary_charge = coeff['elementary_charge'];\n a_0 = coeff['a_0'];\n\n Zsq = Z_i * Z_j * elementary_charge * elementary_charge;\n if (not (Z_i == 0)) or (not (Z_j == 0)):\n aF = 0.8853 * a_0 / math.pow(math.sqrt(Z_i) + math.sqrt(Z_j), 2.0 / 3.0);\n else:\n aF = 1.0;\n return _hoomd.make_scalar2(Zsq, aF);\n\nclass zbl(pair):\n R\"\"\" ZBL pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`zbl` specifies that a Ziegler-Biersack-Littmark pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{ZBL}}(r) = & \\frac{Z_i Z_j e^2}{4 \\pi \\epsilon_0 r_{ij}} \\left[ 0.1818 \\exp \\left( -3.2 \\frac{r_{ij}}{a_F} \\right) + 0.5099 \\exp \\left( -0.9423 \\frac{r_{ij}}{a_F} \\right) + 0.2802 \\exp \\left( -0.4029 \\frac{r_{ij}}{a_F} \\right) + 0.02817 \\exp \\left( -0.2016 \\frac{r_{ij}}{a_F} \\right) \\right], & r < r_{\\mathrm{cut}} \\\\\n = & 0, & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`Z_i` - *Z_i* - Atomic number of species i (unitless)\n - :math:`Z_j` - *Z_j* - Atomic number of species j (unitless)\n - :math:`e` - *elementary_charge* - The elementary charge (in charge units)\n - :math:`a_0` - *a_0* - The Bohr radius (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n zbl = pair.zbl(r_cut = 3.0, nlist=nl)\n zbl.pair_coeff.set('A', 'B', Z_i = 54.0, Z_j = 7.0, elementary_charge = 1.0, a_0 = 1.0);\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairZBL(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairZBL;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairZBLGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairZBLGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['Z_i', 'Z_j', 'elementary_charge', 'a_0'];\n self.pair_coeff.set_default_coeff('elementary_charge', 1.0);\n self.pair_coeff.set_default_coeff('a_0', 1.0);\n\n def process_coeff(self, coeff):\n Z_i = coeff['Z_i'];\n Z_j = coeff['Z_j'];\n elementary_charge = coeff['elementary_charge'];\n a_0 = coeff['a_0'];\n\n Zsq = Z_i * Z_j * elementary_charge * elementary_charge;\n if (not (Z_i == 0)) or (not (Z_j == 0)):\n aF = 0.88534 * a_0 / ( math.pow( Z_i, 0.23 ) + math.pow( Z_j, 0.23 ) );\n else:\n aF = 1.0;\n return _hoomd.make_scalar2(Zsq, aF);\n\n def set_params(self, coeff):\n \"\"\" :py:class:`zbl` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\nclass tersoff(pair):\n R\"\"\" Tersoff Potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`tersoff` specifies that the Tersoff three-body potential should be applied to every\n non-bonded particle pair in the simulation. Despite the fact that the Tersoff potential accounts\n for the effects of third bodies, it is included in the pair potentials because the species of the\n third body is irrelevant. It can thus use type-pair parameters similar to those of the pair potentials.\n\n The Tersoff potential is a bond-order potential based on the Morse potential that accounts for the weakening of\n individual bonds with increasing coordination number. It does this by computing a modifier to the\n attractive term of the potential. The modifier contains the effects of third-bodies on the bond\n energies. The potential also includes a smoothing function around the cutoff. The smoothing function\n used in this work is exponential in nature as opposed to the sinusoid used by Tersoff. The exponential\n function provides continuity up (I believe) the second derivative.\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialTersoff(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialTersoff;\n else:\n self.cpp_force = _md.PotentialTersoffGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialTersoffGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['cutoff_thickness', 'C1', 'C2', 'lambda1', 'lambda2', 'dimer_r', 'n', 'gamma', 'lambda3', 'c', 'd', 'm', 'alpha']\n self.pair_coeff.set_default_coeff('cutoff_thickness', 0.2);\n self.pair_coeff.set_default_coeff('dimer_r', 1.5);\n self.pair_coeff.set_default_coeff('C1', 1.0);\n self.pair_coeff.set_default_coeff('C2', 1.0);\n self.pair_coeff.set_default_coeff('lambda1', 2.0);\n self.pair_coeff.set_default_coeff('lambda2', 1.0);\n self.pair_coeff.set_default_coeff('lambda3', 0.0);\n self.pair_coeff.set_default_coeff('n', 0.0);\n self.pair_coeff.set_default_coeff('m', 0.0);\n self.pair_coeff.set_default_coeff('c', 0.0);\n self.pair_coeff.set_default_coeff('d', 1.0);\n self.pair_coeff.set_default_coeff('gamma', 0.0);\n self.pair_coeff.set_default_coeff('alpha', 3.0);\n\n def process_coeff(self, coeff):\n cutoff_d = coeff['cutoff_thickness'];\n C1 = coeff['C1'];\n C2 = coeff['C2'];\n lambda1 = coeff['lambda1'];\n lambda2 = coeff['lambda2'];\n dimer_r = coeff['dimer_r'];\n n = coeff['n'];\n gamma = coeff['gamma'];\n lambda3 = coeff['lambda3'];\n c = coeff['c'];\n d = coeff['d'];\n m = coeff['m'];\n alpha = coeff['alpha'];\n\n gamman = math.pow(gamma, n);\n c2 = c * c;\n d2 = d * d;\n lambda3_cube = lambda3 * lambda3 * lambda3;\n\n tersoff_coeffs = _hoomd.make_scalar2(C1, C2);\n exp_consts = _hoomd.make_scalar2(lambda1, lambda2);\n ang_consts = _hoomd.make_scalar3(c2, d2, m);\n\n return _md.make_tersoff_params(cutoff_d, tersoff_coeffs, exp_consts, dimer_r, n, gamman, lambda3_cube, ang_consts, alpha);\n\n\nclass revcross(pair):\n R\"\"\" Reversible crosslinker three-body potential to model bond swaps.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`revcross` specifies that the revcross three-body potential should be applied to every\n non-bonded particle pair in the simulation. Despite the fact that the revcross potential accounts\n for the effects of third bodies, it is included in the pair potentials because its is actually just a\n combination of two body potential terms. It can thus use type-pair parameters similar to those of the pair potentials.\n\n The revcross potential has been described in detail in `S. Ciarella and W.G. Ellenbroek 2019 `_. It is based on a generalized-Lennard-Jones pairwise\n attraction to form bonds between interacting particless:\n\n .. math::\n :nowrap:\n\n \\begin{equation}\n V_{ij}(r) = 4 \\varepsilon \\left[ \\left( \\dfrac{ \\sigma}{r_{ij}} \\right) ^{2n}- \\left( \\dfrac{ \\sigma}{r_{ij}} \\right)^{n} \\right] \\qquad r r_{min}~.\\\\\n \\end{cases}\n \\end{equation}\n\n .. attention::\n\n The revcross potential models an asymmetric interaction between two different chemical moieties that can form a reversible bond. \n\tThis requires the definition of (at least) two different types of particles.\n\tA reversible bond is only possible between two different species, otherwise :math:` v^{\\left( 3b \\right)}_{ijk}` would prevent any bond.\n\tIn our example we then set the interactions for types A and B with ``potRevC.pair_coeff.set(['A','B'],['A','B'],sigma=0.0,n=0,epsilon=0,lambda3=0)`` and the only non-zero energy only between the different types ``potRevC.pair_coeff.set('A','B',sigma=1,n=100,epsilon=100,lambda3=1) ``. \n\tNotice that the number of the minoritary species corresponds to the maximum number of bonds.\n \n\n This three-body term also tunes the energy required for a bond swap through the coefficient: \n - :math:`\\lambda` - *lambda3* (unitless)\n in `S. Ciarella and W.G. Ellenbroek 2019 `_ is explained that setting :math:`\\lambda=1` corresponds to no energy requirement to initiate bond swap, while this\n energy barrier scales roughly as :math:`\\beta \\Delta E_\\text{sw} =\\beta \\varepsilon(\\lambda-1)`.\n\n Note:\n\n Choosing :math:`\\lambda=1` pushes the system towards clusterization because the three-body term is not enough to\n compensate the energy of multiple bonds, so it may cause unphysical situations. \n \n\n Example::\n\n nl = md.nlist.cell()\n potBondSwap = md.pair.revcross(r_cut=1.3,nlist=nl)\n potBondSwap.pair_coeff.set(['A','B'],['A','B'],sigma=0,n=0,epsilon=0,lambda3=0)\n\t# a bond can be made only between A-B and not A-A or B-B\n potBondSwap.pair_coeff.set('A','B',sigma=1,n=100,epsilon=10,lambda3=1)\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialRevCross(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialRevCross;\n else:\n self.cpp_force = _md.PotentialRevCrossGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialRevCrossGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['sigma', 'n', 'epsilon', 'lambda3']\n self.pair_coeff.set_default_coeff('sigma', 2.);\n self.pair_coeff.set_default_coeff('n', 1.0);\n self.pair_coeff.set_default_coeff('epsilon', 1.0);\n self.pair_coeff.set_default_coeff('lambda3', 1.0);\n\n def process_coeff(self, coeff):\n sigma = coeff['sigma'];\n n = coeff['n'];\n epsilon = coeff['epsilon'];\n lambda3 = coeff['lambda3'];\n\n return _md.make_revcross_params(sigma, n, epsilon, lambda3);\n\n\n\nclass mie(pair):\n R\"\"\" Mie pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`mie` specifies that a Mie pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{mie}}(r) = & \\left( \\frac{n}{n-m} \\right) {\\left( \\frac{n}{m} \\right)}^{\\frac{m}{n-m}} \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{n} -\n \\left( \\frac{\\sigma}{r} \\right)^{m} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`n` - *n* (unitless)\n - :math:`m` - *m* (unitless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n mie = pair.mie(r_cut=3.0, nlist=nl)\n mie.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0, n=12, m=6)\n mie.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, n=14, m=7, r_cut=3.0, r_on=2.0);\n mie.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, n=15.1, m=6.5, r_cut=2**(1.0/6.0), r_on=2.0);\n mie.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMie(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMie;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMieGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMieGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'n', 'm'];\n\n def process_coeff(self, coeff):\n epsilon = float(coeff['epsilon']);\n sigma = float(coeff['sigma']);\n n = float(coeff['n']);\n m = float(coeff['m']);\n\n mie1 = epsilon * math.pow(sigma, n) * (n/(n-m)) * math.pow(n/m,m/(n-m));\n mie2 = epsilon * math.pow(sigma, m) * (n/(n-m)) * math.pow(n/m,m/(n-m));\n mie3 = n\n mie4 = m\n return _hoomd.make_scalar4(mie1, mie2, mie3, mie4);\n\n\nclass _shape_dict(dict):\n \"\"\"Simple dictionary subclass to improve handling of anisotropic potential\n shape information.\"\"\"\n def __getitem__(self, key):\n try:\n return super(_shape_dict, self).__getitem__(key)\n except KeyError as e:\n raise KeyError(\"No shape parameters specified for particle type {}!\".format(key)) from e\n\n\nclass ai_pair(pair):\n R\"\"\"Generic anisotropic pair potential.\n\n Users should not instantiate :py:class:`ai_pair` directly. It is a base class that\n provides common features to all anisotropic pair forces. Rather than repeating all of that documentation in a\n dozen different places, it is collected here.\n\n All anisotropic pair potential commands specify that a given potential energy, force and torque be computed\n on all non-excluded particle pairs in the system within a short range cutoff distance :math:`r_{\\mathrm{cut}}`.\n The interaction energy, forces and torque depend on the inter-particle separation\n :math:`\\vec r` and on the orientations :math:`\\vec q_i`, :math:`q_j`, of the particles.\n \"\"\"\n\n ## \\internal\n # \\brief Initialize the pair force\n # \\details\n # The derived class must set\n # - self.cpp_class (the pair class to instantiate)\n # - self.required_coeffs (a list of the coeff names the derived class needs)\n # - self.process_coeffs() (a method that takes in the coeffs and spits out a param struct to use in\n # self.cpp_force.set_params())\n def __init__(self, r_cut, nlist, name=None):\n # initialize the base class\n force._force.__init__(self, name);\n\n self.global_r_cut = r_cut;\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n self.pair_coeff.set_default_coeff('r_cut', self.global_r_cut);\n\n # setup the neighbor list\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n self._shape = _shape_dict()\n\n def set_params(self, mode=None):\n R\"\"\"Set parameters controlling the way forces are computed.\n\n Args:\n mode (str): (if set) Set the mode with which potentials are handled at the cutoff\n\n valid values for mode are: \"none\" (the default) and \"shift\":\n\n - *none* - No shifting is performed and potentials are abruptly cut off\n - *shift* - A constant shift is applied to the entire potential so that it is 0 at the cutoff\n\n Examples::\n\n mypair.set_params(mode=\"shift\")\n mypair.set_params(mode=\"no_shift\")\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode is not None:\n if mode == \"no_shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.no_shift)\n elif mode == \"shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.shift)\n else:\n hoomd.context.msg.error(\"Invalid mode\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n @property\n def shape(self):\n R\"\"\"Get or set shape parameters per type.\n\n In addition to any pair-specific parameters required to characterize a\n pair potential, individual particles that have anisotropic interactions\n may also have their own shapes that affect the potentials. General\n anisotropic pair potentials may set per-particle shapes using this\n method.\n \"\"\"\n return self._shape\n\n def update_coeffs(self):\n coeff_list = self.required_coeffs + [\"r_cut\"];\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify(coeff_list):\n hoomd.context.msg.error(\"Not all pair coefficients are set\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n for i in range(0,ntypes):\n self._set_cpp_shape(i, type_list[i])\n\n for j in range(i,ntypes):\n # build a dict of the coeffs to pass to process_coeff\n coeff_dict = {}\n for name in coeff_list:\n coeff_dict[name] = self.pair_coeff.get(type_list[i], type_list[j], name);\n\n param = self.process_coeff(coeff_dict);\n self.cpp_force.setParams(i, j, param);\n self.cpp_force.setRcut(i, j, coeff_dict['r_cut']);\n\n def _set_cpp_shape(self, type_id, type_name):\n \"\"\"Update shape information in C++.\n\n This method must be implemented by subclasses to generate the\n appropriate shape structure. The default behavior is to do nothing.\"\"\"\n pass\n\nclass gb(ai_pair):\n R\"\"\" Gay-Berne anisotropic pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`gb` computes the Gay-Berne potential between anisotropic particles.\n\n This version of the Gay-Berne potential supports identical pairs of uniaxial ellipsoids,\n with orientation-independent energy-well depth.\n\n The interaction energy for this anisotropic pair potential is\n (`Allen et. al. 2006 `_):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{GB}}(\\vec r, \\vec e_i, \\vec e_j) = & 4 \\varepsilon \\left[ \\zeta^{-12} -\n \\zeta^{-6} \\right] & \\zeta < \\zeta_{\\mathrm{cut}} \\\\\n = & 0 & \\zeta \\ge \\zeta_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n\n \\zeta = \\left(\\frac{r-\\sigma+\\sigma_{\\mathrm{min}}}{\\sigma_{\\mathrm{min}}}\\right)\n\n \\sigma^{-2} = \\frac{1}{2} \\hat{\\vec{r}}\\cdot\\vec{H^{-1}}\\cdot\\hat{\\vec{r}}\n\n \\vec{H} = 2 \\ell_\\perp^2 \\vec{1} + (\\ell_\\parallel^2 - \\ell_\\perp^2) (\\vec{e_i} \\otimes \\vec{e_i} + \\vec{e_j} \\otimes \\vec{e_j})\n\n with :math:`\\sigma_{\\mathrm{min}} = 2 \\min(\\ell_\\perp, \\ell_\\parallel)`.\n\n The cut-off parameter :math:`r_{\\mathrm{cut}}` is defined for two particles oriented parallel along\n the **long** axis, i.e.\n :math:`\\zeta_{\\mathrm{cut}} = \\left(\\frac{r-\\sigma_{\\mathrm{max}} + \\sigma_{\\mathrm{min}}}{\\sigma_{\\mathrm{min}}}\\right)`\n where :math:`\\sigma_{\\mathrm{max}} = 2 \\max(\\ell_\\perp, \\ell_\\parallel)` .\n\n The quantities :math:`\\ell_\\parallel` and :math:`\\ell_\\perp` denote the semi-axis lengths parallel\n and perpendicular to particle orientation.\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\ell_\\perp` - *lperp* (in distance units)\n - :math:`\\ell_\\parallel` - *lpar* (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n gb = pair.gb(r_cut=2.5, nlist=nl)\n gb.pair_coeff.set('A', 'A', epsilon=1.0, lperp=0.45, lpar=0.5)\n gb.pair_coeff.set('A', 'B', epsilon=2.0, lperp=0.45, lpar=0.5, r_cut=2**(1.0/6.0));\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n ai_pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.AnisoPotentialPairGB(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairGB;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.AnisoPotentialPairGBGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairGBGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'lperp', 'lpar'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n lperp = coeff['lperp'];\n lpar = coeff['lpar'];\n\n return _md.make_pair_gb_params(epsilon, lperp, lpar);\n\n def get_type_shapes(self):\n \"\"\"Get all the types of shapes in the current simulation.\n\n Example:\n\n >>> my_gb.get_type_shapes()\n [{'type': 'Ellipsoid', 'a': 1.0, 'b': 1.0, 'c': 1.5}]\n\n Returns:\n A list of dictionaries, one for each particle type in the system.\n \"\"\"\n return super(ai_pair, self)._return_type_shapes();\n\nclass dipole(ai_pair):\n R\"\"\" Screened dipole-dipole interactions.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`dipole` computes the (screened) interaction between pairs of\n particles with dipoles and electrostatic charges. The total energy\n computed is:\n\n .. math::\n\n U_{dipole} = U_{dd} + U_{de} + U_{ee}\n\n U_{dd} = A e^{-\\kappa r} \\left(\\frac{\\vec{\\mu_i}\\cdot\\vec{\\mu_j}}{r^3} - 3\\frac{(\\vec{\\mu_i}\\cdot \\vec{r_{ji}})(\\vec{\\mu_j}\\cdot \\vec{r_{ji}})}{r^5}\\right)\n\n U_{de} = A e^{-\\kappa r} \\left(\\frac{(\\vec{\\mu_j}\\cdot \\vec{r_{ji}})q_i}{r^3} - \\frac{(\\vec{\\mu_i}\\cdot \\vec{r_{ji}})q_j}{r^3}\\right)\n\n U_{ee} = A e^{-\\kappa r} \\frac{q_i q_j}{r}\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n :py:class:`dipole` does not implement and energy shift / smoothing modes due to the function of the force.\n\n The following coefficients must be set per unique pair of particle types:\n\n - mu - magnitude of :math:`\\vec{\\mu} = \\mu (1, 0, 0)` in the particle local reference frame\n - A - electrostatic energy scale :math:`A` (default value 1.0)\n - kappa - inverse screening length :math:`\\kappa`\n\n Example::\n\n # A/A interact only with screened electrostatics\n dipole.pair_coeff.set('A', 'A', mu=0.0, A=1.0, kappa=1.0)\n dipole.pair_coeff.set('A', 'B', mu=0.5, kappa=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n ## tell the base class how we operate\n\n # initialize the base class\n ai_pair.__init__(self, r_cut, nlist, name);\n\n ## create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.AnisoPotentialPairDipole(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairDipole;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.AnisoPotentialPairDipoleGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairDipoleGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n ## setup the coefficient options\n self.required_coeffs = ['mu', 'A', 'kappa'];\n\n self.pair_coeff.set_default_coeff('A', 1.0)\n\n def process_coeff(self, coeff):\n mu = float(coeff['mu']);\n A = float(coeff['A']);\n kappa = float(coeff['kappa']);\n\n return _md.make_pair_dipole_params(mu, A, kappa);\n\n def set_params(self, *args, **kwargs):\n \"\"\" :py:class:`dipole` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for dipole');\n return;\n\n\nclass reaction_field(pair):\n R\"\"\" Onsager reaction field pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`reaction_field` specifies that an Onsager reaction field pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n Reaction field electrostatics is an approximation to the screened electrostatic interaction,\n which assumes that the medium can be treated as an electrostatic continuum of dielectric\n constant :math:`\\epsilon_{RF}` outside the cutoff sphere of radius :math:`r_{\\mathrm{cut}}`.\n See: `Barker et. al. 1973 `_.\n\n .. math::\n\n V_{\\mathrm{RF}}(r) = \\varepsilon \\left[ \\frac{1}{r} +\n \\frac{(\\epsilon_{RF}-1) r^2}{(2 \\epsilon_{RF} + 1) r_c^3} \\right]\n\n By default, the reaction field potential does not require charge or diameter to be set. Two parameters,\n :math:`\\varepsilon` and :math:`\\epsilon_{RF}` are needed. If :math:`epsilon_{RF}` is specified as zero,\n it will represent infinity.\n\n If *use_charge* is set to True, the following formula is evaluated instead:\n .. math::\n\n V_{\\mathrm{RF}}(r) = q_i q_j \\varepsilon \\left[ \\frac{1}{r} +\n \\frac{(\\epsilon_{RF}-1) r^2}{(2 \\epsilon_{RF} + 1) r_c^3} \\right]\n\n where :math:`q_i` and :math:`q_j` are the charges of the particle pair.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in units of energy*distance)\n - :math:`\\epsilon_{RF}` - *eps_rf* (dimensionless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - *use_charge* (boolean), evaluate potential using particle charges\n - *optional*: defaults to False\n\n .. versionadded:: 2.1\n\n\n Example::\n\n nl = nlist.cell()\n reaction_field = pair.reaction_field(r_cut=3.0, nlist=nl)\n reaction_field.pair_coeff.set('A', 'A', epsilon=1.0, eps_rf=1.0)\n reaction_field.pair_coeff.set('A', 'B', epsilon=-1.0, eps_rf=0.0)\n reaction_field.pair_coeff.set('B', 'B', epsilon=1.0, eps_rf=0.0)\n reaction_field.pair_coeff.set(system.particles.types, system.particles.types, epsilon=1.0, eps_rf=0.0, use_charge=True)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairReactionField(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairReactionField;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairReactionFieldGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairReactionFieldGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'eps_rf', 'use_charge'];\n self.pair_coeff.set_default_coeff('use_charge', False)\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n eps_rf = coeff['eps_rf'];\n use_charge = coeff['use_charge']\n\n return _hoomd.make_scalar3(epsilon, eps_rf, _hoomd.int_as_scalar(int(use_charge)));\n\nclass DLVO(pair):\n R\"\"\" DLVO colloidal interaction\n\n :py:class:`DLVO` specifies that a DLVO dispersion and electrostatic interaction should be\n applied between every non-excluded particle pair in the simulation.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n d_max (float): Maximum diameter particles in the simulation will have (in distance units)\n\n :py:class:`DLVO` evaluates the forces for the pair potential\n .. math::\n\n V_{\\mathrm{DLVO}}(r) = & - \\frac{A}{6} \\left[\n \\frac{2a_1a_2}{r^2 - (a_1+a_2)^2} + \\frac{2a_1a_2}{r^2 - (a_1-a_2)^2}\n + \\log \\left( \\frac{r^2 - (a_1+a_2)^2}{r^2 - (a_1+a_2)^2} \\right) \\right]\n + \\frac{a_1 a_2}{a_1+a_2} Z e^{-\\kappa(r - (a_1+a_2))} & r < (r_{\\mathrm{cut}} + \\Delta)\n = & 0 & r \\ge (r_{\\mathrm{cut}} + \\Delta)\n\n where math:`a_i` is the radius of particle :math:`i`, :math:`\\Delta = (d_i + d_j)/2` and\n :math:`d_i` is the diameter of particle :math:`i`.\n\n The first term corresponds to the attractive van der Waals interaction with A being the Hamaker constant,\n the second term to the repulsive double-layer interaction between two spherical surfaces with Z proportional\n to the surface electric potential.\n\n See Israelachvili 2011, pp. 317.\n\n The DLVO potential does not need charge, but does need diameter. See :py:class:`slj` for an explanation\n on how diameters are handled in the neighbor lists.\n\n Due to the way that DLVO modifies the cutoff condition, it will not function properly with the\n xplor shifting mode. See :py:class:`pair` for details on how forces are calculated and the available energy\n shifting and smoothing modes.\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in units of energy*distance)\n - :math:`\\kappa` - *kappa* (in units of 1/distance)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n\n Example::\n\n nl = nlist.cell()\n DLVO.pair_coeff.set('A', 'A', epsilon=1.0, kappa=1.0)\n DLVO.pair_coeff.set('A', 'B', epsilon=2.0, kappa=0.5, r_cut=3.0, r_on=2.0);\n DLVO.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=0.5, kappa=3.0)\n \"\"\"\n def __init__(self, r_cut, nlist, d_max=None, name=None):\n hoomd.util.print_status_line();\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # update the neighbor list\n if d_max is None :\n sysdef = hoomd.context.current.system_definition;\n d_max = sysdef.getParticleData().getMaxDiameter()\n hoomd.context.msg.notice(2, \"Notice: DLVO set d_max=\" + str(d_max) + \"\\n\");\n\n # SLJ requires diameter shifting to be on\n self.nlist.cpp_nlist.setDiameterShift(True);\n self.nlist.cpp_nlist.setMaximumDiameter(d_max);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDLVO(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDLVO;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDLVOGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDLVOGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['kappa', 'Z', 'A'];\n\n def process_coeff(self, coeff):\n Z = coeff['Z'];\n kappa = coeff['kappa'];\n A = coeff['A'];\n\n return _hoomd.make_scalar3(kappa, Z, A);\n\nclass square_density(pair):\n R\"\"\" Soft potential for simulating a van-der-Waals liquid\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`square_density` specifies that the three-body potential should be applied to every\n non-bonded particle pair in the simulation, that is harmonic in the local density.\n\n The self energy per particle takes the form\n\n .. math:: \\Psi^{ex} = B (\\rho - A)^2\n\n which gives a pair-wise additive, three-body force\n\n .. math:: \\vec{f}_{ij} = \\left( B (n_i - A) + B (n_j - A) \\right) w'_{ij} \\vec{e}_{ij}\n\n Here, :math:`w_{ij}` is a quadratic, normalized weighting function,\n\n .. math:: w(x) = \\frac{15}{2 \\pi r_{c,\\mathrm{weight}}^3} (1-r/r_{c,\\mathrm{weight}})^2\n\n The local density at the location of particle *i* is defined as\n\n .. math:: n_i = \\sum\\limits_{j\\neq i} w_{ij}\\left(\\big| \\vec r_i - \\vec r_j \\big|\\right)\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in units of volume^-1) - mean density (*default*: 0)\n - :math:`B` - *B* (in units of energy*volume^2) - coefficient of the harmonic density term\n\n Example::\n\n nl = nlist.cell()\n sqd = pair.van_der_waals(r_cut=3.0, nlist=nl)\n sqd.pair_coeff.set('A', 'A', A=0.1)\n sqd.pair_coeff.set('A', 'A', B=1.0)\n\n For further details regarding this multibody potential, see\n\n Warning:\n Currently HOOMD does not support reverse force communication between MPI domains on the GPU.\n Since reverse force communication is required for the calculation of multi-body potentials, attempting to use the\n square_density potential on the GPU with MPI will result in an error.\n\n [1] P. B. Warren, \"Vapor-liquid coexistence in many-body dissipative particle dynamics\"\n Phys. Rev. E. Stat. Nonlin. Soft Matter Phys., vol. 68, no. 6 Pt 2, p. 066702, 2003.\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialSquareDensity(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialSquareDensity;\n else:\n self.cpp_force = _md.PotentialSquareDensityGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialSquareDensityGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['A','B']\n self.pair_coeff.set_default_coeff('A', 0.0)\n\n def process_coeff(self, coeff):\n return _hoomd.make_scalar2(coeff['A'],coeff['B'])\n\n\nclass buckingham(pair):\n R\"\"\" Buckingham pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`buckingham` specifies that a Buckingham pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Buckingham}}(r) = & A \\exp\\left(-\\frac{r}{\\rho}\\right) -\n \\frac{C}{r^6} & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in energy units)\n - :math:`\\rho` - *rho* (in distance units)\n - :math:`C` - *C* (in energy * distance**6 units )\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n .. versionchanged:: 2.2\n\n Example::\n\n nl = nlist.cell()\n buck = pair.buckingham(r_cut=3.0, nlist=nl)\n buck.pair_coeff.set('A', 'A', A=1.0, rho=1.0, C=1.0)\n buck.pair_coeff.set('A', 'B', A=2.0, rho=1.0, C=1.0, r_cut=3.0, r_on=2.0);\n buck.pair_coeff.set('B', 'B', A=1.0, rho=1.0, C=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n buck.pair_coeff.set(['A', 'B'], ['C', 'D'], A=1.5, rho=2.0, C=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairBuckingham(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairBuckingham;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairBuckinghamGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairBuckinghamGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A', 'rho', 'C'];\n\n def process_coeff(self, coeff):\n A = coeff['A'];\n rho = coeff['rho'];\n C = coeff['C'];\n\n return _hoomd.make_scalar4(A, rho, C, 0.0);\n\n\nclass lj1208(pair):\n R\"\"\" Lennard-Jones 12-8 pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`lj1208` specifies that a Lennard-Jones pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{8} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n .. versionchanged:: 2.2\n\n Example::\n\n nl = nlist.cell()\n lj1208 = pair.lj1208(r_cut=3.0, nlist=nl)\n lj1208.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n lj1208.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, alpha=0.5, r_cut=3.0, r_on=2.0);\n lj1208.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n lj1208.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairLJ1208(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ1208;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairLJ1208GPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ1208GPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 8.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass fourier(pair):\n R\"\"\" Fourier pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`fourier` specifies that a fourier series form potential.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Fourier}}(r) = & \\frac{1}{r^{12}} + \\frac{1}{r^2}\\sum_{n=1}^4 [a_n cos(\\frac{n \\pi r}{r_{cut}}) + b_n sin(\\frac{n \\pi r}{r_{cut}})] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where:\n \\begin{eqnarray*}\n a_1 = \\sum_{n=2}^4 (-1)^n a_n cos(\\frac{n \\pi r}{r_{cut}})\n \\end{eqnarray*}\n\n \\begin{eqnarray*}\n b_1 = \\sum_{n=2}^4 n (-1)^n b_n cos(\\frac{n \\pi r}{r_{cut}})\n \\end{eqnarray*}\n\n is calculated to enforce close to zero value at r_cut.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`a` - *a* (array of 3 values corresponding to a2, a3 and a4 in the Fourier series, unitless)\n - :math:`a` - *b* (array of 3 values corresponding to b2, b3 and b4 in the Fourier series, unitless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n fourier = pair.fourier(r_cut=3.0, nlist=nl)\n fourier.pair_coeff.set('A', 'A', a=[a2,a3,a4], b=[b2,b3,b4])\n \"\"\"\n\n def __init__(self, r_cut, nlist, name=None):\n\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairFourier(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairFourier;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairFourierGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairFourierGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficent options\n\n self.required_coeffs = ['fourier_a','fourier_b'];\n # self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n fourier_a = coeff['fourier_a'];\n fourier_b = coeff['fourier_b'];\n\n return _md.make_pair_fourier_params(fourier_a,fourier_b);\n","sub_path":"hoomd/md/pair.py","file_name":"pair.py","file_ext":"py","file_size_in_byte":128672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"343756841","text":"# Copyright 2019-2021 Jitsuin, inc\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# This is API SAMPLE CODE, not for production use.\n\n\"\"\"Create an event for an asset given url to Archivist and user Token.\n\nThe module contains four functions: main, create_asset, create_event and fetch_event.\nMain function parses in a url to the Archivist and a token, which is a user authorization.\nThe main function would initialize an archivist connection using the url and\nthe token, called \"aconn\", then call create_assets and pass in \"aconn\" and\ncreate_assets will build create_asset, which is a archivist connection function\nto create a new asset for the archivist through archivist connection. The main funciton then\ncalls create_event and pass in \"aconn\" and the created asset to create a new event for the asset.\nMain function calls fetch_event and pass in \"aconn\" and the identity of the event to get the event.\n\"\"\"\n\nfrom archivist.archivist import Archivist\n\n\ndef create_event(arch, asset):\n \"\"\"Create an event for the passed-in asset.\n\n Args:\n arch: archivist connection.\n asset: an asset created using aconn\n\n Returns:\n new_event: a new event for the asset.\n \"\"\"\n # props can be defined for different behaviours and the attributes associated with\n # different behaviours are also different. More details can be found here:\n # https://jitsuin-archivist.readthedocs.io/en/latest/assetv2/index.html\n props = {\n \"operation\": \"Record\",\n # This event is used to record evidence, more behaviour explanation can be found here:\n # https://jitsuin-archivist.readthedocs.io/en/latest/assetv2/index.html\n \"behaviour\": \"RecordEvidence\",\n # Optional Client-claimed time at which the maintenance was performed\n \"timestamp_declared\": \"2019-11-27T14:44:19Z\",\n # Optional Client-claimed identity of person performing the operation\n \"principal_declared\": {\n \"issuer\": \"idp.synsation.io/1234\",\n \"subject\": \"phil.b\",\n \"email\": \"phil.b@synsation.io\",\n },\n }\n attrs = {\n # Required Details of the RecordEvidence request\n \"arc_description\": \"Safety conformance approved for version 1.6.\",\n # Required The evidence to be retained in the asset history\n \"arc_evidence\": \"DVA Conformance Report attached\",\n # Example Client can add any additional information in further attributes,\n # including free text or attachments\n \"conformance_report\": \"blobs/e2a1d16c-03cd-45a1-8cd0-690831df1273\",\n }\n\n return arch.events.create(asset[\"identity\"], props=props, attrs=attrs)\n\n\ndef create_asset(arch):\n \"\"\"Create an asset using Archivist Connection.\n\n Args:\n arch: archivist connection.\n\n Returns:\n newasset: a new asset created.\n \"\"\"\n attrs = {\n \"arc_display_name\": \"display_name\", # Asset's display name in the user interface\n \"arc_description\": \"display_description\", # Asset's description in the user interface\n \"arc_display_type\": \"desplay_type\", # Arc_display_type is a free text field\n # allowing the creator of\n # an asset to specify the asset\n # type or class. Be careful when setting this:\n # assets are grouped by type and\n # sharing policies can be\n # configured to share assets based on\n # their arc_display_type.\n # So a mistake here can result in asset data being\n # under- or over-shared.\n \"some_custom_attribute\": \"value\" # You can add any custom value as long as\n # it does not start with arc_\n }\n behaviours = [\n \"Attachments\",\n \"Firmware\",\n \"LocationUpdate\",\n \"Maintenance\",\n \"RecordEvidence\",\n ]\n\n # The first argument is the behaviours of the asset\n # The second argument is the attributes of the asset\n # The third argument is wait for confirmation:\n # If @confirm@ is True then this function will not\n # return until the asset is confirmed on the blockchain and ready\n # to accept events (or an error occurs)\n # After an asset is submitted to the blockchain (submitted),\n # it will be in the \"Pending\" status.\n # Once it is added to the blockchain, the status will be changed to \"Confirmed\"\n return arch.assets.create(behaviours, attrs, confirm=True)\n\n\ndef main():\n \"\"\"Main function of create event.\n\n Parse in user input of url and auth token and use them to\n create an example archivist connection and create an asset.\n The main function then uses the asset to create an event for\n the asset and fetch the event.\n \"\"\"\n with open(\".auth_token\", mode=\"r\") as tokenfile:\n authtoken = tokenfile.read().strip()\n\n # Initialize connection to Archivist\n arch = Archivist(\n \"https://soak-0-avid.engineering-k8s-stage-2.dev.wild.jitsuin.io\",\n auth=authtoken,\n )\n # Create a new asset\n new_asset = create_asset(arch)\n # Create a new event\n new_event = create_event(arch, new_asset)\n # Fetch the event\n unused_event = arch.events.read(new_event[\"identity\"])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/create_event/create_event.py","file_name":"create_event.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"84218015","text":"\"\"\"\nThe year is divided into four seasons: spring, summer, fall and winter. While the\nexact dates that the seasons change vary a little bit from year to year because of the\nway that the calendar is constructed.\n\nCreate a program that reads a month and day from the user. The user will enter\nthe name of the month as a string, followed by the day within the month as an\ninteger. Then your program should display the season associated with the date\nthat was entered.\n\"\"\"\n\nSPRING = \"March 20\"\nSUMMER = \"June 21\"\nFALL = \"September 22\"\nWINTER = \"December 21\"\n\nmonth = input(\"Enter the name of the month: \")\nday = int(input(\"Enter the day number: \"))\nseason = ''\n\nif month == \"January\" or month == \"February\":\n season = \"Winter\"\nelif month == \"March\":\n if day < 20:\n season = \"Winter\"\n else:\n season = \"Spring\"\nelif month == \"April\" or month == \"May\":\n season = \"Spring\"\nelif month == \"June\":\n if day < 21:\n season = \"Spring\"\n else:\n season = \"Summer\"\nelif month == \"July\" or month == \"August\":\n season = \"Summer\"\nelif month == \"September\":\n if day < 22:\n season = \"Summer\"\n else:\n season = \"Fall\"\nelif month == \"October\" or month == \"November\":\n season = \"Fall\"\nelif month == \"December\":\n if day < 21:\n season = \"Fall\"\n else:\n season = \"Winter\"\n\nprint(month, day, \"is in\", season)","sub_path":"2 If Statements/46_season_from_month_and_day.py","file_name":"46_season_from_month_and_day.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205152188","text":"import subprocess\nimport traceback\nfrom subprocess import CalledProcessError\nimport os\nimport logging\nimport sys\nimport smtplib\nimport signal\nfrom types import SimpleNamespace\nimport importlib.util\nimport re\nimport fileinput\nimport contextlib\nfrom io import BytesIO\nimport tarfile\nimport shutil\n\nimport requests\n\nfrom nicelogger import enable_pretty_logging\nfrom htmlutils import parse_document_from_requests\nfrom myutils import at_dir\nfrom mailutils import assemble_mail\nimport archpkg\n\nUserAgent = 'lilac/0.1 (package auto-build bot, by lilydjwg)'\n\ns = requests.Session()\ns.headers['User-Agent'] = UserAgent\nlogger = logging.getLogger(__name__)\nSPECIAL_FILES = ('package.list', 'lilac.py', '.gitignore')\nEMPTY_COMMIT = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'\n_g = SimpleNamespace()\nbuild_output = None\nPYPI_URL = 'https://pypi.python.org/pypi/%s/json'\n\n# to be override\nAUR_REPO_DIR = '/tmp'\nMAILTAG = 'lilac'\n\ndef smtp_connect():\n s = smtplib.SMTP()\n s.connect()\n return s\n\ndef send_error_report(name, *, msg=None, exc=None, subject=None):\n # exc_info used as such needs Python 3.5+\n logger.error('%s\\n\\n%s', subject, msg, exc_info=exc)\n\nclass Dependency:\n _CACHE = {}\n\n @classmethod\n def get(cls, topdir, what):\n if isinstance(what, tuple):\n pkgbase, pkgname = what\n else:\n pkgbase = pkgname = what\n\n key = pkgbase, pkgname\n if key not in cls._CACHE:\n cls._CACHE[key] = cls(topdir, pkgbase, pkgname)\n return cls._CACHE[key]\n\n def __init__(self, topdir, pkgbase, pkgname):\n self.pkgbase = pkgbase\n self.pkgname = pkgname\n self.directory = os.path.join(topdir, pkgbase)\n\n def resolve(self):\n try:\n return self._find_local_package()\n except FileNotFoundError:\n return None\n\n def _find_local_package(self):\n with at_dir(self.directory):\n fnames = [x for x in os.listdir() if x.endswith('.pkg.tar.xz')]\n pkgs = []\n for x in fnames:\n info = archpkg.PkgNameInfo.parseFilename(x)\n if info.name == self.pkgname:\n pkgs.append(x)\n\n if len(pkgs) == 1:\n return os.path.abspath(pkgs[0])\n elif not pkgs:\n raise FileNotFoundError\n else:\n ret = sorted(\n pkgs, reverse=True, key=lambda n: os.stat(n).st_mtime)[0]\n return os.path.abspath(ret)\n\nclass MissingDependencies(Exception):\n def __init__(self, pkgs):\n self.deps = pkgs\n\nclass BuildPrefixError(Exception):\n def __init__(self, build_prefix):\n self.build_prefix = build_prefix\n\nclass AurDownloadError(Exception):\n def __init__(self, pkgname):\n self.pkgname = pkgname\n\ndef download_official_pkgbuild(name):\n url = 'https://www.archlinux.org/packages/search/json/?name=' + name\n logger.info('download PKGBUILD for %s.', name)\n info = s.get(url).json()\n r = [r for r in info['results'] if r['repo'] != 'testing'][0]\n repo = r['repo']\n arch = r['arch']\n if repo in ('core', 'extra'):\n gitrepo = 'packages'\n else:\n gitrepo = 'community'\n pkgbase = [r['pkgbase'] for r in info['results'] if r['repo'] != 'testing'][0]\n\n tree_url = 'https://projects.archlinux.org/svntogit/%s.git/tree/repos/%s-%s?h=packages/%s' % (\n gitrepo, repo, arch, pkgbase)\n doc = parse_document_from_requests(tree_url, s)\n blobs = doc.xpath('//div[@class=\"content\"]//td/a[contains(concat(\" \", normalize-space(@class), \" \"), \" ls-blob \")]')\n files = [x.text for x in blobs]\n for filename in files:\n blob_url = 'https://projects.archlinux.org/svntogit/%s.git/plain/repos/%s-%s/%s?h=packages/%s' % (\n gitrepo, repo, arch, filename, pkgbase)\n with open(filename, 'wb') as f:\n logger.debug('download file %s.', filename)\n data = s.get(blob_url).content\n f.write(data)\n return files\n\ndef try_aur_url(name):\n aur4url = 'https://aur.archlinux.org/cgit/aur.git/snapshot/{name}.tar.gz'\n templates = [aur4url]\n urls = [url.format(first_two=name[:2], name=name) for url in templates]\n for url in urls:\n response = s.get(url)\n if response.status_code == 200:\n logger.debug(\"downloaded aur tarball '%s' from url '%s'\", name, url)\n return response.content\n logger.error(\"failed to find aur url for '%s'\", name)\n raise AurDownloadError(name)\n\ndef download_aur_pkgbuild(name):\n content = BytesIO(try_aur_url(name))\n files = []\n with tarfile.open(name=name+\".tar.gz\", mode=\"r:gz\", fileobj=content) as tarf:\n for tarinfo in tarf:\n basename, remain = os.path.split(tarinfo.name)\n if basename == '':\n continue\n if remain in ('.AURINFO', '.SRCINFO', '.gitignore'):\n continue\n tarinfo.name = remain\n tarf.extract(tarinfo)\n files.append(remain)\n return files\n\ndef get_pypi_info(name):\n return s.get(PYPI_URL % name).json()\n\ndef get_pkgver_and_pkgrel():\n pkgrel = None\n pkgver = None\n with open('PKGBUILD') as f:\n for l in f:\n if l.startswith('pkgrel='):\n pkgrel = float(l.rstrip().split('=', 1)[-1].strip('\\'\"'))\n if int(pkgrel) == pkgrel:\n pkgrel = int(pkgrel)\n elif l.startswith('pkgver='):\n pkgver = l.rstrip().split('=', 1)[-1]\n return pkgver, pkgrel\n\ndef update_pkgrel(rel=None):\n with open('PKGBUILD') as f:\n pkgbuild = f.read()\n\n def replacer(m):\n nonlocal rel\n if rel is None:\n rel = int(float(m.group(1))) + 1\n return str(rel)\n\n pkgbuild = re.sub(r'''(?<=^pkgrel=)['\"]?([\\d.])+['\"]?''', replacer, pkgbuild, count=1, flags=re.MULTILINE)\n with open('PKGBUILD', 'w') as f:\n f.write(pkgbuild)\n logger.info('pkgrel updated to %s', rel)\n\ndef find_maintainer(me, file='*'):\n cmd = [\n \"git\", \"log\", \"--format=%H %an <%ae>\", \"--\", file,\n ]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)\n\n try:\n while True:\n line = p.stdout.readline()\n commit, author = line.rstrip().split(None, 1)\n if me not in author:\n return author\n finally:\n p.terminate()\n\ndef sendmail(to, from_, subject, msg):\n s = smtp_connect()\n if len(msg) > 5 * 1024 ** 2:\n msg = msg[:1024 ** 2] + '\\n\\n日志过长,省略ing……\\n\\n' + msg[-1024 ** 2:]\n msg = assemble_mail('[%s] %s' % (MAILTAG, subject), to, from_, text=msg)\n s.send_message(msg)\n s.quit()\n\ndef get_changed_packages(revisions, U=None):\n cmd = [\"git\", \"diff\", \"--name-only\", revisions]\n r = run_cmd(cmd).splitlines()\n ret = {x.split('/', 1)[0] for x in r}\n if U is not None:\n ret &= U\n return ret\n\ndef pkgrel_changed(revisions, pkgname):\n cmd = [\"git\", \"diff\", \"-p\", revisions, '--', pkgname + '/PKGBUILD']\n r = run_cmd(cmd, silent=True).splitlines()\n return any(x.startswith('+pkgrel=') for x in r)\n\ndef clean_directory():\n '''clean all PKGBUILD and related files'''\n files = run_cmd(['git', 'ls-files']).splitlines()\n logger.info('clean directory')\n ret = []\n for f in files:\n if f in SPECIAL_FILES:\n continue\n try:\n logger.debug('unlink file %s', f)\n os.unlink(f)\n ret.append(f)\n except FileNotFoundError:\n pass\n return ret\n\ndef git_rm_files(files):\n if files:\n run_cmd(['git', 'rm', '--cached', '--'] + files)\n\ndef git_add_files(files):\n if isinstance(files, str):\n files = [files]\n try:\n run_cmd(['git', 'add', '--'] + files)\n except CalledProcessError:\n # on error, there may be a partial add, e.g. some files are ignored\n run_cmd(['git', 'reset', '--'] + files)\n raise\n\ndef git_commit(*, check_status=True):\n if check_status:\n ret = [x for x in\n run_cmd([\"git\", \"status\", \"-s\", \".\"]).splitlines()\n if x.split(None, 1)[0] != '??']\n if not ret:\n return\n\n run_cmd(['git', 'commit', '-m', 'auto update for package %s' % (\n os.path.split(os.getcwd())[1])])\n\ndef git_pull():\n output = run_cmd(['git', 'pull', '--no-edit'])\n return 'up-to-date' not in output\n\ndef git_reset_hard():\n run_cmd(['git', 'reset', '--hard'])\n\ndef git_push():\n while True:\n try:\n run_cmd(['git', 'push'])\n break\n except CalledProcessError as e:\n if 'non-fast-forward' in e.output or 'fetch first' in e.output:\n run_cmd([\"git\", \"pull\", \"--rebase\"])\n else:\n raise\n\ndef git_last_commit(ref=None):\n cmd = ['git', 'log', '-1', '--format=%H']\n if ref:\n cmd.append(ref)\n return run_cmd(cmd).strip()\n\ndef aur_pre_build(name=None, *, do_vcs_update=True):\n if os.path.exists('PKGBUILD'):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n else:\n pkgver = None\n\n _g.aur_pre_files = clean_directory()\n if name is None:\n name = os.path.basename(os.getcwd())\n _g.aur_building_files = download_aur_pkgbuild(name)\n\n new_pkgver, new_pkgrel = get_pkgver_and_pkgrel()\n if pkgver and pkgver == new_pkgver:\n # change to larger pkgrel\n update_pkgrel(max(pkgrel, new_pkgrel))\n\n if do_vcs_update and name.endswith(('-git', '-hg', '-svn', '-bzr')):\n vcs_update()\n # recheck after sync, because AUR pkgver may lag behind\n new_pkgver, new_pkgrel = get_pkgver_and_pkgrel()\n if pkgver and pkgver == new_pkgver:\n update_pkgrel(max(pkgrel, new_pkgrel))\n\ndef vcs_update():\n # clean up the old source tree\n shutil.rmtree('src', ignore_errors=True)\n run_cmd(['makepkg', '-od'], use_pty=True)\n\ndef aur_post_build():\n git_rm_files(_g.aur_pre_files)\n git_add_files(_g.aur_building_files)\n output = run_cmd([\"git\", \"status\", \"-s\", \".\"]).strip()\n if output:\n git_commit()\n del _g.aur_pre_files, _g.aur_building_files\n\ndef pypi_pre_build(depends=None, python2=False, pypi_name=None, arch=None,\n makedepends=None, depends_setuptools=True,\n provides=None,\n optdepends=None, license=None,\n ):\n if os.path.exists('PKGBUILD'):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n else:\n pkgver = None\n\n pkgname = os.path.basename(os.getcwd())\n if pypi_name is None:\n pypi_name = pkgname.split('-', 1)[-1]\n pkgbuild = run_cmd(['pypi2pkgbuild', pypi_name], silent=True)\n\n if depends_setuptools:\n if depends is None:\n depends = ['python-setuptools']\n else:\n depends.append('python-setuptools')\n elif makedepends is None:\n makedepends = ['python-setuptools']\n elif makedepends:\n makedepends.append('python-setuptools')\n\n pkgbuild = re.sub(r'^pkgname=.*', f'pkgname={pkgname}',\n pkgbuild, flags=re.MULTILINE)\n\n if license:\n pkgbuild = re.sub(r'^license=.*', f'license=({license})',\n pkgbuild, flags=re.MULTILINE)\n\n if depends:\n pkgbuild = pkgbuild.replace(\n \"depends=('python')\",\n \"depends=('python' %s)\" % ' '.join(f\"'{x}'\" for x in depends))\n\n if makedepends:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\nmakedepends=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in makedepends))\n\n if optdepends:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\noptdepends=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in optdepends))\n\n if provides:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\nprovides=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in provides))\n\n if python2:\n pkgbuild = re.sub(r'\\bpython3?(?!\\.)', 'python2', pkgbuild)\n if arch is not None:\n pkgbuild = pkgbuild.replace(\n \"arch=('any')\",\n \"arch=(%s)\" % ' '.join(\"'%s'\" % x for x in arch))\n with open('PKGBUILD', 'w') as f:\n f.write(pkgbuild)\n\n new_pkgver = get_pkgver_and_pkgrel()[0]\n if pkgver and pkgver == new_pkgver:\n # change pkgrel to what specified in PKGBUILD\n update_pkgrel(pkgrel)\n\ndef pypi_post_build():\n git_add_files('PKGBUILD')\n git_commit()\n\ndef lilac_build(repodir, build_prefix=None, oldver=None, newver=None, accept_noupdate=False, depends=(), bindmounts=()):\n with load_lilac() as mod:\n run_cmd([\"sh\", \"-c\", \"rm -f -- *.pkg.tar.xz *.pkg.tar.xz.sig *.src.tar.gz\"])\n success = False\n\n global build_output\n # reset in case no one cleans it up\n build_output = None\n\n try:\n if not hasattr(mod, '_G'):\n # fill nvchecker result unless already filled (e.g. by hand)\n mod._G = SimpleNamespace(oldver = oldver, newver = newver)\n if hasattr(mod, 'pre_build'):\n logger.debug('accept_noupdate=%r, oldver=%r, newver=%r', accept_noupdate, oldver, newver)\n mod.pre_build()\n recv_gpg_keys()\n\n need_build_first = set()\n\n build_prefix = build_prefix or mod.build_prefix\n if not isinstance(build_prefix, str) or 'i686' in build_prefix:\n raise BuildPrefixError(build_prefix)\n\n depend_packages = []\n for x in depends:\n p = x.resolve()\n if p is None:\n need_build_first.add(x.pkgbase)\n else:\n depend_packages.append(p)\n if need_build_first:\n raise MissingDependencies(need_build_first)\n\n makechrootpkg_args = []\n if hasattr(mod, 'makechrootpkg_args'):\n makechrootpkg_args = mod.makechrootpkg_args\n\n call_build_cmd(build_prefix, depend_packages, bindmounts, makechrootpkg_args)\n pkgs = [x for x in os.listdir() if x.endswith('.pkg.tar.xz')]\n if not pkgs:\n raise Exception('no package built')\n if hasattr(mod, 'post_build'):\n mod.post_build()\n success = True\n finally:\n if hasattr(mod, 'post_build_always'):\n mod.post_build_always(success=success)\n\ndef call_build_cmd(tag, depends, bindmounts=(), makechrootpkg_args=[]):\n global build_output\n if tag == 'makepkg':\n cmd = ['makepkg', '--holdver']\n else:\n cmd = ['%s-build' % tag, '--']\n\n if depends:\n for x in depends:\n cmd += ['-I', x]\n\n if bindmounts:\n for x in bindmounts:\n cmd += ['-d', x]\n\n cmd.extend(makechrootpkg_args)\n cmd.extend(['--', '--holdver'])\n\n # NOTE that Ctrl-C here may not succeed\n build_output = run_cmd(cmd, use_pty=True)\n build_output = build_output.replace('\\r\\n', '\\n')\n build_output = re.sub(r'.*\\r', '', build_output)\n\ndef single_main(build_prefix='makepkg'):\n prepend_self_path()\n enable_pretty_logging('DEBUG')\n lilac_build(\n build_prefix = build_prefix,\n repodir = os.path.dirname(\n os.path.dirname(sys.modules['__main__'].__file__)),\n accept_noupdate = True,\n )\n\ndef prepend_self_path():\n mydir = os.path.realpath(os.path.dirname(__file__))\n path = os.environ['PATH']\n os.environ['PATH'] = mydir + os.pathsep + path\n\ndef run_cmd(cmd, *, use_pty=False, silent=False):\n logger.debug('running %r, %susing pty,%s showing output', cmd,\n '' if use_pty else 'not ',\n ' not' if silent else '')\n if use_pty:\n rfd, stdout = os.openpty()\n stdin = stdout\n # for fd leakage\n logger.debug('pty master fd=%d, slave fd=%d.', rfd, stdout)\n else:\n stdin = subprocess.DEVNULL\n stdout = subprocess.PIPE\n\n exited = False\n def child_exited(signum, sigframe):\n nonlocal exited\n exited = True\n old_hdl = signal.signal(signal.SIGCHLD, child_exited)\n\n p = subprocess.Popen(cmd, stdin = stdin, stdout = stdout, stderr = subprocess.STDOUT)\n if use_pty:\n os.close(stdout)\n else:\n rfd = p.stdout.fileno()\n out = []\n\n while True:\n try:\n r = os.read(rfd, 4096)\n if not r:\n if exited:\n break\n else:\n continue\n except InterruptedError:\n continue\n except OSError as e:\n if e.errno == 5: # Input/output error: no clients run\n break\n else:\n raise\n r = r.replace(b'\\x0f', b'') # ^O\n if not silent:\n sys.stderr.buffer.write(r)\n out.append(r)\n\n code = p.wait()\n if use_pty:\n os.close(rfd)\n if old_hdl is not None:\n signal.signal(signal.SIGCHLD, old_hdl)\n\n out = b''.join(out)\n out = out.decode('utf-8', errors='replace')\n if code != 0:\n raise CalledProcessError(code, cmd, out)\n return out\n\ndef edit_file(filename):\n with fileinput.input(files=(filename,), inplace=True) as f:\n for line in f:\n yield line.rstrip('\\n')\n\ndef recv_gpg_keys():\n run_cmd(['recv_gpg_keys'])\n\n@contextlib.contextmanager\ndef load_lilac():\n try:\n spec = importlib.util.spec_from_file_location('lilac.py', 'lilac.py')\n mod = spec.loader.load_module()\n yield mod\n finally:\n try:\n del sys.modules['lilac.py']\n except KeyError:\n pass\n\ndef _update_aur_repo_real(pkgname):\n aurpath = os.path.join(AUR_REPO_DIR, pkgname)\n if not os.path.isdir(aurpath):\n logger.info('cloning AUR repo: %s', aurpath)\n with at_dir(AUR_REPO_DIR):\n run_cmd(['git', 'clone', 'aur@aur.archlinux.org:%s.git' % pkgname])\n else:\n with at_dir(aurpath):\n git_reset_hard()\n git_pull()\n\n logger.info('copying files to AUR repo: %s', aurpath)\n files = run_cmd(['git', 'ls-files']).splitlines()\n for f in files:\n if f in SPECIAL_FILES:\n continue\n logger.debug('copying file %s', f)\n shutil.copy(f, aurpath)\n\n with at_dir(aurpath):\n run_cmd(['mksrcinfo'])\n run_cmd(['git', 'add', '.'])\n run_cmd(['git', 'commit', '-m', 'update by lilac'])\n run_cmd(['git', 'push'])\n\ndef update_aur_repo():\n pkgname = os.path.basename(os.getcwd())\n try:\n _update_aur_repo_real(pkgname)\n except CalledProcessError as e:\n tb = traceback.format_exc()\n send_error_report(\n pkgname,\n exc = (e, tb),\n subject = '[lilac] 提交软件包 %s 到 AUR 时出错',\n )\n\ndef kill_child_processes():\n pids = subprocess.check_output(\n ['pid_children', str(os.getpid())]\n ).decode().split()\n for pid in pids:\n try:\n os.kill(int(pid), signal.SIGKILL)\n except OSError:\n pass\n\ndef is_nodejs_thing():\n with open('PKGBUILD') as f:\n data = f.read()\n return 'nodejs' in data and 'npm' in data\n\ndef update_pkgver_and_pkgrel(newver):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n\n for line in edit_file('PKGBUILD'):\n if line.startswith('pkgver=') and pkgver != newver:\n line = f'pkgver={newver}'\n elif line.startswith('pkgrel='):\n if pkgver != newver:\n line = 'pkgrel=1'\n else:\n line = f'pkgrel={int(pkgrel)+1}'\n\n print(line)\n\n run_cmd([\"updpkgsums\"])\n","sub_path":"lilaclib.py","file_name":"lilaclib.py","file_ext":"py","file_size_in_byte":17830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"22489124","text":"\"\"\"ロギングモジュール\nアプリケーション内のログ設定を定義するモジュール\nアプリケーションのログは必ずここのロガーを通してロギングする必要がある\n\"\"\"\nimport logging\nimport sys\n\nfrom domain.enums.core_enums import LogLevel\n\nfrom core.config import CoreSettings\n\nsettings = CoreSettings()\n\n# ------------------------\n# ログフォーマット定義\n# ------------------------\nAPP_LOG_FORMAT = \"Level:%(levelname)s\\tType:CoreApiApp\\tTime:%(asctime)s\\tFile:%(pathname)s\\tMessage:%(message)s\"\nACCESS_LOG_FORMAT = \"Level:%(levelname)s\\tType:CoreApiAccess\\tTime:%(asctime)s\\tProcessTime:%(process_time)s\\tClient:%(client_addr)s\\tMethod:%(method)s\\tPath:%(path)s\\tQuery:%(query)s\\tStatusCode:%(status_code)s\"\nJSON_LOG_FORMAT = \"Level:%(levelname)s\\tType:%(type)s\\tTime:%(asctime)s\\tMessage:%(message)s\"\n\n\ndef create_app_logger(log_name: str) -> logging.Logger:\n \"\"\"アプリケーションロガー作成関数\n アプリケーションロガーを作成する\n Args:\n log_name: ロガー名\n Returns:\n logging.Logger: ロガー\n \"\"\"\n\n return _create_logger(\n log_name=log_name,\n log_format=APP_LOG_FORMAT\n )\n\n\ndef create_access_logger() -> logging.Logger:\n \"\"\"アクセスロガー作成関数\n\n Returns:\n logging.Logger: ロガー\n \"\"\"\n return _create_logger(\n log_name=\"access_logger\",\n log_format=ACCESS_LOG_FORMAT\n )\n\n\ndef create_json_logger() -> logging.Logger:\n \"\"\"JSON形式のログメッセージを出力するロガー作成関数\n\n Returns:\n logging.Logger: ロガー\n \"\"\"\n return _create_logger(\n log_name=\"json_logger\",\n log_format=JSON_LOG_FORMAT\n )\n\n\ndef _create_logger(log_name: str, log_format: str) -> logging.Logger:\n \"\"\"ロガー作成関数\n ロガーを作成する\n Args:\n log_name: ロガー��\n log_format: ログフォーマット\n Returns:\n logging.Logger: ロガー\n \"\"\"\n # ロガーの作成\n log = logging.getLogger(log_name)\n\n # ログレベルの設定\n if settings.api_log_level == LogLevel.INFO:\n log.setLevel(logging.INFO)\n elif settings.api_log_level == LogLevel.DEBUG:\n log.setLevel(logging.DEBUG)\n\n # 標準出力に出力\n handler = logging.StreamHandler(stream=sys.stdout)\n # LTSV形式で出力\n formatter = logging.Formatter(log_format)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n # プロパゲートしない\n log.propagate = False\n\n return log\n\n\n# ------------------------\n# 名前付きロガー定義\n# ------------------------\nACCESS_LOGGER = create_access_logger()\nJSON_LOGGER = create_json_logger()\n","sub_path":"src/app/core/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"333893244","text":"import random\n\n\nclass Word(object):\n counter = 0\n descendants = {}\n\n def __init__(self, counter, descendants):\n self.counter = counter\n self.descendants = descendants\n\n\ndef get_random_word(d):\n keys = list(d.keys())\n index = random.randint(0, len(keys) - 1)\n return keys[index]\n\n\ndef get_next_word(word):\n if len(word.descendants) == 0:\n return None\n\n rand = random.randint(1, 99)\n prob = 0\n\n for key, value in word.descendants.items():\n prob += (value / word.counter) * 100\n\n if rand <= prob:\n return key\n\n return None\n\n\ndef generate():\n # text = input(\"Enter text: \")\n text = \"Только такая цель позволяет человеку прожить свою жизнь с достоинством и получить настоящую радость. Да, радость! Подумайте: если человек ставит себе задачей увеличивать в жизни добро, приносить людям счастье, какие неудачи могут его постигнуть? Не тому помочь? Но много ли людей не нуждаются в помощи?\"\n # k = int(input(\"Enter k: \"))\n k = 7\n # stop = int(input(\"Enter length to stop: \"))\n stop = 1000\n\n words = {}\n\n for x in range(0, len(text)):\n key = text[x:x + k]\n next_key = text[x + k:x + k + k]\n\n word = words.setdefault(key, Word(0, {}))\n word.counter += 1\n\n word.descendants.setdefault(next_key, 0)\n word.descendants[next_key] += 1\n\n next_key = get_random_word(words)\n\n while stop > 0:\n yield next_key\n\n word = words[next_key]\n next_key = get_next_word(word) or get_random_word(words)\n stop -= len(next_key)\n\n\nif __name__ == '__main__':\n for text in generate():\n print(text, end='')\n\n print()\n","sub_path":"BDA/delirium.py","file_name":"delirium.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"109254123","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 24 13:29:54 2020\r\n\r\n@author: viktorwu02\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.basemap import Basemap\r\nfrom shapely.geometry import Point\r\nfrom shapely.geometry import Polygon\r\n\r\n \r\nfrom netCDF4 import Dataset\r\n\r\nfor year in range(2000,2020):\r\n\r\n file = 'MODIS_2000_2019/' + year + '/Greenland_Reflectivity_' + year + '_5km_C6.nc'\r\n#file = 'MODIS_2000_2019/2012/Greenland_Reflectivity_2012_5km_C6.nc'\r\n nc = Dataset(file,'r')\r\n \r\n### To calculate the cumulative slush-days\r\n \r\n for day in range(1,366):\r\n \r\n albedos = nc.variables[\"albedo\"][day]\r\n icemask = nc.variables[\"icemask\"]\r\n dem = nc.variables[\"dem\"]\r\n lats = nc.variables['lat'][:]\r\n lons = nc.variables['lon'][:]\r\n mod_lons = lons + 360\r\n cumulative_slush = np.zeros((561,301))\r\n \r\n (rows,cols) = np.shape(dem)\r\n for r in range(1,rows-1):\r\n for c in range(1,cols-1):\r\n temp_window = albedos[r-1:r+2,c-1:c+2]\r\n mean = np.sum(temp_window)/9\r\n temp_list = []\r\n \r\n for cell in np.nditer(temp_window, op_flags=['readwrite']):\r\n variance = (cell - mean)**2\r\n temp_list.append(variance)\r\n st_deviation = math.sqrt(sum(temp_list)/9)\r\n \r\n \r\n if st_deviation >= 0.05 and icemask[r,c] == 1: \r\n cumulative_slush[r,c] += 1\r\n \r\n### To classify one image\r\n \r\nfile = 'MODIS_2000_2019/2012/Greenland_Reflectivity_2012_5km_C6.nc' \r\nnc = Dataset(file,'r')\r\n \r\nalbedos = nc.variables[\"albedo\"][day]\r\nicemask = nc.variables[\"icemask\"]\r\ndem = nc.variables[\"dem\"]\r\nlats = nc.variables['lat'][:]\r\nlons = nc.variables['lon'][:]\r\nmod_lons = lons + 360\r\nslush_ice = np.zeros((561,301))\r\n \r\n(rows,cols) = np.shape(dem)\r\nfor r in range(1,rows-1):\r\n for c in range(1,cols-1):\r\n temp_window = albedos[r-1:r+2,c-1:c+2]\r\n mean = np.sum(temp_window)/9\r\n temp_list = []\r\n \r\n for cell in np.nditer(temp_window, op_flags=['readwrite']):\r\n variance = (cell - mean)**2\r\n temp_list.append(variance)\r\n st_deviation = math.sqrt(sum(temp_list)/9)\r\n\r\n if st_deviation >= 0.05 and icemask[r,c] == 1 and cumulative_slush[r,c] < 2800: \r\n slush_ice[r,c] = 1\r\n elif icemask[r,c] != 1 and albedos[r,c] > 0:\r\n slush_ice[r,c] = 3\r\n elif icemask[r,c] != 1:\r\n slush_ice[r,c] = -1 \r\n else: \r\n slush_ice[r,c] = 2\r\n\r\n\r\n\r\n### To count pixels in drainage systems \r\n\r\n#if st_deviation >= 0.05 and icemask[r,c] == 1 and slush_hotspot[r,c] < 2800 and Polygon(polyname).contains(Point(lats[r,c],mod_lons[r,c])): \r\n \r\n#pixlist21.append(len(slush_list))\r\n#topelev21.append(np.percentile(slush_list,90))\r\n\r\n\r\n\r\n \r\n \r\n \r\n#slush_ice = np.flipud(slush_ice)\r\n\r\n #slush_list.append(slush_ice)\r\n\r\n\r\n\r\n\r\n\r\n#plot one\r\n\r\n#from matplotlib.colors import from_levels_and_colors\r\n#cmap, norm = from_levels_and_colors([-1,1,2,3,4],['white','orangered','azure','silver'])\r\n#fig = plt.figure(figsize=(8, 6))\r\n#m = Basemap(projection='lcc', resolution='l',\r\n# width=2E6, height=3E6, lat_0=72, lon_0=-37,)\r\n#mplot = m.pcolormesh(lons, lats, slush_ice,latlon=True, cmap=cmap, norm=norm)\r\n#mplot = m.drawparallels(np.arange(-80.,81.,10.),labels=[True,False,True,False])\r\n#mplot = m.drawmeridians(np.arange(-180.,181.,20.),labels=[False,False,False,True])\r\n#plt.clim(-1, 4)\r\n#plt.title('Slush on GrIS')\r\n#plt.colorbar; \r\n\r\n\r\n\r\n \r\n# To create output\r\n\r\n#header = \"ncols {}\\n\".format(slush_ice.shape[1])\r\n#header += \"nrows {}\\n\".format(slush_ice.shape[0])\r\n#header += \"xllcorner -440510.18862\\n\"\r\n#header += \"yllcorner -3467275.427575\\n\"\r\n#header += \"cellsize 5000\\n\"\r\n#header += \"NODATA_value -9999\"\r\n\r\n#np.savetxt(\"slush2019\"+\"_thresh8_5_wtr\"+\".asc\",slush_ice, header=header, fmt=\"%1.2f\", comments='')\r\n\r\n\r\n\r\n\r\n\r\n\r\n##### To load polygons\r\n \r\n#with open('GrnDrainageSystems_Ekholm.txt', 'r') as f:\r\n\r\n # data = f.readlines() # Reading all data\r\n \r\n # Removing header\r\n # idx = 0\r\n # while not 'END OF HEADER' in data[idx]:\r\n # print(data[idx]) # If you want to print the header\r\n # idx += 1\r\n \r\n # Extracting the first point of the first polygon\r\n # Needs to start at idx+1 since not incrementing after found end of header\r\n # tempLine = data[idx+1] # Current coordinate\r\n # print(tempLine.split(' '))\r\n # tempPoint = tempLine.strip().split(' ') # Removing leading (and ending) spaces and splitting\r\n # indices that gives:\r\n # code, latitude, longitude:\r\n # [0],[6],[11]\r\n \r\n #Extracting the point of each polygon\r\n # tempPolyID = float(tempPoint[0])\r\n #\r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n # tempPolyList is a list with polygon ID followed by a series of tuples with lat,lon coordinates for that polygon\r\n \r\n \r\n \r\n \r\n # Start looping over the data.\r\n # for i in range(idx+2, len(data)):\r\n # tempLine = data[i] # Current coordinate\r\n # tempPoint = tempLine.strip().split(' ') # Removing leading (and ending) spaces and splitting\r\n \r\n # if float(tempPoint[0]) == tempPolyID: # Not recommended to use == for float....\r\n # New point of current polygon \r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n # else:\r\n # New polygon\r\n # tempPolyID = float(tempPoint[0])\r\n # polyList.append(tempPolyID)\r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n\r\n\r\n\r\n##########################\r\n\r\n\r\n#fig = plt.figure(figsize=(8, 6))\r\n#cmap = plt.get_cmap('rainbow')\r\n#cmap.set_under('white') \r\n#m = Basemap(projection='lcc', resolution='l',\r\n# width=2E6, height=3E6, lat_0=72, lon_0=-37,)\r\n#mplot = m.pcolormesh(lons, lats, slush_hotspot, vmin= 0.5, cmap=cmap, latlon=True)\r\n#mplot = m.drawparallels(np.arange(-80.,81.,10.),labels=[True,False,True,False])\r\n#mplot = m.drawmeridians(np.arange(-180.,181.,20.),labels=[False,False,False,True])\r\n#mplot = m.drawcoastlines()\r\n#plt.title('Cumulative slush-days')\r\n#plt.colorbar;\r\n \r\n","sub_path":"detect_slush_on_greenland.py","file_name":"detect_slush_on_greenland.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5976834","text":"# Feature selection (mordred)\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# This is the output from the rdkit descriptor calculator tool on Galaxy\nfilename1 = \"molecular-descriptors-mordred.tabular\"\n\n# This is the initial dataset that contains a list of compounds \\\n# (in SMILES format) and a label in the last column (0 or 1) which \\\n# indicates if the compound is active against the estrogen nuclear receptor\nfilename2 = \"er-data.smi\"\n\n# Import data into a pandas dataframe\np_df1 = pd.read_csv(filename1, sep='\\t', dtype='O')\np_df2 = pd.read_csv(filename2, sep='\\t', dtype='O')\n\n# Keep only columns that represent features i.e the molecular descriptors\nX = p_df1\ny = p_df2['label']\n\n\n# np.reshape(y, (X.shape[0], 1))\n# Change the datatype of the features to float and the labels to int\nX = X.astype(\"float32\")\ny = y.astype(\"int32\")\n\n# Replace inf to nan\nX = X.replace([np.inf], np.nan)\ny = y.replace([np.inf], np.nan)\n\n# Convert nan values to 0\nX.fillna(value=0, inplace=True)\ny.fillna(value=0, inplace=True)\n\n\n# Apply SelectKBest class to extract top n best features\nbestfeatures = SelectKBest(score_func=f_classif, k=20)\n\n# Apply ExtraTreesClassifier class to get ranking of the features\n#bestfeatures = ExtraTreesClassifier()\n\nfit = bestfeatures.fit(X, y)\n\nscores = pd.DataFrame(fit.scores_)\n#scores = pd.DataFrame(fit.feature_importances_)\ncolumns = pd.DataFrame(X.columns)\n\n# Concat two dataframes\nfeature_scores = pd.concat([columns, scores], axis=1)\nfeature_scores.columns = ['Feature', 'Score']\nn_largest = feature_scores.nlargest(20, 'Score')\nprint(n_largest)\nfeatures = n_largest['Feature'].values.tolist()\n\n# Extract selected features out of the dataset.\nX = X[features]\n\n# Separate data into train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, shuffle=True)\n\nfile_names = ['X_train', 'X_test', 'y_train', 'y_test']\ndatasets = [X_train, X_test, y_train, y_test]\n\n# Convert the train and test sets to csv files\nfor dataset, file_name in zip(datasets, file_names):\n dataset.to_csv(file_name, sep='\\t', header=None, index=False)\n\n\n# Fit the training data on a random forest classifier\nrForest = RandomForestClassifier(min_samples_leaf=15, n_estimators=250, max_depth=20, random_state=0)\nrForest.fit(X_train, y_train)\n\nscore = rForest.score(X_test, y_test)\nprint(\"Quality of the model: \" + str(score))\n","sub_path":"featureSelection-mordred.py","file_name":"featureSelection-mordred.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"232799113","text":"class Fraccion():\n def __init__(self,num, denom = None):\n self.num = num\n if denom is not None:\n self.denom = denom\n else:\n self.denom = 1\n\n def sumar(self,otro):\n denominador = self.denom*otro.denom\n numerador = (self.num*otro.denom)+(otro.num*self.denom)\n\n return numerador,denominador\n\n def restar(self,otro):\n denominador = self.denom*otro.denom\n numerador = (self.num*otro.denom)-(otro.num*self.denom)\n\n return numerador,denominador\n\n def multiplicar(self,otro):\n numerador = self.num * otro.num\n denominador = self.denom * otro.denom\n\n return numerador,denominador\n\n def dividir(self,otro):\n numerador = self.num * otro.denom\n denominador = self.denom * otro.num\n\n return numerador,denominador\n\nclass TestFraccion():\n def test_sumar(self):\n\n f1 = Fraccion(2,3)\n f2 = Fraccion(5,6)\n\n suma = f1.sumar(f2) #3/2\n return suma\n\n def test_restar(self):\n\n f1 = Fraccion(7,5)\n f2 = Fraccion(8,9)\n\n resta = f1.restar(f2) #23/45\n return resta\n\n def test_multiplicar(self):\n\n f1 = Fraccion(5,3)\n f2 = Fraccion(9)\n\n multiplicacion = f1.multiplicar(f2) #15/1\n return multiplicacion\n\n def test_dividir(self):\n\n f1 = Fraccion(6,1)\n f2 = Fraccion(9)\n\n division = f1.dividir(f2) #2/3\n return division\n\ntest = TestFraccion()\nprint(test.test_sumar())\nprint(test.test_restar())\nprint(test.test_multiplicar())\nprint(test.test_dividir())\n\n\n\n","sub_path":"class_Fraccion.py","file_name":"class_Fraccion.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224338991","text":"# -*- coding: cp936 -*-\nimport pythoncom\nimport pyHook\nimport time\nimport win32api\nimport os\nimport re\n\n\ndef getDomin(dirName):\n domain = dirName.split(\"_\")\n # print(\"dddddddddddddddddddddddddddddd:\"+str(domain))\n for i in reversed(domain):\n if ((i.replace(\"\\n\", \"\") in firstClassDomain) or (i.replace(\"\\n\", \"\") in conturyDomain)):\n pass\n else:\n return i\n\ndef writeToSave(date,fsaveToPath):#把输入保存到指定文件,fsaveToPath为文件描述符,https为带保存数据,可能为str,也可能为list\n #print(date)\n if(type(date) is type(\"\")):\n fsaveToPath.write(str(date).replace(\"\\n\",\"\") + \"\\n\")\n return 1\n for i in date:\n fsaveToPath.write(str(i).replace(\"\\n\",\"\") + \"\\n\")\n return 2\n\ndef main():\n visitedList=[]\n firstDir = os.listdir(dirPath)\n for second in firstDir:\n secondDir = os.listdir(dirPath + \"\\\\\" + second)\n for i in secondDir:\n visitedList.append(getDomin(i))\n print(writeToSave(visitedList,open(visitedDomainZL,\"a\")))\n\ndef getDomin(url):\n temp=url.split(\"/\")\n if(len(temp)<=2):\n return None\n temp2=temp[2].split(\"?\")[0]\n temp3=temp2.split(\"#\")[0]\n domain=temp3.split(\".\")\n #print(\"dddddddddddddddddddddddddddddd:\"+str(domain))\n for i in reversed(domain):\n if((i.replace(\"\\n\",\"\") in firstClassDomain) or (i.replace(\"\\n\",\"\") in conturyDomain)):\n pass\n else:\n return i\n\ndef test():\n pass\n\ndef jdtxt():\n lis = []\n pattern=\"aaaaaabbb\"\n rr=re.compile(pattern)\n num=0\n with open(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\", 'r+') as fp:\n for i in fp.readlines():\n if(re.search(rr,i)!=None):\n num=1\n if(num==1):\n lis.append(i)\n print (lis)\n os.remove(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\")\n with open(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\", 'a+')as f:\n for i in lis[1:]:\n #print (i)\n f.write(i)\n\nif __name__ == \"__main__\":\n firstClassDomain = (\"biz\", \"com\", \"edu\", \"gov\", \"info\", \"int\", \"mil\", \"name\", \"net\", \"org\", \"pro\", \"xxx\",\n \"aero\", \"cat\", \"coop\", \"jobs\", \"museum\", \"travel\", \"mobi\", \"asia\", \"tel\", \"arpa\", \"root\",\n \"post\")\n conturyDomain = (\"cn\", \"de\",\"uk\", \"us\", \"jp\", \"fr\", \"eg\", \"eu\", \"br\")\n dirPath = r\"E:\\pic\"\n visitedDomainZL = r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\VDZL.txt\"\n\n #main()\n #test()\n #jdtxt()\n print(getDomin(\"http://ckadk.lskdjf.com#?#fjdk=qkjw&ajskdj=KJk\"))","sub_path":"level_unauthorized/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"222791307","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2013-2014 DNAnexus, Inc.\n#\n# This file is part of dx-toolkit (DNAnexus platform client libraries).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import print_function\n\nimport dxpy\nimport json\nimport string\nimport random\nimport sys\nimport argparse\nimport os\n\n# to find the magic library\nimport magic\nimport subprocess\n\ndef id_generator(size=10, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\ndef unpack(input):\n m = magic.Magic()\n\n # determine compression format\n try:\n file_type = m.from_file(input)\n except Exception as e:\n raise dxpy.AppError(\"Error while identifying compression format: \" + str(e))\n \n # if we find a tar file throw a program error telling the user to unpack it\n if file_type == 'application/x-tar':\n raise dxpy.AppError(\"App does not support tar files. Please unpack.\")\n\n # since we haven't returned, the file is compressed. Determine what program to use to uncompress\n uncomp_util = None\n if file_type == 'XZ compressed data':\n uncomp_util = 'xzcat'\n elif file_type[:21] == 'bzip2 compressed data':\n uncomp_util = 'bzcat'\n elif file_type[:20] == 'gzip compressed data':\n uncomp_util = 'zcat'\n elif file_type == 'POSIX tar archive (GNU)' or 'tar' in file_type:\n raise dxpy.AppError(\"Found a tar archive. Please untar your sequences before importing\")\n else:\n # just return input filename since it's already uncompressed\n return input\n\n if uncomp_util != None: \n # bzcat does not support -t. Use non streaming decompressors for testing input\n test_util = None\n if uncomp_util == 'xzcat':\n test_util = 'xz'\n elif uncomp_util == 'bzcat':\n test_util = 'bzip2'\n elif uncomp_util == 'zcat':\n test_util = 'gzip'\n\n try:\n subprocess.check_call(\" \".join([test_util, \"-t\", input]), shell=True)\n except subprocess.CalledProcessError:\n raise dxpy.AppError(\"File failed integrity check by \"+uncomp_util+\". Compressed file is corrupted.\")\n\n # with that in hand, unzip file. If we find a tar archive then exit with error.\n try:\n with subprocess.Popen([uncomp_util, input], stdout=subprocess.PIPE).stdout as pipe:\n line = pipe.next()\n uncomp_type = m.from_buffer(line)\n except Exception as e:\n raise dxpy.AppError(\"Error detecting file format after decompression: \" + str(e))\n\n if uncomp_type == 'POSIX tar archive (GNU)' or 'tar' in uncomp_type:\n raise dxpy.AppError(\"Found a tar archive after decompression. Please untar your files before importing\")\n elif 'ASCII text' not in uncomp_type:\n raise dxpy.AppError(\"After decompression found file type other than plain text\")\n \n try:\n out_name = id_generator()\n subprocess.check_call(\" \".join([uncomp_util, \"--stdout\", input, \">\", out_name]), shell=True)\n return out_name\n except subprocess.CalledProcessError as e:\n raise dxpy.AppError(\"Unable to open compressed input for reading: \" + str(e))\n\ndef detect_type(bed_file):\n delimiter = find_delimiter(bed_file)\n with open(bed_file, 'rU') as bf:\n header=\"\"\n while \"track\" not in header:\n header=bf.readline()\n # if this isn't a browser line either then there isn't a header\n if \"browser\" not in header:\n break\n if \"type=bedDetail\" in header:\n print(\"File is a BED detail file\", file=sys.stderr)\n return {\"type\": \"bedDetail\", \"delimiter\": delimiter}\n \n num_cols = find_num_columns(bed_file, delimiter)\n if num_cols >= 12:\n return {\"type\": \"genes\", \"delimiter\": delimiter}\n else:\n return {\"type\": \"spans\", \"delimiter\": delimiter}\n \n# takes the whole bed file and splits into separate files for each track contained in it\n\ndef split_on_track(bed_file):\n files = []\n current_filename = id_generator()\n # open bed file\n with open(bed_file, 'rU') as bf:\n curr_file = open(current_filename, \"w\")\n line = bf.readline()\n if line.startswith(\"browser\"):\n line = bf.readline()\n curr_file.write(line)\n line = bf.readline()\n while True:\n if line.startswith(\"track\"):\n # close and save our last track as a new file\n curr_file.close()\n files.append(current_filename)\n # open a new file for the next track\n current_filename = id_generator()\n curr_file = open(current_filename, \"w\")\n elif line == \"\":\n curr_file.close()\n files.append(current_filename)\n break\n \n curr_file.write(line)\n line = bf.readline()\n\n return files\n\ndef find_num_columns(bed_file, delimiter=\"\\t\"):\n num_cols = 0\n\n with open(bed_file, \"rU\") as bf:\n line = bf.readline()\n while line != \"\":\n if line.startswith(\"track\"):\n line = bf.readline()\n line = line.split(delimiter)\n if len(line) > num_cols:\n num_cols = len(line)\n line = bf.readline()\n\n print(\"Found num cols: \" + str(num_cols), file=sys.stderr)\n return num_cols\n\ndef find_delimiter(bed_file):\n with open(bed_file, \"rU\") as bf: \n line = bf.readline()\n if line.startswith(\"track\"):\n line = bf.readline()\n tab_split = line.split(\"\\t\")\n \n if len(tab_split) >= 3: \n print(\"Bed file is tab delimited\", file=sys.stderr)\n return \"\\t\"\n else: \n space_split = line.split()\n if len(space_split) < 3: \n raise dxpy.AppError(\"File is not a valid bed file (neither space delimited nor tab delimited)\")\n print(\"Bed file is space delimited\", file=sys.stderr)\n return \" \"\n \ndef import_spans(bed_file, table_name, ref_id, file_id, additional_types, property_keys, property_values, tags, isBedDetail, delimiter=\"\\t\"):\n num_cols = find_num_columns(bed_file, delimiter)\n\n # if this is a bedDetail file we should treat the last two columns separately\n if isBedDetail:\n num_cols -= 2\n \n possible_columns = [(\"chr\", \"string\"),\n (\"lo\", \"int32\"),\n (\"hi\", \"int32\"),\n (\"name\", \"string\"),\n (\"score\", \"float\"),\n (\"strand\", \"string\"),\n (\"thick_start\", \"int32\"),\n (\"thick_end\", \"int32\"),\n (\"item_rgb\", \"string\")]\n\n bedDetail_columns = [(\"bedDetail_ID\", \"string\"),\n (\"bedDetail_desc\", \"string\")]\n\n possible_default_row = [\"\", 0, 0, \"\", 0, \".\", 0, 0, \"\"]\n\n columns = possible_columns[:num_cols]\n\n if isBedDetail:\n columns.extend(bedDetail_columns)\n\n if num_cols > len(columns):\n for i in range(len(columns), num_cols):\n columns.append((\"BED_column_\"+str(i+1), \"string\"))\n possible_default_row.append(\"\")\n\n default_row = possible_default_row[:num_cols]\n\n if isBedDetail:\n default_row.extend([\"\",\"\"])\n\n column_descs = [dxpy.DXGTable.make_column_desc(name, type) for name, type in columns]\n \n indices = [dxpy.DXGTable.genomic_range_index(\"chr\",\"lo\",\"hi\", 'gri')]\n for c in columns:\n if \"name\" in c:\n indices.append(dxpy.DXGTable.lexicographic_index([\n dxpy.DXGTable.lexicographic_index_column(\"name\", True, False),\n dxpy.DXGTable.lexicographic_index_column(\"chr\"),\n dxpy.DXGTable.lexicographic_index_column(\"lo\"),\n dxpy.DXGTable.lexicographic_index_column(\"hi\")], \"search\"))\n break\n \n with open(bed_file, 'rU') as bed, dxpy.new_dxgtable(column_descs, indices=indices, mode='w') as span:\n details = {\"original_contigset\": dxpy.dxlink(ref_id)}\n if file_id != None:\n details[\"original_file\"] = dxpy.dxlink(file_id)\n if len(property_keys) != len(property_values):\n raise dxpy.AppError(\"Expected each provided property to have a corresponding value.\")\n for i in range(len(property_keys)):\n details[property_keys[i]] = property_values[i] \n \n span.set_details(details)\n\n span.add_types([\"Spans\", \"gri\"])\n span.rename(table_name)\n\n for line in bed:\n row = list(default_row)\n\n if line.startswith(\"track\"):\n details = span.get_details()\n details['track'] = line\n span.set_details(details)\n continue\n line = line.rstrip(\"\\n\")\n line = line.split(delimiter)\n if isBedDetail:\n # only the first 4 columns are guaranteed to be defined by UCSC\n validate_line(line[:4])\n # save last two fields separately\n bedDetailFields = line[-2:]\n line = line[:-2] \n else: \n validate_line(line[:num_cols])\n \n # check to see if this is a weird line\n if len(line) == 0:\n break\n if len(line) < 3:\n raise dxpy.AppError(\"Line: \"+\"\\t\".join(line)+\" in BED file contains less than the minimum 3 columns. Invalid BED file.\")\n\n try:\n row[0] = line[0]\n row[1] = int(line[1])\n row[2] = int(line[2])\n row[3] = line[3]\n # dashes are sometimes used when field is invalid\n if line[4] == \"-\" or line[4] == \".\":\n line[4] = 0\n row[4] = float(line[4])\n row[5] = line[5]\n # dashes are sometimes used when field is invalid\n if line[6] == \"-\" or line[6] == \".\":\n line[6] = 0\n row[6] = int(line[6])\n # dashes are sometimes used when field is invalid\n if line[7] == \"-\" or line[7] == \".\":\n line[7] = 0\n row[7] = int(line[7])\n row[8] = line[8]\n\n # an index error would come from having fewer columns in a row, which we should handle ok\n except IndexError:\n pass\n # value error when fields are messed up and string gets converted to int, etc. Throw these out.\n except ValueError:\n continue\n \n if isBedDetail:\n # add these in at the end if we have a bedDetail file\n row[num_cols] = bedDetailFields[0]\n row[num_cols+1] = bedDetailFields[1]\n \n span.add_row(row)\n\n span.flush()\n\n return dxpy.dxlink(span.get_id())\n\n\n##########named spans###############END\n\ndef generate_gene_row(line, block_size, block_start, span_type, default_row, parent_id, span_id):\n row = list(default_row)\n\n try:\n # chr\n row[0] = line[0]\n\n # lo\n row[1] = int(line[1])\n # if we're a child, add our offset\n if parent_id != -1:\n row[1] += block_start\n\n # hi\n # if we're a child, just add size to our start\n if parent_id != -1:\n row[2] = row[1] + block_size\n else:\n row[2] = int(line[2]) \n\n # name\n row[3] = line[3]\n\n # span_id\n row[4] = span_id\n\n # type\n row[5] = span_type\n\n # strand\n row[6] = line[5]\n\n # is_coding\n if span_type == \"CDS\":\n row[7] = True\n elif \"UTR\" in span_type:\n row[7] = False\n else:\n row[7] = False\n\n # parent_id\n row[8] = parent_id\n\n # frame\n row[9] = -1\n\n # description\n row[10] = \"\\t\".join(line[12:])\n # BED files have no description?\n\n # a misformed line can have string columns where they should be int\n except ValueError:\n return None\n # if missing columns then also throw out the line\n except IndexError:\n return None\n\n return row\n\n\ndef import_genes(bed_file, table_name, ref_id, file_id, additional_types, property_keys, property_values, tags, delimiter=\"\\t\"):\n # implement BED importing from this format:\n # http://genome.ucsc.edu/FAQ/FAQformat.html#format1\n\n columns = [(\"chr\", \"string\"),\n (\"lo\", \"int32\"),\n (\"hi\", \"int32\"),\n (\"name\", \"string\"),\n (\"span_id\", \"int32\"),\n (\"type\", \"string\"),\n (\"strand\", \"string\"),\n (\"is_coding\", \"boolean\"),\n (\"parent_id\", \"int32\"),\n (\"frame\", \"int16\"),\n (\"description\", \"string\")]\n\n column_descs = [dxpy.DXGTable.make_column_desc(name, type) for name, type in columns]\n \n indices = [dxpy.DXGTable.genomic_range_index(\"chr\",\"lo\",\"hi\", 'gri'), \n dxpy.DXGTable.lexicographic_index([\n dxpy.DXGTable.lexicographic_index_column(\"name\", True, False),\n dxpy.DXGTable.lexicographic_index_column(\"chr\"),\n dxpy.DXGTable.lexicographic_index_column(\"lo\"),\n dxpy.DXGTable.lexicographic_index_column(\"hi\"),\n dxpy.DXGTable.lexicographic_index_column(\"type\")], \"search\")]\n\n default_row = [\"\", 0, 0, \"\", -1, \"\", \".\", False, -1, -1, \"\"]\n\n with open(bed_file, 'rU') as bed, dxpy.new_dxgtable(column_descs, indices=indices, mode='w') as span:\n span_table_id = span.get_id()\n\n details = {\"original_contigset\": dxpy.dxlink(ref_id)}\n if file_id != None:\n details[\"original_file\"] = dxpy.dxlink(file_id)\n if len(property_keys) != len(property_values):\n raise dxpy.AppError(\"Expected each provided property to have a corresponding value.\")\n for i in range(len(property_keys)):\n details[property_keys[i]] = property_values[i]\n span.set_details(details)\n\n span.add_types([\"gri\", \"Genes\"])\n span.rename(table_name)\n\n current_span_id = 0\n\n # where the parsing magic happens\n for line in bed:\n if line.startswith(\"track\"):\n details = span.get_details()\n details['track'] = line\n span.set_details(details)\n continue\n line = line.rstrip(\"\\n\")\n row = list(default_row)\n line = line.split(delimiter)\n validate_line(line)\n if len(line) < 12:\n raise dxpy.AppError(\"Line: \"+\"\\t\".join(line)+\" in gene model-like BED file contains less than 12 columns. Invalid BED file.\")\n\n # add parent gene track\n row = generate_gene_row(line, 0, 0, \"transcript\", default_row, -1, current_span_id)\n if row != None:\n span.add_row(row)\n current_parent_id = current_span_id\n current_span_id += 1 \n \n # add all children\n blockCount = int(line[9])\n line[10] = line[10].rstrip(\",\").split(\",\")\n blockSizes = [int(line[10][n]) for n in range(blockCount)]\n line[11] = line[11].rstrip(\",\").split(\",\")\n blockStarts = [int(line[11][n]) for n in range(blockCount)]\n\n gene_lo = int(line[1])\n gene_hi = int(line[2])\n\n # set thick* to be within the gene if outside\n thickStart = min(max(int(line[6]), gene_lo), gene_hi)\n thickEnd = max(min(int(line[7]), gene_hi), gene_lo)\n \n for i in range(blockCount):\n # look to thickStart and thickEnd to get information about the type of this region\n # if thick* are the same or cover the whole transcript then we ignore them\n # else, we partition the exons into CDS and UTR based on their boundaries\n if thickStart == thickEnd or (thickStart == gene_lo and thickEnd == gene_hi):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"exon\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n else:\n exon_lo = int(line[1])+blockStarts[i]\n exon_hi = int(exon_lo+blockSizes[i])\n\n # we're all UTR if we enter either of these\n if (exon_hi <= thickStart and line[5] == '+') or (exon_lo >= thickEnd and line[5] == '-'):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"5' UTR\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n elif (exon_hi <= thickStart and line[5] == '-') or (exon_lo >= thickEnd and line[5] == '+'):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"3' UTR\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # if this is true then we overlap CDS partially or completely\n elif (exon_lo < thickEnd and exon_hi > thickStart):\n # entirely contained\n if exon_lo >= thickStart and exon_hi <= thickEnd:\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"CDS\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n else:\n # left portion is UTR\n if exon_lo < thickStart:\n if line[5] == '+':\n UTR_type = \"5' UTR\"\n else:\n UTR_type = \"3' UTR\"\n UTR_size = (min(blockSizes[i], thickStart - exon_lo))\n span.add_row(generate_gene_row(line, \n UTR_size, \n blockStarts[i], \n UTR_type,\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # CDS portion\n CDS_size = blockSizes[i] - (max(exon_lo, thickStart) - exon_lo)\n CDS_size -= (exon_hi - min(exon_hi, thickEnd))\n CDS_start = (max(exon_lo, thickStart) - exon_lo) + blockStarts[i]\n span.add_row(generate_gene_row(line, \n CDS_size, \n CDS_start, \n \"CDS\",\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # right portion is UTR\n if exon_hi > thickEnd:\n if line[5] == '+':\n UTR_type = \"3' UTR\"\n else:\n UTR_type = \"5' UTR\"\n UTR_size = (min(blockSizes[i], exon_hi - thickEnd))\n UTR_start = blockStarts[i] + thickEnd - exon_lo\n span.add_row(generate_gene_row(line, \n UTR_size, \n UTR_start, \n UTR_type,\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n return dxpy.dxlink(span.get_id())\n\n\nparser = argparse.ArgumentParser(description='Import a local BED file as a Spans or Genes object. If multiple tracks exist in the BED file, one object will be created for each.')\nparser.add_argument('filename', help='local filename to import')\nparser.add_argument('reference', help='ID of ContigSet object (reference) that this BED file annotates')\nparser.add_argument('--file_id', default=None, help='the DNAnexus file-id of the original file. If provided, a link to this id will be added in the type details')\nparser.add_argument('--additional_type', default=[], action='append', help='This will be added to the list of object types (in addition to the type \\\"Spans\\\", or \\\"Genes\\\" which is added automatically)')\nparser.add_argument('--property_key', default=[], action='append', help='The keys in key-value pairs that will be added to the details of the object. The nth property key will be paired with the nth property value. The number of keys must equal the number of values provided')\nparser.add_argument('--property_value', default=[], action='append', help='The values in key-value pairs that will be added to the details of the object. The nth property key will be paired with the nth property value. The number of keys must equal the number of values provided')\nparser.add_argument('--tag', default=[], action='append', help='\"A set of tags (string labels) that will be added to the resulting Variants table object. (You can use tags and properties to better describe and organize your data)')\n\n\ndef import_BED(**args):\n if len(args) == 0:\n cmd_line_args = parser.parse_args(sys.argv[1:])\n args['filename'] = cmd_line_args.filename\n args['reference'] = cmd_line_args.reference\n args['file_id'] = cmd_line_args.file_id\n args['additional_type'] = cmd_line_args.additional_type\n args['property_key'] = cmd_line_args.property_key\n args['property_value'] = cmd_line_args.property_value\n args['tag'] = cmd_line_args.tag\n\n bed_filename = args['filename']\n reference = args['reference']\n file_id = args['file_id']\n additional_types = args['additional_type']\n property_keys = args['property_key']\n property_values = args['property_value']\n tags = args['tag']\n\n job_outputs = []\n # uncompresses file if necessary. Returns new filename\n bed_filename_uncomp = unpack( bed_filename )\n\n current_file = 1\n\n for import_filename in split_on_track(bed_filename_uncomp):\n try:\n bed_basename = os.path.basename(bed_filename)\n except:\n bed_basename = bed_filename\n if current_file == 1:\n name = bed_basename\n else:\n name = bed_basename+\"_\"+str(current_file)\n current_file += 1\n bed_type = detect_type(import_filename)[\"type\"]\n delimiter = detect_type(import_filename)[\"delimiter\"]\n\n print(\"Bed type is : \" + bed_type, file=sys.stderr)\n if bed_type == \"genes\":\n print(\"Importing as Genes Type\", file=sys.stderr)\n job_outputs.append(import_genes(import_filename, name, reference, file_id, additional_types, property_keys, property_values, tags, delimiter))\n elif bed_type == \"spans\" or bed_type == \"bedDetail\":\n print(\"Importing as Spans Type\", file=sys.stderr)\n if bed_type == \"bedDetail\":\n print(\"input file is in 'bedDetails' format...\", file=sys.stderr)\n bedDetail=True\n else:\n bedDetail=False\n job_outputs.append(import_spans(import_filename, name, reference, file_id, additional_types, property_keys, property_values, tags, bedDetail, delimiter))\n else:\n raise dxpy.AppError(\"Unable to determine type of BED file\")\n\n subprocess.check_call(\" \".join([\"rm\", import_filename]), shell=True)\n\n if(bed_filename != bed_filename_uncomp):\n subprocess.check_call(\" \".join([\"rm\", bed_filename_uncomp]), shell=True)\n\n print(json.dumps(job_outputs))\n return job_outputs\n\ndef validate_line(line):\n line_str = \"\\t\".join(line)\n entries = list(line)\n \n if len(entries) > 1:\n try:\n if int(entries[1]) < 0:\n raise dxpy.AppError(\"The start position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[1]))\n except ValueError:\n raise dxpy.AppError(\"One of the start values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[1]))\n \n if len(entries) > 2: \n try:\n if int(entries[2]) < 0:\n raise dxpy.AppError(\"The end position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[2]))\n except ValueError:\n raise dxpy.AppError(\"One of the end values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[2]))\n \n if len(entries) > 4: \n try:\n if entries[4] != \".\" and entries[4] != \"-\":\n float(entries[4])\n except ValueError:\n raise dxpy.AppError(\"One of the score values for one entry could not be translated to a number. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[4]))\n \n if len(entries) > 5:\n if entries[5] != \"+\" and entries[5] != \"-\" and entries[5] != \".\":\n raise dxpy.AppError(\"The strand indicated for an element was not \\\"+\\\", \\\"-\\\", or \\\".\\\"\" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[5]))\n \n if len(entries) > 6:\n try:\n if entries[6] != \".\" and entries[6] != \"-\":\n if int(entries[6]) < 0:\n raise dxpy.AppError(\"The thickStart position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[6]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickStart values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[6]))\n \n if len(entries) > 7: \n try:\n if entries[7] != \".\" and entries[7] != \"-\":\n if int(entries[7]) < 0:\n raise dxpy.AppError(\"The thickEnd position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[7]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickEnd values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[7]))\n \n if len(entries) > 9:\n try:\n if int(entries[9]) < 0:\n raise dxpy.AppError(\"The number of exons (blockCount) for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[9]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickEnd values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[9]))\n \n if len(entries) > 10: \n try:\n entries[10] = entries[10].rstrip(\",\").split(\",\")\n blockStarts = [int(entries[10][n]) for n in range(int(entries[9]))]\n except:\n raise dxpy.AppError(\"Could not parse the blockSizes entry as a comma-separated list of integers \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[10]))\n \n if len(entries) > 11:\n try:\n entries[11] = entries[11].rstrip(\",\").split(\",\")\n blockStarts = [int(entries[11][n]) for n in range(int(entries[9]))]\n except:\n raise dxpy.AppError(\"Could not parse the blockStarts entry as a comma-separated list of integers \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[11]))\n\n\ndef main(**args):\n import_BED(**args)\n\nif __name__ == '__main__':\n import_BED()\n","sub_path":"src/python/dxpy/scripts/dx_bed_to_spans.py","file_name":"dx_bed_to_spans.py","file_ext":"py","file_size_in_byte":31038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"580490568","text":"import pygame\nfrom pygame.locals import *\n\n\nclass Block(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.PINK = (0, 200, 0)\n self.image = pygame.Surface((32,32))\n self.image.fill(self.PINK)\n self.image.convert()\n self.rect = pygame.Rect(x, y, 32, 32)","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"397563020","text":"import joblib\nimport numpy as np\nimport pandas as pd\nimport uvicorn\n\nfrom fastapi import status\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom app.app import *\n\napp = FastAPI()\n\ntopic_data = pd.read_csv(\"data/topic_data.csv\")\n\n@app.get(\"/\")\ndef hello():\n return {\"message\":\"Hello Sherlock\"}\n\n@app.get('/top_10_clusters')\nasync def top_10_clusters():\n top_10_labels = [0, 3, 2, 5, 34, 33, 18, 22, 12, 41]\n LDA_model = joblib.load('models/LDA_models_50.pkl')\n \n results = [str(top_10_words(LDA_model, label)) for label in top_10_labels]\n res = \"-\".join(results)\n return res\n\n@app.get('/get_score')\nasync def get_score(text: str):\n scores = calculate_score(text)\n res = str(list(scores.values())).strip('[]')\n return res\n\n@app.get('/similar_tickets')\nasync def similar_tickets(label: int, nb_tickets: int):\n return topic_data[topic_data.topic == label][:nb_tickets][['Number', 'Description']]\n\n@app.get('/LDA_predict')\nasync def LDA_predict(model_name: str, data: str):\n embedded_data = preprocess(data)\n LDA_model = joblib.load('models/LDA_models_50.pkl')\n prediction = LDA_model.transform(embedded_data).argmax(axis=1)[0]\n \n top10Words = top_10_words(LDA_model, prediction)\n top10Words = ' '.join(top10Words)\n \n result = str(prediction) + \" - \" + top10Words\n\n return result\n\n\n@app.get('/predict')\nasync def predict(model_name: str, data: str):\n embedded_data = preprocess(data)\n embedded_data = np.atleast_2d(embedded_data)\n \n model = joblib.load('models/{}'.format(model_name))\n \n prediction = str(model.predict(embedded_data)[0])\n \n \n return prediction\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)\n\n\"\"\"\nTo cover:\n- possible return types: not nympy array, etc\n\"\"\"","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"30208432","text":"import pytest\n\nfrom .common import simple_ok_check, simple_nok_check\n\n\ndef test_max_file_lines_ok():\n code = \"\\n\".join([\"tool\"] * 1000)\n simple_ok_check(code)\n\n\ndef test_max_file_lines_nok():\n code = \"\\n\".join([\"tool\"] * 1001)\n simple_nok_check(code, \"max-file-lines\", 1001)\n\n\n# fmt: off\n@pytest.mark.parametrize('code', [\n\"\"\"\n#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\",\n])\ndef test_max_line_length_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\n#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\",\n])\ndef test_max_line_length_nok(code):\n simple_nok_check(code, 'max-line-length')\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nfunc foo():\n var x\n\n\n\"\"\",\n\"\"\"\nfunc foo():\n pass\n\"\"\",\n\"\"\"\nfunc foo():\n\tx.bar()\n\"\"\",\n])\ndef test_trailing_ws_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"func foo():\n pass \n\"\"\",\n\"\"\"func foo():\n pass \n\"\"\",\n\"\"\"func foo():\n pass\t\n\"\"\",\n\"\"\"func foo():\n pass \t \n\"\"\",\n])\ndef test_trailing_ws_nok(code):\n simple_nok_check(code, 'trailing-whitespace')\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nfunc foo():\n pass\n\"\"\",\n\"\"\"\nfunc foo():\n\tpass\n\"\"\",\n])\ndef test_mixed_tabs_and_spaces_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nclass X:\n func foo():\n \tpass\n\"\"\",\n\"\"\"\nclass X:\n\tfunc foo():\n\t pass\n\"\"\",\n])\ndef test_mixed_tabs_and_spaces_nok(code):\n simple_nok_check(code, 'mixed-tabs-and-spaces', line=4)\n","sub_path":"tests/linter/test_format_checks.py","file_name":"test_format_checks.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"319792351","text":"import socket\nimport time\nimport httplib\nimport json\nfrom urllib import urlencode\nfrom threading import Lock, Event\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom graphite.node import LeafNode, BranchNode\nfrom graphite.readers import FetchInProgress\nfrom graphite.logger import log\nfrom graphite.util import unpickle\nfrom graphite.intervals import IntervalSet, Interval\nfrom graphite import opentsdb\nfrom graphite import tree\n\n\nclass RemoteStore(object):\n lastFailure = 0.0\n available = property(lambda self: time.time() - self.lastFailure > settings.REMOTE_RETRY_DELAY)\n\n def __init__(self, host):\n self.host = host\n\n def find(self, query):\n request = FindRequest(self, query)\n request.send()\n return request\n\n def fail(self):\n self.lastFailure = time.time()\n\n\nclass OpenTSDBRemoteStore(object):\n lastFailure = 0.0\n available = property(lambda self: time.time() - self.lastFailure > settings.REMOTE_RETRY_DELAY)\n\n def __init__(self, host):\n self.host = host\n\n def find(self, query):\n log.info(\"OpenTSDBRemoteStore:find \" + str(query))\n request = OpenTSDBFindRequest(self, query)\n request.send()\n return request\n\n def fail(self):\n self.lastFailure = time.time()\n\n\nclass FindRequest(object):\n __slots__ = ('store', 'query', 'connection',\n 'failed', 'cache_key', 'cached_result')\n\n def __init__(self, store, query):\n self.store = store\n self.query = query\n self.connection = None\n self.failed = False\n\n if query.start_time:\n start = query.start_time - (query.start_time % settings.FIND_CACHE_DURATION)\n else:\n start = \"\"\n\n if query.end_time:\n end = query.end_time - (query.end_time % settings.FIND_CACHE_DURATION)\n else:\n end = \"\"\n\n self.cache_key = \"find:%s:%s:%s:%s\" % (store.host, query.pattern, start, end)\n self.cached_result = None\n\n def send(self):\n log.info(\"FindRequest.send(host=%s, query=%s) called\" % (self.store.host, self.query))\n\n self.cached_result = cache.get(self.cache_key)\n if self.cached_result is not None:\n log.info(\n \"FindRequest(host=%s, query=%s) using cached result\" % (\n self.store.host, self.query)\n )\n return\n\n self.connection = HTTPConnectionWithTimeout(self.store.host)\n self.connection.timeout = settings.REMOTE_FIND_TIMEOUT\n\n query_params = [\n ('local', '1'),\n ('format', 'pickle'),\n ('query', self.query.pattern),\n ]\n if self.query.start_time:\n query_params.append(('from', self.query.start_time))\n\n if self.query.end_time:\n query_params.append(('until', self.query.end_time))\n\n query_string = urlencode(query_params)\n\n try:\n self.connection.request('GET', '/metrics/find/?' + query_string)\n except:\n log.exception(\n \"FindRequest.send(host=%s, query=%s) exception during request\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n self.failed = True\n\n def get_results(self):\n if self.failed:\n return\n\n if self.cached_result is not None:\n results = self.cached_result\n else:\n if self.connection is None:\n self.send()\n\n try:\n response = self.connection.getresponse()\n assert response.status == 200, \"received error response %s - %s\" % (\n response.status, response.reason)\n result_data = response.read()\n results = unpickle.loads(result_data)\n\n except:\n log.exception(\n \"FindRequest.get_results(host=%s, query=%s) exception processing response\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n return\n\n cache.set(self.cache_key, results, settings.FIND_CACHE_DURATION)\n\n for node_info in results:\n if node_info.get('isLeaf'):\n reader = RemoteReader(self.store, node_info, bulk_query=self.query.pattern)\n node = LeafNode(node_info['metric_path'], reader)\n else:\n node = BranchNode(node_info['metric_path'])\n\n node.local = False\n yield node\n\n\nclass OpenTSDBFindRequest(object):\n __slots__ = ('store', 'query')\n\n def __init__(self, store, query):\n self.store = store\n self.query = query\n\n def _query_prefix(self):\n return self.query.pattern\n\n def send(self):\n pass\n\n def get_results(self):\n client = opentsdb.API(self.store.host)\n try:\n results = tree.OpenTSDBMetricsMeta(client).find(self._query_prefix())\n except:\n log.exception(\n \"OpenTSDBFindRequest.get_results(host=%s, query=%s) exception processing response\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n return\n\n # cache.set(self.cache_key, results, settings.FIND_CACHE_DURATION)\n\n log.info(\"RESULTS: \" + str(results))\n for node_info in results:\n if node_info.get('isLeaf'):\n reader = OpenTSDBRemoteReader(self.store, node_info, bulk_query=self.query.pattern)\n node = LeafNode(node_info['metric_path'], reader)\n else:\n node = BranchNode(node_info['metric_path'])\n\n node.local = False\n yield node\n\n\nclass RemoteReader(object):\n __slots__ = ('store', 'metric_path', 'intervals', 'query', 'connection')\n cache_lock = Lock()\n request_cache = {}\n request_locks = {}\n request_times = {}\n\n def __init__(self, store, node_info, bulk_query=None):\n self.store = store\n self.metric_path = node_info['metric_path']\n self.intervals = IntervalSet([Interval(*args) for args in node_info['intervals']])\n self.query = bulk_query or node_info['metric_path']\n self.connection = None\n\n def __repr__(self):\n return '' % (id(self), self.store.host)\n\n def get_intervals(self):\n return self.intervals\n\n def fetch(self, start_time, end_time):\n query_params = [\n ('target', self.query),\n ('format', 'pickle'),\n ('local', '1'),\n ('noCache', '1'),\n ('from', str(int(start_time))),\n ('until', str(int(end_time)))\n ]\n query_string = urlencode(query_params)\n urlpath = '/render/?' + query_string\n url = \"http://%s%s\" % (self.store.host, urlpath)\n\n # Quick cache check up front\n self.clean_cache()\n cached_results = self.request_cache.get(url)\n if cached_results:\n for series in cached_results:\n if series['name'] == self.metric_path:\n time_info = (series['start'], series['end'], series['step'])\n return (time_info, series['values'])\n\n # Synchronize with other RemoteReaders using the same bulk query.\n # Despite our use of thread synchronization primitives, the common\n # case is for synchronizing asynchronous fetch operations within\n # a single thread.\n (request_lock, wait_lock, completion_event) = self.get_request_locks(url)\n\n if request_lock.acquire(False): # we only send the request the first time we're called\n try:\n log.info(\"RemoteReader.request_data :: requesting %s\" % url)\n self.connection = HTTPConnectionWithTimeout(self.store.host)\n self.connection.timeout = settings.REMOTE_FETCH_TIMEOUT\n self.connection.request('GET', urlpath)\n except:\n completion_event.set()\n self.store.fail()\n log.exception(\"Error requesting %s\" % url)\n raise\n\n def wait_for_results():\n if wait_lock.acquire(False): # the FetchInProgress that gets waited on waits for the actual completion\n try:\n response = self.connection.getresponse()\n if response.status != 200:\n raise Exception(\"Error response %d %s from %s\" % (response.status, response.reason, url))\n\n pickled_response = response.read()\n results = unpickle.loads(pickled_response)\n self.cache_lock.acquire()\n self.request_cache[url] = results\n self.cache_lock.release()\n completion_event.set()\n return results\n except:\n completion_event.set()\n self.store.fail()\n log.exception(\"Error requesting %s\" % url)\n raise\n\n else: # otherwise we just wait on the completion_event\n completion_event.wait(settings.REMOTE_FETCH_TIMEOUT)\n cached_results = self.request_cache.get(url)\n if cached_results is None:\n raise Exception(\"Passive remote fetch failed to find cached results\")\n else:\n return cached_results\n\n def extract_my_results():\n for series in wait_for_results():\n if series['name'] == self.metric_path:\n time_info = (series['start'], series['end'], series['step'])\n return (time_info, series['values'])\n\n return FetchInProgress(extract_my_results)\n\n def clean_cache(self):\n self.cache_lock.acquire()\n try:\n if len(self.request_locks) >= settings.REMOTE_READER_CACHE_SIZE_LIMIT:\n log.info(\"RemoteReader.request_data :: clearing old from request_cache and request_locks\")\n now = time.time()\n for url, timestamp in self.request_times.items():\n age = now - timestamp\n if age >= (2 * settings.REMOTE_FETCH_TIMEOUT):\n del self.request_locks[url]\n del self.request_times[url]\n if url in self.request_cache:\n del self.request_cache[url]\n finally:\n self.cache_lock.release()\n\n def get_request_locks(self, url):\n self.cache_lock.acquire()\n try:\n if url not in self.request_locks:\n self.request_locks[url] = (Lock(), Lock(), Event())\n self.request_times[url] = time.time()\n return self.request_locks[url]\n finally:\n self.cache_lock.release()\n\n\nclass OpenTSDBRemoteReader(object):\n __slots__ = ('store', 'metric_path', 'intervals', 'query')\n request_times = {}\n\n def __init__(self, store, node_info, bulk_query=None):\n self.store = store\n self.metric_path = node_info['metric_path']\n self.query = bulk_query or node_info['metric_path']\n\n def __repr__(self):\n return '' % (id(self), self.store.host)\n\n def get_intervals(self):\n return IntervalSet([Interval(float(\"-inf\"), float(\"inf\"))])\n\n def _make_time_info(self, ts):\n dps = ts['dps']\n timestamps = map(int, dps.keys())\n start_time = min(timestamps)\n end_time = max(timestamps)\n step = (end_time - start_time) / len(timestamps)\n return (start_time, end_time, step)\n\n def _make_values(self, ts):\n return [item[1] for item in sorted(ts['dps'].items())]\n\n def fetch(self, start_time, end_time):\n log.info(\"FETCH: \" + str(start_time) + \", \" + str(end_time))\n api = opentsdb.API(self.store.host)\n results = api.query(self.metric_path, start_time, end_time)\n log.info(\"RESULTS: %s\" % str(results)[:100])\n def _extract_my_results():\n for series in results:\n log.info(\"SERIES: %s\" % series.keys())\n if series['metric'] == self.metric_path:\n time_info = self._make_time_info(series)\n data = (time_info, self._make_values(series))\n log.info(\"DATA: \" + str(data)[:400])\n return data\n\n return FetchInProgress(_extract_my_results)\n\n\n# This is a hack to put a timeout in the connect() of an HTTP request.\n# Python 2.6 supports this already, but many Graphite installations\n# are not on 2.6 yet.\n\nclass HTTPConnectionWithTimeout(httplib.HTTPConnection):\n timeout = 30\n\n def connect(self):\n msg = \"getaddrinfo returns an empty list\"\n for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):\n af, socktype, proto, canonname, sa = res\n try:\n self.sock = socket.socket(af, socktype, proto)\n try:\n # default self.timeout is an object() in 2.6\n self.sock.settimeout(float(self.timeout))\n except:\n pass\n self.sock.connect(sa)\n self.sock.settimeout(None)\n except socket.error as e:\n msg = e\n if self.sock:\n self.sock.close()\n self.sock = None\n continue\n break\n if not self.sock:\n raise socket.error(msg)\n","sub_path":"webapp/graphite/remote_storage.py","file_name":"remote_storage.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"391059750","text":"from flask import Blueprint\r\nfrom flask import render_template\r\nfrom flask import redirect\r\nfrom flask import url_for\r\nfrom flask import request\r\nfrom flask import flash\r\n\r\nfrom mdizabela.mod.access import access\r\n\r\nfrom mdizabela.models import db\r\nfrom mdizabela.models import SysUserLevel\r\n\r\nfrom .forms import UpraveniUserLevelForm\r\nfrom .forms import VytvoritUserLevelForm\r\n\r\nmod_user_level = Blueprint('mod_user_level', __name__)\r\n\r\n####\r\n#### přehled uživatelských úrovní\r\n####\r\n@mod_user_level.route('/prehled/', methods=['GET'])\r\n@access('admin')\r\ndef view_user_level():\r\n user_level = SysUserLevel.query.order_by(SysUserLevel.id.asc()).all()\r\n add_user_level_form = VytvoritUserLevelForm()\r\n upraveni_form = UpraveniUserLevelForm()\r\n\r\n return render_template('mod_user_level/prehled_user_level.jinja', pridat_form = add_user_level_form, upraveni_form = upraveni_form, levels = user_level)\r\n\r\n####\r\n#### Přidání nového uživatele\r\n####\r\n@mod_user_level.route('/pridat/', methods=['POST'])\r\n@access('admin')\r\ndef pridat_user_level():\r\n add_user_level_form =VytvoritUserLevelForm(request.form)\r\n\r\n if add_user_level_form.validate():\r\n level_exist = SysUserLevel.query.filter_by(ident=add_user_level_form.ident.data).first()\r\n if not level_exist:\r\n level = SysUserLevel()\r\n level.ident = add_user_level_form.ident.data\r\n level.nazev = add_user_level_form.nazev.data\r\n level.popis = add_user_level_form.popis.data\r\n\r\n db.session.add(level)\r\n db.session.commit()\r\n\r\n flash(f'Level {add_user_level_form.ident.data} byl úspěšně vytvořen.', 'alert-success')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n flash(f'Uživatelský level {add_user_level_form.ident.data} již existuje.', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n for error in add_user_form.errors.values():\r\n for item in error:\r\n flash(f'{item}', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_prehled_uzivatelu'))\r\n\r\n@mod_user_level.route('/upravit/', methods=['POST'])\r\n@access('admin')\r\ndef upravit_user_level(level_id):\r\n upraveni_form = UpraveniUserLevelForm(request.form)\r\n\r\n if upraveni_form.validate():\r\n level = SysUserLevel.query.filter_by(id = level_id).first()\r\n if level.ident == upraveni_form.ident.data:\r\n if level.nazev != upraveni_form.nazev.data:\r\n level.nazev = upraveni_form.nazev.data\r\n flash(f'Název pro uživatelské oprávnění {level.ident} byl úspěšně změněno na {level.nazev}.', 'alert-success')\r\n\r\n if level.popis != upraveni_form.popis.data:\r\n level.popis = upraveni_form.popis.data\r\n if len(upraveni_form.popis.data) == 0:\r\n flash(f'Popis pro uživatelské oprávnění {level.ident} byl úspěšně smazán.', 'alert-success')\r\n else:\r\n flash(f'Popis pro uživatelské oprávnění {level.ident} byl úspěšně změněno na {level.popis}.', 'alert-success')\r\n\r\n db.session.add(level)\r\n db.session.commit()\r\n\r\n else:\r\n flash(f'Pokus o změnu identifikátoru.', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n for error in upraveni_form.errors.values():\r\n for item in error:\r\n flash(f'{item}', 'alert-danger')\r\n\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n","sub_path":"mdizabela/mod/user_level/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"447284176","text":"import numpy as np\r\nfrom collections import defaultdict\r\nfrom scipy.optimize import minimize\r\npd.set_option('display.max_columns', None)\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\ndef optimize_parameter(\r\n data, \r\n start_variance= 20 ** 2, \r\n beta_square = 3 ** 2,\r\n verbose = True,\r\n tolerance = 1e-2,\r\n):\r\n '''Fits the parameters in B-T model.\r\n Args:\r\n winners: The array of winners for each of N contests, of shape [N, 2].\r\n losers: The array of losers for each of N contests, of shape [N, 2].\r\n surface: The array of surfaces for each of N contest, of shape [N, 3].\r\n beta: The uncontral variances of the game\r\n start_variance_1: The initial variance of the surface 1\r\n verbose: Whether or not to print the progress of the optimisation.\r\n tolerance: The tolerance required for the optimisation to successfully terminate.\r\n '''\r\n def fun_to_minimize(theta):\r\n # Constrain\r\n variance = theta \r\n _, discrepancy = calculate_ratings(data = data,start_mean = 1500,start_var = variance ,beta_square = beta_square,k = 0.0001,gamma_q =1/2)\r\n \r\n if verbose:\r\n print('variance: {} ; discrepancy: {}'.format(variance[0],discrepancy[0]))\r\n return discrepancy\r\n \r\n opt_result = minimize(fun_to_minimize,\r\n np.array([start_variance],dtype='float'),\r\n method='Nelder-Mead',\r\n tol=tolerance,)\r\n return (opt_result.success, {'variance':opt_result.x[0]})\r\n","sub_path":"Lin Zhe Ching's Thesis/code/BT_model/optimize_parameter.py","file_name":"optimize_parameter.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"133575298","text":"#!/bin/python\nimport os.path as path\nimport os, re, sys, shutil, zipfile\nfrom distutils.dir_util import copy_tree\n\nORIGINAL_DIRECTORY = path.abspath(path.join(__file__ , \"../..\"))\nWORKING_DIRECTORY = path.abspath(path.join(__file__ , \"../out/miniorange-oauth-client\"))\nAUTOLOAD = path.abspath(path.join(WORKING_DIRECTORY, \"_autoload.php\"))\nSETTINGS = path.abspath(path.join(WORKING_DIRECTORY, \"mo_oauth_settings.php\"))\nBASE_DECREMENTAL = 10\n\n\ndef get_version(file):\n f = open(file)\n string = f.read()\n matched_lines = [line for line in string.split('\\n') if \"VERSION\" in line]\n f.close()\n if len(matched_lines) > 1:\n return false\n return matched_lines[0].split(',')[1].split('\\'')[1].split('_')[1].upper();\n\n\ndef write_version(file):\n f = open(file)\n string = f.read()\n matched_lines = [line for line in string.split('\\n') if \"Version\" in line]\n f.close()\n version = matched_lines[0].split(\"Version\")[1].split(\": \")[1].split(\".\")\n old_version = ''\n for y in version:\n old_version = old_version + y + '.'\n\n new_version = ''\n for x in compute_version(version):\n new_version = new_version + x + \".\"\n\n\n\n new_version = new_version[:-1]\n old_version = old_version[:-1]\n print(\"Old Version: \" + old_version)\n print(\"New Version: \" + new_version)\n f = open(file, \"w\")\n f.write(string.replace(old_version, new_version))\n f.close()\n return new_version\n\n\ndef compute_version(current_version):\n version_to_compute = get_version(AUTOLOAD)\n decremental = BASE_DECREMENTAL\n if version_to_compute == \"ENTERPRISE\":\n decremental = 0\n if version_to_compute == \"PREMIUM\":\n decremental = BASE_DECREMENTAL * 1\n if version_to_compute == \"STANDARD\":\n decremental = BASE_DECREMENTAL * 2\n if version_to_compute == \"FREE\":\n decremental = BASE_DECREMENTAL * 3\n\n current_version[0] = str(int(current_version[0]) - decremental)\n return current_version\n\n\ndef manage_dirs():\n if not os.path.exists(WORKING_DIRECTORY):\n os.makedirs(WORKING_DIRECTORY)\n print(\"Directory \" + WORKING_DIRECTORY + \" Created \")\n else:\n print(\"Directory \" + WORKING_DIRECTORY + \" already exists\")\n\n print(\"Removing entire build dir...\")\n delete_files_from(WORKING_DIRECTORY)\n\n\ndef delete_files_from(folder_path):\n for file_object in os.listdir(folder_path):\n file_object_path = os.path.join(folder_path, file_object)\n if os.path.isfile(file_object_path):\n os.remove(file_object_path)\n else:\n shutil.rmtree(file_object_path)\n\ndef copy_files():\n print(\"Copying files...\")\n copy_tree(path.abspath(path.join(ORIGINAL_DIRECTORY, \"classes\")), path.abspath(path.join(WORKING_DIRECTORY, \"classes\")))\n copy_tree(path.abspath(path.join(ORIGINAL_DIRECTORY, \"resources\")), path.abspath(path.join(WORKING_DIRECTORY, \"resources\")))\n shutil.copy(path.abspath(path.join(ORIGINAL_DIRECTORY, \"mo_oauth_settings.php\")), WORKING_DIRECTORY)\n shutil.copy(path.abspath(path.join(ORIGINAL_DIRECTORY, \"_autoload.php\")), WORKING_DIRECTORY)\n\ndef generate_version():\n basepath = path.abspath(path.join(WORKING_DIRECTORY, \"classes\"))\n version = get_version(AUTOLOAD)\n if version == \"PREMIUM\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n if version == \"STANDARD\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n delete_files_from(path.abspath(path.join(basepath, \"Premium\")))\n if version == \"FREE\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n delete_files_from(path.abspath(path.join(basepath, \"Premium\")))\n delete_files_from(path.abspath(path.join(basepath, \"Standard\")))\n\ndef prepare_plugin(new_version):\n output_filename = 'mo_oauth_client_' + new_version\n shutil.make_archive(output_filename, 'zip', path.abspath(path.join(WORKING_DIRECTORY, \"..\")))\n print(\"Archive Successfully created at: \" + path.abspath(path.join(WORKING_DIRECTORY, output_filename + \".zip\")))\n\nmanage_dirs()\ncopy_files()\ngenerate_version()\nnew_version = write_version(path.abspath(path.join(WORKING_DIRECTORY, \"mo_oauth_settings.php\")))\nzipfile = prepare_plugin(new_version)\n","sub_path":"wp-content/plugins/miniorange-oauth-oidc-single-sign-on/build/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"334582478","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport config\n\nimport tweepy\nimport random\nfrom datetime import datetime\n\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\n\nauth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret)\nauth.set_access_token(config.access_key, config.access_secret)\napi = tweepy.API(auth)\n\n\nmonth_map = {\n '1': 'January',\n '2': 'February',\n '3': 'March',\n '4': 'April',\n '5': 'May',\n '6': 'June',\n '7': 'July',\n '8': 'August',\n '9': 'September',\n '10': 'October',\n '11': 'November',\n '12': 'December'\n}\n\n\nmessages = [\n 'Happy day!',\n 'Have a nice day!',\n 'How\\'s your day going?',\n 'One of the best days of the year!',\n 'Remember to smile today!',\n 'Today is yesterday\\'s tomorrow!',\n 'Today will be tomorrow\\'s yesterday!',\n 'Another day!',\n 'Today is great!',\n 'What\\'s the news today?',\n 'The week\\'s going by so fast! Enjoy today!',\n 'Enjoy your time on this earth. Especially today!',\n 'Make today special!',\n 'Make the most of your day today!',\n 'What will today bring?',\n 'Have a great day!',\n 'What a beautiful day!'\n]\n\n\n# get current date string\ndatetime_now = datetime.now()\n\nmonth_int = datetime_now.strftime('%m')\nmonth_str = month_map[str(int(month_int))]\n\nday_int = datetime_now.strftime('%d')\nday_str = str(int(day_int))\n\n\n# construct wiki url\nwiki_link = 'https://en.wikipedia.org/wiki/' + month_str + '_' + day_str\n\n\n# commit tweet\ntweet_components = [\n random.choice(messages),\n month_str,\n day_str + ':',\n wiki_link\n]\n\napi.update_status(' '.join(tweet_components))\n\n\n\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486778927","text":"# -*- coding: utf-8 -*-\n# import os\n# import log_func as log\n# from log_func import log_log\n\nsettings = {\n # 设置templates路径:\n # 'template_path': os.path.join(os.path.dirname(__file__), \"templates\"),\n\n # 设置静态文件解析路径:\n # 'static_path': os.path.join(os.path.dirname(__file__), \"static\"),\n\n # 设置防跨站请求攻击:默认为False,即不可防御。\n 'xsrf_cookies': False,\n\n # 设置登陆路径,未登陆用户在操作时跳转会用到这个参数:默认为@tornado.web.authenticated\n # 'login_url': \"/login\",\n\n # 设置调试模式:默认为False,即不是调试模式\n 'debug': True,\n\n # 设置cookie密钥:默认为字符串\"secure cookies\"\n 'cookie_secret': \"dskfhisdjklagkfdklag;lkjasdklgjkldsjaklgjkldsfksdklf\",\n\n # 设置是否自动编码:不设置默认为自动编码。\n 'autoescape': None,\n\n # 设置template_loader,可以从独立的路径中导入template:其中your_moudle为自己定义的模块,ZipLoader是tornado.template.BaseLoader的子类\n # 'template_loader': your_moudle.ZipLoader,\n\n # 设置gzip压缩:\n # 'gzip': True,\n\n # 设置静态路径头部:默认是\"/static/\"\n # 'static_url_prefix': \"/mystatic/\",\n\n # 设置静态文件处理类:默认是tornado.web.StaticFileHandler\n # 'static_handler_class': MyStaticFileHandler,\n\n # 设置静态文件的参数:默认为空字典。\n # 'static_handler_args': {\"key1\": \"value1\", \"key2\": \"value2\"},\n\n # 设置日志处理函数\n # 'log_function': log_log\n}\n","sub_path":"celery_test/new_test/tornado_setting.py","file_name":"tornado_setting.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"41938275","text":"__author__ = 'heocon'\nimport dryscrape\nfrom threading import Thread\nimport logging\n\nfilename='data.xml'\narg1='MacBook'\narg2='stuxnet'\nlogfile='file.log'\n\nclass client():\n\n def __init__(self):\n self.data = []\n #self.file={}\n self.file1={}\n self.file2={}\n self.threads = []\n #define logger\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M',\n filename=logfile,\n filemode='a')\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n # define a Handler which writes INFO messages or higher to the sys.stderr\n\n\n def google(self,arg,savefile):\n #def google(self,arg):\n sess = dryscrape.Session(base_url = 'http://scholar.google.fr')\n logging.info('Visiting in google scholar')\n #print 'Visiting in google scholar'\n sess.visit('/scholar?hl=en&q='+arg)\n content= sess.xpath('//*[@class=\"gs_rs\"]')\n if content==None:\n logging.error('Site is invalid when visiting')\n return -1\n logging.debug('Scrapping content')\n #print 'Scrapping content'\n author=sess.xpath('//*[@class=\"gs_a\"]')\n logging.debug('Scrapping author')\n #print 'Scrapping author'\n title=sess.xpath('//*[@class=\"gs_rt\"]')\n logging.debug('Scrapping title')\n with open(savefile,'a') as f:\n logging.info('Star writing in example.log with google search')\n f.write('\\n')\n f.write('\\n')\n for n in range(0,len(content)-1):\n logging.info('Write in each row %d of google search' %n)\n f.write(' \\n')\n a=self.namespace={\"title\":title[n].text(),\"author\":author[n].text(),\"content\":content[n].text()}\n #self.file1[n] = a\n if a['title']==None:\n logging.error('Site is invalid in google search')\n return -1\n else:\n for key1 in a.keys():\n if key1==None:\n logging.error(\"Site is invalid\")\n exit()\n b=' <'+str(key1)+'>'+str(a[key1])+'\\n'\n f.write(b)\n f.write(' \\n')\n f.write('\\n')\n def amazon(self,arg,savefile):\n #def amazon(self,arg):\n sess=dryscrape.Session(base_url = 'http://www.amazon.com')\n logging.info('Visiting in amazon')\n #print 'Visiting in amazon'\n sess.visit('/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords='+arg)\n\n # save in the dictionary form\n with open(savefile,'a') as f:\n logging.info('Writing in example.log with amazon search')\n f.write('\\n')\n f.write('\\n')\n for i in range(0,15):\n f.write(' \\n')\n a=self.search_amazon(i,sess)\n logging.info('Write in each row %d of amazon search' %i)\n #self.file1[i] = a\n if a['name']==None:\n logging.error(\"Site is invalid in amazon search\")\n return -1\n else:\n for key in a.keys():\n b=' <'+str(key)+'>'+str(a[key])+'\\n'\n f.write(b)\n f.write(' \\n')\n f.write('\\n')\n\n\n def search_amazon(self,i,sess):\n name='//li[@id=\"result_'+str(i)+'\\\"]'\n nodes=sess.xpath(name)\n logging.debug('Scrapping item')\n #print 'Scraping item'\n ref=None\n name=None\n price=None\n descrip=None\n otherprice=None\n shipping=None\n star=None\n for node in nodes:\n node2=node.xpath('div/div[2][@class=\"a-row a-spacing-mini\"]')\n if node2==None:\n logging.error('Website is invalid when visiting amazon')\n return -1\n node3=node.xpath('div/div[3][@class=\"a-row a-spacing-mini\"]')\n node4=node.xpath('div/div[4][@class=\"a-row a-spacing-top-mini a-spacing-mini\"]')\n node5=node.xpath('div/div[5][@class=\"a-row a-spacing-none\"]')\n for a in node2:\n a_1=a.xpath('div/a[@href]')\n logging.debug('Scrapping title and link')\n #print 'Scrapping title and link'\n for b in a_1:\n ref=b['href']\n name=b['title']\n if name==None:\n logging.error('Name is invalid')\n return -1\n for a in node3:\n f=a.xpath('div')\n i=len(f)\n logging.debug('Scrapping price, description, and other_price')\n #print 'Scrapping price, description, and other_price'\n a_2=a.xpath('div/a/span[@class=\"a-size-base a-color-price s-price a-text-bold\"]')\n #if a_2==None:\n # logging.error('Price is invalid')\n # return -1\n a_3=a.xpath('div[2]/div/span[@class=\"a-size-small a-color-price\"]')\n #if a_3==None:\n # logging.error('Price is invalid')\n # return -1\n a_4=a.xpath('div['+str(i)+']/a/span[@class=\"a-size-base a-color-price a-text-bold\"]')\n #if a_4==None:\n # logging.error('Price is invalid')\n # return -1\n for b in a_2:\n price=b.text()\n for c in a_3:\n descrip=c.text()\n for d in a_4:\n otherprice=d.text()\n for a in node4:\n logging.debug('Scrapping shipping content')\n #print 'Scrapping shipping content'\n a_5=a.xpath('div/span[@class=\"a-size-small a-color-secondary\"]')\n\n for b in a_5:\n shipping=b.text()\n for a in node5:\n logging.debug('Scrapping star of item')\n #print 'Scrapping star of item'\n star= a.text()\n # save in dictionary form\n self.namespace={'ref':ref,'name':name,'price_new':price,'price_used':otherprice,'description':descrip,'shipping':shipping,'star':star}\n return self.namespace\n #def save_file(self,filename):\n def save_file(self,filename,file):\n with open(filename,'w') as f:\n row=file\n logging.info('Save in example.log')\n #print 'Save in example.log'\n ##row = file\n #f.write('\\n')\n #f.write('\\n')\n #for i in range(0,len(row)-1):\n # f.write(' \\n')\n for key in row.keys():\n if key==None:\n logging.error('Site is invalid')\n exit()\n a=' <'+str(key)+'>'+str(row[key])+'\\n'\n f.write(a)\n # f.write(' \\n')\n #f.write('\\n')\n\n\n def go(self):\n #self.google(arg2)\n #self.amazon(arg1)\n t1 = Thread(target=self.google,args=(arg2,filename))\n t2 = Thread(target=self.amazon,args=(arg1,filename))\n\n t1.start()\n t2.start()\n self.threads.append(t1)\n self.threads.append(t2)\n\n [t.join() for t in self.threads]\ndef main():\n a = client()\n a.go()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n","sub_path":"task_2/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":8034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"255080165","text":"\"\"\"\ntprime.py\n\nA poisitive integer is considered to be a\nT-prime if it has exactly 3 divisors.\n\nThe problem states that you are given an\narray of n positive integers and must determine\nwhether or not they are T-prime\n\"\"\"\ndef brute_force(nums):\n tprimes = []\n for n in nums:\n if _brute_force(n) == True:\n tprimes.append(n)\n return tprimes\n\ndef _brute_force(n):\n divisors = 1\n for i in range(1,n):\n if divisors > 3:\n return False\n if n % i == 0:\n divisors += 1\n \n #This last little bit of logic is because\n #a prime number is an edgecase\n if divisors < 3:\n return False\n return True","sub_path":"Algorithms/tprime.py","file_name":"tprime.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"402783975","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom csv import writer\n\nurl = \"https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page=1\"\ncurrent = 0\nnext_page = 2\n\nwhile True:\n response = requests.get(url).text\n soup = BeautifulSoup(response, \"html.parser\")\n\n divs = soup.select(\"._1-2Iqu\")\n if not divs:\n break\n\n with open(\"rahul_mi.csv\", \"a\", newline=\"\") as file:\n csv_writer = writer(file)\n if not current:\n csv_writer.writerow([\"Mobile Name\", \"Price\"])\n\n for div in divs:\n mobile_name = div.select(\"._3wU53n\")[0].get_text()\n mobile_price = div.select(\"._1vC4OE\")[0].get_text()[1:]\n # print(f\"{mobile_name} --> {mobile_price}\")\n csv_writer.writerow([mobile_name, mobile_price])\n\n a_tags = soup.select(\"._2Xp0TH\")\n\n for tag in a_tags:\n if not current:\n pass\n else:\n url = f\"https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page={next_page}\"\n # print(url)\n print(f\"😈 Scarping Done {next_page}😈\")\n next_page += 1\n break\n current += 1\n","sub_path":"Web Scraping with BeautifulSoup/Flipkart Scripting/mi_phone.py","file_name":"mi_phone.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"286575885","text":"def recursion(ten,count = 0):\n if ten == 0 or ten == 1:\n return count\n elif ten % 2 == 0:\n count = count + 1\n ten = ten / 2\n return recursion(ten,count)\n elif ten % 2 == 1:\n count = count + 1\n ten = (ten+1) / 2\n return recursion(ten,count)\ndef tentotwo(ten):\n two = bin(ten)\n two = two[2:]\n while len(two) != 11:#change 11 output#\n two = '0'+two\n return two\ndef manytime(ten):#do recur n+1#\n alldata = 0\n for i in range(0,ten+1):#0~n n+1 time#\n alldata = alldata + recursion(i)#i#\n return alldata#alldata not in for#\nwhile True:\n data = input()\n ten = int(data,2)\n print(tentotwo(manytime(ten)))#many#\n split = input()\n if split == '-1':\n break\n","sub_path":"ds/circuit2.py","file_name":"circuit2.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"312499442","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the PyMVPA package for the\n# copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Unit tests for PyMVPA pattern handling\"\"\"\n\nfrom mvpa.datasets.masked import *\nfrom mvpa.misc.exceptions import DatasetError\n\nimport unittest\nimport numpy as N\nimport random\n\nclass MaskedDatasetTests(unittest.TestCase):\n\n def testCreateMaskedDataset(self):\n data = MaskedDataset(samples=[range(5)], labels=1,\n chunks=1)\n # simple sequence has to be a single pattern\n self.failUnlessEqual( data.nsamples, 1)\n # check correct pattern layout (1x5)\n self.failUnless(\n (data.samples == N.array([[0, 1, 2, 3, 4]])).all() )\n\n # check for single label and origin\n self.failUnless( (data.labels == N.array([1])).all() )\n self.failUnless( (data.chunks == N.array([1])).all() )\n\n # now try adding pattern with wrong shape\n self.failUnlessRaises(DatasetError,\n data.__iadd__,\n MaskedDataset(samples=N.ones((2,3)), labels=1,\n chunks=1))\n\n # now add two real patterns\n data += MaskedDataset(samples=N.random.standard_normal((2,5)),\n labels=2, chunks=2)\n self.failUnlessEqual( data.nsamples, 3 )\n self.failUnless( (data.labels == N.array([1,2,2]) ).all() )\n self.failUnless( (data.chunks == N.array([1,2,2]) ).all() )\n\n\n # test unique class labels\n data += MaskedDataset(samples=N.random.standard_normal((2,5)),\n labels=3)\n self.failUnless( (data.uniquelabels == N.array([1,2,3]) ).all() )\n\n # test wrong label length\n self.failUnlessRaises(DatasetError,\n MaskedDataset,\n samples=N.random.standard_normal((4,2,3,4)),\n labels=[1, 2, 3],\n chunks=2)\n\n # test wrong origin length\n self.failUnlessRaises( DatasetError,\n MaskedDataset,\n samples=N.random.standard_normal((4,2,3,4)),\n labels=[1, 2, 3, 4],\n chunks=[2, 2, 2])\n\n\n def testShapeConversion(self):\n data = MaskedDataset(samples=N.arange(24).reshape((2,3,4)),\n labels=1, chunks=1)\n self.failUnlessEqual(data.nsamples, 2)\n self.failUnlessEqual(data.samples.shape, (2,12))\n self.failUnless((data.samples ==\n N.array([range(12),range(12,24)])).all())\n\n\n def testPatternShape(self):\n data = MaskedDataset(samples=N.ones((10,2,3,4)), labels=1, chunks=1)\n self.failUnless(data.samples.shape == (10,24))\n\n\n def testFeature2Coord(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset( samples=origdata, labels=2, chunks=2 )\n\n def randomCoord(shape):\n return [ random.sample(range(size),1)[0] for size in shape ]\n\n # check 100 random coord2feature transformations\n for i in xrange(100):\n # choose random coord\n c = randomCoord((2,4,3,5))\n # tranform to feature_id\n id = data.mapper.getOutId(c)\n\n # compare data from orig array (selected by coord)\n # and data from pattern array (selected by feature id)\n orig = origdata[:,c[0],c[1],c[2],c[3]]\n pat = data.samples[:, id]\n\n self.failUnless((orig == pat).all())\n\n\n def testCoord2Feature(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n def randomCoord(shape):\n return [ random.sample(range(size),1)[0] for size in shape ]\n\n for id in xrange(data.nfeatures):\n # transform to coordinate\n c = data.mapper.getInId(id)\n self.failUnlessEqual(len(c), 4)\n\n # compare data from orig array (selected by coord)\n # and data from pattern array (selected by feature id)\n orig = origdata[:,c[0],c[1],c[2],c[3]]\n pat = data.samples[:, id]\n\n self.failUnless((orig == pat).all())\n\n\n def testFeatureSelection(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n unmasked = data.samples.copy()\n\n # default must be no mask\n self.failUnless( data.nfeatures == 120 )\n self.failUnless(data.mapper.getOutSize() == 120)\n\n # check that full mask uses all features\n sel = data.selectFeaturesByMask( N.ones((2,4,3,5)) )\n self.failUnless( sel.nfeatures == data.samples.shape[1] )\n self.failUnless( data.nfeatures == 120 )\n\n # check partial array mask\n partial_mask = N.zeros((2,4,3,5), dtype='uint')\n partial_mask[0,0,2,2] = 1\n partial_mask[1,2,2,0] = 1\n\n sel = data.selectFeaturesByMask( partial_mask )\n self.failUnless( sel.nfeatures == 2 )\n self.failUnless( sel.mapper.getMask().shape == (2,4,3,5))\n\n # check that feature selection does not change source data\n self.failUnless(data.nfeatures == 120)\n self.failUnlessEqual(data.mapper.getOutSize(), 120)\n\n # check selection with feature list\n sel = data.selectFeatures([0,37,119])\n self.failUnless(sel.nfeatures == 3)\n\n # check size of the masked patterns\n self.failUnless( sel.samples.shape == (10,3) )\n\n # check that the right features are selected\n self.failUnless( (unmasked[:,[0,37,119]]==sel.samples).all() )\n\n\n def testPatternSelection(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n self.failUnless( data.nsamples == 10 )\n\n # set single pattern to enabled\n sel=data.selectSamples(5)\n self.failUnless( sel.nsamples == 1 )\n self.failUnless( data.nsamples == 10 )\n\n # check duplicate selections\n sel = data.selectSamples([5,5])\n self.failUnless( sel.nsamples == 2 )\n self.failUnless( (sel.samples[0] == sel.samples[1]).all() )\n self.failUnless( len(sel.labels) == 2 )\n self.failUnless( len(sel.chunks) == 2 )\n\n self.failUnless( sel.samples.shape == (2,120) )\n\n def testCombinedPatternAndFeatureMasking(self):\n data = MaskedDataset(\n samples=N.arange( 20 ).reshape( (4,5) ), labels=1, chunks=1 )\n\n self.failUnless( data.nsamples == 4 )\n self.failUnless( data.nfeatures == 5 )\n fsel = data.selectFeatures([1,2])\n fpsel = fsel.selectSamples([0,3])\n self.failUnless( fpsel.nsamples == 2 )\n self.failUnless( fpsel.nfeatures == 2 )\n\n self.failUnless( (fpsel.samples == [[1,2],[16,17]]).all() )\n\n\n def testOrigMaskExtraction(self):\n origdata = N.random.standard_normal((10,2,4,3))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n # check with custom mask\n sel = data.selectFeatures([5])\n self.failUnless( sel.samples.shape[1] == 1 )\n origmask = sel.mapper.getMask()\n self.failUnless( origmask[0,1,2] == True )\n self.failUnless( origmask.shape == (2,4,3) )\n\n\n\n def testPatternMerge(self):\n data1 = MaskedDataset(samples=N.ones((5,5,1)), labels=1, chunks=1)\n data2 = MaskedDataset(samples=N.ones((3,5,1)), labels=2, chunks=1)\n\n merged = data1 + data2\n\n self.failUnless(merged.nsamples == 8 )\n self.failUnless((merged.labels == [ 1,1,1,1,1,2,2,2]).all())\n self.failUnless((merged.chunks == [ 1,1,1,1,1,1,1,1]).all())\n\n data1 += data2\n\n self.failUnless(data1.nsamples == 8 )\n self.failUnless((data1.labels == [ 1,1,1,1,1,2,2,2]).all())\n self.failUnless((data1.chunks == [ 1,1,1,1,1,1,1,1]).all())\n\n\n def testLabelRandomizationAndSampling(self):\n data = MaskedDataset(samples=N.ones((5,1)), labels=range(5), chunks=1)\n data += MaskedDataset(samples=N.ones((5,1))+1, labels=range(5), chunks=2)\n data += MaskedDataset(samples=N.ones((5,1))+2, labels=range(5), chunks=3)\n data += MaskedDataset(samples=N.ones((5,1))+3, labels=range(5), chunks=4)\n data += MaskedDataset(samples=N.ones((5,1))+4, labels=range(5), chunks=5)\n self.failUnless( data.samplesperlabel == {0:5, 1:5, 2:5, 3:5, 4:5} )\n\n sample = data.getRandomSamples( 2 )\n self.failUnless( sample.samplesperlabel.values() == [ 2,2,2,2,2 ] )\n\n self.failUnless( (data.uniquechunks == range(1,6)).all() )\n\n # store the old labels\n origlabels = data.labels.copy()\n\n data.permuteLabels(True)\n\n self.failIf( (data.labels == origlabels).all() )\n\n data.permuteLabels(False)\n\n self.failUnless( (data.labels == origlabels).all() )\n\n # now try another object with the same data\n data2 = MaskedDataset(samples=data.samples, labels=data.labels,\n chunks=data.chunks )\n\n # labels are the same as the originals\n self.failUnless( (data2.labels == origlabels).all() )\n\n # now permute in the new object\n data2.permuteLabels( True )\n\n # must not affect the old one\n self.failUnless( (data.labels == origlabels).all() )\n # but only the new one\n self.failIf( (data2.labels == origlabels).all() )\n\n\n def testFeatureMasking(self):\n mask = N.zeros((5,3),dtype='bool')\n mask[2,1] = True; mask[4,0] = True\n data = MaskedDataset(\n samples=N.arange( 60 ).reshape( (4,5,3) ), labels=1, chunks=1,\n mask=mask)\n\n # check simple masking\n self.failUnless( data.nfeatures == 2 )\n self.failUnless( data.mapper.getOutId( (2,1) ) == 0 \n and data.mapper.getOutId( (4,0) ) == 1 )\n self.failUnlessRaises( ValueError, data.mapper.getOutId, (2,3) )\n self.failUnless( data.mapper.getMask().shape == (5,3) )\n self.failUnless( tuple(data.mapper.getInId( 1 )) == (4,0) )\n\n # selection should be idempotent\n self.failUnless(data.selectFeaturesByMask( mask ).nfeatures == data.nfeatures )\n # check that correct feature get selected\n self.failUnless( (data.selectFeatures([1]).samples[:,0] \\\n == N.array([12, 27, 42, 57]) ).all() )\n self.failUnless(tuple( data.selectFeatures([1]).mapper.getInId(0) ) == (4,0) )\n self.failUnless( data.selectFeatures([1]).mapper.getMask().sum() == 1 )\n\n # check sugarings\n # Access to simple attributes and samples\n self.failUnless(N.all(data.I == data.origids))\n self.failUnless(N.all(data.C == data.chunks))\n self.failUnless(N.all(data.L == data.labels))\n self.failUnless(N.all(data.S == data.samples))\n self.failUnless(N.all(data.O == data.mapper.reverse(data.samples)))\n\n # Access to unique attributes\n self.failUnless(N.all(data.UC == data.uniquechunks))\n self.failUnless(N.all(data.UL == data.uniquelabels))\n\n\n# def testROIMasking(self):\n# mask=N.array([i/6 for i in range(60)], dtype='int').reshape(6,10)\n# data = MaskedDataset(\n# N.arange( 180 ).reshape( (3,6,10) ), 1, 1, mask=mask )\n#\n# self.failIf( data.mapper.getMask().dtype == 'bool' )\n# # check that the 0 masked features get cut\n# self.failUnless( data.nfeatures == 54 )\n# self.failUnless( (data.samples[:,0] == [6,66,126]).all() )\n# self.failUnless( data.mapper.getMask().shape == (6,10) )\n#\n# featsel = data.selectFeatures([19])\n# self.failUnless( (data.samples[:,19] == featsel.samples[:,0]).all() )\n#\n# # check single ROI selection works\n# roisel = data.selectFeaturesByGroup([4])\n# self.failUnless( (data.samples[:,19] == roisel.samples[:,1]).all() )\n#\n# # check dual ROI selection works (plus keep feature order)\n# roisel = data.selectFeaturesByGroup([6,4])\n# self.failUnless( (data.samples[:,19] == roisel.samples[:,1]).all() )\n# self.failUnless( (data.samples[:,32] == roisel.samples[:,8]).all() )\n#\n# # check if feature coords can be recovered\n# self.failUnless( (roisel.getCoordinate(8) == (3,8)).all() )\n\n\ndef suite():\n return unittest.makeSuite(MaskedDatasetTests)\n\n\nif __name__ == '__main__':\n import runner\n\n","sub_path":"mvpa/tests/test_maskeddataset.py","file_name":"test_maskeddataset.py","file_ext":"py","file_size_in_byte":12807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"186732842","text":"# -*- coding: utf-8 -*-\r\nfrom perform.defines import *\r\nfrom perform.object import MagAttackPerform as CustomPerform\r\n\r\n#导表开始\nclass Perform(CustomPerform):\n\tid = 1211\n\tname = \"风雷弹\"\n\ttargetType = PERFORM_TARGET_ENEMY\n\ttargetCount = 1\n\tdamage = lambda self,SLV:SLV*2+20\n\tpower = 60\n\tconsumeList = {\n\t\t\"真气\": lambda SLV:SLV*1.2+20,\n\t}\n\trecoverList = {\n\t\t\"符能\": 10,\n\t}\n\tspeRatio = 100\n\tconfigInfo = {\n\t\t\"治疗\":lambda SLV:SLV*2+20,\n\t\t\"治疗威力\":50,\n\t\t\"目标数\":5,\n\t}\n#导表结束\r\n\r\n\tdef perform(self, att, vicCast):\r\n\t\tCustomPerform.perform(self, att, vicCast)\r\n\t\t\r\n\t\ttargetList = self.getPerformTargetList(att, att, 99)\r\n\t\ttargetList.sort(key=lambda w:w.hp)\r\n\t\ttargetCount = self.configInfo[\"目标数\"]\r\n\t\ttargetList = targetList[:targetCount]\r\n\t\ttargetCount = len(targetList)\r\n\t\tdamRatio = self.calDamageRatio(att, vicCast, vicCast, targetCount)\r\n\t\tfor vic in targetList:\r\n\t\t\tif vic.isDead():\r\n\t\t\t\tcontinue\r\n\t\t\tdp = self.calCure(att, vic, vicCast, damRatio)\r\n\t\t\tvic.addHP(dp, att)\r\n\t\t\t\t\r\n\tdef calCure(self, att, vic, vicCast, damRatio):\r\n\t\tmagDam = int(self.transCode(self.configInfo[\"治疗\"], att, vic))\r\n\t\tpower = self.configInfo[\"治疗威力\"]\r\n\t\tdp = att.calCure(vic, magDam, power, damRatio, self.getAttackType())\r\n\t\treturn dp\r\n\t\t\t\t","sub_path":"logic/perform/school/pf1211.py","file_name":"pf1211.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"506687236","text":"import sys\n \nimport pygame\nfrom pygame.locals import *\n \npygame.init()\n \nfps = 60\nfps_clock = pygame.time.Clock()\n \nwidth, height = 640, 480\nscreen = pygame.display.set_mode((width, height))\n \n# Game loop.\nwhile True:\n screen.fill((0, 0, 0))\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n # Update.\n \n # Draw.\n \n pygame.display.flip()\n fps_clock.tick(fps)","sub_path":"pygame/lesson_1.py","file_name":"lesson_1.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"256786200","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.views.generic import RedirectView\nfrom users.views import auth_view\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('shops/', include('shops.urls')),\n path('', RedirectView.as_view(url='login/', permanent=True)),\n]\n\n# Add Django site authentication urls (for, logout, password management) and custom login view\nurlpatterns += [\n path('login/', auth_view, name='custom_login'),\n path('accounts/', include('django.contrib.auth.urls')),\n]\n\n# Url for list of users\nurlpatterns += [\n path('loggedin/', include('users.urls')),\n]\n","sub_path":"django_crud_app/django_crud_app/django_crud_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"117259872","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 21 13:07:56 2015\n\n@author: xiaohu\n\"\"\"\n\nimport requests\nimport datetime\nimport time\nimport re\nimport json\n\ns= requests.Session()\nlogin_url = \"http://www.learning.gov.cn/study/login.php\"\najax_url = \"http://www.learning.gov.cn/study/ajax.php\"\ncourse_url = \"http://www.learning.gov.cn/course/course.php\"\n\n\ndef login():\n data = {'username':'320323197111221058', 'password':'19981226'}\n resp = s.post(login_url, data, allow_redirects=False)\n resp.encoding = 'utf-8'\n print(resp.status_code)\n print(resp.headers)\n print(resp.text)\n if 'profile' in resp.headers['location']:\n return True\n return False\n\ndef list_course():\n r = s.get('http://www.learning.gov.cn/study')\n r.encoding = 'utf-8'\n m = re.findall(r'course.php\\?act=detail&courseid=\\d+', r.text)\n courses = [re.search(r'\\d+', x).group() for x in m]\n print(\"course list: \" + str(courses))\n return courses\n \ndef start_course():\n login()\n delay = 1200000\n for course_id in list_course():\n set_course_session(course_id, delay)\n msg1 = log_course(course_id)\n log_id = msg1['logId']\n err = '0'\n while err != '1' :\n msg = update_time(course_id, log_id)\n err = msg['err']\n if err == '2':\n print(\"重新登录...\")\n while login() == False:\n time.sleep(2)\n set_course_session(course_id, delay)\n log_id = log_course(course_id)['logId']\n elif err == '0':\n time.sleep(60)\n print(\"完成学习: course \" + course_id) \n \ndef set_course_session(course_id, delay):\n data = {'act':'set_course_session', 'courseId':course_id, 'delay':delay}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n return msg\n \ndef log_course(course_id):\n data = {'act':'insert', 'courseId':course_id}\n print('开始课程学习日志: course ' + course_id)\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n return msg\n\ndef update_time(course_id, log_id):\n err = 0\n msg = ''\n while err==0:\n data = {'act':'update', 'courseId':course_id, 'logId':log_id}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n err = msg['err']\n return msg\n \n \ndef exit_course(course_id, log_id):\n data = {'act':'exit', 'courseId':course_id, 'logId':log_id}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n delta = msg['playTime'] if 'playTime' in msg else 0\n total_time = str(datetime.timedelta(seconds=delta))\n print('本次共学习: '+total_time)\n \nif __name__ == '__main__':\n start_course()\n","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"298549516","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayOpenLotteryCampSubmitModel(object):\n\n def __init__(self):\n self._env = None\n\n @property\n def env(self):\n return self._env\n\n @env.setter\n def env(self, value):\n self._env = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.env:\n if hasattr(self.env, 'to_alipay_dict'):\n params['env'] = self.env.to_alipay_dict()\n else:\n params['env'] = self.env\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayOpenLotteryCampSubmitModel()\n if 'env' in d:\n o.env = d['env']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayOpenLotteryCampSubmitModel.py","file_name":"AlipayOpenLotteryCampSubmitModel.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"38214159","text":"i,j,k =input().split()\nm=int(i)\no=int(j)\np=int(k)\n\nif (m>o and m>p):\n print(m)\nelif(o>p):\n print(o)\nelse:\n print(p)\n","sub_path":"threebigest.py","file_name":"threebigest.py","file_ext":"py","file_size_in_byte":125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"515641334","text":"from random import randint\n\ndef calc_fib(n):\n if (n <= 1):\n return n\n\n return calc_fib(n - 1) + calc_fib(n - 2)\n\ndef calc_fib_2(n):\n arr = [0,1]\n\n for i in range(2, n):\n arrLength = len(arr)\n toAppend = arr[arrLength-1] + arr[arrLength-2]\n arr.append(toAppend)\n\n return arr[n-1] + arr[n-2]\n\nwhile (True):\n random_n = randint(3, 25)\n print('random number: ', random_n)\n\n res1 = calc_fib(random_n)\n res2 = calc_fib_2(random_n)\n\n if res1 != res2:\n print('Wrong answer: ', res1, ' | ', res2)\n break\n else:\n print('OK')\n\n","sub_path":"algo-toolbox/week2_algorithmic_warmup/1_fibonacci_number/stress_test_fibonacci.py","file_name":"stress_test_fibonacci.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"174204551","text":"\"\"\"Operator functions for synaptor DAGs.\"\"\"\nfrom __future__ import annotations\nimport os\nfrom typing import Optional\n\nfrom airflow import DAG\nfrom airflow.utils.weight_rule import WeightRule\nfrom airflow.operators.python import PythonOperator\nfrom airflow.models import Variable, BaseOperator\n\nfrom worker_op import worker_op\nfrom param_default import default_synaptor_image\nfrom igneous_and_cloudvolume import check_queue, upload_json, read_single_file\nfrom slack_message import task_failure_alert, task_done_alert, slack_message\nfrom nglinks import ImageLayer, SegLayer, generate_ng_payload, wrap_payload\nfrom kombu_helper import drain_messages\n\n\n# hard-coding these for now\nMOUNT_POINT = \"/root/.cloudvolume/secrets/\"\nTASK_QUEUE_NAME = \"synaptor\"\n\n\n# Op functions\ndef generate_nglink(\n net_output_path: str,\n seg_path: str,\n workflowtype: str,\n storagedir: str,\n add_synapse_points: str,\n img_path: Optional[str] = None,\n voxelres: Optional[tuple[int, int, int]] = None,\n) -> None:\n \"\"\"Generates a neuroglancer link to view the results.\"\"\"\n layers = [\n ImageLayer(\"network output\", net_output_path),\n SegLayer(\"synaptor segmentation\", seg_path),\n ]\n\n if img_path:\n layers = [ImageLayer(\"image\", img_path)] + layers\n\n payload = generate_ng_payload(layers)\n\n if \"Assignment\" in workflowtype and getboolean(add_synapse_points):\n presyn_pts, postsyn_pts = read_pts(storagedir)\n payload = add_annotation_layer(payload, presyn_pts, postsyn_pts, voxelres)\n\n upload_json(storagedir, \"ng.json\", payload)\n slack_message(wrap_payload(os.path.join(storagedir, \"ng.json\")), broadcast=True)\n\n\ndef getboolean(rawvalue: str) -> bool:\n \"\"\"Simulating configparser.getboolean\"\"\"\n value = rawvalue.lower()\n if value in [True, 1, \"yes\", \"y\", \"true\", \"t\", \"on\"]:\n return True\n elif value in [False, 0, \"no\", \"n\", \"false\", \"f\", \"off\"]:\n return False\n else:\n raise ValueError(f\"unrecognized boolean value: {rawvalue}\")\n\n\ndef read_pts(storagedir: str) -> tuple[list, list]:\n maybe_content = read_single_file(storagedir, \"final_edgelist.df\")\n\n if maybe_content:\n content = maybe_content.decode(\"utf-8\")\n else:\n raise ValueError(\"no edge list found\")\n\n lines = content.split(\"\\n\")\n header, rows = lines[0], lines[1:]\n\n # indices for the columns we want\n colnames = header.split(\",\")\n pre_x_i = colnames.index(\"presyn_x\")\n pre_y_i = colnames.index(\"presyn_y\")\n pre_z_i = colnames.index(\"presyn_z\")\n post_x_i = colnames.index(\"postsyn_x\")\n post_y_i = colnames.index(\"postsyn_y\")\n post_z_i = colnames.index(\"postsyn_z\")\n\n # extracting points\n presyn_pts = list()\n postsyn_pts = list()\n for row in rows:\n if \",\" not in row:\n continue\n\n fields = row.split(\",\")\n presyn_pt = fields[pre_x_i], fields[pre_y_i], fields[pre_z_i]\n postsyn_pt = fields[post_x_i], fields[post_y_i], fields[post_z_i]\n\n presyn_pts.append(list(map(int, presyn_pt)))\n postsyn_pts.append(list(map(int, postsyn_pt)))\n\n return presyn_pts, postsyn_pts\n\n\ndef add_annotation_layer(\n payload: dict, presyn_pts: list, postsyn_pts: list, voxel_res: tuple\n) -> dict:\n annotations = [\n {\n \"pointA\": list(presyn_pt),\n \"pointB\": list(postsyn_pt),\n \"type\": \"line\",\n \"id\": str(index),\n }\n for (index, (presyn_pt, postsyn_pt)) in enumerate(zip(presyn_pts, postsyn_pts))\n ]\n\n annotation_layer = {\n \"type\": \"annotation\",\n \"tool\": \"annotateLine\",\n \"tab\": \"annotations\",\n \"source\": {\n \"url\": \"local://annotations\",\n \"transform\" : {\n \"outputDimensions\": {\n \"x\": [f\"{voxel_res[0]}e-9\", \"m\"],\n \"y\": [f\"{voxel_res[1]}e-9\", \"m\"],\n \"z\": [f\"{voxel_res[2]}e-9\", \"m\"],\n }\n }\n },\n \"annotations\": annotations,\n }\n\n payload[\"layers\"][\"synapses\"] = annotation_layer\n\n return payload\n\n\ndef nglink_op(\n dag: DAG,\n net_output_path: str,\n seg_path: str,\n workflowtype: str,\n storagedir: str,\n add_synapse_points: str,\n img_path: str,\n voxelres: tuple[int, int, int],\n) -> PythonOperator:\n return PythonOperator(\n task_id=\"nglink\",\n python_callable=generate_nglink,\n op_args=(\n net_output_path, seg_path, workflowtype, storagedir, add_synapse_points\n ),\n op_kwargs=dict(img_path=img_path, voxelres=voxelres),\n priority_weight=100000,\n on_failure_callback=task_failure_alert,\n weight_rule=WeightRule.ABSOLUTE,\n queue=\"manager\",\n dag=dag,\n )\n\n\ndef drain_op(\n dag: DAG,\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n queue: Optional[str] = \"manager\",\n) -> PythonOperator:\n \"\"\"Drains leftover messages from the RabbitMQ.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n\n return PythonOperator(\n task_id=\"drain_messages\",\n python_callable=drain_messages,\n priority_weight=100_000,\n op_args=(broker_url, task_queue_name),\n weight_rule=WeightRule.ABSOLUTE,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n queue=\"manager\",\n dag=dag,\n )\n\n\ndef manager_op(\n dag: DAG,\n synaptor_task_name: str,\n queue: str = \"manager\",\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"An operator fn for running synaptor tasks on the airflow node.\"\"\"\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n command = f\"{synaptor_task_name} {config_path}\"\n\n # these variables will be mounted in the containers\n variables = [\"synaptor_param.json\"]\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=synaptor_task_name,\n command=command,\n force_pull=True,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=queue,\n dag=dag,\n )\n\n\ndef generate_op(\n dag: DAG,\n taskname: str,\n op_queue_name: Optional[str] = \"manager\",\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n tag: Optional[str] = None,\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"Generates tasks to run and adds them to the RabbitMQ.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n\n command = (\n f\"generate {taskname} {config_path}\"\n f\" --queueurl {broker_url}\"\n f\" --queuename {task_queue_name}\"\n )\n\n # these variables will be mounted in the containers\n variables = add_secrets_if_defined([\"synaptor_param.json\"])\n\n task_id = f\"generate_{taskname}\" if tag is None else f\"generate_{taskname}_{tag}\"\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=task_id,\n command=command,\n force_pull=True,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=op_queue_name,\n dag=dag,\n )\n\n\ndef synaptor_op(\n dag: DAG,\n i: int,\n op_queue_name: Optional[str] = \"synaptor-cpu\",\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n tag: Optional[str] = None,\n use_gpus: Optional[bool] = False,\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"Runs a synaptor worker until it receives a self-destruct task.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n\n command = (\n f\"worker --configfilename {config_path}\"\n f\" --queueurl {broker_url} \"\n f\" --queuename {task_queue_name}\"\n \" --lease_seconds 300\"\n )\n\n # these variables will be mounted in the containers\n variables = add_secrets_if_defined([\"synaptor_param.json\"])\n\n task_id = f\"worker_{i}\" if tag is None else f\"worker_{tag}_{i}\"\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=task_id,\n command=command,\n use_gpus=use_gpus,\n force_pull=True,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=op_queue_name,\n dag=dag,\n # qos='quality of service'\n # this turns of a 5-minute failure timer that can kill nodes between\n # task waves or during database tasks\n qos=False,\n retries=100,\n retry_exponential_backoff=False,\n )\n\n\ndef wait_op(dag: DAG, taskname: str) -> PythonOperator:\n \"\"\"Waits for a task to finish.\"\"\"\n return PythonOperator(\n task_id=f\"wait_for_queue_{taskname}\",\n python_callable=check_queue,\n op_args=(TASK_QUEUE_NAME,),\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n on_success_callback=task_done_alert,\n queue=\"manager\",\n dag=dag,\n )\n\n\n# Helper functions\ndef add_secrets_if_defined(variables: list[str]) -> list[str]:\n \"\"\"Adds CloudVolume secret files to the mounted variables if defined.\n\n Synaptor still needs to store the google-secret.json file sometimes\n bc it currently uses an old version of gsutil.\n \"\"\"\n maybe_aws = Variable.get(\"aws-secret.json\", None)\n maybe_gcp = Variable.get(\"google-secret.json\", None)\n\n if maybe_aws is not None:\n variables.append(\"aws-secret.json\")\n if maybe_gcp is not None:\n variables.append(\"google-secret.json\")\n\n return variables\n","sub_path":"dags/synaptor_ops.py","file_name":"synaptor_ops.py","file_ext":"py","file_size_in_byte":9909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600774703","text":"from omsdk.sdkcenum import EnumWrapper\n\nProtocolEnum = EnumWrapper('ProtocolEnum', {\n 'SNMP' : 1,\n 'WSMAN' : 2,\n 'REDFISH' : 3,\n 'REST' : 4,\n 'Other' : 100,\n 'Simulator' : 101\n }).enum_type\n\nProtoMethods = EnumWrapper(\"FST\", {\n \"HuntMode\" : \"HuntMode\",\n \"MergeMode\" : \"MergeMode\"\n}).enum_type\n\nclass ProtoPreference:\n def __init__(self, *args):\n self.orig_protocols = []\n for arg in args:\n self.orig_protocols.append(arg)\n self.orig_mode = ProtoMethods.HuntMode\n self.reset()\n\n def set_mode(self, mode):\n self.mode = mode\n\n def reset(self):\n self.protocols = []\n self.include_flag = []\n for arg in self.orig_protocols:\n self.protocols.append(arg)\n self.include_flag.append(True)\n self.mode = self.orig_mode\n\n def add(self, *protoenums):\n for protoenum in protoenums:\n if not protoenum in self.orig_protocols:\n self.orig_protocols.append(protoenum)\n self.protocols.append(protoenum)\n self.include_flag.append(True)\n\n def clone(self):\n s = ProtoPreference()\n for i in range(0, len(self.protocols)):\n s.protocols.append(self.protocols[i])\n s.include_flag.append(self.include_flag[i])\n s.mode = self.mode\n return s\n\n def copy(self, source):\n # clean all preferences\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = False\n\n # set include flag for all those source protocols\n for j in range(0, len(source.protocols)):\n for i in range(0, len(self.protocols)):\n if self.protocols[i] == source.protocols[j]:\n self.include_flag[i] = source.include_flag[j]\n\n if not source.mode is None:\n self.mode = source.mode\n\n return self\n\n def set_preferred(self, protoenum):\n moveit = []\n for i in range(0, len(self.protocols)):\n if (self.protocols[i] == protoenum):\n moveit.append(i)\n tt2 = []\n tt3 = []\n for i in range(len(moveit), 0, -1):\n tt2.insert(0, self.protocols[moveit[i-1]])\n tt3.insert(0, self.include_flag[moveit[i-1]])\n del self.protocols[moveit[i-1]]\n del self.include_flag[moveit[i-1]]\n self.protocols[0:0] = tt2\n self.include_flag[0:0] = tt3\n\n def exclude(self, *protoenums):\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = False\n\n def include(self, *protoenums):\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = True\n\n def include_all(self):\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = True\n\n def include_only(self, *protoenums):\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = False\n\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = True\n\n def printx(self):\n counter = 0\n for i in range(0, len(self.protocols)):\n counter = counter + 1\n print (str(counter) + \" :\" + str(self.protocols[i]) + \"(\" + str(self.include_flag[i]) + \")\")\n\n","sub_path":"omsdk/sdkprotopref.py","file_name":"sdkprotopref.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"480712630","text":"import distance\nimport numpy as np\nfrom sklearn.model_selection import ShuffleSplit\n\nfrom bpm_lstm.bpm_lstm_model import BPM_LSTM\nfrom bpm_lstm.bpm_lstm_utils import save_results, load_dataset_with_features\nfrom bpm_lstm.next_step.next_step_models import available_models\nfrom bpm_lstm.next_step.next_step_utils import build_train_test_datasets, discretize_softmax\n\n\n# noinspection PyAttributeOutsideInit\nclass BPM_LSTM_NEXT_STEP(BPM_LSTM):\n def __init__(self, log_name, log_filepath, write_logs, model_name='new_model_v1', output_filepath='../outputs',\n logs_filepath='logs/', validation_split=0.2, test_split=0.1, test_prefix_size=5, epochs=300):\n super().__init__(log_name, log_filepath, model_name, write_logs, output_filepath,\n logs_filepath, validation_split, test_split, test_prefix_size, epochs)\n self._model_type = 'next_step'\n self._results_filepath = '/'.join(\n [self._output_filepath, self._model_type, self._model_name, self._log_name, ''])\n\n def _evaluate_model_test(self):\n test_scores = [[], []]\n\n for sample, additional_features in zip(self._X_test[0], self._X_test[1]):\n predicted_trace = np.expand_dims(np.zeros(sample.shape), 0)\n predicted_trace[:, :self._test_prefix_size] = sample[:self._test_prefix_size:]\n\n for i in range(self._test_prefix_size, self._X_train[0].shape[1]):\n activity_id, resource_id, time = self._model.predict(\n [predicted_trace, np.expand_dims(additional_features, 0)])\n activity_id = discretize_softmax(activity_id)\n resource_id = discretize_softmax(resource_id)\n predicted_trace[:, i] = np.concatenate([activity_id, resource_id, time], axis=-1)\n\n sample_activity = np.argmax(sample[:, :self._max_activity_id + 1], 1)\n sample_activity_string = ''.join(str(e) for e in sample_activity.tolist())\n\n predicted_activity = np.argmax(predicted_trace[:, :, :self._max_activity_id + 1], 2)[0]\n predicted_activity_string = ''.join(str(e) for e in predicted_activity.tolist())\n\n sample_resource = np.argmax(\n sample[:, self._max_activity_id + 1:self._max_activity_id + self._max_resource_id + 2], 1)\n sample_resource_string = ''.join(str(e) for e in sample_resource.tolist())\n\n predicted_resource = np.argmax(\n predicted_trace[:, :, self._max_activity_id + 1:self._max_activity_id + self._max_resource_id + 2], 2)[\n 0]\n predicted_resource_string = ''.join(str(e) for e in predicted_resource.tolist())\n\n sample_time = sample[:, -1]\n predicted_time = predicted_trace[:, :, -1][0]\n\n test_scores[0].append((1 - distance.nlevenshtein(sample_activity_string, predicted_activity_string)))\n test_scores[1].append((1 - distance.nlevenshtein(sample_resource_string, predicted_resource_string)))\n\n test_scores = np.array(test_scores)\n return np.mean(test_scores, -1)\n\n def train(self, folds):\n dataset, additional_features, self._max_activity_id, self._max_resource_id = load_dataset_with_features(\n self._log_filepath, shuffle=True)\n\n (self._X_train, self._Y_train), self._X_test = build_train_test_datasets(\n dataset,\n additional_features,\n self._max_activity_id,\n self._max_resource_id,\n self._test_split)\n\n kfold = ShuffleSplit(n_splits=folds, test_size=0.2)\n model_scores = {'validation': [],\n 'test': []}\n\n fold = 0\n for train_indexes, validation_indexes in kfold.split(self._X_train[0]):\n checkpoint_filepath = self._create_checkpoints_path(fold)\n log_path = self._create_logs_path(fold)\n\n self._model = available_models[self._model_name](self._X_train, self._max_activity_id,\n self._max_resource_id)\n history = self._train_model(checkpoint_filepath, log_path, train_indexes, validation_indexes)\n validation_scores = history.history\n model_scores['validation'].append(\n (validation_scores['val_activity_id_categorical_accuracy'][-1],\n validation_scores['val_resource_id_categorical_accuracy'][-1],\n validation_scores['val_time_mean_squared_error'][-1]))\n\n test_scores = self._evaluate_model_test()\n model_scores['test'].append(test_scores)\n\n fold += 1\n model_scores['validation'] = np.array(model_scores['validation'])\n model_scores['test'] = np.array(model_scores['test'])\n\n save_results(self._results_filepath, model_scores)\n","sub_path":"src/bpm_lstm/next_step/next_step_model.py","file_name":"next_step_model.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"160059309","text":"import sys\r\nimport os\r\nimport argparse\r\nimport codecs\r\n\r\ntotallines = 0\r\nfiles = None\r\ncl = None\r\ncb = None \r\ncc = None\r\ncw = None\r\n\r\ndef parseargs():\r\n global cl\r\n global cb\r\n global cc\r\n global cw\r\n global files\r\n parser = argparse.ArgumentParser(description = \"wc\", prog = \"wc\")\r\n parser.add_argument(\"-c\", dest = \"bytes\", help = \"Print byte count\", action = \"store_false\")\r\n parser.add_argument(\"-m\", dest = \"chars\", help = \"Print char count\", action = \"store_false\")\r\n parser.add_argument(\"-w\", dest = \"words\", help = \"Print word count\", action = \"store_false\")\r\n parser.add_argument(\"-l\", dest = \"lines\", help = \"Print line count\", action = \"store_false\")\r\n parser.add_argument(\"files\", metavar = \"files\", nargs = '+', default = sys.stdin)\r\n res = parser.parse_args()\r\n# for x in res: print(x)\r\n cb = res.bytes\r\n cc = res.chars\r\n cw = res.words\r\n cl = res.lines\r\n files = res.files\r\n\r\ndef process(fin):\r\n ffin = None\r\n try:\r\n ffin = open(fin, 'r')\r\n except:\r\n sys.stderr.write(\"error while opening file \" + fin + \"\\n\")\r\n return None, None, None, None\r\n nbytes = os.stat(fin).st_size\r\n rlines = ffin.readlines()\r\n lines = len(rlines)\r\n words = 0\r\n chars = 0\r\n for x in rlines:\r\n x = x.split()\r\n words += len(x)\r\n for y in x:\r\n chars += len(y)\r\n return nbytes, chars, words, lines\r\n\r\nparseargs()\r\nif files == sys.stdin:\r\n process(sys.stdin)\r\nelse:\r\n for x in files:\r\n b, c, w, l = process(x)\r\n if b == None:\r\n continue\r\n totallines += l\r\n print(\"In file\", x,)\r\n if cb: print(\"\\tBytes:\", b)\r\n if cc: print(\"\\tChars:\", c)\r\n if cw: print(\"\\tWords:\", w)\r\n if cl: print(\"\\tLines:\", w)\r\nprint(\"Total Lines: \", totallines)","sub_path":"practice_python/wc.py","file_name":"wc.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"75660584","text":"from itertools import islice\nimport sys\nimport os\nimport json\nimport time\nimport csv\n\nfrom dateutil import parser\nfrom pyspark import SparkContext, SparkConf\n\n\nDATA_TYPE_INTEGER = 0\nDATA_TYPE_REAL = 1\nDATA_TYPE_DATETIME = 2\nDATA_TYPE_TEXT = 3\n\n\ndef inspect_type(cell):\n try:\n value = long(cell)\n except:\n try:\n value = float(cell)\n except:\n try:\n value = parser.parse(cell).replace(tzinfo=None)\n except:\n return DATA_TYPE_TEXT, cell\n return DATA_TYPE_DATETIME, value\n return DATA_TYPE_REAL, value\n return DATA_TYPE_INTEGER, value\n\n\ndef map_column(cell):\n type_name, value = inspect_type(cell)\n return cell, type_name, value\n\n\ninput_file = sys.argv[1]\noutput_dir = sys.argv[2]\n\n\nos.system('mkdir -p %s' % output_dir)\n\nsc = SparkContext()\nsc.setLogLevel(\"ERROR\")\n\nfor line in open(input_file):\n start = time.time()\n input_file = '/user/hm74/NYCOpenData/%s' % line.strip()\n dataset_name = input_file.split('/')[-1]\n output_file = '%s/%s.json' % (output_dir, dataset_name)\n output = {\n 'dataset_name': dataset_name,\n 'columns': [],\n 'key_column_candidates': [],\n }\n\n print('Processing %s ...' % dataset_name)\n\n rdd = sc.textFile(input_file)\n rdd = rdd.mapPartitions(lambda x: csv.reader(x, delimiter=\"\\t\"))\n column_names = rdd.first()\n print('columns[%d]' % len(column_names))\n rdd = rdd.mapPartitionsWithIndex(lambda idx, it: islice(it, 1, None) if idx == 0 else it)\n number_all = rdd.count()\n\n for i, column_name in enumerate(column_names):\n print('%d/%d' % (i+1, len(column_names)))\n rdd_col = rdd.map(lambda x: x[i])\n print('%d/%d - all count' % (i+1, len(column_names)))\n print('%d/%d - non empty count' % (i+1, len(column_names)))\n number_non_empty_cells = rdd_col.filter(lambda x: x != '').count()\n number_empty_cells = number_all - number_non_empty_cells\n print('%d/%d - value2cnt' % (i+1, len(column_names)))\n rdd_value2cnt = rdd_col.map(lambda x: (x, 1)).reduceByKey(lambda a, b: a + b)\n number_distinct_values = rdd_value2cnt.count()\n print('%d/%d - frequent_values' % (i+1, len(column_names)))\n frequent_values = rdd_value2cnt.sortBy(lambda x: x[1], False).keys().take(5)\n\n data_types = []\n print('%d/%d - map column' % (i+1, len(column_names)))\n rdd_cell_dtype_value = rdd_col.map(map_column)\n\n # INTEGER (LONG)\n print('%d/%d - checking type of INTEGER (LONG) ...' % (i+1, len(column_names)))\n rdd_int = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_INTEGER)\\\n .map(lambda x: x[2])\n count = rdd_int.count()\n if (count > 0):\n data_types.append({\n 'type': 'INTEGER (LONG)',\n 'count': count,\n 'max_value': rdd_int.max(),\n 'min_value': rdd_int.min(),\n 'mean': rdd_int.mean(),\n 'stddev': rdd_int.stdev(),\n })\n if count == number_all and count == number_distinct_values:\n output['key_column_candidates'].append(column_name)\n\n\n # REAL\n print('%d/%d - checking type of REAL ...' % (i+1, len(column_names)))\n rdd_real = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_REAL)\\\n .map(lambda x: x[2])\n count = rdd_real.count()\n if (count > 0):\n data_types.append({\n 'type': 'REAL',\n 'count': count,\n 'max_value': rdd_real.max(),\n 'min_value': rdd_real.min(),\n 'mean': rdd_real.mean(),\n 'stddev': rdd_real.stdev(),\n })\n\n\n # DATE/TIME\n print('%d/%d - checking type of DATE/TIME ...' % (i+1, len(column_names)))\n rdd_datetime = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_DATETIME)\\\n .map(lambda x: (x[0], x[2]))\n count = rdd_datetime.count()\n if (count > 0):\n data_types.append({\n 'type': 'DATE/TIME',\n 'count': count,\n 'max_value': rdd_datetime.max(key=lambda x: x[1])[0],\n 'min_value': rdd_datetime.min(key=lambda x: x[1])[0],\n })\n if count == number_all and count == number_distinct_values:\n output['key_column_candidates'].append(column_name)\n\n # TEXT\n print('%d/%d - checking type of TEXT ...' % (i+1, len(column_names)))\n rdd_text_len = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_TEXT)\\\n .map(lambda x: (x[2], len(x[2])))\n count = rdd_text_len.count()\n if (count > 0):\n rdd_text_len_uniq = rdd_text_len.distinct()\n data_types.append({\n 'type': 'REAL',\n 'count': count,\n 'shortest_values': rdd_text_len_uniq.sortBy(lambda x: x[1]).keys().take(5),\n 'longest_values': rdd_text_len_uniq.sortBy(lambda x: x[1], False).keys().take(5),\n 'average_length': rdd_text_len_uniq.map(lambda x: x[1]).mean(),\n })\n\n output['columns'].append({\n 'column_name': column_name,\n 'number_non_empty_cells': number_non_empty_cells,\n 'number_empty_cells': number_empty_cells,\n 'number_distinct_values': number_distinct_values,\n 'frequent_values': frequent_values,\n 'data_types': data_types,\n })\n\n with open(output_file, 'w') as fout:\n fout.write(json.dumps(output, indent=4))\n\n print('%s: time cost %d seconds' % (dataset_name, time.time() - start))\n","sub_path":"Section A/group17/task1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"416023950","text":"KEY_MOD_LCTRL = 0x1D\nKEY_MOD_LSHIFT = 0x2A\nKEY_MOD_LALT = 0x38\n\nKEY_CAPSLOCK = 0x3A # Keyboard Caps Lock\n\n\n\nKEY_NONE = 0x00 \nKEY_A = 0x1E # Keyboard a and A\nKEY_B = 0x30 # Keyboard b and B\nKEY_C = 0x2E # Keyboard c and C\nKEY_D = 0x20 # Keyboard d and D\nKEY_E = 0x12 # Keyboard e and E\nKEY_F = 0x21 # Keyboard f and F\nKEY_G = 0x22 # Keyboard g and G\nKEY_H = 0x23 # Keyboard h and H\nKEY_I = 0x17 # Keyboard i and I\nKEY_J = 0x24 # Keyboard j and J\nKEY_K = 0x25 # KeyboardK andK\nKEY_L = 0x26 # Keyboard l and L\nKEY_M = 0x32 # Keyboard m and M\nKEY_N = 0x31 # Keyboard n and N\nKEY_O = 0x18 # Keyboard o and O\nKEY_P = 0x19 # Keyboard p and P\nKEY_Q = 0x10 # Keyboard q and Q\nKEY_R = 0x13 # Keyboard r and R\nKEY_S = 0x1F # Keyboard s and S\nKEY_T = 0x14 # Keyboard t and T\nKEY_U = 0x16 # Keyboard u and U\nKEY_V = 0x2F # Keyboard v and V\nKEY_W = 0x11 # Keyboard w and W\nKEY_X = 0x2D # Keyboard x and X\nKEY_Y = 0x15 # Keyboard y and Y\nKEY_Z = 0x2C # Keyboard z and Z\n\nKEY_1 = 0x02 # Keyboard 1 and !\nKEY_2 = 0x03 # Keyboard 2 and @\nKEY_3 = 0x04 # Keyboard 3 and #\nKEY_4 = 0x05 # Keyboard 4 and $\nKEY_5 = 0x06 # Keyboard 5 and %\nKEY_6 = 0x07 # Keyboard 6 and ^\nKEY_7 = 0x08 # Keyboard 7 and &\nKEY_8 = 0x09 # Keyboard 8 and *\nKEY_9 = 0x0A # Keyboard 9 and (\nKEY_0 = 0x0B # Keyboard 0 and )\n\nKEY_ENTER = 0x1C # Keyboard Return (ENTER)\nKEY_ESC = 0x01 # Keyboard ESCAPE\nKEY_BACKSPACE = 0x0E # Keyboard DELETE (Backspace)\nKEY_TAB = 0x0F # Keyboard Tab\nKEY_SPACE = 0x39 # Keyboard Spacebar\nKEY_MINUS = 0x0C # Keyboard - and _\nKEY_EQUAL = 0x0D # Keyboard = and +\nKEY_LEFTBRACE = 0x1A # Keyboard [ and {\nKEY_RIGHTBRACE = 0x1B # Keyboard ] and }\nKEY_BACKSLASH = 0x2B # Keyboard \\ and |\nKEY_TILDE = 0x29 # Keyboard Non-US # and ~\nKEY_SEMICOLON = 0x27 # Keyboard ; and :\nKEY_APOSTROPHE = 0x28 # Keyboard ' and \"\nKEY_GRAVE = 0x29 # Keyboard ` and ~\nKEY_COMMA = 0x33 # Keyboard , and <\nKEY_DOT = 0x34 # Keyboard . and >\nKEY_SLASH = 0x35 # Keyboard / and ?\n\nKEY_F1 = 0x3B # Keyboard F1\nKEY_F2 = 0x3C # Keyboard F2\nKEY_F3 = 0x3D # Keyboard F3\nKEY_F4 = 0x3E # Keyboard F4\nKEY_F5 = 0x3F # Keyboard F5\nKEY_F6 = 0x40 # Keyboard F6\nKEY_F7 = 0x41 # Keyboard F7\nKEY_F8 = 0x42 # Keyboard F8\nKEY_F9 = 0x43 # Keyboard F9\nKEY_F10 = 0x44 # Keyboard F10\nKEY_F11 = 0x85 # Keyboard F11\nKEY_F12 = 0x86 # Keyboard F12\n\n\nKEY_KP1 = 0x4F # Keypad 1 and End\nKEY_KP2 = 0x50 # Keypad 2 and Down Arrow\nKEY_KP3 = 0x51 # Keypad 3 and PageDn\nKEY_KP4 = 0x4B # Keypad 4 and Left Arrow\nKEY_KP5 = 0x4C # Keypad 5\nKEY_KP6 = 0x4D # Keypad 6 and Right Arrow\nKEY_KP7 = 0x47 # Keypad 7 and Home\nKEY_KP8 = 0x48 # Keypad 8 and Up Arrow\nKEY_KP9 = 0x49 # Keypad 9 and Page Up\nKEY_KP0 = 0x52 # Keypad 0 and Insert\nKEY_KPDOT = 0x53 # Keypad . and Delete\n\n########################################################\n## not done\n\nKEY_MOD_RCTRL = 0x10##nd\nKEY_MOD_RSHIFT = 0x36##nd\nKEY_MOD_RALT = 0x40##nd\nKEY_SYSRQ = 0x46 # Keyboard Print Screen\nKEY_SCROLLLOCK = 0x47 # Keyboard Scroll Lock\nKEY_PAUSE = 0x48 # Keyboard Pause\nKEY_INSERT = 0x49 # Keyboard Insert\nKEY_HOME = 0x4a # Keyboard Home\nKEY_PAGEUP = 0x4b # Keyboard Page Up\nKEY_DELETE = 0x4c # Keyboard Delete Forward\nKEY_END = 0x4d # Keyboard End\nKEY_PAGEDOWN = 0x4e # Keyboard Page Down\nKEY_RIGHT = 0x4f # Keyboard Right Arrow\nKEY_LEFT = 0x50 # Keyboard Left Arrow\nKEY_DOWN = 0x51 # Keyboard Down Arrow\nKEY_UP = 0x52 # Keyboard Up Arrow\n\nKEY_NUMLOCK = 0x45 # Keyboard Num Lock and Clear\nKEY_KPSLASH = 0x54 # Keypad /\nKEY_KPASTERISK = 0x37 # Keypad *\nKEY_KPMINUS = 0x4A # Keypad -\nKEY_KPPLUS = 0x4E # Keypad +\nKEY_KPENTER = 0x58 # Keypad ENTER\n\n\nKEY_102ND = 0x64 # Keyboard Non-US \\ and |\nKEY_COMPOSE = 0x65 # Keyboard Application\nKEY_POWER = 0x66 # Keyboard Power\nKEY_KPEQUAL = 0x67 # Keypad =\n\nKEY_F13 = 0x68 # Keyboard F13\nKEY_F14 = 0x69 # Keyboard F14\nKEY_F15 = 0x6a # Keyboard F15\nKEY_F16 = 0x6b # Keyboard F16\nKEY_F17 = 0x6c # Keyboard F17\nKEY_F18 = 0x6d # Keyboard F18\nKEY_F19 = 0x6e # Keyboard F19\nKEY_F20 = 0x6f # Keyboard F20\nKEY_F21 = 0x70 # Keyboard F21\nKEY_F22 = 0x71 # Keyboard F22\nKEY_F23 = 0x72 # Keyboard F23\nKEY_F24 = 0x73 # Keyboard F24\n\nKEY_OPEN = 0x74 # Keyboard Execute\nKEY_HELP = 0x75 # Keyboard Help\nKEY_PROPS = 0x76 # Keyboard Menu\nKEY_FRONT = 0x77 # Keyboard Select\nKEY_STOP = 0x78 # Keyboard Stop\nKEY_AGAIN = 0x79 # Keyboard Again\nKEY_UNDO = 0x7a # Keyboard Undo\nKEY_CUT = 0x7b # Keyboard Cut\nKEY_COPY = 0x7c # Keyboard Copy\nKEY_PASTE = 0x7d # Keyboard Paste\nKEY_FIND = 0x7e # Keyboard Find\nKEY_MUTE = 0x7f # Keyboard Mute\nKEY_VOLUMEUP = 0x80 # Keyboard Volume Up\nKEY_VOLUMEDOWN = 0x81 # Keyboard Volume Down\nKEY_KPCOMMA = 0x85 # Keypad Comma\nKEY_RO = 0x87 # Keyboard International1\nKEY_KATAKANAHIRAGANA = 0x88 # Keyboard International2\nKEY_YEN = 0x89 # Keyboard International3\nKEY_HENKAN = 0x8a # Keyboard International4\nKEY_MUHENKAN = 0x8b # Keyboard International5\nKEY_KPJPCOMMA = 0x8c # Keyboard International6\nKEY_HANGEUL = 0x90 # Keyboard LANG1\nKEY_HANJA = 0x91 # Keyboard LANG2\nKEY_KATAKANA = 0x92 # Keyboard LANG3\nKEY_HIRAGANA = 0x93 # Keyboard LANG4\nKEY_ZENKAKUHANKAKU = 0x94 # Keyboard LANG5\nKEY_KPLEFTPAREN = 0xb6 # Keypad (\nKEY_KPRIGHTPAREN = 0xb7 # Keypad )\n\nKEY_LEFTCTRL = 0xe0 # Keyboard Left Control\nKEY_LEFTSHIFT = 0xe1 # Keyboard Left Shift\nKEY_LEFTALT = 0xe2 # Keyboard Left Alt\nKEY_LEFTMETA = 0xe3 # Keyboard Left GUI\nKEY_RIGHTCTRL = 0xe4 # Keyboard Right Control\nKEY_RIGHTSHIFT = 0xe5 # Keyboard Right Shift\nKEY_RIGHTALT = 0xe6 # Keyboard Right Alt\nKEY_RIGHTMETA = 0xe7 # Keyboard Right GUI\n\nKEY_MEDIA_PLAYPAUSE = 0xe8\nKEY_MEDIA_STOPCD = 0xe9\nKEY_MEDIA_PREVIOUSSONG = 0xea\nKEY_MEDIA_NEXTSONG = 0xeb\nKEY_MEDIA_EJECTCD = 0xec\nKEY_MEDIA_VOLUMEUP = 0xed\nKEY_MEDIA_VOLUMEDOWN = 0xee\nKEY_MEDIA_MUTE = 0xef\nKEY_MEDIA_WWW = 0xf0\nKEY_MEDIA_BACK = 0xf1\nKEY_MEDIA_FORWARD = 0xf2\nKEY_MEDIA_STOP = 0xf3\nKEY_MEDIA_FIND = 0xf4\nKEY_MEDIA_SCROLLUP = 0xf5\nKEY_MEDIA_SCROLLDOWN = 0xf6\nKEY_MEDIA_EDIT = 0xf7\nKEY_MEDIA_SLEEP = 0xf8\nKEY_MEDIA_COFFEE = 0xf9\nKEY_MEDIA_REFRESH = 0xfa\nKEY_MEDIA_CALC = 0xfb\n\n#endif # USB_HID_KEYS\n","sub_path":"FINAL/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"225465429","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nimport csv\n\nBase_url = 'https://u24.ru/news/city/?p=0'\n\nheaders = {'accept': '*/*',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'}\n\n\ndef U24_parse(Base_url, headers):\n news = []\n session = requests.Session()\n request = session.get(Base_url, headers=headers)\n if request.status_code == 200:\n soup = bs(request.content, 'lxml')\n divs = soup.find_all('div', attrs={'class': 'col-sm-9'})\n for div in divs:\n title = div.find('div', attrs={'class': 'title'}).text\n href = 'https://u24.ru' + div.find('a')['href']\n text = div.find('a', attrs={'class': 'txt'}).text\n date = div.find('div', attrs={'class': 'newsdate'}).text\n divs_img = soup.find_all ('div', attrs = {'class': 'col-sm-3'})\n for div in divs_img:\n img = div.find ('img')[ 'src' ]\n news.append({\n 'title': title,\n 'href': href,\n 'text ': text ,\n 'date': date,\n 'img': img\n })\n else:\n print('Error')\n return news\n\n\ndef files_writer(news):\n with open('parsed_news.csv', 'w') as file:\n a_pen = csv.writer(file)\n a_pen.writerow((\"Новость\", \"URL\", \"Загаловок\", \"Фото\", \"Дата\"))\n for new in news:\n a_pen.writerow((new['title'], new['href'], new['text '], new['img'], new['date']))\n\nnews = U24_parse(Base_url, headers)\nfiles_writer(news)\n","sub_path":"U24_official.py","file_name":"U24_official.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"15180542","text":"from __future__ import print_function\nimport os\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n# The GPU id to use, usually either \"0\" or \"1\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n# supress annoying TF messages at the beginning\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\n\nimport tensorflow.keras, os, DataBaseManager, time, math\nfrom tensorflow.keras.layers import Dense, Flatten, BatchNormalization, Dropout, Activation, Concatenate\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, MaxPooling1D, AveragePooling2D, Reshape, Input, UpSampling2D, Conv1D, Lambda\nfrom tensorflow.keras import backend as K\nimport numpy as np\nfrom numpy.random import seed\nimport Utilities as utils\nfrom shutil import copy2\nimport sys\nimport MaskedMLP\nimport ActiveMaskedMLP\n\nprint(\"TF version: \", tf.__version__)\nprint(\"TF.keras version: \", tensorflow.keras.__version__)\n\nnp.set_printoptions(threshold=sys.maxsize)\n\n\n###############################################################################################\n# set memory constraints\n###############################################################################################\ndef get_session(gpu_fraction=0.80):\n gpu_options = tf.compat.v1.GPUOptions(allow_growth=True)\n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction, allow_growth=True)\n return tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=gpu_options))\n\n\ntf.compat.v1.keras.backend.set_session(get_session())\n\nbatch_size = 60000\nepochs = 1\nlearning_rate = 0.001\n\nsaveToDisk = True\ncurrentFileName = os.path.basename(__file__).replace(\".py\", \"\")\nrunName = currentFileName + \"_\" + utils.DateToString()\ndirNameDefault = \"./Outputs/\" + runName + \"/\"\nworkingDir = os.getcwd()\nntraindata = 60000\nntestdata = 10000\n\nnp.random.seed(None)\n\n\n# myseed = np.random.randint(0, 100)\n# myseed=17\n# myseed =9503629\n\n# from tensorflow.keras.layers import Layer\n\ndef makeSharedLayerCNN(inputshape, nclasses, name=None):\n input_img = Input(shape=inputshape)\n\n L1 = Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=inputshape)(input_img)\n L1 = BatchNormalization()(L1)\n L1 = Dropout(0.3)(L1)\n\n conv1 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu')\n\n L2 = conv1(L1)\n L3 = conv1(L2)\n L4 = conv1(L3)\n L5 = conv1(L4)\n L6 = conv1(L5)\n L6 = BatchNormalization()(L6)\n\n L7 = MaxPooling2D(pool_size=(2, 2))(L6)\n conv2 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu')\n\n L8 = conv2(L7)\n L9 = conv2(L8)\n L10 = conv2(L9)\n L11 = conv2(L10)\n L12 = conv2(L11)\n L12 = BatchNormalization()(L12)\n\n L13 = Flatten()(L12)\n\n D = Dense(512, activation='relu')(L13)\n D = Dropout(0.2)(D)\n classes = Dense(nclasses, activation='softmax')(D)\n\n model = Model(input_img, classes)\n model.compile(loss='categorical_crossentropy',\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef makeSahredLayersdMLP(fullarch):\n inputshape = fullarch[0]\n outshape = fullarch[-1]\n\n input_img = Input(shape=(inputshape,))\n\n # add the first hidden layer and connect it to the input\n t0 = Dense(100, 'relu')\n L1 = t0(input_img)\n\n # method 1\n # t1 = Dense(100, 'relu')\n # L2 = t1(L1)\n # L3 = t1(L2)\n # L4 = t1(L3)\n # L5 = t1(L4)\n\n # method 2\n # L2=Dense(100, 'relu')(L1)\n # L3=Dense(100, 'relu')(L2)\n # L4=Dense(100, 'relu')(L3)\n # L5=Dense(100, 'relu')(L4)\n\n # method 3\n L5 = Dense(100, 'relu')(L1)\n\n # here is the last layer, connected to the one before\n # (either the ones from the loop or the one before\n LN = Dense(outshape, 'softmax')(L5)\n\n # define the model, connecting the input to the last layer (LN)\n model = Model(input_img, LN)\n\n # set a network name\n import uuid\n ID = uuid.uuid4().hex\n\n model._name = \"FC\" + a2s(fullarch) + \"_ID\" + ID[len(ID) - 7:]\n\n model.compile(loss='categorical_crossentropy',\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef makeMLP(inputshape, outshape, arch, name, opt, loss):\n model = Sequential(name=name)\n\n model.add(Dense(arch[0], activation='relu', input_dim=inputshape))\n\n if len(arch) != 0:\n for i in range(1, len(arch)):\n model.add(Dense(arch[i], activation='relu'))\n\n model.add(Dense(outshape, activation='softmax', input_dim=inputshape))\n\n model.compile(loss=loss,\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef MakeAverageImageForClass(X, Y):\n averages = []\n\n for c in range(0, 10):\n # get all images of class c\n index_c = np.argmax(Y, axis=1) == c\n\n img_c = X[index_c,]\n\n avg_img_c = np.mean(img_c, axis=0)\n\n averages.append(avg_img_c)\n\n return averages\n\n\ndef RealTo3D(a):\n if len(a.shape) != 2:\n return a\n c = np.expand_dims(a, axis=2)\n\n pad_up = 1\n pad_dn = 1\n c = np.pad(c, ((0, 0), (0, 0), (pad_up, pad_dn)), 'constant', constant_values=(0, 0))\n\n # find indices where the values are <0\n lt0 = (a < 0)\n eq0 = (a == 0)\n\n c[eq0, 0] = 1 # blue\n c[lt0, 1] = 0 # green\n c[lt0, 2] = -a[lt0] # red\n\n return c\n\n\ndef SetMaskToONe(full_arch):\n masks = []\n dense_arch = full_arch[1:-1]\n inputsize = full_arch[0]\n nclasses = full_arch[-1]\n\n c = 1\n\n if len(dense_arch) == 0:\n m = c * np.ones((inputsize, nclasses), dtype=np.float32)\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n else:\n m = c * np.ones((inputsize, dense_arch[0]), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (inputsize, dense_arch[0]))\n # m = np.random.randint(0, 3, (inputsize, dense_arch[0]))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n for t in range(1, len(dense_arch)):\n m = c * np.ones((dense_arch[t - 1], dense_arch[t]), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (dense_arch[t - 1], dense_arch[t]))\n # m = np.random.randint(0, 3, (dense_arch[t - 1], dense_arch[t]))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n m = c * np.ones((dense_arch[-1], nclasses), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (dense_arch[-1], nclasses))\n # m = np.random.randint(0, 3, (dense_arch[-1], nclasses))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n return masks\n\n\n#\n# class MyLayer(Layer):\n#\n# def __init__(self, output_dim, weight_mask, activation, seed, **kwargs):\n# self.output_dim = output_dim\n# self.mask = weight_mask\n# self.seed = seed\n# self.activation = activation\n#\n# super(MyLayer, self).__init__(**kwargs)\n#\n# def build(self, input_shape):\n# ki = tensorflow.keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=self.seed)\n#\n# self.kernel = self.add_weight(name='kernel',\n# shape=(input_shape.as_list()[1], self.output_dim),\n# initializer=ki,\n# trainable=True)\n#\n# # bi = tensorflow.keras.initializers.zeros()\n# # self.bias = self.add_weight(name='bias',\n# # shape=(self.output_dim,),\n# # initializer=ki,\n# # trainable=True)\n#\n# super(MyLayer, self).build(input_shape) # Be sure to call this at the end\n#\n# def call(self, x):\n# act = K.dot(x, self.kernel * self.mask) # + self.bias\n#\n# if 'relu' in self.activation:\n# act = tensorflow.keras.activations.relu(act)\n#\n# if 'softmax' in self.activation:\n# act = tensorflow.keras.activations.softmax(act)\n#\n# return act\n#\n# def compute_output_shape(self, input_shape):\n# return (input_shape.as_list()[1], self.output_dim)\n#\n# def get_weights(self):\n# w = super(MyLayer, self).get_weights()\n# return w * self.mask\n#\n# def get_seed(self):\n# return self.seed\n#\n# def set_weights(self, weights):\n# super(MyLayer, self).set_weights(weights)\n\ndef RetrainWithMask(myseed, old_weights, fullarch, pruneamount, epochs, data):\n new_weights, masks = SetWeightsToZeroPerLayer(old_weights, pruneamount)\n net = MaskedMLP.makeMaskedMLP(fullarch, masks, myseed)\n\n # Xtrain, Ytrain, Xtest, Ytest = data\n # net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=epochs, verbose=0, shuffle=True, validation_data=(Xtest, Ytest))\n\n if epochs != 0:\n net.fit(data[0], data[1], batch_size=batch_size, epochs=epochs, verbose=0, shuffle=True, validation_data=(data[2], data[3]))\n\n return net\n\n\ndef a2s(a):\n if len(a) == 0:\n return \"0_\"\n\n s = \"\"\n for i in range(len(a) - 1):\n s += str(a[i]) + \"_\"\n\n s += str(a[-1])\n\n return s\n\n\ndef ToArray(W):\n bag = []\n for i in range(0, len(W)):\n w = W[i].reshape(-1)\n bag.extend(w)\n\n B = np.asarray(bag)\n\n return B\n\n\ndef CalculateThreshold(a, p):\n # sort array\n s = np.sort(np.abs(a))\n\n # we know that the i-th element is larger than the ones below\n i = int(p * (a.shape[0] - 1))\n t = s[i]\n\n # print(\"threshold:\", t)\n\n return t\n\n\ndef SetWeightsToZeroPerLayer(net_weights, p):\n new_weights = net_weights.copy()\n masks = net_weights.copy()\n\n for l in range(0, len(net_weights)):\n # for l in range(0, 1):\n # make a copy of the current layer weights, including biases\n layerw = net_weights[l]\n # if len(layerw.shape)<2:\n # continue\n\n # print(type(masks[l]))\n\n masks[l] = np.zeros_like(masks[l])\n\n threshold = CalculateThreshold(ToArray(layerw), p)\n # mn = (ToArray(layerw)).mean()\n\n # set all weights and biases to zero\n # new_weights[l] = mn * np.ones_like(layerw)\n new_weights[l] = np.zeros_like(layerw)\n\n # get indices of the weight which are larger than threshold\n indices = np.abs(layerw) > threshold\n\n # set net_weights[indices] to the values of layerw\n new_weights[l][indices] = layerw[indices]\n masks[l][indices] = 1\n\n return new_weights, masks\n\n\ndef SetWeightsToZeroGlobally(net_weights, p):\n new_weights = net_weights.copy()\n masks = net_weights.copy()\n\n threshold = CalculateThreshold(ToArray(new_weights), p)\n\n for l in range(0, len(net_weights)):\n # for l in range(0, 1):\n # make a copy of the current layer weights, including biases\n layerw = net_weights[l]\n # if len(layerw.shape)<2:\n # continue\n\n # print(type(masks[l]))\n\n masks[l] = np.zeros_like(masks[l])\n\n # mn = (ToArray(layerw)).mean()\n\n # set all weights and biases to zero\n # new_weights[l] = mn * np.ones_like(layerw)\n new_weights[l] = np.zeros_like(layerw)\n\n # get indices of the weight which are larger than threshold\n indices = np.abs(layerw) > threshold\n\n # set net_weights[indices] to the values of layerw\n new_weights[l][indices] = layerw[indices]\n masks[l][indices] = 1\n\n return new_weights, masks\n\n\ndef MaskWeights(old_weights, mask):\n new_weights = old_weights.copy()\n\n for l in range(0, len(old_weights)):\n new_weights[l] = old_weights[l] * mask[l]\n\n return new_weights\n\n\ndef DrawWeights(name, net_weights):\n import cv2\n\n for l in range(0, len(net_weights)):\n layerw = net_weights[l].copy()\n if len(layerw.shape) > 1:\n # layerw -= layerw.min()\n layerw = np.abs(layerw)\n layerw /= layerw.max()\n cv2.imshow(name + str(l), layerw)\n cv2.waitKey(1)\n\n cv2.waitKey(-1)\n return 0\n\n\n#\n# def makeMaskedMLP(inputshape, outshape, arch, masks, seed):\n# input_img = Input(shape=(inputshape,))\n#\n# # if there are no hidden layers then add just\n# # the last layer connected to the input (input_img)\n# if len(arch) == 0:\n# # e = np.random.randint(0, 2, (inputshape, outshape))\n# # e = np.ones(inputshape, outshape)\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# LN = MyLayer(outshape, masks[0], 'softmax', seed)(input_img)\n#\n# # if there are hidden layers then\n# else:\n# # add the first hidden layer and connect it to the input\n# # e = np.random.randint(0, 2, (inputshape, arch[0]))\n# # e = np.ones((inputshape, arch[0]))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# Li = MyLayer(arch[0], masks[0], 'relu', seed)(input_img)\n#\n# # add the rest of the hidden layers (if any) and connect\n# # them to the previous ones\n# for i in range(1, len(arch)):\n# # e = np.random.randint(0, 2, (arch[i - 1], arch[i]))\n# # e = np.ones((arch[i - 1], arch[i]))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# Li = MyLayer(arch[i], masks[i], 'relu', seed)(Li)\n#\n# # here is the last layer, connected to the one before\n# # (either the ones from the loop or the one before\n# # e = np.random.randint(0, 2, (arch[-1], outshape))\n# # e = np.ones((arch[-1], outshape))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# LN = MyLayer(outshape, masks[-1], 'softmax', seed)(Li)\n#\n# # define the model, connecting the input to the last layer (LN)\n# model = Model(input_img, LN)\n#\n# # set a network name\n# import uuid\n# ID = uuid.uuid4().hex\n#\n# model._name = \"FC\" + a2s(arch) + \"_10_ID\" + ID[len(ID) - 7:] + \"_S\" + str(seed)\n#\n# model.compile(loss='categorical_crossentropy',\n# optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n# metrics=['accuracy'])\n#\n# return model\n#\n\n\ndef customstopping(model, X, Y):\n \"\"\"\n :param model:\n :param X: traindata\n :param Y: train labels\n :return: to stop or not to stop\n \"\"\"\n\n loss, acc = model.evaluate(X, Y, verbose=0)\n prediction = model.predict(X)\n\n epsilon = np.finfo(prediction.dtype).eps\n # epsilon=0\n confidences = np.sum(np.log(prediction + epsilon) * (Y), axis=1)\n\n sumlog = -np.sum(confidences)\n size = model.count_params()\n\n print(\"--- Custom stopping ---\")\n print(\" loss \", loss * X.shape[0])\n # print(\" acc \", acc)\n # print(\" size \", size)\n print(\" sumlog \", sumlog)\n\n # if mean - std * 2 < size - mean < mean + std * 2:\n # if size * 1.1 > sumlog2 > size * 0.9:\n # print(sumlog2, size)\n\n # if sumlog2 <= size:\n # print(\"size and sumlog2 are comparable\")\n # return 1\n\n return 0\n\n\ndef VisualizeNetwork(net):\n masks = []\n old_weights = []\n for l in range(1, len(net.layers)):\n m = net.layers[l].get_mask()\n ow = net.layers[l].get_weights()\n masks.append(m)\n old_weights.append(ow)\n print(\"mshape\", m.shape)\n print(\"owshape\", ow.shape)\n\n # print(m.shape)\n\n m = np.swapaxes(masks[0], 0, 1)\n ow = np.swapaxes(old_weights[0], 0, 1)\n ow = ow * m\n # ow = ow - ow.min()\n # ow /= ow.max()\n ow = ow.reshape(-1, 28, 28)\n owcolor = []\n\n for o in range(ow.shape[0]):\n owrgb = RealTo3D(ow[o])\n\n for oo in range(0, 3):\n if owrgb[oo].max() != 0:\n owrgb /= owrgb[oo].std()\n\n owcolor.append(owrgb)\n\n import cv2\n cv2.imshow(\"Weights\" + str(net.name), utils.MakeGridOfImages3D(owcolor))\n cv2.waitKey(1)\n\n return 0\n\n\ndef runmodels(networks, data, n_epochs=None, outputdir=None):\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n # averages = MakeAverageImageForClass(trainImages, trainLabels)\n # import cv2\n # cv2.imshow(\"averages\", utils.MakeGridOfImages(averages))\n # cv2.waitKey(1)\n\n def InvertMask(masks):\n invertedmask = masks.copy()\n\n for i in range(len(masks)):\n invertedmask[i] = 1 - masks[i]\n\n return invertedmask\n\n if outputdir is None:\n dirName = dirNameDefault\n else:\n dirName = outputdir\n\n if n_epochs is None:\n n_epochs = epochs\n\n if saveToDisk:\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data will be saved in \", dirName)\n\n start = time.time()\n\n e = 0\n trainedWeights = {}\n\n ne = 150\n stop = False\n\n # predictions0=\n import localutils\n\n TransitionsTrain = []\n TransitionsTest = []\n\n while e < 1500 and stop == False:\n for net, t in zip(networks, range(0, len(networks))):\n # get train data for network t\n Xtrain = data[t][0]\n Ytrain = data[t][1]\n Xtest = data[t][2]\n Ytest = data[t][3]\n\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # print(\"untrained net test accuracy\", acc)\n\n # VisualizeNetwork(net)\n # input()\n\n # pred0Train = net.predict(Xtrain)\n # pred0Test = net.predict(Xtest)\n\n # earlystopping_callback = EarlyStopping(monitor='loss', mode='min', baseline=0.1)\n # tf.keras.callbacks.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=0, verbose=0, mode='auto', baseline=None,\n # restore_best_weights=False)\n # earlystopping_callback=tf.keras.callbacks.EarlyStopping(monitor='loss', mode='max', baseline=0.1)\n fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False)\n\n # weights = net.get_weights()\n # print(type(weights))\n # ss=0\n # for w in weights:\n # # print(type(w))\n # print(w.shape)\n # print(w.size)\n # ss+=w.size\n # print(\"ss\",ss)\n # input()\n\n # getmaskandweights = False\n # if getmaskandweights:\n # a = 1\n # W = []\n # M = []\n # for l in range(1, len(net.layers)):\n # w = net.layers[l].get_weights()[0]\n # m = net.layers[l].get_active_mask()\n # print(m)\n # M.append(m)\n # W.append(w)\n\n # pred1Train = net.predict(Xtrain)\n # pred1Test = net.predict(Xtest)\n #\n # transTrain = localutils.AnalizeTransitions(pred0Train, pred1Train, Ytrain)\n # transTest = localutils.AnalizeTransitions(pred0Test, pred1Test, Ytest)\n #\n # TransitionsTrain.append(transTrain)\n # TransitionsTest.append(transTest)\n\n # def TransitionSummary(transition, msg):\n #\n # wws = transition[0, 0, 1]\n # wwo = transition[0, 0, 0]\n # wc = transition[0, 1, :].sum()\n # cw = transition[1, 0, :].sum()\n # cc = transition[1, 1, :].sum()\n #\n # print(msg)\n # print(\" - from wrong->wrong \", wwo, \"(other), \", wws, \"same\")\n # print(\" - from wrong->correct \", wc)\n # print(\" - from correct->wrong \", cw)\n # print(\" - from correct->correct \", cc)\n # print(\"\\n\\n\\n\\n\")\n #\n # return 0\n\n # TransitionSummary(transTrain, \"Train transitions\")\n # TransitionSummary(transTest, \"Test transitions\")\n #\n # print(transTrain.sum())\n # print(transTest.sum())\n\n # continue\n\n W = []\n for l in range(1, len(net.layers)):\n w = net.layers[l].get_weights()[0]\n W.append(w)\n\n # DrawWeights(\"asdfgh\", W)\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # print(\"trained net test accuracy \", acc)\n\n if customstopping(model=net, X=Xtrain, Y=Ytrain):\n stop = True\n\n retrainwithmaskweights = False\n if retrainwithmaskweights:\n old_weights = net.get_weights().copy()\n full_arch = localutils.ExtractFullArch(old_weights)\n netseed = localutils.ExtractSeed(net.name)\n new_weights, masks = SetWeightsToZeroGlobally(old_weights, 0.8)\n\n masks_ones = SetMaskToONe(full_arch)\n\n LTHnet = MaskedMLP.makeMaskedMLP(full_arch, masks_ones, netseed)\n # LTHnet.set_weights(masks)\n\n loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n print(\"pretrain accuracy:\", acc)\n # fit_history = LTHnet.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True, validation_data=(Xtest, Ytest))\n\n # loss, acc = LTHnet.evaluate(Xtest, Ytest, verbose=0)\n # print(\"retrain accuracy:\", acc)\n\n trainnewnetwork = False\n if trainnewnetwork:\n import cv2\n\n old_weights = net.get_weights().copy()\n full_arch = localutils.ExtractFullArch(old_weights)\n\n # full_arch.append(old_weights[0].shape[0])\n # full_arch.append(old_weights[0].shape[1])\n #\n # for i in range(1, len(old_weights)):\n # full_arch.append(old_weights[i].shape[1])\n\n percentages = 0.01 * np.arange(0, 101, 1)\n percentages = 0.01 * np.arange(0, 100, 10)\n # percentages = np.append(percentages, np.arange(1, 11) / 1000 + 0.99)\n netseed = localutils.ExtractSeed(net.name)\n\n print(\"\\n\\nTraining a copy of the first network, masked\")\n for pruneamount in percentages:\n print(\"- pruning by:\", pruneamount)\n\n K.clear_session()\n\n # new_weights, masks = SetWeightsToZeroPerLayer(old_weights, pruneamount)\n new_weights, masks = SetWeightsToZeroGlobally(old_weights, pruneamount)\n LTHnet = MaskedMLP.makeMaskedMLP(full_arch, masks, netseed)\n VisualizeNetwork(LTHnet)\n\n # LTHnet.set_weights(masks)\n # fit_history = LTHnet.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True,validation_data=(Xtest, Ytest))\n\n # masksI = InvertMask(masks)\n # LTHnetI = MaskedMLP.makeMaskedMLP(full_arch, masksI, netseed)\n # loss, acc = LTHnetI.evaluate(Xtest, Ytest, verbose=0)\n # print(\" inverted mask test accuracy\", acc)\n #\n # masks=masksI\n # print(masks[0].shape)\n m = np.swapaxes(masks[0], 0, 1)\n ow = np.swapaxes(old_weights[0], 0, 1)\n\n # print(m.shape)\n # print(ow.shape)\n # ow = ow * m\n # # ow = ow - ow.min()\n # # ow /= ow.max()\n # ow = ow.reshape(-1, 28, 28)\n # owcolor = []\n #\n # for o in range(ow.shape[0]):\n # owrgb = RealTo3D(ow[o])\n #\n # for oo in range(0, 3):\n # if owrgb[oo].max() != 0:\n # owrgb /= owrgb[oo].std()\n #\n # owcolor.append(owrgb)\n\n # # cv2.imshow(\"Masks\" + str(pruneamount), utils.MakeGridOfImages(m.reshape(-1, 28, 28)))\n #\n # # ow3c = RealTo3D(ow)\n #\n # cv2.imshow(\"Weights\" + str(pruneamount), utils.MakeGridOfImages3D(owcolor))\n # cv2.waitKey(1)\n continue\n #\n # # find zero points and replace them with 0.01\n # # for m in masks:\n # # condition = (m == 0)\n # # # print(condition)\n # # m[condition] = 0.001\n # netseed = ExtractSeed(net.name)\n #\n # mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, netseed)\n #\n # # cv2.imshow(\"asdff\" + str(l), utils.MakeGridOfImages(net.layers[1].get_mask().reshape(-1, 28, 28)))\n # # cv2.imshow(\"asdff\" + str(l), utils.MakeGridOfImages(masks[0].reshape(-1, 28, 28)))\n # # cv2.imshow(\"ow\" + str(l), utils.MakeGridOfImages(old_weights[0].reshape(-1, 28, 28)))\n # # cv2.waitKey(1)\n #\n # # for l in range(1, len(mlp.layers)):\n # # m = net.layers[l].get_mask()\n # # print(m.shape)\n # #\n # # cv2.imshow(\"mlp pruned masks\" + str(l), m)\n #\n # print(\"network name:\", mlp.name)\n # print(\"parameters: \", mlp.count_params())\n #\n # loss, acc = mlp.evaluate(Xtest, Ytest, verbose=0)\n # # print(\" test accuracy\", acc)\n #\n # print(\"pruning by: {:1.2f}\".format(pruneamount), \" test accuracy\", acc)\n # mlp.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True)\n\n netseed = localutils.ExtractSeed(net.name)\n # add the network's weights to the dictionary of trained weights\n trainedWeights[netseed] = W\n\n e += 1\n # cv2.waitKey(-1)\n\n # import matplotlib.pyplot as plt\n #\n # # plot the graph of transitions\n #\n # plots = np.zeros((epochs, 5))\n # i = 0\n # labels = []\n # for t in TransitionsTest:\n # wws = t[0, 0, 1]\n # wwo = t[0, 0, 0]\n # wc = t[0, 1, :].sum()\n # cw = t[1, 0, :].sum()\n # cc = t[1, 1, :].sum()\n #\n # plots[i, 0] = wws\n # labels.append(\"wws\")\n #\n # plots[i, 1] = wwo\n # labels.append(\"wwo\")\n #\n # plots[i, 2] = wc\n # labels.append(\"wc\")\n #\n # plots[i, 3] = cw\n # labels.append(\"cw\")\n #\n # plots[i, 4] = cc\n # labels.append(\"cc\")\n #\n # i += 1\n #\n # plt.plot(plots[:,0], label=\"wws\")\n # plt.plot(plots[:,1], label=\"wwo\")\n # plt.plot(plots[:,2], label=\"wc\")\n # plt.plot(plots[:,3], label=\"cw\")\n # plt.plot(plots[:,4], label=\"cc\")\n # plt.legend(fontsize=9)\n # plt.show()\n #\n # input()\n\n # testScores = []\n # for net, t in zip(networks, range(0, len(networks))):\n # Xtest = data[t][2]\n # Ytest = data[t][3]\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # testScores.append(acc)\n # print(\"loss \", loss, \" accuracy\", acc)\n #\n # prunenetwork = False\n #\n # if prunenetwork:\n # print(\"clone net test loss: \")\n # pruned_metrics = []\n # # net_clone = tensorflow.keras.models.clone_model(net)\n # #\n # # net_clone.compile(loss='categorical_crossentropy',\n # # optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1.2e-3),\n # # metrics=['accuracy'])\n #\n # net_clone = net\n # old_weights = net.get_weights().copy()\n # old_acc = acc\n #\n # percentages = 0.01 * np.arange(0, 100, 3)\n # percentages = np.append(percentages, np.arange(1, 11) / 1000 + 0.99)\n #\n # print(percentages)\n #\n # # for p in range(0, 101, 1):\n # for p in percentages:\n # new_weights, masks = SetWeightsToZeroPerLayer(old_weights, p)\n # # new_weights = SetWeightsToZeroGlobally(old_weights, p / 100)\n #\n # # print(\"nonzero old_weights\", np.count_nonzero(ToArray(old_weights)))\n # # print(\"nonzero new_weights\", np.count_nonzero(ToArray(new_weights)))\n #\n # net_clone.set_weights(new_weights)\n # # DrawWeights(masks)\n # DrawWeights(new_weights)\n # loss, acc = net_clone.evaluate(Xtest, Ytest, verbose=0)\n # nzow = np.count_nonzero(ToArray(old_weights))\n # nznw = np.count_nonzero(ToArray(new_weights))\n # msg = \"{:3.2f}%: new acc={:1.4f}({:1.5f}), newW/oldW={:.4f}\".format(p * 100, acc, acc / old_acc, nznw / nzow)\n # # msg=\"- %d\"\n # print(msg)\n # # print(\" -\", p, \"%: acc=\", acc, \" new/old = \", acc / old_acc, \"!0-oldW\", nzow, \"!0-newW\", nznw)\n # pruned_metrics.append([loss, acc])\n #\n # print(\"test score: \", testScores)\n #\n\n import pickle\n\n print(\"keys:\", trainedWeights.keys())\n\n if saveToDisk:\n # save the models\n # for net in networks:\n # net.save(dirName + \"Net_\" + net.name)\n\n # save to disk the dictionary for all networks\n file = open(dirName + \"SeedsAndArchitectures.pkl\", \"wb\")\n pickle.dump(trainedWeights, file)\n file.close()\n\n end = time.time()\n print(\" execution time:\", end - start)\n\n return 0\n\n\ndef customtraining(net, data):\n Xtrain = data[0][0]\n Ytrain = data[0][1]\n Xtest = data[0][2]\n Ytest = data[0][3]\n\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', mode='min', baseline=0.1)\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', mode='min', min_delta=0.0001, verbose=1)\n\n maximumtrainepochs = 3000\n e = 1\n bs = 128\n ajn = 0\n\n M = []\n for l in range(1, len(net.layers)):\n m = net.layers[l].get_mask()[0].reshape(-1)\n M.extend(m)\n\n Ma = np.asarray(M)\n Wj = -np.count_nonzero(Ma)\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1000, verbose=2, shuffle=False, callbacks=[earlystopping_callback])\n\n while e < maximumtrainepochs:\n if e < 20:\n bs = 60\n if 100 > e > 20:\n bs = 600\n if e > 100:\n bs = 60000\n\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1, verbose=2, shuffle=False, callbacks=[earlystopping_callback])\n fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1, verbose=2, shuffle=False) # , callbacks=[earlystopping_callback])\n # print(\"approx sumlog2 \", fit_history.history['loss'][0] * 60000)\n Pj = -fit_history.history['loss'][-1] * Xtrain.shape[0]\n Ajn = Wj + Pj\n\n print(\"epoch\", e)\n print(\" loss*Datasize = \", fit_history.history['loss'][-1] * Xtrain.shape[0])\n print(\" loss = \", fit_history.history['loss'])\n print(\" Ajn = \", Ajn)\n e += 1\n\n return 0\n\n\ndef runmodels2(net, data, n_epochs=None, outputdir=None):\n if outputdir is None:\n dirName = dirNameDefault\n else:\n dirName = outputdir\n\n if n_epochs is None:\n n_epochs = epochs\n\n if saveToDisk:\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data will be saved in \", dirName)\n\n start = time.time()\n\n e = 0\n trainedWeights = {}\n\n ne = 150\n stop = False\n\n import localutils\n\n # get train data for network t\n Xtrain = data[0][0]\n Ytrain = data[0][1]\n Xtest = data[0][2]\n Ytest = data[0][3]\n\n # localutils.customtraining2(net, data)\n\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', min_delta=0.05)\n Loss = []\n VLoss = []\n batch_size = 1280\n patience = 10\n while e < 1500:\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False,validation_data=(Xtest, Ytest)) # , callbacks=[earlystopping_callback])\n fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False, validation_data=(Xtest, Ytest))\n # print(\"approx sumlog2 \", fit_history.history['loss'][0] * 60000)\n print(\"epoch\", e)\n # print(fit_history.history['loss'][-1] * batch_size)\n print(fit_history.history['loss'], fit_history.history['val_loss'])\n Loss.append(fit_history.history['loss'])\n VLoss.append(fit_history.history['val_loss'])\n\n if len(Loss) >= 2 * patience:\n vl0 = np.mean(np.asarray(VLoss)[-patience:-patience // 2])\n vl1 = np.mean(np.asarray(VLoss)[-patience // 2:])\n if vl1 > vl0:\n break\n\n # if e % 10 == 0:\n # customstopping(model=net, X=Xtrain, Y=Ytrain)\n\n e += 1\n\n W = []\n for l in range(1, len(net.layers)):\n w = net.layers[l].get_weights()[0]\n W.append(w)\n\n netseed = localutils.ExtractSeed(net.name)\n # add the network's weights to the dictionary of trained weights\n trainedWeights[netseed] = W\n\n import pickle\n\n print(\"keys:\", trainedWeights.keys())\n\n if saveToDisk:\n # save the models\n # for net in networks:\n # net.save(dirName + \"Net_\" + net.name)\n\n # save to disk the dictionary for all networks\n file = open(dirName + \"SeedsAndArchitectures.pkl\", \"wb\")\n pickle.dump(trainedWeights, file)\n file.close()\n\n end = time.time()\n print(\" execution time:\", end - start)\n\n return 0\n\n\ndef MakeModels():\n trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareFashionData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareCIFAR10Data()\n\n # print(\"nonzeros mean\",np.count_nonzero(trainImages,axis=(1,2,3)).mean())\n # print(\"nonzeros std\",np.count_nonzero(trainImages,axis=(1,2,3)).std())\n # print(\"nonzeros min\",np.count_nonzero(trainImages,axis=(1,2,3)).min())\n # print(\"nonzeros max\",np.count_nonzero(trainImages,axis=(1,2,3)).max())\n # input()\n\n # trainImages = (trainImages - trainImages.mean()) / trainImages.std()\n # testImages = (testImages - testImages.mean()) / testImages.std()\n\n (n_examples, sx, sy, nchannels) = trainImages.shape\n\n trainImages_f = trainImages.reshape(-1, sx * sy * nchannels)\n testImages_f = testImages.reshape(-1, sx * sy * nchannels)\n\n NNets = 20\n\n networks = []\n data = []\n\n import uuid\n for i in range(NNets):\n # dense_arch = np.asarray([20])\n # dense_arch = np.append(dense_arch, np.random.randint(20, 25, 3), axis=0)\n # np.random.seed(17)\n # dense_arch = np.random.randint(50, 100, 4)\n # dense_arch = [np.random.randint(290, 310), np.random.randint(90, 110)]\n dense_arch = []\n dense_arch = [300, 100]\n full_arch = [trainImages_f.shape[1]]\n full_arch.extend(dense_arch)\n full_arch.append(nclasses)\n\n masks = SetMaskToONe(full_arch)\n\n # for m in range(len(masks)):\n # print(masks[m])\n # DrawWeights(\"Weights_\", masks)\n\n # for t in range(1, 15):\n # if t % 2 == 1:\n # dense_arch[t] = 28 * 28\n myseed = np.random.randint(0, 123456789)\n # myseed = 24690568\n mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, myseed)\n networks.append(mlp)\n # mlp = makeSahredLayersdMLP(full_arch)\n # activemlp = ActiveMaskedMLP.makeActiveMaskedMLP(full_arch, masks, myseed)\n\n # mlp.set_weights(masks)\n # DrawWeights(\"aldjas\", mlp.get_weights())\n # cnn = makeSharedLayerCNN(trainImages.shape[1:], 10, \"cnn\")\n # networks.append(cnn)\n\n # simeplMLP=makeMLP(full_arch,)\n id = uuid.uuid4().hex\n\n # model_mlp = makeMLP(sx * sy * nchannels, nclasses, dense_arch,\n # name=\"mlp_\" + a2s(dense_arch) + \"_ID\" + id,\n # opt='adam', loss='categorical_crossentropy')\n # networks.append(activemlp)\n\n data.append([trainImages_f, trainLabels, testImages_f, testLabels])\n # data.append([trainImages, trainLabels, testImages, testLabels])\n\n for n in networks:\n n.summary()\n print(\"network name:\", n.name)\n print(\"parameters: \", n.count_params())\n\n print(\"\\n\\n\\n\")\n runmodels2(networks, data, n_epochs=epochs)\n\n return 0\n\n\ndef MakeModel():\n trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n (n_examples, sx, sy, nchannels) = trainImages.shape\n\n trainImages_f = trainImages.reshape(-1, sx * sy * nchannels)\n testImages_f = testImages.reshape(-1, sx * sy * nchannels)\n\n data = []\n\n import uuid\n dense_arch = []\n dense_arch = [289, 100]\n full_arch = [trainImages_f.shape[1]]\n full_arch.extend(dense_arch)\n full_arch.append(nclasses)\n\n masks = SetMaskToONe(full_arch)\n print(len(masks))\n print(masks[0].shape)\n import localutils\n # masks[0] = localutils.unfoldconvolution(28, 28, 12, 1)\n # masks[1] = localutils.unfoldconvolution(17, 17, 8, 1)\n # input()\n print(\"nonzeromasks:\", np.count_nonzero(ToArray(masks)))\n\n myseed = np.random.randint(0, 123456789)\n myseed = 24690568\n mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, myseed)\n id = uuid.uuid4().hex\n\n data.append([trainImages_f, trainLabels, testImages_f, testLabels])\n # data.append([trainImages, trainLabels, testImages, testLabels])\n\n mlp.summary()\n print(\"network name:\", mlp.name)\n print(\"parameters: \", mlp.count_params())\n print(\"\\n\\n\\n\")\n runmodels2(mlp, data, n_epochs=epochs)\n\n return 0\n\n\ndef main():\n MakeModel()\n\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"LotteryTickets/LTH.py","file_name":"LTH.py","file_ext":"py","file_size_in_byte":38368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"107061525","text":"from datetime import datetime\nfrom decimal import Decimal\n\nfrom peewee import fn\n\nfrom cockroachdb.modules.models import Order, OrderLine, Customer\nfrom cockroachdb.modules.transactions.base import BaseTransaction\n\n\nclass DeliveryTransaction(BaseTransaction):\n \"\"\"\n Delivery transaction\n\n Example:\n delivery = DeliveryTransaction(1, 100)\n delivery.run()\n \"\"\"\n\n DISTRICT_ITER_RANGE = [index + 1 for index in range(10)]\n\n def __init__(self, warehouse_id: int, carrier_id: int):\n \"\"\"\n Initiate a transaction for processing customer payment\n :param warehouse_id: warehouse number\n :param carrier_id: carrier identifier\n \"\"\"\n super().__init__()\n self.warehouse_id = warehouse_id\n self.carrier_id = carrier_id\n\n def _execute(self):\n \"\"\"\n Execute new delivery transaction\n :return: None\n \"\"\"\n for district_id in DeliveryTransaction.DISTRICT_ITER_RANGE:\n # Find next available order ID for delivery\n try:\n next_delivery_order: Order = (\n Order.select()\n .where(\n Order.carrier_id.is_null()\n & (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == district_id)\n )\n .order_by(Order.id)\n .limit(1)\n .get()\n )\n order_id = next_delivery_order.id\n except Order.DoesNotExist:\n continue\n\n if order_id is not None:\n # Retrieve order and order line details\n order_line: OrderLine = (\n OrderLine.select(fn.SUM(OrderLine.amount).alias(\"amount\"))\n .where(\n (OrderLine.warehouse_id == self.warehouse_id)\n & (OrderLine.district_id == district_id)\n & (OrderLine.order_id == order_id)\n )\n .get()\n )\n\n # Update order carrier ID\n Order.update(carrier_id=self.carrier_id).where(\n (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == district_id)\n & (Order.id == order_id)\n ).execute()\n\n # Update associated order line items\n OrderLine.update(delivery_date=datetime.utcnow()).where(\n (OrderLine.warehouse_id == self.warehouse_id)\n & (OrderLine.district_id == district_id)\n & (OrderLine.order_id == order_id)\n ).execute()\n\n # Update customer balance and delivery count\n Customer.update(\n balance=Customer.balance + Decimal(order_line.amount),\n delivery_count=Customer.delivery_count + 1,\n ).where(\n (Customer.warehouse_id == self.warehouse_id)\n & (Customer.district_id == district_id)\n & (Customer.id == next_delivery_order.customer_id)\n ).execute()\n\n @property\n def transaction_name(self):\n \"\"\"\n Transaction name\n :return: transaction name\n \"\"\"\n return \"delivery\"\n","sub_path":"cockroachdb/modules/transactions/delivery.py","file_name":"delivery.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"111937087","text":"import bs4\nimport re\nimport googlemaps\nimport json\nfrom datetime import datetime\nfrom googletrans import Translator\n\nfp = open(\"2019_7_page_5.html\", encoding =\"utf8\")\nsoup = bs4.BeautifulSoup(fp,'lxml')\naddr = []\naddrt = []\nt = Translator()\n\nfor i in soup.findAll(id = re.compile('^ContentPlaceHolder1_gdvMissingRegistrationdetails_lbllinkedfir')):\n if(i.text.find('रहात्या')==-1 & i.text.find('रहाच्या')==-1 &i.text.find('राहते')==-1 & i.text.find('राहच्या')==-1 & i.text.find('राहत्या')==-1 & i.text.find('रहाते')==-1 ):\n addr.append(i.text)\n\nfp = open(\"db_gen.txt\",\"a\",encoding=\"utf8\")\nfp1 = open(\"dbn_gen.txt\",\"a\",encoding=\"utf8\")\ngmaps = googlemaps.Client(key='AIzaSyBNbSHpD55qfU-m2WbrhoPEEIAHFEIIKVE')\nfor i in addr:\n result = gmaps.geocode(i)\n if (len(result)!=0) :\n lat = result[0][\"geometry\"][\"location\"][\"lat\"]\n lon = result[0][\"geometry\"][\"location\"][\"lng\"]\n fp.write(str(lat) + \" \" + str(lon) + \"\\n\")\n fp1.write(str(lat) + \" \" + str(lon) +\"\\n\" + \" [\" + i +\"]\" + \"\\n\")\nfp.close()\nfp1.close()\n\n\n \n","sub_path":"Data_analysis/db_gen_analysis.py","file_name":"db_gen_analysis.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"180276707","text":"import time\nfrom time import strftime, sleep\nimport subprocess\nimport digitalio\nimport board\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_rgb_display.st7789 as st7789\nimport qwiic_joystick\n\n\n\ncs_pin = digitalio.DigitalInOut(board.CE0)\ndc_pin = digitalio.DigitalInOut(board.D25)\nreset_pin = None\nBAUDRATE = 64000000\nspi = board.SPI()\ndisp = st7789.ST7789(\n spi,\n cs=cs_pin,\n dc=dc_pin,\n rst=reset_pin,\n baudrate=BAUDRATE,\n width=135,\n height=240,\n x_offset=53,\n y_offset=40,\n)\n\n\nheight = disp.width \nwidth = disp.height\nimage = Image.new(\"RGB\", (width, height))\nrotation = 90\n\ndraw = ImageDraw.Draw(image)\ndraw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))\ndisp.image(image, rotation)\n\npadding = -2\ntop = padding\nbottom = height - padding\nx = 0\n\nfont = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 18)\n\n# Turn on the backlight\nbacklight = digitalio.DigitalInOut(board.D22)\nbacklight.switch_to_output()\nbacklight.value = True\n\n# Enable the buttons for demo\nbuttonA = digitalio.DigitalInOut(board.D23)\nbuttonB = digitalio.DigitalInOut(board.D24)\n\n# Define default coordination\nx, y = 0, 0\n\n# Enable the joystick\njoystick = qwiic_joystick.QwiicJoystick()\n\nif joystick.is_connected() == False:\n print(\"The Qwiic Joystick device isn't connected to the system. Please check your connection\", \\\n file=sys.stderr)\n\njoystick.begin()\n\nprint(\"Initialized. Firmware Version: %s\" % joystick.get_version())\n\nwhile True:\n # Draw a black filled box to clear the image.\n draw.rectangle((0, 0, width, height), outline=0, fill=0)\n\n #TODO: fill in here. You should be able to look in cli_clock.py and stats.py \n\n # Get current time hour \n hour = int(strftime(\"%H\"))\n\n print(\"X: %d, Y: %d, Button: %d\" % ( \\\n joystick.get_horizontal(), \\\n joystick.get_vertical(), \\\n joystick.get_button()))\n\n time.sleep(0.1)\n\n # Button Push\n # while joystick.get_button() == 0:\n # ma_img = Image.open(\"mawen.jpeg\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n\n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Left\n while 500 < joystick.get_horizontal() <= 600 and joystick.get_vertical() == 0:\n ma_img = Image.open(\"species_icon/human.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Upper Left\n # while joystick.get_horizontal() == 1023 and 0 <= joystick.get_vertical() < 100:\n # ma_img = Image.open(\"2.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Up\n while joystick.get_horizontal() == 1023 and 500 <= joystick.get_vertical() < 600:\n ma_img = Image.open(\"species_icon/pikachu.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Upper Right\n # while joystick.get_horizontal() == 1023 and 1000 <= joystick.get_vertical() < 1024:\n # ma_img = Image.open(\"4.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Right\n while 500 <= joystick.get_horizontal() < 600 and 0 <= joystick.get_vertical() == 1023:\n ma_img = Image.open(\"species_icon/dog.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Lower Right\n # while joystick.get_horizontal() == 0 and 1000 <= joystick.get_vertical() < 1024:\n # ma_img = Image.open(\"6.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Down\n # while joystick.get_horizontal() == 0 and 500 <= joystick.get_vertical() < 600:\n # ma_img = Image.open(\"7.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Lower Left\n # while 0 <=joystick.get_horizontal() < 100 and 0 <= joystick.get_vertical() < 100:\n # ma_img = Image.open(\"8.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n\n \n\n\n\n\n # Display image.\n disp.image(image, rotation)\n time.sleep(1)\n","sub_path":"Final Project/translator copy.py","file_name":"translator copy.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"647152098","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport sys\nfrom PIL import Image\n\n# camera_idx为视频来源\ndef CatcUsbVideo(windows_name, camera_idx):\n cv2.namedWindow(windows_name)\n\n # 用cap接收视频来源\n cap = cv2.VideoCapture(camera_idx)\n print(camera_idx)\n\n # 获取视频的帧速率fps\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n # 获取视频的宽高\n size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n # 设置视频的解码器\n fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')\n # 获取视频的总帧数\n frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n print('视频详细信息:\\n\\tfps:', fps, '\\n\\t宽、高:', size, '\\n\\t总帧数:', frames, '\\n\\t解码器:', fourcc)\n\n # 告诉openCV使用人脸分类器\n classfier = cv2.CascadeClassifier(\"/home/ylhy/PycharmProjects/untitled/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_alt2.xml\")\n\n # 定义一个边框颜色\n color = (0, 255, 0)\n\n s = 0\n # 如果视频能被打开就开始循环\n while cap.isOpened():\n ok, frame = cap.read()\n if not ok:\n print(\"错误\")\n break\n # 将当前视频所循环获取的帧转换为灰度视频进行识别,提高速度\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # 开始人脸检测,把处理好的灰度视频传入\n # 1.2为图片缩放比例,3为需要检测的有效点数\n faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n # 如果大于0说明检测到了人脸\n if len(faceRects) > 0:\n for faceRects in faceRects:\n x, y, w, h = faceRects\n cv2.rectangle(frame, (x - 10, y - 10),(x + w +10, y + h +10), color, 2)\n s = s + 1\n cv2.imwrite('/home/ylhy/桌面/image_'+str(s)+'.jpg', frame)\n cv2.imshow(windows_name, frame)\n\n c = cv2.waitKey(10)\n if c & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n CatcUsbVideo(\"开始\",'/home/ylhy/桌面/as.mp4')\n","sub_path":"dome.py","file_name":"dome.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"147882568","text":"from collections import deque\n\n\n\"\"\"\nBinary search trees are a data structure that enforce an ordering over\nthe data they store. That ordering in turn makes it a lot more efficient\nat searching for a particular piece of data in the tree.\n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\n\n\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def __repr__(self):\n return f\"{self.value}\"\n\n # Insert the given value into the tree\n def insert(self, value):\n # First we check if the new value is less than the initial instances value\n if value < self.value:\n # We then check if the initial instances left pointer is equal to None\n if self.left is None:\n # If it is we then instantiate a new instance and set the initial instances left pointer to the new instance\n self.left = BSTNode(value)\n else:\n # We hop over the node that the instance is pointing to and insert new node recursively\n self.left.insert(value)\n else:\n # If the value of the instance was greater\n # We then check if the instances right pointer is equal to None\n if self.right is None:\n # If it is we then instantiate a new instance and set the initial instances right pointer to the new instance\n self.right = BSTNode(value)\n else:\n # We hop over the node that the instance is pointing to and insert new node recursively\n self.right.insert(value)\n\n # Return True if the tree contains the value\n # False if it does not\n\n def contains(self, target):\n # If initial instance value is the same as the new value return true\n if self.value is target:\n return True\n # We then decide which direction to traverse down the tree\n # If this is true we go left and check the values\n if self.value > target:\n if self.left is not None:\n return self.left.contains(target)\n # If this is true we go right and check the values\n elif self.value < target:\n if self.right is not None:\n return self.right.contains(target)\n else:\n # If neither of the previous conditions are met we return False\n return False\n\n # Return the maximum value found in the tree\n\n def get_max(self):\n if self.right == None:\n return self.value\n else:\n return self.right.get_max()\n\n # Call the function `fn` on the value of each node\n def for_each(self, fn):\n base = self.value\n if not self.left and not self.right:\n return fn(base)\n if self.left and not self.right:\n return fn(base), self.left.for_each(fn)\n if self.right and not self.left:\n return fn(base), self.right.for_each(fn)\n if self.right and self.left:\n return fn(base), self.right.for_each(fn), self.left.for_each(fn)\n\n # Part 2 -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n if node:\n self.in_order_print(node.left)\n print(node.value)\n self.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n\n def bft_print(self, node):\n queue = []\n queue.append(node)\n\n while len(queue) > 0:\n node = queue.pop(0)\n print(node.value)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n\n def dft_print(self, node):\n stack = []\n stack.append(node)\n\n while len(stack) > 0:\n node = stack.pop(-1)\n print(node.value)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self, node):\n pass\n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n pass\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244244441","text":"\"\"\"\nsentry.tagstore.v2.backend\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2010-2017 by the Sentry Team, see AUTHORS for more details.\n:license: BSD, see LICENSE for more details.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport six\n\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom django.db import connections, router, IntegrityError, transaction\nfrom django.db.models import Q, Sum\nfrom django.utils import timezone\nfrom operator import or_\nfrom six.moves import reduce\n\nfrom sentry import buffer\nfrom sentry.tagstore import TagKeyStatus\nfrom sentry.tagstore.base import TagStorage\nfrom sentry.utils import db\n\nfrom .models import EventTag, GroupTagKey, GroupTagValue, TagKey, TagValue\n\n\nclass TagStorage(TagStorage):\n \"\"\"\\\n The v2 tagstore backend stores and respects ``environment_id``.\n\n An ``environment_id`` value of ``None`` is used to keep track of the aggregate value across\n all environments.\n \"\"\"\n\n def setup(self):\n self.setup_deletions(\n tagkey_model=TagKey,\n tagvalue_model=TagValue,\n grouptagkey_model=GroupTagKey,\n grouptagvalue_model=GroupTagValue,\n eventtag_model=EventTag,\n )\n\n self.setup_cleanup(\n tagvalue_model=TagValue,\n grouptagvalue_model=GroupTagValue,\n eventtag_model=EventTag,\n )\n\n self.setup_merge(\n grouptagkey_model=GroupTagKey,\n grouptagvalue_model=GroupTagValue,\n )\n\n self.setup_tasks(\n tagkey_model=TagKey,\n )\n\n self.setup_receivers(\n tagvalue_model=TagValue,\n grouptagvalue_model=GroupTagValue,\n )\n\n # TODO(brett): v2-specific receivers for keeping environment aggregates up to date\n\n def create_tag_key(self, project_id, environment_id, key, **kwargs):\n return TagKey.objects.create(\n project_id=project_id,\n environment_id=environment_id,\n key=key,\n **kwargs\n )\n\n def get_or_create_tag_key(self, project_id, environment_id, key, **kwargs):\n return TagKey.objects.get_or_create(\n project_id=project_id,\n environment_id=environment_id,\n key=key,\n **kwargs\n )\n\n def create_tag_value(self, project_id, environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return TagValue.objects.create(\n project_id=project_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n value=value,\n **kwargs\n )\n\n def get_or_create_tag_value(self, project_id, environment_id,\n key, value, key_id=None, **kwargs):\n if key_id is None:\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n key_id = tag_key.id\n\n return TagValue.objects.get_or_create(\n project_id=project_id,\n environment_id=environment_id,\n _key_id=key_id,\n value=value,\n **kwargs\n )\n\n def create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return GroupTagKey.objects.create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n **kwargs\n )\n\n def get_or_create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return GroupTagKey.objects.get_or_create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n **kwargs\n )\n\n def create_group_tag_value(self, project_id, group_id, environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n tag_value, _ = self.get_or_create_tag_value(\n project_id, environment_id, key, value, **kwargs)\n\n return GroupTagValue.objects.create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n _value_id=tag_value.id,\n **kwargs\n )\n\n def get_or_create_group_tag_value(self, project_id, group_id,\n environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n tag_value, _ = self.get_or_create_tag_value(\n project_id, environment_id, key, value, **kwargs)\n\n return GroupTagValue.objects.get_or_create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n _value_id=tag_value.id,\n **kwargs\n )\n\n def create_event_tags(self, project_id, group_id, environment_id, event_id, tags):\n try:\n # don't let a duplicate break the outer transaction\n with transaction.atomic():\n # Tags are bulk inserted because this is an all-or-nothing situation.\n # Either the whole transaction works, or it doesn't. There's no value\n # in a partial success where we'd need to replay half of the rows.\n EventTag.objects.bulk_create([\n EventTag(\n project_id=project_id,\n environment_id=environment_id,\n group_id=group_id,\n event_id=event_id,\n key_id=key_id,\n value_id=value_id,\n )\n for key_id, value_id in tags\n ])\n except IntegrityError:\n pass\n\n def get_tag_key(self, project_id, environment_id, key, status=TagKeyStatus.VISIBLE):\n from sentry.tagstore.exceptions import TagKeyNotFound\n\n qs = TagKey.objects.filter(\n project_id=project_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n if status is not None:\n qs = qs.filter(status=status)\n\n try:\n return qs.get()\n except TagKey.DoesNotExist:\n raise TagKeyNotFound\n\n def get_tag_keys(self, project_id, environment_id, status=TagKeyStatus.VISIBLE):\n qs = TagKey.objects.filter(\n project_id=project_id,\n **self._get_environment_filter(environment_id)\n )\n\n if status is not None:\n qs = qs.filter(status=status)\n\n return list(qs)\n\n def get_tag_value(self, project_id, environment_id, key, value):\n from sentry.tagstore.exceptions import TagValueNotFound\n\n qs = TagValue.objects.filter(\n project_id=project_id,\n _key__key=key,\n value=value,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except TagValue.DoesNotExist:\n raise TagValueNotFound\n\n def get_tag_values(self, project_id, environment_id, key):\n qs = TagValue.objects.filter(\n project_id=project_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n return list(qs)\n\n def get_group_tag_key(self, project_id, group_id, environment_id, key):\n from sentry.tagstore.exceptions import GroupTagKeyNotFound\n\n qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except GroupTagKey.DoesNotExist:\n raise GroupTagKeyNotFound\n\n def get_group_tag_keys(self, project_id, group_id, environment_id, limit=None):\n qs = GroupTagKey.objects.filter(\n group_id=group_id,\n **self._get_environment_filter(environment_id)\n )\n\n if limit is not None:\n qs = qs[:limit]\n\n return list(qs)\n\n def get_group_tag_value(self, project_id, group_id, environment_id, key, value):\n from sentry.tagstore.exceptions import GroupTagValueNotFound\n\n qs = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key=key,\n _value__value=value,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except GroupTagValue.DoesNotExist:\n raise GroupTagValueNotFound\n\n def get_group_tag_values(self, project_id, group_id, environment_id, key):\n qs = GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n return list(qs)\n\n def delete_tag_key(self, project_id, key):\n from sentry.tagstore.tasks import delete_tag_key as delete_tag_key_task\n\n tagkeys_qs = TagKey.objects.filter(\n project_id=project_id,\n key=key,\n )\n\n deleted = []\n for tagkey in tagkeys_qs:\n updated = TagKey.objects.filter(\n id=tagkey.id,\n status=TagKeyStatus.VISIBLE,\n ).update(status=TagKeyStatus.PENDING_DELETION)\n\n if updated:\n delete_tag_key_task.delay(object_id=tagkey.id)\n deleted.append(tagkey)\n\n return deleted\n\n def delete_all_group_tag_keys(self, project_id, group_id):\n GroupTagKey.objects.filter(\n project_id=project_id,\n group_id=group_id,\n ).delete()\n\n def delete_all_group_tag_values(self, project_id, group_id):\n GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n ).delete()\n\n def incr_tag_key_values_seen(self, project_id, environment_id, key, count=1):\n buffer.incr(TagKey,\n columns={\n 'values_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'environment_id': environment_id,\n 'key': key,\n })\n\n def incr_tag_value_times_seen(self, project_id, environment_id,\n key, value, extra=None, count=1):\n buffer.incr(TagValue,\n columns={\n 'times_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'environment_id': environment_id,\n 'key': key,\n 'value': value,\n },\n extra=extra)\n\n def incr_group_tag_key_values_seen(self, project_id, group_id, environment_id, key, count=1):\n buffer.incr(GroupTagKey,\n columns={\n 'values_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'group_id': group_id,\n 'environment_id': environment_id,\n 'key': key,\n })\n\n def incr_group_tag_value_times_seen(self, project_id, group_id, environment_id,\n key, value, extra=None, count=1):\n buffer.incr(GroupTagValue,\n columns={\n 'times_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'group_id': group_id,\n 'environment_id': environment_id,\n 'key': key,\n 'value': value,\n },\n extra=extra)\n\n def get_group_event_ids(self, project_id, group_id, environment_id, tags):\n tagkeys = dict(\n TagKey.objects.filter(\n project_id=project_id,\n key__in=tags.keys(),\n status=TagKeyStatus.VISIBLE,\n **self._get_environment_filter(environment_id)\n ).values_list('key', 'id')\n )\n\n tagvalues = {\n (t[1], t[2]): t[0]\n for t in TagValue.objects.filter(\n reduce(or_, (Q(_key__key=k, value=v)\n for k, v in six.iteritems(tags))),\n project_id=project_id,\n **self._get_environment_filter(environment_id)\n ).values_list('id', '_key__key', 'value')\n }\n\n try:\n tag_lookups = [(tagkeys[k], tagvalues[(k, v)])\n for k, v in six.iteritems(tags)]\n # [(1, 10), ...]\n except KeyError:\n # one or more tags were invalid, thus the result should be an empty\n # set\n return []\n\n # Django doesnt support union, so we limit results and try to find\n # reasonable matches\n\n # get initial matches to start the filter\n k, v = tag_lookups.pop()\n matches = list(\n EventTag.objects.filter(\n project_id=project_id,\n group_id=group_id,\n key_id=k,\n value_id=v,\n **self._get_environment_filter(environment_id)\n ).values_list('event_id', flat=True)[:1000]\n )\n\n # for each remaining tag, find matches contained in our\n # existing set, pruning it down each iteration\n for k, v in tag_lookups:\n matches = list(\n EventTag.objects.filter(\n project_id=project_id,\n group_id=group_id,\n event_id__in=matches,\n key_id=k,\n value_id=v,\n **self._get_environment_filter(environment_id)\n ).values_list('event_id', flat=True)[:1000]\n )\n if not matches:\n return []\n\n return matches\n\n def get_groups_user_counts(self, project_id, group_ids, environment_id):\n qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id__in=group_ids,\n _key__key='sentry:user',\n **self._get_environment_filter(environment_id)\n )\n\n return defaultdict(int, qs.values_list('group_id', 'values_seen'))\n\n def get_group_tag_value_count(self, project_id, group_id, environment_id, key):\n if db.is_postgres():\n # This doesnt guarantee percentage is accurate, but it does ensure\n # that the query has a maximum cost\n using = router.db_for_read(GroupTagValue)\n cursor = connections[using].cursor()\n cursor.execute(\n \"\"\"\n SELECT SUM(t)\n FROM (\n SELECT times_seen as t\n FROM tagstore_grouptagvalue\n INNER JOIN tagstore_tagkey\n ON (tagstore_grouptagvalue.key_id = tagstore_tagkey.id)\n WHERE tagstore_grouptagvalue.group_id = %s\n AND tagstore_grouptagvalue.environment_id = %s\n AND tagstore_tagkey.key = %s\n ORDER BY last_seen DESC\n LIMIT 10000\n ) as a\n \"\"\", [group_id, environment_id, key]\n )\n return cursor.fetchone()[0] or 0\n\n cutoff = timezone.now() - timedelta(days=7)\n return GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n last_seen__gte=cutoff,\n **self._get_environment_filter(environment_id)\n ).aggregate(t=Sum('times_seen'))['t']\n\n def get_top_group_tag_values(self, project_id, group_id, environment_id, key, limit=3):\n if db.is_postgres():\n # This doesnt guarantee percentage is accurate, but it does ensure\n # that the query has a maximum cost\n return list(\n GroupTagValue.objects.raw(\n \"\"\"\n SELECT *\n FROM (\n SELECT tagstore_grouptagvalue.id,\n tagstore_grouptagvalue.project_id,\n tagstore_grouptagvalue.group_id,\n tagstore_grouptagvalue.environment_id,\n tagstore_grouptagvalue.times_seen,\n tagstore_grouptagvalue.key_id,\n tagstore_grouptagvalue.value_id,\n tagstore_grouptagvalue.last_seen,\n tagstore_grouptagvalue.first_seen\n FROM tagstore_grouptagvalue\n INNER JOIN tagstore_tagkey\n ON (tagstore_grouptagvalue.key_id = tagstore_tagkey.id)\n WHERE tagstore_grouptagvalue.group_id = %%s\n AND tagstore_grouptagvalue.environment_id = %%s\n AND tagstore_tagkey.key = %%s\n ORDER BY last_seen DESC\n LIMIT 10000\n ) as a\n ORDER BY times_seen DESC\n LIMIT %d\n \"\"\" % limit, [group_id, environment_id, key]\n )\n )\n\n cutoff = timezone.now() - timedelta(days=7)\n return list(\n GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n last_seen__gte=cutoff,\n **self._get_environment_filter(environment_id)\n ).order_by('-times_seen')[:limit]\n )\n\n def get_first_release(self, project_id, group_id):\n try:\n first_release = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key__in=('sentry:release', 'release'),\n ).order_by('first_seen')[0]\n except IndexError:\n return None\n else:\n return first_release.value\n\n def get_last_release(self, project_id, group_id):\n try:\n last_release = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key__in=('sentry:release', 'release'),\n ).order_by('-last_seen')[0]\n except IndexError:\n return None\n\n return last_release.value\n\n def get_release_tags(self, project_ids, environment_id, versions):\n return list(TagValue.objects.filter(\n project_id__in=project_ids,\n _key__key='sentry:release',\n value__in=versions,\n **self._get_environment_filter(environment_id)\n ))\n\n def get_group_ids_for_users(self, project_ids, event_users, limit=100):\n return list(GroupTagValue.objects.filter(\n project_id__in=project_ids,\n environment_id__isnull=True,\n _key__key='sentry:user',\n _value__value__in=[eu.tag_value for eu in event_users],\n ).order_by('-last_seen').values_list('group_id', flat=True)[:limit])\n\n def get_group_tag_values_for_users(self, event_users, limit=100):\n tag_filters = [\n Q(_value__value=eu.tag_value, project_id=eu.project_id)\n for eu in event_users\n ]\n\n return list(GroupTagValue.objects.filter(\n reduce(or_, tag_filters),\n environment_id__isnull=True,\n _key__key='sentry:user',\n ).order_by('-last_seen')[:limit])\n\n def get_group_ids_for_search_filter(self, project_id, environment_id, tags):\n from sentry.search.base import ANY, EMPTY\n # Django doesnt support union, so we limit results and try to find\n # reasonable matches\n\n # ANY matches should come last since they're the least specific and\n # will provide the largest range of matches\n tag_lookups = sorted(six.iteritems(tags), key=lambda x: x != ANY)\n\n # get initial matches to start the filter\n matches = None\n\n # for each remaining tag, find matches contained in our\n # existing set, pruning it down each iteration\n for k, v in tag_lookups:\n if v is EMPTY:\n return None\n\n elif v != ANY:\n base_qs = GroupTagValue.objects.filter(\n project_id=project_id,\n _key__key=k,\n _value__value=v,\n **self._get_environment_filter(environment_id)\n )\n\n else:\n base_qs = GroupTagValue.objects.filter(\n project_id=project_id,\n _key__key=k,\n **self._get_environment_filter(environment_id)\n ).distinct()\n\n if matches:\n base_qs = base_qs.filter(group_id__in=matches)\n else:\n # restrict matches to only the most recently seen issues\n base_qs = base_qs.order_by('-last_seen')\n\n matches = list(base_qs.values_list('group_id', flat=True)[:1000])\n\n if not matches:\n return None\n\n return matches\n\n def update_group_tag_key_values_seen(self, project_id, group_ids):\n gtk_qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id__in=group_ids\n )\n\n for instance in gtk_qs:\n instance.update(\n values_seen=GroupTagValue.objects.filter(\n project_id=instance.project_id,\n group_id=instance.group_id,\n environment_id=instance.environment_id,\n key=instance.key,\n ).count(),\n )\n\n def get_tag_value_qs(self, project_id, environment_id, key, query=None):\n queryset = TagValue.objects.filter(\n project_id=project_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n if query:\n queryset = queryset.filter(value__contains=query)\n\n return queryset\n\n def get_group_tag_value_qs(self, project_id, group_id, environment_id, key):\n return GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n def update_group_for_events(self, project_id, event_ids, destination_id):\n return EventTag.objects.filter(\n project_id=project_id,\n event_id__in=event_ids,\n ).update(group_id=destination_id)\n\n def _get_environment_filter(self, environment_id):\n if environment_id is None:\n return {'environment_id__isnull': True}\n else:\n return {'environment_id': environment_id}\n","sub_path":"src/sentry/tagstore/v2/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":23262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"515340574","text":"import abc\nimport serial # type: ignore\nimport telnetlib\nimport threading\n\nfrom typing import Optional\n\nimport logging\n\nlogging.basicConfig()\n_LOGGER = logging.getLogger(\"nad_receiver.transport\")\n\n\nDEFAULT_TIMEOUT = 1\n\n\nclass NadTransport(abc.ABC):\n @abc.abstractmethod\n def communicate(self, command: str) -> str:\n pass\n\n\nclass SerialPortTransport:\n \"\"\"Transport for NAD protocol over RS-232.\"\"\"\n\n def __init__(self, serial_port: str) -> None:\n \"\"\"Create RS232 connection.\"\"\"\n self.ser = serial.Serial(\n serial_port,\n baudrate=115200,\n timeout=DEFAULT_TIMEOUT,\n write_timeout=DEFAULT_TIMEOUT,\n )\n self.lock = threading.Lock()\n\n def __repr__(self):\n return f\"SerialPortTransport\"\n\n def _open_connection(self) -> None:\n if not self.ser.is_open:\n self.ser.open()\n _LOGGER.debug(\"serial open: %s\", self.ser.is_open)\n\n def communicate(self, command: str) -> str:\n with self.lock:\n self._open_connection()\n\n self.ser.write(f\"\\r{command}\\r\".encode(\"utf-8\"))\n # To get complete messages, always read until we get '\\r'\n # Messages will be of the form '\\rMESSAGE\\r' which\n # pyserial handles nicely\n msg = self.ser.read_until(\"\\r\")\n if not msg.strip(): # discard '\\r' if it was sent\n msg = self.ser.read_until(\"\\r\")\n assert isinstance(msg, bytes)\n return msg.strip().decode()\n\n\nclass TelnetTransport:\n \"\"\"\n Support NAD amplifiers that use telnet for communication.\n Supports all commands from the RS232 base class\n\n Known supported model: Nad T787.\n \"\"\"\n\n def __init__(self, host: str, port: int, timeout: int) -> None:\n \"\"\"Create NADTelnet.\"\"\"\n self.telnet: Optional[telnetlib.Telnet] = None\n self.host = host\n self.port = port\n self.timeout = timeout\n\n def _open_connection(self) -> None:\n if not self.telnet:\n try:\n self.telnet = telnetlib.Telnet(self.host, self.port, 3)\n # Some versions of the firmware report Main.Model=T787.\n # some versions do not, we want to clear that line\n self.telnet.read_until(\"\\n\".encode(), self.timeout)\n # Could raise eg. EOFError, UnicodeError\n except (EOFError, UnicodeError):\n pass\n\n def communicate(self, cmd: str) -> str:\n self._open_connection()\n assert self.telnet\n\n self.telnet.write(f\"\\r{cmd}\\r\".encode())\n msg = self.telnet.read_until(b\"\\r\", self.timeout)\n return msg.strip().decode()\n","sub_path":"nad_receiver/nad_transport.py","file_name":"nad_transport.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"436238173","text":"import tkinter as tk\n\nHEIGHT = 700\nWIDTH = 600\nroot = tk.Tk()\nroot.title(\"App\")\n\ntk.Label(root, text=\"First Name\").grid(row=0)\ntk.Label(root, text=\"Last Name\").grid(row=1)\n\ne1 = tk.Entry(root)\ne2 = tk.Entry(root)\n\ne1.grid(row=0, column=1)\ne2.grid(row=1, column=1)\n\n\nroot.mainloop()","sub_path":"vijay47.py","file_name":"vijay47.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"368685780","text":"\r\nclass ACO():\r\n\t\"\"\"docstring for ACO\"\"\"\r\n\r\n\tdistance_matrix = None\r\n\tcity_count = None\r\n\tparams = {}\r\n\r\n\tants = []\r\n\tpheromone = []\r\n\r\n\tdef __init__(self, distance_matrix, params):\r\n\t\t\"\"\"args - distance matrix\"\"\"\r\n\t\tACO.distance_matrix = distance_matrix\r\n\t\tACO.city_count = len(distance_matrix)\r\n\t\tACO.pheromone = [[0 for i in range(ACO.city_count)] for j in range(ACO.city_count)]\r\n\r\n\t\tsource = 0\r\n\t\tfor i in range(30):\r\n\t\t\tACO.ants.append(Ant(source))\r\n\t\t\tsource += 1\r\n\t\t\tsource = source % ACO.city_count\r\n\r\n\tdef find_route(self):\r\n\t\tprint('finding route')\r\n\r\n\tdef best_route(self):\r\n\t\tprint('the best route is')\r\n\r\n\r\nclass Ant():\r\n\r\n\tdef __init__(self, start_city):\r\n\t\tself.cur_city = start_city\r\n\t\tself.path = [start_city]\r\n\t\tself.tour_length = 0\r\n\r\n\tdef move_to_city(self, city):\r\n\t\tself.path.append(city)\r\n\t\tself.tour_length += ACO.distance_matrix[self.cur_city][city]\r\n\t\tif len(self.path) == ACO.city_count:\r\n\t\t\tself.tour_length += ACO.distance_matrix[self.path[-1]][self.path[0]]\r\n\t\tself.cur_city = city\r\n\r\n\tdef can_move(self):\r\n\t\treturn len(self.path) < ACO.city_count\r\n\r\n\tdef reset(self, city):\r\n\t\tself.cur_city = city\r\n\t\tself.path = [city]\r\n\t\tself.tour_length = 0.\r\n","sub_path":"aco.py","file_name":"aco.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"510401534","text":"import sympy\n\nif __name__ == \"__main__\":\n overall = 600851475143\n largestPrimeFactor = None\n checkNum = 5\n while (checkNum * checkNum) <= overall:\n checkNum = sympy.nextprime(checkNum)\n if overall % checkNum == 0:\n largestPrimeFactor = checkNum\n print(\"Largest prime factor of 600851475143 is: {0}\".format(largestPrimeFactor))\n","sub_path":"python/3_largestPrime.py","file_name":"3_largestPrime.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"562344287","text":"'''\n\nThis module is for tests using a combination of n-grams and other features.\n\nFor n-gram only tests, use ngram-only-tests.py.\n\nFor non n-gram only tests, use non-ngram-only-tests.py.\n\nThe code relating to scikit-learn was adapted from code on the scikit-learn website: https://scikit-learn.org/\n\n'''\nimport numpy as np\nimport sys\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.feature_extraction.text import CountVectorizer\n\ncorpus = [] # List of sentences in human-readable form (i.e. not in a bag of words representation).\ndocumentClassificationList = [] # Stored as strings - true = formal, false = informal.\nformalityScoreList = [] # Mechanical Turk formality scores.\nnonDocumentData = [] # List of lists, each containing a sentence's attribute data.\ndataFileFieldNames = [] # The field names from the top of the data spreadsheet.\ncorpus = [] # List of sentences in human-readable form (i.e. not in a bag of words representation).\ndocumentClassificationList = [] # Stored as strings - true = formal, false = informal.\nformalityScoreList = [] # Mechanical Turk formality scores.\nnonDocumentData = [] # List of lists, each containing a sentence's attribute data.\ndataFileFieldNames = [] # The field names from the top of the data spreadsheet.\nfieldsToSelectFrom = [] # List of features that the user has not selected for the test.\nchosenFields = [] # List of features that the user has selected for the test.\nfileName = \"new_formality_data.csv\"\n\n\n# Checks if the 'fileName' is the correct file name\ndef checkFileNameCorrect():\n global fileName\n print(\"The default data file name is \", fileName, \"\\n\")\n print(\"If this is the name of the data file you are using, simply press enter\")\n newFileName = input(\"Otherwise, please provide the correct name, and then press enter: \")\n if newFileName != \"\":\n fileName = newFileName\n print(\"\\nThank you. The file name has been changed to:\", fileName)\n else:\n print(\"\\nThank you. You have confirmed that the existing file name is correct:\", fileName)\n\n\n# Checks if file present. Code for this module adapted from:\n# https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python\ndef checkFilePresent():\n try:\n f = open(fileName, 'rb')\n except OSError:\n print(\"\\nFile not found:\", fileName)\n print(\"Please ensure that the data file is in the same folder as the program file.\")\n print(\"Exiting program.\")\n sys.exit()\n\n\n# This function loads the data from the file and stores it in the data structures shown above.\n# It is always the first function to be run.\ndef loadData():\n checkFileNameCorrect() # Asks user is data file name is correct\n checkFilePresent() # Checks if data file is present\n with open(fileName, encoding='utf-8') as inputFile:\n firstLine = inputFile.readline()\n firstLineAsList = firstLine.split(\",\")\n # Copy the data file field names into a global list:\n for items in firstLineAsList:\n dataFileFieldNames.append(items)\n\n # The sentence field is always the final field on the right. Therefore, the sentence index is the number of\n # fields up to and including the one immediately preceding the 'sentence' field.\n sentenceIndex = len(firstLineAsList)-1\n for line in inputFile:\n\n # Searches through the line for commas, character by character. Stops when 'sentenceIndex' number of commas\n # have been encountered.\n # The document is located to the right of the comma corresponding to index 'sentenceIndex'.\n # Everything to the left of that comma is data relating to the document.\n numCommas = 0\n for character in range(len(line)):\n\n # Increments numCommas whenever a comma is encountered in the line.\n if line[character] == \",\":\n numCommas = numCommas + 1\n\n # The code below is run when when the number of commas encountered equals the value of 'sentenceIndex'.\n # When the code below is run, it means that everything on the line to the right of the last comma\n # encountered is part of the sentence, and not attribute data.\n if numCommas == sentenceIndex:\n dataExcludingSentence = line[:character]\n dataExcludingSentenceAsList = dataExcludingSentence.split(\",\")\n nonDocumentData.append(dataExcludingSentenceAsList)\n formalityScore = float(dataExcludingSentenceAsList[2])\n formalityScoreList.append(formalityScore)\n # If mechanical Turk formality score >=4 then formal status = true:\n documentClassificationList.append(formalityScore >= 4)\n documentToAdd = line[character + 1:] # The rest of the current line is comprised of the document\n documentToAdd.replace('\\n', '') # Removes 'next line' symbol \\n from the end of the document\n\n # Puts document into a list of Strings:\n corpus.append(documentToAdd)\n break # returns to the outer 'for' loop, so the next line can be processed.\n inputFile.close()\n print(\"\\nNo of records uploaded: \", len(corpus))\n\n\n# This function performs the machine learning test and outputs a classification prediction result summary.\ndef classificationResults(featureData, classificationLabels, featureDescription):\n\n # The two lines below convert the lists passed into the function to arrays.\n X = np.array(featureData)\n y = np.array(classificationLabels)\n\n # Splits the data into training and testing sets using 5 split k fold:\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=12345)\n skf.split(X, y)\n X_train = []\n X_test = []\n y_train = []\n y_test = []\n for train_index, test_index in skf.split(X, y):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n\n # Fits the data to a model. The model is initially instantiated as SVC so that the definitions of 'classifier' in\n # the 'if' statements below it aren't out of scope of the rest of the module.\n model = SVC(gamma='scale', kernel='linear', probability=True).fit(X_train, y_train)\n if classifier == \"Logistic Regression\":\n model = LogisticRegression(random_state=0, solver='lbfgs',max_iter=1000).fit(X_train, y_train)\n if classifier == \"Multinomial Bayes\":\n model = MultinomialNB().fit(X_train, y_train)\n if classifier == \"Random Forest\":\n model = RandomForestClassifier().fit(X_train, y_train)\n\n # Generates a prediction for each sentence, and stores them in a list called 'predictions'.\n predictions = model.predict(np.array(X_test))\n\n # Calculates true positives, true negatives, false positives and false negatives:\n truePositives = 0\n trueNegatives = 0\n falsePositives = 0\n falseNegatives = 0\n numberInList = 0\n for prediction in predictions:\n\n # Is this a formal sentence which was predicted to be formal?\n if y_test[numberInList] and prediction:\n truePositives = truePositives + 1\n\n # Is this an informal sentence which was predicted to be informal?\n if not y_test[numberInList] and not prediction:\n trueNegatives = trueNegatives + 1\n\n # Is this an informal sentence which was predicted to be formal?\n if not y_test[numberInList] and prediction:\n falsePositives = falsePositives + 1\n\n # Is this a formal sentence which was predicted to be informal?\n if y_test[numberInList] and not prediction:\n falseNegatives = falseNegatives + 1\n numberInList = numberInList + 1\n\n # Performance metrics\n if (truePositives + trueNegatives + falsePositives + falseNegatives) > 0:\n accuracy = (truePositives + trueNegatives) / (truePositives + trueNegatives + falsePositives + falseNegatives)\n else:\n accuracy = 0\n if (truePositives + falsePositives) > 0:\n precision = truePositives / (truePositives + falsePositives)\n else:\n precision = 0\n if (truePositives + falseNegatives) > 0:\n recall = truePositives / (truePositives + falseNegatives)\n else:\n recall = 0\n if (trueNegatives + falsePositives) > 0:\n fallout = falsePositives / (trueNegatives + falsePositives) # 'Fallout' is the same as the false positive rate.\n else:\n fallout = 0\n balAccuracy = balanced_accuracy_score(y_test, predictions)\n\n # Area under roc curve\n y_scores = model.predict_proba(X_test)\n y_scores = y_scores[:, 1]\n rocAreaUnderCurve = roc_auc_score(y_test, y_scores)\n\n # Console output\n print(\"\\nFeature tested:\\n\", featureDescription)\n print(\"Classifier: \" + classifier, \"\\n\")\n print(\"Total predictions: \", numberInList)\n print(\"TRUE POSITIVES: \", truePositives)\n print(\"FALSE POSITIVES: \", falsePositives)\n print(\"TRUE NEGATIVES: \", trueNegatives)\n print(\"FALSE NEGATIVES: \", falseNegatives)\n # Division by zero is illegal, so if the denominator is zero, then 'N/A' is given as the metric's value.\n if accuracy > 0:\n print(\"Accuracy: %3.2f\" % accuracy)\n else:\n print(\"Accuracy: N/A\")\n if precision > 0:\n print(\"Precision: %3.2f\" % precision)\n else:\n print(\"Precision: N/A\")\n if recall > 0:\n print(\"Recall: %3.2f\" % recall)\n else:\n print(\"Recall: N/A\")\n if fallout > 0:\n print(\"False positive rate: %3.2f\" % fallout)\n else:\n print(\"False positive rate: N/A\")\n print(\"AUC: %3.2f\" % rocAreaUnderCurve)\n print(\"Balanced accuracy: %3.2f\" % balAccuracy)\n\n\n# Asks the user what type of n-gram they want to test.\ndef askForType():\n print(\"\\nThe n-gram types are: \")\n print(\"1 - Unigram\")\n print(\"2 - Bigram\")\n print(\"3 - Trigram\")\n print(\"4 - Unigram and bigram combined\")\n print(\"5 - Unigram, bigram and trigram combined\")\n userChoice = input(\"\\nChoose an option by typing a number between 1 and 5 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global nGramType\n userChoice = int(userChoice)\n if userChoice == 1:\n nGramType = \"unigram\"\n return\n if userChoice == 2:\n nGramType = \"bigram\"\n return\n if userChoice == 3:\n nGramType = \"trigram\"\n return\n if userChoice == 4:\n nGramType = \"1, 2 gram\"\n return\n if userChoice == 5:\n nGramType = \"1, 2, 3 gram\"\n return\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForType()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForType()\n\n\n# Asks user whether n-gram will be binary, non-binary or TF-IDF representation\ndef askForRepresentation():\n print(\"\\nThe representation options are: \")\n print(\"1 - Binary\")\n print(\"2 - Non-Binary\")\n print(\"3 - TF-IDF\")\n userChoice = input(\"\\nChoose an option by typing a number between 1 and 3 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global representation\n userChoice = int(userChoice)\n if userChoice == 1:\n representation = \"binary\"\n return\n if userChoice == 2:\n representation = \"non-binary\"\n return\n if userChoice == 3:\n representation = \"TF-IDF\"\n return\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForRepresentation()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForRepresentation()\n\n\n# Asks the user if they want stop words including in their test\ndef askAboutStopWords():\n print(\"\\nThe stop word options are: \")\n print(\"1 - Include stop words\")\n print(\"2 - No, do not include stop words\")\n userChoice = input(\"\\nChoose an option by typing 1 or 2 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global stops\n userChoice = int(userChoice)\n if userChoice == 1:\n stops = \"with stop words\"\n return\n if userChoice == 2:\n stops = \"without stop words\"\n return\n else:\n print(\"Invalid selection. Please try again\")\n askAboutStopWords()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askAboutStopWords()\n\n\n# Asks user which classifier to use\ndef askForClassifier():\n print(\"\\nThe classifiers are: \\n1 - Support Vector Machine\\n2 - Logistic Regression\\n3 - Multinomial Bayes\\n\"\n \"4 - Random Forest\")\n classifierChoice = input(\"\\nPlease choose a classifier by typing a number between 1 and 4 and then press 'enter': \")\n if classifierChoice.isnumeric():\n classifierChoice = int(classifierChoice)\n global classifier\n if classifierChoice == 1:\n print(\"You have selected Support Vector Machine\")\n classifier = \"Support Vector Machine\"\n return\n if classifierChoice == 2:\n print(\"You have selected Logistic Regression\")\n classifier = \"Logistic Regression\"\n return\n if classifierChoice == 3:\n print(\"You have selected Multinomial Bayes\")\n classifier = \"Multinomial Bayes\"\n return\n if classifierChoice == 4:\n print(\"You have selected Random Forest\")\n classifier = \"Random Forest\"\n return\n else:\n print(\"\\nThat was not a valid selection. Please try again.\")\n askForClassifier()\n else:\n print(\"\\nThat was not a valid selection. Please try again.\")\n askForClassifier()\n\n\n# Selects the correct vector type to create based on the user's test choices.\ndef setVector(nGramType, representation, stops):\n # UNIGRAMS\n\n # Unigram, binary representation, stop words included.\n if nGramType == \"unigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 1))\n\n # Unigram, binary representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 1))\n\n # Unigram, non-binary representation, stop words included.\n if nGramType == \"unigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 1))\n\n # Unigram, non-binary representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 1))\n\n # Unigram, TF-IDF representation, stop words included.\n if nGramType == \"unigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 1))\n\n # Unigram, TF-IDF representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 1))\n\n # BIGRAMS\n\n # Bigram, binary representation, stop words included.\n if nGramType == \"bigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(2, 2))\n\n # Bigram, binary representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(2, 2))\n\n # Bigram, non-binary representation, stop words included.\n if nGramType == \"bigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(2, 2))\n\n # Bigram, non-binary representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(2, 2))\n\n # Bigram, TF-IDF representation, stop words included.\n if nGramType == \"bigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(2, 2))\n\n # Bigram, TF-IDF representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(2, 2))\n\n # TRIGRAMS\n\n # Trigram, binary representation, stop words included.\n if nGramType == \"trigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(3, 3))\n\n # Trigram, binary representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(3, 3))\n\n # Trigram, non-binary representation, stop words included.\n if nGramType == \"trigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(3, 3))\n\n # Trigram, non-binary representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(3, 3))\n\n # Trigram, TF-IDF representation, stop words included.\n if nGramType == \"trigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(3, 3))\n\n # Trigram, TF-IDF representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(3, 3))\n\n # UNIGRAMS AND BIGRAMS COMBINED\n\n # Unigram and bigram combined, binary representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 2))\n\n # Unigram and bigram combined, binary representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 2))\n\n # Unigram and bigram combined, non-binary representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 2))\n\n # Unigram and bigram combined, non-binary representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 2))\n\n # Unigram and bigram combined, TF-IDF representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 2))\n\n # Unigram and bigram combined, TF-IDF representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 2))\n\n # UNIGRAMS, BIGRAMS AND TRIGRAMS COMBINED\n\n # Unigram, bigram and trigram combined, binary representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, binary representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, non-binary representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, non-binary representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, TF-IDF representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, TF-IDF representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 3))\n\n\n# Puts all non n-gram feature field names into list 'fieldsToSelectFrom', except those that are not feature fields.\ndef createFeatureFieldList():\n nonFeatureFields = ['HIT ID', 'Sentence ID', 'Formality', 'Actual sentence\\n']\n for fieldName in dataFileFieldNames:\n if fieldName not in nonFeatureFields:\n fieldsToSelectFrom.append(fieldName)\n\n\n# Prints a list of fields that are available (excludes fields already selected by the user)\ndef printAvailableFields():\n count = 1\n print(\"\\nYou can add the following features to the test: \\n\")\n for fieldName in fieldsToSelectFrom:\n print(count, \"-\", fieldName)\n count = count + 1\n\n\n# Asks the user to choose the features they want to test. Stores field names in 'chosenFields'.\ndef askForNonNgramFeatures():\n if not fieldsToSelectFrom: # If all the available features have already been selected by the user\n print(\"\\nYou have selected all the available features. You will now be asked to choose a classifier.\")\n if not chosenFields: # If no selections yet made by the user.\n printAvailableFields()\n print(\"\\nNo features have been selected yet\")\n featureChoice = input(\"\\nPlease choose the number of a feature to add: \")\n if featureChoice.isnumeric():\n featureChoice = int(featureChoice)\n\n # If a valid selection is made, adds the field name to chosenFields and removes it from fieldsToSelect.\n if 0 <= featureChoice <= len(fieldsToSelectFrom):\n print(\"\\nYou have just selected: \" + fieldsToSelectFrom[featureChoice - 1])\n chosenFields.append(fieldsToSelectFrom[featureChoice - 1])\n fieldsToSelectFrom.remove(fieldsToSelectFrom[featureChoice - 1])\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a valid number. Please try again.\")\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a number. Please try again.\")\n askForNonNgramFeatures()\n\n # If the user has made at least one selection already\n else:\n print(\"\\nSo far, you have selected the following features: \")\n for fields in chosenFields:\n print(fields)\n printAvailableFields()\n featureChoice = input(\"\\nPlease choose an additional feature and press 'enter'\\nor press C then 'enter' to \"\n \"select your classifier: \")\n if featureChoice.isnumeric():\n featureChoice = int(featureChoice)\n\n # If a valid selection is made, adds the field name to chosenFields and removes it from fieldsToSelect.\n if 0 <= featureChoice <= len(fieldsToSelectFrom):\n print(\"\\nYou have just selected: \" + fieldsToSelectFrom[featureChoice - 1])\n chosenFields.append(fieldsToSelectFrom[featureChoice - 1])\n fieldsToSelectFrom.remove(fieldsToSelectFrom[featureChoice - 1])\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a valid number. Please try again.\")\n askForNonNgramFeatures()\n\n # Pressing 'C' exits the function.\n elif featureChoice == \"C\":\n return\n\n # If neither 'C' nor a number entered:\n else:\n print(\"You did not enter a number. Please try again.\")\n askForNonNgramFeatures()\n\n\n# Creates a human-readable description of the selected features.\ndef nonNGramFeatureDescription():\n featureDesc = \"\"\n count = 0\n for feature in chosenFields:\n count = count + 1\n\n # If the first or only feature\n if count == 1:\n featureDesc = '\\'' + feature + '\\''\n continue\n\n # If not final feature in list of multiple features (but not the first)\n if count != len(chosenFields):\n featureDesc = featureDesc + \", \" + '\\'' + feature + '\\''\n\n # If final feature in list of multiple features\n if count == len(chosenFields):\n featureDesc = featureDesc + \" and \" + '\\'' + feature + '\\''\n return featureDesc\n\n\ndef setParameters():\n # Gets n-gram requirements from user and then puts them into a vector\n askForType()\n askForRepresentation()\n askAboutStopWords()\n\n # Creates vector based on n-gram requirements\n corpusVector = setVector(nGramType, representation, stops)\n fittedCorpusVector = corpusVector.fit_transform(corpus)\n corpusVectorAsArray = fittedCorpusVector.toarray()\n\n\n # Gets non n-gram features from user\n createFeatureFieldList() # Puts all feature field names into list 'fieldsToSelectFrom'.\n askForNonNgramFeatures() # Asks the user to choose the features they want to test. Stores in 'chosenFields'.\n\n # Puts the indexes of the fields relating to the selected non-ngram features into a newly created list,\n # featureIndexList (so that the relevant feature data can later be obtained from list nonDocumentData).\n featureIndexList = []\n for fieldName in chosenFields:\n featureIndex = dataFileFieldNames.index(fieldName)\n featureIndexList.append(featureIndex)\n\n # Produces, for each record, a list of the non n-gram feature data for that record, and stores it in 'list of\n # lists' featuresToTestDataList.\n featuresToTestDataList = []\n for records in nonDocumentData:\n dataThisLine = [] # List of the current line's non n-gram feature data.\n for references in featureIndexList:\n records[references] = float(records[references]) # Float used as all feature data is numeric\n dataThisLine.append(records[references])\n # Add sentence's non n-gram feature data to featuresToTestDataList once it's been extracted to dataThisLine.\n featuresToTestDataList.append(dataThisLine)\n\n # Asks the user which classifier they require\n askForClassifier()\n\n # Console output prior to test being run, to confirm the test details\n nonNGramFeatures = nonNGramFeatureDescription()\n featureDescription = nGramType + \" with \" + representation + \" representation and \" + stops + \\\n \" with the following non n-gram features:\\n\" + nonNGramFeatures\n print(\"\\nTEST SUMMARY\\n\" + \"------------\\n\" + featureDescription)\n print(\"Your classifier is: \", classifier)\n print(\"\\nThe test may take a while. Please be patient.\")\n\n # Appends each line's non-ngram feature data to the end of the n-gram vector, and store in featureData[].\n featureData = []\n recordNum = 0\n for documentBagsOfWords in corpusVectorAsArray:\n featureData.append(np.hstack((documentBagsOfWords, featuresToTestDataList[recordNum])))\n recordNum = recordNum + 1\n # Call function to run the test and display the results\n classificationResults(featureData, documentClassificationList, featureDescription)\n\n\n# FUNCTION CALLS THAT EXECUTE WHENEVER THE PROGRAM IS RUN\nloadData()\nsetParameters()\n","sub_path":"ngram-and-non-ngram-tests-combined.py","file_name":"ngram-and-non-ngram-tests-combined.py","file_ext":"py","file_size_in_byte":28672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"608465246","text":"#!/usr/bin/env python\n\n# Setup module for the Topic Sever\n#\n# March 2016\n\nfrom setuptools import setup\n\n# Read the requirements.txt file (used by Travis CI)\n# ans use for setup's install_requires[] list.\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\n# -----------------------------------------------------------------------------\n# setup\n# -----------------------------------------------------------------------------\nsetup(\n\n name='TopicServer',\n version='1.0.5',\n platforms=['any'],\n\n url='https://github.com/JudiciaryPag/TopicServer',\n license='http://www.apache.org/licenses/LICENSE-2.0',\n author='Judiciary Pag',\n author_email='JudiciaryPag@users.noreply.github.com',\n description='A topic-based message server',\n long_description='A simple memory-resident topic-based Twisted message'\n ' server where messages, posted against topics,'\n ' remain until read by subscribers.',\n\n test_suite='server.test',\n\n # Installation dependencies.\n # This ia the list of registered PyPI modules that we use.\n install_requires=required,\n\n # Our packages here.\n # Specific modules can be found in the MANIFEST.in file.\n packages=['client', 'server', 'server.test'],\n\n # Project classification...\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Framework :: Twisted',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards',\n 'Topic :: Internet :: WWW/HTTP :: HTTP Servers'\n ]\n\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"543864910","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\n \ndef write_pred_dataframe(valid_data , pred_coord , folder,file_name , file_col_name ,\n patches_coord=None, write_index = False , is_valid = True ):\n \"\"\"\n Goal: write prediction coordinates to DATAFRAME csv and return the panda dataframe\n\n params:\n valid_data: panda dataframe of validation data. used for giving file name and types\n pred_coord: prediction coordiantes shape [batch_size , 2 * landmark]\n folder: folder to save\n file_name: name of the csv file. When is None, function doesn't save the csv\n patches_coord: lists of coodinates for each patch. [batch_size, n patches] (dtype = list)\n \"\"\"\n # Get the name and view from Valid data\n df_file_names = valid_data.df.drop(valid_data.coords_cols , axis=1 , errors = 'ignore')\n df_file_names = df_file_names.reset_index(drop=True)\n result = pd.DataFrame(pred_coord, columns = valid_data.coords_cols )\n if not os.path.exists(folder):\n os.makedirs(folder)\n \n if is_valid:\n gt_coords = valid_data.df[valid_data.coords_cols].values\n pred_coord[gt_coords==-1] = -1\n \n # Write the polygons in if there is given patches_coord\n # Other wise assign all -1.\n\n # if patches_coord is None:\n # patches_coord = np.ones((result.shape[0], len(valid_data.patches_cols))) * -1 \n # p_result = pd.DataFrame(patches_coord, columns = valid_data.patches_cols)\n\n result = pd.concat([df_file_names,result],axis=1)\n\n if file_name is not None:\n result.to_csv(folder+file_name+\".csv\" , index =write_index)\n return result\n\ndef build_result_dict(result_dict= {},name = None,\n pck = None, mean_pck = None, pck_threshold = None,\n diff_per_pt=None, mean_diff_per_pt = None,\n in_poly = None, mean_in_poly = None,\n iou = None, mean_iou = None,\n precision = None, mean_precision = None,\n pck_50 = None, pck_150 = None, pck_200 = None, pck_300 = None ):\n \"\"\"\n Goals: write value into dictionry, the default value is None\n which the dict can be used into grid searching result.\n \"\"\"\n remove_keys = ['restore_param_file', 'config_name']\n for remove_key in remove_keys:\n if remove_key in result_dict.keys():\n result_dict.pop(remove_key)\n\n result_dict['name'] = name\n result_dict['pck{}'.format(pck_threshold)] = pck\n result_dict['mean_pck'] = mean_pck\n result_dict['diff_per_pt'] = diff_per_pt\n result_dict['mean_diff_per_pt'] = mean_diff_per_pt\n result_dict['in_poly'] = in_poly\n result_dict['mean_in_poly'] = mean_in_poly\n result_dict['iou'] = iou\n result_dict['mean_iou'] = mean_iou\n result_dict['precision'] = precision\n result_dict['mean_precision'] = mean_precision\n\n result_dict['pck_50'] = pck_50\n result_dict['pck_150'] = pck_150\n result_dict['pck_200'] = pck_200\n result_dict['pck_300'] = pck_300\n result_dict = {str(k):str(v) for k,v in result_dict.items()}\n return result_dict\n\n### Heatmap functions:\ndef plot_heatmaps(dir, heatmaps, img, file_name, names = None, img_per_row = 5):\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n results = np.array([], dtype=np.int64).reshape(0, img.shape[1] * img_per_row,3)\n row = np.array([], dtype=np.int64).reshape(img.shape[0],0,3)\n\n for i in range(heatmaps.shape[-1]):\n # Fore every pic\n\n heatmap = heatmaps[...,i:i+1]\n # print(np.min(img_temp),np.max(img_temp))\n heatmap = np.interp(heatmap,[np.min(heatmap),np.max(heatmap)],[0,255]).astype(np.uint8)\n heatmap = cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)\n\n heatmap = cv2.resize(heatmap, dsize=(img.shape[1], img.shape[0]),\n interpolation = cv2.INTER_NEAREST)\n\n dst = cv2.addWeighted(img,0.5,heatmap,0.5,0)\n if names is not None:\n cv2.putText(dst, names[i], (50,50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (200, 200, 200), 2, cv2.LINE_AA)\n\n if (i+1) % img_per_row !=0:\n row = np.hstack((row, dst))\n else:\n row = np.hstack((row, dst))\n results = np.vstack((results, row))\n row = np.array([], dtype=np.int64).reshape(img.shape[0],0,3)\n if heatmaps.shape[-1] % img_per_row !=0: \n offset = (img_per_row-heatmaps.shape[-1] % img_per_row)\n blank = np.zeros((img.shape[0] , img.shape[1] * offset , 3)).astype(np.uint8)\n\n row = np.hstack((row , blank))\n results = np.vstack((results, row))\n \n cv2.imwrite( os.path.join(dir, \"{}.png\".format(file_name)),results)\n\n\n\ndef save_heatmaps(dir, heatmaps, file_name, pt_names):\n dir = os.path.join(dir, file_name)\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n for i in range(heatmaps.shape[-1]):\n # Fore every pic\n heatmap = heatmaps[...,i:i+1]\n heatmap = np.interp(heatmap,[np.min(heatmap),np.max(heatmap)],[0,255]).astype(np.uint8)\n cv2.imwrite( os.path.join(dir, \"{}.jpg\".format(pt_names[i])),heatmap)\n\n\n### Deprecate ####\n\ndef write_point_result(pred_coord , gt_coords,lm_cnt, params, folder):\n \"\"\"\n Goal: write the evaluation (PCK, pixel difference) on json\n\n params:\n pred_coords: predicted coordinates, shape:[batch , lm_cnt * 2]\n gt_coords: ground-truth coordinates. shape:[batch , lm_cnt * 2]\n lm_cnt: landmark count\n params: hyperparams and config dictionary\n folder: dir for saving the json\n \"\"\"\n\n print(\"deprecated\")\n # if not os.path.exists(folder):\n # os.makedirs(folder)\n # pck_threshold = params['pck_threshold']\n # diff_per_pt ,pck= pck_accuracy(pred_coord , gt_coords, lm_cnt=5 , \n # pck_threshold = params['pck_threshold'],scale = 1)\n # diff_per_pt_all ,pck_all= pck_accuracy(pred_coord , gt_coords, lm_cnt=lm_cnt , \n # pck_threshold = params['pck_threshold'],scale = 1)\n # result = {}\n # result['config'] = get_info_from_params_points(params)\n # result['pck-{}'.format(pck_threshold)] =pck.tolist()\n # result['pixel_diff'] = diff_per_pt.tolist()\n # result['mean_pck-{}'.format(pck_threshold)] =np.mean(pck)\n\n # result['pck_all-{}'.format(pck_threshold)] =pck_all.tolist()\n # result['pixel_diff_all'] = diff_per_pt_all.tolist()\n # result['mean_pck_all-{}'.format(pck_threshold)] =np.mean(pck_all)\n\n # result_name = \"{}_{}.json\".format(str(date.today()) ,params[\"name\"])\n # print(\"write into: \", result_name)\n # f = open(folder+result_name,\"w\")\n # f.write(json.dumps(result ,indent=2 , sort_keys=True))\n # f.close()\n\n### Goal: Get the dictionray from params.\n# Used in write_point_result\ndef get_info_from_params_points(params):\n \"\"\"\n Goal: Get useful properties of the config dictionray.\n \"\"\"\n print(\"deprecated\")\n\n # outputs = {}\n # keys = [\"name\", \"category\" ,\"img_aug\", \"nepochs\" , \"learning_rate\",\"batch_size\",\n # \"decay_step\" , \"decay_step\" , \"dropout_rate\" , \"nlow\" ,\"nstacks\"]\n # for key in keys:\n # assert key in params.keys() , \"No this keys, check the config file\"\n # outputs[key] = params[key]\n # return outputs\n\n\n\ndef write_coord(pred_coords , gt_coords , folder,file_name = \"hg_valid_coords\" ):\n \"\"\"\n deprecated\n Goal: write coords only in csv\n \"\"\"\n print(\"deprecated\")\n # pred_file_name = folder + file_name+\"_pred.csv\"\n # gt_file_name = folder +file_name + \"_gt.csv\"\n # print(\"Save VALID prediction in \"+pred_file_name)\n # print(\"save GROUND TRUTH in \" + gt_file_name)\n # np.savetxt(pred_file_name, pred_coords, delimiter=\",\")\n # np.savetxt(gt_file_name, gt_coords, delimiter=\",\")\n\n\n","sub_path":"util/points_io.py","file_name":"points_io.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"639862986","text":"\"\"\"\r\n6、多窗口切换\r\n窗口的苏醒 handle\r\n\r\n\"\"\"\r\n# coding:utf-8\r\nfrom selenium import webdriver\r\nimport time\r\n\r\ndriver = webdriver.Firefox()\r\ndriver.get(\"http://sz.ganji.com/\")\r\ntime.sleep(1)\r\n\r\ndriver.find_element_by_link_text(\"行政后勤\").click()\r\ntime.sleep(1)\r\n\r\nhandle = driver.current_window_handle # 获取单个handle属性\r\nprint(handle)\r\n\r\nhandlee = driver.window_handles # 获取多个handle属性\r\nprint(handlee)\r\n\r\nhandle_new = handlee[1] # 取新窗口的句柄\r\ndriver.switch_to.window(handle_new) # 切换新窗口\r\nprint(driver.title) # 获取页面的标题\r\n\r\n# 回到第一个窗口上\r\ndriver.switch_to.window(handlee[0])\r\nprint(driver.title)\r\n\r\n\r\ndriver.quit()\r\n","sub_path":"day04/02句柄.py","file_name":"02句柄.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"461031376","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# Plot figures in external window:\nfrom IPython import get_ipython\nget_ipython().run_line_magic('matplotlib', 'qt') \n\nData_tpx3 = np.genfromtxt('shot_19970_W0020_J07-200128-170807-1-0.csv', delimiter=',')\nData_tpx3_cent = np.genfromtxt('shot_19970_W0020_J07-200128-170807-1_cent-0.csv', delimiter=',')\n\ntime_tpx3 = np.array([row[2] for row in Data_tpx3])\ntime_new = time_tpx3 * 25/4096/1e6\ndata_tpx3 = np.array([row[3] for row in Data_tpx3])\ntot_total = np.array([row[4] for row in Data_tpx3_cent])\n\ncol = np.array([row[0] for row in Data_tpx3])\nrow = np.array([row[1] for row in Data_tpx3])\n\n# =============================================================================\n# Plot\n# =============================================================================\n\nfig1 = plt.figure(1)\n\n#plt.plot(time_new, data_tpx3)\n#plt.plot(time_new)\nplt.xlabel(\"t, [ms]\")\nplt.ylabel(\",[-]\")\n\nplt.hist(data_tpx3, 300, (0, 7500), histtype='step')\nToT = np.histogram(data_tpx3, 300, (0, 7500))\n\nfig2 = plt.figure(2)\n\nplt.hist(time_new, 128, (14400, 14600), histtype='step')\n\nfig3 = plt.figure(3)\n\nplt.hist(tot_total, 1000, (0, 25000), histtype='step')\n\nfig4 = plt.figure(4)\nplt.plot(time_new, data_tpx3)\n\n","sub_path":"wtf/Scrappy/tpx3.py","file_name":"tpx3.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"602134721","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 21 18:01:19 2019\n\n@author: mushtu\n\"\"\"\n##Find the minimum first and then its index\nls= [809,834,477,478,307,122,96,102,324,476]\n#min(ls) \nlow = min(ls)\nmin_index = ls.index(low)\nprint (min_index) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n##Find Remove Find\ndef find_two_smallest(L): \n 'Return a tuple of the indices of the two smallest values in list L.'\n smallest = min(L) \n min1 = L.index(smallest) \n L.remove(smallest) \n next_smallest = min(L) \n min2 = L.index(next_smallest)\n##Insert at index min1 \n L.insert(min1, smallest) \n if min1 <= min2: \n min2 += 1\n return (min1, min2)\n\nL=[809,834,477,478,307,122,96,102,324,476]\nfind_two_smallest(L)\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##Sort, Identify Mins, Get Indices\ndef find_two_smallest(L):\n temp_list = L[:] \n temp_list.sort() \n smallest = temp_list[0] \n next_smallest = temp_list[1] \n min1 = L.index(smallest) \n min2 = L.index(next_smallest) \n return (min1, min2)\nfind_two_smallest(L)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#Walk through the List\ndef find_two_smallest(L): \n# set min1 and min2 to the indices of the smallest and next-smallest \n# values at the beginning of L \n if L[0] < L[1]: \n min1, min2 = 0, 1 \n else: \n min2, min1 = 1, 0\n# examine each value in the list in order \n for i in range(2, len(L)):\n if L[i] < L[min1]: \n min2 = min1 \n min1 = i\n# New second smallest? \n elif L[i] < L[min2]: \n min2 = i\n return (min1, min2)\nfind_two_smallest(L)\n\n","sub_path":"CS1010Fall2019-master/Class Excercises/Problem Solving and Design UM.py","file_name":"Problem Solving and Design UM.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"621877911","text":"import sys\nsys.path = [\"../../deps\"] + sys.path\n\nfrom math import pi, sin, cos\n\nfrom pyglet.gl import *\nfrom pyglet.window import key\nimport pyglet\n\nfrom euclid import *\n\ntry:\n # Try and create a window with multisampling (antialiasing)\n config = Config(sample_buffers=1, samples=4,\n depth_size=16, double_buffer=True,)\n window = pyglet.window.Window(resizable=True, config=config)\nexcept pyglet.window.NoSuchConfigException:\n # Fall back to no multisampling for old hardware\n window = pyglet.window.Window(resizable=True)\n\nkeyboard = key.KeyStateHandler()\nwindow.push_handlers(keyboard)\nwindow.set_exclusive_mouse(True)\n\nlabel = pyglet.text.Label('Hello, torus!',\n font_name='Times New Roman',\n font_size=18,\n x=0, y=0, color=(0,0,0,255),\n anchor_x='left', anchor_y='bottom')\n\nmouse_dxdy = [0, 0]\nsensitivity = 20.0\n\ncamera_pos = Vector3(0, 0, 2)\ncamera_rot = Quaternion()\n\nright = Vector3(1, 0, 0)\nup = Vector3(0, 1, 0)\nforward = Vector3(0, 0, 1)\n\ncamera_right = right.copy()\ncamera_up = up.copy()\n\n@window.event\ndef on_resize(width, height):\n # Override the default on_resize handler to create a 3D projection\n glViewport(0, 0, width, height)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(60., width / float(height), .1, 1000.)\n glMatrixMode(GL_MODELVIEW)\n return pyglet.event.EVENT_HANDLED\n\n# does the mouse thang\n@window.event\ndef on_mouse_motion(x, y, dx, dy):\n global camera_rot\n \n mouse_dxdy[0] = (dx / sensitivity)\n mouse_dxdy[1] = -(dy / sensitivity)\n \n # view right/left\n if (dx > 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[0], camera_up)\n camera_rot = q * camera_rot\n if (dx < 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[0], camera_up)\n camera_rot = q * camera_rot\n \n # view up/down\n if (dy > 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[1], camera_right)\n camera_rot = q * camera_rot\n if (dy < 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[1], camera_right)\n camera_rot = q * camera_rot\n\ndef update(dt):\n # fill types\n if keyboard[key._1]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # solid\n if keyboard[key._2]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # wireframe\n if keyboard[key._3]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_POINT) # point\n\n global sensitivity\n\n # sensitivity controls\n if keyboard[key._4]:\n sensitivity -= 1.0 if sensitivity > 5.0 else 0.0\n if keyboard[key._5]:\n sensitivity += 1.0 if sensitivity > 5.0 else 0.0\n \n\n global camera_pos\n global camera_rot\n\n global right\n global up\n global forward\n\n global camera_right\n global camera_up\n\n camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n\n # movement\n if keyboard[key.S]:\n # camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n y, x, z = camera_rot.get_euler()\n camera_pos.x -= sin(y)\n camera_pos.y += sin(x)\n camera_pos.z += cos(y)\n # camera_pos -= camera_dir\n if keyboard[key.W]:\n # camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n y, x, z = camera_rot.get_euler()\n camera_pos.x += sin(y)\n camera_pos.y -= sin(x)\n camera_pos.z -= cos(y)\n # camera_pos += camera_dir\n\n # camera\n if keyboard[key.LEFT]:\n q = Quaternion.new_rotate_axis(-.1, camera_up)\n camera_rot = q * camera_rot\n if keyboard[key.RIGHT]:\n q = Quaternion.new_rotate_axis( .1, camera_up)\n camera_rot = q * camera_rot\n if keyboard[key.UP]:\n q = Quaternion.new_rotate_axis(-.1, camera_right)\n camera_rot = q * camera_rot\n if keyboard[key.DOWN]:\n q = Quaternion.new_rotate_axis( .1, camera_right)\n camera_rot = q * camera_rot\n if keyboard[key.A]:\n camera_dir = camera_up.cross(camera_right)\n q = Quaternion.new_rotate_axis( .1, camera_dir)\n camera_rot = q * camera_rot\n if keyboard[key.D]:\n camera_dir = camera_up.cross(camera_right)\n q = Quaternion.new_rotate_axis(-.1, camera_dir)\n camera_rot = q * camera_rot\n\n y, x, z = tuple(map(lambda x: x*180/pi, camera_rot.get_euler()))\n label.text = \"pitch: %d yaw: %d roll: %d\" % (x,y,z) + \" X: %d Y: %d Z: %d \" % (camera_pos.x, camera_pos.y, camera_pos.z)\n\npyglet.clock.set_fps_limit(30)\npyglet.clock.schedule(update)\n\n@window.event\ndef on_draw():\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glLoadIdentity()\n camera()\n for t in torus:\n t.draw()\n to_ortho()\n label.draw()\n from_ortho()\n\ndef camera():\n angle, axis = camera_rot.get_angle_axis()\n glRotatef(angle*180/pi, axis.x, axis.y, axis.z)\n glTranslated(-camera_pos.x, -camera_pos.y, -camera_pos.z) # translate screen to camera position\n\ndef to_ortho():\n glDisable(GL_DEPTH_TEST)\n glMatrixMode(GL_PROJECTION)\n glPushMatrix()\n glLoadIdentity()\n glOrtho(0, window.width, 0 , window.height, -1, 1)\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\ndef from_ortho():\n glEnable(GL_DEPTH_TEST)\n glMatrixMode(GL_PROJECTION)\n glPopMatrix()\n glMatrixMode(GL_MODELVIEW)\n\ndef setup():\n # One-time GL setup\n glClearColor(1, 1, 1, 1) # rgba (white)\n glColor3f(1, 0, 0) # rgb (red)\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_CULL_FACE)\n\n # Simple light setup. On Windows GL_LIGHT0 is enabled by default,\n # but this is not the case on Linux or Mac, so remember to always\n # include it.\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glEnable(GL_LIGHT1)\n\n # Define a simple function to create ctypes arrays of floats:\n def vec(*args):\n return (GLfloat * len(args))(*args)\n\n glLightfv(GL_LIGHT0, GL_POSITION, vec(.5, .5, 1, 0)) # xyz homogenous\n glLightfv(GL_LIGHT0, GL_SPECULAR, vec(.5, .5, 1, 1)) # rgba (blue)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, vec(1, 1, 1, 1)) # rgba (white)\n\n glLightfv(GL_LIGHT1, GL_POSITION, vec(1, 0, .5, 0))\n glLightfv(GL_LIGHT1, GL_DIFFUSE, vec(.5, .5, .5, 1))\n glLightfv(GL_LIGHT1, GL_SPECULAR, vec(1, 1, 1, 1))\n\n glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0, 0.3, 1)) # rgba (purple)\n glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, vec(1, 1, 1, 1)) # rgba (white)\n glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50) # [0-128] with 0 being most shiny\n\nclass Torus(object):\n def __init__(self, radius, inner_radius, slices, inner_slices):\n # Create the vertex and normal arrays.\n vertices = []\n normals = []\n\n u_step = 2 * pi / (slices - 1)\n v_step = 2 * pi / (inner_slices - 1)\n u = 0.\n for i in range(slices):\n cos_u = cos(u)\n sin_u = sin(u)\n v = 0.\n for j in range(inner_slices):\n cos_v = cos(v)\n sin_v = sin(v)\n\n d = (radius + inner_radius * cos_v)\n x = d * cos_u\n y = d * sin_u\n z = inner_radius * sin_v\n\n nx = cos_u * cos_v\n ny = sin_u * cos_v\n nz = sin_v\n\n vertices.extend([x, y, z])\n normals.extend([nx, ny, nz])\n v += v_step\n u += u_step\n\n # Create ctypes arrays of the lists\n vertices = (GLfloat * len(vertices))(*vertices)\n normals = (GLfloat * len(normals))(*normals)\n\n # Create a list of triangle indices.\n indices = []\n for i in range(slices - 1):\n for j in range(inner_slices - 1):\n p = i * inner_slices + j\n indices.extend([p, p + inner_slices, p + inner_slices + 1])\n indices.extend([p, p + inner_slices + 1, p + 1])\n indices = (GLuint * len(indices))(*indices)\n\n # Compile a display list\n self.list = glGenLists(1) # create an array of lists (only one here)\n glNewList(self.list, GL_COMPILE) # only compile list, don't execute it yet\n\n glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) # push context\n\n glEnableClientState(GL_VERTEX_ARRAY) # context can display vertexes\n glEnableClientState(GL_NORMAL_ARRAY) # context can display normals\n glVertexPointer(3, GL_FLOAT, 0, vertices) # array of vertices in 3-space, stride is 0 for non-interleaved arrays\n glNormalPointer(GL_FLOAT, 0, normals) # same as above except normals are always in 3-space\n glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)\n\n glPopClientAttrib() # pop context\n\n glEndList() # end list\n\n def draw(self):\n glCallList(self.list)\n\nsetup()\ntorus = [\n Torus(1.1, 0.2, 100, 50),\n Torus(0.7, 0.2, 75, 40),\n Torus(0.3, 0.2, 50, 30)\n]\n\npyglet.app.run()\n","sub_path":"game/graphics/scripts/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":8918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"414206847","text":"import pygame\nimport engine as eng\n# from graphics import *\nfrom itertools import cycle\nimport ipdb\nimport random\n\nDATA_STAGES = {\"raw\": 1, \"crunched\": 2, \"paper\": 3}\nASSET_FOLDER = \"assets/\"\nGRAVITY_VELOCITY = 4 # lets cheat for now\nFLOOR_Y = 580\nPLAYER_SPEED = 20\nPLAYER_THROW_SPEED = eng.Vector(20, -5)\nFOLLOWER_SPEED = PLAYER_SPEED - 3 # just slower than the players\nPATROL_SPEED = 4 # just slower than the players\nJUMP_VELOCITY = -20\nDATA_DEVICE_TIMER = .01\nTIMER_WIDTH = 100\nPLAYER_INTERACT_DIST = 50\nEJECT_SPEED = eng.Vector(20, -20)\nPLAYER_MASH_NUMBER = 10 # the number of times the player has to mash a button to escape\nMEETING_EVENT_HORIZON = 50 # the distance where the player will need to escape\nMEETING_GRAVITAIONAL_SPHERE = 100 # the distance where the player begins to be pulled in\nMEETING_PULL = 5\nMEETING_TIMER = .01\nDEBUG = True\nSTUN_VELOCITY_LOSER = eng.Vector(10, -15)\nSTUN_VELOCITY_WINNER = eng.Vector(5, -10)\nSTUN_WINNER_TIMER = 10\nSTUN_LOSER_TIMER = 20\nLEFT_FRAME_ID = 'l_'\n\n\ndef draw_message(x, bottom, message, window):\n \"\"\"draw text somewhere on the screen\"\"\"\n eng.FONT.set_bold(True)\n font_to_render = eng.FONT.render(str(message), True, (0, 0, 0))\n font_rect = font_to_render.get_rect()\n font_rect.x = x\n font_rect.bottom = bottom\n window.blit(font_to_render, font_rect)\n return font_rect\n\n\ndef draw_timer(game_obj, surface, ascending=True):\n outline_rect = pygame.Rect(0, 0, TIMER_WIDTH, 20)\n outline_rect.centerx = game_obj.rect.centerx\n outline_rect.centery = game_obj.rect.y - outline_rect.height\n timer_rect = pygame.Rect(outline_rect)\n if ascending:\n timer_rect.width = TIMER_WIDTH * game_obj.timer\n else:\n timer_rect.width = 101 - TIMER_WIDTH * game_obj.timer # off by one error fix later\n \n \n\n print(timer_rect.width)\n\n pygame.draw.rect(surface, (255, 0, 255), timer_rect)\n pygame.draw.rect(surface, (128, 0, 128), outline_rect, 1)\n if timer_rect.width == TIMER_WIDTH - 1 or not ascending:\n # TODO: optimize the clearing of the timer if need be\n return outline_rect\n\n\n# TODO: add more things to do\nclass GameObject(object):\n \"\"\"the top level game object. All game objects inherit from this class.\"\"\"\n id = 0\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n self.rect = pygame.Rect((startx, starty, width, height))\n if not obj_id:\n self.id = GameObject.id # assign\n GameObject.id += 1\n else:\n self.id = obj_id\n self.render = True\n self.message_str = None # info that is displayed above the object\n self.to_del = False\n self.physics = False # Does this class need physics? i.e. movement\n self.collision = True # Does this class need collisions\n self.dirt_sprite = True # only draw sprite if dirty\n\n def update(self):\n \"\"\"anything that the object needs to do every frame\"\"\"\n return\n\n def animate(self):\n return\n\n\nclass NetworkedObject(object):\n def __init__(self, attribute_list):\n self.attribute_list = attribute_list\n\n def build_packet(self, accumulator):\n packet = {}\n for attribute in self.attribute_list:\n packet[attribute] = self.__getattribute__(attribute)\n accumulator.append(packet)\n\n def read_packet(self, packet):\n for attribute in self.attribute_list:\n self.__setattr__(attribute, packet[attribute])\n\n\nclass AnimateSpriteObject(object):\n \"\"\"a stand alone object that allows the inherited game object to have animation \n sprites\"\"\"\n\n def __init__(self, animation_dict, des_width, des_height):\n \"\"\"Initilize all the frames of the animated sprite object\n :param animation_dict: a dictionary that is keyed on the name of the animation. The dictionary \n contains a tuple pair, with the name of the file at [0] and the number of frames of the sprite sheet\n at [1][0] for the x and [1][1] for the y. So \n animation_dict[animation_name] -> (sprite_sheet_filename, (sprite_sheet_x, sprite_sheet_y) \n :type animation_dict: dict\n :param des_width: the desired width of each frame \n :type des_width: int\n :param des_height: the desired height of each frame\n :type des_height: int\n \"\"\"\n object.__init__(self)\n frame_dict = {}\n self.animation_frames = {}\n self.sprite_sheets = {}\n for animation_name, (filename, (width, height)) in animation_dict.items():\n self.sprite_sheets[animation_name], self.animation_frames[animation_name] = self._get_frames(\n ASSET_FOLDER + filename, int(width),\n int(height), des_width=des_width,\n des_height=des_height)\n\n # get the left facing sprite\n left_animation = LEFT_FRAME_ID + animation_name\n self.sprite_sheets[left_animation] = pygame.transform.flip(self.sprite_sheets[animation_name], 1, 0)\n self.animation_frames[left_animation] = self.animation_frames[animation_name][::-1]\n\n self.current_animation = 'idle'\n self.current_cycle = cycle(self.animation_frames[self.current_animation])\n self.current_frame = next(self.current_cycle)\n self.animation_time = 3\n self.animation_timer = 0\n self.hold_end_frame = False # set to true for animations where the end should be held (like falling)\n\n def change_animation(self, frame):\n \"\"\"change the frames that player object is currently cycling through.\n :param frame: a key that maps to a list of animation frames in self.animation_frames\n :type frame: str\"\"\"\n if not frame in self.animation_frames:\n frame = 'idle'\n\n self.current_animation = frame # TODO: evaluate if we need this member\n self.current_cycle = cycle(self.animation_frames[self.current_animation])\n\n def reverse_animation(self, direction):\n \"\"\"take the current animation and point it in the other direction specified\n returns new animation name the object needs to change to or None\"\"\"\n is_left = True if LEFT_FRAME_ID in self.current_animation else False\n new_animation = None\n if direction == -1 and not is_left:\n # moving right, but trying to flip to the left\n new_animation = LEFT_FRAME_ID + self.current_animation\n elif direction == 1 and is_left:\n # moving left, but trying to flip right\n new_animation = self.current_animation[len(LEFT_FRAME_ID):]\n return new_animation\n\n\n def animate(self):\n \"\"\"Updates the animation timer goes to next frame in current animation cycle\n after the alloted animation time has passed.\"\"\"\n self.animation_timer += 1\n if self.animation_timer == self.animation_time:\n self.current_frame = next(self.current_cycle)\n self.animation_timer = 0\n\n def draw(self, surface):\n \"\"\"Draws the player object onto surface\n :param surface: the surface to draw the object, typically the window\n :type surface: pygame.Surface\"\"\"\n surface.blit(self.sprite_sheets[self.current_animation], self.rect, area=self.current_frame)\n\n def _get_frames(self, filename, columns, rows, des_width=30, des_height=30):\n \"\"\"returns a new sprite sheet and a list of rectangular coordinates in the\n file that correspond to frames in the file name. It also manipulates the spritesheet \n so each frame will have the des_width and des_height\n :param filename: sprite sheet file\n :type filename: str\n :param columns: the number of columns in the sprite sheet\n :type columns: int\n :param rows: the number of rows in the sprite sheet\n :type rows: int\n :param des_width: the desired width of a single frame\n :type des_width: int\n :param des_height: the desired height of a single frame\n :type des_height: int\"\"\"\n sheet = pygame.image.load(filename)\n sheet_rect = sheet.get_rect()\n sheet_width = columns * des_width\n sheet_height = rows * des_height\n\n sheet = pygame.transform.smoothscale(sheet, (sheet_width, sheet_height))\n sheet_rect = sheet.get_rect()\n frames = []\n for x in range(0, sheet_rect.width, des_width):\n for y in range(0, sheet_rect.height, des_height):\n frames.append(pygame.Rect(x, y, des_width, des_height))\n return sheet, frames\n\n\nclass Constructor(object):\n \"\"\"A special object that contains a reference to the entire game. Inherited\n by classes that need to construct objects in the game world\"\"\"\n\n def __init__(self, game):\n object.__init__(self)\n self.game = game\n\n def add_to_world(self, obj):\n if self.game:\n self.game.added.append(obj)\n else:\n ipdb.set_trace()\n\n\nclass MovableGameObject(GameObject):\n \"\"\"any game object that moves\"\"\"\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n super(MovableGameObject, self).__init__(startx, starty, width, height, obj_id=obj_id)\n self.velocity = eng.Vector(0, 0)\n self.physics = True # most movable game objects need physics\n self.last_rect = self.rect.copy()\n\n def move(self, velocity):\n self.velocity = velocity\n\n def stop(self):\n self.velocity = [0, 0]\n\n def hide_object(self):\n \"\"\"moves turns of physics and rendering for the object\"\"\"\n self.render = False\n self.physics = False\n self.rect.x, self.rect.y = -1000, -1000 # move somewhere far off screen to\n\n def unhide_object(self):\n \"\"\"moves turns of physics and rendering for the object\"\"\"\n self.render = True\n self.physics = True\n\n def respond_to_collision(self, obj, axis=None):\n \"\"\"Contains the callback for the collision between a move able object and the\n object passed in. If the object passed in is the environment (i.e. SimpleScenery)\n it will treate the environment as a wall and stop the object.\n :param obj: object player is colliding with\n :type obj: GameObject\n :param axis: which axis was the player moving along.\n :type axis: String \"\"\"\n if isinstance(obj, BackGroundScenery):\n if axis == 'y':\n self._handle_background_collision(obj)\n return\n if axis == 'x':\n if self.velocity.x > 0:\n self.rect.right = obj.rect.left\n if self.velocity.x < 0:\n self.rect.left = obj.rect.right\n self.velocity.x = 0\n if axis == 'y':\n if self.velocity.y > 0:\n self.rect.bottom = obj.rect.top\n if self.velocity.y < 0:\n self.rect.top = obj.rect.bottom\n self.velocity.y = 0\n\n def _handle_background_collision(self, obj):\n \"\"\"collisions with things that are in the background i.e. things you can\n jump on but walk through\"\"\"\n if self.velocity.y > 0 and self.last_rect.bottom <= obj.rect.top:\n # only collide going down (rember +y = down)\n self.rect.bottom = obj.rect.top\n self.velocity.y = 0 # stop the object\n\n def update(self):\n self.last_rect = self.rect.copy()\n\n\nclass BackGroundScenery(GameObject):\n \"\"\"objects that you can jump on top of but can run through. Think of them as\n in the background that the play jumps up on. For example a platform in mario. \n Doesn't update during gameplay so no need to inherit network object\"\"\"\n\n def __init(self, startx, starty, width, height, obj_id=None):\n super(BackGroundScenery, self).__init__(startx, starty, width, height, obj_id=obj_id)\n\n def draw(self, surface):\n pygame.draw.rect(surface, (128, 0, 128), self.rect, 3)\n\n\nclass SimpleScenery(GameObject):\n \"\"\"Simple SimpleScenery object. Game objects that are just simple shapes\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, obj_id=None):\n super(SimpleScenery, self).__init__(startx, starty, width, height, obj_id=obj_id)\n self.color = color\n\n def draw(self, surface):\n \"\"\"Draw the simple scenery object\"\"\"\n if self.message_str:\n # message_rect = pygame.Rect(0,0,0,0)\n x = self.rect.centerx\n bottom = self.rect.top - 10\n # message_rect.bottom = self.rect.top - 10\n return draw_message(x, bottom, self.message_str, surface)\n\n\nclass Player(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n def __init__(self, startx, starty, width, height, sprite_sheet=None, color=None, obj_id=None):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'current_animation', 'id',\n 'render'])\n self.color = color\n self.rect = pygame.Rect((startx, starty, width, height))\n self.sprite_sheet = sprite_sheet\n self.data = None\n self.direction = 1\n self.moving = False\n self.mash_left = 0\n self.mash_right = 0\n self.interact_dist = PLAYER_INTERACT_DIST # The max distance needed for the player to interact with something\n self.trapped = False\n self.trapper = None # Object trapping the player\n self.mash_left = False\n self.mash_right = False\n self.escape_hit = 0\n self.score = 0\n self.message_str = \"hello\"\n self.movement_event = False # set to true if another object is mucking with the players velocity\n self.escape_mash_number = PLAYER_MASH_NUMBER\n self.stunned_timer = 0\n self.stunned_velocity = eng.Vector(0, 0)\n self.invincible_timer = 0\n self.invincible = False\n self.jumping = False\n self.on_ladder = False\n self.near_ladder = False\n\n\n def jump(self):\n if not self.trapped and not self.stunned_timer and not self.jumping:\n self.velocity.y = JUMP_VELOCITY\n\n def update(self):\n \"\"\"set velocity to be moved by the physics engine\"\"\"\n MovableGameObject.update(self)\n if self.stunned_timer:\n self.stunned_timer -= 1\n # self.velocity.x = self.stunned_velocity.x\n elif not self.movement_event and self.moving and not self.trapped:\n self.velocity.x = self.direction * PLAYER_SPEED\n if self.invincible_timer:\n self.invincible_timer -= 1\n else:\n self.invincible = False\n\n def escape(self, direction):\n \"\"\"mash a button to escape students\"\"\"\n if self.trapped:\n print(\"trying to escape\")\n if direction == 1:\n self.mash_left = True\n elif direction == 2:\n self.mash_right = True\n if self.mash_left and self.mash_right:\n self.mash_left = False\n self.mash_right = False\n self.escape_hit += 1\n if self.escape_hit > self.escape_mash_number:\n self.trapper.un_trap(self)\n self.trapper = None\n self.trapped = False\n self.mash_left = False\n self.mash_right = False\n self.escape_hit = 0\n self.invincible_timer = 60\n self.invincible = True\n\n def write_paper(self):\n return\n\n def move_right(self):\n \"\"\"DEPRICATED: use move(1): sets velocity of player to move right\"\"\"\n self.move(1)\n\n def move_left(self):\n \"\"\"DEPRICATED use move(-1): sets velocity of player to move left\"\"\"\n self.move(-1)\n\n def move(self, direction):\n \"\"\"sets move to the direction passed in\"\"\"\n if self.on_ladder:\n self.do_ladder_things()\n return # Don't move to the side while on ladder\n self.direction = direction\n self.moving = True\n self.change_animation('moving')\n new_animation = self.reverse_animation(direction) # change animation frame if need be\n if new_animation:\n self.change_animation(new_animation)\n\n def stop_right(self):\n \"\"\"sets velocity to 0\"\"\"\n if self.direction == 1:\n self.velocity.x = 0\n self.moving = False\n\n # TODO: why have two methods for stop\n def stop_left(self):\n \"\"\"sets velocity to 0\"\"\"\n if self.direction == -1:\n self.velocity.x = 0\n self.moving = False\n\n def read_packet(self, packet):\n if packet['current_animation'] != self.current_frame:\n self.change_animation(packet['current_animation'])\n super(Player, self).read_packet(packet)\n\n def interact(self, game_objs):\n \"\"\"a catch all function that called when hitting the interact button. It will\n look through the game_objs and if it's with a minimum threshold(self.interact_dist), call specific functions\n based on what the objects are.\n :param game_objs: A list of game objects that the player can potentially interact\n with\n :type game_objs: list of GameObject\"\"\"\n for game_obj in game_objs:\n if isinstance(game_obj, DataDevice):\n if eng.distance(self.rect, game_obj.rect) < self.interact_dist:\n game_obj.interact(self)\n\n def do_ladder_things(game_obj):\n if self.rect.colliderect(game_obj.rect):\n if self.on_ladder:\n self.on_ladder = False\n else:\n self.on_ladder = True\n\n\n\n def draw(self, surface):\n \"\"\"Draws the player object onto surface\n :param surface: the surface to draw the object, typically the window\n :type surface: pygame.Surface\"\"\"\n AnimateSpriteObject.draw(self, surface)\n pygame.draw.rect(surface, (128, 0, 128), self.rect, 1)\n\n def respond_to_collision(self, obj, axis=None):\n \"\"\"Contains the callback for the collision between a player object and a game object passed in. Axis is needed\n for collisions that halt movement\n :param obj: object player is colliding with\n :type obj: GameObject\n :param axis: which axis was the player moving along.\n :type axis: String \"\"\"\n if type(obj) == Data:\n if self.data is None:\n self.data = obj\n self.data.hide_object()\n self.change_animation('hasdata')\n else:\n super(Player, self).respond_to_collision(obj, axis)\n if isinstance(obj, Player) and not self.stunned_timer:\n self.joust_attack(obj)\n if (isinstance(obj, Meeting) or isinstance(obj, Follower)) and not self.trapped:\n # got sucked trapped by something\n obj.trap(self)\n\n def joust_attack(self, other_player):\n \"\"\"The player collided with another, determine who 'won' and properly stun the player\"\"\"\n if self.rect.centery < other_player.rect.centery:\n dominate_player = self\n losing_player = other_player\n elif self.rect.centery > other_player.rect.centery:\n dominate_player = other_player\n losing_player = self\n else:\n return # are currently on the same plane\n # figure out which way the dominate player bumped into the loser were going\n if dominate_player.rect.centerx > losing_player.rect.centerx:\n # hit right side of loser, push to the left\n losing_player.velocity.x = -STUN_VELOCITY_LOSER.x\n dominate_player.velocity.x = STUN_VELOCITY_WINNER.x\n elif dominate_player.rect.centerx < losing_player.rect.centerx:\n losing_player.velocity.x = STUN_VELOCITY_LOSER.x\n dominate_player.velocity.x = -STUN_VELOCITY_WINNER.x\n else:\n # on top of the other player, pick one at random\n modifier = random.randint(0, 1) * 2 - 1\n losing_player.velocity.x = STUN_VELOCITY_LOSER.x * modifier\n dominate_player.velocity.x = STUN_VELOCITY_WINNER.x * -modifier\n\n losing_player.stunned_timer = STUN_LOSER_TIMER\n dominate_player.stunned_timer = STUN_WINNER_TIMER\n dominate_player.velocity.y = STUN_VELOCITY_WINNER.y\n losing_player.velocity.y = STUN_VELOCITY_LOSER.y\n if losing_player.data:\n losing_player.drop_data()\n\n\n def drop_data(self):\n self.throw_data()\n\n def stun_event(self):\n \"\"\" if something is happening the the player, \"\"\"\n\n\n def throw_data(self):\n \"\"\"Through the data that the player is holding\"\"\"\n if self.data:\n if self.moving:\n exit_buff = PLAYER_SPEED # if the player is moving, have to throw the data ahead a frame\n else:\n exit_buff = 0\n if self.direction == -1:\n self.data.rect.right = self.rect.left + (exit_buff * self.direction)\n else:\n self.data.rect.left = self.rect.right + (exit_buff * self.direction)\n\n self.data.velocity.x = self.velocity.x + PLAYER_THROW_SPEED.x * self.direction\n self.data.rect.y = self.rect.y\n self.data.velocity.y = PLAYER_THROW_SPEED.y\n self.data.unhide_object()\n self.data = None\n self.change_animation('moving')\n\n\nclass DataDevice(BackGroundScenery, Constructor, NetworkedObject):\n \"\"\"Devices that are scenery, but output data when interacted with\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, obj_id=None, game=None):\n BackGroundScenery.__init__(self, startx, starty, width, height, obj_id=obj_id)\n Constructor.__init__(self, game)\n NetworkedObject.__init__(self, ['rect', 'id', 'timer', 'message_str'])\n self.timer = None\n self.color = color\n self.data = None\n self.collision = False # for now, only interaction comes with explicit buttons\n\n def generate_data(self):\n game_obj = Data(20, 20, 40, 40)\n print(game_obj)\n game_obj.rect.centerx = self.rect.centerx\n game_obj.rect.bottom = self.rect.top\n game_obj.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n game_obj.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.add_to_world(game_obj)\n return game_obj\n\n def interact(self, player, timer=DATA_DEVICE_TIMER):\n if not self.timer: # only allow one timer at a time\n self.timer = timer\n\n\n def draw(self, surface):\n BackGroundScenery.draw(self, surface) # SimpleScenery.draw\n if self.timer:\n outline_rect = pygame.Rect(0, 0, TIMER_WIDTH, 20)\n outline_rect.centerx = self.rect.centerx\n outline_rect.centery = self.rect.y - outline_rect.height\n timer_rect = pygame.Rect(outline_rect)\n timer_rect.width = TIMER_WIDTH * self.timer\n pygame.draw.rect(surface, (255, 0, 255), timer_rect)\n pygame.draw.rect(surface, (128, 0, 128), outline_rect, 1)\n if timer_rect.width == TIMER_WIDTH - 1:\n # TODO: clear timer. Do this by returning the area that needs to be cleared\n return outline_rect\n\n def update(self):\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n\n def respond_to_collision(self, obj, axis=None):\n return\n\n def get_data(self, data):\n self.timer = DATA_DEVICE_TIMER # start timer\n self.data = data\n # TODO: Make a better hide/delete function\n data.rect.x, data.rect.y = (-100, -100)\n data.velocity.x = 0\n data.velocity.y = 0\n\n\nclass DataCruncher(DataDevice):\n \"\"\"Second stage of collecting data\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, amount_data_needed=1,\n concurrent_data=1, obj_id=None,\n game=None):\n super(DataCruncher, self).__init__(startx, starty, width, height, obj_id=obj_id, game=None)\n # Constructor.__init__(self, game)\n self.accept_stage = accept_stage\n self.amount_data_needed = amount_data_needed\n self.data_collected = 0\n\n def handle_data(self, game_obj):\n if game_obj.stage == self.accept_stage:\n self.data_collected += 1\n if self.data_collected == self.amount_data_needed:\n self.timer = DATA_DEVICE_TIMER # start timer\n self.message_str = None\n self.data_collected = 0\n else:\n # if there can be more data \n self.message_str = str(self.data_collected) + \"/\" + str(self.amount_data_needed)\n # TODO: THis is wrong, need a destructor \n self.data = game_obj\n self.data.advance_data()\n self.data.hide_object()\n\n def update(self):\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n\n def generate_data(self):\n self.data.rect.centerx = self.rect.centerx\n self.data.rect.bottom = self.rect.top\n self.data.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n self.data.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.data.unhide_object()\n\n\nclass Desk(DataDevice):\n \"\"\"Where the player will sit and write the paper after collecting data\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, obj_id=None,\n game=None):\n super(Desk, self).__init__(startx, starty, width, height, obj_id=obj_id, game=None)\n self.player = None\n\n def update(self):\n if self.player:\n self.player.escape_hit = 0 # Don't allow player to escape\n # player siting at desk, update timer\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n self.player.trapped = False\n self.player = None\n\n def generate_data(self):\n self.data.rect.centerx = self.rect.centerx\n self.data.rect.bottom = self.rect.top\n self.data.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n self.data.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.data.advance_data()\n self.data.unhide_object()\n\n def interact(self, player, timer=DATA_DEVICE_TIMER):\n if not self.player and player.data:\n # player hasn't interacted yet and has data\n self.player = player\n self.player.trapped = True\n self.player.escape_hit = 0\n self.timer = timer\n self.data = self.player.data\n self.player.data = None\n\n\nclass PublishingHouse(DataCruncher):\n \"\"\"Where the player brings the final paper\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, amount_data_needed=1,\n concurrent_data=1, obj_id=None, game=None):\n super(PublishingHouse, self).__init__(startx, starty, width, height, accept_stage=accept_stage,\n amount_data_needed=amount_data_needed, concurrent_data=concurrent_data,\n obj_id=obj_id, game=game)\n\n def generate_data(self):\n # TODO: make a scoring mechanic\n print(\"score\")\n\n\nclass Data(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n def __init__(self, startx, starty, width, height, color=None, sprite_sheet={\"idle\": [\"light_blue.png\", [\"1\", \"1\"]]},\n obj_id=None):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'id', 'render', 'stage'])\n self.color = color\n self.sprite_sheet = sprite_sheet\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n self.stage = 1\n self.frame = 'idle'\n\n def draw(self, surface):\n super(Data, self).draw(surface) # animatedSpriteObject.draw\n if DEBUG:\n x = self.rect.centerx\n bottom = self.rect.top - 10\n return draw_message(x, bottom, self.stage, surface)\n\n def respond_to_collision(self, obj, axis=None):\n if isinstance(obj, Player):\n obj.respond_to_collision(self)\n elif isinstance(obj, DataCruncher) and self.stage == obj.accept_stage:\n obj.handle_data(self)\n else:\n # TODO: this makes the data go through players\n super(Data, self).respond_to_collision(obj, axis)\n\n def advance_data(self):\n # TODO: hacked for now with no sprite sheet\n self.stage += 1\n\n\nclass Follower(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n \"\"\"a class that follows it's leader\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, sprite_sheet=None, obj_id=None, site_range=200):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'id', 'render'])\n self.color = color\n self.leader = None\n self.velocity = eng.Vector(0, 0)\n self.site = site_range\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n\n def trap(self, game_obj):\n if not game_obj.invincible:\n game_obj.trapped = True\n game_obj.trapper = self\n\n def update(self):\n MovableGameObject.update(self)\n if self.leader and eng.distance(self.rect, self.leader.rect) < self.site:\n # figure out which direction to move\n if self.leader.rect.centerx - self.rect.centerx > 0:\n self.velocity.x = FOLLOWER_SPEED # move right\n elif self.leader.rect.centerx - self.rect.centerx < 0:\n self.velocity.x = -FOLLOWER_SPEED # move left\n else:\n self.velocity.x = 0\n elif self.leader:\n self.leader = None\n self.velocity.x = 0\n\n def check_for_leader(self, leader_list):\n self.leader = None\n closest_leader = leader_list[0]\n closest_distance = eng.distance(self.rect, closest_leader.rect)\n for potential_leader in leader_list[1:]:\n distance = eng.distance(self.rect, potential_leader.rect)\n if distance < closest_distance and (not potential_leader.trapped or potential_leader.trapper == self):\n closest_leader = potential_leader\n closest_distance = distance\n if closest_distance < self.site and (not closest_leader.trapped or potential_leader.trapper == self):\n self.leader = closest_leader\n\n def respond_to_collision(self, obj, axis=None):\n if isinstance(obj, Player):\n obj.respond_to_collision(self, axis)\n super(Follower, self).respond_to_collision(obj, axis)\n\n def un_trap(self, game_obj):\n \"\"\"Called after a player has escaped the patrollers grasp\"\"\"\n if self.rect.x < game_obj.rect.x:\n # on the left, push back to the left\n self.velocity.x = -10\n self.velocity.y = -20\n else:\n self.velocity.x = 10\n self.velocity.y = -20\n\n\nclass Patroller(Follower):\n \"\"\"class that patrols it's give x area\"\"\"\n\n def __init__(self, startx, starty, width, height, sprite_sheet=None, obj_id=None, patrol_range=100, site_range=200):\n super(Patroller, self).__init__(startx, starty, width, height, obj_id=obj_id, sprite_sheet=sprite_sheet, site_range=site_range)\n self.patrol_range = patrol_range\n self.reset_patrol()\n self.direction = 1 # scaler to multiple speed by to get direction\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n\n def update(self):\n if self.leader:\n super(Patroller, self).update()\n if not self.leader:\n # leader moved out of range, set new start and end patrol to start from the middle\n self.reset_patrol()\n self.do_patrol()\n else:\n self.do_patrol()\n\n def do_patrol(self):\n if self.velocity.x > 0 and self.rect.centerx > self.end_patrol:\n self.direction = -1\n if self.velocity.x < 0 and self.rect.centerx < self.start_patrol:\n self.direction = 1\n self.velocity.x = PATROL_SPEED * self.direction\n\n def reset_patrol(self):\n \"\"\"sets the partrol to be equidistance from the current center\"\"\"\n self.start_patrol = self.rect.centerx - self.patrol_range / 2\n self.end_patrol = self.rect.centerx + self.patrol_range / 2\n self.velocity.x = PATROL_SPEED\n\n\n\nclass Meeting(SimpleScenery, NetworkedObject):\n \"\"\"A meeting trap that will pull the players into at a certain range\"\"\"\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n SimpleScenery.__init__(self, startx, starty, width, height, obj_id=obj_id)\n NetworkedObject.__init__(self, ['rect', 'id', 'timer', 'message_str'])\n self.pulling_player = None\n self.timer = None\n\n def check_player(self, players):\n \"\"\"check if the player is close enough to be pulled in\"\"\"\n if self.timer:\n # cooling down\n return\n\n for player in players:\n distance = eng.distance(self.rect, player.rect)\n\n if eng.distance(self.rect, player.rect) < MEETING_GRAVITAIONAL_SPHERE:\n player.movement_event = True # inform the player that the meeting is in control now!!\n # ipdb.set_trace()\n self.pull_event(player)\n else:\n player.movement_event = False\n\n def pull_event(self, player, **kwargs):\n \"\"\"a function to give the player\"\"\"\n # distance = kwargs['distance']\n distance = eng.distance(self.rect, player.rect)\n if self.rect.x >= player.rect.x:\n # on the right side of it, pull to the right\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED + MEETING_PULL\n elif self.rect.x < player.rect.x:\n # on the left side of it, pull to the left\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = -MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED - MEETING_PULL\n player.velocity.x = pull_velocity\n\n def un_trap(self, game_obj):\n \"\"\"Release the mortal from the bonds of responsibility\"\"\"\n self.timer = MEETING_TIMER\n game_obj.movement_event = False\n\n\n def draw(self, surface):\n super(Meeting, self).draw(surface)\n if self.timer:\n return draw_timer(self, surface, False) # draw a descending timer\n\n def trap(self, game_obj):\n if not self.timer:\n game_obj.trapped = True\n game_obj.trapper = self\n\n\n def update(self):\n super(Meeting, self).update()\n if self.timer:\n self.timer += MEETING_TIMER\n if self.timer >= 1:\n self.timer = None\n\n\ndef Portal(GameObject):\n \"\"\"a special object that contains a pointer to another portal object, creating a \n link in gamespace bewteen the two\"\"\"\n\ndef Laddder(GameObject):\n \"\"\"Simple ladder object\"\"\"\n def __init__(self, startx, starty, width, height, obj_id=None):\n super(Laddder, self)\n\n def pull_event(self, player, **kwargs):\n \"\"\"a function to give the player\"\"\"\n # distance = kwargs['distance']\n distance = eng.distance(self.rect, player.rect)\n if self.rect.x >= player.rect.x:\n # on the right side of it, pull to the right\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED + MEETING_PULL\n elif self.rect.x < player.rect.x:\n # on the left side of it, pull to the left\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = -MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED - MEETING_PULL\n player.velocity.x = pull_velocity","sub_path":"world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":33878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"197735626","text":"\nfrom app import app\nfrom config import client\nfrom bson.json_util import dumps\nimport random\nimport string\nfrom flask import Flask, jsonify, request, make_response\n\n\ndb = client.Bank\ncol = db.Account\n\n@app.route(\"/api/createuser\",methods=['POST'])\ndef createUser():\n try:\n record = request.get_json()\n id = record.get(\"_id\")\n filter = {\"_id\": id}\n accno = ''.join(random.choices(string.digits, k=8))\n col.insert_one(record)\n col.update_one(filter, {\"$set\":{\"AccountNo \":accno}})\n res = make_response(jsonify({\"Message\": \"Record inserted\", \"Account Number\": accno}), 200)\n return res\n except:\n res = {\n \"Message\":\"Error occurred !\"\n }\n return make_response(jsonify(res),503)\n\n@app.route(\"/api/users\", methods=['GET'])\ndef getUsers():\n try:\n users = col.find()\n res = dumps(users)\n return res\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n@app.route(\"/api/users/\", methods=['GET'])\ndef getSingleUser(accno):\n try:\n user = col.find_one({\"AccountNo \":accno})\n if user:\n res = {\n \"Account Info\": user\n }\n return make_response(jsonify(res), 200)\n else:\n res = {\n \"Message\": \"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n@app.route(\"/api/update/\", methods=['PUT'])\ndef updateUser(accno):\n try:\n if col.find_one({\"AccountNo \":accno}):\n req = request.get_json()\n print(req)\n filter = {\"AccountNo \":accno}\n for i in req:\n col.update_one(filter, {\"$set\":{i:req[i]}})\n return \"Record updated successfully!\",200\n else:\n res = {\n \"Message\":\"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n\n@app.route(\"/api/delete/\", methods=[\"DELETE\"])\ndef delete_collection(accno):\n try:\n if col.find_one({\"AccountNo \":accno}):\n query = {\"AccountNo \":accno}\n col.delete_one(query)\n res = make_response(jsonify({\"Message\": \"Record deleted successfully\"}), 200)\n return res\n else:\n res = {\n \"Message\": \"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n\n","sub_path":"app/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"465514314","text":"from __future__ import print_function, division\n\n# WORKING COPY OF SPLAT CODE LIBRARY\n# based on routines developed by:\n# Christian Aganze\n# Daniella Bardalez Gagliuffi\n# Adam Burgasser\n# Caleb Choban\n# Ivanna Escala\n# Aishwarya Iyer\n# Yuhui Jin\n# Michael Lopez\n# Alex Mendez\n# Gretel Mercado\n# Jonathan Parra\n# Maitrayee Sahi\n# Adrian Suarez\n# Melisa Tallis\n# Tomoki Tamiya\n\n#\n# CURRENT STATUS (3/12/2015)\n# URGENT\n# fails when reading in unpublished (online) data\n#\n# LESS URGENT\n# reformat fits files so headers have valid information, and spectra are flux calibrated\n# update information for sources in source database\n# add help sections to all programs\n# plotspectrum => multiplot, multipage files\n# proper SQL search for database\n# have classifybyindex return individual index classifications (e.g., 'full' keyword)\n\n# verify the version is correct\nimport sys\nif sys.version_info.major != 2 and sys.version_info.major != 3:\n raise NameError('\\nSPLAT only works on Python 2.7 and 3.X\\n')\n\n# imports\nimport astropy\nimport base64\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\nimport random\nimport re\nimport requests\nimport scipy\nif sys.version_info.major == 2: # switch for those using python 3\n import string\nimport warnings\n\nfrom astropy.io import fits # for reading in spreadsheet\nfrom astropy.table import Table, join # for reading in table files\nfrom astropy.coordinates import SkyCoord # coordinate conversion\nfrom astropy import units as u # standard units\nfrom astropy import constants as const # physical constants in SI units\nfrom scipy import stats, signal\nfrom scipy.integrate import trapz # for numerical integration\nfrom scipy.interpolate import interp1d\n\n# suppress warnings - probably not an entirely safe approach!\nnumpy.seterr(all='ignore')\nwarnings.simplefilter(\"ignore\")\n#from splat._version import __version__\n\n#set the SPLAT PATH, either from set environment variable or from sys.path\nSPLAT_PATH = './'\nif os.environ.get('SPLAT_PATH') != None:\n SPLAT_PATH = os.environ['SPLAT_PATH']\n# get from PYTHONPATH\nif os.environ.get('PYTHONPATH') != None and SPLAT_PATH == './':\n path = os.environ['PYTHONPATH']\n for i in path.split(':'):\n if 'splat' in i:\n SPLAT_PATH = i\n# get from system path\nif SPLAT_PATH == './':\n checkpath = ['splat' in r for r in sys.path]\n if max(checkpath):\n SPLAT_PATH = sys.path[checkpath.index(max(checkpath))]\n\n# local application/library specific import\n#import bdevopar as splevol\nfrom splat_db import *\nfrom splat_model import *\nfrom splat_plot import *\n#import splat_db\n\n#################### CONSTANTS ####################\nSPLAT_URL = 'http://pono.ucsd.edu/~adam/splat/'\nDATA_FOLDER = '/reference/Spectra/'\n\n# explicitly read in source and spectral databases\nDB_SOURCES = fetchDatabase(splat.DB_SOURCES_FILE)\nDB_SPECTRA = fetchDatabase(splat.DB_SPECTRA_FILE)\n\nmonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\nspex_pixel_scale = 0.15 # spatial scale in arcseconds per pixel\nuspex_pixel_scale = 0.10 # spatial scale in arcseconds per pixel\nspex_wave_range = [0.65,2.45]*u.micron # default wavelength range\nmax_snr = 1000.0 # maximum S/N ratio permitted\nTMPFILENAME = 'splattmpfile'\n\nSPEX_STDFILES = { \\\n 'M0.0': '11335_10505.fits',\\\n 'M1.0': '11364_10806.fits',\\\n 'M2.0': '11181_10187.fits',\\\n 'M3.0': '10823_11422.fits',\\\n 'M4.0': '12004_10444.fits',\\\n 'M5.0': '10829_10104.fits',\\\n 'M6.0': '11182_10188.fits',\\\n 'M7.0': '10822_11283.fits',\\\n 'M8.0': '10824_11423.fits',\\\n 'M9.0': '10821_11058.fits',\\\n 'L0.0': '10107_10315.fits',\\\n 'L1.0': '11072_11527.fits',\\\n 'L2.0': '10600_10957.fits',\\\n 'L3.0': '10592_11111.fits',\\\n 'L4.0': '10675_11572.fits',\\\n 'L5.0': '10351_10583.fits',\\\n 'L6.0': '10375_10696.fits',\\\n 'L7.0': '10678_10105.fits',\\\n 'L8.0': '10115_11254.fits',\\\n 'L9.0': '10268_10237.fits',\\\n 'T0.0': '10771_10871.fits',\\\n 'T1.0': '10767_10591.fits',\\\n 'T2.0': '10017_10945.fits',\\\n 'T3.0': '10034_10874.fits',\\\n 'T4.0': '10143_11632.fits',\\\n 'T5.0': '10021_11106.fits',\\\n 'T6.0': '10200_11236.fits',\\\n 'T7.0': '10159_10513.fits',\\\n 'T8.0': '10126_10349.fits',\\\n 'T9.0': '11536_10509.fits'}\n# EMPTY DICTIONARY\nSPEX_STDS = {}\n\nSPEX_SD_STDFILES = { \\\n 'sdM5.5': '11670_11134.fits',\\\n 'sdM6.0': '10265_10045.fits',\\\n 'sdM7.0': '10197_11074.fits',\\\n 'sdM8.0': '10123_10145.fits',\\\n 'sdM9.5': '10188_10700.fits',\\\n 'sdL0.0': '11972_10248.fits',\\\n 'sdL3.5': '10364_10946.fits',\\\n 'sdL4.0': '10203_11241.fits'}\n# EMPTY DICTIONARY\nSPEX_SD_STDS = {}\n\nSPEX_ESD_STDFILES = { \\\n 'esdM5.0': '10229_10163.fits',\\\n# 'esdM6.5': '_10579.fits',\\\n 'esdM7.0': '10521_10458.fits',\\\n 'esdM8.5': '10278_10400.fits'}\n# EMPTY DICTIONARY\nSPEX_ESD_STDS = {}\n\n\n# filters\nFILTER_FOLDER = '/reference/Filters/'\nFILTERS = { \\\n '2MASS_J': {'file': 'j_2mass.txt', 'description': '2MASS J-band', 'zeropoint': 1594.0}, \\\n '2MASS_H': {'file': 'h_2mass.txt', 'description': '2MASS H-band', 'zeropoint': 1024.0}, \\\n '2MASS_KS': {'file': 'ks_2mass.txt', 'description': '2MASS Ks-band', 'zeropoint': 666.7}, \\\n 'BESSEL_I': {'file': 'bessel_i.txt', 'description': 'Bessel I-band', 'zeropoint': 2405.3}, \\\n 'HAWK_Y': {'file': 'hawk-y.txt', 'description': 'HAWK Y-band', 'zeropoint': 2092.9}, \\\n 'HAWK_J': {'file': 'hawk-j.txt', 'description': 'HAWK J-band', 'zeropoint': 1543.5}, \\\n 'HAWK_H': {'file': 'hawk-h.txt', 'description': 'HAWK H-band', 'zeropoint': 1053.6}, \\\n 'HAWK_H2': {'file': 'hawk-h2.txt', 'description': 'HAWK H2-band', 'zeropoint': 688.8}, \\\n 'HAWK_CH4': {'file': 'hawk-ch4.txt', 'description': 'HAWK CH4-band', 'zeropoint': 1093.4}, \\\n 'HAWK_KS': {'file': 'hawk-ks.txt', 'description': 'HAWK Ks-band', 'zeropoint': 675.3}, \\\n 'HAWK_BRG': {'file': 'hawk-brg.txt', 'description': 'HAWK Brackett Gamma', 'zeropoint': 638.9}, \\\n 'HAWK_NB1060': {'file': 'hawk-nb1060.txt', 'description': 'HAWK Narrow Band 1060', 'zeropoint': 2003.27}, \\\n 'HAWK_NB1190': {'file': 'hawk-nb1190.txt', 'description': 'HAWK Narrow Band 1190', 'zeropoint': 1697.50}, \\\n 'HAWK_NB2090': {'file': 'hawk-nb2090.txt', 'description': 'HAWK Narrow Band 2090', 'zeropoint': 706.68}, \\\n 'FOURSTAR_J': {'file': 'fourstar-j.txt', 'description': 'FOURSTAR J-band', 'zeropoint': 1581.2}, \\\n 'FOURSTAR_J1': {'file': 'fourstar-j1.txt', 'description': 'FOURSTAR J1-band', 'zeropoint': 1978.7}, \\\n 'FOURSTAR_J2': {'file': 'fourstar-j2.txt', 'description': 'FOURSTAR J2-band', 'zeropoint': 1774.5}, \\\n 'FOURSTAR_J3': {'file': 'fourstar-j3.txt', 'description': 'FOURSTAR J3-band', 'zeropoint': 1488.8}, \\\n 'FOURSTAR_H': {'file': 'fourstar-h.txt', 'description': 'FOURSTAR H-band', 'zeropoint': 1054.9}, \\\n 'FOURSTAR_H_SHORT': {'file': 'fourstar-hshort.txt', 'description': 'FOURSTAR H short', 'zeropoint': 1119.1}, \\\n 'FOURSTAR_H_LONG': {'file': 'fourstar-hlong.txt', 'description': 'FOURSTAR H long', 'zeropoint': 980.7}, \\\n 'FOURSTAR_KS': {'file': 'fourstar-j.txt', 'description': 'FOURSTAR Ks-band', 'zeropoint': 675.7}, \\\n 'IRAC_CH1': {'file': 'irac1.txt', 'description': 'IRAC Channel 1 (3.6 micron)', 'zeropoint': 280.9}, \\\n 'IRAC_CH2': {'file': 'irac2.txt', 'description': 'IRAC Channel 2 (4.5 micron)', 'zeropoint': 179.7}, \\\n 'IRAC_CH3': {'file': 'irac3.txt', 'description': 'IRAC Channel 3 (5.8 micron)', 'zeropoint': 115.0}, \\\n 'IRAC_CH4': {'file': 'irac4.txt', 'description': 'IRAC Channel 4 (8.0 micron)', 'zeropoint': 64.13}, \\\n 'MKO_J_ATM': {'file': 'j_atm_mko.txt', 'description': 'MKO J-band + atmosphere', 'zeropoint': 1562.3}, \\\n 'MKO_H_ATM': {'file': 'h_atm_mko.txt', 'description': 'MKO H-band + atmosphere', 'zeropoint': 1045.9}, \\\n 'MKO_K_ATM': {'file': 'k_atm_mko.txt', 'description': 'MKO K-band + atmosphere', 'zeropoint': 647.7}, \\\n 'MKO_J': {'file': 'mko_j.txt', 'description': 'MKO J-band + atmosphere', 'zeropoint': 1562.3}, \\\n 'MKO_H': {'file': 'mko_h.txt', 'description': 'MKO H-band + atmosphere', 'zeropoint': 1045.9}, \\\n 'MKO_K': {'file': 'mko_ks.txt', 'description': 'MKO K-band', 'zeropoint': 647.7}, \\\n 'MKO_KP': {'file': 'mko_kp.txt', 'description': 'MKO Kp-band', 'zeropoint': 693.7}, \\\n 'MKO_LP': {'file': 'mko_lp.txt', 'description': 'MKO Lp-band', 'zeropoint': 248.3}, \\\n 'MKO_MP': {'file': 'mko_mp.txt', 'description': 'MKO Mp-band', 'zeropoint': 164.7}, \\\n 'NICMOS_F090M': {'file': 'nic1_f090m.txt', 'description': 'NICMOS F090M', 'zeropoint': 2255.0}, \\\n 'NICMOS_F095N': {'file': 'nic1_f095n.txt', 'description': 'NICMOS F095N', 'zeropoint': 2044.6}, \\\n 'NICMOS_F097N': {'file': 'nic1_f097n.txt', 'description': 'NICMOS F097N', 'zeropoint': 2275.4}, \\\n 'NICMOS_F108N': {'file': 'nic1_f108n.txt', 'description': 'NICMOS F108N', 'zeropoint': 1937.3}, \\\n 'NICMOS_F110M': {'file': 'nic1_f110m.txt', 'description': 'NICMOS F110M', 'zeropoint': 1871.8}, \\\n 'NICMOS_F110W': {'file': 'nic1_f110w.txt', 'description': 'NICMOS F110W', 'zeropoint': 1768.5}, \\\n 'NICMOS_F113N': {'file': 'nic1_f113n.txt', 'description': 'NICMOS F113N', 'zeropoint': 1821.0}, \\\n 'NICMOS_F140W': {'file': 'nic1_f140w.txt', 'description': 'NICMOS F140W', 'zeropoint': 1277.1}, \\\n 'NICMOS_F145M': {'file': 'nic1_f145m.txt', 'description': 'NICMOS F145M', 'zeropoint': 1242.0}, \\\n 'NICMOS_F160W': {'file': 'nic1_f160w.txt', 'description': 'NICMOS F160W', 'zeropoint': 1071.7}, \\\n 'NICMOS_F164N': {'file': 'nic1_f164n.txt', 'description': 'NICMOS F164N', 'zeropoint': 1003.0}, \\\n 'NICMOS_F165M': {'file': 'nic1_f165m.txt', 'description': 'NICMOS F165M', 'zeropoint': 1023.6}, \\\n 'NICMOS_F166N': {'file': 'nic1_f166n.txt', 'description': 'NICMOS F166N', 'zeropoint': 1047.7}, \\\n 'NICMOS_F170M': {'file': 'nic1_f170m.txt', 'description': 'NICMOS F170M', 'zeropoint': 979.1}, \\\n 'NICMOS_F187N': {'file': 'nic1_f187n.txt', 'description': 'NICMOS F187N', 'zeropoint': 803.7}, \\\n 'NICMOS_F190N': {'file': 'nic1_f190n.txt', 'description': 'NICMOS F190N', 'zeropoint': 836.5}, \\\n 'NIRC2_J': {'file': 'nirc2-j.txt', 'description': 'NIRC2 J-band', 'zeropoint': 1562.7}, \\\n 'NIRC2_H': {'file': 'nirc2-h.txt', 'description': 'NIRC2 H-band', 'zeropoint': 1075.5}, \\\n 'NIRC2_HCONT': {'file': 'nirc2-hcont.txt', 'description': 'NIRC2 H-continuum band', 'zeropoint': 1044.5}, \\\n 'NIRC2_K': {'file': 'nirc2-k.txt', 'description': 'NIRC2 K-band', 'zeropoint': 648.9}, \\\n 'NIRC2_KP': {'file': 'nirc2-kp.txt', 'description': 'NIRC2 Kp-band', 'zeropoint': 689.3}, \\\n 'NIRC2_KS': {'file': 'nirc2-ks.txt', 'description': 'NIRC2 Ks-band', 'zeropoint': 676.2}, \\\n 'NIRC2_KCONT': {'file': 'nirc2-kcont.txt', 'description': 'NIRC2 K continuum-band', 'zeropoint': 605.9}, \\\n 'NIRC2_FE2': {'file': 'nirc2-fe2.txt', 'description': 'WIRC Fe II', 'zeropoint': 1019.7}, \\\n 'NIRC2_LP': {'file': 'nirc2-lp.txt', 'description': 'WIRC Fe II', 'zeropoint': 248.0}, \\\n 'NIRC2_M': {'file': 'nirc2-ms.txt', 'description': 'WIRC Fe II', 'zeropoint': 165.8}, \\\n 'PANSTARRS_I': {'file': 'panstarrs-i.txt', 'description': 'PANSTARRS i-band', 'zeropoint': 2584.6}, \\\n 'PANSTARRS_Z': {'file': 'panstarrs-z.txt', 'description': 'PANSTARRS z-band', 'zeropoint': 2584.6}, \\\n 'PANSTARRS_Y': {'file': 'panstarrs-y.txt', 'description': 'PANSTARRS y-band', 'zeropoint': 2584.6}, \\\n 'UKIDSS_Z': {'file': 'ukidss-z.txt', 'description': 'UKIDSS Z-band', 'zeropoint': 2261.4}, \\\n 'UKIDSS_Y': {'file': 'ukidss-y.txt', 'description': 'UKIDSS Y-band', 'zeropoint': 2057.2}, \\\n 'UKIDSS_J': {'file': 'ukidss-j.txt', 'description': 'UKIDSS J-band', 'zeropoint': 1556.8}, \\\n 'UKIDSS_H': {'file': 'ukidss-h.txt', 'description': 'UKIDSS H-band', 'zeropoint': 1038.3}, \\\n 'UKIDSS_K': {'file': 'ukidss-k.txt', 'description': 'UKIDSS K-band', 'zeropoint': 644.1}, \\\n 'VISTA_Z': {'file': 'vista_z.txt', 'description': 'VISTA Z-band', 'zeropoint': 2263.81}, \\\n 'VISTA_Y': {'file': 'vista_y.txt', 'description': 'VISTA Y-band', 'zeropoint': 2087.32}, \\\n 'VISTA_J': {'file': 'vista_j.txt', 'description': 'VISTA J-band', 'zeropoint': 1554.03}, \\\n 'VISTA_H': {'file': 'vista_h.txt', 'description': 'VISTA H-band', 'zeropoint': 1030.40}, \\\n 'VISTA_KS': {'file': 'vista_ks.txt', 'description': 'VISTA Ks-band', 'zeropoint': 674.83}, \\\n 'WFC3_F127M': {'file': 'wfc3_F127M.txt', 'description': 'WFC3 F127M', 'zeropoint': 2261.3}, \\\n 'WFC3_F139M': {'file': 'wfc3_F139M.txt', 'description': 'WFC3 F139M', 'zeropoint': 2261.3}, \\\n 'WFC3_F164N': {'file': 'wfc3_F164M.txt', 'description': 'WFC3 F164N', 'zeropoint': 2261.3}, \\\n 'WFC3_F167N': {'file': 'wfc3_F160W.txt', 'description': 'WFC3 F160W', 'zeropoint': 2261.3}, \\\n 'WFCAM_Z': {'file': 'wfcam-z.txt', 'description': 'UKIRT WFCAM Z', 'zeropoint': 2261.3}, \\\n 'WFCAM_Y': {'file': 'wfcam-y.txt', 'description': 'UKIRT WFCAM Y', 'zeropoint': 2040.9}, \\\n 'WFCAM_J': {'file': 'wfcam-j.txt', 'description': 'UKIRT WFCAM J', 'zeropoint': 1548.7}, \\\n 'WFCAM_H': {'file': 'wfcam-h.txt', 'description': 'UKIRT WFCAM H', 'zeropoint': 1027.1}, \\\n 'WFCAM_H2': {'file': 'wfcam-h2.txt', 'description': 'UKIRT WFCAM H2', 'zeropoint': 677.1}, \\\n 'WFCAM_BRG': {'file': 'wfcam-brg.txt', 'description': 'UKIRT WFCAM Brackett Gamma', 'zeropoint': 645.5}, \\\n 'WFCAM_K': {'file': 'wfcam-k.txt', 'description': 'UKIRT WFCAM K', 'zeropoint': 630.0}, \\\n 'WIRCAM_Y': {'file': 'wircam-cfht-y.txt', 'description': 'CFHT WIRCAM Y', 'zeropoint': 2073.32}, \\\n 'WIRCAM_J': {'file': 'wircam-cfht-j.txt', 'description': 'CFHT WIRCAM J', 'zeropoint': 1551.01}, \\\n 'WIRCAM_H': {'file': 'wircam-cfht-h.txt', 'description': 'CFHT WIRCAM H', 'zeropoint': 1044.35}, \\\n 'WIRCAM_KS': {'file': 'wircam-cfht-ks.txt', 'description': 'CFHT WIRCAM Ks', 'zeropoint': 674.62}, \\\n 'WIRCAM_KCONT': {'file': 'wircam-cfht-kcont.txt', 'description': 'CFHT WIRCAM K-cont', 'zeropoint': 636.17}, \\\n 'WIRCAM_CH4_OFF': {'file': 'wircam-cfht-ch4s.txt', 'description': 'CFHT WIRCAM CH4-on', 'zeropoint': 987.39}, \\\n 'WIRCAM_CH4_ON': {'file': 'wircam-cfht-ch4l.txt', 'description': 'CFHT WIRCAM CH4-off', 'zeropoint': 1076.31}, \\\n 'WIRC_J': {'file': 'wirc_jcont.txt', 'description': 'WIRC J-cont', 'zeropoint': 0.}, \\\n 'WIRC_H': {'file': 'wirc_hcont.txt', 'description': 'WIRC H-cont', 'zeropoint': 0.}, \\\n 'WIRC_K': {'file': 'wirc_kcont.txt', 'description': 'WIRC K-cont', 'zeropoint': 0.}, \\\n 'WIRC_CO': {'file': 'wirc_co.txt', 'description': 'WIRC CO', 'zeropoint': 0.}, \\\n 'WIRC_CH4S': {'file': 'wirc_ch4s.txt', 'description': 'WIRC CH4S', 'zeropoint': 0.}, \\\n 'WIRC_CH4L': {'file': 'wirc_ch4l.txt', 'description': 'WIRC CH4L', 'zeropoint': 0.}, \\\n 'WIRC_FE2': {'file': 'wirc_feii.txt', 'description': 'WIRC Fe II', 'zeropoint': 0.}, \\\n 'WIRC_BRGAMMA': {'file': 'wirc_brgamma.txt', 'description': 'WIRC H I Brackett Gamma', 'zeropoint': 0.}, \\\n 'WIRC_PABETA': {'file': 'wirc_pabeta.txt', 'description': 'WIRC H I Paschen Beta', 'zeropoint': 0.}, \\\n 'WISE_W1': {'file': 'wise_w1.txt', 'description': 'WISE W1 (3.5 micron)', 'zeropoint': 309.54}, \\\n 'WISE_W2': {'file': 'wise_w2.txt', 'description': 'WISE W2 (4.6 micron)', 'zeropoint': 171.79}, \\\n 'WISE_W3': {'file': 'wise_w3.txt', 'description': 'WISE W3 (13 micron)', 'zeropoint': 31.67}, \\\n 'WISE_W4': {'file': 'wise_w4.txt', 'description': 'WISE W4 (22 micron)', 'zeropoint': 8.363} \\\n }\n\n# Index sets\nindex_sets = ['burgasser','bardalez','tokunaga','reid','geballe','allers','testi','slesnick','mclean','rojas']\n\n# change the command prompt\nsys.ps1 = 'splat> '\n\n#####################################################\n\n\n# helper functions from Alex\ndef lazyprop(fn):\n attr_name = '_lazy_' + fn.__name__\n @property\n def _lazyprop(self):\n if not hasattr(self, attr_name):\n setattr(self, attr_name, fn(self))\n return getattr(self, attr_name)\n return _lazyprop\n\ndef Show(fn):\n def _show(self, *args, **kwargs):\n noplot = kwargs.pop('noplot', False)\n quiet = kwargs.pop('quiet', False)\n tmp = fn(self, *args, **kwargs)\n# if not quiet:\n# self.info()\n# if not noplot:\n# self.plot(**kwargs)\n return tmp\n return _show\n\ndef Copy(fn):\n def _copy(self, *args, **kwargs):\n out = copy.copy(self)\n return fn(out, *args, **kwargs)\n return _copy\n\n\n# define the Spectrum class which contains the relevant information\nclass Spectrum(object):\n '''\n :Description: Primary class for containing spectral and source data for SpeX Prism Library.\n\n :param model:\n :type model: optional, default = False\n :param wlabel: label of wavelength\n :type wlabel: optional, default = 'Wavelength'\n :param wunit: unit in which wavelength is measured\n :type wunit: optional, default = ``u.micron``\n :param wunit_label: label of the unit of wavelength\n :type wunit_label: optional, default = :math:`\\\\mu m`\n :param flabel: label of flux density\n :type flabel: optional, default = :math:`F_\\\\lambda`\n :param fscale: string describing how flux density is scaled\n :type fscale: optional, default = ''\n :param funit: unit in which flux density is measured\n :type funit: optional, default = ``u.erg/(u.cm**2 * u.s * u.micron)``\n :param funit_label: label of the unit of flux density\n :type funit_label: optional, default = :math:`erg\\;cm^{-2} s^{-1} \\\\mu m^{-1}`\n :param resolution:\n :type resolution: optional, default = 150\n :param slitpixelwidth: Width of the slit measured in subpixel values.\n :type slitpixelwidth: optional, default = 3.33\n :param slitwidth: Actual width of the slit, measured in arc seconds. Default value is the ``slitpixelwidth`` multiplied by the spectrograph pixel scale of 0.15 arcseconds.\n :type slitwidth: optional, default = ``slitpixelwidth`` * 0.15\n :param header: header info of the spectrum\n :type header: optional, default = Table()\n :param filename: a string containing the spectrum's filename.\n :type filename: optional, default = ''\n :param file: same as filename\n :type file: optional, default = ''\n :param idkey: spectrum key of the desired spectrum\n :type idkey: optional, default = False\n\n :Example:\n >>> import splat\n >>> sp = splat.Spectrum(filename='myspectrum.fits') # read in a file\n >>> sp = splat.Spectrum('myspectrum.fits') # same\n >>> sp = splat.Spectrum(10002) # read in spectrum with idkey = 10002\n >>> sp = splat.Spectrum(wave=wavearray,flux=fluxarray) # create objects with wavelength & flux arrays\n '''\n\n def __init__(self, *args, **kwargs):\n# some presets\n sdb = False\n self.model = kwargs.get('model',False)\n self.wlabel = kwargs.get('wlabel',r'Wavelength')\n self.wunit = kwargs.get('wunit',u.micron)\n self.wunit_label = kwargs.get('wunit_label',r'$\\mu$m')\n self.flabel = kwargs.get('flabel',r'F$_{\\lambda}$')\n self.fscale = kwargs.get('fscale','')\n self.funit = kwargs.get('funit',u.erg/(u.cm**2 * u.s * u.micron))\n self.funit_label = kwargs.get('funit_label',r'erg~cm$^{-2}$~s$^{-1}$~$\\mu$m$^{-1}$')\n self.resolution = kwargs.get('resolution',150) # default placeholder\n self.slitpixelwidth = kwargs.get('slitwidth',3.33) # default placeholder\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n# self.header = kwargs.get('header',fits.PrimaryHDU())\n self.header = kwargs.get('header',{})\n self.filename = kwargs.get('file','')\n self.filename = kwargs.get('filename',self.filename)\n self.idkey = kwargs.get('idkey',False)\n\n# option 1: a filename is given\n if (len(args) > 0):\n if isinstance(args[0],str):\n self.filename = args[0]\n if kwargs.get('file',self.filename) != '':\n self.filename = kwargs.get('file',self.filename)\n if kwargs.get('filename',self.filename) != '':\n self.filename = kwargs.get('filename',self.filename)\n\n# option 2: a spectrum ID is given\n if (len(args) > 0):\n if isinstance(args[0],int):\n self.idkey = args[0]\n\n\n if self.idkey != False:\n# self.idkey = kwargs.get('idkey',self.idkey)\n try:\n sdb = keySpectrum(self.idkey)\n if sdb != False:\n self.filename = sdb['DATA_FILE'][0]\n except:\n print('Warning: problem reading in spectral database, a known problem for Python 3.X')\n elif self.model == False and self.filename != '':\n kwargs['filename']=self.filename\n kwargs['silent']=True\n try:\n t = searchLibrary(**kwargs)\n if len(t) > 0:\n sdb = t\n except:\n print('Warning: problem reading in source or spectral database, a known problem for Python 3.X') \n else:\n sdb = False\n\n# set up folder - by default this is local data directory\n kwargs['folder'] = kwargs.get('folder',SPLAT_PATH+DATA_FOLDER)\n self.simplefilename = os.path.basename(self.filename)\n self.file = self.filename\n self.name = kwargs.get('name',self.simplefilename)\n kwargs['filename'] = self.filename\n\n# option 3: wave and flux are given\n if len(kwargs.get('wave','')) > 0 and len(kwargs.get('flux','')) > 0:\n self.wave = kwargs['wave']\n self.flux = kwargs['flux']\n if len(kwargs.get('noise','')) > 0:\n self.noise = kwargs['noise']\n else:\n self.noise = numpy.array([numpy.nan for i in self.wave])\n\n# read in data from file\n elif self.filename != '':\n try:\n rs = readSpectrum(self.filename,**kwargs)\n self.wave = rs['wave']\n self.flux = rs['flux']\n self.noise = rs['noise']\n self.header = rs['header']\n except:\n raise NameError('\\nCould not load spectral file {:s}, recheck the filename and path'.format(kwargs.get('filename','')))\n\n# empty spectrum vessel (used for copying)\n else:\n self.wave = []\n self.flux = []\n self.noise = []\n\n# process spectral data\n if len(self.wave) > 0:\n# convert to numpy arrays\n self.wave = numpy.array(self.wave)\n self.flux = numpy.array(self.flux)\n self.noise = numpy.array(self.noise)\n# enforce positivity and non-nan\n if (numpy.nanmin(self.flux) < 0):\n self.flux[numpy.where(self.flux < 0)] = 0.\n self.flux[numpy.isnan(self.flux)] = 0.\n# check on noise being too low\n if (numpy.nanmax(self.flux/self.noise) > max_snr):\n self.noise[numpy.where(self.flux/self.noise > max_snr)]=numpy.median(self.noise)\n# convert to astropy quantities with units\n# assuming input is flam in erg/s/cm2/micron\n if ~isinstance(self.wave,astropy.units.quantity.Quantity):\n self.wave = numpy.array(self.wave)*self.wunit\n if ~isinstance(self.flux,astropy.units.quantity.Quantity):\n self.flux = numpy.array(self.flux)*self.funit\n if ~isinstance(self.wave,astropy.units.quantity.Quantity):\n self.noise = numpy.array(self.noise)*self.funit\n# some conversions\n self.flam = self.flux\n self.nu = self.wave.to('Hz',equivalencies=u.spectral())\n self.fnu = self.flux.to('Jy',equivalencies=u.spectral_density(self.wave))\n self.fnu_unit = u.Jansky\n# calculate variance\n self.variance = self.noise**2\n self.dof = numpy.round(len(self.wave)/self.slitpixelwidth)\n# signal to noise\n w = numpy.where(self.flux.value > numpy.median(self.flux.value))\n self.snr = numpy.nanmean(self.flux.value[w]/self.noise.value[w])\n\n# preserve original values\n self.wave_original = copy.deepcopy(self.wave)\n self.flux_original = copy.deepcopy(self.flux)\n self.noise_original = copy.deepcopy(self.noise)\n self.variance_original = copy.deepcopy(self.variance)\n# self.resolution = copy.deepcopy(self.resolution)\n# self.slitpixelwidth = copy.deepcopy(self.slitpixelwidth)\n else:\n print ('Warning: not information provided, creating an empty Spectrum object')\n\n# populate information on source and spectrum from database\n if sdb != False:\n for k in sdb.keys():\n setattr(self,k.lower(),sdb[k][0])\n self.shortname = designationToShortName(self.designation)\n self.date = self.observation_date\n# convert some data into numbers\n kconv = ['ra','dec','julian_date','median_snr','resolution','airmass',\\\n 'jmag','jmag_error','hmag','hmag_error','kmag','kmag_error','source_key']\n for k in kconv:\n try:\n setattr(self,k,float(getattr(self,k)))\n except:\n setattr(self,k,numpy.nan)\n# print(getattr(self,k))\n \n\n# information on model\n if self.model == True:\n self.teff = kwargs.get('teff',numpy.nan)\n self.logg = kwargs.get('logg',numpy.nan)\n self.z = kwargs.get('z',numpy.nan)\n self.fsed = kwargs.get('fsed',numpy.nan)\n self.cld = kwargs.get('cld',numpy.nan)\n self.kzz = kwargs.get('kzz',numpy.nan)\n self.slit = kwargs.get('slit',numpy.nan)\n self.modelset = kwargs.get('set','')\n self.name = self.modelset+' Teff='+str(self.teff)+' logg='+str(self.logg)+' [M/H]='+str(self.z)\n self.fscale = 'Surface'\n\n# populate header \n kconv = ['designation','name','shortname','ra','dec','slitwidth','source_key','data_key','observer',\\\n 'data_reference','discovery_reference','program_pi','program_number','airmass','reduction_spextool_version',\\\n 'reduction_person','reduction_date','observation_date','julian_date','median_snr','resolution','airmass']\n for k in kconv:\n try:\n self.header[k] = getattr(self,k)\n except:\n self.header[k] = ''\n\n self.history = ['Loaded']\n\n\n def __copy__(self):\n s = type(self)()\n s.__dict__.update(self.__dict__)\n return s\n\n# backup version\n def copy(self):\n s = type(self)()\n s.__dict__.update(self.__dict__)\n return s\n\n def __repr__(self):\n '''\n :Purpose: A simple representation of an object is to just give it a name\n '''\n return 'Spectrum of {}'.format(self.name)\n\n def __add__(self,other):\n '''\n :Purpose: Adds two spectra\n :param other: the other spectrum to add to the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.add(self.flux,f(self.wave)*other.funit)\n sp.variance = sp.variance+n(self.wave)*(other.funit**2)\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' + '+other.name\n return sp\n\n def __sub__(self,other):\n '''\n :Purpose: Subtracts two spectra\n :param other: the other spectrum to subtract from the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.subtract(self.flux,f(self.wave)*other.funit)\n sp.variance = sp.variance+n(self.wave)*(other.funit**2)\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' - '+other.name\n return sp\n\n def __mul__(self,other):\n '''\n :Purpose: Multiplies two spectra\n :param other: the other spectrum to multiply by the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.multiply(self.flux,f(self.wave)*other.funit)\n sp.variance = numpy.multiply(sp.flux**2,(\\\n numpy.divide(self.variance.value,sp.flux.value**2)+numpy.divide(n(self.wave),f(self.wave)**2)))\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' x '+other.name\n sp.funit = sp.flux.unit\n return sp\n\n def __div__(self,other):\n '''\n :Purpose: Divides two spectra\n :param other: the other spectrum to divide by the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.divide(self.flux,f(self.wave)*other.funit)\n sp.variance = numpy.multiply(sp.flux**2,(\\\n numpy.divide(self.variance.value,sp.flux.value**2)+numpy.divide(n(self.wave),f(self.wave)**2)))\n sp.noise = sp.variance**0.5\n# clean up infinities\n sp.flux = numpy.where(numpy.absolute(sp.flux) == numpy.inf, numpy.nan, sp.flux)*u.erg/u.erg\n sp.noise = numpy.where(numpy.absolute(sp.noise) == numpy.inf, numpy.nan, sp.noise)*u.erg/u.erg\n sp.variance = numpy.where(numpy.absolute(sp.variance) == numpy.inf, numpy.nan, sp.variance)*u.erg/u.erg\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' / '+other.name\n sp.funit = sp.flux.unit\n return sp\n\n def info(self):\n '''\n :Purpose: Reports some information about this spectrum.\n '''\n if (self.model):\n print('\\n{} model with the following parmeters:'.format(self.modelset))\n print('Teff = {} K'.format(self.teff))\n print('logg = {} cm/s2'.format(self.logg))\n print('z = {}'.format(self.z))\n print('fsed = {}'.format(self.fsed))\n print('cld = {}'.format(self.cld))\n print('kzz = {}'.format(self.kzz))\n print('Smoothed to slit width {} arcseconds\\n'.format(self.slit))\n else:\n# print('\\nSpectrum of {0} observed on {1}'''.format(self.name, self.date))\n text = ['Spectrum of','Observed on','Observed by','at an airmass of','Full source designation is', 'Median S/N =','SPLAT source key is','SPLAT spectrum key is']\n ref = ['name','date','observer','airmass','designation','median_snr','source_key','data_key']\n for i,k in enumerate(ref):\n try:\n if getattr(self,k) != '':\n print('\\t{} {}'.format(text[i],getattr(self,k)))\n except:\n pass\n try:\n bib = getBibTex(self.data_reference)\n print('\\tData published in {}'.format(shortRef(bib)))\n except:\n pass\n# print('\\nPlot spectrum using .plot()')\n return\n\n def flamToFnu(self):\n '''\n :Purpose: Converts flux density from :math:`F_\\\\lambda` to :math:`F_\\\\nu`, the later in Jy\n '''\n self.funit = u.Jy\n self.flabel = 'F_nu'\n self.flux.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.noise.to(self.funit,equivalencies=u.spectral_density(self.wave))\n return\n\n def fluxCalibrate(self,f,mag,**kwargs):\n '''\n :Purpose: Calibrates spectrum to input magnitude\n '''\n absolute = kwargs.get('absolute',False)\n apparent = kwargs.get('apparent',False)\n self.normalize()\n apmag,apmag_e = filterMag(self,f,**kwargs)\n# NOTE: NEED TO INCORPORATE UNCERTAINTY INTO SPECTRAL UNCERTAINTY\n if (~numpy.isnan(apmag)):\n self.scale(10.**(0.4*(apmag-mag)))\n if (absolute):\n self.fscale = 'Absolute'\n if (apparent):\n self.fscale = 'Apparent'\n return\n\n# determine maximum flux, by default in non telluric regions\n def fluxMax(self,**kwargs):\n '''\n :Purpose: Determines maximum flux of spectrum\n :param maskTelluric: masks telluric regions\n :type maskTelluric: optional, default = True\n '''\n if kwargs.get('maskTelluric',True):\n return numpy.nanmax(self.flux.value[numpy.where(\\\n numpy.logical_or(\\\n numpy.logical_and(self.wave > 0.9*u.micron,self.wave < 1.35*u.micron),\n numpy.logical_and(self.wave > 1.42*u.micron,self.wave < 1.8*u.micron),\n numpy.logical_and(self.wave > 1.92*u.micron,self.wave < 2.3*u.micron)))])*self.funit\n else:\n return numpy.nanmax(self.flux.value[numpy.where(\\\n numpy.logical_and(self.wave > 0.9*u.micron,self.wave < 2.3*u.micron))])*self.funit\n\n def fnuToFlam(self):\n '''\n :Purpose: Converts flux density from :math:`F_\\\\nu` to :math:`F_\\\\lambda`, the later in erg/s/cm2/Hz\n '''\n self.funit = u.erg/(u.cm**2 * u.s * u.micron)\n self.flabel = 'F_lam'\n self.flux.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.noise.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.variance = self.noise**2\n return\n\n def normalize(self,**kwargs):\n '''\n :Purpose: Normalizes spectrum to its maximum flux.\n :param maskTelluric: masks telluric regions\n :type maskTelluric: optional, default = True\n '''\n if kwargs.get('waveRange',False) != False:\n rng = kwargs.get('waveRange')\n if not isinstance(rng,list):\n rng = [rng]\n if len(rng) < 2:\n rng = [rng[0]-0.02,rng[0]+0.02]\n self.scale(1./numpy.nanmax(self.flux.value[numpy.where(numpy.logical_and(self.wave > rng[0]*u.micron,self.wave < rng[1]*u.micron))]))\n else:\n self.scale(1./self.fluxMax(**kwargs).value)\n self.fscale = 'Normalized'\n return\n\n def plot(self,**kwargs):\n '''\n :Purpose: Plots spectrum. See SPLAT Plotting Routines page for more details.\n '''\n plotSpectrum(self,showNoise=True,showZero=True,**kwargs)\n\n def reset(self):\n '''\n :Purpose: Resets to original spectrum\n '''\n self.wave = copy.deepcopy(self.wave_original)\n self.flux = copy.deepcopy(self.flux_original)\n self.noise = copy.deepcopy(self.noise_original)\n self.variance = copy.deepcopy(self.variance_original)\n self.resolution = copy.deepcopy(self.resolution_original)\n self.slitpixelwidth = copy.deepcopy(self.slitpixelwidth_original)\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.fscale = ''\n return\n\n def export(self,*args,**kwargs):\n '''\n :Purpose: export spectrum object to a file, either fits or ascii depending on file extension\n '''\n filename = self.simplefilename\n if len(args) > 0:\n filename = args[0]\n filename = kwargs.get('filename',filename)\n filename = kwargs.get('file',filename)\n\n# determine which type of file\n ftype = filename.split('.')[-1]\n\n# fits file\n if (ftype == 'fit' or ftype == 'fits'):\n try:\n data = numpy.vstack((self.wave.value,self.flux.value,self.noise.value)).T\n hdu = fits.PrimaryHDU(data)\n for k in self.header.keys():\n hdu.header[k] = self.header[k]\n hdu.writeto(filename,clobber=True)\n except:\n raise NameError('Problem saving spectrum object to file {}'.format(filename))\n\n# ascii file - by default space delimited (could make this more flexible)\n else:\n try:\n t = Table([self.wave.value,self.flux.value,self.noise.value],names=['wavelength','flux','uncertainty'])\n if kwargs.get('header',True):\n hd = ['{} = {}'.format(k,self.header[k]) for k in self.header.keys()]\n hd = list(set(hd))\n hd.sort()\n t.meta['comments']=hd\n ascii.write(t,output=filename,format=kwargs.get('format','commented_header'))\n except:\n raise NameError('Problem saving spectrum object to file {}'.format(filename))\n return\n\n def scale(self,factor):\n '''\n :Purpose: Smooths spectrum to a constant slit width (smooths by pixels)\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n :param slitpixelwidth: Width of the slit measured in subpixel values.\n :type slitpixelwidth: optional, default = 3.33\n :param slitwidth: Actual width of the slit, measured in arc seconds. Default value is the ``slitpixelwidth`` multiplied by the spectrograph pixel scale of 0.15 arcseconds.\n :param resolution:\n :type resolution: optional, default = 150\n :type slitwidth: optional, default = slitpixelwidth * 0.15\n '''\n self.flux = self.flux*factor\n self.noise = self.noise*factor\n self.variance = self.noise**2\n self.fscale = 'Scaled'\n return\n\n def smooth(self,**kwargs):\n '''Smooth spectrum to a constant slit width (smooth by pixels)'''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n swargs = copy.deepcopy(kwargs)\n if (kwargs.get('slitPixelWidth','') != ''):\n del swargs['slitPixelWidth']\n self.smoothToSlitPixelWidth(kwargs['slitPixelWidth'],**swargs)\n elif (kwargs.get('resolution','') != ''):\n del swargs['resolution']\n self.smoothToResolution(kwargs['resolution'],**swargs)\n elif (kwargs.get('slitWidth','') != ''):\n del swargs['slitWidth']\n self.smoothToSlitWidth(kwargs['slitWidth'],**swargs)\n return\n\n def smoothToResolution(self,resolution,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant resolution\n :param resolution: resolution for smoothing the spectrum\n :param overscale: used for computing number of samples in the window\n :type overscale: optional, default = 10.\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n overscale = kwargs.get('overscale',10.)\n method = kwargs.get('method','hamming')\n kwargs['method'] = method\n\n# do nothing if requested resolution is higher than current resolution\n if (resolution < self.resolution):\n# sample onto a constant resolution grid at 5x current resolution\n r = resolution*overscale\n waveRng = self.waveRange()\n npix = numpy.floor(numpy.log(waveRng[1]/waveRng[0])/numpy.log(1.+1./r))\n wave_sample = [waveRng[0]*(1.+1./r)**i for i in numpy.arange(npix)]\n f = interp1d(self.wave,self.flux,bounds_error=False,fill_value=0.)\n v = interp1d(self.wave,self.variance,bounds_error=False,fill_value=numpy.nan)\n flx_sample = f(wave_sample)*self.funit\n var_sample = v(wave_sample)*self.funit**2\n# now convolve a function to smooth resampled spectrum\n window = signal.get_window(method,numpy.round(overscale))\n neff = numpy.sum(window)/numpy.nanmax(window) # effective number of pixels\n flx_smooth = signal.convolve(flx_sample, window/numpy.sum(window), mode='same')\n var_smooth = signal.convolve(var_sample, window/numpy.sum(window), mode='same')/neff\n# resample back to original wavelength grid\n f = interp1d(wave_sample,flx_smooth,bounds_error=False,fill_value=0.)\n v = interp1d(wave_sample,var_smooth,bounds_error=False,fill_value=0.)\n self.flux = f(self.wave)*self.funit\n self.variance = v(self.wave)*self.funit**2\n self.noise = numpy.array([n**0.5 for n in self.variance])\n self.slitpixelwidth = self.slitpixelwidth*self.resolution/resolution\n self.resolution = resolution\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.history = ['Smoothed to constant resolution {}'.format(self.resolution)]\n return\n\n def smoothToSlitPixelWidth(self,width,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant slit width\n :param width: width for smoothing the spectrum\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n# do nothing if requested resolution is higher than current resolution\n if (width > self.slitpixelwidth):\n# convolve a function to smooth spectrum\n window = signal.get_window(method,numpy.round(width))\n neff = numpy.sum(window)/numpy.nanmax(window) # effective number of pixels\n self.flux = signal.convolve(self.flux, window/numpy.sum(window), mode='same')\n self.variance = signal.convolve(self.variance, window/numpy.sum(window), mode='same')/neff\n self.noise = numpy.array([n**0.5 for n in self.variance])\n self.resolution = self.resolution*self.slitpixelwidth/width\n self.slitpixelwidth = width\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.history = ['Smoothed to slit width of {}'.format(self.slitwidth)]\n return\n\n def smoothToSlitWidth(self,width,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant slit width (smooths by pixels)\n :param width: width for smoothing the spectrum\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n pwidth = width/spex_pixel_scale\n self.smoothToSlitPixelWidth(pwidth,**kwargs)\n return\n\n def snr(self):\n '''\n :Purpose: Compute a representative S/N value\n .. note:: Unfinished\n '''\n pass\n return\n\n def surface(self,radius):\n '''\n :Purpose: Convert to surface fluxes given a radius, assuming at absolute fluxes\n .. note:: Unfinished\n '''\n pass\n return\n\n def waveRange(self):\n ii = numpy.where(self.flux.value > 0)\n return [numpy.nanmin(self.wave[ii]), numpy.nanmax(self.wave[ii])]\n\n\n\n\n# FUNCTIONS FOR SPLAT\ndef caldateToDate(d):\n '''\n :Purpose: Convert from numeric date to calendar date, and vice-versa.\n :param d: A numeric date of the format '20050412', or a date in the\n calendar format '2005 Jun 12'\n :Example:\n >>> import splat\n >>> caldate = splat.dateToCaldate('20050612')\n >>> print caldate\n 2005 Jun 12\n >>> date = splat.caldateToDate('2005 June 12')\n >>> print date\n 20050612\n '''\n return d[:4]+str((months.index(d[5:8])+1)/100.)[2:4]+d[-2:]\n\n\ndef checkFile(filename,**kwargs):\n '''\n :Purpose: Checks if a spectrum file exists in the SPLAT's library.\n :param filename: A string containing the spectrum's filename.\n :Example:\n >>> import splat\n >>> spectrum1 = 'spex_prism_1315+2334_110404.fits'\n >>> print splat.checkFile(spectrum1)\n True\n >>> spectrum2 = 'fake_name.fits'\n >>> print splat.checkFile(spectrum2)\n False\n '''\n url = kwargs.get('url',SPLAT_URL)+DATA_FOLDER\n return requests.get(url+filename).status_code == requests.codes.ok\n# flag = checkOnline()\n# if (flag):\n# try:\n# r = requests.get(url+filename)\n# open(os.path.basename(filename), 'wb').write(r.content)\n# open(os.path.basename(filename), 'wb').write(urllib2.urlopen(url+filename).read())\n# except:\n# flag = False\n# return flag\n\n\ndef checkAccess(**kwargs):\n '''\n :Purpose: Checks if user has access to unpublished spectra in SPLAT library.\n :Example:\n >>> import splat\n >>> print splat.checkAccess()\n True\n :Note: Must have the file .splat_access in your home directory with the correct passcode to use.\n '''\n access_file = '.splat_access'\n result = False\n\n try:\n home = os.environ.get('HOME')\n if home == None:\n home = './'\n bcode = requests.get(SPLAT_URL+access_file).content\n lcode = base64.b64encode(open(home+'/'+access_file,'r').read())\n if (bcode in lcode): # changed to partial because of EOL variations\n result = True\n except:\n result = False\n\n if (kwargs.get('report','') != ''):\n if result == True:\n print('You have full access to all SPLAT data')\n else:\n print('You have access only to published data')\n return result\n\n\ndef checkLocal(inputfile):\n '''\n :Purpose: Checks if a file is present locally or within the SPLAT\n code directory\n :Example:\n >>> import splat\n >>> splat.checkLocal('splat.py')\n True # found the code\n >>> splat.checkLocal('parameters.txt')\n False # can't find this file\n >>> splat.checkLocal('SpectralModels/BTSettl08/parameters.txt')\n True # found it\n '''\n if not os.path.exists(inputfile):\n if not os.path.exists(SPLAT_PATH+inputfile):\n return ''\n else:\n return SPLAT_PATH+inputfile\n else:\n return inputfile\n\n\ndef checkOnline(*args):\n '''\n :Purpose: Checks if SPLAT's URL is accessible from your machine--\n that is, checks if you and the host are online. Alternately\n checks if a given filename is present locally or online\n :Example:\n >>> import splat\n >>> splat.checkOnline()\n True # SPLAT's URL was detected.\n >>> splat.checkOnline()\n False # SPLAT's URL was not detected.\n >>> splat.checkOnline('SpectralModels/BTSettl08/parameters.txt')\n '' # Could not find this online file.\n '''\n if (len(args) != 0):\n if 'http://' in args[0]:\n if requests.get(args[0]).status_code == requests.codes.ok:\n \treturn args[0]\n return ''\n else:\n if requests.get(SPLAT_URL+args[0]).status_code == requests.codes.ok:\n return SPLAT_URL+args[0]\n return ''\n else:\n \treturn requests.get(SPLAT_URL).status_code == requests.codes.ok\n\n\n\n\ndef classifyByIndex(sp, *args, **kwargs):\n '''\n :Purpose: Determine the spectral type and uncertainty for a spectrum\n based on indices. Makes use of published index-SpT relations\n from `Reid et al. (2001) `_;\n `Testi et al. (2001) `_;\n `Allers et al. (2007) `_;\n and `Burgasser (2007) `_. Returns 2-element tuple\n containing spectral type (numeric or string) and\n uncertainty.\n\n :param sp: Spectrum class object, which should contain wave, flux and\n noise array elements.\n\n :param set: named set of indices to measure and compute spectral type\n\n - *'allers'*: H2O from `Allers et al. (2007) `_\n - *'burgasser'*: H2O-J, CH4-J, H2O-H, CH4-H, CH4-K from `Burgasser (2007) `_\n - *'reid'*:H2O-A and H2O-B from `Reid et al. (2001) `_\n - *'testi'*: sHJ, sKJ, sH2O_J, sH2O_H1, sH2O_H2, sH2O_K from `Testi et al. (2001) `_\n\n :type set: optional, default = 'burgasser'\n :param string: return spectral type as a string (uses typeToNum)\n :type string: optional, default = False\n :param round: rounds off to nearest 0.5 subtypes\n :type round: optional, default = False\n :param remeasure: force remeasurement of indices\n :type remeasure: optional, default = True\n :param nsamples: number of Monte Carlo samples for error computation\n :type nsamples: optional, default = 100\n :param nloop: number of testing loops to see if spectral type is within a certain range\n :type nloop: optional, default = 5\n\n :Example:\n >>> import splat\n >>> spc = splat.getSpectrum(shortname='0559-1404')[0]\n >>> print splat.classifyByIndex(spc, string=True, set='burgasser', round=True)\n ('T4.5', 0.2562934083414341)\n\n .. note::\n * Need to allow output of individual spectral types from individual indices\n '''\n\n str_flag = kwargs.get('string', True)\n verbose = kwargs.get('verbose', False)\n rnd_flag = kwargs.get('round', False)\n rem_flag = kwargs.get('remeasure', True)\n nsamples = kwargs.get('nsamples', 100)\n nloop = kwargs.get('nloop', 5)\n set = kwargs.get('set','burgasser')\n set = kwargs.get('ref',set)\n kwargs['set'] = set\n allowed_sets = ['aganze','burgasser','reid','testi','allers']\n if (set.lower() not in allowed_sets):\n print('\\nWarning: index classification method {} not present; returning nan\\n\\n'.format(set))\n return numpy.nan, numpy.nan\n\n# measure indices if necessary\n if (len(args) != 0):\n indices = args[0]\n\n# Reid et al. (2001, AJ, 121, 1710)\n elif (set.lower() == 'reid'):\n if (rem_flag or len(args) == 0):\n indices = measureIndexSet(sp, **kwargs)\n sptoffset = 20.\n sptfact = 1.\n coeffs = { \\\n 'H2O-A': {'fitunc': 1.18, 'range': [18,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-32.1, 23.4]}, \\\n 'H2O-B': {'fitunc': 1.02, 'range': [18,28], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-24.9, 20.7]}}\n\n# Testi et al. (2001, ApJ, 522, L147)\n elif (set.lower() == 'testi'):\n if (rem_flag or len(args) == 0):\n indices = measureIndexSet(sp, **kwargs)\n sptoffset = 20.\n sptfact = 10.\n coeffs = { \\\n 'sHJ': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-1.87, 1.67]}, \\\n 'sKJ': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-1.20, 2.01]}, \\\n 'sH2O_J': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [1.54, 0.98]}, \\\n 'sH2O_H1': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [1.27, 0.76]}, \\\n 'sH2O_H2': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [2.11, 0.29]}, \\\n 'sH2O_K': {'fitunc': 0.5, 'range': [20,26], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [2.36, 0.60]}}\n\n# Burgasser (2007, ApJ, 659, 655) calibration\n elif (set.lower() == 'burgasser'):\n if (rem_flag or len(args) == 0):\n indices = measureIndexSet(sp, **kwargs)\n sptoffset = 20.\n sptfact = 1.\n coeffs = { \\\n 'H2O-J': {'fitunc': 0.8, 'range': [20,39], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [1.038e2, -2.156e2, 1.312e2, -3.919e1, 1.949e1]}, \\\n 'H2O-H': {'fitunc': 1.0, 'range': [20,39], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [9.087e-1, -3.221e1, 2.527e1, -1.978e1, 2.098e1]}, \\\n 'CH4-J': {'fitunc': 0.7, 'range': [30,39], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [1.491e2, -3.381e2, 2.424e2, -8.450e1, 2.708e1]}, \\\n 'CH4-H': {'fitunc': 0.3, 'range': [31,39], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [2.084e1, -5.068e1, 4.361e1, -2.291e1, 2.013e1]}, \\\n 'CH4-K': {'fitunc': 1.1, 'range': [20,37], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-1.259e1, -4.734e0, 2.534e1, -2.246e1, 1.885e1]}}\n\n# Allers et al. (2013, ApJ, 657, 511)\n elif (set.lower() == 'allers'):\n if (rem_flag or len(args) == 0):\n kwargs['set'] = 'mclean'\n i1 = measureIndexSet(sp, **kwargs)\n kwargs['set'] = 'slesnick'\n i2 = measureIndexSet(sp, **kwargs)\n kwargs['set'] = 'allers'\n i3 = measureIndexSet(sp, **kwargs)\n if sys.version_info.major == 2:\n indices = dict(i1.items() + i2.items() + i3.items())\n else:\n indices = dict(i1.items() | i2.items() | i3.items())\n sptoffset = 10.\n sptfact = 1.\n coeffs = { \\\n 'H2O': {'fitunc': 0.390, 'range': [15,25], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [24.0476, -104.424, 169.388,-83.5437]}, \\\n 'H2O-1': {'fitunc': 1.097, 'range': [14,25], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [28.5982, -80.7404, 39.3513, 12.1927]}, \\\n 'H2OD': {'fitunc': 0.757, 'range': [20,28], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [-97.230, 229.884, -202.245, 79.4477]}, \\\n 'H2O-2': {'fitunc': 0.501, 'range': [14,22], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n 'coeff': [37.5013, -97.8144, 55.4580, 10.8822]}}\n\n# Aganze et al. 2015 (in preparation)\n# elif (set.lower() == 'aganze'):\n# if (rem_flag or len(args) == 0):\n# kwargs['set'] = 'geballe'\n# i1 = measureIndexSet(sp, **kwargs)\n# kwargs['set'] = 'slesnick'\n# i2 = measureIndexSet(sp, **kwargs)\n# kwargs['set'] = 'allers'\n# i3 = measureIndexSet(sp, **kwargs)\n# kwargs['set'] = 'burgasser'\n# i4 = measureIndexSet(sp, **kwargs)\n# kwargs['set'] = 'reid'\n# i5 = measureIndexSet(sp, **kwargs)\n# kwargs['set'] = 'tokunaga'\n# i6 = measureIndexSet(sp, **kwargs)\n# if sys.version_info.major == 2:\n# indices = dict(i1.items() + i2.items() + i3.items()+ i4.items() + i5.items() + i6.items())\n# else:\n# indices = dict(i1.items() | i2.items() | i3.items()| i4.items() | i5.items() | i6.items())\n# sptoffset = 0.0\n# sptfact = 1.0\n# coeffs = { \\\n# 'H2O': {'fitunc': 0.863, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -361.25130485, 1663.93768276, -2870.50724103, 2221.99873698, -638.03203556]}, \\\n# 'H2O-J': {'fitunc': 0.902, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -146.21144969 , 632.34633568, -1008.79681307, 678.80156994 , -137.92921741]}, \\\n# 'H2O-K': {'fitunc':0.973, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [-21366.79781425, 38630.25299752, -25984.2424891 , 7651.46728497, -805.79462608]}, \\\n# 'K1': {'fitunc':0.878, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ 10.29493194 , -62.71016723 , 115.76162692, -60.72606292 , 15.1905955 ]}, \\\n# 'K2': {'fitunc':0.934, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -44.78083424 , 225.58312733 ,-428.98225919 ,379.28205312 , -114.74469746]}, \\\n# 'H2O-1': {'fitunc':1.035, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -2999.69506898 , 11118.42653046 , -15340.87706264 ,9307.5183138, -2068.63608393]}, \\\n# 'H2O-B': {'fitunc':1.096, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -458.07448646 , 1547.35113353 , -1936.51451632 , 1041.95275566 , -178.50240834]}, \\\n# 'H2O-H': {'fitunc':1.041, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [ -767.21126974 , 2786.26168556 , -3762.93498987, 2211.62680244, -451.54693932]}, \\\n# 'CH4-2.2': {'fitunc': 0.932, 'range': [15,23], 'spt': 0., 'sptunc': 99., 'mask': 1., \\\n# 'coeff': [-331.74150369, 133.08406514 , -0.84614999 , 19.78717161 , 17.18479766]}}\n\n else:\n sys.stderr.write('\\nWarning: '+set.lower()+' SpT-index relation not in classifyByIndex code\\n\\n')\n return numpy.nan, numpy.nan\n\n for index in coeffs.keys():\n vals = numpy.polyval(coeffs[index]['coeff'],numpy.random.normal(indices[index][0],indices[index][1],nsamples))*sptfact\n coeffs[index]['spt'] = numpy.nanmean(vals)+sptoffset\n coeffs[index]['sptunc'] = (numpy.nanstd(vals)**2+coeffs[index]['fitunc']**2)**0.5\n# print(index, coeffs[index]['spt'], coeffs[index]['range'], coeffs[index]['spt'] < coeffs[index]['range'][0], coeffs[index]['spt'] > coeffs[index]['range'][1])\n if (coeffs[index]['spt'] < coeffs[index]['range'][0] or coeffs[index]['spt'] > coeffs[index]['range'][1]):\n coeffs[index]['mask'] = 0.\n else:\n coeffs[index]['mask'] = 1.\n\n for i in numpy.arange(nloop):\n wts = [coeffs[index]['mask']/coeffs[index]['sptunc']**2 for index in coeffs.keys()]\n if (numpy.nansum(wts) == 0.):\n sys.stderr.write('\\nIndices do not fit within allowed ranges\\n\\n')\n return numpy.nan, numpy.nan\n vals = [coeffs[index]['mask']*coeffs[index]['spt']/coeffs[index]['sptunc']**2 \\\n for index in coeffs.keys()]\n sptn = numpy.nansum(vals)/numpy.nansum(wts)\n sptn_e = 1./numpy.nansum(wts)**0.5\n for index in coeffs.keys():\n if (sptn < coeffs[index]['range'][0] or sptn > coeffs[index]['range'][1]):\n coeffs[index]['mask'] = 0\n\n# report individual subtypes\n if verbose:\n for i in coeffs.keys():\n flg = '*'\n if coeffs[i]['mask'] == 0:\n flg = ''\n print('{}{} = {:.3f}+/-{:.3f} = SpT = {}+/-{}'.format(flg,i,indices[i][0],indices[i][1],typeToNum(coeffs[i]['spt']),coeffs[i]['sptunc']))\n\n# round off to nearest 0.5 subtypes if desired\n if (rnd_flag):\n sptn = 0.5*numpy.around(sptn*2.)\n\n# change to string if desired\n if (str_flag):\n spt = typeToNum(sptn,uncertainty=sptn_e)\n else:\n spt = sptn\n\n return spt, sptn_e\n\n\n\ndef classifyByStandard(sp, *args, **kwargs):\n '''\n :Purpose: Determine the spectral type and uncertainty for a\n spectrum by direct comparison to spectral standards.\n Standards span M0-T9 and include the standards listed in\n `Kirkpatrick et al. (2010) `_\n with addition of UGPS 0722-0540 as the T9 standard. Returns the best\n match or an F-test weighted mean and uncertainty. There is an option\n to follow the procedure of `Kirkpatrick et al. (2010)\n `_, fitting only in\n the 0.9-1.4 micron region.\n\n .. :Usage: spt,unc = splat.classifyByStandard(sp, \\**kwargs)\n\n :param sp: spectrum class object, which should contain wave, flux and\n noise array elements.\n :param best: return the best fit standard type only\n :type best: optional, default = True\n :param average: return an chi-square weighted type only\n :type average: optional, default = True\n :param compareto: compare to a single standard (string or number)\n :type compareto: optional, default = False\n :param plot: generate a plot comparing best fit standard to source, can be saved to a file using the ``file`` keyword\n :type plot: optional, default = False\n :param file: output spectrum plot to a file\n :type file: optional, default = ''\n :param method: set to ``'kirkpatrick'`` to follow the `Kirkpatrick et al. (2010) `_ method, fitting only to the 0.9-1.4 micron band\n :type method: optional, default = ''\n :param sptrange: constraint spectral type range to fit, can be strings or numbers\n :type sptrange: optional, default = ['M0','T9']\n :param string: return spectral type as a string\n :type string: optional, default = True\n :param verbose: give lots of feedback\n :type verbose: optional, default = False\n\n :Example:\n >>> import splat\n >>> spc = splat.getSpectrum(shortname='1507-1627')[0]\n >>> print splat.classifyByStandard(spc,string=True,method='kirkpatrick',plot=True)\n ('L4.5', 0.7138959194725174)\n '''\n\n verbose = kwargs.get('verbose',False)\n method = kwargs.get('method','')\n best_flag = kwargs.get('best',True)\n average_flag = kwargs.get('average',not best_flag)\n sptrange = kwargs.get('sptrange',[10,39])\n sptrange = kwargs.get('range',sptrange)\n sptrange = kwargs.get('spt',sptrange)\n if not isinstance(sptrange,list):\n sptrange = [sptrange,sptrange]\n if (isinstance(sptrange[0],str) != False):\n sptrange = [typeToNum(sptrange[0]),typeToNum(sptrange[1])]\n unc_sys = 0.5\n\n\n# if you just want to compare to one standard\n cspt = kwargs.get('compareto',False)\n if (cspt != False):\n if (isinstance(cspt,str) == False):\n cspt = typeToNum(cspt)\n# round off\n cspt = typeToNum(numpy.round(typeToNum(cspt)))\n mkwargs = copy.deepcopy(kwargs)\n mkwargs['compareto'] = False\n mkwargs['sptrange'] =[cspt,cspt]\n return classifyByStandard(sp,**mkwargs)\n\n# read in standards is necessary\n initiateStandards(**kwargs)\n\n# get standards\n# stds = getStandard(sptrange,**kwargs)\n\n# assign subclasses\n if kwargs.get('sd',False):\n stds = splat.SPEX_SD_STDS\n subclass = 'sd'\n elif kwargs.get('esd',False):\n stds = splat.SPEX_ESD_STDS\n subclass = 'esd'\n else:\n stds = splat.SPEX_STDS\n subclass = ''\n\n# select desired spectral range\n spt_allowed = numpy.array([typeToNum(s) for s in stds.keys()])\n spt_sample = spt_allowed[numpy.where(spt_allowed >= sptrange[0])]\n spt_sample = spt_sample[numpy.where(spt_sample <= sptrange[1])]\n\n# determine comparison range based on method\n if (method == 'kirkpatrick'):\n comprng = [0.9,1.4]*u.micron # as prescribed in Kirkpatrick et al. 2010, ApJS,\n else:\n comprng = [0.7,2.45]*u.micron # by default, compare whole spectrum\n\n# which comparison statistic to use\n if numpy.isnan(numpy.median(sp.noise)):\n compstat = 'stddev_norm'\n else:\n compstat = 'chisqr'\n\n# compute fitting statistics\n stat = []\n sspt = []\n\n for t in spt_sample:\n chisq,scale = compareSpectra(sp,stds[typeToNum(t,subclass=subclass)],fit_ranges=[comprng],stat=compstat,novar2=True)\n stat.append(chisq)\n sspt.append(t)\n# if (verbose):\n# print(t, chisq, scale)\n\n# list of sorted standard files and spectral types\n sorted_stdsptnum = [x for (y,x) in sorted(zip(stat,sspt))]\n\n# select either best match or an ftest-weighted average\n# note that these are NUMBERS\n if (best_flag or len(stat) == 1):\n sptn = sorted_stdsptnum[0]\n sptn_e = unc_sys\n else:\n try:\n st = stat.value\n except:\n st = stat\n if numpy.isnan(numpy.median(sp.noise)):\n mean,var = weightedMeanVar(sspt,st)\n else:\n mean,var = weightedMeanVar(sspt,st,method='ftest',dof=sp.dof)\n if (var**0.5 < 1.):\n sptn = numpy.round(mean*2)*0.5\n else:\n sptn = numpy.round(mean)\n sptn_e = (unc_sys**2+var)**0.5\n\n# string or not?\n if (kwargs.get('string', True) == True):\n spt = typeToNum(sptn,uncertainty=sptn_e,subclass=subclass)\n else:\n spt = sptn\n\n# plot spectrum compared to best spectrum\n if (kwargs.get('plot',False) != False):\n# spstd = Spectrum(file=sorted_stdfiles[0])\n# print(typeToNum(sorted_stdsptnum[0],subclass=subclass))\n spstd = getStandard(typeToNum(sorted_stdsptnum[0],subclass=subclass))[0]\n chisq,scale = compareSpectra(sp,spstd,fit_ranges=[comprng],stat=compstat)\n spstd.scale(scale)\n if kwargs.get('colors',False) == False:\n kwargs['colors'] = ['k','r']\n if kwargs.get('labels',False) == False:\n kwargs['labels'] = [sp.name,typeToNum(sorted_stdsptnum[0],subclass=subclass)+' Standard']\n plotSpectrum(sp,spstd,**kwargs)\n\n return spt, sptn_e\n\n\n\n\ndef classifyByTemplate(sp, *args, **kwargs):\n '''\n :Purpose: Determine the spectral type and uncertainty for a\n spectrum by direct comparison to a large set of spectra in\n the library. One can select down the spectra by using the set\n command. Returns the best match or an F-test weighted mean and\n uncertainty. There is an option to follow the procedure of\n `Kirkpatrick et al. (2010) `_,\n fitting only in the 0.9-1.4 micron region.\n\n .. :Usage: result = splat.classifyByTemplate(sp, \\*args, \\**kwargs)\n\n :Output: Returns a dictionary containing the following keys:\n\n - **result**: a tuple containing the spectral type and its uncertainty)\n - **chisquare**: array of nbest chi-square values\n - **name**: array of nbest source names\n - **scale**: array of nbest optimal scale factors\n - **spectra**: array of nbest Spectrum objects\n - **spt**: array of nbest spectral types\n\n :param sp: Spectrum class object, which should contain wave, flux and\n noise array elements.\n :param spt or spt_range: restrict the spectral type range over which templates are chosen\n :type best: optional, default = None\n :param best: return only the best fit template type\n :type best: optional, default = False\n :param nbest: number of best fitting spectra to return\n :type nbest: optional, default = 1\n :param plot: generate a plot comparing best fit standard to source, can be save to a file using the file keyword\n :type plot: optional, default = False\n :param file: output spectrum plot to a file\n :type file: optional, default = ''\n :param method: set to ``'kirkpatrick'`` to follow the `Kirkpatrick et al. (2010) `_ method, fitting only to the 0.9-1.4 micron band\n :type method: optional, default = ''\n :param set: string defining which spectral template set you want to compare to; several options which can be combined:\n\n - *m dwarf*: fit to M dwarfs only\n - *l dwarf*: fit to M dwarfs only\n - *t dwarf*: fit to M dwarfs only\n - *vlm*: fit to M7-T9 dwarfs\n - *optical*: only optical classifications\n - *high sn*: median S/N greater than 100\n - *young*: only young/low surface gravity dwarfs\n - *companion*: only companion dwarfs\n - *subdwarf*: only subdwarfs\n - *single*: only dwarfs not indicated a binaries\n - *spectral binaries*: only dwarfs indicated to be spectral binaries\n - *standard*: only spectral standards (use classifyByStandard instead)\n\n :type set: optional, default = ''\n\n :param string: return spectral type as a string\n :type string: optional, default = True\n :param spt_type: specify which spectral classification type to return; can be 'spex', 'opt', 'nir', or 'lit'\n :type spt_type: optional, default = 'literature'\n :param verbose: give lots of feedback\n :type verbose: optional, default = False\n\n :Example:\n >>> import splat\n >>> spc = splat.getSpectrum(shortname='1507-1627')[0]\n >>> print splat.classifyByTemplate(spc,string=True,set='l dwarf, high sn', spt_type='spex', plot=True)\n ('L4.5', 0.7138959194725174)\n '''\n\n#\n spt_type = kwargs.get('spt_type','literature')\n spt_range = kwargs.get('spt_range',[10.,39.9])\n spt_range = kwargs.get('spt',spt_range)\n nbest = kwargs.get('nbest',1)\n verbose = kwargs.get('verbose',False)\n published = kwargs.get('published','')\n published = kwargs.get('public',published)\n set = kwargs.get('select','')\n# placeholder for a systematic uncertainty term\n unc_sys = 0.\n if (kwargs.get('method','') == 'kirkpatrick'):\n comprng = [0.9,1.4]*u.micron # as prescribed in Kirkpatrick et al. 2010, ApJS,\n else:\n comprng = [0.7,2.45]*u.micron # by default, compare whole spectrum\n\n# canned searches\n# constrain spectral types\n if ('lit' in spt_type.lower()):\n spt_type = 'LIT_TYPE'\n elif ('opt' in spt_type.lower() or 'optical' in set):\n spt_type = 'OPT_TYPE'\n elif ('nir' in spt_type.lower()):\n spt_type = 'NIR_TYPE'\n else:\n spt_type = 'LIT_TYPE'\n\n if ('m dwarf' in set.lower()):\n spt_range = [10,19.9]\n if ('l dwarf' in set.lower()):\n spt_range = [20,29.9]\n if ('t dwarf' in set.lower()):\n spt_range = [30,39.9]\n if ('vlm' in set.lower()):\n spt_range = [numpy.max([17,spt_range[0]]),numpy.min([39.9,spt_range[-1]])]\n\n# constrain S/N\n snr = 0.\n if ('high sn' in set.lower()):\n snr = 100.\n snr = kwargs.get('snr',snr)\n\n# don't compare to same spectrum\n try:\n excludefile = [sp.filename]\n except:\n excludefile = []\n if kwargs.get('excludefile',False) != False:\n e = kwargs.get('excludefile')\n if isinstance(e,list):\n excludefile.extend(e)\n else:\n excludefile.append(e)\n try:\n excludekey = [sp.data_key]\n except:\n excludekey = []\n if kwargs.get('excludekey',False) != False:\n e = kwargs.get('excludekey')\n if isinstance(e,list):\n excludekey.extend(e)\n else:\n excludekey.append(e)\n try:\n excludeshortname = [sp.shortname]\n except:\n excludeshortname = []\n if kwargs.get('excludeshortname',False) != False:\n e = kwargs.get('excludeshortname')\n if isinstance(e,list):\n excludeshortname.extend(e)\n else:\n excludeshortname.append(e)\n# print(excludefile, excludekey, excludeshortname)\n\n# other classes\n giant = ''\n if 'giant' in set.lower():\n giant = True\n if 'not giant' in set.lower():\n giant = False\n companion = ''\n if 'companion' in set.lower():\n companion = True\n if 'not companion' in set.lower():\n companion = False\n young = ''\n if 'young' in set.lower():\n young = True\n if 'not young' in set.lower():\n young = False\n binary = ''\n if 'binary' in set.lower():\n binary = True\n if 'not binary' in set.lower():\n binary = False\n spbinary = ''\n if 'spectral binary' in set.lower():\n spbinary = True\n if 'not spectral binary' in set.lower():\n spbinary = False\n\n# REARRANGE THIS - SEND IN KWARGS WITH OUTPUT, LOGIC SET, AND THE REST ARE UP TO USER?\n\n lib = searchLibrary(excludefile=excludefile,excludekey=excludekey,excludeshortname=excludeshortname, \\\n snr=snr,spt_type=spt_type,spt_range=spt_range,published=published, \\\n giant=giant,companion=companion,young=young,binary=binary,spbinary=spbinary,output='all',logic='and')\n\n# print([x for x in compsp])\n# elif ('companion' in set):\n# lib = searchLibrary(output='all',excludefile=excludefile,snr=snr,spt=spt,companion=True,published=published,giant=False,logic='and')\n# elif ('young' in set):\n# lib = searchLibrary(output='all',excludefile=excludefile,snr=snr,spt=spt,young=True,published=published,logic='and')\n# elif ('subdwarf' in set):\n# lib = searchLibrary(output='all',excludefile=excludefile,snr=snr,spt=spt,subdwarf=True,published=published,logic='and')\n# elif ('single' in set):\n# lib = searchLibrary(output='all',excludefile=excludefile,snr=snr,spt=spt,spbinary=False,published=published,binary=False,giant=False,logic='and')\n# elif ('spectral binaries' in set):\n# lib = searchLibrary(output='all',excludefile=excludefile,snr=snr,spt=spt,spbinary=True,published=published,logic='and')\n# elif (set != ''):\n# lib = searchLibrary(output='all',excludefile=excludefile,published=published,snr=snr,spt=spt)\n# else:\n# lib = searchLibrary(output='all',excludefile=excludefile,published=published,**kwargs)\n\n# lib = lib[:][numpy.where(lib[sptref] != '')]\n\n# first search for the spectra desired - parameters are set by user\n if len(lib) == 0:\n print('\\nNo templates available for comparison\\n\\n')\n return numpy.nan, numpy.nan\n\n files = lib['DATA_FILE']\n dkey = lib['DATA_KEY']\n sspt = [typeToNum(s) for s in lib[spt_type]]\n\n if (verbose):\n print('\\nComparing to {} templates\\n\\n'.format(len(files)))\n if len(files) > 100:\n print('\\nComparing to {} templates\\n\\n'.format(len(files)))\n print('This may take some time!\\n\\n'.format(len(files)))\n\n# do comparison\n stat = []\n scl = []\n for i,d in enumerate(dkey):\n\n# INSERT TRY STATEMNT HERE?\n\n s = Spectrum(idkey=d)\n chisq,scale = compareSpectra(sp,s,fit_ranges=[comprng],stat='chisqr',novar2=True,*kwargs)\n stat.append(chisq)\n scl.append(scale)\n if (verbose):\n print(keySpectrum(d)['NAME'][0], typeToNum(sspt[i]), chisq, scale)\n\n# list of sorted standard files and spectral types\n sorted_dkey = [x for (y,x) in sorted(zip(stat,dkey))]\n sorted_spt = [x for (y,x) in sorted(zip(stat,sspt))]\n sorted_scale = [x for (y,x) in sorted(zip(stat,scl))]\n\n# select either best match or an ftest-weighted average\n if (kwargs.get('best',False) or len(stat) == 1):\n sptn = sorted_spt[0]\n sptn_e = unc_sys\n else:\n mean,var = weightedMeanVar(sspt,stat,method='ftest',dof=sp.dof)\n# allow 1/2 subtypes if uncertainty is less than 1.0\n if (var**0.5 < 1.):\n sptn = numpy.round(mean*2.)*0.5\n else:\n sptn = numpy.round(mean)\n sptn_e = (unc_sys**2+var)**0.5\n\n# plot spectrum compared to best spectrum\n if (kwargs.get('plot',False) != False):\n s = Spectrum(idkey=sorted_dkey[0])\n# chisq,scale = compareSpectra(s,sp,fit_ranges=[comprng],stat='chisqr',novar2=True)\n s.scale(sorted_scale[0])\n plotSpectrum(sp,s,colors=['k','r'],title=sp.name+' vs '+s.name,**kwargs)\n\n# string or not?\n if (kwargs.get('string', True) == True):\n spt = typeToNum(sptn,uncertainty=sptn_e)\n else:\n spt = sptn\n\n# return dictionary of results\n return {'result': (spt,sptn_e), \\\n 'chisquare': sorted(stat)[0:nbest], 'spt': sorted_spt[0:nbest], 'scale': sorted_scale[0:nbest], \\\n 'name': [keySpectrum(d)['NAME'][0] for d in sorted_dkey[0:nbest]], \\\n 'spectra': [Spectrum(idkey=d) for d in sorted_dkey[0:nbest]]}\n\n\n\ndef classifyGravity(sp, *args, **kwargs):\n '''\n :Purpose: Determine the gravity classification of a brown dwarf using the method of `Allers & Liu (2013) `_\n\n :param sp: Spectrum class object, which should contain wave, flux and\n noise array elements. Must be between M6.0 and L7.0.\n :param indices: specify indices set using ``measureIndexSet``.\n :type indices: optional, default = False\n :param spt: spectral type of ``sp``. Must be between M6.0 and L7.0\n :type spt: optional, default = False\n :param plot: plot against spectral standard\n :type plot: optional, default = False\n :param allscores: returns the full result, including the gravity scores from different indices\n :type allscores: optional, default = False\n :param verbose: give lots of feedback\n :type verbose: optional, default = False\n\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='1507-1627')[0]\n >>> print splat.classifyGravity(sp)\n FLD-G\n >>> print splat.classifyGravity(sp, allscores = True)\n {'VO-z': 0.0, 'FeH-z': 1.0, 'gravity_class': 'FLD-G', 'H-cont': 0.0, 'KI-J': 1.0, 'score': 0.5}\n '''\n\n verbose = kwargs.get('verbose',False)\n\n# Chart for determining gravity scores based on gravity sensitive\n# indices as described in the Allers and Liu paper.\n# The key to the overall indices dictionary is each index name.\n# The key to each index dictionary are the spectral types, which\n# contain the limits for each gravity score.\n# To access a value do the following: print grav['FeH-z']['M5'][0]\n# which should return 'nan'\n\n# Note: alternate method is Canty et al. (2013, MNRAS, 435, 2650)\n# H2(K) index: median[2.16-2.18]/median[2.23-2.25]\n\n grav = {\\\n 'FeH-z':{'M5.0':[numpy.nan,numpy.nan],'M6.0':[1.068,1.039],'M7.0':[1.103,1.056],'M8.0':[1.146,1.074],'M9.0': [1.167,1.086],'L0.0': [1.204,1.106],'L1.0':[1.252,1.121],'L2.0':[1.298,1.142],'L3.0': [1.357,1.163],'L4.0': [1.370,1.164],'L5.0': [1.258,1.138],'L6.0': [numpy.nan,numpy.nan],'L7.0': [numpy.nan,numpy.nan]},\\\n 'VO-z': {'M5.0':[numpy.nan,numpy.nan],'M6.0':[numpy.nan,numpy.nan],'M7.0': [numpy.nan,numpy.nan],'M8.0': [numpy.nan,numpy.nan],'M9.0': [numpy.nan,numpy.nan],'L0.0': [1.122,1.256],'L1.0': [1.112,1.251],'L2.0': [1.110,1.232],'L3.0': [1.097,1.187],'L4.0': [1.073,1.118],'L5.0': [numpy.nan,numpy.nan],'L6.0': [numpy.nan,numpy.nan],'L7.0': [numpy.nan,numpy.nan]},\\\n 'KI-J': {'M5.0': [numpy.nan,numpy.nan], 'M6.0': [1.042,1.028], 'M7.0': [1.059,1.036],'M8.0': [1.077,1.046],'M9.0': [1.085,1.053],'L0.0': [1.098,1.061],'L1.0': [1.114,1.067],'L2.0': [1.133,1.073],'L3.0': [1.135,1.075],'L4.0': [1.126,1.072],'L5.0': [1.094,1.061],'L6.0': [numpy.nan,numpy.nan],'L7.0': [numpy.nan,numpy.nan]},\\\n 'H-cont': {'M5.0': [numpy.nan,numpy.nan], 'M6.0': [.988,.994], 'M7.0': [.981,.990],'M8.0': [.963,.984],'M9.0': [.949,.979],'L0.0': [.935,.972],'L1.0': [.914,.968],'L2.0': [.906,.964],'L3.0': [.898,.960],'L4.0': [.885,.954],'L5.0': [.869,.949],'L6.0': [.874,.950],'L7.0': [numpy.nan,numpy.nan]}}\n\n# Calculate Allers indices and their uncertainties\n ind = kwargs.get('indices',False)\n if ind == False:\n ind = measureIndexSet(sp,set='allers')\n\n# Determine the object's NIR spectral type and its uncertainty\n sptn = kwargs.get('spt',False)\n if sptn == False:\n sptn, spt_e = classifyByIndex(sp,string=False,set='allers')\n if numpy.isnan(sptn):\n print('Spectral type could not be determined from indices')\n return numpy.nan\n if isinstance(sptn,str):\n sptn = typeToNum(sptn)\n Spt = typeToNum(numpy.round(sptn))\n\n#Check whether the NIR SpT is within gravity sensitive range values\n if ((sptn < 16.0) or (sptn > 27.0)):\n print('Spectral type '+typeToNum(sptn)+' outside range for gravity classification')\n return numpy.nan\n\n# print spt if verbose\n if verbose:\n print('\\nGravity Classification:\\n\\tSpT = {}'.format(Spt))\n\n#Creates an empty array with dimensions 4x1 to fill in later with 5 gravscore values\n gravscore = {'spt': Spt}\n medgrav = []\n\n# Use the spt to pick the column that contains the\n# values we want to compare our indices with.\n for k in grav.keys():\n val = 0.0\n if k == 'VO-z' or k=='H-cont':\n if numpy.isnan(grav[k][Spt][0]):\n val = numpy.nan\n if ind[k][0] >= grav[k][Spt][0]:\n val = 1.0\n if ind[k][0] >= grav[k][Spt][1]:\n val = 2.0\n if verbose:\n print('\\t{}: {:.3f}+/-{:.3f} => {}'.format(k,ind[k][0], ind[k][1], val))\n if k == 'FeH-z' or k=='KI-J':\n if numpy.isnan(grav[k][Spt][0]):\n val = numpy.nan\n if ind[k][0] <= grav[k][Spt][0]:\n val = 1.0\n if ind[k][0] <= grav[k][Spt][1]:\n val = 2.0\n if verbose:\n print('\\t{}: {:.3f}+/-{:.3f} => {}'.format(k,ind[k][0], ind[k][1], val))\n gravscore[k] = val\n medgrav.append(val)\n\n# determine median score, or mean if even\n if (len(numpy.where(numpy.isnan(medgrav) == False))%2 == 0):\n gravscore['score'] = scipy.stats.nanmean(medgrav)\n else:\n gravscore['score'] = scipy.stats.nanmedian(medgrav)\n\n if gravscore['score'] <= 0.5:\n gravscore['gravity_class'] = 'FLD-G'\n elif gravscore['score'] > 0.5 and gravscore['score'] < 1.5:\n gravscore['gravity_class'] = 'INT-G'\n elif gravscore['score'] >= 1.5:\n gravscore['gravity_class'] = 'VL-G'\n else:\n gravscore['gravity_class'] = 'UNKNOWN'\n\n# print spt if verbose\n if verbose:\n print('\\tGravity Class = {}\\n'.format(gravscore['gravity_class']))\n\n\n# plot spectrum against standard\n if (kwargs.get('plot',False) != False):\n spt,unc = classifyByStandard(sp,compareto=Spt,method='kirkpatrick',**kwargs)\n\n# return gravity class or entire dictionary\n if (kwargs.get('allscores',False) == False):\n return gravscore['gravity_class']\n else:\n return gravscore\n\n\n\ndef compareSpectra(sp1, sp2, *args, **kwargs):\n '''\n :Purpose: Compare two spectra against each other. Returns the stat value as well as\n the scale factor. Minimum possible value is 1.e-9.\n\n :param sp1: Spectrum class object\n :param sp2: Spectrum class object to compare with ``sp1``\n :param weights: set weights for flux values of ``sp1``\n :type weights: optional, default = [1, ..., 1] for len(sp1.wave)\n :param mask: mask any flux value of ``sp1``; has to be an array with length equal as ``sp1`` with only 0 (unmask) or 1 (mask).\n :type mask: optional, default = [0, ..., 0] for len(sp1.wave)\n :param fit_ranges: wavelength range, measured in microns\n :type fit_ranges: optional, default = [0.65,2.45]\n :param mask_ranges: mask any flux value of ``sp1`` by specifying the wavelength range. Must be in microns\n :type mask_ranges: optional, default = []\n :param mask_telluric: masks certain wavelengths to avoid effects from telluric absorption\n :type mask_telluric: optional, default = False\n :param mask_standard: same as ``mask_telluric``\n :type mask_standard: optional, default = False\n :param novar2: compute without using variance of ``sp2``\n :type novar2: optional, default = False\n :param stat: string defining which statistical method to use; available options are:\n\n - *'chisqr'*: compare by computing chi squared value\n - *'stddev'*: compare by computing standard deviation\n - *'stddev_norm'*: compare by computing normalized standard deviation\n - *'absdev'*: compare by computing absolute deviation\n\n :type stat: optional, default = 'chisqr'\n :param plot: plot ``sp1`` with scaled ``sp2``\n :type plot: optional, default = False\n\n :Example:\n >>> import splat\n >>> import numpy\n >>> sp1 = splat.getSpectrum(shortname = '2346-3153')[0]\n >>> sp2 = splat.getSpectrum(shortname = '1421+1827')[0]\n >>> print splat.compareSpectra(sp1, sp2)\n (, 1.1354366238893992e-15)\n >>> m = numpy.zeros(len(sp1.wave))\n >>> m[200:300] = 1\n >>> m_range = [[1.3, 1.5]]\n >>> splat.compareSpectra(sp1, sp2, mask = m, mask_ranges = m_range, novar2 = True)\n (, 1.1694685419610533e-15)\n '''\n weights = kwargs.get('weights',numpy.zeros(len(sp1.wave)))\n mask = kwargs.get('mask',numpy.zeros(len(sp1.wave))) # mask = 1 -> ignore\n fit_ranges = kwargs.get('fit_ranges',[spex_wave_range])\n mask_ranges = kwargs.get('mask_ranges',[])\n mask_standard = kwargs.get('mask_standard',False)\n mask_telluric = kwargs.get('mask_telluric',mask_standard)\n var_flag = kwargs.get('novar2',True)\n stat = kwargs.get('stat','chisqr')\n minreturn = 1.e-9\n if ~isinstance(fit_ranges[0],astropy.units.quantity.Quantity):\n fit_ranges*=u.micron\n\n if (mask_standard):\n mask_telluric == True\n\n# create interpolation function for second spectrum\n f = interp1d(sp2.wave,sp2.flux,bounds_error=False,fill_value=0.)\n if var_flag:\n v = interp1d(sp2.wave,sp2.variance*numpy.nan,bounds_error=False,fill_value=numpy.nan)\n else:\n v = interp1d(sp2.wave,sp2.variance,bounds_error=False,fill_value=numpy.nan)\n\n# total variance - funny form to cover for nans\n vtot = numpy.nanmax([sp1.variance.value,sp1.variance.value+v(sp1.wave.value)],axis=0)\n # vtot = sp1.variance\n\n# Mask certain wavelengths\n# telluric absorption\n if (mask_telluric):\n mask_ranges.append([0.,0.65]) # meant to clear out short wavelengths\n mask_ranges.append([1.35,1.42])\n mask_ranges.append([1.8,1.92])\n mask_ranges.append([2.45,99.]) # meant to clear out long wavelengths\n\n if (mask_standard):\n mask_ranges.append([0.,0.8]) # standard short cut\n mask_ranges.append([2.35,99.]) # standard long cut\n\n if ~isinstance(fit_ranges[0],astropy.units.quantity.Quantity):\n mask_ranges*=u.micron\n\n for ranges in mask_ranges:\n mask[numpy.where(((sp1.wave >= ranges[0]) & (sp1.wave <= ranges[1])))] = 1\n\n# set the weights\n for ranges in fit_ranges:\n weights[numpy.where(((sp1.wave >= ranges[0]) & (sp1.wave <= ranges[1])))] = 1\n\n# mask flux < 0\n mask[numpy.where(numpy.logical_or(sp1.flux < 0,f(sp1.wave) < 0))] = 1\n\n weights = weights*(1.-mask)\n\n# comparison statistics\n\n# switch to standard deviation if no uncertainty\n if numpy.isnan(numpy.nanmax(vtot)):\n stat = 'stddev'\n\n# chi^2\n if (stat == 'chisqr'):\n# compute scale factor\n scale = numpy.nansum(weights*sp1.flux.value*f(sp1.wave)/vtot)/ \\\n numpy.nansum(weights*f(sp1.wave)*f(sp1.wave)/vtot)\n# correct variance\n vtot = numpy.nanmax([sp1.variance.value,sp1.variance.value+v(sp1.wave)*scale**2],axis=0)\n stat = numpy.nansum(weights*(sp1.flux.value-f(sp1.wave)*scale)**2/vtot)\n unit = sp1.funit/sp1.funit\n\n# normalized standard deviation\n elif (stat == 'stddev_norm'):\n# compute scale factor\n scale = numpy.nansum(weights*sp1.flux.value)/ \\\n numpy.nansum(weights*f(sp1.wave))\n# correct variance\n stat = numpy.nansum(weights*(sp1.flux.value-f(sp1.wave)*scale)**2)/ \\\n numpy.median(sp1.flux.value)**2\n unit = sp1.funit/sp1.funit\n\n# standard deviation\n elif (stat == 'stddev'):\n# compute scale factor\n scale = numpy.nansum(weights*sp1.flux.value*f(sp1.wave))/ \\\n numpy.nansum(weights*f(sp1.wave)*f(sp1.wave))\n# correct variance\n stat = numpy.nansum(weights*(sp1.flux.value-f(sp1.wave)*scale)**2)\n unit = sp1.funit**2\n\n# absolute deviation\n elif (stat == 'absdev'):\n# compute scale factor\n scale = numpy.nansum(weights*sp1.flux.value)/ \\\n numpy.nansum(weights*f(sp1.wave))\n# correct variance\n stat = numpy.nansum(weights*abs(sp1.flux.value-f(sp1.wave)*scale))\n unit = sp1.funit\n\n# error\n else:\n print('Error: statistic {} for compareSpectra not available'.format(stat))\n return numpy.nan, numpy.nan\n\n# plot spectrum compared to best spectrum\n if (kwargs.get('plot',False) != False):\n spcomp = sp2.copy()\n spcomp.scale(scale)\n kwargs['colors'] = kwargs.get('colors',['k','r','b'])\n kwargs['title'] = kwargs.get('title',sp1.name+' vs '+sp2.name)\n plotSpectrum(sp1,spcomp,sp1-spcomp,**kwargs)\n\n return numpy.nanmax([stat,minreturn])*unit, scale\n\n\ndef coordinateToDesignation(c):\n '''\n :Purpose: Converts right ascension and declination into a designation string\n :param c: RA and Dec to be converted; can be a SkyCoord object with units of degrees,\n a list with RA and Dec in degrees, or a string with RA measured in hour\n angles and Dec in degrees\n :Example:\n >>> import splat\n >>> from astropy.coordinates import SkyCoord\n >>> c = SkyCoord(238.86, 9.90, unit=\"deg\")\n >>> print splat.coordinateToDesignation(c)\n J15552640+0954000\n >>> print splat.coordinateToDesignation([238.86, 9.90])\n J15552640+0954000\n >>> print splat.coordinateToDesignation('15:55:26.4 +09:54:00.0')\n J15552640+0954000\n '''\n# input is ICRS\n if isinstance(c,SkyCoord):\n cc = c\n else:\n cc = properCoordinates(c)\n# input is [RA,Dec] pair in degrees\n if sys.version_info.major == 2:\n return string.replace('J{0}{1}'.format(cc.ra.to_string(unit=u.hour, sep='', precision=2, pad=True), \\\n cc.dec.to_string(unit=u.degree, sep='', precision=1, alwayssign=True, pad=True)),'.','')\n else:\n return replace('J{0}{1}'.format(cc.ra.to_string(unit=u.hour, sep='', precision=2, pad=True), \\\n cc.dec.to_string(unit=u.degree, sep='', precision=1, alwayssign=True, pad=True)),'.','')\n\n\ndef dateToCaldate(d):\n '''\n :Purpose: Converts numeric date to calendar date\n :param d: string in the form 'YYYYMMDD'\n :Example:\n >>> import splat\n >>> print splat.dateToCaldate('19940523')\n 1994 May 23\n '''\n return d[:4]+' '+months[int(d[5:6])-1]+' '+d[-2:]\n\n\ndef designationToCoordinate(value, **kwargs):\n '''\n :Purpose: Convert a designation into a RA, Dec tuple or ICRS\n :param value: string with RA measured in hour angles and Dec in degrees\n :param icrs: returns coordinate in ICRS frame if ``True``\n :type icrs: optional, defualt = True\n :Example:\n >>> import splat\n >>> print splat.designationToCoordinate('1555.2640+0954.000')\n \n '''\n icrsflag = kwargs.get('icrs',True)\n\n a = re.sub('[j.:hms]','',value.lower())\n fact = 1.\n spl = a.split('+')\n if len(spl) == 1:\n spl = a.split('-')\n fact = -1.\n ra = 15.*float(spl[0][0:2])\n if (len(spl[0]) > 2):\n ra+=15.*float(spl[0][2:4])/60.\n if (len(spl[0]) > 4):\n ra+=15.*float(spl[0][4:6])/3600.\n if (len(spl[0]) > 6):\n ra+=15.*float(spl[0][6:8])/360000.\n dec = float(spl[1][0:2])\n if (len(spl[0]) > 2):\n dec+=float(spl[1][2:4])/60.\n if (len(spl[0]) > 4):\n dec+=float(spl[1][4:6])/3600.\n if (len(spl[1]) > 6):\n dec+=float(spl[1][6:8])/360000.\n dec = dec*fact\n if icrsflag:\n return SkyCoord(ra=ra*u.degree, dec=dec*u.degree, frame='icrs')\n else:\n return [ra,dec]\n\n\ndef designationToShortName(value):\n '''\n :Purpose: Produce a shortened version of designation\n :param value: string with RA measured in hour angles and Dec in degrees\n :Example:\n >>> import splat\n >>> print splat.designationToShortName('1555.2640+0954.000')\n J1555+0954\n '''\n if isinstance(value,str):\n a = re.sub('[j.:hms]','',value.lower())\n mrk = '+'\n spl = a.split(mrk)\n if len(spl) == 1:\n mrk = '-'\n spl = a.split(mrk)\n if len(spl) == 2:\n return 'J'+spl[0][0:4]+mrk+spl[1][0:4]\n else:\n return value\n else:\n raise ValueError('\\nMust provide a string value for designation\\n\\n')\n\n\n\n\n\n# DEPRECATED\n#def filenameToNameDate(filename):\n# '''Extract from a SPLAT filename the source name and observation date'''\n# ind = filename.rfind('.')\n# base = filename[:ind]\n# spl = base.split('_')\n# if (len(spl) < 2):\n# return '', ''\n# else:\n# name = spl[-2]\n# d = spl[-1]\n# try:\n# float(d)\n# date = '20'+d\n# except ValueError:\n# print(filename+' does not contain a date')\n# date = ''\n#\n# return name, date\n#\n\n\ndef filterMag(sp,f,*args,**kwargs):\n '''\n :Purpose: Determine the photometric magnitude of a source based on the\n spectrum. Spectra are convolved with the filter specified by\n the ``filter`` input. By default this filter is also\n convolved with a model of Vega to extract Vega magnitudes,\n but the user can also specify AB magnitudes, photon flux or\n energy flux.\n\n .. :Usage: mag, unc = splat.filterMag(sp, 'filter name',\\*args, \\**kwargs) (Unneeded)\n\n :param sp: Spectrum class object, which should contain wave, flux and\n noise array elements.\n :param filter: name of filter\n \n :param info: give the filter names available\n :type info: optional, default = False\n :param custom: specify to a 2 x N vector array specifying the wavelengths and transmissions for a custom filter\n :type custom: optional, default = False\n :param ab: compute AB magnitudes\n :type ab: optional, default = False\n :param vega: compute Vega magnitudes\n :type vega: optional, default = True\n :param energy: compute energy flux\n :type energy: optional, default = False\n :param photon: compute photon flux\n :type photon: optional, default = False\n :param filterFolder: folder containing the filter transmission files\n :type filterFolder: optional, default = ''\n :param vegaFile: name of file containing Vega flux file, must be within ``filterFolder``\n :type vegaFile: optional, default = ''\n :param nsamples: number of samples to use in Monte Carlo error estimation\n :type nsamples: optional, default = 100\n\n :Example:\n >>> import splat\n >>> spc = splat.getSpectrum(shortname='1507-1627')[0]\n >>> spc.fluxCalibrate('2MASS J',14.5)\n >>> print splat.filterMag(spc,'MKO J')\n (14.345894376898123, 0.027596454828421831)\n '''\n# keyword parameters\n filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER)\n if not os.path.exists(filterFolder):\n filterFolder = SPLAT_URL+FILTERFOLDER\n vegaFile = kwargs.get('vegaFile','vega_kurucz.txt')\n info = kwargs.get('info',False)\n custom = kwargs.get('custom',False)\n vega = kwargs.get('vega',True)\n ab = kwargs.get('ab',False)\n photons = kwargs.get('photons',False)\n energy = kwargs.get('energy',False)\n nsamples = kwargs.get('nsamples',100)\n\n\n# check that requested filter is in list\n f = f.replace(' ','_')\n f.upper()\n if (f not in FILTERS.keys() and isinstance(custom,bool)):\n print('Filter '+f+' not included in filterMag')\n info = True\n\n# print out what's available\n if (info):\n print('Filter names:')\n for x in FILTERS.keys():\n print(x+': '+FILTERS[x]['description'])\n return numpy.nan, numpy.nan\n\n# Read in filter\n if isinstance(custom,bool):\n fwave,ftrans = numpy.genfromtxt(filterFolder+FILTERS[f]['file'], comments='#', unpack=True, \\\n missing_values = ('NaN','nan'), filling_values = (numpy.nan))\n else:\n fwave,ftrans = custom[0],custom[1]\n fwave = fwave[~numpy.isnan(ftrans)]*u.micron # temporary fix\n ftrans = ftrans[~numpy.isnan(ftrans)]\n\n# interpolate spectrum onto filter wavelength function\n wgood = numpy.where(~numpy.isnan(sp.noise))\n if len(sp.wave[wgood]) > 0:\n d = interp1d(sp.wave[wgood],sp.flux[wgood],bounds_error=False,fill_value=0.)\n n = interp1d(sp.wave[wgood],sp.noise[wgood],bounds_error=False,fill_value=numpy.nan)\n# catch for models\n else:\n print(f+': no good points')\n d = interp1d(sp.wave,sp.flux,bounds_error=False,fill_value=0.)\n n = interp1d(sp.wave,sp.flux*1.e-9,bounds_error=False,fill_value=numpy.nan)\n\n result = []\n if (vega):\n# Read in Vega spectrum\n vwave,vflux = numpy.genfromtxt(filterFolder+vegaFile, comments='#', unpack=True, \\\n missing_values = ('NaN','nan'), filling_values = (numpy.nan))\n vwave = vwave[~numpy.isnan(vflux)]*u.micron\n vflux = vflux[~numpy.isnan(vflux)]*(u.erg/(u.cm**2 * u.s * u.micron))\n vflux.to(sp.funit,equivalencies=u.spectral_density(vwave))\n# interpolate Vega onto filter wavelength function\n v = interp1d(vwave,vflux,bounds_error=False,fill_value=0.)\n for i in numpy.arange(nsamples):\n# result.append(-2.5*numpy.log10(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.funit,fwave)/trapz(ftrans*v(fwave)*sp.funit,fwave)))\n result.append(-2.5*numpy.log10(trapz(ftrans*(d(fwave)+numpy.random.normal(0,1.)*n(fwave))*sp.funit,fwave)/trapz(ftrans*v(fwave)*sp.funit,fwave)))\n\n if (energy or photons):\n for i in numpy.arange(nsamples):\n# result.append(trapz(ftrans*numpy.random.normal(d(fwave),n(fwave))*sp.funit,fwave))\n result.append(trapz(ftrans*(d(fwave)+numpy.random.normal(0,1.)*n(fwave))*sp.funit,fwave))\n if (photons):\n convert = const.h.to('erg s')*const.c.to('micron/s')\n result = result/convert.value\n if (ab):\n fnu = fwave.to('Hz',equivalencies=u.spectral())\n fconst = 3631*u.jansky\n fconst = fconst.to(sp.fnu_unit,equivalencies=u.spectral())\n d = interp1d(sp.nu,sp.fnu,bounds_error=False,fill_value=0.)\n n = interp1d(sp.nu,sp.noise,bounds_error=False,fill_value=0.)\n b = trapz((ftrans/fnu)/fconst,fnu)\n for i in numpy.arange(nsamples):\n a = trapz(ftrans*(d(fnu)+numpy.random.normal(0,1)*n(fnu))*sp.fnu_unit/fnu,fnu)\n result.append(-2.5*numpy.log10(a/b))\n\n val = numpy.nanmean(result)\n err = numpy.nanstd(result)\n if len(sp.wave[wgood]) == 0:\n err = 0.\n return val,err\n\n\ndef filterProperties(f,**kwargs):\n '''\n :Purpose: Returns a dictionary containing key factors about a filter profile.\n .. :Usage: info = splat.filterProperties('filter name',**kwargs)\n\n :param 'filter name': name of filter, must be one of the specifed filters given by splat.FILTERS\n :param verbose: print out information about filter to screen\n :type custom: optional, default = False\n '''\n\n filt = f.replace(' ','_')\n filterFolder = kwargs.get('filterFolder',SPLAT_PATH+FILTER_FOLDER)\n if not os.path.exists(filterFolder):\n filterFolder = SPLAT_URL+FILTERFOLDER\n\n if (filt not in FILTERS.keys()):\n print('Filter '+f+' not among the available filters:')\n for k in FILTERS.keys():\n print(' '+k.replace('_',' ')+': '+FILTERS[k]['description'])\n return None\n else:\n report = {}\n report['name'] = f\n report['description'] = FILTERS[filt]['description']\n report['zeropoint'] = FILTERS[filt]['zeropoint']\n fwave,ftrans = numpy.genfromtxt(filterFolder+FILTERS[filt]['file'], comments='#', unpack=True, \\\n missing_values = ('NaN','nan'), filling_values = (numpy.nan))\n report['lambda_mean'] = trapz(fwave*ftrans,fwave)/trapz(ftrans,fwave)\n report['lambda_pivot'] = numpy.sqrt(trapz(fwave*ftrans,fwave)/trapz(ftrans/fwave,fwave))\n fw = fwave[numpy.where(ftrans > 0.5*ftrans)]\n report['lambda_central'] = 0.5*(numpy.max(fw)+numpy.min(fw))\n report['lambda_fwhm'] = numpy.max(fw)-numpy.min(fw)\n fw = fwave[numpy.where(ftrans > 0.01*ftrans)]\n report['lambda_min'] = numpy.min(fw)\n report['lambda_max'] = numpy.max(fw)\n if kwargs.get('verbose',False):\n print('\\nFilter '+f+': '+report['description'])\n print('Filter zeropoint = {} Jy'.format(report['zeropoint']))\n# print('Filter mid-points: mean = {:.3f} micron, pivot = {:.3f} micron, central = {:.3f} micron'.format(report['lambda_mean'],report['lambda_pivot'],report['lambda_central'],))\n print('Filter mid-point: = {:.3f} micron'.format(report['lambda_mean'],report['lambda_pivot'],report['lambda_central'],))\n print('Filter FWHM = {:.3f} micron'.format(report['lambda_fwhm']))\n print('Filter range = {:.3f} to {:.3f} micron\\n'.format(report['lambda_min'],report['lambda_max']))\n return report\n\n\ndef getSpectrum(*args, **kwargs):\n '''\n :Purpose: Gets a spectrum from the SPLAT library using various selection criteria.\n .. :Usage: [sp] = splat.getSpectrum({search commands},**kwargs)\n\n :param sp: array of Spectrum class objects, each of which should contain wave, flux and\n noise array elements.\n :param optional name: search by source name (e.g., ``name = 'Gliese 570D'``)\n :param optional shortname: search be short name (e.g. ``shortname = 'J1457-2124'``)\n :param optional designation: search by full designation (e.g., ``designation = 'J11040127+1959217'``)\n :param optional coordinate: search around a coordinate by a radius specified by radius keyword (e.g., ``coordinate = [180.,+30.], radius = 10.``)\n :param radius: search radius in arcseconds for coordinate search\n :type radius: optional, default = 10\n :param optional spt: search by SpeX spectral type; single value is exact, two-element array gives range (e.g., ``spt = 'M7'`` or ``spt = [24,39]``)\n :param optional spex_spt: same as ``spt``\n :param optional opt_spt: same as ``spt`` for literature optical spectral types\n :param optional nir_spt: same as ``spt`` for literature NIR spectral types\n :param optional jmag, hmag, kmag: select based on faint limit or range of J, H or Ks magnitudes (e.g., ``jmag = [12,15]``)\n :param optional snr: search on minimum or range of S/N ratios (e.g., ``snr = 30.`` or ``snr = [50.,100.]``)\n :param optional subdwarf, young, binary, spbinary, red, blue, giant, wd, standard: classes to search on (e.g., ``young = True``)\n :param logic: search logic, can be ``and`` or ``or``\n :type logic: optional, default = 'and'\n :param combine: same as logic\n :type combine: optional, default = 'and'\n :param optional date: search by date (e.g., ``date = '20040322'``) or range of dates (e.g., ``date=[20040301,20040330]``)\n :param optional reference: search by list of references (bibcodes) (e.g., ``reference = '2011ApJS..197...19K'``)\n :param sort: sort results based on Right Ascension\n :type sort: optional, default = True\n :param list: if True, return just a list of the data files (can be done with searchLibrary as well)\n :type list: optional, default = False\n :param lucky: if True, return one randomly selected spectrum from the selected sample\n :type lucky: optional, default = False\n\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='1507-1627')[0]\n Retrieving 1 file\n >>> sparr = splat.getSpectrum(spt='M7')\n Retrieving 120 files\n >>> sparr = splat.getSpectrum(spt='T5',young=True)\n No files match search criteria\n '''\n\n result = []\n kwargs['output'] = 'all'\n search = searchLibrary(*args, **kwargs)\n\n if len(search) > 0:\n files = []\n for i,x in enumerate(search['DATA_KEY']):\n files.append(str(search['DATA_KEY'][i])+'_'+str(search['SOURCE_KEY'][i])+'.fits')\n\n# return just the filenames\n if (kwargs.get('list',False) != False):\n return files\n\n if (len(files) == 1):\n print('\\nRetrieving 1 file\\n')\n result.append(Spectrum(files[0],header=search[0]))\n else:\n if (kwargs.get('lucky',False) == True):\n print('\\nRetrieving 1 lucky file\\n')\n ind = random.choice(range(len(files)))\n result.append(Spectrum(files[ind],header=search[ind]))\n else:\n print('\\nRetrieving {} files\\n'.format(len(files)))\n for i,x in enumerate(files):\n result.append(Spectrum(x,header=search[i:i+1]))\n\n else:\n if checkAccess() == False:\n sys.stderr.write('\\nNo published files match search criteria\\n\\n')\n else:\n sys.stderr.write('\\nNo files match search criteria\\n\\n')\n\n return result\n\n\n\ndef getStandard(spt, **kwargs):\n '''\n :Purpose: Gets one of the pre-defined spectral standards from the SPLAT library.\n NOTE: THIS PROGRAM MAY BE OBSOLETE\n\n .. :Usage: [sp] = splat.getStandard(spt,**kwargs)\n\n :param sp: array of Spectrum class objects\n :param spt: spectral type of standard desired ('M7')\n\n :param optional sd: get subdwarf standard\n :type sd: optional, default = False\n :param optional esd: get extreme subdwarf standard\n :type esd: optional, default = False\n\n :Example:\n >>> import splat\n >>> sp = splat.getStandard('M7')[0]\n Spectrum of VB 8\n >>> sparr = splat.getStandard('T5',esd=True)\n Type esdT5.0 is not in esd standards: try one of the following:\n ['esdM5.0', 'esdM7.0', 'esdM8.5']\n '''\n\n# if not isinstance(sptrange,list):\n# sptrange = [sptrange,sptrange]\n\n# make sure standards are read in\n initiateStandards(**kwargs)\n\n# get standards\n if kwargs.get('sd',False):\n stds = splat.SPEX_SD_STDS\n subclass = 'sd'\n elif kwargs.get('esd',False):\n stds = splat.SPEX_ESD_STDS\n subclass = 'esd'\n else:\n stds = splat.SPEX_STDS\n subclass = ''\n\n# set up subtype to use, convert to number then back to string\n if (isinstance(spt,str) != False):\n spt = typeToNum(spt)\n spt = typeToNum(spt,subclass=subclass)\n\n# select among defined spectra - just getting closest match\n# spt_allowed = numpy.array([typeToNum(s) for s in stds.keys()])\n# spt_sample = spt_allowed[numpy.where(spt_allowed >= sptrange[0])]\n# spt_sample = spt_sample[numpy.where(spt_sample <= sptrange[1])]\n\n# nothing there, return\n if spt not in stds.keys():\n print('Type {} is not in {} standards: try one of the following:'.format(spt,subclass))\n print(sorted(stds.keys()))\n return []\n else:\n return [stds[spt]]\n\n# build up file or Spectrum list\n# result = {}\n# for t in spt_sample:\n# result[typeToNum(t,subclass=subclass)] = stds[typeToNum(t,subclass=subclass)]\n#\n# return result\n\n\ndef initiateStandards(**kwargs):\n '''\n :Purpose: Initiates the spectral standards (dwarf, subdwarf or extreme subdwarf) in the SpeX library.\n .. :Usage: splat.initateStandards(**kwargs)\n\n :param optional sd: get subdwarf standard\n :type sd: optional, default = False\n :param optional esd: get extreme subdwarf standard\n :type esd: optional, default = False\n\n :Example:\n >>> import splat\n >>> splat.initiateStandards()\n >>> splat.SPEX_SDS['M5']\n '''\n\n# choose what kind of standards desired - d, sd, esd\n# and read in standards into dictionary if they haven't been already\n if kwargs.get('sd',False):\n if len(splat.SPEX_SD_STDS) == 0:\n for t in splat.SPEX_SD_STDFILES.keys():\n splat.SPEX_SD_STDS[t] = Spectrum(file=splat.SPEX_SD_STDFILES[t])\n elif kwargs.get('esd',False):\n if len(splat.SPEX_ESD_STDS) == 0:\n for t in splat.SPEX_ESD_STDFILES.keys():\n splat.SPEX_ESD_STDS[t] = Spectrum(file=splat.SPEX_ESD_STDFILES[t])\n else:\n if len(splat.SPEX_STDS) == 0:\n for t in splat.SPEX_STDFILES.keys():\n splat.SPEX_STDS[t] = Spectrum(file=splat.SPEX_STDFILES[t])\n\n return\n\n\n# simple number checker\ndef isNumber(s):\n '''\n :Purpose: Checks if something is a number.\n :param s: object to be checked\n :Example:\n >>> import splat\n >>> print splat.isNumber(3)\n True\n >>> print splat.isNumber('hello')\n False\n '''\n try:\n t = float(s)\n return (True and ~numpy.isnan(t))\n except ValueError:\n return False\n\n\n\ndef estimateDistance(sp, **kwargs):\n '''\n :Purpose: Takes the apparent magnitude and either takes or determines the absolute\n magnitude, then uses the magnitude/distance relation to estimate the\n distance to the object in parsecs. Returns estimated distance and\n uncertainty in parsecs\n\n :param sp: Spectrum class object, which should be flux calibrated to its empirical apparent magnitude\n :param mag: apparent magnitude of ``sp``\n :type mag: optional, default = False\n :param mag_unc: uncertainty of the apparent magnitude\n :type mag_unc: optional, default = 0\n :param absmag: absolute magnitude of ``sp``\n :type absmag: optional, default = False\n :param absmag_unc: uncertainty of the absolute magnitude\n :type absmag_unc: optional, default = 0\n :param spt: spectral type of ``sp``\n :type spt: optional, default = False\n :param spt_e: uncertainty of the spectral type\n :type spt_e: optional, default = 0\n :param nsamples: number of samples to use in Monte Carlo error estimation\n :type nsamples: optional, default = 100\n :param filter: Name of filter, must be one of the following:\n\n - '2MASS J', '2MASS H', '2MASS Ks'\n - 'MKO J', 'MKO H', 'MKO K', MKO Kp', 'MKO Ks'\n - 'NICMOS F090M', 'NICMOS F095N', 'NICMOS F097N', 'NICMOS F108N'\n - 'NICMOS F110M', 'NICMOS F110W', 'NICMOS F113N', 'NICMOS F140W'\n - 'NICMOS F145M', 'NICMOS F160W', 'NICMOS F164N', 'NICMOS F165M'\n - 'NICMOS F166N', 'NICMOS F170M', 'NICMOS F187N', 'NICMOS F190N'\n - 'NIRC2 J', 'NIRC2 H', 'NIRC2 Kp', 'NIRC2 Ks'\n - 'WIRC J', 'WIRC H', 'WIRC K', 'WIRC CH4S', 'WIRC CH4L'\n - 'WIRC CO', 'WIRC PaBeta', 'WIRC BrGamma', 'WIRC Fe2'\n - 'WISE W1', 'WISE W2'\n\n :type filter: optional, default = False\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='1555+0954')[0]\n >>> print splat.estimateDistance(sp)\n Please specify the filter used to determine the apparent magnitude\n (nan, nan)\n >>> print splat.estimateDistance(sp, mag = 12.521, mag_unc = 0.022, absmag = 7.24, absmag_unc = 0.50, spt = 'M3')\n (116.36999172188771, 33.124820555524224)\n '''\n\n mag = kwargs.get('mag', False)\n mag_unc = kwargs.get('mag_unc', 0.)\n absmag = kwargs.get('absmag', False)\n absmag_unc = kwargs.get('absmag_unc', 0.)\n spt = kwargs.get('spt', False)\n spt_unc = kwargs.get('spt_e', 0.)\n nsamples = kwargs.get('nsamples', 100)\n filt = kwargs.get('filter', False)\n\n# if no apparent magnitude then calculate from spectrum\n if (mag == False):\n if (filt == False):\n sys.stderr.write('\\nPlease specify the filter used to determine the apparent magnitude\\n')\n return numpy.nan, numpy.nan\n mag, mag_unc = filterMag(sp,filt)\n\n# if no spt then calculate from spectrum\n if spt == False:\n spt, spt_unc = classifyByIndex(sp)\n\n\n# if no absolute magnitude then estimate from spectral type\n if absmag == False:\n if filt == False:\n sys.stderr.write('\\nPlease specify the filter used to determine the absolute magnitude\\n')\n return numpy.nan, numpy.nan\n absmag, absmag_unc = typeToMag(spt,filt,unc=spt_unc)\n print(absmag, absmag_unc)\n\n# create Monte Carlo sets\n if mag_unc > 0.:\n mags = numpy.random.normal(mag, mag_unc, nsamples)\n else:\n mags = nsamples*[mag]\n\n if absmag_unc > 0.:\n absmags = numpy.random.normal(absmag, absmag_unc, nsamples)\n else:\n absmags = nsamples*[absmag]\n\n# calculate\n distances = 10.**(numpy.subtract(mags,absmags)/5. + 1.)\n d = numpy.mean(distances)\n unc = numpy.std(distances)\n\n return d, unc\n\n\ndef measureEW(sp, *args, **kwargs):\n '''\n :Purpose: Measures equivalent widths (EWs) of specified lines\n :param sp: Spectrum class object, which should contain wave, flux and noise array elements\n :param args: wavelength arrays. Needs at least two arrays to measure line and continuum regions.\n :type nsamples: optional, default = 100\n :param nonoise:\n :type nonoise: optional, default = False\n :param line:\n :type nonoise: optional, default = ''\n\n .. not too sure about how this one works; will come back later.\n '''\n\n# presets\n nsamples = kwargs.get('nsamples',100)\n noiseFlag = kwargs.get('nonoise',False)\n\n# predefined lines\n specline = kwargs.get('line','').replace(' ','').lower()\n if 'nai' in specline:\n if '2.2' in specline:\n wave_line = [2.2020, 2.2120]\n wave_cont = [2.1965, 2.2125, 2.2175]\n elif 'cai' in specline:\n if '2.2' in specline:\n wave_line = [2.2580, 2.2690]\n wave_cont = [2.2510, 2.2580, 2.2705, 2.2760]\n else:\n if len(args) < 2:\n print('measureEW needs at least two wavelength arrays to measure line and continuum regions')\n return numpy.nan, numpy.nan\n else:\n wave_line = args[0]\n wave_cont = args[1]\n\n\n# create interpolation routines\n w = numpy.where(numpy.isnan(sp.flux) == False)\n f = interp1d(sp.wave.value[w],sp.flux.value[w],bounds_error=False,fill_value=0.)\n w = numpy.where(numpy.isnan(sp.noise) == False)\n\n# note that units are stripped out\n if (numpy.size(w) != 0):\n n = interp1d(sp.wave.value[w],sp.noise.value[w],bounds_error=False,fill_value=numpy.nan)\n noiseFlag = False or noiseFlag\n else:\n n = interp1d(sp.wave.value[:],sp.noise.value[:],bounds_error=False,fill_value=numpy.nan)\n noiseFlag = True or noiseFlag\n\n wLine = (numpy.arange(0,nsamples+1.0)/nsamples)* \\\n (numpy.nanmax(wave_line)-numpy.nanmin(wave_line))+numpy.nanmin(wave_line)\n fLine = f(wLine)\n nLine = n(wLine)\n fCont = f(wave_cont)\n nCont = n(wave_cont)\n\n if noiseFlag == True:\n#linear fit to continuum\n pCont = numpy.poly1d(numpy.polyfit(wave_cont,fCont,1))\n fContFit = pCont(wLine)\n ew = trapz((numpy.ones(len(fLine))-(fLine/fContFit)), wLine)*1e4\n return ew*u.angstrom, numpy.nan\n#monte carlo\n else:\n ew=[]\n for i in range(nsamples):\n#generate simulated fluxes\n# fContVar = fCont+numpy.random.normal(0.,1.)*nCont\n# fLineVar = fLine+numpy.random.normal(0.,1.)*nLine\n fContVar = numpy.random.normal(fCont,nCont)\n fLineVar = numpy.random.normal(fLine,nLine)\n\n#linear fit to continuum\n pCont = numpy.poly1d(numpy.polyfit(wave_cont,fContVar,1))\n fContFit = pCont(wLine)\n ew.append(trapz((numpy.ones(len(fLineVar))-(fLineVar/fContFit)), wLine)*1e4)\n\n# some error checking\n# plt.plot(wLine,fContFit,color='r')\n# plt.plot(wLine,fLine,color='k')\n# plt.show()\n\n# following line is more correct but having problem with output\n# return numpy.nanmean(ew)*u.angstrom, numpy.nanstd(ew)*u.angstrom\n return numpy.nanmean(ew), numpy.nanstd(ew)\n\n\ndef measureEWSet(sp,*args,**kwargs):\n '''\n :Purpose: Measures equivalent widths (EWs) of lines from specified sets. Returns dictionary of indices.\n :param sp: Spectrum class object, which should contain wave, flux and noise array elements\n :param set: string defining which EW measurement set you want to use; options include:\n\n - *rojas*: EW measures from `Rojas-Ayala et al. (2012) `_;\n uses Na I 2.206/2.209 Ca I 2.26 micron lines.\n\n :type set: optional, default = 'rojas'\n\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='1555+0954')[0]\n >>> print splat.measureEWSet(sp, set = 'rojas')\n {'Na I 2.206/2.209': (1.7484002652013144, 0.23332441577025356), 'Ca I 2.26': (1.3742491939667159, 0.24867705962337672), 'names': ['Na I 2.206/2.209', 'Ca I 2.26'], 'reference': 'EW measures from Rojas-Ayala et al. (2012)'}\n '''\n set = kwargs.get('set','rojas')\n\n# determine combine method\n if ('rojas' in set.lower()):\n reference = 'EW measures from Rojas-Ayala et al. (2012)'\n names = ['Na I 2.206/2.209','Ca I 2.26']\n ews = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n ews[0],errs[0] = measureEW(sp,[2.2020, 2.2120],[2.1965, 2.2125, 2.2175],**kwargs)\n ews[1],errs[1] = measureEW(sp,[2.2580, 2.2690],[2.2510, 2.2580, 2.2705, 2.2760],**kwargs)\n else:\n print('{} is not one of the sets used for measureIndexSet'.format(set))\n return numpy.nan\n\n# output dictionary of indices\n result = {names[i]: (ews[i],errs[i]) for i in numpy.arange(len(names))}\n result['reference'] = reference\n result['names'] = names\n# result['reference'] = reference\n# return inds,errs,names\n\n return result\n\n\ndef measureIndex(sp,*args,**kwargs):\n '''\n :Purpose: Measure an index on a spectrum based on defined methodology\n measure method can be mean, median, integrate\n index method can be ratio = 1/2, valley = 1-2/3, OTHERS\n output is index value and uncertainty\n .. will also come back to this one\n '''\n\n# keyword parameters\n method = kwargs.get('method','ratio')\n sample = kwargs.get('sample','integrate')\n nsamples = kwargs.get('nsamples',100)\n noiseFlag = kwargs.get('nonoise',False)\n\n# create interpolation functions\n w = numpy.where(numpy.isnan(sp.flux) == False)\n f = interp1d(sp.wave.value[w],sp.flux.value[w],bounds_error=False,fill_value=0.)\n w = numpy.where(numpy.isnan(sp.noise) == False)\n# note that units are stripped out\n if (numpy.size(w) != 0):\n s = interp1d(sp.wave.value[w],sp.noise.value[w],bounds_error=False,fill_value=numpy.nan)\n noiseFlag = False\n else:\n s = interp1d(sp.wave.value[:],sp.noise.value[:],bounds_error=False,fill_value=numpy.nan)\n noiseFlag = True\n\n# error checking on number of arguments provided\n if (len(args) < 2):\n print('measureIndex needs at least two samples to function')\n return numpy.nan, numpy.nan\n elif (len(args) < 3 and (method == 'line' or method == 'allers' or method == 'inverse_line')):\n print(method+' requires at least 3 sample regions')\n return numpy.nan, numpy.nan\n\n# define the sample vectors\n values = numpy.zeros((len(args),nsamples))\n\n# loop over all sampling regions\n for i,waveRng in enumerate(args):\n xNum = (numpy.arange(0,nsamples+1.0)/nsamples)* \\\n (numpy.nanmax(waveRng)-numpy.nanmin(waveRng))+numpy.nanmin(waveRng)\n yNum = f(xNum)\n yNum_e = s(xNum)\n\n# now do MonteCarlo measurement of value and uncertainty\n for j in numpy.arange(0,nsamples):\n\n# sample variance\n if (numpy.isnan(yNum_e[0]) == False):\n yVar = yNum+numpy.random.normal(0.,1.)*yNum_e\n# NOTE: I'M NOT COMFORTABLE WITH ABOVE LINE - SEEMS TO BE TOO COARSE OF UNCERTAINTY\n# BUT FOLLOWING LINES GIVE UNCERTAINTIES THAT ARE WAY TOO SMALL\n# yVar = numpy.random.normal(yNum,yNum_e)\n# yVar = yNum+numpy.random.normal(0.,1.,len(yNum))*yNum_e\n else:\n yVar = yNum\n\n# choose function for measuring indices\n if (sample == 'integrate'):\n values[i,j] = trapz(yVar,xNum)\n elif (sample == 'average'):\n values[i,j] = numpy.nanmean(yVar)\n elif (sample == 'median'):\n values[i,j] = numpy.median(yVar)\n elif (sample == 'maximum'):\n values[i,j] = numpy.nanmax(yVar)\n elif (sample == 'minimum'):\n values[i,j] = numpy.nanmin(yVar)\n else:\n values[i,j] = numpy.nanmean(yVar)\n\n# compute index based on defined method\n# default is a simple ratio\n if (method == 'ratio'):\n vals = values[0,:]/values[1,:]\n elif (method == 'line'):\n vals = 0.5*(values[0,:]+values[1,:])/values[2,:]\n elif (method == 'inverse_line'):\n vals = 2.*values[0,:]/(values[1,:]+values[2,:])\n elif (method == 'change'):\n vals = 2.*(values[0,:]-values[1,:])/(values[0,:]+values[1,:])\n elif (method == 'allers'):\n vals = (((numpy.mean(args[0])-numpy.mean(args[1]))/(numpy.mean(args[2])-numpy.mean(args[1])))*values[2,:] \\\n + ((numpy.mean(args[2])-numpy.mean(args[0]))/(numpy.mean(args[2])-numpy.mean(args[1])))*values[1,:]) \\\n /values[0,:]\n else:\n vals = values[0,:]/values[1,:]\n\n# output mean, standard deviation\n if (noiseFlag):\n return numpy.nanmean(vals), numpy.nan\n else:\n return numpy.nanmean(vals), numpy.nanstd(vals)\n\n\n# wrapper function for measuring specific sets of indices\n\ndef measureIndexSet(sp,**kwargs):\n '''\n :Purpose: Measures indices of ``sp`` from specified sets. Returns dictionary of indices.\n :param sp: Spectrum class object, which should contain wave, flux and noise array elements\n :param set: string defining which indices set you want to use; options include:\n\n - *bardalez*: H2O-J, CH4-J, H2O-H, CH4-H, H2O-K, CH4-K, K-J, H-dip, K-slope, J-slope, J-curve, H-bump, H2O-Y from `Bardalez Gagliuffi et al. (2014) `_\n - *burgasser*: H2O-J, CH4-J, H2O-H, CH4-H, H2O-K, CH4-K, K-J from `Burgasser et al. (2006) `_\n - *tokunaga*: K1, K2 from `Tokunaga & Kobayashi (1999) `_\n - *reid*: H2O-A, H2O-B from `Reid et al. (2001) `_\n - *geballe*: H2O-1.2, H2O-1.5, CH4-2.2 from `Geballe et al. (2002) `_\n - *allers*: H2O, FeH-z, VO-z, FeH-J, KI-J, H-cont from `Allers et al. (2007) `_, `Allers & Liu (2013) `_\n - *testi*: sHJ, sKJ, sH2O-J, sH2O-H1, sH2O-H2, sH2O-K from `Testi et al. (2001) `_\n - *slesnick*: H2O-1, H2O-2, FeH from `Slesnick et al. (2004) `_\n - *mclean*: H2OD from `McLean et al. (2003) `_\n - *rojas*: H2O-K2 from `Rojas-Ayala et al.(2012) `_\n\n :type set: optional, default = 'burgasser'\n\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='1555+0954')[0]\n >>> print splat.measureIndexSet(sp, set = 'reid')\n {'H2O-B': (1.0531856077273236, 0.0045092074790538221), 'H2O-A': (0.89673318593633422, 0.0031278302105038594)}\n '''\n# keyword parameters\n set = kwargs.get('set','burgasser')\n\n if ('allers' in set.lower()):\n reference = 'Indices from Allers et al. (2007), Allers & Liu (2013)'\n refcode = 'ALL13'\n names = ['H2O','FeH-z','VO-z','FeH-J','KI-J','H-cont']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.55,1.56],[1.492,1.502],method='ratio',sample='average',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[0.99135,1.00465],[0.97335,0.98665],[1.01535,1.02865],method='allers',sample='average',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[1.05095,1.06505],[1.02795,1.04205],[1.07995,1.09405],method='allers',sample='average',**kwargs)\n inds[3],errs[3] = measureIndex(sp,[1.19880,1.20120],[1.19080,1.19320],[1.20680,1.20920],method='allers',sample='average',**kwargs)\n inds[4],errs[4] = measureIndex(sp,[1.23570,1.25230],[1.21170,1.22830],[1.26170,1.27830],method='allers',sample='average',**kwargs)\n inds[5],errs[5] = measureIndex(sp,[1.54960,1.57040],[1.45960,1.48040],[1.65960,1.68040],method='allers',sample='average',**kwargs)\n elif ('bardalez' in set.lower()):\n reference = 'Indices from Bardalez Gagliuffi et al. (2014)'\n refcode = 'BAR14'\n names = ['H2O-J','CH4-J','H2O-H','CH4-H','H2O-K','CH4-K','K-J','H-dip','K-slope','J-slope','J-curve','H-bump','H2O-Y']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.14,1.165],[1.26,1.285],method='ratio',sample='integrate',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[1.315,1.335],[1.26,1.285],method='ratio',sample='integrate',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[1.48,1.52],[1.56,1.60],method='ratio',sample='integrate',**kwargs)\n inds[3],errs[3] = measureIndex(sp,[1.635,1.675],[1.56,1.60],method='ratio',sample='integrate',**kwargs)\n inds[4],errs[4] = measureIndex(sp,[1.975,1.995],[2.08,2.12],method='ratio',sample='integrate',**kwargs)\n inds[5],errs[5] = measureIndex(sp,[2.215,2.255],[2.08,2.12],method='ratio',sample='integrate',**kwargs)\n inds[6],errs[6] = measureIndex(sp,[2.06,2.10],[1.25,1.29],method='ratio',sample='integrate',**kwargs)\n inds[7],errs[7] = measureIndex(sp,[1.61,1.64],[1.56,1.59],[1.66,1.69] ,method='inverse_line',sample='integrate',**kwargs)\n inds[8],errs[8] = measureIndex(sp,[2.06,2.10],[2.10,2.14],method='ratio',sample='integrate',**kwargs)\n inds[9],errs[9] = measureIndex(sp,[1.27,1.30],[1.30,1.33],method='ratio',sample='integrate',**kwargs)\n inds[10],errs[10] = measureIndex(sp,[1.04,1.07],[1.26,1.29],[1.14,1.17],method='line',sample='integrate',**kwargs)\n inds[11],errs[11] = measureIndex(sp,[1.54,1.57],[1.66,1.69],method='ratio',sample='integrate',**kwargs)\n inds[12],errs[12] = measureIndex(sp,[1.04,1.07],[1.14,1.17],method='ratio',sample='integrate',**kwargs)\n elif ('burgasser' in set.lower()):\n reference = 'Indices from Burgasser et al. (2006)'\n refcode = 'BUR06'\n names = ['H2O-J','CH4-J','H2O-H','CH4-H','H2O-K','CH4-K','K-J']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.14,1.165],[1.26,1.285],method='ratio',sample='integrate',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[1.315,1.335],[1.26,1.285],method='ratio',sample='integrate',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[1.48,1.52],[1.56,1.60],method='ratio',sample='integrate',**kwargs)\n inds[3],errs[3] = measureIndex(sp,[1.635,1.675],[1.56,1.60],method='ratio',sample='integrate',**kwargs)\n inds[4],errs[4] = measureIndex(sp,[1.975,1.995],[2.08,2.12],method='ratio',sample='integrate',**kwargs)\n inds[5],errs[5] = measureIndex(sp,[2.215,2.255],[2.08,2.12],method='ratio',sample='integrate',**kwargs)\n inds[6],errs[6] = measureIndex(sp,[2.06,2.10],[1.25,1.29],method='ratio',sample='integrate',**kwargs)\n elif ('geballe' in set.lower()):\n reference = 'Indices from Geballe et al. (2002)'\n refcode = 'GEB02'\n names = ['H2O-1.2','H2O-1.5','CH4-2.2']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.26,1.29],[1.13,1.16],method='ratio',sample='integrate',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[1.57,1.59],[1.46,1.48],method='ratio',sample='integrate',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[2.08,2.12],[2.215,2.255],method='ratio',sample='integrate',**kwargs)\n elif ('mclean' in set.lower()):\n reference = 'Indices from McLean et al. (2003)'\n refcode = 'MCL03'\n names = ['H2OD']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.951,1.977],[2.062,2.088],method='ratio',sample='average',**kwargs)\n elif ('reid' in set.lower()):\n reference = 'Indices from Reid et al. (2001)'\n refcode = 'REI01'\n names = ['H2O-A','H2O-B']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.33,1.35],[1.28,1.30],method='ratio',sample='average',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[1.47,1.49],[1.59,1.61],method='ratio',sample='average',**kwargs)\n elif ('rojas' in set.lower()):\n reference = 'Indices from Rojas-Ayala et al.(2012)'\n refcode = 'ROJ12'\n names = ['H2O-K2']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n num, er1= measureIndex(sp,[2.070,2.090],[2.235,2.255],method='ratio',sample='average',**kwargs)\n den, er2= measureIndex(sp,[2.235,2.255],[2.360,2.380],method='ratio',sample='average',**kwargs)\n inds[0]= num/den\n errs[0]= inds[0]*numpy.sqrt((er1/num)**2+(er2/den)**2)\n elif ('slesnick' in set.lower()):\n reference = 'Indices from Slesnick et al. (2004)'\n refcode = 'SEL04'\n names = ['H2O-1','H2O-2','FeH']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.335,1.345],[1.295,1.305],method='ratio',sample='average',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[2.035,2.045],[2.145,2.155],method='ratio',sample='average',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[1.1935,1.2065],[1.2235,1.2365],method='ratio',sample='average',**kwargs)\n elif ('testi' in set.lower()):\n reference = 'Indices from Testi et al. (2001)'\n refcode = 'TES01'\n names = ['sHJ','sKJ','sH2O_J','sH2O_H1','sH2O_H2','sH2O_K']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[1.265,1.305],[1.6,1.7],method='change',sample='average',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[1.265,1.305],[2.12,2.16],method='change',sample='average',**kwargs)\n inds[2],errs[2] = measureIndex(sp,[1.265,1.305],[1.09,1.13],method='change',sample='average',**kwargs)\n inds[3],errs[3] = measureIndex(sp,[1.60,1.70],[1.45,1.48],method='change',sample='average',**kwargs)\n inds[4],errs[4] = measureIndex(sp,[1.60,1.70],[1.77,1.81],method='change',sample='average',**kwargs)\n inds[5],errs[5] = measureIndex(sp,[2.12,2.16],[1.96,1.99],method='change',sample='average',**kwargs)\n elif ('tokunaga' in set.lower()):\n reference = 'Indices from Tokunaga & Kobayashi (1999)'\n refcode = 'TOK99'\n names = ['K1','K2']\n inds = numpy.zeros(len(names))\n errs = numpy.zeros(len(names))\n inds[0],errs[0] = measureIndex(sp,[2.1,2.18],[1.96,2.04],method='change',sample='average',**kwargs)\n inds[1],errs[1] = measureIndex(sp,[2.2,2.28],[2.1,2.18],method='change',sample='average',**kwargs)\n else:\n print('{} is not one of the sets used for measureIndexSet'.format(set))\n return numpy.nan\n\n# output dictionary of indices\n result = {names[i]: (inds[i],errs[i]) for i in numpy.arange(len(names))}\n# result['reference'] = reference\n# return inds,errs,names\n\n return result\n\n\ndef metallicity(sp,**kwargs):\n '''\n :Purpose: Metallicity measurement using Na I and Ca I lines and H2O-K2 index as described in `Rojas-Ayala et al.(2012) `_\n :param sp: Spectrum class object, which should contain wave, flux and noise array elements\n :param nsamples: number of Monte Carlo samples for error computation\n :type nsamples: optional, default = 100\n\n :Example:\n >>> import splat\n >>> sp = splat.getSpectrum(shortname='0559-1404')[0]\n >>> print splat.metallicity(sp)\n (-0.50726104530066363, 0.24844773591243882)\n '''\n nsamples = kwargs.get('nsamples',100)\n\n coeff_feh = [-1.039,0.092,0.119]\n coeff_feh_e = [0.17,0.023,0.033]\n feh_unc = 0.100\n coeff_mh = [-0.731,0.066,0.083]\n coeff_mh_e = [0.12,0.016,0.023]\n mh_unc = 0.100\n\n h2ok2,h2ok2_e = measureIndexSet(sp, set='rojas')['H2O-K2']\n ew = measureEWSet(sp,set='rojas')\n nai = kwargs.get('nai',False)\n nai_e = kwargs.get('nai_e',0.)\n if nai is False:\n nai, nai_e = ew['Na I 2.206/2.209']\n cai = kwargs.get('cai',False)\n cai_e = kwargs.get('cai_e',0.)\n if cai is False:\n cai, cai_e = ew['Ca I 2.26']\n\n\n mh = numpy.ones(nsamples)*coeff_mh[0]+\\\n (numpy.random.normal(nai,nai_e,nsamples)/numpy.random.normal(h2ok2,h2ok2_e,nsamples))*coeff_mh[1]+\\\n (numpy.random.normal(cai,cai_e,nsamples)/numpy.random.normal(h2ok2,h2ok2_e,nsamples))*coeff_mh[2]\n\n return numpy.nanmean(mh), numpy.sqrt(numpy.nanstd(mh)**2+mh_unc**2)\n\n\ndef properCoordinates(c):\n '''\n :Purpose: Converts various coordinate forms to the proper SkyCoord format. Convertible forms include lists and strings.\n\n :param c: coordinate to be converted. Can be a list (ra, dec) or a string.\n\n :Example:\n >>> import splat\n >>> print splat.properCoordinates([104.79, 25.06])\n \n >>> print splat.properCoordinates('06:59:09.60 +25:03:36.0')\n \n >>> print splat.properCoordinates('J06590960+2503360')\n \n '''\n if isinstance(c,SkyCoord):\n return c\n elif isinstance(c,list):\n return SkyCoord(c[0]*u.deg,c[1]*u.deg,frame='icrs')\n# input is sexigessimal string\n elif isinstance(c,str):\n if c[0] == 'J':\n return designationToCoordinate(c)\n else:\n return SkyCoord(c,'icrs', unit=(u.hourangle, u.deg))\n else:\n raise ValueError('\\nCould not parse input format\\n\\n')\n\n\ndef readSpectrum(*args,**kwargs):\n '''\n .. will come back to this one\n '''\n# keyword parameters\n folder = kwargs.get('folder','')\n catchSN = kwargs.get('catchSN',True)\n local = kwargs.get('local',True)\n online = kwargs.get('online',not local and checkOnline())\n local = not online\n url = kwargs.get('url',SPLAT_URL+DATA_FOLDER)\n kwargs['model'] = False\n\n\n# filename\n file = kwargs.get('file','')\n file = kwargs.get('filename',file)\n if (len(args) > 0):\n file = args[0]\n kwargs['filename'] = file\n kwargs['model'] = False\n\n# a filename must be passed\n if (kwargs['filename'] == ''):\n raise NameError('\\nNeed to pass in filename to read in spectral data (readSpectrum)\\n\\n')\n\n# first pass: check if file is local\n if online == False:\n file = checkLocal(kwargs['filename'])\n if file=='':\n file = checkLocal(kwargs['folder']+os.path.basename(kwargs['filename']))\n if file=='':\n# print('Cannot find '+kwargs['filename']+' locally, trying online\\n\\n')\n local = False\n\n# second pass: download file if necessary\n online = not local\n if online == True:\n file = checkOnline(url+kwargs['filename'])\n if file=='':\n raise NameError('\\nCannot find file '+kwargs['filename']+' on SPLAT website\\n\\n')\n else:\n# read in online file\n file = kwargs['filename']\n try:\n# file = TMPFILENAME+'.'+ftype\n if os.path.exists(os.path.basename(file)):\n os.remove(os.path.basename(file))\n# open(os.path.basename(file), 'wb').write(urllib2.urlopen(url+file).read())\n open(os.path.basename(file), 'wb').write(requests.get(url+file).content)\n# print(file)\n# kwargs['filename'] = os.path.basename(file)\n# sp = Spectrum(**kwargs)\n# os.remove(os.path.basename(tmp))\n# return sp\n except:\n raise NameError('\\nProblem reading in '+file+' from SPLAT website\\n\\n')\n\n# determine which type of file\n ftype = file.split('.')[-1]\n\n# fits file\n if (ftype == 'fit' or ftype == 'fits'):\n with fits.open(file) as data:\n if 'NAXIS3' in data[0].header.keys():\n d = numpy.copy(data[0].data[0,:,:])\n else:\n d = numpy.copy(data[0].data)\n header = data[0].header\n\n# ascii file\n else:\n try:\n d = numpy.genfromtxt(file, comments='#', unpack=False, \\\n missing_values = ('NaN','nan'), filling_values = (numpy.nan)).transpose()\n except ValueError:\n d = numpy.genfromtxt(file, comments=';', unpack=False, \\\n missing_values = ('NaN','nan'), filling_values = (numpy.nan)).transpose()\n header = fits.Header() # blank header\n\n# delete file if this was an online read\n if online and not local and os.path.exists(os.path.basename(file)):\n os.remove(os.path.basename(file))\n\n# assign arrays to wave, flux, noise\n wave = d[0,:]\n flux = d[1,:]\n if len(d[:,0]) > 2:\n noise = d[2,:]\n else:\n noise = numpy.zeros(len(flux))\n noise[:] = numpy.nan\n\n# fix places where noise is claimed to be 0\n w = numpy.where(noise == 0.)\n noise[w] = numpy.nan\n\n# fix nans in flux\n w = numpy.where(numpy.isnan(flux) == True)\n flux[w] = 0.\n\n# fix to catch badly formatted files where noise column is S/N\n# print(flux, numpy.median(flux))\n if (catchSN):\n w = numpy.where(flux > stats.nanmedian(flux))\n if (stats.nanmedian(flux[w]/noise[w]) < 1.):\n noise = flux/noise\n w = numpy.where(numpy.isnan(noise))\n noise[w] = stats.nanmedian(noise)\n\n# clean up\n# if url != '' and not local:\n# os.remove(os.path.basename(TMPFILENAME))\n\n return {'wave':wave,'flux':flux,'noise':noise,'header':header}\n\n\n\ndef redden(sp, **kwargs):\n '''\n Description:\n Redden a spectrum based on an either Mie theory or a standard interstellar profile\n using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)\n\n **Usage**\n\n >>> import splat\n >>> sp = splat.Spectrum(10001) # read in a source\n >>> spr = splat.redden(sp,av=5.,rv=3.2) # redden to equivalent of AV=5\n\n **Note**\n This routine is still in beta form; only the CCM89 currently works\n\n '''\n w = sp.wave.value # assuming in microns!\n av = kwargs.get('av',0.0)\n\n\n if kwargs.get('mie',False): # NOT CURRENTLY FUNCTIONING\n a = kwargs.get('a',10.) # grain size\n n = kwargs.get('n',1.33) # complex index of refraction\n x = 2*numpy.pi*a/w\n x0 = 2.*numpy.pi*a/0.55 # for V-band\n qabs = -4.*x*((n**2-1)/(n**2+2)).imag\n qsca = (8./3.)*(x**4)*(((n**2-1)/(n**2+2))**2).real\n# tau = numpy.pi*(a**2)*(qabs+qsca)\n tau = 1.5*(qabs+qsca)/a # for constant mass\n qabs0 = -4.*x0*((n**2-1)/(n**2+2)).imag\n qsca0 = (8./3.)*(x0**4)*(((n**2-1)/(n**2+2))**2).real\n# tau0 = numpy.pi*(a**2)*(qabs0+qsca0)\n tau0 = 1.5*(qabs0+qsca0)/a # for constant mass\n scale = (10.**(-0.4*av))\n absfrac = scale*numpy.exp(numpy.max(tau)-tau)\n else:\n x = 1./w\n a = 0.574*(x**1.61)\n b = -0.527*(x**1.61)\n rv = kwargs.get('rv',3.1)\n absfrac = 10.**(-0.4*av*(a+b/rv))\n\n if kwargs.get('normalize',False):\n absfrac = absfrac/numpy.median(absfrac)\n\n print(tau0, min(tau), max(tau), max(absfrac), min(absfrac))\n spabs = splat.Spectrum(wave=w,flux=absfrac)\n return sp*spabs\n\n\n\n\ndef test():\n '''\n :Purpose: Tests the SPLAT Code\n :Checks the following:\n\n - If you are online and can see the SPLAT website\n - If you have access to unpublished spectra\n - If you can search for and load a spectrum\n - If ``searchLibrary`` functions properly\n - If index measurement routines functions properly\n - If classification routines function properly\n - If ``typeToTeff`` functions properly\n - If flux calibration and normalization function properly\n - If ``loadModel`` functions properly\n - If ``compareSpectra`` functions properly\n - If ``plotSpectrum`` functions properly\n '''\n\n test_src = 'Random'\n\n sys.stderr.write('\\n\\n>>>>>>>>>>>> TESTING SPLAT CODE <<<<<<<<<<<<\\n')\n# check you are online\n if checkOnline():\n sys.stderr.write('\\n...you are online and can see SPLAT website\\n')\n else:\n sys.stderr.write('\\n...you are NOT online or cannot see SPLAT website\\n')\n\n# check your access\n if checkAccess():\n sys.stderr.write('\\n...you currently HAVE access to unpublished spectra\\n')\n else:\n sys.stderr.write('\\n...you currently DO NOT HAVE access to unpublished spectra\\n')\n\n# check you can search for and load a spectrum\n# sp = getSpectrum(shortname=test_src)[0]\n sp = getSpectrum(spt=['L5','T5'],lucky=True)[0]\n sp.info()\n sys.stderr.write('\\n...getSpectrum successful\\n')\n\n# check searchLibrary\n list = searchLibrary(young=True,output='DATA_FILE')\n sys.stderr.write('\\n{} young spectra in the SPL ...searchLibrary successful\\n'.format(len(list)))\n\n# check index measurement\n ind = measureIndexSet(sp,set='burgasser')\n sys.stderr.write('\\nSpectral indices for '+test_src+':\\n')\n for k in ind.keys():\n print('\\t{:s}: {:4.3f}+/-{:4.3f}'.format(k, ind[k][0], ind[k][1]))\n sys.stderr.write('...index measurement successful\\n')\n\n# check classification\n spt, spt_e = classifyByIndex(sp,set='burgasser')\n sys.stderr.write('\\n...index classification of '+test_src+' = {:s}+/-{:2.1f}; successful\\n'.format(spt,spt_e))\n\n spt, spt_e = classifyByStandard(sp,method='kirkpatrick')\n sys.stderr.write('\\n...standard classification of '+test_src+' = {:s}+/-{:2.1f}; successful\\n'.format(spt,spt_e))\n\n grav = classifyGravity(sp)\n sys.stderr.write('\\n...gravity class of '+test_src+' = {}; successful\\n'.format(grav))\n\n# check SpT -> Teff\n teff, teff_e = typeToTeff(spt,unc=spt_e)\n sys.stderr.write('\\n...Teff of '+test_src+' = {:.1f}+/-{:.1f} K; successful\\n'.format(teff,teff_e))\n\n# check flux calibration\n sp.normalize()\n sp.fluxCalibrate('2MASS J',15.0,apparent=True)\n mag,mag_e = filterMag(sp,'MKO J')\n sys.stderr.write('\\n...apparent magnitude MKO J = {:3.2f}+/-{:3.2f} from 2MASS J = 15.0; filter calibration successful\\n'.format(mag,mag_e))\n\n# check models\n# mdl = loadModel(teff=1000,logg=5.0,set='BTSettl2008')\n logg = 5.2\n if grav == 'VL-G':\n logg = 4.2\n elif grav == 'INT-G':\n logg = 4.6\n mdl = loadModel(teff=teff,logg=logg,set='BTSettl2008')\n sys.stderr.write('\\n...interpolated model generation successful\\n')\n\n# check normalization\n sys.stderr.write('\\n...normalization successful\\n')\n\n# check compareSpectrum\n chi, scale = compareSpectra(sp,mdl,mask_standard=True,stat='chisqr')\n sys.stderr.write('\\nScaling model: chi^2 = {}, scale = {}'.format(chi,scale))\n sys.stderr.write('\\n...compareSpectra successful\\n'.format(chi,scale))\n\n# check plotSpectrum\n mdl.scale(scale)\n plotSpectrum(sp,mdl,colors=['k','r'],title='If this appears everything is OK: close window')\n sys.stderr.write('\\n...plotSpectrum successful\\n')\n sys.stderr.write('\\n>>>>>>>>>>>> SPLAT TEST SUCCESSFUL; HAVE FUN! <<<<<<<<<<<<\\n\\n')\n\n\ndef typeToMag(spt, filt, **kwargs):\n \"\"\"\n :Purpose: Takes a spectral type and a filter, and returns absolute magnitude\n :param spt: string or integer of the spectral type\n :param filter: filter of the absolute magnitude. Options are MKO K, MKO H, MKO J, MKO Y, MKO LP, 2MASS J, 2MASS K, or 2MASS H\n :param nsamples: number of Monte Carlo samples for error computation\n :type nsamples: optional, default = 100\n :param unc: uncertainty of ``spt``\n :type unc: optional, default = 0.\n :param ref: Abs Mag/SpT relation used to compute the absolute magnitude. Options are:\n\n - *burgasser*: Abs Mag/SpT relation from `Burgasser (2007) `_.\n Allowed spectral type range is L0 to T8, and allowed filters are MKO K.\n - *faherty*: Abs Mag/SpT relation from `Faherty et al. (2012) `_.\n Allowed spectral type range is L0 to T8, and allowed filters are MKO J, MKO H and MKO K.\n - *dupuy*: Abs Mag/SpT relation from `Dupuy & Liu (2012) `_.\n Allowed spectral type range is M6 to T9, and allowed filters are MKO J, MKO Y, MKO H, MKO K, MKO LP, 2MASS J, 2MASS H, and 2MASS K.\n - *filippazzo*: Abs Mag/SpT relation from Filippazzo et al. (2015). Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J and WISE W2.\n\n\n :type ref: optional, default = 'dupuy'\n :Example:\n >>> import splat\n >>> print splat.typeToMag('L3', '2MASS J')\n (12.730064813273996, 0.4)\n >>> print splat.typeToMag(21, 'MKO K', ref = 'burgasser')\n (10.705292820099999, 0.26)\n >>> print splat.typeToMag(24, '2MASS J', ref = 'faherty')\n Invalid filter given for Abs Mag/SpT relation from Faherty et al. (2012)\n (nan, nan)\n >>> print splat.typeToMag('M0', '2MASS H', ref = 'dupuy')\n Spectral Type is out of range for Abs Mag/SpT relation from Dupuy & Liu (2012) Abs Mag/SpT relation\n (nan, nan)\n \"\"\"\n\n#Keywords\n nsamples = kwargs.get('nsamples', 100)\n ref = kwargs.get('ref', 'dupuy')\n unc = kwargs.get('unc', 0.)\n\n#Convert spectral type string to number\n if (type(spt) == str):\n spt = typeToNum(spt, uncertainty=unc)\n else:\n spt = copy.deepcopy(spt)\n\n#Faherty\n if (ref.lower() == 'faherty'):\n sptoffset = 10.\n reference = 'Abs Mag/SpT relation from Faherty et al. (2012)'\n coeffs = { \\\n 'MKO J': {'fitunc' : 0.30, 'range' : [20., 38.], \\\n 'coeff': [.000203252, -.0129143, .275734, -1.99967, 14.8948]}, \\\n 'MKO H': {'fitunc' : 0.27, 'range' : [20., 38.], \\\n 'coeff' : [.000175368, -.0108205, .227363, -1.60036, 13.2372]}, \\\n 'MKO K': {'fitunc' : 0.28, 'range' : [20., 38.], \\\n 'coeff' : [.0000816516, -.00469032, .0940816, -.485519, 9.76100]}}\n\n# Burgasser\n elif (ref.lower() == 'burgasser'):\n sptoffset = 20.\n reference = 'Abs Mag/SpT relation from Burgasser (2007)'\n coeffs = { \\\n 'MKO K': {'fitunc' : 0.26, 'range' : [20., 38.], \\\n 'coeff': [.0000001051, -.000006985, .0001807, -.002271, .01414, -.04024, .05129, .2322, 10.45]}}\n\n# Dupuy & Liu, default reference\n elif (ref.lower() == 'dupuy'):\n reference = 'Abs Mag/SpT relation from Dupuy & Liu (2012)'\n sptoffset = 10.\n coeffs = { \\\n 'MKO J': {'fitunc' : 0.39, 'range' : [16., 39.], \\\n 'coeff' : [-.00000194920, .000227641, -.0103332, .232771, -2.74405, 16.3986, -28.3129]}, \\\n 'MKO Y': {'fitunc': 0.40, 'range' : [16., 39.], \\\n 'coeff': [-.00000252638, .000285027, -.0126151, .279438, -3.26895, 19.5444, -35.1560]}, \\\n 'MKO H': {'fitunc': 0.38, 'range' : [16., 39.], \\\n 'coeff': [-.00000224083, .000251601, -.0110960, .245209, -2.85705, 16.9138, -29.7306]}, \\\n 'MKO K': {'fitunc': 0.40, 'range' : [16., 39.], \\\n 'coeff': [-.00000104935, .000125731, -.00584342, .135177, -1.63930, 10.1248, -15.2200]}, \\\n 'MKO LP': {'fitunc': 0.28, 'range': [16., 39.], \\\n 'coeff': [0.00000, 0.00000, .0000546366, -.00293191, .0530581, -.196584, 8.89928]}, \\\n '2MASS J': {'fitunc': 0.40, 'range': [16., 39.], \\\n 'coeff': [-.000000784614, .000100820, -.00482973, .111715, -1.33053, 8.16362, -9.67994]}, \\\n '2MASS H': {'fitunc': 0.40, 'range': [16., 39.], \\\n 'coeff': [-.00000111499, .000129363, -.00580847, .129202, -1.50370, 9.00279, -11.7526]}, \\\n '2MASS KS': {'fitunc': 0.43, 'range':[16., 39.], \\\n 'coeff': [1.06693e-4, -6.42118e-3, 1.34163e-1, -8.67471e-1, 1.10114e1]}, \\\n 'WISE W1': {'fitunc': 0.39, 'range':[16., 39.], \\\n 'coeff': [1.58040e-5, -3.33944e-4, -4.38105e-3, 3.55395e-1, 7.14765]}, \\\n 'WISE W2': {'fitunc': 0.35, 'range':[16., 39.], \\\n 'coeff': [1.78555e-5, -8.81973e-4, 1.14325e-2, 1.92354e-1, 7.46564]}}\n\n elif (ref.lower() == 'filippazzo'):\n reference = 'Abs Mag/SpT relation from Filippazzo et al. (2015)'\n sptoffset = 10.\n coeffs = { \\\n '2MASS J': {'fitunc': 0.40, 'range': [16., 39.], \\\n 'coeff': [3.478e-5, -2.684e-3, 7.771e-2, -1.058e0, 7.157e0, -8.350e0]}, \\\n 'WISE W2': {'fitunc': 0.40, 'range': [16., 39.], \\\n 'coeff': [8.190e-6, -6.938e-4, 2.283e-2, -3.655e-1, 3.032e0, -5.043e-1]}}\n\n else:\n sys.stderr.write('\\nInvalid Abs Mag/SpT relation given: %s\\n' % ref)\n return numpy.nan, numpy.nan\n\n if (filt.upper() in coeffs.keys()) == 1:\n for f in coeffs.keys():\n if filt.upper() == f:\n coeff = coeffs[f]['coeff']\n fitunc = coeffs[f]['fitunc']\n rng = coeffs[f]['range']\n else:\n sys.stderr.write('\\n Invalid filter {} given for {}\\n'.format(filt,reference))\n return numpy.nan, numpy.nan\n\n# compute magnitude if its in the right spectral type range\n if (rng[0] <= spt <= rng[1]):\n if (unc > 0.):\n vals = numpy.polyval(coeff, numpy.random.normal(spt - sptoffset, unc, nsamples))\n abs_mag = numpy.nanmean(vals)\n abs_mag_error = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n return abs_mag, abs_mag_error\n else:\n abs_mag = numpy.polyval(coeff, spt-sptoffset)\n return abs_mag, fitunc\n else:\n sys.stderr.write('\\nSpectral Type is out of range for %s Abs Mag/SpT relation\\n' % reference)\n return numpy.nan, numpy.nan\n\n\ndef typeToNum(input, **kwargs):\n '''\n :Purpose: Converts between string and numeric spectral types, and vise versa.\n :param input: Spectral type to convert. Can convert a number or a string from 0 (K0) and 49.0 (Y9).\n :param error: magnitude of uncertainty. ':' for uncertainty > 1 and '::' for uncertainty > 2.\n :type error: optional, default = ''\n :param uncertainty: uncertainty of spectral type\n :type uncertainty: optional, default = 0\n :param subclass: subclass of object. Options include:\n\n - *sd*: object is a subdwarf\n - *esd*: object is an extreme subdwarf\n - *usd*: object is an ultra subdwarf\n\n :type subclass: optional, default = ''\n :param lumclass: luminosity class of object represented by roman numerals\n :type lumclass: optional, default = ''\n :param ageclass: age class of object\n :type ageclass: optional, default = ''\n :param colorclass: color class of object\n :type colorclass: optional, default = ''\n :param peculiar: if object is peculiar or not\n :type peculiar: optional, default = False\n\n .. not too sure how colorclass and ageclass work\n\n :Example:\n >>> import splat\n >>> print splat.typeToNum(30)\n T0.0\n >>> print splat.typeToNum('T0.0')\n 30.0\n >>> print splat.typeToNum(27, peculiar = True, uncertainty = 1.2, lumclass = 'II')\n L7.0IIp:\n >>> print splat.typeToNum(50)\n Spectral type number must be between 0 (K0) and 49.0 (Y9)\n nan\n '''\n# keywords\n error = kwargs.get('error','')\n unc = kwargs.get('uncertainty',0.)\n subclass = kwargs.get('subclass','')\n lumclass = kwargs.get('lumclass','')\n ageclass = kwargs.get('ageclass','')\n colorclass = kwargs.get('colorclass','')\n peculiar = kwargs.get('peculiar',False)\n spletter = 'KMLTY'\n\n# number -> spectral type\n if (isNumber(input)):\n spind = int(abs(input/10))\n spdec = numpy.around(input,1)-spind*10.\n pstr = ''\n if (unc > 1.):\n error = ':'\n if (unc > 2.):\n error = '::'\n if (peculiar):\n pstr = 'p'\n if (0 <= spind < len(spletter)):\n output = colorclass+subclass+spletter[spind]+'{:3.1f}'.format(spdec)+ageclass+lumclass+pstr+error\n else:\n print('Spectral type number must be between 0 ({}0) and {} ({}9)'.format(spletter[0],len(spletter)*10.-1.,spletter[-1]))\n output = numpy.nan\n\n# spectral type -> number\n elif isinstance(input,str):\n if (sys.version_info.major == 2):\n input = string.split(input,sep='+')[0] # remove +/- sides\n input = string.split(input,sep='-')[0] # remove +/- sides\n else:\n input = input.split('+')[0] # remove +/- sides\n input = input.split('-')[0] # remove +/- sides\n\n sptype = re.findall('[{}]'.format(spletter),input)\n if (len(sptype) == 1):\n output = spletter.find(sptype[0])*10.\n spind = input.find(sptype[0])+1\n if (spind < len(input)):\n if (input.find('.') < 0):\n if (isNumber(input[spind])):\n output = output+float(input[spind])\n else:\n output = output+float(input[spind:spind+3])\n spind = spind+3\n ytype = re.findall('[abcd]',input.split('p')[-1])\n if (len(ytype) == 1):\n ageclass = ytype[0]\n if (input.find('p') != -1):\n peculiar = True\n if (input.find('sd') != -1):\n subclass = 'sd'\n if (input.find('esd') != -1):\n subclass = 'esd'\n if (input.find('usd') != -1):\n subclass = 'usd'\n if (input.count('I') > 0):\n lumclass = ''.join(re.findall('I',input))\n if (input.count(':') > 0):\n error = ''.join(re.findall(':',input))\n if (input[0] == 'b' or input[0] == 'r'):\n colorclass = input[0]\n if (len(sptype) != 1):\n# print('Only spectral classes {} are handled with this routine'.format(spletter))\n output = numpy.nan\n# none of the above - return the input\n else:\n output = input\n return output\n\n\ndef typeToTeff(input, **kwargs):\n '''\n :Purpose: Returns an effective temperature (Teff) and its uncertainty for a given spectral type\n :param input: Spectral type; can be a number or a string from 0 (K0) and 49.0 (Y9).\n :param uncertainty: uncertainty of spectral type\n :type uncertainty: optional, default = 0.001\n :param unc: same as ``uncertainty``\n :type unc: optional, default = 0.001\n :param spt_e: same as ``uncertainty``\n :type spt_e: optional, default = 0.001\n :param ref: Teff/SpT relation used to compute the effective temperature. Options are:\n\n - *golimowski*: Teff/SpT relation from `Golimowski et al. (2004) `_.\n Allowed spectral type range is M6 to T8.\n - *looper*: Teff/SpT relation from `Looper et al. (2008) `_.\n Allowed spectral type range is L0 to T8.\n - *stephens*: Teff/SpT relation from `Stephens et al. (2009) `_.\n Allowed spectral type range is M6 to T8 and uses alternate coefficients for L3 to T8.\n - *marocco*: Teff/SpT relation from `Marocco et al. (2013) `_.\n Allowed spectral type range is M7 to T8.\n - *filippazzo*: Teff/SpT relation from Filippazzo et al. (2015). Allowed spectral type range is M6 to T9.\n\n :type ref: optional, default = 'stephens2009'\n :param set: same as ``ref``\n :type set: optional, default = 'stephens2009'\n :param method: same as ``ref``\n :type method: optional, default = 'stephens2009'\n :param nsamples: number of samples to use in Monte Carlo error estimation\n :type nsamples: optional, default = 100\n\n :Example:\n >>> import splat\n >>> print splat.typeToTeff(20)\n (2233.4796740905499, 100.00007874571999)\n >>> print splat.typeToTeff(20, unc = 0.3, ref = 'golimowski')\n (2305.7500497902788, 127.62548366132124)\n '''\n# keywords\n nsamples = kwargs.get('nsamples',100)\n unc = kwargs.get('uncertainty',0.001)\n unc = kwargs.get('unc',unc)\n unc = kwargs.get('spt_e',unc)\n ref = kwargs.get('ref','stephens2009')\n ref = kwargs.get('set',ref)\n ref = kwargs.get('method',ref)\n\n# convert spectral type string to number\n if (type(input) == str):\n spt = typeToNum(input,uncertainty=unc)\n else:\n spt = copy.deepcopy(input)\n\n# if spt < 20. and 'marocco' not in ref.lower():\n# ref='stephens2009'\n\n# choose among possible options\n\n# Golimowski et al. (2004, AJ, 127, 3516)\n if ('golimowski' in ref.lower()):\n reference = 'Teff/SpT relation from Golimowski et al. (2004)'\n sptoffset = 10.\n coeff = [9.5373e-4,-9.8598e-2,4.0323,-8.3099e1,9.0951e2,-5.1287e3,1.4322e4]\n range = [16.,38.]\n fitunc = 124.\n\n# Looper et al. (2008, ApJ, 685, 1183)\n elif ('looper' in ref.lower()):\n reference = 'Teff/SpT relation from Looper et al. (2008)'\n sptoffset = 20.\n coeff = [9.084e-4,-4.255e-2,6.414e-1,-3.101,1.950,-108.094,2319.92]\n range = [20.,38.]\n fitunc = 87.\n\n# Stephens et al. (2009, ApJ, 702, 1545); using OPT/IR relation for M6-T8\n# plus alternate coefficients for L3-T8\n elif ('stephens' in ref.lower()):\n reference = 'Teff/SpT relation from Stephens et al. (2009)'\n sptoffset = 10.\n coeff = [-0.0025492,0.17667,-4.4727,54.67,-467.26,4400.]\n range = [16.,38.]\n fitunc = 100.\n coeff_alt = [-0.011997,1.2315,-50.472,1031.9,-10560.,44898.]\n range_alt = [23.,38.]\n\n# Marocco et al. (2013, AJ, 146, 161)\n elif ('marocco' in ref.lower()):\n reference = 'Teff/SpT relation from Marocco et al. (2013)'\n sptoffset = 10.\n coeff = [7.4211e-5,-8.43736e-3,3.90319e-1,-9.46896,129.141,-975.953,3561.47,-1613.82]\n range = [17.,38.]\n fitunc = 140.\n\n elif ('filippazzo' in ref.lower()):\n reference = 'Teff/SpT relation from Filippazzo et al. (2015)'\n sptoffset = 10.\n coeff = [1.546e-4, -1.606e-2, 6.318e-1, -1.191e1, 1.155e2, -7.005e2, 4.747e3]\n range = [16., 39.]\n fitunc = 113.\n\n else:\n sys.stderr.write('\\nInvalid Teff/SpT relation given ({})\\n'.format(ref))\n return numpy.nan, numpy.nan\n\n if (range[0] <= spt <= range[1]):\n vals = numpy.polyval(coeff,numpy.random.normal(spt-sptoffset,unc,nsamples))\n if ('stephens' in ref.lower()):\n if (range_alt[0] <= spt <= range_alt[1]):\n vals = numpy.polyval(coeff_alt,numpy.random.normal(spt-sptoffset,unc,nsamples))\n teff = numpy.nanmean(vals)\n teff_e = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n return teff, teff_e\n else:\n sys.stderr.write('\\nSpectral Type is out of range for {:s} Teff/SpT relation\\n'.format(reference))\n return numpy.nan, numpy.nan\n\n\ndef weightedMeanVar(vals, winp, *args, **kwargs):\n '''\n :Purpose: Computes weighted mean of an array of values through various methods. Returns weighted mean and weighted uncertainty.\n :param vals: array of values\n :param winp: array of weights associated with ``vals``\n :param method: input type of weights. Default is where ``winp`` is the actual weights of ``vals``. Options include:\n\n - *uncertainty*: uncertainty weighting, where ``winp`` is the uncertainties of ``vals``\n - *ftest*: ftest weighting, where ``winp`` is the chi squared values of ``vals``\n\n :type method: optional, default = ''\n :param weight_minimum: minimum possible weight value\n :type weight_minimum: optional, default = 0.\n :param dof: effective degrees of freedom\n :type dof: optional, default = len(vals) - 1\n\n .. note:: When using ``ftest`` method, extra ``dof`` value is required\n\n :Example:\n >>> import splat\n >>> print splat.weightedMeanVar([3.52, 5.88, 9.03], [0.65, 0.23, 0.19])\n (5.0057009345794379, 4.3809422657000594)\n >>> print splat.weightedMeanVar([3.52, 5.88, 9.03], [1.24, 2.09, 2.29], method = 'uncertainty')\n (5.0069199363443841, 4.3914329968409946)\n '''\n\n method = kwargs.get('method','')\n minwt = kwargs.get('weight_minimum',0.)\n dof = kwargs.get('dof',len(vals)-1)\n if (numpy.nansum(winp) <= 0.):\n weights = numpy.ones(len(vals))\n if isinstance(winp,astropy.units.quantity.Quantity):\n winput = winp.value\n else:\n winput = copy.deepcopy(winp)\n\n# uncertainty weighting: input is unceratinties\n if (method == 'uncertainty'):\n weights = [w**(-2) for w in winput]\n# ftest weighting: input is chisq values, extra dof value is required\n elif (method == 'ftest'):\n# fix issue of chi^2 = 0\n minchi = numpy.nanmin(winput)\n weights = numpy.array([stats.f.pdf(w/minchi,dof,dof) for w in winput])\n# just use the input as the weights\n else:\n weights = [w for w in winput]\n\n weights = weights/numpy.nanmax(weights)\n weights[numpy.where(weights < minwt)] = 0.\n mn = numpy.nansum(vals*weights)/numpy.nansum(weights)\n var = numpy.nansum(weights*(vals-mn)**2)/numpy.nansum(weights)\n if (method == 'uncertainty'):\n var+=numpy.nansum([w**2 for w in winput])/(len(winput)**2)\n\n return mn,numpy.sqrt(var)\n\n\n# run test program if calling from command line\nif __name__ == \"__main__\":\n test()\n","sub_path":"splat.py","file_name":"splat.py","file_ext":"py","file_size_in_byte":162038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"484425970","text":"import pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import r2_score\r\n\r\ndef calculate_quality(clf):\r\n data_ = pd.read_csv('files/lesson_9/train.csv')\r\n X = data_.drop(columns = [\"target\", \"ID\"])\r\n X_train, X_test, y_train, y_test = train_test_split(X, data_.target, test_size=0.33, random_state=42)\r\n clf.fit(X_train, y_train)\r\n y_result = clf.predict(X.test)\r\n print(\"sad\")\r\n print(r2_score(y_test, y_result))","sub_path":"data_analysis/prac_9/__pycache__/fff.py","file_name":"fff.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"419590556","text":"import csv\r\nimport numpy as np\r\nimport scipy\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\n\nest = LinearRegression(fit_intercept=False)\n\n#est = RandomForestRegressor()\n\n\nx_file = \"x_train.csv\"\r\ny_file = \"y_train.csv\"\n\nxt_file = \"x_test.csv\"\n\nyt_file = \"y_test.csv\"\n\nremove_cols = [7, 8 , 14, 27, 31, 47, 52,70, 71, 77, 88, 95, 105,108, 118, 119,126, 136, 139, 142, 145, 168, 169, 184, 194, 200,201, 209, 217]\n#with open(x_file,'r') as dest_f:\r \n# data_iter = csv.reader(dest_f, \r\n# delimiter = \";\", \r\n# quotechar = '\"')\r\n# data_x = [data for data in data_iter]\r\n\r\n#with open(y_file,'r') as y_f:\r\n# data_y_iter = csv.reader(y_f, \r\n# delimiter = \";\", \r\n# quotechar = '\"')\r\n# data_y = [data for data in data_y_iter]\r\n\n\ndata_x = np.genfromtxt(x_file, dtype=float, delimiter=';') \ndata_y = np.genfromtxt(y_file, dtype=float, delimiter=';') \ndata_xt = np.genfromtxt(xt_file, dtype=float, delimiter=';') \n\noffset1 =1\n\nfor i in remove_cols:\n data_x = scipy.delete(data_x, i-offset1, 1) # delete 6th column\n data_xt = scipy.delete(data_xt, i-offset1, 1) # delete\n offset1 += 1\n\n\n#print (data_x.tolist())\n\n\n#with open(xt_file,'r') as xt_f:\r\n# data_xt_iter = csv.reader(xt_f, dtype=float,\n# delimiter = \";\", \r\n## quotechar = '\"')\r\n# data_xt = [data for data in data_xt_iter]\r\n#print (data_xt)\n\n#with open(yt_file,'w') as ot_f:\r\n# data_yt_iter = csv.writer(xt_f, \r\n# delimiter = \";\", \r\n# quotechar = '\"')\r\n# data_yt = [data for data in data_xt_iter]\r\n\n\n\n#y2 = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)\n# Fit the model on 33%\n#print (data_xt)\n##corr_x=data_x.corr()\n\nest.fit(data_x, data_y)\n##z=est.coef_ # access coefficients\n\n\n#est.score(data_xt, y2)\nxxx = est.predict(data_xt)\ny2 = xxx.tolist()\n#print (y2)\n#print (type(xxx))\nfor i in y2:\n print(int (i))\n\n\r\n\r\n\r\n#print data_x[0][33]\r\n#print data_y\r\n","sub_path":"t_cluster.py","file_name":"t_cluster.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"117138271","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# pylint: disable=line-too-long\nimport argparse\nfrom azure.cli.core.util import CLIError\nfrom azure.cli.core.commands.validators import get_default_location_from_resource_group\nfrom azure.cli.core.commands.parameters import (\n resource_group_name_type,\n get_enum_type,\n get_three_state_flag,\n tags_type\n)\nfrom azure.cli.core.util import get_json_object\nfrom azure.cli.command_modules.servicefabric._validators import (\n validate_create_service,\n validate_update_application,\n validate_create_application,\n validate_create_managed_cluster\n)\nfrom knack.arguments import CLIArgumentType\n\n\ndef load_arguments(self, _): # pylint: disable=too-many-statements\n # PARAMETER REGISTRATION\n application_parameters = CLIArgumentType(\n options_list=['--parameters', '--application-parameters'],\n action=AddAppParamsAction,\n nargs='+',\n help='Specify the application parameters as key/value pairs. These parameters must exist in the application manifest. '\n 'for example: --application-parameters param1=value1 param2=value2')\n\n minimum_nodes = CLIArgumentType(\n options_list=['--min-nodes', '--minimum-nodes'],\n help='Specify the minimum number of nodes where Service Fabric will reserve capacity for this application, '\n 'this does not mean that the application is guaranteed to have replicas on all those nodes. The value of this parameter must be a non-negative integer. '\n 'Default value for this is zero, which means no capacity is reserved for the application.')\n\n maximum_nodes = CLIArgumentType(\n options_list=['--max-nodes', '--maximum-nodes'],\n help='Specify the maximum number of nodes on which to place an application. '\n 'The value of this parameter must be a non-negative integer. The default value is 0, which indicates the application can be placed on any number of nodes in the cluster.')\n\n application_type_version = CLIArgumentType(\n options_list=['--version', '--application-type-version'],\n help='Specify the application type version.')\n\n package_url = CLIArgumentType(\n help='Specify the url of the application package sfpkg file.')\n\n with self.argument_context('sf') as c:\n c.argument('resource_group_name', arg_type=resource_group_name_type, id_part=None, help='Specify the resource group name. You can configure the default group using `az configure --defaults group=`')\n c.argument('cluster_name', options_list=['--cluster-name', '-c'], help='Specify the name of the cluster, if not given it will be same as resource group name')\n c.argument('location', validator=get_default_location_from_resource_group)\n c.argument('secret_identifier', help='The existing Azure key vault secret URL')\n c.argument('certificate_file', help='The existing certificate file path for the primary cluster certificate.')\n c.argument('parameter_file', help='The path to the template parameter file.')\n c.argument('template_file', help='The path to the template file.')\n c.argument('vm_password', help='The password of the Vm')\n c.argument('certificate_output_folder', options_list=['--certificate-output-folder', '--cert-out-folder'], help='The folder of the new certificate file to be created.')\n c.argument('certificate_password', help='The password of the certificate file.')\n c.argument('certificate_subject_name', options_list=['--certificate-subject-name', '--cert-subject-name'], help='The subject name of the certificate to be created.')\n c.argument('vault_resource_group_name', options_list=['--vault-resource-group'], help='Key vault resource group name, if not given it will be cluster resource group name')\n c.argument('vault_name', help='Azure key vault name, it not given it will be the cluster resource group name')\n c.argument('cluster_size', options_list=['--cluster-size', '-s'], help='The number of nodes in the cluster. Default are 5 nodes')\n c.argument('vm_sku', help='VM Sku')\n c.argument('vm_user_name', help='The user name for logging to Vm. Default will be adminuser')\n c.argument('vm_os', arg_type=get_enum_type(['WindowsServer2012R2Datacenter',\n 'WindowsServer2016Datacenter',\n 'WindowsServer2016DatacenterwithContainers',\n 'UbuntuServer1604',\n 'WindowsServer1709',\n 'WindowsServer1709withContainers',\n 'WindowsServer1803withContainers',\n 'WindowsServer1809withContainers',\n 'WindowsServer2019Datacenter',\n 'WindowsServer2019DatacenterwithContainers']),\n default='WindowsServer2016Datacenter', options_list=['--vm-os', '--os'],\n help='The Operating System of the VMs that make up the cluster.')\n c.argument('node_type', help='the Node type name.')\n\n # cluster\n with self.argument_context('sf cluster list') as c:\n c.argument('resource_group_name', arg_type=resource_group_name_type, id_part=None, help='The resource group name')\n\n with self.argument_context('sf client certificate') as c:\n c.argument('certificate_common_name', help='client certificate common name.')\n c.argument('admin_client_thumbprints', options_list=['--admin-client-thumbprints', '--admin-client-tps'], nargs='+', help='Space-separated list of client certificate thumbprint that only has admin permission, ')\n c.argument('certificate_issuer_thumbprint', options_list=['--certificate-issuer-thumbprint', '--cert-issuer-tp'], help='client certificate issuer thumbprint.')\n\n with self.argument_context('sf cluster certificate') as c:\n c.argument('thumbprint', help='The cluster certificate thumbprint to be removed')\n\n with self.argument_context('sf cluster client-certificate') as c:\n c.argument('is_admin', help='Client authentication type.')\n c.argument('certificate_issuer_thumbprint', options_list=['--certificate-issuer-thumbprint', '--cert-issuer-tp'], help='client certificate issuer thumbprint.')\n c.argument('certificate_common_name', options_list=['--certificate-common-name', '--cert-common-name'], help='client certificate common name.')\n c.argument('admin_client_thumbprints', options_list=['--admin-client-thumbprints', '--admin-client-tps'], nargs='+', help='client certificate thumbprint that only has admin permission.')\n c.argument('readonly_client_thumbprints', options_list=['--readonly-client-thumbprints', '--readonly-client-tps'], nargs='+', help='Space-separated list of client certificate thumbprint that has read only permission.')\n\n with self.argument_context('sf cluster client-certificate add') as c:\n c.argument('thumbprint', help='client certificate thumbprint.')\n\n with self.argument_context('sf cluster client-certificate remove') as c:\n c.argument('thumbprints', nargs='+', help='A single or Space-separated list of client certificate thumbprint(s) to be remove.')\n\n with self.argument_context('sf cluster node') as c:\n c.argument('number_of_nodes_to_add', options_list=['--number-of-nodes-to-add', '--nodes-to-add'], help='number of nodes to add.')\n c.argument('number_of_nodes_to_remove', options_list=['--number-of-nodes-to-remove', '--nodes-to-remove'], help='number of nodes to remove.')\n\n with self.argument_context('sf cluster node-type') as c:\n c.argument('capacity', help='The capacity tag applied to nodes in the node type. The cluster resource manager uses these tags to understand how much capacity a node has.')\n c.argument('vm_tier', help='VM tier.')\n\n with self.argument_context('sf cluster') as c:\n c.argument('durability_level', arg_type=get_enum_type(['Bronze', 'Silver', 'Gold']), help='durability level.')\n\n with self.argument_context('sf cluster setting') as c:\n c.argument('parameter', help='parameter name')\n c.argument('section', help='section name')\n c.argument('value', help='Specify the value')\n c.argument('settings_section_description', options_list=['--settings-section-description', '--settings-section'], help='Specify the value')\n\n with self.argument_context('sf cluster upgrade-type set') as c:\n c.argument('version', help='cluster code version')\n c.argument('upgrade_mode', arg_type=get_enum_type(['manual', 'automatic']), help='cluster upgrade mode')\n\n with self.argument_context('sf cluster reliability') as c:\n c.argument('reliability_level', arg_type=get_enum_type(['Bronze', 'Silver', 'Gold', 'Platinum']), help='durability level.')\n c.argument('auto_add_node', help='Add node count automatically when changing reliability.')\n\n with self.argument_context('sf cluster setting set') as c:\n c.argument('settings_section_description', options_list=['--settings-section-description', '--settings-section'], type=get_json_object,\n help='JSON encoded parameters configuration. Use @{file} to load from a file. '\n 'For example: [{\"section\": \"NamingService\",\"parameter\": \"MaxOperationTimeout\",\"value\": 1000},{\"section\": \"MaxFileOperationTimeout\",\"parameter\": \"Max2\",\"value\": 1000]')\n\n with self.argument_context('sf cluster setting remove') as c:\n c.argument('settings_section_description', options_list=['--settings-section-description', '--settings-section'], type=get_json_object,\n help='JSON encoded parameters configuration. Use @{file} to load from a file. '\n 'For example: [{\"section\": \"NamingService\",\"parameter\": \"MaxOperationTimeout\"}]')\n\n with self.argument_context('sf cluster client-certificate remove') as c:\n c.argument('client_certificate_common_names', options_list=['--client-certificate-common-names', '--client-cert-cn'], type=get_json_object,\n help='JSON encoded parameters configuration. Use @{file} to load from a file. '\n 'For example: [{\"certificateCommonName\": \"test.com\",\"certificateIssuerThumbprint\": \"22B4AE296B504E512DF880A77A2CAE20200FF922\"}]')\n\n with self.argument_context('sf cluster client-certificate add') as c:\n c.argument('client_certificate_common_names', options_list=['--client-certificate-common-names', '--client-cert-cn'], type=get_json_object,\n help='JSON encoded parameters configuration. Use @{file} to load from a file. '\n 'For example: [{\"isAdmin\":true, \"certificateCommonName\": \"test.com\", '\n '\"certificateIssuerThumbprint\": \"22B4AE296B504E512DF880A77A2CAE20200FF922\"}]')\n\n # application-type\n with self.argument_context('sf application-type') as c:\n c.argument('application_type_name', options_list=['--name', '--application-type-name'], help='Specify the application type name.')\n\n # application-type version\n with self.argument_context('sf application-type version') as c:\n c.argument('version', arg_type=application_type_version)\n c.argument('package_url', arg_type=package_url)\n\n # application\n with self.argument_context('sf application') as c:\n c.argument('application_name', options_list=['--name', '--application-name'], help='Specify the application name.')\n\n with self.argument_context('sf application update', validator=validate_update_application) as c:\n c.argument('application_type_version', arg_type=application_type_version)\n c.argument('application_parameters', arg_type=application_parameters)\n c.argument('minimum_nodes', arg_type=minimum_nodes)\n c.argument('maximum_nodes', arg_type=maximum_nodes)\n c.argument('force_restart', arg_type=get_three_state_flag(),\n help='Indicates that the service host restarts even if the upgrade is a configuration-only change.')\n c.argument('service_type_health_policy_map', options_list=['--service-type-health-policy-map', '--service-type-policy'],\n help='Specify the map of the health policy to use for different service types as a hash table in the following format: {\\\"ServiceTypeName\\\" : \\\"MaxPercentUnhealthyPartitionsPerService,MaxPercentUnhealthyReplicasPerPartition,MaxPercentUnhealthyServices\\\"}. For example: @{ \\\"ServiceTypeName01\\\" = \\\"5,10,5\\\"; \\\"ServiceTypeName02\\\" = \\\"5,5,5\\\" }')\n\n with self.argument_context('sf application update', arg_group='Upgrade description') as c:\n c.argument('upgrade_replica_set_check_timeout', options_list=['--upgrade-replica-set-check-timeout', '--replica-check-timeout', '--rep-check-timeout'],\n help='Specify the maximum time, in seconds, that Service Fabric waits for a service to reconfigure into a safe state, if not already in a safe state, before Service Fabric proceeds with the upgrade.')\n c.argument('failure_action', arg_type=get_enum_type(['Rollback', 'Manual']),\n help='Specify the action to take if the monitored upgrade fails. The acceptable values for this parameter are Rollback or Manual.')\n c.argument('health_check_retry_timeout', options_list=['--hc-retry-timeout', '--health-check-retry-timeout'],\n help='Specify the duration, in seconds, after which Service Fabric retries the health check if the previous health check fails.')\n c.argument('health_check_wait_duration', options_list=['--hc-wait-duration', '--health-check-wait-duration'],\n help='Specify the duration, in seconds, that Service Fabric waits before it performs the initial health check after it finishes the upgrade on the upgrade domain.')\n c.argument('health_check_stable_duration', options_list=['--hc-stable-duration', '--health-check-stable-duration'],\n help='Specify the duration, in seconds, that Service Fabric waits in order to verify that the application is stable before moving to the next upgrade domain or completing the upgrade. This wait duration prevents undetected changes of health right after the health check is performed.')\n c.argument('upgrade_domain_timeout', options_list=['--ud-timeout', '--upgrade-domain-timeout'],\n help='Specify the maximum time, in seconds, that Service Fabric takes to upgrade a single upgrade domain. After this period, the upgrade fails.')\n c.argument('upgrade_timeout',\n help='Specify the maximum time, in seconds, that Service Fabric takes for the entire upgrade. After this period, the upgrade fails.')\n c.argument('consider_warning_as_error', options_list=['--warning-as-error', '--consider-warning-as-error'], arg_type=get_three_state_flag(),\n help='Indicates whether to treat a warning health event as an error event during health evaluation.')\n c.argument('default_service_type_max_percent_unhealthy_partitions_per_service', options_list=['--max-porcent-unhealthy-partitions', '--max-unhealthy-parts'],\n help='Specify the maximum percent of unhelthy partitions per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.')\n c.argument('default_service_type_max_percent_unhealthy_replicas_per_partition', options_list=['--max-porcent-unhealthy-replicas', '--max-unhealthy-reps'],\n help='Specify the maximum percent of unhelthy replicas per service allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.')\n c.argument('default_service_type_max_percent_unhealthy_services', options_list=['--max-porcent-unhealthy-services', '--max-unhealthy-servs'],\n help='Specify the maximum percent of unhelthy services allowed by the health policy for the default service type to use for the monitored upgrade. Allowed values are form 0 to 100.')\n c.argument('max_percent_unhealthy_deployed_applications', options_list=['--max-porcent-unhealthy-apps', '--max-unhealthy-apps'],\n help='Specify the maximum percentage of the application instances deployed on the nodes in the cluster that have a health state of error before the application health state for the cluster is error. Allowed values are form 0 to 100.')\n\n with self.argument_context('sf application create', validator=validate_create_application) as c:\n c.argument('application_type_name', options_list=['--type-name', '--application-type-name'], help='Specify the application type name.')\n c.argument('application_type_version', arg_type=application_type_version)\n c.argument('package_url', arg_type=package_url)\n c.argument('application_parameters', arg_type=application_parameters)\n c.argument('minimum_nodes', arg_type=minimum_nodes)\n c.argument('maximum_nodes', arg_type=maximum_nodes)\n\n # service\n with self.argument_context('sf service') as c:\n c.argument('service_name', options_list=['--name', '--service-name'],\n help='Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName')\n\n with self.argument_context('sf service create', validator=validate_create_service) as c:\n c.argument('service_type',\n help='Specify the service type name of the application, it should exist in the application manifest.')\n c.argument('application_name', options_list=['--application', '--application-name'],\n help='Specify the name of the service. The application name must be a prefix of the service name, for example: appName~serviceName')\n c.argument('state', arg_type=get_enum_type(['stateless', 'stateful']), help='Specify if the service is stateless or stateful.')\n c.argument('instance_count', help='Specify the instance count for the stateless service. If -1 is used, it means it will run on all the nodes.')\n c.argument('min_replica_set_size', options_list=['--min-replica-set-size', '--min-replica'], help='Specify the min replica set size for the stateful service.')\n c.argument('target_replica_set_size', options_list=['--target-replica-set-size', '--target-replica'], help='Specify the target replica set size for the stateful service.')\n c.argument('default_move_cost', arg_type=get_enum_type(['Zero', 'Low', 'Medium', 'High']),\n help='Specify the default cost for a move. Higher costs make it less likely that the Cluster Resource Manager will move the replica when trying to balance the cluster.')\n c.argument('partition_scheme', arg_type=get_enum_type(['singleton', 'uniformInt64', 'named']),\n help='Specify what partition scheme to use. '\n 'Singleton partitions are typically used when the service does not require any additional routing. '\n 'UniformInt64 means that each partition owns a range of int64 keys. '\n 'Named is usually for services with data that can be bucketed, within a bounded set. Some common examples of data fields used as named partition keys would be regions, postal codes, customer groups, or other business boundaries.')\n\n # managed cluster\n\n with self.argument_context('sf managed-cluster create', validator=validate_create_managed_cluster) as c:\n c.argument('admin_password', help='Admin password used for the virtual machines.')\n c.argument('admin_user_name', help='Admin user used for the virtual machines.', default='vmadmin')\n c.argument('dns_name', help='Cluster\\'s dns name.')\n c.argument('sku', help='Cluster\\'s Sku, the options are Basic: it will have a minimum of 3 seed nodes and only allows 1 node type and Standard: it will have a minimum of 5 seed nodes and allows multiple node types.', default='Basic')\n c.argument('client_connection_port', options_list=['--client-connection-port', '--client-port'], help='Port used for client connections to the cluster.', default=19000)\n c.argument('gateway_connection_port', options_list=['--gateway-connection-port', '--gateway-port'], help='Port used for http connections to the cluster.', default=19080)\n c.argument('client_cert_is_admin', options_list=['--client-cert-is-admin', '--cert-is-admin'], arg_type=get_three_state_flag(), help='Client authentication type.')\n c.argument('client_cert_thumbprint', options_list=['--client-cert-thumbprint', '--cert-thumbprint'], help='Client certificate thumbprint.')\n c.argument('client_cert_common_name', options_list=['--client-cert-common-name', '--cert-common-name'], help='Client certificate common name.')\n c.argument('client_cert_issuer_thumbprint', options_list=['--client-cert-issuer-thumbprint', '--cert-issuer-thumbprint', '--cert-issuer-tp'], nargs='+', help='Space-separated list of issuer thumbprints.')\n c.argument('tags', arg_type=tags_type)\n\n with self.argument_context('sf managed-cluster update') as c:\n c.argument('client_connection_port', options_list=['--client-connection-port', '--client-port'], help='Port used for client connections to the cluster.')\n c.argument('gateway_connection_port', options_list=['--gateway-connection-port', '--gateway-port'], help='Port used for http connections to the cluster.')\n c.argument('dns_name', help='Cluster\\'s dns name')\n c.argument('tags', arg_type=tags_type)\n\n with self.argument_context('sf managed-cluster client-certificate add') as c:\n c.argument('is_admin', arg_type=get_three_state_flag(), help='Client authentication type.')\n c.argument('thumbprint', help='Client certificate thumbprint.')\n c.argument('common_name', help='Client certificate common name.')\n c.argument('issuer_thumbprint', nargs='+', help='Space-separated list of issuer thumbprints.')\n\n with self.argument_context('sf managed-cluster client-certificate delete') as c:\n c.argument('thumbprint', nargs='+', help='A single or Space-separated list of client certificate thumbprint(s) to be remove.')\n c.argument('common_name', nargs='+', help='A single or Space-separated list of client certificate common name(s) to be remove.')\n\n # managed node type\n\n capacity = CLIArgumentType(\n options_list=['--capacity'],\n action=AddNodeTypeCapacityAction,\n nargs='+',\n help='Capacity tags applied to the nodes in the node type as key/value pairs, the cluster resource manager uses these tags to understand how much resource a node has. Updating this will override the current values.'\n 'for example: --capacity ClientConnections=65536 param2=value2')\n\n placement_property = CLIArgumentType(\n options_list=['--placement-property'],\n action=AddNodeTypePlacementPropertyAction,\n nargs='+',\n help='Placement tags applied to nodes in the node type as key/value pairs, which can be used to indicate where certain services (workload) should run. Updating this will override the current values.'\n 'for example: --placement-property NodeColor=Green SomeProperty=5')\n\n with self.argument_context('sf managed-node-type') as c:\n c.argument('node_type_name', options_list=['-n', '--name', '--node-type-name'], help='node type name.')\n c.argument('instance_count', help='essage = \"The number of nodes in the node type.')\n c.argument('primary', arg_type=get_three_state_flag(), help='Specify if the node type is primary. On this node type will run system services. Only one node type should be marked as primary. Primary node type cannot be deleted or changed for existing clusters.')\n c.argument('disk_size', help='Disk size for each vm in the node type in GBs.', default=100)\n c.argument('application_start_port', options_list=['--application-start-port', '--app-start-port'], help='Application start port of a range of ports.')\n c.argument('application_end_port', options_list=['--application-end-port', '--app-end-port'], help='Application End port of a range of ports.')\n c.argument('ephemeral_start_port', help='Ephemeral start port of a range of ports.')\n c.argument('ephemeral_end_port', help='Ephemeral end port of a range of ports.')\n c.argument('vm_size', help='The size of virtual machines in the pool. All virtual machines in a pool are the same size.', default='Standard_D2')\n c.argument('vm_image_publisher', help='The publisher of the Azure Virtual Machines Marketplace image.', default='MicrosoftWindowsServer')\n c.argument('vm_image_offer', help='The offer type of the Azure Virtual Machines Marketplace image.', default='WindowsServer')\n c.argument('vm_image_sku', help='The SKU of the Azure Virtual Machines Marketplace image.', default='2019-Datacenter')\n c.argument('vm_image_version', help='The version of the Azure Virtual Machines Marketplace image. ', default='latest')\n c.argument('capacity', arg_type=capacity)\n c.argument('placement_property', arg_type=placement_property)\n\n with self.argument_context('sf managed-node-type node') as c:\n c.argument('node_name', nargs='+', help='list of target nodes to perform the operation.')\n c.argument('force', arg_type=get_three_state_flag(), help='Using this flag will force the operation even if service fabric is unable to disable the nodes. Use with caution as this might cause data loss if stateful workloads are running on the node.')\n\n with self.argument_context('sf managed-node-type vm-extension') as c:\n c.argument('extension_name', help='extension name.')\n c.argument('force_update_tag', help='If a value is provided and is different from the previous value, the extension handler will be forced to update even if the extension configuration has not changed.')\n c.argument('publisher', help='The name of the extension handler publisher.')\n c.argument('extension_type', help='Specifies the type of the extension; an example is \\\"CustomScriptExtension\\\".')\n c.argument('type_handler_version', help='Specifies the version of the script handler.')\n c.argument('auto_upgrade_minor_version', options_list=['--auto-upgrade-minor-version', '--auto-upgrade'], arg_type=get_three_state_flag(), help='Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true.')\n c.argument('setting', help='Json formatted public settings for the extension.')\n c.argument('protected_setting', help='The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all.')\n c.argument('provision_after_extension', options_list=['--provision-after-extension', '--provision-after'], help='Collection of extension names after which this extension needs to be provisioned.')\n\n with self.argument_context('sf managed-node-type vm-secret') as c:\n c.argument('source_vault_id', help='Key Vault resource id containing the certificates.')\n c.argument('certificate_url', help='This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8:

{
\\\"data\\\":\\\"\\\",
\\\"dataType\\\":\\\"pfx\\\",
\\\"password\\\":\\\"\\\"
}/')\n c.argument('certificate_store', help='Specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account.')\n\n\ndef paramToDictionary(values):\n params = {}\n for item in values:\n key, value = item.split('=', 1)\n params[key] = value\n return params\n\n\n# pylint: disable=protected-access\n# pylint: disable=too-few-public-methods\nclass AddAppParamsAction(argparse._AppendAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n try:\n namespace.application_parameters = paramToDictionary(values)\n except ValueError:\n raise CLIError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string))\n\n\nclass ManagedClusterClientCertAddAction(argparse._AppendAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n ClientCertificate = namespace._cmd.get_models('ClientCertificate')\n try:\n kwargs = paramToDictionary(values.split())\n return ClientCertificate(**kwargs)\n except ValueError:\n raise CLIError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string))\n\n\n# pylint: disable=protected-access\n# pylint: disable=too-few-public-methods\nclass AddNodeTypeCapacityAction(argparse._AppendAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n try:\n namespace.capacity = paramToDictionary(values)\n except ValueError:\n raise CLIError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string))\n\n\n# pylint: disable=protected-access\n# pylint: disable=too-few-public-methods\nclass AddNodeTypePlacementPropertyAction(argparse._AppendAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n try:\n namespace.placement_property = paramToDictionary(values)\n except ValueError:\n raise CLIError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string))\n","sub_path":"src/azure-cli/azure/cli/command_modules/servicefabric/_params.py","file_name":"_params.py","file_ext":"py","file_size_in_byte":30451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"111391613","text":"# -*- coding: utf-8 -*-\n\n\n'''\nReverse a linked list from position m to n. Do it in-place and in one-pass.\n\nFor example:\nGiven 1->2->3->4->5->NULL, m = 2 and n = 4,\n\nreturn 1->4->3->2->5->NULL.\n\nNote:\nGiven m, n satisfy the following condition:\n1 ≤ m ≤ n ≤ length of list.\n'''\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n dummy=ListNode(0)\n dummy.next=head\n end=start=startBefore=dummy\n for i in range(m):\n start=start.next\n for i in range(m-1):\n startBefore=startBefore.next\n for j in range(n):\n end=end.next\n startBefore.next=self.reverse(start,end)\n return dummy.next\n def reverse(self,head,tail):\n dummy=ListNode(0)\n dummy.next=head\n while dummy.next!=tail:\n tmp=head.next\n head.next=tmp.next\n tmp.next=dummy.next\n dummy.next=tmp\n return dummy.next\n","sub_path":"linked list/Reverse_Linked_List_II.py","file_name":"Reverse_Linked_List_II.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"4822406","text":"def test_checksum():\n from transformation_invariant_image_search import models, main\n app = main.create_app(db_uri='sqlite://')\n csm_value = '54abb6e1eb59cccf61ae356aff7e491894c5ca606dfda4240d86743424c65faf'\n with app.app_context():\n models.DB.create_all()\n m = models.Checksum(value=csm_value, ext='png')\n models.DB.session.add(m)\n models.DB.session.commit()\n assert m.id == 1\n\n res = models.DB.session.query(models.Checksum).filter_by(id=1).first()\n assert res.value == csm_value\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"95941222","text":"#!/usr/bin/env python\n\nimport argparse\n\n\nclass StepDimensionGenerator(object):\n\n CREATE_TEMPLATE = \"\"\"CREATE TABLE {} (\n {} int,\n total_steps int,\n this_step int,\n steps_remaining int);\\n\"\"\"\n\n INSERT_TEMPLATE = \"\"\"INSERT INTO step_dim (step_dim_key, total_steps, this_step, steps_remaining) VALUES ({}, {}, {}, {});\\n\"\"\"\n\n def __init__(self, max_steps, output_file, table_name, pk_column):\n self.max_steps = max_steps\n self.output_file = output_file\n self.table_name = table_name\n self.pk_column = pk_column\n\n def generate(self):\n\n create_statement = self.CREATE_TEMPLATE.format(self.table_name, self.pk_column)\n self.output_file.write(create_statement)\n\n row_key = 1\n inserts = []\n for session in range(self.max_steps + 1):\n for step in range(1, session + 1):\n inserts.append(\n self.INSERT_TEMPLATE.format(\n row_key, session, step, session - step\n )\n )\n row_key += 1\n\n for insert in inserts:\n self.output_file.write(insert)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n insert_group = parser.add_argument_group(\"Insert generation\")\n insert_group.add_argument('-s', '--steps', type=int, default=100,\n help=\"Number of steps in the biggest session.\")\n insert_group.add_argument('-o', '--output-file', type=argparse.FileType('w'),\n default='create_step_dimension.sql',\n help='Output destination for the CREATE/INSERT script.')\n\n create_group = parser.add_argument_group(\"Table creation\")\n create_group.add_argument('--table-name', default='step_dim',\n help='Name of the step dimension table.')\n create_group.add_argument('--primary-key-column', default=\"step_dim_key\",\n help='Namem of the primary key column.')\n\n args = parser.parse_args()\n StepDimensionGenerator(args.steps, args.output_file, args.table_name,\n args.primary_key_column).generate()\n","sub_path":"step_dimension.py","file_name":"step_dimension.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211658379","text":"import my_lib\r\nselect_challenge(\"repaired\")\r\nthink(0)\r\n\r\nclass TestRobot(RepairedRobot):\r\n def follow_left_wall(self):\r\n if self.left_is_clear():\r\n self.turn_left()\r\n self.move()\r\n elif self.front_is_clear():\r\n self.move()\r\n elif self.right_is_clear():\r\n self.turn_right()\r\n else:\r\n self.turn_around() \r\n\r\n def follow_right_wall(self):\r\n if self.right_is_clear():\r\n self.turn_right()\r\n self.move()\r\n elif self.front_is_clear():\r\n self.move()\r\n elif self.left_is_clear():\r\n self.turn_left()\r\n else:\r\n self.turn_around()\r\n\r\nreeborg = TestRobot(leaky=True)\r\n\r\n\r\nwhile not reeborg.token_here():\r\n reeborg.follow_left_wall()\r\n\r\nwhile not reeborg.object_here() == \"star\":\r\n reeborg.follow_right_wall()\r\nreeborg.turn_left()\r\n\r\nwhile not reeborg.object_here() == \"triangle\":\r\n reeborg.move()\r\n\r\nreeborg.move()\r\nreeborg.move()\r\nreeborg.face_east()\r\nreeborg.move()\r\nreeborg.face_west()\r\nreeborg.move()\r\nreeborg.move()\r\n\r\nwhile not reeborg.is_facing_south():\r\n reeborg.turn_left()\r\nreeborg.move()\r\nreeborg.turn_right()\r\n\r\nwhile not reeborg.object_here() == \"square\":\r\n reeborg.move()\r\n\r\nreeborg.face_north()\r\nwhile not reeborg.at_goal():\r\n reeborg.move()","sub_path":"test_robot.py","file_name":"test_robot.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"117519946","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n # Examples:\n # url(r'^$', 'parkcar.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n # url(r'^cekjumlah/', 'parkapp.views.number_of_parked_cars'),\n url(r'^park/', 'parkapp.views.park'),\n url(r'^unpark/', 'parkapp.views.unpark'),\n url(r'^get_car_information/', 'parkapp.views.get_car_information'),\n url(r'^get_slot_information/', 'parkapp.views.get_slot_information'),\n]\n","sub_path":"parkcar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"475547836","text":"#!/usr/local/bin/python3\nimport discord\nfrom discord.ext import commands\nimport asyncio\nimport configparser\nfrom functools import partial\nimport logging\nlogging.basicConfig(level=logging.INFO)\nprint = partial(print, flush=True)\n\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\ntry:\n token = config['Config']['token']\nexcept KeyError:\n print(\"Please assign your token in config.ini\")\n input()\nif token == \"\":\n print(\"Please assign your token in config.ini\")\n input()\ntry:\n snip = config['Config']['snip']\nexcept KeyError:\n print(\"Please assign your snip directory in config.ini\")\n input()\nif token == \"\":\n print(\"Please assign your token in config.ini\")\n input()\n\n# Set's bot's desciption and prefixes in a list\ndescription = \"\"\nbot = commands.Bot(command_prefix=['musicself.'], description=description, self_bot=True)\n\n###################\n## Startup Stuff ##\n###################\n\nbot.remove_command('help')\n\n@bot.event\nasync def on_ready():\n # Outputs login data to console\n print(\"---------------------------\")\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print(\"---------------------------\")\n savesong = \"_____________\"\n while True:\n song = pull_song()\n song = song[:song.rfind('[')-1]\n if savesong != song:\n savesong = song\n if song.strip() == '':\n await bot.change_presence(game=discord.Game())\n print(\"Stopped playing music.\")\n else:\n await bot.change_presence(game=discord.Game(name=song))\n print(\"Listening to: {}\".format(song))\n await asyncio.sleep(1)\n\n@bot.event\nasync def on_message(message):\n if message.content == \"!np\":\n song = pull_song()\n if song.strip() == '':\n await bot.send_message(message.channel, \"```css\\nNot listening to anything!```\")\n else:\n await bot.send_message(message.channel, \"```css\\nListening to: {}```\".format(song))\n yt_message = await bot.send_message(message.channel, \"~yt {}\".format(song))\n await bot.delete_message(yt_message)\n await bot.process_commands(message)\n\ndef pull_song():\n # $if(%ispaused%,,\n # $if(%artist%,%artist% - ,$if(%album%,%album% - ))\n # %title%\n # )\n file = open(snip, encoding=\"utf8\")\n song = file.read()\n return song\n\n##############################\n## FANCY TOKEN LOGIN STUFFS ##\n##############################\n\ntry:\n bot.run(token, bot=False)\nexcept discord.errors.LoginFailure:\n print(\"Invalid token\")\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"166065356","text":"\n\"\"\"\nTests github api helper\n\"\"\"\n\nimport os\nfrom git_api_tries import github_api_calls\nimport json\n\n\n#TOKEN = os.getenv(\"GITHUB_TOKEN\")\nTOKEN='38bdfcb675dc130b977824f008b4379753ab34f8'\n#USER = os.getenv(\"GITHUB_USER\")\nUSER='Anastasiia-Khab'\nGITHUB_ORG = \"Lv-323python\"\nCLIENT = github_api_calls.Client(api_user=USER, api_token=TOKEN, org=GITHUB_ORG)\nCLIENT2 = github_api_calls.Client(api_user=USER, api_token=TOKEN)\n\n#print(CLIENT.get_repos(\"learnRepo\"))'\nprint('\\n____________________________________\\n')\nprint(CLIENT2.get_user())\n#print(CLIENT.get_org_members())\n#print(CLIENT.owner)\n#print(CLIENT2.owner)\n#print(CLIENT.get_repo('learnRepo')['created_at'])\n\n#print(type(CLIENT.get_repo('learnRepo')))\n#print(type(CLIENT.get_repo('learnRepo')['id']))\n\n#print(type(CLIENT.get_commits('learnRepo')))\n#print(CLIENT.get_commits('learnRepo'))\n\nresponse=CLIENT.get_repo('learnRepo')\nresult=[]\nresult.append({'id':response['id'],\n 'reponame':response['name'],\n 'datecreated':response['created_at'],\n 'owner':response['owner']['login'],\n 'url':response['url']})\nprint(json.dumps(result))\n\nprint('/n____________________________________________________/n')\nimport requests\nresponse=requests.get('https://api.github.com/repos/Lv-323python/learnRepo/commits').json()\nresult=[]\nfor commit in response:\n result.append({'hash': commit['sha'],\n 'author': commit['commit']['author']['name'],\n 'message': commit['commit']['message'],\n 'date': 0})\nprint(result)\n\n#print(json.dumps(response))\n\n\n\n\n\n","sub_path":"git_api_tries/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"585590164","text":"#!/usr/bin/python3\nimport sys\nimport os\n\nif \"SOFA_ROOT\" not in os.environ:\n print(\"WARNING: missing SOFA_ROOT in you environment variable. \") \n sys.exit(-1)\n\nsys.path.append(os.path.abspath(\"./bindings/Sofa/package\"))\nsys.path.append(os.path.abspath(\"./bindings/SofaRuntime/package\"))\nsys.path.append(os.path.abspath(\"./bindings/SofaTypes/package\"))\n\nimport Sofa\nimport SofaRuntime\n\n## Register all the common component in the factory. \n#SofaRuntime.importPlugin(\"SofaPython3\")\nSofaRuntime.importPlugin(\"SofaAllCommonComponents\")\n\nif len(sys.argv) != 2:\n print(\"USAGE: python3 runSimu.py scene.py\")\n sys.exit(-1)\n\n## Init the simulation singleton. \nSofaRuntime.reinit()\nc=SofaRuntime.load(sys.argv[1])\nprint(\"COUCOU2 \"+c)\n#SofaRuntime.getSimulation().init(rootNode)\n\n \n \n \n","sub_path":"runSimu.py","file_name":"runSimu.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"249106855","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC COPYRIGHT: Columbia Sportswear 2018
\n# MAGIC DESCRIPTION: This Notebook loads Staging Foundation Country look up table and writeit down to adw for Reporting\n# MAGIC \n# MAGIC -----------------------------------------------------------------\n# MAGIC ###### MODIFICATION LOG\n# MAGIC | Programmmer | Change Request | Date | Change Description |\n# MAGIC |----------------------|-----------------|------------|--------------------------------------------------------------------|\n# MAGIC | Sasi Nagireddy | Teradata Decommission | 08/01/2018 | Initial Deployment |\n# MAGIC \n# MAGIC \n\n# COMMAND ----------\n\ndbutils.widgets.text(\"schmNm\", \"\", \"\")\ndbutils.widgets.text(\"tblNm\", \"\", \"\")\n\ndbutils.widgets.text(\"deltaTS\", \"\", \"\")\ndbutils.widgets.text(\"initFlg\", \"\", \"\")\n\n\ndbutils.widgets.get(\"deltaTS\")\ndeltaTS = getArgument(\"deltaTS\")\n\ndbutils.widgets.get(\"initFlg\")\ninitFlg = getArgument(\"initFlg\")\n\ndbutils.widgets.get(\"schmNm\")\nschmNm = getArgument(\"schmNm\")\n\ndbutils.widgets.get(\"tblNm\")\ntblNm = getArgument(\"tblNm\")\n\n#Update the Timestamp to remove T\ndeltaTS = deltaTS.replace('T',' ')\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE DATABASE IF NOT EXISTS ENTPR_FOUNDATION\n# MAGIC location '/mnt/entadls/published/eim/managed/entpr_foundation';\n# MAGIC \n# MAGIC CREATE TABLE IF NOT EXISTS ENTPR_FOUNDATION.CTRY_LKUP\n# MAGIC (\n# MAGIC \tCTRY_ALPHA2_CD string,\n# MAGIC \tCTRY_ALPHA3_CD string,\n# MAGIC \tCTRY_NM string,\n# MAGIC \tEDW_CRT_TS timestamp,\n# MAGIC \tEDW_UPDT_TS timestamp,\n# MAGIC \tEDW_HASH_CHK string,\n# MAGIC EDW_ACTV_FLG string\n# MAGIC )\n# MAGIC USING DELTA\n# MAGIC --PARTITIONED BY (Field list)\n# MAGIC LOCATION '/mnt/entadls/published/eim/managed/entpr_foundation/ctry_lkup';\n\n# COMMAND ----------\n\n#Truncate working from 4.8\nif initFlg == \"X\" :\n\n truncateTable = \"TRUNCATE TABLE {0}.{1}\".format(schmNm, tblNm)\n spark.sql(truncateTable)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ###### Ctry_lkup STG notebook for Databricks staging and writing to Azure Datawarehouse\n\n# COMMAND ----------\n\n#%sql\nsqlQuery = \"\"\"CREATE OR REPLACE TEMPORARY VIEW src_delta_ctry AS\n select t5.land1 AS CTRY_ALPHA2_CD\n, t5.intca3 AS CTRY_ALPHA3_CD , t5t.landx50 AS CTRY_NM \nfrom EDW_LND_SAP_VIEW.t005 t5 left outer join EDW_LND_SAP_VIEW.t005t t5t on t5.land1=t5t.land1 and t5t.spras='E'\"\"\"\n #WHERE EDW_UPDT_TS >= '{0}'\"\"\".format(deltaTS)\nspark.sql(sqlQuery)\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE TEMPORARY VIEW src_ctry_lkup\n# MAGIC AS\n# MAGIC SELECT\n# MAGIC CTRY_ALPHA2_CD\n# MAGIC ,CTRY_ALPHA3_CD\n# MAGIC ,CTRY_NM\n# MAGIC ,'Y' AS EDW_ACTV_FLG\n# MAGIC ,MD5(CTRY_ALPHA3_CD||CTRY_NM) AS EDW_HASH_CHK\n# MAGIC from src_delta_ctry \n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ctry_lkup\n# MAGIC AS\n# MAGIC Select \n# MAGIC s.CTRY_ALPHA2_CD \n# MAGIC ,s.CTRY_ALPHA3_CD \n# MAGIC ,s.CTRY_NM \n# MAGIC ,current_timestamp AS EDW_CRT_TS\n# MAGIC ,current_timestamp AS EDW_UPDT_TS\n# MAGIC ,CAST(NULL AS STRING) AS EDW_ROW_CHKSUM\n# MAGIC ,s.EDW_HASH_CHK \n# MAGIC ,s.EDW_ACTV_FLG \n# MAGIC \n# MAGIC from src_ctry_lkup s\n# MAGIC \n# MAGIC UNION\n# MAGIC \n# MAGIC SELECT\n# MAGIC tgt.CTRY_ALPHA2_CD \n# MAGIC ,tgt.CTRY_ALPHA3_CD \n# MAGIC ,tgt.CTRY_NM \n# MAGIC ,current_timestamp AS EDW_CRT_TS\n# MAGIC ,current_timestamp AS EDW_UPDT_TS\n# MAGIC ,CAST(NULL AS STRING) AS EDW_ROW_CHKSUM\n# MAGIC ,tgt.EDW_HASH_CHK \n# MAGIC ,'N' AS EDW_ACTV_FLG \n# MAGIC from ENTPR_FOUNDATION.CTRY_LKUP tgt\n# MAGIC LEFT JOIN src_ctry_lkup src\n# MAGIC ON tgt.CTRY_ALPHA2_CD = src.CTRY_ALPHA2_CD \n# MAGIC WHERE src.CTRY_ALPHA2_CD IS NULL\n# MAGIC ;\n# MAGIC --By default table gets created in global_temp database.\n# MAGIC -- To query the global temp table. Ex:Select * from global_temp.ctry_lkup\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC --Merge upsert to Staging table.\n# MAGIC MERGE INTO ENTPR_FOUNDATION.CTRY_LKUP tgt\n# MAGIC USING global_temp.ctry_lkup dlta\n# MAGIC ON tgt.CTRY_ALPHA2_CD = dlta.CTRY_ALPHA2_CD\n# MAGIC WHEN MATCHED THEN\n# MAGIC UPDATE SET\n# MAGIC tgt.CTRY_ALPHA2_CD = dlta.CTRY_ALPHA2_CD \n# MAGIC ,tgt.CTRY_ALPHA3_CD = dlta.CTRY_ALPHA3_CD \n# MAGIC ,tgt.CTRY_NM = dlta.CTRY_NM \n# MAGIC ,tgt.EDW_UPDT_TS = CURRENT_TIMESTAMP \n# MAGIC ,tgt.EDW_HASH_CHK = dlta.EDW_HASH_CHK\n# MAGIC ,tgt.EDW_ACTV_FLG = dlta.EDW_ACTV_FLG\n# MAGIC WHEN NOT MATCHED \n# MAGIC THEN INSERT\n# MAGIC (\n# MAGIC CTRY_ALPHA2_CD \n# MAGIC ,CTRY_ALPHA3_CD \n# MAGIC ,CTRY_NM \n# MAGIC ,EDW_CRT_TS \n# MAGIC ,EDW_UPDT_TS \n# MAGIC ,EDW_HASH_CHK \n# MAGIC ,EDW_ACTV_FLG\n# MAGIC )\n# MAGIC VALUES\n# MAGIC (\n# MAGIC dlta.CTRY_ALPHA2_CD \n# MAGIC ,dlta.CTRY_ALPHA3_CD \n# MAGIC ,dlta.CTRY_NM \n# MAGIC ,current_timestamp\n# MAGIC ,current_timestamp \n# MAGIC ,dlta.EDW_HASH_CHK\n# MAGIC ,dlta.EDW_ACTV_FLG\n# MAGIC );\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE DATABASE IF NOT EXISTS ENTPR_FOUNDATION_VIEW;\n# MAGIC CREATE OR REPLACE VIEW ENTPR_FOUNDATION_VIEW.CTRY_LKUP \n# MAGIC AS\n# MAGIC SELECT\n# MAGIC CTRY_ALPHA2_CD \n# MAGIC ,CTRY_ALPHA3_CD \n# MAGIC ,CTRY_NM \n# MAGIC ,EDW_CRT_TS \n# MAGIC ,EDW_UPDT_TS \n# MAGIC ,EDW_HASH_CHK \n# MAGIC \n# MAGIC FROM \n# MAGIC (SELECT\n# MAGIC CTRY_ALPHA2_CD \n# MAGIC ,CTRY_ALPHA3_CD \n# MAGIC ,CTRY_NM \n# MAGIC ,EDW_CRT_TS \n# MAGIC ,EDW_UPDT_TS \n# MAGIC ,EDW_HASH_CHK \n# MAGIC ,EDW_ACTV_FLG\n# MAGIC FROM ENTPR_FOUNDATION.CTRY_LKUP\n# MAGIC )Flg\n# MAGIC WHERE Flg.EDW_ACTV_FLG='Y'\n# MAGIC \n\n# COMMAND ----------\n\n#all those notebooks that should write to Azure datawarehouse should include the below code.\n#schemaNm = landing schema in Azure datawarehouse.Schema will gets created if not exists. Naming Standard: DatabaseName_LND \n#Ex: ENTPR_PRODUCT_LND, ENTPR_CUSTOMER_LND, ENTPR_RETAIL_LND..\n#tableNm = This is the datawarehouse table name \n#dbrxTable = This is the databricks global table name\n# To view the processing of this reusable notebook, click on the notebook job(below in blue) while or after execution. \ndbutils.notebook.run(\"/Users/svceimdbrx@columbia.com/edw_admin/adw_integration_write\", 120, {\"schemaNm\": \"ENTPR_FOUNDATION_LND\", \"tableNm\": \"CTRY_LKUP\", \"dbrxTable\": \"ctry_lkup\", \"writeMode\": \"overwrite\"})\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC DROP VIEW IF EXISTS global_temp.CTRY_LKUP\n","sub_path":"Prod/entpr_foundation/ctry_lkup.py","file_name":"ctry_lkup.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"109352023","text":"\"\"\"Author: Gina Chatzimarkaki\"\"\"\n\n#test-calculator-multiply.py\ndef handle(str):\n \"\"\"\n Multiple two numbers and return the result. If there are more\n just take the first two\n\n Parameters\n ----------\n str : String\n the provided input\n\n Returns\n -------\n int\n the 2 numbers multiplied\n \"\"\"\n try:\n numbers = str.strip().split()\n\n if len(numbers) == 2:\n print( float(numbers[0]) * float(numbers[1]) )\n else:\n print(\"*** Need two values got\", len(numbers))\n\n except ValueError as v:\n print(\"*** Value Error: \", v)\n except Exception as x:\n print(\"*** Error: \", x)\n","sub_path":"functions/calculator/multiply/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"375182802","text":"import sys\nreload(sys)\nsys.setdefaultencoding('UTF8')\nimport socket\nimport re\nimport logging\nimport json\nfrom netaddr import IPAddress, IPNetwork\nimport argparse\nfrom cStringIO import StringIO\nimport cgitb\n\nimport kazoo.client\nimport kazoo.exceptions\nimport cfgm_common\nfrom cfgm_common.ifmap.client import client, namespaces\nfrom cfgm_common.ifmap.request import NewSessionRequest\nfrom cfgm_common.ifmap.response import Response, newSessionResult\nfrom cfgm_common.imid import ifmap_read_all, parse_search_result\nimport pycassa\nimport utils\n\nimport vnc_cfg_ifmap\nfrom schema_transformer import to_bgp\nfrom discovery import disc_cassdb\n\nMAX_COL = 10000000\nclass DatabaseChecker(object):\n def __init__(self, args_str):\n self._parse_args(args_str)\n\n self._logger = utils.ColorLog(logging.getLogger(__name__))\n log_level = 'ERROR'\n if self._args.verbose:\n log_level = 'INFO'\n if self._args.debug:\n log_level = 'DEBUG'\n self._logger.setLevel(log_level)\n logformat = logging.Formatter(\"%(levelname)s: %(message)s\")\n stdout = logging.StreamHandler()\n stdout.setLevel(log_level)\n stdout.setFormatter(logformat)\n self._logger.addHandler(stdout)\n\n # cassandra connection\n self._cassandra_servers = self._api_args.cassandra_server_list\n db_info = vnc_cfg_ifmap.VncServerCassandraClient.get_db_info()\n rd_consistency = pycassa.cassandra.ttypes.ConsistencyLevel.QUORUM\n self._cf_dict = {}\n for ks_name, cf_name_list in db_info:\n pool = pycassa.ConnectionPool(keyspace=ks_name,\n server_list=self._cassandra_servers, prefill=False)\n for cf_name in cf_name_list:\n self._cf_dict[cf_name] = pycassa.ColumnFamily(pool, cf_name,\n read_consistency_level=rd_consistency)\n\n # ifmap connection\n self._connect_to_ifmap_servers()\n # end __init__\n\n def _parse_args(self, args_str):\n parser = argparse.ArgumentParser()\n\n help=\"Path to contrail-api conf file, default /etc/contrail-api.conf\"\n parser.add_argument(\n \"--api-conf\", help=help, default=\"/etc/contrail/contrail-api.conf\")\n parser.add_argument(\n \"--verbose\", help=\"Run in verbose/INFO mode, default False\",\n action='store_true', default=False)\n parser.add_argument(\n \"--debug\", help=\"Run in debug mode, default False\",\n action='store_true', default=False)\n parser.add_argument(\n \"--ifmap-servers\",\n help=\"List of ifmap-ip:ifmap-port, default from api-conf\")\n parser.add_argument(\n \"--ifmap-credentials\",\n help=\": for read-only user\",\n required=True)\n\n args_obj, remaining_argv = parser.parse_known_args(args_str.split())\n self._args = args_obj\n\n self._api_args = utils.parse_args('-c %s %s'\n %(self._args.api_conf, ' '.join(remaining_argv)))[0]\n # end _parse_args\n\n def checker(func):\n def wrapper(*args, **kwargs):\n self = args[0]\n try:\n ok, msg = func(*args, **kwargs)\n if ok:\n self._logger.info('Checker %s: Success' %(func.__name__))\n else:\n self._logger.error('Checker %s: Failed, %s' %(func.__name__, msg))\n\n return ok, msg\n except Exception as e:\n string_buf = StringIO()\n cgitb.Hook(\n file=string_buf,\n format=\"text\",\n ).handle(sys.exc_info())\n err_msg = string_buf.getvalue()\n self._logger.exception('Checker %s: Exception, %s' %(func.__name__, err_msg))\n\n # end wrapper\n\n return wrapper\n # end checker\n\n @checker\n def check_zk_mode_and_node_count(self):\n ret_ok = True\n ret_msg = ''\n stats = {}\n modes = {}\n modes['leader'] = 0\n modes['follower'] = 0\n modes['standalone'] = 0\n # Collect stats\n for server in self._api_args.zk_server_ip.split(','):\n zk_client = kazoo.client.KazooClient(server)\n zk_client.start()\n self._logger.debug(\"Issuing 'stat' on %s: \", server)\n stat_out = zk_client.command('stat')\n self._logger.debug(\"Got: %s\" %(stat_out))\n zk_client.stop()\n stats[server] = stat_out\n\n # Check mode\n for stat_out in stats.values():\n mode = re.search('Mode:(.*)\\n', stat_out).group(1).strip()\n modes[mode] += 1\n n_zk_servers = len(self._api_args.zk_server_ip.split(','))\n if n_zk_servers == 1:\n # good-case: 1 node in standalone\n if not modes['standalone'] == 1:\n ret_ok = False\n ret_msg += \"Error, Single zookeeper node and modes %s.\\n\" \\\n %(str(modes))\n else:\n # good-case: 1 node in leader, >=1 in followers\n if (modes['leader'] == 1) and (modes['follower'] >= 1):\n pass # ok\n else:\n ret_ok = False\n ret_msg += \"Error, Incorrect modes %s.\\n\" %(str(modes))\n\n # Check node count\n node_counts = []\n for stat_out in stats.values():\n nc = int(re.search('Node count:(.*)\\n', stat_out).group(1))\n node_counts.append(nc)\n # all nodes should have same count, so set should have 1 elem\n if len(set(node_counts)) != 1:\n ret_ok = False\n ret_msg += \"Error, Differing node counts %s.\\n\" %(str(node_counts))\n\n return ret_ok, ret_msg\n # end check_zk_mode_and_node_count\n\n @checker\n def check_cassandra_keyspace_replication(self):\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n for server in self._cassandra_servers:\n sys_mgr = pycassa.SystemManager(server)\n db_info = vnc_cfg_ifmap.VncCassandraClient.get_db_info() + \\\n to_bgp.SchemaTransformer.get_db_info() + \\\n disc_cassdb.DiscoveryCassandraClient.get_db_info()\n for ks_name, _ in db_info:\n logger.debug(\"Reading keyspace properties for %s on %s: \",\n ks_name, server)\n ks_prop = sys_mgr.get_keyspace_properties(ks_name)\n logger.debug(\"Got %s\", ks_prop)\n\n repl_factor = int(ks_prop['strategy_options']['replication_factor'])\n if (repl_factor != len(self._cassandra_servers)):\n errmsg = 'Incorrect replication factor %d for keyspace %s' \\\n %(repl_factor, ks_name)\n ret_msg += \"Error, %s.\\n\" %(errmsg)\n\n return ret_ok, ret_msg\n # end check_cassandra_keyspace_replication\n\n @checker\n def check_rabbitmq_queue(self):\n ret_ok = True\n ret_msg = ''\n\n return ret_ok, ret_msg\n # end check_rabbitmq_queue\n\n @checker\n def check_fq_name_uuid_ifmap_match(self):\n # ensure items in obj-fq-name-table match to\n # a. obj-uuid-table, b. local ifmap server\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n obj_fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n fq_name_table_all = []\n logger.debug(\"Reading all objects from obj_fq_name_table\")\n for obj_type, cols in obj_fq_name_table.get_range(column_count=MAX_COL):\n for fq_name_str_uuid in cols:\n fq_name_str = ':'.join(fq_name_str_uuid.split(':')[:-1])\n fq_name_str = cfgm_common.utils.decode_string(fq_name_str)\n obj_uuid = fq_name_str_uuid.split(':')[-1]\n fq_name_table_all.append((obj_type, fq_name_str, obj_uuid))\n try:\n obj_cols = obj_uuid_table.get(obj_uuid, column_count=MAX_COL)\n obj_fq_name_str = ':'.join(json.loads(obj_cols['fq_name']))\n if fq_name_str != obj_fq_name_str:\n ret_ok = False\n ret_msg += 'Error, Mismatched FQ Name %s vs %s.\\n' \\\n %(fq_name_str, obj_fq_name_str)\n except pycassa.NotFoundException:\n ret_ok = False\n ret_msg += 'Error, Missing object %s %s %s in uuid table.\\n'\\\n %(obj_uuid, obj_type, fq_name_str)\n # end for all objects in a type\n # end for all obj types\n logger.debug(\"Got %d objects\", len(fq_name_table_all))\n\n uuid_table_all = []\n logger.debug(\"Reading all objects from obj_uuid_table\")\n for obj_uuid, cols in obj_uuid_table.get_range(column_count=MAX_COL):\n obj_type = json.loads(cols['type'])\n fq_name_str = ':'.join(json.loads(cols['fq_name']))\n uuid_table_all.append((obj_type, fq_name_str, obj_uuid))\n\n logger.debug(\"Got %d objects\", len(uuid_table_all))\n\n for extra in set(fq_name_table_all) - set(uuid_table_all):\n obj_type, fq_name_str, obj_uuid = extra\n ret_ok = False\n ret_msg += 'Error, Extra object %s %s %s in obj_fq_name_table.\\n' \\\n %(obj_type, fq_name_str, obj_uuid)\n\n for extra in set(uuid_table_all) - set(fq_name_table_all):\n obj_type, fq_name_str, obj_uuid = extra\n ret_ok = False\n ret_msg += 'Error, Extra object %s %s %s in obj_uuid_table.\\n' \\\n %(obj_type, fq_name_str, obj_uuid)\n\n for mapclient in self._mapclients:\n search_results = parse_search_result(ifmap_read_all(mapclient))\n # parse_search_result returns in form of\n # [ ({'config-root': 'root'}, )\n # ({'config-root': 'root',\n # 'global-system-config': 'default-global-system-config'},\n # ) ]\n # convert it into set of identifiers\n all_ifmap_idents = []\n for ident_s, meta in search_results:\n # ref to same type appears as list of idents\n # flatten so set can be used\n for ident in ident_s.values():\n if type(ident) == list:\n all_ifmap_idents.extend(ident)\n else:\n all_ifmap_idents.append(ident)\n\n all_ifmap_idents = set(all_ifmap_idents)\n all_cassandra_idents = set([item[1] for item in fq_name_table_all])\n logger.debug(\"Got %d idents from %s server\",\n len(all_ifmap_idents), mapclient._client__url)\n\n extra = all_ifmap_idents - all_cassandra_idents\n if (len(extra) == 1) and (extra == set(['root'])):\n pass # good\n else:\n ret_ok = False\n ret_msg += 'Error, Extra identifiers %s in ifmap %s vs obj_fq_name_table.\\n' \\\n %(extra, mapclient._client__url)\n extra = all_cassandra_idents - all_ifmap_idents\n if extra:\n ret_ok = False\n ret_msg += 'Error, Missing identifiers %s in ifmap %s vs obj_fq_name_table.\\n' \\\n %(extra, mapclient._client__url)\n\n\n return ret_ok, ret_msg\n # end check_fq_name_uuid_ifmap_match\n\n @checker\n def check_obj_mandatory_fields(self):\n # ensure fq_name, type, uuid etc. exist\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n logger.debug(\"Reading all objects from obj_uuid_table\")\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n num_objs = 0\n num_bad_objs = 0\n for obj_uuid, cols in obj_uuid_table.get_range(column_count=MAX_COL):\n num_objs += 1\n reqd_col_names = ['type', 'fq_name', 'prop:id_perms']\n for col_name in reqd_col_names:\n if col_name in cols:\n continue\n num_bad_objs += 1\n ret_ok = False\n ret_msg += 'Error, obj %s missing column %s.\\n' \\\n %(obj_uuid, col_name)\n\n logger.debug(\"Got %d objects %d with missing mandatory fields\",\n num_objs, num_bad_objs)\n\n return ret_ok, ret_msg\n # end check_obj_mandatory_fields\n\n @checker\n def check_subnet_uuid(self):\n # whether useragent subnet uuid and uuid in subnet property match\n ret_ok = True\n ret_msg = ''\n\n # check in useragent table whether net-id subnet -> subnet-uuid\n # and vice-versa exist for all subnets\n ua_kv_cf = self._cf_dict['useragent_keyval_table']\n ua_all_subnet_uuids = []\n for key, cols in ua_kv_cf.get_range():\n mch = re.match('(.* .*/.*)', key)\n if mch: # subnet key -> uuid\n subnet_key = mch.group(1)\n subnet_id = cols['value']\n try:\n rev_map = ua_kv_cf.get(subnet_id)\n except pycassa.NotFoundException:\n ret_ok = False\n errmsg = \"Mismatch no subnet id %s for %s in useragent\" \\\n %(subnet_id, subnet_key)\n ret_msg += \"Error, %s.\\n\" %(errmsg)\n else: # uuid -> subnet key\n subnet_id = key\n subnet_key = cols['value']\n ua_all_subnet_uuids.append(subnet_id)\n try:\n rev_map = ua_kv_cf.get(subnet_key)\n except pycassa.NotFoundException:\n ret_ok = False\n errmsg = \"Mismatch no subnet key %s for %s in useragent\" \\\n %(subnet_id, subnet_key)\n ret_msg += \"Error, %s\\n\" %(errmsg)\n\n # check all subnet prop in obj_uuid_table to see if subnet-uuid exists\n vnc_all_subnet_uuids = []\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n vn_row = fq_name_table.get('virtual_network', column_count=MAX_COL)\n vn_uuids = [x.split(':')[-1] for x in vn_row]\n for vn_id in vn_uuids:\n try:\n ipam_refs = obj_uuid_table.get(vn_id,\n column_start='ref:network_ipam:',\n column_finish='ref:network_ipam;',\n column_count=MAX_COL)\n except pycassa.NotFoundException:\n continue\n\n for ipam in ipam_refs:\n ipam_col = obj_uuid_table.get(vn_id,\n columns=[ipam], column_count=MAX_COL)\n attr_dict = json.loads(ipam_col[ipam])['attr']\n for subnet in attr_dict['ipam_subnets']:\n try:\n sn_id = subnet['subnet_uuid']\n vnc_all_subnet_uuids.append(sn_id)\n except KeyError:\n ret_ok = False\n errmsg = \"Missing subnet uuid in vnc for %s %s\" \\\n %(vn_id, subnet['subnet']['ip_prefix'])\n ret_msg += \"Error, %s.\\n\" %(errmsg)\n\n # check #subnets in useragent table vs #subnets in obj_uuid_table\n if len(ua_all_subnet_uuids) != len(vnc_all_subnet_uuids):\n ret_ok = False\n ret_msg += \"Error, Mismatch #subnets usergent %d #subnets vnc %d.\\n\" \\\n %(len(ua_all_subnet_uuids), len(vnc_all_subnet_uuids))\n\n # check if subnet-uuids match in useragent table vs obj_uuid_table\n extra_ua_subnets = set(ua_all_subnet_uuids) - set(vnc_all_subnet_uuids)\n if extra_ua_subnets:\n ret_ok = False\n ret_msg += \"Error, Extra useragent subnets %s.\\n\" \\\n %(str(extra_ua_subnets))\n extra_vnc_subnets = set(vnc_all_subnet_uuids) - set(ua_all_subnet_uuids)\n if extra_vnc_subnets:\n ret_ok = False\n ret_msg += \"Error, Extra vnc subnets %s.\\n\" \\\n %(str(extra_vnc_subnets))\n\n return ret_ok, ret_msg\n # end check_subnet_uuid\n\n @checker\n def check_subnet_addr_alloc(self):\n # whether ip allocated in subnet in zk match iip+fip in cassandra\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n zk_server = self._api_args.zk_server_ip.split(',')[0]\n zk_client = kazoo.client.KazooClient(zk_server)\n zk_client.start()\n zk_all_vns = {}\n base_path = '/api-server/subnets'\n logger.debug(\"Doing recursive read from %s from %s\",\n base_path, zk_server)\n num_addrs = 0\n subnets = []\n try:\n subnets = zk_client.get_children(base_path)\n except kazoo.exceptions.NoNodeError:\n pass\n for subnet in subnets:\n vn_fq_name_str = ':'.join(subnet.split(':')[:-1])\n pfx = subnet.split(':')[-1]\n zk_all_vns[vn_fq_name_str] = {}\n pfxlen_path = base_path + '/' + subnet\n pfxlen = zk_client.get_children(pfxlen_path)\n if not pfxlen:\n continue\n subnet_key = '%s/%s' %(pfx, pfxlen[0])\n zk_all_vns[vn_fq_name_str][subnet_key] = []\n addrs = zk_client.get_children(pfxlen_path+'/'+pfxlen[0])\n if not addrs:\n continue\n zk_all_vns[vn_fq_name_str][subnet_key] = \\\n [str(IPAddress(int(addr))) for addr in addrs]\n num_addrs += len(zk_all_vns[vn_fq_name_str])\n # end for all subnet paths\n zk_client.stop()\n logger.debug(\"Got %d networks %d addresses\",\n len(zk_all_vns), num_addrs)\n\n logger.debug(\"Reading instance/floating-ip objects from cassandra\")\n cassandra_all_vns = {}\n num_addrs = 0\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n try:\n iip_row = fq_name_table.get('instance_ip', column_count=MAX_COL)\n except pycassa.NotFoundException:\n iip_row = []\n iip_uuids = [x.split(':')[-1] for x in iip_row]\n ok, msg = self._addr_alloc_process_ip_objects(cassandra_all_vns,\n 'instance-ip', iip_uuids)\n if not ok:\n ret_ok = False\n ret_msg += msg\n\n num_addrs += len(iip_uuids)\n\n try:\n fip_row = fq_name_table.get('floating_ip', column_count=MAX_COL)\n except pycassa.NotFoundException:\n fip_row = []\n\n fip_uuids = [x.split(':')[-1] for x in fip_row]\n ok, msg = self._addr_alloc_process_ip_objects(cassandra_all_vns,\n 'floating-ip', fip_uuids)\n if not ok:\n ret_ok = False\n ret_msg += msg\n\n num_addrs += len(fip_uuids)\n\n logger.debug(\"Got %d networks %d addresses\", \n len(cassandra_all_vns), num_addrs)\n\n # check for differences in networks\n extra_vn = set(zk_all_vns.keys()) - set(cassandra_all_vns.keys())\n if extra_vn:\n ret_ok = False\n errmsg = 'Extra VN in zookeeper for %s' %(str(extra_vn))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n extra_vn = set(cassandra_all_vns.keys()) - set(zk_all_vns.keys())\n if extra_vn:\n ret_ok = False\n errmsg = 'Extra VN in cassandra for %s' %(str(extra_vn))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n # check for differences in subnets\n zk_all_vn_sn = []\n for vn_key, vn in zk_all_vns.items():\n zk_all_vn_sn.extend([(vn_key, sn_key) for sn_key in vn])\n\n cassandra_all_vn_sn = []\n for vn_key, vn in cassandra_all_vns.items():\n cassandra_all_vn_sn.extend([(vn_key, sn_key) for sn_key in vn])\n\n extra_vn_sn = set(zk_all_vn_sn) - set(cassandra_all_vn_sn)\n if extra_vn_sn:\n ret_ok = False\n errmsg = 'Extra VN/SN in zookeeper for %s' %(str(extra_vn_sn))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n extra_vn_sn = set(cassandra_all_vn_sn) - set(zk_all_vn_sn)\n if extra_vn_sn:\n ret_ok = False\n errmsg = 'Extra VN/SN in cassandra for %s' %(str(extra_vn_sn))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n # check for differences in ip addresses\n for vn, sn_key in set(zk_all_vn_sn) & set(cassandra_all_vn_sn):\n sn_gw_ip = cassandra_all_vns[vn][sn_key]['gw']\n zk_ips = zk_all_vns[vn][sn_key]\n cassandra_ips = cassandra_all_vns[vn][sn_key]['addrs']\n extra_ips = set(zk_ips) - set(cassandra_ips)\n for ip_addr in extra_ips:\n # ignore network and gateway ips\n if IPAddress(ip_addr) == IPNetwork(sn_key).network:\n continue\n if ip_addr == sn_gw_ip:\n continue\n\n ret_ok = False\n errmsg = 'Extra IPs in zookeeper for vn %s %s' \\\n %(vn, str(extra_ips))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n # end all zk extra ips\n\n extra_ips = set(cassandra_ips) - set(zk_ips)\n for ip_addr in extra_ips:\n ret_ok = False\n errmsg = 'Extra IPs in cassandra for vn %s %s' \\\n %(vn, str(extra_ips))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n # end all cassandra extra ips\n\n # check gateway ip present/reserved in zookeeper\n if sn_gw_ip not in zk_ips:\n ret_ok = False\n errmsg = 'Gateway ip not reserved in zookeeper %s %s' \\\n %(vn, str(extra_ips))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n # for all common VN/subnets\n\n return ret_ok, ret_msg\n # end check_subnet_addr_alloc\n\n @checker\n def check_route_targets_id(self):\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n # read in route-target ids from zookeeper\n zk_server = self._api_args.zk_server_ip.split(',')[0]\n zk_client = kazoo.client.KazooClient(zk_server)\n zk_client.start()\n base_path = '/id/bgp/route-targets'\n logger.debug(\"Doing recursive read from %s from %s\",\n base_path, zk_server)\n zk_all_rtgts = {}\n auto_rtgt_start = 8000000\n num_bad_rtgts = 0 \n for rtgt in zk_client.get_children(base_path) or []:\n ri_fq_name_str = zk_client.get(base_path+'/'+rtgt)[0]\n zk_all_rtgts[rtgt] = ri_fq_name_str\n if int(rtgt) >= auto_rtgt_start:\n continue # all good\n\n ret_ok = False\n errmsg = 'Wrong route-target range in zookeeper %s' %(rtgt)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n num_bad_rtgts += 1\n\n logger.debug(\"Got %d route-targets, %d of them from wrong range\",\n len(zk_all_rtgts), num_bad_rtgts)\n\n # read in virtual-networks from cassandra to find user allocated rtgts\n # and ensure they are not from auto-allocated range\n num_user_rtgts = 0\n num_bad_rtgts = 0\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n logger.debug(\"Reading virtual-network objects from cassandra\")\n try:\n vn_row = fq_name_table.get('virtual_network', column_count=MAX_COL)\n except pycassa.NotFoundException:\n vn_row = []\n vn_uuids = [x.split(':')[-1] for x in vn_row]\n for vn_id in vn_uuids:\n try:\n rtgt_list_json = obj_uuid_table.get(vn_id,\n columns=['prop:route_target_list'],\n column_count=MAX_COL)['prop:route_target_list']\n rtgt_list = json.loads(rtgt_list_json).get('route_target', [])\n except pycassa.NotFoundException:\n continue\n\n for rtgt in rtgt_list:\n rtgt_num = int(rtgt.split(':')[-1])\n if rtgt_num < auto_rtgt_start:\n num_user_rtgts += 1\n continue # all good\n\n num_bad_rtgts += 1\n ret_ok = False\n errmsg = 'Wrong route-target range in cassandra %d' %(rtgt_num)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n # end for all rtgt\n # end for all vns\n\n logger.debug(\"Got %d user configured route-targets, %d in bad range\",\n num_user_rtgts, num_bad_rtgts)\n\n # read in route-target objects from cassandra and ensure their count\n # matches user-defined + auto allocated and also match RI names(TODO)\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n logger.debug(\"Reading route-target objects from cassandra\")\n try:\n rtgt_row = fq_name_table.get('route_target', column_count=MAX_COL)\n except pycassa.NotFoundException:\n rtgt_row = []\n rtgt_uuids = [x.split(':')[-1] for x in rtgt_row]\n logger.debug(\"Got %d route-target objects from cassandra\",\n len(rtgt_uuids))\n\n if len(rtgt_uuids) != (num_user_rtgts + len(zk_all_rtgts)):\n ret_ok = False\n errmsg = 'Mismatch in route-target count, %d user %d auto, cassandra has %d' \\\n %(num_user_rtgts, len(zk_all_rtgts), len(rtgt_uuids))\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n return ret_ok, ret_msg\n # end check_route_targets_id\n\n @checker\n def check_virtual_networks_id(self):\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n # read in virtual-network ids from zookeeper\n zk_server = self._api_args.zk_server_ip.split(',')[0]\n zk_client = kazoo.client.KazooClient(zk_server)\n zk_client.start()\n base_path = '/id/virtual-networks'\n logger.debug(\"Doing recursive read from %s from %s\",\n base_path, zk_server)\n zk_all_vns = {}\n for vn_id in zk_client.get_children(base_path) or []:\n vn_fq_name_str = zk_client.get(base_path+'/'+vn_id)[0]\n # VN-id in zk starts from 0, in cassandra starts from 1\n zk_all_vns[int(vn_id)+1] = vn_fq_name_str\n\n logger.debug(\"Got %d virtual-networks with id\", len(zk_all_vns))\n\n # read in virtual-networks from cassandra to get id+fq_name\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n logger.debug(\"Reading virtual-network objects from cassandra\")\n try:\n vn_row = fq_name_table.get('virtual_network', column_count=MAX_COL)\n except pycassa.NotFoundException:\n vn_row = []\n vn_uuids = [x.split(':')[-1] for x in vn_row]\n cassandra_all_vns = {}\n for vn_uuid in vn_uuids:\n vn_cols = obj_uuid_table.get(vn_uuid,\n columns=['prop:virtual_network_properties', \n 'prop:virtual_network_network_id',\n 'fq_name'],\n column_count=MAX_COL)\n try:\n vn_id = json.loads(vn_cols['prop:virtual_network_network_id'])\n except KeyError:\n try:\n # upgrade case older VNs had it in composite prop\n vn_props = json.loads(vn_cols['prop:virtual_network_properties'])\n vn_id = vn_props['network_id']\n except KeyError:\n errmsg = 'Missing network-id in cassandra for vn %s' \\\n %(vn_uuid)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n continue\n\n vn_fq_name_str = ':'.join(json.loads(vn_cols['fq_name']))\n cassandra_all_vns[vn_id] = vn_fq_name_str\n\n logger.debug(\"Got %d virtual-networks with id\", len(cassandra_all_vns))\n\n zk_set = set([(id, fqns) for id, fqns in zk_all_vns.items()])\n cassandra_set = set([(id, fqns) for id, fqns in cassandra_all_vns.items()])\n extra_vn_ids = zk_set - cassandra_set\n for vn_id, vn_fq_name_str in extra_vn_ids:\n ret_ok = False\n errmsg = 'Extra VN IDs in zookeeper for vn %s %s' \\\n %(vn_fq_name_str, vn_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n extra_vn_ids = cassandra_set - zk_set\n for vn_id, vn_fq_name_str in extra_vn_ids:\n ret_ok = False\n errmsg = 'Extra VN IDs in cassandra for vn %s %s' \\\n %(vn_fq_name_str, vn_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n return ret_ok, ret_msg\n # end check_virtual_networks_id\n\n @checker\n def check_security_groups_id(self):\n ret_ok = True\n ret_msg = ''\n logger = self._logger\n\n # read in virtual-network ids from zookeeper\n zk_server = self._api_args.zk_server_ip.split(',')[0]\n zk_client = kazoo.client.KazooClient(zk_server)\n zk_client.start()\n base_path = '/id/security-groups/id'\n logger.debug(\"Doing recursive read from %s from %s\",\n base_path, zk_server)\n zk_all_sgs = {}\n for sg_id in zk_client.get_children(base_path) or []:\n # sg-id of 0 is reserved\n if int(sg_id) == 0:\n sg_val = zk_client.get(base_path+'/'+sg_id)[0]\n if sg_val != '__reserved__':\n ret_ok = False\n ret_msg += 'Error, SG-ID 0 not reserved %s.\\n' %(sg_val)\n continue\n \n sg_fq_name_str = zk_client.get(base_path+'/'+sg_id)[0]\n zk_all_sgs[int(sg_id)] = sg_fq_name_str\n\n logger.debug(\"Got %d security-groups with id\", len(zk_all_sgs))\n\n # read in security-groups from cassandra to get id+fq_name\n fq_name_table = self._cf_dict['obj_fq_name_table']\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n logger.debug(\"Reading security-group objects from cassandra\")\n try:\n sg_row = fq_name_table.get('security_group', column_count=MAX_COL)\n except pycassa.NotFoundException:\n sg_row = []\n sg_uuids = [x.split(':')[-1] for x in sg_row]\n cassandra_all_sgs = {}\n for sg_uuid in sg_uuids:\n sg_cols = obj_uuid_table.get(sg_uuid,\n columns=['prop:security_group_id', 'fq_name'],\n column_count=MAX_COL)\n sg_id = json.loads(sg_cols['prop:security_group_id'])\n sg_fq_name_str = ':'.join(json.loads(sg_cols['fq_name']))\n cassandra_all_sgs[sg_id] = sg_fq_name_str\n\n logger.debug(\"Got %d security-groups with id\", len(cassandra_all_sgs))\n\n zk_set = set([(id, fqns) for id, fqns in zk_all_sgs.items()])\n cassandra_set = set([(id, fqns) for id, fqns in cassandra_all_sgs.items()])\n extra_sg_ids = zk_set - cassandra_set\n for sg_id, sg_fq_name_str in extra_sg_ids:\n ret_ok = False\n errmsg = 'Extra SG IDs in zookeeper for sg %s %s' \\\n %(sg_fq_name_str, sg_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n extra_sg_ids = cassandra_set - zk_set\n for sg_id, sg_fq_name_str in extra_sg_ids:\n ret_ok = False\n errmsg = 'Extra SG IDs in cassandra for sg %s %s' \\\n %(sg_fq_name_str, sg_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n\n return ret_ok, ret_msg\n # end check_security_groups_id\n\n def _addr_alloc_process_ip_objects(self, cassandra_all_vns,\n ip_type, ip_uuids):\n ret_ok = True\n ret_msg = ''\n\n if ip_type == 'instance-ip':\n addr_prop = 'prop:instance_ip_address'\n elif ip_type == 'floating-ip':\n addr_prop = 'prop:floating_ip_address'\n else:\n raise Exception('Unknown ip type %s' %(ip_type))\n\n obj_uuid_table = self._cf_dict['obj_uuid_table']\n for ip_id in ip_uuids:\n # get addr\n ip_cols = obj_uuid_table.get(ip_id, column_count=MAX_COL)\n try:\n ip_addr = json.loads(ip_cols[addr_prop])\n except KeyError:\n ret_ok = False\n errmsg = 'Missing ip addr in %s %s' %(ip_type, ip_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n continue\n\n # get vn uuid\n vn_id = None\n for col_name in ip_cols.keys():\n mch = re.match('ref:virtual_network:(.*)', col_name)\n if not mch:\n continue\n vn_id = mch.group(1)\n\n if not vn_id:\n ret_ok = False\n ret_msg += 'Error, Missing vn-id in %s %s.\\n' %(ip_type, ip_id)\n continue\n\n fq_name_json = obj_uuid_table.get(vn_id,\n columns=['fq_name'],\n column_count=MAX_COL)['fq_name']\n fq_name_str = ':'.join(json.loads(fq_name_json))\n if fq_name_str not in cassandra_all_vns:\n # find all subnets on this VN and add for later check\n cassandra_all_vns[fq_name_str] = {}\n ipam_refs = obj_uuid_table.get(vn_id,\n column_start='ref:network_ipam:',\n column_finish='ref:network_ipam;',\n column_count=MAX_COL)\n for ipam in ipam_refs:\n ipam_col = obj_uuid_table.get(vn_id,\n columns=[ipam], column_count=MAX_COL)\n attr_dict = json.loads(ipam_col[ipam])['attr']\n for subnet in attr_dict['ipam_subnets']:\n sn_key = '%s/%s' %(subnet['subnet']['ip_prefix'],\n subnet['subnet']['ip_prefix_len'])\n gw = subnet['default_gateway']\n cassandra_all_vns[fq_name_str][sn_key] = {'gw': gw,\n 'addrs': []}\n # end first encountering vn\n\n for sn_key in cassandra_all_vns[fq_name_str]:\n addr_added = False\n subnet = cassandra_all_vns[fq_name_str][sn_key]\n if not IPAddress(ip_addr) in IPNetwork(sn_key):\n continue\n cassandra_all_vns[fq_name_str][sn_key]['addrs'].append(ip_addr)\n addr_added = True\n break\n # end for all subnets in vn\n\n if not addr_added:\n ret_ok = False\n errmsg = 'Missing subnet for ip %s %s' %(ip_type, ip_id)\n ret_msg += 'Error, %s.\\n' %(errmsg)\n # end handled the ip\n # end for all ip_uuids\n\n return ret_ok, ret_msg\n # end _addr_alloc_process_ip_objects\n\n def _connect_to_ifmap_servers(self):\n self._mapclients = []\n mapclients = []\n NAMESPACES = {\n 'env': \"http://www.w3.org/2003/05/soap-envelope\",\n 'ifmap': \"http://www.trustedcomputinggroup.org/2010/IFMAP/2\",\n 'meta':\n \"http://www.trustedcomputinggroup.org/2010/IFMAP-METADATA/2\",\n 'contrail': \"http://www.contrailsystems.com/vnc_cfg.xsd\"\n }\n ifmap_user, ifmap_passwd = self._args.ifmap_credentials.split(':')\n # pick ifmap servers from args to this utility and if absent\n # pick it from contrail-api conf file\n if self._args.ifmap_servers:\n ifmap_ips_ports = [(ip_port.split(':'))\n for ip_port in self._args.ifmap_servers]\n else:\n ifmap_ips_ports = [(self._api_args.ifmap_server_ip,\n self._api_args.ifmap_server_port)]\n for ifmap_ip, ifmap_port in ifmap_ips_ports:\n mapclient = client((ifmap_ip, ifmap_port),\n ifmap_user, ifmap_passwd,\n NAMESPACES)\n self._mapclients.append(mapclient)\n connected = False\n while not connected:\n try:\n result = mapclient.call('newSession', NewSessionRequest())\n connected = True\n except socket.error as e:\n time.sleep(3)\n\n mapclient.set_session_id(newSessionResult(result).get_session_id())\n mapclient.set_publisher_id(newSessionResult(result).get_publisher_id())\n\n # end _connect_to_ifmap_servers\n\n# end class DatabaseChecker\n\n\ndef db_check():\n cgitb.enable(format='text')\n\n args_str = ' '.join(sys.argv[1:])\n db_checker = DatabaseChecker(args_str)\n\n # Mode and node count check across all nodes\n db_checker.check_zk_mode_and_node_count()\n db_checker.check_cassandra_keyspace_replication()\n db_checker.check_obj_mandatory_fields()\n db_checker.check_fq_name_uuid_ifmap_match()\n db_checker.check_subnet_uuid()\n db_checker.check_subnet_addr_alloc()\n db_checker.check_route_targets_id()\n db_checker.check_virtual_networks_id()\n db_checker.check_security_groups_id()\n# end db_check\n\n\nif __name__ == '__main__':\n db_check()\n","sub_path":"controller/src/config/api-server/db_manage.py","file_name":"db_manage.py","file_ext":"py","file_size_in_byte":37547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"293049157","text":"#!/usr/bin/env python\nimport sys\nimport cProfile\nsys.path.append(\"../\")\n\nfrom laspy import file as File\ninFile = File.File(sys.argv[1],mode= \"r\")\nprint(\"File length: \" + str(len(inFile)) + \" points to be copied.\")\noutFile = File.File(sys.argv[2],mode= \"w\", header = inFile.header)\n\nspec = inFile.reader.point_format.lookup.keys()\n\ndef f():\n outFile.X = inFile.X\n outFile.Y = inFile.Y\n\ncProfile.run(\"f()\")\n\n#for x in spec:\n# print(x)\n# outFile.writer.set_dimension(x, inFile.reader.get_dimension(x))\n\n\ninFile.close()\noutFile.close()\n","sub_path":"misc/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353761443","text":"## Lesson4_PermCheck\n\n\"\"\"\n给出了由N个整数组成的非空数组A.\n\n甲排列是含有从1到N的每个元素一旦一个序列,并且只有一次。\n\n例如,数组A使得:\n\n A [0] = 4\n A [1] = 1\n A [2] = 3\n A [3] = 2\n是一个排列,但是数组A使得:\n\n A [0] = 4\n A [1] = 1\n A [2] = 3\n不是排列,因为缺少值2。\n\n目标是检查阵列A是否是排列。\n\n写一个函数:\n\ndef PermCheck(A):\n\n在给定数组A的情况下,如果数组A是排列,则返回1,如果不是,则返回0。\n\n例如,给定数组A,使得:\n\n A [0] = 4\n A [1] = 1\n A [2] = 3\n A [3] = 2\n该函数应返回1。\n\n给定数组A,使得:\n\n A [0] = 4\n A [1] = 1\n A [2] = 3\n该函数应返回0。\n\n为以下假设编写有效的算法:\n\nN是[ 1 ... 100,000 ] 范围内的整数;\n数组A的每个元素是[ 1 ... 1,000,000,000 ] 范围内的整数。\n\n\"\"\"\n\ndef PermCheck(A):\n\n # for i in range(len(A)):\n # if i+1 in A:\n # continue\n # else:\n # return 0\n # return 1\n## 本题需要去重,因此使用set()是很方便的\n m = max(A)\n if len(A) != len(set(A)):\n return 0\n elif m == len(set(A)):\n return 1\n else:\n return 0\n\n\n\ndef main():\n # A = [2]\n A = [1, 3, 8]\n print(PermCheck(A))\n\nif (__name__ == \"__main__\"):\n main()\n\n","sub_path":"Lesson4_CountingElements/Lesson4_PermCheck.py","file_name":"Lesson4_PermCheck.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"192002119","text":"from django.shortcuts import render, redirect, HttpResponseRedirect\nfrom django.conf import settings\nfrom django.contrib.auth import login\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom functools import wraps\n\nfrom todolib.models import TaskStatus\n\nfrom todolib.exceptions import ObjectNotFoundError, LibError\nfrom todoapp import get_service\nfrom .forms import (TaskForm,\n FolderForm,\n SubTaskForm,\n MemberForm,\n PlanForm,\n ReminderForm,\n TaskSearchForm)\n\n\ndef execute_plans(func):\n def wrapper(request, *args, **kwargs):\n get_service().execute_plans(request.user.username)\n return func(request, *args, **kwargs)\n\n return wrapper\n\n\ndef error_catcher(func):\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except LibError:\n return redirect('todoapp:index')\n\n return wrapper\n\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('todoapp:index')\n else:\n form = UserCreationForm()\n return render(request,\n 'registration/signup.html',\n {'form': form})\n\n\n@login_required\n@execute_plans\ndef add_folder(request):\n\n if request.method == 'POST':\n form = FolderForm(request.POST)\n if form.is_valid():\n service = get_service()\n name = form.cleaned_data['name']\n user = request.user.username\n\n folder = service.get_folder_by_name(user=user, name=name)\n\n if folder:\n form.add_error('name', f'You already have folder {name}')\n return render(request, 'tasks/add.html', {'form': form})\n\n folder = service.create_folder(user=user, name=name)\n return redirect('todoapp:folder_tasks', folder.id)\n\n else:\n form = FolderForm()\n\n return render(request, 'folders/add.html', {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef edit_folder(request, folder_id):\n if request.method == 'POST':\n form = FolderForm(request.POST)\n if form.is_valid():\n service = get_service()\n user = request.user.username\n name = form.cleaned_data['name']\n folder_id = int(folder_id)\n\n folder = service.get_folder_by_name(user=user, name=name)\n\n if folder and folder.id != folder_id:\n form.add_error('name', f'You already have folder {name}')\n return render(request,\n 'tasks/edit.html',\n {'form': form})\n\n service.update_folder(user=user, folder_id=folder_id, name=name)\n return redirect('todoapp:folder_tasks', folder_id)\n\n else:\n form = FolderForm()\n\n return render(request, 'folders/edit.html', {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef delete_folder(request, folder_id):\n if request.method == 'POST':\n service = get_service()\n user = request.user.username\n folder_id = int(folder_id)\n\n service.delete_folder(user=user,\n folder_id=folder_id)\n\n return redirect('todoapp:tasks')\n\n\n@login_required\n@execute_plans\ndef add_task(request):\n\n user = request.user.username\n\n if request.method == 'POST':\n form = TaskForm(user, request.POST)\n if form.is_valid():\n try:\n service = get_service()\n task = service.create_task(user=user,\n name=form.cleaned_data['name'],\n description=form.cleaned_data['description'],\n priority=form.cleaned_data['priority'],\n status=form.cleaned_data['status'],\n event=form.cleaned_data['event'],\n start_date=form.cleaned_data['start_date'],\n end_date=form.cleaned_data['end_date'],\n assigned=form.cleaned_data['assigned'])\n except ValueError as e:\n form.add_error('start_date', e)\n return render(request, 'tasks/add.html', {'form': form})\n\n folders_ids = form.cleaned_data['folders']\n\n for folder_id in folders_ids:\n service.populate_folder(user=user,\n folder_id=folder_id,\n task_id=task.id)\n return redirect('todoapp:show_task', task.id)\n\n else:\n form = TaskForm(user, None)\n return render(request, 'tasks/add.html', {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef edit_task(request, task_id):\n\n service = get_service()\n user = request.user.username\n task_id = int(task_id)\n\n task = service.get_task(user=user, task_id=task_id)\n\n # button to edit task would be disabled. but link to edit task\n # still will be available. due to forms requests of get type on init form\n if task.status == TaskStatus.ARCHIVED:\n return redirect('todoapp:index')\n\n if request.method == 'POST':\n form = TaskForm(user, request.POST)\n if form.is_valid():\n try:\n task = service.update_task(user=user,\n task_id=task_id,\n name=form.cleaned_data['name'],\n description=form.cleaned_data['description'],\n priority=form.cleaned_data['priority'],\n status=form.cleaned_data['status'],\n event=form.cleaned_data['event'],\n start_date=form.cleaned_data['start_date'],\n end_date=form.cleaned_data['end_date'])\n except ValueError as e:\n form.add_error('start_date', e)\n return render(request, 'tasks/edit.html', {'form': form})\n\n assigned = form.cleaned_data['assigned']\n\n if assigned:\n service.assign_user(user=user,\n task_id=task.id,\n user_receiver=assigned)\n\n current_folders = service.get_task_folders(task_id=task.id,\n user=user)\n\n old_folders = set(map(lambda folder: folder.id, current_folders))\n new_folders = set(form.cleaned_data['folders'])\n\n add = new_folders.difference(old_folders)\n remove = old_folders.difference(new_folders)\n\n for folder_id in add:\n service.populate_folder(user=user,\n folder_id=folder_id,\n task_id=task.id)\n for folder_id in remove:\n service.unpopulate_folder(user=user,\n folder_id=folder_id,\n task_id=task.id)\n\n return redirect('todoapp:show_task', task.id)\n\n else:\n assigned = None\n if task.assigned:\n assigned = User.objects.filter(username=task.assigned).get()\n\n initial_folders = [folder.id for folder\n in service.get_task_folders(task.id, user=user)]\n\n if not initial_folders:\n initial_folders = 0\n form = TaskForm(\n user,\n initial={\n 'name': task.name,\n 'description': task.description,\n 'status': task.status.value,\n 'priority': task.priority.value,\n 'event': task.event,\n 'start_date': task.start_date,\n 'end_date': task.end_date,\n 'assigned': assigned,\n 'folders': initial_folders\n })\n\n return render(request,\n 'tasks/edit.html',\n {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef show_task(request, task_id):\n user = request.user.username\n service = get_service()\n\n task_id = int(task_id)\n task = service.get_task(user=user, task_id=task_id)\n\n subtasks = service.get_subtasks(user=user,\n task_id=task_id)\n\n return render(request, 'tasks/show.html',\n {'task': task, 'subtasks': subtasks})\n\n\n@login_required\ndef tasks(request):\n return own_tasks(request)\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef add_subtask(request, parent_task_id):\n user = request.user.username\n\n if request.method == 'POST':\n form = SubTaskForm(user, request.POST)\n if form.is_valid():\n service = get_service()\n task_id = form.cleaned_data['task_id']\n parent_task_id = int(parent_task_id)\n\n try:\n service.add_subtask(user=user,\n task_id=task_id,\n parent_task_id=parent_task_id)\n except ValueError as e:\n form.add_error('task_id', e)\n return render(request,\n 'tasks/add_subtask.html',\n {'form': form})\n\n return redirect('todoapp:show_task', parent_task_id)\n\n else:\n form = SubTaskForm(user)\n\n return render(request,\n 'tasks/add_subtask.html',\n {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef detach_task(request, task_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n task_id = int(task_id)\n service.detach_task(user=user,\n task_id=task_id)\n\n link = request.META.get('HTTP_REFERER', None)\n if link:\n return redirect(link)\n\n return redirect('todoapp:show_task', task_id)\n\n return redirect('todoapp:index')\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef share_task(request, task_id):\n if request.method == 'POST':\n form = MemberForm(request.POST)\n if form.is_valid():\n service = get_service()\n user = request.user.username\n task_id = int(task_id)\n member = form.cleaned_data['member'].username\n service.share_task(user=user,\n task_id=task_id,\n user_receiver=member)\n return redirect('todoapp:show_task', task_id)\n\n else:\n form = MemberForm()\n\n return render(request,\n 'tasks/add_member.html',\n {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef unshare_task(request, task_id, member):\n user = request.user.username\n service = get_service()\n task_id = int(task_id)\n service.unshare_task(user=user,\n task_id=task_id,\n user_receiver=member)\n\n return redirect('todoapp:show_task', task_id)\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef done_task(request, task_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n task_id = int(task_id)\n service.change_task_status(user=user,\n task_id=task_id,\n status=TaskStatus.DONE.value)\n\n link = request.META.get('HTTP_REFERER', None)\n if link:\n return redirect(link)\n\n return redirect('todoapp:show_task', task_id)\n\n return redirect('todoapp:index')\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef archive_task(request, task_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n task_id = int(task_id)\n service.change_task_status(user=user,\n task_id=task_id,\n status=TaskStatus.ARCHIVED.value,\n apply_on_subtasks=True)\n\n link = request.META.get('HTTP_REFERER', None)\n if link:\n return redirect(link)\n\n return redirect('todoapp:show_task', task_id)\n\n return redirect('todoapp:index')\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef delete_task(request, task_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n task_id = int(task_id)\n service.delete_task(user=user,\n task_id=task_id)\n\n link = request.META.get('HTTP_REFERER', None)\n if link:\n return redirect(link)\n\n return redirect('todoapp:index')\n\n\ndef search_tasks(request):\n user = request.user.username\n if request.method == 'POST':\n form = TaskSearchForm(user, request.POST)\n if form.is_valid():\n service = get_service()\n\n tasks = service.get_filtered_tasks(user=user,\n name=form.cleaned_data['name'],\n description=form.cleaned_data['description'],\n parent_task_id=form.cleaned_data['parent_task_id'],\n owner=form.cleaned_data['owner'],\n assigned=form.cleaned_data['assigned'],\n status=form.cleaned_data['status'],\n priority=form.cleaned_data['priority'],\n event=form.cleaned_data['event'])\n\n return render(request, 'tasks/search_result.html',\n {'header': 'Search result',\n 'tasks': tasks})\n\n else:\n form = TaskSearchForm(user, None)\n return render(request, 'tasks/search.html', {'form': form})\n\n\n@login_required\n@execute_plans\ndef own_tasks(request):\n service = get_service()\n user = request.user.username\n tasks = [task for task in service.get_filtered_tasks(user=user, owner=user)\n if task.status != TaskStatus.ARCHIVED]\n folders = service.get_all_folders(user)\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks, 'header': 'My tasks',\n 'folders': folders,\n 'nav_active': 'own'})\n\n\n@login_required\n@execute_plans\ndef available_tasks(request):\n service = get_service()\n user = request.user.username\n tasks = [task for task in service.get_available_tasks(user=user)\n if task.status != TaskStatus.ARCHIVED]\n folders = service.get_all_folders(user)\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks, 'header': 'Available tasks',\n 'folders': folders,\n 'nav_active': 'available'})\n\n\n@login_required\n@execute_plans\ndef assigned_tasks(request):\n service = get_service()\n user = request.user.username\n tasks = [task for task in service.get_user_assigned_tasks(user)\n if task.status != TaskStatus.ARCHIVED]\n folders = service.get_all_folders(user)\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks, 'header': 'Assigned tasks',\n 'folders': folders,\n 'nav_active': 'assigned'})\n\n\n@login_required\n@execute_plans\ndef archived_tasks(request):\n service = get_service()\n user = request.user.username\n tasks = service.get_filtered_tasks(user=user,\n status=TaskStatus.ARCHIVED)\n folders = service.get_all_folders(user)\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks, 'header': 'Archived tasks',\n 'folders': folders,\n 'nav_active': 'archived'})\n\n\n@login_required\n@execute_plans\ndef done_tasks(request):\n service = get_service()\n user = request.user.username\n tasks = service.get_filtered_tasks(user=user,\n status=TaskStatus.DONE)\n folders = service.get_all_folders(user)\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks,\n 'header': 'Done tasks',\n 'folders': folders,\n 'nav_active': 'done'})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef folder_tasks(request, folder_id):\n service = get_service()\n user = request.user.username\n\n folder = service.get_folder(user=user,\n folder_id=folder_id)\n folders = service.get_all_folders(user=user)\n\n tasks = [task for task in folder.tasks\n if task.status != TaskStatus.ARCHIVED]\n\n return render(request, 'tasks/list.html',\n {'tasks': tasks,\n 'header': f'{folder.name} tasks',\n 'folders': folders,\n 'nav_active': folder.id})\n\n\n@login_required\n@execute_plans\ndef plans(request):\n service = get_service()\n user = request.user.username\n plans = service.get_all_plans(user=user)\n\n return render(request, 'plans/list.html',\n {'plans': plans,\n 'header': 'Available plans'})\n\n\n@login_required\n@execute_plans\ndef add_plan(request):\n\n user = request.user.username\n\n if request.method == 'POST':\n form = PlanForm(user, None, request.POST)\n if form.is_valid():\n try:\n service = get_service()\n task = service.create_plan(\n user=user,\n task_id=int(form.cleaned_data['task_id']),\n period_amount=form.cleaned_data['period_amount'],\n period=form.cleaned_data['period'],\n start_date=form.cleaned_data['start_date'],\n repetitions_amount=form.cleaned_data['repetitions_amount'],\n end_date=form.cleaned_data['end_date'])\n\n except ValueError as e:\n form.add_error('end_date', e)\n return render(request, 'plans/add.html', {'form': form})\n\n return redirect('todoapp:show_plan', task.id)\n\n else:\n form = PlanForm(user, None, None)\n\n return render(request, 'plans/add.html', {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef edit_plan(request, plan_id):\n\n service = get_service()\n user = request.user.username\n\n plan_id = int(plan_id)\n plan = service.get_plan(user=user, plan_id=plan_id)\n\n # deny requests when plan already activated\n if plan.start_date != plan.last_activated:\n return redirect('todoapp:index')\n\n if request.method == 'POST':\n form = PlanForm(user, plan_id, request.POST)\n if form.is_valid():\n plan = service.update_plan(\n user=user,\n plan_id=plan_id,\n period=form.cleaned_data['period'],\n period_amount=form.cleaned_data['period_amount'],\n repetitions_amount=form.cleaned_data['repetitions_amount'],\n end_date=form.cleaned_data['end_date'],\n )\n return redirect('todoapp:show_plan', plan.id)\n\n else:\n form = PlanForm(\n user,\n plan_id,\n None,\n initial={\n 'period': plan.period.value,\n 'period_amount': plan.period_amount,\n 'repetitions_amount': plan.repetitions_amount,\n 'start_date': plan.start_date,\n 'end_date': plan.end_date,\n })\n\n return render(request,\n 'plans/edit.html',\n {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef show_plan(request, plan_id):\n user = request.user.username\n service = get_service()\n plan_id = int(plan_id)\n plan = service.get_plan(user=user,\n plan_id=plan_id)\n\n return render(request, 'plans/show.html',\n {'plan': plan})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef delete_plan(request, plan_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n plan_id = int(plan_id)\n service.delete_plan(user=user,\n plan_id=plan_id)\n\n return redirect('todoapp:plans')\n\n\n@login_required\n@execute_plans\ndef add_reminder(request):\n\n user = request.user.username\n\n if request.method == 'POST':\n form = ReminderForm(user, request.POST)\n if form.is_valid():\n try:\n service = get_service()\n service.create_reminder(\n user=user,\n task_id=int(form.cleaned_data['task_id']),\n date=form.cleaned_data['date'])\n\n except ValueError as e:\n form.add_error('date', e)\n return render(request, 'reminders/add.html', {'form': form})\n\n return redirect('todoapp:reminders')\n\n else:\n form = ReminderForm(user, None)\n\n return render(request, 'reminders/add.html', {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef edit_reminder(request, reminder_id):\n\n service = get_service()\n user = request.user.username\n\n reminder_id = int(reminder_id)\n reminder = service.get_reminder(user=user, reminder_id=reminder_id)\n\n if request.method == 'POST':\n form = ReminderForm(user, request.POST)\n if form.is_valid():\n try:\n service.update_reminder(user=user,\n reminder_id=reminder_id,\n date=form.cleaned_data['date'])\n except ValueError as e:\n form.add_error('start_date', e)\n return render(request, 'reminders/edit.html',\n {'form': form})\n\n return redirect('todoapp:reminders')\n\n else:\n\n form = ReminderForm(\n user,\n initial={\n 'date': reminder.date})\n\n return render(request,\n 'reminders/edit.html',\n {'form': form})\n\n\n@login_required\n@error_catcher\n@execute_plans\ndef delete_reminder(request, reminder_id):\n if request.method == 'POST':\n user = request.user.username\n service = get_service()\n reminder_id = int(reminder_id)\n service.delete_reminder(user=user,\n reminder_id=reminder_id)\n\n return redirect('todoapp:reminders')\n\n\n@login_required\n@execute_plans\ndef reminders(request):\n service = get_service()\n user = request.user.username\n reminders = service.get_all_reminders(user=user)\n\n return render(request, 'reminders/list.html',\n {'reminders': reminders,\n 'header': 'Available reminders'})\n","sub_path":"todoweb/todoapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"338621064","text":"#! python3\nimport os\nimport sys\nimport time\nimport re\nimport pathlib\n\n#all this code is in main so that it is possible for the package \n#to create a script in site-packages/scripts.\ndef main():\n\n #we have to add the current path and its parent to the search path.\n current_dir = pathlib.WindowsPath(__file__)\n parent_dir =current_dir.parent\n for p in (current_dir,parent_dir):\n sys.path.append(str(p))\n \n \n \n #\n print('Starting start_configurenatlink.py,')\n print('Try to run configurenatlink.py, the Natlink Config GUI, in Elevated mode...')\n print()\n\n if sys.version.find(\"64 bit\") >= 0:\n print('''=============================================\\n\n You run this module from a 64 bit version of Python.\\n\n Natlink cannot run with this version, please be sure to \\n\n install a 32 bit version of python, and run from there.\\n\n See https://qh.antenna.nl/unimacro/installation/problemswithinstallation.html\\n\n =============================================''')\n time.sleep(30)\n sys.exit()\n\n try:\n import wx\n from win32api import ShellExecute, GetVersionEx\n except (Exception, e):\n print(f'''Unable to run the GUI configuration program of Natlink/Unimacro/Vocola\\n\n because a module was not found. An error occurred during import. This is probably due to a missing or incorrect prequisite.\\n\n Please run 'pip install -r requirements.txt in {thisDir}\\n\n More information https://qh.antenna.nl/unimacro/installation/problemswithinstallation.html\\n\\n\n Exception Details:\\n{e}''')\n time.sleep(30)\n sys.exit()\n\n try:\n import natlinkconfigfunctions\n except ImportError:\n print('''Unable to start the configuration program of Natlink/Unimacro/Vocola:\\n\n the python module natlinkconfigfunctions.py gives an error.\\n\n Please report this error message to the Natlink developers,\\n\n preferably to q.hoogenboom@antenna.nl\\n''')\n import traceback\n traceback.print_exc()\n\n # time.sleep(30)\n sys.exit()\n\n\n try:\n # see natlinkstatus.py for windows versions (getWindowsVersion)\n wversion = GetVersionEx()\n if wversion[3] == 2 and wversion[0] >= 6:\n # Vista and later, run as administrator, so elevated mode:\n openpar = \"runas\"\n else:\n openpar = \"open\"\n #python and pythonw.exe may be in a scripts directory in virtualenvs. \n #to find the path of the python executable, \n pathToPythonExecutables=\"\\\\\".join(sys.executable.split('\\\\')[0:-1])\n\n pathToPythonW = f\"{pathToPythonExecutables}\\\\pythonw.exe\" \n if not os.path.isfile(pathToPythonW):\n print(\"cannot find the Pythonw exectutable: %s\"% pathToPythonW)\n # time.sleep(30)\n sys.exit()\n\n configPath = os.path.join(os.path.dirname(__file__), \"configurenatlink.pyw\")\n if not os.path.isfile(configPath):\n print(\"cannot find the Natlink/Unimacro/Vocola configuration program: %s\"% configPath)\n # time.sleep(30)\n sys.exit()\n\n\n #print('run with \"%s\": %s'% (openpar, configPath)\n #print('sys.version: ', sys.version\n #time.sleep(5)\n ShellExecute(0, openpar, pathToPythonW, configPath, \"\", 1)\n import traceback\n traceback.print_exc()\n except:\n import traceback\n traceback.print_exc()\n time.sleep(60)\n\nmain()\n","sub_path":"src/natlinkpy/ConfigureNatlink/start_configurenatlink.py","file_name":"start_configurenatlink.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"269480109","text":"import cv2\nimport csv\nimport numpy as np\nimport os\n\ndef getDrivingLogEntries(dataPath, skipHeader=False):\n \"\"\"\n Returns the entries from driving log file in `dataPath`.\n If the file include headers, pass `skipHeader=True`.\n \"\"\"\n entries = []\n with open(dataPath + '/driving_log_rel.csv') as csvFile:\n reader = csv.reader(csvFile)\n if skipHeader:\n next(reader, None)\n for row in reader:\n entries.append(row)\n return entries\n\n\ndef getImageDirectories(dataPath):\n \"\"\"\n Returns the paths to images and measurements for all data recording folders in `dataPath`.\n Returns `([centerPaths], [leftPath], [rightPath], [measurement])`\n \"\"\"\n recFolders = [x[0] for x in os.walk(dataPath)]\n recordings = list(filter(lambda recording: os.path.isfile(recording + '/driving_log_rel.csv'), recFolders))\n centerCam = []\n leftCam = []\n rightCam = []\n steerAngleMeas = []\n for recording in recordings:\n entries = getDrivingLogEntries(recording)\n center = []\n left = []\n right = []\n measurements = []\n for entry in entries:\n measurements.append(float(entry[3]))\n center.append(recording + entry[0].strip())\n left.append(recording + entry[1].strip())\n right.append(recording + entry[2].strip())\n centerCam.extend(center)\n leftCam.extend(left)\n rightCam.extend(right)\n steerAngleMeas.extend(measurements)\n\n return (centerCam, leftCam, rightCam, steerAngleMeas)\n\ndef correctMeasurements(center, left, right, steerMeasurements, correction):\n \"\"\"\n Corrects the steering measurements for camera images 'left' and 'right' \n using the correction factor `correction` and combines images & measurements\n Returns ([imageDir], [measurements])\n \"\"\"\n imageDir = []\n imageDir.extend(center)\n imageDir.extend(left)\n imageDir.extend(right)\n measurements = []\n measurements.extend(steerMeasurements)\n measurements.extend([steering_center + correction for steering_center in steerMeasurements])\n measurements.extend([steering_center - correction for steering_center in steerMeasurements])\n return (imageDir, measurements)\n\nimport sklearn\n\ndef generator(samples, batch_size=32):\n \"\"\"\n Generate the required images and measurements for training/\n `samples` is a list of pairs (`imagePath`, `measurement`).\n \"\"\"\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n samples = sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for imagePath, measurement in batch_samples:\n originalImage = cv2.imread(imagePath)\n image = cv2.cvtColor(originalImage, cv2.COLOR_BGR2RGB)\n images.append(image)\n angles.append(measurement)\n # Flipping\n images.append(cv2.flip(image,1))\n angles.append(measurement*-1.0)\n\n # trim image to only see section with road\n inputs = np.array(images)\n outputs = np.array(angles)\n yield sklearn.utils.shuffle(inputs, outputs)\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D\nfrom keras.layers.pooling import MaxPooling2D\nimport matplotlib.pyplot as plt\n\ndef createPreProcessingLayers():\n \"\"\"\n Creates a model with the initial pre-processing layers.\n \"\"\"\n model = Sequential()\n model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))\n model.add(Cropping2D(cropping=((50,20), (0,0))))\n return model\n\ndef nVidiaModel():\n \"\"\"\n Creates nVidea Autonomous Car Group model\n \"\"\"\n model = createPreProcessingLayers()\n model.add(Convolution2D(24,5,5, subsample=(2,2), activation='relu'))\n model.add(Convolution2D(36,5,5, subsample=(2,2), activation='relu'))\n model.add(Convolution2D(48,5,5, subsample=(2,2), activation='relu'))\n model.add(Convolution2D(64,3,3, activation='relu'))\n model.add(Convolution2D(64,3,3, activation='relu'))\n model.add(Flatten())\n model.add(Dense(100))\n model.add(Dense(50))\n model.add(Dense(10))\n model.add(Dense(1))\n return model\n\n\n# Get image directories & correct measurements for left and right camera images\ncenterDir, leftDir, rightDir, measurements = getImageDirectories('data')\nimageDirectories, measurements = correctMeasurements(centerDir, leftDir, rightDir, measurements, 0.2)\nprint('Total Images: {}'.format( len(imageDirectories)))\n\n# Split training & validation samples\nfrom sklearn.model_selection import train_test_split\nsamples = list(zip(imageDirectories, measurements))\ntrain_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\nprint('Train samples: {}'.format(len(train_samples)))\nprint('Validation samples: {}'.format(len(validation_samples)))\n\n# Create generators\ntrain_generator = generator(train_samples, batch_size=32)\nvalidation_generator = generator(validation_samples, batch_size=32)\n\n# Create model (based on nVidia model)\nmodel = nVidiaModel()\n\n# Compile & train the model\nmodel.compile(loss='mse', optimizer='adam')\nhistory_object = model.fit_generator(train_generator, samples_per_epoch= \\\n len(train_samples), validation_data=validation_generator, \\\n nb_val_samples=len(validation_samples), nb_epoch=3, verbose=1)\n\nmodel.save('model.h5')\nprint(history_object.history.keys())\nprint('Loss')\nprint(history_object.history['loss'])\nprint('Validation Loss')\nprint(history_object.history['val_loss'])\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"448823405","text":"# -*- coding: utf-8 -*-\nfrom flask import Blueprint, request, render_template, current_app, session, jsonify\nfrom flask import g\nfrom flask import make_response\n\nfrom webpanda.common.NrckiLogger import NrckiLogger\nfrom webpanda.dashboard import route_s\nfrom webpanda.services import tasks_, jobs_\nfrom webpanda.tasks import Task\n\nbp = Blueprint('tasks', __name__, url_prefix=\"/tasks\")\n_logger = NrckiLogger().getLogger(\"dashboard.tasks\")\n\n\n@route_s(bp, \"/\", methods=['GET'])\ndef list_all():\n hours_limit = request.args.get('hours', current_app.config['HOURS_LIMIT'], type=int)\n display_limit = request.args.get('display_limit', current_app.config['DISPLAY_LIMIT'], type=int)\n session['hours_limit'] = hours_limit\n session['display_limit'] = display_limit\n return render_template(\"dashboard/tasks/list.html\")\n\n\n@route_s(bp, \"/\", methods=['GET'])\ndef task_info(id):\n \"\"\"\n Task info view\n :param guid: guid of job\n :return: Response obj\n \"\"\"\n task = tasks_.get(id)\n jobs = jobs_.find(tags=task.tag)\n return render_template(\"dashboard/tasks/task.html\", jobs=jobs, task=task)\n\n\n@route_s(bp, \"/list\", methods=['GET'])\ndef tasks_list():\n \"\"\"\n Get list of jobs method for ajax\n :return: List of Job obj\n \"\"\"\n user = g.user\n\n # show users jobs\n tasks = tasks_.find(owner_id=user.id).order_by(Task.id.desc()).all()\n\n return make_response(jsonify({\"data\": tasks}), 200)\n","sub_path":"webpanda/dashboard/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"421347062","text":"import subprocess\n\nimport utils.hook as hook\nimport utils.repl as repl\n\nclass Exec(object):\n\n @hook.command(command=\">>\", flags=\"a\")\n def _exec(self, bot, event, args):\n \"\"\"\n\n Executes the specified code in a python interpreter and replies with\n the result.\n \"\"\"\n console = repl.Repl({\n \"self\": self,\n \"bot\": bot,\n \"event\": event,\n \"args\": args\n })\n output = console.run(args).splitlines()\n for line in output:\n if len(line) > 0:\n bot.reply(event, line)\n\n @hook.command(command=\">\", flags=\"a\")\n def _shell(self, bot, event, args):\n \"\"\"\n\n Runs the specified command in a shell and replies with the result.\n \"\"\"\n output = subprocess.check_output(args, stderr=subprocess.STDOUT, shell=True)\n if output:\n output = output.decode(\"UTF-8\", \"ignore\").splitlines()\n for line in output:\n if len(line) > 0:\n bot.reply(event, line)\n\nClass = Exec\n","sub_path":"plugins/Exec.py","file_name":"Exec.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"172626843","text":"\n# Copyright 2017-present Open Networking Foundation\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 datetime\nimport json\nimport pytz\nimport inspect\nimport sys\nimport threading\nfrom django.db import models\nfrom django.utils.timezone import now\nfrom django.db.models import *\nfrom django.db import transaction\nfrom django.forms.models import model_to_dict\nfrom django.utils import timezone\nfrom django.core.exceptions import PermissionDenied\nfrom cgi import escape as html_escape\nfrom django.db.models.deletion import Collector\nfrom django.db import router\nfrom django.contrib.contenttypes.models import ContentType\n\nimport redis\nfrom redis import ConnectionError\n\nXOS_GLOBAL_DEFAULT_SECURITY_POLICY = True\n\ndef date_handler(obj):\n if isinstance(obj, pytz.tzfile.DstTzInfo):\n # json can't serialize DstTzInfo\n return str(obj)\n return obj.isoformat() if hasattr(obj, 'isoformat') else obj\n\nclass StrippedCharField(models.CharField):\n \"\"\" CharField that strips trailing and leading spaces.\"\"\"\n def clean(self, value, *args, **kwds):\n if value is not None:\n value = value.strip()\n return super(StrippedCharField, self).clean(value, *args, **kwds)\n\n\n# This manager will be inherited by all subclasses because\n# the core model is abstract.\nclass XOSBaseDeletionManager(models.Manager):\n def get_queryset(self):\n parent=super(XOSBaseDeletionManager, self)\n if hasattr(parent, \"get_queryset\"):\n return parent.get_queryset().filter(deleted=True)\n else:\n return parent.get_query_set().filter(deleted=True)\n\n # deprecated in django 1.7 in favor of get_queryset().\n def get_query_set(self):\n return self.get_queryset()\n\n# This manager will be inherited by all subclasses because\n# the core model is abstract.\nclass XOSBaseManager(models.Manager):\n def get_queryset(self):\n parent=super(XOSBaseManager, self)\n if hasattr(parent, \"get_queryset\"):\n return parent.get_queryset().filter(deleted=False)\n else:\n return parent.get_query_set().filter(deleted=False)\n\n # deprecated in django 1.7 in favor of get_queryset().\n def get_query_set(self):\n return self.get_queryset()\n\nclass PlModelMixIn(object):\n # Provides useful methods for computing which objects in a model have\n # changed. Make sure to do self._initial = self._dict in the __init__\n # method.\n\n # Also includes useful utility, like getValidators\n\n # This is broken out of XOSBase into a Mixin so the User model can\n # also make use of it.\n\n @property\n def _dict(self):\n return model_to_dict(self, fields=[field.name for field in\n self._meta.fields])\n\n def fields_differ(self,f1,f2):\n if isinstance(f1,datetime.datetime) and isinstance(f2,datetime.datetime) and (timezone.is_aware(f1) != timezone.is_aware(f2)):\n return True\n else:\n return (f1 != f2)\n\n @property\n def diff(self):\n d1 = self._initial\n d2 = self._dict\n diffs = [(k, (v, d2[k])) for k, v in d1.items() if self.fields_differ(v,d2[k])]\n return dict(diffs)\n\n @property\n def has_changed(self):\n return bool(self.diff)\n\n @property\n def changed_fields(self):\n if self.is_new:\n return self._dict.keys()\n return self.diff.keys()\n\n @property\n def is_new(self):\n return self.pk is None\n\n def has_field_changed(self, field_name):\n return field_name in self.diff.keys()\n\n def get_field_diff(self, field_name):\n return self.diff.get(field_name, None)\n\n #classmethod\n def getValidators(cls):\n \"\"\" primarily for REST API, return a dictionary of field names mapped\n to lists of the type of validations that need to be applied to\n those fields.\n \"\"\"\n validators = {}\n for field in cls._meta.fields:\n l = []\n if field.blank==False:\n l.append(\"notBlank\")\n if field.__class__.__name__==\"URLField\":\n l.append(\"url\")\n validators[field.name] = l\n return validators\n\n def get_backend_register(self, k, default=None):\n try:\n return json.loads(self.backend_register).get(k, default)\n except AttributeError:\n return default\n\n def set_backend_register(self, k, v):\n br = {}\n try:\n br=json.loads(self.backend_register)\n except AttributeError:\n br={}\n\n br[k] = v\n self.backend_register = json.dumps(br)\n\n def get_backend_details(self):\n try:\n scratchpad = json.loads(self.backend_register)\n except AttributeError:\n return (None, None, None, None)\n\n try:\n exponent = scratchpad['exponent']\n except KeyError:\n exponent = None\n\n try:\n last_success_time = scratchpad['last_success']\n dt = datetime.datetime.fromtimestamp(last_success_time)\n last_success = dt.strftime(\"%Y-%m-%d %H:%M\")\n except KeyError:\n last_success = None\n\n try:\n failures = scratchpad['failures']\n except KeyError:\n failures=None\n\n try:\n last_failure_time = scratchpad['last_failure']\n dt = datetime.datetime.fromtimestamp(last_failure_time)\n last_failure = dt.strftime(\"%Y-%m-%d %H:%M\")\n except KeyError:\n last_failure = None\n\n return (exponent, last_success, last_failure, failures)\n\n def get_backend_icon(self):\n is_perfect = (self.backend_status is not None) and self.backend_status.startswith(\"1 -\")\n is_good = (self.backend_status is not None) and (self.backend_status.startswith(\"0 -\") or self.backend_status.startswith(\"1 -\"))\n is_provisioning = self.backend_status is None or self.backend_status == \"Provisioning in progress\" or self.backend_status==\"\"\n\n # returns (icon_name, tooltip)\n if (self.enacted is not None) and (self.enacted >= self.updated and is_good) or is_perfect:\n return (\"success\", \"successfully enacted\")\n else:\n if is_good or is_provisioning:\n return (\"clock\", \"Pending sync, last_status = \" + html_escape(self.backend_status, quote=True))\n else:\n return (\"error\", html_escape(self.backend_status, quote=True))\n\n def enforce_choices(self, field, choices):\n choices = [x[0] for x in choices]\n for choice in choices:\n if field==choice:\n return\n if (choice==None) and (field==\"\"):\n # allow \"\" and None to be equivalent\n return\n raise Exception(\"Field value %s is not in %s\" % (field, str(choices)))\n\n def serialize_for_redis(self):\n \"\"\" Serialize the object for posting to redis.\n\n The API serializes ForeignKey fields by naming them _id\n whereas model_to_dict leaves them with the original name. Modify\n the results of model_to_dict to provide the same fieldnames.\n \"\"\"\n\n field_types = {}\n for f in self._meta.fields:\n field_types[f.name] = f.get_internal_type()\n\n fields = model_to_dict(self)\n for k in fields.keys():\n if field_types.get(k,None) == \"ForeignKey\":\n new_key_name = \"%s_id\" % k\n if (k in fields) and (new_key_name not in fields):\n fields[new_key_name] = fields[k]\n del fields[k]\n\n return fields\n\n def push_redis_event(self):\n # Transmit update via Redis\n try:\n r = redis.Redis(\"redis\")\n # NOTE the redis event has been extended with model properties to facilitate the support of real time notification in the UI\n # keep this monitored for performance reasons and eventually revert it back to fetch model properties via the REST API\n model = self.serialize_for_redis()\n bases = inspect.getmro(self.__class__)\n # bases = [x for x in bases if issubclass(x, XOSBase)]\n class_names = \",\".join([x.__name__ for x in bases])\n model['class_names'] = class_names\n payload = json.dumps({'pk': self.pk, 'changed_fields': self.changed_fields, 'object': model}, default=date_handler)\n r.publish(self.__class__.__name__, payload)\n except ConnectionError:\n # Redis not running.\n # TODO add log statement\n pass\n\n# For cascading deletes, we need a Collector that doesn't do fastdelete,\n# so we get a full list of models.\nclass XOSCollector(Collector):\n def can_fast_delete(self, *args, **kwargs):\n return False\n\nclass ModelLink:\n def __init__(self,dest,via,into=None):\n self.dest=dest\n self.via=via\n self.into=into\n\n","sub_path":"xos/core/models/attic/xosbase_header.py","file_name":"xosbase_header.py","file_ext":"py","file_size_in_byte":9408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"306681325","text":"# XMLValidator\n# Based upon https://emredjan.github.io/blog/2017/04/08/validating-xml/\n# Version 1.4\n# Fabrice Kinnar - 2019\n\n# Import required modules\nfrom lxml import etree # etree, to read XML\nfrom io import StringIO # StringIo, to pass strings as files to etree\n\n# XMLValidator Class\n#\n# Allow the user to check the validity of a XML file\n# If no XSD schema is given, only the XML syntax is tested\n# If both XML and XSD are given, XML and XSD syntaxes are tested, then the validity of the XML is cheched\n#\n# PUBLIC INTERFACE:\n# - XMLValidator(xml_filename [, xsd_filename]) : Constructor\n# - check() : Check XML file\n# - get_xml_document() : Get the current XML document\nclass XMLValidator:\n # CONSTRUCTOR\n # Initialise private members and open files\n def __init__(self, xml_filename, xsd_filename=None):\n # Name of the XML file\n self.__xml_filename = xml_filename.strip() if xml_filename != None else None\n # Name of the XSD file\n self.__xsd_filename = xsd_filename.strip() if xsd_filename != None else None\n # Handler of the XML and XSD file\n # Set to None here, so in __open_files fails, we know at destruction time that the file is not opened (and does not need to be closed)\n self.__xml_file = None\n self.__xsd_file = None\n # Parsed XML document\n self.__xml_document = None\n # Parsed XSD document\n self.__xsd_document = None\n # Parsed XSD schema\n self.__xml_schema = None\n\n # PUBLIC ACCESSORS\n def get_xml_filename(self):\n return self.__xml_filename\n\n def get_xsd_filename(self):\n return self.__xsd_filename\n\n def get_xml_document(self):\n return self.__xml_document\n\n def get_xsd_document(self):\n return self.__xsd_document\n\n def get_xml_schema(self):\n return self.__xml_schema\n\n # PUBLIC: check\n # Checks the validity of the XML file\n # Returns:\n # - on problem: a tuple (errorCode, errorMessage, parsingLog)\n # - on ok: None\n def check(self):\n rc = self.__open_files()\n # Files can be opened\n if rc == None:\n # Is the structure of the XML document OK ?\n rc = self.__test_xml()\n if rc == None:\n # Is the structure of the XSD document OK ?\n rc = self.__test_xsd()\n if rc == None:\n # Does the XML document comply to the XSD\n rc = self.__test_schema()\n # Return the result code\n return rc\n\n # PUBLIC: get_xml_document\n # Returns the current XML document\n def get_xml_document(self):\n return self.__xml_document\n\n # DESTRUCTOR\n # Closes all files if needed\n def __del__(self):\n if self.__xml_file != None:\n self.__xml_file.close()\n if self.__xsd_file != None:\n self.__xsd_file.close()\n\n # PRIVATE: __parse_xml_document\n # Parse a XML document from file\n # Throw exceptions on error:\n # - on IO problem: IOError\n # - on Invalid XML: etree.XMLSyntaxError\n # - on UnicodeDecodeError\n def __parse_xml_document(self, xml_file):\n # Just in case the method is called several times\n xml_file.seek(0)\n # Read the file\n xml_to_check = xml_file.read()\n\n # Try to parse what we've just read\n return etree.parse(StringIO(xml_to_check))\n\n # PRIVATE: __parse_xml\n # Parse the XML file\n # Throw exceptions on error:\n # - on IO problem: IOError\n # - on Invalid XML: etree.XMLSyntaxError\n def __parse_xml(self):\n # Do nothing if there is no XML file\n if self.__xml_file == None:\n return None\n # Try to parse the XML file and keep the returned document to not parse it again on future call\n if self.__xml_document == None:\n self.__xml_document = self.__parse_xml_document(self.__xml_file)\n # Return the document\n return self.__xml_document\n\n # PRIVATE: __parse_xsd\n # Parse the XSD file\n # Throw exceptions on error:\n # - on IO problem: IOError\n # - on Invalid XML: etree.XMLSyntaxError\n def __parse_xsd(self):\n # Do nothing if there is no XSD file\n if self.__xsd_file == None:\n return None\n # Try to parse the XSD file and keep the returned document to not parse it again on future call\n if self.__xsd_document == None:\n self.__xsd_document = self.__parse_xml_document(self.__xsd_file)\n # Return the document\n return self.__xsd_document\n\n # PRIVATE: __validate_schema\n # Validate the XML regarding the XSD schema\n # Throw exceptions on error:\n # - on IO problem: IOError\n # - on Invalid XML: etree.DocumentInvalid\n def __validate_schema(self):\n # Do nothing if there is no XSD file\n if self.__xsd_file == None:\n return None\n # Try to validate the XML document according to the schema\n self.__xml_schema = etree.XMLSchema(self.__xsd_document)\n self.__xml_schema.assertValid(self.__xml_document)\n # Return the schema\n return self.__xml_schema\n\n # PRIVATE: __open_files\n # Opens provided files if possible\n # Returns:\n # - on problem: a tuple (errorCode, errorMessage, None)\n # - on ok : None\n def __open_files(self):\n rc = None\n try:\n # Handle of the XML file\n self.__xml_file = (\n open(self.__xml_filename, \"r\") if self.__xml_filename != None else None\n )\n # Handle of the XSD file\n self.__xsd_file = (\n open(self.__xsd_filename, \"r\") if self.__xsd_filename != None else None\n )\n except FileNotFoundError as e:\n # Provided files cannot be opened\n rc = (-41, \"!! File \" + e.filename + \" not found !!\", None)\n return rc\n\n # PRIVATE: __test_xml\n # Checks the validity of the XML file\n # Returns:\n # - on problem: a tuple (errorCode, errorMessage, parsingLog)\n # - on ok: None\n def __test_xml(self):\n rc = None\n try:\n # Try to parse the XML file\n self.__parse_xml()\n except IOError:\n # EXCEPTION: IO error\n rc = (-11, \"!! IO error !!\", None)\n except etree.XMLSyntaxError as e:\n # EXCEPTION: XML sytax error\n rc = (-12, \"!! XML syntax error !!\", e.error_log)\n except UnicodeDecodeError as e:\n # EXCEPTION: XML unicode decoding error\n rc = (-13, \"!! XML unicode error !!\", \"Position : \" + str(e.start))\n # Return the result code\n return rc\n\n # PRIVATE: __test_xsd\n # Checks the validity of the XSD file\n # Returns:\n # - on problem: a tuple (errorCode, errorMessage, parsingLog)\n # - on ok: None\n def __test_xsd(self):\n rc = None\n try:\n # Try to parse the XSD file\n self.__parse_xsd()\n except IOError:\n # EXCEPTION: IO error\n rc = (-21, \"!! IO error !!\", None)\n except etree.XMLSyntaxError as e:\n # EXCEPTION: XML sytax error\n rc = (-22, \"!! XML syntax error !!\", e.error_log)\n except UnicodeDecodeError as e:\n # EXCEPTION: XML unicode decoding error\n rc = (-23, \"!! XML unicode error !!\", \"Position : \" + str(e.start))\n # Return the result code\n return rc\n\n # PRIVATE: __test_schema\n # Checks the validity of the XML file according to the XSD schema\n # Returns:\n # - on problem: a tuple (errorCode, errorMessage, parsingLog)\n # - on ok: None\n def __test_schema(self):\n rc = None\n try:\n self.__validate_schema()\n except IOError:\n # EXCEPTION: IO error\n rc = (-31, \"!! IO error !!\", None)\n except etree.DocumentInvalid as e:\n # EXCEPTION: XML schema error\n rc = (-32, \"!! XML schema error !!\", e.error_log)\n # Return the result code\n return rc\n","sub_path":"xmlvalidator.py","file_name":"xmlvalidator.py","file_ext":"py","file_size_in_byte":8085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"589390932","text":"import os\nimport time\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nfrom torchvision import datasets\nfrom torchvision import transforms\n\nfrom augmentations import AugmixDataset\nfrom WideResNet_pytorch.wideresnet import WideResNet\n\nPATH = \"./ckpt/augmix.ckpt\"\n\nCORRUPTIONS = [\n 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur',\n 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog',\n 'brightness', 'contrast', 'elastic_transform', 'pixelate',\n 'jpeg_compression'\n]\n\n_CIFAR_MEAN, _CIFAR_STD = (0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)\n\ndef test(model, test_data, batch_size):\n test_loader = torch.utils.data.DataLoader(\n test_data,\n batch_size=batch_size,\n shuffle=False,\n pin_memory=True)\n with torch.no_grad():\n model.eval()\n total = 0\n correct = 0\n for i, (images, targets) in enumerate(test_loader):\n images, targets = images.cuda(), targets.cuda()\n logits = model(images)\n logits = torch.argmax(logits, dim=-1)\n correct += targets.eq(logits).sum().item()\n total += targets.size()[0]\n acc = correct * 1. / total\n return acc\n\ndef main():\n torch.manual_seed(2020)\n np.random.seed(2020)\n epochs = 100\n js_loss = True\n model_load = False\n lmbda = 12\n batch_size = 256\n dataset = \"CIFAR-10\"\n os.makedirs('./ckpt/', exist_ok=True)\n\n # 1. dataload\n # basic augmentation & preprocessing\n train_base_aug = [\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32, padding=4)\n ]\n preprocess = [\n transforms.ToTensor(),\n transforms.Normalize(_CIFAR_MEAN, _CIFAR_STD)\n ]\n if js_loss: \n train_transform = transforms.Compose(train_base_aug)\n else:\n train_transform = transforms.Compose(train_base_aug + preprocess)\n test_transform = transforms.Compose(preprocess)\n # load data\n if dataset == \"CIFAR-10\":\n train_data = datasets.CIFAR10('./data/cifar', train=True, transform=train_transform, download=True)\n test_data = datasets.CIFAR10('./data/cifar', train=False, transform=test_transform, download=True)\n else:\n train_data = datasets.CIFAR100('./data/cifar', train=True, transform=train_transform, download=True)\n test_data = datasets.CIFAR100('./data/cifar', train=False, transform=test_transform, download=True)\n if js_loss:\n train_data = AugmixDataset(train_data, test_transform)\n train_loader = torch.utils.data.DataLoader(\n train_data,\n batch_size=batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=True)\n # 2. model\n # wideresnet 40-2\n n_classes = 10 if dataset==\"CIFAR-10\" else 100\n model = WideResNet(depth=40, num_classes=n_classes, widen_factor=2, drop_rate=0.0)\n\n # 3. Optimizer & Scheduler\n optimizer = torch.optim.SGD(\n model.parameters(),\n 0.1,\n momentum=0.9,\n weight_decay=0.0005,\n nesterov=True)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs*len(train_loader), eta_min=1e-6, last_epoch=-1)\n\n model = nn.DataParallel(model).cuda()\n cudnn.benchmark = True\n if not model_load:\n # training model with cifar100\n model.train()\n losses = []\n start = time.time()\n for epoch in range(epochs):\n for i, (images, targets) in tqdm(enumerate(train_loader)):\n if js_loss:\n images = torch.cat(images, axis=0)\n images, targets = images.cuda(), targets.cuda()\n optimizer.zero_grad()\n if js_loss:\n logits = model(images)\n shape = targets.size()[0]\n loss = F.cross_entropy(logits[:shape], targets)\n p_origin, p_aug1, p_aug2 = F.softmax(logits[:shape], dim=-1), F.softmax(logits[shape:2*shape], dim=-1), F.softmax(logits[shape*2:], dim = -1)\n M = torch.clamp((p_origin + p_aug1 + p_aug2) / 3., min= 1e-7, max=1.).log()\n loss += lmbda * (F.kl_div(M, p_origin, reduction='batchmean')+F.kl_div(M, p_aug1, reduction='batchmean')+F.kl_div(M, p_aug2, reduction='batchmean')) / 3.\n else:\n logits = model(images)\n loss = F.cross_entropy(logits, targets)\n loss.backward()\n optimizer.step()\n scheduler.step()\n losses.append(loss.item())\n if epoch == 0:\n print(\"Time takes for 1 epochs: %s\" %(time.time()-start))\n print(\"Train Loss: {:.4f}\".format(loss.item()))\n torch.save({\n \"epoch\": epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'losses': losses\n }, PATH)\n else:\n ckpt = torch.load(PATH)\n model.load_state_dict(ckpt[\"model_state_dict\"])\n # calculate clean error\n acc = test(model, test_data, 2000)\n print(\"[TEST] CLEAN Accuracy : {:.2f}\".format(acc))\n \n # evaluate on cifar100-c\n CEs = []\n for corruption in CORRUPTIONS:\n test_data.data = np.load('./data/cifar/'+dataset+'-C/%s.npy' % corruption)\n test_data.targets = torch.LongTensor(np.load('./data/cifar/'+dataset+'-C/labels.npy'))\n acc = test(model, test_data, 2000)\n print(\"%s: %f\" %(corruption, 1-acc))\n CEs.append(1-acc)\n mCE = sum(CEs) / len(CEs)\n print(\"[TEST] mCE : {:.2f}\".format(mCE))\n\nif __name__==\"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"352882636","text":"import struct\nimport sys\nimport hashlib\n\n__all__ = [\n 'Uint64', 'Uint32', 'Uint16', 'Uint8',\n 'Int64', 'Int32', 'Int16', 'Int8',\n 'Float', 'Double', 'Bool',\n 'serializable',\n 'polymorphic',\n 'Vector', 'Array', 'BasicString', 'String', 'WString',\n 'MemoryInputArchive', 'MemoryOutputArchive'\n ]\n\ndef make_function(name, code):\n environment = dict()\n environment.update(serialization_exports)\n exec(code, environment)\n return environment[name]\n\nclass SerializationGenerator(object):\n class Code(list):\n def __init__(self):\n super(SerializationGenerator.Code, self).__init__(self)\n self.level = 0\n self.tag = None\n\n def __iadd__(self, lines):\n self.tag = None\n new_lines = []\n for line in lines:\n for line in line.split('\\n'):\n new_lines += [''.join((' ' * 4 * self.level, line))]\n super(SerializationGenerator.Code, self).__iadd__(new_lines)\n return self\n\n def append_with_tag(self, tag, lines):\n result = self.__iadd__(lines)\n self.tag = tag\n return result\n\n def tag(self):\n return self.tag\n\n def __init__(self, cls, archive_type):\n if archive_type in output_archives:\n self.mode = 'serialize'\n elif archive_type in input_archives:\n self.mode = 'deserialize'\n else:\n raise TypeError(\"Invalid archive type.\")\n\n self.function_name = '_'.join(('optimized', self.mode, cls.__name__))\n self.cls = cls\n self.archive_type = archive_type\n self.code = self.Code()\n self.code += [''.join(('def ', self.function_name, '(self, archive):'))]\n self.code.level += 1\n self.item_id = 0\n self.shortcut_id = 0\n self.index_id = 0\n self.archive_generator = self.archive_type.CodeGenerator(self.code)\n\n def generate_code(self):\n self.archive_generator.generate_start()\n self._generate_code(self.cls, 'self')\n self.archive_generator.generate_end()\n zpp_class = self.cls.__zpp_class__\n if self.mode == 'deserialize':\n if hasattr(zpp_class, 'serialization_id') or zpp_class.fundamental:\n self.code += ['return self']\n return ('_'.join((self.archive_type.name, self.mode)), self.make_function())\n\n def _item_id(self):\n item_id = self.item_id\n self.item_id += 1\n return item_id\n\n def _shortcut_id(self):\n shortcut_id = self.shortcut_id\n self.shortcut_id += 1\n return shortcut_id\n\n def _index_id(self):\n index_id = self.index_id\n self.index_id += 1\n return index_id\n\n def _generate_code(self, cls, variable_name):\n if not hasattr(cls, '__zpp_class__'):\n self.archive_generator.generate(cls, variable_name)\n return\n\n if cls.__zpp_class__.trivially_copyable:\n self.archive_generator.generate(cls, variable_name)\n return\n\n if cls.__zpp_class__.container:\n if not hasattr(cls.__zpp_class__, 'array_size'):\n if self.mode == 'serialize':\n self._generate_code(SizeType,\n 'SizeType(len({variable_name}))'.format(\n variable_name=variable_name))\n else:\n self._generate_code(SizeType, 'container_size')\n\n if cls.element.__zpp_class__.trivially_copyable:\n context = type('context', (object,),\n {'container_element_size': cls.element.__zpp_class__.size})\n return self.archive_generator.generate(bytearray,\n '{variable_name}.data'.format(\n variable_name=variable_name),\n context=context)\n else:\n if self.mode == 'deserialize':\n if hasattr(cls.element.__zpp_class__, 'serialization_id'):\n index_name = '_'.join(('index', str(self._index_id())))\n self.archive_generator.generate_enter_loop()\n self.code += [\n '{variable_name}.items = [None] * container_size' '\\n'\n 'for {index} in xrange(container_size):'.format(\n index=index_name)\n ]\n self.code.level += 1\n self._generate_code(cls.element,\n '{variable_name}[{index}]'.format(\n variable_name=variable_name,\n index=index_name))\n self.code.level -= 1\n self.index_id -= 1\n self.archive_generator.generate_exit_loop()\n return\n\n if not hasattr(cls.__zpp_class__, 'array_size'):\n self.code += [\n '{variable_name}.items = '\n 'tuple({variable_name}.element() for i in xrange(container_size))'.format(\n variable_name=variable_name)\n ]\n\n item_name = '_'.join(('item', str(self._item_id())))\n self.archive_generator.generate_enter_loop()\n self.code += [\n 'for {item} in {variable_name}:'.format(\n variable_name=variable_name,\n item=item_name)\n ]\n self.code.level += 1\n self._generate_code(cls.element, item_name)\n self.code.level -= 1\n self.archive_generator.generate_exit_loop()\n self.item_id -= 1\n return\n\n is_polymorphic = hasattr(cls.__zpp_class__, 'serialization_id')\n\n shortcut_set = False\n if '.' in variable_name and not (is_polymorphic and self.mode == 'deserialize'):\n shortcut_set = True\n shortcut = '_'.join(('current', str(self._shortcut_id())))\n self.code += [\n '{shortcut} = {variable_name}'.format(shortcut=shortcut,\n variable_name=variable_name)\n ]\n variable_name = shortcut\n\n if hasattr(cls.__zpp_class__, 'serialization_id'):\n if self.mode == 'serialize':\n self._generate_code(Uint64,\n '{variable_name}.__zpp_class__.serialization_id'.format(\n variable_name=variable_name))\n else:\n self._generate_code(Uint64, 'serialization_id')\n self.archive_generator.generate_flush()\n self.code += [\n '{variable_name} = registry[serialization_id]()' '\\n'\n '{variable_name}.{deserialize}({variable_name}, archive)'.format(\n variable_name=variable_name,\n deserialize='_'.join(('__zpp_class__.non_polymorphic',\n self.archive_type.name,\n 'deserialize')))\n ]\n self.archive_generator.generate_reload()\n if shortcut_set:\n self.shortcut_id -= 1\n return\n\n for member in cls.__zpp_class__.members:\n self._generate_code(getattr(cls, member),\n '.'.join((variable_name, member)))\n if shortcut_set:\n self.shortcut_id -= 1\n\n def make_function(self):\n return make_function(self.function_name, '\\n'.join(self.code))\n\nclass serializable(object):\n def __init__(self):\n self.previous_trace = sys.gettrace()\n sys.settrace(self.trace)\n\n def __call__(self, cls):\n base_members = tuple()\n trivially_copyable = True\n bases_size = 0\n for base in cls.__bases__:\n if hasattr(base, '__zpp_class__'):\n base_members += base.__zpp_class__.members\n if base.__zpp_class__.trivially_copyable:\n bases_size += base.__zpp_class__.size\n else:\n trivially_copyable = False\n\n derived_members = tuple(name for name in self.names \\\n if hasattr(cls, name) and hasattr(getattr(cls, name), '__zpp_class__'))\n for derived_member in derived_members:\n derived_member = getattr(cls, derived_member)\n if not derived_member.__zpp_class__.trivially_copyable:\n trivially_copyable = False\n\n if trivially_copyable and not hasattr(self, 'serialization_id'):\n size = bases_size + sum(getattr(cls, derived_member).__zpp_class__.size \\\n for derived_member in derived_members)\n return self.trivially_copyable(cls, bases_size, size, base_members, derived_members)\n\n return self.non_trivially_copyable(cls, base_members, derived_members)\n\n def non_trivially_copyable(self, cls, base_members, derived_members):\n def constructor(self, *args, **kwargs):\n def initialize_bases(cls):\n for base in cls.__bases__:\n if not hasattr(base, '__zpp_class__'):\n super(cls, self).__init__()\n continue\n\n initialize_bases(base)\n\n for name, member in base.__dict__.iteritems():\n if hasattr(member, '__zpp_class__'):\n object.__setattr__(self, name, member())\n\n initialize_bases(type(self))\n\n for name, member in type(self).__dict__.iteritems():\n if hasattr(member, '__zpp_class__'):\n object.__setattr__(self, name, member())\n\n user_defined_constructor = self.__zpp_class__.user_defined_constructor\n\n if args and not user_defined_constructor:\n if len(args) != 1:\n raise TypeError(\"Invalid argument was sent.\")\n item = args[0]\n for name in self.__zpp_class__.members:\n if hasattr(item, name):\n try:\n setattr(self, name, getattr(item, name))\n except Exception as error:\n setattr(self, name, getattr(item, name)())\n\n unordered_members = self.__zpp_class__.unordered_members\n for name, value in kwargs.iteritems():\n if name in unordered_members:\n setattr(self, name, value)\n\n user_defined_constructor = self.__zpp_class__.user_defined_constructor\n if user_defined_constructor:\n user_defined_constructor(self, *args, **{name: value for name, value in kwargs if name not in unordered_members})\n\n def copy_constructor(self, other):\n def initialize_bases(cls):\n for base in cls.__bases__:\n if not hasattr(base, '__zpp_class__'):\n super(cls, self).__init__()\n continue\n\n initialize_bases(base)\n\n for name, member in base.__dict__.items():\n if hasattr(member, '__zpp_class__'):\n object.__setattr__(self, name, member())\n\n initialize_bases(type(self))\n\n for name, member in type(self).__dict__.items():\n if hasattr(member, '__zpp_class__'):\n object.__setattr__(self, name, member())\n\n for name in self.__zpp_class__.members:\n try:\n setattr(self, name, getattr(other, name))\n except Exception as error:\n setattr(self, name, getattr(other, name)())\n\n def assign(self, name, value):\n try:\n member_type = getattr(type(self), name)\n return object.__setattr__(self, name, member_type.__zpp_class__.make(value))\n except AttributeError as error:\n raise TypeError(\"Type '%s' has no member named '%s'.\" % (type(self).__name__, name))\n\n def to_string(self, level=0, name=None):\n prefix = ' ' * level * 4\n if name:\n result = prefix + name + \": class \" + type(self).__name__ + \" {\\n\"\n else:\n result = prefix + \"class \" + type(self).__name__ + \" {\\n\"\n level += 1\n prefix = ' ' * level * 4\n for name in self.__zpp_class__.members:\n member = getattr(self, name)\n if member.__zpp_class__.fundamental:\n result += prefix + '%s: %s(%s),\\n' % (name, type(member).__name__, member)\n else:\n result += member.__str__(level, name) + ',\\n'\n level -= 1\n prefix = ' ' * level * 4\n result += prefix + '}'\n return result\n\n cls_members = base_members + derived_members\n\n members = dict(cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'members': cls_members,\n 'unordered_members': set(cls_members),\n 'fundamental': False,\n 'container': False,\n 'trivially_copyable': False,\n 'copy_constructor': staticmethod(copy_constructor),\n 'user_defined_constructor': cls.__init__ if cls.__init__ not in (base.__init__ for base in cls.__bases__) else None,\n }),\n '__init__': constructor,\n '__setattr__': assign,\n '__getattribute__': object.__getattribute__,\n '__str__': to_string,\n '__repr__': to_string,\n })\n\n cls = type(cls.__name__, cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n def make(value):\n obj = cls.__new__(cls)\n copy_constructor(obj, value)\n return obj\n\n cls.__zpp_class__.make = staticmethod(make)\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else make(value))\n return cls\n\n def trivially_copyable(self, cls, base_sizes, size, base_members, derived_members):\n def constructor(self, *args, **kwargs):\n if '__zpp_data__' in kwargs:\n object.__setattr__(self, '__zpp_data__', kwargs['__zpp_data__'])\n return\n else:\n object.__setattr__(self, '__zpp_data__', bytearray(type(self).__zpp_class__.size))\n\n user_defined_constructor = self.__zpp_class__.user_defined_constructor\n\n if args and not user_defined_constructor:\n if len(args) != 1:\n raise TypeError(\"Invalid argument was sent.\")\n item = args[0]\n for name in self.__zpp_class__.members:\n try:\n setattr(self, name, getattr(item, name))\n except Exception as error:\n setattr(self, name, getattr(item, name)())\n\n unordered_members = self.__zpp_class__.unordered_members\n for name, value in kwargs.items():\n if name in unordered_members:\n setattr(self, name, value)\n\n user_defined_constructor = self.__zpp_class__.user_defined_constructor\n if user_defined_constructor:\n user_defined_constructor(self, *args, **{name: value for name, value in kwargs if name not in unordered_members})\n\n def copy_constructor(self, other):\n object.__setattr__(self, '__zpp_data__', bytearray(type(self).__zpp_class__.size))\n\n for name in self.__zpp_class__.members:\n try:\n setattr(self, name, getattr(other, name))\n except Exception as error:\n setattr(self, name, getattr(other, name)())\n\n def at(self, name):\n attribute = object.__getattribute__(self, name)\n if not hasattr(attribute, '__zpp_class__'):\n return attribute\n zpp_class = type(self).__zpp_class__\n if name not in zpp_class.offsets:\n return attribute\n member_type = attribute\n offset = zpp_class.offsets[name]\n if member_type.__zpp_class__.fundamental:\n size = member_type.__zpp_class__.size\n return member_type(member_type.deserialize(\n memoryview(self.__zpp_data__)[offset:offset+size])[0])\n size = member_type.__zpp_class__.size\n return member_type(__zpp_data__=memoryview(self.__zpp_data__)[offset:offset+size])\n\n def assign(self, name, value):\n zpp_class = type(self).__zpp_class__\n if name not in zpp_class.unordered_members:\n return object.__setattr__(self, name, value)\n member_type = getattr(type(self), name)\n offset = zpp_class.offsets[name]\n size = member_type.__zpp_class__.size\n if member_type.__zpp_class__.fundamental:\n self.__zpp_data__[offset:offset+size] = member_type.serialize(member_type(value))\n return\n if member_type.__zpp_class__.container and hasattr(value, '__len__'):\n member_type(value, __zpp_data__=memoryview(self.__zpp_data__)[offset:offset+size])\n return\n if member_type != type(value):\n raise TypeError(\"Cannot convert from '%s' to '%s'.\" % (type(value), member_type))\n self.__zpp_data__[offset:offset+size] = value.__zpp_data__\n\n def to_string(self, level=0, name=None):\n prefix = ' ' * level * 4\n if name:\n result = prefix + name + \": class \" + type(self).__name__ + \" {\\n\"\n else:\n result = prefix + \"class \" + type(self).__name__ + \" {\\n\"\n level += 1\n prefix = ' ' * level * 4\n for name in self.__zpp_class__.members:\n member = getattr(self, name)\n if member.__zpp_class__.fundamental:\n result += prefix + '%s: %s(%s),\\n' % (name, type(member).__name__, member)\n else:\n result += member.__str__(level, name) + ',\\n'\n level -= 1\n prefix = ' ' * level * 4\n result += prefix + '}'\n return result\n\n cls_members = base_members + derived_members\n offsets = dict()\n offset = 0\n for member in cls_members:\n offsets[member] = offset\n offset += getattr(cls, member).__zpp_class__.size\n\n members = dict(cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'members': cls_members,\n 'unordered_members': set(cls_members),\n 'fundamental': False,\n 'container': False,\n 'trivially_copyable': True,\n 'offsets': offsets,\n 'size': size,\n 'copy_constructor': staticmethod(copy_constructor),\n 'user_defined_constructor': cls.__init__ if cls.__init__ not in (base.__init__ for base in cls.__bases__) else None,\n }),\n '__init__': constructor,\n '__getattribute__': at,\n '__setattr__': assign,\n '__str__': to_string,\n '__repr__': to_string,\n })\n\n cls = type(cls.__name__, cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n def make(value):\n obj = cls.__new__(cls)\n copy_constructor(obj, value)\n return obj\n\n cls.__zpp_class__.make = staticmethod(make)\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else make(value))\n return cls\n\n def trace(self, frame, event, argument):\n self.names = [name for name in frame.f_code.co_names if not name.startswith('_')]\n sys.settrace(self.previous_trace)\n\nclass polymorphic(serializable):\n registry = dict()\n\n def __init__(self, identifier):\n self.serialization_id = Uint64.deserialize(hashlib.sha1(identifier.encode('ascii')).digest()[:8])[0]\n super(polymorphic, self).__init__()\n\n def __call__(self, cls):\n cls = super(polymorphic, self).__call__(cls)\n cls.__zpp_class__.serialization_id = self.serialization_id\n cls.__zpp_class__.trivially_copyable = False\n\n cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))\n for output_archive in output_archives:\n function_name, function = SerializationGenerator(cls, output_archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n for input_archive in input_archives:\n function_name, function = SerializationGenerator(cls, input_archive).generate_code()\n setattr(cls.__zpp_class__, '_'.join(('non_polymorphic', function_name)),\n staticmethod(getattr(cls.__zpp_class__, function_name)))\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n self.registry[self.serialization_id] = cls\n\n def make(value):\n if isinstance(value, cls):\n obj = type(value).__new__(type(value))\n obj.__zpp_class__.copy_constructor(obj, value)\n return obj\n obj = cls.__new__(cls)\n obj.__zpp_class__.copy_constructor(obj, value)\n return obj\n\n cls.__zpp_class__.make = staticmethod(make)\n cls.__zpp_class__.make_view = staticmethod(make)\n return cls\n\ndef printable_container(cls):\n def to_string(self, level=0, name=None):\n prefix = ' ' * level * 4\n if name:\n result = prefix + name + \": class \" + type(self).__name__ + \\\n '<' + self.element.__name__ + '>' + \" {\\n\"\n else:\n result = prefix + \"class \" + type(self).__name__ + \" {\\n\"\n level += 1\n prefix = ' ' * level * 4\n if self.element.__zpp_class__.fundamental:\n for index, item in enumerate(self):\n result += prefix + '[%s]: %s,\\n' % (index, item)\n else:\n for index, item in enumerate(self):\n result += item.__str__(level, name='[' + str(index) + ']') + ',\\n'\n level -= 1\n prefix = ' ' * level * 4\n result += prefix + '}'\n return result\n\n members = dict(cls.__dict__)\n members.update({\n '__str__': to_string,\n '__repr__': to_string,\n })\n new_class = type(cls.__name__, cls.__bases__, members)\n return new_class\n\nclass make_vector(object):\n def __init__(self, cls):\n self.cls = cls\n\n def __call__(self, element):\n if element.__zpp_class__.fundamental:\n return self.fundamental_vector(element)\n elif element.__zpp_class__.trivially_copyable:\n return self.trivially_copyable_vector(element)\n else:\n return self.vector(element)\n\n def vector(self, element):\n def constructor(self, *args, **kwargs):\n values = None\n size = 0\n if kwargs:\n if args:\n raise TypeError(\"Vector initialized correctly\")\n size = kwargs['size']\n elif args:\n if len(args) != 1:\n raise TypeError(\"Vector initialized correctly\")\n size = args[0]\n if hasattr(size, '__len__'):\n values = size\n size = len(values)\n\n if values:\n self.items = [self.element.__zpp_class__.make(value) for value in values]\n else:\n self.items = [self.element() for index in range(size)]\n\n def at(self, index):\n return self.items[index]\n\n def assign(self, index, value):\n if type(index) is slice:\n self.items[index] = [self.element.__zpp_class__.make(item) for item in value]\n else:\n self.items[index] = self.element.__zpp_class__.make(value)\n\n def iterate(self):\n return (item for item in self.items)\n\n def size(self):\n return len(self.items)\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': False,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n \n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\n def trivially_copyable_vector(self, element):\n def constructor(self, *args, **kwargs):\n values = []\n count = 0\n if kwargs:\n if args:\n raise TypeError(\"Vector initialized correctly.\")\n count = kwargs['size']\n elif args:\n if len(args) != 1:\n raise TypeError(\"Vector initialized correctly.\")\n count = args[0]\n if hasattr(count, '__len__'):\n values = count\n count = len(values)\n\n size = self.element.__zpp_class__.size\n self.data = bytearray(size * count)\n\n if values:\n for index, value in enumerate(values):\n self.data[index * size : (index + 1) * size] = \\\n self.element.__zpp_class__.make_view(value).__zpp_data__\n\n def at(self, index):\n size = self.element.__zpp_class__.size\n return self.element(__zpp_data__=memoryview(self.data)[index * size : (index + 1) * size])\n\n def assign(self, index, value):\n size = self.element.__zpp_class__.size\n if type(index) is slice:\n for i, item in enumerate(value):\n self.data[(index.start + i) * size : (index.start + i + 1) * size] = \\\n self.element.__zpp_class__.make_view(item).__zpp_data__\n else:\n self.data[index * size : (index + 1) * size] = \\\n self.element.__zpp_class__.make_view(value).__zpp_data__\n\n def iterate(self):\n for index in xrange(len(self.data) // self.element.__zpp_class__.size):\n yield self[index]\n\n def size(self):\n return len(self.data) // self.element.__zpp_class__.size\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': False,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n\n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\n def fundamental_vector(self, element):\n def constructor(self, *args, **kwargs):\n values = []\n count = 0\n if kwargs:\n if args:\n raise TypeError(\"Vector initialized correctly.\")\n count = kwargs['size']\n elif args:\n if len(args) != 1:\n raise TypeError(\"Vector initialized correctly.\")\n count = args[0]\n if hasattr(count, '__len__'):\n values = count\n count = len(values)\n\n self.data = bytearray(count * self.element.__zpp_class__.size)\n out = MemoryOutputArchive(self.data, index=0)\n for value in values:\n out(self.element.__zpp_class__.make_view(value))\n\n def at(self, index):\n size = self.element.__zpp_class__.size\n return self.element(self.element.deserialize(\n memoryview(self.data)[index * size : (index + 1) * size])[0])\n\n def assign(self, index, value):\n size = self.element.__zpp_class__.size\n if type(index) is slice:\n for i, item in enumerate(value):\n self.data[(index.start + i) * size : (index.start + i + 1) * size] = \\\n self.element.serialize(self.element.__zpp_class__.make_view(item))\n else:\n self.data[index * size : (index + 1) * size] = \\\n self.element.serialize(self.element.__zpp_class__.make_view(value))\n\n def iterate(self):\n for index in xrange(len(self.data) // self.element.__zpp_class__.size):\n yield self[index]\n\n def size(self):\n return len(self.data) // self.element.__zpp_class__.size\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': False,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n\n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\nclass make_array(object):\n def __init__(self, cls):\n self.cls = cls\n\n def __call__(self, element, size):\n if element.__zpp_class__.fundamental:\n return self.fundamental_array(element, size)\n elif element.__zpp_class__.trivially_copyable:\n return self.trivially_copyable_array(element, size)\n else:\n return self.array(element, size)\n\n def array(self, element, array_size):\n def constructor(self, values=None):\n if values:\n if len(values) != array_size:\n raise ValueError(\"Array size mismatch.\")\n self.items = [self.element.__zpp_class__.make(value) for value in values]\n else:\n self.items = [self.element() for index in xrange(array_size)]\n\n def at(self, index):\n return self.items[index]\n\n def assign(self, index, value):\n if type(index) is slice:\n if index.stop > array_size:\n raise ValueError(\"This operation will adjust the length of the array.\")\n self.items[index] = [self.element.__zpp_class__.make(item) for item in value]\n else:\n self.items[index] = self.element.__zpp_class__.make(value)\n\n def iterate(self):\n return (item for item in self.items)\n\n def size(self):\n return len(self.items)\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': False,\n 'array_size': array_size,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n\n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\n def trivially_copyable_array(self, element, array_size):\n def constructor(self, values=None, **kwargs):\n if kwargs:\n if '__zpp_data__' not in kwargs or len(kwargs) != 1:\n raise ValueError(\"Invalid argument was sent.\")\n self.__zpp_data__ = kwargs['__zpp_data__']\n else:\n self.__zpp_data__ = bytearray(array_size * self.element.__zpp_class__.size)\n\n if values:\n if len(values) != array_size:\n raise ValueError(\"Array size mismatch.\")\n size = self.element.__zpp_class__.size\n for index, value in enumerate(values):\n self.__zpp_data__[index * size : (index + 1) * size] = \\\n self.element.__zpp_class__.make_view(value).__zpp_data__\n\n def at(self, index):\n size = self.element.__zpp_class__.size\n return self.element(__zpp_data__=memoryview(self.__zpp_data__)[index * size : (index + 1) * size])\n\n def assign(self, index, value):\n size = self.element.__zpp_class__.size\n if type(index) is slice:\n if index.stop > array_size:\n raise ValueError(\"This operation will adjust the length of the array.\")\n for i, item in enumerate(value):\n self.__zpp_data__[(index.start + i) * size : (index.start + i + 1) * size] = \\\n self.element.__zpp_class__.make_view(item).__zpp_data__\n else:\n if index > array_size:\n raise ValueError(\"This operation will adjust the length of the array.\")\n self.__zpp_data__[index * size : (index + 1) * size] = \\\n self.element.__zpp_class__.make_view(value).__zpp_data__\n\n def iterate(self):\n for index in xrange(len(self.__zpp_data__) // self.element.__zpp_class__.size):\n yield self[index]\n\n def size(self):\n return len(self.__zpp_data__) // self.element.__zpp_class__.size\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': True,\n 'size': array_size * element.__zpp_class__.size,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n\n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for archive in archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\n def fundamental_array(self, element, array_size):\n def constructor(self, values=None, **kwargs):\n if kwargs:\n if '__zpp_data__' not in kwargs or len(kwargs) != 1:\n raise ValueError(\"Invalid argument was sent.\")\n self.__zpp_data__ = kwargs['__zpp_data__']\n else:\n self.__zpp_data__ = bytearray(array_size * self.element.__zpp_class__.size)\n\n if values:\n if len(values) != array_size:\n raise ValueError(\"Array size mismatch.\")\n out = MemoryOutputArchive(self.__zpp_data__, index=0)\n for value in values:\n out(self.element(value))\n\n def at(self, index):\n size = self.element.__zpp_class__.size\n return self.element(self.element.deserialize(\n memoryview(self.__zpp_data__)[index * size : (index + 1) * size])[0])\n\n def assign(self, index, value):\n size = self.element.__zpp_class__.size\n if type(index) is slice:\n if index.stop > array_size:\n raise ValueError(\"This operation will adjust the length of the array.\")\n for i, item in enumerate(value):\n self.__zpp_data__[(index.start + i) * size : (index.start + i + 1) * size] = \\\n self.element.serialize(self.element(item))\n else:\n if index > array_size:\n raise ValueError(\"This operation will adjust the length of the array.\")\n self.__zpp_data__[index * size : (index + 1) * size] = \\\n self.element.serialize(self.element(value))\n\n def iterate(self):\n for index in xrange(len(self.__zpp_data__) // self.element.__zpp_class__.size):\n yield self[index]\n\n def size(self):\n return len(self.__zpp_data__) // self.element.__zpp_class__.size\n\n members = dict(self.cls.__dict__)\n members.update({\n '__zpp_class__': type('zpp_class', (object,), {\n 'fundamental': False,\n 'container': True,\n 'trivially_copyable': True,\n 'size': array_size * element.__zpp_class__.size,\n }),\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__iter__': iterate,\n '__len__': size,\n 'element': element,\n })\n\n cls = type(self.cls.__name__, self.cls.__bases__, members)\n for output_archive in output_archives:\n function_name, function = SerializationGenerator(cls, archive).generate_code()\n setattr(cls.__zpp_class__, function_name, staticmethod(function))\n\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\nclass make_basic_string(object):\n def __init__(self, cls):\n self.cls = cls\n\n def __call__(self, element):\n cls = Vector(element)\n\n def constructor(self, values=[]):\n self.data = bytearray(len(values))\n out = MemoryOutputArchive(self.data, index=0)\n for value in values:\n out(self.element(ord(value)))\n\n def at(self, index):\n size = self.element.__zpp_class__.size\n return self.character(self.element.deserialize(\n memoryview(self.data)[index * size : (index + 1) * size])[0])\n\n def assign(self, index, value):\n size = self.element.__zpp_class__.size\n if type(index) is slice:\n for i, item in enumerate(value):\n self.data[(index.start + i) * size : (index.start + i + 1) * size] = \\\n self.element.serialize(self.element(ord(item)))\n else:\n self.data[index * size : (index + 1) * size] = \\\n self.element.serialize(self.element(ord(value)))\n\n def to_string(self, level=0, name=None):\n prefix = ' ' * level * 4\n string = self.data.decode(self.encoding)\n if not level:\n return string\n if name:\n result = prefix + name + \": class \" + type(self).__name__ + \\\n \"('\" + string + \"')\"\n else:\n result = prefix + \": class \" + type(self).__name__ + \\\n \"('\" + string + \"')\"\n return result\n\n members = dict(cls.__dict__)\n members.update({\n '__init__': constructor,\n '__getitem__': at,\n '__setitem__': assign,\n '__str__': to_string,\n '__repr__': to_string,\n 'encoding': 'ascii' if element.__zpp_class__.size == 1 else 'utf-16',\n 'character': staticmethod(lambda value: (chr(value) if element.__zpp_class__.size == 1 else unichr(value)))\n })\n\n name = self.cls.__name__\n if element.__zpp_class__.size == 1:\n name = 'String'\n elif element.__zpp_class__.size == 2:\n name = 'WString'\n\n cls = type(name, cls.__bases__, members)\n cls.__zpp_class__.make = staticmethod(lambda value: cls(value))\n cls.__zpp_class__.make_view = staticmethod(lambda value: value if type(value) == cls else cls(value))\n return cls\n\n@make_vector\n@printable_container\nclass Vector(object):\n pass\n\n@make_array\n@printable_container\nclass Array(object):\n pass\n\n@make_basic_string\nclass BasicString(object):\n pass\n\nclass BasicMemoryArchiveCodeGenerator(object):\n def __init__(self, code):\n self.code = code\n self.index = 0\n self.loop = 0\n self.indices = []\n\n def generate_start(self):\n self.code += [\n 'data = archive.data' '\\n'\n 'index = archive.index'\n ]\n\n def generate_end(self):\n index_string = ' '.join(('+', str(self.index)))\n self.code += [\n 'archive.index = index{index}'.format(index=self._index_string())\n ]\n\n def generate_flush(self):\n self.code += [\n 'archive.index = index{index}'.format(index=self._index_string())\n ]\n\n def generate_reload(self):\n self.code += [\n 'index = archive.index'\n ]\n\n def generate_enter_loop(self):\n self.loop += 1\n self.indices.append(self.index)\n\n def generate_exit_loop(self):\n previous_index = self.indices.pop()\n self.loop -= 1\n self.code.level += 1\n if self.code.tag and 'index_addition_optimization' in self.code.tag:\n self.code.pop()\n expression, addition_immediate = self.code.tag['index_addition_optimization']\n addition_immediate += self.index - previous_index\n self.code += [\n 'index += {expression}{difference}'.format(\n expression=expression,\n difference=self._difference_string(addition_immediate))\n ]\n else:\n self.code += [\n 'index += {difference}'.format(difference=self.index-previous_index)\n ]\n self.index = previous_index\n self.code.level -= 1\n\n def _index_string(self):\n if self.index:\n return ' '.join((' +', str(self.index)))\n return ''\n\n def _index_plus_size_string(self, size):\n if self.index + size:\n return ' '.join((' +', str(self.index + size)))\n return ''\n\n def _difference_string(self, index):\n if index:\n return ' '.join((' +', str(index)))\n return ''\n\nclass MemoryOutputArchive(object):\n name = \"memory\"\n\n class CodeGenerator(BasicMemoryArchiveCodeGenerator):\n def __init__(self, code):\n super(MemoryOutputArchive.CodeGenerator, self).__init__(code)\n\n def generate(self, member_type, variable_name, context=None):\n if not hasattr(member_type, '__zpp_class__'):\n self.code.append_with_tag({'index_addition_optimization': ('size', self.index)}, [\n 'size = len({variable_name})' '\\n'\n 'data[index{index} : index{index} + size] = {variable_name}' '\\n'\n 'index += size{index}'.format(variable_name=variable_name,\n index=self._index_string())\n ])\n self.index = 0\n elif member_type.__zpp_class__.fundamental:\n size = member_type.__zpp_class__.size\n self.code += [\n 'data[index{index} : index{index_plus_size}] = '\n '{member_type}.serialize({variable_name})'.format(\n variable_name=variable_name,\n index=self._index_string(),\n index_plus_size=self._index_plus_size_string(size),\n member_type=member_type.__name__)\n ]\n self.index += size\n elif member_type.__zpp_class__.trivially_copyable:\n size = member_type.__zpp_class__.size\n self.code += [\n 'data[index{index} : index{index_plus_size}] = '\n '{variable_name}.__zpp_data__'.format(\n variable_name=variable_name,\n index=self._index_string(),\n index_plus_size=self._index_plus_size_string(size))\n ]\n self.index += size\n else:\n raise TypeError('Invalid argument of type %s.' % (member_type.__name__,))\n\n def __init__(self, data, index=None):\n self.data = data\n if index is not None:\n self.index = index\n else:\n self.index = len(data)\n\n def __call__(self, *args):\n for item in args:\n type(item).__zpp_class__.memory_serialize(item, self)\n\n def reset(self, index):\n self.index = index\n\nclass MemoryInputArchive(object):\n name = \"memory\"\n\n class CodeGenerator(BasicMemoryArchiveCodeGenerator):\n def __init__(self, code):\n super(MemoryInputArchive.CodeGenerator, self).__init__(code)\n\n def generate(self, member_type, variable_name, context=None):\n if context and hasattr(context, 'container_element_size'):\n self.code.append_with_tag({'index_addition_optimization': ('size', self.index)}, [\n 'size = container_size * {size}' '\\n'\n '{variable_name}[:] = '\n 'memoryview(data)[index{index} : index{index} + size]' '\\n'\n 'index += size{index}'.format(variable_name=variable_name,\n size=context.container_element_size,\n index=self._index_string())\n ])\n self.index = 0\n elif not hasattr(member_type, '__zpp_class__'):\n self.code.append_with_tag({'index_addition_optimization': ('size', self.index)}, [\n 'size = len({variable_name})' '\\n'\n '{variable_name}[:] = '\n 'memoryview(data)[index{index} : index{index} + size]' '\\n'\n 'index += size{index}'.format(variable_name=variable_name,\n index=self._index_string())\n ])\n self.index = 0\n elif member_type.__zpp_class__.fundamental:\n size = member_type.__zpp_class__.size\n self.code += [\n '{variable_name} = {member_type}({member_type}.deserialize('\n 'memoryview(data)[index{index} : index{index_plus_size}])[0])'.format(\n variable_name=variable_name,\n member_type=member_type.__name__,\n index=self._index_string(),\n index_plus_size=self._index_plus_size_string(size))\n ]\n self.index += size\n elif member_type.__zpp_class__.trivially_copyable:\n size = member_type.__zpp_class__.size\n self.code += [\n '{variable_name}.__zpp_data__[:] = '\n 'memoryview(data)[index{index} : index{index_plus_size}]'.format(\n variable_name=variable_name,\n index=self._index_string(),\n index_plus_size=self._index_plus_size_string(size))\n ]\n self.index += size\n else:\n raise TypeError('Invalid argument of type %s.' % (member_type.__name__,))\n\n def __init__(self, data, index=0):\n self.data = data\n self.index = index\n\n def __call__(self, *args):\n return tuple(item.__zpp_class__.memory_deserialize(item, self) for item in args) if \\\n len(args) > 1 else args[0].__zpp_class__.memory_deserialize(args[0], self)\n\n def reset(self, index):\n self.index = index\n\nclass Uint64(long):\n tag = '= self.lower]\n ts = ts.loc[ts.index <= self.upper]\n\n return ts\n\n def run_select_method(self, input):\n \"\"\"Select data from the resampler according to the declared method.\n\n :param str average: arithmetic mean\n :param str instance: sample instance at the resampled time step\n \"\"\"\n\n if self.select_method == 'average':\n output = input.mean()\n if self.select_method == 'instance':\n output = input.asfreq()\n\n return output\n\n def resample_to_freq(self, ts, freq):\n \"\"\"Check the consistency of the time step frequency in a time series.\n Resample time series only if the user-defined data frequency is lower\n than the existing data frequency, and then derive new time series based\n on :func:`~crosscheck_ts.crosscheck_ts.run_select_method`.\n \"\"\"\n\n time_diff = ts.index.to_series().diff()\n\n if len(time_diff[1:].unique()) == 1:\n\n if (freq > time_diff[1].components.minutes)\\\n and (self.select_data == 'end'):\n\n ts = ts.resample(str(freq)+'T', label='right', closed='right')\n\n ts = self.run_select_method(ts)\n\n print()\n print('resampling '+ts.columns.values[0]+' every '+str(freq)\n + ' minutes using the '+self.select_method+' method')\n\n else:\n\n print()\n print(time_diff[1:].unique())\n sys.exit('ERROR: TIME SERIES DOES NOT HAVE CONSTANT TIME STEPS')\n\n return ts\n\n def align_time(self, base, c):\n \"\"\"Align datetime indices of baseline and comparison datasets.\n When the length of the resultant combine data frame does not match\n the user-defined, desired data length, print error messages.\n \"\"\"\n\n base_data = self.trim_ts(base['data'])\n comp_data = self.trim_ts(c['data'])\n\n base_data = self.resample_to_freq(base_data, base['freq'])\n comp_data = self.resample_to_freq(comp_data, c['freq'])\n\n # Match time series data frequencies\n # Set baseline data time series as 1st column\n\n # If averaging method is not defined, then perform a simple merge\n # according to time indices\n if self.select_data is None:\n\n combine_df = pd.merge(\n base_data, comp_data, left_index=True, right_index=True)\n\n print()\n print('performing a simple merge between baseline and')\n print('comparison datasets according to time indices')\n\n # When declared data frequencies differ, resample according to\n # the time indicies of the lower-frequency dataset,\n # calculate the mean of data and record at the end of the time step\n elif self.select_data == 'end':\n\n if base['freq'] < c['freq']:\n\n base_data = base_data.resample(\n str(c['freq'])+'T', label='right', closed='right',\n origin=comp_data.index.min())\n\n base_data = self.run_select_method(base_data)\n\n print()\n print('aligning the '+str(base['freq'])+'-miniute baseline '\n + 'data ('+base_data.columns.values[0]+') to match the ')\n print(str(c['freq'])+'-minute comparison data ('\n + comp_data.columns.values[0]+'), at the end of the')\n print('measurement period using the '\n + self.select_method+' method')\n\n if base['freq'] > c['freq']:\n\n comp_data = comp_data.resample(\n str(base['freq'])+'T', label='right',\n closed='right', origin=base_data.index.min())\n\n comp_data = self.run_select_method(comp_data)\n\n print()\n print('aligning the '+str(c['freq'])+'-miniute comparison '\n + 'data ('+comp_data.columns.values[0]+') to match the ')\n print(str(base['freq'])+'-minute baseline data ('\n + base_data.columns.values[0]+'), at the end of the')\n print('measurement period using the '\n + self.select_method+' method')\n\n combine_df = pd.merge(\n base_data, comp_data, left_index=True, right_index=True)\n\n t_min = combine_df.index.min()\n t_max = combine_df.index.max()\n\n freq = (combine_df.index[1] - t_min).total_seconds() / 60.0\n diff_minute = (t_max - t_min).total_seconds() / 60.0\n\n print()\n print('evaluate '+', '.join(combine_df.columns.values)\n + ' from '+str(t_min)+' to '+str(t_max)\n )\n print('every '+str(freq)+' minutes, total of '+str(len(combine_df))\n + ' time steps')\n\n # data_len = (diff_minute + freq) / freq\n\n desired_period_minute = (self.upper - self.lower).total_seconds()\\\n / 60.0\n\n desired_len = (desired_period_minute + freq) / freq\n\n if diff_minute != desired_period_minute:\n\n print()\n print('!!!!!!!!!!')\n print('WARNING: DESIERED EVALUATION DURATION DOES NOT MATCH '\n + 'DATA DURATION'\n )\n print('DESIRED: FROM '+str(self.lower)+' TO '+str(self.upper))\n print('DATA: FROM '+str(t_min)+' TO '+str(t_max))\n print('!!!!!!!!!!')\n\n # Correct\n if len(combine_df) == desired_len:\n\n pass\n\n else:\n\n print()\n print('!!!!!!!!!!')\n print('WARNING: DATA FREQUENCY DOES NOT MATCH DESIRED '\n + 'EVALUATION PERIOD FREQUENCY')\n print('SHOULD HAVE '+str(desired_len)+' TIME STEPS IN DATA')\n print('ONLY HAVE '+str(len(combine_df))+' TIME STEPS IN DATA')\n print('!!!!!!!!!!')\n\n return combine_df\n","sub_path":"qc/crosscheck_ts.py","file_name":"crosscheck_ts.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"199675764","text":"\"\"\"\n 变量\n 练习:\n exercise01.py\n demo02.py\n\n 程序运行在哪里? 内存\n 程序在处理什么? 数据\n 作用:程序存储数据\n 语法:名称 = 对象\n 本质:内存示意图\n\"\"\"\n\na = \"赵敏\"\nb = \"张无忌\"\na = \"敏儿\"\n# a与b的运算,实际操作的是变量ab所指向的数据。\n# 运算结果产生新的对象\nc = a + b\nprint(c)\n\n#11:25\n# 其他语法\nnum01 = name02 = 500\nnum03 , name04 = 800,1000\n\n\n\n\n\n\n","sub_path":"01-python基础/code/day02/demo02.py","file_name":"demo02.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"194446659","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ramusus/workspace/manufacture_old/env/src/django-facebook-pages-statistic/facebook_pages_statistic/tests.py\n# Compiled at: 2015-03-06 07:16:08\nfrom datetime import datetime\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom facebook_api.signals import facebook_api_post_fetch\nfrom facebook_pages.factories import PageFactory\nfrom facebook_pages.models import Page\nfrom models import PageStatistic\nPAGE_FANS_ID = 19292868552\n\nclass FacebookPagesStatisticTest(TestCase):\n\n def test_page_statistic_create(self):\n self.assertEqual(PageStatistic.objects.count(), 0)\n page = PageFactory(graph_id=PAGE_FANS_ID, likes_count=10, talking_about_count=20)\n self.assertEqual(PageStatistic.objects.count(), 0)\n facebook_api_post_fetch.send(sender=page.__class__, instance=page, created=True)\n self.assertEqual(PageStatistic.objects.count(), 1)\n stat = page.statistics.latest()\n self.assertEqual(stat.likes_count, 10)\n self.assertEqual(stat.talking_about_count, 20)\n self.assertTrue(isinstance(stat.updated_at, datetime))\n page = Page.remote.fetch(PAGE_FANS_ID)\n self.assertEqual(PageStatistic.objects.count(), 2)\n stat = page.statistics.latest()\n self.assertTrue(stat.likes_count > 10)\n self.assertTrue(stat.talking_about_count > 20)\n self.assertTrue(isinstance(stat.updated_at, datetime))\n\n def test_null_stats_test(self):\n page = PageFactory(likes_count=None, talking_about_count=None)\n facebook_api_post_fetch.send(sender=page.__class__, instance=page, created=True)\n self.assertEqual(PageStatistic.objects.count(), 0)\n return","sub_path":"pycfiles/django-facebook-pages-statistic-0.6.0.tar/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"314175917","text":"N = int(input())\nmax_l = 0\nmax_list = []\nfor i in range(N+1):\n result = [N, i]\n j = 0\n while(True):\n a = result[j] - result[j+1]\n if a <= -1:\n break\n result.append(a)\n if max_l < len(result):\n max_l = len(result)\n max_list = result[:]\n j += 1\nprint(max_l)\nfor e in max_list:\n print(e, end=\" \")\nprint()","sub_path":"18.numberlink.py","file_name":"18.numberlink.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"382009535","text":"from __future__ import unicode_literals\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\nimport random\nfrom .templatetags import bizztags\nfrom django.utils.encoding import python_2_unicode_compatible\n\n# note: this decorator ensures that our __str__ is compatible with python 2 (essentially\n# creates an implementation of __unicode__\n@python_2_unicode_compatible\nclass BizzFuzzUser(models.Model):\n \"\"\" Fairly simple user model for this bizz fuzzy app. Only includes two fields:\n birthday, which is a DateField & randomNum which is a random number between 1 and 100\n\n \"\"\"\n birthday = models.DateField(verbose_name='Birthday')\n # code review note: convert method names to underscores (no camel)\n randomNum = models.IntegerField(max_length=3, blank=True, null=False, editable=False)\n\n def save(self):\n # if our random number does not fall between 1-100, create/overwrite it\n if not (0 < self.randomNum <= 100):\n self.randomNum = random.randrange(1, 100)\n super(BizzFuzzUser, self).save()\n\n def __str__(self):\n \"\"\" This is also called when __unicode__ is invoked because of the @python_2_unicode_compatible decorator\n \"\"\"\n\n # code review note: use str.format() instead of concat. much more powerful\n return 'User with birthday of {birthday} and # {num}'.format(birthday=str(self.birthday), num=str(self.randomNum))\n\n def get_absolute_url(self):\n # usually a good idea to define this\n return reverse('users:detail', kwargs={'pk': self.pk})\n\n def get_user_list(self):\n \"\"\" Generates a list of rows which can be used to generate a csv. Inclues\n a header row.\n\n \"\"\"\n\n # grab all users\n users = BizzFuzzUser.objects.all()\n\n # header row\n contents = []\n contents.append(['ID', 'Birthdate', 'Allowed', 'Random Number', 'Bizz Fuzz'])\n\n for user in users:\n # write a row for each user\n contents.append([user.pk, user.birthday, bizztags.allowed(user.birthday),\n user.randomNum, bizztags.bizzFuzz(user.randomNum)])\n\n return contents\n","sub_path":"bear1605/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"294399284","text":"#coding:utf-8\n#将t2t预测的分块结果转化成annotation文件,包括.txt和.ann后缀文件\nimport sys, os\nimport random\nfrom .scanannpath import read_path\nimport json\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nsentence_num_per_file = 20\nfile_num_per_document = 50\n\nuser_list = [u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9', u'10', u'11', u'12']\n\ndef read_text(path):\n #读一个path下的所有text\n files = os.listdir(path)\n text = []\n for s in files:\n son = os.path.join(path, s)\n if os.path.isdir(son):\n temp_text = read_text(son)\n text.extend(temp_text)\n else:\n if son.endswith(u'.txt'):\n reader = open(son, u'r')\n for textline in reader:\n textline = unicode(textline.strip())\n if len(textline) == 0:\n continue\n items = textline.split(u'。')\n for item in items:\n item = unicode(item.strip())\n if len(item) > 4:\n text.append(item)\n return text\n\ndef read_annotation(path, field):\n #从annotation中获取field字段内容\n files = os.listdir(path)\n text = set()\n for s in files:\n son = os.path.join(path, s)\n if os.path.isdir(son):\n temp_text = read_annotation(son, field)\n text = text | temp_text\n else:\n if son.endswith(u'.ann'):\n reader = open(son, u'r')\n for textline in reader:\n textline = unicode(textline.strip())\n if len(textline) == 0:\n continue\n pos1 = textline.find(u'\\t')\n if textline[pos1+1:].startswith(field):\n pos2 = textline.find(u'\\t', pos1 + 1)\n sentences = textline[pos2+1:].split(u'。')\n for s in sentences:\n s = unicode(s.strip())\n for ss in s.split(u'。'):\n ss = ss.strip()\n if len(ss) > 0:\n text.add(ss)\n return text\n\n\ndef read_prediction(pred_file, field):\n #pred_file:预测的json文件,从该文件中抽取对应字段\n reader = open(pred_file)\n value = []\n for line in reader:\n line = unicode(line.strip())\n if len(line) == 0:\n continue\n item = json.loads(line)\n if field in item:\n value.append(item[field])\n return value\n\ndef format_num(num):\n #将num转化成string,并在前面补0\n num_str = str(num)\n return u'0'*(5-len(num_str))+num_str\n\ndef devide_prediction_by_documentsize(text, path, start_documents=1):\n #将text平均放到文件夹,和divide_prediction不同的是,这里指定了每个文件夹最大包含的文件个数\n global sentence_num_per_file, file_num_per_document\n count = len(text)\n sentence_num_per_document = sentence_num_per_file * file_num_per_document\n document_num = count / sentence_num_per_document\n if count % sentence_num_per_document > 0:\n document_num += 1\n user_list = [str(x+start_documents) for x in xrange(document_num)]\n\n file_num = count / sentence_num_per_file\n if count % sentence_num_per_file > 0:\n file_num += 1\n text_file = [text[i * sentence_num_per_file: min((i + 1) * sentence_num_per_file, len(text))] for i in\n xrange(file_num)]\n\n user_index = 0\n file_index = 1\n for t in text_file:\n write_annotation(t, [], user_list[user_index], format_num(file_index), path)\n file_index += 1\n if file_index > file_num_per_document:\n file_index = 1\n user_index += 1\n\n\ndef divide_prediction_sorted(text, path):\n #将text按照顺序,放入各个文件夹,比如前100个都放到1,101-200放到2...\n global sentence_num_per_file, user_list\n count = len(text)\n file_num = count / sentence_num_per_file\n if count % sentence_num_per_file > 0:\n file_num += 1\n text_file = [text[i*sentence_num_per_file: min((i+1)*sentence_num_per_file, len(text))] for i in xrange(file_num)]\n\n user_num = len(user_list)\n file_num_per_user = file_num / user_num\n if file_num % user_num > 0:\n file_num_per_user += 1\n\n user_index = 0\n file_index = 1\n for t in text_file:\n write_annotation(t, [], user_list[user_index], format_num(file_index), path)\n file_index += 1\n if file_index > file_num_per_user:\n file_index = 1\n user_index += 1\n\ndef divide_prediction(text, annotation, path):\n #将text平均放到各个文件夹,1放到文件夹1,2放到文件夹2,...\n global sentence_num_per_file, user_list\n file_num = 0\n while file_num*sentence_num_per_file < len(text):\n file_text = text[file_num*sentence_num_per_file: min((file_num+1)*sentence_num_per_file, len(text))]\n if len(annotation) == 0:\n file_annotation = []\n else:\n file_annotation = annotation[file_num*sentence_num_per_file: min((file_num+1)*sentence_num_per_file, len(text))]\n text_user = user_list[file_num%len(user_list)]\n text_num = file_num/len(user_list)+1\n text_num = format_num(text_num)\n write_annotation(file_text, file_annotation, text_user, text_num, path)\n file_num += 1\n\ndef extract_annotation_perline(text, annotation):\n begin = 0\n end = 0\n last_pos = u''\n none_singals = [u'pad']\n result = []\n if len(text) != len(annotation):\n print(u'bad input')\n for index in xrange(len(text)):\n if index >= len(text) and last_pos != u'':\n result.append([last_pos, begin, end, text[begin:end]])\n break\n else:\n if last_pos == u'':\n if annotation[index] in none_singals:\n continue\n else:\n last_pos = annotation[index]\n begin = index\n end = begin+1\n elif last_pos == annotation[index]:\n end += 1\n else:\n result.append([last_pos, begin, end, text[begin:end]])\n begin = index\n end = begin+1\n if annotation[index] in none_singals:\n last_pos = u''\n else:\n last_pos = annotation[index]\n return result\n\ndef add_annotation(set, items, num):\n for item in items:\n set.append([item[0], str(item[1]+num), str(item[2]+num), item[3]])\n return set\n\ndef write_annotation(text, annotation, user, num, path):\n if not os.path.exists(path):\n os.mkdir(path)\n if not os.path.exists(path+user):\n os.mkdir(path+user)\n file_name = path + user + u'/text' + num\n writer_txt = open(file_name + u'.txt', u'w')\n writer_ann = open(file_name + u'.ann', u'w')\n for line in text:\n writer_txt.write(line+u'\\n')\n writer_txt.close()\n if len(annotation) == 0:\n writer_ann.close()\n else:\n annotation_num = 0\n annotation_set = []\n for line_num in xrange(len(annotation)):\n ann_items = extract_annotation_perline(text[line_num], annotation[line_num])\n annotation_set = add_annotation(annotation_set, ann_items, annotation_num)\n annotation_num += len(annotation[line_num])+1\n index = 0\n for item in annotation_set:\n writer_ann.write(u'T'+str(index) + u'\\t' + item[0] + u' ' + item[1] + u' ' + item[2] + u'\\t' + item[3] + u'\\n')\n index += 1\n\ndef read_dict(path):\n dct = set()\n reader = open(path, u'r')\n for line in reader:\n line = unicode(line.strip())\n if len(line) == 0:\n continue\n dct.add(line+u'ct')\n dct.add(line+u'b超')\n dct.add(line+u'x线')\n return dct\n\ndef removen(text):\n result = []\n for line in text:\n line = line.strip()\n line = line.replace(u'\\n', u'')\n if len(line) == 0:\n continue\n result.append(line)\n return result\n\ndef main():\n '''\n text = read_prediction(u'data/ret.json', u'text')\n annotation = read_prediction(u'data/ret.json', u'pred')\n divide_prediction(text, annotation, u'/Users/sj/PycharmProjects/medical_structuring/annotation_tool/data/zhusu_cut/')\n '''\n\n #text = read_prediction(u'data/abstract1117.txt', u'abs')\n #divide_prediction(text, [], u'/Users/sj/PycharmProjects/medical_structuring/annotation_tool/data/zhusu_zhengzhuang/')\n\n #text = read_prediction(u'data/xianbingshi.txt', u'xbs')\n #divide_prediction(text, [], u'/Users/sj/PycharmProjects/medical_structuring/annotation_tool/data/xianbingshi/')\n\n #抽出来一部分语料,需要医生把其中对体针块标识出来\n #text = read_prediction(u'data/vid_text_sj.txt', u'text')\n #divide_prediction(text, [], u'/Users/sj/PycharmProjects/medical_structuring/annotation_tool/data/more_signal/')\n\n #医生对现病史分块,根据分块结果,抽取特定的文本,比如症状,让医生从这里面看有哪些属性需要抽取\n #text = list(read_annotation(u'data/xianbingshi_annotated', u'test'))\n #random.shuffle(text)\n #devide_prediction_by_documentsize(text, u'data/test_test_xbs/', 1)\n #divide_prediction(text, [], u'/Users/sj/PycharmProjects/medical_structuring/annotation_tool/data/test_signal_xbs/')\n\n #text1 = list(read_annotation(u'data/test_signal_xbs_old', u'Person'))\n #text2 = list(read_annotation(u'data/more_signal', u'signal'))\n #text1.extend(text2)\n #devide_prediction_by_documentsize(text1, u'data/test_signal_xbs/', 1)\n\n #text = read_text(u'data/test_relation_xbs')\n #text.sort(lambda a, b: len(a)-len(b))\n #divide_prediction_sorted(text, u'data/test_relation_xbs_less/')\n\n #text = read_text(u'data/test_relation_xbs')\n #text = list(set(text)) #去重\n #devide_prediction_by_documentsize(text, u'data/test_relation_xbs_less/')\n\n #text = read_text(u'data/test_relation_xbs')\n #text = list(set(text))\n #random.shuffle(text)\n #devide_prediction_by_documentsize(text, u'data/shuffle_ralation_xbs/', 31) #医生要求从31开始\n\n #杨蕊给的120个科室,每个科室最大1万条化验数据,加上医生现病史分块中的化验数据,代替brat服务器上的test_test_xbs,医生标化验关系\n #text1 = read_prediction(u'data/xbsId_testHUAYANll.json', u'test')\n #text2 = read_annotation(u'data/xianbingshi_annotated', u'test')\n #for x in text1:\n # text2.add(x)\n #text = list(text2)\n #random.shuffle(text)\n #devide_prediction_by_documentsize(text, u'data/test_test_xbs/', 1)\n\n # 杨蕊给的120个科室,每个科室最大1万条检查数据,加上医生现病史分块中的检查数据,代替brat服务器上的test_inspectll_xbs,医生标化验关系\n # text1 = read_prediction(u'data/xbsId_inspectll.json', u'inspect')\n # text2 = read_annotation(u'data/xianbingshi_annotated', u'inspect')\n # for x in text1:\n # text2.add(x)\n # text = list(text2)\n # text = text[:50000]\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/test_inspect_xbs/', 1)\n\n # 医生现病史分块中的治疗数据,代替brat服务器上的test_inspectll_xbs,医生标化验关系\n # text2 = read_annotation(u'data/xianbingshi_annotated', u'treatment')\n # text = list(text2)\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/test_treatment_xbs/', 1)\n\n # 杨蕊给的120个科室,每个科室最大1万条诊断数据,分成4类放到brat上,分别是:初步诊断、鉴别诊断、诊断依据、诊疗计划\n # text = read_prediction(u'data/120treatment/初步诊断_1w', u'text')\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/120treatment/pre_diagnosis/', 1)\n #\n # text = read_prediction(u'data/120treatment/鉴别诊断_1w', u'text')\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/120treatment/identify_diagnosis/', 1)\n #\n # text = read_prediction(u'data/120treatment/诊断依据_1w', u'text')\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/120treatment/diagnosis_base/', 1)\n #\n # text = read_prediction(u'data/120treatment/诊疗计划_1w', u'text')\n # random.shuffle(text)\n # devide_prediction_by_documentsize(text, u'data/120treatment/treatment_plan/', 1)\n\n # 医生审核完检查的18个分块,将审核完的语料放到brat上供医生标关系\n # en2cn_dict_inspect = {'ultrasound': u'超声检查',\n # 'pathology': u'病理检查',\n # 'electrocardiogram': u'心电图检查',\n # 'electromyogram': u'肌电图检查',\n # 'electroencephalogram': u'脑电图检查',\n # 'pulmonary': u'肺功能检查',\n # 'endoscope': u'内窥镜检查',\n # 'petct': u'PET-CT检查',\n # 'nuclearbone': u'骨核医学检查',\n # 'nuclearother': u'其他核医学检查',\n # 'ct': u'CT检查',\n # 'magnetic': u'磁共振检查',\n # 'x': u'X线检查',\n # 'hearing': u'听力检查',\n # 'oculi': u'眼底检查',\n # 'puncture': u'穿刺类检查',\n # 'other': u'其他',\n # 'test': u'化验'}\n # if not os.path.exists(u'data/inspect_relation/'):\n # os.mkdir(u'data/inspect_relation/')\n # for field, value in en2cn_dict_inspect.items():\n # text1 = read_annotation(u'data/test_inspect_xbs', field)\n #\n # text2 = read_prediction(u'data/tmp/abstract_'+value+u'.json', value)\n # text2 = set(text2)\n # for txt in text1:\n # if txt in text2:\n # text2.remove(txt)\n # text1 = list(text1)\n # random.shuffle(text1)\n # text2 = list(text2)\n # random.shuffle(text2)\n # text1.extend(text2)\n # path = u'data/inspect_relation/'+field+u'/'\n # if not os.path.exists(path):\n # os.mkdir(path)\n # devide_prediction_by_documentsize(text1, u'data/inspect_relation/'+field+u'/', 1)\n # print(value+':'+str(len(text1)))\n\n # 给高医生的既往史\n # text = read_prediction(u'data/jiwangshi_out.txt', u'text')\n # text = list(set(text))\n # devide_prediction_by_documentsize(text, u'/Users/sj/PycharmProjects/annotation_tool/data/jiwangshi/')\n\n #给高医生新的现病史\n # text = read_prediction(u'data/new_xbs.json', u'xbs')\n # text = list(set(text))\n # devide_prediction_by_documentsize(text, u'/Users/sj/PycharmProjects/annotation_tool/data/xbs_new/')\n\n #给高医生的妇产科现病史\n # text = read_prediction(u'data/dept_xbs.txt', u'xbs')\n # text = list(set(text))\n # devide_prediction_by_documentsize(text, u'/Users/sj/PycharmProjects/annotation_tool/data/xbs_fc/')\n\n #从药品数据中抽取适应症\n text = read_prediction(u'data/drug.json', u'indication')\n text = list(set(text))\n text = removen(text)\n devide_prediction_by_documentsize(text, u'/Users/sj/PycharmProjects/annotation_tool/data/drug_indication/')\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"problem_util_yr/brat_generate_tool_yrtest/predict2annotation.py","file_name":"predict2annotation.py","file_ext":"py","file_size_in_byte":15590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"438973020","text":"\"\"\"\nYou are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.\n\nIn one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.\n\nReturn the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.\n\nExample 1:\nInput: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\n\nExample 2:\nInput: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\n\nExample 3:\nInput: maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n\n\nConstraints:\nmaze.length == m\nmaze[i].length == n\n1 <= m, n <= 100\nmaze[i][j] is either '.' or '+'.\nentrance.length == 2\n0 <= entrancerow < m\n0 <= entrancecol < n\nentrance will always be an empty cell.\n\nhints:\n1 Which type of traversal lets you find the distance from a point?\n2 Try using a Breadth First Search.\n\"\"\"\nimport collections\nfrom typing import List\n\n\nclass NearestExitFromEntranceInMaze:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n rows, cols = len(maze), len(maze[0])\n start_row, start_col = entrance\n maze[start_row][start_col] = \"+\"\n dirs = [0, 1, 0, -1, 0]\n q = collections.deque([(start_row, start_col, 0)])\n while q:\n r, c, dist = q.popleft()\n for i in range(len(dirs) - 1):\n nb_r, nb_c = r + dirs[i], c + dirs[i + 1]\n if 0 <= nb_r < rows and 0 <= nb_c < cols and maze[nb_r][nb_c] == \".\":\n if 0 == nb_r or rows - 1 == nb_r or 0 == nb_c or cols - 1 == nb_c:\n return dist + 1\n maze[nb_r][nb_c] = \"+\"\n q.append((nb_r, nb_c, dist + 1))\n return -1\n","sub_path":"LeetCodePython/NearestExitFromEntranceInMaze.py","file_name":"NearestExitFromEntranceInMaze.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"71382717","text":"import logging\nimport ptf.testutils as testutils\nimport pytest\nimport time\n\nfrom ipaddress import ip_network, IPv6Network, IPv4Network\nfrom tests.arp.arp_utils import clear_dut_arp_cache, increment_ipv6_addr, increment_ipv4_addr\nfrom tests.common.helpers.assertions import pytest_assert, pytest_require\n\npytestmark = [\n pytest.mark.topology('t0', 'dualtor')\n]\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef setup_ptf_arp(config_facts, ptfhost, intfs_for_test):\n _, _, intf1_index, _, = intfs_for_test\n ip_addr_config_cmd = 'ip addr {} {}/{} dev {}'\n\n # Calculate the IPv6 address to assign to the PTF port\n vlan_addrs = config_facts['VLAN_INTERFACE'].items()[0][1].keys()\n intf_ipv6_addr = None\n intf_ipv4_addr = None\n\n for addr in vlan_addrs:\n if type(ip_network(addr, strict=False)) is IPv6Network:\n intf_ipv6_addr = ip_network(addr, strict=False)\n elif type(ip_network(addr, strict=False)) is IPv4Network:\n intf_ipv4_addr = ip_network(addr, strict=False)\n\n # The VLAN interface on the DUT has an x.x.x.1 address assigned (or x::1 in the case of IPv6)\n # But the network_address property returns an x.x.x.0 address (or x::0 for IPv6) so we increment by two to avoid conflict\n ptf_intf_name = \"eth{}\".format(intf1_index)\n\n if intf_ipv4_addr is not None:\n ptf_intf_ipv4_addr = increment_ipv4_addr(intf_ipv4_addr.network_address, incr=2)\n ptfhost.shell(ip_addr_config_cmd.format('replace', ptf_intf_ipv4_addr, intf_ipv4_addr.prefixlen, ptf_intf_name))\n else:\n ptf_intf_ipv4_addr = None\n\n if intf_ipv6_addr is not None:\n ptf_intf_ipv6_addr = increment_ipv6_addr(intf_ipv6_addr.network_address, incr=2)\n ptfhost.shell(ip_addr_config_cmd.format('replace', ptf_intf_ipv6_addr, intf_ipv6_addr.prefixlen, ptf_intf_name))\n else:\n ptf_intf_ipv6_addr = None\n\n logger.info(\"Configured {} and {} on PTF interface {}\".format(ptf_intf_ipv4_addr, ptf_intf_ipv6_addr, ptf_intf_name))\n\n yield ptf_intf_ipv4_addr, ptf_intf_ipv6_addr, ptf_intf_name \n\n logger.info(\"Removing {} and {} from PTF interface {}\".format(ptf_intf_ipv4_addr, ptf_intf_ipv6_addr, ptf_intf_name))\n\n if intf_ipv4_addr is not None:\n ptfhost.shell(ip_addr_config_cmd.format('del', ptf_intf_ipv4_addr, intf_ipv4_addr.prefixlen, ptf_intf_name))\n\n if intf_ipv6_addr is not None:\n ptfhost.shell(ip_addr_config_cmd.format('del', ptf_intf_ipv6_addr, intf_ipv6_addr.prefixlen, ptf_intf_name))\n\n\n@pytest.fixture\ndef garp_setup(duthosts, enum_rand_one_per_hwsku_frontend_hostname, config_facts):\n duthost = duthosts[enum_rand_one_per_hwsku_frontend_hostname]\n\n clear_dut_arp_cache(duthost)\n\n vlan_intfs = config_facts['VLAN_INTERFACE'].keys()\n garp_check_cmd = 'sonic-db-cli CONFIG_DB HGET \"VLAN_INTERFACE|{}\" grat_arp'\n garp_enable_cmd = 'sonic-db-cli CONFIG_DB HSET \"VLAN_INTERFACE|{}\" grat_arp enabled'\n cat_arp_accept_cmd = 'cat /proc/sys/net/ipv4/conf/{}/arp_accept'\n arp_accept_vals = []\n old_grat_arp_vals = {}\n for vlan in vlan_intfs:\n old_grat_arp_res = duthost.shell(garp_check_cmd.format(vlan))\n old_grat_arp_vals[vlan] = old_grat_arp_res['stdout']\n res = duthost.shell(garp_enable_cmd.format(vlan))\n\n if res['rc'] != 0:\n pytest.fail(\"Unable to enable GARP for {}\".format(vlan))\n else:\n logger.info(\"Enabled GARP for {}\".format(vlan))\n\n # Get the `arp_accept` values for each VLAN interface and yield them\n # to the caller, who can decide how to proceed\n arp_accept_res = duthost.shell(cat_arp_accept_cmd.format(vlan))\n arp_accept_vals.append(arp_accept_res['stdout'])\n\n yield arp_accept_vals\n\n garp_disable_cmd = 'sonic-db-cli CONFIG_DB HDEL \"VLAN_INTERFACE|{}\" grat_arp'\n for vlan in vlan_intfs:\n old_grat_arp_val = old_grat_arp_vals[vlan]\n\n if 'enabled' not in old_grat_arp_val:\n res = duthost.shell(garp_disable_cmd.format(vlan))\n\n if res['rc'] != 0:\n pytest.fail(\"Unable to disable GARP for {}\".format(vlan))\n else:\n logger.info(\"GARP disabled for {}\".format(vlan))\n\n\ndef test_arp_garp_enabled(duthosts, enum_rand_one_per_hwsku_frontend_hostname, garp_setup, setup_ptf_arp, intfs_for_test, config_facts, ptfadapter):\n '''\n Send a gratuitous ARP (GARP) packet from the PTF to the DUT\n\n The DUT should learn the (previously unseen) ARP info from the packet\n '''\n duthost = duthosts[enum_rand_one_per_hwsku_frontend_hostname]\n ptf_intf_ipv4_addr, _, _ = setup_ptf_arp\n arp_accept_vals = garp_setup\n pytest_require(all(int(val) == 1 for val in arp_accept_vals), 'Gratuitous ARP not enabled for this device')\n\n arp_request_ip = increment_ipv4_addr(ptf_intf_ipv4_addr)\n arp_src_mac = '00:00:07:08:09:0a'\n _, _, intf1_index, _, = intfs_for_test\n\n pkt = testutils.simple_arp_packet(pktlen=60,\n eth_dst='ff:ff:ff:ff:ff:ff',\n eth_src=arp_src_mac,\n vlan_pcp=0,\n arp_op=2,\n ip_snd=arp_request_ip,\n ip_tgt=arp_request_ip,\n hw_snd=arp_src_mac,\n hw_tgt='ff:ff:ff:ff:ff:ff'\n )\n\n logger.info(\"Sending GARP for target {} from PTF interface {}\".format(arp_request_ip, intf1_index))\n testutils.send_packet(ptfadapter, intf1_index, pkt)\n\n vlan_intfs = config_facts['VLAN_INTERFACE'].keys()\n\n switch_arptable = duthost.switch_arptable()['ansible_facts']\n pytest_assert(switch_arptable['arptable']['v4'][arp_request_ip]['macaddress'].lower() == arp_src_mac.lower())\n pytest_assert(switch_arptable['arptable']['v4'][arp_request_ip]['interface'] in vlan_intfs)\n\n\n@pytest.mark.parametrize('ip_version', ['v4', 'v6'])\ndef test_proxy_arp(duthosts, enum_rand_one_per_hwsku_frontend_hostname, setup_ptf_arp, intfs_for_test, ptfhost, config_facts, ip_version, tbinfo):\n '''\n Send an ARP request or neighbor solicitation (NS) to the DUT for an IP address within the subnet of the DUT's VLAN.\n\n DUT should reply with an ARP reply or neighbor advertisement (NA) containing the DUT's own MAC\n '''\n duthost = duthosts[enum_rand_one_per_hwsku_frontend_hostname]\n ptf_intf_ipv4_addr, ptf_intf_ipv6_addr, ptf_intf_name = setup_ptf_arp\n\n pytest_require(duthost.has_config_subcommand('config vlan proxy_arp'), \"Proxy ARP command does not exist on device\")\n\n if ip_version == 'v4':\n pytest_require(ptf_intf_ipv4_addr is not None, 'No IPv4 VLAN address configured on device')\n elif ip_version == 'v6':\n pytest_require(ptf_intf_ipv6_addr is not None, 'No IPv6 VLAN address configured on device')\n\n proxy_arp_config_cmd = 'config vlan proxy_arp {} {}'\n\n # We are leveraging the fact that ping will automatically send a neighbor solicitation/ARP request for us\n # However, we expect the ping itself to always fail since no interface is configured with the pinged IP, so add '|| true' so we can continue\n ping_cmd = 'ping {} -I {} -c 1 || true' \n\n # Enable proxy ARP/NDP for the VLANs on the DUT\n vlans = config_facts['VLAN']\n vlan_ids =[vlans[vlan]['vlanid'] for vlan in vlans.keys()]\n\n for vid in vlan_ids:\n duthost.shell(proxy_arp_config_cmd.format(vid, 'enabled'))\n time.sleep(3)\n logger.info(\"Enabled proxy ARP for VLAN {}\".format(vid))\n\n clear_dut_arp_cache(ptfhost)\n\n ping_addr = None\n if ip_version == 'v4':\n ping_addr = increment_ipv4_addr(ptf_intf_ipv4_addr)\n elif ip_version == 'v6':\n ping_addr = increment_ipv6_addr(ptf_intf_ipv6_addr)\n \n logger.info(\"Pinging {} using PTF interface {}\".format(ping_addr, ptf_intf_name))\n ptfhost.shell(ping_cmd.format(ping_addr, ptf_intf_name))\n time.sleep(2)\n\n neighbor_table = ptfhost.switch_arptable()['ansible_facts']['arptable'][ip_version]\n\n topology = tbinfo['topo']['name']\n if 'dualtor' in topology:\n dut_macs = []\n\n for vlan_details in vlans.values():\n dut_macs.append(vlan_details['mac'].lower())\n else:\n router_mac = duthost.shell('sonic-cfggen -d -v \\'DEVICE_METADATA.localhost.mac\\'')[\"stdout_lines\"][0].decode(\"utf-8\")\n dut_macs = [router_mac]\n\n pytest_assert(ping_addr in neighbor_table.keys())\n pytest_assert(neighbor_table[ping_addr]['macaddress'].lower() in dut_macs)\n pytest_assert(neighbor_table[ping_addr]['interface'] == ptf_intf_name)\n pytest_assert(neighbor_table[ping_addr]['state'].lower() not in ['failed', 'incomplete'])\n","sub_path":"tests/arp/test_arp_dualtor.py","file_name":"test_arp_dualtor.py","file_ext":"py","file_size_in_byte":8702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"219915019","text":"import copy\nimport math\nfrom functools import partial\nfrom typing import Any, Callable, List, Optional, Sequence\n\nimport torch\nfrom torch import nn, Tensor\nfrom torchvision.ops import StochasticDepth\n\nfrom .._internally_replaced_utils import load_state_dict_from_url\nfrom ..ops.misc import ConvNormActivation, SqueezeExcitation\nfrom ._utils import _make_divisible\n\n\n__all__ = [\n \"EfficientNet\",\n \"efficientnet_b0\",\n \"efficientnet_b1\",\n \"efficientnet_b2\",\n \"efficientnet_b3\",\n \"efficientnet_b4\",\n \"efficientnet_b5\",\n \"efficientnet_b6\",\n \"efficientnet_b7\",\n]\n\n\nmodel_urls = {\n # Weights ported from https://github.com/rwightman/pytorch-image-models/\n \"efficientnet_b0\": \"https://download.pytorch.org/models/efficientnet_b0_rwightman-3dd342df.pth\",\n \"efficientnet_b1\": \"https://download.pytorch.org/models/efficientnet_b1_rwightman-533bc792.pth\",\n \"efficientnet_b2\": \"https://download.pytorch.org/models/efficientnet_b2_rwightman-bcdf34b7.pth\",\n \"efficientnet_b3\": \"https://download.pytorch.org/models/efficientnet_b3_rwightman-cf984f9c.pth\",\n \"efficientnet_b4\": \"https://download.pytorch.org/models/efficientnet_b4_rwightman-7eb33cd5.pth\",\n # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/\n \"efficientnet_b5\": \"https://download.pytorch.org/models/efficientnet_b5_lukemelas-b6417697.pth\",\n \"efficientnet_b6\": \"https://download.pytorch.org/models/efficientnet_b6_lukemelas-c76e70fd.pth\",\n \"efficientnet_b7\": \"https://download.pytorch.org/models/efficientnet_b7_lukemelas-dcc49843.pth\",\n}\n\n\nclass MBConvConfig:\n # Stores information listed at Table 1 of the EfficientNet paper\n def __init__(\n self,\n expand_ratio: float,\n kernel: int,\n stride: int,\n input_channels: int,\n out_channels: int,\n num_layers: int,\n width_mult: float,\n depth_mult: float,\n ) -> None:\n self.expand_ratio = expand_ratio\n self.kernel = kernel\n self.stride = stride\n self.input_channels = self.adjust_channels(input_channels, width_mult)\n self.out_channels = self.adjust_channels(out_channels, width_mult)\n self.num_layers = self.adjust_depth(num_layers, depth_mult)\n\n def __repr__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"expand_ratio={expand_ratio}\"\n s += \", kernel={kernel}\"\n s += \", stride={stride}\"\n s += \", input_channels={input_channels}\"\n s += \", out_channels={out_channels}\"\n s += \", num_layers={num_layers}\"\n s += \")\"\n return s.format(**self.__dict__)\n\n @staticmethod\n def adjust_channels(channels: int, width_mult: float, min_value: Optional[int] = None) -> int:\n return _make_divisible(channels * width_mult, 8, min_value)\n\n @staticmethod\n def adjust_depth(num_layers: int, depth_mult: float):\n return int(math.ceil(num_layers * depth_mult))\n\n\nclass MBConv(nn.Module):\n def __init__(\n self,\n cnf: MBConvConfig,\n stochastic_depth_prob: float,\n norm_layer: Callable[..., nn.Module],\n se_layer: Callable[..., nn.Module] = SqueezeExcitation,\n ) -> None:\n super().__init__()\n\n if not (1 <= cnf.stride <= 2):\n raise ValueError(\"illegal stride value\")\n\n self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels\n\n layers: List[nn.Module] = []\n activation_layer = nn.SiLU\n\n # expand\n expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio)\n if expanded_channels != cnf.input_channels:\n layers.append(\n ConvNormActivation(\n cnf.input_channels,\n expanded_channels,\n kernel_size=1,\n norm_layer=norm_layer,\n activation_layer=activation_layer,\n )\n )\n\n # depthwise\n layers.append(\n ConvNormActivation(\n expanded_channels,\n expanded_channels,\n kernel_size=cnf.kernel,\n stride=cnf.stride,\n groups=expanded_channels,\n norm_layer=norm_layer,\n activation_layer=activation_layer,\n )\n )\n\n # squeeze and excitation\n squeeze_channels = max(1, cnf.input_channels // 4)\n layers.append(se_layer(expanded_channels, squeeze_channels, activation=partial(nn.SiLU, inplace=True)))\n\n # project\n layers.append(\n ConvNormActivation(\n expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None\n )\n )\n\n self.block = nn.Sequential(*layers)\n self.stochastic_depth = StochasticDepth(stochastic_depth_prob, \"row\")\n self.out_channels = cnf.out_channels\n\n def forward(self, input: Tensor) -> Tensor:\n result = self.block(input)\n if self.use_res_connect:\n result = self.stochastic_depth(result)\n result += input\n return result\n\n\nclass EfficientNet(nn.Module):\n def __init__(\n self,\n inverted_residual_setting: List[MBConvConfig],\n dropout: float,\n stochastic_depth_prob: float = 0.2,\n num_classes: int = 1000,\n block: Optional[Callable[..., nn.Module]] = None,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n **kwargs: Any,\n ) -> None:\n \"\"\"\n EfficientNet main class\n\n Args:\n inverted_residual_setting (List[MBConvConfig]): Network structure\n dropout (float): The droupout probability\n stochastic_depth_prob (float): The stochastic depth probability\n num_classes (int): Number of classes\n block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet\n norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use\n \"\"\"\n super().__init__()\n\n if not inverted_residual_setting:\n raise ValueError(\"The inverted_residual_setting should not be empty\")\n elif not (\n isinstance(inverted_residual_setting, Sequence)\n and all([isinstance(s, MBConvConfig) for s in inverted_residual_setting])\n ):\n raise TypeError(\"The inverted_residual_setting should be List[MBConvConfig]\")\n\n if block is None:\n block = MBConv\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n\n layers: List[nn.Module] = []\n\n # building first layer\n firstconv_output_channels = inverted_residual_setting[0].input_channels\n layers.append(\n ConvNormActivation(\n 3, firstconv_output_channels, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=nn.SiLU\n )\n )\n\n # building inverted residual blocks\n total_stage_blocks = sum([cnf.num_layers for cnf in inverted_residual_setting])\n stage_block_id = 0\n for cnf in inverted_residual_setting:\n stage: List[nn.Module] = []\n for _ in range(cnf.num_layers):\n # copy to avoid modifications. shallow copy is enough\n block_cnf = copy.copy(cnf)\n\n # overwrite info if not the first conv in the stage\n if stage:\n block_cnf.input_channels = block_cnf.out_channels\n block_cnf.stride = 1\n\n # adjust stochastic depth probability based on the depth of the stage block\n sd_prob = stochastic_depth_prob * float(stage_block_id) / total_stage_blocks\n\n stage.append(block(block_cnf, sd_prob, norm_layer))\n stage_block_id += 1\n\n layers.append(nn.Sequential(*stage))\n\n # building last several layers\n lastconv_input_channels = inverted_residual_setting[-1].out_channels\n lastconv_output_channels = 4 * lastconv_input_channels\n layers.append(\n ConvNormActivation(\n lastconv_input_channels,\n lastconv_output_channels,\n kernel_size=1,\n norm_layer=norm_layer,\n activation_layer=nn.SiLU,\n )\n )\n\n self.features = nn.Sequential(*layers)\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.classifier = nn.Sequential(\n nn.Dropout(p=dropout, inplace=True),\n nn.Linear(lastconv_output_channels, num_classes),\n )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\")\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n init_range = 1.0 / math.sqrt(m.out_features)\n nn.init.uniform_(m.weight, -init_range, init_range)\n nn.init.zeros_(m.bias)\n\n def _forward_impl(self, x: Tensor) -> Tensor:\n x = self.features(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n\n x = self.classifier(x)\n\n return x\n\n def forward(self, x: Tensor) -> Tensor:\n return self._forward_impl(x)\n\n\ndef _efficientnet_conf(width_mult: float, depth_mult: float, **kwargs: Any) -> List[MBConvConfig]:\n bneck_conf = partial(MBConvConfig, width_mult=width_mult, depth_mult=depth_mult)\n inverted_residual_setting = [\n bneck_conf(1, 3, 1, 32, 16, 1),\n bneck_conf(6, 3, 2, 16, 24, 2),\n bneck_conf(6, 5, 2, 24, 40, 2),\n bneck_conf(6, 3, 2, 40, 80, 3),\n bneck_conf(6, 5, 1, 80, 112, 3),\n bneck_conf(6, 5, 2, 112, 192, 4),\n bneck_conf(6, 3, 1, 192, 320, 1),\n ]\n return inverted_residual_setting\n\n\ndef _efficientnet_model(\n arch: str,\n inverted_residual_setting: List[MBConvConfig],\n dropout: float,\n pretrained: bool,\n progress: bool,\n **kwargs: Any,\n) -> EfficientNet:\n model = EfficientNet(inverted_residual_setting, dropout, **kwargs)\n if pretrained:\n if model_urls.get(arch, None) is None:\n raise ValueError(\"No checkpoint is available for model type {}\".format(arch))\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n model.load_state_dict(state_dict)\n return model\n\n\ndef efficientnet_b0(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B0 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.0, depth_mult=1.0, **kwargs)\n return _efficientnet_model(\"efficientnet_b0\", inverted_residual_setting, 0.2, pretrained, progress, **kwargs)\n\n\ndef efficientnet_b1(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B1 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.0, depth_mult=1.1, **kwargs)\n return _efficientnet_model(\"efficientnet_b1\", inverted_residual_setting, 0.2, pretrained, progress, **kwargs)\n\n\ndef efficientnet_b2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B2 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.1, depth_mult=1.2, **kwargs)\n return _efficientnet_model(\"efficientnet_b2\", inverted_residual_setting, 0.3, pretrained, progress, **kwargs)\n\n\ndef efficientnet_b3(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B3 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.2, depth_mult=1.4, **kwargs)\n return _efficientnet_model(\"efficientnet_b3\", inverted_residual_setting, 0.3, pretrained, progress, **kwargs)\n\n\ndef efficientnet_b4(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B4 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.4, depth_mult=1.8, **kwargs)\n return _efficientnet_model(\"efficientnet_b4\", inverted_residual_setting, 0.4, pretrained, progress, **kwargs)\n\n\ndef efficientnet_b5(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B5 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.6, depth_mult=2.2, **kwargs)\n return _efficientnet_model(\n \"efficientnet_b5\",\n inverted_residual_setting,\n 0.4,\n pretrained,\n progress,\n norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01),\n **kwargs,\n )\n\n\ndef efficientnet_b6(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B6 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=1.8, depth_mult=2.6, **kwargs)\n return _efficientnet_model(\n \"efficientnet_b6\",\n inverted_residual_setting,\n 0.5,\n pretrained,\n progress,\n norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01),\n **kwargs,\n )\n\n\ndef efficientnet_b7(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:\n \"\"\"\n Constructs a EfficientNet B7 architecture from\n `\"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n inverted_residual_setting = _efficientnet_conf(width_mult=2.0, depth_mult=3.1, **kwargs)\n return _efficientnet_model(\n \"efficientnet_b7\",\n inverted_residual_setting,\n 0.5,\n pretrained,\n progress,\n norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01),\n **kwargs,\n )\n","sub_path":"torchvision/models/efficientnet.py","file_name":"efficientnet.py","file_ext":"py","file_size_in_byte":16254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"494258724","text":"\"\"\"\nJibeCommerceBank spider created on top of the Jibe Spider\nscrapy crawl jibe_commercebank -a mining_job_id=9999 -a iteration=1 -a url=\"http://commercebank.jibeapply.com/\" -a extract=1\n\nNote:\n\"req id-1\" = external jobs\n\"req id-3\" = internal jobs\nOnly jobs with \"req id-1\" in the job details url\n\nsample urls:\n http://commercebank.jibeapply.com/\n\"\"\"\n\nfrom re import compile\nfrom json import loads as json_loads\n\nfrom urlparse import urljoin\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.spiders.jibe import JibeSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, ConvertDateString\n\npattern = {\n 'external_job': compile(r'(\\d+-1)'),\n}\n\n\nclass JibeCommerceBank(JibeSpider):\n\n \"\"\" Jibe_CommerceBank Crawler. \"\"\"\n\n name = \"jibe_commercebank\"\n\n def parse_job(self, response):\n \"\"\" Parse job items (json). \"\"\"\n sel = Selector(response)\n if sel.xpath('//pre/text()'):\n json_output = '' . join(sel.xpath('//pre/text()').extract()).\\\n encode('utf-8')\n else:\n json_output = response.body\n\n content = json_loads(json_output)\n\n if 'jobs' in content:\n jobs = content['jobs']\n count = content['count']\n for job in jobs:\n if job.get('data', {}):\n job = job.get('data', {})\n else:\n job = job\n\n self.count += 1\n slug = job.get('slug', '')\n match = pattern['external_job'].search(slug)\n if match:\n loader = BrightcorpItemLoader(selector=job)\n\n ref_num = job.get('seo_title', '')\n url = urljoin(response.url, '/jobs/%s/%s' % (slug, ref_num))\n\n loader.add_value('url', url)\n loader.add_value('title', job.get('title', ''))\n loader.add_value('description', job.get('description', ''))\n loader.add_value('company', job.get('employer_name', ''))\n loader.add_value('apply_url', job.get('apply_url', ''))\n loader.add_value(\n 'location',\n [\n job.get('city', ''), job.get('state', ''),\n job.get('country', '')\n ],\n NormalizedJoin(\", \")\n )\n loader.add_value(\n 'date', job.get('update_date', ''),\n ConvertDateString('%Y-%m-%dT%H:%M:%S+0000')\n )\n loader.add_value(\n 'jobcategory', self.get_category(job), NormalizedJoin(\", \")\n )\n loader.add_value(\n 'referencenumber', slug,\n Prefix('%s-%s-' % (self.name, self.sub_domain))\n )\n\n yield loader.load_item()\n\n if self.count < count:\n self.offset += 10\n url = urljoin(\n response.url,\n 'jobs?offset=%d&limit=10' % self.offset)\n\n yield Request(\n url, callback=self.parse_job_callback(),\n headers=self.headers\n )\n","sub_path":"brightcorp/brightcorp/spiders/jibe_commercebank.py","file_name":"jibe_commercebank.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"286604915","text":"# -*- coding: utf-8 -*\n# Copyright (c) 2019 BuildGroup Data Services Inc.\n# All rights reserved.\n# This software is proprietary and confidential and may not under\n# any circumstances be used, copied, or distributed.\nimport logging\nimport time\n\nfrom caravaggio_python_bindings import status\nfrom coreapi import exceptions\n\n_logger = logging.getLogger(\"caravaggio_python_bindings.resource\")\n\n\nclass Resource(object):\n sec_btw_tries = 5\n \"\"\"\n How much time we need to wait for the next try to do the request to\n the server if we got a HTTP_429_TOO_MANY_REQUESTS error.\n \"\"\"\n\n def __init__(self, api, tries=12):\n self.api = api\n self.n_tries = tries\n\n def get_absolute_url(self, relative_url):\n return \"{}{}{}\".format(self.api.domain, \"/\" if not self.api.domain.endswith(\"/\") else \"\", relative_url)\n\n def action(\n self,\n keys,\n params=None,\n validate=True,\n overrides=None,\n action=None,\n encoding=None,\n transform=None,\n n_tries=None,\n sec_btw_tries=None,\n ):\n n_tries = self.n_tries if n_tries is None else n_tries\n sec_btw_tries = self.sec_btw_tries if sec_btw_tries is None else sec_btw_tries\n while n_tries:\n try:\n if self.api.organization_id:\n params[\"_org_id\"] = str(self.api.organization_id)\n\n return self.api.client.action(\n self.api.schema,\n keys,\n params=params,\n validate=validate,\n overrides=overrides,\n action=action,\n encoding=encoding,\n transform=transform,\n )\n except exceptions.ErrorMessage as error:\n if error.error.title.startswith(str(status.HTTP_429_TOO_MANY_REQUESTS)):\n _logger.info(\"Throttling the request! waiting {} seconds\".format(sec_btw_tries))\n n_tries -= 1\n time.sleep(sec_btw_tries)\n else:\n raise error\n","sub_path":"src/caravaggio_python_bindings/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"412456544","text":"import boto3\r\n\r\n\r\ndef get_client():\r\n \"\"\"\r\n Returns the ec2 boto3 client\r\n \"\"\"\r\n return boto3.client('ec2')\r\n\r\n\r\ndef list_ec2_instances():\r\n \"\"\"\r\n List EC2 InstanceId\r\n \"\"\"\r\n ec2 = get_client()\r\n\r\n response = ec2.describe_instances()\r\n if response:\r\n for res in response.get('Reservations', []):\r\n for instance in res.get('Instances', []):\r\n yield instance['InstanceId']\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Main entry\r\n \"\"\"\r\n\r\n for instance in list_ec2_instances():\r\n print(instance)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"moto_week3/my_ec2.py","file_name":"my_ec2.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"618205286","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/3 20:56\n# @Author : PasserQi\n# @Email : passerqi@gmail.com\n# @File : DownloadWebsite\n# @Software: PyCharm\n# @Version :\n# @Desc :\n\nimport time\nfrom selenium import webdriver\nimport os\nimport json\nfrom tqdm import tqdm\n\nDOMAIN = 'https://www.geomesa.org/documentation/' #爬取的域名,最后要有'/'\nSAVE_DIR = 'geomesa_en' #保存路径\n\ndef load_json(fp):\n with open(fp, 'r') as f:\n return json.load(f)\ndef save_json(fp, obj):\n if os.path.exists(fp):\n os.remove(fp)\n with open(fp, 'w+') as f:\n json.dump(obj, f, indent=4)\n f.close()\n return fp\ndef mkdir(path):\n path = path.strip()\n path = path.rstrip(\"\\\\\")\n if not os.path.exists(path):\n os.makedirs(path)\n # print(\"[OK] Create Dir:{}\".format(path) )\n return True\ndef get_save_path(url):\n fn = url.split('/')[-1]\n prefix = url.replace(DOMAIN, '').replace(fn, '')\n dir = os.path.join(SAVE_DIR, prefix)\n fp = os.path.join(dir, fn)\n mkdir(dir) #创建保存目录\n return fp,dir,fn\ndef save_url(url):\n fp, dir, fn = get_save_path(url) #获得本地保存路径\n if os.path.exists(fp):\n # print(\"[is exists] {} {}\".format(url, fp))\n return fp\n\n driver.get(url)\n time.sleep(5)\n context = driver.page_source\n with open(fp, 'w', encoding=\"utf-8\") as file:\n file.write(context)\n file.close()\n # print(\"[save] {} {}\".format(url, fp))\n return fp\n\nfrom urllib.request import urlretrieve\ndef save_file(url):\n fp, dir, fn = get_save_path(url)\n # 检查路径是否存在\n if os.path.exists(fp):\n # 已经存在\n # print(\"[is exists] {} {}\".format(url, fp))\n return fp\n # 下载\n urlretrieve(url, fp)\n # print(\"[save] {} {}\".format(url, fp))\n\nif __name__ == '__main__':\n visit_path = os.path.join(SAVE_DIR, \"visit.json\")\n img_path = os.path.join(SAVE_DIR, \"img.json\")\n assets_path = os.path.join(SAVE_DIR, \"assets.json\")\n\n driver = webdriver.Chrome(executable_path='../tools/chromedriver.exe')\n # 网速太慢需要等待\n driver.set_page_load_timeout(10 * 60)\n driver.set_script_timeout(10 * 60)\n\n print(\"\\ndownload img\")\n if os.path.exists(img_path):\n img_urls = load_json(img_path)\n for img in tqdm(img_urls):\n save_file(img)\n\n print(\"\\ndownload assets\")\n if os.path.exists(assets_path):\n other_assets = load_json(assets_path)\n for url in tqdm(other_assets):\n if DOMAIN in url:\n save_file(url)\n\n print(\"\\ndownload html\")\n if os.path.exists(visit_path):\n visit_list = load_json(visit_path)\n for html in tqdm(visit_list):\n save_url(html)\n\n pass","sub_path":"2 download_selenium_v1.0.py","file_name":"2 download_selenium_v1.0.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"521772945","text":"# 今天要讲的概念有两个 一个是局部作用域 一个是全局作用域\n\n# 首先看名字 局部作用域:局部 说明不是全部的地方,作用域 是产生作用的区域\n# 全局作用域:全局 说明是全部的地方\n\n# 现在要将这个概念应用在函数里\n# 首先写一段代码:\n\n\ndef change_nums(x, y, z): # 第一处\n x = 10\n y = 20\n z = 50\n\n\ndef add_two_nums(x, y): # 第二处\n z = x + y\n print(\"两个数字的和为:\", z)\n\n\nx, y, z = 0, 1, 20 # 第三处\nprint(\"在调用函数之前,他们的值为\", x, y, z)\nchange_nums(x, y, z)\nadd_two_nums(x, y)\n\nprint(\"在调用函数之后,他们的值为\", x, y, z)\n\n# 在上面的例子里 标注出来的 第一处 和 第二处 还有 第三处,发现都有 x,y 并且在函数的内部和外部 都有z\n# 这句话 需要记住:\n# 1. 函数内部是局部作用域,函数的外部是非局部作用域,对于这个文件ch6_4_1.py来说,全部文件是全局作用域\n# 2. 局部作用域之间的变量(也就是x和y和z)都是不相互影响的可以看上面的结果 不管怎么加 怎么变,z还是那个z,还是20\n# 也许看到上面你发现了两点:\n# 1. 真麻烦,全局 局部 非局部。。。\n# 2. 到底x是啥 y又是啥 z呢???这到处用 乱死了\n\n# 为了避免上面的问题,有一个简单的解决方法:\n# 为不用用途的变量设置不同的值,比如:\ni, j, k = 1, 2, 3\n\n\ndef my_func(val1, val2):\n val3 = val2 + val1\n print(val3)\n\n\ndef your_func(a, b, c):\n if (a + b) < c:\n c = a + b\n else:\n a = c + b\n print(a, b, c)\n\n\nmy_func(i, j)\n\nyour_func(i, j, k)\n\n# 上面就很清楚了,该是谁的变量都各自认领了。不会出现混乱,调用函数的时候 把需要的参数传到函数里一算,完美\n# 所以不想乱,就要记得把不同的变量 命名成不同的名字~\n","sub_path":"ch6/ch6_4_1.py","file_name":"ch6_4_1.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"435624750","text":"import os\nimport sys\nfrom git import *\nfrom sklearn.utils import shuffle\n\ngetConsecutivePRPairs_flag = True\n\nrepo_type = 'training' # 'testing'\n# repo_type = 'testing'\nall_repos = ['mozilla-b2g/gaia', 'twbs/bootstrap', 'scikit-learn/scikit-learn', 'rust-lang/rust', 'servo/servo',\n 'pydata/pandas', 'saltstack/salt', 'nodejs/node', 'symfony/symfony-docs', 'zendframework/zf2',\n 'symfony/symfony', 'kubernetes/kubernetes', 'cocos2d/cocos2d-x', 'dotnet/corefx', 'django/django',\n 'angular/angular.js', 'JuliaLang/julia', 'ceph/ceph', 'joomla/joomla-cms', 'facebook/react',\n 'hashicorp/terraform', 'rails/rails', 'docker/docker', 'elastic/elasticsearch', 'emberjs/ember.js',\n 'ansible/ansible']\n\nif (repo_type == 'training'):\n print(\"randomly pick a repo...\")\n # repos = ['mozilla-b2g/gaia']\n repos = ['mozilla-b2g/gaia', 'twbs/bootstrap', 'scikit-learn/scikit-learn', 'rust-lang/rust', 'servo/servo',\n 'pydata/pandas', 'saltstack/salt', 'nodejs/node', 'symfony/symfony-docs', 'zendframework/zf2',\n 'symfony/symfony', 'kubernetes/kubernetes']\nelse: # testing repos\n print(\"randomly pick a repo...\")\n # repos = ['cocos2d/cocos2d-x']\n repos = ['cocos2d/cocos2d-x', 'dotnet/corefx', 'django/django', 'angular/angular.js', 'JuliaLang/julia',\n 'ceph/ceph',\n 'joomla/joomla-cms', 'facebook/react', 'hashicorp/terraform', 'rails/rails', 'docker/docker',\n 'elastic/elasticsearch', 'emberjs/ember.js', 'ansible/ansible']\n\n# get Duplicate PR pairs from MSR Dataset\nmsr_pr_pair = set()\nmsr_repo_prList_map = {k: [] for k in all_repos}\n\nwith open('data/msr_positive_pairs.txt') as f:\n for t in f.readlines():\n # print(t)\n r, n1, n2 = t.split()\n if r in all_repos:\n msr_pr_pair.add((r, n1, n2))\n msr_repo_prList_map[r].append(n1)\n msr_repo_prList_map[r].append(n2)\n\ngen_num = 0\n\n\ndef getConsecutiveNonDupPRPairs(repo, prID):\n # get all pr\n pull_list = get_repo_info(repo, 'pull')\n pull_list = list(filter(lambda x: (int(x['number']) < int(prID)), pull_list))\n pull_list = sorted(pull_list, key=lambda x: int(x['number']), reverse=True)\n# pull_list = pull_list[:10]\n pull_list = pull_list[10:50]\n pull_list = [x['number'] for x in pull_list]\n pr_pair_list = []\n for old_pr in pull_list:\n old_pr = str(old_pr)\n if (repo, prID, old_pr) not in msr_pr_pair and (repo, old_pr, prID) not in msr_pr_pair:\n pr_pair_list.append((repo, prID, old_pr))\n else:\n print(repo + ',' + prID + ',' + old_pr + ' is duplicate')\n return pr_pair_list\n\n\ndef work(file):\n add_flag = False\n\n has = set()\n if os.path.exists(file):\n if not add_flag:\n raise Exception('file already exists!')\n with open(file) as f:\n for t in f.readlines():\n r, n = t.strip().split()\n has.add((r, n))\n\n for repo in repos:\n print('Generating PRs from', repo)\n total = len(msr_repo_prList_map[repo])\n print(str(total) + 'prs in total')\n count = 1;\n for msr_pr in msr_repo_prList_map[repo]:\n print('current pr in MSR:' + msr_pr)\n if getConsecutivePRPairs_flag:\n result = getConsecutiveNonDupPRPairs(repo, msr_pr)\n# print(result)\n count += 1\n print(str(count)+'/'+str(total))\n for pair in result:\n with open(file, 'a') as f:\n print(\"\\t\".join(pair), file=f)\n else:\n pulls = get_repo_info(repo, 'pull')\n ps = shuffle(pulls)\n\n cnt = 0\n with open(file, 'a+') as f:\n for p in ps:\n if check_large(p):\n continue\n if (repo, str(p['number'])) in has:\n continue\n cnt += 1\n print(repo, p['number'], file=f)\n\n if cnt == gen_num:\n break\n\n\nif __name__ == \"__main__\":\n if (len(sys.argv) == 1):\n file = 'data/consecutive_NonDupPR_pairs_' + repo_type + '.txt'\n gen_num = 100\n else:\n file = sys.argv[1].strip()\n gen_num = int(sys.argv[2].strip())\n\n print(file)\n print(repo_type)\n work(file)\n","sub_path":"gen_select_subset_pr.py","file_name":"gen_select_subset_pr.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"556113873","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 15 22:42:46 2018\n\n7組不重複大樂透電腦選號: 6個 1-49 的亂數\n\"\"\"\nimport random\n\n# Create lotto numbers without duplicates \ndef createLotto(): \n lotto = []\n n = 1\n while n <= 6:\n rn = random.randint(1, 49)\n if rn not in lotto:\n lotto.append(rn)\n n += 1\n lotto.sort()\n #lotto2 = [str(x).zfill(2) for x in lotto]\n #print(lotto2)\n return lotto\n \ndef main():\n lottoLst = []\n c = 1\n while c <= 7:\n newLotto = createLotto()\n if newLotto not in lottoLst:\n lottoLst.append(newLotto)\n c += 1\n print(newLotto)\n \nmain()","sub_path":"textbook/sample-code_s1_s2/s2_list_3_lottos.py","file_name":"s2_list_3_lottos.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353978326","text":"\"\"\"\nduel.py\n\nA module to handle xboard or winboard engine matches.\n\"\"\"\n\n\nimport subprocess\nimport argparse\nimport time\nimport random\nimport concurrent.futures\nfrom concurrent.futures import ProcessPoolExecutor\nimport logging\nfrom statistics import mean\nfrom typing import List\n\n\nlogging.basicConfig(\n filename='log_duel.txt', filemode='a',\n level=logging.DEBUG,\n format='%(asctime)s - pid%(process)5d - %(levelname)5s - %(message)s')\n\n\nclass Timer:\n def __init__(self, base_time, inc_time):\n \"\"\"\n The time unit is in ms (milliseconds)\n \"\"\"\n self.base_time = base_time\n self.inc_time = inc_time\n self.rem_time = self.base_time + self.inc_time\n\n def update(self, elapse):\n \"\"\"\n This is called after every engine move is completed.\n \"\"\"\n self.rem_time -= elapse\n self.rem_time += self.inc_time\n\n def is_zero_time(self):\n return True if self.rem_cs() <= 0 else False\n\n def rem_cs(self):\n return self.rem_time // 10\n\n\ndef define_engine(engine_option_value):\n \"\"\"\n Define engine files, name and options.\n \"\"\"\n ed1, ed2 = {}, {}\n e1 = {'proc': None, 'cmd': None, 'name': 'test', 'opt': ed1, 'tc': '', 'depth': 0}\n e2 = {'proc': None, 'cmd': None, 'name': 'base', 'opt': ed2, 'tc': '', 'depth': 0}\n for i, eng_opt_val in enumerate(engine_option_value):\n for value in eng_opt_val:\n if i == 0:\n if 'cmd=' in value:\n e1.update({'cmd': value.split('=')[1]})\n elif 'option.' in value:\n # Todo: support float value\n # option.QueenValueOpening=1000\n optn = value.split('option.')[1].split('=')[0]\n optv = int(value.split('option.')[1].split('=')[1])\n ed1.update({optn: optv})\n e1.update({'opt': ed1})\n elif 'tc=' in value:\n e1.update({'tc': value.split('=')[1]})\n elif 'name=' in value:\n e1.update({'name': value.split('=')[1]})\n elif 'depth=' in value:\n e1.update({'depth': int(value.split('=')[1])})\n elif i == 1:\n if 'cmd=' in value:\n e2.update({'cmd': value.split('=')[1]})\n elif 'option.' in value:\n optn = value.split('option.')[1].split('=')[0]\n optv = int(value.split('option.')[1].split('=')[1])\n ed2.update({optn: optv})\n e2.update({'opt': ed2})\n elif 'tc=' in value:\n e2.update({'tc': value.split('=')[1]})\n elif 'name=' in value:\n e2.update({'name': value.split('=')[1]})\n elif 'depth=' in value:\n e2.update({'depth': int(value.split('=')[1])})\n\n return e1, e2\n\n\ndef get_fen_list(fn, is_rand=False):\n \"\"\"\n Read fen file and return a list of fens.\n \"\"\"\n fens = []\n\n if fn is None:\n return fens\n\n with open(fn) as f:\n for lines in f:\n fen = lines.strip()\n fens.append(fen)\n\n if is_rand:\n random.shuffle(fens)\n\n return fens\n\n\ndef get_tc(tcd):\n \"\"\"\n tc=0/3+1 or 3+1, blitz 3m + 1s inc\n tc=0/0:5+0.1 or 0:5+0.1, blitz 0m + 5s + 0.1s inc\n \"\"\"\n base_minv, base_secv, inc_secv = 0, 0, 0.0\n\n if tcd == '':\n return base_minv, base_secv, inc_secv\n\n # Check base time with minv:secv format.\n if '/' in tcd:\n basev = tcd.split('/')[1].split('+')[0].strip()\n else:\n basev = tcd.split('+')[0].strip()\n\n if ':' in basev:\n base_minv = int(basev.split(':')[0])\n base_secv = int(basev.split(':')[1])\n else:\n base_minv = int(basev)\n\n if '/' in tcd:\n inc_secv = float(tcd.split('/')[1].split('+')[1].strip())\n else:\n inc_secv = float(tcd.split('+')[1].strip())\n\n return base_minv, base_secv, inc_secv\n\n\ndef turn(fen):\n \"\"\"\n Return side to move of the given fen.\n \"\"\"\n side = fen.split()[1].strip()\n if side == 'w':\n return True\n return False\n\n\ndef save_game(outfn, fen, moves, scores, depths, e1, e2, start_turn, gres,\n termination='', variant=''):\n logging.info('Saving game ...')\n with open(outfn, 'a') as f:\n f.write('[Event \"Optimization test\"]\\n')\n f.write(f'[White \"{e1 if start_turn else e2}\"]\\n')\n f.write(f'[Black \"{e1 if not start_turn else e2}\"]\\n')\n f.write(f'[Result \"{gres}\"]\\n')\n\n f.write(f'[Variant \"{variant}\"]\\n')\n\n if termination != '':\n f.write(f'[Termination \"{termination}\"]\\n')\n\n if not isinstance(fen, int):\n f.write(f'[FEN \"{fen}\"]\\n\\n')\n else:\n f.write('\\n')\n\n for i, (m, s, d) in enumerate(zip(moves, scores, depths)):\n num = i + 1\n if num % 2 == 0:\n if start_turn:\n str_num = f'{num // 2}... '\n else:\n str_num = f'{num // 2}. '\n else:\n num += 1\n if start_turn:\n str_num = f'{num // 2}. '\n else:\n str_num = f'{num // 2}... '\n f.write(f'{str_num}{m} {{{s}/{d}}} ')\n if (i + 1) % 5 == 0:\n f.write('\\n')\n f.write('\\n\\n')\n\n\ndef adjudicate_win(score_history, resign_option, side):\n logging.info('Try adjudicating this game by win ...')\n ret, gres, e1score = False, '*', 0.0\n\n if len(score_history) >= 40:\n fcp_score = score_history[0::2]\n scp_score = score_history[1::2]\n\n fwin_cnt, swin_cnt = 0, 0\n movecount = resign_option['movecount'] * 2\n score = resign_option['score']\n\n for i, (fs, ss) in enumerate(zip(reversed(fcp_score),\n reversed(scp_score))):\n if i >= movecount:\n break\n if i <= movecount and fs >= score and ss <= -score:\n fwin_cnt += 1\n elif i <= movecount and fs <= -score and ss >= score:\n swin_cnt += 1\n\n if fwin_cnt >= movecount:\n gres = '1-0' if side else '0-1'\n e1score = 1.0\n logging.info(f'{\"White\" if side else \"Black\"} wins by adjudication.')\n ret = True\n if swin_cnt >= movecount:\n gres = '1-0' if side else '0-1'\n e1score = 0\n logging.info(f'{\"White\" if side else \"Black\"} wins by adjudication.')\n ret = True\n\n return ret, gres, e1score\n\n\ndef adjudicate_draw(score_history, draw_option):\n logging.info('Try adjudicating this game by draw ...')\n ret, gres, e1score = False, '*', 0.0\n\n if len(score_history) >= draw_option['movenumber'] * 2:\n fcp_score = score_history[0::2]\n scp_score = score_history[1::2]\n\n draw_cnt = 0\n movecount = draw_option['movecount'] * 2\n score = draw_option['score']\n\n for i, (fs, ss) in enumerate(zip(reversed(fcp_score),\n reversed(scp_score))):\n if i >= movecount:\n break\n if (i <= movecount and abs(fs) <= score\n and abs(ss) <= score):\n draw_cnt += 1\n\n if draw_cnt >= movecount:\n gres = '1/2-1/2'\n e1score = 0.5\n logging.info('Draw by adjudication.')\n ret = True\n\n return ret, gres, e1score\n\n\ndef is_game_end(line, test_engine_color):\n game_end, gres, e1score, termination, comment = False, '*', 0.0, '', ''\n\n if '1-0' in line:\n game_end = True\n e1score = 1.0 if test_engine_color else 0.0\n gres = '1-0'\n termination = 'white mates black'\n elif '0-1' in line:\n game_end = True\n e1score = 1.0 if not test_engine_color else 0.0\n gres = '0-1'\n termination = 'black mates white'\n elif '1/2-1/2' in line:\n game_end = True\n e1score = 0.5\n gres = '1/2-1/2'\n if 'repetition' in line.lower():\n termination = 'draw by repetition'\n elif 'insufficient' in line.lower():\n termination = 'draw by insufficient mating material'\n elif 'fifty' in line.lower():\n termination = 'draw by insufficient mating material'\n elif 'stalemate' in line.lower():\n termination = 'draw by stalemate'\n\n return game_end, gres, e1score, termination\n\n\ndef param_to_dict(param):\n \"\"\"\n Convert string param to a dictionary.\n \"\"\"\n ret_param = {}\n for par in param.split(','):\n par = par.strip()\n sppar = par.split() # Does not support param with space\n spname = sppar[0].strip()\n spvalue = int(sppar[1].strip())\n ret_param.update({spname: spvalue})\n\n return ret_param\n\n\ndef time_forfeit(is_timeup, current_color, test_engine_color):\n game_end, gres, e1score = False, '*', 0.0\n\n if is_timeup:\n # test engine loses as white\n if current_color and test_engine_color:\n gres = '0-1'\n e1score = 0.0\n game_end = True\n print(f'test engine with color {test_engine_color} loses on time')\n # test engine loses as black\n elif not current_color and not test_engine_color:\n gres = '1-0'\n e1score = 0.0\n game_end = True\n print(f'test engine with color {test_engine_color} loses on time')\n # test engine wins as white\n elif not current_color and test_engine_color:\n gres = '1-0'\n e1score = 1.0\n game_end = True\n print(f'test engine with color {test_engine_color} wins on time')\n # test engine wins as black\n elif current_color and not test_engine_color:\n gres = '0-1'\n e1score = 1.0\n game_end = True\n print(f'test engine with color {test_engine_color} wins on time')\n\n if game_end:\n logging.info('Game ends by time forfeit.')\n\n return game_end, gres, e1score\n\n\ndef match(e1, e2, fen, output_game_file, variant, draw_option,\n resign_option, repeat=2) -> List[float]:\n \"\"\"\n Run an engine match between e1 and e2. Save the game and print result\n from e1 perspective.\n \"\"\"\n move_hist = []\n all_e1score = []\n is_show_search_info = False\n\n # Start engine match, 2 games will be played.\n for gn in range(repeat):\n logging.info(f'Match game no. {gn + 1}')\n logging.info(f'Test engine plays as {\"first\" if gn % 2 == 0 else \"second\"} engine.')\n\n pe1 = subprocess.Popen(e1['cmd'], stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True, bufsize=1)\n\n pe2 = subprocess.Popen(e2['cmd'], stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True, bufsize=1)\n\n e1.update({'proc': pe1})\n e2.update({'proc': pe2})\n\n if gn % 2 == 0:\n eng = [e1, e2]\n else:\n eng = [e2, e1]\n\n for i, pr in enumerate(eng):\n e = pr['proc']\n pn = pr['name']\n\n e.stdin.write('xboard\\n')\n logging.debug(f'{pn} > xboard')\n e.stdin.write('protover 2\\n')\n logging.debug(f'{pn} > protover 2')\n\n for eline in iter(e.stdout.readline, ''):\n line = eline.strip()\n logging.debug(f'{pn} < {line}')\n if 'done=1' in line:\n break\n\n # Set param to engines.\n for k, v in pr['opt'].items():\n e.stdin.write(f'option {k}={v}\\n')\n logging.debug(f'{pn} > option {k}={v}')\n\n timer, depth_control = [], []\n for i, pr in enumerate(eng):\n e = pr['proc']\n pn = pr['name']\n\n e.stdin.write(f'variant {variant}\\n')\n logging.debug(f'{pn} > variant {variant}')\n\n e.stdin.write('ping 1\\n')\n logging.debug(f'{pn} > ping 1')\n for eline in iter(e.stdout.readline, ''):\n line = eline.strip()\n logging.debug(f'{pn} < {line}')\n if 'pong' in line:\n break\n\n e.stdin.write('new\\n')\n logging.debug(f'{pn} > new')\n\n e.stdin.write('post\\n')\n logging.debug(f'{pn} > post')\n\n # Define time control, base time in minutes and inc in seconds.\n base_minv, base_secv, incv = get_tc(pr['tc'])\n all_base_sec = base_minv * 60 + base_secv\n\n logging.info(f'base_minv: {base_minv}m, base_secv: {base_secv}s, incv: {incv}s')\n\n # Send level command to each engine.\n tbase = max(1, all_base_sec//60)\n e.stdin.write(f'level 0 {tbase} {float(incv):0.2f}\\n')\n logging.debug(f'{pn} > level 0 {tbase} {float(incv):0.2f}')\n\n # Setup Timer, convert base time to ms and inc in sec to ms\n timer.append(Timer(all_base_sec * 1000, int(incv * 1000)))\n\n depth_control.append(pr['depth'])\n\n e.stdin.write('force\\n')\n logging.debug(f'{pn} > force')\n\n e.stdin.write(f'setboard {fen}\\n')\n logging.debug(f'{pn} > setboard {fen}')\n\n e.stdin.write('ping 2\\n')\n logging.debug(f'{pn} > ping 2')\n for eline in iter(e.stdout.readline, ''):\n line = eline.strip()\n logging.debug(f'{pn} < {line}')\n if 'pong' in line:\n break\n\n num, side, move, line, game_end = 0, 0, None, '', False\n score_history, elapse_history, depth_history = [], [], []\n start_turn = turn(fen) if not isinstance(fen, int) else True\n gres, e1score = '*', 0.0\n is_time_over = [False, False]\n current_color = start_turn # True if white to move\n\n test_engine_color = True if ((start_turn and gn % 2 == 0) or (not start_turn and gn % 2 != 0)) else False\n termination = ''\n\n # Start the game.\n while True:\n if depth_control[side] > 0:\n eng[side]['proc'].stdin.write(f'sd {depth_control[side]}\\n')\n logging.debug(f'{eng[side][\"name\"]} > sd {depth_control[side]}')\n else:\n eng[side]['proc'].stdin.write(f'time {timer[side].rem_cs()}\\n')\n logging.debug(f'{eng[side][\"name\"]} > time {timer[side].rem_cs()}')\n\n eng[side]['proc'].stdin.write(f'otim {timer[not side].rem_cs()}\\n')\n logging.debug(f'{eng[side][\"name\"]} > otim {timer[not side].rem_cs()}')\n\n t1 = time.perf_counter_ns()\n\n if num == 0:\n eng[side]['proc'].stdin.write('go\\n')\n logging.debug(f'{eng[side][\"name\"]} > go')\n else:\n move_hist.append(move)\n eng[side]['proc'].stdin.write(f'{move}\\n')\n logging.debug(f'{eng[side][\"name\"]} > {move}')\n\n # Send another go because of force.\n if num == 1:\n eng[side]['proc'].stdin.write('go\\n')\n logging.debug(f'{eng[side][\"name\"]} > go')\n\n num += 1\n score, depth = None, None\n\n for eline in iter(eng[side]['proc'].stdout.readline, ''):\n line = eline.strip()\n\n logging.debug(f'{eng[side][\"name\"]} < {line}')\n\n if is_show_search_info:\n if not line.startswith('#'):\n print(line)\n\n # Save score and depth from engine search info.\n if line.split()[0].isdigit():\n score = int(line.split()[1]) # cp\n depth = int(line.split()[0])\n\n # Check end of game as claimed by engines.\n game_endr, gresr, e1scorer, termi = is_game_end(line, test_engine_color)\n if game_endr:\n game_end, gres, e1score, termination = game_endr, gresr, e1scorer, termi\n break\n\n if 'move ' in line and not line.startswith('#'):\n elapse = (time.perf_counter_ns() - t1) // 1000000\n timer[side].update(elapse)\n elapse_history.append(elapse)\n\n move = line.split('move ')[1]\n score_history.append(score if score is not None else 0)\n depth_history.append(depth if depth is not None else 0)\n\n if timer[side].is_zero_time():\n is_time_over[current_color] = True\n termination = 'forfeits on time'\n logging.info('time is over')\n break\n\n if game_end:\n break\n\n # Game adjudications\n\n # Resign\n if (resign_option['movecount'] is not None\n and resign_option['score'] is not None):\n game_endr, gresr, e1scorer = adjudicate_win(\n score_history, resign_option, side)\n\n if game_endr:\n gres, e1score = gresr, e1scorer\n logging.info('Game ends by resign adjudication.')\n break\n\n # Draw\n if (draw_option['movenumber'] is not None\n and draw_option['movenumber'] is not None\n and draw_option['score'] is not None):\n game_endr, gresr, e1scorer = adjudicate_draw(\n score_history, draw_option)\n if game_endr:\n gres, e1score = gresr, e1scorer\n logging.info('Game ends by resign adjudication.')\n break\n\n # Time is over\n if depth_control[side] == 0:\n game_endr, gresr, e1scorer = time_forfeit(\n is_time_over[current_color], current_color, test_engine_color)\n if game_endr:\n gres, e1score = gresr, e1scorer\n break\n\n side = not side\n current_color = not current_color\n\n if output_game_file is not None:\n save_game(output_game_file, fen, move_hist, score_history,\n depth_history, eng[0][\"name\"], eng[1][\"name\"],\n start_turn, gres, termination, variant)\n\n for i, e in enumerate(eng):\n e['proc'].stdin.write('quit\\n')\n logging.debug(f'{e[\"name\"]} > quit')\n\n all_e1score.append(e1score)\n\n return all_e1score\n\n\ndef round_match(fen, e1, e2, output_game_file, repeat, draw_option,\n resign_option, variant, posround=1) -> List[float]:\n \"\"\"\n Play a match between e1 and e2 using fen as starting position. By default\n 2 games will be played color is reversed. If posround is more than 1, the\n match will be repeated posround times. The purpose of posround is to verify\n that the match result is repeatable with the use of only a single fen.\n \"\"\"\n test_engine_score = []\n\n for _ in range(posround):\n res = match(e1, e2, fen, output_game_file, variant,\n draw_option, resign_option, repeat=repeat)\n test_engine_score.append(res)\n\n return test_engine_score\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-rounds', required=False,\n help='Number of encounter. Can be number of games if repeat is 2, default=2\\n',\n type=int, default=2)\n parser.add_argument('-repeat', required=False,\n help='Number of times to play a certain opening\\n'\n 'default is 2 so that the position will be\\n'\n 'played twice and each engine takes both white\\n'\n 'and black at the start of each game.',\n type=int, default=2)\n parser.add_argument('-engine', nargs='*', action='append', required=True,\n metavar=('cmd=', 'name='),\n help='This option is used to define the engines.\\n'\n 'Example:\\n'\n '-engine cmd=engine1.exe name=test ...'\n ' --engine cmd=engine2.exe name=base')\n parser.add_argument('-draw', nargs='*', action='append', required=False,\n metavar=('movenumber=', 'movecount='),\n help='Adjudicates game to a draw result. Example:\\n'\n '-draw movenumber=40 movecount=10 score=0')\n parser.add_argument('-resign', nargs='*', action='append', required=False,\n metavar=('movecount=', 'score='),\n help='Adjudicates game to a loss result. Example:\\n'\n '-resign movecount=10 score=900')\n parser.add_argument('-pgnout', required=False,\n metavar='pgn_output_filename',\n help='pgn output filename')\n parser.add_argument('-concurrency', required=False,\n help='number of game to run in parallel, default=1',\n type=int, default=1)\n parser.add_argument('-variant', required=True, help='name of the variant')\n parser.add_argument('-each', nargs='*', action='append', required=False,\n metavar=('tc=', 'option.='),\n help='This option is used to apply to both engnes.\\n'\n 'Example where tc is applied to each engine:\\n'\n '-each tc=1+0.1')\n parser.add_argument('-openings', nargs='*', action='append',\n required=False,\n metavar=('file=', 'format='),\n help='Define start openings. Example:\\n'\n '-openings file=start.fen format=epd')\n parser.add_argument('-tournament', required=False, default='round-robin',\n metavar='tour_type',\n help='tournament type, default=round-robin')\n\n args = parser.parse_args()\n\n # Define engine files, name and options.\n e1, e2 = define_engine(args.engine)\n\n # Exit if engine file is not defined.\n if e1['cmd'] is None or e2['cmd'] is None:\n print('Error, engines are not properly defined!')\n return\n\n each_engine_option = {}\n if args.each is not None:\n for opt in args.each:\n for value in opt:\n key = value.split('=')[0]\n val = value.split('=')[1].strip()\n each_engine_option.update({key: val})\n\n # Update tc of e1/e2 from each.\n if e1['tc'] == '' or e2['tc'] == '':\n if 'tc' in each_engine_option:\n for key, val in each_engine_option.items():\n if key == 'tc':\n e1.update({key: val})\n e2.update({key: val})\n break\n\n # Update depth of e1/e2 from each.\n if e1['depth'] == 0 or e2['depth'] == 0:\n if 'depth' in each_engine_option:\n for key, val in each_engine_option.items():\n if key == 'depth':\n e1.update({key: int(val)})\n e2.update({key: int(val)})\n break\n\n # Exit if there are no tc or depth.\n if e1['tc'] == '' or e2['tc'] == '':\n if e1['depth'] == 0 or e2['depth'] == 0:\n raise Exception('Error! tc or depth are not defined.')\n\n # Start opening file\n fen_file = None\n if args.openings is not None:\n for opt in args.openings:\n for value in opt:\n if 'file=' in value:\n fen_file = value.split('=')[1]\n\n draw_option = {'movenumber': None, 'movecount': None, 'score': None}\n if args.draw is not None:\n for opt in args.draw[0]:\n key = opt.split('=')[0]\n val = int(opt.split('=')[1])\n draw_option.update({key: val})\n\n resign_option = {'movecount': None, 'score': None}\n if args.resign is not None:\n for opt in args.resign[0]:\n key = opt.split('=')[0]\n val = int(opt.split('=')[1])\n resign_option.update({key: val})\n\n is_random_startpos = True\n posround = 1 # Number of times the same position is played\n\n fens = get_fen_list(fen_file, is_random_startpos)\n\n output_game_file = args.pgnout\n\n # Start match\n joblist = []\n test_engine_score_list = []\n total_games = max(1, args.rounds // args.repeat)\n\n # Use Python 3.8 or higher\n with ProcessPoolExecutor(max_workers=args.concurrency) as executor:\n for i, fen in enumerate(fens if len(fens) else range(1000)):\n if i >= total_games:\n break\n job = executor.submit(round_match, fen, e1, e2,\n output_game_file, args.repeat,\n draw_option, resign_option, args.variant,\n posround)\n joblist.append(job)\n\n for future in concurrent.futures.as_completed(joblist):\n try:\n test_engine_score = future.result()[0]\n for s in test_engine_score:\n test_engine_score_list.append(s)\n perf = mean(test_engine_score_list)\n games = len(test_engine_score_list)\n print(f'Score of {e1[\"name\"]} vs {e2[\"name\"]}: [{perf}] {games}')\n except concurrent.futures.process.BrokenProcessPool as ex:\n print(f'exception: {ex}')\n\n logging.info(f'final test score: {mean(test_engine_score_list)}')\n print('Finished match')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"duel.py","file_name":"duel.py","file_ext":"py","file_size_in_byte":26013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"196588146","text":"import logging\nfrom multiprocessing import Process\n\nfrom fantom_util.constants import DATA_DIR, FASTTEXT_CALCULATOR_PORT\nfrom fantom_util.feature_extraction.nlp import preload_model\nfrom fantom_util.misc import normalize_vector\n\nlogger = logging.getLogger(__name__)\n\n\ndef fasttext_model():\n import zmq\n\n context = zmq.Context()\n s = context.socket(zmq.REQ)\n s.connect(f\"tcp://localhost:{FASTTEXT_CALCULATOR_PORT}\")\n return s\n\n\n@preload_model(fasttext_model)\ndef word_embeddings(fasttext_socket, tokens):\n \"\"\"Calculate FastText word embeddings for each token.\"\"\"\n if not tokens:\n return None\n fasttext_socket.send_pyobj(tokens)\n return fasttext_socket.recv_pyobj()\n\n\n@preload_model(fasttext_model)\ndef sentence_embeddings(model, text):\n \"\"\"Calculate FastText sentence embeddings for each token.\"\"\"\n if not text:\n return None\n return model.get_sentence_vector(text)\n\n\ncalculate_fasttext_started = False\n\n\ndef start_calculate_fasttext_process():\n global calculate_fasttext_started\n if not calculate_fasttext_started:\n calculate_fasttext_started = True\n p = Process(target=calculate_fasttext)\n p.daemon = True\n p.start()\n\n\ndef calculate_fasttext():\n import zmq\n from fastText import load_model\n context = zmq.Context()\n s = context.socket(zmq.REP)\n s.bind(f\"tcp://*:{FASTTEXT_CALCULATOR_PORT}\")\n logger.info(\"Started fasttext server at port %s\", FASTTEXT_CALCULATOR_PORT)\n logger.info(\n \"about to load model from: %s\", f\"{DATA_DIR}/wiki-news-300d-1M-subword.bin\"\n )\n model = load_model(f\"{DATA_DIR}/wiki-news-300d-1M-subword.bin\")\n logger.info(\"Loaded fasttext model. Waiting for jobs\")\n while True:\n tokens = s.recv_pyobj()\n logger.debug(\"tokens received %s\", tokens)\n s.send_pyobj(\n [normalize_vector(model.get_word_vector(token)) for token in tokens]\n )\n\n","sub_path":"fantom_util/fantom_util/feature_extraction/fasttext_extractor.py","file_name":"fasttext_extractor.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"317851423","text":"import os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n'''\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': 'norma',\n 'USER': 'root',\n 'PASSWORD': 'master',\n 'HOST': 'localhost', # Or an IP Address that your DB is hosted on\n 'PORT': '3306',\n }\n}\n\n'''\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'brand.sqlite3'),\n }\n}\n\n\nSTATICFILES_DIRS = (\n # os.path.join(BASE_DIR, 'static'),\n # os.path.join(BASE_DIR, 'manager', 'static'),\n os.path.join(os.path.abspath(os.path.dirname(__file__) + '/..'), 'static'),\n )\n\nSTATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__) + '/..'), 'statics/')\nSTATIC_URL = '/static/'\n\n\nLOGIN_URL = \"/\"\nLOGIN_REDIRECT_VIEW = \"/\"\nLOGOUT_URL = \"/logout/\"\n\nEMAIL_HOST = 'mail.atomyc.house'\nEMAIL_HOST_USER = 'rios@atomyc.house'\nEMAIL_HOST_PASSWORD = 'zserdx'\nDEFAULT_FROM_EMAIL = 'rios@atomyc.house'\nSERVER_EMAIL = 'rios@atomyc.house'\nEMAIL_PORT = 25\nEMAIL_USE_TLS = False\n","sub_path":"brandline/local_settings.py","file_name":"local_settings.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"303325771","text":"import argparse\nimport subprocess\n\nparser = argparse.ArgumentParser(description=\"Subset bed file to callable regions only\")\nparser.add_argument('--input_benchmark', metavar=\"I\", type=str, nargs=\"+\", help=\"input bed file\")\nparser.add_argument('--input_genes', metavar=\"I\", type=str, nargs=\"+\", help=\"input bed file\")\nparser.add_argument('--output', metavar=\"O\", type=str, nargs=\"+\", help=\"output file\")\nargs = parser.parse_args()\n\nbenchmark_filename = args.input_benchmark[0]\n\nf_input_genes = open(args.input_genes[0], \"r\")\nf_input_genes_lines = f_input_genes.readlines()\nf_out = open(args.output[0], \"w+\")\n\nbases_covered_per_gene = []\n\nfor gene in f_input_genes_lines:\n gene = gene.strip(\"\\n\")\n print(gene)\n tmf = open(\"temp_gene_file_\" + args.output[0], \"w\")\n tmf.write(gene)\n tmf.flush()\n tmf.close()\n #subprocess.check_output(\"echo '\" + gene + \"' > temp_gene_file_\" + args.output[0], shell = True)\n covered_bases = subprocess.check_output(\"bedtools intersect -a temp_gene_file_\" + args.output[0] + \" -b \" + benchmark_filename + \" | sort -k1,1 -k2,2n - | bedtools merge -i stdin | awk '{sum+=$3-$2} END {print sum}'\", shell = True).strip()\n if covered_bases != '':\n bases_covered_per_gene.append(covered_bases)\n else:\n bases_covered_per_gene.append('0')\n subprocess.check_output(\"rm temp_gene_file_\" + args.output[0], shell = True)\n\nprint(bases_covered_per_gene)\nfor i in range(0, len(f_input_genes_lines)):\n line = f_input_genes_lines[i]\n if \"#\" in line:\n f_out.write(line)\n f_out.flush()\n continue \n line_split = line.split(\"\\t\")\n start = int(line_split[1])\n end = int(line_split[2])\n gene_length = end - start\n coverage = bases_covered_per_gene[i]\n coverage_percentage = float(coverage)/float(gene_length)\n to_write_out = line_split[0] + \"\\t\" + line_split[1] + \"\\t\" + line_split[2] + \"\\t\" + line_split[3].strip() + \"\\t\" + str(coverage) + \"\\t\" + str(coverage_percentage) + \"\\n\"\n f_out.write(to_write_out)\n f_out.flush() \n\nf_out.close()\nf_input_genes.close()","sub_path":"analysis/benchmark_generation/find_overlap_per_gene.py","file_name":"find_overlap_per_gene.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"558155027","text":"from django.views.decorators.csrf import csrf_exempt\nimport requests\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, Http404\nfrom django.http import JsonResponse\n\nfrom django.contrib import messages\n\n\ndef verifyRole(request, role):\n #role = 'cms' 'pmo' 'er' 'po'\n # pmo @ singapore.com\n # cmsoperator @ singapore.com\n # emergencyresponse @ singapore.com\n cookie = request.COOKIES.get('auth')\n dictToSend = {\n 'cookie': cookie\n }\n authenticatedRole = requests.post('http://localhost:5002/checkCookie', json=dictToSend)\n print('role:', authenticatedRole.text)\n if authenticatedRole.text == 'error':\n messages.warning(request, 'You are not authorised to visit that page. Please login again.')\n response = redirect('login')\n return response, authenticatedRole.text\n else:\n if authenticatedRole.text not in role:\n messages.warning(request, 'You are not authorised to visit that page. Please login again.')\n response = redirect('login')\n return response, authenticatedRole.text\n else:\n return 'success', authenticatedRole.text\n\n########################################################################################################################\n# Views\n########################################################################################################################\n\ndef get_user_role(request):\n if request.method == 'POST':\n try:\n cookie = request.POST.get(\"cookie\")\n except KeyError:\n return HttpResponse('unsuccessful')\n dictToSend = {\n 'cookie': cookie\n }\n authenticatedRole = requests.post('http://localhost:5002/checkCookie', json=dictToSend)\n print('role:123', authenticatedRole.text)\n\n data = {\n 'role': authenticatedRole.text\n }\n return JsonResponse(data)\n\n\ndef login(request):\n return render(request, 'login.html')\n\n\ndef home(request):\n res, role = verifyRole(request, ['cms', 'po', 'er'])\n if res != 'success':\n return res\n if role == 'po':\n return render(request, 'base_po.html', {'page_name': \"Homepage\"})\n elif role == 'cms':\n return render(request, 'home.html', {'page_name': \"Homepage\"})\n elif role == 'er':\n return render(request, 'base_en.html', {'page_name': \"Homepage\"})\n return HttpResponse('login failed')\n\n########################################################################################################################\n# APIs\n########################################################################################################################\n\n@csrf_exempt\ndef authorization(request):\n if request.method == 'POST':\n # try:\n # Log the user in\n dictToSend = {\n 'username': request.POST.get('username'),\n 'password': request.POST.get('password')\n }\n session_cookie = requests.post('http://localhost:5002/login', json=dictToSend)\n print('session_cookie', session_cookie.text[:10])\n if not (session_cookie.text == 'error'):\n # response = HttpResponse(\"successful\")\n response = redirect('home')\n response.set_cookie('auth', session_cookie.text)\n return response\n # except Exception:\n # return HttpResponse(\"fail\")\n return HttpResponse(\"fail\")\n\n\n\n","sub_path":"scse_cz3003_2018_s1_cms_app/views/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"103876017","text":"#!/usr/bin/python\n\"\"\"\n (C) Copyright 2020 Intel Corporation.\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 GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE\n The Government's rights to use, modify, reproduce, release, perform, display,\n or disclose this software are subject to the terms of the Apache License as\n provided in Contract No. B609815.\n Any reproduction of computer software, computer software documentation, or\n portions thereof marked with this legend must also reproduce the markings.\n\"\"\"\nimport threading\nimport re\nimport time\nimport os\n\nfrom general_utils import run_task\nfrom command_utils_base import CommandFailure\nfrom avocado.core.exceptions import TestFail\nfrom ior_test_base import IorTestBase\nfrom test_utils_pool import TestPool\nfrom ior_utils import IorCommand\n\ntry:\n # python 3.x\n import queue\nexcept ImportError:\n # python 2.7\n import Queue as queue\n\ndef get_device_ids(dmg, servers):\n \"\"\"Get the NVMe Device ID from servers\n\n Args:\n dmg: DmgCommand class instance.\n servers (list): list of server hosts.\n\n Returns:\n devices (dictionary): Device UUID for servers.\n\n \"\"\"\n devices = {}\n dmg.set_sub_command(\"storage\")\n dmg.sub_command_class.set_sub_command(\"query\")\n dmg.sub_command_class.sub_command_class.set_sub_command(\"list-devices\")\n for host in servers:\n dmg.hostlist = host\n try:\n result = dmg.run()\n except CommandFailure as _error:\n raise \"dmg command failed for list-devices\"\n drive_list = []\n for line in result.stdout.split('\\n'):\n if 'UUID' in line:\n drive_list.append(line.split(':')[1])\n devices[host] = drive_list\n return devices\n\nclass ServerFillUp(IorTestBase):\n \"\"\"\n Class to fill up the servers based on pool percentage given.\n It will get the drives listed in yaml file and find the maximum capacity of\n the pool which will be created.\n IOR block size will be calculated as part of function based on percentage\n of pool needs to fill up.\n \"\"\"\n # pylint: disable=too-many-ancestors\n # pylint: disable=too-many-instance-attributes\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize a IorTestBase object.\"\"\"\n super(ServerFillUp, self).__init__(*args, **kwargs)\n self.no_of_pools = 1\n self.capacity = 1\n self.no_of_servers = 1\n self.no_of_drives = 1\n self.pool = None\n self.dmg = None\n self.set_faulty_device = False\n self.scm_fill = False\n self.nvme_fill = False\n self.ior_matrix = None\n\n def setUp(self):\n \"\"\"Set up each test case.\"\"\"\n # obtain separate logs\n self.update_log_file_names()\n # Start the servers and agents\n super(ServerFillUp, self).setUp()\n self.hostfile_clients = None\n self.ior_default_flags = self.ior_cmd.flags.value\n self.ior_scm_xfersize = self.ior_cmd.transfer_size.value\n self.ior_read_flags = self.params.get(\"read_flags\",\n '/run/ior/iorflags/*',\n '-r -R -k -G 1')\n self.ior_nvme_xfersize = self.params.get(\n \"nvme_transfer_size\", '/run/ior/transfersize_blocksize/*',\n '16777216')\n #Get the number of daos_io_servers\n self.daos_io_servers = (self.server_managers[0].manager\n .job.yaml.server_params)\n self.out_queue = queue.Queue()\n\n def get_max_capacity(self, mem_size_info):\n \"\"\"Get storage capacity based on server yaml file.\n\n Args:\n mem_size_info(dict): List of NVMe/SCM size from each servers\n\n Returns:\n int: Maximum NVMe storage capacity.\n\n \"\"\"\n # Get the Maximum storage space among all the servers.\n drive_capa = []\n for server in self.hostlist_servers:\n for daos_io_server in range(len(self.daos_io_servers)):\n drive_capa.append(sum(mem_size_info[server][daos_io_server]))\n print('Maximum Storage space from the servers is {}'\n .format(int(min(drive_capa) * 0.96)))\n\n #Return the 99% of storage space as it won't be used 100% for\n #pool creation.\n return int(min(drive_capa) * 0.96)\n\n def get_scm_lsblk(self):\n \"\"\"Get SCM size using lsblk from servers.\n\n Returns:\n dict: Dictionary of server mapping with disk ID and size\n 'wolf-A': {'nvme2n1': '1600321314816'}.\n \"\"\"\n scm_data = {}\n\n task = run_task(self.hostlist_servers, \"lsblk -b | grep pmem\")\n for _rc_code, _node in task.iter_retcodes():\n if _rc_code == 1:\n print(\"Failed to lsblk on {}\".format(_node))\n raise ValueError\n #Get the drive size from each daos_io_servers\n for buf, nodelist in task.iter_buffers():\n for node in nodelist:\n pcmem_data = {}\n output = str(buf).split('\\n')\n for _tmp in output:\n pcmem_data[_tmp.split()[0]] = _tmp.split()[3]\n scm_data['{}'.format(node)] = pcmem_data\n\n return scm_data\n\n def get_nvme_lsblk(self):\n \"\"\"Get NVMe size using lsblk from servers.\n\n Returns:\n dict: Dictionary of server mapping with disk ID and size\n 'wolf-A': {'nvme2n1': '1600321314816'}.\n \"\"\"\n nvme_data = {}\n\n task = run_task(self.hostlist_servers, \"lsblk -b /dev/nvme*n*\")\n for _rc_code, _node in task.iter_retcodes():\n if _rc_code == 1:\n print(\"Failed to lsblk on {}\".format(_node))\n raise ValueError\n #Get the drive size from each daos_io_servers\n for buf, nodelist in task.iter_buffers():\n for node in nodelist:\n disk_data = {}\n output = str(buf).split('\\n')\n for _tmp in output[1:]:\n if 'nvme' in _tmp:\n disk_data[_tmp.split()[0]] = _tmp.split()[3]\n nvme_data['{}'.format(node)] = disk_data\n\n return nvme_data\n\n def get_nvme_readlink(self):\n \"\"\"Get NVMe readlink from servers.\n\n Returns:\n dict: Dictionary of server readlink pci mapping with disk ID\n 'wolf-A': {'0000:da:00.0': 'nvme9n1'}.\n Dictionary of server mapping with disk ID and size\n 'wolf-A': {'nvme2n1': '1600321314816'}.\n \"\"\"\n nvme_lsblk = self.get_nvme_lsblk()\n nvme_readlink = {}\n\n #Create the dictionary for NVMe readlink.\n for server, items in nvme_lsblk.items():\n tmp_dict = {}\n for drive in items:\n cmd = ('readlink /sys/block/{}/device/device'\n .format(drive.split()[0]))\n task = run_task([server], cmd)\n for _rc_code, _node in task.iter_retcodes():\n if _rc_code == 1:\n print(\"Failed to readlink on {}\".format(_node))\n raise ValueError\n #Get the drive size from each daos_io_servers\n for buf, _node in task.iter_buffers():\n output = str(buf).split('\\n')\n tmp_dict[output[0].split('/')[-1]] = drive.split()[0]\n nvme_readlink[server] = tmp_dict\n\n return nvme_lsblk, nvme_readlink\n\n def get_scm_max_capacity(self):\n \"\"\"Check with server.yaml and return maximum SCM size allow to create.\n\n Returns:\n int: Maximum NVMe storage capacity for pool creation.\n\n Note: Read the PCMEM sizes from the server using lsblk command.\n This need to be replaced with dmg command when it's available.\n \"\"\"\n scm_lsblk = self.get_scm_lsblk()\n\n scm_size = {}\n #Create the dictionary for Max SCM size for all the servers.\n for server in scm_lsblk:\n tmp_dict = {}\n for daos_io_server in range(len(self.daos_io_servers)):\n tmp_disk_list = []\n for pcmem in (self.server_managers[0].manager.job.yaml.\n server_params[daos_io_server].scm_list.value):\n pcmem_num = pcmem.split('/')[-1]\n if pcmem_num in scm_lsblk[server].keys():\n tmp_disk_list.append(int(scm_lsblk[server][pcmem_num]))\n else:\n self.fail(\"PCMEM {} can not found on server {}\"\n .format(pcmem, server))\n tmp_dict[daos_io_server] = tmp_disk_list\n scm_size[server] = tmp_dict\n\n return self.get_max_capacity(scm_size)\n\n def get_nvme_max_capacity(self):\n \"\"\"Get Server NVMe storage maximum capacity.\n\n Returns:\n int: Maximum NVMe storage capacity for pool creation.\n\n Note: Read the drive sizes from the server using lsblk command.\n This need to be replaced with dmg command when it's available.\n This is time consuming and not a final solution to get the maximum\n capacity of servers.\n \"\"\"\n drive_info = {}\n nvme_lsblk, nvme_readlink = self.get_nvme_readlink()\n\n #Create the dictionary for NVMe size for all the servers and drives.\n for server in nvme_lsblk:\n tmp_dict = {}\n for daos_io_server in range(len(self.daos_io_servers)):\n tmp_disk_list = []\n for disk in (self.server_managers[0].manager.job.yaml.\n server_params[daos_io_server].bdev_list.value):\n if disk in nvme_readlink[server].keys():\n size = int(nvme_lsblk[server]\n [nvme_readlink[server][disk]])\n tmp_disk_list.append(size)\n else:\n self.fail(\"Disk {} can not found on server {}\"\n .format(disk, server))\n tmp_dict[daos_io_server] = tmp_disk_list\n drive_info[server] = tmp_dict\n\n return self.get_max_capacity(drive_info)\n\n def start_ior_thread(self, results, operation='WriteRead'):\n \"\"\"Start IOR write/read threads and wait until all threads are finished.\n\n Args:\n results (queue): queue for returning thread results\n operation (str): IOR operation for read/write.\n Default it will do whatever mention in ior_flags\n set.\n \"\"\"\n _create_cont = True\n self.ior_cmd.flags.value = self.ior_default_flags\n #For IOR Read only operation, retrieve the stored container UUID\n if 'Read' in operation:\n _create_cont = False\n self.ior_cmd.flags.value = self.ior_read_flags\n\n #For IOR Other operation, calculate the block size based on server %\n #to fill up. Store the container UUID for future reading operation.\n block_size = self.calculate_ior_block_size()\n self.ior_cmd.block_size.update('{}'.format(block_size))\n\n # run IOR Command\n try:\n out = self.run_ior_with_pool(create_cont=_create_cont)\n self.ior_matrix = IorCommand.get_ior_metrics(out)\n results.put(\"PASS\")\n except (CommandFailure, TestFail) as _error:\n results.put(\"FAIL\")\n\n def calculate_ior_block_size(self):\n \"\"\"\n Calculate IOR Block size to fill up the Server\n\n Returns:\n block_size(int): IOR Block size\n \"\"\"\n #Check the replica for IOR object to calculate the correct block size.\n _replica = re.findall(r'_(.+?)G', self.ior_cmd.dfs_oclass.value)\n if not _replica:\n replica_server = 1\n #This is for EC Parity\n elif 'P' in _replica[0]:\n replica_server = re.findall(r'\\d+', _replica[0])[0]\n else:\n replica_server = _replica[0]\n\n print('Replica Server = {}'.format(replica_server))\n if self.scm_fill:\n free_space = self.pool.get_pool_daos_space()[\"s_total\"][0]\n self.ior_cmd.transfer_size.value = self.ior_scm_xfersize\n elif self.nvme_fill:\n free_space = self.pool.get_pool_daos_space()[\"s_total\"][1]\n self.ior_cmd.transfer_size.value = self.ior_nvme_xfersize\n else:\n self.fail('Provide storage type (SCM/NVMe) to be filled')\n\n #Get the block size based on the capacity to be filled. For example\n #If nvme_free_space is 100G and to fill 50% of capacity.\n #Formula : (107374182400 / 100) * 50.This will give 50% of space to be\n #filled. Divide with total number of process, 16 process means each\n #process will write 3.12Gb.last, if there is replica set, For RP_2G1\n #will divide the individual process size by number of replica.\n #3.12G (Single process size)/2 (No of Replica) = 1.56G\n #To fill 50 % of 100GB pool with total 16 process and replica 2, IOR\n #single process size will be 1.56GB.\n _tmp_block_size = (((free_space/100)*self.capacity)/self.processes)\n _tmp_block_size = int(_tmp_block_size / int(replica_server))\n block_size = ((_tmp_block_size/int(self.ior_cmd.transfer_size.value))\n *int(self.ior_cmd.transfer_size.value))\n return block_size\n\n def set_device_faulty(self, server, disk_id):\n \"\"\"\n Set the devices (disk_id) to Faulty and wait for rebuild to complete on\n given server hostname.\n\n args:\n server(string): server hostname where it generate the NVMe fault.\n disk_id(string): NVMe disk ID where it will be changed to faulty.\n \"\"\"\n self.dmg.hostlist = server\n self.dmg.storage_set_faulty(disk_id)\n result = self.dmg.storage_query_device_health(disk_id)\n #Check if device state changed to FAULTY.\n if 'State:FAULTY' not in result.stdout:\n self.fail(\"device State {} on host {} suppose to be FAULTY\"\n .format(disk_id, server))\n # Wait for rebuild to start\n self.pool.wait_for_rebuild(True)\n # Wait for rebuild to complete\n self.pool.wait_for_rebuild(False)\n\n def set_device_faulty_loop(self):\n \"\"\"\n Set the devices to Faulty one by one and wait for rebuild to complete.\n \"\"\"\n #Get the device ids from all servers and try to eject the disks\n device_ids = get_device_ids(self.dmg, self.hostlist_servers)\n\n #no_of_servers and no_of_drives can be set from test yaml.\n #1 Server, 1 Drive = Remove single drive from single server\n for num in range(0, self.no_of_servers):\n server = self.hostlist_servers[num]\n for disk_id in range(0, self.no_of_drives):\n self.set_device_faulty(server, device_ids[server][disk_id])\n\n def create_pool_max_size(self, scm=False, nvme=False):\n \"\"\"\n Method to create the single pool with Maximum NVMe/SCM size available.\n\n arg:\n scm(bool): To create the pool with max SCM size or not.\n nvme(bool): To create the pool with max NVMe size or not.\n\n Note: Method to Fill up the server. It will get the maximum Storage\n space and create the pool.\n Replace with dmg options in future when it's available.\n \"\"\"\n # Create a pool\n self.pool = TestPool(self.context, self.get_dmg_command())\n self.pool.get_params(self)\n\n #If NVMe is True get the max NVMe size from servers\n if nvme:\n avocao_tmp_dir = os.environ['AVOCADO_TESTS_COMMON_TMPDIR']\n capacity_file = os.path.join(avocao_tmp_dir, 'storage_capacity')\n if not os.path.exists(capacity_file):\n #Stop servers.\n self.stop_servers()\n total_nvme_capacity = self.get_nvme_max_capacity()\n with open(capacity_file,\n 'w') as _file: _file.write(\n '{}'.format(total_nvme_capacity))\n #Start the server.\n self.start_servers()\n else:\n total_nvme_capacity = open(capacity_file).readline().rstrip()\n\n print(\"Server NVMe Max Storage capacity = {}\"\n .format(total_nvme_capacity))\n self.pool.nvme_size.update('{}'.format(total_nvme_capacity))\n\n #If SCM is True get the max SCM size from servers\n if scm:\n total_scm_capacity = self.get_scm_max_capacity()\n print(\"Server SCM Max Storage capacity = {}\"\n .format(total_scm_capacity))\n self.pool.scm_size.update('{}'.format(total_scm_capacity))\n\n #Create the Pool\n self.pool.create()\n\n def start_ior_load(self, storage='NVMe', operation=\"Write\", percent=1):\n \"\"\"\n Method to Fill up the server either SCM or NVMe.\n Fill up based on percent amount given using IOR.\n\n arg:\n storage(string): SCM or NVMe, by default it will fill NVMe.\n operation(string): Write/Read operation\n percent(int): % of storage to be filled\n\n Returns:\n None\n \"\"\"\n self.capacity = percent\n # Fill up NVMe by default\n self.nvme_fill = True if 'NVMe' in storage else False\n self.scm_fill = True if 'SCM' in storage else False\n\n if operation not in ['Read', 'Write']:\n self.fail('Please provide the valid IO operation instead {}'\n .format(operation))\n\n # Create the IOR threads\n job = threading.Thread(target=self.start_ior_thread,\n kwargs={\"results\":self.out_queue,\n \"operation\": operation})\n # Launch the IOR thread\n job.start()\n\n #Set NVMe device faulty if it's set\n if self.set_faulty_device:\n time.sleep(60)\n #Set the device faulty\n self.set_device_faulty_loop()\n\n # Wait to finish the thread\n job.join()\n\n # Verify the queue and make sure no FAIL for any IOR run\n while not self.out_queue.empty():\n if self.out_queue.get() == \"FAIL\":\n self.fail(\"FAIL\")\n","sub_path":"src/tests/ftest/util/nvme_utils.py","file_name":"nvme_utils.py","file_ext":"py","file_size_in_byte":18886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"478634679","text":"# Implementation of Path Consistency Learning\n# Author : Laetitia Teodorecu\n#\n# Reference : Nachum et. al. 2017\n\nimport sys\nimport numpy as np\nfrom tqdm import tqdm\nfrom copy import copy\n\nsys.path.append('../..')\n\nimport utils.gibbspolicy as gp\nimport utils.parametricvalue as pv\n\nclass PCL():\n \n def __init__(self, env, T, eta_pi, eta_phi, discount, d, tau, B=1000, alpha=0):\n self.env = env\n self.T = T\n self.eta_pi = eta_pi\n self.eta_phi = eta_phi\n self.discount = discount\n self.d = d\n self.tau = tau\n self.B = B\n self.alpha = alpha\n self.pi_theta = gp.GibbsPolicy(self.env, self.T, .5, gamma=self.discount)\n self.V_phi = pv.RBFValueFunction(10, 10)\n self.buff = []\n \n def done(self, state):\n pos = state[0]\n if pos >= 0.5:\n return True\n else:\n return False\n \n def rollout_traj(self, traj, idx):\n T = len(traj)\n if (T - idx) > self.d:\n return traj[idx:idx+self.d]\n else:\n return traj[idx:]\n \n def R(self, s):\n # reward of a trajectory\n r = 0\n for _, _, rew, _ in s:\n r += rew\n return r\n \n def C(self, s):\n first_state = s[0][0]\n last_state = s[-1][0]\n c = - self.V_phi.value(first_state) + self.discount**(len(s)-1) \\\n *self.V_phi.value(last_state) + self.R(s) - self.tau*self.G(s)\n return c\n \n def G(self, s):\n g = 0\n for i, [state, action, _, _] in enumerate(s):\n g += self.discount**i * self.pi_theta.logproba(state, action)\n return g\n \n def grad_G(self, s):\n grad_g = 0\n for i, [state, action, _, _] in enumerate(s):\n grad_g += self.discount**i * self.pi_theta.gradlog(state, action)\n return grad_g\n \n def grad_V(self, state):\n return self.V_phi.grad(state)\n \n def gradients(self, traj):\n delta_theta = 0\n delta_phi = 0\n for idx in range(len(traj)):\n s = self.rollout_traj(traj, idx)\n C = self.C(s)\n first_state = s[0][0]\n last_state = s[-1][0]\n delta_theta += C * self.grad_G(s) # define pi_theta\n delta_phi += C * (self.grad_V(first_state)\\\n - self.discount**self.d * self.grad_V(last_state))\n return delta_theta, delta_phi\n \n def episode(self, render=False):\n traj = []\n state = self.env.reset()\n for t in range(self.T):\n if not self.done(state):\n if render:\n self.env.render()\n action = self.pi_theta.sample(state)\n next_state, reward, _, _ = self.env.step(action)\n traj.append([state, action, reward, next_state])\n state = next_state\n else:\n break\n return traj\n \n def update(self, theta, phi):\n self.pi_theta.set_theta(theta)\n self.V_phi.set_phi(phi)\n \n def reset(self):\n self.pi_theta.set_theta(self.pi_theta.zero())\n self.V_phi.set_phi(self.V_phi.zero())\n \n def learn_one(self, N, theta=None, phi=None):\n avg_length = 0\n if theta is None:\n theta = self.pi_theta.zero()\n if phi is None:\n phi = self.V_phi.zero()\n for n in tqdm(range(N)):\n traj = self.episode()\n delta_theta, delta_phi = self.gradients(traj)\n avg_length += 1/N * len(traj)\n theta += self.eta_pi*delta_theta\n phi += self.eta_phi*delta_phi\n # TODO : replay buffer\n r = self.R(traj)\n # add in buffer\n if self.buff:\n if r >= self.buff[0]['reward']:\n self.buff.insert(0, {'traj': traj, 'reward': r})\n else:\n self.buff.append({'traj': traj, 'reward': r})\n else: # empty buffer\n self.buff.append({'traj': traj, 'reward': r})\n # is buffer full ?\n if len(self.buff) > self.B:\n self.buff.pop(-1) # remove last element\n # replay from buffer\n traj = np.random.choice(self.buff)['traj']\n delta_theta, delta_phi = self.gradients(traj)\n theta += self.eta_pi*delta_theta\n phi += self.eta_phi*delta_phi\n return copy(theta), copy(phi), avg_length\n \n def learn(self, I, N):\n theta = self.pi_theta.get_theta()\n phi = self.V_phi.get_phi()\n trace = [[theta, phi]]\n lengths = []\n for i in tqdm(range(I)):\n t, p, length = self.learn_one(N, theta, phi)\n trace.append([t, p])\n lengths.append(length)\n self.update(t, p)\n return trace, lengths\n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"RL/pcl/PCL.py","file_name":"PCL.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205055542","text":"#!/usr/bin/python\n\nimport operator\nimport os\nimport smtplib\nimport subprocess\nimport sys\n\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nfrom email.MIMEBase import MIMEBase\nfrom email import encoders\nfrom subprocess import Popen,PIPE,STDOUT\n\ndef runCommand(str):\n process = Popen(args=str, stdout=PIPE, shell=True)\n return process.communicate()[0]\n\ndef runXfsFragCheck():\n runCommand(\"./runFlightCheckStaging > runFlightCheckStaging.txt 2>&1\")\n \ndef getSMTPPassword():\n credentials = {}\n with open('../../.noreplypw','r') as f:\n for line in f:\n user, pw = line.strip().split(':')\n\n return pw\n\n\ndef emailReport(RECIPIENTS):\n fromaddr = 'noreply@r1soft.com'\n toaddr = RECIPIENTS\n\n msg = MIMEMultipart()\n\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = 'Nightly staging flightCheck'\n\n body = 'Nightly staging flightCheck results (see attached).'\n\n msg.attach(MIMEText(body, 'plain'))\n\n filename = 'runFlightCheckStaging.txt'\n\n attachment = open(filename, 'r')\n\n part = MIMEBase('application', 'octet-stream')\n part.set_payload((attachment).read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)\n msg.attach(part)\n\n pw = getSMTPPassword()\n\n server = smtplib.SMTP('smtp.office365.com', 587)\n server.starttls()\n server.login(fromaddr, pw) \n text = msg.as_string()\n server.sendmail(fromaddr, toaddr, text)\n server.quit()\n \n attachment.close()\n\n\ndef main():\n runXfsFragCheck()\n RECIPIENTS = 'scott.gillespie@r1soft.com,alex.vongluck@r1soft.com,stan.love@r1soft.com,tariq.siddiqui@r1soft.com'\n #RECIPIENTS = 'scott.gillespie@r1soft.com'\n emailReport(RECIPIENTS)\n\n \nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n sys.exit()\n\n\n","sub_path":"FlightCheck/run_flightcheck_staging.py","file_name":"run_flightcheck_staging.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"569308066","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution.\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see ...\n#\n##############################################################################\n\nfrom datetime import datetime, timedelta\nfrom openerp.osv import fields, osv\nfrom openerp import SUPERUSER_ID\nfrom datetime import datetime, date, time, timedelta\nimport calendar\nimport operator\n\nclass curso_type(osv.osv):\n# \"\"\" curso Type DEPRECATED!!! \"\"\"\n _name = 'curso.type'\n _description = __doc__\n _columns = {\n }\n\ncurso_type()\n\nclass curso_invoice(osv.osv_memory):\n \"\"\" Wizard para imprimir las facturas \"\"\"\n _name = 'curso.invoice'\n _description = __doc__\n\n#-----------------------------------------------------------------------------------------------------------------------\n def create_invoice(self, cr, uid, ids, invoice_data, context):\n\n print('creando la factura -------->>>>>>>>>>>>>>>>>> ')\n print('fecha',invoice_data.get('date_invoice'))\n print('codigo',invoice_data.get('instance_code'))\n print('alumna',invoice_data.get('partner_id').name)\n print('cuota',invoice_data.get('share'))\n print('curso',invoice_data.get('curso_id').name)\n print('company',invoice_data.get('company_id').name)\n print('precio', invoice_data.get('curso_id').list_price)\n print('producto',invoice_data.get('curso_id').product.name)\n print('codigo',invoice_data.get('curso_id').product.default_code)\n print('a facturar','[{}] {}'.format(invoice_data.get('curso_id').product.default_code,\n invoice_data.get('curso_id').product.name.encode('utf-8')))\n\n instance_code = '{}{:0>2d}'.format(invoice_data.get('curso_id').product.default_code,\n invoice_data.get('curso_id').instance)\n product_id = invoice_data.get('curso_id').product\n date_invoice = datetime.strptime(invoice_data.get('date_invoice'), '%Y-%m-%d')\n date_due = (date_invoice + timedelta(days=10))\n\n print('>>>>>>>>>>>>>>>>>>', instance_code)\n\n\n invoice_line = {\n 'name': '[{}] {}'.format(product_id.default_code,\n product_id.name.encode('utf-8')),\n 'sequence': 5,\n 'invoice_id': False,\n 'account_id': 87,\n 'account_analytic_id': 4,\n 'price_unit': product_id.list_price,\n 'quantity': 1.0,\n }\n\n invoice_line_id = self.pool.get('account.invoice.line').create(cr, uid, invoice_line, context=context)\n\n new_invoice = {\n 'date_due': date_due.strftime('%Y-%m-%d'),\n 'date_invoice': date_invoice.strftime('%Y-%m-%d'),\n 'name': 'F {} C{:.0f}'.format(instance_code,invoice_data.get('share')),\n 'type': 'out_invoice',\n 'reference': '{} C{:.0f}'.format(invoice_data.get('instance_code'),invoice_data.get('share')),\n 'account_id': 11,\n 'partner_id': invoice_data.get('partner_id').id,\n 'journal_id':10,\n 'invoice_line': [(6, 0, [invoice_line_id])],\n 'currency_id': 20,#commission.invoice.currency_id.id,\n 'comment': 'generado automaticamente',\n 'fiscal_position': invoice_data.get('partner_id').property_account_position.id,\n 'company_id': invoice_data.get('company_id').id,\n 'user_id': uid\n }\n\n invoice_id = self.pool.get('account.invoice').create(cr, uid, new_invoice, context=context)\n\n# self.write(cr,\n# uid,\n# [commission.id],\n# {'supplier_invoice': invoice_id},\n# context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_invoice(self, cr, uid, ids, context=None):\n \"\"\" Generar facturas en borrador de todos los alumnos que están cursando.\n \"\"\"\n\n # revisamos cada inscripción en estado confirmada\n for rec in self.browse(cr, uid, ids, context=context):\n idate = rec.invoice_date\n\n register_pool = self.pool.get('curso.registration')\n records = register_pool.search(cr, uid, [('state', '=', 'confirm')], order='id')\n for item in register_pool.browse(cr, uid, records, context):\n if (item):\n #chequeamos ademas que el importe no sea cero\n if (item.curso_id.list_price != 0):\n invoice_data ={\n 'date_invoice': idate,\n 'instance_code': '{}{:0>2d}'.format(item.curso_id.product.default_code, item.curso_id.instance),\n 'partner_id': item.partner_id,\n 'share': 2,\n 'curso_id': item.curso_id,\n 'company_id': item.company_id,\n }\n\n self.create_invoice(cr, uid, ids, invoice_data, context=None)\n\n return []\n\n _columns = {\n 'invoice_date': fields.date('Fecha de las facturas', required=True),\n }\ncurso_invoice()\n\n#-----------------------------------------------------------------------------------------------------------------------\nclass curso_curso(osv.osv):\n \"\"\" Representa una instancia de un curso \"\"\"\n _name = 'curso.curso'\n _description = __doc__\n _order = 'date_begin'\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n\n\n class weekdays():\n _weekload = []\n\n#-----------------------------------------------------------------------------------------------------------------------\n def __init__(self, wl, date):\n self._weekload = wl\n self._start_day = date\n\n #Obtener el dia de la semana que empieza el curso\n self._start_weekday = self._start_day.weekday()\n\n #chequear con cada horario para ver si coincide con alguno\n self._current_ix = None\n for ix, rec in enumerate(self._weekload):\n if (int(rec.get('weekday')) == self._start_weekday):\n self._current_ix = ix\n break\n\n if (self._current_ix == None):\n raise osv.except_osv(('Error!'),(\"La fecha de inicio no corresponde con Dia 1 ni con Dia 2\"))\n\n#-----------------------------------------------------------------------------------------------------------------------\n def current_weekload(self):\n return self._weekload[self._current_ix]\n\n#-----------------------------------------------------------------------------------------------------------------------\n def next_delta(self):\n last_weekday = int(self._weekload[self._current_ix].get('weekday'))\n\n self._current_ix = self._current_ix+1\n if (self._current_ix >= len(self._weekload)):\n self._current_ix = 0\n\n current_weekday = int(self._weekload[self._current_ix].get('weekday'))\n delta = current_weekday - last_weekday\n\n if (delta == 0) and (self._current_ix == 0):\n delta = 7\n if (delta < 0):\n delta = delta +7\n\n return delta\n\n#-----------------------------------------------------------------------------------------------------------------------\n def name_get(self, cr, uid, ids, context=None):\n if not ids:\n return []\n\n if isinstance(ids, (long, int)):\n ids = [ids]\n\n res = []\n for record in self.browse(cr, uid, ids, context=context):\n curs = record.product.name\n display_name = record.name\n res.append((record['id'], display_name))\n return res\n\n#-----------------------------------------------------------------------------------------------------------------------\n def copy(self, cr, uid, id, default=None, context=None):\n \"\"\" Reset the state and the registrations while copying an curso\n \"\"\"\n if not default:\n default = {}\n default.update({\n 'state': 'draft',\n 'registration_ids': False,\n })\n return super(curso_curso, self).copy(cr, uid, id, default=default, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_draft(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state': 'draft'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_cancel(self, cr, uid, ids, context=None):\n registration = self.pool.get('curso.registration')\n reg_ids = registration.search(cr, uid, [('curso_id','in',ids)], context=context)\n for curso_reg in registration.browse(cr,uid,reg_ids,context=context):\n if curso_reg.state == 'done':\n raise osv.except_osv(('Error!'),(\"Este curso no se puede cancelar porque tiene al menos una inscripción informada como Cumplida.\") )\n registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)\n return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n#TODO cuando termina el curso debe terminar cada una de las inscripciones en estado confirm\n def button_done(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state': 'done'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def check_registration_limits(self, cr, uid, ids, context=None):\n for self.curso in self.browse(cr, uid, ids, context=context):\n total_confirmed = self.curso.register_current\n if total_confirmed < self.curso.register_min or total_confirmed > self.curso.register_max and self.curso.register_max!=0:\n raise osv.except_osv(('Error!'),(\"El total de inscripciones confirmadas para el curso '%s' no cumple con los requerimientos esperados de minimo/maximo. Reconsidere estos limites antes de continuar.\") % (self.curso.name))\n\n#-----------------------------------------------------------------------------------------------------------------------\n def check_registration_limits_before(self, cr, uid, ids, no_of_registration, context=None):\n for curso in self.browse(cr, uid, ids, context=context):\n available_seats = curso.register_avail\n if available_seats and no_of_registration > available_seats:\n raise osv.except_osv(('Cuidado!'),(\"Solo hay %d vacantes disponnibles!\") % (available_seats))\n elif available_seats == 0:\n raise osv.except_osv(('Cuidado!'),(\"No Hay mas vacantes en este curso!\"))\n\n#-----------------------------------------------------------------------------------------------------------------------\n def confirm_curso(self, cr, uid, ids, context=None):\n register_pool = self.pool.get('curso.registration')\n if self.curso.email_confirmation_id:\n #send reminder that will confirm the curso for all the people that were already confirmed\n reg_ids = register_pool.search(cr, uid, [\n ('curso_id', '=', self.curso.id),\n ('state', 'not in', ['draft', 'cancel'])], context=context)\n register_pool.mail_user_confirm(cr, uid, reg_ids)\n return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_confirm(self, cr, uid, ids, context=None):\n \"\"\" Confirmar curso and send confirmation email to all register peoples\n \"\"\"\n # Verificar si tiene fecha de inicio.\n for curso in self.browse(cr, uid, ids, context=context):\n if not (curso.date_begin):\n raise osv.except_osv(('Error!'), (\"No se puede confirmar el curso porque no tiene fecha de inicio.\"))\n\n if not ( (curso.schedule_1) and (curso.weekday_1) ):\n raise osv.except_osv(('Error!'), (\"No se puede confirmar el curso porque no horario y dia asignados.\"))\n\n if isinstance(ids, (int, long)):\n ids = [ids]\n self.check_registration_limits(cr, uid, ids, context=context)\n return self.confirm_curso(cr, uid, ids, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def _get_register(self, cr, uid, ids, fields, args, context=None):\n \"\"\" Get Confirm or uncofirm register value.\n @param ids: List of curso registration type's id\n @param fields: List of function fields(register_current and register_prospect).\n @param context: A standard dictionary for contextual values\n @return: Dictionary of function fields value.\n \"\"\"\n res = {}\n for curso in self.browse(cr, uid, ids, context=context):\n res[curso.id] = {}\n reg_open = reg_done = reg_draft =0\n for registration in curso.registration_ids:\n if registration.state == 'confirm':\n reg_open += registration.nb_register\n elif registration.state == 'done':\n reg_done += registration.nb_register\n elif registration.state == 'draft':\n reg_draft += registration.nb_register\n for field in fields:\n number = 0\n if field == 'register_current':\n number = reg_open\n elif field == 'register_attended':\n number = reg_done\n elif field == 'register_prospect':\n number = reg_draft\n elif field == 'register_avail':\n #the number of ticket is unlimited if the curso.register_max field is not set.\n #In that cas we arbitrary set it to 9999, it is used in the kanban view to special case the display of the 'subscribe' button\n number = curso.register_max - reg_open if curso.register_max != 0 else 9999\n res[curso.id][field] = number\n return res\n\n#-----------------------------------------------------------------------------------------------------------------------\n def _subscribe_fnc(self, cr, uid, ids, fields, args, context=None):\n \"\"\"This functional fields compute if the current user (uid) is already subscribed or not to the curso passed in parameter (ids)\n \"\"\"\n register_pool = self.pool.get('curso.registration')\n res = {}\n for curso in self.browse(cr, uid, ids, context=context):\n res[curso.id] = False\n curr_reg_id = register_pool.search(cr, uid, [('user_id', '=', uid), ('curso_id', '=' ,curso.id)])\n if curr_reg_id:\n for reg in register_pool.browse(cr, uid, curr_reg_id, context=context):\n if reg.state in ('confirm','done'):\n res[curso.id]= True\n continue\n return res\n\n#-----------------------------------------------------------------------------------------------------------------------\n def get_holiday_dates(self, cr, uid, ids, context=None):\n hd = []\n holidays = self.pool.get('curso.holiday')\n reg_ids = holidays.search(cr, uid, [], context=context)\n for holiday in holidays.browse(cr,uid,reg_ids,context=context):\n hd.append(datetime.strptime(holiday.date,'%Y-%m-%d'))\n return hd\n\n#-----------------------------------------------------------------------------------------------------------------------\n def _get_day(self, cursor, user_id, context=None):\n return (\n ('0', 'Lunes'),\n ('1', 'Martes'),\n ('2', 'Miercoles'),\n ('3', 'Jueves'),\n ('4', 'Viernes'),\n ('5', 'Sabado'),\n ('6', 'Domingo'))\n\n#-----------------------------------------------------------------------------------------------------------------------\n def compute_lecture_data(self, cr, uid, ids, date_begin,weekload,tot_lectures, context=None):\n\n date = datetime.strptime(date_begin,'%Y-%m-%d')\n weekdays = self.weekdays(weekload, date)\n lecture_data = []\n holliday_dates = self.get_holiday_dates(cr, uid, ids, context=None)\n while (len(lecture_data) < tot_lectures):\n if (date in holliday_dates):\n date = date + timedelta(days=weekdays.next_delta())\n else:\n aa = weekdays.current_weekload()\n lecture_data.append({\n 'date':date,\n 'schedule':aa.get('schedule'),\n 'weekday':aa.get('weekday')\n })\n date = date + timedelta(days=weekdays.next_delta())\n return lecture_data\n\n#-----------------------------------------------------------------------------------------------------------------------\n def create_lectures(self, cr, uid, ids, lecture_data, default_code, context=None):\n lectures_pool = self.pool.get('curso.lecture')\n for reg in self.browse(cr, uid, ids, context=context):\n curso_id = reg.id\n for data in lecture_data:\n lectures_pool.create(cr, uid, {\n 'date': data.get('date'),\n 'schedule_id': data.get('schedule'),\n 'curso_id': curso_id\n } )\n\n#-----------------------------------------------------------------------------------------------------------------------\n def generate_lectures(self, cr, uid, ids, context=None):\n \"\"\" Generar las clases que correspondan a este curso\n \"\"\"\n for reg in self.browse(cr, uid, ids, context=context):\n date_begin = reg.date_begin\n tot_hs_lecture = reg.product.tot_hs_lecture\n hs_lecture = reg.product.hs_lecture\n schedule_1 = reg.schedule_1.id\n weekday_1 = reg.weekday_1\n schedule_2 = reg.schedule_2.id\n weekday_2 = reg.weekday_2\n default_code = reg.default_code\n\n if (operator.mod(tot_hs_lecture, hs_lecture) !=0):\n raise osv.except_osv(('Error!'), (\"la cantidad de horas catedra no es divisible por las horas de clase!.\"))\n\n tot_lectures = tot_hs_lecture // hs_lecture\n weekload = []\n\n if (schedule_1 != False ) and (weekday_1 != False):\n weekload = [\n {'schedule':schedule_1,\n 'weekday':weekday_1},\n ]\n\n if (schedule_2 != False ) and (weekday_2 != False):\n weekload.append(\n {'schedule':schedule_2,\n 'weekday':weekday_2}\n )\n\n if (weekload==[]):\n raise osv.except_osv(('Error!'), (\"No se definieron horarios!.\"))\n\n lecture_data = self.compute_lecture_data(cr, uid, ids, date_begin, weekload, tot_lectures, context=None)\n self.create_lectures(cr, uid, ids,lecture_data,default_code, context=None)\n return 0\n\n _columns = {\n 'name': fields.char('Nombre del curso', size=64, required=False, readonly=True, states={'draft': [('readonly', False)]}),\n 'instance': fields.integer('Instancia'),\n 'user_id': fields.many2one('res.users', 'Responsable', readonly=True, states={'done': [('readonly', True)]}),\n 'product':fields.many2one('product.product', 'Producto', readonly=True, required=True, domain=\"[('tot_hs_lecture','!=','0')]\", states={'draft': [('readonly', False)]}),\n 'register_max': fields.integer('Vacantes max', readonly=True, states={'draft': [('readonly', False)]},\n help=\"La cantidd máxima de vacantes del curso. Si la cantidad de inscripciones es mayor, no se puede arrancar el curso. (poner 0 para ignorar la regla)\"),\n 'register_min': fields.integer('Vacantes min', readonly=True,\n help=\"La cantidad mínima de inscripciones en el curso. Si no hay suficientes inscripcones no se puede arrancar el curso. (poner 0 para ignorar la regla)\", states={'draft': [('readonly', False)]}),\n\n 'register_current': fields.integer(compute='_get_register', string='Vacantes conf',\n help=\"La cantidad de alumnas que confirmaron pagando (al menos una seña)\", multi='register_numbers'),\n 'register_avail': fields.integer(compute='_get_register', string='Vacantes', multi='register_numbers'),\n 'register_prospect': fields.integer(compute='_get_register', string='Interesadas',\n help=\"La cantidad de alumnas interesadas que todavía no concretaron\", multi='register_numbers'),\n 'register_attended': fields.integer(compute='_get_register', string='Egresadas', multi='register_numbers',\n help=\"Cantidad de alumnas que termino el curso con exito.\"),\n 'registration_ids': fields.one2many('curso.registration', 'curso_id', 'Inscripciones', readonly=False, states={'done': [('readonly', True)]}),\n 'lecture_ids': fields.one2many('curso.lecture', 'curso_id', 'Clases', readonly=False ),\n 'date_begin': fields.date('Fecha de inicio',\n help=\"La fecha en la que inicia el curso, se puede dejar en blanco si no está definida todavia pero se debe ingresar para confirmar el curso\", required=False, readonly=True, states={'draft': [('readonly', False)]}),\n 'schedule_1': fields.many2one('curso.schedule', 'Horario 1', readonly=True, states={'draft': [('readonly', False)]}),\n 'schedule_2': fields.many2one('curso.schedule', 'Horario 2', readonly=True, states={'draft': [('readonly', False)]}),\n 'weekday_1': fields.selection(_get_day,'Dia 1', readonly=True, states={'draft': [('readonly', False)]}),\n 'weekday_2': fields.selection(_get_day,'Dia 2', readonly=True, states={'draft': [('readonly', False)]}),\n 'state': fields.selection([\n ('draft', 'Borrador'),\n ('cancel', 'Cancelado'),\n ('confirm', 'Cursando'),\n ('done', 'Terminado')],\n 'Status', readonly=True, required=True,\n track_visibility='onchange',\n help='Cuando se crea el curso el estado es \\'Borrador\\'. Si se confirma el curso el estado es \\'Cursando\\'. Si el curso termina el estado es \\'Terminado\\'. Si el curso es cancelado el estado pasa a \\'Cancelado\\'.'),\n 'email_registration_id' : fields.many2one('email.template','Confirmación de inscripción',\n help='Si definís una plantilla, la misma se enviará cada vez que se confirme una inscripción a este curso.'),\n 'email_confirmation_id' : fields.many2one('email.template','Confirmación curso',\n help=\"Si definis una plantilla de mail, cada participante recibirá este mail anunciando la confirmación del curso.\"),\n 'reply_to': fields.char('Mail de respuesta', size=64, readonly=False, states={'done': [('readonly', True)]},\n help=\"La dirección de mail del que organiza los cursos, cuando el alumno responde el mail que se le envia en automático responderá a esta dirección.\"),\n 'main_speaker_id': fields.many2one('res.partner','Profesora', readonly=False, states={'done': [('readonly', True)]},\n help=\"La profesora que va a dar el curso.\"),\n 'country_id': fields.related('address_id', 'country_id',\n type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}),\n 'note': fields.text('Description', readonly=False, states={'done': [('readonly', True)]}),\n 'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),\n 'is_subscribed' : fields.boolean(compute='_subscribe_fnc', string='Subscribed'),\n\n # Related fields\n 'tot_hs_lecture': fields.related('product', 'tot_hs_lecture', type='float', string='Hs catedra', readonly=True),\n 'list_price': fields.related('product', 'list_price', type='float', string='Precio', readonly=True),\n 'hs_lecture': fields.related('product', 'hs_lecture', type='float', string='Hs clase', readonly=True),\n 'default_code': fields.related('product', 'default_code', type='char', string='Codigo', readonly=True),\n\n # Deprecated fields\n 'type': fields.many2one('curso.type', 'Type of curso', readonly=False, states={'done': [('readonly', True)]}),\n }\n _defaults = {\n 'state': 'draft',\n 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'curso.curso', context=c),\n 'user_id': lambda obj, cr, uid, context: uid,\n }\n\n#-----------------------------------------------------------------------------------------------------------------------\n def subscribe_to_curso(self, cr, uid, ids, context=None):\n register_pool = self.pool.get('curso.registration')\n user_pool = self.pool.get('res.users')\n num_of_seats = int(context.get('ticket', 1))\n self.check_registration_limits_before(cr, uid, ids, num_of_seats, context=context)\n user = user_pool.browse(cr, uid, uid, context=context)\n curr_reg_ids = register_pool.search(cr, uid, [('user_id', '=', user.id), ('curso_id', '=' , ids[0])])\n #the subscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to subscribe\n if not curr_reg_ids:\n curr_reg_ids = [register_pool.create(cr, SUPERUSER_ID, {'curso_id': ids[0] ,'email': user.email, 'name':user.name, 'user_id': user.id, 'nb_register': num_of_seats})]\n else:\n register_pool.write(cr, uid, curr_reg_ids, {'nb_register': num_of_seats}, context=context)\n return register_pool.confirm_registration(cr, SUPERUSER_ID, curr_reg_ids, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def unsubscribe_to_curso(self, cr, uid, ids, context=None):\n register_pool = self.pool.get('curso.registration')\n #the unsubscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to unsubscribe\n curr_reg_ids = register_pool.search(cr, SUPERUSER_ID, [('user_id', '=', uid), ('curso_id', '=', ids[0])])\n return register_pool.button_reg_cancel(cr, SUPERUSER_ID, curr_reg_ids, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def onchange_curso_product(self, cr, uid, ids, product, context=None):\n values = {}\n if product:\n type_info = self.pool.get('product.product').browse(cr,uid,product,context)\n\n instance = 0\n r_pool = self.pool.get('curso.curso')\n records = r_pool.search(cr, uid, [('default_code', '=', type_info.default_code)], context=context)\n for item in r_pool.browse(cr, uid, records, context):\n if (item):\n if (instance < item.instance):\n instance = item.instance\n instance = instance +1\n\n values.update( {\n 'name': \"[{}{:0>2d}] - {}\".format(type_info.default_code,instance,type_info.name.encode('utf-8')),\n 'instance': instance,\n 'default_code': type_info.default_code,\n })\n\n return { 'value' : values }\n\n#-----------------------------------------------------------------------------------------------------------------------\n def on_change_address_id(self, cr, uid, ids, address_id, context=None):\n values = {}\n if not address_id:\n return values\n address = self.pool.get('res.partner').browse(cr, uid, address_id, context=context)\n values.update({\n 'street' : address.street,\n 'street2' : address.street2,\n 'city' : address.city,\n 'country_id' : address.country_id and address.country_id.id or False,\n 'state_id' : address.state_id and address.state_id.id or False,\n 'zip' : address.zip,\n })\n return {'value' : values}\n\n#-----------------------------------------------------------------------------------------------------------------------\nclass curso_registration(osv.osv):\n \"\"\" Curso Registration\"\"\"\n _name= 'curso.registration'\n _description = __doc__\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n _columns = {\n 'id': fields.integer('ID'),\n 'curso_id': fields.many2one('curso.curso', 'Curso', required=True, readonly=True, states={'draft': [('readonly', False)]}),\n 'partner_id': fields.many2one('res.partner', 'Alumna', required=True, states={'done': [('readonly', True)]}),\n 'create_date': fields.date('Creación' , readonly=True),\n 'date_closed': fields.date('Fecha de cierre', readonly=True),\n 'date_open': fields.date('Fecha de inscripción', readonly=True),\n 'reply_to': fields.related('curso_id','reply_to',string='Reply-to Email', type='char', size=128, readonly=True,),\n 'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('model','=',_name)]),\n 'curso_begin_date': fields.related('curso_id', 'date_begin', type='datetime', string=\"curso Start Date\", readonly=True),\n 'user_id': fields.many2one('res.users', 'User', states={'done': [('readonly', True)]}),\n 'company_id': fields.related('curso_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),\n 'state': fields.selection([('draft', 'Interesada'),\n ('cancel', 'Cancelado'),\n ('confirm', 'Cursando'),\n ('done', 'Cumplido')], 'Estado',\n track_visibility='onchange',\n size=16, readonly=True),\n 'email': fields.char('Email', size=64),\n 'phone': fields.char('Telefono', size=64),\n 'name': fields.char('Nombre', size=128, select=True),\n 'share': fields.integer('Nro de cuota', help=\"Es el numero de cuota que va a pagar en la proxima factura\"),\n\n # Deprecated fields\n 'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),\n\n }\n _defaults = {\n 'nb_register': 1,\n 'state': 'draft',\n }\n _order = 'name, create_date desc'\n\n#-----------------------------------------------------------------------------------------------------------------------\n def do_draft(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state': 'draft'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def confirm_registration(self, cr, uid, ids, context=None):\n for reg in self.browse(cr, uid, ids, context=context or {}):\n self.pool.get('curso.curso').message_post(cr, uid, [reg.curso_id.id], body=('New registration confirmed: %s.') % (reg.name or '', ),subtype=\"curso.mt_curso_registration\", context=context)\n return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)\n\n#-----------------------------------------------------------------------------------------------------------------------\n def registration_open(self, cr, uid, ids, context=None):\n \"\"\" Open Registration\n \"\"\"\n curso_obj = self.pool.get('curso.curso')\n for register in self.browse(cr, uid, ids, context=context):\n curso_id = register.curso_id.id\n no_of_registration = register.nb_register\n curso_obj.check_registration_limits_before(cr, uid, [curso_id], no_of_registration, context=context)\n res = self.confirm_registration(cr, uid, ids, context=context)\n self.mail_user(cr, uid, ids, context=context)\n return res\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_reg_close(self, cr, uid, ids, context=None):\n \"\"\" Close Registration\n \"\"\"\n if context is None:\n context = {}\n today = fields.datetime.now()\n for registration in self.browse(cr, uid, ids, context=context):\n if today >= registration.curso_id.date_begin:\n values = {'state': 'done', 'date_closed': today}\n self.write(cr, uid, ids, values)\n else:\n raise osv.except_osv(('Error!'), (\"Hay que esperar al dia de inicio del curso para decir que lo cumplio.\"))\n return True\n\n#-----------------------------------------------------------------------------------------------------------------------\n def button_reg_cancel(self, cr, uid, ids, context=None, *args):\n return self.write(cr, uid, ids, {'state': 'cancel'})\n\n#-----------------------------------------------------------------------------------------------------------------------\n def mail_user(self, cr, uid, ids, context=None):\n \"\"\"\n Send email to user with email_template when registration is done\n \"\"\"\n for registration in self.browse(cr, uid, ids, context=context):\n if registration.curso_id.state == 'confirm' and registration.curso_id.email_confirmation_id.id:\n self.mail_user_confirm(cr, uid, ids, context=context)\n else:\n template_id = registration.curso_id.email_registration_id.id\n if template_id:\n mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)\n return True\n\n#-----------------------------------------------------------------------------------------------------------------------\n def mail_user_confirm(self, cr, uid, ids, context=None):\n \"\"\"\n Send email to user when the curso is confirmed\n \"\"\"\n for registration in self.browse(cr, uid, ids, context=context):\n template_id = registration.curso_id.email_confirmation_id.id\n if template_id:\n mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)\n return True\n\n#-----------------------------------------------------------------------------------------------------------------------\n def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):\n if not contact:\n return {}\n addr_obj = self.pool.get('res.partner')\n contact_id = addr_obj.browse(cr, uid, contact, context=context)\n return {'value': {\n 'email':contact_id.email,\n 'name':contact_id.name,\n 'phone':contact_id.phone,\n }}\n\n#-----------------------------------------------------------------------------------------------------------------------\n def onchange_partner_id(self, cr, uid, ids, part, context=None):\n res_obj = self.pool.get('res.partner')\n data = {}\n if not part:\n return {'value': data}\n addr = res_obj.address_get(cr, uid, [part]).get('default', False)\n if addr:\n d = self.onchange_contact_id(cr, uid, ids, addr, part, context)\n data.update(d['value'])\n return {'value': data}\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"curso.py","file_name":"curso.py","file_ext":"py","file_size_in_byte":36670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96627437","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 1 12:54:34 2018\n\n@author: Alicia\n\"\"\"\n#Question 1\nimport pandas\nimport matplotlib.pyplot as plt\n\ndf=pandas.read_csv(\"UWvMSU_1-22-13.txt\",sep=\"\\t\",header=0)\nprint(df)\ndf[\"UWscore\"]=df.loc[df[\"team\"]==\"UW\",\"score\"].cumsum()\ndf[\"MSUscore\"]=df.loc[df[\"team\"]==\"MSU\",\"score\"].cumsum()\ndf2=df.fillna(method=\"ffill\")\ndf2=df.fillna(0)\nprint(df2)\nsorted_data=df2.sort_values('time')\nprint(sorted_data)\ndf2.loc[df2['time'].between(0,10.99),'Quarter']='First'\ndf2.loc[df2['time'].between(11,20.99),'Quarter']='Second'\ndf2.loc[df2['time'].between(21,30.99),'Quarter']='Third'\ndf2.loc[df2['time'].between(31,40.99),'Quarter']='Fourth'\nprint(df2)\nplt.plot(df2[\"Quarter\"],df2[\"UWscore\"],\"r-\",df2[\"Quarter\"],df2[\"MSUscore\"],\"g-\")\nplt.grid(True)\nplt.axes([\"First\",\"Fourth\", 0, 50])\nplt.xticks(['First','Second','Third','Fourth'])\nplt.axes().spines[\"left\"].set_position((\"data\",40))\n#Note that when I convert time to quarters on the x-axis it returns lines with vertical additions at each x-axis tick (I am not sure how to get rid of this)\n#If I were to comment out the lines that create the 'Quarter' column and change plt.plot(df2[\"Quarter\"],df2[\"UWscore\"],\"r-\",df2[\"Quarter\"],df2[\"MSUscore\"],\"g-\")\n#to plt.plot(df2[\"time\"],df2[\"UWscore\"],\"r-\",df2[\"time\"],df2[\"MSUscore\"],\"g-\") I would get a continuous graph but the x-axis would only be labeled by time and not by quarters\n\n#Question 2 - Guess My Number\nimport random\n\nn = random.randint(1, 100)\nprint('I am thinking of a number between 1 and 100.')\nguess = input(\"Take a guess \")\nguess = int(guess)\nwhile n != \"guess\":\n print(guess)\n if guess < n:\n print('Your guess is too low.')\n guess = input(\"Take a guess \")\n guess = int(guess)\n elif guess > n:\n print('Your guess is too high.')\n guess = input(\"Take a guess \")\n guess = int(guess)\n else:\n print(\"You guessed right!\")\n break\n print\n\n\n\n","sub_path":"TutorialEx08.py","file_name":"TutorialEx08.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627970470","text":"\"\"\"\nThis program plots the acceleration data from a YEI Technologies 3-Space Sensor\n(1) in 3D, (2) x acceleration vs time, (3) y acceleration vs time, and\n(4) z accerlation vs time. Acceleration is in units of g's and time is in units\nof seconds. The program requests data from the sensor at a frequency of 1 Hz.\n\nThe plots scroll with the time data maintaining a window of 60 seconds.\nThe plots also show a grid and axes labels for ease of reference.\n\n\nAuthor: Ali Kakakhel (alikakakhel@yahoo.com)\nBased on Code by: Eli Bendersky (eliben@gmail.com)\nLicense: GPLv3\n\"\"\"\n\n\"\"\"\nTo Do:\n--------------------------------------------------------------------------------\n 1. Complete single 2D (x,y) plot conversion to four plot design (3D, x vs t, y vs t, z vs t).\n 2. Set grid visibility to on and remove ability to change.\n 3. Set labels visibility to on and remove ability to change.\n 4. Change menubar functionality to toolbar functionality.\n 5. Add automatic comport detection or else add in-app comport selection.\n 6. Add in-app time window selection.\n 7. Add in-app intra-data-gathering period selection.\n 8. Add more status bar updates.\n 9. Determine if I want to have a save data function.\n10. Remove unnecessary bits, eg. saving data, upper/lower limits, grid on/off, labels on/off.\n11. Remove as many dependencies as possible, eg. numpy, os, pylab, pprint, random, sys.\n12. Comment up the wazoo.\n13. Use the same conventions/style throughout, eg. naming, using ' or \" for strings, commenting.\n14. Send to Dr. Markovic for testing.\n16. Create documentation.\n\"\"\"\n\n\n\nimport matplotlib\nimport matplotlib.pyplot\nmatplotlib.use('WXAgg')\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_wxagg import \\\n FigureCanvasWxAgg as FigCanvas, \\\n NavigationToolbar2WxAgg as NavigationToolbar\nimport numpy, os, pylab, pprint, random, serial, sys, wx\n\n\n# Define a class of global variables and methods.\nclass g(object):\n dummy = 0 # a dummy variable\n COM_PORT = 'COM24' # the comport the sensor is to be plugged into. Need to add an automatic check for this.\n TimeWindow = 60 # The width of the time window desired in seconds. This is the width to be kept for the scrolling plot.\n GatheringPeriod = 1000 # Time in between successive data gatherings in milliseconds. Default is 1000 ms.\n\nclass getAccData(object):\n # A class that gets data from the YEI 3-Space Sensor for display.\n \n def __init__(self, init=[0,0,0]):\n # Initialize the data value set.\n self.data = self.init = init\n \n def next(self):\n # Returns the next data value set.\n self._recalc_data()\n return self.data\n \n def _recalc_data(self):\n # Gets accelerometer data from the yei 3-space sensor.\n # Returns three floats consisting of the x, y, z\n # acceleration data, respectively.\n\n # Start Bytes, indicates the start of a command packet\n TSS_START_BYTE = 0xf7\n \n # For a full list of commands refer to the 3-Space Manual for your sensor\n TSS_GET_ALL_CORRECTED_COMPONENT_SENSOR_DATA = 0x25\n \n # This creates the comport handle and does initial setup like baudrates and timeouts\n serial_port = serial.Serial(g.COM_PORT, timeout=0.2, writeTimeout=0.2, baudrate=115200)\n \n print(\"TSS_GET_ALL_CORRECTED_COMPONENT_SENSOR_DATA\")\n # With parameterless wired commands the command byte will be the same as the checksum\n write_bytes = bytearray((TSS_START_BYTE,\n TSS_GET_ALL_CORRECTED_COMPONENT_SENSOR_DATA,\n TSS_GET_ALL_CORRECTED_COMPONENT_SENSOR_DATA))\n \n # Write the bytes to the serial\n serial_port.write(write_bytes)\n \n data_struct = struct.Struct('>fffffffff') # format must conform to the expected data\n \n # Read the bytes returned from the serial\n data_str = serial_port.read(data_struct.size)\n \n # The data must be flipped to little endian to be read correctly\n data = data_struct.unpack(data_str)\n\n # Close the serial\n serial_port.close()\n\n # Return acceleration in g's.\n self.data = [data[3], data[4], data[5]]\n\nclass getAccDataTest(object):\n # A class that generates pseudo-random data for display.\n \n def __init__(self, init=[0,0,0]):\n # Initialize the data value set.\n self.data = self.init = init\n \n def next(self):\n # Generate the next data value set.\n self._recalc_data()\n return self.data\n \n def _recalc_data(self):\n # Generate a data value set.\n # Returns three floats consisting of the x, y, z\n # acceleration data, respectively.\n self.data[0] += random.uniform(-0.1, 0.1)\n self.data[1] += random.uniform(-0.1, 0.1)\n self.data[2] += random.uniform(-0.1, 0.1)\n\n\nclass BoundControlBox(wx.Panel):\n \"\"\" A static box with a couple of radio buttons and a text\n box. Allows to switch between an automatic mode and a \n manual mode with an associated value.\n \"\"\"\n def __init__(self, parent, ID, label, initval):\n wx.Panel.__init__(self, parent, ID)\n \n self.value = initval\n \n box = wx.StaticBox(self, -1, label)\n sizer = wx.StaticBoxSizer(box, wx.VERTICAL)\n \n self.radio_auto = wx.RadioButton(self, -1, label=\"Auto\", style=wx.RB_GROUP)\n self.radio_manual = wx.RadioButton(self, -1, label=\"Manual\")\n self.manual_text = wx.TextCtrl(self, -1, size=(35,-1), value=str(initval), style=wx.TE_PROCESS_ENTER)\n \n self.Bind(wx.EVT_UPDATE_UI, self.on_update_manual_text, self.manual_text)\n self.Bind(wx.EVT_TEXT_ENTER, self.on_text_enter, self.manual_text)\n \n manual_box = wx.BoxSizer(wx.HORIZONTAL)\n manual_box.Add(self.radio_manual, flag=wx.ALIGN_CENTER_VERTICAL)\n manual_box.Add(self.manual_text, flag=wx.ALIGN_CENTER_VERTICAL)\n \n sizer.Add(self.radio_auto, 0, wx.ALL, 10)\n sizer.Add(manual_box, 0, wx.ALL, 10)\n \n self.SetSizer(sizer)\n sizer.Fit(self)\n \n def on_update_manual_text(self, event):\n self.manual_text.Enable(self.radio_manual.GetValue())\n \n def on_text_enter(self, event):\n self.value = self.manual_text.GetValue()\n \n def is_auto(self):\n return self.radio_auto.GetValue()\n \n def manual_value(self):\n return self.value\n\n\nclass GraphFrame(wx.Frame):\n # The main frame of the application.\n \n \n def __init__(self):\n # Initialize the main plotting frame.\n wx.Frame.__init__(self, None, -1, \"Yei Plotter\")\n \n # Initialize the data and the pause status.\n self.getAccDataTest = getAccDataTest()\n nextData = self.getAccDataTest.next()\n self.dataX = [nextData[0]]\n self.dataY = [nextData[1]]\n self.dataZ = [nextData[2]]\n self.paused = True\n \n # Create the major components: menu, status bar, and main panel.\n self.create_menu()\n self.create_status_bar()\n self.create_main_panel()\n \n # Set timer to get the data every GatheringPeriod (ms).\n self.redraw_timer = wx.Timer(self)\n self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) \n self.redraw_timer.Start(g.GatheringPeriod)\n\n def create_menu(self):\n self.menubar = wx.MenuBar()\n \n menu_file = wx.Menu()\n m_expt = menu_file.Append(-1, \"&Save plot\\tCtrl-S\", \"Save plot to file\")\n self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt)\n menu_file.AppendSeparator()\n m_exit = menu_file.Append(-1, \"E&xit\\tCtrl-X\", \"Exit\")\n self.Bind(wx.EVT_MENU, self.on_exit, m_exit)\n \n self.menubar.Append(menu_file, \"&File\")\n self.SetMenuBar(self.menubar)\n\n def create_main_panel(self):\n # Create the panel.\n self.panel = wx.Panel(self)\n\n # Initialize the panel.\n self.init_plot()\n self.canvas = FigCanvas(self.panel, -1, self.figure)\n\n # Create control boxes for time and the accelerations.\n self.Tmin_control = BoundControlBox(self.panel, -1, \"X min\", 0)\n self.Tmax_control = BoundControlBox(self.panel, -1, \"X max\", g.TimeWindow)\n self.Amin_control = BoundControlBox(self.panel, -1, \"Y min\", -1)\n self.Amax_control = BoundControlBox(self.panel, -1, \"Y max\", 1)\n \n # Create the pause button.\n # Default is the start position.\n self.pause_button = wx.Button(self.panel, -1, \"Start\")\n self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button)\n self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button)\n \n # Create a checkbox to overlay the plots with a grid or not.\n # By default it is set to show the grid.\n self.cb_grid = wx.CheckBox(self.panel, -1, \"Show Grid\", style=wx.ALIGN_RIGHT)\n self.Bind(wx.EVT_CHECKBOX, self.on_cb_grid, self.cb_grid)\n self.cb_grid.SetValue(True)\n \n # Create a checkbox to show time labels or not.\n # By default it is set to show the labels.\n self.cb_Tlab = wx.CheckBox(self.panel, -1, \"Show T labels\", style=wx.ALIGN_RIGHT)\n self.Bind(wx.EVT_CHECKBOX, self.on_cb_Tlab, self.cb_Tlab) \n self.cb_Tlab.SetValue(True)\n \n # Make a box to house the pause button, grid checkbox, and labels checkbox.\n self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)\n self.hbox1.AddSpacer(20)\n self.hbox1.Add(self.cb_grid, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)\n self.hbox1.AddSpacer(10)\n self.hbox1.Add(self.cb_Tlab, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)\n \n # Make a box to house the time and acceleration min/max values.\n self.hbox2 = wx.BoxSizer(wx.HORIZONTAL)\n self.hbox2.Add(self.Tmin_control, border=5, flag=wx.ALL)\n self.hbox2.Add(self.Tmax_control, border=5, flag=wx.ALL)\n self.hbox2.AddSpacer(24)\n self.hbox2.Add(self.Amin_control, border=5, flag=wx.ALL)\n self.hbox2.Add(self.Amax_control, border=5, flag=wx.ALL)\n \n # Make a box to hold the above two boxes.\n self.vbox = wx.BoxSizer(wx.VERTICAL)\n self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) \n self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP)\n self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP)\n \n # Place the above containing box into the panel.\n self.panel.SetSizer(self.vbox)\n self.vbox.Fit(self)\n \n def create_status_bar(self):\n self.statusbar = self.CreateStatusBar()\n\n def init_plot(self):\n # Setup the figure with its subfigures.\n self.figure = matplotlib.figure.Figure()\n self.axes1 = self.figure.add_subplot(2,2,1, projection='3d')\n self.axes2 = self.figure.add_subplot(2,2,2)\n self.axes3 = self.figure.add_subplot(2,2,3)\n self.axes4 = self.figure.add_subplot(2,2,4)\n\n # Add the subfigure titles.\n self.axes1.set_title('3D Vector Trace', size=12)\n self.axes2.set_title('X Acceleration', size=12)\n self.axes3.set_title('Y Acceleration', size=12)\n self.axes4.set_title('Z Acceleration', size=12)\n \n # Get the ticklabels.\n # Remember to change the axes1 to handle the 3D nature correctly. As written in this comment block, it assumes a 2D plot.\n pylab.setp(self.axes1.get_xticklabels(), fontsize=10)\n pylab.setp(self.axes1.get_yticklabels(), fontsize=10)\n pylab.setp(self.axes1.get_zticklabels(), fontsize=10)\n pylab.setp(self.axes2.get_xticklabels(), fontsize=10)\n pylab.setp(self.axes2.get_yticklabels(), fontsize=10)\n pylab.setp(self.axes3.get_xticklabels(), fontsize=10)\n pylab.setp(self.axes3.get_yticklabels(), fontsize=10)\n pylab.setp(self.axes4.get_xticklabels(), fontsize=10)\n pylab.setp(self.axes4.get_yticklabels(), fontsize=10)\n\n # Plot the subfigures as line series and save the reference to the plotted line series.\n self.plot_data1 = self.axes1.plot(numpy.array(self.dataX),\n numpy.array(self.dataY),\n numpy.array(self.dataZ),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data2 = self.axes2.plot(numpy.array(self.dataX),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data3 = self.axes3.plot(numpy.array(self.dataY),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data4 = self.axes4.plot(numpy.array(self.dataZ),\n color=(0.8, 0.2, 0.8))[0] \n\n#\n# Start here when continuing the adaption to my needs.\n# Remember that x is really time until it is adapted.\n# Remember to change the independent variable from x to T.\n# Remember to change the dependent variables from y to X, Y, Z.\n# However, .get_xticklabels() is a method that works on the independent variable generically. It does not reference x specifically so it remains unaffected by the x to T changing.\n#\n def draw_plot(self):\n # Redraws the plot\n\n # when Tmin is on auto, it \"follows\" Tmax to produce a \n # sliding window effect. therefore, Tmin is assigned after\n # Tmax.\n # The data values are taken as the x values. This needs to be changed to reflect the four plots.\n if self.Tmax_control.is_auto():\n Tmax = len(self.dataX) if len(self.dataX) > g.TimeWindow else g.TimeWindow\n else:\n Tmax = int(self.Tmax_control.manual_value())\n \n if self.Tmin_control.is_auto(): \n Tmin = Tmax - g.TimeWindow\n else:\n Tmin = int(self.xTmin_control.manual_value())\n\n # for Amin and Amax, find the minimal and maximal values\n # in the data set and add a mininal margin.\n # \n # note that it's easy to change this scheme to the \n # minimal/maximal value in the current display, and not\n # the whole data set.\n #\n # The data values are taken as the x values. This needs to be changed to reflect the four plots.\n if self.Amin_control.is_auto():\n Amin = round(min(self.dataX), 0) - 1\n else:\n Amin = int(self.Amin_control.manual_value())\n \n if self.Amax_control.is_auto():\n Amax = round(max(self.dataX), 0) + 1\n else:\n Amax = int(self.Amax_control.manual_value())\n\n # Set the upper and lower bounds for the various axes.\n self.axes1.set_xbound(lower=Amin, upper=Amax)\n self.axes1.set_ybound(lower=Amin, upper=Amax)\n self.axes1.set_zbound(lower=Amin, upper=Amax)\n self.axes2.set_xbound(lower=Tmin, upper=Tmax)\n self.axes2.set_ybound(lower=Amin, upper=Amax)\n self.axes3.set_xbound(lower=Tmin, upper=Tmax)\n self.axes3.set_ybound(lower=Amin, upper=Amax)\n self.axes4.set_xbound(lower=Tmin, upper=Tmax)\n self.axes4.set_ybound(lower=Amin, upper=Amax)\n \n # anecdote: axes.grid assumes b=True if any other flag is\n # given even if b is set to False.\n # so just passing the flag into the first statement won't\n # work.\n if self.cb_grid.IsChecked():\n self.axes1.grid(True, color='gray')\n self.axes2.grid(True, color='gray')\n self.axes3.grid(True, color='gray')\n self.axes4.grid(True, color='gray')\n else:\n self.axes1.grid(False)\n self.axes2.grid(False)\n self.axes3.grid(False)\n self.axes4.grid(False)\n\n # Using setp here is convenient, because get_xticklabels\n # returns a list over which one needs to explicitly \n # iterate, and setp already handles this.\n # However, .get_xticklabels() is a method that works on the independent variable generically. It does not reference x specifically so it remains unaffected by the x to T changing.\n pylab.setp(self.axes2.get_xticklabels(), visible=self.cb_Tlab.IsChecked())\n pylab.setp(self.axes3.get_xticklabels(), visible=self.cb_Tlab.IsChecked())\n pylab.setp(self.axes4.get_xticklabels(), visible=self.cb_Tlab.IsChecked())\n\n # Plot the subfigures as line series and save the reference to the plotted line series.\n self.plot_data1 = self.axes1.plot(numpy.array(self.dataX),\n numpy.array(self.dataY),\n numpy.array(self.dataZ),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data2 = self.axes2.plot(numpy.array(self.dataX),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data3 = self.axes3.plot(numpy.array(self.dataY),\n color=(0.8, 0.2, 0.8))[0]\n self.plot_data4 = self.axes4.plot(numpy.array(self.dataZ),\n color=(0.8, 0.2, 0.8))[0]\n \n## # Set the plot data according to the determined lower, upper bounds.\n## # This still needs to be adapted for the four plots.\n## self.plot_data1.set_xdata(numpy.array(self.dataX))\n## self.plot_data1.set_ydata(numpy.array(self.dataY))\n## self.plot_data1.set_zdata(numpy.array(self.dataZ))\n## self.plot_data2.set_xdata(numpy.arange(len(self.dataX)))\n## self.plot_data2.set_ydata(numpy.array(self.dataX))\n## self.plot_data3.set_xdata(numpy.arange(len(self.dataY)))\n## self.plot_data3.set_ydata(numpy.array(self.dataY))\n## self.plot_data4.set_xdata(numpy.arange(len(self.dataZ)))\n## self.plot_data4.set_ydata(numpy.array(self.dataZ))\n \n # Draw the canvas.\n self.canvas.draw()\n \n def on_pause_button(self, event):\n self.paused = not self.paused\n \n def on_update_pause_button(self, event):\n label = \"Start\" if self.paused else \"Pause\"\n self.pause_button.SetLabel(label)\n \n def on_cb_grid(self, event):\n self.draw_plot()\n \n def on_cb_Tlab(self, event):\n self.draw_plot()\n \n def on_save_plot(self, event):\n file_choices = \"PNG (*.png)|*.png\"\n \n dlg = wx.FileDialog(\n self, \n message=\"Save plot as...\",\n defaultDir=os.getcwd(),\n defaultFile=\"plot.png\",\n wildcard=file_choices,\n style=wx.SAVE)\n \n if dlg.ShowModal() == wx.ID_OK:\n path = dlg.GetPath()\n self.canvas.print_figure(path, dpi=self.dpi)\n self.flash_status_message(\"Saved to %s\" % path)\n \n def on_redraw_timer(self, event):\n # if paused do not add data, but still redraw the plot\n # (to respond to scale modifications, grid change, etc.)\n\n if not self.paused:\n nextData = self.getAccDataTest.next()\n self.dataX.append(nextData[0])\n self.dataY.append(nextData[1])\n self.dataZ.append(nextData[2])\n \n self.draw_plot()\n \n def on_exit(self, event):\n self.Destroy()\n \n def flash_status_message(self, msg, flash_len_ms=1500):\n # Show the specified message, msg, in the status bar for a brief period, flash_len_ms, in milliseconds.\n self.statusbar.SetStatusText(msg)\n self.timeroff = wx.Timer(self)\n self.Bind(\n wx.EVT_TIMER, \n self.on_flash_status_off, \n self.timeroff)\n self.timeroff.Start(flash_len_ms, oneShot=True)\n \n def on_flash_status_off(self, event):\n # Resest the status bar message to empty.\n self.statusbar.SetStatusText('')\n\n\nif __name__ == '__main__':\n g()\n app = wx.PySimpleApp()\n app.frame = GraphFrame()\n app.frame.Show()\n app.MainLoop()\n\n","sub_path":"YeiPlotter-dev2.py","file_name":"YeiPlotter-dev2.py","file_ext":"py","file_size_in_byte":20237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"633781286","text":"from app import chatit, db, LoginManager\r\nfrom flask import Flask, render_template, flash, redirect, url_for\r\nfrom flask_login import current_user, login_user, logout_user, login_required\r\nfrom app.forms import *\r\nfrom app.models import User, Friend, Blocked, directMessage\r\nfrom app.datamanagement import addFriend, blockUser, deleteFriend, unblockUser\r\nfrom sqlalchemy import literal\r\n\r\n@chatit.route('/')\r\ndef toLogin():\r\n \"\"\"\r\n\r\n Redirects users to the login page\r\n \r\n Args: None\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n return redirect(url_for('login'))\r\n\r\n@chatit.route('/index')\r\n@login_required\r\ndef index():\r\n \"\"\"\r\n\r\n A welcome page for users who are logged in\r\n \r\n Args: None\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n user = {'username': 'David'}\r\n return render_template('index.html', title = 'Home', user = user)\r\n\r\n@chatit.route('/login', methods = ['GET', 'POST'])\r\ndef login():\r\n \"\"\"\r\n\r\n Logs users into the site\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n password (PasswordField)\r\n remember (BooleanField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n if current_user.is_authenticated:\r\n return redirect(url_for('index'))\r\n form = userLogin()\r\n title = 'Log in'\r\n if form.validate_on_submit():\r\n user = User.query.filter_by(username = form.username.data).first()\r\n if user is None or not user.check_password(form.password.data):\r\n flash('Invalid username or password')\r\n return redirect(url_for('login'))\r\n login_user(user, remember = form.rememberMe.data)\r\n return redirect(url_for('index'))\r\n return render_template('login.html', form = form, title = title)\r\n\r\n@chatit.route('/logout')\r\n@login_required\r\ndef logout():\r\n \"\"\"\r\n\r\n Logs a user out of the website\r\n \r\n Args: None\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n logout_user()\r\n return redirect(url_for('index'))\r\n\r\n@chatit.route('/addfriend', methods = ['GET', 'POST'])\r\n@login_required\r\ndef add_friend():\r\n \"\"\"\r\n\r\n Adds a user to the friends list based on an inputted username\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n user = current_user\r\n form = friendSearch()\r\n title = 'Add Friend'\r\n if form.validate_on_submit():\r\n for i in current_user.blockedList:\r\n if i.blockedUsername == form.usernameQuery.data:\r\n flash('You have this user in your Blocked list.')\r\n return redirect(url_for('add_friend'))\r\n newFriend = User.query.filter_by(username = form.usernameQuery.data).first()\r\n if newFriend is None :\r\n flash('No user with that username')\r\n return redirect(url_for('add_friend'))\r\n for i in user.friendsList:\r\n if (i.friendUsername == newFriend.username):\r\n flash ('This user is already in your friends list')\r\n return redirect(url_for('add_friend'))\r\n flash('Successfully added new friend')\r\n addFriend(user, newFriend)\r\n return render_template('addfriend.html', form = form, title = title)\r\n\r\n@chatit.route('/blockuser', methods = ['GET', 'POST'])\r\n@login_required\r\ndef block_user():\r\n \"\"\"\r\n\r\n Adds a user to the block list based on an inputted username\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n user = current_user\r\n form = blockSearch()\r\n title = 'Block User'\r\n if form.validate_on_submit():\r\n for i in current_user.friendsList:\r\n if i.friendUsername == form.usernameQuery.data:\r\n flash('You have this user in your Friends list.')\r\n return redirect(url_for('block_user'))\r\n newBlock = User.query.filter_by(username = form.usernameQuery.data).first()\r\n if newBlock is None :\r\n flash('No user with that username')\r\n return redirect(url_for('block_user'))\r\n for i in user.blockedList:\r\n if (i.blockedUsername == newBlock.username):\r\n flash ('This user is already blocked')\r\n return redirect(url_for('block_user'))\r\n flash('Successfully blocked a new user')\r\n blockUser(user, newBlock)\r\n return render_template('blockuser.html', form = form, title = title)\r\n\r\n@chatit.route('/unfriend', methods = ['GET', 'POST'])\r\n@login_required\r\ndef unfriend():\r\n \"\"\"\r\n\r\n Removes a user from the friends list based on an inputted username\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n form = unfriendSearch()\r\n title = 'Unfriend a User'\r\n if form.validate_on_submit():\r\n for i in current_user.friendsList:\r\n if i.friendUsername == form.usernameQuery.data:\r\n flash('Successfully removed ' + str(i.friendUsername) + ' from friends list.')\r\n deleteFriend(i)\r\n return redirect(url_for('index'))\r\n flash('No such user in your friends list.')\r\n return redirect(url_for('unfriend'))\r\n return render_template('unfrienduser.html', form = form, title = title, friendsList = current_user.friendsList)\r\n\r\n@chatit.route('/unblock', methods = ['GET', 'POST'])\r\n@login_required\r\ndef unblock():\r\n \"\"\"\r\n\r\n Removes a user from the block list based on an inputted username\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n form = unblockSearch()\r\n title = 'Unblock a User'\r\n if form.validate_on_submit():\r\n for i in current_user.blockedList:\r\n if i.blockedUsername == form.usernameQuery.data:\r\n flash('Successfully removed ' + str(i.blockedUsername) + ' from blocked list.')\r\n unblockUser(i)\r\n return redirect(url_for('index'))\r\n flash('No such user in your blocked list.')\r\n return redirect(url_for('unblock'))\r\n return render_template('unblockuser.html', form = form, title = title, blockedList = current_user.blockedList)\r\n\r\n@chatit.route('/search', methods = ['GET', 'POST'])\r\n@login_required\r\ndef search_user():\r\n \"\"\"\r\n\r\n Searches the User database for any usernames that contain the inputted form data\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n\r\n Returns: A list of usernames containing the input data\r\n \"\"\"\r\n form = userSearch()\r\n title = 'Search for User'\r\n if form.validate_on_submit():\r\n userInput = '%' + str(form.usernameQuery.data) + '%'\r\n if User.query.filter(User.username.ilike(userInput)).first() is None:\r\n flash('No users match the username')\r\n return redirect(url_for('search_user'))\r\n userList = User.query.filter(User.username.ilike(userInput))\r\n return render_template('searchresults.html', title = 'Results of Search', userList = userList)\r\n return render_template('searchuser.html', form = form, title = title)\r\n\r\n@chatit.route('/chat', methods = ['GET', 'POST'])\r\n@login_required\r\ndef chat():\r\n \"\"\"\r\n\r\n Sends a message to another user with a subject and body\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n subject (StringField)\r\n body (StringField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n form = sendMessage()\r\n title = 'Chat With Other Users'\r\n if form.validate_on_submit():\r\n recipient = User.query.filter_by(username = form.usernameQuery.data).first()\r\n if recipient is None:\r\n flash('Invalid Recipient')\r\n return redirect(url_for('chat'))\r\n if recipient.username == current_user.username:\r\n flash('You cant send messages to yourself!')\r\n return redirect(url_for('chat'))\r\n for i in recipient.blockedList:\r\n if i.blockedUsername == current_user.username:\r\n flash('Cannot send messages to users that have you blocked.')\r\n return redirect(url_for('chat'))\r\n for i in current_user.blockedList:\r\n if i.blockedUsername == recipient.username:\r\n flash('Cannot send messages to users that you have blocked.')\r\n return redirect(url_for('chat'))\r\n sender = current_user\r\n messageSubject = form.subject.data\r\n messageBody = form.body.data\r\n message = directMessage(sent = sender, receive = recipient, body = messageBody, subject = messageSubject)\r\n db.session.add(message)\r\n db.session.commit()\r\n flash('Message sent!')\r\n return redirect(url_for('index'))\r\n return render_template('chat.html', title = title, form = form)\r\n \r\n@chatit.route('/messages', methods = ['GET'])\r\n@login_required\r\ndef messages():\r\n \"\"\"\r\n\r\n Displays all sent and received messages\r\n \r\n Args: None\r\n\r\n Returns: A list of sent and received messages\r\n \"\"\"\r\n title = 'Sent and Received Messages'\r\n sentMessages = directMessage.query.filter_by(sent = current_user)\r\n receivedMessages = directMessage.query.filter_by(receive = current_user)\r\n return render_template('viewmessages.html', title = title, sentMessages = sentMessages, receivedMessages = receivedMessages)\r\n\r\n@chatit.route('/friends', methods = ['GET'])\r\n@login_required\r\ndef friends():\r\n \"\"\"\r\n\r\n Displays all friends\r\n \r\n Args: None\r\n\r\n Returns: A list of friend usernames\r\n \"\"\"\r\n title = 'Friends'\r\n a = current_user\r\n return render_template('friends.html', title = title, friends = a.friendsList)\r\n\r\n@chatit.route('/blocked', methods = ['GET'])\r\n@login_required\r\ndef blocked():\r\n \"\"\"\r\n\r\n Displays all blocked users\r\n \r\n Args: None\r\n\r\n Returns: A list of blocked usernames\r\n \"\"\"\r\n title = 'Blocked Users'\r\n blockedList = current_user.blockedList\r\n return render_template('blocked.html', title = title, blockedList = blockedList)\r\n\r\n@chatit.route('/register', methods = ['GET', 'POST'])\r\ndef register():\r\n \"\"\"\r\n\r\n Registers a new user to the database\r\n \r\n Inputs: Form data\r\n username (StringField)\r\n email (StringField)\r\n password (PasswordField)\r\n password2 (PasswordField)\r\n submit (SubmitField)\r\n\r\n Returns: Nothing\r\n \"\"\"\r\n if current_user.is_authenticated:\r\n return redirect(url_for('index'))\r\n form = userRegistry()\r\n title = 'Register New User'\r\n if form.validate_on_submit():\r\n if User.query.filter_by(username = form.username.data).first() is not None:\r\n flash('A user with this username already exists. Please pick a different one.')\r\n return redirect(url_for('register'))\r\n user = User(username = form.username.data, email = form.email.data)\r\n user.set_password(form.password.data)\r\n db.session.add(user)\r\n db.session.commit()\r\n flash('Congratulations, you are now a registered user!')\r\n return redirect(url_for('login'))\r\n return render_template('registry.html', title = title, form = form)","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"34593312","text":"#------------------------------------------------------------------------------\n# Using saved/trained model\n#------------------------------------------------------------------------------\n\nimport cv2\nimport tensorflow as tf\nimport os # directories and paths in os\nimport matplotlib.pyplot as plt # show the image\n\nCATEGORIES = [\"Dog\",\"Cat\"] # will use this to convert prediction num to string value\nDATADIR = \"C:/Users/Michal/Dropbox/Neural network/dogs_and_cats/pictures\"\nmodel = tf.keras.models.load_model(\"3x64x0-CNN-75.model\")\nIMG_SIZE = 75\n\ndef prepare(filepath):\n img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) # read in the image, convert to grayscale\n new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize image to match model's expected sizing\n return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1) # return the image with shaping that TF wants\n\ndef predict_images(datadir):\n path = os.path.join(datadir)\n for img in os.listdir(path): # iterate over each image per dogs and cats\n try:\n prediction = model.predict([prepare(os.path.join(path, img))]) # always predict a list\n print(\"Prediction for {}: \".format(img), CATEGORIES[int(prediction[0][0])])\n\n img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) # read in the image, convert to grayscale\n new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize image to match model's expected sizing\n plt.imshow(new_array, cmap=\"gray\")\n plt.show()\n except Exception as e:\n print(e)\n\npredict_images(DATADIR)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"634544748","text":"import os\n\n#this script should be executed under the root directory\n\nfilelist = []\nposfix='_100x100.bin'\n\ndef listfile(dirname, f):\n for x in os.listdir(dirname):\n path = os.path.join(os.path.abspath(dirname), x)\n if os.path.isdir(path):\n listfile(path, f)\n elif os.path.isfile(path) and x.endswith(posfix):\n mId = os.path.basename(dirname)\n f.write(mId + ' ' + path + '\\n')\n \ndef createFeatureList(datadir):\n f = open(\"../data/featureslist.txt\", 'w')\n listfile(datadir, f)\n f.close()\n","sub_path":"utils/getFeatureList.py","file_name":"getFeatureList.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"420879692","text":"'''\r\n@author: Abel\r\n'''\r\ncity_dic = {}\r\ncitiesInContinent = {}\r\n\r\n''' City object holds all the information for a city/airport. \r\n Each City object is stored in a City dictionary as a value\r\n for a key that holds the city's code. '''\r\nclass City(object):\r\n def __init__(self, code, name, country, continent, timezone, coordinates, population, region):\r\n self.code = code\r\n self.name = name\r\n self.country = country\r\n self.continent = continent\r\n self.timezone = timezone\r\n self.coordinates = coordinates\r\n self.population = population\r\n self.region = region\r\n self.flights = {}","sub_path":"graphLib/City.py","file_name":"City.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"436882798","text":"def getchoicenumber():\r\n return int(input(\"Enter a number/limit: \")) #We return what needs to be returned, we then set a variable to what was returned, also no need to use global variable\r\n\r\ndef getnaturalnumbers():\r\n choicenumber = getchoicenumber() #This is the correct way of doing it, in java i did it a bit different, this is how it suppose to be.\r\n number = 0\r\n total = 0\r\n if choicenumber != 0 and choicenumber > 0:\r\n index = 0\r\n for index in range(index,choicenumber):\r\n number += 1\r\n if number % 3 == 0 or number % 5 == 0 and number <= choicenumber:\r\n total += number\r\n print(\"The sum of all numbers from 1 - \" + str(choicenumber) + \" are \" + str(total))\r\n else:\r\n print(\"The number entered is invalid\")\r\n\r\nif __name__ == \"__main__\":\r\n getnaturalnumbers()\r\n\r\n","sub_path":"NaturalNumbers.py","file_name":"NaturalNumbers.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"451723305","text":"import datetime as _datetime\n\nfrom kuber import versioning as _versioning\n\n# Information about the kubernetes API library version associated with this\n# package and kuber metadata around its creation and labeling within the\n# kuber library.\nKUBERNETES_VERSION = _versioning.KubernetesVersion(\n label=\"latest\",\n version=\"v1.21.0\",\n major=\"1\",\n minor=\"21\",\n patch=\"0\",\n pre_release=\"\",\n build=\"\",\n created_at=_datetime.datetime(2021, 4, 26),\n commit_sha=\"cb303e613a121a29364f75cc67d3d580833a7479\",\n)\n","sub_path":"kuber/latest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"273331621","text":"import requests\n\ndef calc_age(uid):\n token = '7c40e5767c40e5767c40e576f17c2b955277c407c40e576215a1da5cf3ef910dd4f6bd0'\n url = 'https://api.vk.com/method/{}.get?v=5.71&access_token={}&user_ids={}'\n \n response = requests.get(url.format('users',token,uid)).json()\n user_id = response['response'][0]['id']\n print(user_id)\n\n url = 'https://api.vk.com/method/{}.get?v=5.71&access_token={}&user_id={}&fields=bdate'\n response = requests.get(url.format('friends', token, user_id)).json()\n #number_friends = response['response']['count']\n friends = response['response']['items']\n\n #print(number_friends)\n data_hist = {}\n for friend in friends:\n #print(friend)\n try:\n age = 2019 - int(friend['bdate'].split('.')[2])\n data_hist[age] = data_hist.get(age,0) + 1\n except:\n continue\n\n data_hist = data_hist.items()\n s = sorted(data_hist, key=lambda x: x[0])\n return sorted(s, key=lambda x: x[1], reverse=True)\n \n\nif __name__ == '__main__':\n res = calc_age('reigning')\n print(res)\n\n\n","sub_path":"vk_age_histogram/req/friends.py","file_name":"friends.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"239796249","text":"#from skimage.io import imread\n#from skimage.util import crop\n#from skimage.transform import rotate,resize,rescale\nimport random\nimport cv2\nimport numpy as np\nimport os\nimport codecs\nfrom shapely.geometry import Point, Polygon\n#from torch.utils.data import Dataset, DataLoader\nimport torch\nfrom torch_geometric.data import Data, Dataset,DataLoader\nfrom torch_scatter import scatter_mean\nimport torch_geometric.transforms as GT\nimport math\nimport json\nimport csv\n\n# 加入位置feature\n# 加入文字feature\n# 加入图像feature。 图像和文本框难以对齐,这样估计:上下加半个文本框,左右加一个文本框。\n# scitsr数据集\n\nalphabet = \"0123456789abcdefghijklmnopqrstuvwxyz,. \"\nvob = {x:ind for ind, x in enumerate(alphabet)}\n\ndef encode_text(ins, vob, max_len = 10, default = \" \"):\n out = []\n sl = len(ins)\n minl = min(sl, max_len)\n for i in range(minl):\n char = ins[i]\n if char in vob:\n out.append(vob[char])\n else:\n out.append(vob[default])\n if len(out)<=max_len:\n out = out +[vob[default]]*(max_len-len(out))\n return out\n\n\nclass ScitsrDataset(Dataset):\n def __init__(self, root_path, transform=None, pre_transform=None):\n super(ScitsrDataset, self).__init__(root_path, transform, pre_transform)\n self.root_path = root_path\n self.jsonfile = os.path.join(self.root_path, \"imglist.json\")\n self.img_size = 256\n self.kernel = np.ones((3,3),np.uint8) # 把图像的线变粗一点\n if os.path.exists(self.jsonfile): # imglist.json去掉了一些有疑问的文件\n with open(self.jsonfile, \"r\") as read_file:\n self.imglist = json.load(read_file)\n else: \n self.imglist = list(filter(lambda fn:fn.lower().endswith('.jpg') or fn.lower().endswith('.png') ,\n os.listdir(os.path.join(self.root_path,\"/content/scitsr_data/train/img\"))))\n self.imglist = self.check_all()\n with open(self.jsonfile, \"w\") as write_file:\n json.dump(self.imglist, write_file)\n self.graph_transform = GT.KNNGraph(k=6)\n \n @property\n def raw_file_names(self):\n return []\n\n @property\n def processed_file_names(self):\n return []\n \n def read_structure(self):\n return \n \n def reset(self):\n pass\n \n def check_all(self):\n validlist=[]\n for idx in range(len(self.imglist)):\n print(\"*** file:\",self.imglist[idx])\n structs, chunks ,img = self.readlabel(idx)\n vi = self.check_chunks(structs, chunks)\n if vi==1 and (not img is None):\n validlist.append(self.imglist[idx])\n print(\"valid:\", len(validlist))\n return validlist\n \n # structs中不应该有空的cell,但是实际上可能有。空cell存在,会影响在chunk中的index。\n def remove_empty_cell(self,structs):\n structs.sort(key=lambda p: p[\"id\"])\n news = []; idx = 0\n for st in structs:\n text = st[\"tex\"].strip().replace(\" \",\"\")\n if text==\"\" or text=='$\\\\mathbf{}$': #空的cell\n continue\n st[\"id\"] = idx\n news.append(st)\n idx +=1\n return news\n\n def check_chunks(self,structs, chunks):\n structs = self.remove_empty_cell(structs)\n for st in structs:\n id = st[\"id\"] \n if id>=len(chunks):\n print(\"chunk index out of range.\", id)\n return 0\n ch = chunks[id]\n txt1 = st[\"tex\"].replace(\" \",\"\")\n txt2 = ch[\"text\"].replace(\" \",\"\")\n #print(id, txt1,\" \", txt2)\n if txt1!=txt2:\n print(id, \"mismatch:\",txt1,\" \", txt2)\n if st[\"end_row\"]-st[\"start_row\"] !=0 or st[\"end_col\"]-st[\"start_col\"]!=0:\n print(\"span cells:\", id)\n return 1\n \n def format_html(self,structs, chunks):\n rowcnt = max(structs, key=lambda p: p[\"end_row\"])[\"end_row\"]+1\n colcnt = max(structs, key=lambda p: p[\"end_col\"])[\"end_col\"]+1\n #print(\"row , col number:\", rowcnt, colcnt)\n mat = [[\"
\"]*colcnt for i in range(rowcnt)]\n for st in structs: # 填空\n mat[st[\"start_row\"]][st[\"start_col\"]] = \"\"\n html = \"\"\n #print(mat)\n for row in mat:\n html += \"\"+\"\".join(row)+\"\"\n return html \n \n \n def readlabel(self,idx):\n imgfn = self.imglist[idx]\n# print('img: {}'.format(imgfn))\n structfn = os.path.join(self.root_path,\"/content/scitsr_data/train/structure\",os.path.splitext(os.path.basename(imgfn))[0] +\".json\")\n chunkfn = os.path.join(self.root_path,\"/content/scitsr_data/train/chunk\",os.path.splitext(os.path.basename(imgfn))[0]+\".chunk\")\n relfn = os.path.join(self.root_path,\"/content/scitsr_data/train/rel\",os.path.splitext(os.path.basename(imgfn))[0]+\".rel\")\n imgfn = os.path.join(self.root_path,\"/content/scitsr_data/train/img\",os.path.splitext(os.path.basename(imgfn))[0]+\".png\")\n #print(\"***\",chunkfn)\n if not os.path.exists(structfn) or not os.path.exists(chunkfn) or not os.path.exists(imgfn):\n print(\"can't find files.\")\n return\n with open(chunkfn, 'r') as f:\n chunks = json.load(f)['chunks']\n if len(chunks) == 0:\n print(chunkfn)\n with open(structfn, 'r') as f:\n structs = json.load(f)['cells']\n img = cv2.imread(imgfn)\n if not img is None:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.dilate(img,self.kernel,iterations = 1)\n img = cv2.resize(img, (self.img_size,self.img_size), interpolation = cv2.INTER_AREA) \n \n #with open(relfn, 'r') as f:\n # reader = csv.reader(f,delimiter='\\t')\n # rels = list(reader)\n #if (len(chunks) != len(structs)):\n # print(\"chunks cells do not match. \" + chunkfn)\n # print(len(chunks),len(structs))\n \n #self.check_chunks(structs,chunks)\n return structs, chunks ,img \n \n \n def __len__(self):\n return len(self.imglist)\n \n \n def box_center(self, chkp):\n # x1, x2, y1, y2 in chkp\n return [(chkp[0]+chkp[1])/2, (chkp[2]+chkp[3])/2]\n \n def get_html(self, idx):\n structs, chunks, img = self.readlabel(idx)\n self.check_chunks(structs,chunks)\n html = self.format_html(structs, chunks)\n return html\n \n \n def cal_chk_limits(self, chunks):\n x_min = min(chunks, key=lambda p: p[\"pos\"][0])[\"pos\"][0]\n x_max = max(chunks, key=lambda p: p[\"pos\"][1])[\"pos\"][1]\n y_min = min(chunks, key=lambda p: p[\"pos\"][2])[\"pos\"][2]\n y_max = max(chunks, key=lambda p: p[\"pos\"][3])[\"pos\"][3]\n hlist = [p[\"pos\"][3]-p[\"pos\"][2] for p in chunks] \n avhei = sum(hlist)/len(hlist)\n # 加入一点边界, 大概对应整个图像。\n width = x_max-x_min + 2*avhei\n height = y_max-y_min + 0.5*2*avhei\n return [x_min,x_max,y_min,y_max,width,height,avhei] # \n \n # 相对的位置。\n def pos_feature(self,chk,cl): \n x1=(chk[\"pos\"][0]-cl[0]+cl[6])/cl[4] \n x2=(chk[\"pos\"][1]-cl[0]+cl[6])/cl[4] \n x3=(chk[\"pos\"][2]-cl[2]+0.5*cl[6])/cl[5] \n x4=(chk[\"pos\"][3]-cl[2]+0.5*cl[6])/cl[5]\n x5 = (x1+x2)*0.5 # 中心点\n x6 = (x3+x4)*0.5\n x7 = x2-x1 # 文本宽度\n x8 = x4-x3 # 文本高度\n return [x1,x2,x3,x4,x5,x6,x7,x8]\n \n def augmentation_chk(self, chunks):\n for chk in chunks:\n chk[\"pos\"][0] += random.normalvariate(0,1)\n chk[\"pos\"][1] += random.normalvariate(0,1)\n chk[\"pos\"][2] += random.normalvariate(0,1)\n chk[\"pos\"][3] += random.normalvariate(0,1)\n \n def get(self, idx):\n structs, chunks, img = self.readlabel(idx)\n \n # self.augmentation_chk(chunks)\n \n cl = self.cal_chk_limits(chunks)\n #print(cl)\n #x = [chunks[st[\"id\"]][\"pos\"] for st in structs]\n x,pos,tbpos,xtext,imgpos=[],[],[],[],[]\n plaintext = []\n structs = self.remove_empty_cell(structs)\n# if len(structs) != len(chunks):\n# print(\"Err: len(struct) = {}; len(chunks) = {}\".format(len(structs), len(chunks)))\n# exit(0)\n for st in structs:\n id = st[\"id\"] \n chk = chunks[id]\n xt = self.pos_feature(chk,cl)\n x.append(xt)\n pos.append(xt[4:6])\n tbpos.append([st[\"start_row\"],st[\"end_row\"],st[\"start_col\"],st[\"end_col\"]])\n xtext.append(encode_text(chk[\"text\"],vob))\n plaintext.append(chk[\"text\"].encode('utf-8'))\n imgpos.append([(1.0-xt[5])*2-1.0, xt[4]*2-1.0]) # 图像中的y是倒过来的。这是归一化[-1,1]之间。图像的y在前,和H对应。\n #y = []\n #for rel in rels: # 先考虑同行的关系\n # if rel[2][0] == '1':\n # y.append([int(rel[0]),int(rel[1])])\n \n \n x = torch.FloatTensor(x) \n pos = torch.FloatTensor(pos) \n data = Data(x=x,pos=pos)\n data = self.graph_transform(data) # 构造图的连接\n y = self.cal_label(data, tbpos)\n img = torch.FloatTensor(img/255.0).unsqueeze(0).unsqueeze(0)\n #print(img.size(), img.dtype)\n data.y = torch.LongTensor(y)\n data.img = img\n data.imgpos = torch.FloatTensor(imgpos)\n data.nodenum = torch.LongTensor([len(structs)])\n # print(type(xtext)) #\n data.xtext = torch.LongTensor(xtext)\n # print(type(plaintext))\n # print(plaintext)\n # data.plaintext = plaintext\n # print(data)\n return data\n \n def cal_label(self,data,tbpos): # 根据构造的图,计算边的标注。\n edges = data.edge_index # [2, 边的个数] 无向图的边是对称的,即有2条。\n y = []\n for i in range(edges.size()[1]):\n# y.append(self.if_same_row(edges[0,i], edges[1,i],tbpos))\n y.append(self.if_same_col(edges[0,i], edges[1,i],tbpos))\n return y\n \n def if_same_row(self,si,ti,tbpos):\n ss,se = tbpos[si][0], tbpos[si][1]\n ts,te = tbpos[ti][0], tbpos[ti][1]\n if (ss>=ts and se<=te):\n return 1\n if (ts>=ss and te<=se):\n return 1\n return 0\n \n def if_same_col(self,si,ti,tbpos):\n ss,se = tbpos[si][2], tbpos[si][3]\n ts,te = tbpos[ti][2], tbpos[ti][3]\n if (ss>=ts and se<=te):\n return 1\n if (ts>=ss and te<=se):\n return 1\n return 0\n \n \n def if_same_cell(self):\n pass\n \n \nif __name__ == \"__main__\": \n \n #a=torch.load(\"temp.pt\")\n #print(a)\n #print(a.nodenum,a.imgpos[0:20,:])\n #exit(0)\n\n# root_path = '/home/deepvision/hz2/SciTSR/train'\n root_path = '/home/deepvision/lyr/out'\n \n ds = ScitsrDataset(root_path)\n# print(len(ds))\n #ds.check_all()\n #print(ds.get_html(76))\n# print(ds[1])\n# exit(0)\n test_loader = DataLoader(ds, batch_size=5 )\n for data in test_loader:\n print(data,data.num_graphs)\n print(\"data.x:{}\".format(data.x))\n #x = scatter_mean(data.x, data.batch, dim=0)\n #print(data.edge_index)\n #print(x.size())\n print(\"ratio:\",data.y.sum().float()/data.y.size()[0])\n print(data.imgpos[0:10,:], data.nodenum)\n #torch.save(data, \"temp.pt\")\n","sub_path":"GFTE-pos+text+img-test/dataset3.py","file_name":"dataset3.py","file_ext":"py","file_size_in_byte":11669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"342117807","text":"#*****************************************************************************/\n# @file main.py\n# @author Majid Nasiri 95340651\n# @version V1.0.0\n# @date 22 Dec 2017\n# @brief multiobjective problem\n#*****************************************************************************/\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport ga\n\n\nplt.close(\"all\")\nresult_dir = './results'\nxover_list = ['single']\nmutation_list = ['uniform']\nparent_selection_list = [('FPS', 'roulette_wheel')]\n#survivor_selection_list = [('mu_plus_lambda', 1.5),\n# ('generational', None),]\n\n\n#parent_selection_list = [('FPS', 'roulette_wheel'),\n# ('FPS', 'SUS'),\n# ('linear_ranking', 'roulette_wheel'),\n# ('linear_ranking', 'SUS'),\n# ('exponential_ranking', 'roulette_wheel'),\n# ('exponential_ranking', 'SUS'),\n# ('best_n_of_k', 2, 5), # 2 best of 5 random\n# ('best_n_of_k', 1, 5), # 1 best of 5 random\n# ]\n#\nsurvivor_selection_list = [('generational', None),\n ('GENITOR', 0.5), # worst 50% replaced by new offspring\n ('round_robin', None),\n ('mu_plus_lambda', 1.4), # best mu number of mu+lamba will be remain (lamba = 40% * mu)\n ('mu_lambda', 1.4), # best mu number of lamba will be remain (lamba = 1.4 * mu)\n ]\n\n\nfor ps in parent_selection_list:\n for ss in survivor_selection_list:\n # create a model with hyperparameters \n multobjective_model = ga.evolutionary_computing(rep ='float',\n max_generation = 20,\n population_size = 20*4,\n crossover = xover_list[0],\n crossover_prob = 0.9,\n mutation = mutation_list[0],\n mutation_prob = 0.9,\n ps = ps,\n ss = ss,\n result_dir = result_dir,\n verbose = True,\n )\n\n # run the model \n multobjective_model.run() \n gar = multobjective_model.generation_array\n gp = multobjective_model.generation_pareto\n garr = np.asarray(gar[1:])\n generation_variance_array = [np.var(g) for g in garr]\n plt.plot(generation_variance_array, label='survival selection type= '+ss[0])\n plt.xlabel('Generation')\n plt.ylabel('Variance of generation chromosomes')\n plt.legend()\n plt.grid()\n \n\n# fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True,)\n# cmap = plt.get_cmap('tab20')\n# for j,g in enumerate(gar[1:]): #[gar[-1]]\n# ax1.scatter(g[:,0], g[:,1], s=40, cmap=cmap, edgecolors='none', label='generation= '+str(j))\n# ax1.legend()\n# ax1.set_title('Decision Space')\n# ax1.set_xlabel('Radius of cone')\n# ax1.set_ylabel('Height of cone')\n# ax1.set_xlim([0, 0.9])\n# ax1.set_ylim([0, 4])\n# ax1.grid(True)\n#\n# for j,g in enumerate(gp[1:]): #[gp[-1]]\n# ax2.scatter(g[:,0], g[:,1], s=40, cmap=cmap, edgecolors='none', label='generation= '+str(j)) \n# ax2.legend()\n# ax2.set_title('Objective Space')\n# ax2.set_xlabel('Volume of cone')\n# ax2.set_ylabel('Surface of cone') \n# ax2.set_xlim([0, 13])\n# # ax2.set_ylim([0, 12])\n# ax2.grid(True)\n# \n# fig.set_size_inches(14, 8)\n# fig.savefig(result_dir+'/#parent_selection='+ps[0]+\\\n# '__#survival_selection='+ss[0]+'.jpg', dpi=100)\n# plt.close('all')\n\n","sub_path":"evolutionary_computing/EHHW6_multiobjective/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"441765647","text":"# Complete the function below.\ndef illuminated(N, pos, lampDBX, lampDBY):\n x, y = pos\n adjacent = ((x,y),(x-1,y+1),(x,y+1),(x+1,y+1),(x+1,y),(x+1,y-1),(x,y-1),(x-1,y-1),(x-1,y))\n\n if len(lampDBX[x]) > 0:\n for yPos in lampDBX[x]:\n if (x, yPos) not in adjacent:\n return 'LIGHT'\n if len(lampDBY[y]) > 0:\n for xPos in lampDBY[y]:\n if (xPos, y) not in adjacent:\n return 'LIGHT'\n diff = 1\n while x + diff <= N or x - diff >= 1 or y + diff <= N or y - diff >= 1:\n nw = (x - diff, y + diff)\n ne = (x + diff, y + diff)\n se = (x + diff, y - diff)\n sw = (x - diff, y - diff)\n\n for coord in [nw, ne, se, sw]:\n cX, cY = coord\n if cX in lampDBX and cY in lampDBX[cX] and (cX, cY) not in adjacent:\n return 'LIGHT'\n if cY in lampDBY and cX in lampDBY[cY] and (cX, cY) not in adjacent:\n return 'LIGHT'\n diff += 1\n\n return 'DARK'\n\ndef checkIllumination(N, lamps, queries):\n lampDBX, lampDBY = {}, {}\n\n for i in range(1, N + 1):\n lampDBX[i], lampDBY[i] = set(), set()\n\n for lamp in lamps:\n x, y = lamp\n lampDBX[x].add(y)\n lampDBY[y].add(x)\n\n return [illuminated(N, pos, lampDBX, lampDBY) for pos in queries]\n\n\nlambs = [[4,3],[4,4]]\nqs = [[3,4],[7,6]]\nprint(checkIllumination(8, lambs, qs))","sub_path":"interviews/dbox.py","file_name":"dbox.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"540577990","text":"from setuptools import setup\nfrom setuptools import find_packages\n\n\nNAME = \"documentr\"\nVERSION = \"1.0.0\"\n\nREQUIRES = [\n \"Jinja2\"\n]\n\nsetup(\n name=NAME,\n version=VERSION,\n description=\"Documentor\",\n author_email=\"introduccio@gmail.com\",\n keywords=[\"hive\", \"documentation\"],\n install_requires=REQUIRES,\n tests_require=[],\n packages=find_packages()\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"546209043","text":"# Copyright 2017 BlyNotes. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\r\n###############################################\r\n# Author: Original code provided by Professor for CS 6375\r\n#\r\n# Modified by: Stephen Blystone\r\n#\r\n# Purpose: Modify hyperparameters using Adam Optimizer\r\n# and modified MNIST data to achieve highest\r\n# test accuracy that you can.\r\n###############################################\r\n\r\nimport os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\n\r\nfrom our_mnist import *\r\n\r\nimport tensorflow as tf\r\nimport sys\r\nimport csv\r\nimport numpy as np\r\nimport timeit\r\nmnist = read_data_sets('MNIST_data', one_hot=True)\r\n\r\n\r\n# Variables initialized below for automation\r\n# X = tf.placeholder(tf.float32, shape=[None, 784])\r\n# Y = tf.placeholder(tf.float32, shape=[None, 10])\r\n# keep_prob = tf.placeholder(tf.float32)\r\n\r\n# *******************************************************************\r\n# DO NOT MODIFY THE CODE ABOVE THIS LINE\r\n# MAKE CHANGES TO THE CODE BELOW:\r\n\r\n# Flag to disable printing every 100 batches\r\nDISABLEBATCHPRINT = True\r\n\r\n\r\ndef weight_variable(shape):\r\n \"\"\"a method for initializing weights. Initialize to small random values.\"\"\"\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef bias_variable(shape):\r\n \"\"\"a method for initializing bias. Initialize to 0.1.\"\"\"\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef buildSingleLayer(input, numInputs, layer_dict, layerNum, keep_prob_label):\r\n \"\"\"Build a single layer of the network (either Hidden or Output).\r\n This is a fully connected Layer of layer_dict['layerSize'] nodes\r\n\r\n Input:\r\n -input: input values to this layer (output from the previous layer, or X for first layer)\r\n -numInputs: number of nodes in the input layer (i.e. size of previous layer)\r\n -layer_dict: python dictionary holding layer-specific parameters\r\n -layerNum: index of which layer is being built\r\n -keep_prob_label: python list holding tf.placeholder(tf.float32) for the keep_prob for that layer\r\n\r\n Output:\r\n -v_fc: output values for the layer\r\n -W_fc: weights calculated for this layer; used for regularization calculations later\r\n \"\"\"\r\n\r\n # Print layer-specific information\r\n print(\"Building Layer {}. numInputs = {} and layerSize = {}\".format(\r\n layerNum + 1, numInputs, layer_dict['layerSize']))\r\n\r\n # Create Weight and Bias variables using layer-specific values in layer_dict\r\n W_fc = weight_variable([numInputs, layer_dict['layerSize']])\r\n b_fc = bias_variable([layer_dict['layerSize']])\r\n\r\n # Every node type calculates the matrix multiplication\r\n matmul = tf.matmul(input, W_fc) + b_fc\r\n\r\n # Apply specific node type\r\n if (layer_dict['nodeType'] == \"ReLU\"):\r\n v_fc = tf.nn.relu(matmul)\r\n elif (layer_dict['nodeType'] == \"Sigmoid\"):\r\n v_fc = tf.nn.sigmoid(matmul)\r\n elif (layer_dict['nodeType'] == \"Linear\"):\r\n # Linear, so no need to apply anything\r\n v_fc = matmul\r\n else:\r\n print(\"ERROR: Unknown nodeType in layer_dict: {}\".format(layer_dict['nodeType']))\r\n sys.exit(1)\r\n\r\n # Add drop-out layer if specified\r\n if (layer_dict['dropoutFlag']):\r\n print(\"Dropout Layer\")\r\n v_fc = tf.nn.dropout(v_fc, keep_prob_label[layerNum])\r\n\r\n return (v_fc, W_fc)\r\n\r\n\r\ndef buildLayers(layers, keep_prob_label, X):\r\n \"\"\"Builds all of the layers specified by layerSizes list.\r\n It prints message when it builds input layer, Hidden layers or output layer\r\n\r\n Inputs:\r\n -layers: list of all of the layer_dicts\r\n -keep_prob_label: python list holding tf.placeholder(tf.float32) for the keep_prob for each layer\r\n -X: initial input values\r\n\r\n Outputs:\r\n -tmpVal: This is the predicted_Y value\r\n -weights: This is the list of weights for each layer; used later in regularization calculations\r\n \"\"\"\r\n print(\"Building Layers\")\r\n\r\n # Set tmpVal equal to output of current layer built\r\n # Use tmpVal to build next layer\r\n tmpVal = X\r\n\r\n # Set tmpSize equal to size of X initially\r\n tmpSize = X.get_shape().dims[1].value\r\n\r\n # initialize weights list\r\n weights = []\r\n\r\n # Iterate over each layer_dict\r\n # enumerate returns an index along with the data\r\n # index (idx) used to print whether we are building a Hidden Layer or Output Layer\r\n for idx, layer_dict in enumerate(layers):\r\n if (idx < len(layers) - 1):\r\n print(\"Building Hidden Layer {}\".format(idx + 1))\r\n else:\r\n print(\"Building Output Layer\")\r\n\r\n # Build layer and get output values\r\n tmpVal, tmpWeight = buildSingleLayer(\r\n tmpVal, tmpSize, layer_dict, idx, keep_prob_label)\r\n # Store the size of the current layer to be used as the input size for the next layer\r\n tmpSize = layer_dict['layerSize'] # Use this for next iteration\r\n # Append the weights from the current layer to the weights list\r\n weights.append(tmpWeight)\r\n\r\n # tmpVal is the predicted_Y value\r\n # weights is the list of weights used in each layer\r\n return (tmpVal, weights)\r\n\r\n\r\ndef runAlgorithm(param, outputText=\"\"):\r\n \"\"\"Function that runs the algorithm.\r\n\r\n Inputs:\r\n -param: a dict containing all the variables I can adjust\r\n -outputText: used for writing to the output file\r\n\r\n Outputs:\r\n -test_accuracy: The test accuracy for the run.\r\n -time_duration: The time it took to complete the run.\r\n \"\"\"\r\n\r\n # Reset the default graph to free memory\r\n # If you were to run a for loop over runAlgorithm trying different configurations,\r\n # Tensorflow places each node into a graph (the default graph if no other is specified).\r\n # Eventually this will cause an Out Of Memory error to occur, because the graph size\r\n # continues to grow.\r\n # To fix this issue, I reset the default graph everytime I call runAlgorithm.\r\n # This causes Tensorflow to remove the old graph and create a brand new graph each time.\r\n tf.reset_default_graph()\r\n\r\n # As a result of reseting the default graph, I have to recreate the X and Y placeholder variables.\r\n # Placing them after reset_default_graph causes Tensorflow to add these first to the new graph.\r\n X = tf.placeholder(tf.float32, shape=[None, 784])\r\n Y = tf.placeholder(tf.float32, shape=[None, 10])\r\n\r\n # Start interactive session\r\n sess = tf.InteractiveSession()\r\n\r\n # Start timer. Used to time how long it takes runAlgorithm to complete\r\n start_time = timeit.default_timer()\r\n\r\n # Initialize keep_prob list\r\n # keep_prob holds the actual probability values specified in the layers list.\r\n # keep_prob_label holds the tf.placeholder values for each layer\r\n keep_prob = []\r\n keep_prob_label = []\r\n # enumerate over the layers to get the keep_prob values\r\n for idx, layer in enumerate(param['layers']):\r\n # print(\"{}: {}\".format(idx, layer))\r\n # create placeholder value for keep_prob for each layer\r\n tmpProbHolder = tf.placeholder(tf.float32)\r\n # Append placeholder value to keep_prob_label list\r\n keep_prob_label.append(tmpProbHolder)\r\n # Append actual probability for each layer to end of keep_prob list\r\n keep_prob.append(layer['keep_prob'])\r\n\r\n # Create feed_dict for printing the output and testing\r\n feed_dict_Print_Train = {keep_prob_label[i]: 1 for i in range(0, len(param['layers']))}\r\n feed_dict_Print_Train[X] = mnist.train.images\r\n feed_dict_Print_Train[Y] = mnist.train.labels\r\n\r\n # Create feed_dict for printing the output and testing\r\n feed_dict_Test = {keep_prob_label[i]: 1 for i in range(0, len(param['layers']))}\r\n feed_dict_Test[X] = mnist.test.images\r\n feed_dict_Test[Y] = mnist.test.labels\r\n\r\n # Build layers and get predicted_Y and layerWeights back\r\n predicted_Y, layerWeights = buildLayers(param['layers'], keep_prob_label, X)\r\n\r\n # Calculate cross_entropy\r\n cross_entropy = tf.reduce_mean(\r\n tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=predicted_Y))\r\n\r\n # Calculate regularization value\r\n # Assert that the number of layers equals to the number of layers for which we have weights\r\n # This is required for zip to work properly below\r\n assert len(param['layers']) == len(layerWeights)\r\n # Use Python's zip function, along with list comprehension to calculate the regularization values\r\n # Zip takes 2 data structures of equal lengths and returns the i'th value of the first structure along\r\n # with the i'th value of the second structure.\r\n # For example:\r\n # d1 = [1, 2, 3]\r\n # d2 = [10, 100, 1000]\r\n # for elementFrom_d1, elementFrom_d2 in zip(d1, d2):\r\n # print(elementFrom_d1 * elementFrom_d2)\r\n #\r\n # The above example outputs:\r\n # 10\r\n # 200\r\n # 3000\r\n #\r\n # The list comprehension is basically a shorthand way of doing the following:\r\n # tmp = []\r\n # for a, b in zip(param['layers'], layerWeights):\r\n # tmp.append(a['regLambda'] * tf.nn.l2_loss(b))\r\n #\r\n # Using the above example, the corresponding list comprehension would be:\r\n # d1 = [1, 2, 3]\r\n # d2 = [10, 100, 1000]\r\n # tmp = []\r\n # for elementFrom_d1, elementFrom_d2 in zip(d1, d2):\r\n # tmp.append(elementFrom_d1 * elementFrom_d2)\r\n #\r\n # Printing the tmp value out, we would get:\r\n # [10, 200, 3000]\r\n #\r\n # I then wrap the list comprehension using sum(), which adds up each of the values.\r\n # Performing this on our tmp list:\r\n # sum(tmp) = 3210\r\n #\r\n #\r\n # If you look at the code the Professor originally provided, the below code performs the same\r\n # function, but with a variable number of layers and lambda values.\r\n regularizer = sum([a['regLambda'] * tf.nn.l2_loss(b)\r\n for a, b in zip(param['layers'], layerWeights)])\r\n\r\n # calculate the loss\r\n loss = tf.reduce_mean(cross_entropy + regularizer)\r\n\r\n # Use Adam to minimize the loss\r\n train_step = tf.train.AdamOptimizer(\r\n learning_rate=param['learning_rate'], beta1=param['beta1'], beta2=param['beta2'], epsilon=param['epsilon']).minimize(loss)\r\n sess.run(tf.global_variables_initializer())\r\n\r\n print(\"Starting Training...\")\r\n # Only print if DISABLEBATCHPRINT is not set\r\n if (not DISABLEBATCHPRINT):\r\n print(\"epoch\\ttrain_accuracy\\ttest_accuracy\")\r\n\r\n for i in range(3000):\r\n batch = mnist.train.next_batch(param['batch_size'])\r\n\r\n # Only print if DISABLEBATCHPRINT is not set\r\n if (not DISABLEBATCHPRINT):\r\n if i % 100 == 0:\r\n correct_prediction = tf.equal(tf.argmax(predicted_Y, 1), tf.argmax(Y, 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n test_accuracy = accuracy.eval(feed_dict=feed_dict_Test)\r\n train_accuracy = accuracy.eval(feed_dict=feed_dict_Print_Train)\r\n\r\n print(\"%d \\t %.3f \\t\\t %.3f\" % (i, train_accuracy, test_accuracy))\r\n\r\n # Create feed_dict for Training\r\n feed_dict_Train = {keep_prob_label[i]: keep_prob[i] for i in range(0, len(param['layers']))}\r\n feed_dict_Train[X] = batch[0]\r\n feed_dict_Train[Y] = batch[1]\r\n\r\n # TRAIN STEP\r\n train_step.run(feed_dict=feed_dict_Train)\r\n # end for loop\r\n\r\n correct_prediction = tf.equal(tf.argmax(predicted_Y, 1), tf.argmax(Y, 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n test_accuracy = accuracy.eval(feed_dict=feed_dict_Test)\r\n\r\n # End timer\r\n time_duration = timeit.default_timer() - start_time\r\n\r\n print(\"test accuracy: \", test_accuracy)\r\n print(\"test duration: \", time_duration)\r\n\r\n # Write to output file information about every run\r\n # Opening a file using the \"with open() as f\" is considered good practice when dealing with files.\r\n # \"with open\" ensures that the file is closed properly even if an exception is raised.\r\n # This is much shorter than writing equivalent try-catch-finally blocks\r\n with open('OutputRunsScript2AutomatedRuns.xls', 'a', newline='') as outfile:\r\n # Use Python's csv module to write to an output file with a tab-delimiter\r\n writer = csv.writer(outfile, delimiter='\\t')\r\n # The csv.writer.writerow function takes a single list as input,\r\n # and each column is an item in the list\r\n writer.writerow([test_accuracy, param['layers'], param['learning_rate'], param['beta1'],\r\n param['beta2'], param['epsilon'], param['batch_size'], time_duration, outputText])\r\n\r\n # Free up memory by closing the session\r\n sess.close()\r\n\r\n return (test_accuracy, time_duration)\r\n\r\n\r\ndef main():\r\n # Use 3 iterations for each set of parameters to get an average % accuracy\r\n num_iterations = 3\r\n\r\n # Define ranges for each of the values you can change.\r\n # numLayerRange specifies the range on the number of Hidden Layers.\r\n # I determined from script1_checkLayerShapes.py that 2 hidden layers is\r\n # the optimal number of layers for this project.\r\n # You can specify a range of values using the following syntax:\r\n # numLayerRange = range(2, 5, 1) # 3 iterations\r\n # The above example would use 2, 3, and 4 layers.\r\n # Note that range is non-inclusive of the maximum value specified. [2, 5)\r\n # I am going to just use the optimal number of layers, since I want to determine\r\n # what the other parameters should be.\r\n numLayerRange = [2, 3] # 2 iterations\r\n\r\n # layerSizeRange contains how many nodes can go in any layer\r\n # I want the range to be [20, 49, 98, 147, 196, ... 1568]\r\n # I cannot only set it to a range() value and have it give me what I want.\r\n # Instead I have to first initialize the list to 20,\r\n # and then extend with the range values.\r\n layerSizeRange = [20]\r\n layerSizeRange.extend(range(49, 1569, 49)) # 31 iterations\r\n\r\n # dropoutRange is True if use dropout and False otherwise\r\n dropoutRange = [True, False]\r\n\r\n # probRange is the dropout keep probability range\r\n # Have to use NumPy's arange function since these are decimal values\r\n probRange = np.arange(0.3, 1, 0.05) # 14 iterations\r\n\r\n # lambdaRange is the range for the lambda values for regularization\r\n # Have to use NumPy's arange function since these are decimal values\r\n lambdaRange = np.arange(0, 0.001, 0.0001) # 9 iterations\r\n\r\n # learnRange will use 2 ranges put together\r\n # Some configurations work well with larger learning rates.\r\n # Other configurations end up stuck in the \"0\" range of ReLU and\r\n # end up dying. These require smaller learning rates\r\n #\r\n # Have to use NumPy's arange function since these are decimal values\r\n learnRange = []\r\n learnRange.extend(np.arange(0.0001, 0.002, 0.0001)) # 19 iterations\r\n # Some configurations work better with larger learning rates\r\n learnRange.extend(np.arange(0.002, 0.05, 0.005)) # 9 iterations\r\n\r\n # Range for beta1\r\n # Have to use NumPy's arange function since these are decimal values\r\n beta1Range = np.arange(0.899, 1, 0.01) # 10 iterations\r\n\r\n # Range for beta2\r\n # Have to use NumPy's arange function since these are decimal values\r\n beta2Range = np.arange(0.5, 1, 0.05) # 10 iterations\r\n\r\n # Range for epsilon\r\n epsilonRange = [1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10,\r\n 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1] # 15 iterations\r\n\r\n # batchsizeRange holds the range for batch size\r\n batchsizeRange = range(1, 500, 50) # 9 iterations\r\n\r\n # paramRanges is a dictionary that holds the ranges for each key\r\n paramRanges = {\r\n \"numLayers\": numLayerRange,\r\n \"layer1\": layerSizeRange,\r\n \"layer2\": layerSizeRange,\r\n \"layer3\": layerSizeRange,\r\n \"layer4\": layerSizeRange,\r\n \"dropout1\": dropoutRange,\r\n \"dropout2\": dropoutRange,\r\n \"dropout3\": dropoutRange,\r\n \"dropout4\": dropoutRange,\r\n \"keep_prob1\": probRange,\r\n \"keep_prob2\": probRange,\r\n \"keep_prob3\": probRange,\r\n \"keep_prob4\": probRange,\r\n 'lambdaVal1': lambdaRange,\r\n 'lambdaVal2': lambdaRange,\r\n 'lambdaVal3': lambdaRange,\r\n 'lambdaVal4': lambdaRange,\r\n 'lambdaValOut': lambdaRange,\r\n 'learnRate': learnRange,\r\n 'beta1': beta1Range,\r\n 'beta2': beta2Range,\r\n 'epsilon': epsilonRange,\r\n 'batchsize': batchsizeRange\r\n }\r\n\r\n # initial guesses for best parameter values based on prior tests\r\n bestNumLayers = 3\r\n bestLayer1 = 1176\r\n bestLayer2 = 980\r\n bestLayer3 = 1323\r\n bestLayer4 = 20\r\n bestDropout1 = True\r\n bestDropout2 = True\r\n bestDropout3 = True\r\n bestDropout4 = True\r\n bestKeep_prob1 = 0.55\r\n bestKeep_prob2 = 0.7\r\n bestKeep_prob3 = 0.6\r\n bestKeep_prob4 = 0.6\r\n bestLambdaVal1 = 0\r\n bestLambdaVal2 = 0\r\n bestLambdaVal3 = 0\r\n bestLambdaVal4 = 0\r\n bestLambdaValOut = 0.005\r\n bestLearnRate = 0.001\r\n bestBeta1 = 0.9\r\n bestBeta2 = 0.999\r\n bestEpsilon = 1e-08\r\n bestBatchSize = 100\r\n\r\n # values to store after each run\r\n percent = 0 # Initialize to 0 and take the largest; iterate up from there\r\n\r\n # dictionary used to hold the best parameters for comparison\r\n bestParams = None\r\n\r\n # For output printing\r\n runCounter = 0\r\n\r\n # infinite loop\r\n while(True):\r\n runCounter += 1\r\n\r\n # Iterate through each parameter and range\r\n # Capture the values that give the highest % and use that as the new best value\r\n for key, rangeVal in paramRanges.items():\r\n # This iterates over each key/value pair in the paramRanges dictionary\r\n # For example, the first run might iterate over the lambdaVal2 range.\r\n # Next time through the for loop might iterate over the keep_prob1 range.\r\n\r\n # initialize all values for this run:\r\n numLayers = bestNumLayers\r\n layer1 = bestLayer1\r\n layer2 = bestLayer2\r\n layer3 = bestLayer3\r\n layer4 = bestLayer4\r\n dropout1 = bestDropout1\r\n dropout2 = bestDropout2\r\n dropout3 = bestDropout3\r\n dropout4 = bestDropout4\r\n keep_prob1 = bestKeep_prob1\r\n keep_prob2 = bestKeep_prob2\r\n keep_prob3 = bestKeep_prob3\r\n keep_prob4 = bestKeep_prob4\r\n lambdaVal1 = bestLambdaVal1\r\n lambdaVal2 = bestLambdaVal2\r\n lambdaVal3 = bestLambdaVal3\r\n lambdaVal4 = bestLambdaVal4\r\n lambdaValOut = bestLambdaValOut\r\n learnRate = bestLearnRate\r\n beta1 = bestBeta1\r\n beta2 = bestBeta2\r\n epsilon = bestEpsilon\r\n batchSize = bestBatchSize\r\n\r\n # Initialize list containing parameters for each run\r\n multipleRuns = []\r\n\r\n # Go through each value in the range we are looking at, and append to multipleRuns list\r\n for val in rangeVal:\r\n # Update numLayers before checking if we can skip the parameter if N/A for numLayers\r\n if key == \"numLayers\":\r\n # This means we are testing number of layers\r\n numLayers = val\r\n print(\"Key is numLayers: {}\".format(val))\r\n\r\n # Check if parameter is N/A based on numLayers\r\n # If we are currently testing with 2 layers and we are trying to iterate over a range\r\n # for a parameter that ends with 3 or 4, then we can skip this parameter and move on.\r\n if numLayers < 3:\r\n if key[-1:] in ['3', '4']:\r\n # No need to run change to parameter ending in 3 or 4 because don't have that many layers\r\n break\r\n\r\n # If we are currently testing with 2 or 3 layers and we are trying to iterate over a range\r\n # for a parameter that ends with 4, then we can skip this parameter and move on.\r\n if numLayers < 4:\r\n if key[-1:] in ['4']:\r\n # No need to run change to parameter ending in 4 because don't have that many layers\r\n break\r\n\r\n # Set appropriate variable to be the new value \"val\" from the range we are iterating over.\r\n if key == \"layer1\":\r\n layer1 = val\r\n print(\"Key is layer1: {}\".format(val))\r\n\r\n elif key == \"layer2\":\r\n layer2 = val\r\n print(\"Key is layer2: {}\".format(val))\r\n\r\n elif key == \"layer3\":\r\n layer3 = val\r\n print(\"Key is layer3: {}\".format(val))\r\n\r\n elif key == \"layer4\":\r\n layer4 = val\r\n print(\"Key is layer4: {}\".format(val))\r\n\r\n elif key == \"dropout1\":\r\n dropout1 = val\r\n print(\"Key is dropout1: {}\".format(val))\r\n\r\n elif key == \"dropout2\":\r\n dropout2 = val\r\n print(\"Key is dropout2: {}\".format(val))\r\n\r\n elif key == \"dropout3\":\r\n dropout3 = val\r\n print(\"Key is dropout3: {}\".format(val))\r\n\r\n elif key == \"dropout4\":\r\n dropout4 = val\r\n print(\"Key is dropout4: {}\".format(val))\r\n\r\n elif key == \"keep_prob1\":\r\n keep_prob1 = val\r\n print(\"Key is keep_prob1: {}\".format(val))\r\n\r\n elif key == \"keep_prob2\":\r\n keep_prob2 = val\r\n print(\"Key is keep_prob2: {}\".format(val))\r\n\r\n elif key == \"keep_prob3\":\r\n keep_prob3 = val\r\n print(\"Key is keep_prob3: {}\".format(val))\r\n\r\n elif key == \"keep_prob4\":\r\n keep_prob4 = val\r\n print(\"Key is keep_prob4: {}\".format(val))\r\n\r\n elif key == \"lambdaVal1\":\r\n lambdaVal1 = val\r\n print(\"Key is lambdaVal1: {}\".format(val))\r\n\r\n elif key == \"lambdaVal2\":\r\n lambdaVal2 = val\r\n print(\"Key is lambdaVal2: {}\".format(val))\r\n\r\n elif key == \"lambdaVal3\":\r\n lambdaVal3 = val\r\n print(\"Key is lambdaVal3: {}\".format(val))\r\n\r\n elif key == \"lambdaVal4\":\r\n lambdaVal4 = val\r\n print(\"Key is lambdaVal4: {}\".format(val))\r\n\r\n elif key == \"lambdaValOut\":\r\n lambdaValOut = val\r\n print(\"Key is lambdaValOut: {}\".format(val))\r\n\r\n elif key == \"learnRate\":\r\n learnRate = val\r\n print(\"Key is learnRate: {}\".format(val))\r\n\r\n elif key == \"beta1\":\r\n beta1 = val\r\n print(\"Key is beta1: {}\".format(val))\r\n\r\n elif key == \"beta2\":\r\n beta2 = val\r\n print(\"Key is beta2: {}\".format(val))\r\n\r\n elif key == \"epsilon\":\r\n epsilon = val\r\n print(\"Key is epsilon: {}\".format(val))\r\n\r\n elif key == \"batchSize\":\r\n batchSize = val\r\n print(\"Key is batchSize: {}\".format(val))\r\n\r\n elif key == \"numLayers\":\r\n pass # Do nothing; already handled this at the top of for loop\r\n\r\n else:\r\n print(\"WARNING: Unknown Key: {}\".format(key))\r\n break\r\n\r\n # Append values to multipleRuns based on numLayers\r\n #\r\n # multipleRuns is a list of dictionaries.\r\n # Each dictionary is for a different run of the algorithm.\r\n # Dictionaries are a data structure that use a key/value pair.\r\n #\r\n # The following are global parameters for the run:\r\n # learning_rate\r\n # batch_size\r\n #\r\n # The other parameters are layer specific.\r\n # The 'layers' key has a list as its value.\r\n # The layers list consists of multiple dictionaries, one for each layer.\r\n # Each layer must specify the following:\r\n # layerSize: number of nodes in that layer\r\n # dropoutFlag: True, False\r\n # nodeType: \"ReLU\", \"Sigmoid\", \"Linear\"\r\n # regLambda: Lambda values for that layer\r\n # keep_prob: dropout keep probability for that layer\r\n if numLayers == 2:\r\n print(\"Number Layers is 2\")\r\n multipleRuns.append({'learning_rate': learnRate, 'beta1': beta1, 'beta2': beta2, 'epsilon': epsilon, 'batch_size': batchSize,\r\n 'layers': [\r\n {'layerSize': layer1, 'dropoutFlag': dropout1,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal1, 'keep_prob': keep_prob1},\r\n {'layerSize': layer2, 'dropoutFlag': dropout2,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal2, 'keep_prob': keep_prob2},\r\n {'layerSize': 10, 'dropoutFlag': False,\r\n 'nodeType': \"Linear\", 'regLambda': lambdaValOut, 'keep_prob': 1}\r\n ]})\r\n elif numLayers == 3:\r\n print(\"Number Layers is 3\")\r\n multipleRuns.append({'learning_rate': learnRate, 'beta1': beta1, 'beta2': beta2, 'epsilon': epsilon, 'batch_size': batchSize,\r\n 'layers': [\r\n {'layerSize': layer1, 'dropoutFlag': dropout1,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal1, 'keep_prob': keep_prob1},\r\n {'layerSize': layer2, 'dropoutFlag': dropout2,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal2, 'keep_prob': keep_prob2},\r\n {'layerSize': layer3, 'dropoutFlag': dropout3,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal3, 'keep_prob': keep_prob3},\r\n {'layerSize': 10, 'dropoutFlag': False,\r\n 'nodeType': \"Linear\", 'regLambda': lambdaValOut, 'keep_prob': 1}\r\n ]})\r\n elif numLayers == 4:\r\n print(\"Number Layers is 4\")\r\n multipleRuns.append({'learning_rate': learnRate, 'beta1': beta1, 'beta2': beta2, 'epsilon': epsilon, 'batch_size': batchSize,\r\n 'layers': [\r\n {'layerSize': layer1, 'dropoutFlag': dropout1,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal1, 'keep_prob': keep_prob1},\r\n {'layerSize': layer2, 'dropoutFlag': dropout2,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal2, 'keep_prob': keep_prob2},\r\n {'layerSize': layer3, 'dropoutFlag': dropout3,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal3, 'keep_prob': keep_prob3},\r\n {'layerSize': layer4, 'dropoutFlag': dropout4,\r\n 'nodeType': \"ReLU\", 'regLambda': lambdaVal4, 'keep_prob': keep_prob4},\r\n {'layerSize': 10, 'dropoutFlag': False,\r\n 'nodeType': \"Linear\", 'regLambda': lambdaValOut, 'keep_prob': 1}\r\n ]})\r\n else:\r\n print(\"INVALID # LAYERS: {}\".format(numLayers))\r\n sys.exit(1)\r\n\r\n # At this point in the code, All values in the current range have been appended to multipleRuns\r\n\r\n # tmpMaxPercent holds the current best accuracy\r\n tmpMaxPercent = percent\r\n\r\n # tmpParams holds the best parameters if I find a better accuracy\r\n tmpParams = None\r\n\r\n # tmpTime holds the time value for the best parameters if I find a better accuracy.\r\n # This is only used in the output file.\r\n tmpTime = None\r\n\r\n # Flag to exit early if we are testing Learning Rate and encounter percentages < 0.1\r\n # This is when we get stuck in the \"0\" region of ReLU\r\n exitDueToLearningRate = False\r\n\r\n # Enumerate over all of the runs\r\n for idx, params in enumerate(multipleRuns):\r\n # Zero out the average percent.\r\n # This is used to get the average percentage over num_iterations of the same parameters.\r\n # I want to find parameters that on average give a high percentage for my project presentation.\r\n avgPercent = 0\r\n\r\n # Run over num_iterations to get a good average for these parameters\r\n for i in range(0, num_iterations):\r\n # Print information about the current run\r\n print(\"On iteration {} of {} using parameters for run {} of {} for {}\".format(\r\n i + 1, num_iterations, idx + 1, len(multipleRuns), key))\r\n\r\n # Run algorithm\r\n tmpPercent, tmpTimeVal = runAlgorithm(\r\n params, \"Automated individual run on iteration {} of {} for {}\".format(i + 1, num_iterations, key))\r\n\r\n # increase avgPercent with the percent just found\r\n avgPercent += tmpPercent\r\n\r\n # If the percent we just found is greater than the previous max percent:\r\n # - Set tmpMaxPercent = percent we just found\r\n # - Set tmpParams = params we just ran with\r\n # - Set tmpTime = time it just took\r\n if tmpPercent > tmpMaxPercent:\r\n print(\"Found larger percent: {} > {}\".format(tmpPercent, tmpMaxPercent))\r\n tmpMaxPercent = tmpPercent\r\n tmpParams = None # Clear it out before copying over\r\n tmpParams = params\r\n tmpTime = tmpTimeVal # used just for output file\r\n\r\n # Check if we are in the \"0\" region of ReLU AND we are testing on learning rate\r\n if (tmpPercent < 0.1) and (key == \"learnRate\"):\r\n # Reached 0 region in the ReLU, and it will not escape\r\n # Continuing to take the learning rate higher will not improve\r\n exitDueToLearningRate = True\r\n print(\r\n \"Stopping iteration over learning rate values since percent is < 0.1: {}\".format(tmpPercent))\r\n\r\n # Print out the average percent accuracy and current parameters.\r\n # Opening a file using the \"with open() as f\" is considered good practice when dealing with files.\r\n # \"with open\" ensures that the file is closed properly even if an exception is raised.\r\n # This is much shorter than writing equivalent try-catch-finally blocks\r\n with open('OutputRunsScript2AverageParams.xls', 'a', newline='') as outfile:\r\n # Use Python's csv module to write to an output file with a tab-delimiter\r\n writer = csv.writer(outfile, delimiter='\\t')\r\n # The csv.writer.writerow function takes a single list as input,\r\n # and each column is an item in the list\r\n writer.writerow(\r\n [avgPercent / num_iterations, params, tmpTime, \"Average Parameters on run {} for {}\".format(runCounter, key)])\r\n\r\n # If in \"0\" region of ReLU, break out of loop and move onto another parameter\r\n if exitDueToLearningRate:\r\n break\r\n\r\n # If found a better accuracy, then update values accordingly\r\n if tmpParams is not None:\r\n # Update max percent\r\n percent = tmpMaxPercent\r\n\r\n # Update best parameters\r\n bestParams = tmpParams\r\n\r\n # Update Best values for the parameter we are testing\r\n if key == \"layer1\":\r\n # extract layerSize for layer1 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLayer1 = bestParams['layers'][0]['layerSize']\r\n\r\n if key == \"layer2\":\r\n # extract layerSize for layer2 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLayer2 = bestParams['layers'][1]['layerSize']\r\n\r\n if key == \"layer3\":\r\n # extract layerSize for layer3 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLayer3 = bestParams['layers'][2]['layerSize']\r\n\r\n if key == \"layer4\":\r\n # extract layerSize for layer4 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLayer4 = bestParams['layers'][3]['layerSize']\r\n\r\n if key == \"dropout1\":\r\n # extract dropoutFlag for dropout1 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestDropout1 = bestParams['layers'][0]['dropoutFlag']\r\n\r\n if key == \"dropout2\":\r\n # extract dropoutFlag for dropout2 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestDropout2 = bestParams['layers'][1]['dropoutFlag']\r\n\r\n if key == \"dropout3\":\r\n # extract dropoutFlag for dropout3 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestDropout3 = bestParams['layers'][2]['dropoutFlag']\r\n\r\n if key == \"dropout4\":\r\n # extract dropoutFlag for dropout4 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestDropout4 = bestParams['layers'][3]['dropoutFlag']\r\n\r\n if key == \"keep_prob1\":\r\n # extract keep_prob for keep_prob1 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestKeep_prob1 = bestParams['layers'][0]['keep_prob']\r\n\r\n if key == \"keep_prob2\":\r\n # extract keep_prob for keep_prob2 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestKeep_prob2 = bestParams['layers'][1]['keep_prob']\r\n\r\n if key == \"keep_prob3\":\r\n # extract keep_prob for keep_prob3 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestKeep_prob3 = bestParams['layers'][2]['keep_prob']\r\n\r\n if key == \"keep_prob4\":\r\n # extract keep_prob for keep_prob4 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestKeep_prob4 = bestParams['layers'][3]['keep_prob']\r\n\r\n if key == \"lambdaVal1\":\r\n # extract regLambda for lambdaVal1 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLambdaVal1 = bestParams['layers'][0]['regLambda']\r\n\r\n if key == \"lambdaVal2\":\r\n # extract regLambda for lambdaVal2 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLambdaVal2 = bestParams['layers'][1]['regLambda']\r\n\r\n if key == \"lambdaVal3\":\r\n # extract regLambda for lambdaVal3 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLambdaVal3 = bestParams['layers'][2]['regLambda']\r\n\r\n if key == \"lambdaVal4\":\r\n # extract regLambda for lambdaVal4 from bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLambdaVal4 = bestParams['layers'][3]['regLambda']\r\n\r\n if key == \"lambdaValOut\":\r\n # extract regLambda from the last layer of bestParams\r\n # convoluted syntax is due to nested data structures\r\n bestLambdaValOut = bestParams['layers'][len(\r\n bestParams['layers']) - 1]['regLambda']\r\n\r\n if key == \"learnRate\":\r\n # extract learning_rate from bestParams\r\n bestLearnRate = bestParams['learning_rate']\r\n\r\n if key == \"beta1\":\r\n # extract beta1 from bestParams\r\n bestBeta1 = bestParams['beta1']\r\n\r\n if key == \"beta2\":\r\n # extract beta2 from bestParams\r\n bestBeta2 = bestParams['beta2']\r\n\r\n if key == \"epsilon\":\r\n # extract epsilon from bestParams\r\n bestEpsilon = bestParams['epsilon']\r\n\r\n if key == \"batchSize\":\r\n # extract batch_size from bestParams\r\n bestBatchSize = bestParams['batch_size']\r\n\r\n # Write the best parameters to output file\r\n # Opening a file using the \"with open() as f\" is considered good practice when dealing with files.\r\n # \"with open\" ensures that the file is closed properly even if an exception is raised.\r\n # This is much shorter than writing equivalent try-catch-finally blocks\r\n with open('OutputRunsScript2BestParams.xls', 'a', newline='') as outfile:\r\n # Use Python's csv module to write to an output file with a tab-delimiter\r\n writer = csv.writer(outfile, delimiter='\\t')\r\n # The csv.writer.writerow function takes a single list as input,\r\n # and each column is an item in the list\r\n writer.writerow(\r\n [percent, bestParams, tmpTime, \"Best Parameters on run {} for {}\".format(runCounter, key)])\r\n\r\n\r\n# Call the main function\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"script2_Adamautomated.py","file_name":"script2_Adamautomated.py","file_ext":"py","file_size_in_byte":40171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563965023","text":"\n# coding: utf-8\n\n# In[54]:\n\n#All imports\nget_ipython().magic('matplotlib inline')\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#plt.rcParams['figure.figsize']=(20,0,10,0)\n\n\n# In[56]:\n\n#Reading the data of headbrain.csv file \ndata = pd.read_csv('E:\\Python Data Science\\MYWORK\\headbrain.csv')\n#print(data.Gender)\ndata.head()\n\n\n# In[57]:\n\n#Collect the particular value from the CSV file and assigned to X and Y\nX = data['Head Size(cm^3)'].values\nY = data['Brain Weight(grams)'].values\n#Y\n#X\n\n\n# In[94]:\n\n#find the mean valu of X and Y\nmean_x = np.mean(X)\nmean_y = np.mean(Y)\n#mean_x\n#mean_y\n\n\n# In[98]:\n\n#So now find the total number of values of X\nn = len(X)\n#n\n\n\n# In[38]:\n\n#Calculate the value of b1 and b0,i mean m(coef) and c(intercept) respectivly using the formula...\n# y = mx + c or y = c + mx or y = b0 + b1*x or y = b1*x + b0 \n# b1 = sum of (X[i]-mean_x)*(Y[i]-mean_y)/sum of (X[i]-mean_x)**2\n# b0 = mean_y-(b1 * mean_x)\n\nnumber = 0\ndenom = 0\nfor i in range(n):\n number += (X[i]-mean_x)*(Y[i]-mean_y)\n denom += (X[i]-mean_x)**2\nb1 = number/denom\nb0 = mean_y-(b1 * mean_x)\n\n#Print cofficients\nprint(b1,b0)\n \n\n\n# In[115]:\n\n#Ploting values and regression line\n\nmax_x = np.max(X) + 100\nmin_x = np.min(X) - 100\nmin_x\n\n\n# In[106]:\n\n#calculate the line value of X and Y\nx = np.linspace(min_x,max_x,1000)\ny = b0 + b1*x\n\n\n# In[107]:\n\n#ploting line\nplt.plot(x,y, color='blue', label='Linear Regression')\n#ploting scatter points\nplt.scatter(X,Y, c='#ef5423', label='Scatter Plot')\nplt.xlabel('Head Size')\nplt.ylabel('Brain Weight')\nplt.legend()\nplt.show()\n\n\n# In[116]:\n\n#now find R2 ,how efficient the linear regession line is ?\ntss_t = 0\ntss_r = 0\nfor i in range(n):\n y_pred = b0+b1*X[i]\n tss_r+=(Y[i]-y_pred)**2\n tss_t+=(Y[i]-mean_y)**2\n \nr2=1-(tss_r/tss_t)\nprint(r2)\n\n\n# In[ ]:\n\n#so we can see the both of the R2 score is same...which is 0.639311719957\n\n\n# In[110]:\n\n#now we will see the machine learning library which is sklearn.LinearModel\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\nX = X.reshape((n,1))\n#create model\nreg = LinearRegression()\n#filtering training data\nreg = reg.fit(X,Y)\n#Y prediction\nY_pred = reg.predict(X)\n#calculating RMSE R2 score\nmse = mean_squared_error(Y,Y_pred)\nrmse = np.sqrt(mse)\nr2_score = reg.score(X,Y)\nprint(np.sqrt(mse))\nprint(r2_score)\n\n\n# In[ ]:\n\n#so we can see the both of the R2 score is same...which is 0.639311719957\n\n","sub_path":"LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"585322249","text":"#----------------------------------------------------------------------\r\n# Copyright (c) 2013, Guy Carver\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without modification,\r\n# are permitted provided that the following conditions are met:\r\n#\r\n# * Redistributions of source code must retain the above copyright notice,\r\n# this list of conditions and the following disclaimer.\r\n#\r\n# * Redistributions in binary form must reproduce the above copyright notice,\r\n# this list of conditions and the following disclaimer in the documentation\r\n# and/or other materials provided with the distribution.\r\n#\r\n# * The name of Guy Carver may not be used to endorse or promote products # derived#\r\n# from # this software without specific prior written permission.#\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\r\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n#\r\n# FILE VisualStudio.py\r\n# BY Guy Carver\r\n# DATE 06/05/2013 09:06 PM\r\n#----------------------------------------------------------------------\r\n\r\nimport sublime, sublime_plugin\r\nimport functools\r\nimport sys, os\r\nimport re\r\n\r\npackagepath = os.path.dirname(__file__)\r\n#print(packagepath)\r\n\r\n'''Python3.3.5 and pywin32-220 must be installed on the computer for this plugin to work.\r\n If they are not you will get import errors.'''\r\n\r\nsys.path.append(packagepath + \"\\\\pywin32\")\r\nsys.path.append(packagepath + \"\\\\pywin32\\\\win32\")\r\nsys.path.append(packagepath + \"\\\\pywin32\\\\win32\\\\lib\")\r\nsys.path.append(packagepath + \"\\\\pywin32\\\\pythonwin\")\r\n\r\n#print(sys.path)\r\n\r\nimport VisualStudio.pywin32.win32com.client as win32\r\nimport win32gui\r\n\r\ndte_settings = None\r\n\r\nStepPause = .2\r\n\r\ndef plugin_loaded( ) :\r\n global dte_settings\r\n dte_settings = sublime.load_settings(\"VisualStudio.sublime-settings\")\r\n\r\nclass MyDTE :\r\n def __init__( self, ExHandler = None ) :\r\n try:\r\n self.ex = ExHandler\r\n v = dte_settings.get(\"version\", \"15.0\")\r\n objectName = \"VisualStudio.DTE.\" + v\r\n# print(\"Getting DTE \" + objectName)\r\n #Might need to do this to ensure the com interface is generated.\r\n #win32.gencache.EnsureDispatch(objectName)\r\n self.dte = win32.GetActiveObject(objectName)\r\n except Exception as ve:\r\n if self.ex :\r\n self.ex(ve)\r\n print(ve)\r\n self.dte = None\r\n\r\n def __enter__( self ) :\r\n return self.dte\r\n\r\n def __exit__( self, type, value, traceback ) :\r\n #If we had and exception pass to the handler.\r\n if value != None and self.ex != None :\r\n self.ex(value)\r\n return True\r\n\r\ndef GetAllBreakpoints( ) :\r\n with MyDTE() as dte :\r\n return dte.Debugger.Breakpoints\r\n return [] #return an empty list.\r\n\r\ndef GetBreakpoints( aView, aOn ) :\r\n with MyDTE() as dte :\r\n deb = dte.Debugger\r\n if deb.BreakPoints :\r\n fname = format(aView.file_name()).lower()\r\n return [ brk for brk in deb.Breakpoints if ((fname == brk.File.lower()) and (brk.Enabled == aOn)) ]\r\n return [] #return an empty list.\r\n\r\ndef ShowBreakpoints( aView, aList, aType, aColor ) :\r\n aView.erase_regions(aType)\r\n if aList :\r\n g = lambda line: aView.line(aView.text_point(line - 1, 0))\r\n regs = [ g(brk.FileLine) for brk in aList ]\r\n aView.add_regions(aType, regs, aColor, \"dot\", sublime.HIDDEN)\r\n\r\ndef UpdateBreakpoints( aView ) :\r\n if aView.file_name() and dte_settings.get(\"showbreakpoints\") :\r\n bon = GetBreakpoints(aView, True)\r\n oncolor = dte_settings.get(\"bpointoncolor\", \"red\")\r\n# print(\"On: \" + str(len(bon)))\r\n ShowBreakpoints(aView, bon, \"breakon\", oncolor)\r\n boff = GetBreakpoints(aView, False)\r\n offcolor = dte_settings.get(\"bpointoffcolor\", \"gray\")\r\n ShowBreakpoints(aView, boff, \"breakoff\", offcolor)\r\n\r\ndef SetFileAndLine( aDTE, aView ) :\r\n # print(\"filename \" + aView.file_name())\r\n res = aDTE.ExecuteCommand(\"File.OpenFile\", aView.file_name())\r\n if res == None :\r\n sel = aView.sel()[0]\r\n line, _ = aView.rowcol(sel.begin())\r\n line = line + 1\r\n# print \"line %d\" % (line)\r\n res = aDTE.ExecuteCommand(\"Edit.Goto\", str(line))\r\n\r\n # print(\"res \" + str(res))\r\n return res\r\n\r\nclass DteSelectBreakpointCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n brks = GetAllBreakpoints()\r\n brkdata = [ b.File + \":\" + str(b.FileLine) for b in brks ]\r\n self.window.show_quick_panel(brkdata, functools.partial(self.on_done, brkdata))\r\n\r\n def on_done( self, aBreaks, aIndex ) :\r\n if aIndex != -1 :\r\n path = aBreaks[aIndex]\r\n vw = self.window.open_file(path, sublime.ENCODED_POSITION)\r\n\r\nclass DteToggleBreakpointCommand( sublime_plugin.TextCommand ) :\r\n def run( self, edit ) :\r\n with MyDTE(lambda x : sublime.status_message(\"ToggleBreakPoint failed\")) as dte :\r\n # print(\"Setting file and line.\")\r\n res = SetFileAndLine(dte, self.view)\r\n if res == None :\r\n # print(\"ToggleBreakPoint\")\r\n dte.ExecuteCommand(\"Debug.ToggleBreakPoint\", \"\")\r\n # print(\"UpdatingBreakPoint\")\r\n UpdateBreakpoints(self.view)\r\n\r\nclass DteEnableBreakpointCommand( sublime_plugin.TextCommand ) :\r\n def run( self, edit ) :\r\n with MyDTE(lambda x : sublime.status_message(\"EnableBreakPoint failed\")) as dte :\r\n # print(\"Setting file and line.\")\r\n res = SetFileAndLine(dte, self.view)\r\n if res == None :\r\n # print(\"ToggleBreakPoint\")\r\n dte.ExecuteCommand(\"Debug.EnableBreakPoint\", \"\")\r\n # print(\"UpdatingBreakPoint\")\r\n UpdateBreakpoints(self.view)\r\n\r\nclass DteSetFileLineCommand( sublime_plugin.TextCommand ) :\r\n def run( self, edit ) :\r\n with MyDTE(lambda x : sublime.status_message(\"SetFileAndLine failed\")) as dte :\r\n # print(\"Setting fileandline\")\r\n SetFileAndLine(dte, self.view)\r\n\r\ncompileFileName = re.compile(\"^.*Compile:[ \\t]+([\\w.]*).*\", re.MULTILINE | re.IGNORECASE)\r\n\r\n#If on a secondary file attempt to find the main .cpp file to compile. Either change filename extension to\r\n# .cpp or find the filename in the Compile: field of the file header.\r\nclass DteCompilecppCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n vw = self.window.active_view()\r\n if not vw.is_scratch() :\r\n if vw.is_dirty():\r\n vw.run_command(\"save\")\r\n\r\n fname = self.FindCompileFileName(vw)\r\n if not fname :\r\n fname = vw.file_name()\r\n #Get file name and make sure extension is .cpp.\r\n if fname :\r\n fpath, fext = os.path.splitext(fname)\r\n fname = fpath + '.cpp'\r\n# print(\"opening \" + fname)\r\n with MyDTE(lambda x : sublime.status_message(\"Compile failed\")) as dte :\r\n res = dte.ExecuteCommand(\"File.OpenFile\", fname)\r\n if res == None :\r\n dte.ExecuteCommand(\"Build.Compile\", \"\")\r\n else :\r\n print(\"Failed to compile \" + fname)\r\n\r\n #Look for Compile: in the header and use the filename indicated by that to compile instead of current file.\r\n def FindCompileFileName( self, vw ) :\r\n #This may be temporary. Need to use a comment range perhaps?\r\n name = None\r\n hr = vw.extract_scope(1)\r\n lt = vw.substr(hr)\r\n# print(\"testing \" + lt)\r\n match = compileFileName.search(lt)\r\n if (match != None) :\r\n name = match.group(1)\r\n# print(\"Compile: \" + name)\r\n\r\n return name\r\n\r\nclass DteCommandCommand( sublime_plugin.TextCommand ) :\r\n def run( self, edit, command, syncfile = True, save = False ) :\r\n with MyDTE(lambda x : sublime.status_message(str(x))) as dte :\r\n if save and self.view.is_dirty():\r\n self.view.run_command(\"save\")\r\n\r\n if syncfile :\r\n SetFileAndLine(dte, self.view)\r\n\r\n res = dte.ExecuteCommand(command, \"\")\r\n\r\ndef SyncFileLine( aDTE, aWindow ) :\r\n doc = aDTE.ActiveDocument\r\n if doc :\r\n textDoc = doc.Object(\"TextDocument\")\r\n sel = textDoc.Selection\r\n tp = sel.TopPoint\r\n line = tp.Line\r\n path = doc.FullName + \":\" + str(line)\r\n vw = aWindow.open_file(path, sublime.ENCODED_POSITION)\r\n # This doesn't currently work.\r\n # if vw:\r\n # while (vw.is_loading()) :\r\n # pass\r\n # UpdateBreakpoints(vw)\r\n\r\nclass DteStepIntoCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n with MyDTE(lambda x : sublime.status_message(\"StepInto failed\")) as dte :\r\n deb = dte.Debugger\r\n if deb.StepInto(False) == None :\r\n time.sleep(StepPause)\r\n SyncFileLine(dte, self.window)\r\n# print \"res %d\" % (res)\r\n\r\nclass DteStepOverCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n with MyDTE(lambda x : sublime.status_message(\"StepOver failed\")) as dte :\r\n deb = dte.Debugger\r\n if deb.StepOver(False) == None :\r\n time.sleep(StepPause)\r\n SyncFileLine(dte, self.window)\r\n# print \"res %d\" % (res)\r\n\r\nclass DteStepOutCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n with MyDTE(lambda x : sublime.status_message(\"StepOut failed\")) as dte :\r\n deb = dte.Debugger\r\n if deb.StepOut(False) == None :\r\n time.sleep(StepPause)\r\n SyncFileLine(dte, self.window)\r\n# print \"res %d\" % (res)\r\n\r\nclass DteSyncFileLineCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n with MyDTE(lambda x : sublime.status_message(\"SyncFileLine failed\")) as dte :\r\n SyncFileLine(dte, self.window)\r\n\r\nclass DteBreakUpdater(sublime_plugin.EventListener):\r\n def on_activated( self, view ) :\r\n UpdateBreakpoints(view)\r\n\r\nclass DtePickCmdCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n #todo: Make a list of commands.\r\n def err( ex ) : sublime.status_message(\"PickCommand failed\")\r\n with MyDTE(err) as dte :\r\n cmds = [ cmd.Name\r\n for cmd in dte.Commands\r\n if cmd.Name != ''\r\n ]\r\n# print(cmds)\r\n #Show Selection\r\n self.window.show_quick_panel(cmds, functools.partial(self.on_done, cmds))\r\n\r\n def on_done( self, aCommands, aIndex ) :\r\n if aIndex != -1 :\r\n def err( ex ) : sublime.status_message(str(ex))\r\n with MyDTE(err) as dte :\r\n command = aCommands[aIndex]\r\n #Run command\r\n res = dte.ExecuteCommand(command, \"\")\r\n sublime.status_message(command + \" returned \" + str(res))\r\n # print \"%s\" % aCommands[aIndex]\r\n\r\nclass FindWindowCommand(sublime_plugin.WindowCommand) :\r\n def run( self ) :\r\n self._handle = None\r\n wildcard = \"80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2x0x8x0\"\r\n# wildcard = \"Microsoft Visual Studio\"\r\n win32gui.EnumWindows(self._window_enum_callback, wildcard)\r\n if self._handle != None:\r\n win32gui.BringWindowToTop(self._handle)\r\n\r\n def _window_enum_callback(self, hwnd, wildcard):\r\n if (win32gui.GetWindowText(hwnd) == wildcard) :\r\n self._handle = hwnd\r\n\r\nclass DteDirCommand( sublime_plugin.WindowCommand ) :\r\n def run( self ) :\r\n #todo: Make a list of commands.\r\n def err( ex ) : sublime.status_message(\"DteDirCommand failed\")\r\n with MyDTE(err) as dte :\r\n print(dir(dte))\r\n\r\n","sub_path":"VisualStudio.py","file_name":"VisualStudio.py","file_ext":"py","file_size_in_byte":11637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"223031184","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : oom\nDate : 2020-06-11\nPurpose: Rock the Casbah\n\"\"\"\n\nimport argparse\n\n\n# ----------------------------------------------------------------------------\ndef get_args():\n \"\"\"Get command-line arguments\"\"\"\n\n parser = argparse.ArgumentParser(\n description='Gashlycrumb',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('letter',\n metavar=\"letter\",\n nargs=\"+\",\n help='Letter(s)')\n\n parser.add_argument('-f',\n '--file',\n help='Input file',\n metavar='FILE',\n type=argparse.FileType('r'),\n default=open('gashlycrumb.txt'))\n\n return parser.parse_args()\n\n\n# ----------------------------------------------------------------------------\ndef main():\n \"\"\"Make a jazz noise here\"\"\"\n\n args = get_args()\n letters = args.letter\n fh = args.file\n\n # Create dictionary from file:\n gashlycrumb = dict()\n for line in fh:\n gashlycrumb[line[0].lower()] = line\n\n # Loop over letter and show the dict entry\n for letter in letters:\n if letter.lower() in gashlycrumb:\n print(gashlycrumb[letter.lower()], end=\"\")\n else:\n print(f\"I do not know \\\"{letter}\\\".\")\n\n# ----------------------------------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"07_gashlycrumb/gashlycrumb.py","file_name":"gashlycrumb.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"213657642","text":"import re\nfrom collections import Counter\nfrom distutils.util import strtobool\n\nimport click\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental.preprocessing import \\\n TextVectorization\nfrom tqdm import tqdm\n\ntf.get_logger().setLevel(\"ERROR\")\n\nnp.random.seed(42)\n\nN = 929606\n\n\ndef preprocess_embedding_from_NILC(embedding_path_origin: str, embed_dim: int):\n # Pré-processa embedding baseado na lista 04\n with open(f\"data/cbow_s{embed_dim}.txt\", \"r\") as file:\n head = [next(file) for x in range(N)]\n\n head[0] = str(N - 1) + \" \" + f\"{embed_dim}\" + \"\\n\" # Conserta contagem de palavras\n vocab = set()\n with open(f\"data/word2vec_{embed_dim}dim_200k.txt\", \"w\") as file:\n i = 0\n iter_rows = iter(head)\n next(iter_rows)\n for line in tqdm(\n iter_rows, total=N, desc=\"Preprocessing Embeddings from NILC file\"\n ):\n word_vector = line.split()\n word = word_vector[0]\n embedding = word_vector[1:]\n if len(embedding) != embed_dim:\n print(f\"word line {i} is corrupt, skipping it.\")\n continue\n i += 1\n if word in vocab:\n continue\n vocab.add(word)\n file.write(line)\n return None\n\n\ndef filtro(b2wCorpus: pd.DataFrame) -> pd.DataFrame:\n df = b2wCorpus[[\"review_text\", \"overall_rating\"]].copy()\n df = df[df[\"overall_rating\"].isin([0, 1, 2, 3, 4, 5])]\n return df.reset_index(drop=True)\n\n\ndef partilha(\n path_original_dataset: str,\n train_proportion=0.65,\n val_proportion=0.1,\n test_proportion=0.25,\n sep=\";\",\n) -> pd.DataFrame:\n if (train_proportion + val_proportion + test_proportion) != 1:\n raise ValueError(\"Train, Validation and Test size should always be 1\")\n\n b2wCorpus = pd.read_csv(path_original_dataset, sep=sep)\n df = filtro(b2wCorpus)\n X_train, X_val, y_train, y_val = train_test_split(\n df[\"review_text\"],\n df[\"overall_rating\"],\n train_size=0.8,\n random_state=42,\n stratify=df[\"overall_rating\"],\n )\n\n train_df = pd.DataFrame([X_train, y_train]).T\n val_df = pd.DataFrame([X_val, y_val]).T\n X_val, X_test, y_val, y_test = train_test_split(\n val_df[\"review_text\"],\n val_df[\"overall_rating\"],\n train_size=val_proportion / (val_proportion + test_proportion),\n random_state=42,\n stratify=val_df[\"overall_rating\"],\n )\n val_df = pd.DataFrame([X_val, y_val]).T\n test_df = pd.DataFrame([X_test, y_test]).T\n assert len(df) == (len(train_df) + len(val_df) + len(test_df))\n train_df.to_csv(\"data/train.csv\", index=False)\n val_df.to_csv(\"data/validation.csv\", index=False)\n test_df.to_csv(\"data/test.csv\", index=False)\n return None\n\n\ndef gera_embeddings(path: str, embed_dim=50) -> np.ndarray:\n \"\"\"\n This function gets the NILC embeddings and store it\n as a numpy matrix\n All words are going to be initialized as zero and then\n they are modified according to specific vector\n \"\"\"\n # embedding_matrix = np.zeros((N, embed_dim))\n with open(path, \"r\") as file:\n i = 0\n embed_matrix = [np.zeros((2, embed_dim))]\n embed_vocab = []\n for line in tqdm(file, total=N, desc=\"Generating Embedding Matrix\"):\n splitted_words = line.split()\n embed_matrix.append(np.array(splitted_words[1:]).reshape(1, -1))\n embed_vocab.append(splitted_words[0])\n i += 1\n embed_matrix = np.vstack(embed_matrix)\n return embed_matrix, embed_vocab\n\n\ndef codifica(\n train_df_text: pd.Series, tammax: int, embed_dim: int\n) -> (TextVectorization, np.ndarray):\n embed_matrix, embed_vocab = gera_embeddings(\n f\"data/word2vec_{embed_dim}dim_200k.txt\"\n )\n tokenizer_layer = TextVectorization(\n max_tokens=len(embed_vocab) + 2, # OOV and 0 is used for mask\n standardize=\"lower_and_strip_punctuation\",\n split=\"whitespace\",\n ngrams=None,\n output_mode=\"int\",\n output_sequence_length=tammax,\n )\n tokenizer_layer.set_vocabulary(\n embed_vocab\n ) # we need to set it to follow the same input matrix\n\n return tokenizer_layer, embed_matrix, embed_vocab\n\n\ndef cria_modelo(\n embed_matrix: np.ndarray,\n tokenizer_layer: TextVectorization,\n lstm_units: int,\n use_birectional: bool,\n dropout_rate: float,\n) -> keras.Model:\n vocab_size = embed_matrix.shape[0]\n embed_dim = embed_matrix.shape[1]\n inputs = layers.Input(shape=(1,), dtype=tf.string, name=\"input_text\")\n embedding_layer = layers.Embedding(\n input_dim=vocab_size,\n output_dim=embed_dim,\n weights=[embed_matrix],\n trainable=False,\n )\n lstm_layer = tf.keras.layers.LSTM(\n units=lstm_units,\n activation=\"tanh\",\n kernel_initializer=\"glorot_uniform\",\n )\n bidirectional_layer = tf.keras.layers.Bidirectional(lstm_layer)\n dropout_layer = layers.Dropout(dropout_rate)\n output_layer = layers.Dense(6, activation=\"softmax\")\n\n x = tokenizer_layer(inputs)\n x = embedding_layer(x)\n if use_birectional:\n x = bidirectional_layer(x)\n else:\n x = lstm_layer(x)\n x = dropout_layer(x)\n outputs = output_layer(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n print(model.summary())\n return model\n\n\ndef treina_modelo(model: keras.Model, df_train: pd.DataFrame, df_val: pd.DataFrame):\n batch_size = 32\n steps_per_epoch = len(df_train) // batch_size\n my_callbacks = [\n tf.keras.callbacks.EarlyStopping(patience=1, restore_best_weights=True),\n tf.keras.callbacks.ModelCheckpoint(\n filepath=\"data/logs/mymodel_{epoch}\",\n save_best_only=True,\n monitor=\"val_loss\",\n ),\n ]\n lr_schedule = tf.keras.optimizers.schedules.InverseTimeDecay(\n 0.001, decay_steps=steps_per_epoch * 50, decay_rate=0.5, staircase=False\n )\n\n model.compile(\n optimizer=tf.keras.optimizers.Adam(lr_schedule),\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"accuracy\"],\n )\n history = model.fit(\n df_train[\"review_text\"].values,\n df_train[\"overall_rating\"].values,\n batch_size=batch_size,\n epochs=100,\n validation_data=(df_val[\"review_text\"].values, df_val[\"overall_rating\"].values),\n validation_freq=5,\n callbacks=my_callbacks,\n workers=8,\n shuffle=True,\n verbose=1,\n )\n return history\n\n\ndef aplica_treinamento(train_df, val_df, use_birectional, dropout_rate, embed_matrix):\n print(\n f\"Aplicando treinamento com birectional {use_birectional} \"\n f\"e taxa de dropout em {dropout_rate}\"\n )\n tokenizer_layer, embed_matrix, embed_vocab = codifica(\n train_df_text=train_df[\"review_text\"], tammax=256, embed_dim=50\n )\n model = cria_modelo(\n embed_matrix,\n tokenizer_layer,\n lstm_units=32,\n use_birectional=use_birectional,\n dropout_rate=dropout_rate,\n )\n history = treina_modelo(model, train_df, val_df)\n return history, model\n\n\ndef executa_experimento(\n use_birectional, dropout_rate, train_df, val_df, test_df, embed_matrix\n):\n history, model = aplica_treinamento(\n train_df, val_df, use_birectional, dropout_rate, embed_matrix\n )\n plot_metrics(history, use_birectional, dropout_rate)\n print(\"Avaliação nos dados de teste\")\n results = model.evaluate(\n test_df[\"review_text\"].values, test_df[\"overall_rating\"].values, batch_size=256\n )\n print(\"test loss, test acc:\", results)\n return None\n\n\ndef plot_metrics(history, use_birectional, dropout_rate):\n # summarize history for loss\n # Inspired from here:\n # https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/\n plt.plot(history.history[\"loss\"])\n epochs = range(4, len(history.history[\"loss\"]), 5)\n plt.plot(epochs, history.history[\"val_loss\"])\n plt.title(\n f\"Gráfico de loss com bidrecional={use_birectional} e taxa de dropout={dropout_rate*100}%\"\n )\n plt.ylabel(\"loss\")\n plt.xlabel(\"época\")\n plt.legend([\"treinamento\", \"validação\"], loc=\"upper right\")\n plt.savefig(\n f\"data/learning_curve_bidirectional_{use_birectional}_dropout_rate_{dropout_rate}.png\"\n )\n plt.show()\n return None\n\n\n@click.command()\n@click.option(\n \"--usar_bidirecional\",\n prompt=True,\n required=True,\n type=click.Choice([\"False\", \"True\"]),\n)\n@click.option(\n \"--taxa_de_dropout\",\n prompt=\"Indique a Taxa de Dropout\",\n required=True,\n type=click.Choice([\"0\", \"0.25\", \"0.5\"]),\n)\ndef aplica_experimento(usar_bidirecional, taxa_de_dropout):\n usar_bidirecional = bool(strtobool(usar_bidirecional))\n taxa_de_dropout = float(taxa_de_dropout)\n preprocess_embedding_from_NILC(\"data/bow_s50.txt\", 50)\n partilha(\n \"data/B2W-Reviews01.csv\",\n train_proportion=0.8,\n val_proportion=0.1,\n test_proportion=0.1,\n sep=\";\",\n )\n train_df = pd.read_csv(\"data/train.csv\")\n val_df = pd.read_csv(\"data/validation.csv\")\n test_df = pd.read_csv(\"data/test.csv\")\n tokenizer_layer, embed_matrix, embed_vocab = codifica(\n train_df_text=train_df[\"review_text\"], tammax=256, embed_dim=50\n )\n executa_experimento(\n usar_bidirecional, taxa_de_dropout, train_df, val_df, test_df, embed_matrix\n )\n\n\nif __name__ == \"__main__\":\n aplica_experimento()\n","sub_path":"EP 2/src/ep2.py","file_name":"ep2.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"333452499","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^polls/', include('polls.urls', namespace=\"polls\")),\n url(r'^admin/', include(admin.site.urls)),\n #url(r'^UserLogin/', include('UserLogin.urls', namespace=\"UserLogin\")),\n url(r'^registration/', include('registration.urls', namespace=\"registration\")),\n )\n","sub_path":"MyDjango/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"479404142","text":"#\r\nimport turtle\r\n\r\nt = turtle.Turtle()\r\nt.ht()\r\n\r\nradius = 150\r\ncolor1 = \"black\"\r\ncolor2 = \"white\"\r\n\r\nt.color(color1)\r\nt.begin_fill()\r\nt.circle(radius/2., 180)\r\nt.circle(radius, 180)\r\nt.left(180)\r\nt.circle(-radius/2., 180)\r\nt.color(color1)\r\nt.left(90)\r\nt.up()\r\nt.forward(radius*0.375)\r\nt.end_fill()\r\nt.right(90)\r\nt.down()\r\nt.color(color2)\r\nt.begin_fill()\r\nt.circle(radius*0.125)\r\nt.end_fill()\r\nt.left(90)\r\nt.up()\r\nt.backward(radius*0.375)\r\nt.down()\r\nt.left(90)\r\n\r\n# A VOUS DE POURSUIVRE CE DESSIN BIEN CONNU\r\n","sub_path":"skulpt/python/ying.py","file_name":"ying.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"298961998","text":"from flask import Blueprint, jsonify, render_template, request, redirect, url_for\nfrom blueprints.backend.model.reservations.models import Reservation\nfrom blueprints.backend.model.roles.models import Role\nfrom blueprints.backend.model.rooms.models import Rooms\nfrom blueprints.backend.model.payments.models import Payment\nfrom blueprints.backend.model.users.models import User\nfrom blueprints.backend.form.rooms.forms import RoomsForm\nfrom blueprints.backend.form.reservations.forms import ReservationForm\nfrom blueprints.backend.form.roles.forms import RoleForm\nfrom blueprints.backend.form.users.forms import UserForm,SearchForm\n\nfrom passlib.hash import sha256_crypt\nfrom extension import db\nfrom sqlalchemy import or_\n\nbackend = Blueprint('backend', __name__, template_folder=\"templates\")\n\n\n@backend.route('/')\ndef index():\n return 'WELCOME TO SSCR-dC Hotel' \n\n@backend.route('/dashboard')\ndef dashboard():\n return render_template('dashboard/dashboard.html') \n\n@backend.route('/payments')\ndef payments():\n return render_template('payments/payments.html') \n\n@backend.route('/users', methods=['GET', 'POST'])\ndef users_index():\n form = SearchForm()\n users = User.query.all()\n\n if form.validate_on_submit():\n\n search = form.search.data\n users = User.query.filter(or_(\n User.firstname.like('%'+search+'%'),\n User.lastname.like('%'+search+'%'),\n User.mobile.like('%'+search+'%'),\n User.role.like('%'+search+'%'),\n User.email.like('%'+search+'%'))).all()\n\n return render_template('users/index.html', form = form, users=users)\n\n@backend.route('/users/create',methods=['GET','POST'])\ndef users_create():\n form = UserForm(request.form)\n if request.method == 'POST' and form.validate():\n firstname = request.form.get('firstname')\n lastname = request.form.get('lastname')\n middlename = request.form.get('middlename')\n address = request.form.get('address')\n mobile = request.form.get('mobile')\n email = request.form.get('email')\n role = request.form.get('role')\n password = request.form.get('password')\n pw_hash = sha256_crypt.encrypt(str(password))\n #created_at = request.form.get('created_at')\n #updated_at = request.form.get('updated_at')\n\n users = User (\n firstname=firstname,\n lastname=lastname,\n middlename=middlename,\n address=address,\n mobile=mobile,\n email=email,\n role=role,\n password=pw_hash,\n #created_at=created_at,\n #updated_at=updated_at\n\n )\n\n users.store()\n\n return redirect(url_for('backend.users_index'))\n return render_template('users/create.html',form=form)\n\n@backend.route('/users/', methods=['GET'])\ndef users_show(id):\n users = User.query.filter_by(id=id).first() \n\n return render_template('users/show.html', users=users)\n\n@backend.route('/users//edit', methods=['GET','POST'])\ndef users_edit(id):\n form = UserForm(request.form)\n users = User.query.filter_by(id=id).first()\n\n if request.method == 'POST' and form.validate():\n\n firstname = request.form.get('firstname')\n lastname = request.form.get('lastname')\n middlename = request.form.get('middlename')\n address = request.form.get('address')\n mobile = request.form.get('mobile')\n email = request.form.get('email')\n role = request.form.get('role')\n password = request.form.get('password')\n pw_hash = sha256_crypt.encrypt(str(password))\n method = request.form.get('_method')\n users = User.query.get(id)\n \n\n if method == 'PUT':\n users.update (firstname=firstname,lastname=lastname,middlename=middlename,address=address, mobile=mobile,email=email,role=role,password=password)\n\n return redirect(url_for('backend.users_index'))\n\n return render_template('users/edit.html', form=form,users=users)\n\n@backend.route('/users//delete', methods=['GET','POST'])\ndef usersdelete(id):\n users = User.query.get(id) \n db.session.delete(users)\n db.session.commit()\n return redirect(url_for('backend.users_index'))\n\n \n@backend.route('/roles', methods=['GET', 'POST'])\ndef roles_index():\n form = SearchForm()\n roles = Role.query.all()\n if form.validate_on_submit():\n\n search = form.search.data\n roles = Role.query.filter((Role.name.like('%'+search+'%'))).all()\n\n return render_template('roles/index.html',form=form,roles=roles)\n\n\n@backend.route('/roles/create',methods=['GET','POST'])\ndef roles_create():\n form = RoleForm(request.form)\n if request.method == 'POST' and form.validate():\n name = request.form.get('name')\n description = request.form.get('description')\n\n roles = Role(name=name,description=description)\n roles.store()\n return redirect(url_for('backend.roles_index'))\n\n return render_template('roles/create.html', form=form)\n\n@backend.route('/roles/', methods=['GET'])\ndef roles_show(id):\n roles = Role.query.filter_by(id=id).first()\n\n return render_template('roles/show.html', roles=roles)\n\n@backend.route('/roles//edit', methods=['GET','POST'])\ndef roles_edit(id):\n form = RoleForm(request.form)\n roles = Role.query.filter_by(id=id).first()\n\n if request.method == 'POST' and form.validate():\n\n name = request.form.get('name')\n description = request.form.get('description')\n method = request.form.get('_method')\n roles = Role.query.get(id)\n\n if method == 'PUT':\n roles.update(name=name, description=description)\n\n return redirect(url_for('backend.roles_index'))\n\n return render_template('roles/edit.html',form=form, roles=roles)\n\n@backend.route('/roles//delete', methods=['GET', 'POST'])\ndef rolesdelete(id):\n roles = Role.query.get(id) \n db.session.delete(roles)\n db.session.commit()\n return redirect(url_for('backend.roles_index'))\n\n@backend.route('/reservations',methods=['GET','POST'])\ndef reservations_index():\n form = SearchForm(request.form)\n reservations = Reservation.query.all()\n if form.validate_on_submit():\n search = form.search.data\n reservations = Reservation.query.filter(or_(\n Reservation.users_id.like('%'+search+'%'),\n Reservation.rooms_id.like('%'+search+'%'))).all()\n\n return render_template('reservations/index.html',form=form,reservations=reservations)\n\n@backend.route('/reservations/create',methods=['GET','POST'])\ndef reservations_create():\n form = ReservationForm(request.form)\n users = User.query.all()\n rooms = Rooms.query.all()\n \n\n if request.method == 'POST' and form.validate():\n users_id = request.form.get('users_id')\n rooms_id = request.form.get('rooms_id')\n date_in = request.form.get('date_in')\n date_out = request.form.get('date_out')\n child_count = request.form.get('child_count')\n adult_count= request.form.get('adult_count')\n\n reservations = Reservation (\n users_id=users_id, \n rooms_id=rooms_id,\n date_in = date_in,\n date_out=date_out,\n child_count=child_count, \n adult_count=adult_count\n \n )\n reservations.store()\n\n return redirect(url_for('backend.reservations_index'))\n\n return render_template('reservations/create.html',form=form,users=users,rooms=rooms) \n\n@backend.route('/reservations/', methods=['GET'])\ndef reservations_show(id):\n reservations = Reservation.query.filter_by(id=id).first()\n\n return render_template('reservations/show.html', reservations=reservations)\n\n@backend.route('/reservations//edit', methods=['GET','POST'])\ndef reservations_edit(id):\n form = ReservationForm(request.form)\n users = Users.query.all()\n rooms = Rooms.query.all()\n reservations = Reservation.query.filter_by(id=id).first()\n\n if request.method == 'POST' and form.validate():\n\n users_id = request.form.get('users_id')\n rooms_id = request.form.get('rooms_id')\n date_in = request.form.get('date_in')\n date_out = request.form.get('date_out')\n child_count = request.form.get('child_count')\n adult_count= request.form.get('adult_count')\n method = request.form.get('_method')\n reservations = Reservation.query.get(id)\n\n if method == 'PUT':\n reservations.update (\n users_id=users_id, \n rooms_id=rooms_id,\n date_in = date_in,\n date_out=date_out,\n child_count=child_count, \n adult_count=adult_count\n )\n\n return redirect(url_for('backend.reservations_index'))\n\n return render_template('reservations/edit.html',form=form, reservations=reservations,rooms=rooms,users=users)\n\n@backend.route('/reservations//delete', methods=['GET', 'POST'])\ndef reservationsdelete(id):\n reservations = Reservation.query.get(id) \n db.session.delete(reservations)\n db.session.commit()\n return redirect(url_for('backend.reservations_index'))\n\n@backend.route('/rooms', methods=['GET', 'POST'])\ndef rooms_index():\n form = SearchForm()\n rooms = Rooms.query.all()\n\n if form.validate_on_submit():\n\n search = form.search.data\n rooms = Rooms.query.filter(or_(\n Rooms.room_type.like('%'+search+'%'),\n Rooms.status.like('%'+search+'%'),\n Rooms.price.like('%'+search+'%'))).all()\n\n return render_template('rooms/index.html', form = form, rooms=rooms)\n\n@backend.route('/rooms/create',methods=['GET','POST'])\ndef rooms_create():\n form = RoomsForm(request.form)\n if request.method == 'POST' and form.validate():\n\n room_type = request.form.get('room_type')\n status = request.form.get('status')\n price = request.form.get('price')\n \n\n rooms = Rooms (\n \n room_type = room_type,\n status = status,\n price = price\n )\n\n rooms.store()\n\n return redirect(url_for('backend.rooms_index')) \n return render_template('rooms/create.html',form=form)\n \n@backend.route('/rooms/', methods=['GET'])\ndef rooms_show(id):\n rooms = Rooms.query.filter_by(id=id).first()\n #user = Map(\n # style=\"width: 100%;height: 500px;\",\n # identifier=\"user\",\n # varname=\"user\",\n #lat=14.4348822,\n #lng=120.9472825,\n #markers=[ [terminals.latitude,terminals.longitude,terminals.address]])\n\n return render_template('rooms/show.html', rooms=rooms)\n\n@backend.route('/rooms//edit', methods=['GET','POST'])\ndef rooms_edit(id):\n form = RoomsForm(request.form)\n rooms = Rooms.query.filter_by(id=id).first()\n\n if request.method == 'POST' and form.validate():\n\n room_type = request.form.get('room_type')\n status = request.form.get('status')\n price = request.form.get('price')\n method = request.form.get('_method')\n rooms = Rooms.query.get(id)\n\n if method == 'PUT':\n rooms.update (\n \n room_type=room_type, \n status=status, \n price=price\n \n )\n\n return redirect(url_for('backend.rooms_index'))\n\n return render_template('rooms/edit.html', form=form,rooms=rooms)\n\n@backend.route('/rooms//delete', methods=['GET', 'POST'])\ndef roomsdelete(id):\n rooms = Rooms.query.get(id) \n db.session.delete(rooms)\n db.session.commit()\n return redirect(url_for('backend.rooms_index'))\n\n\n\n@backend.route('/payments/', methods=['GET'])\ndef payments_show(id):\n\n payments = Payment.query.filter_by(id=id).first()\n\n reservations = Reservation.query.filter_by(id=id).first()\n\n return render_template('payments/show.html', payments=payments, reservations=reservations)\n\n\n@backend.route('/payments//edit', methods=['GET'])\ndef payments_edit(id):\n\n payments = Payment.query.filter_by(id=id).first()\n return render_template('/payments/edit.html', payments=payments)\n\n@backend.route('/payments/', methods=['POST'])\ndef payments_update_or_destroy(id):\n\n reserve_id = request.form.get('reserve_id')\n first\n firstname = request.form.get('firstname')\n lastname = request.form.get('lastname')\n mode = request.form.get('mode')\n method = request.form.get('_method')\n payments = Payment.query.get(id)\n\n if method == 'PUT':\n payments.update (\n reserve_id=reserve_id, \n firstname=firstname, \n lastname=lastname, \n mode=mode\n )\n return redirect(url_for('backend.payments'))\n\n@backend.route('/payments//delete', methods=['GET', 'POST'])\ndef delete(id):\n payments = Payment.query.get(id) \n db.session.delete(payments)\n db.session.commit()\n return redirect(url_for('backend/payments'))","sub_path":"hotel/blueprints/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"94786417","text":"import math\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\n# значения по умолчанию для y = cos(x)\ndef plot_cos(k=1, a=0, b=0):\n x = []\n y = []\n for i in np.arange(-12, 12, 0.1):\n x.append(i)\n y.append(k * math.cos(i - a) + b)\n plt.plot(x, y)\n plt.show()\n\n\nplot_cos()\nplot_cos(2, 1, 3)\nplot_cos(-1, 0, 0)\n","sub_path":"intro_hi_math/homework_03/ex_01_theme3.py","file_name":"ex_01_theme3.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"654280663","text":"\"\"\"\nThis code defines a machine interface class, with which code can create and use\nan object of the Patent-type class.\n\"\"\"\n\n# Standard imports.\nimport json\n\n# Local imports.\nfrom .patent import Patent\nfrom .patent_peerage import PatentPeerage\nfrom .patent_peerage_feudal import PatentPeerageFeudal\n\n##############\n# MAIN CLASS #\n##############\n\nclass MachineInterface:\n \"\"\" The class in question. \"\"\"\n # Class attributes.\n PATENT_TYPE_KEY = \"type\"\n PEERAGE_TYPE = \"peerage\"\n PEERAGE_FEUDAL_TYPE = \"peerage-feudal\"\n\n def __init__(self, path_to_input_file):\n self.path_to_input_file = path_to_input_file\n self.patent_obj = self.make_patent_object()\n\n def make_patent_object(self):\n \"\"\" Make the patent object, given the input file. \"\"\"\n with open(self.path_to_input_file, \"r\") as input_file:\n input_dict = json.loads(input_file.read())\n patent_type = input_dict.pop(self.PATENT_TYPE_KEY)\n if patent_type == self.PEERAGE_FEUDAL_TYPE:\n result = PatentPeerageFeudal(**input_dict)\n elif patent_type == self.PEERAGE_TYPE:\n result = PatentPeerage(**input_dict)\n else:\n result = Patent(**input_dict)\n return result\n\n def generate(self):\n \"\"\" Generate the output. \"\"\"\n self.patent_obj.generate()\n","sub_path":"source/machine_interface.py","file_name":"machine_interface.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"613214754","text":"class RingBuffer:\n def __init__(self, capacity):\n self.capacity = capacity\n self.data = []\n self.index =0\n \n \n def append(self, item):\n # check if the buffer is full\n if len(self.data) == self.capacity: \n # overwrite the past value with new item \n self.data.pop(self.index)\n self.data.insert(self.index,item)\n self.index = (self.index +1 ) % self.capacity\n else:\n self.data.append(item)\n \n def get(self):\n return self.data\n\nbuffer = RingBuffer(3)\nprint(buffer.get())\nbuffer.append('a')\nbuffer.append('b')\nbuffer.append('c')\nprint(buffer.get())\nbuffer.append('d')\nprint(buffer.get())\n\nbuffer.append('e')\nprint(buffer.get())","sub_path":"ring_buffer/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"32516617","text":"\r\n\r\ndef gPrimo(N):\r\n\ti=1\r\n\twhile i self.nb_train_images:\n self.train_index = 0\n self.epoch += 1\n\n start = self.train_index\n stop = start + batch_size\n\n images = self.train_images[start:stop]\n labels = self.train_labels[start:stop]\n\n return images, labels \n\n def get_val_batch(self, batch_size):\n if self.val_index + batch_size > self.nb_val_images:\n self.val_index = 0\n\n start = self.val_index\n stop = start + batch_size\n\n images = self.validation_images[start:stop]\n labels = self.validation_labels[start:stop]\n\n return images, labels \n\n def get_val(self):\n return self.validation_images, self.validation_labels\n\n def get_test_batch(self, batch_size):\n if self.test_index + batch_size > self.nb_test_images:\n self.test_done = 1\n\n start = self.test_index\n stop = start + batch_size\n return self.test_images\n\n # read and normalize test data (range 0 <-> 1)\n def _read_test_data(self):\n self.test_images = pd.read_csv(self.test_file).values\n self.test_images = self.test_images.astype(np.float)\n self.test_images = np.multiply(self.test_images, 1.0/255.0)\n print('test_images({0[0]},{0[1]})'.format(self.test_images.shape))\n\n # read and normalize training data (range 0 <-> 1)\n def _read_training_data(self):\n self.data = pd.read_csv(self.train_file)\n print('data({0[0]},{0[1]})'.format(self.data.shape))\n\n self._store_images()\n self._build_labels()\n self._split_data(VALIDATION_SIZE)\n\n def _store_images(self):\n self.images = self.data.iloc[:,1:].values\n self.images = self.images.astype(np.float)\n self.images = np.multiply(self.images, 1.0 / 255.0)\n print('images({0[0]},{0[1]})'.format(self.images.shape))\n\n self.image_size = self.images.shape[1]\n # in this case all images are square\n self.image_width = self.image_height = np.ceil(np.sqrt(self.image_size)).astype(np.uint8)\n \n print ('image_width => {0}\\nimage_height => {1}'.format(self.image_width,self.image_height))\n\n # convert labels from scalars to one-hot vectors\n @staticmethod\n def _dense_to_one_hot(labels_dense, num_classes):\n num_labels = labels_dense.shape[0]\n index_offset = np.arange(num_labels) * num_classes\n labels_one_hot = np.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n return labels_one_hot\n\n def _build_labels(self):\n labels_flat = self.data[[0]].values.ravel()\n\n self.nb_classes = np.unique(labels_flat).shape[0]\n \n self.labels = self._dense_to_one_hot(labels_flat, self.nb_classes)\n self.labels = self.labels.astype(np.uint8)\n \n def _split_data(self, val_size):\n # split data into training & validation\n self.validation_images = self.images[:val_size]\n self.validation_labels = self.labels[:val_size]\n \n self.train_images = self.images[val_size:]\n self.train_labels = self.labels[val_size:]\n \n print('train_images({0[0]},{0[1]})'.format(self.train_images.shape))\n print('validation_images({0[0]},{0[1]})'.format(self.validation_images.shape))\n\n def _display(self, image_to_display, which_set, usr_images=None):\n # (784) => (28,28)\n if which_set == 'training':\n img = self.images[image_to_display]\n elif which_set == 'validation':\n img = self.validation_images[image_to_display]\n elif which_set == 'test':\n img = self.test_images[image_to_display]\n else: # others\n img = usr_images[image_to_display]\n plothelper.display(img, self.image_width, self.image_height)\n","sub_path":"src/datahandlers/mnistdatahandler.py","file_name":"mnistdatahandler.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"68430868","text":"\"module for base-class Observable and inheritor-class X\"\nclass Observable():\n \"class saves values as attributes and print only public attributes\"\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n def __str__(self):\n public_attr = {}\n for (key, value) in self.__dict__.items():\n if key[0] != '_':\n public_attr.update({key: value})\n return '{}({})'.format(self.__class__.__name__,\n ', '.join('{}={}'.format(key, value)\n for (key, value) in public_attr.items()))\n\nclass X(Observable):\n \"inheritor class\"\n pass\n\nx = X(foo=1, bar=5, _bazz=12, name='Amok', props=('One', 'two'))\nprint(x)\nprint(x.foo)\nprint(x.name)\nprint(x._bazz)\n","sub_path":"Lesson 5/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"492338086","text":"from tkinter import *\nfrom tkinter import ttk\n\nimport random\nimport time\nimport os\nimport collections\n\nclass Scramble:\n\tdef __init__(self):\n\t\tself.solve = StringVar()\n\t\t#A list of all the valid turns on a 3x3 cube\n\t\tself.turns = ['R', 'L', 'U', 'D', 'F', 'B', \"R'\", \"L'\", \"U'\", \"D'\", \"F'\", \"U'\", \"R2\", \"L2\", \"U2\", \"D2\", \"F2\", \"B2\", \"R2'\", \"L2'\", \"U2'\", \"D2'\", \"F2'\", \"B2'\"]\n\n\tdef setScramble(self):\n\t\tturnList = []\n\t\tsame = False\n\t\tfor i in range(0,20):\n\t\t\tr = random.randint(0, len(self.turns) - 1)\n\t\t\tif i > 0:\n\t\t\t\tif self.turns[r][0] == turnList[i-1][0]: #Check to see if the first character of a randomised turn is the same as the previous turn \n\t\t\t\t\tsame = True #If so select another random turn from the list until no longer matching\n\t\t\t\t\twhile same is True:\n\t\t\t\t\t\tr = random.randint(0, len(self.turns) - 1)\n\t\t\t\t\t\tif self.turns[r] != turnList[i-1]:\n\t\t\t\t\t\t\tsame = False\n\t\t\t\t\t\t\tturnList.append(self.turns[r])\n\t\t\t\telse:\n\t\t\t\t turnList.append(self.turns[r]) \n\t\t\telse:\n\t\t\t\tturnList.append(self.turns[r])\n\t\t\t\t\n\t\t#Convert list to a spaced string and set the StringVar() for tkinter\n\t\tturnList = ' '.join(turnList)\n\t\tself.solve.set(turnList) \n\nclass StopWatch(Frame):\n\tdef __init__(self, master = None):\n\t\tFrame.__init__(self, master)\n\t\tself.start = 0.0\n\t\tself.master = master\n\t\tself.elapsed = 0.0\n\t\tself.running = 0\n\t\tself.timeStr = StringVar() #tkinter string variable used to store current elapsed time\n\t\tself.scram = Scramble()\n\t\tself.custom_font_serif = ('Times', 24, 'bold') #Custom font for scramble, Makes the scramble the largest font on screen\n\t\tself.makeFrame()\n\n\tdef makeFrame(self): \n\t\t#Set tkinter frame title and size\n\t\tself.master.title(\"Rubik's Scramble\")\n\t\tself.master.geometry(\"950x125\") \n\n\t\t#Generate a menu at the top of the frame, holding the stats option\n\t\tmenu = Menu(self.master)\n\t\tself.master.config(menu=menu)\n\t\tfile = Menu(menu)\n\t\tfile.add_command(label=\"Stats 's'\", command=self.openStatsWindow)\n\t\tmenu.add_cascade(label=\"File\", menu=file)\n\t\t\n\t\t#The scramble label used to show the user the new scramble\n\t\tscrambleLabel = Label(self, textvariable=self.scram.solve, font = self.custom_font_serif, fg='blue')\n\t\tscrambleLabel.pack(fill = X, side = TOP) \n\n\t\t#Label to display elapsed time to the user\n\t\tl = Label(self, textvariable = self.timeStr, font = self.custom_font_serif, fg='red')\n\t\tself.setTime(self.elapsed)\n\t\tl.pack(fill = X, expand = NO, pady = 2, padx = 2)\n\n\t\t#Scramble button which calls the scramble command to recieve a new scramble\n\t\tscrambleButton = Button(self, text='Scramble', command = self.scram.setScramble).pack(side=BOTTOM) \n\n\tdef setTime(self, elapsed):\n\t\tminutes = int(elapsed/60)\n\t\tseconds = int(elapsed - minutes*60)\n\t\tmSeconds = int((elapsed - minutes*60 - seconds) * 100)\n\t\tself.timeStr.set('%02d:%02d:%02d' % (minutes, seconds, mSeconds))\n\n\tdef update(self):\n\t\tself.elapsed = time.time() - self.start\n\t\tself.setTime(self.elapsed)\n\t\tself.timer = self.after(1, self.update)\n\n\tdef startClock(self, event = None):\n\t\tif not self.running:\n\t\t\tself.start = time.time() - self.elapsed\n\t\t\tself.update()\n\t\t\tself.running = 1\n\t\t\tself.Reset()\n\t\telse:\n\t\t\tself.after_cancel(self.timer)\n\t\t\tself.running = 0\n\t\t\tself.writeData()\n\n\tdef writeData(self):\n\t\tif os.path.isfile(\"times.txt\"):\n\t\t\tdata = open(\"times.txt\", \"a\")\n\t\t\tdata.write(str(\"%.2f\" % self.elapsed) + \", \")\n\t\t\tdata.close()\n\t\telse:\n\t\t\tdata = open(\"times.txt\", \"w\")\n\t\t\tdata.write(str(\"%.2f\" % self.elapsed) + \", \")\n\t\t\tdata.close()\n\n\tdef Reset(self):\n\t\tself.start = time.time()\n\t\tself.elapsed = 0.0\n\t\tself.setTime(self.elapsed)\n\n\tdef openStatsWindow(self, event = None):\n\t\tself.newWindow = Tk()\n\t\tstats = StatsWindow(self.newWindow)\n\nclass StatsWindow(Frame):\n\tdef __init__(self, master):\n\t\tFrame.__init__(self, master)\n\t\tself.master = master\n\t\tself.totalSolves = 0\n\t\tself.splitTimes = {}\n\t\tself.orderedSplit = []\n\t\tself.userTimes = []\n\t\tself.setConfigTimes()\n\t\tself.readData() \n\t\tself.setWindow()\t\t\n\n\tdef setWindow(self):\n\t\tself.master.title(\"Statistics\")\n\t\tself.master.geometry(\"300x300\")\n\n\t\tmenu = Menu(self.master)\n\t\tself.master.config(menu=menu)\n\t\tfile = Menu(menu)\n\t\tfile.add_command(label=\"Clear times\", command = self.clearTimes)\n\t\tmenu.add_cascade(label=\"Options\", menu=file)\n\n\t\ttimeValues = []\n\n\t\tfor t in self.orderedSplit:\n\t\t\tvalue = (self.splitTimes[t] / self.totalSolves) * 100\n\t\t\ttimeValues.append(value)\n\n\t\ttitleLabel = Label(self.master, text = \"Time Statistics\").grid(row=0, column=1)\n\n\n\t\tsubLabel1 = Label(self.master, text = \"Sub \" + self.orderedSplit[0]).grid(row=1, column = 0)\n\t\tsub1Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[0]), maximum = 100).grid(row=1, column = 1)\n\t\tspaceLabel1 = Label(self.master, text = \"\").grid(row=2, column = 0)\n\t\tsub1Percent = Label(self.master, text = \"%.3f\" % timeValues[0] + \"%\").grid(row = 1, column = 3)\n\n\t\tsubLabel2 = Label(self.master, text = \"Sub \" + self.orderedSplit[1]).grid(row=3, column = 0)\n\t\tsub2Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[1]), maximum = 100).grid(row=3, column = 1)\n\t\tspaceLabel2 = Label(self.master, text = \"\").grid(row=4, column = 0)\n\t\tsub2Percent = Label(self.master, text = \"%.3f\" % timeValues[1] + \"%\").grid(row = 3, column = 3)\n\n\t\tsubLabel3 = Label(self.master, text = \"Sub \" + self.orderedSplit[2]).grid(row=5, column = 0)\n\t\tsub3Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[2]), maximum = 100).grid(row=5, column = 1)\n\t\tspaceLabel3 = Label(self.master, text = \"\").grid(row=6, column = 0)\n\t\tsub3Percent = Label(self.master, text = \"%.3f\" % timeValues[2] + \"%\").grid(row = 5, column = 3)\n\n\t\tsubLabel4 = Label(self.master, text = \"Sub \" + self.orderedSplit[3]).grid(row=7, column = 0)\n\t\tsub4Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[3]), maximum = 100).grid(row=7, column = 1)\n\t\tspaceLabel4 = Label(self.master, text = \"\").grid(row=8, column = 0)\n\t\tsub4Percent = Label(self.master, text = \"%.3f\" % timeValues[3] + \"%\").grid(row = 7, column = 3)\n\n\t\tsubLabel5 = Label(self.master, text = \"Sub \" + self.orderedSplit[4]).grid(row=9, column = 0)\n\t\tsub5Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[4]), maximum = 100).grid(row=9, column = 1)\n\t\tspaceLabel5 = Label(self.master, text = \"\").grid(row=10, column = 0)\n\t\tsub5Percent = Label(self.master, text = \"%.3f\" % timeValues[4] + \"%\").grid(row = 9, column = 3)\n\n\t\tsubLabel6 = Label(self.master, text = \"Sub \" + self.orderedSplit[5]).grid(row=11, column = 0)\n\t\tsub6Progresbar = ttk.Progressbar(self.master, orient= HORIZONTAL, length = 100, mode = \"determinate\", value = int(timeValues[5]), maximum = 100).grid(row=11, column = 1)\n\t\tspaceLabel6 = Label(self.master, text = \"\").grid(row=12, column = 0)\n\t\tsub6Percent = Label(self.master, text = \"%.3f\" % timeValues[5] + \"%\").grid(row = 11, column = 3)\n\n\t\ttotalSolvesLabel = Label(self.master, text = \"Total Solves: \" + str(self.totalSolves)).grid(row=13, column=0)\n\n\n\n\tdef setConfigTimes(self):\n\t\tif os.path.isfile(\"config.txt\"):\n\t\t\tdata = open(\"config.txt\") \n\t\t\tfor l in data:\n\t\t\t\twords = l.split(\" \")\n\t\t\t\tself.splitTimes[words[1].strip()] = 0\n\t\t\t\tself.orderedSplit.append(words[1].strip())\n\t\t\t\n\n\tdef readData(self):\n\t\tif os.path.isfile(\"times.txt\"):\n\t\t\tdata = open(\"times.txt\", \"r\")\n\t\t\ttimeData = data.read().split(\",\")\n\t\telse:\n\t\t\tprint(\"File does not exist\")\n\n\t\ti = 0\n\t\taverageTime = 0.0\n\t\ttotalTime = 0.0\n\t\tfor t in timeData:\n\t\t\tif t is not \" \":\n\t\t\t\tfor time, amount in self.splitTimes.items():\n\t\t\t\t\tif float(t) < float(time):\n\t\t\t\t\t\tself.splitTimes[time] += 1\n\t\t\t\ttotalTime = totalTime + float(t)\n\n\t\t\t\ti += 1\n\t\tself.totalSolves = i\n\n\tdef clearTimes(self):\n\t\tif os.path.isfile('times.txt'):\n\t\t\tfileData = open('times.txt', 'w')\n\t\t\tfileData.close()\n\ndef main():\n\troot = Tk() \n\n\tsw = StopWatch(root)\n\tsw.pack(side = BOTTOM)\n\n\troot.bind(\"\", sw.startClock)\n\troot.bind(\"\", sw.openStatsWindow)\n\troot.mainloop()\n\t\t\t\nif __name__ == '__main__':\n\tmain()","sub_path":"Scramble.py","file_name":"Scramble.py","file_ext":"py","file_size_in_byte":8199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"616831103","text":"from datetime import datetime, timedelta\n\n\ndef getweekday(y, m, d):\n print('구하고자 하는 일자는 %d년 %d월 %d일입니다.' % (y, m, d))\n\n days = 0\n daydic = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n wddic = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일']\n\n # Compute count from 1-01-01\n for i in range(1, y):\n if i % 4 == 0 and i % 100 != 0:\n days += 366\n elif i % 400 == 0:\n days += 366\n else:\n days += 365\n\n if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:\n daydic[1] = 29\n\n for i in range(1, m):\n days += daydic[i - 1]\n\n days += d\n\n # Compute Weekday\n wd = days % 7\n print('요청하신 날짜는 %s입니다.' % wddic[wd])\n\n\ndef inputproc():\n datestr = input(\"Date(Y-M-D): \")\n adddate = timedelta(days=int(input(\"Plus: \")))\n firstdate = datetime.strptime(datestr, '%Y-%m-%d')\n targetdate = firstdate + adddate\n getweekday(targetdate.year, targetdate.month, targetdate.day)\n\n\ninputproc()\n","sub_path":"2016-01 소프트웨어적사고/01 Class/12 Calc Date.py","file_name":"12 Calc Date.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234218841","text":"import numpy as np\nimport json as j\nimport random\n\n# Which output node corresponds to what language\noutputContext = {\n \"en\" : 0,\n \"fr\" : 1,\n \"de\" : 2,\n \"la\" : 3,\n # \"mi\" : 4,\n # \"es\" : 5,\n # \"sw\" : 6,\n # \"et\" : 7\n}\n\n# Letters\nletters = \"abcdefghijklmnopqrstuvwxyz\"\n\n\n# Converts letters into numbers\nletterDict = {}\n\n# Holds every training example before being turned into...\ngrandArray = []\n \n# This array\noutputArray = []\n\n# And this one\ninputArray = []\n\n# Turn a string into an array of it's letters' index in letters\ndef index(word):\n indexarray = [letterDict[letter.lower()] for letter in word]\n\n # Fill the remaining spots with zeroes (to keep array shape)\n for i in range(0, 16 - len(indexarray)):\n indexarray.append(0)\n return indexarray\n\ndef generateOutput(languageCode):\n # There are four output nodes so the array has to be (4, )\n outputarray = [0] * 4\n\n # Make the right node 1\n outputarray[outputContext[languageCode]] = 1\n\n return outputarray\n\n\ndef main():\n\n # Generate the letter conversion dictionary\n for i in range(len(letters)):\n letterDict[letters[i]] = i + 1\n\n # Load the data\n with open(f\"/home/mattecatte/STEM/ml/data/scripts/dump/datafile.json\", \"r\") as jsonfile:\n json = j.load(jsonfile)\n\n # For every word\n for language, words in json.items():\n print(f\"Processing language: '{language}'\")\n for word in words:\n \n # Appended to an array so that the data can be shuffled (dicts have no order)\n grandArray.append({\n \"output\" : generateOutput(language),\n \"input\" : index(word),\n \"human symbols\" : word,\n \"language\" : language\n })\n\n\n # Set the expected output for each input example\n for key in outputContext.keys():\n outputContext[key] = generateOutput(key)\n\n # Shuffle the data\n random.shuffle(grandArray)\n\n # Turn the array of key value pairs into two 'linked' arrays\n for i in range(100):\n for element in grandArray:\n outputArray.append(element[\"output\"])\n inputArray.append(element[\"input\"])\n \n print(f\"\\n~Processed {len(grandArray)} elements~\")\n\n # Return those arrays\n return np.array(inputArray, dtype=float), np.array(outputArray, dtype=float)\n\n","sub_path":"data/scripts/generateMatrix.py","file_name":"generateMatrix.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486639820","text":"from ..scheduler.resources.resource_manager import ResourceManager\nfrom copy import deepcopy\n\n_mock_resources = [{'node_id': \"Node-0001\",\n 'Hostname': \"hostname1\",\n 'Availability': \"active\",\n 'State': \"ready\",\n 'CPUs': 5,\n 'MemoryBytes': 30000000000\n },\n {'node_id': \"Node-0002\",\n 'Hostname': \"hostname2\",\n 'Availability': \"active\",\n 'State': \"ready\",\n 'CPUs': 96,\n 'MemoryBytes': 500000000000\n },\n {'node_id': \"Node-0003\",\n 'Hostname': \"hostname3\",\n 'Availability': \"active\",\n 'State': \"ready\",\n 'CPUs': 42,\n 'MemoryBytes': 200000000000\n }\n ]\ndef mock_resources():\n return deepcopy(_mock_resources)\n\nclass MockResourceManager(ResourceManager):\n \"\"\"\n A mock resource manager implementing the abstract interface for testing\n a set of mock resources\n \"\"\"\n\n def __init__(self):\n self.set_resources(mock_resources())\n self.resource_map = {'Node-0001':0, 'Node-0002':1, 'Node-0003':2}\n\n def release_resources(self, allocated_resources):\n pass\n\n def set_resources(self, resources):\n self.resources = resources\n\n def get_resources(self):\n \"\"\"\n Get metadata of all managed resoures.\n \"\"\"\n return self.resources\n\n def get_resource_ids(self):\n \"\"\"\n Get the identifiers for all managed resources\n\n \"\"\"\n for resource in self.resources:\n yield resource['node_id']\n\n def allocate_resource(self, resource_id: str, requested_cpus: int,\n requested_memory:int =0, partial:bool =False):\n \"\"\"\n Attemt to allocate the requested resources.\n \"\"\"\n resource_key = self.resource_map[resource_id]\n hostname = self.resources[resource_key][\"Hostname\"]\n cpus_allocated = 0\n error = True\n cpu_allocation_map={}\n available_cpus = self.resources[resource_key][\"CPUs\"]\n available_memory = self.resources[resource_key][\"MemoryBytes\"]\n if (available_cpus >= requested_cpus):\n #Can satisfy full request\n #Update the resource table\n self.resources[resource_key][\"CPUs\"] -= requested_cpus\n self.resources[resource_key][\"MemoryBytes\"] -= requested_memory\n allocated_cpus = requested_cpus\n error = False\n elif(partial and available_cpus > 0):\n #Can satisfy partial request\n #Update the resource table\n self.resources[resource_key][\"CPUs\"] -= requested_cpus\n self.resources[resource_key][\"MemoryBytes\"] -= requested_memory\n allocated_cpus = available_cpus\n error = False\n elif(partial and available_cpus == 0):\n #No error, just no allocation, no need to hit DB\n allocated_cpus = 0\n error = False\n else:\n #TODO consider exceptions here? Let callers catch them and respond???\n #logging.debug(\"Requested CPUs greater than CPUs available: requested = {}, available = {}, NodeId = {}\".format(requested_cpus, available_cpus, hostname))\n pass\n if not error:\n cpu_allocation_map = {'node_id': resource_id, 'Hostname': hostname, 'cpus_allocated': allocated_cpus,\n 'mem': requested_memory}\n\n #Return the allocation map, {} if failure\n return cpu_allocation_map\n\n def get_available_cpu_count(self):\n \"\"\"\n Returns a count of all available CPU's summed across all resources\n at the time of calling. Not guaranteed avaialable until allocated.\n\n Returns\n -------\n total available CPUs\n \"\"\"\n count = 0\n for id in self.get_resource_ids():\n count += self.resources[ self.resource_map[id] ]['CPUs']\n return count\n\n def create_job_entry(self, allocation_map):\n return \"42\"\n\nclass EmptyResourceManager(ResourceManager):\n \"\"\"\n A mock resource manager implementing the abstract interface for testing\n a set of non-existing resources\n \"\"\"\n def __init__(self):\n self.resources={}\n\n def release_resources(self, allocated_resources):\n pass\n\n def set_resources(self):\n self.resources={}\n\n def get_resources(self):\n \"\"\"\n Get metadata of all managed resoures.\n \"\"\"\n return [{}]\n\n def get_resource_ids(self):\n \"\"\"\n Get the identifiers for all managed resources\n\n \"\"\"\n return []\n\n def allocate_resource(self, resource_id: str, requested_cpus: int,\n requested_memory:int =0, partial:bool =False):\n \"\"\"\n Attemt to allocate the requested resources.\n \"\"\"\n return {}\n\n def get_available_cpu_count(self):\n \"\"\"\n Returns a count of all available CPU's summed across all resources\n at the time of calling. Not guaranteed avaialable until allocated.\n\n Returns\n -------\n total available CPUs\n \"\"\"\n return 0\n","sub_path":"python/lib/scheduler/nwmaas/test/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"360421018","text":"def addResult(teams, name, result):\n if name in teams:\n L = teams[name]\n else:\n L = [0, 0, 0]\n if result == 'win':\n L[0] += 1\n elif result == 'draw':\n L[1] += 1\n else:\n L[2] += 1\n teams[name] = L\n\ndef calcPoints(name, results):\n points = 3*results[0] + results[1]\n return (points, name, results)\n\ndef toString(teamRec):\n points, name, results = teamRec\n won, lost, draw = results\n played = won + lost + draw\n s = f'Team: {name}, Matches Played: {played}, Won: {won}, Lost: {draw}, Draw: {lost}, Points: {points}'\n return s\nn = int(input()) \nteams = {}\nif n == 0:\n print(\"No Output\")\nelse:\n for i in range(n):\n line = input().split(';')\n team1 = line[0].strip()\n team2 = line[1].strip()\n result = line[2].strip()\n addResult(teams, team1, result)\n if result == 'win':\n result = 'loss'\n elif result == 'loss':\n result = 'win'\n addResult(teams, team2, result)\n\nL = []\nfor name in teams:\n L.append(calcPoints(name, teams[name]))\n\nL.sort(reverse=True)\n\nfor rec in L:\n print(toString(rec))","sub_path":"IPL-MATCHS.py","file_name":"IPL-MATCHS.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"574073470","text":"import glob\nimport pickle\nfrom PIL import Image\nimport PIL\nimport numpy as np\nimport pandas as pd\n\n'''\n Save training images in train folder, save training labels csv file, train_y.csv, in train folder\n train_y.csv file in a column\n Save testing images in test folder, save testing labels csv file, test_y.csv, in test folder\n test_y.csv file in a column\n'''\n\n# basewidth = input('Resiezed images horisontal dimension (100):')\nbasewidth = 100\n\n# hsize = input('Resiezed images vertical dimension (100):')\nhsize = 100\n\n# Reading train Y data\n\ny_file_name = 'train/train_y.csv'\ny = pd.read_csv(y_file_name, header=None)\ny = y.values\ntrain_num = y.shape[0]\n\nsave_file = 'train/train_y.pkl'\noutput = open(save_file, 'wb')\npickle.dump(y, output)\noutput.close()\n\n# Reading train X feature data\n\nx_feature_file_name = 'train/train_x_feature.csv'\nx_feature = pd.read_csv(x_feature_file_name, header=None)\nx_feature = x_feature.values\n\nsave_file = 'train/train_x_feature.pkl'\noutput = open(save_file, 'wb')\npickle.dump(x_feature, output)\noutput.close()\n\n# Reading train X image data\nsave_file = 'train/train_x_image.pkl'\nimage_data = np.zeros((train_num, 3, basewidth, hsize))\n\nimg_index = 0\nfor filename in sorted(glob.glob('train/*.jpg')):\n img = Image.open(filename)\n img_resize = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)\n img_resize_np = np.array(img_resize)\n img_reshape = np.zeros((1, 3, basewidth, hsize))\n img_reshape[:, 0, :, :] = img_resize_np[:, :, 0]\n img_reshape[:, 1, :, :] = img_resize_np[:, :, 1]\n img_reshape[:, 2, :, :] = img_resize_np[:, :, 2]\n image_data[img_index, :, :, :] = img_reshape\n img_index = img_index + 1\n\noutput = open(save_file, 'wb')\npickle.dump(image_data, output)\noutput.close()\n\n####################################\n\n\n#testing data\n\n\n####################################\n\n# Reading test Y data\n\ny_file_name = 'test/test_y.csv'\ny = pd.read_csv(y_file_name, header=None)\ny = y.values\ntest_num = y.shape[0]\n\nsave_file = 'test/test_y.pkl'\noutput = open(save_file, 'wb')\npickle.dump(y, output)\noutput.close()\n\n# Reading test X feature data\n\nx_feature_file_name = 'test/test_x_feature.csv'\nx_feature = pd.read_csv(x_feature_file_name, header=None)\nx_feature = x_feature.values\n\nsave_file = 'test/test_x_feature.pkl'\noutput = open(save_file, 'wb')\npickle.dump(x_feature, output)\noutput.close()\n\n# Reading test X data\nsave_file = 'test/test_x_image.pkl'\nimage_data = np.zeros((test_num, 3, basewidth, basewidth))\n\nimg_index = 0\nfor filename in sorted(glob.glob('test/*.jpg')):\n img = Image.open(filename)\n img_resize = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)\n img_resize_np = np.array(img_resize)\n img_reshape = np.zeros((1, 3, basewidth, hsize))\n img_reshape[:, 0, :, :] = img_resize_np[:, :, 0]\n img_reshape[:, 1, :, :] = img_resize_np[:, :, 1]\n img_reshape[:, 2, :, :] = img_resize_np[:, :, 2]\n image_data[img_index, :, :, :] = img_reshape\n img_index = img_index + 1\n\noutput = open(save_file, 'wb')\npickle.dump(image_data, output)\noutput.close()\n","sub_path":"read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"178548619","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 19:40:02 2019\n\n@author: 非均匀尺度随机均匀采样\n\"\"\"\n\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nfrom time import time\nimport datetime\nfrom scipy import stats\nfrom sklearn.preprocessing import StandardScaler\n\n# In[]:\n# 1、生成 0-1 之间的随机数\n# 1.1、指定生成随机数矩阵: 产生均匀分布的随机数\na = np.random.rand(100000,1) # 10行2列矩阵: 100个随机数\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(a, bins=100, color='green', ax=axe)\n\n# 1.2、随机数列表: 产生均匀分布的随机数\nb = np.random.random(100000) # 列表: 50个随机数\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(b, bins=100, color='green', ax=axe)\n\n# In[]:\n# 2、指定生成范围:\n# 2.1、整数: 产生均匀分布的随机数\na = np.random.randint(0,100000,(100000,1)) # 0到10的范围, 4行3列矩阵: 如果只是一个数字,则生成列表\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(a, bins=100, color='green', ax=axe)\n\n# 2.2、浮点数: 产生均匀分布的随机数\nb = np.random.uniform(0,100000,(100000,1)) # 0到10的范围, 4行3列矩阵: 如果只是一个数字,则生成列表\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(b, bins=100, color='green', ax=axe)\n\n# In[]:\n# 3、产生标准正态分布随机数\na = np.random.randn(100000,1)\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(a, bins=100, color='green', ax=axe)\n\nb = np.random.standard_normal([100000])\nfig, axe = plt.subplots(1,1,figsize=(15,10))\nsns.distplot(b, bins=100, color='green', ax=axe)\n\n\n\n# In[]:\n# 非均匀尺度随机均匀采样\n# 数据间隔太大,直方图不能很好表示,只能分桶\n# 90%的采样点分布在[0.1, 1]之间,只有10%分布在[0.0001, 0.1]之间\na = 0.0001\nb = 1\nnum = 100000\nbins = [0.0001, 0.001, 0.01, 0.1, 1]\n\nresult = np.random.uniform(a, b, num)\n\nscore_cut = pd.cut(result, bins)\nprint(score_cut.value_counts())\n\n# In[]:\n# 10**np.log10(0.0001) = 0.0001, 10**np.log10(1) = 1\nresult = np.logspace(np.log10(a), np.log10(b), num, base=10) # 默认10为底\n\nscore_cut = pd.cut(result, bins)\nprint(score_cut.value_counts())\n\n# In[]:\nm = np.log10(a)\nn = np.log10(b)\nr = np.random.rand(num,1) # 生成 0-1 之间的随机数: 产生均匀分布的随机数\nr = m + (n-m)*r # 2维\nresult = np.power(10,r).ravel()\n\nscore_cut = pd.cut(result, bins)\nprint(score_cut.value_counts())\n\n# In[]:\nm = np.log10(a)\nn = np.log10(b)\nr = np.random.uniform(m, n, num) # 浮点数: 产生均匀分布的随机数\nresult = np.power(10,r)\n\nscore_cut = pd.cut(result, bins)\nprint(score_cut.value_counts())\n\n\n\n\n\n\n","sub_path":"3_DataAnalysis/100_Sklearn/7_SVM/Non-uniform_scale_random_uniform_sampling.py","file_name":"Non-uniform_scale_random_uniform_sampling.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"138012234","text":"import logging\nimport logging.config\nimport logging.handlers\nfrom Runners import SVM_runner\nimport time\nimport sys\n\n\ndef main():\n\n \"\"\"\n main function\n :param run_type: int, type of run to preform. default 1 = market data run.\n :return:\n \"\"\"\n logger = None\n try:\n data_file_path = sys.argv[1]\n time1 = time.time()\n\n # configure logging\n logging.handlers = logging.handlers\n logging.config.fileConfig('log_config.conf')\n logger = logging.getLogger(\"root\")\n\n # initialize runner:\n testrun = SVM_runner.SVM_Runner(logger,data_file_path)\n testrun.lin_svm()\n\n time2 = time.time()\n logger.info(\"run time %s\" % (time2-time1))\n\n except Exception as error:\n if logger is not None:\n logger.exception(error)\n else:\n print(error)\n\n\nif __name__ == \"__main__\":\n main()\n # print('finished running main')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"9572596","text":"import json\n\n\n__all__ = ['SearchFunction']\n\n\nclass SearchFunction:\n \"\"\"A list of all search functions.\n\n To add a function, use the :py:meth:`.SearchFunction.add` decorator. This\n passes the function itself through (so multiple invocations of the add\n decorator can be called on the same item), and appends it to the internal\n store of search functions.\n\n To get a function, use the :py:meth:`.SearchFunction.get` classmethod.\n This returns the function described by the given name, or raises KeyError\n if no function is available.\n\n This class should basically be used as a singleton instance - all methods\n are class methods, and operate on a shared store of data. This probably\n isn't best practice, but it works for now.\n\n See :py:meth:`.SearchFunction.add` for details on what a search function\n should actually look like.\n \"\"\"\n\n funcs = {}\n\n @classmethod\n def add(cls, *funcnames):\n \"\"\"Add a function to the current list of functions.\n\n The function should have the following signature:\n\n :param any key: The key for which a value should be found. This is\n usually not important - the function is also passed the index that\n pertains to this particular key.\n\n :param str operator: The operator/name that this function has been\n called under. Sometimes it is simpler if different operators all\n map to the same function (for example, all string methods map to\n one function that dynamically calls the method on a string\n instance). This can be then used to work out the specific\n operation.\n\n :param any argument: The argument passed to this particular operator.\n\n :param index: The index related to the key being searched against.\n This is basically a dict mapping every value that has been assigned\n to this key to a list of the ids of the documents where this\n key-value mapping exists.\n :type index: dict[any: list[id]]\n\n :param set[id] all: The set of all ids that are currently stored.\n This is useful in the case where you want to search for, say,\n non-existance of a key, in which case the set of ids that should\n be returned is the set of all ids that aren't in the index that\n the function has been passed.\n \"\"\"\n def _add(func):\n for name in funcnames:\n cls.funcs[name] = func\n return func\n return _add\n\n @classmethod\n def get(cls, funcname):\n if funcname in cls.funcs:\n return cls.funcs[funcname]\n else:\n m = \"Unrecognised search term: {term}\"\n raise KeyError(m.format(term=funcname))\n\n\n@SearchFunction.add('exists')\ndef exists(key, op, arg, index, query, al):\n resp = []\n for ids in index.values():\n resp.extend(ids)\n\n if arg:\n return set(resp)\n else:\n return al - set(resp)\n\n\n@SearchFunction.add('eq', '==', 'equal')\n@SearchFunction.add('gte', '>=', 'greater-than-equal')\n@SearchFunction.add('lte', '<=', 'less-than-equal')\n@SearchFunction.add('lt', '<', 'less-than')\n@SearchFunction.add('gt', '>', 'greater-than')\ndef comparison(key, op, arg, index, query, all):\n resp = []\n for value in index:\n try:\n svalue = json.loads(value)\n\n if op in {\"gt\", '>', 'greater-than'}:\n if svalue > arg:\n resp.extend(index[value])\n elif op in {\"lt\", '<', 'less-than'}:\n if svalue < arg:\n resp.extend(index[value])\n elif op in {'gte', '>=', 'greater-than-equal'}:\n if svalue >= arg:\n resp.extend(index[value])\n elif op in {'lte', '<=', 'less-than-equal'}:\n if svalue <= arg:\n resp.extend(index[value])\n elif op in {'eq', '==', 'equal'}:\n if svalue == arg:\n resp.extend(index[value])\n else:\n assert False, \"Unrecognised op for comparison function: \" + op\n\n except (ValueError, TypeError):\n continue\n\n return set(resp)\n\n\n# TODO: expand this to other string operators?\n@SearchFunction.add('startswith')\n@SearchFunction.add('endswith')\n@SearchFunction.add('contains')\n@SearchFunction.add('isalnum')\n@SearchFunction.add('isalpha')\n@SearchFunction.add('isdecimal')\n@SearchFunction.add('isdigit')\n@SearchFunction.add('isidentifier')\n@SearchFunction.add('islower')\n@SearchFunction.add('isnumeric')\n@SearchFunction.add('isprintable')\n@SearchFunction.add('isspace')\n@SearchFunction.add('istitle')\n@SearchFunction.add('isupper')\ndef startswith(key, op, arg, index, query, all):\n resp = []\n for value in index:\n val = json.loads(value)\n try:\n if op == 'contains':\n if arg in val:\n resp.extend(index[value])\n elif op.startswith('is'):\n if getattr(val, op)() == arg:\n resp.extend(index[value])\n elif getattr(val, op)(arg):\n resp.extend(index[value])\n except (ValueError, TypeError, AttributeError):\n continue\n\n return set(resp)\n","sub_path":"ogitm/gitdb/search_functions.py","file_name":"search_functions.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"333348128","text":"from django.conf.urls import url\nfrom . import views\nurlpatterns = [\n\n # 跟团游\n url(r'^grouptravel/$',views.grouptravel,name='grouptravel'),\n\n # 自助游\n url(r'^divtravel/$',views.divtravel,name='divtravel'),\n\n # 景点\n url(r'^scenic/$',views.Scenic,name='scenic'),\n\n # 游记\n url(r'^travel_notes/$',views.TravelnotesView,name='travel_notes'),\n # 我的游记\n url(r'^travel_mynotes/$', views.TravelmynotesView, name='travel_mynotes'),\n\n # 写游记\n url(r'^travel_writernotes/$', views.TravelwriternotesView, name='travel_writernotes'),\n\n\n # 游记信息页\n url(r'^travel_notes_info/$',views.TravelnotesInfoView,name='travel_notes_info'),\n\n # 旅游详情页\n url(r'travel_detail/$',views.TraveldetailView.as_view(),name='travel_detail'),\n\n # 订单提交页\n url(r'travel_submit_order/$', views.TravelsubmitorderView.as_view(), name='travel_submit_order'),\n\n # 订单确认\n url(r'travel_confirm_order/$', views.TravelconfirmorderView.as_view(), name='travel_confirm_order'),\n]\n","sub_path":"CenturyBrigade/apps/travel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"97104491","text":"from __future__ import division\nimport sys\nimport math\nfrom datetime import datetime\nfrom collections import defaultdict\n\nfrom elasticsearch import Elasticsearch\nfrom slipstream_api import Api\nfrom log import get_logger\nfrom utils import config_get\n\nlogger = get_logger(name='summarizer')\n\nss_api = Api()\nserver_host = 'localhost'\nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n\ndatetime_format = \"%Y-%m-%dT%H:%M:%S\"\n\n\ndef timestamp():\n return datetime.utcnow().strftime(datetime_format)\n\n\ndef _find_msg(msgs, mstr):\n \"\"\"\n :param msgs: example: @MAPPER_RUN 2018-02-06T16:03:52 start deployment\n :param mstr: string to match\n :return: matched string\n \"\"\"\n for m in msgs:\n if mstr in m:\n return m\n return ''\n\n\ndef _time_at(msgs, mstr):\n \"\"\"\n :param msgs: example: @MAPPER_RUN 2018-02-06T16:03:52 start deployment\n :param mstr: string to match\n :return: datetime.datetime object\n \"\"\"\n msg = _find_msg(msgs, mstr)\n if msg:\n time_str = msg.split(' ', 2)[1]\n return datetime.strptime(time_str, datetime_format)\n else:\n raise Exception('Failed to find %s in the list of messages to determine time.' % mstr)\n\n\ndef _total_time(dpl_state_times):\n total_time = dpl_state_times['Ready'] - _start_time(dpl_state_times)\n return total_time.seconds\n\n\ndef _start_time(dpl_state_times):\n return dpl_state_times['Created']\n\n\ndef _provisioning_time(dpl_state_times):\n return dpl_state_times['Executing'] - _start_time(dpl_state_times)\n\n\ndef _get_dpl_state_times(duid):\n events = ss_api.get_deployment_events(duid)\n states_times = {}\n for e in events:\n states_times[e.content.get('state')] = \\\n datetime.strptime(e.timestamp, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n logger.debug('depl %s state times: %s' % (duid, states_times))\n return states_times\n\n\ndef _intra_node_time(data, dpl_state_times):\n provisioning_time = _provisioning_time(dpl_state_times)\n\n install_time = _time_at(data, \"start deployment\") - \\\n dpl_state_times['Executing']\n\n processing_time = _time_at(data, 'finish processing') - \\\n _time_at(data, 'start processing')\n\n deployment_time = _time_at(data, 'finish deployment') - \\\n _time_at(data, 'start deployment')\n\n return {'provisioning': provisioning_time.seconds,\n 'install': install_time.seconds,\n 'deployment': deployment_time.seconds,\n 'processing': processing_time.seconds,\n 'intra-total': install_time.seconds + deployment_time.seconds}\n\n\ndef _compute_time_records(mappers_logs, reducer_logs, duid):\n \"\"\"\n :param mappers_logs: list of lists with logs from each mapper\n :type mappers_logs: [[],]\n :param reducer_logs: list of logs from reducer\n :type reducer_logs: []\n :param duid: deployment id\n :return:\n \"\"\"\n dpl_state_times = _get_dpl_state_times(duid)\n mappers_time = map(lambda x: _intra_node_time(x, dpl_state_times), mappers_logs)\n for i, v in enumerate(mappers_logs):\n mappers_time[i]['download'] = _download_time(v)\n\n reducer_time = _intra_node_time(reducer_logs, dpl_state_times)\n reducer_time['upload'] = _upload_time(reducer_logs)\n\n return {'mappers': mappers_time,\n 'reducer': reducer_time,\n 'total': _total_time(dpl_state_times)}\n\n\ndef _upload_time(data):\n upload_time = _time_at(data, 'finish uploading') - \\\n _time_at(data, 'start uploading')\n return upload_time.seconds\n\n\ndef _download_time(data):\n download_time = _time_at(data, 'finish downloading') - \\\n _time_at(data, 'start downloading')\n return download_time.seconds\n\n\ndef _get_service_offer(mapper, reducer):\n so_m = str(mapper[0]['_source']['fields']['service-offer'])\n so_r = str(reducer[0]['_source']['fields']['service-offer'])\n return {'mapper': so_m, 'reducer': so_r}\n\n\ndef _get_products_list(log_entries_per_mapper):\n products = []\n for logs_list in log_entries_per_mapper:\n msg = _find_msg(logs_list, \"finish downloading\")\n msg_parts = msg.split(' -- ')\n if len(msg_parts) >= 2:\n prods = msg_parts[-1].split(' ')\n products += map(lambda x: x.strip(), prods)\n return products\n\n\ndef _service_offer(id):\n return ss_api.cimi_get(id).json\n\n\ndef _get_specs(id):\n js = ss_api.cimi_get(id).json\n return [js['resource:vcpu'], js['resource:ram'], js['resource:disk']]\n\n\ndef get_price(service_offers, time_records):\n mapper_multiplicity = len(time_records['mappers'])\n time_total = time_records['total']\n mapper_so = ss_api.cimi_get(service_offers.get('mapper'))\n reducer_so = ss_api.cimi_get(service_offers.get('reducer'))\n try:\n mapper_unit_price = float(mapper_so.json['price:unitCost'])\n reducer_unit_price = float(reducer_so.json['price:unitCost'])\n except (TypeError, AttributeError) as ex:\n logger.warn(\"No pricing available with: %s\" % ex)\n return 0\n\n if mapper_so.json['price:billingPeriodCode'] == 'HUR':\n time_total = math.ceil(float(time_total / 3600))\n else:\n time_total = float(time_total / 3600)\n cost = time_total * ((mapper_unit_price * mapper_multiplicity) + reducer_unit_price)\n return cost\n\n\ndef _extract_field(data, field):\n return [v['_source'][field] for v in data.values()]\n\n\ndef _filter_field(hits, field, value):\n if hits['total'] > 0:\n result = [h for h in hits['hits']\n if h['_source']['fields'][field] == value]\n else:\n result = {}\n return result\n\n\ndef _div_node(run):\n mapper = _filter_field(run, \"nodename\", \"mapper\")\n reducer = _filter_field(run, \"nodename\", \"reducer\")\n\n return mapper, reducer\n\n\ndef _extract_node_data(mappers, reducer, duiid):\n l = []\n for m in mappers:\n l.append((m['_source']['host'], m['_source']['message']))\n\n mappers = defaultdict(list)\n for v, k in l:\n mappers[v].append(k)\n\n reducer = [r['_source']['message'] for r in reducer]\n\n return mappers, reducer\n\n\ndef _query_run(duid, cloud):\n query = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\"match\": {\"fields.cloud\": cloud}},\n {\"match\": {\"fields.duid\": duid}}\n ]\n }\n }\n }\n\n return es.search(index='_all', body=query, size=300)\n\n\ndef _create_run_doc(cloud, canned_offer, time_records, products, service_offers):\n run = {\n canned_offer: {\n 'components': {'mapper': _get_specs(service_offers.get('mapper')),\n 'reducer': _get_specs(service_offers.get('reducer'))},\n 'products': products,\n 'price': '%.5f' % (get_price(service_offers, time_records)),\n 'timestamp': timestamp(),\n 'execution_time': time_records['total'],\n 'time_records': {\n 'mappers': time_records['mappers'],\n 'reducer': time_records['reducer'],\n 'total': time_records['total']}\n }\n }\n logger.info('Persisting run summary: %s' % run)\n\n rep = es.update(index='sar',\n doc_type='eo-proc',\n id=cloud,\n body={\"doc\": run})\n\n\ndef _publish_benchmarks(cloud, canned_offer, time_records, products, service_offers):\n for node_name in ['mapper', 'reducer']:\n benchmark = {'eoproc:cannedoffer-name': canned_offer,\n 'eoproc:cannedoffer-node-name': node_name,\n 'eoproc:cannedoffer-products': products,\n 'eoproc:cannedoffer-execution_time': time_records['total'],\n 'eoproc:cannedoffer-cloud': cloud\n }\n creds = {\"credentials\": [{\"href\": \"credential/513d53b6-5aba-4b34-be28-21061ccb6890\"}]}\n so = {\"serviceOffer\": {\"href\": service_offers.get(node_name)}}\n acl = {\n \"acl\": {\n \"owner\": {\n \"principal\": \"super\",\n \"type\": \"USER\"\n },\n \"rules\": [{\n \"type\": \"ROLE\",\n \"principal\": \"USER\",\n \"right\": \"VIEW\"\n }]\n }\n }\n benchmark.update(so)\n benchmark.update(creds)\n benchmark.update(acl)\n ss_api.cimi_add('serviceBenchmarks', benchmark)\n\n\ndef summarize_run(duid, cloud, canned_offer):\n logger.info(\"Running summarizer: %s, %s, %s\" % (duid, cloud, canned_offer))\n run = _query_run(duid, cloud)\n mappers, reducer = _div_node(run['hits'])\n logger.info('summarize_run mappers: %s' % mappers)\n logger.info('summarize_run reducer: %s' % reducer)\n mappers_data_dict, reducer_data = _extract_node_data(mappers, reducer, duid)\n logger.info('summarize_run mappers_data: %s' % mappers_data_dict)\n logger.info('summarize_run reducer_data: %s' % reducer_data)\n\n time_records = _compute_time_records(mappers_data_dict.values(), reducer_data, duid)\n products = _get_products_list(mappers_data_dict.values())\n service_offers = _get_service_offer(mappers, reducer)\n\n _create_run_doc(cloud, canned_offer, time_records, products, service_offers)\n _publish_benchmarks(cloud, canned_offer, time_records, products, service_offers)\n logger.info(\"Done summarizer: %s, %s, %s\" % (duid, cloud, canned_offer))\n\n\nif __name__ == '__main__':\n duid, cloud, offer = sys.argv[1:4]\n ss_username = config_get('ss_username')\n ss_password = config_get('ss_password')\n ss_api.login_internal(ss_username, ss_password)\n summarize_run(duid, cloud, offer)\n","sub_path":"app/dmm/summarizer.py","file_name":"summarizer.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"269219476","text":"\"\"\"This runs the nquads tests for the W3C RDF Working Group's N-Quads\ntest suite.\"\"\"\n\n\nimport os\nfrom test.data import TEST_DATA_DIR\nfrom test.utils.manifest import RDFTest, read_manifest\nfrom test.utils.namespace import RDFT\nfrom typing import Callable, Dict\n\nimport pytest\n\nfrom rdflib import ConjunctiveGraph\nfrom rdflib.term import Node, URIRef\n\nverbose = False\n\n\ndef nquads(test):\n g = ConjunctiveGraph()\n\n try:\n g.parse(test.action, format=\"nquads\")\n if not test.syntax:\n raise AssertionError(\"Input shouldn't have parsed!\")\n except:\n if test.syntax:\n raise\n\n\ntesters: Dict[Node, Callable[[RDFTest], None]] = {\n RDFT.TestNQuadsPositiveSyntax: nquads,\n RDFT.TestNQuadsNegativeSyntax: nquads,\n}\n\n\n@pytest.mark.parametrize(\n \"rdf_test_uri, type, rdf_test\",\n read_manifest(os.path.join(TEST_DATA_DIR, \"suites\", \"w3c/nquads/manifest.ttl\")),\n)\ndef test_manifest(rdf_test_uri: URIRef, type: Node, rdf_test: RDFTest):\n testers[type](rdf_test)\n","sub_path":"test/test_w3c_spec/test_nquads_w3c.py","file_name":"test_nquads_w3c.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"534671988","text":"from dash import dcc, html\nimport dash\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\nfrom app import app\nimport traceback\nimport plotly.express as px\nimport pandas as pd\nfrom apps import generalFunctions\n\n####################################################################################\n## Reading Data data\n####################################################################################\n\ndf = pd.read_csv('./data/Life Expectancy Data.csv')\ndf['Year'] = df['Year'].astype(str)\ncolNames = df[df.dtypes[(df.dtypes==\"float64\")|(df.dtypes==\"int64\")].index.values].columns\n\n##################################################################################\n# Tab layout for Missing Tab Treatment\n##################################################################################\n\noutliersTabBody = dbc.Container(\n [\n html.Br(),\n dbc.Row(\n [\n dbc.Col(\n [\n dbc.Card(\n [\n dbc.Label(html.B('Select Column Name')),\n dcc.Dropdown(\n id='outliers_dropdown',\n options = [{'value': c, 'label':c} for c in colNames],\n className='dropdowns'\n ),\n\n ],\n className='side_panel'\n )\n\n ],\n width=3\n ),\n dbc.Col(\n [\n dcc.Graph(id = 'outliers_fig')\n ],\n width=8\n )\n ],\n align='start'\n )\n ],\n fluid=True\n)\n\n##################################################################################\n# Function to update dropdown\n##################################################################################\n\n@app.callback(\n Output('outliers_fig', 'figure'),\n Input('outliers_dropdown', 'value')\n)\ndef update_output(value):\n try:\n if value is not None:\n fig = px.box(df, y=value)\n fig.update_layout(\n generalFunctions.common_layout,\n width = 1000,\n height = 650\n )\n fig.update_xaxes(generalFunctions.common_Xaxes)\n fig.update_yaxes(generalFunctions.common_Yaxes)\n return fig\n else:\n return dash.no_update\n except Exception as e:\n print(traceback.format_exc())\n","sub_path":"apps/outliersTab.py","file_name":"outliersTab.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"175403179","text":"\"\"\"rttypes.py\n\nDatatypes for general dicom processing including masking, rescaling, and fusion\n\"\"\"\n\nimport sys\nimport os\nimport pdb\nimport logging\nimport warnings\nimport math\nfrom math import ceil, floor\nimport numpy as np\nimport pickle\nimport struct\nimport copy\nimport warnings\nfrom PIL import Image, ImageDraw\nfrom scipy.ndimage import interpolation\n\nfrom . import dcmio, misc\nfrom .misc import ensure_extension\nfrom .fileio.strutils import getFileType, isFileByExt\n\n# initialize module logger\nlogger = logging.getLogger(__name__)\n\n\nclass FrameOfReference:\n \"\"\"Defines a dicom frame of reference to which BaseVolumes can be conformed for fusion of pre-registered\n image data\n \"\"\"\n def __init__(self, start=None, spacing=None, size=None, UID=None):\n \"\"\"Define a dicom frame of reference\n\n Args:\n start -- (x,y,z) describing the start of the FOR (mm)\n spacing -- (x,y,z) describing the spacing of voxels in each direction (mm)\n size -- (x,y,z) describing the number of voxels in each direction (integer)\n UID -- dicom FrameOfReferenceUID can be supplied to support caching in BaseVolume\n\n Standard Anatomical Directions Apply:\n x -> increasing from patient right to left\n y -> increasing from patient anterior to posterior\n z -> increasing from patient inferior to superior\n \"\"\"\n self.start = start\n self.spacing = spacing\n self.size = size\n self.UID = UID\n\n @classmethod\n def fromDatasetList(cls, dataset_list):\n import pydicom # pydicom\n\n # check that all elements are valid slices, if not remove and continue\n nRemoved = 0\n for i, slice in enumerate(dataset_list):\n if (not isinstance(slice, pydicom.dataset.Dataset)):\n logger.debug('invalid type ({t:s}) at idx {i:d}. removing.'.format(\n t=str(type(slice)),\n i=i ) )\n dataset_list.remove(slice)\n nRemoved += 1\n elif (len(slice.dir('ImagePositionPatient')) == 0):\n logger.debug('invalid .dcm image at idx {:d}. removing.'.format(i))\n dataset_list.remove(slice)\n nRemoved += 1\n if (nRemoved > 0):\n logger.info('# slices removed with invalid types: {:d}'.format(nRemoved))\n\n # sort datasets by increasing slicePosition (inferior -> superior)\n dataset_list.sort(key=lambda dataset: dataset.ImagePositionPatient[2], reverse=False)\n\n # build object properties\n start = dataset_list[0].ImagePositionPatient\n spacing = (*dataset_list[0].PixelSpacing, dataset_list[0].SliceThickness)\n try:\n # some modalities don't provide NumberOfSlices attribute\n size = (dataset_list[0].Columns, dataset_list[0].Rows, dataset_list[0].NumberOfSlices)\n except:\n # use length of list instead\n size = (dataset_list[0].Columns, dataset_list[0].Rows, len(dataset_list))\n\n UID = dataset_list[0].FrameOfReferenceUID\n return cls(start, spacing, size, UID)\n\n @classmethod\n def fromDir(cls, path, recursive=False):\n dataset_list = dcmio.read_dicom_dir(path, recursive=recursive, only_headers=True)\n return cls.fromDatasetList(dataset_list)\n\n def copy(self):\n new = FrameOfReference()\n new.start = copy.deepcopy(self.start)\n new.size = copy.deepcopy(self.size)\n new.spacing = copy.deepcopy(self.spacing)\n new.UID = copy.deepcopy(self.UID)\n return new\n\n def __repr__(self):\n return '{!s}:\\n'.format(self.__class__) + \\\n ' start (x,y,z): ({:0.3f}, {:0.3f}, {:0.3f})\\n'.format(*self.start) + \\\n ' spacing (x,y,z): ({:0.3f}, {:0.3f}, {:0.3f})\\n'.format(*self.spacing) + \\\n ' size (x,y,z): ({:d}, {:d}, {:d})\\n'.format(*self.size)\n\n def __eq__(self, compare):\n if (self.start == compare.start and\n self.spacing == compare.spacing and\n self.size == compare.size):\n return True\n else: return False\n\n def changeSpacing(self, new_spacing):\n \"\"\"change frameofreference resolution while maintaining same bounding box\n Changes occur in place, self is returned\n Args:\n new_spacing (3-tuple): spacing expressed as (X, Y, Z)\n \"\"\"\n old_spacing = self.spacing\n old_size = self.size\n self.spacing = new_spacing\n self.size = tuple((np.array(old_size) * np.array(old_spacing) / np.array(self.spacing)).astype(int).tolist())\n return self\n\n def end(self):\n \"\"\"Calculates the (x,y,z) coordinates of the end of the frame of reference (mm)\n \"\"\"\n # compute ends\n end = []\n for i in range(3):\n end.insert(i, self.spacing[i] * self.size[i] + self.start[i])\n\n return tuple(end)\n\n def volume(self):\n \"\"\"Calculates the volume of the frame of reference (mm^3)\n \"\"\"\n length = []\n end = self.end()\n vol = 1\n for i in range(3):\n length.insert(i, end[i] - self.start[i])\n vol *= length[i]\n\n return vol\n\n def getIndices(self, position):\n \"\"\"Takes a position (x, y, z) and returns the indices at that location for this FrameOfReference\n\n Args:\n position -- 3-tuple of position coordinates (mm) in the format: (x, y, z)\n \"\"\"\n indices = []\n for i in range(3):\n indices.insert(i, math.floor(int(round((position[i] - self.start[i]) / self.spacing[i] ))))\n\n return tuple(indices)\n\n\nclass ROI:\n \"\"\"Defines a labeled RTStruct ROI for use in masking and visualization of Radiotherapy contours\n \"\"\"\n def __init__(self, roicontour=None, structuresetroi=None):\n self.roinumber = None\n self.refforuid = None\n self.frameofreference = None\n self.roiname = None\n self.coordslices = []\n # Cached variables\n self.__cache_densemask = None # storage for BaseVolume when consecutive calls to\n # makeDenseMask are made\n # with the same frameofreference object\n\n if roicontour and structuresetroi:\n self._fromDicomDataset(roicontour, structuresetroi)\n\n def __repr__(self):\n return '{!s}:\\n'.format(self.__class__) + \\\n ' roiname: {!s}\\n'.format(self.roiname) + \\\n ' {!s}\\n'.format(self.frameofreference)\n\n @staticmethod\n def _loadRtstructDicom(rtstruct_path):\n \"\"\"load rtstruct dicom data from a direct path or containing directory\"\"\"\n if (not os.path.exists(rtstruct_path)):\n logger.debug('invalid path provided: \"{:s}\"'.format(rtstruct_path))\n raise FileNotFoundError\n\n # check if path is file or dir\n if (os.path.isdir(rtstruct_path)):\n # search recursively for a valid rtstruct file\n ds_list = dcmio.read_dicom_dir(rtstruct_path, recursive=True)\n if (ds_list is None or len(ds_list) == 0):\n logger.debug('no rtstruct datasets found at \"{:s}\"'.format(rtstruct_path))\n raise Exception\n ds = ds_list[0]\n elif (os.path.isfile(rtstruct_path)):\n ds = dcmio.read_dicom(rtstruct_path)\n return ds\n\n def _fromDicomDataset(self, roicontour, structuresetroi):\n \"\"\"takes FrameOfReference object and roicontour/structuresetroi dicom dataset objects and stores\n sorted contour data\n\n Args:\n roicontour -- dicom dataset containing contour point coords for all slices\n structuresetroi -- dicom dataset containing additional information about contour\n \"\"\"\n self.roinumber = int(structuresetroi.ROINumber)\n self.refforuid = str(structuresetroi.ReferencedFrameOfReferenceUID)\n self.roiname = str(structuresetroi.ROIName)\n\n # Populate list of coordslices, each containing a list of ordered coordinate points\n contoursequence = roicontour.ContourSequence\n if (len(contoursequence) <= 0):\n logger.debug('no coordinates found in roi: {:s}'.format(self.roiname))\n else:\n logger.debug('loading roi: {:s} with {:d} slices'.format(self.roiname, len(roicontour.ContourSequence)))\n for coordslice in roicontour.ContourSequence:\n points_list = []\n for x, y, z in misc.grouper(3, coordslice.ContourData):\n points_list.append( (x, y, z) )\n self.coordslices.append(points_list)\n\n # sort by slice position in ascending order (inferior -> superior)\n self.coordslices.sort(key=lambda coordslice: coordslice[0][2], reverse=False)\n\n # # create frameofreference based on the extents of the roi and apparent spacing\n # self.frameofreference = self.getROIExtents()\n\n @classmethod\n def roiFromFile(cls, rtstruct_path, name, casesensitive=True):\n ds = cls._loadRtstructDicom(rtstruct_path)\n if (ds is not None):\n # get structuresetROI sequence\n StructureSetROI_list = ds.StructureSetROISequence\n nContours = len(StructureSetROI_list)\n if (nContours <= 0):\n logger.exception('no contours were found')\n\n for StructureSetROI in StructureSetROI_list:\n if (casesensitive and StructureSetROI.ROIName == name) or (not casesensitive and str(StructureSetROI.ROIName).lower() == name.lower()):\n ROIContour = None\n for ROIContour in ds.ROIContourSequence:\n if ROIContour.ReferencedROINumber == StructureSetROI.ROINumber:\n return cls(ROIContour, StructureSetROI)\n return None\n\n else:\n logger.exception('no dataset was found')\n\n @classmethod\n def collectionFromFile(cls, rtstruct_path, keep_empty=False):\n \"\"\"loads an rtstruct specified by path and returns a dict of ROI objects\n\n Args:\n rtstruct_path -- path to rtstruct.dcm file\n\n Returns:\n dict\n \"\"\"\n ds = cls._loadRtstructDicom(rtstruct_path)\n\n # parse rtstruct file and instantiate maskvolume for each contour located\n # add each maskvolume to dict with key set to contour name and number?\n if (ds is not None):\n # get structuresetROI sequence\n StructureSetROI_list = ds.StructureSetROISequence\n nContours = len(StructureSetROI_list)\n if (nContours <= 0):\n logger.exception('no contours were found')\n\n # Add structuresetROI to dict\n StructureSetROI_dict = {StructureSetROI.ROINumber: StructureSetROI\n for StructureSetROI\n in StructureSetROI_list }\n\n # get dict containing a contour dataset for each StructureSetROI with a paired key=ROINumber\n ROIContour_dict = {ROIContour.ReferencedROINumber: ROIContour\n for ROIContour\n in ds.ROIContourSequence }\n\n # construct a dict of ROI objects where contour name is key\n roi_dict = {}\n for ROINumber, structuresetroi in StructureSetROI_dict.items():\n roi_dict[structuresetroi.ROIName] = (cls(roicontour=ROIContour_dict[ROINumber],\n structuresetroi=structuresetroi))\n # prune empty ROIs from dict\n if not keep_empty:\n for roiname, roi in dict(roi_dict).items():\n if (roi.coordslices is None or len(roi.coordslices) <= 0):\n logger.debug('pruning empty ROI: {:s} from loaded ROIs'.format(roiname))\n del roi_dict[roiname]\n\n logger.debug('loaded {:d} ROIs succesfully'.format(len(roi_dict)))\n return roi_dict\n else:\n logger.exception('no dataset was found')\n\n @staticmethod\n def getROINames(rtstruct_path):\n ds = ROI._loadRtstructDicom(rtstruct_path)\n\n if (ds is not None):\n # get structuresetROI sequence\n StructureSetROI_list = ds.StructureSetROISequence\n nContours = len(StructureSetROI_list)\n if (nContours <= 0):\n logger.exception('no contours were found')\n\n roi_names = []\n for structuresetroi in StructureSetROI_list:\n roi_names.append(structuresetroi.ROIName)\n\n return roi_names\n else:\n logger.exception('no dataset was found')\n\n def makeDenseMaskSlice(self, position, frameofreference=None):\n \"\"\"Takes a FrameOfReference and constructs a dense binary mask for the ROI (1 inside ROI, 0 outside)\n as a numpy 2dArray\n\n Args:\n position -- position of the desired slice (mm) within the frameofreference along z-axis\n frameofreference -- FrameOfReference that defines the position of ROI and size of dense volume\n\n Returns:\n numpy 2dArray\n \"\"\"\n # get FrameOfReference params\n if (frameofreference is None):\n if (self.frameofreference is not None):\n frameofreference = self.frameofreference\n else:\n logger.exception('no frame of reference provided')\n raise Exception\n xstart, ystart, zstart = frameofreference.start\n xspace, yspace, zspace = frameofreference.spacing\n cols, rows, depth = frameofreference.size\n\n # get nearest coordslice\n minerror = 5000\n coordslice = None\n ### REVISIT THE CORRECT SETTING OF TOLERANCE TODO\n tolerance = frameofreference.spacing[2]*0.95 - 1e-9 # if upsampling too much then throw error\n for slice in self.coordslices:\n # for each list of coordinate tuples - check the slice for distance from position\n error = abs(position - slice[0][2])\n if error <= minerror:\n # if minerror != 5000:\n # logger.info('position:{:0.3f} | slicepos:{:0.3f}'.format(position, slice[0][2]))\n # logger.info('improved with error {:f}'.format(error))\n minerror = error\n coordslice = slice\n # logger.debug('updating slice')\n else:\n # we've already passed the nearest slice, break\n break\n\n # check if our result is actually valid or we just hit the end of the array\n if coordslice and minerror >= tolerance:\n logger.debug('No slice found within {:f} mm of position {:f}'.format(tolerance, position))\n # print(minerror, tolerance)\n # print(position)\n # print(zstart, zspace*depth)\n # for slice in self.coordslices:\n # if abs(slice[0][2]-position) < 100:\n # print(slice[0][2])\n return np.zeros((rows, cols))\n # raise Exception('Attempt to upsample ROI to densearray beyond 5x')\n logger.debug('slice found at {:f} for position query at {:f}'.format(coordslice[0][2], position))\n\n # get coordinate values\n index_coords = []\n for x, y, z in coordslice:\n # shift x and y and scale appropriately\n x_idx = int(round((x-xstart)/xspace))\n y_idx = int(round((y-ystart)/yspace))\n index_coords.append( (x_idx, y_idx) )\n\n # use PIL to draw the polygon as a dense image (PIL uses shape: (width, height))\n im = Image.new('1', (cols, rows), color=0)\n imdraw = ImageDraw.Draw(im)\n imdraw.polygon(index_coords, fill=1, outline=None)\n del imdraw\n\n # convert from PIL image to np.ndarray and threshold to binary\n return np.array(im.getdata()).reshape((rows, cols))\n\n def makeDenseMask(self, frameofreference=None):\n \"\"\"Takes a FrameOfReference and constructs a dense binary mask for the ROI (1 inside ROI, 0 outside)\n as a BaseVolume\n\n Args:\n frameofreference -- FrameOfReference that defines the position of ROI and size of dense volume\n\n Returns:\n BaseVolume\n \"\"\"\n # get FrameOfReference params\n if (frameofreference is None):\n if (self.frameofreference is not None):\n frameofreference = self.frameofreference\n else:\n logger.exception('no frame of reference provided')\n raise Exception\n\n # check cache for similarity between previously and currently supplied frameofreference objects\n if (self.__cache_densemask is not None\n and frameofreference == self.__cache_densemask.frameofreference):\n # cached mask frameofreference is similar to current, return cached densemask volume\n # logger.debug('using cached dense mask volume')\n return self.__cache_densemask\n else:\n xstart, ystart, zstart = frameofreference.start\n xspace, yspace, zspace = frameofreference.spacing\n cols, rows, depth = frameofreference.size\n\n # generate binary mask for each slice in frameofreference\n maskslicearray_list = []\n # logger.debug('making dense mask volume from z coordinates: {:f} to {:f}'.format(\n # zstart, (zspace * (depth+1) + zstart)))\n for i in range(depth):\n position = zstart + i * zspace\n # get a slice at every position within the current frameofreference\n densemaskslice = self.makeDenseMaskSlice(position, frameofreference)\n maskslicearray_list.append(densemaskslice.reshape((1, *densemaskslice.shape)))\n\n # construct BaseVolume from dense slice arrays\n densemask = BaseVolume.fromArray(np.concatenate(maskslicearray_list, axis=0), frameofreference)\n self.__cache_densemask = densemask\n return densemask\n\n def getROIExtents(self, spacing=None):\n \"\"\"Creates a tightly bound frame of reference around the ROI which allows visualization in a cropped\n frame\n \"\"\"\n # guess at spacing and assign arbitrarily where necessary\n # get list of points first\n point_list = []\n for slice in self.coordslices:\n for point3d in slice:\n point_list.append(point3d)\n\n # set actually z spacing estimated from separation of coordslice point lists\n min_z_space = 9999\n prev_z = point_list[0][2]\n for point3d in point_list[1:]:\n z = point3d[2]\n this_z_space = abs(z-prev_z)\n if (this_z_space > 0 and this_z_space < min_z_space):\n min_z_space = this_z_space\n prev_z = z\n\n if (min_z_space <= 0 or min_z_space > 10):\n # unreasonable result found, arbitrarily set\n new_z_space = 1\n logger.debug('unreasonable z_spacing found: {:0.3f}, setting to {:0.3f}'.format(\n min_z_space, new_z_space))\n min_z_space = new_z_space\n else:\n logger.debug('estimated z_spacing: {:0.3f}'.format(min_z_space))\n\n # arbitrarily set spacing\n if spacing is None:\n spacing = (1, 1, min_z_space)\n warnings.warn('Inferred spacing is deprecated in favor of manual specification. Please change code immediately to ensure correctness', DeprecationWarning)\n else:\n if min_z_space != spacing[2]:\n warnings.warn('Inferred slice thickness from rtstruct ({0:g}) not equal to user specified ({:g}). Using user specification ({1:g})'.format(min_z_space, spacing[2]))\n\n # get start and end of roi volume extents\n global_limits = {'xmax': -5000,\n 'ymax': -5000,\n 'zmax': -5000,\n 'xmin': 5000,\n 'ymin': 5000,\n 'zmin': 5000 }\n for slice in self.coordslices:\n # convert coords list to ndarray\n coords = np.array(slice)\n (xmin, ymin, zmin) = tuple(coords.min(axis=0, keepdims=False))\n (xmax, ymax, zmax) = tuple(coords.max(axis=0, keepdims=False))\n\n # update limits\n if xmin < global_limits['xmin']:\n global_limits['xmin'] = xmin\n if ymin < global_limits['ymin']:\n global_limits['ymin'] = ymin\n if zmin < global_limits['zmin']:\n global_limits['zmin'] = zmin\n if xmax > global_limits['xmax']:\n global_limits['xmax'] = xmax\n if ymax > global_limits['ymax']:\n global_limits['ymax'] = ymax\n if zmax > global_limits['zmax']:\n global_limits['zmax'] = zmax\n\n # build FrameOfReference\n start = (global_limits['xmin'],\n global_limits['ymin'],\n global_limits['zmin'] )\n size = (int(ceil((global_limits['xmax'] - global_limits['xmin']) / spacing[0])),\n int(ceil((global_limits['ymax'] - global_limits['ymin']) / spacing[1])),\n int(ceil((global_limits['zmax'] - global_limits['zmin']) / spacing[2])) )\n\n logger.debug('ROIExtents:\\n'\n ' start: {:s}\\n'\n ' spacing: {:s}\\n'\n ' size: {:s}'.format(str(start), str(spacing), str(size)))\n frameofreference = FrameOfReference(start, spacing, size, UID=None)\n return frameofreference\n\n def toPickle(self, path):\n \"\"\"convenience function for storing ROI to pickle file\"\"\"\n warnings.warn('ROI.toPickle() will be deprecated soon in favor of other serialization methods.', DeprecationWarning)\n _dirname = os.path.dirname(path)\n if (_dirname and _dirname is not ''):\n os.makedirs(_dirname, exist_ok=True)\n with open(path, 'wb') as p:\n pickle.dump(self, p)\n\n @staticmethod\n def fromPickle(path):\n \"\"\"convenience function for restoring ROI from pickle file\"\"\"\n warnings.warn('ROI.fromPickle() will be deprecated soon in favor of other serialization methods.', DeprecationWarning)\n with open(path, 'rb') as p:\n return pickle.load(p)\n\n def toHDF5(self, path):\n \"\"\"serialize object to file in h5 format\"\"\"\n import h5py\n path = ensure_extension(path, '.h5')\n with h5py.File(path, 'w') as f:\n # store attributes\n f.attrs['roinumber'] = self.roinumber\n f.attrs['roiname'] = self.roiname\n f.attrs['refforuid'] = self.refforuid\n f.attrs['FrameOfReference.start'] = self.frameofreference.start\n f.attrs['FrameOfReference.spacing'] = self.frameofreference.spacing\n f.attrs['FrameOfReference.size'] = self.frameofreference.size\n f.attrs['fileversion'] = '1.0'\n\n # store datasets\n g = f.create_group('coordslices')\n g.attrs['Nslices'] = len(self.coordslices)\n for i, slice in enumerate(self.coordslices):\n arr = np.array(slice)\n g.create_dataset('{:04d}'.format(i), data=arr)\n\n @classmethod\n def fromHDF5(cls, path):\n \"\"\"reconstruct object from serialized data in h5 format\"\"\"\n import h5py\n self = cls()\n path = ensure_extension(path, '.h5')\n with h5py.File(path, 'r') as f:\n self.roinumber = int(f.attrs['roinumber'])\n self.roiname = str(f.attrs['roiname'])\n self.refforuid = str(f.attrs['refforuid'])\n self.frameofreference = FrameOfReference(\n tuple(f.attrs['FrameOfReference.start']),\n tuple(f.attrs['FrameOfReference.spacing']),\n tuple(f.attrs['FrameOfReference.size'])\n )\n self.coordslices = []\n for k in sorted(f['coordslices'].keys()):\n points = []\n data = f['coordslices'][k]\n npdata = np.empty(data.shape, dtype=data.dtype)\n data.read_direct(npdata)\n for i in range(data.shape[0]):\n points.append(tuple(npdata[i, :]))\n self.coordslices.append(points)\n return self\n\n\n\nclass BaseVolume:\n \"\"\"Defines basic storage for volumetric voxel intensities within a dicom FrameOfReference\n \"\"\"\n def __init__(self):\n \"\"\"Entrypoint to class, initializes members\n \"\"\"\n self.data = None\n self.init_object = None\n self.frameofreference = None\n self.modality = None\n self.feature_label = None\n self.valid_exts = set()\n\n def __repr__(self):\n return '{!s}:\\n'.format(self.__class__) + \\\n ' modality: {!s}\\n'.format(self.modality) + \\\n ' feature_label: {!s}\\n'.format(self.feature_label) + \\\n ' {!s}\\n'.format(self.frameofreference)\n\n @property\n def nslices(self):\n if len(self.frameofreference.size)>=3:\n return self.frameofreference.size[-1]\n else:\n return 1\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, v):\n self._data = v\n\n @property\n def array(self):\n warnings.warn('use of BaseVolume.array property is deprecated. use BaseVolume.data instead')\n return self.data\n\n @array.setter\n def array(self, v):\n warnings.warn('use of BaseVolume.array property is deprecated. use BaseVolume.data instead')\n self.data = v\n\n @property\n def frame(self):\n return self.frameofreference\n\n @frame.setter\n def frame(self, v):\n self.frameofreference = v\n\n def astype(self, type):\n self.data = self.data.astype(type)\n return self\n\n def _getDataDict(self):\n xstr = misc.xstr # shorter call-name for use in function\n return {'arraydata': self.data,\n 'size': self.frameofreference.size[::-1],\n 'start': self.frameofreference.start[::-1],\n 'spacing': self.frameofreference.spacing[::-1],\n 'for_uid': xstr(self.frameofreference.UID),\n 'modality': xstr(self.modality),\n 'feature_label': xstr(self.feature_label),\n 'order': 'ZYX'\n }\n\n @classmethod\n def load(cls, fname, frameofreference=None, recursive=False):\n if os.path.isfile(fname):\n constructorByType = {'.nii': cls.fromNII,\n '.nii.gz': cls.fromNII,\n '.dcm': cls.fromDicom,\n '.mag': cls.fromDicom,\n '.mat': cls.fromMatlab,\n '.pickle': cls.fromPickle,\n '.raw': cls.fromBinary,\n '.png': cls.fromImage,\n '.jpg': cls.fromImage,\n '.jpeg': cls.fromImage,\n None: cls.fromBinary,\n '.h5': cls.fromHDF5}\n return constructorByType[getFileType(fname)](fname)\n elif os.path.isdir(fname):\n vols = []\n # collect all full paths to dirs containing medical image files\n for dirpath, dirnames, filenames in os.walk(fname, followlinks=True):\n for f in filenames:\n if isFileByExt(f, '.dcm') or isFileByExt(f, '.mag'):\n try:\n vols.append(cls.fromDir(dirpath))\n break\n except Exception as e:\n logger.warning('failed to open dicom directory: \"{}\"\\n{}'.format(dirpath, e))\n if not recursive: break\n if len(vols) > 1: return vols\n elif len(vols)==1: return vols[0]\n else: raise RuntimeError('Failed to load')\n\n @classmethod\n def fromArray(cls, array, frameofreference=None):\n \"\"\"Constructor: from a numpy array and FrameOfReference object\n\n Args:\n array -- numpy array\n frameofreference -- FrameOfReference object\n \"\"\"\n # ensure array matches size in frameofreference\n self = cls()\n if array.ndim == 2:\n array = np.atleast_3d(array)\n if frameofreference is not None:\n self.data = array.reshape(frameofreference.size[::-1])\n self.frameofreference = frameofreference\n else:\n self.data = array\n self.frameofreference = FrameOfReference((0,0,0), (1,1,1), (*array.shape[::-1], 1))\n\n return self\n\n @classmethod\n def fromImage(cls, fname, frameofreference=None, normalize=True):\n with open(fname, 'rb') as fd:\n im = Image.open(fd, 'r')\n if im.mode in ['1', 'L', 'P']:\n dim = 1\n if im.mode=='P':\n im = im.convert('L')\n elif im.mode in ['RGB', 'YCbCr']:\n dim = 3\n elif im.mode in ['RGBA', 'CMYK']:\n dim = 4\n else:\n raise RuntimeError(\"Couldn't determine dimensionality of image with mode=\\\"{!s}\\\"\".format(im.mode))\n maxint = 255 # assume all 8-bit per channel\n arr = np.asarray(im).transpose([2,0,1])\n if normalize:\n # normalize to [0,1]\n arr = arr.astype('float32')\n arr /= maxint\n\n # def plotChannels(arr):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=(9,3))\n titles = ['red', 'green', 'blue']\n for i in range(arr.shape[0]):\n ax = fig.add_subplot(1,3,i+1)\n ax.imshow(arr[i,:,:], cmap=\"Greys\")\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n ax.set_title(titles[i])\n plt.show()\n\n if frameofreference is None:\n frame = FrameOfReference((0,0,0), (1,1,1), arr.shape)\n return cls.fromArray(arr, frame)\n\n def toImage(self, fname, mode='L', resize=None, cmap='Set3'):\n array = self.data\n array = np.squeeze(array)\n if array.ndim != 2:\n raise RuntimeError('Saving image with ndim={} is not supported'.format(array.ndim))\n\n if mode in ['RGB', 'RGBA']:\n # convert integer class ids to rgb colors according to cmap\n rng = abs(np.max(array)-np.min(array))\n if rng == 0: rng = 1\n normarray = (array - np.min(array)) / rng\n im = Image.fromarray(np.uint8(plt.cm.get_cmap(cmap)(normarray)*255))\n elif mode in ['P']:\n # separates gray values so they can be distinguished\n array*=math.floor((255 / len(np.unique(array))))\n im = Image.fromarray(array.astype('uint8'))\n elif mode in ['1', 'L', 'P']:\n im = Image.fromarray(array.astype('uint8'))\n else: raise RuntimeError\n\n # restore image to original dims\n if isinstance(resize, numbers.Number) and resize>0 and not resize==1:\n im = im.resize( [int(resize*s) for s in im.size], resample=Image.NEAREST)\n\n fname = ensure_extension(fname, '.png')\n im.save(fname)\n logger.debug('file saved to {}'.format(fname))\n\n\n @classmethod\n def fromDir(cls, path, recursive=False):\n \"\"\"constructor: takes path to directory containing dicom files and builds a sorted array\n\n Args:\n recursive -- find dicom files in all subdirectories?\n \"\"\"\n # get the datasets from files\n dataset_list = dcmio.read_dicom_dir(path, recursive=recursive)\n\n # pass dataset list to constructor\n self = cls.fromDatasetList(dataset_list)\n\n return self\n\n @classmethod\n def fromBinary(cls, path, frameofreference):\n \"\"\"constructor: takes path to binary file (neylon .raw)\n data is organized as binary float array in row-major order\n\n Args:\n path (str): path to .raw file in binary format\n frameofreference (FOR): most importantly defines mapping from 1d to 3d array\n \"\"\"\n if not os.path.isfile(path) or os.path.splitext(path)[1].lower() not in ['.raw', '.bin', None, '']:\n raise Exception('data is not formatted properly. must be one of [.raw, .bin]')\n\n if not isinstance(frameofreference, FrameOfReference):\n if not isinstance(frameofreference, tuple):\n raise TypeError('frameofreference must be a valid FrameOfReference or tuple of dimensions')\n frameofreference = FrameOfReference(start=(0,0,0), spacing=(1,1,1), size=frameofreference)\n\n with open(path, mode='rb') as f:\n flat = f.read()\n _shape = frameofreference.size[::-1]\n _expected_n = np.product(_shape)\n thetype = None\n for type in ['f', 'd']:\n _n = int(os.path.getsize(path)/struct.calcsize(type))\n if _n != _expected_n:\n logger.debug('filesize ({:f}) doesn\\'t match expected ({:f}) size'.format(\n os.path.getsize((path)), struct.calcsize(type)*_expected_n\n ))\n else:\n thetype = type\n break\n if thetype is None:\n raise RuntimeError(\"filesize ({:f}) doesn't match expected size ({:f})\".format(\n os.path.getsize((path)), struct.calcsize('f')*_expected_n\n ))\n s = struct.unpack(thetype*_n, flat)\n vol = np.array(s).reshape(_shape)\n # vol[vol>1e10] = 0\n # vol[vol<-1e10] = 0\n return cls.fromArray(vol, frameofreference)\n\n @classmethod\n def fromDicom(cls, fname):\n return cls.fromDatasetList([dcmio.read_dicom(fname)])\n\n def toDicom(self, dname, fprefix=''):\n import pydicom # pydicom\n SeriesInstanceUID = pydicom.uid.generate_uid()\n StudyInstanceUID = pydicom.uid.generate_uid()\n FrameOfReferenceUID = pydicom.uid.generate_uid()\n min_val = np.min(self.data)\n for i in range(self.frameofreference.size[2]):\n ds = dcmio.make_dicom_boilerplate(SeriesInstanceUID, StudyInstanceUID, FrameOfReferenceUID)\n ds.SliceThickness = self.frameofreference.spacing[2]\n ds.PixelSpacing = list(self.frameofreference.spacing[:2])\n ds.SliceLocation = self.frameofreference.start[2] + i*self.frameofreference.spacing[2]\n ds.ImagePositionPatient = [*self.frameofreference.start[:2], ds.SliceLocation]\n ds.Columns = self.frameofreference.size[0]\n ds.Rows = self.frameofreference.size[1]\n ds.AcquisitionNumber = i+1\n ds.Modality = self.modality if self.modality is not None else ''\n ds.DerivationDescription = self.feature_label if self.feature_label is not None else ''\n ds.PixelData = ((self.data[i, :, :]-min_val).flatten().astype(np.uint16)).tostring()\n ds.RescaleSlope = 1.0\n ds.RescaleIntercept = floor(min_val)\n ds.PixelRepresentation = 0 # unsigned integers\n os.makedirs(dname, exist_ok=True)\n ds.save_as(os.path.join(dname, '{}{:04d}.dcm'.format(fprefix, i)))\n\n @classmethod\n def fromDatasetList(cls, dataset_list):\n \"\"\"constructor: takes a list of dicom slice datasets and builds a BaseVolume array\n Args:\n slices\n \"\"\"\n import pydicom # pydicom\n self = cls()\n if (dataset_list is None):\n raise ValueError('no valid dataset_list provided')\n\n # check that all elements are valid slices, if not remove and continue\n nRemoved = 0\n for i, slice in enumerate(dataset_list):\n if (not isinstance(slice, pydicom.dataset.Dataset)):\n logger.debug('invalid type ({t:s}) at idx {i:d}. removing.'.format(\n t=str(type(slice)),\n i=i ) )\n dataset_list.remove(slice)\n nRemoved += 1\n elif (len(slice.dir('ImagePositionPatient')) == 0):\n logger.debug('invalid .dcm image at idx {:d}. removing.'.format(i))\n dataset_list.remove(slice)\n nRemoved += 1\n if (nRemoved > 0):\n logger.info('# slices removed with invalid types: {:d}'.format(nRemoved))\n\n # sort datasets by increasing slicePosition (inferior -> superior)\n dataset_list.sort(key=lambda dataset: dataset.ImagePositionPatient[2], reverse=False)\n\n # build object properties\n start = dataset_list[0].ImagePositionPatient\n spacing = (*dataset_list[0].PixelSpacing, dataset_list[0].SliceThickness)\n try:\n # some modalities don't provide NumberOfSlices attribute\n size = (dataset_list[0].Columns, dataset_list[0].Rows, dataset_list[0].NumberOfSlices)\n except:\n # use length of list instead\n size = (dataset_list[0].Columns, dataset_list[0].Rows, len(dataset_list))\n\n UID = dataset_list[0].FrameOfReferenceUID\n self.frameofreference = FrameOfReference(start, spacing, size, UID)\n\n # standardize modality labels\n mod = dataset_list[0].Modality\n if (mod == 'PT'):\n mod = 'PET'\n self.modality = mod\n\n # construct 3dArray\n array_list = []\n for dataset in dataset_list:\n array = dataset.pixel_array.astype(np.int16)\n factor = dataset.RescaleSlope\n offset = dataset.RescaleIntercept\n array = array * factor + offset\n array = array.reshape((1, array.shape[0], array.shape[1]))\n array_list.append(array)\n\n # stack arrays\n self.data = np.concatenate(array_list, axis=0)\n # self.data = self.data.astype(int)\n return self\n\n @classmethod\n def fromPickle(cls, path):\n \"\"\"initialize BaseVolume from unchanging format so features can be stored and recalled long term\n \"\"\"\n warnings.warn('{!s}.fromPickle() will be deprecated soon in favor of other serialization methods.'.format(cls.__name__), DeprecationWarning)\n path = ensure_extension(path, '.pickle')\n if (not os.path.exists(path)):\n logger.info('file at path: {:s} doesn\\'t exists'.format(path))\n with open(path, 'rb') as p:\n # added to fix broken module refs in old pickles\n sys.modules['utils'] = sys.modules[__name__]\n sys.modules['utils.rttypes'] = sys.modules[__name__]\n basevolumeserial = pickle.load(p)\n del sys.modules['utils.rttypes']\n del sys.modules['utils']\n\n # import data to this object\n try:\n self = cls()\n self.data = basevolumeserial.dataarray\n self.frameofreference = FrameOfReference(basevolumeserial.startposition,\n basevolumeserial.spacing,\n basevolumeserial.size)\n self.modality = basevolumeserial.modality\n self.feature_label = basevolumeserial.feature_label\n except:\n raise SerialOutdatedError()\n return self\n\n def toPickle(self, path):\n \"\"\"store critical data to unchanging format that can be pickled long term\n \"\"\"\n warnings.warn('{!s}.toPickle() will be deprecated soon in favor of other serialization methods.'.format(self.__class__), DeprecationWarning)\n basevolumeserial = BaseVolumeSerial()\n basevolumeserial.startposition = self.frameofreference.start\n basevolumeserial.spacing = self.frameofreference.spacing\n basevolumeserial.size = self.frameofreference.size\n basevolumeserial.dataarray = self.data\n basevolumeserial.modality = self.modality\n basevolumeserial.feature_label = self.feature_label\n\n path = ensure_extension(path, '.pickle')\n _dirname = os.path.dirname(path)\n if (_dirname and _dirname is not ''):\n os.makedirs(_dirname, exist_ok=True)\n with open(path, 'wb') as p:\n pickle.dump(basevolumeserial, p)\n\n @classmethod\n def fromMatlab(cls, path):\n \"\"\"restore BaseVolume from .mat file that was created using BaseVolume.toMatlab() \"\"\"\n import scipy.io # savemat -> save to .mat\n path = ensure_extension(path, '.mat')\n extract_str = misc.numpy_safe_string_from_array\n data = scipy.io.loadmat(path, appendmat=True)\n # for key, obj in data.items():\n # print('{!s}({!s}: {!s}'.format(key, type(obj), obj))\n converted_data = {\n 'arraydata': data['arraydata'],\n 'size': tuple(data['size'][0,:])[::-1],\n 'start': tuple(data['start'][0,:])[::-1],\n 'spacing': tuple(data['spacing'][0,:])[::-1],\n 'for_uid': extract_str(data['for_uid']),\n 'modality': extract_str(data['modality']),\n 'feature_label': extract_str(data['feature_label']),\n 'order': extract_str(data['order'])\n }\n\n # construct new volume\n self = cls()\n self.data = converted_data['arraydata']\n self.frameofreference = FrameOfReference(converted_data['start'],\n converted_data['spacing'],\n converted_data['size'],\n converted_data['for_uid'])\n self.modality = converted_data['modality']\n self.feature_label = converted_data['feature_label']\n\n return self\n\n\n def toMatlab(self, path, compress=False):\n \"\"\"store critical data to .mat file compatible with matlab loading\n This is essentially .toPickle() with compat. for matlab reading\n\n Optional Args:\n compress (bool): compress dataarray at the cost of write speed\n \"\"\"\n import scipy.io # savemat -> save to .mat\n # first represent as dictionary for savemat()\n data = self._getDataDict()\n data['order'] = 'ZYX'\n path = ensure_extension(path, '.mat')\n\n # write to .mat\n scipy.io.savemat(path, data, appendmat=False, format='5', long_field_names=False,\n do_compression=compress, oned_as='row')\n\n def toHDF5(self, path, compress=False):\n \"\"\"store object to hdf5 file with image data stored as dataset and metadata as attributes\"\"\"\n import h5py\n data = self._getDataDict()\n arraydata = data.pop('arraydata')\n path = ensure_extension(path, '.h5')\n with h5py.File(path, 'w') as f:\n for k, v in data.items():\n f.attrs.__setitem__(k, v)\n f.create_dataset('arraydata', data=arraydata)\n f.attrs['fileversion'] = '1.0'\n\n def _fromDoseH5(self, path):\n \"\"\"load from dosecalc defined h5 file\"\"\"\n import h5py\n with h5py.File(path, 'r') as f:\n ad = f['dose']\n self.data = np.empty(ad.shape)\n ad.read_direct(self.data)\n self.data = np.array(self.data)\n self.frameofreference = FrameOfReference(\n tuple(ad.attrs['dicom_start_cm'])[::-1],\n tuple(ad.attrs['voxel_size_cm'])[::-1],\n tuple(ad.shape)[::-1]\n )\n return self\n\n def _fromH5(self, path):\n \"\"\"load from pymedimage defined h5 file\"\"\"\n import h5py\n extract_str = misc.numpy_safe_string_from_array\n with h5py.File(path, 'r') as f:\n ad = f['arraydata']\n self.data = np.empty(ad.shape)\n ad.read_direct(self.data)\n self.data = np.array(self.data)\n self.frameofreference = FrameOfReference(\n tuple(f.attrs['start'])[::-1],\n tuple(f.attrs['spacing'])[::-1],\n tuple(f.attrs['size'])[::-1],\n extract_str(f.attrs['for_uid'])\n )\n self.modality = f.attrs['modality']\n self.feature_label = f.attrs['feature_label']\n\n @classmethod\n def fromHDF5(cls, path):\n \"\"\"restore objects from hdf5 file with image data stored as dataset and metadata as attributes\"\"\"\n # construct new volume\n self = cls()\n path = ensure_extension(path, '.h5')\n loaded = False\n except_msgs = []\n for meth in [self._fromDoseH5, self._fromH5]:\n try:\n meth(path)\n loaded = True\n break\n except Exception as e: except_msgs.append(str(e))\n if not loaded:\n raise RuntimeError('failed to load \"{!s}\"\\n{!s}'.format(path, '\\n'.join(except_msgs)))\n return self\n\n def toImage(self, fname):\n if self.nslices > 1:\n ext = os.path.splitext(fname)[1]\n for i in range(self.nslices):\n fname = fname.replace(ext, '_{:0.4d}.{}'.format(i, ext))\n arr = self.data[i,:,:].reshape(self.frameofreference.size[0:2:-1])\n arr = (arr-np.min(arr))/(np.max(arr)-np.min(arr)) * 255\n im = Image.fromarray(arr).convert('L')\n im.save(fname)\n else:\n arr = self.data[0,:,:].reshape(self.frameofreference.size[-2:-4:-1])\n arr = (arr-np.min(arr))/(np.max(arr)-np.min(arr)) * 255\n im = Image.fromarray(arr).convert('L')\n im.save(fname)\n\n def toNII(self, fname, affine=None):\n import nibabel as nib\n if affine is None:\n logger.warning('No information about global coordinate system provided')\n affine = np.diag([1,1,1,1])\n\n fname = ensure_extension(fname, '.nii')\n img = nib.Nifti1Image(self.data, affine)\n img.to_filename(fname)\n return fname\n\n @classmethod\n def fromNII(cls, fname):\n import nibabel as nib\n img = nib.load(fname)\n h = img.header\n # TODO: add support for non-axially oriented slices (with affine view transformation)\n data = np.transpose(img.get_data(), (2,1,0))\n frame = FrameOfReference((0,0,0), h.get_zooms(), h.get_data_shape())\n self = cls.fromArray(data, frame)\n self.init_object = img\n return self\n\n\n # PUBLIC METHODS\n def conformTo(self, frameofreference):\n \"\"\"Resamples the current BaseVolume to the supplied FrameOfReference\n\n Args:\n frameofreference -- FrameOfReference object to resample the Basevolume to\n\n Returns:\n BaseVolume\n \"\"\"\n # conform volume to alternate FrameOfReference\n if (frameofreference is None):\n logger.exception('no FrameOfReference provided')\n raise ValueError\n elif (ROI.__name__ in (str(type(frameofreference)))):\n frameofreference = frameofreference.frameofreference\n elif (FrameOfReference.__name__ not in str(type(frameofreference))): # This is an ugly way of type-checking but cant get isinstance to see both as the same\n logger.exception(('supplied frameofreference of type: \"{:s}\" must be of the type: \"FrameOfReference\"'.format(\n str(type(frameofreference)))))\n raise TypeError\n\n if self.frameofreference == frameofreference:\n return self\n\n # first match self resolution to requested resolution\n zoomarray, zoomFOR = self._resample(frameofreference.spacing)\n\n # crop to active volume of requested FrameOfReference in frameofreference\n xstart_idx, ystart_idx, zstart_idx = zoomFOR.getIndices(frameofreference.start)\n # xend_idx, yend_idx, zend_idx = zoomFOR.getIndices(frameofreference.end())\n # force new size to match requested FOR size\n xend_idx, yend_idx, zend_idx = tuple((np.array((xstart_idx, ystart_idx, zstart_idx)) + np.array(frameofreference.size)).tolist())\n try:\n cropped = zoomarray[zstart_idx:zend_idx, ystart_idx:yend_idx, xstart_idx:xend_idx]\n zoomFOR.start = frameofreference.start\n zoomFOR.size = cropped.shape[::-1]\n except:\n logger.exception('request to conform to frame outside of volume\\'s frame of reference failed')\n raise Exception()\n\n # reconstruct volume from resampled array\n resampled_volume = MaskableVolume.fromArray(cropped, zoomFOR)\n resampled_volume.modality = self.modality\n resampled_volume.feature_label = self.feature_label\n return resampled_volume\n\n def _resample(self, new_voxelsize=None, mode='nearest', order=3, zoom_factors=None):\n if zoom_factors is None and new_voxelsize is None: raise RuntimeError('must set either factor or new_voxelsize')\n if zoom_factors is not None and not isinstance(zoom_factors, list) and not isinstance(zoom_factors, tuple):\n zoom_factors = tuple([zoom_factors]*self.data.ndim)\n\n if new_voxelsize is not None and zoom_factors is None:\n if new_voxelsize == self.frameofreference.spacing:\n # no need to resample\n return (self.data, self.frameofreference)\n # voxelsize spec is in order (X,Y,Z) but array is kept in order (Z, Y, X)\n zoom_factors = np.true_divide(self.frameofreference.spacing, new_voxelsize)\n\n logger.debug('resizing volume with factors (xyz): {!s}'.format(zoom_factors))\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n zoomarray = interpolation.zoom(self.data, zoom_factors[::-1], order=order, mode=mode)\n zoomFOR = FrameOfReference(self.frameofreference.start, new_voxelsize, zoomarray.shape[::-1])\n return (zoomarray, zoomFOR)\n\n def resample(self, *args, **kwargs):\n \"\"\"resamples volume to new voxelsize\n\n Args:\n new_voxelsize: 3 tuple of voxel size in mm in the order (X, Y, Z)\n\n \"\"\"\n zoomarray, zoomFOR = self._resample(*args, **kwargs)\n new_vol = MaskableVolume.fromArray(zoomarray, zoomFOR)\n new_vol.modality = self.modality\n new_vol.feature_label = self.feature_label\n return new_vol\n\n def getSlice(self, idx, axis=0, flatten=False):\n \"\"\"Extracts 2dArray of idx along the axis.\n Args:\n idx -- idx identifying the slice along axis\n\n Optional Args:\n axis -- specifies axis along which to extract\n Uses depth-row major ordering:\n axis=0 -> depth: axial slices inf->sup\n axis=1 -> rows: coronal slices anterior->posterior\n axis=2 -> cols: sagittal slices: pt.right->pt.left\n flatten -- return a 1darray in depth-stacked row-major order\n \"\"\"\n cols, rows, depth = self.frameofreference.size\n\n # perform index bounding\n if (axis==0):\n if (idx < 0 or idx >= depth):\n logger.exception('index out of bounds. must be between 0 -> {:d}'.format(depth-1))\n raise IndexError\n thisslice = self.data[idx, :, :]\n elif (axis==1):\n if (idx < 0 or idx >= rows):\n logger.exception('index out of bounds. must be between 0 -> {:d}'.format(rows-1))\n raise IndexError\n thisslice = self.data[:, idx, :]\n elif (axis==2):\n if (idx < 0 or idx >= cols):\n logger.exception('index out of bounds. must be between 0 -> {:d}'.format(cols-1))\n raise IndexError\n thisslice = self.data[:, :, idx]\n else:\n logger.exception('invalid axis supplied. must be between 0 -> 2')\n raise ValueError\n\n # RESHAPE\n if (flatten):\n thisslice = thisslice.flatten(order='C').reshape((-1, 1))\n\n return thisslice\n\n def vectorize(self):\n \"\"\"flatten self.data in stacked-depth row-major order\n \"\"\"\n return self.data.flatten(order='C').reshape((-1, 1))\n\n def get_val(self, z, y, x):\n \"\"\"take xyz indices and return the value in array at that location\n \"\"\"\n frameofreference = self.frameofreference\n # get volume size\n (cols, rows, depth) = frameofreference.size\n\n # perform index bounding\n if (x < 0 or x >= cols):\n logger.exception('x index ({:d}) out of bounds. must be between 0 -> {:d}'.format(x, cols-1))\n raise IndexError\n if (y < 0 or y >= rows):\n logger.exception('y index ({:d}) out of bounds. must be between 0 -> {:d}'.format(y, rows-1))\n raise IndexError\n if (z < 0 or z >= depth):\n logger.exception('z index ({:d}) out of bounds. must be between 0 -> {:d}'.format(z, depth-1))\n raise IndexError\n\n return self.data[z, y, x]\n\n def set_val(self, z, y, x, value):\n \"\"\"take xyz indices and value and reassing the value in array at that location\n \"\"\"\n frameofreference = self.frameofreference\n # get volume size\n (cols, rows, depth) = frameofreference.size\n\n # perform index bounding\n if (x < 0 or x >= cols):\n logger.exception('x index ({:d}) out of bounds. must be between 0 -> {:d}'.format(x, cols-1))\n raise IndexError\n if (y < 0 or y >= rows):\n logger.exception('y index ({:d}) out of bounds. must be between 0 -> {:d}'.format(y, rows-1))\n raise IndexError\n if (z < 0 or z >= depth):\n logger.exception('z index ({:d}) out of bounds. must be between 0 -> {:d}'.format(z, depth-1))\n raise IndexError\n\n # reassign value\n self.data[z, y, x] = value\n\n\nclass MaskableVolume(BaseVolume):\n \"\"\"Subclass of BaseVolume that adds support for ROI masking of the data array\n \"\"\"\n def __init__(self):\n \"\"\"Entry point to class\"\"\"\n # call to base class initializer\n BaseVolume.__init__(self)\n\n def conformTo(self, frameofreference):\n \"\"\"Resamples the current MaskableVolume to the supplied FrameOfReference and returns a new Volume\n\n Args:\n frameofreference -- FrameOfReference object to resample the MaskableVolume to\n\n Returns:\n MaskableVolume\n \"\"\"\n base = super().conformTo(frameofreference)\n maskable = MaskableVolume().fromBaseVolume(base)\n return maskable\n\n # CONSTRUCTOR METHODS\n def deepCopy(self):\n \"\"\"makes deep copy of self and returns the copy\"\"\"\n copy_vol = MaskableVolume()\n copy_vol.data = copy.deepcopy(self.data)\n copy_vol.frameofreference = copy.deepcopy(self.frameofreference)\n copy_vol.modality = self.modality\n copy_vol.feature_label = self.feature_label\n return copy_vol\n\n def fromBaseVolume(self, base):\n \"\"\"promotion constructor that converts baseVolume to MaskableVolume, retaining member variables\n\n Args:\n base -- BaseVolume object\n\n Returns:\n MaskableVolume\n \"\"\"\n # copy attributes\n self.data = base.data\n self.frameofreference = copy.deepcopy(base.frameofreference)\n self.modality = base.modality\n self.feature_label = base.feature_label\n return self\n\n # PUBLIC METHODS\n def getSlice(self, idx, axis=0, flatten=False, roi=None):\n \"\"\"Extracts 2dArray of idx along the axis.\n Args:\n idx -- idx identifying the slice along axis\n\n Optional Args:\n axis -- specifies axis along which to extract\n Uses depth-row major ordering:\n axis=0 -> depth: axial slices inf->sup\n axis=1 -> rows: coronal slices anterior->posterior\n axis=2 -> cols: sagittal slices: pt.right->pt.left\n flatten -- return a 1darray in depth-stacked row-major order\n roi -- ROI object that can be supplied to mask the output of getSlice\n \"\"\"\n # call to base class\n slicearray = super().getSlice(idx, axis, flatten)\n\n # get equivalent slice from densemaskarray\n if (roi is not None):\n maskslicearray = roi.makeDenseMask(self.frameofreference).getSlice(idx, axis, flatten)\n # apply mask\n slicearray = np.multiply(slicearray, maskslicearray)\n\n return slicearray\n\n def vectorize(self, roi=None):\n \"\"\"flatten self.data in stacked-depth row-major order\n\n Args:\n roi -- ROI object that can be supplied to mask the output of getSlice\n \"\"\"\n array = self.data.flatten(order='C').reshape((-1, 1))\n\n # get equivalent array from densemaskarray\n if (roi is not None):\n if isinstance(roi, ROI):\n maskarray = roi.makeDenseMask(self.frameofreference)\n elif isinstance(roi, BaseVolume):\n maskarray = roi\n # apply mask\n array = np.multiply(array, maskarray.vectorize())\n\n return array\n\n def applyMask(self, roi):\n \"\"\"Applies roi mask to entire array and returns masked copy of class\n\n Args:\n roi -- ROI object that supplies the mask definition\n \"\"\"\n volume_copy = self.deepCopy()\n masked_array = self.vectorize(roi).reshape(self.frameofreference.size[::-1])\n volume_copy.data = masked_array\n return volume_copy\n\n\nclass SerialOutdatedError(Exception):\n def __init__(self):\n super().__init__('a missing value was requested from a BaseVolumeSerial object')\n\n\nclass BaseVolumeSerial:\n \"\"\"Defines common object that can store feature data for long term I/O\n \"\"\"\n def __init__(self):\n self.dataarray = None # numpy ndarray\n self.startposition = None # (x, y, z)\n self.spacing = None # (x, y, z)\n self.size = None # (x, y, z)\n self.modality = None # string\n self.feature_label = None # string\n","sub_path":"pymedimage/rttypes.py","file_name":"rttypes.py","file_ext":"py","file_size_in_byte":58547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"222579663","text":"'''\n1.上传文件的接口,上传1M的文件,上传2G的文件,耗时时间不同\n 默认的超时时间不够用时,可以设置接口超时时间\n2.接口性能测试,看接口是否能在某个时间内返回\n'''\nimport requests\n# requests.exceptions.ReadTimeout超时错误\nfor i in range(10):\n try:\n r = requests.get('http://jy001:8081/futureloan/mvc/api/member/list', timeout=0.01)\n print(r.text)\n except Exception as e:\n print(e)","sub_path":"day01/timeout.py","file_name":"timeout.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"233482761","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\n\nfrom XiaoShuoSpider.items import WXappSpiderItem\n\n\nclass WxappSpiderSpider(CrawlSpider):\n name = 'wxapp_spider'\n allowed_domains = ['wxapp-union.com']\n start_urls = ['http://wxapp-union.com/']\n\n rules = (\n Rule(LinkExtractor(allow=r'.+mod=list&catid=2&page=\\d'), follow=True),\n Rule(LinkExtractor(allow=r'.+article-.+-1.html'), callback=\"parse_item\", follow=True),\n )\n\n def parse_item(self, response):\n title = response.xpath(\"//div[@class='h hm cl']/div/h1/text()\").get()\n author = response.xpath(\"//div[@class='avatar_right cl']/div/p/a/text()\").get()\n time = response.xpath(\"//div//p[@class='authors']/span/text()\").get()\n content_list = response.xpath(\"//div[@class='content_middle cl']/div[@class='d']/table//td//p/text()\").extract()\n content = \"\"\n for c in content_list:\n content += c.strip()\n\n yield WXappSpiderItem(title=title, author=author, time=time, content=content)\n","sub_path":"XiaoShuoSpider/spiders/wxapp_spider.py","file_name":"wxapp_spider.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"26282538","text":"from ee.clickhouse.client import sync_execute\nfrom ee.clickhouse.materialized_columns.columns import TRIM_AND_EXTRACT_PROPERTY, get_materialized_columns\nfrom posthog.celery import app\nfrom posthog.models.property import PropertyName, TableWithProperties\nfrom posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_REPLICATION\n\nDELAY_SECONDS = 4 * 60 * 60\n\n\n@app.task(ignore_result=True, max_retries=3)\ndef check_backfill_done(table: TableWithProperties, property: PropertyName) -> None:\n should_retry = True\n\n try:\n updated_table = \"sharded_events\" if CLICKHOUSE_REPLICATION and table == \"events\" else table\n # :TRICKY: On cloud, we ON CLUSTER updates to events/sharded_events but not to persons. Why? ¯\\_(ツ)_/¯\n execute_on_cluster = f\"ON CLUSTER {CLICKHOUSE_CLUSTER}\" if table == \"events\" else \"\"\n column_name = get_materialized_columns(table, use_cache=False)[property]\n\n results = sync_execute(\n f\"\"\"\n SELECT count(*)\n FROM system.mutations\n WHERE table = '{table}'\n AND command LIKE '%UPDATE%'\n AND command LIKE '%{column_name} = {column_name}%'\n \"\"\"\n )\n\n if results[0][0] == 0:\n sync_execute(\n f\"\"\"\n ALTER TABLE {updated_table}\n {execute_on_cluster}\n MODIFY COLUMN\n {column_name} VARCHAR MATERIALIZED {TRIM_AND_EXTRACT_PROPERTY}\n \"\"\",\n {\"property\": property},\n )\n should_retry = False\n finally:\n if should_retry:\n check_backfill_done.apply_async((table, property,), countdown=DELAY_SECONDS)\n","sub_path":"ee/tasks/materialized_column_backfill.py","file_name":"materialized_column_backfill.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"236804953","text":"donor_list = [\n ['Bill Gates', 1.00, 10.00, 100.00],\n ['John Doe', 2.00],\n ['Jane Doe', 3.00, 6.00, 10.00]\n]\n\ndef print_intro():\n \"\"\"\n Introduction output\n \"\"\"\n print()\n print(\"Welcome to Mailroom Madness\")\n print()\n print(\"Choose from the following:\")\n print()\n print(\"T - Send a (T)hank You Letter\")\n print()\n print(\"R - Create a (R)eport\")\n print()\n print(\"quit - Quit the program\")\n print()\n\ndef print_donors(d):\n \"\"\"\n Print donor history in table format.\n Displays name, total, number, and average donations.\n \"\"\"\n for curr in d:\n curr_name = curr[0]\n donation_count = len(curr) - 1\n donation_total = 0\n j = 1\n while j <= donation_count:\n donation_total = donation_total + curr[j]\n j = j + 1\n\n print(curr_name, donation_total, donation_count, donation_total/donation_count)\n\ndef send_thank_you():\n \"\"\"\n \"\"\"\n donor_name = input(\"Please enter a donor's full name: \")\n str_donor = str(donor_name).upper\n\n if str_donor == \"LIST\":\n print_donor_list(donor_list)\n elif donor_name == \"QUIT\":\n return False\n else:\n donation_amt = get_donation_amt()\n create_letter(donor_name, donation_amt)\n\ndef print_donor_list(dl):\n for donor in dl:\n print(donor[0])\n return send_thank_you()\n\ndef get_donation_amt():\n amt = input(\"Please enter donation amount: \")\n if float(donation):\n return amt\n else:\n print(\"Invalid donation amount.\")\n return get_donation_amt()\n\n\ndef main_menu():\n \"\"\"\n\n \"\"\"\n print_intro()\n\n user_input = input(\"> \")\n user_input = user_input.upper()\n\n if user_input == \"T\":\n send_thank_you()\n elif user_input == \"R\":\n create_report(donor_list)\n elif user_input == \"QUIT\":\n return False\n else:\n print(\"Invalid input.\")\n main_menu()\n\n\nmain_menu()\n","sub_path":"hw/hw11/mailroom_test.py","file_name":"mailroom_test.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"556102420","text":"#!/usr/bin/python3\n#Author: Joseph Sevigny\n#Affiliation: Hubbard Center for Genome Studies, University of New Hampshire\n#Date: 02/23/2017\n\nimport sys, re, os, subprocess, argparse\nfrom Bio import SeqIO\n\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n#OPTIONAL ARGUMENTS\nparser.add_argument(\"-v\", \"--verbose\", help=\"increase output verbosity\", action=\"store_true\")\n#parser.add_argument(\"-h\",\"--help\",\"-help\", help=\"prints help and exits\")\nparser.add_argument(\"--cutoff_species\", help=\"cutoff for finest taxonomic level\", type=int, default=97)\nparser.add_argument(\"--cutoff_family\", help=\"cutoff for family taxonomic level\", type=int, default=90)\nparser.add_argument(\"--cutoff_phylum\", help=\"cutoff for phylum taxonomic level, also acts as ultimate cutoff value for blast\", type=int, default=80)\nparser.add_argument(\"--length_percentage\", help=\"cutoff for query_hit/length_of_query i.e. query coverage\", type=float, default=0.8)\nparser.add_argument(\"--length_cutoff\", help=\"primary cutoff for length of hit\", type=int, default=0)\nparser.add_argument(\"--hits_to_consider\", help=\"number of hits to consider when gathering consensus taxonomy\", type=float, default=5)\nparser.add_argument(\"--percent_sway\", help=\"when comparing greater than 1 blast hit, value is the percent from best hit considered. i.e. if best blast hit is 99.5 ID, a value of 0.5 will consider everything 99 and greater when creating the consensus\", type=float, default=0.5)\nparser.add_argument(\"--otu_file\", help=\"precomputed otu file, will run otu picking if not given\")\nparser.add_argument(\"--blast_file\", help=\"precomputed blast results, MUST BE MY CUSTOMIZED FORMAT, '6 qseqid qlen sseqid pident length qstart qend sstart send evalue bitscore'\")\nparser.add_argument(\"--ncbi_nt\", help=\"REQUIRED flag for use of ncbi nt database\", action=\"store_true\")\nparser.add_argument(\"--blast_evalue\", help=\"setting for e-value cutoff for blast, must be in form 1e-X\", type=str, default=\"1e-10\")\nparser.add_argument(\"--make_biom\", help=\"make a otu biom table using otus and taoxnomy assignments\", action=\"store_true\")\n\n#REQUIRED ARGUMENTS\nparser.add_argument(\"sequence_file\", help=\"seqs.fna file from qiime or any multifasta, just make sure header has unique id with a space\")\nparser.add_argument(\"blast_database\", help=\"path tp blast database, be sure to run makeblastdb on the database first, type 'IGNORE' if precomputed blast is given\")\nparser.add_argument(\"tax_file\", help=\"path to silva or customized blast database taxonomy file\")\n\n\n#parser.add_argument\nargs = parser.parse_args()\nif args.verbose:\n print ('####VERBOSE OPTION GIVEN\\n')\n print ('MAIN ARGUMENTS')\n print ('sequence_file: ', args.sequence_file)\n print ('blast_database: ', args.blast_database)\n print ('taxonomy_file: ', args.tax_file)\n print ('\\nOPTIONS')\n print ('blast_hits_to_consider: ', args.hits_to_consider)\n print ('sway_from_best_hit: ', args.percent_sway)\n print ('phylum_level_cutoff: ', args.cutoff_phylum)\n print ('family_level_cutoff: ', args.cutoff_family)\n print ('species_level_cutoff', args.cutoff_species)\n print ('length_of_hit_cutoff: ', args.length_cutoff)\n print ('proportion_of_query_coverage: ', args.length_percentage)\n print ('blast e-value cutoff: ', args.blast_evalue)\n print ('Construct OTU BIOM table: ', args.make_biom)\n print ('OTU_file given?: ', args.otu_file)\n print ('BLAST_file given?: ', args.blast_file)\n print ('NCBI flag?: ', args.ncbi_nt)\n\n\n###INFO FOR TAXONOMY DATABASES\ntaxonomy_categories = ['superkingdom', 'kingdom', 'phylum', 'subphylum', 'superclass', 'class', 'subclass', 'superorder', 'order', 'superfamily', 'family', 'subfamily', 'family', 'genus', 'species']\n#qiime_all_level_12_categories = [superkingdom, subkingdom, sub_subkingdom, kingdom, tmp1, tmp2, phylum, subphylum, class, order, family, genus, species]\n\n### OTHER OPTIONS BASED ON DATABASE OF CHOICE\nuncultured_cutoff_level = len(taxonomy_categories)\nspecies_level = 14\nfamily_level = 10\nphylum_level = 2\n#taxonomy_to_grab = [0,3,6,10,11,12] # file for qiime output\ntaxonomy_to_grab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]\n\n#OUTPUT_FILES\noutdir = 'Assigned_Taxonomy/'; os.mkdir(outdir)\notu_sequences_output = outdir + 'otu_seqs.fasta'\ntaxonomy_assignment_outfile = outdir + 'taxonomy_assignment_per_sequence.txt'\nlog_file_handle = open(outdir + 'log_file.txt','w')\n\n\n\n#Potential Additions:\n## --> Add option to blast more than one otu if they might be different, make the otu selection strigent\n\n\n\n\n#####Dictionaries\n\nsequence_dict = SeqIO.to_dict(SeqIO.parse(args.sequence_file, \"fasta\"))\notu_dictionary = {} # otu:[sequences]\ntaxonomy_dictionary = {} # tax_code:[taxonomy]\notu_taxonomy_dict = {} # otu:[best_taxonomy]\npercent_id_dict = {}\n\n\n######OTU PICKING\n\ndef run_otu_picker(sequence_file, otu_output_dir):\n '''perform otu_picking with uclust'''\n otu_pid = '0.99'\n otu_command = [\"pick_otus.py\", \"-i\", sequence_file, \"-o\", otu_output_dir, \"-s\", otu_pid, \"--enable_rev_strand_match\"] #command to complete otus\n # if args.verbose:\n # print ('Command =', ' '.join(otu_command))\n sp = subprocess.Popen(otu_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)#blast = sp.communicate()\n sp.communicate()\n\n\n\nif args.otu_file == None:\n if args.verbose:\n print ('\\nConstructing OTUS from sequence file')\n otu_output_dir = \"otu_picking_output/\"\n run_otu_picker(args.sequence_file, otu_output_dir)\n otu_list_dir = os.listdir(otu_output_dir)\n for file in otu_list_dir:\n if file.endswith('.txt'):\n otu_file = otu_output_dir + file\nelse:\n otu_file = args.otu_file\n\n\n###parse otu file\n\nif args.verbose:\n print ('Constructing OTU seed fasta file for blast')\nfor line in open(otu_file,'r'):\n elements = line.rstrip().split('\\t')\n group = elements[0]\n for sample_id in elements[1:]:\n if group in otu_dictionary.keys():\n otu_dictionary[group].append(sample_id)\n else:\n otu_dictionary[group] = [sample_id]\n\n###parse sequence_file and pick otu seed (select reference fasta for blast)\notu_sequences_output_handle = open(outdir + 'otu_seqs.fasta', 'w')\nfor key, value in otu_dictionary.items(): #could make this a little better than first one????\n otu_sequences_output_handle.writelines('>'+key+'\\n' + sequence_dict[value[0]].seq+'\\n')\n\n\n\n#parse taxonomy file\n\nif args.verbose:\n print ('Parsing taxonomy file and storing info in dictionary (might take a moment if using nt database)')\nfor line in open(args.tax_file,'r'):\n elements = line.rstrip().split('\\t')\n tax_id = elements[0]\n tax_info =re.sub('D_[0-9]*__','',elements[1]).replace(' ','_').split(';')\n taxonomy_dictionary[tax_id]=tax_info\n #taxonomy_dictionary[tax_id]=[tax_info[3],tax_info[6:]] ???\n\n###do_blast\ndef do_blast(query, database, blast_output):\n '''performs blasts and returns the results'''\n custom_blast_format = '6 qseqid qlen sseqid pident length qstart qend sstart send evalue bitscore staxids'\n #db_command = [\"makeblastdb\", \"-in\", subject, \"-dbtype\", \"nucl\", \"-out\", \"temp_db\"] #command to construct database\n #sd = subprocess.Popen(db_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE); sd.communicate()\n blast_command = [\"blastn\", \"-query\", query, \"-db\", database , \"-num_threads\", \"48\", \"-evalue\", args.blast_evalue, \"-out\", blast_output, \"-outfmt\", custom_blast_format] #command to complete blastn\n sp = subprocess.Popen(blast_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)#blast = sp.communicate()\n sp.communicate()\n\nif args.blast_file == None:\n if args.verbose:\n print ('Running blast on OTU seeds (this step takes the longest, maybe run overnight')\n blast_file = 'otu_seqs_blast.tsv'\n do_blast(otu_sequences_output,args.blast_database,blast_file)\nelse:\n blast_file = args.blast_file\n\n\n####PARSE BLAST and ASSIGN TAXONOMY#######\n#make so assignment avoids one mis when the rest agree\n\nif args.verbose:\n print ('Parsing Blast and Assigning Taxonomy')\n\ncurrent_best_hits = {} #count_code:[percent_id, tax_code]\ncurrent_query = ''\nfor line in open(blast_file,'r'):\n elements = line.rstrip().split('\\t'); sequence_id = elements[0]; tax_code = elements[2]\n percent_id = elements[3]; length_hit = elements[4]; length_query = elements[1]; ncbi_id = elements[-1]\n\n if args.ncbi_nt:\n if ';' in ncbi_id:\n ncbi_id = ncbi_id.split(';')[0]\n tax_code = ncbi_id\n\n if current_query != sequence_id: #INITIATION of new query\n if bool(current_best_hits) and current_query: #ENSURE A SET OF BLASTS TO PARSE\n\n if args.verbose:\n print ('\\nASSIGNING TAXONOMY FOR', current_query, 'total hits passing initial filters = ', len(current_best_hits))\n\n ##FILTER FOR THE BEST HIT and set cutoff\n\n #find best hit based on percent id\n top_hits = [] #should add check for best bitscore\n for key, value in current_best_hits.items():#TURN INTO LAMBDA\n top_hits.append(float(value[0]))\n\n #Fill best_blast_dictionary with those within sway distance of best blast hit\n best_blast_dictionary = {} #unique_blast_id:[percent_id, tax_code]\n for key, value in current_best_hits.items():\n if float(value[0]) > (max(top_hits)) - args.percent_sway : # *****important cutoff\n best_blast_dictionary[key]=value\n if args.verbose:\n print (current_query, value[1], value[0], '--> CAPTURED after percent sway filter')\n ##Assign Taxonomic Certainty\n level = phylum_level #'phylum'\n if max(top_hits) >= args.cutoff_family:\n level = family_level #'family'\n if max(top_hits) >= args.cutoff_species:\n level = species_level #'species'\n\n\n\n blast_percent = max(top_hits)\n\n ##Assign Taxonomy\n temp_taxonomy_dict = {} #unique_code:[taxonomy]\n count = 0\n for key,value in best_blast_dictionary.items():\n count += 1\n pkey = str(value[0])+ '_'+str(count)\n #Mask uncultured taxonomy\n if 'uncultured' in ' '.join(taxonomy_dictionary[value[1]][:uncultured_cutoff_level+1]) or 'unidentified' in ' '.join(taxonomy_dictionary[value[1]][:uncultured_cutoff_level+1]):\n pkey = 'X'+pkey\n #print ('UNCULTURED', current_query)\n temp_taxonomy_dict[pkey]=taxonomy_dictionary[value[1]]#[:level]\n\n\n #Determine best common taxonomy up to set certainty (certainty = cutoff level)\n # for l, t in temp_taxonomy_dict.items():\n # print (l, t)\n\n best_level_taxonomy = [] #final taxonomy assignment\n set_list = []\n for i in range(level+1): # start at kingdom and move toward species until difference is met.\n s = set() # set to hold labels from all tax code.\n the_okay = False\n\n #avoid error when all sequences are uncultured\n for one in temp_taxonomy_dict.keys():\n if not one.startswith('X'):\n the_okay = True\n\n for k,j in temp_taxonomy_dict.items():\n if not k.startswith('X') and len(temp_taxonomy_dict) > 1 and the_okay == True:\n s.add(j[i])\n if the_okay == False:\n s.add(j[i])\n set_list.append(s)\n if len(s) == 1:\n e = next(iter(s))\n best_level_taxonomy.append(e)\n #print (set_list)\n #when there is only one hit or they all match the same thing\n if not bool(best_level_taxonomy):\n for value in temp_taxonomy_dict.values():\n best_level_taxonomy = value[:level]\n\n best_level_taxonomy = list(filter(bool, best_level_taxonomy))#remove empty taxonomic levels\n needed_unknowns = (len(taxonomy_categories)-len(best_level_taxonomy))\n for i in range(needed_unknowns):\n best_level_taxonomy.append('undetermined')\n\n ### FINALLY FILL OTU INFORMATION!!!!\n otu_taxonomy_dict[current_query] = best_level_taxonomy\n percent_id_dict[current_query] = blast_percent\n if args.verbose:\n print ('Taxonomy Assignment for', current_query, '=', best_level_taxonomy[0], best_level_taxonomy[phylum_level], best_level_taxonomy[family_level], best_level_taxonomy[-1])\n\n #reset query_id\n current_query = sequence_id\n current_best_hits = {}\n\n ## Filter Hits and Loop Through current Query and add up to x number of blast hits\n if int(length_hit)/int(length_query)>args.length_percentage and float(percent_id)>args.cutoff_phylum and int(length_hit)>args.length_cutoff:\n if len(current_best_hits.keys()) < args.hits_to_consider:\n label = len(current_best_hits.keys()) # provide unique key based on number of matched\n current_best_hits[label] = [percent_id, tax_code]\n\n\n\n### QIIME FORMATTED OUTPUT\n\nif args.verbose:\n print ('\\nConstructing output files')\n\nnew_output_file = outdir + 'taxonomy_assignment_qiime_format.txt'\n\nfor otu, sequences in otu_dictionary.items():\n output_line = otu+'\\t'\n if otu in otu_taxonomy_dict.keys():\n blast_percent = round((percent_id_dict[otu]/100),2)\n count = 0\n for taxonomy_level in otu_taxonomy_dict[otu]:\n if count in taxonomy_to_grab:\n output_line += 'D_'+str(count)+'__'+taxonomy_level+';'\n count +=1\n output_line = output_line[:-1] + '\\t'+str(blast_percent)+'\\t1'\n else:\n output_line += 'Unassigned\\t1.00\\t1'\n\n with open(new_output_file,'a') as t:\n t.writelines(output_line+'\\n')\n\n\n#Regular Assignment\n\nfor otu, sequences in otu_dictionary.items():\n for seq in sequences:\n if '__' in seq:\n group,seq_id = seq.split('__')\n else:\n group,seq_id = seq.split('_') #if two of these _ are in it\n output_line = group+':'+seq_id+':'+otu\n if otu in otu_taxonomy_dict.keys():\n for taxonomy_level in otu_taxonomy_dict[otu]:\n output_line += (':' + taxonomy_level)\n with open(taxonomy_assignment_outfile,'a') as t:\n t.writelines(output_line+'\\n')\n\n else:\n output_line += (':undetermined'*len(taxonomy_to_grab))\n with open(taxonomy_assignment_outfile,'a') as t:\n t.writelines(output_line+'\\n')\n\n## sort the taxonomy file for viewing\nos.system(\"sort -k2 Assigned_Taxonomy/taxonomy_assignment_qiime_format.txt > Assigned_Taxonomy/taxonomy_assignment_qiime_format2.txt && mv Assigned_Taxonomy/taxonomy_assignment_qiime_format2.txt Assigned_Taxonomy/taxonomy_assignment_qiime_format.txt\")\nos.system(\"sort -t: -k4 Assigned_Taxonomy/taxonomy_assignment_per_sequence.txt > Assigned_Taxonomy/taxonomy_assignment2.txt && mv Assigned_Taxonomy/taxonomy_assignment2.txt Assigned_Taxonomy/taxonomy_assignment_per_sequence.txt\")\n\n\n## construct biom table for qiime\ndef make_otu_table(otu_file,taxonomy_file):\n '''makes otu_table for qiime'''\n output = 'otu_table.biom'\n biom_command = [\"make_otu_table.py\", \"-i\", otu_file, \"-t\", taxonomy_file, \"-o\", output ] #command to complete blastn\n sp = subprocess.Popen(biom_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)#blast = sp.communicate()\n sp.communicate()\n os.system('mv otu_table.biom Assigned_Taxonomy/')\n\nif args.make_biom:\n if args.verbose:\n print ('Constructing OTU table for qiime')\n make_otu_table(otu_file, new_output_file)\n\n \n#Done\nif args.verbose:\n print ('Process Complete. Have a nice day!')\n","sub_path":"archives/taxonomy_assignment_BLAST_V1.py","file_name":"taxonomy_assignment_BLAST_V1.py","file_ext":"py","file_size_in_byte":15889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
\" + st[\"tex\"] + \"