diff --git "a/1494.jsonl" "b/1494.jsonl"
new file mode 100644--- /dev/null
+++ "b/1494.jsonl"
@@ -0,0 +1,699 @@
+{"seq_id":"21885371","text":"import re\nfrom functools import reduce\n\nfile = \"codes.txt\"\noutput = 'stocks_list.txt'\nwith open(file, 'r') as f:\n s = f.read()\nf = open(output, 'w')\nfor c in s:\n if c == '(':\n f.write(' ')\n elif c == ')':\n f.write('\\n')\n else:\n f.write(c)\nf.close()\n\n\ndef get_stock_list():\n with open(output, 'r') as out:\n content = out.read()\n li = re.findall(r'\\d+', content)\n li.sort()\n return li\n\n\n# print(len(get_stock_list()))\n# l = reduce(lambda x, y: x + y, list(map(lambda x: len(x) == 6 and 1, get_stock_list())))\n# print(l)\n\n# for i in range(0, 2964, 340):\n# print(get_stock_list()[i:i + 300])\n\nprint(get_stock_list())","sub_path":"app/get_stocks.py","file_name":"get_stocks.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"127948343","text":"import tkinter\n\nlen_words = 0\n\ndef read_file():\n global len_words\n with open('read.txt','r+',encoding = 'utf-8') as fp:\n file_text = fp.read()\n len_words = len(file_text)\n number.set(len_words)\n address.set('read.txt')\n text_t.insert('insert',file_text)\n\n#write file function\ndef write_file():\n global len_words\n\n file_txt = write_entry.get()\n len_words = len(file_txt)\n number.set(len_words)\n address.set('write.txt')\n\n with open('write.txt','w+',encoding = 'utf-8') as fp:\n fp.write(file_txt)\n\n#create the main window\nmain_window = tkinter.Tk()\n\n#create frames\ntext_frame = tkinter.Frame(main_window)\ntop_frame = tkinter.Frame(main_window)\nmiddle_frame = tkinter.Frame(main_window)\naddress_frame = tkinter.Frame(main_window)\nbottom_frame = tkinter.Frame(main_window)\n\n#create and write read widgets\ntext_t = tkinter.Text(top_frame,width=45, height=5)\ntext_t.pack()\n\n#create and pack write widgets\nwrite_label = tkinter.Label(top_frame,text = '写入文本:')\nwrite_entry = tkinter.Entry(top_frame,width = 35)\n\nwrite_label.pack(side = 'left')\nwrite_entry.pack(side = 'left')\n\n#create count and pack widgets\nwords_label = tkinter.Label(middle_frame,text = '文本字数:')\n\nnumber = tkinter.StringVar() #To update number\nnumber_label = tkinter.Label(middle_frame,textvariable = number)\n\nwords_label.pack(side = 'left')\nnumber_label.pack(side = 'left')\n\n#create and pack address widgets\naddress_label = tkinter.Label(address_frame,text = '文本地址:')\n\naddress = tkinter.StringVar() #To update address\nadd_label = tkinter.Label(address_frame,textvariable = address)\n\naddress_label.pack(side = 'left')\nadd_label.pack(side = 'left')\n\n#create buttons\nread_button = tkinter.Button(bottom_frame,text = '读文件',width=15, height=2, command = read_file)\nwrite_button = tkinter.Button(bottom_frame,text = '写文件', width=15, height=2, command = write_file)\n\nread_button.pack(side = 'left')\nwrite_button.pack(side = 'left')\n\n#pack the frames\ntext_frame.pack()\ntop_frame.pack()\nmiddle_frame.pack()\naddress_frame.pack()\nbottom_frame.pack()\n\n#start the main loop\ntkinter.mainloop()\n\n","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"548105852","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA game:\n how to Guess a Number\n\nCreated on Tue Dec 26 09:05:21 2017\n\n@author: ABSBIN\n\n\"\"\"\n \n \nimport sys\nimport numpy as np\n\ndef main():\n print(\"Hello World!\")\n print(\"Guess number between 1 to 100\")\n randomNumber=35\n randomNumber=np.random.randint(1,100)\n \n \n found=False\n while not found:\n userGuess= int(input(\"Your guess: \"))\n if userGuess == randomNumber:\n print(\"you got it!\")\n found= True\n elif userGuess >randomNumber:\n print(\"You guess is Higher\")\n else:\n print(\" You guess is Lower\")\n \n\nif __name__==\"__main__\":\n main()\n","sub_path":"davin_reddy/python_0.py","file_name":"python_0.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"391408437","text":"from django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom .models import RequestsLogger\n\n\ndef index(request):\n template_name = 'rlogger/index.html'\n\n sort_order = request.GET.get('sort', '0')\n reverse_mode = request.GET.get('mode', '0')\n if reverse_mode == '1':\n sort_order = '1' if sort_order == '0' else '0'\n if sort_order == '1':\n events = RequestsLogger.objects.order_by('priority', 'created_on')[:10]\n else:\n events = RequestsLogger.objects.order_by('-priority', 'created_on')[:10]\n context = {'events': events, 'sort_order': sort_order}\n return render(request, template_name, context)\n\n\n@login_required(login_url='/accounts/login/')\ndef event(request, event_id):\n event = get_object_or_404(RequestsLogger, pk=event_id)\n action = request.GET['action']\n sort_order = request.GET['sort']\n if action == 'up':\n event.priority += 1\n elif action == 'down':\n event.priority -= 1\n event.save()\n url = '%s?sort=%s' % (reverse('requests:index'), sort_order)\n return HttpResponseRedirect(url)\n","sub_path":"apps/rlogger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"577740169","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests/demo of ocfl-object.py client.\"\"\"\nimport json\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\n\n\nclass TestAll(unittest.TestCase):\n \"\"\"TestAll class to run tests.\"\"\"\n\n tmpdir = None\n n = 0\n m = 0\n demo = False\n keep_tmpdirs = False\n\n def setUp(self):\n \"\"\"Setup for each test.\"\"\"\n type(self).n += 1 # access class variable not copy\n self.m = 0\n self.tmpdir = tempfile.mkdtemp(prefix='test' + str(self.n) + '_')\n if self.demo:\n print(\"\\n## %d. %s\" % (self.n, self.shortDescription()))\n\n def tearDown(self):\n \"\"\"Teardown for each test.\"\"\"\n if self.tmpdir is not None and not self.keep_tmpdirs:\n shutil.rmtree(self.tmpdir)\n\n def run_ocfl_store(self, desc, options, text=None, treedir='object',\n include_objdir=True, include_dstdir=False):\n \"\"\"Run the ocfl-store.py script.\"\"\"\n self.m += 1\n if self.demo:\n print(\"\\n### %d.%d %s\\n\" % (self.n, self.m, desc))\n if text:\n print(text + '\\n')\n cmd = ['python', 'ocfl-object.py']\n if include_objdir:\n cmd += ['--objdir', os.path.join(self.tmpdir, treedir)]\n elif include_dstdir:\n cmd += ['--dstdir', self.tmpdir]\n cmd += options\n code = 0\n try:\n out = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8')\n except subprocess.CalledProcessError as e:\n out = e.output.decode('utf-8')\n code = e.returncode\n out = \"```\\n> \" + ' '.join(cmd) + \"\\n\" + out + \"```\\n\"\n if self.demo:\n out = re.sub(self.tmpdir, 'tmp', out)\n print(out)\n else:\n return out\n if code == 0 and include_objdir:\n tree = subprocess.check_output('cd %s; tree -a %s' % (self.tmpdir, treedir),\n stderr=subprocess.STDOUT,\n shell=True).decode('utf-8')\n print(\"```\\n\" + tree + \"```\\n\")\n elif code == 0 and include_dstdir:\n tree = subprocess.check_output('cd %s; tree -a .' % (self.tmpdir),\n stderr=subprocess.STDOUT,\n shell=True).decode('utf-8')\n print(\"```\\n\" + tree + \"```\\n\")\n else:\n print(\"Exited with code %d\" % (code))\n return out\n\n def test01_create_inventory_dryrun(self):\n \"\"\"Test object inventory creation with output to stdout.\"\"\"\n out = self.run_ocfl_store(\"Inventory for new object with just v1\",\n ['--create', '--id', 'http://example.org/obj1', '--src', 'fixtures/1.0/content/cf1/v1'],\n text=\"Without an `--objdir` argument the script just writes out the inventory for the object that would have been created.\",\n include_objdir=False)\n self.assertIn('\"id\": \"http://example.org/obj1\"', out)\n self.assertIn('### Inventory for v1', out)\n out = self.run_ocfl_store(\"Inventory for new object with three versions\",\n ['--build', '--id', 'http://example.org/obj2', '--src', 'fixtures/1.0/content/cf3'],\n text=\"Without an `--objdir` argument the script just writes out the inventory for each version in the object that would have been created.\",\n include_objdir=False)\n self.assertIn('\"id\": \"http://example.org/obj2\"', out)\n self.assertIn('### Inventory for v1', out)\n self.assertIn('### Inventory for v2', out)\n self.assertIn('### Inventory for v3', out)\n\n def test02_create_v1(self):\n \"\"\"Test object creation with just v1.\"\"\"\n out = self.run_ocfl_store(\"New object with just v1\",\n ['--create', '--id', 'http://example.org/obj1', '--src', 'fixtures/1.0/content/cf1/v1', '-v'])\n self.assertIn('Created object http://example.org/obj1', out)\n\n def test03_create_multi(self):\n \"\"\"Test object build with three versions.\"\"\"\n out = self.run_ocfl_store(\"New object with three versions\",\n ['--build', '--id', 'http://example.org/obj2', '--src', 'fixtures/1.0/content/cf3', '-v'])\n self.assertIn('Built object http://example.org/obj2 with 3 versions', out)\n\n def test04_extract(self):\n \"\"\"Test extract of version.\"\"\"\n out = self.run_ocfl_store(\"Extract v1\",\n ['--extract', 'v1', '--objdir', 'fixtures/1.0/objects/spec-ex-full', '-v'],\n include_objdir=False,\n include_dstdir=True)\n # Excpect:\n # v1\n # ├── [ 0] empty.txt\n # ├── [ 102] foo\n # │ └── [ 272] bar.xml\n # └── [ 2021] image.tiff\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v1/empty.txt')), 0)\n self.assertFalse(os.path.exists(os.path.join(self.tmpdir, 'v1/empty2.txt')))\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v1/foo/bar.xml')), 272)\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v1/image.tiff')), 2021)\n out = self.run_ocfl_store(\"Extract v2\",\n ['--extract', 'v2', '--objdir', 'fixtures/1.0/objects/spec-ex-full', '-v'],\n include_objdir=False,\n include_dstdir=True)\n # Expect:\n # v2\n # ├── [ 0] empty.txt\n # ├── [ 0] empty2.txt\n # └── [ 102] foo\n # └── [ 272] bar.xml\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v2/empty.txt')), 0)\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v2/empty2.txt')), 0)\n self.assertEqual(os.path.getsize(os.path.join(self.tmpdir, 'v2/foo/bar.xml')), 272)\n self.assertFalse(os.path.exists(os.path.join(self.tmpdir, 'v2/image.tiff')))\n\n def test20_errors(self):\n \"\"\"Test error conditions.\"\"\"\n out = self.run_ocfl_store(\"No valid command argument\",\n [],\n include_objdir=False)\n self.assertIn('one of the arguments ', out)\n out = self.run_ocfl_store(\"No identifier\",\n ['--create'],\n include_objdir=False)\n self.assertIn('Must specify --srcdir', out)\n out = self.run_ocfl_store(\"No identifier\",\n ['--create', '--srcdir', 'tmp'],\n include_objdir=False)\n self.assertIn('Identifier is not set!', out)\n\n\nif __name__ == '__main__':\n # Run in demo mode if run directly instead of through py.test\n TestAll.demo = True\n print(\"# Demo output from \" + __file__)\n unittest.main()\n","sub_path":"tests/test_ocfl_object_script.py","file_name":"test_ocfl_object_script.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"579654520","text":"from django.urls import path\n\nfrom account.views import *\n\nurlpatterns = [\n path('logining', logining, name=\"login\"),\n path('logout/', logout_view, name=\"logout\"),\n path('register', register, name=\"register\"),\n path('code//', code, name='code'),\n path('admin-panel/', code, name='admin-panel'),\n path('user-update/', update_user, name='user_update_panel'),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"415176102","text":"# -*- coding:utf8 -*-\n\n\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.left_tree = None\n self.right_tree = None\n\n\nclass BinaryTree(object):\n\n def __init__(self):\n self.root = None\n\n def add_node(self, item):\n node = Node(item)\n if self.root is None:\n self.root = node\n return\n queue = [self.root]\n while queue:\n current_node = queue.pop(0)\n if current_node.left_tree is None:\n current_node.left_tree = node\n return\n else:\n queue.append(current_node.left_tree)\n if current_node.right_tree is None:\n current_node.right_tree = node\n return\n else:\n queue.append(current_node.right_tree)\n\n def broad_travel(self):\n if self.root is None:\n return\n queue = [self.root]\n while queue:\n node = queue.pop(0)\n print(node.value, end=\" \")\n if node.left_tree:\n queue.append(node.left_tree)\n if node.right_tree:\n queue.append(node.right_tree)\n\n def pre_travel(self, node):\n if node is None:\n return\n print(node.value, end=\" \")\n self.pre_travel(node.left_tree)\n self.pre_travel(node.right_tree)\n\n def middle_travel(self, node):\n if node is None:\n return\n self.middle_travel(node.left_tree)\n print(node.value, end=\" \")\n self.middle_travel(node.right_tree)\n\n def post_travel(self, node):\n if node is None:\n return\n self.post_travel(node.left_tree)\n self.post_travel(node.right_tree)\n print(node.value, end=\" \")\n\n def pre_travel1(self, node):\n if node is None:\n return\n\n import queue\n stack = queue.LifoQueue()\n stack.put(node)\n res = []\n\n while not stack.empty():\n current_node = stack.get()\n res.append(current_node.value)\n\n if current_node.right_tree:\n stack.put(current_node.right_tree)\n if current_node.left_tree:\n stack.put(current_node.left_tree)\n return res\n\n def middle_travel1(self, node):\n if node is None:\n return\n\n import queue\n stack = queue.LifoQueue()\n cur = node\n res = []\n\n while not stack.empty() or cur:\n while cur:\n stack.put(cur)\n # print(cur.value, 111)\n cur = cur.left_tree\n node = stack.get()\n res.append(node.value)\n cur = node.right_tree\n return res\n\n def post_travel1(self, node):\n if node is None:\n return\n\n import queue\n stack = queue.LifoQueue()\n stack.put(node)\n res = []\n\n while not stack.empty():\n cur = stack.get()\n res.append(cur.value)\n if cur.left_tree:\n stack.put(cur.left_tree)\n if cur.right_tree:\n stack.put(cur.right_tree)\n\n return res\n\n\nif __name__ == '__main__':\n tree = BinaryTree()\n tree.add_node(0)\n tree.broad_travel()\n print()\n tree.pre_travel(tree.root)\n print()\n tree.middle_travel(tree.root)\n print()\n tree.post_travel(tree.root)\n","sub_path":"python/algorithm/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"561780294","text":"import hashlib\nimport urllib\n\nfrom math import ceil\nfrom flask import url_for\nfrom flask import request\nfrom pillarsdk import File\n\n\nclass Pagination(object):\n \"\"\"Pagination snippet coming from http://flask.pocoo.org/snippets/44/\n \"\"\"\n\n def __init__(self, page, per_page, total_count):\n self.page = page\n self.per_page = per_page\n self.total_count = total_count\n\n @property\n def pages(self):\n return int(ceil(self.total_count / float(self.per_page)))\n\n @property\n def has_prev(self):\n return self.page > 1\n\n @property\n def has_next(self):\n return self.page < self.pages\n\n def iter_pages(self, left_edge=2, left_current=2,\n right_current=5, right_edge=2):\n last = 0\n for num in xrange(1, self.pages + 1):\n if num <= left_edge or \\\n (num > self.page - left_current - 1 and \\\n num < self.page + right_current) or \\\n num > self.pages - right_edge:\n if last + 1 != num:\n yield None\n yield num\n last = num\n\n\ndef url_for_other_page(page):\n args = request.view_args.copy()\n args['page'] = page\n return url_for(request.endpoint, **args)\n\n\ndef percentage(items, total):\n if total == 0: return 0.0\n return float(items) * 100 / float(total)\n\n\ndef attach_project_pictures(project, api):\n \"\"\"Utility function that queries for file objects referenced in picture\n header and square. In eve we currently can't embed objects in nested\n properties, this is the reason why this exists.\n This function should be moved in the API, attached to a new Project object.\n \"\"\"\n if project.properties.picture_square:\n # Collect the picture square file object\n project.properties.picture_square = File.find(\n project.properties.picture_square, api=api)\n if project.properties.picture_header:\n # Collect the picture header file object\n project.properties.picture_header = File.find(\n project.properties.picture_header, api=api)\n\n\ndef gravatar(email, size=64, consider_settings=True):\n parameters = {'s':str(size), 'd':'mm'}\n return \"https://www.gravatar.com/avatar/\" + \\\n hashlib.md5(str(email)).hexdigest() + \\\n \"?\" + urllib.urlencode(parameters)\n\n","sub_path":"pillar-web/application/helpers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"264075532","text":"import connexion\nimport pika\nfrom json import dumps\n\nfrom prontogram.models.message import Message # noqa: E501\nfrom datetime import datetime, timezone\n\n\ndef send_message(message=None): # noqa: E501\n \"\"\"sendMessage\n\n Sends the message to ProntoGram for being dispatched to the actual user. API for: ACMESky # noqa: E501\n\n :param message: \n :type message: dict | bytes\n\n :rtype: None\n \"\"\"\n if connexion.request.is_json:\n message = Message.from_dict(connexion.request.get_json()) # noqa: E501\n connection = pika.BlockingConnection(pika.ConnectionParameters('prontogram_mq'))\n channel = connection.channel()\n\n \"\"\"\n Creates a queue with name message.receiver if it does not exist, otherwise does nothing.\n Flag durable set to True requires the queue to be persistent on restart.\n \"\"\"\n channel.queue_declare(queue=message.receiver, durable=True)\n\n # Updating the date format to ISO 8601.\n message.send_time = datetime.now(tz=timezone.utc).isoformat()\n\n # Publishing the message on the queue.\n channel.basic_publish(exchange='',\n routing_key=message.receiver,\n body=bytes(dumps(message.to_dict(), default=str), 'utf-8'),\n properties=pika.BasicProperties(delivery_mode=2)\n )\n\n connection.close()\n\n return \"\", 200\n","sub_path":"prontogram/controllers/default_controller.py","file_name":"default_controller.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"462033280","text":"import random\nimport numpy as np\nfrom numpy.lib.stride_tricks import as_strided\nimport matplotlib.pyplot as plt\nimport cv2\nimport trade_environment\nfrom trade_environment import TradeEnvironment\n\nenv = TradeEnvironment('test.dat', 240, (1, 100, 110))\nenv.reset(False)\n\nvalues = env.episode_values\nmaxs = values.max(axis=1)\nmins = values.min(axis=1)\nptps = maxs - mins\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n\ndef make_kernel(ksize):\n\treturn np.ones(ksize) / ksize, ksize, ksize // 2\n\n\ndef convolve(values, kernel):\n\treturn np.convolve(values, kernel[0], mode='valid'), kernel[2]\n\n\ndef detect_feature_indices(values):\n\treturn np.nonzero(np.diff(np.sign(np.diff(values))))[0] + 2\n\n\ndef remove_small_gap(values, gap_size):\n\treturn np.nonzero(gap_size <= np.abs(np.diff(values)))[0] + 1\n\n\ndef signs_calc(values, kernel):\n\tkernel_size_half = kernel.shape[0] // 2\n\tma = np.convolve(values, kernel, mode='valid')\n\tindices1 = detect_feature_indices(ma)\n\tvalues1 = ma[indices1]\n\treturn ma, indices1 + kernel_size_half, values1, kernel_size_half\n\t# indices2 = detect_feature_indices(values1)\n\t# indices = indices1[indices2]\n\t# values = ma[indices]\n\t# return ma, indices + kernel_size_half, values, kernel_size_half\n\n\ndef signs_x_indices(signs):\n\treturn np.arange(signs[0].shape[0]) + signs[3]\n\n\ndef detect_turning_points(values, gap):\n\t\"\"\"指定数列の折返しポイントの地点を検出する.\n\n\tArgs:\n\t\tvalues: 数列.\n\t\tgap: 折返し判定閾値、この値を超えて反転したら折返しと判断する.\n\n\tReturns:\n\t\t(折返しインデックス, 検出途中に生成した一定値以上距離を保って付いてくる値の数列) のタプル.\n\t\"\"\"\n\tindices = []\n\tstalkers = np.empty((len(values),), dtype=np.int32)\n\tlast_value = values[0]\n\tstalker = last_value\n\tstalkers[0] = stalker\n\tfor i in range(1, len(values)):\n\t\tv = values[i]\n\t\td = v - stalker\n\t\tif last_value < stalker and stalker <= v or stalker < last_value and v <= stalker:\n\t\t\tindices.append(i)\n\t\tif d < -gap:\n\t\t\tstalker = v + gap\n\t\telif gap < d:\n\t\t\tstalker = v - gap\n\t\tstalkers[i] = stalker\n\t\tlast_value = v\n\treturn np.array(indices, dtype=np.int32) - 1, stalkers\n\n\ndef detect_order_indices(values, max_los, search_length):\n\tindices = []\n\n\tindex = 0\n\tindex_end = len(values)\n\tstart_value = values[index]\n\tindices.append(index)\n\n\twhile True:\n\t\tindex += 1\n\t\tif index_end <= index:\n\t\t\tbreak\n\t\tnext_values = values[index:min(index + search_length, index_end)]\n\t\tdeltas = next_values - start_value\n\t\tdeltas_abs = np.abs(deltas)\n\n\t\tend_index = search_length\n\t\tover_los_indices = np.nonzero(max_los <= deltas_abs)[0]\n\t\tif len(over_los_indices):\n\t\t\tover_los_signs_dif = np.diff(np.sign(deltas[over_los_indices]))\n\t\t\tif len(over_los_signs_dif):\n\t\t\t\tturn_indices = np.nonzero(over_los_signs_dif)[0]\n\t\t\t\tif len(turn_indices):\n\t\t\t\t\tend_index = turn_indices[0].item() + 1\n\n\t\tindex += np.argsort(deltas_abs[:end_index])[-1].item()\n\t\tstart_value = values[index]\n\t\tindices.append(index)\n\n\treturn indices\n\n\nkernel = make_kernel(10)\n\no = values[:, 0]\nh = values[:, 1]\nl = values[:, 2]\nc = values[:, 3]\nx = np.arange(c.shape[0])\n\nc_ma = convolve(c, kernel)\nx_ma = np.arange(c_ma[0].shape[0]) + c_ma[1]\n\nax.plot(x, c, label='close')\nax.plot(x_ma, c_ma[0], label='close ma')\n\n# cgap_indices = remove_small_gap(c, 10)\n# cgap_values = c[cgap_indices]\n# ax.plot(x[cgap_indices], cgap_values)\n\nod_indices = detect_order_indices(c, 10, 30)\nod_values = c[od_indices]\nax.plot(x[od_indices], od_values, label='order points', marker='o')\n\ntp_indices, stalkers = detect_turning_points(c, 5)\ntp_values = c[tp_indices]\n# ax.plot(x, stalkers, label='stalker')\nax.plot(x[tp_indices], tp_values, label='turning point', marker='o')\n\n# ksize = 30\n# ksize_half = ksize // 2\n# kernel = np.ones(ksize) / ksize\n# ma = np.convolve(c, kernel, mode='valid')\n# ma_x = np.arange(ma.shape[0]) + ksize_half\n# ax.plot(ma_x, ma)\n\n# feature_indices = detect_feature_indices(ma)\n# feature_x = ma_x[feature_indices]\n# feature_values = ma[feature_indices]\n# ax.plot(feature_x, feature_values)\n\n# gapremoved_indices = remove_small_gap(feature_values, 10)\n# gapremoved_x = feature_x[gapremoved_indices]\n# gapremoved_values = feature_values[gapremoved_indices]\n# ax.plot(gapremoved_x, gapremoved_values)\n\n# ksizes = [30]\n# ma_high = [signs_calc(h, np.ones(ksize) / ksize) for ksize in ksizes]\n# ma_low = [signs_calc(l, np.ones(ksize) / ksize) for ksize in ksizes]\n# ma_closes = [signs_calc(c, np.ones(ksize) / ksize) for ksize in ksizes]\n\n# # ax.plot(h)\n# xbase = np.arange(c.shape[0])\n# for sign in ma_high:\n# \tx = signs_x_indices(sign)\n# \tax.plot(x, sign[0])\n\n# \tidx = np.nonzero(5 < np.abs(np.diff(sign[2])))\n# \tax.plot(x, sign[0])\n\n# \tax.plot(xbase[sign[1]], sign[2])\n\n# x = np.arange(c.shape[0])\n# ma_x = signs_x_indices(ma_high)\n# ax.plot(x[ma_high[1]], ma_high[2])\n# ax.plot(ma_x, ma_high[0])\n# ax.plot(ma_x, ma_low[0])\n\n# maxwins = trade_environment.running_max_min_view(maxs + ptps, 10, 1).max(axis=1)\n# minwins = trade_environment.running_max_min_view(mins - ptps, 10, 1).min(axis=1)\n# # maxwins = trade_environment.running_max_min_view(maxwins, 10, 1).min(axis=1)\n# # minwins = trade_environment.running_max_min_view(minwins, 10, 1).max(axis=1)\n# # x = np.arange(15, 15 + maxwins.shape[0])\n# x = np.arange(maxwins.shape[0])\n# ax.plot(x, maxwins)\n# ax.plot(x, minwins)\n\n# n = maxwins.shape[0]\n# maxs = maxs[:n]\n# mins = mins[:n]\n# c = values[:, 3][:n]\n# down_indices = np.nonzero((c < minwins).astype('i4'))[0]\n# x = np.arange(c.shape[0])\n# # ax.plot(x, maxs)\n# # ax.plot(x, mins)\n# ax.plot(x, c)\n\n# x = x[down_indices]\n# c = c[down_indices]\n# ax.plot(x, c)\n\nplt.legend()\nplt.show()\n","sub_path":"cpf/python/training/auto_trade/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"300692028","text":"#coding=utf-8\n\nimport pytest\nimport allure\nfrom api.mission import missionApi\nfrom Common import Log\nimport datetime\n\nclass TestMission:\n \"\"\"\n 主题议程模块测试\n \"\"\"\n\n log = Log.MyLog()\n expected_msg = \"success\"\n\n\n @allure.severity('normal')\n @allure.story('Collections')\n @pytest.mark.parametrize(\"payload\",\n [\n {\"name\": \"自由讨论\",\n \"desc\": \"sdfgdsfgfdsg\",\n \"ext\": \"{\\\"tagId\\\":\\\"626549294551269829\\\",\\\"meetingType\\\":1,\\\"timeUse\\\":\\\"5分钟\\\"}\",\n \"tagId\": \"626549294551269829\"},\n {\"name\": \"主题演讲\",\n \"desc\": \"\\n \\n \\n \\n \\n Document\\n \\n \\n \\n 461616
\\n \\n \",\n \"ext\": \"{\\\"tagId\\\":\\\"626544899323331013\\\",\\\"meetingType\\\":0,\\\"speaker\\\":\\\"15166841990 Qiucw\\\",\\\"speakerId\\\":\\\"636786270315479359\\\",\\\"timeUse\\\":\\\"9分钟\\\",\\\"teachStyle\\\":\\\"直播演讲\\\",\\\"audio\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"video\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"content\\\":\\\"\\\\n \\\\n \\\\n \\\\n \\\\n Document\\\\n \\\\n \\\\n \\\\n 461616
\\\\n \\\\n \\\"}\",\n \"tagId\": \"626544899323331013\"}\n ])\n def test_createAgenda(self, payload):\n '''\n 添加议程\n 版本v1.0.0\n :param payload:\n :return:\n '''\n self.log.info(\"开始测试添加议程\")\n a = missionApi.createMeeting(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"desc\": \"学习会议的文稿\",\n \"name\": \"新建的学习会\",\n \"content\":\"学习会议的文稿\"\n }])\n def test_createMeeting(self,payload):\n '''\n 用户创建学习会\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"开始测试创建学习会\")\n a = missionApi.createMeeting(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\"agendaIds\":[\"666910263752000147\"],\n \"content\":\"反反复复个广告发个广告广告方法个 v 尺寸\",\n \"desc\": \"反反复复个广告发个广告广告方法个 v 尺寸\",\n \"ext\": \"{\\\"video\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"audio\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"content\\\":{\\\"contentHtml\\\":\\\"\\\",\\\"contentText\\\":\\\"\\\"}}\",\n \"name\": \"测试\",\n \"pid\":\"666892345685312147\",\n \"startTime\":datetime.datetime.strftime(datetime.datetime.now()+datetime.timedelta(minutes=5),'%Y-%m-%d %H:%M:%S')}])\n def test_createTheme(self,payload):\n '''\n 添加主题\n 版本v1.0.0\n :param payload:\n :return:\n '''\n self.log.info(\"开始测试添加主题\")\n a = missionApi.createTheme(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{}])\n def test_delAgendaById(self, payload):\n '''\n 删除议程\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"删除议程\")\n a = missionApi.delAgendaById(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{}])\n def test_delMeetingById(self, payload):\n '''\n 删除我的学习会\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"删除我的学习会\")\n a = missionApi.delMeetingById(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{}])\n def test_delThemeById(self, payload):\n '''\n 删除主题会\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"删除主题会\")\n a = missionApi.delThemeById(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\"desc\": \"再次编辑\",\n \"name\": \"测试编辑学习会\",\n \"content\":\"再次编辑\",\n \"id\":\"667115786527048181\"}])\n def test_editMeeting(self,payload):\n '''\n 编辑我的学习会\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"编辑我的学习会\")\n a = missionApi.editMeeting(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\"agendaIds\":[\"667150077277504157\"],\n \"content\":\"再次修改主题会议内容\",\n \"desc\": \"再次修改主题会议内容\",\n \"ext\": \"{\\\"video\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"audio\\\":{\\\"result\\\":\\\"\\\",\\\"name\\\":\\\"\\\"},\\\"content\\\":{\\\"contentHtml\\\":\\\"\\\",\\\"contentText\\\":\\\"\\\"}}\",\n \"id\": \"667150233641157277\",\n \"name\": \"测试编辑主题会\",\n \"pid\":\"666387367187186323\",\n \"startTime\":\"2020-04-25 23:00:00\"}])\n def test_editTheme(self,payload):\n '''\n 编辑主题内容\n 版本v1.1.0\n :param payload:\n :return:\n '''\n self.log.info(\"开始编辑主题内容\")\n a = missionApi.editTheme(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"idx\": 0,\n \"size\": 20\n }])\n def test_getMeetingDetail(self, payload):\n '''\n 学习会详���\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"学习会详情\")\n a = missionApi.getMeetingDetail(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{}])\n def test_getMeetingList(self, payload):\n '''\n 用户查询所有学习会列表\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"用户查询所有学习会列表\")\n a = missionApi.getMeetingList(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"idx\": 0,\n \"size\": 20\n }])\n def test_getMyMeetingList(self, payload):\n '''\n 用户查看我的会议列表\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"用户查看我的会议列表\")\n a = missionApi.getMyMeetingList(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"idx\": 0,\n \"size\": 20,\n \"userId\": \"636804209588568383\"\n }])\n def test_missionThemeList(self, payload):\n '''\n 任务主题列表查询(首页列表)\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"任务主题列表查询(首页列表)\")\n a = missionApi.missionThemeList(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{}])\n def test_queryThemeInfo(self, payload):\n '''\n 主题详情查询\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"主题详情查询\")\n a = missionApi.queryThemeInfo(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"ext\": \"{\\\"tagId\\\":\\\"626549294551269829\\\",\\\"meetingType\\\":1,\\\"timeUse\\\":\\\"4分钟\\\"}\",\n \"id\": \"667150077277504157\",\n \"name\": \"自由讨论\",\n \"tagId\": \"626549294551269829\"\n }])\n def test_updateAgenda(self, payload):\n '''\n 修改议程\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"修改议程\")\n a = missionApi.updateAgenda(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"missionId\": \"666387367187186323\",\n \"userId\": \"636804209588568383\"\n }])\n def test_userAddMission(self, payload):\n '''\n 用户加入学习会\n 版本v1.0.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"用户加入学习会\")\n a = missionApi.userAddMission(payload)\n assert a[\"msg\"] == self.expected_msg\n\n\n @pytest.mark.parametrize(\"payload\", [{\n \"missionId\": \"666387367187186323\",\n \"userId\": \"636804209588568383\"\n }])\n def test_userExitMission(self, payload):\n '''\n 用户退出学习会\n 版本v1.1.0\n :param payload: 参数\n :return:\n '''\n self.log.info(\"用户退出学习会\")\n a = missionApi.userExitMission(payload)\n assert a[\"msg\"] == self.expected_msg","sub_path":"TestCase/test_mission.py","file_name":"test_mission.py","file_ext":"py","file_size_in_byte":9924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"581251147","text":"\"\"\"\nCopyright (c) 2018-2020 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport enum\nimport math\nimport re\nimport warnings\nfrom collections import OrderedDict\nfrom copy import copy\nfrom functools import partial\nfrom pathlib import Path\n\nfrom ..utils import get_path, cast_to_bool\n\n\nclass ConfigError(ValueError):\n pass\n\n\nclass BaseValidator:\n def __init__(self, on_error=None, additional_validator=None):\n self.on_error = on_error\n self.additional_validator = additional_validator\n\n self.field_uri = None\n\n def validate(self, entry, field_uri=None):\n field_uri = field_uri or self.field_uri\n if self.additional_validator and not self.additional_validator(entry, field_uri):\n self.raise_error(entry, field_uri)\n\n def raise_error(self, value, field_uri, reason=None):\n if self.on_error:\n self.on_error(value, field_uri, reason)\n\n error_message = 'Invalid value \"{value}\" for {field_uri}'.format(value=value, field_uri=field_uri)\n if reason:\n error_message = '{error_message}: {reason}'.format(error_message=error_message, reason=reason)\n\n raise ConfigError(error_message.format(value, field_uri))\n\n\nclass _ExtraArgumentBehaviour(enum.Enum):\n WARN = 'warn'\n IGNORE = 'ignore'\n ERROR = 'error'\n\n\ndef _is_dict_like(entry):\n return hasattr(entry, '__iter__') and hasattr(entry, '__getitem__')\n\n\nclass ConfigValidator(BaseValidator):\n WARN_ON_EXTRA_ARGUMENT = _ExtraArgumentBehaviour.WARN\n ERROR_ON_EXTRA_ARGUMENT = _ExtraArgumentBehaviour.ERROR\n IGNORE_ON_EXTRA_ARGUMENT = _ExtraArgumentBehaviour.IGNORE\n acceptable_unknown_options = ['connector']\n\n def __init__(self, config_uri, on_extra_argument=WARN_ON_EXTRA_ARGUMENT, fields=None, **kwargs):\n super().__init__(**kwargs)\n self.on_extra_argument = on_extra_argument\n\n self.fields = OrderedDict()\n self.field_uri = config_uri\n\n if fields:\n for name in fields.keys():\n self.fields[name] = fields[name]\n if fields[name].field_uri is None:\n fields[name].field_uri = \"{}.{}\".format(config_uri, name)\n else:\n for name in dir(self):\n value = getattr(self, name)\n if not isinstance(value, BaseField):\n continue\n\n field_copy = copy(value)\n field_copy.field_uri = \"{}.{}\".format(config_uri, name)\n self.fields[name] = field_copy\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n field_uri = field_uri or self.field_uri\n if not _is_dict_like(entry):\n raise ConfigError(\"{} is expected to be dict-like\".format(field_uri))\n\n extra_arguments = []\n for key in entry:\n if key not in self.fields and key not in self.acceptable_unknown_options:\n extra_arguments.append(key)\n continue\n\n if key in self.acceptable_unknown_options:\n continue\n\n self.fields[key].validate(entry[key])\n\n required_fields = set(name for name, value in self.fields.items() if value.required())\n missing_arguments = required_fields.difference(entry)\n\n if missing_arguments:\n arguments = ', '.join(map(str, missing_arguments))\n self.raise_error(\n entry, field_uri, \"Invalid config for {}: missing required fields: {}\".format(field_uri, arguments)\n )\n\n if extra_arguments:\n unknown_options_error = \"specifies unknown options: {}\".format(extra_arguments)\n message = \"{} {}\".format(field_uri, unknown_options_error)\n\n if self.on_extra_argument == _ExtraArgumentBehaviour.WARN:\n warnings.warn(message)\n if self.on_extra_argument == _ExtraArgumentBehaviour.ERROR:\n self.raise_error(entry, field_uri, message)\n\n @property\n def known_fields(self):\n return set(self.fields)\n\n def raise_error(self, value, field_uri, reason=None):\n if self.on_error:\n self.on_error(value, field_uri, reason)\n else:\n raise ConfigError(reason)\n\n\nclass BaseField(BaseValidator):\n def __init__(self, optional=False, description=None, default=None, **kwargs):\n super().__init__(**kwargs)\n self.optional = optional\n self.description = description\n self.default = default\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n field_uri = field_uri or self.field_uri\n if self.required() and entry is None:\n raise ConfigError(\"{} is not allowed to be None\".format(field_uri))\n\n @property\n def type(self):\n return None\n\n def required(self):\n return not self.optional and self.default is None\n\n def parameters(self):\n parameters_dict = {}\n for key, _ in self.__dict__.items():\n if not key.startswith('_') and hasattr(self, key) and not hasattr(BaseValidator(), key):\n if isinstance(self.__dict__[key], BaseField):\n parameters_dict[key] = self.__dict__[key].parameters()\n else:\n parameters_dict[key] = self.__dict__[key]\n parameters_dict['type'] = type((self.type or str)()).__name__\n\n return parameters_dict\n\n\nclass StringField(BaseField):\n def __init__(self, choices=None, regex=None, case_sensitive=False, allow_own_choice=False, **kwargs):\n super().__init__(**kwargs)\n self.choices = choices if case_sensitive or not choices else list(map(str.lower, choices))\n self.allow_own_choice = allow_own_choice\n self.case_sensitive = case_sensitive\n self.set_regex(regex)\n\n def set_regex(self, regex):\n if regex is None:\n self._regex = regex\n self._regex = re.compile(regex, flags=re.IGNORECASE if not self.case_sensitive else 0) if regex else None\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n field_uri = field_uri or self.field_uri\n source_entry = entry\n\n if not isinstance(entry, str):\n raise ConfigError(\"{} is expected to be str\".format(source_entry))\n\n if not self.case_sensitive:\n entry = entry.lower()\n\n if self.choices and entry not in self.choices and not self.allow_own_choice:\n reason = \"unsupported option, expected one of: {}\".format(', '.join(map(str, self.choices)))\n self.raise_error(source_entry, field_uri, reason)\n\n if self._regex and not self._regex.match(entry):\n self.raise_error(source_entry, field_uri, reason=None)\n\n @property\n def type(self):\n return str\n\n\nclass DictField(BaseField):\n def __init__(self, key_type=None, value_type=None, validate_keys=True, validate_values=True, allow_empty=True,\n **kwargs):\n super().__init__(**kwargs)\n self.validate_keys = validate_keys if key_type else False\n self.validate_values = validate_values if value_type else False\n self.key_type = _get_field_type(key_type)\n self.value_type = _get_field_type(value_type)\n\n self.allow_empty = allow_empty\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n field_uri = field_uri or self.field_uri\n if not isinstance(entry, dict):\n raise ConfigError(\"{} is expected to be dict\".format(field_uri))\n\n if not entry and not self.allow_empty:\n self.raise_error(entry, field_uri, \"value is empty\")\n\n for k, v in entry.items():\n if self.validate_keys:\n uri = \"{}.keys.{}\".format(field_uri, k)\n self.key_type.validate(k, uri)\n\n if self.validate_values:\n uri = \"{}.{}\".format(field_uri, k)\n\n self.value_type.validate(v, uri)\n\n @property\n def type(self):\n return dict\n\n\nclass ListField(BaseField):\n def __init__(self, value_type=None, validate_values=True, allow_empty=True, **kwargs):\n super().__init__(**kwargs)\n self.validate_values = validate_values if value_type else False\n self.value_type = _get_field_type(value_type)\n self.allow_empty = allow_empty\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n if not isinstance(entry, list):\n raise ConfigError(\"{} is expected to be list\".format(field_uri))\n\n if not entry and not self.allow_empty:\n self.raise_error(entry, field_uri, \"value is empty\")\n\n if self.validate_values:\n for i, val in enumerate(entry):\n self.value_type.validate(val, \"{}[{}]\".format(val, i))\n\n @property\n def type(self):\n return list\n\n\nclass InputField(BaseField):\n INPUTS_TYPES = ('CONST_INPUT', 'INPUT', 'IMAGE_INFO', 'ORIG_IMAGE_INFO', 'LSTM_INPUT', 'IGNORE_INPUT')\n LAYOUT_TYPES = ('NCHW', 'NHWC', 'NCWH', 'NWHC')\n PRECISIONS = ('FP32', 'FP16', 'U8', 'U16', 'I8', 'I16', 'I32', 'I64')\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.name = StringField(description=\"Input name.\")\n self.input_type = StringField(choices=InputField.INPUTS_TYPES, description=\"Type name.\")\n self.value = BaseField(description=\"Input value.\")\n self.layout = StringField(optional=True, choices=InputField.LAYOUT_TYPES,\n description=\"Layout: \" + ', '.join(InputField.LAYOUT_TYPES))\n self.shape = BaseField(optional=True, description=\"Input shape.\")\n self.precision = StringField(optional=True, description='Input precision', choices=InputField.PRECISIONS)\n\n def validate(self, entry, field_uri=None):\n entry['optional'] = entry['type'] not in ['CONST_INPUT', 'LSTM_INPUT']\n super().validate(entry, field_uri)\n\n\nclass ListInputsField(ListField):\n def __init__(self, **kwargs):\n super().__init__(allow_empty=False, value_type=InputField(description=\"Input type.\"), **kwargs)\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n names_set = set()\n for input_layer in entry:\n input_name = input_layer['name']\n if input_name not in names_set:\n names_set.add(input_name)\n else:\n self.raise_error(entry, field_uri, '{} repeated name'.format(input_name))\n\n\nclass NumberField(BaseField):\n def __init__(self, value_type=float, min_value=None, max_value=None, allow_inf=False, allow_nan=False, **kwargs):\n super().__init__(**kwargs)\n self._value_type = value_type\n self.min = min_value\n self.max = max_value\n self._allow_inf = allow_inf\n self._allow_nan = allow_nan\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n field_uri = field_uri or self.field_uri\n if self.type != float and isinstance(entry, float):\n raise ConfigError(\"{} is expected to be int\".format(field_uri))\n if not isinstance(entry, int) and not isinstance(entry, float):\n raise ConfigError(\"{} is expected to be number\".format(field_uri))\n\n if self.min is not None and entry < self.min:\n reason = \"value is less than minimal allowed - {}\".format(self.min)\n self.raise_error(entry, field_uri, reason)\n if self.max is not None and entry > self.max:\n reason = \"value is greater than maximal allowed - {}\".format(self.max)\n self.raise_error(entry, field_uri, reason)\n\n if math.isinf(entry) and not self._allow_inf:\n self.raise_error(entry, field_uri, \"value is infinity\")\n if math.isnan(entry) and not self._allow_nan:\n self.raise_error(entry, field_uri, \"value is NaN\")\n\n @property\n def type(self):\n return self._value_type\n\n\nclass PathField(BaseField):\n def __init__(self, is_directory=False, check_exists=True, file_or_directory=False, **kwargs):\n super().__init__(**kwargs)\n self.is_directory = is_directory\n self.check_exists = check_exists\n self.file_or_directory = file_or_directory\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n field_uri = field_uri or self.field_uri\n try:\n get_path(entry, self.is_directory, self.check_exists, self.file_or_directory)\n except TypeError:\n self.raise_error(entry, field_uri, \"values is expected to be path-like\")\n except FileNotFoundError:\n self.raise_error(entry, field_uri, \"path does not exist\")\n except NotADirectoryError:\n self.raise_error(entry, field_uri, \"path is not a directory\")\n except IsADirectoryError:\n self.raise_error(entry, field_uri, \"path is a directory, regular file expected\")\n\n @property\n def type(self):\n return Path\n\n\nclass BoolField(BaseField):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def validate(self, entry, field_uri=None):\n super().validate(entry, field_uri)\n if entry is None:\n return\n\n field_uri = field_uri or self.field_uri\n if not isinstance(entry, bool):\n raise ConfigError(\"{} is expected to be bool\".format(field_uri))\n\n @property\n def type(self):\n return cast_to_bool\n\n def parameters(self):\n parameters_dict = {}\n for key, _ in self.__dict__.items():\n if not key.startswith('_') and hasattr(self, key) and not hasattr(BaseValidator(), key):\n if isinstance(self.__dict__[key], BaseField):\n parameters_dict[key] = self.__dict__[key].parameters()\n else:\n parameters_dict[key] = self.__dict__[key]\n parameters_dict['type'] = type(bool()).__name__\n return parameters_dict\n\n\ndef _get_field_type(key_type):\n if not isinstance(key_type, BaseField):\n type_ = _TYPE_TO_FIELD_CLASS.get(key_type)\n if callable(type_):\n return type_()\n\n return key_type\n\n\n_TYPE_TO_FIELD_CLASS = {\n int: partial(NumberField, value_type=int),\n float: partial(NumberField, value_type=float),\n dict: partial(DictField, validate_keys=False, validate_values=False),\n list: partial(ListField, validate_values=False),\n Path: PathField,\n str: StringField,\n bool: BoolField,\n}\n","sub_path":"tools/accuracy_checker/accuracy_checker/config/config_validator.py","file_name":"config_validator.py","file_ext":"py","file_size_in_byte":15265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"522120807","text":"class Queue:\n\tdef __init__(self):\n\t\tself.queue=[]\n\n\tdef isEmpty(self):\n\t\tif not self.queue:\n\t\t\t#print(\"Queue is empty\")\n\t\t\treturn True\n\t\telse:\n\t\t\tprint(\"Queue is not empty\")\n\t\t\t#return False\n\n\tdef push(self,data):\n\t\tif type(data) is list:\n\t\t\tfor i in range(0,len(data)):\n\t\t\t\tself.queue.append(data[i])\n\t\telse:\n\t\t\tself.queue.append(data)\n\n\tdef pop(self):\n\t\tif not self.queue:\n\t\t\tprint(\"cannot pop out of queue as queue is empty\")\n\t\t\treturn False\n\t\telse:\n\t\t\t return self.queue.pop(0)\n\n\tdef viewQueue(self):\n\t\ttemp=[]\n\t\ttemp=list(self.queue)\n\t\tif not temp:\n\t\t\tprint(\"Queue is empty\")\n\t\twhile temp:\n\t\t\tprint (temp[0])\n\t\t\ttemp.pop(0)\n\t\n\tdef top(self):\n\t\tif not self.queue:\n\t\t\treturn False \n\t\telse:\n\t\t\treturn self.queue[0]","sub_path":"easy_ds/Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"184690581","text":"from functools import partial\n\nimport pytest\n\nfrom ethereum import rlp\nfrom ethereum.frontier.fork import (\n calculate_intrinsic_cost,\n validate_transaction,\n)\nfrom ethereum.frontier.fork_types import Transaction\nfrom ethereum.utils.hexadecimal import hex_to_uint\nfrom tests.helpers import TEST_FIXTURES\n\nfrom ..helpers.fork_types_helpers import load_test_transaction\n\nETHEREUM_TESTS_PATH = TEST_FIXTURES[\"ethereum_tests\"][\"fixture_path\"]\n\ntest_dir = f\"{ETHEREUM_TESTS_PATH}/TransactionTests\"\n\nload_frontier_transaction = partial(load_test_transaction, network=\"Frontier\")\n\n\n@pytest.mark.parametrize(\n \"test_file_high_nonce\",\n [\n \"ttNonce/TransactionWithHighNonce64Minus1.json\",\n \"ttNonce/TransactionWithHighNonce64.json\",\n \"ttNonce/TransactionWithHighNonce64Plus1.json\",\n ],\n)\ndef test_high_nonce(test_file_high_nonce: str) -> None:\n test = load_frontier_transaction(test_dir, test_file_high_nonce)\n\n tx = rlp.decode_to(Transaction, test[\"tx_rlp\"])\n\n assert validate_transaction(tx) == False\n\n\n@pytest.mark.parametrize(\n \"test_file_nonce\",\n [\n \"ttNonce/TransactionWithHighNonce32.json\",\n \"ttNonce/TransactionWithHighNonce64Minus2.json\",\n ],\n)\ndef test_nonce(test_file_nonce: str) -> None:\n test = load_frontier_transaction(test_dir, test_file_nonce)\n\n tx = rlp.decode_to(Transaction, test[\"tx_rlp\"])\n\n result_intrinsic_gas_cost = hex_to_uint(\n test[\"test_result\"][\"intrinsicGas\"]\n )\n\n assert validate_transaction(tx) == True\n assert calculate_intrinsic_cost(tx) == result_intrinsic_gas_cost\n","sub_path":"tests/frontier/test_transaction.py","file_name":"test_transaction.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"488327923","text":"import json\nimport copy\n\nwith open('ws') as f:\n ws = json.load(f)\n\nwith open('sublist') as f:\n sublist = json.load(f)\n\nwith open('evaluations') as f:\n evals = json.load(f)\n\n # Special case 6.871 evals.\n # evals['6.871'] = evals['HST.956']\n\nclasses = {}\n\ndef all_virtual(sections):\n for s in sections:\n if s[1] != 'Virtual':\n return False\n return True\n\nfor c in ws:\n classes[c] = {\n 'no': c,\n 'co': ws[c]['course'],\n 'cl': ws[c]['class'],\n 'tb': ws[c]['tba'],\n \n 's': ws[c]['sections'],\n 'l': ws[c]['l'],\n 'r': ws[c]['r'],\n 'b': ws[c]['b'],\n 'lr': ws[c]['l_raw'],\n 'rr': ws[c]['r_raw'],\n 'br': ws[c]['b_raw']}\n\n classes[c]['hh'] = ws[c]['HASS-H']\n classes[c]['ha'] = ws[c]['HASS-A']\n classes[c]['hs'] = ws[c]['HASS-S']\n classes[c]['he'] = ws[c]['HASS-E']\n classes[c]['ci'] = ws[c]['CI-H']\n classes[c]['cw'] = ws[c]['CI-HW']\n classes[c]['re'] = ws[c]['REST']\n classes[c]['la'] = ws[c]['LAB']\n classes[c]['pl'] = ws[c]['pLAB']\n classes[c]['u1'] = ws[c]['units1']\n classes[c]['u2'] = ws[c]['units2']\n classes[c]['u3'] = ws[c]['units3']\n classes[c]['le'] = ws[c]['level']\n classes[c]['sa'] = ws[c]['same_as']\n classes[c]['mw'] = ws[c]['meets_with']\n classes[c]['t'] = ws[c]['terms']\n classes[c]['pr'] = ws[c]['prereq']\n classes[c]['d'] = ws[c]['desc']\n classes[c]['n'] = ws[c]['name']\n classes[c]['i'] = ws[c]['in-charge']\n classes[c]['v'] = all_virtual(ws[c]['l'] + ws[c]['r'] + ws[c]['b'])\n\n if c in sublist:\n classes[c]['nx'] = sublist[c]['no_next']\n classes[c]['rp'] = sublist[c]['repeat']\n classes[c]['u'] = sublist[c]['url']\n try:\n classes[c]['f'] = sublist[c]['final']\n except:\n print('failed to get final for', c)\n classes[c]['f'] = False\n else:\n classes[c]['nx'] = False\n classes[c]['rp'] = False\n classes[c]['u'] = ''\n classes[c]['f'] = False\n\n if c in evals:\n total_rating = 0\n total_hours = 0\n total_size = 0\n terms = 0\n \n for t in evals[c]:\n if t['resp'] > 0:\n total_rating += t['rating']\n total_hours += t['oc_hours'] + t['ic_hours']\n total_size += t['eligible']\n terms += 1\n \n if terms == 0:\n terms = 1\n \n classes[c]['ra'] = round(total_rating / terms, 1)\n classes[c]['h'] = round(total_hours / terms, 1)\n classes[c]['si'] = round(total_size / terms, 1)\n else:\n classes[c]['ra'] = 0\n classes[c]['h'] = 0\n classes[c]['si'] = 0\n\n# Special case 2.008 schedule.\n# classes['2.008']['s'] = ['l', 'b']\n# classes['2.008']['r'] = []\n\n\"\"\" try:\n # Special case 14.01/14.02 rec-only sections.\n classes['14.01R'] = copy.deepcopy(classes['14.01'])\n classes['14.01']['r'] = classes['14.01']['r'][:2]\n classes['14.01']['rr'] = classes['14.01']['rr'][:2]\n classes['14.01R']['no'] = '14.01R'\n classes['14.01R']['s'] = ['r']\n classes['14.01R']['r'] = classes['14.01R']['r'][2:]\n classes['14.01R']['rr'] = classes['14.01R']['rr'][2:]\n classes['14.01R']['n'] += \" (recitation only)\"\n del classes['14.01R']['l']\n\n\n classes['14.02R'] = copy.deepcopy(classes['14.02'])\n classes['14.02']['r'] = classes['14.02']['r'][:2]\n classes['14.02']['rr'] = classes['14.02']['rr'][:2]\n classes['14.02R']['no'] = '14.02R'\n classes['14.02R']['s'] = ['r']\n classes['14.02R']['r'] = classes['14.02R']['r'][2:]\n classes['14.02R']['rr'] = classes['14.02R']['rr'][2:]\n classes['14.02R']['n'] += \" (recitation only)\"\n del classes['14.02R']['l'] \n\n\nexcept Exception as e:\n print(e) \"\"\"\n\nwith open('full.json', 'w') as f:\n f.write('var classes = ')\n json.dump(classes, f, separators=(',', ':'))\n f.write(';')\n\n \n \n \n","sub_path":"new_scripts/combiner_ws.py","file_name":"combiner_ws.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"182316219","text":"#Project Euler problem 34\n# find the sum of all numbers which are equal to the sum of the factorial of their digits\ntotalsum=0\nfor i in range(3,100000): #Select a wide enough range.\n b=str(i)\n sum=0\n for j in b:\n a=1\n for k in range(2,int(j)+1):\n a*=k\n sum+=a\n if sum==i:\n totalsum+=sum\nprint(totalsum)\n#Correct!\n","sub_path":"ProjectEulerP34.py","file_name":"ProjectEulerP34.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"257101342","text":"\r\nimport numpy as np\r\nimport json\r\ndef load_tester(path):\r\n with open(path) as f:\r\n data = json.load(f)\r\n print(data)\r\n return np.asarray(data)\r\n\r\nd = load_tester('/home/superadmin/Downloads/via_export_coco (3).json')\r\n\r\nprint(type(d))\r\n\r\nnp.save('mask.npy',d)","sub_path":"scripts/36_json_npy_file.py","file_name":"36_json_npy_file.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"20512048","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\ntry:\n import pyros_msgs.opt_as_array # This will duck punch the standard message type initialization code.\n from pyros_msgs.msg import test_opt_bool_as_array # a message type just for testing\n\nexcept ImportError:\n # Because we need to access Ros message types here (from ROS env or from virtualenv, or from somewhere else)\n import pyros_setup\n # We rely on default configuration to point us ot the proper distro\n pyros_setup.configurable_import().configure().activate()\n import pyros_msgs.opt_as_array # This will duck punch the standard message type initialization code.\n from pyros_msgs.msg import test_opt_bool_as_array # a message type just for testing\n\n# patching\npyros_msgs.opt_as_array.duck_punch(test_opt_bool_as_array, ['data'])\n\nimport nose\n\n\ndef test_init_rosdata():\n msg = test_opt_bool_as_array(data=[True])\n assert msg.data == [True]\n\n msg = test_opt_bool_as_array(data=[False])\n assert msg.data == [False]\n\n msg = test_opt_bool_as_array(data=[])\n assert msg.data == []\n\n\ndef test_init_data():\n msg = test_opt_bool_as_array(data=True)\n assert msg.data == [True]\n\n msg = test_opt_bool_as_array(data=False)\n assert msg.data == [False]\n\n\ndef test_init_raw():\n msg = test_opt_bool_as_array(True)\n assert msg.data == [True]\n\n msg = test_opt_bool_as_array(False)\n assert msg.data == [False]\n\n\ndef test_init_default():\n msg = test_opt_bool_as_array()\n assert msg.data == []\n\n\ndef test_init_except():\n with nose.tools.assert_raises(AttributeError) as cm:\n test_opt_bool_as_array(42)\n assert cm.exception.message == \"field data has value [42] which is not of type bool[]\"\n\n\n# Just in case we run this directly\nif __name__ == '__main__':\n nose.runmodule(__name__)\n","sub_path":"tests/opt_as_array/test_opt_bool.py","file_name":"test_opt_bool.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"435777174","text":"import sqlite3\r\n\r\ncon = sqlite3.connect('carros.db')\r\n\r\ncursor = con.cursor()\r\n\r\ncursor.execute('''\r\nCREATE TABLE carros(\r\n id INTEGER PRIMARY KEY NOT NULL,\r\n nome VARCHAR(100) NOT NULL,\r\n cor VARCHAR(20) NOT NULL\r\n);\r\n''')\r\n\r\ncon.commit()\r\n\r\ncon.close()","sub_path":"exercicio S1.py","file_name":"exercicio S1.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"264442839","text":"#!/usr/bin/python\nimport argparse\nimport sys\nfrom argparse import RawTextHelpFormatter\nfrom itertools import zip_longest as izip_longest\n\nimport numpy as np\nfrom termcolor import colored\n\nimport libs.fingerprint as fingerprint\nfrom libs.config import get_config\nfrom libs.db_sqlite import SqliteDatabase\nfrom libs.reader_microphone import MicrophoneReader\nfrom libs.visualiser_console import VisualiserConsole as visual_peak\nfrom libs.visualiser_plot import VisualiserPlot as visual_plot\nfrom contextlib import redirect_stdout\n\n\n# from libs.db_mongo import MongoDatabase\n\ndef writeTofile(data, filename):\n with open(filename, 'wb') as file:\n file.write(data)\n print(\"Stored blob data into: \", filename, \"\\n\")\n\ndef align_matches(matches):\n diff_counter = {}\n largest = 0\n largest_count = 0\n song_id = -1\n\n\n for tup in matches:\n sid, diff = tup\n\n if diff not in diff_counter:\n diff_counter[diff] = {}\n\n if sid not in diff_counter[diff]:\n diff_counter[diff][sid] = 0\n\n diff_counter[diff][sid] += 1\n\n if diff_counter[diff][sid] > largest_count:\n largest = diff\n largest_count = diff_counter[diff][sid]\n song_id = sid\n\n songM = db.get_song_by_id(song_id)\n #genreM= db.get_song_by_id(song_id)\n #artistM=db.get_song_by_id(song_id)\n\n\n\n\n nseconds = round(float(largest) / fingerprint.DEFAULT_FS *\n fingerprint.DEFAULT_WINDOW_SIZE *\n fingerprint.DEFAULT_OVERLAP_RATIO, 5)\n\n return {\n \"SONG_ID\": song_id,\n \"SONG_NAME\": songM[1],\n \"CONFIDENCE\": largest_count,\n \"OFFSET\": int(largest),\n \"OFFSET_SECS\": nseconds,\n \"GENRE\": songM[3],\n \"ARTIST\":songM[4],\n \"ART\":songM[5],\n \"ALBUM\": songM[6]\n\n }\n\n\ndef grouper(iterable, n, fillvalue=None):\n args = [iter(iterable)] * n\n return (filter(None, values)\n for values in izip_longest(fillvalue=fillvalue, *args))\n\n\ndef find_matches(samples, Fs=fingerprint.DEFAULT_FS):\n hashes = fingerprint.fingerprint(1,samples, Fs=Fs)\n return return_matches(hashes)\n\n\ndef return_matches(hashes):\n mapper = {}\n for hash, offset in hashes:\n mapper[hash.upper()] = offset\n values = mapper.keys()\n\n # https://www.sqlite.org/limits.html\n # To prevent excessive memory allocations,\n # the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER, which defaults to 999 for SQLites\n for split_values in map(list, grouper(values, 999)):\n # @todo move to db related files\n query = \"\"\"\n SELECT upper(hash), song_fk, offset\n FROM fingerprints\n WHERE upper(hash) IN (%s)\n \"\"\"\n query = query % ', '.join('?' * len(split_values))\n\n x = db.executeAll(query, split_values)\n matches_found = len(x)\n\n if matches_found > 0:\n msg = ' ** found %d hash matches (step %d/%d)'\n #print(colored(msg, 'green') % (\n #matches_found,\n #len(split_values),\n #len(values)\n #))\n pass\n else:\n msg = ' ** not matches found (step %d/%d)'\n #print(colored(msg, 'red') % (len(split_values), len(values)))\n\n for hash_code, sid, offset in x:\n # (sid, db_offset - song_sampled_offset)\n if isinstance(offset, bytes):\n # offset come from fingerprint.py and numpy extraction/processing\n offset = np.frombuffer(offset, dtype=np.int)[0]\n yield sid, offset - mapper[hash_code]\n\n\nif __name__ == '__main__':\n sys.stdout = open(\"out.txt\", \"w\")\n config = get_config()\n\n db = SqliteDatabase()\n\n\n\n seconds = 6\n\n chunksize = 2 ** 12 # 4096\n channels = 1 # int(config['channels']) # 1=mono, 2=stereo\n\n record_forever = False\n visualise_console = bool(config['mic.visualise_console'])\n visualise_plot = bool(config['mic.visualise_plot'])\n\n reader = MicrophoneReader(None)\n\n reader.start_recording(seconds=seconds,\n chunksize=chunksize,\n channels=channels)\n\n msg = ' * started recording..'\n #print(colored(msg, attrs=['dark']))\n\n while True:\n bufferSize = int(reader.rate / reader.chunksize * seconds)\n\n for i in range(0, bufferSize):\n nums = reader.process_recording()\n\n if visualise_console:\n msg = colored(' %05d', attrs=['dark']) + colored(' %s', 'green')\n #print(msg % visual_peak.calc(nums))\n else:\n msg = ' processing %d of %d..' % (i, bufferSize)\n #print(colored(msg, attrs=['dark']))\n\n if not record_forever:\n break\n\n if visualise_plot:\n data = reader.get_recorded_data()[0]\n visual_plot.show(data)\n\n reader.stop_recording()\n\n msg = ' * recording has been stopped'\n #print(colored(msg, attrs=['dark']))\n\n data = reader.get_recorded_data()\n\n msg = ' * recorded %d samples'\n #print(colored(msg, attrs=['dark']) % len(data[0]))\n\n # reader.save_recorded('test.wav')\n\n Fs = fingerprint.DEFAULT_FS\n channel_amount = len(data)\n\n result = set()\n matches = []\n\n for channeln, channel in enumerate(data):\n # TODO: Remove prints or change them into optional logging.\n msg = ' fingerprinting channel %d/%d'\n #print(colored(msg, attrs=['dark']) % (channeln + 1, channel_amount))\n\n matches.extend(find_matches(channel))\n\n msg = ' finished channel %d/%d, got %d hashes'\n #print(colored(msg, attrs=['dark']) % (channeln + 1,\n # channel_amount, len(matches)))\n\n total_matches_found = len(matches)\n\n #print('')\n\n if total_matches_found > 0:\n msg = ' ** totally found %d hash matches'\n #print(colored(msg, 'green') % total_matches_found)\n\n song = align_matches(matches)\n\n msg = ' \\n=> Song: %s \\n'\n #msg += ' offset: %d (%d secs)\\n'\n #msg += ' confidence: %d\\n'\n msg += ' Genre: %s\\n'\n msg += ' Artist: %s\\n'\n msg += ' Album:%s\\n'\n msg += '%s\\n'\n\n\n\n\n\n print(colored(msg, 'green') % (song['SONG_NAME'],\n #song['SONG_ID'],\n #song['OFFSET'], song['OFFSET_SECS'],\n #song['CONFIDENCE'],\n song['GENRE'],\n song['ARTIST'],\n song['ALBUM'],\n song['SONG_NAME'] + song['ARTIST']))\n photo=song['ART']\n photoPath = \"example\" + \".jpg\"\n\n writeTofile(photo, photoPath)\n\n else:\n msg = ' \\n\\nNo matches found\\n\\n\\n '\n print(colored(msg, 'red'))\n\n sys.stdout.close()\n\n\n\n\n\n","sub_path":"recognize-from-microphone.py","file_name":"recognize-from-microphone.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"603092051","text":"\nclass atm:\n balance = 1000\n\n def __init__(self, pin):\n self.pin = pin\n \n \n \n def deposit(self):\n amount = eval(input('enter amount to deposit: '))\n self.balance = self.balance + amount\n print('your deposited amount is ', amount, '\\n Your new balance is ', d1.balance)\n print('Transaction successful.')\n \n def atmPin(self):\n pin = input('enter pin to proceed: ')\n if len(pin) == 5:\n return\n else:\n print('enter correct number')\n\n def getBalance(self):\n self.balance = self.balance\n select = eval(input('select account. \\n1: Savings \\n2: current \\nEnter: '))\n if select == 1:\n print(self.balance)\n elif select == 2:\n print(d1.balance)\n else:\n print('service not available')\n\n def transfer(self):\n amount = eval(input('enter amount to transfer: '))\n self.balance = self.balance - amount\n d1.balance = d1.balance + amount\n print(' verify amount to transfer:', amount)\n input(\"Press enter to Proceed.\")\n print('transaction successful')\n \n\n def withdrawal(self):\n amount = eval(input('enter amount to withdraw: '))\n self.balance = self.balance - amount\n print(' verify amount to withdraw:', amount)\n input(\"Press enter to Proceed.\")\n print('transaction successful')\n \n\n def atmProcess(self):\n print('Welcome to Python Bank \\nATM Services.')\n print('tips for the day \\ndo not disclose your pin to anyone to avoid theft.')\n d1.atmPin()\n choice = eval(input('Choose Service \\n1: Deposit \\n2: Withdrawal \\n3: Check balance \\n4: Transfer \\nEnter: '))\n if choice == 1:\n d1.deposit()\n elif choice == 2:\n d1.withdrawal()\n elif choice == 3:\n d1.getBalance()\n elif choice == 4:\n d1.transfer()\n\n else:\n print('you have entered a wrong number.')\n\n \n\n\n\n\n\n\nclass elecBill:\n #unitPrice = 0.7979\n vat = 0.1250\n natElecL = 0.0200\n striL = 0.0300\n nhilGet = 0.0500\n serCharg = 0.4075\n montBill = {}\n\n def __init__(self, unitPrice):\n self.unitPrice = 0.7979\n\n def meterRead(self):\n #self.prev = prev\n #self.cur = cur\n #prev = eval(input('Enter previous meter readings: '))\n #cur = eval(input('Enter current meter readings: '))\n if cur > prev:\n metread = cur - prev\n print(metread, 'kWh')\n\n else:\n return\n\n def monthBill(self):\n self.montBill = round((metread * self.unitPrice),3)\n #return monthBill \n print('Bill is: ', self.montBill)\n\n def vatR(self):\n vaR = ((cur - prev) * self.unitPrice)\n self.va = round((self.vat * ((32*self.serCharg) + vaR)),2)\n print('Vat on bill: ', self.va)\n def natElecLe(self):\n nat = ((cur - prev) * self.unitPrice)\n self.natElec = round((self.natElecL * nat),2)\n print('National Electr. Levy: ', self.natElec)\n def striLi(self):\n light = ((cur - prev) * self.unitPrice)\n self.striLii = round((self.striL * light),2)\n print('street Light: ', self.striLii)\n def nhilGetF(self):\n get = ((cur - prev) * self.unitPrice)\n self.nhilGe = round((self.nhilGet * ((32*self.serCharg) + get)),2)\n print('NHIS and GETFUND Levy: ', self.nhilGe)\n def servChar(self):\n servCha = round((32 * self.serCharg),2)\n print('Service charges for 32days: ', servCha)\n def totalThisMonth(self):\n #current = ((cur -prev ) * self.unitPrice)\n #totalThisMont = round(((current) + (current * self.serCharg) + (current * self.nhilGet) + \n #(current * self.striL) + (current * self.natElecL) + (current * self.vat)),2)\n totalThisMont = round(((self.montBill) + (32 * self.serCharg) + ((self.montBill + (32 * self.serCharg)) * self.nhilGet) + (self.montBill * self.striL) + \n (self.montBill * self.natElecL) + (((self.montBill + (32 * self.serCharg)) * self.vat))),3)\n print('Total current bill: ', totalThisMont)\n\n\n \n def elecCal(self):\n choice = eval(input('choose 1: monthly calcuation \\n2: other services \\nEnter: '))\n if choice == 1:\n d.meterRead()\n d.monthBill()\n d.vatR()\n d.natElecLe()\n d.striLi()\n d.nhilGetF()\n d.servChar()\n d.totalThisMonth()\n elif choice == 2:\n choose = eval(input('1: NHIS and GETFUND \\n2: Service charges \\n3: Value Added Tax(VAT) \\n4: Meter Readings \\n5: Stright Light \\n6: National Electrification Levy \\n7: This Month Bill \\n Enter: '))\n if choose ==1:\n d.nhilGetF()\n elif choose ==2:\n d.servChar()\n elif choose ==3:\n d.vatR()\n elif choose == 4:\n d.meterRead()\n elif choose == 5:\n d.striLi()\n elif choose == 6:\n d.natElecLe()\n else:\n print('Wrong selection.')\n \n \n \n \n else:\n print('start again.')\n\n#print('Electricity bill calculation.')\n#prev = eval(input('Enter previous meter readings: '))\n#cur = eval(input('Enter current meter readings: '))\n#metread = cur - prev\n#d = elecBill(0.7979)\n\n#d.elecCal()\n\nd1 = atm(1234)\nd2 = atm(5678)\n\n\nd1.atmProcess()\n\n","sub_path":"class atm and meter.py","file_name":"class atm and meter.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"635668288","text":"# Descrição: um programa em python GUI for a chat bot\n\n# Biblioteca\nfrom tkinter import *\n\nstorage_adapter=\"chatterbot.storage.MongoDatabaseAdapter\"\nfrom chatterbot import ChatBot\n\n# Uncomment the following lines to enable verbose logging\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n#Criando o objeto tK do tkinter\nroot = Tk()\n\n# Colocando o titulo da janela\nroot.title('Chat Bot Hank')\n\n# Inserindo o tamanho da janela ou Geometria\nroot.geometry('400x500')\n\n#Create a main menu bar\nmain_menu = Menu(root)\n\n#Create submenu\nfile_menu = Menu(root)\nfile_menu.add_command(label='Novo', font=('ubuntu'))\nfile_menu.add_command(label='Salvar como', font=('ubuntu'))\nfile_menu.add_command(label='Sair', font=('ubuntu'))\n\n\nmain_menu.add_cascade(label='File', menu=file_menu)\nmain_menu.add_command(label='Edit')\nmain_menu.add_command(label='Quit')\nroot.config(menu=main_menu)\n\n#Create the chat window\nchatWindow = Text(root, bd=1, bg='black', width=50, height=0)\nchatWindow.place(x=6, y=6, height=385, width=370)\n\n#Create tk message window\nmessageWindow = Text(root, bg='black', width=30, height=4,)\nmessageWindow.place(x=128, y=400, height=88, width=260)\n\n#Create a button to send the message the message\nButton = Button(root, text='ENVIAR', bg='blue', activebackground='light blue', width=12, height=5, font=('ubuntu', 20))\nButton.place(x=6, y=400, height=88, width=120)\n\n#Add a scroll bar\nscrollbar = Scrollbar(root, command=chatWindow.yview())\nscrollbar.place(x=375, y=5, height=385)\n\nroot.mainloop()\n","sub_path":"pythonProject/Interfaces/RealPython/ChatBot_SimpleGUI.py","file_name":"ChatBot_SimpleGUI.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"445048930","text":"import random\nfrom threading import Thread\nimport unittest\nimport uuid\nimport logger\nimport time\n\nfrom membase.helper.spatial_helper import SpatialHelper\nfrom membase.helper.failover_helper import FailoverHelper\n\n\nclass SpatialViewTests(unittest.TestCase):\n def setUp(self):\n self.log = logger.Logger.get_logger()\n self.helper = SpatialHelper(self, \"default\")\n self.helper.setup_cluster()\n\n\n def tearDown(self):\n self.helper.cleanup_cluster()\n\n\n def test_create_multiple_development_spatial(self):\n self.log.info(\"description : create multiple spatial views without \"\n \"running any spatial view query\")\n rest = self.helper.rest\n bucket = self.helper.bucket\n prefix = str(uuid.uuid4())\n name = \"dev_test_spatial_multiple\"\n\n design_names = [\"{0}-{1}-{2}\".format(name, i, prefix) \\\n for i in range(0, 5)]\n for design_name in design_names:\n self.helper.create_index_fun(design_name)\n response = rest.get_spatial(bucket, design_name)\n self.assertTrue(response)\n self.assertEquals(response[\"_id\"],\n \"_design/{0}\".format(design_name))\n self.log.info(response)\n\n\n def test_insert_x_docs(self):\n num_docs = self.helper.input.param(\"num-docs\", 100)\n self.log.info(\"description : create a spatial view on {0} documents\"\\\n .format(num_docs))\n design_name = \"dev_test_insert_{0}_docs\".format(num_docs)\n prefix = str(uuid.uuid4())[:7]\n\n inserted_keys = self._setup_index(design_name, num_docs, prefix)\n self.assertEqual(len(inserted_keys), num_docs)\n\n\n # Does verify the full docs and not only the keys\n def test_insert_x_docs_full_verification(self):\n num_docs = self.helper.input.param(\"num-docs\", 100)\n self.log.info(\"description : create a spatial view with {0} docs\"\n \" and verify the full documents\".format(num_docs))\n design_name = \"dev_test_insert_{0}_docs_full_verification\"\\\n .format(num_docs)\n prefix = str(uuid.uuid4())[:7]\n\n self.helper.create_index_fun(design_name)\n inserted_docs = self.helper.insert_docs(num_docs, prefix,\n return_docs=True)\n self.helper.query_index_for_verification(design_name, inserted_docs,\n full_docs=True)\n\n\n def test_insert_x_delete_y_docs(self):\n num_docs = self.helper.input.param(\"num-docs\", 15000)\n num_deleted_docs = self.helper.input.param(\"num-deleted-docs\", 10000)\n self.log.info(\"description : create spatial view with {0} docs \"\n \" and delete {1} docs\".format(num_docs,\n num_deleted_docs))\n design_name = \"dev_test_insert_{0}_delete_{1}_docs\"\\\n .format(num_docs, num_deleted_docs)\n prefix = str(uuid.uuid4())[:7]\n\n inserted_keys = self._setup_index(design_name, num_docs, prefix)\n\n # Delete documents and very that the documents got deleted\n deleted_keys = self.helper.delete_docs(num_deleted_docs, prefix)\n results = self.helper.get_results(design_name, 2*num_docs)\n result_keys = self.helper.get_keys(results)\n self.assertEqual(len(result_keys), num_docs-len(deleted_keys))\n self.helper.verify_result(inserted_keys, deleted_keys + result_keys)\n\n\n def test_insert_x_update_y_docs(self):\n num_docs = self.helper.input.param(\"num-docs\", 15000)\n num_updated_docs = self.helper.input.param(\"num-updated-docs\", 100)\n self.log.info(\"description : create spatial view with {0} docs \"\n \" and update {1} docs\".format(num_docs,\n num_updated_docs))\n design_name = \"dev_test_insert_{0}_delete_{1}_docs\"\\\n .format(num_docs, num_updated_docs)\n prefix = str(uuid.uuid4())[:7]\n\n self._setup_index(design_name, num_docs, prefix)\n\n # Update documents and verify that the documents got updated\n updated_keys = self.helper.insert_docs(num_updated_docs, prefix,\n dict(updated=True))\n results = self.helper.get_results(design_name, 2*num_docs)\n result_updated_keys = self._get_updated_docs_keys(results)\n self.assertEqual(len(updated_keys), len(result_updated_keys))\n self.helper.verify_result(updated_keys, result_updated_keys)\n\n\n def test_get_spatial_during_x_min_load_y_working_set(self):\n num_docs = self.helper.input.param(\"num-docs\", 10000)\n duration = self.helper.input.param(\"load-time\", 1)\n self.log.info(\"description : this test will continuously insert data \"\n \"and get the spatial view results for {0} minutes\")\n design_name = \"dev_test_insert_and_get_spatial_{0}_mins\"\\\n .format(duration)\n prefix = str(uuid.uuid4())[:7]\n\n self.helper.create_index_fun(design_name)\n\n self.docs_inserted = []\n self.shutdown_load_data = False\n load_thread = Thread(\n target=self._insert_data_till_stopped,\n args=(num_docs, prefix))\n load_thread.start()\n\n self._get_results_for_x_minutes(design_name, duration)\n\n self.shutdown_load_data = True\n load_thread.join()\n\n # self.docs_inserted was set by the insertion thread\n # (_insert_data_till_stopped)\n self.helper.query_index_for_verification(design_name,\n self.docs_inserted)\n\n\n # Create the index and insert documents including verififaction that\n # the index contains them\n # Returns the keys of the inserted documents\n def _setup_index(self, design_name, num_docs, prefix):\n self.helper.create_index_fun(design_name)\n inserted_keys = self.helper.insert_docs(num_docs, prefix)\n self.helper.query_index_for_verification(design_name, inserted_keys)\n\n return inserted_keys\n\n\n # Return the keys for all docs that contain a key called \"updated\"\n # in the value\n def _get_updated_docs_keys(self, results):\n keys = []\n if results:\n rows = results[\"rows\"]\n for row in rows:\n if \"updated\" in row[\"value\"]:\n keys.append(row[\"id\"].encode(\"ascii\", \"ignore\"))\n self.log.info(\"{0} documents to updated\".format(len(keys)))\n return keys\n\n\n def _get_results_for_x_minutes(self, design_name, duration, delay=5):\n random.seed(0)\n start = time.time()\n while (time.time() - start) < duration * 60:\n limit = random.randint(1, 1000)\n self.log.info(\"{0} seconds has passed ....\".format(\n (time.time() - start)))\n results = self.helper.get_results(design_name, limit)\n keys = self.helper.get_keys(results)\n self.log.info(\"spatial view returned {0} rows\".format(len(keys)))\n time.sleep(delay)\n\n def _insert_data_till_stopped(self, num_docs, prefix):\n while not self.shutdown_load_data:\n # Will be read after the function is terminated\n self.docs_inserted = self.helper.insert_docs(\n num_docs, prefix, wait_for_persistence=False)\n\n\n def test_x_docs_failover(self):\n num_docs = self.helper.input.param(\"num-docs\", 10000)\n self.log.info(\"description : test failover with {0} documents\"\\\n .format(num_docs))\n design_name = \"dev_test_failover_{0}\".format(num_docs)\n prefix = str(uuid.uuid4())[:7]\n\n fh = FailoverHelper(self.helper.servers, self)\n\n inserted_keys = self._setup_index(design_name, num_docs, prefix)\n failover_nodes = fh.failover(1)\n self.helper.query_index_for_verification(design_name, inserted_keys)\n\n # The test cleanup expects all nodes running, hence spin the\n # full cluster up again\n fh.undo_failover(failover_nodes)\n","sub_path":"pytests/spatialviewtests.py","file_name":"spatialviewtests.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"90215164","text":"# config.py\n\nimport os\nfrom flask import Flask\n\nWEB_ADDRESS = '0.0.0.0'\nWEB_PORT = 5000\n\n# __file__ : 현재 수행중인 코드를 담고 있는 파일의 위치\n# os.path.abspath(파일명) : 해당 파일의 절대 경로 확인\n# os.path.dirname(경로+파일) : 파일에서 디렉토리 명만 알아냄\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n# 파일의 경로 지정하기\nTEMPLATES = os.path.join(PROJECT_ROOT, 'droneapp/templates')\nSTATIC_FOLDER = os.path.join(PROJECT_ROOT, 'droneapp/static')\n\n# 디버그 모드 설정\nDEBUG = False\n\n# 로그 파일\nLOG_FILE = 'tello.log'\n\n# Flask 인스턴스를 생성\napp = Flask(__name__, template_folder=TEMPLATES, static_folder=STATIC_FOLDER)\n\nif DEBUG: # 만약 디버그 모드라면\n app.debug = DEBUG # flask의 debug모드 활성화","sub_path":"drone-control-with-flask/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"450329844","text":"#!/usr/bin/env python\n\n\"\"\" CHALLENGE, PART 2:\n\nFuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. \nAny mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.\n\nSo, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. \n\nWhat is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? \n(Calculate the fuel requirements for each module separately, then add them all up at the end.)\n\n\"\"\"\n\nimport math\nimport sys\n\ndef total_fuel(fuel): # recursion!\n fuels_fuel = math.floor(fuel / 3) - 2 # the fuel required for each amount of fuel\n if fuels_fuel <= 0:\n return 0 # return zero if less than zero to avoid negatives\n else:\n return fuels_fuel + total_fuel(fuels_fuel) # total together the total amount of fuel needed\n\nwith open(sys.argv[1]) as file: # same as part 1...\n lines = file.readlines()\n total = 0\n for line in lines:\n total += total_fuel(int(line)) # recursion to determine the fuel for each mass of fuel\n print(total)","sub_path":"day-01/python/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"571836070","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#########################################################################\n# File Name: test_getparas.py\n# Author: jyxu\n# mail: ahcigar@foxmail.com\n# Created Time: 四 9/27 15:44:33 2018\n#########################################################################\nimport unittest\n###\nimport numpy as np\nfrom get_paras import *\nclass TestGetParas(unittest.TestCase):\n '''Test get_paras.py'''\n '''def calc_distance(abc, XYZ1, XYZ2):\n XYZ must be absolute coordinates [X, Y, Z]\n # 1----2\n ###\n XYZ1 = (abc.T*XYZ1).T.sum(0)\n XYZ2 = (abc.T*XYZ2).T.sum(0)\n return round(np.linalg.norm(XYZ1-XYZ2), 8)'''\n def test_cal_distance(self):\n \"\"\"Test calculate distance\"\"\"\n abc = np.array([[1,0,0],[0,1,0],[0,0,1]])\n XYZ1 = np.array([1,0,0])\n XYZ2 = np.array([1,0,0])\n XYZ3 = np.array([2,0,0])\n self.assertEqual(0, calc_distance(abc, XYZ1, XYZ2))\n self.assertNotEqual(0, calc_distance(abc, XYZ1, XYZ3))\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"LasAndClf-dev/get_data_packages/GetData3_DAH10/test_getparas.py","file_name":"test_getparas.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"207900704","text":"# -*- coding: utf-8 -*-\n#Python Imports\nfrom datetime import date, datetime, time\nimport xlsxwriter\nimport base64\n\n#Odoo Imports\nfrom odoo import models, fields, api\nfrom odoo.exceptions import UserError, ValidationError\n\nclass ExcelExportMixin(models.AbstractModel):\n _name = 'export.excel.mixin'\n _description = 'This model represents an abstract parent class used to manage excel reports'\n \n name = fields.Char()\n active = fields.Boolean(default=True)\n \n start_date = fields.Date(\n string = 'Date from',\n )\n \n end_date = fields.Date(\n string = 'Date to',\n )\n \n #attachment\n attachment_id = fields.Many2one(\n 'ir.attachment',\n string = 'Excel File',\n readonly = True,\n )\n \n is_generated = fields.Boolean(\n readonly = True,\n default = False,\n )\n \n notes = fields.Char()\n \n #internal/external partner to share the info with\n partner_ids = fields.Many2many(\n 'res.partner',\n string = 'Audience',\n )\n \n ################\n # TOOL METHODS #\n ################\n\n def get_excel(self):\n return {\n 'type': 'ir.actions.act_url',\n 'name': 'get_export_file',\n 'url': '/web/content/%s/%s?download=true' % (self.attachment_id.id, self.attachment_id.name),\n }\n \n def generate_excel(self,data=[{'col1_name':'','col2name':''}]):\n self.ensure_one()\n #build book and sheet\n filename = self.name + '.xlsx'\n workbook = xlsxwriter.Workbook(filename)\n worksheet = workbook.add_worksheet() \n \n #write Header row\n j = 0\n for key,value in data[0].items():\n worksheet.write(0, j, key)\n j += 1\n \n #write the data rows\n i = 1\n for row in data:\n j = 0\n for key,value in row.items():\n worksheet.write(i, j, value)\n j += 1\n i += 1\n \n #close & encode\n workbook.close() \n \n try:\n company = self.company_id.id\n except:\n company = False\n \n #Encode and save as attachment\n with open(filename, \"rb\") as f:\n data = f.read()\n encoded = base64.b64encode(data)\n attachment_data = {\n 'res_id': self.id,\n 'res_model': self._name,\n 'company_id': company,\n 'name': filename,\n 'type': 'binary',\n 'datas_fname': filename,\n 'datas': encoded,\n }\n self.attachment_id = self.env['ir.attachment'].create(attachment_data)\n self.is_generated = True\n \n ######################\n # VALIDATION METHODS #\n ######################\n @api.constrains('start_date', 'end_date')\n def _check_dates(self):\n for export in self:\n if export.start_date and export.end_date:\n if export.start_date > export.end_date:\n raise ValidationError(\"Date configuration error: Date to: {} is before Date from: {}\".format(export.start_date,export.end_date))\n ","sub_path":"vcls-interfaces/models/excel_export_mixin.py","file_name":"excel_export_mixin.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"182493417","text":"#!/usr/bin/env python3\n\nfrom QUBEKit.utils.constants import BOHR_TO_ANGS, ELECTRON_CHARGE, J_TO_KCAL_P_MOL, M_TO_ANGS, PI, VACUUM_PERMITTIVITY\nfrom QUBEKit.utils.decorators import for_all_methods, timer_logger\nfrom QUBEKit.utils.file_handling import extract_charge_data\n\nfrom functools import lru_cache\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.cm import ScalarMappable\n\n# DO NOT REMOVE THIS IMPORT. ALTHOUGH IT IS NOT EXPLICITLY CALLED, IT IS NEEDED FOR 3D PLOTTING.\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\n@for_all_methods(timer_logger)\nclass Charges:\n \"\"\"\n * Identify atoms which need a v-site.\n * Generate sample points in shells around that atom (shells are 1.4-2.0x the vdW radius).\n * Calculate the multipole expansion esp at all of those sample points.\n * Identify the vectors along which a single virtual site would sit, and two virtual sites would sit.\n * Move the virtual sites along this vector and vary the charges.\n * Calculate the monopole esp at all the sample points with each move.\n * Fit the positions and charges of the virtual sites, minimising the difference between the\n full multipole esp and the monopole esp with a virtual site.\n * Store the final locations and charges of the virtual sites, as well as the errors.\n * Plot the results\n\n Numpy arrays are used throughout for faster calculation of esp values.\n \"\"\"\n\n # van der Waal's radii of atoms common in organic compounds; units: Angstroms\n vdw_radii = {\n 'H': 1.44,\n 'B': 2.04,\n 'C': 1.93,\n 'N': 1.83,\n 'O': 1.75,\n 'F': 1.68,\n 'P': 2.07,\n 'S': 2.02,\n 'Cl': 1.97,\n 'I': 2.25,\n }\n\n def __init__(self, molecule):\n\n self.molecule = molecule\n self.coords = self.molecule.coords['qm'] if self.molecule.coords['qm'] is not [] else self.molecule.coords[\n 'input']\n\n self.ddec_data, self.dipole_moment_data, self.quadrupole_moment_data = extract_charge_data(\n self.molecule.ddec_version)\n\n # List of tuples where each tuple is the xyz atom coords, followed by their partial charge\n self.atom_points = [(coord, atom.partial_charge) # [((x, y, z), q), ... ]\n for coord, atom in zip(self.coords, self.molecule.atoms)]\n\n # List of tuples where each tuple is the xyz coords of the v-site(s),\n # followed by their charge and index of the parent atom\n self.v_sites_coords = [] # [((x, y, z), q, atom_index), ... ]\n\n # Kept separate for graphing comparisons\n self.one_site_coords = None # [((x, y, z), q, atom_index), ... ]\n self.two_site_coords = None # [((x, y, z), q, atom_index), ... ]\n\n self.site_errors = {\n 0: None,\n 1: None,\n 2: None,\n }\n\n for atom_index, atom in enumerate(self.molecule.atoms):\n if atom.atomic_symbol in ['N', 'O', 'F', 'P', 'S', 'Cl', 'Br', 'I']:\n self.sample_points = self.generate_sample_points_atom(atom_index)\n self.no_site_esps = self.generate_esp_atom(atom_index)\n self.fit(atom_index)\n self.plot()\n self.write_xyz()\n\n @staticmethod\n def spherical_to_cartesian(spherical_coords):\n \"\"\"\n :return: Cartesian (x, y, z) coords from the spherical (r, theta, phi) coords.\n \"\"\"\n r, theta, phi = spherical_coords\n return np.array([r * np.sin(theta) * np.cos(phi), r * np.sin(theta) * np.sin(phi), r * np.cos(theta)])\n\n @staticmethod\n def xyz_distance(point1, point2):\n \"\"\"\n :param point1: coordinates of a point\n :param point2: coordinates of another point\n :return: distance between the two points\n \"\"\"\n return np.linalg.norm(point1 - point2)\n\n @staticmethod\n def monopole_esp_one_charge(charge, dist):\n \"\"\"\n Calculate the esp from a monopole at a given distance\n :param charge: charge at atom centre\n :param dist: distance from sample_coords to atom_coords\n (provided as argument to prevent repeated calculation)\n :return: monopole esp value\n \"\"\"\n return (charge * ELECTRON_CHARGE * ELECTRON_CHARGE) / (\n 4 * PI * VACUUM_PERMITTIVITY * dist)\n\n @staticmethod\n def monopole_esp_two_charges(charge1, charge2, dist1, dist2):\n \"\"\"\n Calculate the esp from a monopole with two charges, each a different distance from the point of measurement\n :return: monopole esp value\n \"\"\"\n return ((ELECTRON_CHARGE * ELECTRON_CHARGE) / (4 * PI * VACUUM_PERMITTIVITY)) * (\n charge1 / dist1 + charge2 / dist2)\n\n @staticmethod\n def monopole_esp_three_charges(charge1, charge2, charge3, dist1, dist2, dist3):\n \"\"\"\n Calculate the esp from a monopole with three charges, each a different distance from the point of measurement\n :return: monopole esp value\n \"\"\"\n return ((ELECTRON_CHARGE * ELECTRON_CHARGE) / (4 * PI * VACUUM_PERMITTIVITY)) * (\n charge1 / dist1 + charge2 / dist2 + charge3 / dist3)\n\n @staticmethod\n def dipole_esp(dist_vector, dipole_moment, dist):\n \"\"\"\n Calculate the esp from a dipole at a given sample point.\n :param dist_vector: atom_coords - sample_coords\n :param dipole_moment: dipole moment xyz components from Chargemol output\n :param dist: distance from sample_coords to atom_coords\n (provided as argument to prevent repeated calculation)\n :return: dipole esp value\n \"\"\"\n return (dipole_moment * ELECTRON_CHARGE * ELECTRON_CHARGE).dot(dist_vector) / (\n 4 * PI * VACUUM_PERMITTIVITY * dist ** 3)\n\n @staticmethod\n def quadrupole_moment_tensor(q_xy, q_xz, q_yz, q_x2_y2, q_3z2_r2):\n \"\"\"\n :params: quadrupole moment components from Chargemol output\n :return: quadrupole moment tensor, M\n \"\"\"\n return np.array([\n [q_x2_y2 / 2 - q_3z2_r2 / 6, q_xy, q_xz],\n [q_xy, -q_x2_y2 / 2 - q_3z2_r2 / 6, q_yz],\n [q_xz, q_yz, q_3z2_r2 / 3]\n ])\n\n @staticmethod\n def quadrupole_esp(dist_vector, m_tensor, dist):\n \"\"\"\n Calculate the esp from a quadrupole at a given distance\n :param dist_vector: atom_coords - sample_coords\n :param m_tensor: quadrupole moment tensor calculated from Chargemol output\n :param dist: distance from sample_coords to atom_coords\n (provided as argument to prevent repeated calculation)\n :return: quadrupole esp value\n \"\"\"\n return (3 * ELECTRON_CHARGE * ELECTRON_CHARGE * dist_vector.dot(m_tensor * (BOHR_TO_ANGS ** 2)).dot(\n dist_vector)) / (8 * PI * VACUUM_PERMITTIVITY * dist ** 5)\n\n @lru_cache(maxsize=None)\n def generate_sample_points_relative(self, vdw_radius):\n \"\"\"\n Generate evenly distributed points in a series of shells around the point (0, 0, 0)\n This uses fibonacci spirals to produce an even spacing of points on a sphere.\n\n radius of points are between 1.4-2.0x the vdW radius\n :return: list of numpy arrays where each array is the xyz coordinates of a sample point.\n \"\"\"\n\n min_points_per_shell = 32\n shells = 5\n phi = PI * (3.0 - np.sqrt(5.0))\n\n relative_sample_points = []\n for shell in range(shells):\n shell += 1\n points_in_shell = min_points_per_shell * shell * shell\n # 1.4-2.0x the vdw_radius\n shell_radius = (1.4 + ((2.0 - 1.4) / shells) * shell) * vdw_radius\n\n for i in range(points_in_shell):\n y = 1 - (i / (points_in_shell - 1)) * 2\n y_rad = np.sqrt(1 - y * y) * shell_radius\n y *= shell_radius\n\n theta = i * phi\n\n x = np.cos(theta) * y_rad\n z = np.sin(theta) * y_rad\n\n relative_sample_points.append(np.array([x, y, z]))\n\n return relative_sample_points\n\n def generate_sample_points_atom(self, atom_index):\n \"\"\"\n * Get the vdw radius of the atom which is being analysed\n * Using the relative sample points generated from generate_sample_points_relative():\n * Offset all of the points by the position of the atom coords\n :param atom_index: index of the atom around which a v-site will be fit\n :return: list of numpy arrays where each array is the xyz coordinates of a sample point.\n \"\"\"\n\n atom = self.molecule.atoms[atom_index]\n atom_coords = self.coords[atom_index]\n vdw_radius = self.vdw_radii[atom.atomic_symbol]\n\n sample_points = self.generate_sample_points_relative(vdw_radius)\n for point in sample_points:\n point += atom_coords\n\n return sample_points\n\n def generate_esp_atom(self, atom_index):\n \"\"\"\n Using the multipole expansion, calculate the esp at each sample point around an atom.\n :param atom_index: The index of the atom being analysed.\n :return: Ordered list of esp values at each sample point around the atom.\n \"\"\"\n\n atom_coords = self.coords[atom_index]\n\n charge = self.ddec_data[atom_index].charge\n dip_data = self.dipole_moment_data[atom_index]\n dipole_moment = np.array([*dip_data.values()]) * BOHR_TO_ANGS\n\n quad_data = self.quadrupole_moment_data[atom_index]\n\n no_site_esps = []\n for point in self.sample_points:\n dist = Charges.xyz_distance(point, atom_coords)\n dist_vector = point - atom_coords\n\n mono_esp = Charges.monopole_esp_one_charge(charge, dist)\n dipo_esp = Charges.dipole_esp(dist_vector, dipole_moment, dist)\n\n m_tensor = Charges.quadrupole_moment_tensor(*quad_data.values())\n quad_esp = Charges.quadrupole_esp(dist_vector, m_tensor, dist)\n\n v_total = (mono_esp + dipo_esp + quad_esp) * M_TO_ANGS * J_TO_KCAL_P_MOL\n no_site_esps.append(v_total)\n\n return no_site_esps\n\n def generate_atom_mono_esp_two_charges(self, atom_index, site_charge, site_coords):\n \"\"\"\n With a virtual site, calculate the monopole esp at each sample point around an atom.\n :param atom_index: The index of the atom being analysed.\n :param site_charge: The charge of the virtual site.\n :param site_coords: numpy array of the xyz position of the virtual site.\n :return: Ordered list of esp values at each sample point around the atom.\n \"\"\"\n\n atom_coords = self.coords[atom_index]\n # New charge of the atom, having removed the v-site's charge.\n atom_charge = self.ddec_data[atom_index].charge - site_charge\n\n v_site_esps = []\n for point in self.sample_points:\n dist = Charges.xyz_distance(point, atom_coords)\n site_dist = Charges.xyz_distance(point, site_coords)\n\n mono_esp = Charges.monopole_esp_two_charges(atom_charge, site_charge, dist, site_dist)\n v_site_esps.append(mono_esp * M_TO_ANGS * J_TO_KCAL_P_MOL)\n\n return v_site_esps\n\n def generate_atom_mono_esp_three_charges(self, atom_index, q_a, q_b, site_a_coords, site_b_coords):\n \"\"\"\n Calculate the esp at each sample point when two virtual sites are placed around an atom.\n :param atom_index: The index of the atom being analysed.\n :param q_a: charge of v-site a\n :param q_b: charge of v-site b\n :param site_a_coords: coords of v-site a\n :param site_b_coords: coords of v-site b\n :return: ordered list of esp values at each sample point\n \"\"\"\n\n atom_coords = self.coords[atom_index]\n atom_charge = self.ddec_data[atom_index].charge - (q_a + q_b)\n\n v_site_esps = []\n for point in self.sample_points:\n dist = Charges.xyz_distance(point, atom_coords)\n site_a_dist = Charges.xyz_distance(point, site_a_coords)\n site_b_dist = Charges.xyz_distance(point, site_b_coords)\n\n mono_esp = Charges.monopole_esp_three_charges(atom_charge, q_a, q_b, dist, site_a_dist, site_b_dist)\n v_site_esps.append(mono_esp * M_TO_ANGS * J_TO_KCAL_P_MOL)\n\n return v_site_esps\n\n def get_vector_from_coords(self, atom_index, n_sites=1, alt=False):\n \"\"\"\n Given the coords of the atom which will have a v-site and its neighbouring atom(s) coords,\n calculate the vector along which the virtual site will sit.\n :param atom_index: The index of the atom being analysed.\n :param n_sites: The number of virtual sites being placed around the atom.\n :param alt: When placing two sites on an atom with two bonds, there are two placements.\n Is this the usual placement, or the alternative (rotated 90 degrees around the bisecting vector).\n :return Vector(s) along which the v-site will sit. (np array)\n \"\"\"\n\n atom = self.molecule.atoms[atom_index]\n atom_coords = self.coords[atom_index]\n\n # e.g. halogens\n if len(atom.bonds) == 1:\n bonded_index = atom.bonds[0] # [0] is used since bonds is a one item list\n bonded_coords = self.coords[bonded_index]\n r_ab = atom_coords - bonded_coords\n if n_sites == 1:\n return r_ab\n return r_ab, r_ab\n\n # e.g. oxygen\n if len(atom.bonds) == 2:\n bonded_index_b, bonded_index_c = atom.bonds\n bonded_coords_b = self.coords[bonded_index_b]\n bonded_coords_c = self.coords[bonded_index_c]\n r_ab = atom_coords - bonded_coords_b\n r_ac = atom_coords - bonded_coords_c\n if n_sites == 1:\n return r_ab + r_ac\n if alt:\n return (r_ab + r_ac), np.cross(r_ab, r_ac)\n return (r_ab + r_ac), np.cross((r_ab + r_ac), np.cross(r_ab, r_ac))\n\n # e.g. nitrogen\n if len(atom.bonds) == 3:\n bonded_index_b, bonded_index_c, bonded_index_d = atom.bonds\n bonded_coords_b = self.coords[bonded_index_b]\n bonded_coords_c = self.coords[bonded_index_c]\n bonded_coords_d = self.coords[bonded_index_d]\n r_vec = np.cross((bonded_coords_b - bonded_coords_c), (bonded_coords_d - bonded_coords_c))\n if n_sites == 1:\n return r_vec\n else:\n if atom.atomic_symbol == 'N':\n h_s = []\n for atom_index in atom.bonds:\n if self.molecule.atoms[atom_index].atomic_symbol == 'H':\n h_s.append(atom_index)\n # Special case (amine group); position is slightly different\n if len(h_s) == 2:\n h_a_coords = self.coords[h_s[0]]\n h_b_coords = self.coords[h_s[1]]\n r_ha = atom_coords - h_a_coords\n r_hb = atom_coords - h_b_coords\n\n return r_vec, r_ha + r_hb\n return r_vec, r_vec\n\n def esp_from_lambda_and_charge(self, atom_index, q, lam, vec):\n \"\"\"\n Place a v-site at the correct position along the vector by scaling according to the lambda\n calculate the esp from the atom and the v-site.\n :param atom_index: index of the atom with a virtual site to be fit to\n :param q: charge of the virtual site\n :param lam: scaling of the vector along which the v-site sits\n :param vec: the vector along which the v-site sits\n :return: Ordered list of esp values at each sample point\n \"\"\"\n\n # This is the current position of the v-site (moved by the fit() method)\n site_coords = (vec * lam) + self.coords[atom_index]\n return self.generate_atom_mono_esp_two_charges(atom_index, q, site_coords)\n\n def sites_coords_from_vecs_and_lams(self, atom_index, lam_a, lam_b, vec_a, vec_b):\n \"\"\"\n Get the two virtual site coordinates from the vectors they sit along and the atom they are attached to.\n :param atom_index: The index of the atom being analysed.\n :param lam_a: scale factor for vec_a\n :param lam_b: scale factor for vec_b\n :param vec_a: vector deciding virtual site position\n :param vec_b: vector deciding virtual site position\n :return: tuple of np arrays which are the xyz coordinates of the v-sites\n \"\"\"\n\n if len(self.molecule.atoms[atom_index].bonds) == 2:\n site_a_coords = (vec_a * lam_a) + (vec_b * lam_b) + self.coords[atom_index]\n site_b_coords = (vec_a * lam_a) - (vec_b * lam_b) + self.coords[atom_index]\n else:\n site_a_coords = (vec_a * lam_a) + self.coords[atom_index]\n site_b_coords = (vec_b * lam_b) + self.coords[atom_index]\n\n return site_a_coords, site_b_coords\n\n def esp_from_lambdas_and_charges(self, atom_index, q_a, q_b, lam_a, lam_b, vec_a, vec_b):\n \"\"\"\n Place v-sites at the correct positions along the vectors by scaling according to the lambdas\n calculate the esp from the atom and the v-sites.\n :param atom_index: The index of the atom being analysed.\n :param q_a: charge of v-site a\n :param q_b: charge of v-site b\n :param lam_a: scale factor for vec_a\n :param lam_b: scale factor for vec_b\n :param vec_a: vector deciding virtual site position\n :param vec_b: vector deciding virtual site position\n :return: Ordered list of esp values at each sample point\n \"\"\"\n\n site_a_coords, site_b_coords = self.sites_coords_from_vecs_and_lams(atom_index, lam_a, lam_b, vec_a, vec_b)\n\n return self.generate_atom_mono_esp_three_charges(atom_index, q_a, q_b, site_a_coords, site_b_coords)\n\n def fit(self, atom_index, max_err=1.005):\n \"\"\"\n * Take the atom which will have a v-site fit around it\n * Calculate all possible vectors depending on 1 site, 2 site, rot by 90 deg etc\n * Fit\n * Store all v-site coords (one site, two sites)\n * Which fit had lowest error?\n :param max_err: If the addition of a v-site only reduces the error by a factor of max_err, ignore it.\n :param atom_index: The index of the atom being analysed.\n \"\"\"\n\n def one_site_objective_function(q_lam, vec):\n site_esps = self.esp_from_lambda_and_charge(atom_index, *q_lam, vec)\n error = sum(abs(no_site_esp - site_esp)\n for no_site_esp, site_esp in zip(self.no_site_esps, site_esps))\n return error\n\n def two_sites_objective_function(q_q_lam_lam, vec_a, vec_b):\n site_esps = self.esp_from_lambdas_and_charges(atom_index, *q_q_lam_lam, vec_a, vec_b)\n error = sum(abs(no_site_esp - site_esp)\n for no_site_esp, site_esp in zip(self.no_site_esps, site_esps))\n return error\n\n bounds = ((-1.0, 1.0), (-1.0, 1.0), (0.01, 0.5), (0.01, 0.5))\n n_sample_points = len(self.no_site_esps)\n\n # No site\n vec = self.get_vector_from_coords(atom_index, n_sites=1)\n no_site_error = one_site_objective_function((0, 1), vec)\n self.site_errors[0] = no_site_error / n_sample_points\n\n # One site\n one_site_fit = minimize(one_site_objective_function, np.array([0, 1]), args=vec, bounds=bounds[1:3])\n self.site_errors[1] = one_site_fit.fun / n_sample_points\n q, lam = one_site_fit.x\n one_site_coords = [((vec * lam) + self.coords[atom_index], q, atom_index)]\n self.one_site_coords = one_site_coords\n\n # Two sites (first orientation)\n vec_a, vec_b = self.get_vector_from_coords(atom_index, n_sites=2)\n two_site_fit = minimize(two_sites_objective_function, np.array([0, 0, 1, 1]), args=(vec_a, vec_b),\n bounds=bounds)\n self.site_errors[2] = two_site_fit.fun / n_sample_points\n q_a, q_b, lam_a, lam_b = two_site_fit.x\n site_a_coords, site_b_coords = self.sites_coords_from_vecs_and_lams(atom_index, lam_a, lam_b, vec_a, vec_b)\n two_site_coords = [(site_a_coords, q_a, atom_index), (site_b_coords, q_b, atom_index)]\n self.two_site_coords = two_site_coords\n\n # Two sites (alternative orientation)\n if len(self.molecule.atoms[atom_index].bonds) == 2:\n vec_a, vec_b = self.get_vector_from_coords(atom_index, n_sites=2, alt=True)\n alt_two_site_fit = minimize(two_sites_objective_function, np.array([0, 0, 1, 1]), args=(vec_a, vec_b),\n bounds=bounds)\n self.site_errors[2] = alt_two_site_fit.fun / n_sample_points\n q_a, q_b, lam_a, lam_b = alt_two_site_fit.x\n site_a_coords, site_b_coords = self.sites_coords_from_vecs_and_lams(atom_index, lam_a, lam_b, vec_a, vec_b)\n alt_two_site_coords = [(site_a_coords, q_a, atom_index), (site_b_coords, q_b, atom_index)]\n self.two_site_coords = alt_two_site_coords\n\n if self.site_errors[0] < min(self.site_errors[1] * max_err, self.site_errors[2] * max_err):\n print('No virtual site placement has reduced the error significantly.')\n elif self.site_errors[1] < self.site_errors[2] * max_err:\n print('The addition of one virtual site was found to be best.')\n self.v_sites_coords.extend(self.one_site_coords)\n else:\n print('The addition of two virtual sites was found to be best.')\n self.v_sites_coords.extend(self.two_site_coords)\n\n print(\n f'Errors (kcal/mol):\\n'\n f'No Site One Site Two Sites\\n'\n f'{self.site_errors[0]:.4f} {self.site_errors[1]:.4f} {self.site_errors[2]:.4f}'\n )\n\n def plot(self):\n \"\"\"\n Figure with three subplots.\n All plots show the atoms and bonds as balls and sticks; virtual sites are x's; sample points are dots.\n * Plot showing the positions of the sample points.\n * Plot showing the position of a single virtual site.\n * Plot showing the positions of two virtual sites.\n Errors are included to show the impact of virtual site placements.\n \"\"\"\n\n fig = plt.figure(figsize=plt.figaspect(0.33), tight_layout=True)\n # fig.suptitle('Virtual Site Placements', fontsize=20)\n\n norm = plt.Normalize(vmin=-1.0, vmax=1.0)\n cmap = 'cool'\n\n samp_plt = fig.add_subplot(1, 3, 1, projection='3d')\n one_plt = fig.add_subplot(1, 3, 2, projection='3d')\n two_plt = fig.add_subplot(1, 3, 3, projection='3d')\n\n plots = [samp_plt, one_plt, two_plt]\n # Add atom positions to all subplots\n for plot in plots:\n plot.scatter(\n xs=[i[0][0] for i in self.atom_points],\n ys=[i[0][1] for i in self.atom_points],\n zs=[i[0][2] for i in self.atom_points],\n c=[i[1] for i in self.atom_points],\n marker='o',\n s=200,\n cmap=cmap,\n norm=norm,\n )\n\n # Plot the bonds as connecting lines\n for bond in self.molecule.topology.edges:\n plot.plot(\n xs=[self.coords[bond[0]][0], self.coords[bond[1]][0]],\n ys=[self.coords[bond[0]][1], self.coords[bond[1]][1]],\n zs=[self.coords[bond[0]][2], self.coords[bond[1]][2]],\n c='darkslategrey',\n alpha=0.5\n )\n\n # Left subplot contains the sample point positions\n samp_plt.scatter(\n xs=[i[0] for i in self.sample_points],\n ys=[i[1] for i in self.sample_points],\n zs=[i[2] for i in self.sample_points],\n c='darkslategrey',\n marker='o',\n s=5\n )\n samp_plt.title.set_text(f'Sample Points Positions\\nError: {self.site_errors[0]: .5}')\n\n # Centre subplot contains the single v-site\n one_plt.scatter(\n xs=[i[0][0] for i in self.one_site_coords],\n ys=[i[0][1] for i in self.one_site_coords],\n zs=[i[0][2] for i in self.one_site_coords],\n c=[i[1] for i in self.one_site_coords],\n marker='x',\n s=200,\n cmap=cmap,\n norm=norm,\n )\n one_plt.title.set_text(f'One Site Position\\nError: {self.site_errors[1]: .5}')\n\n # Right subplot contains the two v-sites\n two_plt.scatter(\n xs=[i[0][0] for i in self.two_site_coords],\n ys=[i[0][1] for i in self.two_site_coords],\n zs=[i[0][2] for i in self.two_site_coords],\n c=[i[1] for i in self.two_site_coords],\n marker='x',\n s=200,\n cmap=cmap,\n norm=norm,\n )\n error = self.site_errors[2]\n two_plt.title.set_text(f'Two Sites Positions\\nError: {error: .5}')\n\n sm = ScalarMappable(norm=norm, cmap=cmap)\n sm.set_array([])\n cbar = fig.colorbar(sm)\n cbar.ax.set_title('charge')\n\n plt.tight_layout()\n plt.savefig(f'{self.molecule.name}_virtual_sites.png')\n\n def write_xyz(self):\n \"\"\"\n Write an xyz file containing the atom and virtual site coordinates.\n \"\"\"\n\n with open(f'{self.molecule.name}.xyz', 'w+') as xyz_file:\n xyz_file.write(\n f'{len(self.molecule.atoms) + len(self.v_sites_coords)}\\n'\n f'xyz file generated with QUBEKit. '\n f'Error with v-site: {min(self.site_errors.values()): .5f} kcal/mol\\n'\n )\n for i, atom in enumerate(self.coords):\n xyz_file.write(\n f'{self.molecule.atoms[i].atomic_symbol} {atom[0]: .10f} {atom[1]: .10f} {atom[2]: .10f}'\n f' {self.molecule.atoms[i].partial_charge}\\n')\n\n for site in self.v_sites_coords:\n if site[2] == i:\n xyz_file.write(\n f'X {site[0][0]: .10f} {site[0][1]: .10f} {site[0][2]: .10f} {site[1]: .10f}\\n')\n","sub_path":"QUBEKit/virtual_sites.py","file_name":"virtual_sites.py","file_ext":"py","file_size_in_byte":26319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"107784781","text":"# argp@census-labs.com\r\n\r\nimport idautils\r\nimport idaapi\r\nimport ida_idaapi\r\nimport ida_search\r\nimport ida_funcs\r\nimport ida_segment\r\nimport ida_bytes\r\nimport ida_idp\r\nimport idc\r\nimport struct\r\n\r\ntrue = True\r\nfalse = False\r\nnone = None\r\n\r\nkp_flag = false\r\n\r\ntry:\r\n import keypatch\r\n kp_flag = true\r\nexcept:\r\n pass\r\n\r\nprologues = [\"7F 23 03 D5\", \"BD A9\", \"BF A9\"]\r\n\r\ndef find_panic(base_ea):\r\n pk_ea = ida_search.find_text(base_ea, 1, 1, \"double panic in \", ida_search.SEARCH_DOWN)\r\n\r\n if pk_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(pk_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _panic = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_panic\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_image4_load(base_ea):\r\n ea_list = ida_search.find_imm(base_ea, ida_search.SEARCH_DOWN, 0x4D650000)\r\n\r\n if ea_list[0] != ida_idaapi.BADADDR:\r\n func_ea = ida_funcs.get_func(ea_list[0]).start_ea\r\n print(\"\\t[+] _image4_load = 0x%x\" % (func_ea))\r\n idc.set_name(func_ea, \"_image4_load\", idc.SN_CHECK)\r\n return func_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_img4decodeinit(base_ea):\r\n ea_list = ida_search.find_imm(base_ea, ida_search.SEARCH_DOWN, 0x494D0000)\r\n\r\n if ea_list[0] != ida_idaapi.BADADDR:\r\n func_ea = ida_funcs.get_func(ea_list[0]).start_ea\r\n ea_func_list = list(idautils.XrefsTo(func_ea))\r\n\r\n if ea_func_list[0].frm != ida_idaapi.BADADDR:\r\n i4d_ea = ida_funcs.get_func(ea_func_list[0].frm).start_ea\r\n print(\"\\t[+] _Img4DecodeInit = 0x%x\" % (i4d_ea))\r\n idc.set_name(i4d_ea, \"_Img4DecodeInit\", idc.SN_CHECK)\r\n return i4d_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_aes_crypto_cmd(base_ea):\r\n aes_ea = ida_search.find_text(base_ea, 1, 1, \"aes_crypto_cmd\", ida_search.SEARCH_DOWN)\r\n\r\n if aes_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(aes_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _aes_crypto_cmd = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_aes_crypto_cmd\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_main_task(base_ea):\r\n du_ea = ida_search.find_text(base_ea, 1, 1, \"debug-uarts\", ida_search.SEARCH_DOWN)\r\n\r\n if du_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(du_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _main_task = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_main_task\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_boot_check_panic(base_ea, base_end_ea):\r\n seq_ea = ida_search.find_binary(base_ea, base_end_ea, \"1F ?? 03 71\", 16, ida_search.SEARCH_DOWN)\r\n\r\n if seq_ea != ida_idaapi.BADADDR:\r\n func = idaapi.get_func(seq_ea)\r\n print(\"\\t[+] _boot_check_panic = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_boot_check_panic\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_update_device_tree(base_ea):\r\n udt_ea = ida_search.find_text(base_ea, 1, 1, \"development-cert\", ida_search.SEARCH_DOWN)\r\n\r\n if udt_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(udt_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _UpdateDeviceTree = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_UpdateDeviceTree\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_macho_valid(base_ea):\r\n ea_list = ida_search.find_imm(base_ea, ida_search.SEARCH_DOWN, 0xFACF)\r\n\r\n if ea_list[0] == ida_idaapi.BADADDR:\r\n ea_list = ida_search.find_imm(base_ea, ida_search.SEARCH_DOWN, 0xFEEDFACF)\r\n \r\n if ea_list[0] != ida_idaapi.BADADDR:\r\n func_ea = ida_funcs.get_func(ea_list[0]).start_ea\r\n print(\"\\t[+] _macho_valid = 0x%x\" % (func_ea))\r\n idc.set_name(func_ea, \"_macho_valid\", idc.SN_CHECK)\r\n return func_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_loaded_kernelcache(ea):\r\n ea_list = list(idautils.XrefsTo(ea))\r\n\r\n if ea_list[0].frm != ida_idaapi.BADADDR:\r\n func_ea = ida_funcs.get_func(ea_list[0].frm).start_ea\r\n print(\"\\t[+] _loaded_kernelcache = 0x%x\" % (func_ea))\r\n idc.set_name(func_ea, \"_loaded_kernelcache\", idc.SN_CHECK)\r\n return func_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_load_kernelcache(ea):\r\n ea_list = list(idautils.XrefsTo(ea))\r\n\r\n if ea_list[0].frm != ida_idaapi.BADADDR:\r\n func_ea = ida_funcs.get_func(ea_list[0].frm).start_ea\r\n print(\"\\t[+] _load_kernelcache = 0x%x\" % (func_ea))\r\n idc.set_name(func_ea, \"_load_kernelcache\", idc.SN_CHECK)\r\n return func_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_do_go(base_ea):\r\n str_ea = ida_search.find_text(base_ea, 1, 1, \"Memory image not valid\", ida_search.SEARCH_DOWN)\r\n\r\n if str_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(str_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _do_go = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_do_go\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_pmgr_binning_mode_get_value(base_ea):\r\n str_ea = ida_search.find_text(base_ea, 1, 1, \"Invalid low\", ida_search.SEARCH_DOWN)\r\n\r\n if str_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(str_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _pmgr_binning_mode_get_value = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_pmgr_binning_mode_get_value\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_do_printf(base_ea):\r\n str_ea = ida_search.find_text(base_ea, 1, 1, \"\", ida_search.SEARCH_DOWN)\r\n\r\n if str_ea != ida_idaapi.BADADDR:\r\n for xref in idautils.XrefsTo(str_ea):\r\n func = idaapi.get_func(xref.frm)\r\n print(\"\\t[+] _do_printf = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_do_printf\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_image4_get_partial(base_ea):\r\n str_ea = idc.get_name_ea_simple(\"aImg4\")\r\n\r\n if str_ea != ida_idaapi.BADADDR:\r\n aimg4_ea = list(idautils.XrefsTo(str_ea))[0].frm\r\n\r\n if aimg4_ea == ida_idaapi.BADADDR:\r\n return ida_idaapi.BADADDR\r\n\r\n func = idaapi.get_func(aimg4_ea)\r\n print(\"\\t[+] _image4_get_partial = 0x%x\" % (func.start_ea))\r\n idc.set_name(func.start_ea, \"_image4_get_partial\", idc.SN_CHECK)\r\n return func.start_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_putchar(base_ea):\r\n str_ea = idc.get_name_ea_simple(\"aPanic\")\r\n\r\n if str_ea != ida_idaapi.BADADDR:\r\n apanic_ea = list(idautils.XrefsTo(str_ea))[0].frm\r\n\r\n if apanic_ea == ida_idaapi.BADADDR:\r\n return ida_idaapi.BADADDR\r\n\r\n opnd0 = idc.print_operand(apanic_ea + 8, 0)\r\n ins_str = idc.print_insn_mnem(apanic_ea + 8)\r\n\r\n if ins_str == \"BL\":\r\n func_ea = idc.get_name_ea_simple(opnd0)\r\n ea = func_ea\r\n\r\n while ea != ida_idaapi.BADADDR:\r\n ins_str = idc.print_insn_mnem(ea)\r\n \r\n if ins_str == \"ADD\":\r\n opnd2 = idc.print_operand(ea, 2)\r\n \r\n if opnd2 == \"#1\":\r\n ins_ea = ea - 4\r\n opnd0 = idc.print_operand(ins_ea, 0)\r\n ins_str = idc.print_insn_mnem(ins_ea)\r\n\r\n if ins_str == \"BL\":\r\n pc_ea = idc.get_name_ea_simple(opnd0)\r\n print(\"\\t[+] _putchar = 0x%x\" % (pc_ea))\r\n idc.set_name(pc_ea, \"_putchar\", idc.SN_CHECK)\r\n return pc_ea\r\n\r\n ea = ea + 4\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_macho_load(base_ea):\r\n pz_ea = idc.get_name_ea_simple(\"aPagezero\")\r\n\r\n if pz_ea != ida_idaapi.BADADDR:\r\n if len(list(idautils.XrefsTo(pz_ea))) != 3:\r\n return ida_idaapi.BADADDR\r\n\r\n func1_ea = idaapi.get_func(list(idautils.XrefsTo(pz_ea))[0].frm).start_ea\r\n func2_ea = idaapi.get_func(list(idautils.XrefsTo(pz_ea))[1].frm).start_ea\r\n func3_ea = idaapi.get_func(list(idautils.XrefsTo(pz_ea))[2].frm).start_ea\r\n\r\n if func2_ea != func3_ea:\r\n return ida_idaapi.BADADDR\r\n\r\n if func1_ea != func2_ea:\r\n print(\"\\t[+] _macho_load = 0x%x\" % (func2_ea))\r\n idc.set_name(func2_ea, \"_macho_load\", idc.SN_CHECK)\r\n return func2_ea\r\n\r\n return ida_idaapi.BADADDR\r\n\r\ndef find_interesting(base_ea, base_end):\r\n mv_ea = find_macho_valid(base_ea)\r\n\r\n if mv_ea != ida_idaapi.BADADDR:\r\n ldk_ea = find_loaded_kernelcache(mv_ea)\r\n lk_ea = find_load_kernelcache(ldk_ea)\r\n \r\n pk_ea = find_panic(base_ea)\r\n go_ea = find_do_go(base_ea)\r\n pr_ea = find_do_printf(base_ea)\r\n i4l_ea = find_image4_load(base_ea)\r\n i4d_ea = find_img4decodeinit(base_ea)\r\n aes_ea = find_aes_crypto_cmd(base_ea)\r\n udt_ea = find_update_device_tree(base_ea)\r\n ml_ea = find_macho_load(base_ea)\r\n pgv_ea = find_pmgr_binning_mode_get_value(base_ea)\r\n i4p_ea = find_image4_get_partial(base_ea)\r\n mt_ea = find_main_task(base_ea)\r\n bc_ea = find_boot_check_panic(base_ea, base_end)\r\n\r\n pc_ea = find_putchar(base_ea)\r\n\r\n if pc_ea != ida_idaapi.BADADDR and mv_ea == ida_idaapi.BADADDR:\r\n # this is a SecureROM image\r\n segm = ida_segment.getseg(base_ea)\r\n\r\n if segm:\r\n idaapi.set_segm_name(segm, \"SecureROM\", 0)\r\n print(\"[+] Identified as a SecureROM image\")\r\n\r\ndef accept_file(fd, fname):\r\n version = 0\r\n ret = 0\r\n\r\n if type(fname) == str:\r\n fd.seek(0x280)\r\n ver_str = fd.read(0x20)\r\n\r\n try:\r\n # Python 3.x.\r\n label = \"\".join(map(chr, ver_str[:5]))\r\n except TypeError:\r\n # Python 2.x.\r\n label = ver_str[:5]\r\n\r\n if \"iBoot\" == label:\r\n version = ver_str[6:] # for later\r\n ret = {\"format\" : \"iBoot (AArch64)\", \"processor\" : \"arm\"}\r\n\r\n return ret\r\n\r\ndef load_file(fd, neflags, format):\r\n global prologues\r\n size = 0\r\n base_addr = 0\r\n ea = 0\r\n nfunc = 0\r\n\r\n idaapi.set_processor_type(\"arm\", ida_idp.SETPROC_LOADER_NON_FATAL)\r\n idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT\r\n \r\n if (neflags & idaapi.NEF_RELOAD) != 0:\r\n return 1\r\n\r\n fd.seek(0, idaapi.SEEK_END)\r\n size = fd.tell()\r\n\r\n segm = idaapi.segment_t()\r\n segm.bitness = 2 # 64-bit\r\n segm.start_ea = 0\r\n segm.end_ea = size\r\n idaapi.add_segm_ex(segm, \"iBoot\", \"CODE\", idaapi.ADDSEG_OR_DIE)\r\n\r\n fd.seek(0)\r\n fd.file2base(0, 0, size, false)\r\n\r\n idaapi.add_entry(0, 0, \"start\", 1)\r\n ida_funcs.add_func(ea)\r\n\r\n print(\"[+] Marked as code\")\r\n\r\n # heuristic\r\n while(true):\r\n mnemonic = idc.print_insn_mnem(ea)\r\n \r\n if \"LDR\" in mnemonic:\r\n base_str = idc.print_operand(ea, 1)\r\n base_addr = int(base_str.split(\"=\")[1], 16)\r\n \r\n break\r\n\r\n ea += 4\r\n\r\n print(\"[+] Rebasing to address 0x%x\" % (base_addr))\r\n idaapi.rebase_program(base_addr, idc.MSF_NOFIX)\r\n\r\n segment_start = base_addr\r\n segment_end = idc.get_segm_attr(segment_start, idc.SEGATTR_END)\r\n\r\n ea = segment_start\r\n\r\n print(\"[+] Searching and defining functions\")\r\n\r\n for prologue in prologues:\r\n while ea != ida_idaapi.BADADDR:\r\n ea = ida_search.find_binary(ea, segment_end, prologue, 16, ida_search.SEARCH_DOWN)\r\n \r\n if ea != ida_idaapi.BADADDR:\r\n if len(prologue) < 8:\r\n ea = ea - 2\r\n\r\n if (ea % 4) == 0 and ida_bytes.get_full_flags(ea) < 0x200:\r\n # print(\"[+] Defining a function at 0x%x\" % (ea))\r\n ida_funcs.add_func(ea)\r\n nfunc = nfunc + 1\r\n\r\n ea = ea + 4\r\n \r\n idc.plan_and_wait(segment_start, segment_end)\r\n\r\n print(\"[+] Identified %d new functions\" % (nfunc))\r\n\r\n print(\"[+] Looking for interesting functions\")\r\n find_interesting(segment_start, segment_end)\r\n\r\n return 1\r\n\r\n# EOF\r\n","sub_path":"iBoot64helper.py","file_name":"iBoot64helper.py","file_ext":"py","file_size_in_byte":12534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"218536659","text":"\"\"\"\r\n--- Day 1: Chronal Calibration ---\r\n\r\n\"\"\"\r\nfrom utils import load_input\r\n\r\n\r\ndef main():\r\n lines = load_input('https://pastebin.com/raw/ebDxSugK')\r\n print(part_one(lines))\r\n print(part_two(lines))\r\n\r\n\r\ndef part_one(iterable):\r\n return sum([int(change) for change in iterable])\r\n\r\n\r\ndef part_two(iterable):\r\n changes = [int(i) for i in iterable]\r\n\r\n frequencies = set()\r\n current_frequency = int()\r\n\r\n while True:\r\n for change in changes:\r\n current_frequency += change\r\n if current_frequency in frequencies:\r\n return current_frequency\r\n frequencies.add(current_frequency)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Advent of Code/2018/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"172379740","text":"import matplotlib.pyplot as plt\nfrom nltk.corpus import webtext, stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.probability import FreqDist\nfrom wordcloud import WordCloud\n\n\ndef main():\n print('*' * 80)\n\n # текст форума firefox\n firefox_words = webtext.words('firefox.txt')\n\n tokenizer = RegexpTokenizer(r'\\w+')\n\n # токены в нижнем регистре, без английских stop words\n firefox_tokens = [\n token.lower() for token in tokenizer.tokenize(\n webtext.raw('firefox.txt')\n ) if token not in stopwords.words('english')\n ]\n\n print('-' * 80)\n print(str.format(\n '[*] words count in firefox forum: {}', len(firefox_words)\n ))\n print(str.format('[*] firefox tokens count: {}', len(firefox_tokens)))\n\n print('-' * 80)\n\n # частотное распределение (frequency distribution) в форуме Firefox\n freq_dist = FreqDist(token for token in firefox_tokens)\n\n print(str.format('[*] the most frequency term: \"{}\"', freq_dist.max()))\n # print(str.format('[*] the most frequency term: \"{}\"', freq_dist.min()))\n\n print(str.format(\n '[*] frequency distribution for \"firefox\" word: {}',\n freq_dist.freq('firefox')\n ))\n\n # визуализация 10 наиболее частых токенов\n freq_dist.plot(10, title='Firefox top 10 tokens')\n\n print('-' * 80)\n # создаем экземпляр world cloud\n world_cloud = WordCloud()\n world_cloud_firefox = world_cloud.generate_from_frequencies(freq_dist)\n plt.imshow(world_cloud_firefox, interpolation='bilinear')\n plt.axis('off')\n\n # создаем .png файл\n plt.show()\n\n print('*' * 80)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"nltk_package/probability_module/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"267228971","text":"from flexget import plugin\n\nfrom .site_base import SiteBase\n\n\nclass NexusPHP(SiteBase):\n @staticmethod\n def build_sign_in_entry(entry, site_name, config, url, succeed_regex, base_url=None,\n wrong_regex=None):\n site_config = entry['site_config']\n if not isinstance(site_config, str):\n raise plugin.PluginError('{} site_config is not a String'.format(site_name))\n entry['url'] = url\n entry['succeed_regex'] = succeed_regex\n if base_url:\n entry['base_url'] = base_url\n if wrong_regex:\n entry['wrong_regex'] = wrong_regex\n headers = {\n 'cookie': site_config,\n 'user-agent': config.get('user-agent'),\n 'referer': base_url if base_url else url\n }\n entry['headers'] = headers\n\n def sign_in(self, entry, config):\n self.sign_in_by_get(entry, config)\n\n def get_message(self, entry, config):\n self.get_nexusphp_message(entry, config)\n","sub_path":"ptsites/nexusphp.py","file_name":"nexusphp.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"468148343","text":"import PIL.Image as img\nimport os\nimport shutil\nfrom tkinter import *\nimport tkinter.filedialog\n\n\ndef makeImg(oPath,fname):\n fname = fname[:-4]\n npcdat=\"E:/cqres-new/cqres/web_test/_out/assets/icon/neiguan/android/\"\n npcPng = \"E:/cqres-new/cqres/web_test/_out/assets/icon/neiguan/__out/android/\"\n if (os.path.exists(npcdat + fname)):\n print(\"\")\n else:\n os.makedirs(npcdat + fname)\n\n if (os.path.exists(npcPng + fname)):\n print(\"\")\n else:\n os.makedirs(npcPng + fname)\n\n if(os.path.exists(npcdat+\"idle.dat\")):\n os.remove(npcdat+\"idle.dat\")\n shutil.copy(oPath+\"/\"+fname+\".dat\", npcdat+fname+\"/idle.dat\")\n\n if (os.path.exists(npcPng + \"idle.png\")):\n os.remove(npcPng + \"idle.png\")\n shutil.copy(oPath + \"/\" + fname + \".png\", npcPng + fname + \"/idle.png\")\n\n\n\n\ndef xz():\n filename = tkinter.filedialog.askdirectory()\n sPath = filename+\"/\"\n lb.config(text=\"您选择的文件是:\" + sPath)\n dirList = os.listdir(sPath)\n for dirName in dirList:\n makeImg(sPath,dirName)\n lb.config(text=\"图片处理完毕\")\n\n\n\nroot = Tk()\nroot.title(\"拷贝资源\")\nroot.geometry('500x300')\n\nlb = Label(root,text = '点击按钮选择文件夹')\n# lb.place(x=20,y=100)\nlb.pack()\nbtn = Button(root,text=\"选择文件夹开始\",command=xz)\nbtn.place(x=200,y=200)\nroot.mainloop()","sub_path":"tool/CopyOutFile.py","file_name":"CopyOutFile.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"367236681","text":"import glob\nimport os\nimport re\nfrom multiprocessing import Process\nimport DiscoverApi\nfrom DiscoverDb import DiscoverDb\n\ndbPath = 'c:\\\\bin\\\\Discover\\\\database\\\\'\nfiles = [f for f in glob.glob(dbPath + \"**/*\", recursive=True)]\nwordRgx = r\"([A-Za-z0-9']+(\\b[\\,\\.?!])?)\"\ninfoRgx = r\"_{2,}\"\n\ndef processFile(filepath, lyricObjIndex):\n db = DiscoverDb()\n (_, headers) = DiscoverApi.requestAccessToken()\n with open(filepath, 'r') as f:\n song = { 'artist': '', 'name': '', 'lyrics': [] }\n for line in f:\n if re.match(infoRgx, line): # finished processing lyrics, now process song metadata\n _, name = [word.strip() for word in f.readline().split(' ')]\n _, artist = [word.strip() for word in f.readline().split(' ')]\n while (_ != \"Artist\"):\n _, artist = [word.strip() for word in f.readline().split(' ')]\n song['name'] = name\n song['artist'] = artist\n break\n else:\n for word in re.findall(wordRgx, line):\n song['lyrics'].append(word[0])\n f.close()\n name = song['name']\n artist = song['artist']\n lyrics = song['lyrics']\n spotifyId = DiscoverApi.searchSpotifyForSongId(headers, name, artist)\n if (spotifyId is not None):\n trackAttributes = DiscoverApi.getTrackAttributes(headers, spotifyId)\n db.storeLyricData(spotifyId, lyrics)\n db.storeSongData(spotifyId, name, artist, lyricObjIndex, 'lyrics-master')\n db.storeTrackData(trackAttributes)\n print(name, 'by', artist, 'stored')\n else:\n print(name, 'by', artist, 'could not be found on spotify.')\n db.shutdown()\n\nif __name__ == '__main__':\n lyricObjIndex = 0\n for file in files:\n if not os.path.isdir(file):\n lyricObjIndex += 1\n p = Process(target=processFile, args=(file, lyricObjIndex))\n p.start()\n p.join()","sub_path":"lyrics.py","file_name":"lyrics.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"636482020","text":"import matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nimport scipy.io as sio\r\nimport sys\r\n\r\n\r\nimport numpy as np\r\nfrom PyQt5.QtWidgets import QCalendarWidget, QFontDialog, QColorDialog, QTextEdit, QFileDialog, \\\r\n QCheckBox, QLabel,QComboBox,QPushButton, QGridLayout, QMainWindow, QWidget, QLineEdit, QMessageBox, QVBoxLayout,\\\r\n QHBoxLayout, QAction\r\nfrom PyQt5.QtCore import QCoreApplication, Qt\r\n\r\n\r\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5\r\nif is_pyqt5():\r\n from matplotlib.backends.backend_qt5agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nelse:\r\n from matplotlib.backends.backend_qt4agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nfrom matplotlib.figure import Figure\r\n\r\n\r\n\r\n\r\n#################GAGE 12/26/18#####################\r\n\r\nclass File:\r\n def __init__(self):\r\n #Open dialog window to select file path\r\n self.file_path = QFileDialog.getOpenFileName(None, \"Open File\", \"/home\", \"Matlab Files (*.mat)\")[0]\r\n if self.file_path != \"\":\r\n #Load .mat file from file path and store contents\r\n self.mat_contents = sio.loadmat(self.file_path)\r\n #Create a list of channel sets from .mat file contents\r\n self.ecog_SETS = list(self.mat_contents.keys())\r\n\r\nclass channel:\r\n def __init__(self, ch_select, set_select, File):\r\n #Create an array of y values based on the chosen channel collection and individual channel\r\n self.y = File.mat_contents.get(File.ecog_SETS[set_select])[:,ch_select]\r\n #Create an array of x values based on the length of y values\r\n self.x = range(0,len(self.y))\r\n def plot(self):\r\n plt.plot (self.x,self.y)\r\n def gap(self,y_gap):\r\n self.y = self.y + y_gap\r\n\r\nclass ApplicationWindow(QMainWindow):\r\n def __init__(self):\r\n QMainWindow.__init__(self)\r\n self.initUI()\r\n self.setWindowTitle(\"Graphing Application\")\r\n\r\n def initUI(self):\r\n centralwidget = QWidget()\r\n\r\n # create submenu option for later reference\r\n fileDiaglogue = QAction('&Open...', self)\r\n\r\n # create instance of menu bar\r\n mainMenu = self.menuBar()\r\n # create menu option for opening file\r\n fileMenu = mainMenu.addMenu('&File')\r\n # add submenu option to tool bar\r\n fileMenu.addAction(fileDiaglogue)\r\n # connect openFile method to submenu selection\r\n fileDiaglogue.triggered.connect(self.openFile)\r\n\r\n # create dropdown menu gui\r\n self.dropLabel = QLabel('Channel Set', self)\r\n self.comboBox = QComboBox(self)\r\n self.comboBox.currentIndexChanged.connect(self.checkSet)\r\n self.comboBox.currentIndexChanged.connect(self.updateBtns)\r\n\r\n # create y-gap textbox\r\n self.yLabel = QLabel('Y Axis Gap', self)\r\n self.textbox = QLineEdit(self)\r\n\r\n # create update button\r\n update_btn = QPushButton('Update', self)\r\n update_btn.clicked.connect(self.update)\r\n\r\n # instantiate main plot canvas\r\n plot_canvas = FigureCanvas(Figure(figsize=(5, 5)))\r\n\r\n # add toolbar to layout\r\n self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(plot_canvas, self))\r\n\r\n self._static_ax = plot_canvas.figure.subplots()\r\n # label graph axes\r\n xtext = self._static_ax.set_xlabel('my xdata') # returns a Text instance\r\n ytext = self._static_ax.set_ylabel('my ydata')\r\n\r\n #create grid for button layout\r\n self.grid = QGridLayout()\r\n # ensures no stretching occurs when maximizing/minimizing windows\r\n #self.grid.setSpacing(1)\r\n\r\n # assign grid position to each widget\r\n self.grid.addWidget(update_btn, 0, 1, 5, 10)\r\n self.grid.addWidget(self.yLabel, 1, 1)\r\n self.grid.addWidget(self.textbox, 1, 2)\r\n self.grid.addWidget(self.comboBox, 2, 2)\r\n self.grid.addWidget(self.dropLabel, 2, 1)\r\n\r\n # create grid for channel button layout\r\n self.gridButtons = QGridLayout()\r\n\r\n # create layout for the graph canvas\r\n canvasBox = QHBoxLayout()\r\n canvasBox.addWidget(plot_canvas)\r\n\r\n # create top layout\r\n topBox = QHBoxLayout()\r\n topBox.addLayout(canvasBox)\r\n topBox.addLayout(self.grid)\r\n\r\n # create main layout\r\n mainBox = QVBoxLayout()\r\n mainBox.addLayout(topBox)\r\n mainBox.addLayout(self.gridButtons)\r\n\r\n\r\n\r\n centralwidget.setLayout(mainBox)\r\n\r\n self.setCentralWidget(centralwidget)\r\n\r\n self.selected_SET = 0\r\n\r\n # method creates an instance of the File object and fills the dropdown menu with associated channel sets\r\n def openFile(self):\r\n self.file1 = File()\r\n # clear any pre-existing channel sets\r\n self.comboBox.clear()\r\n # check that a file has been chosen by the user\r\n if self.file1.file_path != \"\":\r\n #iterate through all sets and fill the dropdown with the name of each channel set\r\n for s in range(3, len(self.file1.ecog_SETS)):\r\n self.comboBox.addItem(self.file1.ecog_SETS[s])\r\n\r\n # method checks what channel set is currently selected and gets its index\r\n\r\n\r\n def checkSet(self):\r\n # iterate through all channel sets until it matches the currently selected channel set\r\n for s in range(3, len(self.file1.ecog_SETS)):\r\n if self.comboBox.currentText() == self.file1.ecog_SETS[s]:\r\n self.selected_SET = s\r\n\r\n # method creates buttons based on the number channels in the selected set\r\n def updateBtns(self):\r\n # determine the number of channels based on the number of y values in the selected set\r\n self.num_channels = len(self.file1.mat_contents.get(self.file1.ecog_SETS[self.selected_SET])[0, :])\r\n # create a array of checkboxes for later reference\r\n self.box_array = list()\r\n self.list_array = list()\r\n # determine the maximum number of rows based on the numbe\r\n # r of channels\r\n max_rows = np.ceil(self.num_channels / 10)\r\n numB = 0\r\n # for each row, determine if the row will be complete\r\n for i in range(1, max_rows.astype(int) + 1):\r\n if self.num_channels - i * 10 > 0:\r\n columns = 10\r\n else:\r\n columns = self.num_channels % 10\r\n\r\n # create a label for each row indicating the number of each button\r\n self.list_array.append(QLabel())\r\n self.list_array[i - 1].setText(str((i - 1) * 10) + '-' + str(((i - 1) * 10) + columns))\r\n self.gridButtons.addWidget(self.list_array[i - 1], i + 2, 1)\r\n\r\n for j in range(1, columns + 1):\r\n self.box_array.append(QCheckBox(self))\r\n self.gridButtons.addWidget(self.box_array[numB], i+2, j+1)\r\n numB += 1\r\n self.channels_array = list()\r\n for i in range(0, self.num_channels):\r\n self.channels_array.append(channel(i, self.selected_SET, self.file1))\r\n def checkBtns(self):\r\n # reinstantiate selected channels\r\n self.channels_selected = []\r\n # check which buttons and selected and add the respective channel to an array\r\n for b in range(0, len(self.box_array)):\r\n if self.box_array[b].checkState() == Qt.Checked:\r\n self.channels_selected.append(b)\r\n def updatePlot(self):\r\n # clear the axes before graphing selected channels\r\n self._static_ax.clear()\r\n # intantiate y_gap value for later use using the current textbox value\r\n y_gap = self.textbox.text()\r\n\r\n # check that user has entered a y gap value\r\n if y_gap == \"\":\r\n QMessageBox.about(self,\"Error\", \"Please enter a y-gap value.\")\r\n else:\r\n\r\n for j in range(0, len(self.channels_selected)):\r\n self.channels_array[self.channels_selected[j]].gap(float(y_gap) * j)\r\n self._static_ax.plot(self.channels_array[self.channels_selected[j]].x, self.channels_array[self.channels_selected[j]].y)\r\n\r\n self._static_ax.figure.canvas.draw()\r\n\r\n def update(self):\r\n # check if an instance of the File() object has been created\r\n try:\r\n self.test = self.file1\r\n # if no File() object exists instruct the user to select a file\r\n except:\r\n QMessageBox.about(self, \"Error\", \"Please load a .mat file.\")\r\n # call checkBtn() and updatePlot() method if file exists.\r\n else:\r\n self.checkBtns()\r\n self.updatePlot()\r\n\r\nif __name__ == \"__main__\":\r\n qapp = QtWidgets.QApplication(sys.argv)\r\n app = ApplicationWindow()\r\n app.show()\r\n qapp.exec_()\r\n","sub_path":"Graphing Application/Python Files/GraphingAppLayout_1-9-19.py","file_name":"GraphingAppLayout_1-9-19.py","file_ext":"py","file_size_in_byte":8792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"289950349","text":"#!/usr/bin/env python\n\nimport argparse\nimport json\n\nfrom video_utils import prepare_instagram_video\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Prepare arguments for an instagram video\")\n parser.add_argument(\n dest=\"path\",\n type=str,\n help=\"the path to the video\",\n )\n\n args = parser.parse_args()\n\n res = prepare_instagram_video(args.path)\n print(json.dumps(res))\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/prepare_instagram_video.py","file_name":"prepare_instagram_video.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"130665181","text":"'''Passando uma lista para uma função'''\n\ndef greet_users(names):\n\t'''Exibe uma suadaçao simples a cada usuário da lista.'''\n\tfor name in names:\n\t\tmsg = 'Hello, ' + name.title() + '!'\n\t\tprint(msg)\n\nusernames = ['hannah', 'ty', 'margot']\n\ngreet_users(usernames)\n","sub_path":"greet_users.py","file_name":"greet_users.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"413345851","text":"'''\nModule created on 26/11/2014\n\n@author: Regina Zhang\n\n'''\n\nimport unittest\nfrom GStestcases import GSTestCases\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom constants import common\nfrom selenium.common.exceptions import *\nimport registration_login as rl\nimport pickle\nimport sys\nfrom genome_space_test import GenomeSpaceTest as GST\n\n\nclass GSFirefox(unittest.TestCase, GSTestCases):\n\n @classmethod\n def setUpClass(cls):\n '''\n a class method overriding Unittest setUpClass method\n preparation work before the testing starts\n '''\n cls.parse_config()\n cls.driver_name = \"firefox\"\n cls.driver = webdriver.Firefox()\n driver = cls.driver\n driver.implicitly_wait(10)\n cls.wait = WebDriverWait(driver,20)\n driver.maximize_window()\n home_page = common[\"base_url\"] + common[\"home_suffix\"]\n try:\n driver.get(home_page)\n driver.implicitly_wait(20)\n assert \"No results found.\" not in driver.page_source\n except UnexpectedAlertPresentException:\n alert = driver.switch_to_alert()\n text = alert.text\n alert.accept()\n print >>sys.stderr, (\"Unexpected alert present: \" + text)\n except AssertionError:\n driver.close()\n raise Exception(\"Page not found: \" + home_page)\n if GST.developing:\n # load the cookie stored last time.\n # if cookie expired, manual deletion needed\n try:\n cookie_file_name = \"cookies_\" + cls.driver_name + \".pkl\"\n cookies = pickle.load(open(cookie_file_name,\"rb\"))\n for cookie in cookies:\n driver.add_cookie(cookie)\n GST.logged_in = True\n except IOError:\n GST.logged_in = False\n try:\n driver.get(home_page)\n assert \"No results found.\" not in driver.page_source\n except AssertionError:\n driver.close()\n raise Exception(\"Page not found: \" + home_page)\n except UnexpectedAlertPresentException:\n alert = driver.switch_to_alert()\n text = alert.text\n alert.dismiss()\n print >>sys.stderr, \"Unexpected alert present: \" + text\n\n @classmethod\n def tearDownClass(cls):\n '''\n a class method overriding the tearDownClass method in Unittest\n close browser and quit driver when the test is done\n '''\n cls.driver.close()\n cls.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","sub_path":"source/GSfirefox.py","file_name":"GSfirefox.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"348574148","text":"import socket\nimport os\nfrom threading import *\n\nServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhost = \"localhost\"\nport = 12345\n\nseprator_token = \"\"\ndisconectMessage =\"!DISCONNECT\"\nthreadCount = 0\nclientSockets = set()\nnameaccess={}\n\nServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ntry:\n\tServer.bind((host, port))\n\nexcept socket.error as e:\n\tprint(str(e))\n\nprint(\"Server Listening on port \" + str(port))\n\nServer.listen(5)\n\ndef ServerListner(cs):\n\twhile True:\n\t\ttry:\n\t\t\tmsg = cs.recv(1024).decode()\n\t\texcept Exception as e:\n\t\t\tprint(f\"Error: {e}\")\n\t\t\tcs.close()\n\t\t\tbreak\n\t\t\t# clientSockets.remove(cs)\n\t\telse:\n\t\t\tif msg == disconectMessage:\n\t\t\t\tcs.close()\n\t\t\t\tbreak\n\n\t\t\tmsg = msg.replace(seprator_token, \": \")\n\t\t\tprint(msg)\n\t\t\tcounter=0\n\t\t\tfinname=''\n\t\t\twhile msg[counter]!=':':\n\t\t\t\tfinname+=msg[counter]\n\t\t\t\tcounter+=1\n\t\t\tcounter+=2\n\t\t\tnamestr=''\n\t\t\tcounter2=0\n\t\t\tunderscorePresent=0\n\t\t\twhile counter2 best_val_score:\n best_val_score = f1\n copyfile(\n model_file,\n os.path.join(model_dir, 'best_model.pt'))\n log.info('[new best model saved.]')\n\n\nif __name__ == '__main__':\n #test_loader()\n main()\n","sub_path":"src/.ipynb_checkpoints/maintrain-checkpoint.py","file_name":"maintrain-checkpoint.py","file_ext":"py","file_size_in_byte":11041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"424856118","text":"import torch\r\nfrom dataset import trainDataLoader,validDataLoader,testDataLoader\r\nfrom model import Net\r\nfrom train import train\r\n\r\n\r\nepochs = 500\r\n# lr = 0.1\r\nlr = 0.01\r\n\r\nnet = Net()\r\n\r\nif torch.cuda.is_available():\r\n print('CUDA is available! Training on GPU ...\\n')\r\n net.cuda()\r\n\r\n#optimizer = torch.optim.SGD(net.parameters(),lr=0.01) #利用SGD优化器优化神经网络,传入参数,学习率0.5\r\noptimizer = torch.optim.Adam(net.parameters(),lr=lr) #利用SGD优化器优化神经网络,传入参数,学习率0.5\r\nloss_func = torch.nn.MSELoss() #利用均方差进行回归\r\n\r\n\r\nfor epoch in range(epochs):\r\n train(epoch, net, trainDataLoader, optimizer, loss_func, validDataLoader,testDataLoader)\r\n\r\nprint('trainDataLoader')\r\n\r\n\r\n\r\n\r\n","sub_path":"AlexNet_Allsites_ROI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"274653793","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), 'test'))\nimport face_model\n\nimport argparse\nimport cv2\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport shutil\n\nimport time\nfrom PIL import Image\n\nclass Args():\n def __init__(self):\n self.image_size = '112,112'\n self.gpu = 0\n self.model = './models/model-r50-am-lfw/model,0000'\n self.ga_model = './models/gamodel-r50/model,0000'\n self.threshold = 1.24\n self.flip = 0\n self.det = 0\nIMAGE_SIZE = 112 \ndef resize_image(image, height = IMAGE_SIZE, width = IMAGE_SIZE):\n top, bottom, left, right = (0, 0, 0, 0)\n #獲取影象尺寸\n h, w, _ = image.shape\n\n #對於長寬不相等的圖片,找到最長的一邊\n longest_edge = max(h, w) \n #計算短邊需要增加多上畫素寬度使其與長邊等長\n if h < longest_edge:\n dh = longest_edge - h\n top = dh // 2\n bottom = dh - top\n elif w < longest_edge:\n dw = longest_edge - w\n left = dw // 2\n right = dw - left\n else:\n pass \n BLACK = [0, 0, 0]\n #給影象增加邊界,是圖片長、寬等長,cv2.BORDER_CONSTANT指定邊界顏色由value指定\n constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK)\n #調整影象大小並返回\n return cv2.resize(constant, (height, width))\n\nargs = Args()\nmodel = face_model.FaceModel(args)\n\npath = r'../test_data/'\ndst_path = '../test_mtcnn_data/'\n# imgs = os.listdir(path)\ncnt = 0\n\nprint('finished load model')\n\nimages_list = os.listdir(path)\nfor image in images_list:\n print(os.path.join(path, image))\n img = cv2.imread(os.path.join(path, image))\n out = model.get_input(img) # 3x112x112\n try:\n print(f'{out.shape}')\n new_image = np.transpose(out, (1, 2, 0))[:, :, ::-1]\n except:\n new_image = np.transpose(img, (1, 2, 0))[:, :, ::-1]\n new_image = resize_image(img , 112 , 112)\n print(f'{new_image.shape}')\n out = Image.fromarray(new_image)\n out = out.resize((112, 112))\n out = np.asarray(out)\n\n# for point in points:\n# cv2.circle(out, (point[0], point[1]), 2, (0, 0, 255), -1)\n # cv2.putText(image, str(num), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 255, 255), 1, cv2.LINE_AA)\n cv2.imwrite(os.path.join(dst_path, image[:-4] + '_mtcnn.jpg'), out)\n cnt += 1\n ","sub_path":"get_finetune_data/get_test_face.py","file_name":"get_test_face.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"119784437","text":"# encoding: utf-8\n\nimport logging\n\nfrom django.core.paginator import Paginator\nfrom rest_framework.views import APIView\n\nfrom common.models import BackstageHTTPResponse\nfrom common.utils import log_exception\nfrom tables.filters import TablesFilter\nfrom tables.models import Tables\nfrom tables.serializers import TableSerializer\n\nlogger = logging.getLogger(__name__)\n\n\nclass TableListAPI(APIView):\n\n @log_exception\n def get(self, request, *args, **kwargs):\n \"\"\"\n 数据表列表\n ---\n parameters:\n - name: index\n description: 页数\n type: integer\n paramType: query\n required: false\n - name: number\n description: 每页条数\n type: integer\n paramType: query\n required: false\n - name: name\n description: 名字\n type: string\n paramType: query\n required: false\n - name: type\n description: 类型\n type: integer\n paramType: query\n required: false\n \"\"\"\n tables = Tables.objects.all()\n tables = TablesFilter(request.GET, queryset=tables).qs\n paginator = Paginator(tables, request.GET.get('number', 100))\n page = paginator.page(request.GET.get('index', 1))\n serializer = TableSerializer(page, many=True)\n return BackstageHTTPResponse(\n code=BackstageHTTPResponse.API_HTTP_CODE_NORMAL,\n data=serializer.data,\n pageinfo=page\n ).to_response()\n\n\nclass TableDetailAPI(APIView):\n\n @log_exception\n def get(self, request, id, *args, **kwargs):\n \"\"\"\n 数据表\n ---\n parameters:\n - name: id\n description: id\n type: integer\n paramType: path\n required: true\n \"\"\"\n table = Tables.objects.filter(id=id).first()\n if id and not table:\n return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_INVILID_PARAMS, message='没有该表').to_response()\n\n serializer = TableSerializer(table)\n return BackstageHTTPResponse(\n code=BackstageHTTPResponse.API_HTTP_CODE_NORMAL,\n data=serializer.data,\n ).to_response()\n","sub_path":"src/api/tables/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"233103994","text":"import argparse\nimport json\nimport numpy as np\nimport os\nimport tensorflow.keras as keras\n\n\ndef load_data(input_path):\n path = os.path.join(input_path, 'mnist/mnist.npz')\n with np.load(path, allow_pickle=True) as f:\n x_train, y_train = f['x_train'], f['y_train']\n x_test, y_test = f['x_test'], f['y_test']\n x_train = x_train / 255.0\n x_test = x_test / 255.0\n return {\n 'x_train': x_train,\n 'y_train': y_train, \n 'x_test': x_test,\n 'y_test': y_test,\n }\n\n\ndef create_model(params):\n model = keras.models.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dropout(0.2),\n keras.layers.Dense(10, activation='softmax'), # why ,?\n ])\n\n model.compile(\n optimizer=keras.optimizers.Adam(learning_rate=params.learning_rate),\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'],\n )\n return model\n\n\ndef train(model, data, params):\n def print_metrics(epoch, logs):\n print()\n logs = {k: str(v) for (k, v) in logs.items()}\n print(json.dumps({'epoch': epoch, **logs}))\n\n print_metrics_callback = keras.callbacks.LambdaCallback(on_epoch_end=print_metrics)\n\n model.fit(data['x_train'], data['y_train'], epochs=params.epochs, callbacks=[print_metrics_callback])\n\n\ndef evaluate(model, data):\n test_loss, test_acc = model.evaluate(data['x_test'], data['y_test'])\n print(json.dumps({\n 'test_loss': str(test_loss),\n 'test_acc': str(test_acc),\n }))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=5) \n parser.add_argument('--learning_rate', type=float, default=0.001)\n params = parser.parse_args()\n\n input_path = os.getenv('VH_INPUTS_DIR', '/valohai/inputs')\n output_path = os.getenv('VH_OUTPUTS_DIR', '/valohai/outputs')\n\n data = load_data(input_path)\n model = create_model(params)\n train(model, data, params)\n model.save(os.path.join(output_path, 'mnist.h5'))\n evaluate(model, data)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"266890737","text":"#!/usr/bin/python3\n\ndef fact(n):\n if(n==1 or n==0):\n return n\n else:\n return n*fact(n-1)\n\ntemp = fact(100)\nprint(temp)\n\nsum = 0\nwhile(temp):\n sum = sum + temp%10\n temp = temp//10\n\nprint(sum)\n","sub_path":"Problem_20.py","file_name":"Problem_20.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"392908237","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\ndriver=webdriver.Firefox(executable_path=\"C:\\Drivers\\geckodriver-v0.27.0-win64\\geckodriver.exe\")\r\n\r\ndriver.get(\"http://demo.automationtesting.in/Windows.html\") #openng the website\r\n\r\ndriver.find_element(By.XPATH,\"//*[@id='Tabbed']/a/button\").click() #clicking on the button\r\n\r\nprint(driver.current_window_handle) #returns the current window's handle value and prints it off\r\n\r\nhandles=driver.window_handles #stores handle values of all the windows that are opened\r\n\r\nfor handle in handles:\r\n driver.switch_to_window(handle)\r\n print(driver.title) #prints the titles of the windows\r\n\r\n if driver.title==\"Frames & windows\":\r\n driver.close() #this will just close the parent window\r\n\r\ndriver.quit()\r\n\r\n","sub_path":"windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"128969883","text":"# -*- coding:utf-8 -*-\nfrom __future__ import unicode_literals\nfrom baidu import exceptions\nfrom baidu.models import empty\nfrom baidu.models.lbscloud import Column, GeoTable\nfrom baidu.api.base import BaseAPI\n\n\nclass GeoDataAPI(BaseAPI):\n \"\"\"\n \"\"\"\n scope = 'geodata'\n version = 'v3'\n\n def create_geotable(self, name, is_published, geotype=1):\n \"\"\"\n 创建表(create geotable)接口\n\n :param name: geotable的中文名称\n :param is_published: 是否发布到检索\n :param geotype: geotable持有数据的类型。1:点;2:线;3:面。默认为1(当前只支持点)\n \"\"\"\n # 目前只支持点\n if geotype != 1:\n geotype = 1\n data = {\n 'name': name,\n 'geotype': geotype,\n 'is_published': is_published\n }\n result = self.post('/geotable/create', data=data)\n return result['id'] > 0\n\n def get_geotables(self, name=empty):\n \"\"\"\n 查询表(list geotable)接口\n\n :param name: geotable的名字\n \"\"\"\n if name is empty or not name:\n params = {}\n else:\n params = {'name': name}\n result = self.get('/geotable/list', params=params)\n geotables = []\n if result['size'] > 0:\n for geotable_info in result['geotables']:\n geotables.append(GeoTable(**geotable_info))\n\n return geotables\n\n def get_geotable_by_name(self, geotable_name):\n \"\"\"\n 通过位置数据表的表名获取表对象\n\n .. tips:\n 此方法不是百度 LSB API支持的,而是从`get_geotables`变形而来。\n \"\"\"\n geotables = self.get_geotables(name=geotable_name)\n if len(geotables) == 0:\n raise exceptions.GeotableDoesNotExistException()\n assert len(geotables) == 1, \"位置数据表的名称不唯一\"\n return geotables[0]\n\n def get_geotable(self, geotable_id):\n \"\"\"\n 查询指定id表(detail geotable)接口\n\n :param geotable_id: 指定geotable的id\n \"\"\"\n result = self.get('/geotable/detail', params={'id': geotable_id})\n assert 'geotable' in result\n return GeoTable(**result['geotable'])\n\n def update_geotable(self, geotable_id, name=empty, is_published=empty):\n \"\"\"\n 修改表(update geotable)接口\n\n :param geotable_id: geotable主键\n :param name: geotable的中文名称\n :param is_published: 是否发布到检索(会引起批量操作)\n \"\"\"\n data = {'id': geotable_id}\n if name not in (empty, None):\n data['name'] = name\n if is_published not in (empty, None):\n data['is_published'] = is_published\n\n return self.post('/geotable/update', data=data)\n\n def delete_geotable(self, geotable_id):\n \"\"\"\n 删除表(geotable)接口\n\n :param geotable_id: 指定geotable的id\n\n 注意: 当geotable里面没有有效数据时,才能删除geotable。\n \"\"\"\n return self.post('/geotable/delete', data={'id': geotable_id})\n\n def create_column(self, geotable_id, column):\n \"\"\"\n 创建列(create column)接口\n\n :param geotable_id: 所属于的geotable_id\n :param column: 列定义\n \"\"\"\n assert isinstance(column, Column)\n data = {'geotable_id': geotable_id}\n data.update(column.data)\n if 'id' in data:\n data.pop('id')\n result = self.post('/column/create', data=data)\n return result['id'] > 0\n\n def get_columns(self, geotable_id, name=None, key=None):\n \"\"\"\n 查询列(list column)接口\n\n :param geotable_id: 所属于的geotable_id\n :param name: geotable meta的属性中文名称\n :param key: geotable meta存储的属性key\n \"\"\"\n params = {'geotable_id': geotable_id}\n if name is not empty and name:\n params['name'] = name\n if key is not empty and key:\n params['key'] = key\n result = self.get('/column/list', params=params)\n column_list = []\n if result['size'] > 0:\n for column_info in result['columns']:\n column_list.append(Column(**column_info))\n return column_list\n\n def get_column(self, geotable_id, column_id):\n \"\"\"\n 查询指定id列(detail column)详情接口\n\n :param geotable_id: 所属于的geotable_id\n :param column_id: 列的id\n\n \"\"\"\n params = {'geotable_id': geotable_id, 'id': column_id}\n result = self.get('/column/detail', params=params)\n return Column(**result['column'])\n\n def update_column(self, geotable_id, column_id, **kwargs):\n \"\"\"\n 修改指定条件列(column)接口\n\n :param geotable_id: 所属于的geotable_id\n :param column_id: 列的id\n\n :param name: 属性中文名称,可选\n :param default_value: 默认值,可选\n :param max_length: 文本最大长度,可选\n :param is_sortfilter_field: 是否检索引擎的数值排序字段,可选\n :param is_search_field: 是否检索引擎的文本检索字段,可选\n :param is_index_field: 是否存储引擎的索引字段,可选\n :param is_unique_field: 是否存储索引的唯一索引字段,可选\n \"\"\"\n optionals = (\n 'name', 'default_value', 'max_length', 'is_sortfilter_field',\n 'is_search_field', 'is_index_field', 'is_unique_field'\n )\n data = {'geotable_id': geotable_id, 'id': column_id}\n for key in kwargs:\n if key not in optionals:\n kwargs.pop(key)\n if 'key' in kwargs and kwargs['key'] is empty:\n kwargs.pop(key)\n data.update(kwargs)\n return self.post('/column/update', data=data)\n\n def delete_column(self, geotable_id, column_id):\n \"\"\"\n 删除指定条件列(column)接口\n\n :param geotable_id: 所属于的geotable_id\n :param column_id: 列的id\n \"\"\"\n data = {'geotable_id': geotable_id, 'id': column_id}\n return self.post('/column/delete', data=data)\n\n def create_poi(\n self,\n geotable_id,\n longitude,\n latitude,\n coord_type,\n **kwargs):\n \"\"\"\n 创建数据(create poi)接口\n\n TODO: 用户在column定义的key/value对?\n\n :param geotable_id: 记录关联的geotable的标识\n :param longitude: 用户上传的经度\n :param latitude: 用户上传的纬度\n :param coord_type: 用户上传的坐标的类型\n :param title: poi名称,可选\n :param address: 地址,可选\n :param tags: tags,可选\n \"\"\"\n data = {\n 'geotable_id': geotable_id,\n 'latitude': latitude,\n 'longitude': longitude,\n 'coord_type': coord_type,\n }\n data.update(kwargs)\n result = self.post('/poi/create', data=data)\n return result['id']\n\n def get_pois(self, geotable_id, page_index=0, page_size=10, **kwargs):\n \"\"\"\n 查询指定条件的数据(poi)列表接口\n\n column需要设置了is_index_field=1。对于string,是两端匹配。对于int或者double,则是范围查找,传递的格式为最小值,最大值。当无最小值或者最大值时,用-代替,同时,此字段最大长度不超过50,最小值与最大值都是整数\n 例:如加入一个命名为color数据类型为string的column,在检索是可设置为“color=red”的形式来检索color字段为red的POI\n\n :param geotable_id: 记录关联的geotable的标识\n :param title: 记录(数据)名称\n :param tags: 记录的标签(用于检索筛选)\n :param bounds: 查询的矩形区域\n :param page_index: 分页索引\n :param page_size: 分页数目\n\n \"\"\"\n\n params = {'geotable_id': geotable_id}\n params.update(kwargs)\n return self.get('/poi/list', params=params)\n\n def get_poi(self, geotable_id, poi_id):\n \"\"\"\n 查询指定id的数据(poi)详情接口\n\n :param poi_id: 表主键\n :param geotable_id: poi主键\n\n \"\"\"\n params = {'geotable_id': geotable_id, 'id': poi_id}\n return self.get('/poi/detail', params=params)\n\n def update_poi(self, geotable_id, poi_id, coord_type=3, **kwargs):\n \"\"\"\n 修改数据(poi)接口\n\n :param geotable_id: 记录关联的geotable的标识\n :param poi_id: poi的id\n :param coord_type: 用户上传的坐标的类型\n \"\"\"\n\n data = {\n 'geotable_id': geotable_id,\n 'id': poi_id,\n 'coord_type': coord_type\n }\n data.update(kwargs)\n result = self.post('/poi/update', data=data)\n return result['id'] == poi_id\n\n def delete_poi(\n self,\n geotable_id,\n poi_id=empty,\n poi_ids=empty,\n is_total_del=empty,\n **kwargs\n ):\n \"\"\"\n 删除数据(poi)接口(支持批量)\n\n :param geotable_id: geotable_id\n :param poi_id: 如果传了这个参数,此其它的删除条件会被忽略,此时此操作不是批量请求。只会最多删除一个poi\n :param poi_ids: 最多1000个id,如果有这个条件,其它条件将被忽略.\n :param title: 名称\n :param tags: 标签\n :param bounds: string 查询的矩形区域, 格式x1,y1;x2,y2分别代表矩形的左上角和右下角\n\n \"\"\"\n data = {\n 'geotable_id': geotable_id,\n }\n if poi_id is not empty:\n data['id'] = poi_id\n elif poi_ids is not empty and isinstance(poi_ids, list):\n data['ids'] = ','.join(poi_ids)\n else:\n data.update(kwargs)\n\n # 如果是批量删除,则需要传这个参数,值为1;如果不是批量删除,则不用传这个参数\n if is_total_del == 1:\n data['is_total_del'] = 1\n self.post('/poi/delete', data=data)\n return True\n\n # def upload_poi(self,):\n # \"\"\"\n #\n # \"\"\"\n","sub_path":"baidu/api/map/lbscloud.py","file_name":"lbscloud.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"460031834","text":"import numpy as np\nfrom itertools import cycle\n\ndef DataIterator(x, y, batch_size=16, shuffle_on_epoch=True):\n\t\"\"\"\n\tgiven x, y and batch size returns a cyclical data iterator.\n\t\"\"\"\n\n\tassert x.shape[0] == y.shape[0], \"x and y must have same length.\"\n\tdata_size = x.shape[0]\n\n\tshuffle_in_unison(x, y)\n\n\ti = 0\n\twhile 1:\n\t\tif i + batch_size >= data_size:\n\t\t\twrap_around = batch_size + i - data_size\n\t\t\tx_batch = np.concatenate((x[i:,], x[:wrap_around,]), axis=0)\n\t\t\ty_batch = np.concatenate((y[i:,], y[:wrap_around,]), axis=0)\n\t\t\tif shuffle_on_epoch:\n\t\t\t\tshuffle_in_unison(x, y) # re-shuffle the data after every epoch\n\n\t\telse:\n\t\t\tx_batch = x[i:i + batch_size]\n\t\t\ty_batch = y[i:i + batch_size]\n\n\t\ti = (i + batch_size) % data_size\n\n\t\tyield x_batch, y_batch\n\ndef DataIteratorSorted(x, y, groupings, batch_size=16, shuffle_on_epoch=True):\n\t\"\"\"\n\tgiven x, y, groupings and batch size returns a cyclical data iterator.\n\tEach batch contains only elements from the same group, and each group gets equal representation.\n\t\"\"\"\n\tassert x.shape[0] == y.shape[0], \"x and y must have same length.\"\n\tdata_size = x.shape[0]\n\n\tgroup_idxs = {g:np.where(groupings==g) for g in set(groupings)}\n\tgroup_xs = {g:x[group_idxs[g]] for g in group_idxs.keys()}\n\tgroup_ys = {g:y[group_idxs[g]] for g in group_idxs.keys()}\n\tgroup_iterators = [DataIterator(x=group_xs[g], y=group_ys[g], batch_size=batch_size, shuffle_on_epoch=shuffle_on_epoch)\n\t\t\t\t\t\tfor g in group_idxs.keys()]\n\n\titerator_getter = cycle(group_iterators)\n\twhile 1:\n\t\tx, y = next(next(iterator_getter))\n\t\tyield x, y\ndef zipper_sort(x, y):\n\tzipper = zip(x, y)\n\tzipper = sorted(zipper, key=lambda elem:tuple(elem[1]))\n\tx, y = (np.array(data) for data in zip(*zipper))\n\treturn x, y\n\ndef shuffle_in_unison(a, b):\n\tassert(a.shape[0] == b.shape[0])\n\trng_state = np.random.get_state()\n\tnp.random.shuffle(a)\n\tnp.random.set_state(rng_state)\n\tnp.random.shuffle(b)\n\nif __name__ == \"__main__\":\n\tx = np.array(list(range(20)))\n\ty = np.array([[i]*5 for i in range(4)]).flatten()\n\tgroupings = np.array([[i]*10 for i in range(2)]).flatten()\n\tdIter = DataIteratorSorted(x=x, y=y, groupings=groupings, batch_size=3)\n\tfor i in range(10):\n\t\tprint(next(dIter))","sub_path":"utilities/data_iterator.py","file_name":"data_iterator.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"622673218","text":"\"\"\"Confirmation report generator for CLN and FRN-CLN basket trades.\n\nThis script is invoked by calling the homonymous ASQL query.\n\"\"\"\n# Desk Requester Developer CR Number\n# What\n# =============================================================================\n\n# OPS Sipho Ndlalane Lukas Paluzga ABITFA-1269\n# Refactored to use common base; Created CLN report.\n\n# OPS Letitia Carboni Lukas Paluzga ABITFA-1795\n# New letterhead\n\n# OPS Sipho Ndlalane\tSanele Macanda\t\tCHNG0001662676 - ABITFA -No Jira (23/01/2014)\n# Replaced os.startfile() with startFile() see SAGEN_IT_Functions\n\n\nimport os, time\n\nimport acm\n\nimport at, SACM_Trade_Confirmation_PDF as stc\nfrom XMLReport import mkinfo, mkvalues, mkcaption\nfrom zak_funcs import formcurr\nfrom SAGEN_IT_Functions import startFile\n\nclass ReturnConfirmationReport(stc.FRNReportBase):\n def validate_trade(self):\n if self.instrument.InsType() == at.INST_FRN:\n if at.addInfo.get_value(self.trade, at.addInfoSpecEnum.MM_INSTYPE) != 'CLN':\n acm.Log('Instrument type FRN is not an allowed unless CLN is specified in {0}. '.format(at.addInfoSpecEnum.MM_INSTYPE))\n return False\n\n return super(stc.FRNReportBase, self).validate_trade()\n\n def statement_detail(self):\n yield mkinfo(\"\"\"The Note described in this document is subject to the terms and conditions set out in the Applicable Pricing \\\nSupplement and the General Terms and Conditions of the Notes set out in the Programme Memorandum dated 19 July 2007 relating \\\nto the Issuer's Credit-linked Note Programme (the \"Programme Memorandum\"). This document must be read in conjunction with \\\nthe Applicable Pricing Supplement and the Programme Memorandum. In the event of any inconsistency between this document and \\\nthe Applicable Pricing Supplement, the Applicable Pricing Supplement will prevail. In the event of any inconsistency between \\\nthe Applicable Pricing Supplement and the Programme Memorandum, the Applicable Pricing Supplement will prevail.\"\"\")\n \n yield mkcaption('CLN ADVICE NOTE') \n \n if self.trade.Bought():\n yield mkinfo(\"We confirm having BOUGHT the following credit-linked note FROM you.\")\n else:\n yield mkinfo(\"We confirm having SOLD the following credit-linked note TO you.\")\n\n values = [[\"DEAL REFERENCE:\", self.trade.Name()],\n [\"COUNTERPARTY CODE:\", self.trade.Counterparty().Name()],\n [\"NUTRON CODE:\", self.trade.Counterparty().HostId()],\n [\"UNEXCOR CODE:\", self.unexCor()],\n [\"CLN DESCRIPTION\", self.instrument_externalid1()],\n [\"DEAL DATE:\", time.strftime('%d/%m/%Y %H:%M:%S ', time.localtime(self.trade.CreateTime()))],\n [\"SETTLEMENT DATE:\", self.trade.ValueDay()],\n [\"NOMINAL VALUE:\", formcurr(abs(self.trade.Nominal()))],\n [\"CONSIDERATION:\", formcurr(self.trade_ael.premium)]]\n \n try:\n values.append([\"ISSUED BY:\", self.instrument.Issuer().Name()])\n except AttributeError:\n pass\n\n # Do not show maturity date for combination/basket CLNs\n if not self.is_combination_or_basket():\n values.append([\"MATURITY DATE:\", self.instrument.ExpiryDateOnly()])\n\n values.append([\"ALL-IN-PRICE:\", self.trade.Price()])\n values.append([\"ACCRUED INTEREST:\", formcurr(self.traded_interest())])\n \n yield mkvalues(*values)\n\nael_gui_parameters = {'windowCaption':'CLN Confirmation'}\nael_variables = stc.get_ael_variables('Y:/Jhb/Ops CM/Capital Markets Confirmations/CLN Confirmations/')\n\ndef ael_main(parameters):\n trade_numbers = stc.parse_trade_numbers(parameters['TradeNumber'])\n\n if trade_numbers:\n allowed_instypes = [at.INST_FRN, at.INST_COMBINATION]\n reporter = stc.Reporter(stc.prep_reporter_args('CLN', ReturnConfirmationReport, allowed_instypes, parameters))\n\n output_file_name = reporter.create_reports(trade_numbers)\n startFile(output_file_name)\n\ndef ASQL(*rest):\n acm.RunModuleWithParameters('SACM_CLN_Confirmation_PDF', 'Standard') #@UndefinedVariable\n return 'SUCCESS'\n\n","sub_path":"Python modules/SACM_CLN_Confirmation_PDF.py","file_name":"SACM_CLN_Confirmation_PDF.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"80286649","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/18 下午10:38\n# @Author : Aries\n# @Site :\n# @File : Dnn-master.py\n# @Software: PyCharm\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.contrib import layers\n\n'''\n定义训练轮数\n'''\ntraing_steps = 30000\n\n'''\n定义输入的数据和对应的标签并在for循环内进行填充\nbatch数据输入\n'''\ndata = []\nlabel = []\nfor i in range(200):\n\tx1 = np.random.uniform(-1, 1)\n\tx2 = np.random.uniform(0, 2)\n\t'''\n\t策略:对x1 and x2 进行判断,如果落在原点为中心1为半径的圆内,label = 0\n\t\t反之为1\n\t'''\n\tif x1**2 + x2**2 <= 1:\n\t\tdata.append([np.random.normal(x1, 0.1), np.random.normal(x2, 0.1)])\n\t\tlabel.append(0)\n\telse:\n\t\tdata.append([np.random.normal(x1, 0.1), np.random.normal(x2, 0.1)])\n\t\tlabel.append(1)\n\n'''\nnumpy的hstack()函数用于再水平方向将元素堆起来\n函数圆形 numpy.hstack(tup) tup 可以是元组,列表或者numpy数组\nreshape用于反转\n'''\ndata = np.hstack(data).reshape(-1, 2)\nlabel = np.hstack(label).reshape(-1, 1)\n\n'''\n定义完成前馈传递的隐藏层\n'''\n\n\ndef hidden_layer(input, w1, b1, w2, b2, w3, b3):\n\tlayer1 = tf.nn.relu(tf.matmul(input, w1) + b1)\n\tlayer2 = tf.nn.relu(tf.matmul(layer1, w2) + b2)\n\treturn tf.matmul(layer2, w3) + b3\n\n\nx = tf.placeholder(tf.float32, shape=(None, 2), name='x-input')\ny_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-output')\n\n'''\n定义权重参数和偏置参数\n'''\nw1 = tf.Variable(tf.truncated_normal([2, 10], stddev=0.1))\nb1 = tf.Variable(tf.constant(0.1, shape=[10]))\nw2 = tf.Variable(tf.truncated_normal([10, 10], stddev=0.1))\nb2 = tf.Variable(tf.constant(0.1, shape=[10]))\nw3 = tf.Variable(tf.truncated_normal([10, 1], stddev=0.1))\nb3 = tf.Variable(tf.constant(0.1, shape=[1]))\n\n'''\n用len记录data的长度\n'''\nsample_size = len(data)\n\n'''\n得到隐藏层前向传播结果\n'''\ny = hidden_layer(x, w1, b1, w2, b2, w3, b3)\n\n'''\n自定义损失函数\n'''\nerror_loss = tf.reduce_sum(tf.pow(y_ - y, 2)) / sample_size\ntf.add_to_collection('loss', error_loss)\n\nregularizer = layers.l2_regularizer(0.01)\nregularization = regularizer(w1) + regularizer(w2) + regularizer(w3)\ntf.add_to_collection('loss', regularization)\n\n'''\nget_collection()根据name,获取所有的损失值进行加运算\n'''\nloss = tf.add_n(tf.get_collection('loss'))\n\n'''\n定义一个优化器进行梯度更新\n学习率固定为0.01\n'''\ntraing_op = tf.train.AdamOptimizer(0.01).minimize(loss)\n\n'''\nexect()\n'''\nwith tf.Session() as sess:\n\t'''\n\t初始化tf变量\n\t'''\n\ttf.global_variables_initializer().run()\n\t\n\t'''\n\t进行30000次循环\n\t'''\n\tfor i in range(traing_steps):\n\t\tsess.run(traing_op, feed_dict={x: data, y_: label})\n\t\t\n\t\t'''\n\t\t每隔2000次输出一次loss值\n\t\t'''\n\t\tif i % 2000 == 0:\n\t\t\tloss_value = sess.run(loss, feed_dict={x: data, y_: label})\n\t\t\tprint('afer %d step ,loss value is %f' % (i, loss_value))\n","sub_path":"method_of_optimizing_network/DNN/Dnn-master.py","file_name":"Dnn-master.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"99494932","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport json\nimport pandas as pd\nimport numpy as np\nfrom UtilityLib import UtilityLib\n\n\n# In[2]:\n\n\nclass LuisAppProcessor:\n \n def __read_file(self, file_path):\n with open(file_path) as file:\n return json.load(file)\n\n def __extract_utterances_data(self, json_data):\n\n utterance_data = json_data['utterances']\n\n text_col_meta = ('text','object')\n intent_col_meta = ('intent','object')\n file_data_types = [text_col_meta, intent_col_meta]\n\n intent_values = []\n for utt in utterance_data:\n # fetchig utt['text] and utt['intent']\n value = (utt[text_col_meta[0]], utt[intent_col_meta[0]])\n intent_values.append(value)\n\n values = np.array(intent_values, dtype=file_data_types)\n return values\n\n def generate_intent_file(self, file_path):\n file_path = os.path.abspath(file_path)\n bot_file_data = self.__read_file(file_path)\n utts = self.__extract_utterances_data(bot_file_data)\n df = pd.DataFrame(data=utts, index=[i for i in range(len(utts))])\n\n ul = UtilityLib()\n dir_name = ul.get_directory_path(file_path)\n file_name_wo_ext = ul.get_file_name(file_path)\n new_file_name = file_name_wo_ext + '_intent.csv'\n\n new_file_path = ul.path_join(dir_name, new_file_name)\n df.to_csv(new_file_path, index=False)\n return new_file_path\n\n def get_entities(self, file_path):\n json_data = self.__read_file(file_path)\n entities = [ent['name'] for ent in json_data['entities']]\n return entities\n\n def get_entity_training_data(self, file_path):\n\n json_data = self.__read_file(file_path)\n\n utterance_data = json_data['utterances']\n entity_training_data = []\n for utt in utterance_data:\n entities = []\n for entity in utt['entities']:\n # In endPos, add 1 as Python uses these indexes slightly differently than Microsoft.\n entities.append((entity['startPos'], entity['endPos'] + 1, entity['entity']))\n\n ent_train_data = (utt['text'], {'entities': entities})\n entity_training_data.append(ent_train_data)\n return entity_training_data\n\n","sub_path":"Natural Language/Final Scripts/luis_app_processor.py","file_name":"luis_app_processor.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"170782716","text":"\"\"\"\nCore scaffolding for divide and conquer extraction algorithm\n\"\"\"\n\nimport sys\n\nimport numpy as np\n\ntry:\n import cupy as cp\nexcept ImportError:\n pass\n\nfrom gpu_specter.util import get_logger\nfrom gpu_specter.util import get_array_module\nfrom gpu_specter.util import Timer\nfrom gpu_specter.util import gather_ndarray\n\nclass Patch(object):\n def __init__(self, ispec, iwave, bspecmin, nspectra_per_patch, nwavestep, wavepad, nwave,\n bundlesize, ndiag):\n \"\"\"Convenience data wrapper for divide and conquer extraction patches\n\n Args:\n ispec: starting spectrum index\n iwave: starting wavelength index\n bspecmin: starting spectrum index of the bundle that this patch belongs to\n nspectra_per_patch: number of spectra to extract (not including padding)\n nwavestep: number of wavelengths to extract (not including padding)\n wavepad: number of extra wave bins to extract (and discard) on each end\n nwave: number of wavelength bins in for entire bundle\n bundlesize: size of fiber bundles\n ndiag: number of diagonal elements to keep in the resolution matrix\n\n All args become attributes.\n\n Additional attributes created:\n specslice: where this patch goes in the bundle result array\n waveslice: where this patch goes in the bundle result array\n keepslice: wavelength slice to keep from padded patch (the final patch in the bundle\n will be narrower when (nwave % nwavestep) != 0)\n \"\"\"\n\n self.ispec = ispec\n self.iwave = iwave\n\n self.nspectra_per_patch = nspectra_per_patch\n self.nwavestep = nwavestep\n\n #- padding to apply to patch\n self.wavepad = wavepad\n\n #- where this patch should go\n #- note: spec indexing is relative to subbundle\n self.bspecmin = bspecmin\n self.specslice = np.s_[ispec-bspecmin:ispec-bspecmin+nspectra_per_patch]\n self.waveslice = np.s_[iwave-wavepad:iwave-wavepad+nwavestep]\n\n #- how much of the patch to keep\n nwavekeep = min(nwavestep, nwave - (iwave-wavepad))\n self.keepslice = np.s_[0:nwavekeep]\n\n #- to help with reassembly\n self.nwave = nwave\n self.bundlesize = bundlesize\n self.ndiag = ndiag\n\n\ndef assemble_bundle_patches(rankresults):\n \"\"\"\n Assembles bundle patches into output arrays\n\n Args:\n rankresults: list of lists containing individual patch extraction results\n\n Returns:\n (spexflux, specivar, Rdiags) tuple\n \"\"\"\n\n #- flatten list of lists into single list\n allresults = list()\n for rr in rankresults:\n allresults.extend(rr)\n\n #- peak at result to get bundle params\n patch = allresults[0][0]\n nwave = patch.nwave\n bundlesize = patch.bundlesize\n ndiag = patch.ndiag\n\n xp = get_array_module(allresults[0][1]['flux'])\n\n #- Allocate output arrays to fill\n specflux = xp.zeros((bundlesize, nwave))\n specivar = xp.zeros((bundlesize, nwave))\n Rdiags = xp.zeros((bundlesize, 2*ndiag+1, nwave))\n\n #- Now put these into the final arrays\n for patch, result in allresults:\n fx = result['flux']\n fxivar = result['ivar']\n xRdiags = result['Rdiags']\n\n #- put the extracted patch into the output arrays\n specflux[patch.specslice, patch.waveslice] = fx[:, patch.keepslice]\n specivar[patch.specslice, patch.waveslice] = fxivar[:, patch.keepslice]\n Rdiags[patch.specslice, :, patch.waveslice] = xRdiags[:, :, patch.keepslice]\n\n return specflux, specivar, Rdiags\n\n\ndef extract_bundle(image, imageivar, psf, wave, fullwave, bspecmin, bundlesize=25, nsubbundles=1,\n nwavestep=50, wavepad=10, comm=None, gpu=None, loglevel=None):\n \"\"\"\n Extract 1D spectra from a single bundle of a 2D image.\n\n Args:\n image: full 2D array of image pixels\n imageivar: full 2D array of inverse variance for the image\n psf: dictionary psf object (see gpu_specter.io.read_psf)\n wave: 1D array of wavelengths to extract\n fullwave: Padded 1D array of wavelengths to extract\n bspecmin: index of the first spectrum in the bundle\n\n Options:\n bundlesize: fixed number of spectra per bundle (25 for DESI)\n nsubbundles: number of spectra per patch\n nwavestep: number of wavelength bins per patch\n wavepad: number of wavelengths bins to add on each end of patch for extraction\n comm: mpi communicator (no mpi: None)\n rank: integer process identifier (no mpi: 0)\n size: number of mpi processes (no mpi: 1)\n gpu: use GPU for extraction (not yet implemented)\n loglevel: log print level\n\n Returns:\n bundle: (flux, ivar, R) tuple\n\n \"\"\"\n timer = Timer()\n\n if comm is None:\n rank = 0\n size = 1\n else:\n rank = comm.rank\n size = comm.size\n\n log = get_logger(loglevel)\n\n #- Extracting on CPU or GPU?\n if gpu:\n from gpu_specter.extract.gpu import \\\n get_spots, ex2d_padded\n else:\n from gpu_specter.extract.cpu import \\\n get_spots, ex2d_padded\n\n nwave = len(wave)\n ndiag = psf['PSF'].meta['HSIZEY']\n\n timer.split('init')\n\n #- Cache PSF spots for all wavelengths for spectra in this bundle\n if gpu:\n cp.cuda.nvtx.RangePush('get_spots')\n spots, corners = get_spots(bspecmin, bundlesize, fullwave, psf)\n if gpu:\n cp.cuda.nvtx.RangePop()\n\n timer.split('spots/corners')\n\n #- Size of the individual spots\n spot_nx, spot_ny = spots.shape[2:4]\n\n #- Organize what sub-bundle patches to extract\n patches = list()\n nspectra_per_patch = bundlesize // nsubbundles\n for ispec in range(bspecmin, bspecmin+bundlesize, nspectra_per_patch):\n for iwave in range(wavepad, wavepad+nwave, nwavestep):\n patch = Patch(ispec, iwave, bspecmin,\n nspectra_per_patch, nwavestep, wavepad,\n nwave, bundlesize, ndiag)\n patches.append(patch)\n\n if rank == 0:\n log.info(f'Dividing {len(patches)} patches between {size} ranks')\n\n timer.split('organize patches')\n\n #- place to keep extraction patch results before assembling in rank 0\n results = list()\n for patch in patches[rank::size]:\n\n log.debug(f'rank={rank}, ispec={patch.ispec}, iwave={patch.iwave}')\n\n #- Always extract the same patch size (more efficient for GPU\n #- memory transfer) then decide post-facto whether to keep it all\n\n if gpu:\n cp.cuda.nvtx.RangePush('ex2d_padded')\n\n result = ex2d_padded(image, imageivar,\n patch.ispec-bspecmin, patch.nspectra_per_patch,\n patch.iwave, patch.nwavestep,\n spots, corners,\n wavepad=patch.wavepad,\n bundlesize=bundlesize)\n if gpu:\n cp.cuda.nvtx.RangePop()\n\n results.append( (patch, result) )\n\n timer.split('extracted patches')\n\n if comm is not None:\n if gpu:\n # If we have gpu and an MPI comm for this bundle, transfer data\n # back to host before assembling the patches\n patches = []\n flux = []\n fluxivar = []\n resolution = []\n for patch, results in results:\n patches.append(patch)\n flux.append(results['flux'])\n fluxivar.append(results['ivar'])\n resolution.append(results['Rdiags'])\n\n # transfer to host in 3 chunks\n cp.cuda.nvtx.RangePush('copy bundle results to host')\n device_id = cp.cuda.runtime.getDevice()\n log.info(f'Rank {rank}: Moving bundle {bspecmin} patches to host from device {device_id}')\n flux = cp.asnumpy(cp.array(flux, dtype=cp.float64))\n fluxivar = cp.asnumpy(cp.array(fluxivar, dtype=cp.float64))\n resolution = cp.asnumpy(cp.array(resolution, dtype=cp.float64))\n cp.cuda.nvtx.RangePop()\n\n # gather to root MPI rank\n patches = comm.gather(patches, root=0)\n flux = gather_ndarray(flux, comm, root=0)\n fluxivar = gather_ndarray(fluxivar, comm, root=0)\n resolution = gather_ndarray(resolution, comm, root=0)\n\n if rank == 0:\n # unpack patches\n patches = [patch for rankpatches in patches for patch in rankpatches]\n # repack everything\n rankresults = [\n zip(patches, \n map(lambda x: dict(flux=x[0], ivar=x[1], Rdiags=x[2]), \n zip(flux, fluxivar, resolution)\n )\n )\n ]\n else:\n rankresults = comm.gather(results, root=0)\n else:\n # this is fine for GPU w/out MPI comm\n rankresults = [results,]\n\n timer.split('gathered patches')\n\n bundle = None\n if rank == 0:\n if gpu:\n cp.cuda.nvtx.RangePush('assemble patches on device')\n device_id = cp.cuda.runtime.getDevice()\n log.info(f'Rank {rank}: Assembling bundle {bspecmin} patches on device {device_id}')\n bundle = assemble_bundle_patches(rankresults)\n if gpu:\n cp.cuda.nvtx.RangePop()\n if comm is None:\n cp.cuda.nvtx.RangePush('copy bundle results to host')\n device_id = cp.cuda.runtime.getDevice()\n log.info(f'Rank {rank}: Moving bundle {bspecmin} to host from device {device_id}')\n bundle = tuple(cp.asnumpy(x) for x in bundle)\n cp.cuda.nvtx.RangePop()\n timer.split('assembled patches')\n timer.log_splits(log)\n return bundle\n\n\ndef extract_frame(img, psf, bundlesize, specmin, nspec, wavelength=None, nwavestep=50, nsubbundles=1,\n comm=None, rank=0, size=1, gpu=None, loglevel=None):\n \"\"\"\n Extract 1D spectra from 2D image.\n\n Args:\n img: dictionary image object (see gpu_specter.io.read_img)\n psf: dictionary psf object (see gpu_specter.io.read_psf)\n bundlesize: fixed number of spectra per bundle (25 for DESI)\n specmin: index of first spectrum to extract\n nspec: number of spectra to extract\n\n Options:\n wavelength: wavelength range to extract, formatted as 'wmin,wmax,dw'\n nwavestep: number of wavelength bins per patch\n nsubbundles: number of spectra per patch\n comm: mpi communicator (no mpi: None)\n rank: integer process identifier (no mpi: 0)\n size: number of mpi processes (no mpi: 1)\n gpu: use GPU for extraction (not yet implemented)\n loglevel: log print level\n\n Returns:\n frame: dictionary frame object (see gpu_specter.io.write_frame)\n \"\"\"\n\n timer = Timer()\n\n log = get_logger(loglevel)\n\n #- Determine MPI communication strategy based on number of gpu devices and MPI ranks\n if gpu:\n import cupy as cp\n #- TODO: specify number of gpus to use?\n device_count = cp.cuda.runtime.getDeviceCount()\n assert size % device_count == 0, 'Number of MPI ranks must be divisible by number of GPUs'\n device_id = rank % device_count\n cp.cuda.Device(device_id).use()\n\n #- Divide mpi ranks evenly among gpus\n device_size = size // device_count\n bundle_rank = rank // device_count\n\n if device_count > 1:\n #- Multi gpu, MPI communication needs to happen at frame level\n frame_comm = comm.Split(color=bundle_rank, key=device_id)\n if device_size > 1:\n #- If multiple ranks per gpu, also need to communicate at bundle level\n bundle_comm = comm.Split(color=device_id, key=bundle_rank)\n else:\n #- If only one rank per gpu, don't need bundle level communication\n bundle_comm = None\n else:\n #- Single gpu, only do MPI communication at bundle level\n frame_comm = None\n bundle_comm = comm\n else:\n #- No gpu, do MPI communication at bundle level\n frame_comm = None\n bundle_comm = comm\n\n timer.split('init')\n\n imgpixels = imgivar = None\n if rank == 0:\n imgpixels = img['image']\n imgivar = img['ivar']\n\n #- If using MPI, broadcast image, ivar, and psf to all ranks\n if comm is not None:\n if rank == 0:\n log.info('Broadcasting inputs to other MPI ranks')\n imgpixels = comm.bcast(imgpixels, root=0)\n imgivar = comm.bcast(imgivar, root=0)\n psf = comm.bcast(psf, root=0)\n\n #- If using GPU, move image and ivar to device\n #- TODO: is there a way for ranks to share a pointer to device memory?\n if gpu:\n cp.cuda.nvtx.RangePush('copy imgpixels, imgivar to device')\n device_id = cp.cuda.runtime.getDevice()\n log.info(f'Rank {rank}: Moving image data to device {device_id}')\n imgpixels = cp.asarray(imgpixels)\n imgivar = cp.asarray(imgivar)\n cp.cuda.nvtx.RangePop()\n\n timer.split('distributed data')\n\n if wavelength is not None:\n wmin, wmax, dw = map(float, wavelength.split(','))\n else:\n wmin, wmax = psf['PSF'].meta['WAVEMIN'], psf['PSF'].meta['WAVEMAX']\n dw = 0.8\n\n if rank == 0:\n log.info(f'Extracting wavelengths {wmin},{wmax},{dw}')\n \n #- TODO: calculate this instead of hardcoding it\n wavepad = 10\n\n #- Wavelength range that we want to extract\n wave = np.arange(wmin, wmax + 0.5*dw, dw)\n nwave = len(wave)\n \n #- Pad that with buffer wavelengths to extract and discard, including an\n #- extra args.nwavestep bins to allow coverage for a final partial bin\n wavelo = np.arange(wavepad)*dw\n wavelo -= (np.max(wavelo)+dw)\n wavelo += wmin\n wavehi = wave[-1] + (1.0+np.arange(wavepad+nwavestep))*dw\n \n fullwave = np.concatenate((wavelo, wave, wavehi))\n assert np.allclose(np.diff(fullwave), dw)\n \n #- TODO: barycentric wavelength corrections\n\n #- Work bundle by bundle\n if frame_comm is None:\n bundle_start = 0\n bundle_step = 1\n else:\n bundle_start = device_id\n bundle_step = device_count\n bspecmins = list(range(specmin, specmin+nspec, bundlesize))\n bundles = list()\n for bspecmin in bspecmins[bundle_start::bundle_step]:\n log.info(f'Rank {rank}: Extracting spectra [{bspecmin}:{bspecmin+bundlesize}]')\n sys.stdout.flush()\n if gpu:\n cp.cuda.nvtx.RangePush('extract_bundle')\n bundle = extract_bundle(\n imgpixels, imgivar, psf,\n wave, fullwave, bspecmin,\n bundlesize=bundlesize, nsubbundles=nsubbundles,\n nwavestep=nwavestep, wavepad=wavepad,\n comm=bundle_comm,\n gpu=gpu\n )\n if gpu:\n cp.cuda.nvtx.RangePop()\n bundles.append((bspecmin, bundle))\n\n #- for good measure, have other ranks wait for rank 0\n if bundle_comm is not None:\n bundle_comm.barrier()\n\n timer.split('extracted bundles')\n\n if frame_comm is not None:\n # gather results from multiple mpi groups\n if bundle_rank == 0:\n bspecmins, bundles = zip(*bundles)\n flux, ivar, resolution = zip(*bundles)\n bspecmins = frame_comm.gather(bspecmins, root=0)\n flux = gather_ndarray(flux, frame_comm)\n ivar = gather_ndarray(ivar, frame_comm)\n resolution = gather_ndarray(resolution, frame_comm)\n if rank == 0:\n bspecmin = [bspecmin for rankbspecmins in bspecmins for bspecmin in rankbspecmins]\n rankbundles = [list(zip(bspecmin, zip(flux, ivar, resolution))), ]\n else:\n # no mpi or single group with all ranks\n rankbundles = [bundles,]\n\n timer.split('collected data')\n\n #- Finalize and write output\n frame = None\n if rank == 0:\n\n #- flatten list of lists into single list\n allbundles = list()\n for rb in rankbundles:\n allbundles.extend(rb)\n\n allbundles.sort(key=lambda x: x[0])\n\n specflux = np.vstack([b[1][0] for b in allbundles])\n specivar = np.vstack([b[1][1] for b in allbundles])\n Rdiags = np.vstack([b[1][2] for b in allbundles])\n\n timer.split(f'combined data')\n\n #- Convert flux to photons/A instead of photons/bin\n dwave = np.gradient(wave)\n specflux /= dwave\n specivar *= dwave**2\n\n #- TODO: specmask and chi2pix\n specmask = (specivar == 0).astype(np.int)\n chi2pix = np.ones(specflux.shape)\n\n frame = dict(\n specflux = specflux,\n specivar = specivar,\n specmask = specmask,\n wave = wave,\n Rdiags = Rdiags,\n chi2pix = np.ones(specflux.shape),\n imagehdr = img['imagehdr'],\n fibermap = img['fibermap'],\n fibermaphdr = img['fibermaphdr'],\n )\n\n timer.split(f'finished frame')\n timer.log_splits(log)\n\n return frame\n","sub_path":"py/gpu_specter/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":17165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"387396018","text":"import os\nfrom setuptools import setup\n\n# pyInteract, an interface to Responsys Interact Web Services\n# Responsys offers Interact Web Services to offer automation of offered\n# services available through the web UI.\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"pyinteract\",\n version = \"0.7.8\",\n author = \"Johan Nestaas, Mason Dixon\",\n author_email = \"johan.nestaas@oracle.com, mason.dixon@oracle.com\",\n description = (\"A Python API for the SOAP Web Services offered by \"\n \"responsys.\"),\n license = \"BSD\",\n keywords = \"responsys interact marketing oracle marketing cloud\",\n url = \"https://bitbucket.org/johannestaas/responsys_pyinteract\",\n packages=['interact'],\n long_description=read('README'),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: BSD License',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Topic :: Communications :: Email',\n 'Topic :: Office/Business',\n ],\n install_requires=[\n 'suds',\n ],\n)\n","sub_path":"pypi_install_script/pyinteract-0.7.8.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"256775943","text":"from data import *\nfrom tkinter import *\nfrom datetime import date\nimport requests\nimport json\nimport locale\n\nlocale.setlocale(locale.LC_TIME, \"fi_FI\")\n\nnow = date.today()\nrest_nro = 164 #Sodexo ravintolan nro\nurl = \"https://www.sodexo.fi/ruokalistat/output/daily_json/\"+str(rest_nro) + \"/\" + str(now)\nformtd_day = now.strftime(\"%A %d. \").capitalize() + now.strftime(\"%B\").capitalize()\nbg_color = \"#EAFFE5\"#\"lightgrey\"\n\ndef menu(data, nro):\n try:\n theJSON = json.loads(data)\n if \"dietcodes\" in theJSON[\"courses\"][str(nro)]:\n return theJSON[\"courses\"][str(nro)][\"title_fi\"]+\"\\n\"+theJSON[\"courses\"][str(nro)][\"dietcodes\"]+\"\\n\"+theJSON[\"courses\"][str(nro)][\"price\"]\n return theJSON[\"courses\"][str(nro)][\"title_fi\"]+\"\\n\"+theJSON[\"courses\"][str(nro)][\"price\"]\n except:\n return 1\n \ndef get_content():\n try:\n r = requests.get(url)\n return r.content\n except:\n return \"Error on request\"\n\ndef main():\n lunch = []\n root = Tk()\n root.title(\"Ruokalista\")\n root.geometry(\"480x360+680+240\")\n root.configure(bg=bg_color)\n\n day = Label(root, text= formtd_day + \"\\n\", font=\"Arial 18 bold\", bg=bg_color)\n day.pack()\n\n if menu(get_content(), 1) != 1:\n for i in range(4):\n lunch.append(Label(root, text=str(menu(get_content(), i+1))+ \"\\n\", font=\"Arial 12\",bg=bg_color))\n lunch[i].pack()\n else: \n err_msg = Label(root, text=\"Tänään ei lounasta\", font=\"Arial 12\",bg=bg_color)\n err_msg.pack()\n\n root.mainloop()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"529647527","text":"import random\n\nm_rows, m_cols, n_cols = 2, 3, 2\n\nfile = open(\"input/in.data\", 'w+')\n\nfor r in range(1, m_rows+1):\n for c in range(1, m_cols+1):\n file.write('M#' + str(r) + '#' + str(c) + '#' + str(random.randint(0, 9)) + '\\n')\n\nfor r in range(1, m_cols+1):\n for c in range(1, n_cols+1):\n file.write('N#' + str(r) + '#' + str(c) + '#' + str(random.randint(0, 9)) + '\\n')\n\nfile.close()\n","sub_path":"02_MatrixMultiplication/gen-data.py","file_name":"gen-data.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"99305444","text":"#!/usr/bin/env python\nimport os\nimport feedparser\nimport psycopg2\nimport urlparse\n\nurlparse.uses_netloc.append(\"postgres\")\nurl = urlparse.urlparse(os.environ[\"DATABASE_URL\"])\nwith psycopg2.connect(database=url.path[1:],\n user=url.username,\n password=url.password,\n host=url.hostname,\n port=url.port) as dbconnect:\n\tcur = dbconnect.cursor()\n\n\turl = (\n\t\t\t'http://kenvtv.com/news/local.rss',\n\t\t\t'http://news3lv.com/news/local.rss',\n\t\t\t'http://www.fox5vegas.com/category/210851/app-news?clienttype=rss',\n\t\t\t'http://www.telemundolasvegas.com/noticias/local/?rss=y&embedThumb=y&summary=y',\n\t\t\t'http://mynews4.com/news/local.rss',\n\t\t\t'http://www.kolotv.com/feeds/rss',\n\t\t\t'http://foxreno.com/news/local.rss',\n\t\t\t'http://www.ktvn.com/Global/category.asp?C=90455&clienttype=rss',\n\t\t\t'http://kdwn.com/tag/local/feed/',\n\t\t\t'http://lasvegas.cbslocal.com/category/news/feed/',\n\t\t\t'http://www.reviewjournal.com/news/las-vegas/feed',\n\t\t\t'http://elkodaily.com/search/?q=&t=article&l=25&d=&d1=&d2=&s=start_time&sd=desc&c[]=news/local*&f=rss',\n\t\t\t'http://lasvegassun.com/feeds/headlines/all/',\n\t\t\t'http://www.nevadaappeal.com/csp/mediapool/sites/SwiftShared/assets/csp/rssCategoryFeed.csp?pub=NevadaAppeal§ionId=656§ionLabel=Local',\n\t\t\t'http://rssfeeds.rgj.com/reno/news&x=1',\n\t\t\t'http://www.gvnews.com/search/?q=&t=article&l=25&d=&d1=&d2=&s=start_time&sd=desc&c[]=news/local*&f=rss',\n\t\t\t'http://pvtimes.com/taxonomy/term/1/feed',\n\t\t\t'http://www.recordcourier.com/csp/mediapool/sites/SwiftShared/assets/csp/rssCategoryFeed.csp?pub=RecordCourier§ionId=694§ionLabel=Local',\n\t\t\t'http://www.southvalleyjournal.com/categories/news.rss',\n\t\t\t'http://sparkstrib.com/category/news/feed/'\n\t\t\t)\n\n\tfor link in url:\n\t\td = feedparser.parse(link)\n\n\t\tfor data in d.entries:\n\n\n\t\t\ttitle = data.title\n\t\t\tlink = data.link\n\t\t\ttry:\n\t\t\t\ttime = data.published\n\t\t\texcept AttributeError:\n\t\t\t\ttry:\n\t\t\t\t\ttime = d.feed.published\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttime = data.updated\n\n\t\t\ttry: \n\t\t\t\timageUrl = data.links[1].href\n\t\t\texcept (IndexError, AttributeError): \n\t\t\t\ttry:\n\t\t\t\t\timageUrl = data.media_content[0]['url']\n\t\t\t\texcept (AttributeError, KeyError):\n\t\t\t\t\timageUrl = 'http://polar-spire-13485.herokuapp.com/static/img/logo3.png'\n\n\t\t\tsource = d.feed.title\n\t\t\tlocation = \"NV\"\n\n\t\t\ttry:\n\t\t\t\tcur.execute(\"\"\"INSERT INTO feeds_feeds(title, link, time, image, source, location) VALUES (%s, %s, %s, %s, %s, %s)\"\"\", (title, link, time, imageUrl, source, location))\n\t\t\t\tdbconnect.commit()\n\t\t\t\t\n\t\t\texcept psycopg2.IntegrityError:\n\t\t\t\tdbconnect.rollback()\n\n\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t","sub_path":"feeder/states/nv.py","file_name":"nv.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"627409272","text":"from flask import Flask, request\nfrom flask_cors import CORS\nfrom classSlack import SlackApprovedService\nimport json\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n\n@app.route(\"/slack/approved\", methods=['POST'])\ndef slack_service():\n data = json.loads(request.data)\n # slack.push(added_date, idi, description)\n\n added_date = data.get(\"added_date\")\n idi = data.get(\"id\")\n description = data.get(\"description\")\n slack.push_test(added_date, idi, description)\n\n return \"Success\"\n\n\nif __name__ == '__main__':\n slack = SlackApprovedService(\"config.yaml\")\n # slack.message(\"START -> slack-approved-service\")\n app.run(host=slack.host, port=slack.port)\n","sub_path":"slack-service-approved.py","file_name":"slack-service-approved.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"300946679","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# author: syaofox@gmail.com\nfrom PIL import Image, ImageChops\nfrom io import BytesIO\n\n\nclass VSMImage:\n @classmethod\n def trim(cls, im):\n try:\n bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))\n diff = ImageChops.difference(im, bg)\n diff = ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n if bbox:\n return im.crop(bbox)\n except Exception:\n return im\n\n @classmethod\n def rotate_image(cls, in_bytes):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n img2 = im.transpose(Image.ROTATE_90)\n img2.save(out, format='JPEG')\n return out.getvalue()\n except Exception:\n return in_bytes\n\n @classmethod\n def tim_img_bytes(cls, in_bytes):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n im = cls.trim(im)\n if not im:\n return in_bytes\n im.save(out, format='JPEG')\n return out.getvalue()\n except:\n return in_bytes\n\n @classmethod\n def create_poster(cls, in_bytes, middle=False):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n im = cls.trim(im)\n if not im:\n return None\n if im.size[0] < im.size[1]:\n im.save(out, format='JPEG')\n return out.getvalue()\n if middle:\n pos = im.size[0] // 4\n else:\n pos = im.size[0] * 420 // 800\n box = pos, 0, im.size[0], im.size[1]\n region = im.crop(box)\n region.save(out, format='JPEG')\n return out.getvalue()\n except Exception:\n return None\n\n @classmethod\n def IsValidImage(cls, indata):\n bValid = True\n buf = indata\n if isinstance(indata, bytes):\n buf = BytesIO(indata)\n\n try:\n Image.open(buf).verify()\n except:\n bValid = False\n\n return bValid\n\n @classmethod\n def merge_image(cls, poster, bakdrop):\n try:\n out = BytesIO()\n\n stream = BytesIO(poster)\n im_poster = Image.open(stream)\n\n stream = BytesIO(bakdrop)\n im_bakdrop = Image.open(stream)\n\n im_bakdrop = im_bakdrop.resize(im_poster.size, Image.ANTIALIAS)\n\n new_im = Image.new('RGB', (im_poster.size[0] * 2, im_poster.size[1]))\n\n new_im.paste(im_bakdrop, (0, 0))\n new_im.paste(im_poster, (im_poster.size[0], 0))\n\n new_im.save(out, format='JPEG')\n return out.getvalue()\n except Exception:\n pass\n","sub_path":"models/imageEditor.py","file_name":"imageEditor.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"548464404","text":"from django.db import connection\n\n\nclass SQLCountMiddleware(object):\n\n def process_template_response(self, request, response):\n queries = connection.queries\n sql_queries_count = len(queries)\n sql_queries_time = 0.0\n for x in queries:\n sql_queries_time += float(x['time'])\n\n response.context_data['sql_count'] = sql_queries_count\n response.context_data['sql_time'] = sql_queries_time\n return response\n","sub_path":"students/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"157974343","text":"#coding=utf-8\nimport time\nimport paramiko\nimport random\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom sys_info import *\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n#电话弹屏创建警情立案-调派-结案\noptions = Options()\noptions.add_argument(\"--kiosk\") # 加载启动项页面全屏效果,相当于F11。\noptions.add_experimental_option(\"excludeSwitches\", ['enable-automation']) # 禁止谷歌弹出正在被自动化软件控制消息\ndriver = webdriver.Chrome(r\"E:\\lijie\\chromedriver.exe\", 0, options=options,keep_alive=True)\ndriver.get(\"http://192.168.7.7/ers-web/#/\")\ntime.sleep(2)\ndriver.find_element_by_xpath(\"//div/div[2]/form/div[1]/div/div[1]/input\").send_keys(\"kunming001\")\ndriver.find_element_by_xpath(\"//div/div[2]/form/div[2]/div/div[1]/input\").send_keys(\"keda123!\")\ndriver.find_element_by_css_selector(\"#keybtn\").click()\ndriver.implicitly_wait(10)\nall_handles = driver.window_handles\ndriver.switch_to.window(all_handles[-1])\ndriver.maximize_window()\ntime.sleep(3)\ndriver.refresh()\ntime.sleep(3)\n#print(driver.window_handles)\ni = 1\nwhile (i < 10000):\n\n try:\n ssh_client = paramiko.SSHClient()\n ssh_client.load_system_host_keys()\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh_client.connect('192.168.7.38', 22, 'root', 'kedacom888')\n std_in, std_out, std_err = ssh_client.exec_command('cd /opt/sipp-3.4.0/;sh uac_sendbye.sh 17751237537 1009 5080', get_pty=True)\n # 在command命令最后加上 get_pty=True,执行多条命令 的话用;隔开,另外所有命令都在一个大的单引号范围内引用\n std_in.write('PWD' + '\\n') # 执行输入命令,输入sudo命令的密码,会自动执行\n time.sleep(2)\n driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[3]/div/div[3]/div/div/div').click() # 点击接听\n for line in std_out:\n print(line.strip('\\n'))\n ssh_client.close()\n except:\n print(\"voice send fail!\")\n\n #电话录音文件\n driver.implicitly_wait(20)\n j = random.randint(10000,50000)\n\n driver.find_element_by_xpath(\"//div/form/div[1]/div/div/div/div[1]/div[1]/div[1]/input\").send_keys(\"昆明长水国际机场\")\n time.sleep(3)\n driver.find_element_by_xpath(\"//div/form/div[1]/div/div/div/div[1]/div[1]/div[2]/div[1]/div[1]/ul/li[1]/span[1]\").click() # 选择地址\n time.sleep(3)\n\n driver.find_element_by_xpath(\"//div/form/div[3]/div[2]/div/div/div/div[1]/span/span/i\").click() # 下拉\n time.sleep(3)\n driver.find_element_by_xpath(\"//div/div/div/div[2]/div/div[1]/ul/div/div[1]/div/span[2]\").click() # 易燃易爆\n time.sleep(3)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[2]/section/div/div[2]/div/form/div[4]/div[2]/span\").click() # 案件描述自动生成\n time.sleep(2)\n driver.find_element_by_xpath(\"//div/form/div[7]/div[1]/div/div/div/input\").send_keys(\"188565\" + str(j)) # 报警电话\n time.sleep(2)\n driver.find_element_by_xpath(\"//div/form/div[8]/div[1]/div/div/div/input\").send_keys(\"张国庆\" + str(j)) # 报警人姓名\n time.sleep(2)\n\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[3]/div/div/div/div/div[1]/div[1]/div/span[1]/span\").click() # 自定义调派\n time.sleep(2)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[3]/div/div/div/div/div[1]/div[2]/div[2]/div[3]/div/div[2]/div/ul[2]/li[1]/div[2]/span\").click() # 选择队伍\n time.sleep(2)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[2]/section/div/div[2]/div/div[1]/div/div[1]/span\").click() # 立案\n # driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[2]/section/div/div[2]/div/div[1]/div/div[2]/span\").click() #存草稿\n driver.implicitly_wait(30)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[1]/div/div[2]/div/div/div[2]/div/div[1]/div/div[1]/label\").click()#当前灾情\n time.sleep(3)\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div/div[2]/div/div[1]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]\").click() # 编辑\n time.sleep(3)\n driver.find_element_by_id(\"select\").click()\n time.sleep(3)\n driver.find_element_by_xpath(\"/html/body/div[last()]/div/div[1]/ul/li[last()]/span\").click() # 结案\n time.sleep(4)\n\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[1]/div/div/div[2]/ul/li[1]/span[2]\").click()\n time.sleep(3)\n print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\n print(i)\n print(\"cpu利用率: \" + str(get_cpu_info())+\"%\")\n print(get_memory_info())\n i = i + 1\nprint(\"Test Pass!\")\ndriver.quit()","sub_path":"UItest/Case/接处警2.0/语音+调度.py","file_name":"语音+调度.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"87443808","text":"from tkinter import *\n\nclass LoanCalculator:\n def __init__(self):\n window = Tk()\n window.title(\"대출 계산기\")\n\n Label(window, text = \"연이율\").grid(row = 1, column = 1, sticky = W)\n Label(window, text = \"대출년수\").grid(row = 2, column = 1, sticky = W)\n Label(window, text = \"대출금\").grid(row = 3, column = 1, sticky = W)\n Label(window, text = \"월상환금\").grid(row = 4, column = 1, sticky = W)\n Label(window, text = \"총상환금\").grid(row = 5, column = 1, sticky = W)\n\n self.annualInterestRateVar = StringVar()\n Entry(window, textvariable = self.annualInterestRateVar, justify = RIGHT).grid(row = 1, column = 2)\n self.numberOfYearsVar = StringVar()\n Entry(window, textvariable = self.numberOfYearsVar, justify = RIGHT).grid(row = 2, column = 2)\n self.loanAmountVar = StringVar()\n Entry(window, textvariable = self.loanAmountVar, justify = RIGHT).grid(row = 3, column = 2)\n self.monthlyPaymentVar = StringVar()\n lblMonthlyPayment = Label(window, textvariable = self.monthlyPaymentVar).grid(row = 4, column = 2, sticky = E)\n self.totalPatmentVar = StringVar()\n lblTotalPaymentVar = Label(window, textvariable = self.totalPatmentVar).grid(row = 5, column = 2, sticky = E)\n btComputePayment = Button(window, text = \"상환금 계산하기\", command = self.computePayment).grid(row = 6, column = 2, sticky = E)\n\n window.mainloop()\n\n def computePayment(self):\n monthlyPayment = self.getMonthlyPayment(\n float(self.laonAmount.get()), float(self.annualInterestRateVar.get()) / 1200, int(self.numberOfYearsVar.get()))\n self.monthlyPaymentVar.set(format(monthlyPayment, \"10.2f\"))\n totalPayment = float(self.monthlyPaymentVar.get()) * 12 * int(self.numberOfYearsVar.get())\n self.totalPatmentVar.set(format(totalPayment, \"10.2f\"))\n\n def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):\n monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate)**(numberOfYears * 12))\n return monthlyPayment\n\nLoanCalculator()","sub_path":"PythonProgramming/cp09/LoanCalculator.py","file_name":"LoanCalculator.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"343849167","text":"def levelOrder(self, root: TreeNode) -> List[List[int]]:\n \n # iterative solution is easier than recursion (bfs)\n stack = [root]\n levels = []\n while stack:\n nstack = stack\n stack = []\n level = []\n\n # add to new stack left and right of each cur node if it is not None\n while nstack:\n cur = nstack.pop(0)\n if cur is not None:\n level.append(cur.val)\n stack.append(cur.left)\n stack.append(cur.right)\n if level != []:\n levels.append(level)\n return levels","sub_path":"binarytreelevelordertraversal.py","file_name":"binarytreelevelordertraversal.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"122820310","text":"from __future__ import unicode_literals\n\nimport csv\nimport logging\n\nfrom reports.serialize import to_simple\nfrom django.utils.encoding import smart_text, force_text\n\n\nlogger = logging.getLogger(__name__)\n\nLIST_DELIMITER_CSV = ';'\n\ndef from_csv(csvfile, list_delimiter=LIST_DELIMITER_CSV, list_keys=None):\n '''\n Returns an in memory matrix (array of arrays) for the input file\n \n @param list_keys overrides nested list eval for column keys; no brackets '[]' are \n needed to denote these columns as list columns - however, to comply with \n the csv standard, they still have to be quoted (if list_delimiter=csv_delimiter)\n NOTES: \n - nested lists are denoted by brackets, i.e. '[]',\n - to escape use '\\[...' (i.e. when embedding a regex expression)\n TODO: version 2 - read from a stream\n '''\n reader = csv.reader(csvfile)\n return from_csv_iterate(reader, list_delimiter=list_delimiter, list_keys=list_keys)\n \ndef csv_generator(iterable, list_delimiter=LIST_DELIMITER_CSV, list_keys=None):\n list_keys = list_keys or []\n list_keys = list(list_keys)\n i = 0 \n for row in iterable:\n if i == 0:\n keys = [x for x in row]\n else:\n item = dict(zip(keys,row))\n for key in item.keys():\n val = item[key]\n if val and len(val)> 1:\n if val[0] == '\\\\' and val[1] == '[':\n # this could denote an escaped bracket, i.e. for a regex\n item[key] = val[1:]\n elif key in list_keys or val[0]=='[':\n # due to the simplicity of the serializer, above, any \n # quoted string is a nested list\n list_keys.append(key)\n item[key] = [\n x.strip() \n for x in val.strip('\"[]').split(list_delimiter)]\n yield item\n i += 1\n logger.debug('read in data, count: %d', i ) \n \ndef from_csv_iterate(iterable, list_delimiter=LIST_DELIMITER_CSV, list_keys=None):\n '''\n Returns an in memory array of dicts for the iterable, representing a \n csv-like input matrix.\n - the first row is interpreted as the dict keys, unless a list_keys param is \n specified \n '''\n list_keys = list_keys or []\n data_result = []\n i = 0\n keys = []\n list_keys = list(list_keys) \n logger.debug('list_keys: %r', list_keys)\n for row in iterable:\n if i == 0:\n keys = [x for x in row]\n else:\n item = dict(zip(keys,row))\n for key in item.keys():\n val = item[key]\n if val and len(val)> 1:\n if val[0] == '\\\\' and val[1] == '[':\n # this could denote an escaped bracket, i.e. for a regex\n item[key] = val[1:]\n elif key in list_keys or val[0]=='[':\n # due to the simplicity of the serializer, above, any \n # quoted string is a nested list\n list_keys.append(key)\n item[key] = []\n for x in val.strip('\"[]').split(list_delimiter):\n x = x.strip()\n if x:\n item[key].append(x)\n data_result.append(item)\n i += 1\n logger.debug('read in data, count: ' + str(len(data_result)) ) \n return data_result\n\ndef string_convert(val):\n return csv_convert(val, delimiter=',')\n\ndef dict_to_rows(_dict):\n ''' Utility that converts a dict into a table for writing to a spreadsheet\n '''\n \n logger.debug('_dict: %r', _dict)\n values = []\n if isinstance(_dict, dict):\n for key,val in _dict.items():\n for row in dict_to_rows(val):\n if not row:\n values.append([key,None])\n else:\n keyrow = [key]\n if isinstance(row, basestring):\n keyrow.append(row)\n else:\n keyrow.extend(row)\n values.append(keyrow)\n else:\n values = (csv_convert(_dict),)\n return values\n\ndef csv_convert(val, delimiter=LIST_DELIMITER_CSV, list_brackets='[]'):\n delimiter = delimiter + ' '\n if isinstance(val, (list,tuple)):\n if list_brackets:\n return ( list_brackets[0] \n + delimiter.join([smart_text(to_simple(x)) for x in val]) \n + list_brackets[1] )\n else: \n return delimiter.join([smart_text(to_simple(x)) for x in val]) \n elif val != None:\n if type(val) == bool:\n if val:\n return 'TRUE'\n else:\n return 'FALSE'\n else:\n return force_text(to_simple(val))\n else:\n return None\n","sub_path":"reports/serialize/csvutils.py","file_name":"csvutils.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"228307798","text":"import boto3\nimport json\n\nregion = 'us-west-1'\nclient = boto3.client('config', region)\nssm = boto3.client('ssm', region)\namis = ssm.get_parameter(Name=\"/GoldenAMI/latest\")['Parameter']['Value']\nprint(type(amis))\nupdate_ami = {}\nupdate_ami['amiIds'] = amis\njson_update_ami = json.dumps(update_ami)\nprint(json_update_ami)\n\nresponse = client.put_config_rule(\n ConfigRule={\n 'ConfigRuleArn': 'arn:aws:config:us-west-1:811284348584:config-rule/config-rule-suojze',\n 'Source': {\n 'Owner': 'AWS',\n 'SourceIdentifier': 'APPROVED_AMIS_BY_ID',\n },\n 'InputParameters': json_update_ami\n # 'MaximumExecutionFrequency': 'One_Hour'|'Three_Hours'|'Six_Hours'|'Twelve_Hours'|'TwentyFour_Hours',\n },\n)","sub_path":"testbed/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"15947549","text":"\"\"\"\nA perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.\n\nA number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\nAs 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.\n\nFind the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\n\n\"\"\"\n\nimport math\n\n# Improved sum of divisor function\ndef sum_of_divisor(n):\n sum = 1\n p = 2\n while p*p <= n and n > 1:\n if n % p == 0:\n j = p * p\n n //= p\n while n % p == 0:\n j *= p\n n //=p\n sum *= (j - 1)\n sum //= (p - 1)\n if p == 2:\n p = 3 \n else:\n p += 2\n if n > 1:\n sum = sum * (n + 1)\n return sum\n\n# Sum of proper divisor (proper means with out itself :-))\n# as decribed in the solution manual\ndef sum_of_proper_divisors(n):\n return sum_of_divisor(n) - n\n\n\ndef main():\n # Bruteforce solution\n\n # Step 1: Calculate all abundanten number less or equal to 28123\n abundanten_numbers = []\n for i in range(1, 28123 + 1):\n if sum_of_proper_divisors(i) > i: \n abundanten_numbers.append(i)\n\n\n # Step 2: Cross out all number which are sums of abundant numbers\n is_no_abundant_sum = [True] * (28123+1)\n\n for i in range(0, len(abundanten_numbers)):\n for j in range(0, len(abundanten_numbers)):\n if (abundanten_numbers[i] + abundanten_numbers[j]) <= 28123:\n is_no_abundant_sum[abundanten_numbers[i] + abundanten_numbers[j]] = False\n\n # Step 3: Sum up all not crossed numbers \n sum = 0\n for i in range(1,28123+1):\n if is_no_abundant_sum[i] == True:\n sum += i\n\n print(sum)\n\nif __name__ == '__main__':\n main() ","sub_path":"Python/23Non-abundantSums.py","file_name":"23Non-abundantSums.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"493887066","text":"from rlberry.envs.classic_control import MountainCar\nfrom rlberry.wrappers import DiscretizeStateWrapper\n\ncont_env = MountainCar()\nenv = DiscretizeStateWrapper(cont_env, 10) # 10 bins per dimension\n\nprint(cont_env.observation_space)\nprint(env.observation_space)\nprint(\"reset in discrete environment gives initial state = \", env.reset())\n\nenv.enable_rendering()\nfor tt in range(20):\n next_s, _, _, _ = env.step(env.action_space.sample())\n env.sample(54, 1)\nenv.render()\n","sub_path":"examples/demo_discretize_state.py","file_name":"demo_discretize_state.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"480026274","text":"from packages.core.utils.singleton import SingletonClass as Singleton\nfrom packages.core.utils.app_loop import AppLoop\n\nimport itertools\nimport json\nimport asyncio\nimport re\nimport subprocess\nimport aiohttp\nimport logging\nimport sys\nimport concurrent\nfrom random import randint\n\nclass WebClient(metaclass=Singleton):\n\n def __init__(self, *args, **kwargs):\n self.all_sessions = None\n self.lock = asyncio.Lock()\n # faster\n # http://azenv.net/\n # http://httpheader.net/azenv.php\n # http://proxyjudge.us/azenv.php\n # http://www.proxyfire.net/fastenv\n\n # medium\n # http://httpbin.org/get?show_env\n # http://www.sbjudge3.com/azenv.php\n # https://httpbin.org/get?show_env\n\n # > 0.2 sec\n # http://www.proxy-listen.de/azenv.php\n # https://www.proxy-listen.de/azenv.php\n # http://www.sbjudge2.com/azenv.php\n # http://www.proxyjudge.info/azenv.php\n\n # ?\n # https://api.ipify.org?format=json\n # http://ip-api.com/json\n # http://httpbin.org/ip\n\n self.url_judges = (\"http://azenv.net/\", \"http://httpheader.net/azenv.php\")\n\n async def internet_check(self, session, skip=False):\n if skip:\n public_ip = session._connector._local_addr[0]\n self.ip_publics.append(public_ip)\n return session\n for url_judge in self.url_judges:\n async with session.get(url_judge, timeout=20) as resp:\n if resp:\n resp = await resp.text()\n public_ip = re.findall(r\"\\d+\\.\\d+\\.\\d+\\.\\d+\", resp)\n\n if public_ip not in self.ip_publics:\n self.ip_publics.append(public_ip)\n return session\n logging.getLogger('log_print').error(\n f\"internet_check error con: url_judge: {url_judge}, {session._connector._local_addr[0]}\"\n )\n\n await session.close()\n return\n\n async def starts(self):\n try:\n cmd = r\"ip -o -4 addr show|grep ' en\\| eth\\| wl'|awk '{print $4}'|cut -d/ -f1\" # deja solo las redes : \"enp|eth\" sin vpn sin docker\n ps = subprocess.Popen(\n cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n ips = ps.communicate()[0].decode().strip().split()\n except Exception as e: # si es windows\n logging.getLogger('log_print').error(f\"Error, {e}, es windows?\")\n ips = [\"0.0.0.0\"]\n if not ips:\n raise Exception(\"no hay ips de salida disponibles\")\n\n self.sessions = []\n self.ip_publics = []\n coros = []\n for ip in ips:\n conn = aiohttp.connector.TCPConnector(\n local_addr=(ip, 0), limit=300, loop=AppLoop().get_loop()\n )\n session = AutoRetrySession(\n connector=conn,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (compatible MSIE 9.0 Windows NT 6.1 Trident/5.0)\"\n },\n )\n coros.append(self.internet_check(session, skip=len(ips) > 10))\n\n self.sessions = filter(None, await asyncio.gather(*coros))\n if len(self.ip_publics) > 0:\n logging.getLogger(\"log_print\").info(\n f\"Usando {len(self.ip_publics)} Ips_rotativas\"\n )\n else:\n raise Exception(\n f\"Error, no hay ips disponibles con internet testeado con: {self.url_judges}\"\n )\n exit()\n\n self.all_sessions = self.get_all_sessions()\n\n async def do_request(\n self,\n uri:str,\n rq_type=\"get\",\n payload=dict(),\n params=None,\n return_data=\"json\",\n headers=dict(),\n cookies=dict(),\n **kwargs,\n ):\n if payload:\n payload = json.dumps(payload)\n\n max_reintents = 30\n i = 0\n while i < max_reintents: # max_reintents por si no recibe un Json\n i += 1\n async with (await self.get_session()).__getattribute__(rq_type)(\n uri,\n data=payload,\n params=params,\n headers=headers,\n verify_ssl=False,\n cookies=cookies\n ) as resp:\n if not resp:\n logging.getLogger(\"log_print\").error(\n f\"not resp {rq_type} {uri} {payload} {params}\"\n )\n return\n try:\n res_json = {}\n if return_data == \"json\":\n if resp.content_type == \"text/html\":\n logging.getLogger(\"log_print\").error(\n f\"{rq_type} {resp.status} {uri} \\\n error jot json response: {await resp.text()} \"\n )\n return\n\n res_json = await resp.json()\n if isinstance(res_json, (list, dict)):\n final_res = res_json\n elif return_data == \"text\":\n res_text = await resp.text()\n if res_text:\n final_res = res_text\n elif return_data is None:\n final_res = None\n\n if resp.status in (200, 201, 206):\n if isinstance(final_res, list) and any(\n 1 for i in final_res if i.get(\"code\") == 500 or i.get(\"status\") == 500\n ):\n logging.getLogger(\"log_print\").debug(\n f\"{rq_type}, {resp.status}, {resp.url}, some one with code:500\"\n )\n continue\n return final_res\n elif resp.status in (403,): # 403 = Forbidden (meli day limit)\n return final_res\n elif resp.status in (\n 429,\n 500,\n 501,\n 502,\n 409,\n 504,\n ): # 504=not found(temporaly), 409 =optimistic locking, 429 = toomany request\n if 0 < i < 5:\n logging.getLogger(\"log_print\").debug(\n f\"{rq_type} {resp.status} retrying No-{i} , too quikly? {0.2 * i}\"\n )\n elif 5 < i:\n logging.getLogger(\"log_print\").info(\n f\"{rq_type} {resp.status} retrying No-{i} , too quikly? {0.2 * i}\"\n )\n await asyncio.sleep(0.2 * i)\n continue\n # elif resp.status == 401: # expired_token\n # print(\n # f\"{rq_type} status 401, expired_token, forcing to refresh, {resp.url}\"\n # )\n # token = await self.get_token(force=True)\n # params[\"access_token\"] = token\n # max_reintents /= 3\n # continue\n elif resp.status in (404, 400, 401) and isinstance(res_json, dict):\n logging.getLogger(\"log_print\").debug(\n f\"{rq_type}, {resp.status}, {resp.url}, {res_json.get('message')}, {res_json.get('cause')}\"\n )\n return final_res\n else:\n if res_json:\n logging.getLogger(\"log_print\").info(\n f\"{rq_type}, {resp.status}, {resp.url}, -{await resp.text()}-\"\n )\n return final_res\n except Exception as e:\n logging.getLogger(\"log\").error(\n f\"Error on {rq_type} return_data:{return_data} {uri}, {e}\"\n )\n await asyncio.sleep(0.5)\n continue\n\n async def get(\n self, uri, payload={}, params=None, return_data=\"json\", headers={}, **kwargs\n ):\n return await self.do_request(\n rq_type=\"get\",\n uri=uri,\n payload=payload,\n params=params,\n return_data=return_data,\n headers=headers,\n **kwargs,\n )\n\n async def post(\n self, uri, payload={}, params=None, return_data=\"json\", headers={}, **kwargs\n ):\n return await self.do_request(\n rq_type=\"post\",\n uri=uri,\n payload=payload,\n params=params,\n return_data=return_data,\n headers=headers,\n **kwargs,\n )\n\n async def put(\n self, uri, payload={}, params=None, return_data=\"json\", headers={}, **kwargs\n ):\n return await self.do_request(\n rq_type=\"put\",\n uri=uri,\n payload=payload,\n params=params,\n return_data=return_data,\n headers=headers,\n **kwargs,\n )\n\n async def delete(\n self, uri, payload={}, params=None, return_data=\"json\", headers={}, **kwargs\n ):\n return await self.do_request(\n rq_type=\"delete\",\n uri=uri,\n payload=payload,\n params=params,\n return_data=return_data,\n headers=headers,\n **kwargs,\n )\n\n async def get_session(self):\n with await self.lock:\n if not self.all_sessions:\n await self.starts()\n return self.session\n\n @property\n def session(self):\n return next(self.all_sessions)\n\n def get_all_sessions(self):\n positions = itertools.cycle(self.sessions)\n for session in itertools.islice(\n positions, randint(0, len(self.ip_publics)), None\n ):\n yield session\n\nasync def retry_if_disconect(function, *args, **kwargs):\n for i in range(1, 16):\n try:\n return await function(*args, **kwargs)\n except asyncio.TimeoutError: # do not retry if timeout\n error = f\"{function.__name__}:error Timeout = {args}\"\n logging.getLogger(\"log_print\").debug(error)\n return\n except (\n aiohttp.client_exceptions.ClientConnectorError,\n aiohttp.client_exceptions.ServerDisconnectedError,\n aiohttp.client_exceptions.ClientResponseError,\n concurrent.futures.CancelledError,\n ):\n local_ip = function.__self__._connector._local_addr[0]\n logging.getLogger(\"log_print\").warning(\n f\"{function.__name__}: AutoRetrySession sleep({round(0.1 * i, 2)}),{sys.exc_info()[0]}, {args} {local_ip}\"\n )\n await asyncio.sleep(round(0.1 * i, 2))\n except aiohttp.client_exceptions.InvalidURL:\n error = f\"error InvalidURL = {args}\"\n raise Exception(error)\n except Exception as e:\n logging.getLogger('log_print').error(f\"Unexpected error ({e}):\", sys.exc_info()[0])\n\nclass GetRetry:\n def __init__(self, function, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n self.resp = None\n self.function = function\n\n async def __aenter__(self):\n self.resp = await retry_if_disconect(self.function, *self.args, **self.kwargs)\n return self.resp\n\n async def __aexit__(self, exc_type, exc, tb):\n if self.resp:\n await self.resp.release()\n\nclass AutoRetrySession(aiohttp.ClientSession):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def get(self, *args, **kwargs):\n return GetRetry(super().get, *args, **kwargs)\n\n def post(self, *args, **kwargs):\n return GetRetry(super().post, *args, **kwargs)\n\n def put(self, *args, **kwargs):\n return GetRetry(super().put, *args, **kwargs)\n\n def delete(self, *args, **kwargs):\n return GetRetry(super().delete, *args, **kwargs)","sub_path":"packages/core/utils/web_client.py","file_name":"web_client.py","file_ext":"py","file_size_in_byte":12602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"164200274","text":"\"\"\"\n Colorear una serie de cuadrados de distintos colores, cada uno dentro del otro.\n\"\"\"\n\nimport turtle\nfrom random import randint\nfrom math import hypot\n\ns = turtle.Screen()\nt = turtle.Turtle()\ns.bgcolor('black')\nt.hideturtle()\nt.speed(0)\n\n\ndef color_generator():\n \"\"\"Genera un color hexadecimal aleatorio\"\"\"\n return '#%02X%02X%02X' % (randint(0, 255), randint(0, 255), randint(0, 255))\n\n\ndef poligono(vertices, lado):\n \"\"\"Pinta un polígono regular para un lado y número de lados dado por el usuario\"\"\"\n originhead = t.heading()\n t.setheading(90)\n t.down()\n for i in range(vertices * 2):\n t.forward(lado // 2)\n if i % 2 == 0:\n t.right(360 / vertices)\n t.up()\n t.setheading(originhead)\n\n\ndef cuadrados_coloreados(min_size, num_cuadrados):\n \"\"\"Pinta una serie de cuadrados concéntricos de distinto color, cada uno más pequeño que el anterior\"\"\"\n for i in range(num_cuadrados, 1, -1):\n t.up()\n t.setpos(0, 0)\n apotema = min_size * (i * 0.5)\n lado = apotema // 2\n print(\"Apotema \" + str(apotema) + \" - Lado \" + str(lado))\n t.setpos(-lado // 2, 0)\n t.begin_fill()\n t.fillcolor(color_generator())\n poligono(4, lado)\n t.end_fill()\n\n\ncuadrados_coloreados(150, 55)\n\nturtle.done()\n","sub_path":"Ejercicios/SeguTrim/Ejercicio7/Subpaq2/Ejercicio4.py","file_name":"Ejercicio4.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"578818917","text":"import re\nfrom pkg_resources import iter_entry_points\n\n\ndef resolve_uri(uri):\n \"\"\"\n Returns a tuple, (factory, dbkw) where factory is a no-arg callable which\n returns a storage matching the spec defined in the uri. dbkw is a dict of\n keyword arguments that may be passed to ZODB.DB.DB.\n \"\"\"\n factory, dbkw = _resolve_uri(uri)\n return factory, _get_dbkw(dbkw)\n\n# _resolve_uri serves resolve_uri: it returns factory and original raw dbkw.\ndef _resolve_uri(uri):\n scheme = uri[:uri.find(':')]\n for ep in iter_entry_points('zodburi.resolvers'):\n if ep.name == scheme:\n resolver = ep.load()\n factory, dbkw = resolver(uri)\n return factory, dbkw\n else:\n raise KeyError('No resolver found for uri: %s' % uri)\n\nconnection_parameters = '''\n pool_size pool_timeout cache_size cache_size_bytes\n historical_pool_size historical_cache_size historical_cache_size_bytes\n historical_timeout large_record_size\n '''.strip().split()\n\nbytes_parameters = (\n 'cache_size_bytes', 'historical_cache_size_bytes', 'large_record_size')\n\nparameters = dict(database_name = 'database_name')\nfor parameter in connection_parameters:\n parameters['connection_' + parameter] = parameter\n\nhas_units = re.compile(r'\\s*(\\d+)\\s*([kmg])b\\s*$').match\nunits = dict(k=1<<10, m=1<<20, g=1<<30)\ndef _parse_bytes(s):\n m = has_units(s.lower())\n if m:\n v, uname = m.group(1, 2)\n return int(v) * units[uname]\n else:\n return int(s)\n\ndef _get_dbkw(kw):\n dbkw = {\n 'cache_size': 10000,\n 'pool_size': 7,\n 'database_name': 'unnamed',\n }\n for parameter in parameters:\n if parameter in kw:\n v = kw.pop(parameter)\n if parameter.startswith('connection_'):\n if not isinstance(v, int):\n if parameters[parameter] in bytes_parameters:\n v = _parse_bytes(v)\n else:\n v = int(v)\n dbkw[parameters[parameter]] = v\n\n if kw:\n raise KeyError('Unrecognized database keyword(s): %s' % ', '.join(kw))\n\n return dbkw\n","sub_path":"zodburi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"619664506","text":"import json\nimport re\n\n\ndef get_business_id_to_categories_dict():\n business_id_to_categories = {}\n with open('../data/yelp/yelp_academic_dataset_business.json', encoding='utf-8') as f:\n for line in f:\n old_dict = json.loads(line)\n business_id_to_categories[old_dict['business_id']] = old_dict['categories']\n return business_id_to_categories\n\n\ndef save_to_json(business_id_to_categories):\n with open('../data/yelp/review_and_categories.json', 'w', encoding='utf-8') as f1:\n with open('../data/yelp/yelp_academic_dataset_review.json', encoding='utf-8') as f2:\n for line in f2:\n old_dict = json.loads(line)\n\n text = re.sub('[\\n ]+', ' ', old_dict['text'])\n categories = business_id_to_categories[old_dict['business_id']]\n\n new_dict = {\n # 'business_id': old_dict['business_id'],\n 'text': text,\n 'categories': categories\n }\n f1.write(json.dumps(new_dict) + '\\n')\n\n\ndef save_to_txt(business_id_to_categories):\n with open('../data/yelp/reviews.txt', 'w', encoding='utf-8') as f1:\n with open('../data/yelp/labels.txt', 'w', encoding='utf-8') as f2:\n with open('../data/yelp/yelp_academic_dataset_review.json', encoding='utf-8') as f3:\n for line in f3:\n old_dict = json.loads(line)\n\n text = re.sub('[\\n ]+', ' ', old_dict['text'])\n categories = business_id_to_categories[old_dict['business_id']]\n categories = '' if categories is None else categories\n f1.write(text + '\\n')\n f2.write(categories + '\\n')\n\n\ndef parse_json():\n # business_id_to_categories = get_business_id_to_categories_dict()\n # save_to_txt(business_id_to_categories)\n\n categories_set = set()\n with open('../data/yelp/labels.txt', encoding='utf-8') as f:\n for line in f:\n if line == '\\n':\n continue\n for category in line.strip().split(', '):\n categories_set.add(category)\n\n with open('../data/yelp/categories.txt', 'w', encoding='utf-8') as f:\n for category in categories_set:\n f.write(category + '\\n')\n\n with open('sss.txt', 'w', encoding='utf-8') as f:\n f.write(str(categories_set))\n\n\ndef get_sorted_category_count():\n category_count = {}\n\n with open('../data/yelp/categories.txt', encoding='utf-8') as f:\n for line in f:\n category_count[line.strip()] = 0\n\n no_label_count = 0\n with open('../data/yelp/labels.txt', encoding='utf-8') as f:\n for line in f:\n if line == '\\n':\n no_label_count += 1\n continue\n for category in line.strip().split(', '):\n category_count[category] += 1\n\n print('no_label_count: ' + str(no_label_count) + '\\tremoved: 0')\n\n category_count = sorted(category_count.items(), key=lambda kv: kv[1], reverse=True)\n return category_count\n\n\ndef count_removed_docs(category_count):\n for keep_category_count in [10, 20]:\n category_count_set = set([cc[0] for cc in category_count[:10]])\n no_label_count = 0\n with open('../data/yelp/labels.txt', encoding='utf-8') as f:\n for i, line in enumerate(f):\n if line == '\\n':\n no_label_count += 1\n continue\n no_label = True\n for category in line.strip().split(', '):\n if category in category_count_set:\n no_label = False\n break\n\n if no_label:\n no_label_count += 1\n print('no_label_count: ' + str(no_label_count) + '\\tkeep category count: ' + str(keep_category_count))\n\n\ndef remove_docs(category_count, keep_category_count):\n category_count_set = set([cc[0] for cc in category_count[:keep_category_count]])\n no_label_count = 0\n with open('../data/yelp/new_reviews.txt', 'w', encoding='utf-8') as f_new_reviews:\n with open('../data/yelp/new_labels.txt', 'w', encoding='utf-8') as f_new_labels:\n with open('../data/yelp/reviews.txt', encoding='utf-8') as f_reviews:\n with open('../data/yelp/labels.txt', encoding='utf-8') as f_labels:\n for i, (review, label) in enumerate(zip(f_reviews, f_labels)):\n if label == '\\n':\n no_label_count += 1\n continue\n\n no_label = True\n new_label = []\n\n for category in label.strip().split(', '):\n if category in category_count_set:\n new_label.append(category)\n no_label = False\n\n if no_label:\n no_label_count += 1\n continue\n\n # only keep docs with greater than or equal to 4 categories\n if len(new_label) < 4:\n continue\n\n f_new_reviews.write(review)\n f_new_labels.write(', '.join(new_label) + '\\n')\n\n\ndef main():\n category_count = get_sorted_category_count()\n\n dict1 = {}\n for i, cc in enumerate(category_count):\n dict1[cc[0]] = {'id': i, 'count': cc[1]}\n\n with open('ffff.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(dict1))\n\n with open('../data/yelp/labels1.txt', 'w', encoding='utf-8') as f2:\n with open('../data/yelp/labels.txt', encoding='utf-8') as f:\n for i, line in enumerate(f):\n if line == '\\n':\n continue\n prefix = ''\n for category in line.strip().split(', '):\n f2.write(prefix + str(dict1[category]['id']))\n prefix = ', '\n f2.write('\\n')\n\n remove_docs(category_count, 10)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/preprocess/yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":6130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"286156374","text":"import cv2\nfrom model import NN\nimport numpy as np\nimport torch\n\ncap = cv2.VideoCapture(0)\ni = 0 \nclassify = 1 \nlabels =[] \nModel = NN(batch_size = 1)\nModel.load_state_dict(torch.load(\"1\"))\nModel.eval()\ntardict = {1 : 'Face Detected' , 0 : 'Undetected' }\n\nwhile True:\n i += 1\n ret , frame = cap.read()\n gray = cv2.cvtColor(frame , cv2.COLOR_RGB2GRAY)\n gray = cv2.GaussianBlur(gray, (15,15), 0)\n cv2.imshow('feed' , frame)\n gray = torch.from_numpy(gray).view(1 , 1, 480 , 640).float()\n output = torch.round(Model.forward(gray))\n output = output.item()\n print (tardict[output])\n if output != 0:\n input()\n if cv2.waitKey(1) & 0xFF == ord('q') :\n break \n \n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"553217926","text":"#!python\n'''\noptimization algorithms\n'''\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport sys\nimport numpy as np\n\n\nfrom itertools import chain,repeat\n\ndef polynomial(w,x):\n return np.polyval(w[::-1],x)\n \ndef cost(w,x,y,N):\n result=0;\n for n in range(0,N):\n val=polynomial(w,x[n])-y[n] \n val=val*val\n result=result+val\n return (0.5*result/N) \n\ndef gradient(w,x,y,N):\n grad=w*0.\n I=len(w)-1\n pw = range(I+1)\n for n in range(0,N):\n #print(\"n : \" , N)\n val=polynomial(w,x[n])-y[n]\n phi=np.power(x[n],pw)\n grad=grad+phi*val\n #print(\"final\")\n return grad/N \n \ndef step(w,x,y,g,N):\n alpha=0.2\n return alpha\n\n#Algoritmo - Procura de Armijo com backtracking\n\n\n# Nt - Numero total de registos usados para treino\n# #Nb - Numero de registos que vão ser usadas para a amostra - este valor está a ser calculado\n # o Nb vai ser calculado com Nb = ...ceil(T**iterador)\n\n\ndef backtracking(w,xt,yt,Gb,Nt):\n\n #Initialize\n #alpha = alpha_bar\n\n alpha=1\n\n #alpha Gradiente Transposto * gradiente\n #gradiente total = gT\n Gt = gradient(w,xt,yt,Nt)\n\n #Mudar para produto interno\n #Gt*Gb\n\n\n inner_product = np.inner(Gt, np.transpose(Gb))\n cost_k = cost(w,xt,yt,Nt)\n\n w_aux = w\n while cost(w_aux,xt,yt,Nt) > (cost_k - alpha * inner_product):\n alpha = alpha/2\n\n if alpha * np.linalg.norm(Gb) <= 1.e-8 :\n break\n\n w_aux = w - alpha * gradient(w,xt,yt,Nb)\n\n return alpha\n\n\n\n\ndef get_data(xt,yt,Nt,Nb):\n xb=[];yb=[];\n for n in range(0,Nb):\n pos=math.ceil(np.random.rand()*(Nt-1))\n xb.append(xt[pos])\n yb.append(yt[pos])\n return xb,yb\n\n# In this function we need to select the records sequentially and not in a random way.\ndef ncycles(iterable, n):\n return chain.from_iterable(repeat(tuple(iterable), n))\n\ndef get_data_cycle(xt, yt, position, Nb):\n size = len(xt)\n cicle_step = (size % (position+Nb)) + 1\n cicle_list_x = list(ncycles(xt, cicle_step))\n cicle_list_y = list(ncycles(yt, cicle_step))\n return cicle_list_x[position:(position+Nb)], cicle_list_y[position:(position+Nb)], (position+Nb)\n\n\n\ndef get_data_sequencial(xt,yt,Nt,Nb,posicao_actual,posicao_actual_w_Nb):\n xb=[];yb=[];\n ok = True\n\n while ok:\n for n in range(0,Nb):\n pos = n + posicao_actual\n #posicao_actual_w_Nb =posicao_actual_w_Nb-1\n Nb =Nb -1\n if pos == Nt-1:\n #print(\"-----------\")\n #print(\"reiniciou porque pos = \", pos)\n #print(\"Nb está em = \", Nb)\n #print(\"posicao_actual_w_Nb está em = \",posicao_actual_w_Nb)\n #print(\"-----------\")\n posicao_actual = 1\n n=0\n pos = n + posicao_actual\n break # break here\n\n #print(\"pos está em = \",pos)\n xb.append(xt[pos])\n yb.append(yt[pos])\n return xb,yb\n\n if(Nb==0): ok=False;\n\n\n#=========== MAIN CODE ===============\n# read the data file\nx=[];y=[]; N=0\nwith open('P5-large_yes.csv', 'r') as file:\n reader = csv.reader(file)\n for u in reader:\n x=np.append(x,float(u[0]))\n y=np.append(y,float(u[1]))\n N=N+1\nNt=math.floor(N*0.8)\nxt=x[0:Nt] \nyt=y[0:Nt] \nxv=x[Nt:N] \nyv=y[Nt:N] \nI=5;\n#Nb=math.floor(Nt*0.1)\nNb=1\n \n\n'''\nfig = plt.figure()\nplt.plot(x,y,'ro')\ns = np.linspace(0, 1,100, endpoint = True)\nr = 1/5-1/2*(s)+(s*s)-2/3*(s*s*s)+4*(s*s*s*s)-5*(s*s*s*s*s)\nplt.plot(s, r, '-g', label=r'$exato$')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Polynomial Curve')\nplt.show()\n'''\n\nw=np.array([1]*(I+1));\n#w=np.array([1/5,-1/2,1,-2/3,4,-5])\n#xb,yb=get_data(xt,yt,Nt,Nb)\n#print(cost(w,xb,yb,Nb))\n#print(gradient(w,xb,yb,Nb))\n\n\nok=True; iter=0\n\n#posicao actual que vai ser utlizada para verificar em que po\nposicao_actual = 0\n\nwhile ok:\n # O dataset tem de ser modificado e o que teremos de fazer é o seguinte\n # Calcular o T random entre 1 e 2\n import random\n Theta = random.uniform(1, 2)\n\n # O nosso Nb vai ser calculado de um modo dinamico (nisso consiste este metodo de mini-batch dinamico)\n # o Nb vai ser calculado com Nb = ...ceil(T**iterador)\n #Return the ceiling of x as a float, the smallest integer value greater than or equal to x.\n Nb = math.ceil(Theta**iter)\n\n # outro dado imporntante é que o Nb terá de ser sempre o minimo entre o calcuo\n # Nb = min(Nb e o conjunto total dos dados)\n # Nt - Numero total de registos usados para treino\n Nb=min(Nb,Nt)\n\n\n posicao_actual_w_Nb= Nb + posicao_actual\n\n\n\n #print(posicao_actual_w_Nb)\n #xb,yb = get_data_sequencial(xt,yt,Nt,Nb,posicao_actual,posicao_actual_w_Nb)\n\n xb, yb, posicao_actual = get_data_cycle(xt,yt, posicao_actual,Nb)\n\n #xb,yb=get_data(xt,yt,Nt,Nb)\n\n # calculo da direcao estocastica do subconjunto\n Gb=gradient(w,xb,yb,Nb)\n\n\n #alpha=step(w,xb,yb,g,Nb)\n\n\n #Nt - Numero total de registos usados para treino\n alpha=backtracking(w,xt,yt,Gb,Nt)\n\n w=w-alpha*Gb\n\n gT=gradient(w,xt,yt,Nt)\n Norm_gT=np.linalg.norm(gT)\n\n #print(w)\n #print(g)\n # paragem quando o iterador chegar ao valor 20000\n if(iter>5000): ok=False;\n # Imprime-se o custo\n print(iter,cost(w,xb,yb,Nb))\n print(\"Norma Gt : \",Norm_gT)\n\n # Funcao de paragem, é para ser utilizada\n #1 * 10 ^ -8, or .00000001\n\n if(Norm_gT<1.e-8): ok=False\n\n iter=iter+1\n\nprint(\"======================================\")\nprint(\"I={:d}\".format(I))\nprint(\"coefficient\",w)\nprint(\"Nt - numero total de registos usados para treino : \",Nt)\nprint(\"in error sample {:e}\".format(cost(w,xt,yt,Nt)))\nprint(\"out error sample {:e}\".format(cost(w,xv,yv,N-Nt)))\n\nfig = plt.figure()\nplt.plot(x,y,'ro')\ns = np.linspace(0, 1,100, endpoint = True)\nr = w[0]+w[1]*(s)+w[2]*(s*s)+w[3]*(s*s*s)+w[4]*(s*s*s*s)+w[5]*(s*s*s*s*s)\nplt.plot(s, r, '-b', linewidth=3,label=r'$exato$')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Polynomial Curve')\nplt.show()\nprint('bye')\n","sub_path":"material_laboratorio4/T4-amostragem_dinamica/optim_amostragem_dinamica.py","file_name":"optim_amostragem_dinamica.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"209875360","text":"import torch\nfrom torch import nn\n\n\nclass ONet(nn.Module):\n def __init__(self, pretrained=False):\n super(ONet, self).__init__()\n # input: 48x48\n self.conv1 = nn.Conv2d(3, 32, kernel_size=3) # 46x46\n self.bn1 = nn.BatchNorm2d(32)\n self.prelu1 = nn.PReLU(32)\n self.maxpool1 = nn.MaxPool2d(3, 2, ceil_mode=True) # 23x23\n self.conv2 = nn.Conv2d(32, 64, kernel_size=3) # 21x21\n self.bn2 = nn.BatchNorm2d(64)\n self.prelu2 = nn.PReLU(64)\n self.maxpool2 = nn.MaxPool2d(3, 2, ceil_mode=True) # 10x10\n self.conv3 = nn.Conv2d(64, 64, kernel_size=3) # 8x8\n self.bn3 = nn.BatchNorm2d(64)\n self.prelu3 = nn.PReLU(64)\n self.maxpool3 = nn.MaxPool2d(2, 2, ceil_mode=True) # 4x4\n self.conv4 = nn.Conv2d(64, 128, kernel_size=2) # 3x3\n self.bn4 = nn.BatchNorm2d(128)\n self.prelu4 = nn.PReLU(128)\n self.dense5 = nn.Linear(3*3*128, 256)\n self.prelu5 = nn.PReLU(256)\n self.dense6_1 = nn.Linear(256, 1)\n self.sigmoid6_1 = nn.Sigmoid()\n self.dense6_2 = nn.Linear(256, 4)\n self.dense6_3 = nn.Linear(256, 10)\n\n # self.training = False\n #\n if pretrained:\n state_dict_path = 'weights/onet.pth'\n state_dict = torch.load(state_dict_path)\n self.load_state_dict(state_dict)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.prelu1(x)\n x = self.maxpool1(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.prelu2(x)\n x = self.maxpool2(x)\n x = self.conv3(x)\n x = self.bn3(x)\n x = self.prelu3(x)\n x = self.maxpool3(x)\n x = self.conv4(x)\n x = self.bn4(x)\n x = self.prelu4(x)\n x = x.permute(0, 3, 2, 1).contiguous()\n x = self.dense5(x.view(x.shape[0], -1))\n x = self.prelu5(x)\n c = self.dense6_1(x)\n c = self.sigmoid6_1(c)\n b = self.dense6_2(x)\n l = self.dense6_3(x)\n return c, b, l\n\n\nif __name__ == '__main__':\n a = torch.rand(128, 3, 48, 48)\n net = ONet()\n conf, reg, mark = net(a)\n print(conf.shape)\n print(reg.shape)\n print(mark.shape)\n\n","sub_path":"modeling/layers/ONet.py","file_name":"ONet.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"377581377","text":"#Chef has opened his new restaurant and made the first meal free for everyone!\n#\n#You want to try the new restaurant, but since it is offering free meals, many people are coming and a huge queue has formed. Currently (at time T=0), there are M people waiting in the queue. You also know that there are N more people coming; let's denote the time when the i-th person stands at the back of the queue by Ai. You noticed that each exactly L seconds, one place in the restaurant will become vacant and the person currently at the front of the queue takes it, i.e. at time T=L, one person enters, then at time T=2L, another person enters and so on.\n#\n#You do not like to wait in queues, so you want to choose the time when you stand at the back of the queue in such a way that the time between this moment and the moment when you enter the restaurant is minimum possible. Assume that if you decide to stand at the back of the queue at the same moment as some other person, you will stand before them in the queue (closer to the restaurant). Also, you have to stand at the back of the queue no later than in the K-th second, otherwise you will arrive at home late.\n#\n#What is the minimum time you have to spend standing in the queue?\n\nfor y in range(int(input())):\n n,m,k,l=map(int, input().split())\n arr=list(map(int, input().split()))\n arr=sorted(arr)\n mini=(m+1)*l-(1%l)\n for i in range(n):\n s=m-(arr[i]//l)+i\n s=(s+1)*l-(arr[i]%l)\n if s\n\n\n\"\"\"Tests for assessment service handle.\"\"\"\nimport random\n\nimport ddt\n\nfrom ggrc.models import all_models\nfrom integration.ggrc import TestCase\nfrom integration.ggrc.query_helper import WithQueryApi\nfrom integration.ggrc.models import factories\nfrom integration.ggrc.api_helper import Api\nfrom integration.ggrc.generator import ObjectGenerator\n\n\n@ddt.ddt\nclass TestCollection(TestCase, WithQueryApi):\n\n \"\"\"Test for collection assessment objects.\"\"\"\n\n def setUp(self):\n super(TestCollection, self).setUp()\n self.client.get(\"/login\")\n self.clear_data()\n self.api = Api()\n self.generator = ObjectGenerator()\n\n @ddt.data(True, False)\n def test_order_by_test(self, desc):\n \"\"\"Order by fultext attr\"\"\"\n expected_ids = []\n with factories.single_commit():\n assessments = [factories.AssessmentFactory() for _ in range(10)]\n random.shuffle(assessments)\n with factories.single_commit():\n for idx, assessment in enumerate(assessments):\n comment = factories.CommentFactory(description=str(idx))\n factories.RelationshipFactory(source=assessment, destination=comment)\n expected_ids.append(assessment.id)\n query = self._make_query_dict(\n \"Assessment\", order_by=[{\"name\": \"comment\", \"desc\": desc}]\n )\n if desc:\n expected_ids = expected_ids[::-1]\n results = self._get_first_result_set(query, \"Assessment\", \"values\")\n self.assertEqual(expected_ids, [i['id'] for i in results])\n\n @ddt.data(\"Assessor\", \"Creator\", \"Verifier\")\n def test_delete_assessment_by_role(self, role_name):\n \"\"\"Delete assessment not allowed for based on Assignee Type.\"\"\"\n with factories.single_commit():\n assessment = factories.AssessmentFactory()\n context = factories.ContextFactory(related_object=assessment)\n assessment.context = context\n person = factories.PersonFactory()\n object_person_rel = factories.RelationshipFactory(\n source=assessment, destination=person)\n factories.RelationshipAttrFactory(\n relationship_id=object_person_rel.id,\n attr_name=\"AssigneeType\",\n attr_value=role_name,\n )\n assessment_id = assessment.id\n role = all_models.Role.query.filter(\n all_models.Role.name == \"Creator\"\n ).first()\n self.generator.generate_user_role(person, role, context)\n self.api.set_user(person)\n assessment = all_models.Assessment.query.get(assessment_id)\n resp = self.api.delete(assessment)\n self.assert403(resp)\n self.assertTrue(all_models.Assessment.query.filter(\n all_models.Assessment.id == assessment_id).one())\n\n @ddt.data(\n (all_models.Assessment.REWORK_NEEDED, True),\n (all_models.Assessment.DONE_STATE, True),\n (all_models.Assessment.FINAL_STATE, True),\n (all_models.Assessment.START_STATE, False),\n )\n @ddt.unpack\n def test_update_status_need_rework(self, status, is_valid):\n \"\"\"Update assessment state from need rework to valid or invalid states.\"\"\"\n with factories.single_commit():\n assessment = factories.AssessmentFactory(\n status=all_models.Assessment.REWORK_NEEDED\n )\n assessment_id = assessment.id\n resp = self.api.put(assessment, {\"status\": status})\n if is_valid:\n self.assert200(resp)\n check_status = status\n else:\n self.assert400(resp)\n check_status = all_models.Assessment.REWORK_NEEDED\n self.assertEqual(\n check_status, all_models.Assessment.query.get(assessment_id).status)\n","sub_path":"test/integration/ggrc/services/test_assessments.py","file_name":"test_assessments.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"650715434","text":"def arithmetic_arranger(problems, show_results=False):\n\n problems_list = []\n for p in problems:\n problems_list += p.split(\" \")\n\n problems_digits = [pr.replace(\"+\", '1') for pr in problems_list]\n problems_digits = [pr.replace(\"-\", '-1') for pr in problems_digits]\n\n test_total = 0\n\n # Test too many problems - ttmp -\n if len(problems) > 5:\n arranged_problems = \"Error: Too many problems.\"\n test_total += 1\n\n # Test Incorrect Operator - tio -\n count_pl = 1\n tio = 0\n\n while count_pl < len(problems_list):\n\n count_ele = problems_list[count_pl]\n\n if count_ele == \"+\":\n count_ele = count_ele.replace(\"+\", \"0\")\n if count_ele == \"-\":\n count_ele = count_ele.replace(\"-\", \"0\")\n if count_ele.isdigit():\n tio += 1\n\n count_pl += 3\n\n if tio < len(problems):\n arranged_problems = \"Error: Operator must be '+' or '-'.\"\n test_total += 1\n\n # Test Only Digits - tod -\n count_pl = 0\n tod = 0\n\n while count_pl < len(problems_list):\n count_ele = problems_list[count_pl]\n count_ele2 = problems_list[count_pl + 2]\n if count_ele.isnumeric() and count_ele2.isnumeric():\n tod += 1\n count_pl += 3\n\n if tod < len(problems):\n arranged_problems = \"Error: Numbers must only contain digits.\"\n test_total += 1\n\n # Test Too Many Digits - ttmd -\n ttmd = 0\n for pd in problems_digits:\n if len(pd) > 4:\n ttmd += 1\n if ttmd > 0:\n arranged_problems = \"Error: Numbers cannot be more than four digits.\"\n test_total += 1\n\n if test_total == 0:\n tt = 0\n first_row = \"\"\n second_row = \"\"\n underline_row = \"\"\n results = \"\"\n\n while tt < len(problems_digits):\n\n if len(problems_digits[tt]) > len(problems_digits[tt + 2]):\n longest_digit = len(problems_digits[tt])\n else:\n longest_digit = len(problems_digits[tt + 2])\n\n # First numbers row\n first_row_spaces = longest_digit - len(problems_digits[tt])\n first_row_formatted = (' ' * first_row_spaces) + problems_digits[tt]\n first_row += \" \" + first_row_formatted + \" \"\n\n # Second numbers row\n second_row += problems_list[tt + 1]\n second_row_spaces = longest_digit - len(problems_digits[tt + 2])\n second_row_formatted = (' ' * second_row_spaces) + problems_digits[tt + 2]\n second_row += \" \" + second_row_formatted + \" \"\n\n # Underline row\n underline_row_spaces = longest_digit\n underline_formatted = ('-' * underline_row_spaces)\n underline_row += \"--\" + underline_formatted + \" \"\n\n # Results row\n add = int(problems_digits[tt]) + int(problems_digits[tt + 1]) * int(problems_digits[tt + 2])\n result_spaces = (2 + longest_digit) - len(str(add))\n result_formatted = (' ' * result_spaces) + str(add)\n results += result_formatted + \" \"\n\n tt += 3\n\n test_arrangement = first_row[:-4] + \"\\n\" + second_row[:-4] + \"\\n\" + underline_row[:-4]\n test_solutions = test_arrangement + \"\\n\" + results[:-4]\n\n if show_results:\n arranged_problems = test_solutions\n else:\n arranged_problems = test_arrangement\n\n return arranged_problems\n","sub_path":"ArithmeticFormatter/arithmetic_arranger.py","file_name":"arithmetic_arranger.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"131030125","text":"import pandas as pd\nimport numpy as np\nimport os\nimport pdb\nimport re\n\nnew_lakes = pd.read_feather(\"../../../metadata/lake_metadata.feather\")\nnew_lakes = new_lakes['site_id']\nold_lakes = pd.read_csv(\"../../../metadata/lake_metadata.csv\")['nhd_id']\n\n\nold_ct = np.empty_like(old_lakes.values)\nnew_ct = np.empty((new_lakes.values.shape[0] - 5))\nold_tot = np.empty_like(old_lakes.values)\nnew_tot = np.empty((new_lakes.values.shape[0] - 5))\nold_ct[:] = np.nan\nold_tot[:] = np.nan\nnew_ct[:] = np.nan\nnew_tot[:] = np.nan \nfor i, lake in enumerate(old_lakes):\n\t# if lake == '1097324':\n\t\t# pdb.set_trace()\n\tprint(lake)\n\tobs = pd.read_feather(\"../../../data/raw/figure3/nhd_\"+str(lake)+\"_test_train.feather\")\n\tn_s = np.sum(obs['depth'] < 0.25)\n\tn_o = obs.shape[0] - n_s\n\told_ct[i] = n_s\n\told_tot[i] = n_o\n\t#total surface obs\n\nct = -1\nfor i, lake in enumerate(new_lakes):\n\tct += 1\n\tnid = lake\n\tmatch = re.search(\"nhdhr_(.+)\", str(lake))\n\tif nid == 'nhdhr_120018008' or nid == 'nhdhr_120020307' or nid == 'nhdhr_120020636' or nid == 'nhdhr_32671150' or nid =='nhdhr_58125241':\n\t\tct -= 1\n\t\tcontinue\n\n\tlake = match.group(1)\n\n\tobs = pd.read_feather(\"../../../data/raw/figure3/nhd_\"+str(lake)+\"_test_train.feather\")\n\tn_s = np.sum(obs['depth'] < 0.25)\n\tn_o = obs.shape[0] - n_s\n\tnew_ct[ct] = n_s\n\tnew_tot[ct] = n_o\n\n\n\nprint(\"old=\", np.sum(old_ct)/np.sum(old_tot), \", new=\", np.sum(new_ct)/np.sum(new_tot))\n\t#total surface obs\n\n\n","sub_path":"src/scripts/one-off/count_surface_obs.py","file_name":"count_surface_obs.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"289539484","text":"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom .views import createV,deleteV,updateV,sentpostV,inboxpostV,pendingpostV,refusedpostV,confirmedpostV,adminconfirmedpostV,adminrefusedpostV,adminpendingpostV\n\napp_name='Post'\n\nurlpatterns = [\n\n path('create/',createV,name='create'),\n path('delete/',deleteV,name='delete'),\n path('update/',updateV,name='update'),\n path('sent/',sentpostV.as_view(),name='sent'),\n path('inbox/',inboxpostV.as_view(),name='inbox'),\n\n path('pending/',pendingpostV.as_view(),name='pending'),\n path('pending_all/',adminpendingpostV.as_view(),name='pending_all'),\n\n path('refused/',refusedpostV.as_view(),name='refused'),\n path('refused_all/',adminrefusedpostV.as_view(),name='refused_all'),\n\n path('confirmed/',confirmedpostV.as_view(),name='confirmed'),\n path('confirmed_all/',adminconfirmedpostV.as_view(),name='confirmed_all'),\n \n]\n","sub_path":"Post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"70152853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nRun probabilistic line search on a CIFAR-10 example.\n\"\"\"\n\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath('..'))\n\nimport tensorflow as tf\n\nfrom probls.tensorflow_interface.interface_sgd import ProbLSOptimizerSGDInterface\nfrom probls.line_search import ProbLSOptimizer\n\nimport cifar10\n\n#### Specify training specifics here ##########################################\nfrom models import cifar10_2conv_3dense as model\nnum_steps = 4000\nbatch_size = 256\n###############################################################################\n\n\n# Set up model\ntf.reset_default_graph()\nimages, labels = cifar10.distorted_inputs(batch_size=batch_size)\nlosses, variables = model.set_up_model(images, labels)\n\n# Set up ProbLS optimizer\nopt_interface = ProbLSOptimizerSGDInterface()\nopt_interface.minimize(losses, variables)\nsess = tf.Session()\nopt_interface.register_session(sess)\nopt_ls = ProbLSOptimizer(opt_interface, alpha0=1e-3, cW=0.3, c1=0.05,\n target_df=0.5, df_lo=-0.1, df_hi=1.1, expl_policy=\"linear\", fpush=1.0,\n max_change_factor=10., max_steps=10, max_expl=10, max_dmu0=0.0)\n\n# Initialize variables and start queues\ncoord = tf.train.Coordinator()\nsess.run(tf.global_variables_initializer())\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n# Run ProbLS\nopt_ls.prepare()\nfor i in range(num_steps):\n print(opt_ls.proceed())\n\n# Stop queues\ncoord.request_stop()\ncoord.join(threads)","sub_path":"examples/run_probls_cifar10.py","file_name":"run_probls_cifar10.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"631539105","text":"import json\nimport sys\nprint(\"Creator.\")\nff = {}\nwhile 1:\n try:\n s = input(\"Save as: \")\n u = input(\"URL: \")\n ff[\"/home/gdrive/\" + str(s)] = str(u)\n except KeyboardInterrupt:\n print(\"Saving..\")\n fp = open(\"config.json\", 'w')\n json.dump(ff, fp)\n break\n\nsys.exit(0)\n","sub_path":"creator.py","file_name":"creator.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"316287903","text":"# -*- coding: utf-8 -*-\n\"\"\"\\\n==============\npipetestserver\n==============\n\nThis recipe describes how you can create / activate and kill a temporary HTTP\nserver with a WSGI app to provide unittest resources to a client software,\nthat's the target of your application.\n\nFor our demo, we create a stupid wsgi app that returns the double of the value\nprovided in a simple JSON structure.\n\n{\"value\": 5} -> {\"value\": 10}\n{\"value\": \"ta\"} -> {\"value\": \"tata\"}\n{\"value\": {}} -> {\"error\": \"TypeError\", \"traceback\": \"...\"}\n\nRun this module with either::\n\n $ python testserver.py\n $ python -m unittest discover -v\n\nNote that this will work only on an Unix box (use of select.select on a pipe).\nThis code works on Python 2.6 or 2.7 and needs some changes for Python 3.x\n\"\"\"\n\nimport httplib\nimport json\nimport os\nimport select\nimport StringIO\nimport threading\nimport traceback\nimport unittest\nimport urllib2\nimport wsgiref.simple_server\n\n# APPLICATION\n# ===========\n# This part is a portion of your application sw that includes an HTTP client\n\nENDPOINT = \"http://somehost.mydomain.com\"\n\n\ndef proxiedClient(value, endpoint=ENDPOINT):\n proxy = urllib2.ProxyHandler({'http': 'localhost:8500'})\n opener = urllib2.build_opener(proxy)\n urllib2.install_opener(opener)\n payload = json.dumps({'value': value})\n headers = {'Content-Type': 'application/json'}\n request = urllib2.Request(endpoint, payload, headers)\n payload = urllib2.urlopen(request).read()\n result = json.loads(payload)\n if 'value' in result:\n return result['value']\n else:\n return result # dict with 'error' and 'traceback' keys\n\n\ndef client(value, endpoint=ENDPOINT):\n payload = json.dumps({'value': value})\n headers = {'Content-Type': 'application/json'}\n request = urllib2.Request(endpoint, payload, headers)\n payload = urllib2.urlopen(request).read()\n result = json.loads(payload)\n if 'value' in result:\n return result['value']\n else:\n return result # dict with 'error' and 'traceback' keys\n\n\n# RESSOURCES\n# ==========\n# This part sits tipycally in a tests/resources.py module\n# Make an \"application\" that suits your client and mocks a real web service\n\ndef application(environ, start_response):\n \"\"\"The WSGI application that mocks a real server\n \"\"\"\n def make_status(value):\n \"\"\"HTTP status (int) -> WSGI response suitable status\n \"\"\"\n return \"{0} {1}\".format(value, httplib.responses[value])\n\n headers = [('Content-Type', 'application/json')]\n try:\n if environ.get('REQUEST_METHOD') != 'POST':\n start_response(make_status(httplib.METHOD_NOT_ALLOWED, headers))\n return [\"Seul le mode POST est admis\"]\n try:\n request_body_size = int(environ.get('CONTENT_LENGTH', 0))\n except (ValueError):\n request_body_size = 0\n request_body = environ['wsgi.input'].read(request_body_size)\n request_dict = json.loads(request_body)\n value = request_dict[u'value']\n result = 2 * value\n response_body = json.dumps({'value': result})\n status = httplib.OK\n\n except Exception as exc:\n tb_stream = StringIO.StringIO()\n traceback.print_exc(file=tb_stream)\n response = {\n 'exception': exc.__class__.__name__,\n 'traceback': tb_stream.getvalue()\n }\n response_body = json.dumps(response)\n status = httplib.OK\n\n headers.append(('Content-Length', str(len(response_body))))\n start_response(make_status(status), headers)\n return [response_body]\n\n# But you can copy this class as-is in your tests/resources.py module.\n\n\nclass ThreadedServerControl(object):\n\n \"\"\"Will provide a temporary test server in another thread for your\n application.\n\n :param app: A wsgi application\n :param host: Listening hostname or IP\n :param port: Listening port preferably >= 1024 unless you're root\n \"\"\"\n __stop_marker = 'stop'\n\n def __init__(self, app, host='localhost', port=8000):\n self.app = app\n self.host = host\n self.port = port\n\n # Communication pipe with the thread\n self.stop_read, self.stop_write = os.pipe()\n self.started = False\n return\n\n def __run(self):\n httpd = wsgiref.simple_server.make_server(self.host, self.port,\n self.app)\n\n # We don't want logs in the console\n log_request = httpd.RequestHandlerClass.log_request\n no_logging = lambda *args, **kwargs: None\n httpd.RequestHandlerClass.log_request = no_logging\n\n # Notify / unlock self.start()\n self.ready.set()\n while True:\n ready, dummy, dummy = select.select(\n [httpd, self.stop_read], [self.stop_write], []\n )\n # HTTP client request detected ?\n if httpd in ready:\n httpd.handle_request()\n\n # self.stop() synch called ?\n if self.stop_read in ready:\n os.read(self.stop_read, len(self.__stop_marker))\n # Re-enable console logging and exit\n httpd.RequestHandlerClass.log_request = log_request\n break\n\n def start(self):\n \"\"\"Launches the server in a thread\n \"\"\"\n # Bounce protection\n if self.started:\n return\n\n # Threaded server and synch setup\n self.ready = threading.Event()\n self.server_thread = threading.Thread(target=self.__run)\n self.server_thread.start()\n\n # Wait server readyness (if a client runs before -> raise URLError)\n self.ready.wait()\n self.started = True\n return\n\n def stop(self):\n \"\"\"Stops and kills the server and thread\n \"\"\"\n # Bounce protection\n if not self.started:\n return\n\n # Notify thread's suicide\n os.write(self.stop_write, self.__stop_marker)\n\n # Cleanup after thread's suicide\n self.server_thread.join()\n os.close(self.stop_write)\n os.close(self.stop_read)\n self.started = False\n import time\n time.sleep(0.01)\n return\n\n\n# TESTS\n# =====\n# The usual tests suite in a tests/test_somemodule.py module. Look how we\n# start and stop the server respectively in setUpClass and tearDownClass\n\n\nclass ClientTest(object):\n\n \"\"\"Common mixin test case\n \"\"\"\n endpoint = 'http://localhost:8000/' # Our tests server\n\n def test_int(self):\n \"\"\"Integer * 2 -> OK\n \"\"\"\n result = client(2, endpoint=self.endpoint)\n self.assertEqual(result, 4)\n return\n\n def test_str(self):\n \"\"\"String * 2 -> OK\n \"\"\"\n result = client(\"co\", endpoint=self.endpoint)\n self.assertEqual(result, \"coco\")\n return\n\n def test_err(self):\n \"\"\"Dict * 2 -> TypeError (server)\n \"\"\"\n result = client({}, endpoint=self.endpoint)\n self.assertTrue('exception' in result)\n self.assertEqual(result['exception'], 'TypeError')\n self.assertTrue('traceback' in result)\n return\n\n\nclass SetUpClassTest(unittest.TestCase, ClientTest):\n\n \"\"\"Server settings through setUpClass / tearDownClass\n \"\"\"\n @classmethod\n def setUpClass(cls):\n # Create and starts the server\n cls.server = ThreadedServerControl(application)\n cls.server.start()\n return\n\n @classmethod\n def tearDownClass(cls):\n # Stop and delete the server\n cls.server.stop()\n return\n\n\nclass SetUpTest(unittest.TestCase, ClientTest):\n\n \"\"\"Server settings through setUp / tearDown\n \"\"\"\n\n def setUp(self):\n # Create and starts the server\n self.server = ThreadedServerControl(application)\n self.server.start()\n return\n\n def tearDown(self):\n # Stop and delete the server\n self.server.stop()\n return\n\n\nclass SetUpTest(unittest.TestCase, ClientTest):\n\n \"\"\"Server settings through setUp / tearDown\n \"\"\"\n\n def setUp(self):\n # Create and starts the server\n self.server = ThreadedServerControl(application)\n self.server.start()\n return\n\n def tearDown(self):\n # Stop and delete the server\n self.server.stop()\n return\n\n\ndef test_suite():\n suite = unittest.TestSuite()\n tests = [unittest.makeSuite(SetUpTest)]\n if hasattr(unittest, 'skipIf'):\n # New style unittest oy unittest2\n tests += [unittest.makeSuite(SetUpClassTest)]\n suite.addTests(tests)\n return suite\n\n\nif __name__ == '__main__':\n unittest.TextTestRunner().run(test_suite())\n","sub_path":"hoverpy/tests/pipetestserver.py","file_name":"pipetestserver.py","file_ext":"py","file_size_in_byte":8612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"511883909","text":"import pandas as pd\nimport numpy as np\nimport os\nimport pathlib\n\n\ndef clean_zips(df):\n \"\"\"\n A helper function to clean zip code columns\n for Los Angeles Airbnb Data\n \"\"\"\n\n def first_ele(df):\n for i in df:\n return i\n\n def first_five(df):\n return df[2:7]\n\n # Splits data for entries containing period\n df['zipcode'] = df['zipcode'].str.split('.')\n\n # Transform all values into strings\n df['zipcode'] = df['zipcode'].apply(str)\n\n # Returns only the first five characters\n df['zipcode'] = df['zipcode'].map(first_five)\n\n df = df.loc[df['zipcode'] != 'n']\n\n return df\n\n\ndef clean_price(df):\n df['price'] = df['price'].str.strip('$')\n df['cleaning_fee'] = df['cleaning_fee'].str.strip('$')\n\n df['price'] = df['price'].str.replace(',', '')\n df['cleaning_fee'] = df['cleaning_fee'].str.replace(',', '')\n\n df['cleaning_fee'] = df['cleaning_fee'].replace(np.nan, 0)\n\n df['price'] = df['price'].astype(float)\n df['cleaning_fee'] = df['cleaning_fee'].astype(float)\n\n df['total_price'] = df['price'] + df['cleaning_fee']\n df = df.drop(['price', 'cleaning_fee'], axis=1)\n\n df = df[df['total_price'] > 1]\n\n # Log transform total price\n df['price_log'] = df['total_price'].apply(lambda x: np.log(x))\n\n return df\n\n\ndef clean_data(df):\n # Drop columns containing null values\n df = df.dropna()\n\n return df\n\n\ndef data_cleaning():\n print(\"Info: Step 2 - Data Cleaning start ...\")\n\n # Remove old data if present\n file = pathlib.Path(\"data-clean.csv\")\n if file.exists():\n print(\"Info: Removing data-clean.csv\")\n os.remove(\"data-clean.csv\")\n\n df = pd.read_csv('data.csv')\n df = clean_data(clean_price(clean_zips(df)))\n df.to_csv('data-clean.csv', index=False)\n\n print(\"Info: Data Cleaning completed ...\")\n\nif __name__ == '__main__':\n data_cleaning()\n","sub_path":"eb-flask/data_cleaning.py","file_name":"data_cleaning.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"162883190","text":"import numpy as np\nfrom pydub import AudioSegment\nfrom scipy.io import wavfile\nimport random\nimport sys\nimport io\nimport os\nimport glob\nimport IPython\nfrom song_preprocessing import *\n\nfrom keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply\nfrom keras.layers import RepeatVector, Dense, Activation, Lambda\nfrom keras.optimizers import Adam\nfrom keras.utils import to_categorical\nfrom keras.models import load_model, Model\nimport keras.backend as K\nimport tensorflow as tf\n\n# IPython.display.Audio(\"./songs/chuyentinhtoi.wav\")\n# x = graph_spectrogram(\"./songs/chuyentinhtoi.wav\") # (101,156017)\n# x_y = graph_spectrogram(\"./songs/yemsao.wav\") # (101, 116171)\n# # number of column depends on the duration of the song\n# _, data = wavfile.read(\"./songs/chuyentinhtoi.wav\") # (12481536, 2)\n\ndef one_step_attention(a, s_prev):\n # shape of a = (None,S,256)\n s_prev = repeator(s_prev) # (None,S,256)\n concat = concatenator([a, s_prev]) # (None,S,512)\n e = densor1(concat) # (None,S,10)\n energies = densor2(e) # (None,S,1)\n alphas = activator(energies) # (None,S,1)\n context = dotor([alphas, a]) # (None,1,1)\n return context\n\n\ndef model(Tx, Ty, n_a, n_s, n_x, n_y):\n X = Input(shape=(Tx, n_x))\n s0 = Input(shape=(n_s,), name = 's0')\n c0 = Input(shape=(n_s,), name = 'c0')\n s = s0\n c = c0\n\n outputs = []\n\n a = Bidirectional(LSTM(n_a, return_sequences = True))(X) #(None, Tx, n_a*2)\n\n for t in range(Ty):\n\n context = one_step_attention(a,s)\n s, _, c = post_activation_LSTM(context, initial_state = [s,c])\n\n out = output_layer(s)\n outputs.append(out)\n\n model = Model(inputs=[X,s0,c0], outputs = outputs)\n return model\n\nif __name__ == \"__main__\":\n\n S = 1000\n Tx = get_Tx(\"./songs/\")\n Ty = 1\n\n _, n = get_songs(\"./songs/\")\n x,y = preprocessing_data(\"./songs/\", Tx, Ty)\n\n n_a = 128\n n_s = 256\n n_x = 101\n n_y = n\n\n repeator = RepeatVector(Tx)\n concatenator = Concatenate(axis=-1)\n sliding = tf.contrib.data.sliding_window_batch(S)\n densor1 = Dense(10, activation = \"tanh\")\n densor2 = Dense(1, activation = \"relu\")\n activator = Activation(K.softmax, name=\"attention_weights\")\n dotor = Dot(axes= 1)\n\n post_activation_LSTM = LSTM(n_s, return_state = True)\n output_layer = Dense(n, activation=K.softmax)\n print(x.shape)\n print(y.shape)\n outputs = list(y.swapaxes(0,1))\n\n model = model(Tx, Ty, n_a, n_s, n_x, n_y)\n model.compile(optimizer = Adam(lr=0.005, beta_1 = 0.9, beta_2 = 0.999, decay =0.1), metrics = ['accuracy'], loss = 'categorical_crossentropy')\n s0 = np.zeros((n, n_s))\n c0 = np.zeros((n, n_s))\n model.fit([x, s0, c0], outputs, epochs = 100, batch_size = 1)\n","sub_path":"Supervised Learning/Song_Detector/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"145060287","text":"from pandas import DataFrame\nfrom ..utils import get_offset, verify_series\n\n\ndef ABSSIO(close, length=None, offset=None, **kwargs):\n \"\"\"Absolute Strength Index Oscillator\"\"\"\n\n # Validate Arguments\n close = verify_series(close)\n length = length if length and length > 0 else 14\n min_periods = int(\n kwargs['min_periods']) if 'min_periods' in kwargs and kwargs['min_periods'] is not None else length\n offset = get_offset(offset)\n \n # Calculate Result\n \n\n return ('Absolute Strength Index Oscilator')\n","sub_path":"pandas_ta_indicators/trend/ABSSIO.py","file_name":"ABSSIO.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"515723375","text":"import abc\n\nfrom pokeretriever.Ability import Ability\nfrom pokeretriever.Move import Move\nfrom pokeretriever.Pokemon import Pokemon\nfrom pokeretriever.Stats import Stats\n\n\nclass BaseFactory(abc.ABC):\n \"\"\"\n Abstract factory class for Pokedex Objects.\n \"\"\"\n @abc.abstractmethod\n def create_item(self, json_dict):\n \"\"\"\n Create a Pokedex Object.\n :param json_dict: a dictionary with necessary values to initialize a Pokedex Object\n :return: a PokedexObject\n \"\"\"\n pass\n\n\nclass AbilityFactory(BaseFactory):\n \"\"\"\n Factory class for Ability objects.\n \"\"\"\n def create_item(self, ability_dict):\n \"\"\"\n Return an Ability object.\n :param ability_dict: dictionary with key-value pairs necessary to initialize an Ability object\n :return: Ability\n \"\"\"\n generation = ability_dict[\"generation\"][\"name\"]\n if ability_dict[\"effect_entries\"]:\n effect = ability_dict[\"effect_entries\"][1][\"effect\"]\n short_effect = ability_dict[\"effect_entries\"][1][\"short_effect\"]\n else:\n effect = \"N/A\"\n short_effect = \"N/A\"\n pokemon = []\n for item in ability_dict[\"pokemon\"]:\n pokemon.append(item[\"pokemon\"][\"name\"])\n name = ability_dict[\"name\"]\n ability_id = ability_dict[\"id\"]\n return Ability(generation, effect, short_effect, pokemon, name, ability_id)\n\n\nclass MoveFactory(BaseFactory):\n \"\"\"\n Factory class for Move objects.\n \"\"\"\n def create_item(self, move_dict):\n \"\"\"\n Return a Move object.\n :param move_dict: dictionary with key-value pairs necessary to initialize a Move object\n :return: Move\n \"\"\"\n generation = move_dict[\"generation\"][\"name\"]\n accuracy = move_dict[\"accuracy\"]\n pp = move_dict[\"pp\"]\n power = move_dict[\"power\"]\n move_type = move_dict[\"type\"][\"name\"]\n damage_class = move_dict[\"damage_class\"][\"name\"]\n if move_dict[\"effect_entries\"]:\n short_effect = move_dict[\"effect_entries\"][0][\"short_effect\"]\n else:\n short_effect = \"N/A\"\n name = move_dict[\"name\"]\n move_id = move_dict[\"id\"]\n return Move(generation, accuracy, pp, power, move_type, damage_class, short_effect, name, move_id)\n\n\nclass PokemonFactory(BaseFactory):\n \"\"\"\n Factory class for Pokemon objects.\n \"\"\"\n def create_item(self, pokemon_info):\n \"\"\"\n Return a Pokemon object.\n :param pokemon_info: dictionary with key-value pairs necessary to initialize a Move object\n :return: Pokemon\n \"\"\"\n pokemon_info[\"types\"] = [pokemon_type[\"type\"][\"name\"] for pokemon_type in pokemon_info[\"types\"]]\n\n if type(pokemon_info[\"stats\"][0]) is not Stats:\n pokemon_info[\"stats\"] = [(stat[\"stat\"][\"name\"], stat[\"base_stat\"]) for stat in pokemon_info[\"stats\"]]\n pokemon_info[\"abilities\"] = [ability[\"ability\"][\"name\"] for ability in pokemon_info[\"abilities\"]]\n pokemon_info[\"moves\"] = [(\"Move name: \" + move[\"move\"][\"name\"], \"Level acquired: \" + str(move[\"version_group_details\"][0][\"level_learned_at\"])) for move in pokemon_info[\"moves\"]]\n\n return Pokemon(**pokemon_info)\n\n\nclass StatsFactory(BaseFactory):\n \"\"\"\n Factory class for Stats objects.\n \"\"\"\n def create_item(self, stats_info):\n \"\"\"\n Return a Stats object.\n :param stats_info: dictionary necessary to initialize a Stats object\n :return: Stats\n \"\"\"\n return Stats(**stats_info)\n","sub_path":"pokedex/pokeretriever/Factory.py","file_name":"Factory.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"226766563","text":"class Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n start ,leng, dict= 0, 0, {}\n for i in range(len(s)):\n if s[i] in dict:\n if dict[s[i]] >= start:\n start = dict[s[i]]+1\n dict[s[i]] = i\n leng = max(leng, i-start+1)\n return leng\n\n\n# string的题目通常只要返回长度数字,不要返回具体的字符串,这样的话可以采用dict方式记录index很方便。同时采用几个pointers进行遍历也是常用的方法。\n# 用dict的key记录str的char,value记录对应的index简直是神器","sub_path":"3. Longest Substring Without Repeating Characters.py","file_name":"3. Longest Substring Without Repeating Characters.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"183069121","text":"\"\"\"This module defines the text based template responses to be formatted\nand sent to users with the proper data\nThis is meant to be used with the sample weather agent for Dialogflow, located at\nhttps://console.dialogflow.com/api-client/#/agent//prebuiltAgents/Weather\n\"\"\"\n\nLIST_YES = [\n 'Meglio portarlo con te.',\n 'Non fa mai male portarlo con sè.',\n 'Considerando il meteo è meglio averlo con sè.'\n]\n\nLIST_NO = [\n 'No, puoi anche non portarlo.',\n 'Non penso sarà necessario...',\n 'Potresti anche portarlo ma dubito che ne avrai di bisogno.',\n 'A mio parere non ti servirà.'\n]\n\nLIST_COLD = [\n 'Fa freddissimo a {city}. La temperatura si aggira attorno a {temp}°C.',\n '{temp}°C. Fa molto freddo direi a {city}...',\n 'Fa molto freddo a {city}, faresti meglio a non dimenticarti i guanti. Ci sono {temp}°C.',\n 'La temperatura è di {temp}°C a {city}.'\n]\n\nLIST_CHILLY = [\n 'Fa piuttosto freddo a {city}. La temperatura è di {temp}°C.',\n 'Ti servirebbe sicuramente una giacca con {temp}°C a {city}.',\n 'Non fa molto caldo a {city}. Ci sono {temp}°C.',\n 'La temperatura è di {temp}°C a {city}.'\n]\n\nLIST_WARM = [\n 'La temperatura è ottima a {city}. Si attesta attorno a {temp}°C.',\n 'Le temperature si aggirano intorno a valori ottimali a {city} con una media di {temp}°C.',\n 'La temperatura è di {temp}°C a {city}.'\n]\n\nLIST_HOT = [\n 'Oh, a {city} fa molto caldo! Ci sono {temp}°C.',\n 'Fa molto caldo a {city}. La temperatura è di {temp}°C.',\n 'Le temperature sono molto elevate a {city}, fa un gran caldo.',\n 'La temperatura è di {temp}°C a {city}.'\n]\n\nWEATHER_CURRENT = [\n 'A {city} {descr} con {temp}°C e venti da {direct} a {speed} km/h.',\n 'Adesso la temperatura è di {temp}°C a {city} con {descr}. Umidità al {umid}%.',\n 'Attualmente {descr} con {temp}°C a {city}. Venti a {speed} km/h provenienti da {direct}.',\n 'La temperatura a {place} è di {temp}°C con {descr} e venti da {direct}.',\n 'A {city} {descr} con {temp}°C. Umidità al {umid}% con venti da {direct} a {speed} km/h.'\n]\n\nWEATHER_DATE = [\n '{day} in {place} it will be around {temperature} and {condition}.',\n '{day} in {place} you can expect it to be around {temperature} and \\\n {condition}.',\n '{day} in {place} you can expect {condition}, with temperature around \\\n {temperature}.',\n '{day} in {place} it will be {condition}, {temperature}.',\n]\n\nWEATHER_WEEKDAY = [\n 'On {date} in {place} it will be {condition}, {temperature}.',\n 'On {date} in {place} it\\'s expected to be {condition}, {temperature}.',\n 'The forecast for {date} in {place} is {condition}, {temperature}.',\n '{date} in {place} is expected to be {condition}, {temperature}.'\n]\n\nWEATHER_DATE_TIME = [\n '{day} in {place} at {time} it will be around {temperature} and \\\n {condition}.',\n '{day} in {place} at {time} you can expect it to be around {temperature} \\\n and {condition}.',\n '{day} in {place} at {time} you can expect {condition}, with the \\\n temperature around {temperature}.',\n '{day} in {place} at {time} it will be {condition}, {temperature}.',\n 'At {time} on {day} in {place} it will be {temperature} and {condition}.'\n]\n\nWEATHER_TIME_PERIOD = [\n 'It will be {condition} in {city} and around {temp} on period from \\\n {time_start} till {time_end}.'\n]\n\nWEATHER_TIME_PERIOD_DEFINED = [\n 'This {time_period} in {place} it will be {temperature} and {condition}.',\n 'This {time_period} in {place} you can expect {condition}, with \\\n temperature around {temperature}.',\n 'Expect a {condition} {time_period} in {place}, with temperature around \\\n {temperature}.',\n 'It will be {condition} in {place} and around {temperature} this \\\n {time_period}.',\n]\n\nWEATHER_DATE_PERIOD_WEEKEND = [\n 'On Saturday in {city} it will be {condition_sat}, '\n 'with temperatures from {sat_temp_min} to {sat_temp_max}. '\n 'And Sunday should be {condition_sun}, '\n 'with a low of {sun_temp_min} and a high of {sun_temp_max}.'\n]\n\nWEATHER_DATE_PERIOD = [\n 'During period from {date_start} till {date_end}'\n ' in {city} you can expect {condition}, '\n 'with a low of {degree_list_min} and a high of {degree_list_max}.'\n]\n\nWEATHER_ACTIVITY_YES = [\n 'What a nice weather for {activity}!'\n]\n\nWEATHER_ACTIVITY_NO = [\n 'Not the best weather for {activity}.'\n]\n\nRESPONSE_WEATHER_CONDITION = [\n 'Chance of {condition_original} is {condition} percent.'\n]\n\nRESPONSE_WEATHER_OUTFIT = [\n 'Chance of {condition_original} is {condition} percent. {answer}'\n]\n","sub_path":"responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"548075540","text":"#\n# Copyright 2011, Intel Inc.\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; version 2 of the License.\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 Library 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\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n'''\nCreated on 29 sept. 2011\n\n@author: ronan\n'''\nimport os\n\nimport ObsLightOsc\nimport ObsLightErr\nimport ObsLightTools\nimport ObsLightPrintManager\n\nclass ObsLightServer(object):\n\n def __init__(self,\n serverWeb=\"\",\n serverAPI=None,\n serverRepo=\"\",\n alias=None,\n user=None,\n passw=None,\n fromSave=None):\n '''\n Create a reference to a OBS server\n '''\n self.__alias = None\n self.__serverRepo = None\n self.__isReachable = None\n\n self.__projectRreadOnlyBuffer = {}\n\n if fromSave != None:\n if \"isOBSConnected\" in fromSave.keys():\n self.__isOBSConnected = fromSave[\"isOBSConnected\"]\n if \"serverWeb\" in fromSave.keys():\n self.__serverWeb = fromSave[\"serverWeb\"]\n if \"serverAPI\" in fromSave.keys():\n self.__serverAPI = str(fromSave[\"serverAPI\"])\n if \"serverRepo\" in fromSave.keys():\n self.__serverRepo = fromSave[\"serverRepo\"]\n if \"alias\" in fromSave.keys():\n self.__alias = fromSave[\"alias\"]\n if \"user\" in fromSave.keys():\n self.__user = fromSave[\"user\"]\n if \"passw\" in fromSave.keys():\n self.__passw = fromSave[\"passw\"]\n else:\n self.__isOBSConnected = False\n self.__serverWeb = serverWeb\n self.__serverAPI = str(serverAPI)\n self.__serverRepo = serverRepo\n\n self.__alias = alias\n\n self.__user = user\n self.__passw = passw\n\n if (self.__alias == None) or (len(self.__alias) < 1):\n self.__alias = self.__serverAPI\n\n ObsLightOsc.getObsLightOsc().initConf(api=self.__serverAPI,\n user=self.__user,\n passw=self.__passw,\n alias=self.__alias)\n\n def testServer(self):\n self.__isReachable = (self.testServerAPI() and\n self.testServerRepo() and\n self.testServerWeb())\n return self.__isReachable\n\n def testServerAPI(self):\n return ObsLightTools.testHost(self.__serverAPI)\n\n def testServerRepo(self):\n return ObsLightTools.testHost(self.__serverRepo)\n\n def testServerWeb(self):\n return ObsLightTools.testHost(self.__serverWeb)\n\n def isReachable(self):\n if self.__isReachable == None:\n self.__isReachable = self.testServer()\n return self.__isReachable\n\n def getObsProjectPackageList(self, projectObsName):\n return ObsLightOsc.getObsLightOsc().getPackageList(apiurl=self.__serverAPI,\n projectLocalName=projectObsName)\n\n def getFilesListPackage(self,\n projectObsName,\n package):\n return ObsLightOsc.getObsLightOsc().getFilesListPackage(apiurl=self.__serverAPI,\n projectObsName=projectObsName,\n package=package)\n\n\n def getPackageBuildRequires(self,\n projectObsName,\n projectTarget,\n arch,\n specFile,\n extraPackages=[]):\n buildInfoXml = ObsLightOsc.getObsLightOsc().getPackageBuildRequires(self.__serverAPI,\n projectObsName,\n projectTarget,\n arch,\n specFile,\n extraPackages)\n\n buildInfoCli = ObsLightOsc.getObsLightOsc().createBuildInfoObj(buildInfoXml, self.__serverAPI)\n buildInfoCli = ObsLightOsc.getObsLightOsc().updateCache(buildInfoCli, self.__serverAPI)\n\n return buildInfoCli\n\n def getObsServerParameter(self, parameter=None):\n '''\n return the value of the parameter \"parameter\"\n the valid parameter is:\n isOBSConnected\n serverWeb\n serverAPI\n serverRepo\n alias\n user\n passw\n '''\n\n if parameter == \"isOBSConnected\":\n return self.__isOBSConnected\n elif parameter == \"serverWeb\":\n return self.__serverWeb\n elif parameter == \"serverAPI\":\n return str(self.__serverAPI)\n elif parameter == \"serverRepo\":\n return self.__serverRepo\n elif parameter == \"alias\":\n return self.__alias\n elif parameter == \"user\":\n return self.__user\n elif parameter == \"passw\":\n return self.__passw\n\n def getProjectParameter(self, project, parameter):\n '''\n Get the value of a project parameter.\n Valid parameter are:\n title\n description\n remoteurl\n maintainer\n bugowner\n arch\n repository \n '''\n if not parameter in [\"title\",\n \"description\",\n \"remoteurl\",\n \"maintainer\",\n \"bugowner\",\n \"arch\",\n \"repository\",\n \"readonly\"]:\n mess = \"\\\"%s\\\" is not a parameter of a OBS project\" % parameter\n raise ObsLightErr.ObsLightObsServers(mess)\n\n if not project in self.getLocalProjectList(raw=True):\n message = \"Can't return the project parameter,\\n\"\n message += \" '%s' is not a project on obs '%s'\"\n message = message % (project , self.__serverAPI)\n\n raise ObsLightErr.ObsLightObsServers(message)\n\n if parameter == \"readonly\":\n if project in self.__projectRreadOnlyBuffer.keys():\n return self.__projectRreadOnlyBuffer[project]\n res = ObsLightOsc.getObsLightOsc().getProjectParameter(projectObsName=project,\n apiurl=self.__serverAPI,\n parameter=\"maintainer\")\n ro = not self.__user in res\n self.__projectRreadOnlyBuffer[project] = ro\n return ro\n else:\n res = ObsLightOsc.getObsLightOsc().getProjectParameter(projectObsName=project,\n apiurl=self.__serverAPI,\n parameter=parameter)\n return res\n\n def getAPI(self):\n return str(self.__serverAPI)\n\n def getPackageParameter(self, project, package, parameter):\n '''\n Get the value of a package parameter.\n Valid parameter are:\n title\n description\n url\n status \n listFile \n '''\n\n if not parameter in [\"title\",\n \"description\",\n \"url\",\n \"status\",\n \"listFile\"]:\n raise ObsLightErr.ObsLightObsServers(parameter + \" is not a parameter of a OBS package\")\n\n# FIXME: is that necessary ? It's really slow on public OBS servers...\n# if not project in self.getLocalProjectList(raw=True):\n# message = \"Can't return the package parameter,\\n\"\n# message += \"'%s' is not a project on obs '%s'\"\n# message = message % (project, self.__serverAPI)\n#\n# raise ObsLightErr.ObsLightObsServers(message)\n\n if not package in self.getObsProjectPackageList(projectObsName=project):\n message = \"Can't return the package parameter,\\n\"\n message += \"'%s' is not a package of project '%s' on obs '%s'\"\n message = message % (package, project, self.__serverAPI)\n raise ObsLightErr.ObsLightObsServers(message)\n\n if parameter in [\"title\",\n \"description\",\n \"url\"]:\n return ObsLightOsc.getObsLightOsc().getPackageMetaParameter(projectObsName=project,\n package=package,\n apiurl=self.__serverAPI,\n parameter=parameter)\n elif parameter in [\"listFile\"]:\n return ObsLightOsc.getObsLightOsc().getPackageParameter(projectObsName=project,\n package=package,\n apiurl=self.__serverAPI,\n parameter=parameter)\n\n\n def getObsPackageRev(self,\n projectObsName,\n package):\n return ObsLightOsc.getObsLightOsc().getObsPackageRev(apiurl=self.__serverAPI,\n projectObsName=projectObsName,\n package=package)\n\n def getOscPackageRev(self, workingdir):\n return ObsLightOsc.getObsLightOsc().getOscPackageRev(workingdir=workingdir)\n\n def setObsServerParameter(self, parameter=None, value=None):\n '''\n change the value of the parameter \"parameter\"\n the valid parameter is:\n obssOBSConnected\n serverWeb\n serverAPI\n serverRepo\n alias\n user\n passw\n '''\n if value == None:\n raise ObsLightErr.ObsLightObsServers(\"value is not valid for setObsServerParameter\")\n if parameter == \"isOBSConnected\":\n self.__isOBSConnected = value\n elif parameter == \"serverWeb\":\n self.__serverWeb = value\n elif parameter == \"serverAPI\":\n ObsLightOsc.getObsLightOsc().changeAPI(api=self.__serverAPI,\n newApi=value)\n self.__serverAPI = str(value)\n elif parameter == \"serverRepo\":\n self.__serverRepo = value\n elif parameter == \"alias\":\n self.__alias = value\n elif parameter == \"user\":\n ObsLightOsc.getObsLightOsc().changeUser(api=self.__serverAPI,\n user=value)\n self.__user = value\n elif parameter == \"passw\":\n ObsLightOsc.getObsLightOsc().changePassw(api=self.__serverAPI,\n passw=value)\n self.__passw = value\n else:\n raise ObsLightErr.ObsLightObsServers(\"parameter is not valid for setObsServerParameter\")\n return None\n\n def initConfigProject(self, projet, repos, lastResult=None):\n lastResult = lastResult or {}\n #if the repository is link to a listDepProject\n res = ObsLightOsc.getObsLightOsc().getDepProject(apiurl=self.__serverAPI,\n projet=projet,\n repos=repos)\n #the listDepProject must be trust(add to .oscrc )\n if res != None:\n ObsLightOsc.getObsLightOsc().trustRepos(api=self.__serverAPI,\n listDepProject=res)\n\n listProject = res.keys()\n\n dicoProject = dict(lastResult)\n for aprojet in listProject:\n dicoProject[aprojet] = res[aprojet]\n\n for aprojet in listProject:\n if (aprojet != projet) or (res[aprojet] != repos) :\n if (aprojet not in lastResult.keys()):\n self.initConfigProject(projet=aprojet,\n repos=res[aprojet],\n lastResult=dicoProject)\n\n def getDic(self):\n '''\n return a description of the object in a dictionary \n '''\n aDic = {}\n aDic[\"isOBSConnected\"] = self.__isOBSConnected = False\n aDic[\"serverWeb\"] = self.__serverWeb\n aDic[\"serverAPI\"] = str(self.__serverAPI)\n aDic[\"serverRepo\"] = self.__serverRepo\n aDic[\"alias\"] = self.__alias\n aDic[\"user\"] = self.__user\n aDic[\"passw\"] = self.__passw\n return aDic\n\n def getName(self):\n '''\n return the OBS server name.\n '''\n return self.__alias\n\n def getPackageList(self, projectLocalName=None):\n return ObsLightOsc.getObsLightOsc().getPackageList(apiurl=self.__serverAPI,\n projectLocalName=projectLocalName)\n\n def checkoutPackage(self, projectObsName=None, package=None, directory=None):\n ObsLightOsc.getObsLightOsc().checkoutPackage(obsServer=self.__serverAPI,\n projectObsName=projectObsName,\n package=package,\n directory=directory)\n\n def getPackageStatus(self,\n project=None,\n package=None,\n repo=None,\n arch=None):\n return ObsLightOsc.getObsLightOsc().getPackageStatus(obsServer=self.__serverAPI,\n project=project,\n package=package,\n repo=repo,\n arch=arch)\n\n def getDependencyRepositories(self, projectObsName, target, arch):\n '''\n Return the list of the dependency repositories.\n '''\n\n\n result1 = ObsLightOsc.getObsLightOsc().getDependencyProjects(self.__serverAPI,\n projectObsName, target)\n\n result2 = {}\n for prj in result1.keys():\n url = os.path.join(self.__serverRepo, prj.replace(\":\", \":/\"), result1[prj])\n\n alias = ObsLightOsc.getObsLightOsc().getAliasOfRepo(url + \"/\" + prj + \".repo\")\n if alias != None:\n result2[alias] = url\n\n listUrl = ObsLightOsc.getObsLightOsc().getDODUrl(self.__serverAPI, prj, arch)\n if listUrl != None:\n for url in listUrl:\n alias = ObsLightOsc.getObsLightOsc().getAliasOfRepo(url)\n if alias != None:\n result2[alias] = url\n\n return result2\n\n def getRepo(self):\n if self.__serverRepo != None:\n return self.__serverRepo\n else:\n raise ObsLightErr.ObsLightObsServers(\"In \" + self.__alias + \" there is no repo\")\n\n\n def getLocalProjectList(self,\n maintainer=False,\n bugowner=False,\n arch=None,\n remoteurl=False,\n raw=True):\n logger = ObsLightPrintManager.getLogger()\n logger.info(\"Getting project list from %s\" % self.__serverAPI)\n\n if (\"https://api.meego.com\" in self.__serverAPI):\n msg = \"api.meego.com doesn't support search request, Bug 24979\"\n logger.warning(msg)\n\n obsLightOsc = ObsLightOsc.getObsLightOsc()\n if (not raw) and not (\"https://api.meego.com\" in self.__serverAPI):\n aBugowner = None\n if bugowner:\n aBugowner = self.__user\n\n aMaintainer = None\n if maintainer:\n aMaintainer = self.__user\n\n return obsLightOsc.getFilteredProjectListFromServer(self.__serverAPI,\n aMaintainer,\n aBugowner,\n arch,\n remoteurl)\n else:\n return obsLightOsc.getProjectListFromServer(self.__serverAPI)\n\n def getTargetList(self, projectObsName=None):\n return ObsLightOsc.getObsLightOsc().getTargetList(obsServer=self.__serverAPI,\n projectObsName=projectObsName)\n\n def getArchitectureList(self,\n projectObsName=None,\n projectTarget=None):\n return ObsLightOsc.getObsLightOsc().getArchitectureList(obsServer=self.__serverAPI ,\n projectObsName=projectObsName,\n projectTarget=projectTarget)\n\n\n\n def getUrlServerWeb(self):\n return self.__serverWeb\n\n def getProjectTitle(self, projectObsName):\n return ObsLightOsc.getObsLightOsc().getProjectParameter(projectObsName=projectObsName,\n apiurl=self.__serverAPI,\n parameter=\"title\")\n\n def getProjectDescription(self, projectObsName):\n return ObsLightOsc.getObsLightOsc().getProjectParameter(projectObsName=projectObsName,\n apiurl=self.__serverAPI,\n parameter=\"description\")\n\n\n def createObsProject(self, projectObsName, title=\"\", description=\"\"):\n return ObsLightOsc.getObsLightOsc().createObsProject(self.__serverAPI,\n projectObsName,\n self.__user,\n title,\n description)\n\n\n def createObsPackage(self, projectObsName, package, title=\"\", description=\"\"):\n return ObsLightOsc.getObsLightOsc().createObsPackage(self.__serverAPI,\n projectObsName,\n package,\n title,\n description)\n\n def saveProjectConfig(self, projectObsName, target):\n return ObsLightOsc.getObsLightOsc().saveProjectConfig(self.__serverAPI,\n projectObsName,\n target)\n\n","sub_path":"obslight/ObsLight/ObsLightServer.py","file_name":"ObsLightServer.py","file_ext":"py","file_size_in_byte":19951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"38607227","text":"# coding=utf-8\nfrom socket import *\nfrom multiprocessing import *\n# 导入正则\nimport re\n\n# 静态文件根目录\nHTML_ROOT_DIR=\"./html\"\n\ndef handle_conn(client_socket,client_addr):\n\n # 接收数据\n request_data = client_socket.recv(1024);\n print(\"request data:\",request_data)\n\n if(len(request_data)<=0):\n client_socket.close()\n return\n\n # 解析http数据报文\n # 按照换行符进行分割\n request_lines = request_data.splitlines()\n for line in request_lines:\n print(line)\n\n # 提取请求方式\n # 获取第一行\n # 'GET / HTTP/1.1'\n request_start_line = request_lines[0]\n # 提取请求路径\n # 使用正则表达式进行划分\n # \\w+ 多个字母开头 \\s一个或者多个空格 /[^\\s]*表示/后面非空格的多个值\n file_name = re.match(r\"\\w+\\s+(/[^\\s]*)\\s\",request_start_line.decode(\"utf-8\")).group(1)\n # 可以获得第一个/后面的值\n if \"/\" == file_name:\n # 判断默认路径\n file_name = \"/index.html\"\n\n # 打开文件,有可能打开的是图片,以二进制的方式读取\n try:\n file = open(HTML_ROOT_DIR+file_name,\"rb\")\n except IOError:\n response_start_line = \"HTTP/1.1 404 Not Found\\r\\n\"\n response_body=\"the file is not found\"\n else:\n file_data = file.read()\n # 返回响应的数据 http 响应格式\n \"\"\"\n HTTP 1.1 200 OK\\r\\n\n \\r\\n\n hello world\n \"\"\"\n # 构造响应数据\n response_start_line=\"HTTP/1.1 200 OK\\r\\n\"\n response_body=file_data.decode(\"utf-8\")\n\n response_headers=\"Server: My Server\\r\\n\"\n response = response_start_line+response_headers+\"\\r\\n\"+response_body\n print(\"response data:\",response)\n\n # 向客户端返回响应数据\n # client_socket.send(response.encode())\n client_socket.send(bytes(response,\"utf-8\"))\n client_socket.close()\n\nif __name__ == '__main__':\n\n server = socket(AF_INET, SOCK_STREAM)\n # 修改socket级别参数值reuseaddr,重用ip地址\n server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n # 设置端口号\n server.bind(('', 8090))\n # 设置监听队列\n server.listen(128)\n\n while True:\n client_socket,client_addr = server.accept()\n # print(\"[%s %s] 已经连接上了\"%(client_addr[0],client_addr[1]))\n # 等价于\n print(\"[%s %s] 已经连接上了\"%client_addr)\n p = Process(target=handle_conn,args=(client_socket,client_addr))\n p.start()\n # 注意关闭client的socket 由于p进程已经收到client的socket,原先的关闭\n client_socket.close()\n","sub_path":"code/03.web服务器/02.web静态服务简单实现-返回静态页面.py","file_name":"02.web静态服务简单实现-返回静态页面.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"649320665","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nimport datetime\nimport calendar\nfrom django.db.models import Q\nfrom sjdl.news.models import News\nfrom mezzanine.galleries.models import Gallery\nfrom mezzanine.galleries.models import GalleryImage\n\ndef listing(request):\n news = News.latest_news_list()[:8]\n\n archives = News.latest_news_list()\n\n return render(request, 'news/index.html', {'news':news,'archives':archives})\n\ndef archives(request, year, month):\n monthrange = calendar.monthrange(int(year), int(month))\n \n dateMin = datetime.date(int(year),int(month),1)\n dateMax = datetime.date(dateMin.year, dateMin.month, monthrange[1])\n\n news = News.objects.filter(\n Q(publish_date__range = (dateMin,dateMax)) | Q(publish_date__isnull = True)\n ).filter(\n Q(expiry_date__gte = dateMax) | Q(expiry_date__isnull = True)\n ).filter(\n status = 2\n ).order_by('-publish_date')\n\n archives = News.latest_news_list()\n\n return render(request, 'news/index.html', {'news':news,'archives':archives})\n\ndef detail(request, slug):\n news = get_object_or_404(News, slug=slug)\n images = None\n\n if news.ik_diapo_id is not None:\n gallery = Gallery.objects.get(id=news.ik_diapo_id)\n images = GalleryImage.objects.all().filter(gallery_id=gallery.id)\n\n archives = News.latest_news_list()\n\n return render(request, 'news/detail.html', {'news':news, 'images':images,'archives':archives})","sub_path":"news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"393223166","text":"\"\"\"Parsing of Storm Prediction Center SAW Product\n\nThis does not process the legacy SAW products that did not have LAT...LON\n\"\"\"\nimport re\nimport datetime\n\nfrom shapely.geometry import Polygon as ShapelyPolygon\nfrom shapely.geometry import MultiPolygon\nfrom pyiem.nws.product import TextProduct\nfrom pyiem.util import utc\nfrom pyiem.exceptions import SAWException\n\nLATLON = re.compile(r\"LAT\\.\\.\\.LON\\s+((?:[0-9]{8}\\s+)+)\")\nNUM_RE = re.compile(\n r\"WW ([0-9]*) (TEST)?\\s?\" \"(SEVERE TSTM|TORNADO|SEVERE THUNDERSTORM)\"\n)\nREPLACES_RE = re.compile(\"REPLACES WW ([0-9]*)\")\nDBTYPES = [\"TOR\", \"SVR\"]\nTYPE2STRING = [\"Tornado\", \"Severe Thunderstorm\"]\n\n\nclass SAWProduct(TextProduct):\n \"\"\"Class representing a SAW Product\"\"\"\n\n (TORNADO, SEVERE_THUNDERSTORM) = range(2)\n (ISSUES, CANCELS) = range(2)\n\n def __init__(self, text, utcnow=None):\n \"\"\"Constructor\n\n Args:\n text (str): text to parse\n \"\"\"\n TextProduct.__init__(self, text, utcnow=utcnow)\n self.saw = int(self.afos[3:].strip())\n self.action = self.find_action()\n self.geometry = self.find_polygon()\n self.ww_num = self.find_ww_num()\n (self.sts, self.ets) = self.find_time()\n self.ww_type = self.find_ww_type()\n self.affected_wfos = []\n\n def find_action(self):\n \"\"\"Figure out if this is an issuance or cancells statement\n\n Return:\n (int): either ISSUES or CANCELS\n \"\"\"\n if re.findall(\"CANCELLED\", self.unixtext):\n return self.CANCELS\n return self.ISSUES\n\n def compute_wfos(self, txn):\n \"\"\"Figure out who is impacted by this watch\"\"\"\n if self.geometry is None:\n return\n txn.execute(\n \"SELECT distinct wfo from ugcs WHERE \"\n f\"ST_Contains('SRID=4326;{self.geometry.wkt}', geom) \"\n \"and end_ts is null\"\n )\n for row in txn.fetchall():\n self.affected_wfos.append(row[0])\n\n def sql(self, txn):\n \"\"\"Do the necessary database work\n\n Args:\n (psycopg2.transaction): a database transaction\n \"\"\"\n if self.action == self.ISSUES:\n # Delete any current entries\n txn.execute(\n \"DELETE from watches WHERE num = %s and \"\n \"extract(year from issued) = %s\",\n (self.ww_num, self.sts.year),\n )\n # Insert into the main watches table\n giswkt = \"SRID=4326;%s\" % (MultiPolygon([self.geometry]).wkt,)\n sql = (\n \"INSERT into watches (sel, issued, expired, type, report, \"\n \"geom, num) VALUES(%s,%s,%s,%s,%s,%s,%s)\"\n )\n args = (\n \"SEL%s\" % (self.saw,),\n self.sts,\n self.ets,\n DBTYPES[self.ww_type],\n self.unixtext,\n giswkt,\n self.ww_num,\n )\n txn.execute(sql, args)\n # Update the watches_current table\n sql = (\n \"UPDATE watches_current SET issued = %s, expired = %s, \"\n \"type = %s, report = %s, geom = %s, num = %s WHERE sel = %s\"\n )\n args = (\n self.sts,\n self.ets,\n DBTYPES[self.ww_type],\n self.unixtext,\n giswkt,\n self.ww_num,\n \"SEL%s\" % (self.saw,),\n )\n txn.execute(sql, args)\n # Is this a replacement?\n if REPLACES_RE.findall(self.unixtext):\n rnum = REPLACES_RE.findall(self.unixtext)[0][0]\n txn.execute(\n \"UPDATE watches SET expired = %s \"\n \"WHERE num = %s and extract(year from expired) = %s\",\n (self.valid, rnum, self.sts.year),\n )\n elif self.action == self.CANCELS:\n for table in (\"watches\", \"watches_current\"):\n txn.execute(\n f\"UPDATE {table} SET expired = %s \"\n \"WHERE num = %s and extract(year from expired) = %s\",\n (self.valid, self.ww_num, self.valid.year),\n )\n if table == \"watches\" and txn.rowcount != 0:\n self.warnings.append(\n \"Expiration of watch resulted in \"\n f\"update of {txn.rowcount} rows, instead of 1.\"\n )\n\n def find_time(self):\n \"\"\"Find the start and end valid time of this watch\n\n Returns:\n (datetime, datetime): representing the time of this watch\n \"\"\"\n if self.action == self.CANCELS:\n return (None, None)\n tokens = re.findall(\n \"([0-3][0-9])([0-2][0-9])([0-6][0-9])Z - \"\n \"([0-3][0-9])([0-2][0-9])([0-6][0-9])Z\",\n self.unixtext,\n )\n\n day1 = int(tokens[0][0])\n hour1 = int(tokens[0][1])\n minute1 = int(tokens[0][2])\n day2 = int(tokens[0][3])\n hour2 = int(tokens[0][4])\n minute2 = int(tokens[0][5])\n\n sts = utc(self.utcnow.year, self.utcnow.month, day1, hour1, minute1)\n ets = utc(self.utcnow.year, self.utcnow.month, day2, hour2, minute2)\n\n # If we are near the end of the month and the day1 is 1, add 1 month\n if self.utcnow.day > 27 and day1 == 1:\n sts += datetime.timedelta(days=+35)\n sts = sts.replace(day=1)\n if self.utcnow.day > 27 and day2 == 1:\n ets += datetime.timedelta(days=+35)\n ets = ets.replace(day=1)\n return (sts, ets)\n\n def find_ww_num(self):\n \"\"\"Find the Weather Watch Number\n\n Returns:\n (int): The Weather Watch Number\n \"\"\"\n tokens = NUM_RE.findall(self.unixtext)\n if not tokens:\n raise SAWException(\"Could not locate Weather Watch Number\")\n return int(tokens[0][0])\n\n def is_test(self):\n \"\"\"Is this a test watch?\n\n Returns:\n boolean if this SAW is a test or not\n \"\"\"\n tokens = NUM_RE.findall(self.unixtext)\n if not tokens:\n raise SAWException(\"Could not locate Weather Watch Number\")\n return tokens[0][1] == \"TEST\"\n\n def find_ww_type(self):\n \"\"\"Find the Weather Watch Type\n\n Returns:\n (int): The Weather Watch Type\n \"\"\"\n tokens = NUM_RE.findall(self.unixtext)\n if not tokens:\n raise SAWException(\"Could not locate Weather Watch Type\")\n if tokens[0][2] == \"TORNADO\":\n return self.TORNADO\n return self.SEVERE_THUNDERSTORM\n\n def find_polygon(self):\n \"\"\"Search out the text for the LAT...LON polygon\n\n Returns:\n (str): Well Known Text (WKT) representation\n \"\"\"\n if self.action == self.CANCELS:\n return\n tokens = LATLON.findall(self.unixtext.replace(\"\\n\", \" \"))\n if not tokens:\n raise SAWException(\"Could not parse LAT...LON geometry\")\n pts = []\n for pair in tokens[0].split():\n lat = float(pair[:4]) / 100.0\n lon = 0 - float(pair[4:]) / 100.0\n if lon > -40:\n lon = lon - 100.0\n pts.append((lon, lat))\n return ShapelyPolygon(pts)\n\n def get_jabbers(self, uri, _uri2=None):\n \"\"\"Generate the jabber messages for this Product\n\n NOTE: In the past, the messages generated here have tripped twitter's\n spam logic, so we are careful to craft unique messages\n\n Args:\n uri (str): un-used in this context\n \"\"\"\n res = []\n url = (\"https://www.spc.noaa.gov/products/watch/%s/ww%04i.html\") % (\n self.valid.year,\n self.ww_num,\n )\n spc_channels = f\"SPC,SPC.{DBTYPES[self.ww_type]}WATCH\"\n if self.action == self.CANCELS:\n plain = (\n \"Storm Prediction Center cancels Weather Watch Number %s \" \"%s\"\n ) % (self.ww_num, url)\n html = (\n 'Storm Prediction Center cancels '\n \"Weather Watch Number %s
\"\n ) % (url, self.ww_num)\n res.append(\n [plain, html, dict(channels=spc_channels, twitter=plain)]\n )\n # Now create templates\n plain = (\n \"Storm Prediction Center cancels Weather Watch Number %s \"\n \"for portions of %%s %s\"\n ) % (self.ww_num, url)\n html = (\n 'Storm Prediction Center cancels '\n \"Weather Watch Number %s for portions of %%s
\"\n ) % (url, self.ww_num)\n elif self.action == self.ISSUES:\n plain = (\"SPC issues %s Watch %s till %sZ\") % (\n TYPE2STRING[self.ww_type],\n self.ww_num,\n self.ets.strftime(\"%-H:%M\"),\n )\n html = (\n \"Storm Prediction Center issues \"\n '%s Watch %s '\n \"till %s UTC\"\n ) % (\n int(self.ww_num),\n TYPE2STRING[self.ww_type],\n self.ww_num,\n self.ets.strftime(\"%-H:%M\"),\n )\n if REPLACES_RE.findall(self.unixtext):\n rtext = (\"WW %s \") % (\n REPLACES_RE.findall(self.unixtext)[0][0].strip(),\n )\n plain += \", new watch replaces \" + rtext\n html += \", new watch replaces \" + rtext\n\n plain2 = \"%s %s\" % (plain, url)\n plain2 = \" \".join(plain2.split())\n html2 = html + (\n ' (Watch ' \"Quickview)
\"\n ) % (uri, self.sts.year, self.ww_num)\n res.append(\n [plain2, html2, dict(channels=spc_channels, twitter=plain2)]\n )\n # Now create templates\n plain += \" for portions of %%s %s\" % (url,)\n html += (\n \" for portions of %%s \"\n '(Watch '\n \"Quickview)
\"\n ) % (uri, self.sts.year, self.ww_num)\n\n plain = \" \".join(plain.split())\n for wfo in self.affected_wfos:\n res.append(\n [\n plain % (wfo,),\n html % (wfo,),\n dict(channels=wfo, twitter=(plain % (wfo,))),\n ]\n )\n return res\n\n\ndef parser(text, utcnow=None):\n \"\"\"parser of raw SPC SAW Text\n\n Args:\n text (str): the raw text to parse\n utcnow (datetime): the current datetime with timezone set!\n\n Returns:\n SAWProduct instance\n \"\"\"\n return SAWProduct(text, utcnow=utcnow)\n","sub_path":"src/pyiem/nws/products/saw.py","file_name":"saw.py","file_ext":"py","file_size_in_byte":10866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"104576026","text":"\"\"\"Memory related utils.\n\"\"\"\nimport getpass\nimport sys\nimport math\nfrom collections import deque\nimport time\nfrom argparse import ArgumentParser, Namespace\nimport numpy as np\nimport psutil\nfrom loguru import logger\n\nUSER = getpass.getuser()\n\n\ndef get_memory_usage(user: str = USER) -> int:\n \"\"\"Get the memory usage of the specified user.\n\n :param user: The user whose memory usage to get.\n :return: The memory usage of the user in bytes.\n \"\"\"\n STATUS = (\n psutil.STATUS_RUNNING,\n psutil.STATUS_SLEEPING,\n psutil.STATUS_DISK_SLEEP,\n psutil.STATUS_WAKING,\n psutil.STATUS_PARKED,\n psutil.STATUS_IDLE,\n psutil.STATUS_WAITING,\n )\n try:\n return sum(\n p.memory_info().rss for p in psutil.process_iter()\n if p.username() == USER and p.status() in STATUS\n )\n except:\n return get_memory_usage(user)\n\n\ndef monitor_memory_usage(seconds: float = 1, user: str = USER):\n \"\"\"Log out the memory usage of the specified user in a specified frequency.\n\n :param seconds: The number of seconds to wait before the next logging.\n :param user: The user whose memory usage to monitor.\n \"\"\"\n while True:\n time.sleep(seconds)\n logger.info(\"Memory used by {}: {:,}\", user, get_memory_usage(user=user))\n\n\ndef match_memory_usage(\n target: float,\n arr_size: int = 1_000_000,\n sleep_min: float = 1,\n sleep_max: float = 30\n):\n \"\"\"Match a user's memory usage to the specified value.\n The memory usage will gradually increase to the specified value \n if it is smaller than the specified value.\n Otherwise, \n the memory usage drops immediately to match the specified value.\n\n :param target: The target memory in bytes.\n :param arr_size: The size of integer arrays for consuming memory.\n :param sleep_min: The minimum time of sleeping.\n :param sleep_max: The maximum time of sleeping.\n \"\"\"\n logger.info(\"Target memory: {:,.0f}\", target)\n # define an template array\n arr = list(range(arr_size))\n size = sys.getsizeof(arr)\n # deque for consuming memory flexibly\n dq = deque()\n # define 2 points for linear interpolation of sleep seconds\n xp = (0, 10)\n yp = (sleep_max, sleep_min)\n while True:\n mem = get_memory_usage(USER)\n logger.info(\n \"Current used memory by {}: {:,} out of which {:,} is contributed by the memory matcher\",\n USER, mem, size * len(dq)\n )\n diff = (target - mem) / size\n if diff > 0:\n logger.info(\"Consuming more memory ...\")\n dq.append(arr.copy())\n time.sleep(np.interp(diff, xp, yp))\n else:\n count = min(math.ceil(-diff), len(dq))\n logger.info(\"Releasing memory ...\")\n for _ in range(count):\n dq.pop()\n time.sleep(np.interp(count, xp, yp))\n\n\ndef parse_args(args=None, namespace=None) -> Namespace:\n \"\"\"Parse command-line arguments.\n\n :param args: The arguments to parse. \n If None, the arguments from command-line are parsed.\n :param namespace: An inital Namespace object.\n :return: A namespace object containing parsed options.\n \"\"\"\n parser = ArgumentParser(\n description=\"Make memory consumption match the specified target.\"\n )\n mutex = parser.add_mutually_exclusive_group()\n mutex.add_argument(\n \"-g\",\n dest=\"target\",\n type=lambda s: int(s) * 1073741824,\n help=\"Specify target memory in gigabytes.\"\n )\n mutex.add_argument(\n \"-m\",\n dest=\"target\",\n type=lambda s: int(s) * 1048576,\n help=\"Specify target memory in megabytes.\"\n )\n return parser.parse_args(args=args, namespace=namespace)\n\n\ndef main():\n \"\"\"The main function for scripting usage.\n \"\"\"\n args = parse_args()\n match_memory_usage(args.target)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dsutil/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"330551532","text":"import random, string\n\nnum = \"0123456789\"\nupp = \"ABCDEFGHIJKLMNOPQRSTYVWXYZ\"\nlow = \"abcdefghijklmnopqrstuvwxyz\"\n\nen = \"BNZQ:1l36de9583w5516fv3b8691102224f3e\"\nres = \"\"\ncnt = 0\nfor i in range(len(en)):\n c = en[i]\n if c.islower():\n for j in range(len(low)):\n random.seed(\"random\")\n for k in range(cnt):\n random.randrange(0, 1)\n val = chr((ord(low[j])-ord('a')+random.randrange(0,26))%26 + ord('a'))\n if val == c:\n res += low[j]\n cnt += 1\n break\n elif c.isupper():\n for j in range(len(upp)):\n random.seed(\"random\")\n for k in range(cnt):\n random.randrange(0, 1)\n val = chr((ord(upp[j])-ord('A')+random.randrange(0,26))%26 + ord('A'))\n if val == c:\n res += upp[j]\n cnt += 1\n break\n elif c.isdigit():\n for j in range(len(num)):\n random.seed(\"random\")\n for k in range(cnt):\n random.randrange(0, 1)\n val = chr((ord(num[j])-ord('0')+random.randrange(0,10))%10 + ord('0'))\n if val == c:\n res += num[j]\n cnt += 1\n break\n else:\n res += c\n\nprint(res)\n","sub_path":"2017_picoctf/LEVEL_2/Cryptography/SoRandom-75/sorandom_solve.py","file_name":"sorandom_solve.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"410740382","text":"import torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import DataLoader\nimport os\nfrom PIL import Image\nimport pandas as pd\nimport numpy as np\nimport cv2\nfrom elastic_transform import ElasticTransform\n\nclass MyDigitsDataset(Dataset):\n def __init__(self, csv_path,img_path, transform=None):\n \"\"\"\n Args:\n csv_path (string): path to csv file\n img_path (string): path to the folder where images are\n transform: Optional transform to be applied on a sample.\n \"\"\"\n self.data = pd.read_csv(csv_path,sep=\";\")\n self.name_files = np.asarray(self.data.iloc[:, 0])\n self.labels = np.asarray(self.data.iloc[:, 1])\n self.img_path = img_path\n self.transform = transform\n \n def __getitem__(self, index):\n # stuff\n single_image_label = self.labels[index] -1\n if single_image_label==-1:\n single_image_label=9\n\n img_name = os.path.join(self.img_path,self.name_files[index])\n data = Image.open(img_name).convert('RGB')\n #data = data.resize((32, 32)) \n #data=cv2.imread(img_name)\n #data = cv2.resize(data, (32, 32)) \n #data = np.asarray(img)\n #data = np.transpose(data,(2,0,1))\n if self.transform is not None:\n data = self.transform(data)\n # If the transform variable is not empty\n # then it applies the operations in the transforms with the order that it is created.\n return (data, single_image_label)\n\n def __len__(self):\n return len(self.labels) \n\ndef get(batch_size, csv_path='', data_root='/tmp/public_dataset/pytorch', train=True, val=True, show=False, **kwargs):\n #data_root = os.path.expanduser(os.path.join(data_root, 'svhn-data'))\n num_workers = kwargs.setdefault('num_workers', 0)\n kwargs.pop('input_size', None)\n #print(\"Building SVHN data loader with {} workers\".format(num_workers))\n\n def target_transform(target):\n return int(target[0]) - 1\n\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n MyDigitsDataset(\n csv_path=csv_path, img_path=data_root,\n transform=transforms.Compose([\n transforms.RandomApply(\n [transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.3),\n transforms.RandomRotation(15),\n transforms.RandomAffine(0,scale=(0.7,0.9)),\n transforms.RandomAffine(0,scale=(1.1,1.2)),\n transforms.RandomAffine(0,shear=10),\n ElasticTransform(1000,30)],p=0.5),\n transforms.Resize((32,32)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n ),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n\n if val:\n test_loader = torch.utils.data.DataLoader(\n MyDigitsDataset(\n csv_path=csv_path, img_path=data_root,\n transform=transforms.Compose([\n transforms.Resize((32,32)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n ), \n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n \n\n if show:\n show_loader = torch.utils.data.DataLoader(\n MyDigitsDataset(\n csv_path=csv_path, img_path=data_root,\n transform=transforms.Compose([ \n transforms.RandomApply(\n [transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.3),\n transforms.RandomRotation(15),\n transforms.RandomAffine(0,scale=(0.7,0.9)),\n transforms.RandomAffine(0,scale=(1.1,1.2)),\n transforms.RandomAffine(0,shear=10),\n ElasticTransform(1000,30)],p=0.5),\n #transforms.Resize((32,32)),\n transforms.ToTensor()\n ])\n ),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(show_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\n","sub_path":"svhn/dataset_digits.py","file_name":"dataset_digits.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"334010734","text":"import numpy as np\n\n\ndef rbf(d, eps):\n return np.exp(-(d * eps) ** 2)\n\n\ndef distance(x, y):\n return np.sum(np.abs(x - y))\n\n\ndef pairwise_distances(X):\n D = np.zeros((len(X), len(X)))\n\n for i in range(len(X)):\n for j in range(len(X)):\n if i == j:\n continue\n\n d = distance(X[i], X[j])\n\n D[i][j] = d\n D[j][i] = d\n\n return D\n\n\ndef taxicab_sample(n, r):\n sample = []\n\n for _ in range(n):\n spread = r - np.sum([np.abs(x) for x in sample])\n sample.append(spread * (2 * np.random.rand() - 1))\n\n return np.random.permutation(sample)\n\n\nclass RBFUnderSampler:\n def __init__(self, gamma=0.05, n=None, scaled=False):\n self.gamma = gamma\n self.n = n\n self.scaled = scaled\n\n def fit_sample(self, X, y):\n if self.scaled:\n gamma = self.gamma * np.sqrt(X.shape[1])\n else:\n gamma = self.gamma\n\n classes = np.unique(y)\n sizes = [sum(y == c) for c in classes]\n majority_class = classes[np.argmax(sizes)]\n minority_class = classes[np.argmin(sizes)]\n\n if self.n is None:\n n = sum(y == majority_class) - sum(y == minority_class)\n else:\n n = self.n\n\n D = pairwise_distances(X)\n\n scores = np.zeros(len(X))\n\n for i in range(len(X)):\n if y[i] == minority_class:\n scores[i] = -np.inf\n else:\n score = 0.0\n\n for j in range(len(X)):\n multiplier = (1 if y[j] == majority_class else -1)\n score += multiplier * rbf(D[i][j], 1.0 / gamma)\n\n scores[i] = score\n\n discarded = []\n\n while len(discarded) < n:\n candidate = np.argmax(scores)\n discarded.append(candidate)\n\n for i in range(len(X)):\n scores[i] -= rbf(D[i][candidate], 1.0 / gamma)\n\n scores[candidate] = -np.inf\n\n return np.delete(X, discarded, axis=0), np.delete(y, discarded, axis=0)\n\n\nclass RBFOverSampler:\n def __init__(self, gamma=0.05, epsilon=0.05, n=None, n_samples=10, minimize=False, scaled=False):\n self.gamma = gamma\n self.epsilon = epsilon\n self.n = n\n self.n_samples = n_samples\n self.minimize = minimize\n self.scaled = scaled\n\n def fit_sample(self, X, y):\n if self.scaled:\n gamma = self.gamma * np.sqrt(X.shape[1])\n else:\n gamma = self.gamma\n\n classes = np.unique(y)\n sizes = [sum(y == c) for c in classes]\n majority_class = classes[np.argmax(sizes)]\n minority_class = classes[np.argmin(sizes)]\n\n if self.n is None:\n n = sum(y == majority_class) - sum(y == minority_class)\n else:\n n = self.n\n\n appended = []\n\n while len(appended) < n:\n points = []\n scores = []\n\n for _ in range(self.n_samples):\n idx = np.random.choice(range(len(X[y == minority_class])))\n point = X[y == minority_class][idx]\n point += self.epsilon * (2 * np.random.rand(*point.shape) - 1)\n score = 0.0\n\n for i in range(len(X)):\n multiplier = (1 if y[i] == majority_class else -1)\n score += multiplier * rbf(distance(X[i], point), 1.0 / gamma)\n\n points.append(point)\n scores.append(score)\n\n if self.minimize:\n i = np.argmin(scores)\n else:\n i = np.argmax(scores)\n\n appended.append(points[i])\n\n return np.concatenate([X, appended]), np.concatenate([y, minority_class * np.ones(len(appended))])\n\n\nclass RBFCombined:\n def __init__(self, alpha=0.05, gamma=0.05, epsilon=0.05, n_samples=10, minimize=False, scaled=False):\n self.alpha = alpha\n self.gamma = gamma\n self.epsilon = epsilon\n self.n_samples = n_samples\n self.minimize = minimize\n self.scaled = scaled\n\n def fit_sample(self, X, y):\n classes = np.unique(y)\n sizes = [sum(y == c) for c in classes]\n majority_class = classes[np.argmax(sizes)]\n minority_class = classes[np.argmin(sizes)]\n n = sum(y == majority_class) - sum(y == minority_class)\n n_undersample = int(self.alpha * n)\n n_oversample = n - n_undersample\n\n undersampler = RBFUnderSampler(gamma=self.gamma, n=n_undersample, scaled=self.scaled)\n X_undersampled, y_undersampled = undersampler.fit_sample(X, y)\n oversampler = RBFOverSampler(gamma=self.gamma, epsilon=self.epsilon, n=n_oversample, n_samples=self.n_samples,\n minimize=self.minimize, scaled=self.scaled)\n X_oversampled, y_oversampled = oversampler.fit_sample(X_undersampled, y_undersampled)\n\n return X_oversampled, y_oversampled\n\n\nclass RBFADASYN:\n def __init__(self, gamma=0.05, epsilon=0.025, n=None, n_samples=10, minimize=False, scaled=False):\n self.gamma = gamma\n self.epsilon = epsilon\n self.n = n\n self.n_samples = n_samples\n self.minimize = minimize\n self.scaled = scaled\n\n def fit_sample(self, X, y):\n if self.scaled:\n gamma = self.gamma * np.sqrt(X.shape[1])\n else:\n gamma = self.gamma\n\n classes = np.unique(y)\n sizes = [sum(y == c) for c in classes]\n majority_class = classes[np.argmax(sizes)]\n minority_class = classes[np.argmin(sizes)]\n minority = X[y == minority_class]\n\n if self.n is None:\n n = sum(y == majority_class) - sum(y == minority_class)\n else:\n n = self.n\n\n scores = []\n\n for observation in minority:\n score = 0.0\n\n for i in range(len(X)):\n multiplier = (1.0 if y[i] == majority_class else -1.0)\n score += multiplier * rbf(distance(X[i], observation), 1.0 / gamma) / len(X)\n\n scores.append(score)\n\n confidence = np.array(scores) - np.min(scores) + np.max([np.abs(np.max(scores) - np.min(scores)), 1e-6])\n confidence /= np.sum(confidence)\n synthetic_samples = [int(np.round(c * n)) for c in confidence]\n appended = []\n\n for i in range(len(minority)):\n observation = minority[i]\n\n for _ in range(synthetic_samples[i]):\n points = []\n scores = []\n\n for _ in range(self.n_samples):\n point = observation + self.epsilon * (2 * np.random.rand(*observation.shape) - 1)\n score = 0.0\n\n for j in range(len(X)):\n multiplier = (1.0 if y[j] == majority_class else -1.0)\n score += multiplier * rbf(distance(X[j], point), 1.0 / gamma) / len(X)\n\n points.append(point)\n scores.append(score)\n\n if self.minimize:\n j = np.argmin(scores)\n else:\n j = np.argmax(scores)\n\n appended.append(points[j])\n\n return np.concatenate([X, appended]), np.concatenate([y, minority_class * np.ones(len(appended))])\n\n\nclass CCR:\n def __init__(self, energy=None, n=None):\n self.energy = energy\n self.n = n\n\n def fit_sample(self, X, y):\n classes = np.unique(y)\n sizes = [sum(y == c) for c in classes]\n\n assert len(classes) == len(set(sizes)) == 2\n\n minority_class = classes[np.argmin(sizes)]\n majority_class = classes[np.argmax(sizes)]\n minority = X[y == minority_class]\n majority = X[y == majority_class]\n\n if self.n is None:\n n = len(majority) - len(minority)\n else:\n n = self.n\n\n if self.energy is None:\n energy = 0.25 * np.sqrt(X.shape[1])\n else:\n energy = self.energy\n\n distances = np.zeros((len(minority), len(majority)))\n\n for i in range(len(minority)):\n for j in range(len(majority)):\n distances[i][j] = distance(minority[i], majority[j])\n\n radii = np.zeros(len(minority))\n translations = np.zeros(majority.shape)\n\n for i in range(len(minority)):\n minority_point = minority[i]\n remaining_energy = energy\n r = 0.0\n sorted_distances = np.argsort(distances[i])\n current_majority = 0\n\n while True:\n if current_majority == len(majority):\n if current_majority == 0:\n radius_change = remaining_energy / (current_majority + 1.0)\n else:\n radius_change = remaining_energy / current_majority\n\n r += radius_change\n\n break\n\n radius_change = remaining_energy / (current_majority + 1.0)\n\n if distances[i, sorted_distances[current_majority]] >= r + radius_change:\n r += radius_change\n\n break\n else:\n if current_majority == 0:\n last_distance = 0.0\n else:\n last_distance = distances[i, sorted_distances[current_majority - 1]]\n\n radius_change = distances[i, sorted_distances[current_majority]] - last_distance\n r += radius_change\n remaining_energy -= radius_change * (current_majority + 1.0)\n current_majority += 1\n\n radii[i] = r\n\n for j in range(current_majority):\n majority_point = majority[sorted_distances[j]]\n d = distances[i, sorted_distances[j]]\n\n if d < 1e-20:\n majority_point += (1e-6 * np.random.rand(len(majority_point)) + 1e-6) * np.random.choice([-1.0, 1.0], len(majority_point))\n d = distance(minority_point, majority_point)\n\n translation = (r - d) / d * (majority_point - minority_point)\n translations[sorted_distances[j]] += translation\n\n majority += translations\n\n appended = []\n\n for i in range(len(minority)):\n minority_point = minority[i]\n synthetic_samples = int(np.round(1.0 / (radii[i] * np.sum(1.0 / radii)) * n))\n r = radii[i]\n\n for _ in range(synthetic_samples):\n appended.append(minority_point + taxicab_sample(len(minority_point), r))\n\n return np.concatenate([majority, minority, appended]), \\\n np.concatenate([np.tile([majority_class], len(majority)),\n np.tile([minority_class], len(minority) + len(appended))])\n","sub_path":"algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":10790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"13788806","text":"# =====================================================================================\n# PROBLEM A2 \n#\n# Build a Neural Network Model for Horse or Human Dataset.\n# The test will expect it to classify binary classes. \n# Your input layer should accept 150x150 with 3 bytes color as the input shape.\n# Don't use lambda layers in your model.\n#\n# The dataset used in this problem is created by Laurence Moroney (laurencemoroney.com).\n#\n# Desired accuracy and validation_accuracy > 83%\n# ======================================================================================\n\nimport urllib.request\nimport zipfile\nfrom numpy.lib.financial import rate\nimport tensorflow as tf\nimport os\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom tensorflow import keras\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.python.keras.backend import dropout\n\n\ndef solution_A2():\n #data_url_1 = 'https://dicodingacademy.blob.core.windows.net/picodiploma/Simulation/machine_learning/horse-or-human.zip'\n #urllib.request.urlretrieve(data_url_1, 'horse-or-human.zip')\n #local_file = 'horse-or-human.zip'\n #zip_ref = zipfile.ZipFile(local_file, 'r')\n #zip_ref.extractall('data/horse-or-human')\n\n #data_url_2 = 'https://dicodingacademy.blob.core.windows.net/picodiploma/Simulation/machine_learning/validation-horse-or-human.zip'\n #urllib.request.urlretrieve(data_url_2, 'validation-horse-or-human.zip')\n #local_file = 'validation-horse-or-human.zip'\n #zip_ref = zipfile.ZipFile(local_file, 'r')\n #zip_ref.extractall('data/validation-horse-or-human')\n #zip_ref.close()\n\n\n TRAINING_DIR = 'data/horse-or-human'\n VALIDATION_DIR = 'data/validation-horse-or-human'\n\n # YOUR CODE HERE\n train_datagen = ImageDataGenerator(rescale = 1./255)\n\n train_generator = train_datagen.flow_from_directory(\n TRAINING_DIR, \n target_size=(150, 150), \n batch_size=128,\n class_mode='binary')\n\n test_datagen = ImageDataGenerator(rescale = 1./255 )\n\n validation_generator = test_datagen.flow_from_directory(VALIDATION_DIR,\n batch_size = 32,\n class_mode = 'binary', \n target_size = (150, 150)) \n\n model = tf.keras.models.Sequential([\n # YOUR CODE HERE, end with a Neuron Dense, activated by sigmoid\n tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n ])\n from tensorflow.keras.optimizers import Adam\n\n model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0003), metrics=['accuracy'])\n model.fit(train_generator,steps_per_epoch=8, epochs=100, verbose=1, validation_data = validation_generator, validation_steps= 8 )\n\n return model\n\n\n# The code below is to save your model as a .h5 file.\n# It will be saved automatically in your Submission folder.\nif __name__ == '__main__':\n model = solution_A2()\n model.save(\"model_A2.h5\")","sub_path":"Submission A/Problem_A2.py","file_name":"Problem_A2.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"607667514","text":"from pathlib import Path\n\nimport numpy as np\nimport torch\nfrom itertools import chain\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.nn.utils import parameters_to_vector\nfrom itertools import chain\nfrom math import ceil\n\n\nclass RBM():\n\n @classmethod\n def from_weights(cls, weights_dir):\n pathdir = Path(weights_dir)\n visible_bias = torch.load(pathdir / 'visible_bias.pt')\n hidden_bias = torch.load(pathdir / 'hidden_bias.pt')\n n_vis = visible_bias.shape[0]\n n_hin = hidden_bias.shape[0]\n rbm = RBM(n_vis=n_vis, n_hin=n_hin)\n rbm.load_params(weights_dir)\n return rbm\n\n def to(self, param):\n self.weights = self.weights.to(param)\n self.hidden_bias = self.hidden_bias.to(param)\n self.visible_bias = self.visible_bias.to(param)\n return self\n\n def __init__(self, n_vis, n_hin):\n super(RBM, self).__init__()\n self.n_vis = n_vis\n self.n_hin = n_hin\n\n self.initialize_parameters()\n\n def initialize_parameters(self):\n self.weights = torch.randn(\n self.n_hin,\n self.n_vis,\n dtype=torch.double\n ) / np.sqrt(self.n_vis)\n\n self.visible_bias = torch.zeros(self.n_vis, dtype=torch.double)\n self.hidden_bias = torch.zeros(self.n_hin, dtype=torch.double)\n\n def effective_energy(self, v):\n v = v.to(self.weights)\n visible_bias_term = torch.matmul(v, self.visible_bias)\n hid_bias_term = F.softplus(F.linear(v, self.weights, self.hidden_bias)).sum(-1)\n\n return -(visible_bias_term + hid_bias_term)\n\n def effective_energy_gradient(self, v):\n v = (v.unsqueeze(0) if v.dim() < 2 else v).to(self.weights)\n prob = self.prob_h_given_v(v)\n\n W_grad = -torch.matmul(prob.transpose(0, -1), v)\n vb_grad = -torch.sum(v, 0)\n hb_grad = -torch.sum(prob, 0)\n return W_grad, vb_grad, hb_grad\n\n def prob_v_given_h(self, h):\n return (\n torch.matmul(h, self.weights.data, out=None)\n .add_(self.visible_bias.data)\n .sigmoid_()\n .clamp_(min=0, max=1)\n )\n\n def prob_h_given_v(self, v):\n return (\n torch.matmul(v, self.weights.data.t(), out=None)\n .add_(self.hidden_bias.data)\n .sigmoid_()\n .clamp_(min=0, max=1)\n )\n\n def sample_v_given_h(self, h):\n v = self.prob_v_given_h(h)\n v = torch.bernoulli(v) # overwrite v with its sample\n return v\n\n def sample_h_given_v(self, v):\n h = self.prob_h_given_v(v)\n h = torch.bernoulli(h) # overwrite h with its sample\n return h\n\n def draw_samples(self, k, initial_state):\n v = (initial_state.clone()).to(self.weights)\n h = torch.zeros(*v.shape[:-1], self.n_hin).to(self.weights)\n\n for _ in range(k):\n h = self.sample_h_given_v(v)\n v = self.sample_v_given_h(h)\n\n return v\n\n def wavefunction(self, v):\n return (-self.effective_energy(v)).exp().sqrt()\n\n def gradients(self, batch):\n grads_W, grads_vb, grads_hb = self.effective_energy_gradient(batch)\n grads_W /= float(batch.shape[0])\n grads_vb /= float(batch.shape[0])\n grads_hb /= float(batch.shape[0])\n\n return grads_W, grads_vb, grads_hb\n\n def compute_batch_gradients(self, k, pos_phase_batch, neg_phase_batch):\n grads_W, grads_vb, grads_hb = self.gradients(pos_phase_batch)\n\n vk = self.draw_samples(k, neg_phase_batch)\n neg_grads_W, neg_grads_vb, neg_grads_hb = self.gradients(vk)\n\n grads_W -= neg_grads_W\n grads_vb -= neg_grads_vb\n grads_hb -= neg_grads_hb\n\n return grads_W, grads_vb, grads_hb\n\n def shuffle_data(self, data, batch_size):\n permutation = torch.randperm(data.shape[0])\n data = [\n data[batch_start: (batch_start + batch_size)]\n for batch_start in range(0, len(data), batch_size)\n ]\n return data\n\n def params(self):\n return self.weights, self.visible_bias, self.hidden_bias\n\n def save_params(self, dir):\n pathdir = Path(dir)\n if not pathdir.exists():\n pathdir.mkdir(parents=True)\n\n torch.save(self.weights, pathdir / 'weights.pt')\n torch.save(self.visible_bias, pathdir / 'visible_bias.pt')\n torch.save(self.hidden_bias, pathdir / 'hidden_bias.pt')\n\n def load_params(self, dir):\n pathdir = Path(dir)\n self.weights = torch.load(pathdir / 'weights.pt')\n self.visible_bias = torch.load(pathdir / 'visible_bias.pt')\n self.hidden_bias = torch.load(pathdir / 'hidden_bias.pt')\n\n def update_params(self, grads, lr):\n self.weights -= lr * grads[0]\n self.visible_bias -= lr * grads[1]\n self.hidden_bias -= lr * grads[2]\n\n def train(self, input_data, k=10, batch_size=100, lr=0.01):\n\n num_batches = ceil(input_data.shape[0] / batch_size)\n pos_batches = self.shuffle_data(input_data, batch_size)\n neg_batches = self.shuffle_data(input_data, batch_size)\n\n for b in range(num_batches):\n all_gradients = self.compute_batch_gradients(k, pos_batches[b], neg_batches[b])\n\n self.update_params(all_gradients, lr)\n\n def partition_function(self, space):\n logZ = (-self.effective_energy(space)).logsumexp(0)\n return logZ.exp()\n\n def generate_hilbert_space(self):\n dim = np.arange(2 ** self.n_vis)\n space = ((dim[:, None] & (1 << np.arange(self.n_vis))) > 0)[:, ::-1]\n space = space.astype(int)\n return torch.tensor(space, dtype=torch.double)\n\n def psi(self):\n space = self.generate_hilbert_space()\n return self.wavefunction(space) / self.partition_function(space).sqrt()\n\n def log_likelihood(self, data):\n return self.effective_energy(data).sum().item() / len(data)\n","sub_path":"Project_1_RBM_and_Tomography/RBM_helper.py","file_name":"RBM_helper.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"208574835","text":"#!/usr/bin/env python\n\"\"\"\nString-related functions.\n\nHistory\n create - Feng Zhou (zhfe99@gmail.com), 2014-12\n modify - Feng Zhou (zhfe99@gmail.com), 2016-01\n\"\"\"\nimport re\nfrom cell import zeros\n\n\ndef strLstPre(lst0, pre):\n \"\"\"\n Return a sub-list of string that starts with the specified prefix.\n\n Input\n lst0 - original string list, 1 x n0\n pre - prefix\n\n Output\n lst - new string list, 1 x n\n \"\"\"\n lst = []\n for str0 in lst0:\n if str0[: len(pre)] == pre:\n lst.append(str0)\n\n return lst\n\n\ndef strLstPat(lst0, pats):\n \"\"\"\n Return a sub-list of string that match with the specified pattern.\n\n Input\n lst0 - original string list, n0 x\n pats - pattern list, m x\n\n Output\n lst - new string list, n x\n \"\"\"\n lst = []\n for str0 in lst0:\n for pat in pats:\n if re.match(pat, str0):\n lst.append(str0)\n break\n\n return lst\n\n\ndef strDelSub(name0):\n \"\"\"\n Remove subfix from a file name.\n\n Input\n name0 - original name\n\n Output\n name - new name\n \"\"\"\n tail = name0.find('.')\n if tail == -1:\n name = name0\n else:\n name = name0[: tail]\n\n return name\n\n\ndef strGetSub(name):\n \"\"\"\n Get subfix from a file name.\n\n Input\n name - file name\n\n Output\n subx - subfix\n \"\"\"\n tail = name.find('.')\n if tail == -1:\n subx = ''\n else:\n subx = name[tail + 1:]\n\n return subx\n\n\ndef strRepSub(name0, subx):\n \"\"\"\n Replace subfix to the given one.\n\n Input\n name0 - original name\n subx - new subx\n\n Output\n name - new name\n \"\"\"\n name = strDelSub(name0)\n\n return name + '.' + subx\n\n\ndef strNumCo(s):\n \"\"\"\n Count the number character in a given string.\n\n Example\n in: s = 'a32b'\n call: co = strNumCo()\n out: co = 2\n\n Input\n s - string\n\n Output\n co - #number character\n \"\"\"\n co = 0\n for c in s:\n if c >= '0' and c < '9':\n co += 1\n return co\n\n\ndef strLst2Float(arrS):\n \"\"\"\n Convert a string list to a float list.\n\n Input\n arrS - string list, n x 1 (str)\n\n Output\n arrF - float list, n x 1 (float)\n \"\"\"\n arrF = [float(s.strip()) for s in arrS]\n return arrF\n\n\ndef strLst1NotIn2(arr1, arr2):\n \"\"\"\n Compare two string lists to find the strings in arr1 that\n are not contained in arr2.\n\n Input\n arr1 - array 1, n1 x 1\n arr2 - array 2, n2 x 1\n\n Output\n arrD - different elements in arr1, nD x 1\n \"\"\"\n arrD = []\n m2 = len(arr2)\n vis = zeros(m2)\n for s1 in arr1:\n found = False\n for i2, s2 in enumerate(arr2):\n if vis[i2]:\n continue\n\n if s1 == s2:\n vis[i2] = 1\n found = True\n break\n if not found:\n arrD.append(s1)\n return arrD\n\n\ndef str2ran(s):\n \"\"\"\n Convert a string range to an integer list.\n\n Example 1\n input: s = '1'\n call: lst = str2ran(s)\n output: lst = 1\n\n Example 2\n input: s = '2:10'\n call: lst = str2ran(s)\n output: lst = [2, 3, 4, 5, 6, 7, 8, 9]\n\n Example 3\n input: s = '2:10:2'\n call: lst = str2ran(s)\n output: lst = [2, 4, 6, 8]\n\n Example 4\n input: s = '1,3'\n call: lst = str2ran(s)\n output: lst = [1,3]\n\n Example 5\n input: s = ''\n call: lst = str2ran(s)\n output: lst = []\n\n Input\n s - string\n\n Output\n lst - an integer list\n \"\"\"\n if len(s) == 0:\n lst = []\n\n elif ':' in s:\n parts = s.split(':')\n a = [int(part) for part in parts]\n\n if len(parts) == 1:\n lst = a\n elif len(parts) == 2:\n lst = range(a[0], a[1])\n elif len(parts) == 3:\n lst = range(a[0], a[1], a[2])\n else:\n raise Exception('unsupported')\n\n elif ',' in s:\n parts = s.split(',')\n lst = [int(part) for part in parts]\n\n else:\n lst = [int(s)]\n\n return lst\n","sub_path":"str.py","file_name":"str.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"276378213","text":"from rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\nfrom rest_framework import status\r\nfrom products.serializers import ProductSerializer\r\n\r\n\r\n# Create your views here.\r\n\r\n\r\nclass PostMultiple(APIView):\r\n def post(self, request, format=None):\r\n\r\n rejected = []\r\n accepted = []\r\n for req in request.data:\r\n\r\n serializer = ProductSerializer(data=req)\r\n\r\n if serializer.is_valid():\r\n serializer.save()\r\n accepted.append(serializer.data)\r\n else:\r\n rejected.append(serializer.data)\r\n if len(rejected) == 0:\r\n return Response(accepted, status=status.HTTP_201_CREATED)\r\n elif len(accepted) == 0:\r\n return Response(rejected, status=status.HTTP_400_BAD_REQUEST)\r\n return Response(rejected, status=status.HTTP_207_MULTI_STATUS)\r\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"294035499","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport person_pb2\n\n# 为 all_person 填充数据\npers = person_pb2.all_person()\np1 = pers.Per.add()\np1.id = 1\np1.name = 'xieyanke'\np2 = pers.Per.add()\np2.id = 2\np2.name = 'pythoner'\n\n\n# gen protobuf\ndata = pers.SerializeToString()\n#print data\n\n# parse protobuf\ntarget = person_pb2.all_person()\ntarget.ParseFromString(data)\nprint(target.Per[1].name)\n\n\n\n","sub_path":"protobuf/main_person.py","file_name":"main_person.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"3184355","text":"\"\"\"Pydantic attempts to provide \"strongly typed\" data structures to Python.\n\nFeatures include:\n\n* Type hinting at runtime\n* Data validation\n\nPydantic has two model object base classes: BaseModel and dataclass. By default,\nyou'll want to use `BaseModel`.\n\npydantic.dataclasses are a drop in replacement for Python dataclasses which adds\ntype validation.\n\nDifferences between BaseModel and dataclasses include:\n\n* Mutable field initializers. dataclass requires a default_factory\n* BaseModel handles extra fields\n\"\"\"\n\n#\n# `from __future__ import annotations`` allows you to reference a type as an\n# annotation within the type declaration.\n#\n# For example, we define the attr `children` as a list of `Person`. In order to\n# refer to ``Person`, we must import annotations.`\n#\nfrom __future__ import annotations\n\nimport pydantic\nimport pytest\n\n\ndef test_frozen() -> None:\n class Person(pydantic.BaseModel):\n # Example recursive model\n name: str\n children: list[Person] = []\n\n class Config:\n frozen = True\n\n p = Person(name=\"damon\")\n p.children.append(Person(name=\"kari\"))\n\n with pytest.raises(TypeError):\n p.name = \"no\"\n\n\n\n\ndef test_pydantic() -> None:\n class A(pydantic.BaseModel):\n # By default, Pydantic does not reuse field initializers across\n # instances\n lst: list[int] = pydantic.Field(\n default_factory=list, description=\"A list\", max_items=1\n )\n\n class Config:\n \"\"\"Config allows you to customize Pydantic's behavior\"\"\"\n\n # whether to `ignore`, `allow`, or `forbid` extra attributes during\n # model initialization. default: pydantic.Extra.ignore\n extra = pydantic.Extra.allow\n validate_all = True # whether to validate field defaults\n\n @pydantic.dataclasses.dataclass\n class B:\n lst: list[int] = pydantic.Field(default_factory=list)\n\n a, a2 = A(extra=\"123\"), A()\n b, b2 = B(), B()\n\n a.lst.append(1)\n b.lst.append(2)\n\n assert a.extra == \"123\"\n assert a.lst == [1]\n assert a2.lst == []\n\n assert b.lst == [2]\n assert b2.lst == []\n\n #\n # Pydantic's field validation and rules are only enforced during\n # initialization set directly. For example, appending to a mutable list will\n # *not* raise validation errors.\n #\n # Is this configurable? Shouldn't validation be ran for each field set by\n # default?\n #\n a.lst.append(2)\n assert len(a.lst) == 2\n a.lst = [1, 2]\n\n with pytest.raises(ValueError) as ve:\n A(lst=[1, 2])\n assert ve.match(\"max_items\")\n","sub_path":"tests/libraries/test_pydantic.py","file_name":"test_pydantic.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"560160546","text":"import hashlib, pickle\n\ndef UTXO_Scan(pub_addr):\n with open ('ledger.txt', 'rb') as file:\n k = pickle.load(file)\n ledger = list(k)\n \n block_num = 0\n utxo_scan = True\n while utxo_scan == True:\n \n try:\n # Searches for Public Addr in ledger\n obj = ledger[block_num][2][0][2]\n if obj == str(pub_addr):\n utxo_scan = False\n return (ledger[block_num][2][0][0])\n else:\n block_num = int(block_num) + 1\n\n except IndexError:\n return ('Invalid Transaction')\n\ndef Make_Hash(obj):\n return str(hashlib.sha256(codecs.encode(str(obj), 'utf-8')).hexdigest())\n\n\nwith open ('ledger.txt', 'rb') as file:\n k = pickle.load(file)\n\nprint(k)\n","sub_path":"ledger_scan_function.py","file_name":"ledger_scan_function.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"187630475","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 15 10:58:52 2019\n\n@author: parthgoyal123\n\"\"\"\n\n''' --------- K-Means Clustering ----------- '''\n\n# ====== Preprocessing ====== #\n\n# Importing the required libraries\n# ---> Numpy arrays are the most convinient way to work on Machine Learning models\n# ---> Matplotlib allows us to visualise our model in form of various plots/figures\n# ---> Pandas allows us to import the dataset efficiently\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset using pandas library\n# ---> pandas create a dataframe of the dataset\n# ---> iloc : It locates the column by its index. In other words, using ’iloc’ allows us to take columns by just taking their index.\n# ---> .values : It returns the values of the column (by their index) inside a Numpy array(way more efficient than a list)\ndataset = pd.read_csv(\"Mall_Customers.csv\")\nX = dataset.iloc[:, [3,4]].values.astype(float)\n\n\"\"\"\n# Fixing the missing values from the dataset using sklearn.impute\n# ---> Importing the SimpleImputer class from the sklearn.impute library\n# ---> .fit : The fit part is used to extract some info of the data on which the object is applied\n# ---> .transform : the transform part is used to apply some transformation\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(missing_values = np.nan, strategy = 'mean')\nX[:, [1,2]] = imputer.fit_transform(X[:, [1,2]])\n\n# Encoding categorical data (optional part, depends on the dataset)\n# ---> LabelEncoder encodes the categorical data to [0, n_values]\n# ---> OneHotEncoder seperates the LabelEncoded values to different columns, appended leftmost of the dataset\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_x = LabelEncoder()\nlabelencoder_y = LabelEncoder()\nonehotencoder = OneHotEncoder(categorical_features= [-1])\nX[:, -1] = labelencoder_x.fit_transform(X[:, -1])\nX = onehotencoder.fit_transform(X).toarray()\n\n# When the categorical types >= 3, we need to avoid the dummy variable trap\nX = X[:, 1:]\n\"\"\"\n\n# Dividing the dataset to training and test set\n# ---> train_test_split : function of the sklearn.model_selection library that splits the dataset to training and test sets\n# ---> random_state : this parameter is essential to get the same training and test splits(when improving the model time by time)\nfrom sklearn.model_selection import train_test_split\nX_train, X_test = train_test_split(X, test_size = 0.1, random_state = 1)\n\n\"\"\"\n# Feature Scaling the data\n# ---> StandardScaler : no parameters are to be passed to this class, only an object is to be made\nfrom sklearn.preprocessing import StandardScaler\nscale_X = StandardScaler()\nX_train = scale_X.fit_transform(X_train)\nX_test = scale_X.fit_transform(X_test)\n\"\"\"\n\n# ========= Clustering ========= #\n\n# ---- K-Means Clustering ----- #\n\n# Using the Elbow method to get the correct number of clusters\n# ---> wcss : within cluster sum of squares\n# ---> init : 'kmeans++' is an algorithm for initialising the n_init clusters\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1,11):\n k_means = KMeans(n_clusters = i, init = 'k-means++', n_init = 10, max_iter = 300)\n k_means.fit(X_train)\n wcss.append(k_means.inertia_)\n\n# Plotting the Elbow curve to get the optimal number of clusters\nfig = plt.figure(dpi = 100, figsize = (8,6))\nplt.plot(range(1,11), wcss, color = 'blue')\nplt.title('Elbow Mehtod for Optimal number of clusters')\nplt.xlabel('Number of Clusters')\nplt.ylabel('WCSS')\nplt.show()\nfig.savefig('Elbow_Method.png')\n\n# ---> From elbow method, we observe that the major difference occurs at Number of clusters = 5\n# Applying K-means with correct number of clusters\nk_means = KMeans(n_clusters = 5, init = 'k-means++', n_init = 10, max_iter = 300)\nk_means.fit(X)\ny_kmeans = k_means.predict(X_train)\ny_pred_test = k_means.predict(X_test)\n\n# Visualising the Clusters of Training set \nfig =plt.figure(dpi = 100, figsize = (8,6))\nplt.scatter(X_train[y_kmeans == 0, 0], X_train[y_kmeans == 0, 1], color = 'red', s=30, marker = '*', label = 'Cluster 1')\nplt.scatter(X_train[y_kmeans == 1, 0], X_train[y_kmeans == 1, 1], color = 'blue', s=30, marker = '*', label = 'Cluster 2')\nplt.scatter(X_train[y_kmeans == 2, 0], X_train[y_kmeans == 2, 1], color = 'green', s=30, marker = '*', label = 'Cluster 3')\nplt.scatter(X_train[y_kmeans == 3, 0], X_train[y_kmeans == 3, 1], color = 'magenta', s=30, marker = '*', label = 'Cluster 4')\nplt.scatter(X_train[y_kmeans == 4, 0], X_train[y_kmeans == 4, 1], color = 'cyan', s=30, marker = '*', label = 'Cluster 5')\nplt.scatter(k_means.cluster_centers_[:, 0], k_means.cluster_centers_[:, 1], color = 'yellow', s=100, label = 'Centroid')\nplt.title('K-Means Clustering')\nplt.xlabel('')\nplt.ylabel('')\nplt.legend()\nplt.show()\nfig.savefig('K-Means_training.png')\n\n# Visualising the Clusters of Test set \nfig =plt.figure(dpi = 100, figsize = (8,6))\nplt.scatter(X_test[y_pred_test == 0, 0], X_test[y_pred_test == 0, 1], color = 'red', s=30, marker = '*', label = 'Cluster 1')\nplt.scatter(X_test[y_pred_test == 1, 0], X_test[y_pred_test == 1, 1], color = 'blue', s=30, marker = '*', label = 'Cluster 2')\nplt.scatter(X_test[y_pred_test == 2, 0], X_test[y_pred_test == 2, 1], color = 'green', s=30, marker = '*', label = 'Cluster 3')\nplt.scatter(X_test[y_pred_test == 3, 0], X_test[y_pred_test == 3, 1], color = 'magenta', s=30, marker = '*', label = 'Cluster 4')\nplt.scatter(X_test[y_pred_test == 4, 0], X_test[y_pred_test == 4, 1], color = 'cyan', s=30, marker = '*', label = 'Cluster 5')\nplt.scatter(k_means.cluster_centers_[:, 0], k_means.cluster_centers_[:, 1], color = 'yellow', s=100, label = 'Centroid')\nplt.title('K-Means Clustering')\nplt.xlabel('')\nplt.ylabel('')\nplt.legend()\nplt.show()\nfig.savefig('K-Means_test.png')\n\n# ============ K-Means Clustering Complete ============ #","sub_path":"4. Clustering/1. K-Means Clustering/K-Means_Clustering.py","file_name":"K-Means_Clustering.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"539096160","text":"import os\nimport shutil\n\nimport numpy as np\nimport cv2\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom pathlib import Path\nfrom typing import Tuple, Union, Dict\n\nfrom ptf import const\n\n\ndef remove_directory(dir: Union[str, Path]) -> None:\n shutil.rmtree(str(dir), ignore_errors=True)\n\n\ndef load_image(\n path: Union[str, Path],\n to_rgb: bool = True\n) -> np.ndarray:\n image = cv2.imread(str(path), cv2.IMREAD_COLOR)\n if to_rgb:\n return image[:, :, ::-1] # BGR -> RGB\n else:\n return image\n\n\ndef load_mask(path: Union[str, Path]) -> np.ndarray:\n mask = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)\n return mask\n\n\ndef save_img(\n img: np.ndarray,\n name: Union[str, int],\n output_dir: Union[str, Path],\n img_ext: str = '.jpg'\n) -> bool:\n # create outpud directory if needed\n output_dir = Path(output_dir)\n output_dir.mkdir(parents=True, exist_ok=True)\n # result path\n img_path = output_dir / f'{name}{img_ext}'\n return cv2.imwrite(str(img_path), img)\n\n\ndef show_img(\n img: np.ndarray,\n mask: np.ndarray = None,\n fig_size: Tuple[float, float] = (15.0, 15.0),\n to_rgb: bool = False\n) -> None:\n new_fig_size = list(fig_size)\n orig_fig_size = list(matplotlib.rcParams['figure.figsize'])\n if new_fig_size != orig_fig_size:\n matplotlib.rcParams['figure.figsize'] = new_fig_size\n\n if mask is not None:\n img = cv2.bitwise_and(img, img, mask=mask)\n\n img_shape = img.shape\n\n if len(img_shape) == 2:\n plt.imshow(img, cmap='gray')\n else:\n if img_shape[2] == 4:\n img = img[..., 0:3]\n if to_rgb:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n plt.imshow(img)\n\n plt.show()\n\n\ndef num_cpus() -> int:\n \"Get number of cpus\"\n try:\n return len(os.sched_getaffinity(0))\n except AttributeError:\n return os.cpu_count()\n","sub_path":"ptf/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"160453792","text":"import math\n\n\n#2.3-2\ndef merge(A, p, q, r):\n L = A[p:q]\n R = A[q:r]\n\n i, j, k = 0, 0, p\n while i < len(L) and j < len(R):\n if L[i] < R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n k += 1\n\n if i < len(L):\n while i < len(L):\n A[k] = L[i]\n k += 1\n i += 1\n elif j < len(R):\n while j < len(R):\n A[k] = R[j]\n k += 1\n j += 1\n\n return A\n\n\ndef merge_sort(A, p, r):\n if r - p > 1:\n q = math.floor((p + r) / 2)\n merge_sort(A, p, q)\n merge_sort(A, q, r)\n ret = merge(A, p, q, r)\n print(ret)\n return ret\n\n\nprint(merge_sort([3, 41, 52, 26, 38, 57, 9, 49], 0, 8))\n\n\n#2.3-5\ndef binary_search(A, p, q, val):\n if q >= len(A):\n q = len(A) - 1\n if q < p:\n return -1\n mid = math.floor((p + q) / 2)\n if val == A[mid]:\n return mid\n elif val < A[mid]:\n return binary_search(A, p, mid - 1, val)\n else:\n return binary_search(A, mid + 1, q, val)\n\n\n","sub_path":"chpter2/prob2.3.py","file_name":"prob2.3.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"522480614","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nUSAGE\n$ python make_synapse.py [target_directory]\n\"\"\"\n\nimport os\nimport sys\nimport random\n\n\"\"\"\ncomps_to_ln[300_301 or 301_300][pre or post] by Park\ncomps_to_pn[300_200 or 301_200][pre or post] by Park\n\"\"\"\n\ncomps_to_ln = \\\n[[[21015,14644, 8240,15191, 8804,21375, 8239,15706,15171,21088],\\\n[11079,10877,11534,11093,11257,10351,11580,11879,11949,11038]],\\\n[[10351,10877,11083,10380,11422,11681,10351,11083,11219,11093],\\\n[21374,15191, 8242,21309, 8239, 9486,21436, 8804,21088,15070]]]\n\ncomps_to_pn = \\\n[[[2739, 2730, 2366, 2363, 2055, 2050, 1809, 1801, 1590, 1579],\\\n[110, 107, 104, 101, 98, 97, 94, 114, 109, 102]],\\\n[[3572, 4958, 5487, 1846, 6691, 7140, 3610, 3524, 2733, 4517],\\\n[101, 102, 94, 98, 125, 119, 114, 108, 103, 93]]]\n\n\ndef make_synapse_Park():\n gid_to_ln = 3000000\n gid_to_pn = 2000000\n\n n = 10\n\n for file in files:\n pre_cell, post_cell, _ = file.split(\"_\")\n if post_cell[0] == \"3\":\n with open(target + file, \"w\") as f:\n f.write(\"$ PRE_CELL %s\\n\" % pre_cell)\n f.write(\"$ POST_CELL %s\\n\" % post_cell)\n f.write(\"$ NCONNECTIONS %d\\n\" % n)\n index = int(pre_cell[2])\n for i in xrange(n):\n f.write(\"%d %d %d\\n\" % (comps_to_ln[index][0][i], comps_to_ln[index][1][i], gid_to_ln+i))\n gid_to_ln += n\n elif post_cell[0] == \"2\":\n with open(target + file, \"w\") as f:\n f.write(\"$ PRE_CELL %s\\n\" % pre_cell)\n f.write(\"$ POST_CELL %s\\n\" % post_cell)\n f.write(\"$ NCONNECTIONS %d\\n\" % n)\n index = int(pre_cell[2])\n for i in xrange(10):\n f.write(\"%d %d %d\\n\" % (comps_to_pn[index][0][i], comps_to_pn[index][1][i], gid_to_pn+i))\n gid_to_pn += n\n\n\ndef make_synapse_Arase(n):\n gid_to_ln = 3000000\n gid_to_pn = 2000000\n\n for file in files:\n pre_cell, post_cell, _ = file.split(\"_\")\n if post_cell[0] == \"3\":\n with open(target + file, \"w\") as f:\n f.write(\"$ PRE_CELL %s\\n\" % pre_cell)\n f.write(\"$ POST_CELL %s\\n\" % post_cell)\n f.write(\"$ NCONNECTIONS %d\\n\" % nconnections)\n pre_index = int(pre_cell[2])\n post_index = int(post_cell[2])\n for i in xrange(n):\n if i < len(comps_to_ln[pre_index][0]):\n f.write(\"%d %d %d\\n\" % (comps_to_ln[pre_index][0][i], comps_to_ln[pre_index][1][i], gid_to_ln+i))\n else:\n while True:\n pre_comp = random.randint(1, n_comps[pre_index])\n post_comp = random.randint(1, n_comps[post_index])\n if not (pre_comp in comps_to_ln[pre_index][0] and post_comp in comps_to_ln[pre_index][1]):\n break\n f.write(\"%d %d %d\\n\" % (pre_comp, post_comp, gid_to_ln+i))\n gid_to_ln += n\n elif post_cell[0] == \"2\":\n with open(target + file, \"w\") as f:\n f.write(\"$ PRE_CELL %s\\n\" % pre_cell)\n f.write(\"$ POST_CELL %s\\n\" % post_cell)\n f.write(\"$ NCONNECTIONS %d\\n\" % n)\n index = int(pre_cell[2])\n for i in xrange(10):\n f.write(\"%d %d %d\\n\" % (comps_to_pn[index][0][i], comps_to_pn[index][1][i], gid_to_pn+i))\n gid_to_pn += n\n\n\nif __name__ == \"__main__\":\n target = os.path.abspath(sys.argv[1]) + \"/\"\n files = os.listdir(target)\n\n nconnections = 10\n n_comps = [22928-5, 12525-5] #[300, 301]\n\n # make_synapse_Park()\n make_synapse_Arase(nconnections)\n","sub_path":"input/synapse_list/make_synapse.py","file_name":"make_synapse.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"383298103","text":"\"\"\"Write the function valid_email(...) to check if the input string is a valid email address or not.\n\nAn email is a string (a subset of ASCII characters) separated into two parts by @ symbol, a “user_info” and a domain_info, that is personal_info@domain_info:\nin case of correct email the function should be displayed the corresponding message – \"Email is valid\"\nin case of incorrect email the function should be displayed the corresponding message – \"Email is not valid\"\n\nNote: in the function you must use the \"try except\" construct.\n\n\nFunction example:\n\nvalid_email(\"trafik@ukr.tel.com\") #output: \"Email is valid\"\n\nvalid_email(\"trafik@ukr_tel.com\") #output: \"Email is not valid\"\n\nvalid_email(\"tra@fik@ukr.com\") #output: \"Email is not valid\"\n\nvalid_email(\"ownsite@our.c0m\") #output: \"Email is not valid\"\n\n\n\"\"\"\n\ndef valid_email(email):\n import re\n pattern = \"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n try:\n if (re.search(pattern,email)):\n return f\"Email is valid\"\n else:\n raise ValueError(\"Email is not valid\")\n except ValueError as e:\n return e\n","sub_path":"sprint_05_[Exception handling]/Task_1.py","file_name":"Task_1.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"314316446","text":"from random import choice\nfrom time import sleep\nfrom os import path\n\n\nclass Player:\n\n def __init__(self, name, money=200):\n self.name = name\n self.money = money\n self.cards = [] # [suit, number]\n self.current_hand = [] # number only\n self.win = 0\n self.high_score = 0\n self.test = []\n self.max_money = 200\n self.bet = 0\n self.load_data()\n\n def set_up(self, deck):\n self.current_hand = []\n self.cards = []\n self.draw_card(deck)\n self.draw_card(deck)\n self.current_hand = [card[1] for card in self.cards]\n # self.display_cards()\n\n def draw_card(self, deck, display=False):\n deck.check_deck()\n random_suit = choice(list(deck.cards))\n random_number = choice(deck.cards[random_suit])\n deck.cards[random_suit].remove(random_number)\n self.cards.append([random_suit, random_number])\n self.current_hand.append(random_number)\n if display:\n print('--------------------------------')\n print('{name} draws {number} of {suit}\\n'.format(name=self.name, number=random_number, suit=random_suit))\n return random_suit, random_number\n\n def display_cards(self):\n print('-------------------------')\n print(\"{name}'s cards are\\n\".format(name=self.name))\n for card in self.cards:\n if card[1] == 11 or card[1] == 1:\n print('{number} of {suit}'.format(number='Ace', suit=card[0]))\n else:\n print('{number} of {suit}'.format(number=card[1], suit=card[0]))\n\n def player_bet(self):\n print('You have {money} to bet'.format(money=self.money))\n while True:\n try:\n bet = int(input('what is your bet: '))\n except ValueError:\n print('Bet must be a number!')\n else:\n while bet > self.money:\n try:\n bet = int(input('Must bet {} or less: '.format(self.money)))\n except ValueError:\n print('Bet must be a number!')\n self.money -= bet\n self.bet = bet\n break\n return bet\n\n def check_blackjack(self, display=True):\n if len(self.current_hand) == 2:\n if 'Ace' in self.current_hand and 10 in self.current_hand:\n self.current_hand = [21]\n self.win += 1\n self.high_score += 1\n if display:\n print('BlackJack!\\n\\nYou win {bet}\\n'.format(bet=self.bet * 2))\n if self.win >= self.high_score:\n print('New win streak, {streak} games won in a row! '.format(streak=self.high_score))\n print('-------------------------')\n self.money += self.bet * 2\n return False\n elif 'Ace' in self.current_hand and 'Queen' in self.current_hand:\n self.current_hand = [21]\n self.win += 1\n self.high_score += 1\n print('BlackJack!\\n\\nYou win {bet}\\n'.format(bet=self.bet * 2))\n if display:\n if self.win >= self.high_score:\n print('New win streak, {streak} games won in a row! '.format(streak=self.high_score))\n print('-------------------------')\n self.money += self.bet * 2\n return False\n elif 'Ace' in self.current_hand and 'King' in self.current_hand:\n self.current_hand = [21]\n self.win += 1\n self.high_score += 1\n if display:\n print('BlackJack!\\n\\nYou win {bet}\\n'.format(bet=self.bet * 2))\n if self.win >= self.high_score:\n print('New win streak, {streak} games won in a row! '.format(streak=self.high_score))\n print('-------------------------')\n self.money += self.bet * 2\n return False\n elif 'Ace' in self.current_hand and 'Jack' in self.current_hand:\n self.current_hand = [21]\n self.win += 1\n self.high_score += 1\n if display:\n print('BlackJack!\\n\\nYou win {bet}\\n'.format(bet=self.bet * 2))\n if self.win >= self.high_score:\n print('New win streak, {streak} games won in a row! '.format(streak=self.high_score))\n print('-------------------------')\n self.money += self.bet * 2\n return False\n return True\n\n def check_cards(self, deck):\n sleep(2)\n print('-------------------------')\n if len(self.current_hand) == 1: # Check for one card meaning cards were split\n self.draw_card(deck, display=True)\n if not self.check_blackjack(self.bet):\n return False\n self.current_hand = []\n for number in self.cards: # sorting cards and evaluating values\n if number[1] == 'Ace':\n continue\n else:\n self.current_hand.append(deck.values[number[1]])\n for number in self.cards:\n if number[1] == 'Ace':\n if sum(self.current_hand) >= 11:\n self.current_hand.append(deck.values[number[1]][0])\n else:\n self.display_cards()\n print('Current total is {total} '.format(total=sum(self.current_hand)))\n answer = ''\n while answer != 11 and answer != 1:\n try:\n answer = int(input('Would you like your ace to be an 11 or 1? '))\n except ValueError:\n print('Must be a number!')\n number[1] = answer\n self.clear()\n sleep(2)\n self.current_hand.append(answer)\n total = sum(self.current_hand)\n if total == 21:\n self.display_cards()\n print('\\nYou have 21\\n')\n print('-------------------------')\n sleep(2)\n return False\n elif total > 21:\n print('\\nBust!\\nYou had {total}\\n'.format(total=total))\n print('-------------------------')\n return False\n else:\n self.display_cards()\n print('\\nTotaling {total}\\n'.format(total=total))\n print('-------------------------')\n return True\n\n def hit(self, deck):\n if self.money >= self.bet:\n answer = input('Hit or Stand or Double Down (h/s/dd) \\n')\n while answer != 'h' and answer != 's' and answer != 'dd':\n answer = input('Must choose (h) for Hit and (s) for Stand or (dd) for Double Down')\n if answer == 'h':\n self.clear()\n card_suit, card_number = self.draw_card(deck)\n print('{name} draws a'.format(name=self.name))\n print('{number} of {suit}\\n'.format(suit=card_suit, number=card_number))\n return True\n elif answer == 'dd':\n self.money -= self.bet\n self.bet = self.bet * 2\n self.clear()\n card_suit, card_number = self.draw_card(deck)\n print('{name} draws a'.format(name=self.name))\n print('{number} of {suit}\\n'.format(suit=card_suit, number=card_number))\n self.check_cards(deck)\n sleep(2)\n return False\n else:\n answer = input('Hit or Stand (h/s) \\n')\n while answer != 'h' and answer != 's':\n answer = input('Must choose (h) for Hit and (s) for Stand ')\n if answer == 'h':\n self.clear()\n card_suit, card_number = self.draw_card(deck)\n print('{name} draws a'.format(name=self.name))\n print('{number} of {suit}\\n'.format(suit=card_suit, number=card_number))\n return True\n sleep(2)\n return False\n\n def check_split(self):\n if self.money == 0:\n return False\n if self.current_hand.count(self.current_hand[0]) == 2:\n return True\n return False\n\n def clear(self):\n print('\\n' * 50)\n\n def load_data(self):\n # load high score\n HS_FILE = 'highscore.txt'\n self.dir = path.dirname(__file__)\n try:\n open(path.join(self.dir, HS_FILE), 'r+')\n except FileNotFoundError:\n open(path.join(self.dir, HS_FILE), 'w+')\n\n with open(path.join(self.dir, HS_FILE), 'r+') as f:\n try:\n self.highscore = int(f.read())\n except:\n self.highscore = 0\n\n\nclass Dealer:\n\n def __init__(self):\n self.name = 'Dealer'\n self.cards = []\n self.current_hand = []\n\n def draw_card(self, deck, display=False):\n deck.check_deck()\n random_suit = choice(list(deck.cards))\n random_number = choice(deck.cards[random_suit])\n deck.cards[random_suit].remove(random_number)\n self.cards.append([random_suit, random_number])\n self.current_hand.append(random_number)\n if display:\n print('{name} draws {number} of {suit}'.format(name=self.name, number=random_number, suit=random_suit))\n return random_suit, random_number\n\n def set_up(self, deck):\n self.current_hand = []\n self.cards = []\n self.draw_card(deck)\n self.draw_card(deck)\n self.current_hand = [card[1] for card in self.cards]\n self.display_cards()\n\n def display_cards(self): # Dealer can only show one card at first\n self.clear()\n sleep(1)\n print('-------------------------')\n print('The Dealer is showing')\n print('{number} of {suit}'.format(number=self.cards[1][1], suit=self.cards[1][0]))\n print('-------------------------')\n\n def display_all_cards(self):\n print('-------------------------')\n print('The Dealer cards are:')\n for card in self.cards:\n print('{number} of {suit}'.format(number=card[1], suit=card[0]))\n\n def check_blackjack(self):\n if len(self.cards) == 2:\n temp = [card[1] for card in self.cards]\n if 'Ace' in temp and 10 in temp:\n print('Dealer BlackJack!')\n return True\n elif 'Ace' in temp and 'Queen' in temp:\n print('Dealer BlackJack!')\n return True\n elif 'Ace' in temp and 'King' in temp:\n print('Dealer BlackJack!')\n return True\n elif 'Ace' in temp and 'Jack' in temp:\n print('Dealer BlackJack!')\n return True\n\n def check_cards(self): # Dealer's Ace will be 11 if sum of cards is less than 11. Else 1\n temp = []\n for number in self.current_hand:\n index = self.current_hand.index(number)\n if number == \"Ace\":\n continue\n if number == 'Queen' or number == 'Jack' or number == 'King':\n self.current_hand.remove(number)\n self.current_hand.insert(index, 10)\n temp.append(10)\n else:\n temp.append(number)\n for number in self.current_hand: # Deciding what to do with the Ace\n total = sum(temp)\n index = self.current_hand.index(number)\n if number == 'Ace':\n self.current_hand.remove(number)\n if total < 11:\n self.current_hand.insert(index, 11)\n temp.append(11)\n else:\n self.current_hand.insert(index, 1)\n temp.append(1)\n total = sum(self.current_hand)\n # Evaluate hand\n if total == 21:\n self.display_all_cards()\n print('Dealer has 21')\n print('-------------------------')\n sleep(2)\n return False\n elif total > 21:\n self.display_all_cards()\n print('\\nDealer Bust!')\n print('-------------------------')\n sleep(2)\n return False\n else:\n self.display_all_cards()\n print('Totaling {total}\\n'.format(total=total))\n print('-------------------------')\n sleep(2)\n return True\n\n def hit(self, deck):\n dealer_total = sum(self.current_hand)\n if dealer_total < 17:\n card_suit, card_number = self.draw_card(deck)\n print('{name} draws {number} of {suit}\\n'.format(name=self.name, suit=card_suit, number=card_number))\n sleep(2)\n return True\n return False\n\n def clear(self):\n print('\\n' * 50)\n\n\nclass Deck:\n\n def __init__(self):\n self.cards = {'clubs': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'spades': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'hearts': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'diamonds': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']}\n\n self.values = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11,\n 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': [1, 11]}\n\n def check_deck(self):\n for number, suit in self.cards.items():\n if not suit:\n print('\\n---New deck added---\\n')\n self.cards = {'clubs': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'spades': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'hearts': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'],\n 'diamonds': [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']}\n","sub_path":"variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":14083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"111921955","text":"# Train model following the official document\n\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\n\nfrom models import return_pytorch04_xception, return_pytorch04_xception_ft\nfrom transform import xception_default_data_transforms\n\nprint(\"PyTorch Version: \", torch.__version__)\nprint(\"Torchvision Version: \", torchvision.__version__)\n\n# Top level data directory. Here we assume the format of the directory conforms\n# to the ImageFolder structure\n# data_dir = \"/home/jc/Faceforensics_onServer/Final_Faceforensics++\"\ndata_dir = \"/home/jc/Faceforensics_onServer/Final_Faceforensics++no_NT-Big\" # no NT\n\n# Models to choose from [resnet, alexnet, vgg, squeezenet, densenet, inception]\nmodel_name = \"squeezenet\"\n\n# Number of classes in the dataset(to fine-tune)\nnum_classes = 2\n\n# Batch size for training (change depending on how much memory you have)\nbatch_size = 32\n\n\ndef train_model(model, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False):\n since = time.time()\n\n val_acc_history = []\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'train'):\n # Get model outputs and calculate loss\n # Special case for inception because in training it has an auxiliary output. In train\n # mode we calculate the loss by summing the final output and the auxiliary output\n # but in testing we only consider the final output.\n if is_inception and phase == 'train':\n # From https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958\n outputs, aux_outputs = model(inputs)\n loss1 = criterion(outputs, labels)\n loss2 = criterion(aux_outputs, labels)\n loss = loss1 + 0.4*loss2\n else:\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n _, preds = torch.max(outputs, 1)\n\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / len(dataloaders[phase].dataset)\n epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n if phase == 'val':\n val_acc_history.append(epoch_acc)\n\n print()\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model, val_acc_history\n\n\n# if we are feature extracting and only want to compute gradients for the newly initialized layer\n# then we want all of the other parameters to not require gradients. This will make more sense later.\ndef set_parameter_requires_grad(model, feature_extracting):\n if feature_extracting:\n # for param in model.parameters():\n # param.requires_grad = False\n for para in list(model.parameters())[:-1]:\n para.requires_grad = False\n\n\nif __name__ == '__main__':\n print(\"Initializing Datasets and Dataloaders...\")\n\n # Create training and validation datasets\n image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), xception_default_data_transforms[x])\n for x in ['train', 'val']}\n # Create training and validation dataloaders\n dataloaders_dict = {\n x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=0)\n for x in ['train', 'val']}\n\n # Detect if we have a GPU available\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n p = parser = argparse.ArgumentParser(description='Process some integers.')\n p.add_argument('--pretrain3epochs', action='store_true')\n args = p.parse_args()\n\n if args.pretrain3epochs:\n pretrain3epoch = True\n num_epochs = 0\n print('True')\n else:\n pretrain3epoch = False\n num_epochs = 15\n print('False')\n\n\n model_ft = return_pytorch04_xception_ft(True, pretrain3epoch)\n set_parameter_requires_grad(model_ft, pretrain3epoch)\n if pretrain3epoch:\n num_ftrs = model_ft.last_linear.in_features\n model_ft.last_linear = nn.Linear(num_ftrs, num_classes)\n\n print(model_ft)\n\n model_ft = model_ft.to(device)\n\n # Gather the parameters to be optimized/updated in this run. If we are\n # finetuning we will be updating all parameters. However, if we are\n # doing feature extract method, we will only update the parameters\n # that we have just initialized, i.e. the parameters with requires_grad\n # is True.\n params_to_update = model_ft.parameters()\n print(\"Params to learn:\")\n if pretrain3epoch:\n params_to_update = []\n for name, param in model_ft.named_parameters():\n\n if param.requires_grad == True:\n params_to_update.append(param)\n print(\"\\t\", name)\n else:\n for name, param in model_ft.named_parameters():\n if param.requires_grad == True:\n print(\"\\t\", name)\n\n\n # Observe that all parameters are being optimized\n optimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)\n\n # Setup the loss fxn\n criterion = nn.CrossEntropyLoss()\n\n # Train and evaluate\n model_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs)\n\n if pretrain3epoch:\n # torch.save(model_ft.state_dict(), '/home/jc/Faceforensics_onServer/Model/xception-b5690688-after3epochs-noNT-Big.pth')\n torch.save(model_ft.state_dict(),\n '/home/jc/Faceforensics_onServer/Model/xception-b5690688-after0epochs-noNT-Big.pth')\n else:\n torch.save(model_ft.state_dict(),\n '/home/jc/Faceforensics_onServer/Model/xception-b5690688-after15epochs-noNT-Big.pth')\n","sub_path":"TrainModel/TrainModel_2.py","file_name":"TrainModel_2.py","file_ext":"py","file_size_in_byte":7638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"247457387","text":"import Simulation as Games\n\nNUMBER_GAMES = 1000 # number of games within each simulation\n\nNUMBER_FLIPS = 20 # number of coin flips within each game\nHEADS_PROB = 0.4 # probability of heads\n\n# Create simulation called myMoney\nmyMoney = Games.Simulation(1, NUMBER_GAMES, HEADS_PROB)\n# Run each game within myMoney\nmyMoney.simulate(NUMBER_FLIPS)\n\n# Calculate the Expected Value\nprint(myMoney.get_expected_value())","sub_path":"Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"88611071","text":"from django.conf import settings\n\n\nclass SecurityHeaderMiddleware(object):\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n response['X-XSS-Protection'] = '1; mode=block'\n response['X-DNS-Prefetch-Control'] = 'off'\n response['X-Download-Options'] = 'noopen'\n response['X-Content-Type-Options'] = 'nosniff'\n if not settings.DEBUG:\n response['Strict-Transport-Security'] = 'max-age=15552000; includeSubDomains'\n \n return response\n","sub_path":"main/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"470279464","text":"# *-* encoding: utf-8 *-*\nimport argparse,json,os,csv,sys,datetime,re,unicodedata,itertools\n\ndef parserTweetDate(filein,fileout_hsh,fileout_usrhsh,fileout_hshhsh,date):\n counter_sk = 0\n counter_notw = 0\n counter_ok = 0\n counter_line = 0\n\n for line in filein.readlines():\n counter_line += 1\n if counter_line % 100000 == 0:\n print(counter_line,'lines treated')\n try:\n tw = json.loads(line)\n except:\n counter_sk += 1\n continue\n if 'twitter' not in tw.keys():\n counter_notw += 1\n continue\n\n d = [int(i) for i in re.findall(r'[0-9]+',tw['twitter']['created_at'])]\n dt = datetime.datetime(*d[0:6])\n ts = dt.timestamp()\n\n if ts < date:\n if 'hashtags' in tw['twitter']:\n uid = tw['twitter']['user']['id']\n hashtags = tw['twitter']['hashtags']\n hashtags_f = []\n for h in hashtags:\n h_f = ''.join(c for c in unicodedata.normalize('NFD', h) if unicodedata.category(c) != 'Mn').lower()\n t = re.sub(r'[^a-zA-Z0-9]+','',h_f)\n if t == h_f:\n hashtags_f.append(h_f)\n fileout_usrhsh.write(str(uid)+','+h_f+','+str(ts)+'\\n')\n fileout_hsh.write(h_f+','+str(ts)+'\\n')\n if len(hashtags_f) > 1:\n for el in itertools.combinations(hashtags_f,2):\n fileout_hshhsh.write(el[0]+','+el[1]+','+str(ts)+'\\n')\n fileout_hshhsh.write(el[1]+','+el[0]+','+str(ts)+'\\n')\n counter_ok+=1\n\n print('Finished treating file',filein.name,'for date',date)\n print(counter_line,'lines treated')\n print(counter_sk,'lines with no json format')\n print(counter_notw,'lines with no tweet format')\n print(counter_ok,'lines for which entries were created')\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i','--inputfile',\n type=argparse.FileType('r'),\n default=sys.stdin,\n help=\"Input file, json format, tweets\")\n parser.add_argument('-o1','--outputHashes',\n type=argparse.FileType('a'),\n required=True,\n help=\"Output file for hash per period\")\n parser.add_argument('-o2','--outputUserHashes',\n type=argparse.FileType('a'),\n required=True,\n help=\"Output file for user hash per period\")\n parser.add_argument('-o3','--outputHashesHashes',\n type=argparse.FileType('a'),\n required=True,\n help=\"Output file for hash co occurences per period\")\n parser.add_argument('-d','--date',\n type=float,\n required=True,\n help=\"Limit period (epoch time)\")\n\n args = parser.parse_args()\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n parserTweetDate(args.inputfile,args.outputHashes,args.outputUserHashes,args.outputHashesHashes,args.date)\n\n args.inputfile.close()\n args.outputHashes.close()\n args.outputUserHashes.close()\n args.outputHashesHashes.close()\n\nif __name__ == '__main__':\n main()\n\n \n\n","sub_path":"version_20160401.dir/study_period_4_weeks_3_week_ovlerap.dir/evolvingnetwork.dir/intervalfiles.dir/crawlerperperiod.dir/extract_hash_per_period.py","file_name":"extract_hash_per_period.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"630401755","text":"import requests\nimport urllib3\nimport json\nimport urllib\nimport urllib.request\n\nheaders = {\n 'Accept': '*/*',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\n 'Referer':\"https://item.jd.com/100000177760.html#comment\"\n}\n\n# flag\nflag = True\n\n# https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv102&productId=100006154988&score=3&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1\n\n\ndef getjsontxt(url):\n try:\n r = requests.get(url, timeout = 30, headers = headers)\n r.raise_for_status()\n\n return r.text\n except:\n return \"存在异常\"\n\n\nstr = \"https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv102&productId=100006154988&score=3&sortType=5&page=0&pageSize=100&isShadowSku=0&fold=0\"\nres = getjsontxt(str)\nres = res.split('(')[1].split(')')[0]\nprint(res)\n\ndef json_op(result):\n global flag\n j = json.loads(result)\n comments = j[\"comments\"]\n # print(comments)\n for i in comments:\n text = i[\"content\"]\n if flag:\n flag = False\n with open(\"D://CCCC.txt\",'w', encoding='UTF-8') as file:\n file.write(text + \"\\n-----------------------\\n\")\n file.close()\n else:\n with open(\"D://CCCC.txt\", 'a', encoding='UTF-8') as file:\n file.write(text + \"\\n-----------------------\\n\")\n file.close()\n\njson_op(res)","sub_path":"CrawlerSpider.py","file_name":"CrawlerSpider.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"266499365","text":"\"\"\"empty message\n\nRevision ID: 4b2424d9f6a6\nRevises: b54b3d223e13\nCreate Date: 2017-04-02 22:50:01.833232\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4b2424d9f6a6'\ndown_revision = 'b54b3d223e13'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('session_levels',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('session_id', sa.Text(length=128), nullable=True),\n sa.Column('phone_number', sa.String(length=25), nullable=True),\n sa.Column('level', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('session_id')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=64), nullable=True),\n sa.Column('phone_number', sa.String(length=64), nullable=False),\n sa.Column('city', sa.String(length=64), nullable=True),\n sa.Column('registration_date', sa.DateTime(), nullable=True),\n sa.Column('password_hash', sa.String(length=128), nullable=True),\n sa.Column('account', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_users_phone_number'), 'users', ['phone_number'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_users_phone_number'), table_name='users')\n op.drop_table('users')\n op.drop_table('session_levels')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/4b2424d9f6a6_.py","file_name":"4b2424d9f6a6_.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"481579076","text":"class EnumMeta(type):\n def __new__(cls, name, bases, dict):\n\n dict['__mapping__'] = {}\n members = {k: v for (k, v) in dict.items() if not (k.startswith('__') and k.endswith('__'))}\n enum = super().__new__(cls, name, bases, dict)\n for key, value in members.items():\n value = enum(value)\n value.name = key\n setattr(enum, key, value)\n return enum\n\n def __iter__(self):\n return (self.__name__ + \".\" + name for name in self.__dict__.keys() if\n not (name.startswith('__') and name.endswith('__')))\n\n def __getitem__(self, item):\n try:\n return self.__dict__[item]\n except KeyError:\n return \"KeyError: '{}'\".format(item)\n\n\nclass Enum(metaclass=EnumMeta):\n __mapping__ = {}\n\n def __new__(cls, value):\n if value in cls.__mapping__:\n return cls.__mapping__[value]\n v = super().__new__(cls)\n v.value = value\n v.name = ''\n cls.__mapping__[value] = v\n return v\n\n def __repr__(self):\n if self.name in Direction.__dict__:\n return '<{}.{}: {}>'.format(self.__class__.__name__, self.name, self.value)\n else:\n return \"ValueError: {} is not a valid Direction\".format(self.value)\n\n\nclass Direction(Enum):\n north = 0\n east = 90\n south = 180\n west = 270\n\n\nprint(Direction.north)\nprint(Direction.south)\nprint(Direction.north.name)\nprint(Direction.north.value)\nprint(Direction(0))\nprint(Direction(30))\nDirection(30)\n\nfor d in Direction:\n print(d)\n\nprint(\"id of Direction.north: \" + str(id(Direction.north)))\nprint(\"id of Direction(0): \" + str(id(Direction(0))))\n\nprint(Direction['west'])\nprint(Direction['north-west'])\n","sub_path":"lesson OOP-2/Bogucharov_HW2.py","file_name":"Bogucharov_HW2.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"96360883","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport os\nimport sys\nfrom pathlib import Path\nimport pystache\nimport datetime\nimport base64\nimport html\n\nnow = datetime.datetime.now()\n\nhandles = {\n 'YEAR': now.year\n}\n\ntry:\n handles['REPO_TITLE'] = os.environ['REPO_TITLE']\n handles['REPO_NAME'] = os.environ['REPO_NAME']\n handles['RELEASE'] = os.environ['RELEASE']\n handles['MINOR'] = os.environ['MINOR']\n handles['PATCH'] = os.environ['PATCH']\n handles['REPO_PATH'] = os.environ['REPO_PATH']\n handles['DEVELOPER'] = os.environ['DEVELOPER']\nexcept:\n print(\"Error: %s\\n\" % sys.exc_info()[0])\n print(\"Is direnv working correctly?\\n\")\n os.Exit(1)\n\n\ndef load_snippets():\n res = subprocess.getoutput(\"cd / && find %s/repo/snippets -type f -not -path '*/\\.*'\" % handles['REPO_PATH'])\n overlay = str.split(res, '\\n')\n\n for file in overlay:\n # Reverse the full path, cut the short name off, reverse back\n v = str.split(file[::-1],'/')[0][::-1]\n handles[v] = Path(file).read_text()\n\ndef load_commit_count():\n handles['COMMIT_COUNT'] = int(subprocess.getoutput(\"git rev-list --count HEAD\"))\n\ndef load_branch():\n handles['BRANCH'] = subprocess.getoutput(\"git branch | egrep '^\\*' | rev | cut -d'/' -f1 | cut -d' ' -f1 | rev\")\n\n\ndef load_version():\n branch = str.split(subprocess.getoutput(\"git branch|grep '^*'|cut -d' ' -f2\"),'/')\n if branch[0] == 'master' or branch[0] == 'release':\n handles['VERSION'] = \"%s.%s.%s\" % (handles['RELEASE'], handles['MINOR'], handles['PATCH'])\n handles['DEV_VERSION'] = \"\"\n else:\n handles['VERSION'] = \"%s.%s.%s-%s%d\" % (handles['RELEASE'], handles['MINOR'], handles['PATCH'], handles['BRANCH'], handles['COMMIT_COUNT'])\n handles['DEV_VERSION'] = base64.b32encode(bytearray(\"%s.%s\" % (handles['DEVELOPER'], now),'ascii')).decode('utf-8')\n\ndef update_repo():\n res = subprocess.getoutput(\"cd / && find %s/repo/root -type f -not -path '*/\\.*'\" % handles['REPO_PATH'])\n overlay = str.split(res, '\\n')\n\n for template in overlay:\n t = Path(template).read_text()\n d = str.split(template,'repo/root/')[1]\n #print(\"%s -> %s/%s:\\n%s\" % (template, handles['REPO_PATH'], d, pystache.render(t,handles)))\n Path(\"%s/%s\" % (handles['REPO_PATH'], d)).write_text(html.unescape(pystache.render(t,handles)))\n subprocess.getoutput(\"git add %s/%s\" % (handles['REPO_PATH'], d))\n\nstart_dir = os.getcwd()\n\nload_commit_count()\nload_branch()\nload_version()\nload_snippets()\n\n#####\n\nupdate_repo()\n\n#print(handles)\n#fh = Path('../root/README.md').read_text()\n#print(pystache.render(fh,handles))\n\nos.chdir(start_dir)\n","sub_path":"repo/bin/overlay_repo.py","file_name":"overlay_repo.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"216435231","text":"#!/usr/bin/env python\n\n\"\"\"This module defines custom color schemes for pretty-printing colored\noutput to the console via Pygments. This requires ANSI colors, so it\n === WILL NOT WORK IN WINDOWS. ===\n\nTo add a style:\n\n 1. Create a class extending pygments.style.Style and follow the directions\n here: .\n\n See for a list of Pygments tokens and\n their meanings, and look through pygments.lexers.web.JsonLexer to see\n which ones the JSON lexer uses. TL;DR: DarkStyle (below) has everything\n you need to color JSON.\n\n 2. In get_style_by_name(), add an entry that points to your class. The\n name you give the key is what you'd pass to --style on the command\n line. If it contains a space, even just one space, absolutely nobody\n will like you.\n\n Nobody.\n\n So no spaces.\n\n\"\"\"\n\nfrom pygments.style import Style\nfrom pygments.styles import STYLE_MAP as builtin_styles\nfrom pygments.token import Keyword, Name, String, Number, Punctuation\n\n\n# This highlight scheme used when --style is omitted. Not to be confused with\n# the string 'default', which is passed to Pygments when the style that WAS\n# given with --style is not a valid name.\nDEFAULT_STYLE = 'monoclone'\n\n\n# If you don't add your style here, the --style argument won't pick it up. -----\n\n\ndef get_style_by_name(name):\n custom_styles = {\n 'monoclone': MonocloneStyle\n }\n\n try:\n return custom_styles[name]\n except KeyError:\n # 'default' is a magic default value used by Terminal256Formatter.\n return name if name in builtin_styles else 'default'\n\n\n# Custom styles begin here -----------------------------------------------------\n\n\nclass MonocloneStyle(Style):\n \"\"\"A clone of the Monokai scheme.\n\n \"\"\"\n default_style = ''\n\n styles = {\n # true, false, null\n Keyword: '#F92672',\n # { } : ,\n Punctuation: '#f8f8f2',\n # Key names, including their quotes\n Name: '#F92672',\n # Integers\n Number.Integer: '#AE81FF',\n # Floating-point numbers\n Number.Float: '#AE81FF',\n # String values, not including keys\n String.Double: '#E6DB74'\n }\n","sub_path":"styles.py","file_name":"styles.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"280937938","text":"import spacy\nfrom spacy.matcher import Matcher\n\nnlp = spacy.load(\"fr_core_news_sm\")\nmatcher = Matcher(nlp.vocab)\n\ndoc = nlp(\n \"Après avoir effectué la mise à jour d'iOS vous ne constaterez pas de \"\n \"renouveau radical : rien de commun avec le bouleversement que nous \"\n \"avions connu avec iOS 7. Globalement iOS 11 reste très semble à iOS 10. \"\n \"Mais vous découvrirez quelques changements en approfondissant un peu.\"\n)\n\n# Écris un motif des versions complètes d'iOS (\"iOS 7\", \"iOS 11\", \"iOS 10\")\npattern = [{\"TEXT\": \"iOS\"}, {\"IS_DIGIT\": True}]\n\n# Ajoute le motif au matcher et applique le matcher au doc\nmatcher.add(\"IOS_VERSION_PATTERN\", None, pattern)\nmatches = matcher(doc)\nprint(\"Nombre de correspondances trouvées :\", len(matches))\n\n# Itère sur les correspondances et affiche la portion de texte\nfor match_id, start, end in matches:\n print(\"Correspondance trouvée :\", doc[start:end].text)\n","sub_path":"exercises/fr/solution_01_12_01.py","file_name":"solution_01_12_01.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"143664815","text":"\"\"\"\n一周中上一次出现某天时的日期\n\"\"\"\nimport datetime as dt\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil.rrule import *\n\nweekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\n\ndef get_previous_by_day(day_name, start_date=None):\n if start_date is None:\n start_date = dt.datetime.today()\n day_num = start_date.weekday()\n day_num_target = weekdays.index(day_name)\n days_ago = (7 + day_num - day_num_target) % 7\n if days_ago == 0:\n days_ago = 7\n target_date = start_date - dt.timedelta(days=days_ago)\n return target_date\n\n\nnow = dt.datetime.now()\nprint(now)\nprint(now + relativedelta(weekday=MO))\nprint(now + relativedelta(weekday=MO(-1)))\n","sub_path":"3 数字、日期和时间/13 计算上周五的日期.py","file_name":"13 计算上周五的日期.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"356443283","text":"import configparser\nimport datetime\nimport json\nimport time\nimport traceback\nfrom collections import Counter, deque\nfrom random import random\n\nimport httplib2\nfrom googleapiclient.discovery import build\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.file import Storage\nfrom oauth2client.tools import run_flow\n\nimport pywemo\n\nSTORAGE = Storage(\"credentials.storage\")\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\n# Console output will show the temperature in F or C.\nFAHRENHEIT = config.getboolean(\"DEFAULT\", \"Fahrenheit\")\nPOLLING_PERIOD_S = config.getint(\"DEFAULT\", \"PollingPeriodS\")\naux_heat_thresh = config.getint(\"DEFAULT\", \"AuxHeatThreshold\")\nAUX_HEAT_THRESHOLD_C = aux_heat_thresh * 5 / 9.0 if FAHRENHEIT else aux_heat_thresh\nHUMIDITY_PERCENT_TARGET = config.getint(\"DEFAULT\", \"HumidityPercentTarget\")\nHUMIDITY_PERCENT_THRESHOLD = config.getint(\"DEFAULT\", \"HumidityPercentThreshold\")\n\nGOOGLE_ENTERPRISE = config[\"google\"][\"Enterprise\"]\nGOOGLE_CLIENT_SECRET = config[\"google\"][\"ClientSecretFile\"]\nGOOGLE_SCOPE = \"https://www.googleapis.com/auth/sdm.service\"\n\nWEMO_HEATING_DEVICE_NAMES = set(json.loads(config.get(\"wemo\", \"HeatingDeviceNames\")))\nWEMO_COOLING_DEVICE_NAMES = set(json.loads(config.get(\"wemo\", \"CoolingDeviceNames\")))\nWEMO_AUXILLIARY_HEATING_DEVICE_NAMES = set(\n json.loads(config.get(\"wemo\", \"AuxiliaryHeatingDeviceNames\"))\n)\nWEMO_HUMIDIFIER_DEVICE_NAMES = set(json.loads(config.get(\"wemo\", \"HumidifierNames\")))\n\n\ndef authorize_credentials():\n \"\"\"Start the OAuth flow to retrieve credentials.\n This may require launching a browser, one time.\"\"\"\n # Fetch credentials from storage\n credentials = STORAGE.get()\n # If the credentials doesn't exist in the storage location then run the flow.\n if credentials is None or credentials.invalid:\n flow = flow_from_clientsecrets(GOOGLE_CLIENT_SECRET, scope=GOOGLE_SCOPE)\n http = httplib2.Http()\n credentials = run_flow(flow, STORAGE, http=http)\n return credentials\n\n\nservice = None\n\n\ndef nest_client():\n global service\n if service is None:\n credentials = authorize_credentials()\n http = credentials.authorize(httplib2.Http())\n service = build(\n serviceName=\"smartdevicemanagement.googleapis.com\",\n version=\"v1\",\n http=http,\n discoveryServiceUrl=\"https://{api}/$discovery/rest?version={apiVersion}\",\n )\n return service\n\n\ndef get_nest_devices():\n devices = (\n nest_client()\n .enterprises()\n .devices()\n .list(parent=\"enterprises/\" + GOOGLE_ENTERPRISE)\n .execute()\n )\n return devices[\"devices\"]\n\n\ndef get_thermostats():\n devices = get_nest_devices()\n return [x for x in devices if x[\"type\"] == \"sdm.devices.types.THERMOSTAT\"]\n\n\ndef get_nest_device(name):\n return nest_client().enterprises().devices().get(name=name).execute()\n\n\nthermostat_name = None\n\n\ndef get_first_thermostat():\n global thermostat_name\n if thermostat_name is not None:\n try:\n return get_nest_device(thermostat_name)\n except Exception as e:\n # Thermostat has changed?\n print(\"Unable to read thermostat {}: {}\".format(thermostat_name, e))\n thermostat_name = None\n # First time, or the old thermostat is offline\n if thermostat_name is None:\n thermostat_name = get_thermostats()[0][\"name\"]\n print(\"New thermostat discovered: {}\".format(thermostat_name))\n return get_nest_device(thermostat_name)\n\n\n# This tells how far back to remember a wemo device that isn't showing\n# up in discovery any more.\nWEMO_DISCOVERY_HISTORY_LEN = 10\nwemo_discovery_history = deque(maxlen=WEMO_DISCOVERY_HISTORY_LEN)\n# Once the discovery history is full, it refreshes much less frequently\n# (controlled by the refresh probability) and relies on the cached results.\nWEMO_REFRESH_PROB = 0.05\n\n\ndef get_wemo_devices():\n # Merges the last few discovery attempts, in case some wemos\n # intermittently fail to appear.\n if (\n len(wemo_discovery_history) < WEMO_DISCOVERY_HISTORY_LEN\n or random() < WEMO_REFRESH_PROB\n ):\n try:\n wemo_discovery_history.appendleft(pywemo.discover_devices())\n except:\n print(\"Wemo discovery exception:\")\n traceback.print_exc()\n # Merge and filter out duplicates by MAC address\n devices = set()\n macs = set()\n for discovery in wemo_discovery_history:\n for device in discovery:\n if device.mac not in macs:\n macs.add(device.mac)\n devices.add(device)\n return devices\n\n\ndevice_error_count = Counter()\nMAX_RETRIES = config.getint(\"wemo\", \"MaxPowerOffRetries\")\n\n\ndef reset_wemo_devices(device_set, skipping=None):\n \"\"\"Turns as set of wemos off, and removes them from the set if successful.\n Devices specified by 'skipping' are not turned off, although they are\n still removed from the set.\"\"\"\n\n if skipping:\n device_set.difference_update(skipping)\n toggled_successfully = set()\n for device in device_set:\n try:\n print(\"Turning {} off.\".format(device.name))\n device.off()\n toggled_successfully.add(device)\n except:\n print(\"Unable to toggle {}\".format(device.name))\n traceback.print_exc()\n device_error_count[device.mac] += 1\n if device_error_count[device.mac] > MAX_RETRIES:\n print(\n \"Giving up on {} after {} retries.\".format(device.name, MAX_RETRIES)\n )\n toggled_successfully.add(device)\n for device in toggled_successfully:\n device_set.discard(device)\n del device_error_count[device.mac]\n\n\nactivated_heating_devices = set()\nactivated_cooling_devices = set()\nactivated_humidifier_devices = set()\n\n\ndef power_off_unneeded_wemos(hvac_status):\n # Turns off wemos that aren't needed in the current state.\n # Should not mess with devices that were manually toggled, since it acts only\n # on devices that this script turned on.\n if hvac_status == \"COOLING\":\n reset_wemo_devices(\n activated_heating_devices, skipping=activated_humidifier_devices\n )\n elif hvac_status == \"HEATING\":\n reset_wemo_devices(\n activated_cooling_devices, skipping=activated_humidifier_devices\n )\n else:\n reset_wemo_devices(\n activated_heating_devices, skipping=activated_humidifier_devices\n )\n reset_wemo_devices(\n activated_cooling_devices, skipping=activated_humidifier_devices\n )\n\n\ndef power_on_needed_wemo(device, hvac_status):\n # powers on a wemo and adds it to an active set so we can remember\n # to turn if off later when HVAC status changes.\n print(\"Turning {} on for {}.\".format(device.name, hvac_status))\n try:\n device.on()\n if hvac_status == \"COOLING\":\n activated_cooling_devices.add(device)\n activated_heating_devices.discard(device)\n elif hvac_status == \"HEATING\":\n activated_heating_devices.add(device)\n activated_cooling_devices.discard(device)\n elif hvac_status == \"HUMIDIFYING\":\n activated_humidifier_devices.add(device)\n else:\n print(\"Unexpected hvac status to enable a wemo: {}\".format(hvac_status))\n except:\n print(\"Wemo powering exception:\")\n traceback.print_exc()\n\n\ndef aux_heat_is_needed(thermostat):\n # Actual room temperature.\n temperature_c = thermostat[\"traits\"][\"sdm.devices.traits.Temperature\"][\n \"ambientTemperatureCelsius\"\n ]\n # The temperature that the heater is \"set\" to.\n heat_temperature_c = thermostat[\"traits\"][\n \"sdm.devices.traits.ThermostatTemperatureSetpoint\"\n ][\"heatCelsius\"]\n hvac_status = thermostat[\"traits\"][\"sdm.devices.traits.ThermostatHvac\"][\"status\"]\n return (\n hvac_status == \"HEATING\"\n and heat_temperature_c - temperature_c > AUX_HEAT_THRESHOLD_C\n )\n\n\ndef forget_user_controlled_wemos(all_wemos):\n # If code turned a switch on but the user manually turned it off,\n # then forget about turning it off by code later. The user has taken\n # responsibility.\n global activated_heating_devices\n global activated_cooling_devices\n global activated_humidifier_devices\n activated_wemos = (\n activated_heating_devices\n | activated_cooling_devices\n | activated_humidifier_devices\n )\n user_toggled = set()\n\n for device in activated_wemos:\n if device.is_off():\n user_toggled.add(device)\n\n # As a second pass, also check for user-toggled devices by mac address.\n # This might be important if a wemo device's name is changed.\n activated_mac_to_wemo = {x.mac: x for x in activated_wemos}\n for device in all_wemos:\n if device.mac in activated_mac_to_wemo and device.is_off():\n user_toggled.add(activated_mac_to_wemo[device.mac])\n\n activated_heating_devices -= user_toggled\n activated_cooling_devices -= user_toggled\n activated_humidifier_devices -= user_toggled\n\n\ndef print_temp(thermostat):\n # Actual room temperature.\n temperature_c = thermostat[\"traits\"][\"sdm.devices.traits.Temperature\"][\n \"ambientTemperatureCelsius\"\n ]\n if FAHRENHEIT:\n temperature_f = (temperature_c * 9 / 5.0) + 32\n print(\n \"{} temperature: {:.1f} degrees F\".format(\n start.strftime(\"%Y-%m-%d %H:%M\"), temperature_f\n )\n )\n else:\n print(\n \"{} temperature: {:.1f} degrees C\".format(\n start.strftime(\"%Y-%m-%d %H:%M\"), temperature_c\n )\n )\n\n\n# Normally we don't take control of already-running devices since we don't want to override user\n# intent. But on first launch, we do. This prevents devices from getting orphaned on if the script\n# is restarted.\nfirst_iteration = True\nprev_hvac_status = None\naux_heat_engaged = False\nhumidifiers_engaged = False\nwhile True:\n # Detect when the HVAC status changes to heating, cooling, or neither.\n # Toggle Wemo switches accordingly.\n # Remember that some switches may be for both heating and cooling.\n start = datetime.datetime.now()\n try:\n wemos = get_wemo_devices()\n thermostat = get_first_thermostat()\n print_temp(thermostat)\n hvac_status = thermostat[\"traits\"][\"sdm.devices.traits.ThermostatHvac\"][\n \"status\"\n ]\n\n forget_user_controlled_wemos(wemos)\n\n if hvac_status != prev_hvac_status:\n # hvac status has changed. flick some switches.\n aux_heat_engaged = False\n for wemo in wemos:\n if hvac_status == \"COOLING\" and wemo.name in WEMO_COOLING_DEVICE_NAMES:\n power_on_needed_wemo(wemo, hvac_status)\n elif (\n hvac_status == \"HEATING\" and wemo.name in WEMO_HEATING_DEVICE_NAMES\n ):\n power_on_needed_wemo(wemo, hvac_status)\n\n # Humidifiers can kick on or off independent of the hvac\n humidity = thermostat[\"traits\"][\"sdm.devices.traits.Humidity\"][\n \"ambientHumidityPercent\"\n ]\n if (\n not humidifiers_engaged\n and humidity < HUMIDITY_PERCENT_TARGET - HUMIDITY_PERCENT_THRESHOLD\n ):\n humidifiers_engaged = True\n for wemo in wemos:\n if wemo.name in WEMO_HUMIDIFIER_DEVICE_NAMES and (\n wemo.is_off() or first_iteration\n ):\n # dummy hvac status, but our method understands it anyway.\n power_on_needed_wemo(wemo, \"HUMIDIFYING\")\n elif humidity > HUMIDITY_PERCENT_TARGET + HUMIDITY_PERCENT_THRESHOLD:\n humidifiers_engaged = False\n reset_wemo_devices(\n activated_humidifier_devices,\n skipping=activated_cooling_devices | activated_heating_devices,\n )\n\n # Auxiliary heat can kick on in the middle of a cycle, but only once per cycle.\n if aux_heat_is_needed(thermostat) and not aux_heat_engaged:\n aux_heat_engaged = True\n # aux heat includes stuff like little space heaters. If you turned one on\n # manually, I want to leave it out of automatic control so you can have\n # your room as toasty as you like. Hence the \"is_off()\" check before\n # starting automatic control here.\n for wemo in wemos:\n if wemo.name in WEMO_AUXILLIARY_HEATING_DEVICE_NAMES and (\n wemo.is_off() or first_iteration\n ):\n power_on_needed_wemo(wemo, hvac_status)\n power_off_unneeded_wemos(hvac_status)\n prev_hvac_status = hvac_status\n except:\n print(\"Top-level exception:\")\n traceback.print_exc()\n first_iteration = False\n first_iteration = False\n iteration_s = (datetime.datetime.now() - start).total_seconds()\n time.sleep(max(POLLING_PERIOD_S - iteration_s, 5))","sub_path":"wenestmo.py","file_name":"wenestmo.py","file_ext":"py","file_size_in_byte":13088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"215419952","text":"import json\nimport sys\n\nfrom flask import Flask, request\n\nimport consume\nimport parse\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.insert(1, '/home/fabian/cos/scrapi/')\n\napp = Flask(__name__)\n\n\n@app.route('/consume', methods=['GET', 'POST'])\ndef consume_day():\n return consume.consume()\n\n\n@app.route('/process', methods=['GET', 'POST'])\ndef parse_all():\n result = json.loads(request.args.get('doc'))\n timestamp = request.args.get('timestamp')\n return parse.parse(result, timestamp)\n\n\nif __name__ == '__main__':\n app.run(\n host=\"0.0.0.0\",\n port=1338,\n debug=True\n )\n","sub_path":"website/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"277864367","text":"import os\nimport time\nimport datetime\nimport collections\nimport socket\nfrom calendar import timegm\nfrom future.utils import iteritems\n\nimport json\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\ntry:\n from threading import get_ident\nexcept ImportError:\n from thread import get_ident\n\nfrom pandaharvester.harvesterconfig import harvester_config\nfrom pandaharvester.harvestercore import core_utils\nfrom pandaharvester.harvestercore.plugin_factory import PluginFactory\nfrom pandaharvester.harvestercore.db_proxy_pool import DBProxyPool as DBProxy\nfrom pandaharvester.harvestercore.db_interface import DBInterface\n\n# attribute list\n_attribute_list = ['id', 'item', 'score']\n\n# fifo object spec\nFifoObject = collections.namedtuple('FifoObject', _attribute_list, verbose=False, rename=False)\n\n# logger\n_logger = core_utils.setup_logger('fifos')\n\n\n# base class of fifo message queue\nclass FIFOBase(object):\n # constructor\n def __init__(self, **kwarg):\n for tmpKey, tmpVal in iteritems(kwarg):\n setattr(self, tmpKey, tmpVal)\n self.hostname = socket.gethostname()\n self.os_pid = os.getpid()\n self.dbProxy = DBProxy()\n self.dbInterface = DBInterface()\n\n # get process identifier\n def get_pid(self):\n thread_id = get_ident()\n if thread_id is None:\n thread_id = 0\n return '{0}_{1}-{2}'.format(self.hostname, self.os_pid, format(get_ident(), 'x'))\n\n # make logger\n def make_logger(self, base_log, token=None, method_name=None, send_dialog=True):\n if send_dialog and hasattr(self, 'dbInterface'):\n hook = self.dbInterface\n else:\n hook = None\n return core_utils.make_logger(base_log, token=token, method_name=method_name, hook=hook)\n\n # intialize fifo from harvester configuration\n def _initialize_fifo(self):\n self.fifoName = '{0}_fifo'.format(self.titleName)\n self.config = getattr(harvester_config, self.titleName)\n if hasattr(self.config, 'fifoEnable') and self.config.fifoEnable:\n self.enabled = True\n else:\n self.enabled = False\n return\n pluginConf = vars(self.config).copy()\n pluginConf.update( {'titleName': self.titleName} )\n if hasattr(self.config, 'fifoModule') and hasattr(self.config, 'fifoClass'):\n pluginConf.update( {'module': self.config.fifoModule,\n 'name': self.config.fifoClass,} )\n else:\n if not hasattr(harvester_config, 'fifo'):\n return\n pluginConf.update( {'module': harvester_config.fifo.fifoModule,\n 'name': harvester_config.fifo.fifoClass,} )\n pluginFactory = PluginFactory()\n self.fifo = pluginFactory.get_plugin(pluginConf)\n\n # encode\n def encode(self, obj):\n obj_serialized = pickle.dumps(obj, -1)\n return obj_serialized\n\n # decode\n def decode(self, obj_serialized):\n obj = pickle.loads(obj_serialized)\n return obj\n\n # size of queue\n def size(self):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='size')\n retVal = self.fifo.size()\n mainLog.debug('size={0}'.format(retVal))\n return retVal\n\n # enqueue\n def put(self, obj, score=None, encode_item=True):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='put')\n if encode_item:\n # obj_serialized = json.dumps(obj, cls=PythonObjectEncoder)\n obj_serialized = self.encode(obj)\n else:\n obj_serialized = obj\n if score is None:\n score = time.time()\n retVal = self.fifo.put(obj_serialized, score)\n mainLog.debug('score={0}'.format(score))\n return retVal\n\n # enqueue by id, which is unique\n def putbyid(self, id, obj, score=None, encode_item=True):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='putbyid')\n if encode_item:\n # obj_serialized = json.dumps(obj, cls=PythonObjectEncoder)\n obj_serialized = self.encode(obj)\n else:\n obj_serialized = obj\n if score is None:\n score = time.time()\n retVal = self.fifo.putbyid(id, obj_serialized, score)\n mainLog.debug('id={0} score={1}'.format(id, score))\n return retVal\n\n # dequeue to get the first fifo object\n def get(self, timeout=None, protective=False, decode_item=True):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='get')\n object_tuple = self.fifo.get(timeout, protective)\n # retVal = json.loads(obj_serialized, object_hook=as_python_object)\n if object_tuple is None:\n retVal = None\n else:\n id, obj_serialized, score = object_tuple\n if obj_serialized is not None and decode_item:\n obj = self.decode(obj_serialized)\n else:\n obj = obj_serialized\n retVal = FifoObject(id, obj, score)\n mainLog.debug('called. protective={0}'.format(protective))\n return retVal\n\n # dequeue to get the last fifo object\n def getlast(self, timeout=None, protective=False, decode_item=True):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='getlast')\n object_tuple = self.fifo.getlast(timeout, protective)\n # retVal = json.loads(obj_serialized, object_hook=as_python_object)\n if object_tuple is None:\n retVal = None\n else:\n id, obj_serialized, score = object_tuple\n if obj_serialized is not None and decode_item:\n obj = self.decode(obj_serialized)\n else:\n obj = obj_serialized\n retVal = FifoObject(id, obj, score)\n mainLog.debug('called. protective={0}'.format(protective))\n return retVal\n\n # get tuple of the first object and its score without dequeuing\n # If item is large un unnecessary to show int peek, set skip_item=True\n def peek(self, skip_item=False):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='peek')\n object_tuple = self.fifo.peek(skip_item=skip_item)\n if object_tuple is None:\n retVal = None\n mainLog.debug('fifo empty')\n else:\n id, obj_serialized, score = object_tuple\n # retVal = (json.loads(obj_serialized, object_hook=as_python_object), score)\n if obj_serialized is None and score is None:\n retVal = FifoObject(None, None, None)\n else:\n if score is None:\n score = time.time()\n retVal = FifoObject(id, obj_serialized, score)\n mainLog.debug('score={0}'.format(score))\n return retVal\n\n # get tuple of the last object and its score without dequeuing\n def peeklast(self, skip_item=False):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='peeklast')\n object_tuple = self.fifo.peeklast(skip_item=skip_item)\n if object_tuple is None:\n retVal = None\n mainLog.debug('fifo empty')\n else:\n id, obj_serialized, score = object_tuple\n # retVal = (json.loads(obj_serialized, object_hook=as_python_object), score)\n if obj_serialized is None and score is None:\n retVal = FifoObject(None, None, None)\n else:\n if score is None:\n score = time.time()\n retVal = FifoObject(id, obj_serialized, score)\n mainLog.debug('score={0}'.format(score))\n return retVal\n\n # get tuple of the object by id without dequeuing\n def peekbyid(self, id, temporary=False, skip_item=False):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='peekbyid')\n object_tuple = self.fifo.peekbyid(id, temporary, skip_item=skip_item)\n if object_tuple is None:\n retVal = None\n mainLog.debug('fifo empty')\n else:\n id_gotten, obj_serialized, score = object_tuple\n # retVal = (json.loads(obj_serialized, object_hook=as_python_object), score)\n if obj_serialized is None and score is None:\n retVal = FifoObject(None, None, None)\n else:\n if score is None:\n score = time.time()\n retVal = FifoObject(id, obj_serialized, score)\n mainLog.debug('id={0} score={1} temporary={2}'.format(id, score, temporary))\n return retVal\n\n # remove objects by list of ids from temporary space, return the number of objects successfully removed\n def release(self, ids):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='release')\n retVal = self.fifo.delete(ids)\n mainLog.debug('released {0} objects in {1}'.format(retVal, ids))\n return retVal\n\n # restore objects by list of ids from temporary space to fifo; ids=None to restore all objects\n def restore(self, ids=None):\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='restore')\n retVal = self.fifo.restore(ids)\n if ids is None:\n mainLog.debug('restored all objects')\n else:\n mainLog.debug('restored objects in {0}'.format(ids))\n return retVal\n\n\n# Special fifo base for non havester-agent\nclass SpecialFIFOBase(FIFOBase):\n # constructor\n def __init__(self, **kwarg):\n FIFOBase.__init__(self, **kwarg)\n self.fifoName = '{0}_fifo'.format(self.titleName)\n pluginConf = {}\n pluginConf.update( {'titleName': self.titleName} )\n pluginConf.update( {'module': harvester_config.fifo.fifoModule,\n 'name': harvester_config.fifo.fifoClass,} )\n pluginFactory = PluginFactory()\n self.fifo = pluginFactory.get_plugin(pluginConf)\n\n\n# Benchmark fifo\nclass BenchmarkFIFO(SpecialFIFOBase):\n titleName = 'benchmark'\n\n\n# monitor fifo\nclass MonitorFIFO(FIFOBase):\n titleName = 'monitor'\n\n # constructor\n def __init__(self, **kwarg):\n FIFOBase.__init__(self, **kwarg)\n self._initialize_fifo()\n\n def populate(self, seconds_ago=0, clear_fifo=False):\n \"\"\"\n Populate monitor fifo with all active worker chunks and timeNow as score from DB\n with modificationTime earlier than seconds_ago seconds ago\n object in fifo = [(queueName_1, [[worker_1_1], [worker_1_2], ...]), (queueName_2, ...)]\n \"\"\"\n if clear_fifo:\n self.fifo.clear()\n try:\n fifoMaxWorkersToPopulate = self.config.fifoMaxWorkersToPopulate\n except AttributeError:\n fifoMaxWorkersToPopulate = 2**32\n try:\n fifoMaxWorkersPerChunk = self.config.fifoMaxWorkersPerChunk\n except AttributeError:\n fifoMaxWorkersPerChunk = 500\n workspec_iterator = self.dbProxy.get_active_workers(fifoMaxWorkersToPopulate, seconds_ago)\n last_queueName = None\n workspec_chunk = []\n timeNow_timestamp = time.time()\n score = timeNow_timestamp\n for workspec in workspec_iterator:\n workspec.set_work_params({'lastCheckAt': timeNow_timestamp})\n if last_queueName is None:\n try:\n score = timegm(workspec.modificationTime.utctimetuple())\n except Exception:\n pass\n workspec_chunk = [[workspec]]\n last_queueName = workspec.computingSite\n elif workspec.computingSite == last_queueName \\\n and len(workspec_chunk) < fifoMaxWorkersPerChunk:\n workspec_chunk.append([workspec])\n else:\n self.put((last_queueName, workspec_chunk), score)\n try:\n score = timegm(workspec.modificationTime.utctimetuple())\n except Exception:\n pass\n workspec_chunk = [[workspec]]\n last_queueName = workspec.computingSite\n if len(workspec_chunk) > 0:\n self.put((last_queueName, workspec_chunk), score)\n\n def to_check_workers(self, check_interval=harvester_config.monitor.checkInterval):\n \"\"\"\n Justify whether to check any worker by the modificationTime of the first worker in fifo\n retVal True if OK to dequeue to check;\n retVal False otherwise.\n Return retVal, overhead_time\n \"\"\"\n mainLog = self.make_logger(_logger, 'id={0}-{1}'.format(self.fifoName, self.get_pid()), method_name='to_check_worker')\n retVal = False\n overhead_time = None\n timeNow_timestamp = time.time()\n peeked_tuple = self.peek(skip_item=True)\n if peeked_tuple is not None:\n # if False:\n # mainLog.warning('False. Got a null object but with score in FIFO')\n # try:\n # obj_gotten = self.get(timeout=1, protective=False, decode_item=False)\n # if obj_gotten is None:\n # mainLog.debug('Got nothing. Skipped')\n # elif obj_gotten.item is None:\n # mainLog.info('Removed a null object')\n # else:\n # self.put(obj_gotten.item, score=obj_gotten.score, encode_item=False)\n # mainLog.debug('Released an non-null object and put it back')\n # except Exception as _e:\n # mainLog.warning('Error when trying to remove a null object: {0} . Skipped'.format(_e))\n score = peeked_tuple.score\n overhead_time = timeNow_timestamp - score\n if overhead_time > 0:\n retVal = True\n if score < 0:\n mainLog.debug('True. Preempting')\n overhead_time = None\n else:\n mainLog.debug('True')\n mainLog.info('Overhead time is {0} sec'.format(overhead_time))\n else:\n mainLog.debug('False. Workers too young to check')\n mainLog.debug('Overhead time is {0} sec'.format(overhead_time))\n else:\n mainLog.debug('False. Got nothing in FIFO')\n return retVal, overhead_time\n","sub_path":"pandaharvester/harvestercore/fifos.py","file_name":"fifos.py","file_ext":"py","file_size_in_byte":14680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"223948892","text":"import os, stat\nallFiles = os.listdir('.')\nscripts = [name for name in allFiles if name.endswith(('.sh', '.py'))]\nprint(scripts)\n\n# 显示文件信息\nprint(os.stat('a.sh'))\n# os.stat('e.py').st_mode 显示文件权限\n# oct(os.stat('e.py').st_mode human reading 显示文件权限\n# os.chmod('e.py', os.stat('e.py'.st_mode) | stat.S_IXUSR) 给用户加执行权限\n","sub_path":"第三章/2nd.py","file_name":"2nd.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"232201801","text":"from weather import Weather, Unit\nimport datetime\nimport click\n\n\ndef get_scale_info(scale):\n if scale == 'c':\n unit = Unit.CELSIUS\n scale_name = 'celcius'\n elif scale == 'f':\n unit = Unit.FAHRENHEIT\n scale_name = 'fahrenheit'\n return unit, scale_name\n\n\ndef forecast_length(forecast):\n split_forecast = forecast.split(\"+\")\n if len(split_forecast) == 1:\n forecast_len = 0\n else:\n forecast_len = int(split_forecast[1])\n return forecast_len\n\n\ndef print_weather_by_city(city, forcasts_list, scale_name, forecast_len = 0):\n print('The weather in {0} today is {1} with temperatures trailing from {2} - {3} {4}'\n .format(city, forcasts_list[0].text, forcasts_list[0].low, forcasts_list[0].high, scale_name))\n\n if forecast_len > 0:\n print('Forecast for the next {0} days:'.format(forecast_len))\n for i in range(1,forecast_len + 1):\n print('{0} {1} with temperatures trailing from {2} - {3} {4}'\n .format(forcasts_list[i].date, forcasts_list[i].text, forcasts_list[i].low, forcasts_list[i].high, scale_name))\n\n\n@click.command()\n@click.option('--city', help='Name of the city')\n@click.option('--forecast', default='TODAY', help='TODAY or TODAY+n for future forecast, where n = [1-9]',show_default=True)\n@click.option('--scale', type=click.Choice(['c', 'f']), default='c', help='Temperature unit')\n\ndef main(city, forecast, scale):\n unit, scale_name = get_scale_info(scale)\n weather = Weather(unit)\n city_weather_info = weather.lookup_by_location(city)\n forecasts_list = city_weather_info.forecast\n forecast_len = forecast_length(forecast)\n print_weather_by_city(city, forecasts_list, scale_name, forecast_len)\n\nif __name__ == '__main__':\n main()","sub_path":"home-assignments/session2/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"161121974","text":"import numpy as np\nfrom vision import *\nimport cv2\nimport matplotlib.pyplot as plt\n\nclass CameraPlayer():\n\t\"\"\" \n\tPlayer object that deals with given image and Amazon logics.\n\tNote that the board matrix coordination is different from Amazon\n\tboard, i.e., the rows are flipped.\n\tAlso, note that the board shown on PC is different from real world\n\tboard, i.e., the cols are flipped.\n\t\"\"\"\n\tdef __init__(self, params, mac, edge, delay=2):\n\t\t\"\"\"\n\t\t:param: PARAMS: Classifier parameters.\n\t\t:param: MAC: MAC address.\n\t\t:param: EDGE: Edge coordinations.\n\t\t:param: DELAY: Delay time for camera capturing.\n\t\t\"\"\"\n\t\tself.params = params\n\t\tself.video = 'http://admin:admin@%s:8081' % mac\n\t\tself.delay = delay\n\t\tself.board = np.zeros((SIZE, SIZE))\n\t\tself.edge = edge\n\t\t# BOARD init. Keep it synchronized with Java.\n\t\tif SIZE == 10:\n\t\t\tself.board[6][0] = 1\n\t\t\tself.board[6][9] = 1\n\t\t\tself.board[9][3] = 1\n\t\t\tself.board[9][6] = 1\n\t\t\tself.board[3][0] = 2\n\t\t\tself.board[3][9] = 2\n\t\t\tself.board[0][3] = 2\n\t\t\tself.board[0][6] = 2\n\t\telse:\n\t\t\tif SIZE != 7:\n\t\t\t\tprint('error: unsupported SIZE encountered')\n\t\t\t\texit(-1)\n\t\t\tself.board[2][0] = 2\n\t\t\tself.board[2][6] = 2\n\t\t\tself.board[0][2] = 2\n\t\t\tself.board[0][4] = 2\n\t\t\tself.board[4][0] = 1\n\t\t\tself.board[4][6] = 1\n\t\t\tself.board[6][2] = 1\n\t\t\tself.board[6][4] = 1\n\t\tself.turn = 0 # Not used.\n\t\t\n\tdef get_img(self):\n\t\tdelay = self.delay\n\t\tcapture = cv2.VideoCapture(self.video)\n\t\tprint('delay for %f seconds...' % delay)\n\t\tcv2.namedWindow('camera')\n\t\tdelay = delay * 1000\n\t\tperiod = 0\n\t\twhile period < delay:\n\t\t\tsuccess, img = capture.read() # Have to read it continuously \n\t\t\t # to keep the camera activated,\n\t\t\t # else the picture is blackened.\n\t\t\tif not success:\n\t\t\t\tprint('video capturing failed')\n\t\t\t\tcapture.release()\n\t\t\t\texit(0)\n\t\t\tcv2.imshow('camera', img)\n\t\t\tcv2.waitKey(100)\n\t\t\tperiod += 100\n\t\tcv2.destroyWindow('camera')\n\t\tsuccess, img = capture.read()\n\t\tif not success:\n\t\t\tprint('video capturing failed')\n\t\t\tcapture.release()\n\t\t\texit(0)\n\t\tcapture.release()\n\t\treturn img\n\t\t\n\t\t\n\tdef parse_img(self, img):\n\t\t\"\"\"\n\t\tReturns a board matrix given a image.\n\t\t\"\"\"\n\t\tboard = find_board(img, thresh=(115, 170), edge=self.edge, test=False)\n\t\tddw = self.params['ddw']\n\t\tddh = self.params['ddh']\n\t\tbins = self.params['bins']\n\t\though_vote = self.params['hough_vote']\n\t\tvectors = self.params['vectors']\n\t\tcls = CellClassifier(board, ddw=ddw, ddh=ddh, bins=bins, \n\t\t hough_vote=hough_vote, vectors=vectors)\n\t\tcls.parse_board()\n\t\treturn cls.board\n\t\t\n\tdef update_board(self, movement):\n\t\t\"\"\" \n\t\tUpdate my board given a movement. Check the movement before using it.\n\t\t\"\"\"\n\t\tstart, temp = movement.split('-')\n\t\tend, spear = temp.split('(')\n\t\tspear = spear[:-1]\n\t\t\n\t\tx, y = self.parse_string(start)\n\t\tside = int(self.board[SIZE - 1 - y][x])\n\t\tif side != 1 and side != 2: # Start is not a queen.\n\t\t\tprint('Illegal movement!')\n\t\t\texit(-1)\n\t\tself.board[SIZE - 1 - y][x] = 0\n\t\tx, y = self.parse_string(end)\n\t\tself.board[SIZE - 1 - y][x] = side\n\t\tx, y = self.parse_string(spear)\n\t\tself.board[SIZE - 1 - y][x] = 3\n\t\treturn movement\n\t\t\n\tdef check_legal_move(self, move):\n\t\t\"\"\"\n\t\tA movement is legal iff start to end is unblocked and \n\t\tend to spear is unblocked given start as empty.\n\t\t\"\"\"\n\t\tstart, temp = move.split('-')\n\t\tend, spear = temp.split('(')\n\t\tspear = spear[:-1]\n\t\tstart = self.parse_string(start)\n\t\tend = self.parse_string(end)\n\t\tspear = self.parse_string(spear)\n\t\treturn self.isUnblockedMove(start, end, None) \\\n\t\t and self.isUnblockedMove(end, spear, start)\n\t\n\tdef parse_board(self, board, me=1):\n\t\t\"\"\"\n\t\tME represents human player.\n\t\tReturns iff the new movement is legal and the parsed movement.\n\t\tThe movement is parsed by simply comparing the differences after \n\t\tmaking sure the board is legal.\n\t\tNote that SELF.BOARD is the old one, while BOARD is the one prepared to update.\n\t\t\"\"\"\n\t\topponent = 1 if me == 2 else 2\n\t\tif board[board == me].shape[0] != 4 \\\n\t\t or board[board == opponent].shape[0] != 4:\n\t\t\tprint('queens lost!')\n\t\t\treturn False, None\n\t\t# Old spears should be left unmoved.\n\t\tif not np.all(board[self.board == 3] == 3):\n\t\t\tprint('spear inconsistent!')\n\t\t\treturn False, None\n\t\t# Opponent should stay unmoved.\n\t\tif not np.all(board[self.board == opponent] == opponent):\n\t\t\tprint('opponent inconsistent!')\n\t\t\treturn False, None\n\t\t# Find new spear.\n\t\tspears = list(np.argwhere(board == 3)) # Bugs happen if it is an nparray instead of list.\n\t\told_spears = list(np.argwhere(self.board == 3))\n\t\tspears = [[x[0], x[1]] for x in spears]\n\t\told_spears = [[x[0], x[1]] for x in old_spears]\n\t\tspear = None\n\t\tdifference = 0\n\t\tfor sp in spears:\n\t\t\tif sp not in old_spears:\n\t\t\t\tspear = sp\n\t\t\t\tdifference += 1\n\t\tif difference != 1:\n\t\t\tprint('spear num error! difference:', difference)\n\t\t\treturn False, None\n\t\t# Find the moved queen.\t\t\t\n\t\tmy_queens = list(np.argwhere(board == me))\n\t\tmy_old_queens = list(np.argwhere(self.board == me))\n\t\tmy_queens = [[x[0], x[1]] for x in my_queens]\n\t\tmy_old_queens = [[x[0], x[1]] for x in my_old_queens]\n\t\tdifference = 0\n\t\tend = None\n\t\tfor q in my_queens:\n\t\t\tif q not in my_old_queens:\n\t\t\t\tend = q\n\t\t\t\tdifference += 1\n\t\tif difference > 1:\n\t\t\tprint('you CHEATED!')\n\t\t\treturn False, None\n\t\t\t\n\t\tstart = None\n\t\tfor q in my_old_queens:\n\t\t\tif q not in my_queens:\n\t\t\t\tstart = q\n\t\tassert end and start and spear\n\t\t\n\t\t### transform coordination ###\n\t\tstart = [start[1], SIZE - 1 - start[0]]\n\t\tend = [end[1], SIZE - 1 - end[0]]\n\t\tspear = [spear[1], SIZE - 1 - spear[0]]\n\t\t### encode movement ###\n\t\tstart_str = chr(start[0] + 97) + str(start[1] + 1)\n\t\tend_str = chr(end[0] + 97) + str(end[1] + 1)\n\t\tspear_str = chr(spear[0] + 97) + str(spear[1] + 1)\n\t\tmove = start_str + '-' + end_str + '(' + spear_str + ')'\n\t\tresult = self.check_legal_move(move)\n\t\tif result:\n\t\t\treturn True, move\n\t\treturn False, None\n\t\t\n\tdef play(self, img=None, software=False):\n\t\t\"\"\"\n\t\t:param: IMG: Use the img instead of camera capturing if it is not none.\n\t\t:param: SOFTWARE: Manually input the movement iff true.\n\t\t\"\"\"\n\t\tif software:\n\t\t\tmove = input('Pure PC mode:')\n\t\t\tif self.check_legal_move(move): return self.update_board(move)\n\t\t\telse:\n\t\t\t\tprint('illegal input, retrying')\n\t\t\t\treturn self.play(img, software)\n\t\tif img is None:\n\t\t\timg = self.get_img()\n\t\t\t\n\t\tboard = self.parse_img(img)\n\t\tlegal, move = self.parse_board(board)\n\t\tif not legal:\n\t\t\tplt.subplot(1, 2, 1)\n\t\t\tplt.imshow(self.board)\n\t\t\tplt.subplot(1, 2, 2)\n\t\t\tplt.imshow(board)\n\t\t\tplt.show()\n\t\t\tcmd = input('how to deal with it: (manual / retry)')\n\t\t\tif cmd == 'retry': \n\t\t\t\timg = self.get_img()\n\t\t\t\treturn self.play(img, software)\n\t\t\telif cmd == 'manual':\n\t\t\t\tmove = input('type your movement here:')\n\t\t\t\tif self.check_legal_move(move): return self.update_board(move)\n\t\t\t\telse:\n\t\t\t\t\timg = self.get_img()\n\t\t\t\t\tprint('illegal input, retrying')\n\t\t\t\t\treturn self.play(img, software)\n\t\t\telif cmd == 'quit': exit(0)\n\t\t\telse:\n\t\t\t\tprint('illegal input, retrying')\n\t\t\t\timg = self.get_img()\n\t\t\t\treturn self.play(img, software)\n\t\treturn self.update_board(move)\n\t\t \n ### Adapted from Java program, these are lower level functions ###\t\t\n\tdef parse_string(self, string):\n\t\tx = ord(string[0]) - ord('a')\n\t\ty = int(string[1:]) - 1\n\t\treturn x, y\n\t\t\t\n\tdef isUnblockedMove(self, start, end, asempty=None):\n\t\tcolor = 0\n\t\tif asempty:\n\t\t\tcolor = self.board[SIZE - 1 - asempty[1]][asempty[0]]\n\t\t\tself.board[SIZE - 1 - asempty[1]][asempty[0]] = 0\n\t\tresult = self.isLegal(start, end)\n\t\tif asempty:\n\t\t\tself.board[SIZE - 1 - asempty[1]][asempty[0]] = color\n\t\treturn result\n\t\t\n\tdef isLegal(self, start, end):\n\t\t\"\"\"\n\t\tCheck if routes from start to end is unblocked.\n\t\t\"\"\"\n\t\tdirections = [\n\t\t [0, 1], [1, 1], [1, 0], [1, -1],\n\t\t [0, -1], [-1, -1], [-1, 0], [-1, 1]\n\t\t] # [dx, dy]\n\t\tdx, dy = [e - s for e, s in zip(end, start)]\n\t\tdx = dx / abs(dx) if dx != 0 else 0\n\t\tdy = dy / abs(dy) if dy != 0 else 0\n\t\tdir = -1\n\t\tfor i in range(8):\n\t\t\tif [dx, dy] == directions[i]: \n\t\t\t\tdir = i\n\t\t\t\tbreak\n\t\tif dir == -1 or self.check_beset(start) is False:\n\t\t\treturn False\n\t\tcolor = self.board[SIZE - 1 - start[1]][start[0]]\n\t\tminx, maxx = min(start[0], end[0]), max(start[0], end[0])\n\t\tminy, maxy = min(start[1], end[1]), max(start[1], end[1])\n\t\tself.board[SIZE - 1 - start[1]][start[0]] = 0 #temporally set it empty\n\t\tresult = True\n\t\tif dir % 4 == 0:\n\t\t\tfor i in range(miny, maxy + 1):\n\t\t\t\tif self.board[SIZE - 1 - i][minx] != 0:\n\t\t\t\t\tresult = False\n\t\telif dir % 4 == 2:\n\t\t\tfor i in range(minx, maxx + 1):\n\t\t\t\tif self.board[SIZE - 1 - miny][i] != 0:\n\t\t\t\t\tresult = False\n\t\telif dir % 4 == 1:\n\t\t\tfor i, j in zip(range(minx, maxx + 1), range(miny, maxy + 1)):\n\t\t\t\tif self.board[SIZE - 1 - j][i] != 0:\n\t\t\t\t\tresult = False\n\t\telif dir % 4 == 3:\n\t\t\tfor i, j in zip(range(minx, maxx + 1), \n\t\t\t reversed(range(miny, maxy + 1))):\n\t\t\t\tif self.board[SIZE - 1 - j][i] != 0:\n\t\t\t\t\tresult = False\n\t\tself.board[SIZE - 1 - start[1]][start[0]] = color\n\t\treturn result\n\t\t\n\t\n\tdef check_beset(self, pos):\n\t\t\"\"\"\n\t\tCheck if POS is surrounded by solid cells.\n\t\t\"\"\"\n\t\tx, y = pos\n\t\tnum = 0\n\t\tblocks = 0\n\t\tfor i in range(max(0, x-1), min(SIZE, x+2)):\n\t\t\tfor j in range(max(0, y-1), min(SIZE, y+2)):\n\t\t\t\tif i == x and j == y: continue\n\t\t\t\tnum += 1\n\t\t\t\tif self.board[SIZE - 1 - j][i] != 0:\n\t\t\t\t\tblocks += 1\n\t\tif blocks == num: return False\n\t\treturn True\n\ndef test(cam): # Just for testing, don't mind.\n\t# test 1: pass\n\t#img = cv2.imread('../python_vision/2/frames_2.jpg')\n\t#board = cam.parse_img(img)\n\t#plt.subplot(1, 2, 1)\n\t#plt.imshow(cam.board)\n\t#plt.subplot(1, 2, 2)\n\t#plt.imshow(board)\n\t#plt.show()\n\t# test 2:\n\timg = cv2.imread('../python_vision/2/frames_3.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=1)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_4.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=2)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_5.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=1)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_6.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=2)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_7.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=1)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_8.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=2)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_9.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=1)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_10.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=2)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_11.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=1)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\timg = cv2.imread('../python_vision/2/frames_12.jpg')\n\tboard = cam.parse_img(img)\n\tlegal, move = cam.parse_board(board, me=2)\n\tprint(legal, move)\n\tplt.subplot(1, 2, 1)\n\tplt.imshow(cam.board)\n\tplt.subplot(1, 2, 2)\n\tplt.imshow(board)\n\tplt.show()\n\tcam.update_board(move)\n\nif __name__ == '__main__':\n\tvision_params = {\n\t 'ddw': 0,\n\t 'ddh': 0,\n\t 'bins': 16,\n\t 'hough_vote': 15,\n\t 'vectors': None # this must be changed\n\t}\n\tcam = CameraPlayer(vision_params, '0.0.0.0', (170, 224, 392, 461))\n\ttest(cam)\n\t\n","sub_path":"amazons/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":12453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"60464023","text":"#!/usr/bin/env python\nfrom bs4 import BeautifulSoup\nimport urllib2\nimport csv\nimport json\n\ndef load_json(file):\n with open(file) as data_file:\n data = json.load(data_file)\n return data\n\ndef hit_wiki():\n pres_dict = load_json('../data/presidents.json')\n failures = []\n for p in pres_dict:\n p = clean_pres(p)\n try:\n slug = p['president'].replace(' ', '_')\n url = 'http://en.wikipedia.org/wiki/'+slug\n usock = urllib2.urlopen(url)\n html_data = usock.read()\n usock.close()\n soup = BeautifulSoup(html_data)\n images = soup.find(\"table\", class_=\"infobox vcard\").find_all('img')\n p['image'] = images[0].get('src').replace('//', '')\n except:\n failures.append(p['president'])\n\n dump_to_json(pres_dict)\n\ndef clean_pres(p):\n if p[\"president\"] == \"George Bush\":\n p[\"president\"] = \"George H. W. Bush\"\n return p\n\ndef dump_to_json(data_dict):\n with open('../data/presidents_img.json', 'w') as outfile:\n json.dump(data_dict, outfile)\n\nhit_wiki()\n","sub_path":"python/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"609881541","text":"import torch\nfrom typing import List, Tuple, Optional\nfrom .adam import Adam\n\ndef get_group_params(\n named_parameters: List[Tuple[str, torch.nn.Parameter]],\n weight_decay: float,\n no_decay: Optional[List[str]] = None\n):\n \"\"\"\n package the parameters in 2 groups for proper weight decay\n :param named_parameters: named parameters list\n :param weight_decay: weight decay to use\n :param no_decay: list of parameter with no decay\n :return:\n \"\"\"\n optimizer_grouped_parameters = [\n dict(\n params=[p for n, p in named_parameters if not any(nd in n for nd in no_decay)],\n weight_decay=weight_decay\n ), dict(\n params=[p for n, p in named_parameters if any(nd in n for nd in no_decay)],\n weight_decay=0.\n )\n ]\n return optimizer_grouped_parameters\n\ndef get_optimizer(**kwargs) -> torch.optim.Optimizer:\n method = kwargs.get(\"method\")\n params = kwargs.get(\"params\")\n\n if method == \"sgd\":\n optim_cls = torch.optim.sgd.SGD\n optim_params = dict(\n params=params,\n lr=kwargs.get(\"lr\", 0.001)\n )\n elif method == \"rmsprop\":\n optim_cls = torch.optim.rmsprop.RMSprop\n optim_params = dict(\n params=params,\n lr=kwargs.get(\"lr\", 0.001),\n momentum=kwargs.get(\"momentum\", 0.)\n )\n elif method == \"adam\":\n optim_cls = Adam\n optim_params = dict(\n params=params,\n lr=kwargs.get(\"lr\", 0.001),\n )\n else:\n raise NotImplementedError(f\"method {method} not implemented yet\")\n\n return optim_cls(**optim_params)","sub_path":"src/utils/optim/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"313345563","text":"\"\"\"Implementation of Pollsters for ebay.\"\"\"\n__author__ = 'mizeng'\n\nfrom ceilometer.compute import plugin\nfrom ceilometer.compute.pollsters import util\nfrom ceilometer_ebay.compute.virt import inspector as virt_inspector\nfrom ceilometer.openstack.common.gettextutils import _ # noqa\nfrom ceilometer.openstack.common import log\nfrom ceilometer import sample\n\nLOG = log.getLogger(__name__)\n\n\nclass CPUPollster(plugin.ComputePollster):\n\n def get_samples(self, manager, cache, resources):\n for instance in resources:\n LOG.info(_('checking instance %s'), instance.id)\n try:\n cpu_info = manager.inspector.inspect_cpus(instance.id)\n LOG.info(_(\"CPUTIME USAGE: %(instance)s %(time)d\"),\n {'instance': instance.__dict__,\n 'time': cpu_info.time})\n cpu_num = {'cpu_number': cpu_info.number}\n yield util.make_sample_from_instance(\n instance,\n name='cpu',\n type=sample.TYPE_CUMULATIVE,\n unit='ns',\n volume=cpu_info.time,\n additional_metadata=cpu_num,\n )\n except virt_inspector.InstanceNotFoundException as err:\n # Instance was deleted while getting samples. Ignore it.\n LOG.debug(_('Exception while getting samples %s'), err)\n except NotImplementedError:\n # Selected inspector does not implement this pollster.\n LOG.debug(_('Obtaining CPU time is not implemented for %s'\n ), manager.inspector.__class__.__name__)\n except Exception as err:\n LOG.error(_('could not get CPU time for %(id)s: %(e)s') % (\n {'id': instance.id, 'e': err}))\n LOG.exception(err)\n\n\nclass CPUUtilPollster(plugin.ComputePollster):\n\n def get_samples(self, manager, cache, resources):\n self._inspection_duration = self._record_poll_time()\n for instance in resources:\n LOG.debug(_('Checking CPU util for instance %s'), instance.id)\n try:\n cpu_info = manager.inspector.inspect_cpu_util(\n instance, self._inspection_duration)\n LOG.debug(_(\"CPU UTIL: %(instance)s %(util)d\"),\n ({'instance': instance.__dict__,\n 'util': cpu_info.util}))\n yield util.make_sample_from_instance(\n instance,\n name='cpu_util',\n type=sample.TYPE_GAUGE,\n unit='%',\n volume=cpu_info.util,\n )\n except virt_inspector.InstanceNotFoundException as err:\n # Instance was deleted while getting samples. Ignore it.\n LOG.debug(_('Exception while getting samples %s'), err)\n except NotImplementedError:\n # Selected inspector does not implement this pollster.\n LOG.debug(_('Obtaining CPU Util is not implemented for %s'\n ), manager.inspector.__class__.__name__)\n except Exception as err:\n LOG.error(_('Could not get CPU Util for %(id)s: %(e)s'), (\n {'id': instance.id, 'e': err}))\n","sub_path":"ceilometer_ebay/compute/pollsters/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"177205194","text":"# -*- coding: utf-8 -*-\n\nfrom nose.tools import raises\n\nfrom rod.parser import ParserConf as conf\nfrom rod.exception import ParserConfFileNotFound\n\n\ndef test_parser_conf_init():\n conf()\n\n assert conf._ParserConf__conf_instance is not None\n assert conf.get('xpath.maintenance_msg') is not None\n\n cf = conf.get_config()\n assert cf.get('xpath', 'maintenance_msg') is not None\n\n\n\"\"\"\nDefault config file is conf/parser.ini\n\"\"\"\ndef test_parser_conf_no_conf_file():\n\n conf('conf/parser.ini')\n assert conf._ParserConf__conf_instance is not None\n\n\n\"\"\"\nWhen invalid file path is given,\nParserConf raises ParserConfFileNotFound exception.\n\"\"\"\n@raises(ParserConfFileNotFound)\ndef test_parser_conf_no_conf_file():\n conf('')\n","sub_path":"tests/test_parser_conf.py","file_name":"test_parser_conf.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"513934309","text":"# !/usr/bin/env python\nimport sys\nsys.path.append(\"/Users/bdaudert/EE/nasa-roses-datastore\")\n\nimport logging\nimport json\nimport urllib2\nimport hashlib\nfrom datetime import datetime\n\nimport ee\n# Needed to add data to datastore from outside app engine\nfrom google.cloud import datastore\n\n\nimport config\nimport Utils\n\n# Set logging level\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef populate_datastore(region, ds, et_model, compute=True):\n yr_range = config.statics['all_years'][ds]\n for yr in range(int(yr_range[0]), int(yr_range[1])):\n year = str(yr)\n msg = 'PROCESSING Region/Year/Dataset/Model ' + region + '/' + year + '/' + ds + '/' + et_model\n logging.info(msg)\n ET_helper = ET_Util(region, year, ds, et_model)\n data_entities, meta_entities = ET_helper.get_data_and_set_db_entities(compute=compute)\n ET_helper.add_to_db(data_entities)\n ET_helper.add_to_db(meta_entities)\n\n\nclass ET_Util(object):\n '''\n Computes ET statistics for all temporal resolutions\n Args:\n :region Unique ID of geojson obbject, e.g. USFields\n :geoFName geojson file name\n :year year of geojson dataset, might be ALL if not USFields\n USField geojsons change every year\n :dataset MODSI, Landsat or gridMET\n :et_model Evapotranspiration modfel, e.g. SIMS, SSEBop, METRIC\n '''\n def __init__(self, region, year, dataset, et_model):\n self.region = region\n self.year = year\n if self.region in ['Mason', 'US_fields']:\n self.geoFName = region + '_' + year + '_GEOM.geojson'\n else:\n self.geoFName = region + '_GEOM.geojson'\n self.dataset = dataset\n self.et_model = et_model\n self.missing_value = -9999\n self.geo_bucket_url = config.GEO_BUCKET_URL\n self.data_bucket_url = config.DATA_BUCKET_URL\n # Needed to add data to datastore from outside app engine\n self.client = datastore.Client(config.PROJECT_ID)\n\n def read_data_from_bucket(self, fl_path):\n contents = json.load(urllib2.urlopen(fl_path))\n return contents\n\n def get_collection(self, t_res):\n '''\n Gets the ee collection (by name)\n :param dataset: MODIS or LANDSAT\n :param model: et model: SSEBop, SIMS, METRIC etc\n :return: ee.ImageCollection\n '''\n ds = self.dataset\n m = self.et_model\n coll_name = config.statics['ee_coll_name'][ds][m][t_res]\n logging.info('EE CALL: ee.ImageCollection({})'.format(coll_name))\n coll = ee.ImageCollection(coll_name)\n return coll\n\n def filter_coll_by_dates(self, coll, dS_str, dE_str):\n '''\n Gets the ee collection (by nameand tem_res)\n and filters by variable and start/end dates\n\n :param coll ee.ImageCollection\n :param variable:\n \"et\": \"Actual ET\",\n \"etrf\": \"Fractional ET\",\n \"etr\": \"Reference ET\",\n \"pr\": \"Precipitation\"\n :param dS_str start date, format yyyy-mm-dd\n :param dE_str end date, format yyyy-mm-dd\n :return: ee.ImageCollection filtered by variable and dates\n '''\n dS_obj = ee.Date(dS_str, 'GMT')\n dE_obj = ee.Date(dE_str, 'GMT')\n # logging.debug('EE CALL: collection.filterDate({}, {})'\n # .format(dS_str, dE_str))\n f_coll = coll.map(lambda x: x.double())\\\n .filterDate(dS_obj, dE_obj.advance(1, 'day'))\n return f_coll\n\n def filter_coll_by_var(self, coll, variable):\n '''\n Gets the ee collection (by nameand tem_res)\n and filters by variable and start/end dates\n\n :param coll ee.ImageCollection\n :param variable:\n \"et\": \"Actual ET\",\n \"etrf\": \"Fractional ET\",\n \"etr\": \"Reference ET\",\n \"pr\": \"Precipitation\"\n :return: ee.ImageCollection filtered by variable\n '''\n # logging.debug('EE CALL: collection.select({})'.format(variable))\n return coll.select([variable], [variable])\n\n def reduce_collection_to_img(self, coll, stat):\n '''\n Reduces the ee.ImageCollection to a single ee image by applying\n the statistic stat\n\n :param coll ee.ImageCollection\n :param stat statistic: max, min, mean, median\n :return: ee.Image\n '''\n\n if stat == 'Median':\n img = coll.median()\n elif stat == 'Mean':\n img = coll.mean()\n elif stat == 'Max':\n img = coll.max()\n elif stat == 'Min':\n img = coll.min()\n elif stat == 'Total':\n img = coll.sum()\n else:\n img = coll.mean()\n return img\n\n def set_meta_properties(self, geo_props, geom):\n '''\n Populates metadata from the geo properties\n Defined in the geojson data file\n '''\n props = {}\n for prop in config.statics['geo_meta_cols'][self.region]:\n if prop in geo_props.keys():\n props[prop] = geo_props[prop]\n return props\n\n def compute_et_stats(self, coll, var, geom):\n '''\n Computes annual, seasonal (April - Sept) and monthly et stats\n :param coll:\n :param var:\n :param geom:\n :return:\n '''\n def average_over_region(img):\n '''\n Averages the ee.Image over all pixels of ee.Geometry\n '''\n reduced_image_data = img.reduceRegion(\n ee.Reducer.mean(),\n geometry=geom,\n scale=1000,\n tileScale=1,\n crs='EPSG:4326',\n crsTransform=None,\n bestEffort=True\n )\n return ee.Feature(None, reduced_image_data)\n\n etdata = {}\n imgs = []\n for res in config.statics['start_end_mon_days_by_res'].keys():\n # logging.info('PROCESSING STATISTIC ' + res)\n # Filer collection by date\n dS_str = str(self.year) + '-' +\\\n config.statics['start_end_mon_days_by_res'][res][0]\n dE_str = str(self.year) + '-' +\\\n config.statics['start_end_mon_days_by_res'][res][1]\n coll_t = self.filter_coll_by_dates(coll, dS_str, dE_str)\n temporal_stat = config.statics['t_stat_by_var'][var]\n img = self.reduce_collection_to_img(coll_t, temporal_stat)\n # feats = ee.FeatureCollection(average_over_region(img))\n imgs.append(img)\n ee_imgs = ee.ImageCollection(imgs)\n feats = ee.FeatureCollection(ee_imgs.map(average_over_region))\n\n try:\n f_data = feats.getInfo()\n except Exception as e:\n f_data = {'features': []}\n logging.error(e)\n\n for res_idx, res in enumerate(config.statics['start_end_mon_days_by_res'].keys()):\n if 'features' not in f_data.keys() or not f_data['features']:\n etdata['data_' + res] = -9999\n continue\n try:\n feat = f_data['features'][res_idx]\n except:\n etdata['data_' + res] = -9999\n continue\n\n if 'properties' not in feat.keys():\n etdata['data_' + res] = -9999\n continue\n try:\n val = feat['properties'][var + '_' + res]\n etdata['data_' + res] = round(val, 4)\n except:\n etdata['data_' + res] = -9999\n continue\n return etdata\n\n def set_db_data_entity(self, UNIQUE_ID, feat_idx, etdata, var):\n '''\n sets up datastore client and datastore entity belonging to DATA\n Args:\n UNIQUE_ID,: unique identity of the feature, used to define the db key\n f_idx: feature index, need this to query for multiple features\n etdata: dictionary of etdata\n Returns:\n datstore entitity\n '''\n # Instantiates a client and the datastore kind DATA\n db_key = self.client.key('DATA', UNIQUE_ID,)\n entity = datastore.Entity(key=db_key)\n entity.update({\n 'feat_idx': feat_idx,\n 'region': self.region,\n 'year': int(self.year),\n 'dataset': self.dataset,\n 'et_model': self.et_model,\n 'variable': var\n })\n # Set the etdata\n for key, val in etdata.iteritems():\n entity.update({\n key: val\n })\n return entity\n\n def set_db_metadata_entity(self, UNIQUE_ID, feat_idx, meta_props):\n '''\n sets up datastore client and datastore entity belonging to METADATA\n Args:\n UNIQUE_ID,: unique identity of the feature, used to define the db key\n f_idx: feature index, need this to query for multiple features\n etdata: dictionary of etdata\n Returns:\n datstore entitity\n '''\n # Instantiates a client and the datastore kind DATA\n\n db_key = self.client.key('METADATA', UNIQUE_ID, )\n entity = datastore.Entity(key=db_key)\n entity.update({\n 'feat_idx': feat_idx,\n 'region': self.region,\n 'year': int(self.year)\n })\n # Set the metadata\n for key, val in meta_props.iteritems():\n entity.update({\n key: val\n })\n return entity\n\n\n def add_to_db(self, entity_list):\n '''\n Adds multiple data to datastore via the datastore client\n NOTES:\n can be run outside of app engine\n we can only add 500 entries to bd at a time\n '''\n ent_len = len(entity_list)\n num_chunks = ent_len / 500\n if ent_len % 500 != 0:\n end_chunk_len = ent_len % 500\n num_chunks += 1\n num_added = 0\n count = 0\n while num_added < ent_len:\n count +=1\n logging.info('ADDING CHUNK {0} of {1}'.format(str(count), str(num_chunks)))\n start = num_added\n end = start + 500\n if end > ent_len:\n end = start + end_chunk_len\n ents_to_add = entity_list[start:end]\n self.client.put_multi(ents_to_add)\n num_added = end\n\n def get_data_and_set_db_entities(self, compute=True):\n '''\n Gets geo features from geojson file\n and computes the et stats for all variables\n and temporal resolutions\n\n if compute is True, we compute the et stats in EE\n if compute is False, we read the et data from a local\n data file (et data was provided in the data file)\n '''\n # FIX ME: add more vars as data comes online\n # MODIS SSEBop only has et right now\n t_res_list = config.statics['all_t_res']\n var_list = ['et']\n # Read the geo data from the bucket\n fl_path = self.geo_bucket_url + self.geoFName\n geo_data = self.read_data_from_bucket(fl_path)\n if 'features' not in geo_data.keys():\n logging.error('NO DATA FOUND IN BUCKET, FILE: ' + self.geoFName)\n\n data_entities = []\n meta_entities = []\n if not compute:\n # Get the etdata from the local file\n fl_name = self.region + '_' + self.year + '_DATA.json'\n fl_path = self.data_bucket_url + self.et_model + '/' + fl_name\n j_data = self.read_data_from_bucket(fl_path)\n local_etdata = j_data['features']\n else:\n # Get the colllections so we don't have to do it for each feature\n colls = {}\n for t_res in t_res_list:\n coll = self.get_collection(t_res)\n for var in var_list:\n coll = self.filter_coll_by_var(coll, var)\n colls[t_res + '_' + var] = coll\n\n for f_idx, geo_feat in enumerate(geo_data['features']):\n feat_coords = geo_feat['geometry']['coordinates']\n if geo_feat['geometry']['type'] == 'MultiPolygon':\n geom_coords = Utils.orient_polygons_ccw(feat_coords)\n geom = ee.Geometry.MultiPolygon(geom_coords)\n elif geo_feat['geometry']['type'] == 'Polygon':\n geom_coords = [Utils.orient_polygon_ccw(c) for c in feat_coords]\n geom = ee.Geometry.Polygon(geom_coords)\n else:\n continue\n # Add metadata to METADATA Datastore entity\n meta_props = self.set_meta_properties(geo_feat['properties'], geo_feat['geometry'])\n unique_meta_str = ('-').join([self.region, self.year, str(f_idx)])\n UNIQUE_META_ID = hashlib.md5(unique_meta_str).hexdigest()\n meta_entities.append(self.set_db_metadata_entity(UNIQUE_META_ID, str(f_idx), meta_props))\n for var in var_list:\n unique_str = ('-').join([self.region, self.dataset, self.et_model, self.year, var, str(f_idx)])\n UNIQUE_ID = hashlib.md5(unique_str).hexdigest()\n if compute:\n etdata = self.compute_et_stats(coll, var, geom)\n else:\n etdata = {}\n for res in config.statics['start_end_mon_days_by_res'].keys():\n etdata_key = var + '_' + res\n new_key = 'data_' + res\n try:\n etdata[new_key] = local_etdata[f_idx]['properties'][etdata_key]\n except:\n etdata[new_key] = -9999\n data_entities.append(self.set_db_data_entity(UNIQUE_ID, f_idx, etdata, var))\n return data_entities, meta_entities\n\n###################################################\n# M A I N\n###################################################\nif __name__ == \"__main__\":\n startTime = datetime.now()\n print(startTime)\n for region in ['US_states_west_500k', 'US_counties_west_500k']:\n # for region in ['US_states_west_500k']:\n if region == 'Mason':\n # Compute ee stats in EE\n comp = True\n else:\n # use fake data on localhost\n comp = False\n for ds in ['MODIS']:\n for et_model in ['SSEBop']:\n populate_datastore(region, ds, et_model, compute=comp)\n print(datetime.now() - startTime)\n\n\n","sub_path":"mypython/standalone_populate_datastore.py","file_name":"standalone_populate_datastore.py","file_ext":"py","file_size_in_byte":14346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"540637458","text":"import socket,time,datetime,hashlib\r\n'''\r\nSocket is most important module for network binding\r\n'''\r\ns = socket.socket()#Creating a object\r\nprint(\"-------------------Dred-----------------------\")\r\nuserin = input(\"\\n1.New User\\n2.Existing User\\n3.Check History\\n4.Help\\nChoose \")\r\nif userin == \"4\": #For Help\r\n print(\"\\nWhat if you choose New User Option?\\nYou will redirected to a new fresh network between server and client.\\nBut if you choose option 2 then you will be able to access to history of data\\nIf you choose 1 then you will lost your history in you file.\")\r\n print(\"\\nThis works as a server connector to clients where client is strongly connected to server and transmiss data to server\")\r\n exit()\r\nif userin == \"3\": #For accesing history direct from command line.\r\n with open(\"LapyData.txt\",mode=\"r\") as read:\r\n ac = read.read()\r\n print(\"\\nHistory--\")\r\n read.close()\r\n exit()\r\nport = 6380 #Creating a Port\r\ns.bind(('', port))\r\n'''\r\ns.bind with any ip adrress and port of 6380\r\n'''\r\nprint(\"\\nBinded\")\r\ns.listen(5) #Waiting for 5 connections for connect\r\nprint(\"Connecting\")\r\nwhile True: #For New Messages and Connection\r\n c,addr = s.accept()\r\n print(\"\\nGot Connection\",addr,datetime.datetime.now())\r\n if userin == \"2\":\r\n History = ()\r\n with open(\"LapyData.txt\",mode = \"r\") as f: #For Returning One..\r\n f.read()\r\n f.close()\r\n ap = \"Server - Thanks For Connecting\"\r\n c.send(ap.encode())\r\n recieve = str(c.recv(1024))\r\n print(recieve,\"\\n\")\r\n while True:\r\n recieve2 = str(c.recv(1024))\r\n with open(\"LapyData.txt\" ,mode=\"a\") as file:\r\n file.write(\"\\n\"+recieve2+\" \"+str(datetime.datetime.now()))\r\n file.close()\r\n print(recieve2,datetime.datetime.now())\r\n if userin == \"1\":\r\n History = ()\r\n with open(\"LapyData.txt\", mode=\"w\") as f: # For New One One..\r\n f.write(str(History))\r\n f.close()\r\n ap = \"Server - Thanks For Connecting\"\r\n c.send(ap.encode())\r\n recieve = str(c.recv(1024))\r\n print(recieve, \"\\n\")\r\n while True:\r\n recieve2 = str(c.recv(1024))\r\n with open(\"LapyData.txt\", mode=\"a\") as file:\r\n file.write(\"\\n\" + recieve2+\" \"+str(datetime.datetime.now()))\r\n file.close()\r\n print(recieve2, datetime.datetime.now())\r\n c.close()","sub_path":"Client Server.py","file_name":"Client Server.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"609533640","text":"#!/usr/bin/env python3\n\nfrom lexed_to_parsed import *\nfrom lifted_to_rust import *\n\nimport sys\n\nfrom parsed_passes import BINOPS, UNIOPS\n\n\ndef flatten(root, exp, inputs, consts):\n\n def _flatten(exp):\n if type(exp[0]) is list:\n return _flatten(exp[1])\n if exp[0] in ['InputInterval', 'Interval']:\n l = _flatten(exp[1]).replace('[','').replace(']','')\n r = _flatten(exp[2]).replace('[','').replace(']','')\n return \"[{}, {}]\".format(l,r)\n if exp[0] in ['Float', 'Integer']:\n return \"[{}]\".format(exp[1])\n if exp[0] in ['Variable', 'Input']:\n tlist = [t for t in inputs if t[0] == exp[1]]\n if len(tlist) == 1:\n return tlist[0][1]\n else:\n return _flatten(lookup(exp[1]))\n if exp[0] == 'Const':\n return consts[int(exp[1])]\n if exp[0] == 'Return':\n return _flatten(exp[1])\n if exp[0] in ops:\n return \"({}{}{})\".format(_flatten(exp[1]), ops[exp[0]], _flatten(exp[2]))\n if exp[0] in funcs:\n return \"{}({})\".format(funcs[exp[0]], _flatten(exp[1]))\n if exp[0] == 'abs':\n return \"abs({})\".format(_flatten(exp[1]))\n if exp[0] == 'Neg':\n return \"-({})\".format(_flatten(exp[1]))\n if exp[0] == 'pow':\n return \"pow({},{})\".format(_flatten(exp[1]), _flatten(exp[2]))\n if exp[0] == \"ipow\":\n c = consts[int(exp[2][1])]\n return \"pow({},{})\".format(_flatten(exp[1]), c)\n if exp[0] == \"sqrt\":\n return\"sqrt({})\".format(_flatten(exp[1]))\n print(\"Error flattening '{}'\".format(exp))\n sys.exit(-1)\n\n def lookup(var):\n tmp = root\n while tmp[0] != 'Return':\n assign = tmp[0]\n new_var = assign[1][1]\n if new_var == var:\n return assign[2]\n tmp = tmp[1]\n print(\"Invalid lookup: {}\\nIn:{}\\n\".format(var, root))\n sys.exit(-1)\n\n return _flatten(exp)\n\n \n \n\ndef runmain():\n ''' Wrapper to allow constant lifter to run with direct\n command line input '''\n try:\n filename = sys.argv[1]\n with open(filename, 'r') as f:\n data = f.read()\n except IndexError:\n sys.stdout.write('Reading from standard input (type EOF to end):\\n')\n data = sys.stdin.read()\n\n exp = function_parser.parse(data)\n inputs = lift_inputs(exp)\n consts = lift_constants(exp, inputs)\n flattened = flatten(exp, exp, inputs, consts)\n\n print(\"flattened:\")\n print(flattened)\n print()\n print(\"expresions:\")\n while type(exp[0]) is list:\n print(exp[0])\n exp = exp[1]\n print(exp)\n print()\n print(\"inputs:\")\n for i in inputs:\n print(i)\n print()\n print(\"constants:\")\n for c in consts:\n print(c)\n\n# On call run as a util, taking in text and printing the constant lifted version\nif __name__ == \"__main__\":\n runmain()\n","sub_path":"src/frontend/function_transforms/parsed_flatten_pass.py","file_name":"parsed_flatten_pass.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"187802019","text":"# -*- coding: utf-8 -*-\n\n# Preparation for running locally:\n# pip install kaggle numpy pandas tensorflow transformers\n# mkdir -p ~/.kaggle\n# cp kaggle.json ~/.kaggle/\n# ls ~/.kaggle\n# chmod 600 /root/.kaggle/kaggle.json\n# kaggle competitions download -c nlp-getting-started -p input\n\nimport math\nimport os\nimport sys\nimport time\nimport numpy as np\nimport pandas as pd\nimport shutil\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"1\"\nimport tensorflow as tf\nfrom transformers import BertConfig, BertTokenizer, TFBertForSequenceClassification\n\nall = True\nbatch_size = 16\ntokens = 84\ntrain_ratio = .75\nval_ratio = .25\nmax_epochs = 80\nlearning_rate = 2e-5\n\nassert train_ratio + val_ratio <= 1\n\n\ndef read(fname, labeled):\n dtype = {\n \"id\": str,\n #\"keyword\": str,\n \"text\": str,\n #\"location\": str,\n }\n if labeled:\n dtype[\"target\"] = np.int32\n p = os.path.join(os.pardir, \"input\", fname)\n return pd.read_csv(p, dtype=dtype)\n\n\ndef bert_encode_text(df, tokenizer):\n d = tokenizer(text=list(df[\"text\"]),\n padding=\"max_length\",\n truncation=True,\n max_length=tokens,\n return_tensors=\"tf\",\n verbose=1)\n return {\n \"input_ids\": d.input_ids,\n \"attention_mask\": d.attention_mask,\n \"token_type_ids\": d.token_type_ids,\n }\n\n\ndef solve(model, timestamp, train_x, train_y, val_x, val_y, test_x):\n log_dir = os.path.join(os.pardir, \"logs\", timestamp)\n min_val_loss = math.inf\n epochs_with_worse_val_loss = 0\n epochs_since_braking = 0\n test_y = None\n\n def inspect(epoch, logs):\n loss = model.evaluate(train_x, train_y, verbose=0)[0]\n if logs is not None:\n print(f\"\\n\\tloss reported : {logs['loss']:.4f}\")\n print(f\"\\tloss evaluated: {loss:.4f}\")\n\n def settle_down(epoch, logs):\n nonlocal min_val_loss, epochs_with_worse_val_loss, epochs_since_braking, test_y\n val_loss = logs[\"val_loss\"]\n if min_val_loss >= val_loss:\n min_val_loss = val_loss\n epochs_with_worse_val_loss = 0\n if epoch >= 2:\n test_y = np.argmax(model.predict(test_x).logits, axis=1)\n else:\n epochs_with_worse_val_loss += 1\n if epochs_with_worse_val_loss > 2:\n model.stop_training = True\n\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.Adam(learning_rate,\n epsilon=learning_rate * 1e-03)\n model.compile(loss=loss, optimizer=optimizer)\n model.fit(\n x=train_x,\n y=train_y,\n epochs=max_epochs,\n batch_size=batch_size,\n callbacks=[\n tf.keras.callbacks.TensorBoard(log_dir=log_dir),\n #tf.keras.callbacks.LambdaCallback(on_epoch_end=inspect),\n tf.keras.callbacks.LambdaCallback(on_epoch_end=settle_down),\n ],\n validation_data=(val_x, val_y),\n verbose=1)\n return test_y\n\n\ndef main():\n timestamp = time.strftime(\"%Y%m%d-%H%M\")\n shutil.copyfile(sys.argv[0], timestamp + \".py\")\n\n labeled_df = read(\"train.csv\", labeled=True)\n test_df = read(\"test.csv\", labeled=False)\n\n train_size = int(len(labeled_df) * train_ratio)\n val_size = int(len(labeled_df) * val_ratio)\n if not all:\n train_size = 300\n val_size = 100\n test_df = test_df[:10]\n np.random.seed(int(19680516 * (train_ratio + val_ratio)))\n labeled_pick = np.random.permutation(labeled_df.index)\n train_df = labeled_df.iloc[labeled_pick[:train_size]]\n val_df = labeled_df.iloc[labeled_pick[train_size:train_size + val_size]]\n print(len(train_df), \"samples to train on, bincount\",\n np.bincount(train_df[\"target\"]))\n print(len(val_df), \"samples to validate, bincount\",\n np.bincount(val_df[\"target\"]))\n print(len(test_df), \"samples to test\")\n\n model_name = 'bert-base-multilingual-cased'\n tokenizer = BertTokenizer.from_pretrained(model_name)\n bert_config, unused_kwargs = BertConfig.from_pretrained(\n model_name,\n return_unused_kwargs=True,\n output_attentions=False,\n output_hidden_states=False,\n )\n assert not unused_kwargs, unused_kwargs\n train_x = bert_encode_text(train_df, tokenizer)\n val_x = bert_encode_text(val_df, tokenizer)\n test_x = bert_encode_text(test_df, tokenizer)\n train_y = train_df[\"target\"].to_numpy()\n val_y = val_df[\"target\"].to_numpy()\n\n strategy = tf.distribute.get_strategy()\n with strategy.scope():\n bert_inputs = [\n tf.keras.Input(name=name,\n shape=(tokens, ),\n dtype=tf.int32,\n ragged=True) for name in tokenizer.model_input_names\n ]\n assert bert_config.num_labels == 2\n bert_model = TFBertForSequenceClassification(config=bert_config)\n bert_output = bert_model(bert_inputs)\n model = tf.keras.Model(inputs=bert_inputs, outputs=[bert_output])\n model.summary()\n test_y = solve(model=model,\n timestamp=timestamp,\n train_x=train_x,\n train_y=train_y,\n val_x=val_x,\n val_y=val_y,\n test_x=test_x)\n\n submission = test_df[[\"id\"]].assign(target=test_y)\n submission.to_csv(\"submission.csv\", index=False)\n\n\nmain()\n","sub_path":"submission8.py","file_name":"submission8.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"272233284","text":"#!usr/bin/env python3\n #run this in any directory add -v for verbose \n#get Pillow (fork of PIL) from pip before running --> pip install Pillow\n\nimport os\nimport sys\nfrom PIL import Image\nimport shutil\n\n\nsave_path = \"d_C2/\"# change here accordingly\n\ndef compressMe(file, verbose=False):\n\tglobal save_path\n\tfilepath = os.path.join(sys.argv[1], file)\n\toldsize = os.stat(filepath).st_size\n\tprint(\"old:\",oldsize)\n\tpicture = Image.open(filepath)\n\tdim = picture.size\n\t\n\t#set quality= to the preferred quality. \n\t#I found that 85 has no difference in my 6-10mb files and that 65 is the lowest reasonable number\n\tpicture.save(save_path+file,\"JPEG\",optimize=True,quality= 85)\n\t\n\tnewsize = os.stat(save_path+file).st_size\n\t#print(\"new:\",newsize)\n\tpercent = (oldsize-newsize)/float(oldsize)*100\n\tif (verbose):\n\t\tprint(\"File compressed from {0} to {1} or {2}%\".format(oldsize,newsize,percent))\n\treturn percent\n\ndef main():\n\tverbose = False\n\t#checks for verbose flag\n\tif (len(sys.argv)>1):\n\t\tif (sys.argv[1].lower()==\"-v\"):\n\t\t\tverbose = True\n\n\tif not os.path.exists(save_path):\n\t\tos.mkdir(save_path)\n\ttot = 0\n\tnum = 0\n\t\n\tfor file in os.listdir(sys.argv[1]):\n\t\tif os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):\n\t\t\tnum += 1\n\t\t\tif os.stat(sys.argv[1]+'/'+file).st_size >2500000:#only compress image greater than 2.5mb\n\t\t\t\ttot += compressMe(file, verbose)\n\t\t\telse:\n\t\t\t\tshutil.copy(sys.argv[1]+'/'+file, save_path+file)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Project/Code/utils/image_compression.py","file_name":"image_compression.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"344241281","text":"import machine\nimport utime as time\n\nhall_sensor_a = machine.ADC(0) #ADC connector\nhall_sensor_d = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)\n\nnetworkpin = machine.Pin(2, machine.Pin.OUT)\nnetworkpin.off()\n\nwhile True:\n print('DBG: sensor D(): {}, '\n 'sensor A(): {} '\n 'at: {}'.format(hall_sensor_d.value(),\n hall_sensor_a.read(),\n time.time()))\n networkpin.off()\n time.sleep(0.1)\n if ((hall_sensor_d.value() == 0)or(hall_sensor_a.read() < 1024)):\n networkpin.on()\n\n","sub_path":"demo-app/demo-app-010/testing/syncholl01/sensortest.py","file_name":"sensortest.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"404159475","text":"# =============================================================================\n# Author: Shuo Zhou, szhou20@sheffield.ac.uk\n# Haiping Lu, h.lu@sheffield.ac.uk or hplu@ieee.org\n# =============================================================================\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef _none2dict(kwarg):\n if kwarg is None:\n return {}\n else:\n return kwarg\n\n\ndef plot_weights(\n weight_img, background_img=None, color_marker_pos=\"rs\", color_marker_neg=\"gs\", im_kwargs=None, marker_kwargs=None\n):\n \"\"\"Visualize model weights\n\n Args:\n weight_img (array-like): Model weight/coefficients in 2D, could be a 2D slice of a 3D or higher order tensor.\n background_img (array-like, optional): 2D background image. Defaults to None.\n color_marker_pos (str, optional): Color and marker for weights in positive values. Defaults to red \"rs\".\n color_marker_neg (str, optional): Color and marker for weights in negative values. Defaults to blue \"gs\".\n im_kwargs (dict, optional): Key word arguments for background images. Defaults to None.\n marker_kwargs (dict, optional): Key word arguments for background images. Defaults to None.\n\n Returns:\n [matplotlib.figure.Figure]: Figure to plot.\n \"\"\"\n if type(weight_img) != np.ndarray:\n weight_img = np.array(weight_img)\n if len(weight_img.shape) != 2:\n raise ValueError(\n \"weight_img is expected to be a 2D matrix, but got an array in shape %s\" % str(weight_img.shape)\n )\n im_kwargs = _none2dict(im_kwargs)\n marker_kwargs = _none2dict(marker_kwargs)\n fig = plt.figure()\n ax = fig.add_subplot()\n if background_img is not None:\n ax.imshow(background_img, **im_kwargs)\n weight_img[np.where(background_img == 0)] = 0\n\n weight_pos_coords = np.where(weight_img > 0)\n weight_neg_coords = np.where(weight_img < 0)\n\n ax.plot(weight_pos_coords[1], weight_pos_coords[0], color_marker_pos, **marker_kwargs)\n ax.plot(weight_neg_coords[1], weight_neg_coords[0], color_marker_neg, **marker_kwargs)\n\n return fig\n\n\ndef plot_multi_images(images, n_cols=10, n_rows=None, marker_locs=None, im_kwargs=None, marker_kwargs=None):\n \"\"\"Plot multiple images with markers in one figure.\n\n Args:\n images (array-like): Images to plot, shape(n_samples, dim1, dim2)\n n_cols (int, optional): Number of columns for plotting multiple images. Defaults to 10.\n n_rows (int, optional): Number of rows for plotting multiple images. If None, n_rows = n_samples / n_cols.\n marker_locs (array-like, optional): Locations of markers, shape (n_samples, 2 * n_markers). Defaults to None.\n im_kwargs (dict, optional): Key word arguments for plotting images. Defaults to None.\n marker_kwargs (dict, optional): Key word arguments for background images. Defaults to None.\n\n Returns:\n [matplotlib.figure.Figure]: Figure to plot.\n \"\"\"\n if n_rows is None:\n n_rows = int(images.shape[0] / n_cols) + 1\n im_kwargs = _none2dict(im_kwargs)\n marker_kwargs = _none2dict(marker_kwargs)\n fig = plt.figure(figsize=(20, 36))\n\n for i in range(images.shape[0]):\n fig.add_subplot(n_rows, n_cols, i + 1)\n plt.axis(\"off\")\n plt.imshow(images[i, ...], **im_kwargs)\n if marker_locs is not None:\n coords = marker_locs[i, :].reshape((-1, 2))\n n_landmark = coords.shape[0]\n for j in range(n_landmark):\n ix = coords[j, 0]\n iy = coords[j, 1]\n plt.plot(ix, iy, **marker_kwargs)\n plt.title(i + 1)\n\n return fig\n","sub_path":"kale/interpret/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"181879283","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow.python.framework import ops\n\ndef binaryRound(x):\n \"\"\"\n Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1},\n using the straight through estimator for the gradient.\n ref: https://r2rt.com/binary-stochastic-neurons-in-tensorflow.html\n \"\"\"\n g = tf.get_default_graph()\n\n with ops.name_scope(\"BinaryRound\") as name:\n with g.gradient_override_map({\"Round\": \"Identity\"}):\n return tf.round(x, name=name)\n\n#As per Xaiver init, this should be 2/n(input), though many different initializations can be tried. \ndef init_weights(shape,stddev=.1):\n \"\"\" Weight initialization \"\"\"\n weights = tf.random_normal(shape, stddev=stddev)\n return tf.Variable(weights)\n\ndef init_bias(shape, stddev=.1):\n \"\"\" Bias initialization \"\"\"\n biases = tf.random_normal([shape], stddev=stddev)\n return tf.Variable(biases)\n\ndef save_weights(weights,biases,output_folder,weight_name_save,num_layers):\n for i in range(0, num_layers+1):\n weight_i = weights[i].eval()\n np.savetxt(output_folder+weight_name_save+\"/w_\"+str(i)+\".txt\",weight_i,delimiter=',')\n bias_i = biases[i].eval()\n np.savetxt(output_folder+weight_name_save+\"/b_\"+str(i)+\".txt\",bias_i,delimiter=',')\n return\n\ndef load_weights(output_folder,weight_load_name,num_layers):\n weights = []\n biases = []\n for i in range(0, num_layers+1):\n weight_i = np.loadtxt(output_folder+weight_load_name+\"/w_\"+str(i)+\".txt\",delimiter=',')\n w_i = tf.Variable(weight_i,dtype=tf.float32)\n weights.append(w_i)\n bias_i = np.loadtxt(output_folder+weight_load_name+\"/b_\"+str(i)+\".txt\",delimiter=',')\n b_i = tf.Variable(bias_i,dtype=tf.float32)\n biases.append(b_i)\n return weights , biases\n\ndef forwardprop(X, weights, biases, num_layers,):\n for i in range(0, num_layers):\n if i ==0:\n htemp = tf.nn.sigmoid(tf.add(tf.matmul(X, weights[i]), biases[i]))\n else:\n htemp = tf.nn.sigmoid(tf.add(tf.matmul(htemp, weights[i]), biases[i]))\n yval = tf.add(tf.matmul(htemp, weights[-1]), biases[-1])\n return yval","sub_path":"FCNN_1THz/dbr_core.py","file_name":"dbr_core.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"625411246","text":"from importlib import import_module\n\nfrom db.session import session\n\nadditional_value_type = {\n \"book\": (\"Author\", \"authors\"),\n \"author\": (\"Book\", \"books\")\n}\n\n\ndef get_cls(package, cls):\n return getattr(import_module(package), cls)\n\n\ndef prepare_search_response(query_type, objects):\n \"\"\"Serializing function for objects set based on\n query type ( in this app there's only 2 query\n types - book and author) for search requests.\n\n :param query_type:\n request query type : book or author\n :param objects:\n requested type objects\n\n \"\"\"\n return {\n \"results\": [{\n \"id\": obj.id,\n \"name\": obj.name,\n additional_value_type.get(query_type)[1]: [{\n \"id\": a_obj.id,\n \"name\": a_obj.name\n } for a_obj in getattr(obj, additional_value_type.get(query_type)[1])]\n } for obj in objects]\n }\n\n\ndef prepare_view_response(query_type, object_):\n \"\"\"Serializing function for object based on query type\n\n :param query_type:\n request query type : book or author\n :param object_:\n request object\n\n \"\"\"\n if not object_:\n return {\n \"type\": query_type,\n \"name\": \"\",\n \"id\": \"\",\n additional_value_type.get(query_type)[1]: []\n }\n return {\n \"type\": query_type,\n \"id\": object_.id,\n \"name\": object_.name,\n additional_value_type.get(query_type)[1]: [{\n \"id\": a_obj.id,\n \"name\": a_obj.name\n } for a_obj in getattr(object_, additional_value_type.get(query_type)[1])]\n }\n\n\ndef get_additional_objects_set(cls, data):\n \"\"\"Prepopulates additional objects set for create/update\n requests.\n\n :param cls:\n Objects class to be prepopulated\n :param data:\n Request data. Contains list of deserialized objects.\n Every object contains id ( may be empty, in this case\n new object must be created ) and name.\n \"\"\"\n db_session = session()\n existing_objects_ids = [obj.get(\"id\") for obj\n in filter(lambda x: \"id\" in x.keys(), data)]\n existing_objects_set = db_session.query(cls).\\\n filter(cls.id.in_(existing_objects_ids)).\\\n all()\n new_objects_set = [cls(obj.get(\"name\")) for obj\n in filter(lambda x: \"id\" not in x.keys(), data)]\n return existing_objects_set + new_objects_set\n\n\ndef save_object(data):\n \"\"\"Saves object for create/update request.\n\n :param data:\n Request data. Contains :\n - id : May be empty ( in this case new object\n must be created )\n -name : Object name attr\n -extra : Deserialized related objects set\n -type : Object type\n\n \"\"\"\n db_session = session()\n object_cls = get_cls(\"db.models\", data.get(\"type\").capitalize())\n additional_object_cls = get_cls(\n \"db.models\", additional_value_type.get(data.get(\"type\"))[0]\n )\n object_id = data.get(\"id\", None)\n if object_id:\n object_ = db_session.query(object_cls).\\\n filter(object_cls.id == object_id).\\\n one()\n object_.name = data.get(\"name\")\n else:\n object_ = object_cls(data.get(\"name\"))\n setattr(\n object_,\n additional_value_type.get(data.get(\"type\"))[1],\n get_additional_objects_set(\n additional_object_cls, data.get(\"additionalObjects\")\n )\n )\n db_session.add(object_)\n db_session.commit()\n return {\"type\": data.get(\"type\"), \"id\": object_.id}","sub_path":"library/extensions/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"632243768","text":"import sentencepiece as spm\nimport numpy as np\nimport os\nimport pickle\nimport fasttext\nimport argparse\ndef train_sentencepiece_model(path_to_text_data,vocab_size,model_name='model_sentencepiece'):\n \n spm.SentencePieceTrainer.Train('--input='+str(path_to_text_data)+' --model_prefix='+str(model_name)+' --vocab_size='+str(vocab_size))\n# spm.SentencePieceTrainer.Train('--input=/home/sriharshkamma/final/BERT-pytorch/data/version1_test_corpus.small --model_prefix='+str(model_name)+' --vocab_size=10000')\n \ndef create_vocab_file(sentence_piece_model_path,directory_path,vocab_file_name):\n sp=spm.SentencePieceProcessor()\n sp.load(sentence_piece_model_path)\n vocab_sentence_piece=[]\n for i in range(sp.get_piece_size()):\n vocab_sentence_piece.append(sp.id_to_piece(i))\n print(directory_path+'/temp.small')\n with open(directory_path+'/temp.small','w') as f:\n for i in vocab_sentence_piece:\n f.write(i+'\\n')\n print('python dataset/vocab.py -c '+directory_path+'/temp.small'+' -o '+directory_path+'/'+vocab_file_name+'.small')\n os.system('bert-vocab -c '+directory_path+'/temp.small'+' -o '+directory_path+'/'+vocab_file_name+'.small')\n os.system('rm -r '+directory_path+'/temp.small')\n \n \ndef prepare_data(i):\n if len(i.strip())!=0 and len(i.split())>2:\n te=''\n m=len(i.split())\n c=0\n for j in i.split():\n if c==(m//2) -1 :\n te+=j+' \\t '\n else:\n te+=j+' '\n c+=1\n return te.strip().replace('.','')\n else:\n return ''\n\ndef change_data_to_input_format(file_path_input,file_path_output,sentence_piece_model_path):\n with open(file_path_input,'r') as f:\n data=f.read()\n data=data.split('\\n')[:-1]\n sp=spm.SentencePieceProcessor()\n sp.load(sentence_piece_model_path)\n req_data=[]\n for i in data: \n changed_data=prepare_data(' '.join(sp.EncodeAsPieces(i)))\n if changed_data!='':\n req_data.append(changed_data)\n with open(file_path_output,'w') as f:\n for i in req_data:\n f.write(i+'\\n')\n \ndef load_vocab(vocab_path: str):\n with open(vocab_path, \"rb\") as f:\n return pickle.load(f)\n \ndef create_fasttext_embeddings(vocab_file_path,fasttext_model_bin_path,path_to_save_fasttext_embeddings):\n vocab_data=load_vocab(vocab_file_path)\n model=fasttext.load_model(fasttext_model_bin_path)\n arr=[]\n for i in vocab_data.stoi:\n arr.append(model.get_sentence_vector(i))\n arr=np.array(arr)\n np.save(path_to_save_fasttext_embeddings,arr)\n \ndef train_fasttext_model(input_text_file,save_model_path): \n model=fasttext.train_unsupervised(input_text_file,model='skipgram',wordNgrams=3,verbose=1,dim=100,epoch=10)\n model.save_model(save_model_path)\ndef train():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-path_to_text_data\", \"--path_to_text_data\", required=True, type=str, help=\"path to text data\")\n parser.add_argument(\"-vocab_size\", \"--vocab_size\", required=True, type=int,help=\"vocab_size\")\n parser.add_argument(\"-path_to_modified_text_data\", \"--path_to_modified_text_data\", type=str, help=\"path to modified data\")\n parser.add_argument(\"-path_to_fasttext_model\", \"--path_to_fasttext_model\", type=str, help=\"path to fasttext model\")\n \n args = parser.parse_args()\n \n# train_sentencepiece_model(args.path_to_text_data,args.vocab_size)\n# create_vocab_file(os.getcwd()+'/model_sentencepiece.model',os.getcwd(),'vocabfile')\n# print('vocab file created')\n# change_data_to_input_format(args.path_to_text_data,args.path_to_modified_text_data,os.getcwd()+'/model_sentencepiece.model')\n# print('input format created')\n train_fasttext_model(args.path_to_modified_text_data,args.path_to_fasttext_model)\n print('fasttext model created')\n create_fasttext_embeddings(os.getcwd()+'/vocabfile.small',args.path_to_fasttext_model,'./fasttext_vectors.npy')\n #'/home/sriharshkamma/model_filename_big.bin'\n \nif __name__ == \"__main__\":\n train() \n#python preprocessing.py -path_to_text_data /home/sriharshkamma/final/BERT-pytorch/data/version1_test_corpus.small -vocab_size 100 -path_to_modified_text_data ./modified_text_data.small -path_to_fasttext_model ./fasttext.bin","sub_path":"bert_pytorch/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"300369530","text":"\nimport mystery_word as mw\n\n# import pdb\nimport random\nimport re\nimport sys\nimport webbrowser\n\n\nclass DemonWord(mw.MysteryWord):\n \"\"\"DemonWord class is a mystery word game which evilly dodges user guesses\n word_length is the number of letters in word to guess\n difficulty is 'easy'/'medium'/'hard'/'evil'\n\n medium = normal hangman game, computer picks a mystery word\n hard = computer dodges your guesses, always maximizing the number\n of possible words\n evil = same as hard, but hints are misleading\n (suggests worst possible guess)\n easy = same AI as hard mode, but tries to maximize\n player's chance of correct guesses\n\n\n \"\"\"\n def __init__(self, word_length=6, difficulty='evil'):\n \"\"\"Init for DemonWord class\"\"\"\n super(DemonWord, self).__init__()\n self.word_length = 6\n self.regexp = '.'*6\n self.word = None\n self.debug_output = False\n self.hint = ''\n self.word_families = {}\n self.word_list = ['echo', 'heal', 'best', 'lazy']\n self.difficulty = difficulty\n self.current_guess = ''\n self.lying_hints = False\n\n def set_word_length(self, word_length=6):\n \"\"\"Sets the word_length and initial blanke regexp,\n as well as filtering the word_list for the number of characters\n \"\"\"\n self.word_length = word_length\n self.regexp = '.' * word_length\n self.word_list = self.filter_word_list(self.word_list, self.regexp)\n\n def filter_word_list(self, word_list, regexp):\n \"\"\"Converts our simplified regexp to proper python regexp syntax\n Regexp consists of any character that has been correctly guessed\n or '.' if location is as yet unassigned\n \"\"\"\n word_list = [word for word in word_list if len(word) == len(regexp)]\n regexp = ''.join(['[a-z]' if char == '.' else char for char in regexp])\n regextp = ' ' + regexp + ' '\n return re.findall(regexp, ' '.join(word_list))\n\n def attempt_guess(self, letter):\n \"\"\"Return False if invalid, otherwise add to guesses list and return True\n This also triggers re-evaluation of the current word_list\n \"\"\"\n if self.difficulty == 'easy': # irrelevant in medium/normal mode\n evil = False\n else:\n evil = True\n # pdb.set_trace()\n if not self.is_valid_guess(letter):\n return False\n letter = letter.lower()\n\n old_regexp = self.regexp\n self.word_families = self.find_word_families(self.regexp,\n self.word_list, letter)\n self.word_list = self.pick_word_family(self.word_families,\n letter, evil)\n self.guesses.append(letter)\n possible_word = self.word_list[0]\n self.regexp = self.find_word_family(self.regexp, possible_word, letter)\n\n if self.regexp == old_regexp:\n print('Incorrect guess.\\n')\n self.num_guesses_left -= 1\n else:\n print('Correct!\\n')\n\n if not self.check_win():\n self.word = self.pick_single_word() # The final lie\n\n return True\n\n def find_word_families(self, regexp, word_list, guess):\n \"\"\"Given current regexp game state, the current word list, and letter\n guess, returns dictionary containing lists of words indexed by the\n regexp which would include them (if that word family is chosen)\n \"\"\"\n word_families = {}\n family_members = []\n for word in word_list:\n word_family = self.find_word_family(regexp, word, guess)\n family_members = word_families.get(word_family, [])\n family_members.append(word)\n word_families[word_family] = family_members\n return word_families\n\n def find_word_family(self, current_regexp, word, guess):\n \"\"\"Returns the regexp which would leave word in play\n with given guess letter\n \"\"\"\n # assert game.find_word_family('.....', 'river', 'r') == 'r...r'\n # output_list = [self.display_regexp_char(letter, word)\n # for letter in word]\n new_regexp = list(current_regexp)\n if self.debug_output:\n print('current_regexp: {}, word: {}'.format(repr(current_regexp),\n repr(word)))\n for slot, char in enumerate(current_regexp):\n # pdb.set_trace()\n if word[slot] == guess:\n new_regexp[slot] = guess\n output = ''.join(new_regexp)\n return output\n\n def pick_word_family(self, word_families, guess='a', evil=True):\n \"\"\"Picks 'hardest' word list based on word_families dictionary\"\"\"\n max = 0\n word_family = ''\n if (not evil) and len(word_families) > 1:\n # print('word_families: {}'.format(word_families))\n if self.current_guess in ''.join(word_families):\n # if guessed letter is somewhere in the keys\n try:\n # temp = word_families[self.regexp]\n del(word_families[self.regexp])\n # remove incorrect guesses as an option\n except:\n # word_families[self.regexp] = temp\n pass\n # Dirty hack for bug with easy, long, 'q', 'u'\n # -- index out of range\n if self.debug_output:\n print('word_families:{}'.format(word_families))\n for key, value in word_families.items():\n # Refactor this with a lambda\n if len(value) > max:\n max = len(value)\n word_family = key\n if self.debug_output:\n print('{},'.format(len(value)), end='')\n if self.debug_output:\n print('\\nword_family: {}, return word list: {}'.format(\n repr(word_family), repr(word_families[word_family])))\n # consider adding check if it is the last turn to force a loss\n\n return word_families[word_family]\n\n def pick_best_letter(self, lie=False):\n \"\"\"Recommend best letter for user to pick if lie=False, otherwise worst\n \"\"\"\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n available = [letter for letter in alphabet\n if letter not in self.guesses]\n letter_scores = {}\n\n def simple_pick():\n \"\"\"Just pick a letter known to be within >= 1 word_list words\"\"\"\n word_list_set = set(''.join(self.word_list)) # removes duplicates\n available_hits = [letter for letter in available\n if letter in word_list_set]\n self.hint = random.choice(available_hits)\n\n if len(self.word_list) < 3 and not lie:\n simple_pick()\n return\n\n for letter in available:\n # # word_families = self.find_word_families(self.regexp,\n # # self.word_list, letter)\n # # print('word_families: {}'.format(self.word_families))\n # # letter_scores[letter] = ([word_families[x]\n # # for x in word_families])\n # possible_word = self.word_list[0]\n # potential_regexp = self.find_word_family(self.regexp,\n # possible_word, letter)\n # potential_wordlist = self.filter_word_list(self.word_list,\n # potential_regexp)\n # letter_scores[letter] = len(potential_wordlist)\n potential_word_families = self.find_word_families(self.regexp,\n self.word_list,\n letter)\n potential_word_list = self.pick_word_family(potential_word_families,\n letter)\n # possible_word = potential_word_list[0]\n # possible_regexp = self.find_word_family(self.regexp,\n # possible_word, letter)\n\n letter_scores[letter] = potential_word_list\n if self.debug_output:\n print('letter scores: {}'.format([len(letter_scores[x])\n for x in letter_scores]))\n\n try:\n min_score = min([len(letter_scores[letter]) for letter in available\n if letter in ''.join(letter_scores[letter])])\n max_score = max([len(letter_scores[letter]) for letter in available\n if letter not in ''.join(letter_scores[letter])])\n\n except:\n min_score = min([len(letter_scores[letter])\n for letter in available])\n max_score = max([len(letter_scores[letter])\n for letter in available])\n\n if (max_score == 1 and lie is True) or (min_score == 1\n and lie is False):\n simple_pick()\n return\n\n for letter in letter_scores:\n if lie is True and len(letter_scores[letter]) == max_score:\n self.hint = letter\n\n elif lie is False and len(letter_scores[letter]) == min_score:\n self.hint = letter\n\n def display_word(self):\n \"\"\"Returns a string showing which letters from letter_list are in word\n \"\"\"\n output_list = [self.display_letter(letter) for letter in self.regexp]\n output = ' '.join(output_list)\n return output\n\n def is_word_complete(self):\n \"\"\"Returns True if all letters in word are in letter_list\"\"\"\n for letter in self.regexp:\n if letter == '.':\n return False\n return True\n\n def pick_single_word(self):\n \"\"\"Returns a randomly selected word in self.word_list\"\"\"\n return random.choice(self.word_list)\n\n def quick_play(self, silent=False, lying_hint=False):\n \"\"\"Not yet implemented\"\"\"\n pass\n '''\n for _ in range(self.num_guesses_left):\n letter = self.pick_best_letter(lie=lying_hint)\n if not silent:\n print('You guessed {}'.format(letter))\n self.attempt_guess(letter)\n if not silent:\n print(self)\n if self.check_win() is not None:\n break\n '''\n\n\ndef user_interface(show_hint=False, lying_hints=False, show_debug_output=False):\n \"\"\"Gets input from user to conduct a DemonWords game\n show_hint=True shows hints at each turn (overridden by user menu)\n lying_hints=True shows hints that make it harder to win\n (may be overriden by user menu)\n debug_output=True provides prints extra information about each turn\n (may be overriden by command line options)\n \"\"\"\n def guess_prompt():\n guess = ''\n while not game.is_valid_guess(guess):\n guess = input('Please choose a letter: ').lower()\n if not game.is_valid_guess(guess):\n print('Invalid letter, try again...')\n game.current_guess = guess\n return guess\n\n def welcome_menu():\n print('Welcome to Mystery Word!')\n print(\"Please select from the following options.\")\n\n def select_difficulty_menu():\n game.difficulty = one_key_menu(\n choices={'e': 'easy', 'm': 'medium', 'h': 'hard', 'v': 'evil'},\n prompt='Choose a difficulty level -- [E]asy, [M]edium, '\n '[H]ard, e[V]il: ',\n default='m',\n force_compliance=True,\n force_msg='Please choose from the listed options, or q to exit.',\n exit_words=['q', 'quit', 'end', 'exit'])\n\n def choose_hints_menu():\n return one_key_menu(choices={'y': True, 'n': False},\n prompt='Would you like friendly hints? [y/N] : ',\n default='n',\n force_compliance=False,\n force_msg='',\n exit_words=['q', 'quit', 'end', 'exit'])\n\n def word_length_menu():\n valid_choices = 'sml'\n choice = ' '\n while (choice not in valid_choices) or choice == '':\n choice = input('Please choose word length: '\n '[S]hort [M]edium or [L]ong: ').lower()\n if choice == 's':\n game.set_word_length(random.randrange(4, 7))\n if choice == 'm':\n game.set_word_length(random.randrange(6, 9))\n if choice == 'l':\n game.set_word_length(random.randrange(8, 13))\n # Move these elsewhere, if possible:\n if game.difficulty == 'medium':\n\n game.word = random.choice([x for x in game.word_list\n if len(x) == game.word_length])\n game.word_list = [game.word]\n\n if game.difficulty == 'evil':\n game.lying_hints = True\n\n def game_loop():\n while True:\n guess = guess_prompt()\n game.attempt_guess(guess)\n print(game)\n if show_hint:\n show_hints()\n if game.check_win() is not None:\n break\n\n def define_word_menu():\n my_word = game.word if game.check_win() is False else game.regexp\n my_prompt = \"Would you like to know what the heck '{}' means? [y/N]: \"\n my_prompt = my_prompt.format(my_word)\n show_definition = one_key_menu(\n choices={'y': True, 'n': False},\n prompt=my_prompt,\n default='n',\n force_compliance=False,\n force_msg='',\n exit_words=['q', 'quit', 'end', 'exit'])\n if show_definition:\n my_url = 'https://search.yahoo.com/search;?p=define%3A+' + my_word\n webbrowser.open(my_url)\n\n def play_again():\n define_word_menu()\n return one_key_menu(choices={'y': True, 'n': False},\n prompt='Play again [Y/n]?',\n default='y',\n force_compliance=False,\n force_msg='',\n exit_words=['q', 'quit', 'end', 'exit'])\n\n def show_hints():\n if game.check_win() is None:\n game.pick_best_letter(game.lying_hints)\n s = 's' if len(game.word_list) > 1 else ''\n print('Current word list has {} word{}. '.format(\n len(game.word_list), s), end='')\n print(\"Might I recommend you try '{}'?\\n\".format(game.hint))\n\n def one_key_menu(choices={'y': True, 'n': False}, prompt='Y/n?',\n default='y', force_compliance=False,\n force_msg='Please try again. \\n',\n exit_words=['quit', 'end', 'exit']):\n \"\"\"Function for capturing case-insensitive single letter input\n Probably could also be used for >1 letter input with a list input\n into acceptabld choices is an iterable that contains all valid input\n options, must be all lowercase\n\n prompt is the text to display on the line taking input\n\n default is the value to choose on blank or bogus input,\n must be lowercase\n\n force_compliance set to True loops the input prompt until an\n acceptable answer is met\n\n force_msg is a message to display on improper input, including\n newlines if needed\n\n exit_words contains allowed input for exiting the loop,\n must be lowercase\n \"\"\"\n kb_input = input(prompt).lower()\n if kb_input in exit_words:\n sys.exit('Exiting game by user request.')\n\n if kb_input not in choices:\n if force_compliance:\n print(force_msg)\n return one_key_menu()\n else:\n return default\n else:\n return choices[kb_input]\n\n game = DemonWord()\n game.debug_ouput = show_debug_output\n game.import_word_list('/usr/share/dict/words')\n if game.debug_output:\n game.word_list = game.word_list[:1000]\n welcome_menu()\n select_difficulty_menu()\n word_length_menu()\n show_hint = choose_hints_menu()\n print('The Mystery Word contains {} letters.'.format(len(game.regexp)))\n print(game)\n if show_hint:\n show_hints()\n game_loop()\n while(play_again()):\n game = DemonWord()\n game.import_word_list('/usr/share/dict/words')\n if game.debug_output:\n game.word_list = game.word_list[:1000]\n select_difficulty_menu()\n word_length_menu()\n show_hint = choose_hints_menu()\n print('The Mystery Word contains {} letters.'.format(len(game.regexp)))\n print(game)\n if show_hint:\n show_hints()\n game_loop()\n\nif __name__ == '__main__':\n \"\"\"Use 'debug' command line option to enter debug mode\"\"\"\n to_debug = False\n try:\n if len(sys.argv) > 1 and sys.argv[1] == 'debug':\n to_debug = True\n print('Running in debug mode...')\n except:\n pass\n user_interface(show_hint=True, lying_hints=False,\n show_debug_output=to_debug)\n","sub_path":"demon_words.py","file_name":"demon_words.py","file_ext":"py","file_size_in_byte":17482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"365460341","text":"import sys\nimport random\nimport matplotlib\n\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton\nfrom matplotlib import pyplot\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nmatplotlib.use('Qt5Agg')\n\n\nclass MplCanvas(FigureCanvas):\n\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n # fig = Figure(figsize=(width, height), dpi=dpi)\n fig, self.ax = pyplot.subplots(figsize=(15, 7.5))\n # self.ax = fig.add_subplot(111)\n super(MplCanvas, self).__init__(fig)\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.canvas = MplCanvas(self, width=30, height=20, dpi=100)\n self.setCentralWidget(self.canvas)\n\n n_data = 50\n self.xdata = list(range(n_data))\n self.ydata = [random.randint(0, 10) for i in range(n_data)]\n self.update_plot()\n\n button1 = QPushButton(self.canvas)\n button1.setText(\"Button1\")\n button1.move(64, 16)\n button1.clicked.connect(self.update_plot)\n\n self.show()\n\n # Setup a timer to trigger the redraw by calling update_plot.\n # self.timer = QtCore.QTimer()\n # self.timer.setInterval(100)\n # self.timer.timeout.connect(self.update_plot)\n # self.timer.start()\n\n\n def update_plot(self):\n # Drop off the first y element, append a new one.\n self.ydata = self.ydata[1:] + [random.randint(0, 10)]\n self.canvas.ax.cla() # Clear the canvas.\n self.canvas.ax.plot(self.xdata, self.ydata, 'r')\n # Trigger the canvas to update and redraw.\n self.canvas.draw()\n\n\napp = QtWidgets.QApplication(sys.argv)\nw = MainWindow()\napp.exec_()\n","sub_path":"src/qt.py","file_name":"qt.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"512609313","text":"# from PyQt5.QtWidgets import *\n# import sys\n#\n# class Window(QWidget):\n# def __init__(self):\n# QWidget.__init__(self)\n# layout = QGridLayout()\n# self.setLayout(layout)\n#\n# radiobutton = QRadioButton(\"Australia\")\n# radiobutton.setChecked(True)\n# radiobutton.value = 1\n# radiobutton.toggled.connect(self.onClicked)\n# layout.addWidget(radiobutton, 0, 0)\n#\n# radiobutton = QRadioButton(\"China\")\n# radiobutton.value = 2\n# radiobutton.toggled.connect(self.onClicked)\n# layout.addWidget(radiobutton, 0, 1)\n#\n# radiobutton = QRadioButton(\"Japan\")\n# radiobutton.value = 3\n# radiobutton.toggled.connect(self.onClicked)\n# layout.addWidget(radiobutton, 0, 2)\n#\n# def onClicked(self):\n# radioButton = self.sender()\n# if radioButton.isChecked():\n# print(\"Country is %s\" % (radioButton.value))\n#\n#\n# app = QApplication(sys.argv)\n# screen = Window()\n# screen.show()\n# sys.exit(app.exec_())\n\n# import sys\n# import time\n#\n# from PyQt5.QtGui import QPixmap\n# from PyQt5.QtWidgets import (QApplication, QDialog,\n# QProgressBar, QPushButton, QMessageBox)\n# from PyQt5.QtCore import QThread, pyqtSignal\n#\n# TIME_LIMIT = 100\n#\n#\n# class External(QThread):\n# \"\"\"\n# Runs a counter thread.\n# \"\"\"\n#\n# countChanged = pyqtSignal(int)\n#\n# def run(self):\n# count = 0\n# while count < TIME_LIMIT:\n# count += 1\n# time.sleep(0.05)\n# self.countChanged.emit(count)\n# QMessageBox.setIconPixmap(QMessageBox.information(None, \"Concluído\", \"10 imagens rotacionadas.\"),\n# QPixmap(\":verificado.png\"))\n# # QMessageBox.iconPixmap(QMessageBox.information(None, \"Concluído\", \"10 imagens rotacionadas.\"))\n#\n# class Actions(QDialog):\n# \"\"\"\n# Simple dialog that consists of a Progress Bar and a Button.\n# Clicking on the button results in the start of a timer and\n# updates the progress bar.\n# \"\"\"\n#\n# def __init__(self):\n# super().__init__()\n# self.initUI()\n#\n# def initUI(self):\n# self.setWindowTitle('Progress Bar')\n# self.progress = QProgressBar(self)\n# self.progress.setGeometry(0, 0, 300, 25)\n# self.progress.setMaximum(100)\n# self.button = QPushButton('Start', self)\n# self.button.move(0, 30)\n# self.show()\n#\n# self.button.clicked.connect(self.onButtonClick)\n#\n# def onButtonClick(self):\n# self.calc = External()\n# self.calc.countChanged.connect(self.onCountChanged)\n# self.calc.start()\n#\n# def onCountChanged(self, value):\n# self.progress.setValue(value)\n#\n# if __name__ == \"__main__\":\n# app = QApplication(sys.argv)\n# window = Actions()\n# sys.exit(app.exec_())\n\nfrom PyQt5 import QtGui\nfrom PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout\nimport sys\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nimport time\n\n\n# class MyThread(QThread):\n# # Create a counter thread\n# change_value = pyqtSignal(int)\n#\n# def run(self):\n# cnt = 0\n# while cnt &100:\n# cnt += 1\n# time.sleep(0.3)\n# self.change_value.emit(cnt)\n#\n# class Window(QDialog):\n# def __init__(self):\n# super().__init__()\n# self.title = \"PyQt5 ProgressBar\"\n# self.top = 200\n# self.left = 500\n# self.width = 300\n# self.height = 100\n# self.setWindowIcon(QtGui.QIcon(\"icon.png\"))\n# self.setWindowTitle(self.title)\n# self.setGeometry(self.left, self.top, self.width, self.height)\n# vbox = QVBoxLayout()\n# self.progressbar = QProgressBar()\n# # self.progressbar.setOrientation(Qt.Vertical)\n# self.progressbar.setMaximum(100)\n# self.progressbar.setStyleSheet(\"QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}\"\n# \"QProgressBar::chunk {background:yellow}\")\n# # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);\n# # self.progressbar.setStyleSheet(\"QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }\")\n# # self.progressbar.setTextVisible(False)\n# vbox.addWidget(self.progressbar)\n# self.button = QPushButton(\"Start Progressbar\")\n# self.button.clicked.connect(self.startProgressBar)\n# self.button.setStyleSheet('background-color:yellow')\n# vbox.addWidget(self.button)\n# self.setLayout(vbox)\n# self.show()\n#\n# def startProgressBar(self):\n# self.thread = MyThread()\n# self.thread.change_value.connect(self.setProgressVal)\n# self.thread.start()\n#\n# def setProgressVal(self, val):\n# self.progressbar.setValue(val)\n#\n#\n# App = QApplication(sys.argv)\n# window = Window()\n# sys.exit(App.exec())\n\nimport logging\nimport random\nimport sys\nimport time\n\nfrom PyQt5.QtCore import QRunnable, Qt, QThreadPool\nfrom PyQt5.QtWidgets import (\n QApplication,\n QLabel,\n QMainWindow,\n QPushButton,\n QVBoxLayout,\n QWidget,\n)\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\n# 1. Subclass QRunnable\nclass Runnable(QRunnable):\n def __init__(self, n):\n super().__init__()\n self.n = n\n\n def run(self):\n # Your long-running task goes here ...\n for i in range(5):\n logging.info(f\"Working in thread {self.n}, step {i + 1}/5\")\n time.sleep(random.randint(700, 2500) / 1000)\n\nclass Window(QMainWindow):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setupUi()\n\n def setupUi(self):\n self.setWindowTitle(\"QThreadPool + QRunnable\")\n self.resize(250, 150)\n self.centralWidget = QWidget()\n self.setCentralWidget(self.centralWidget)\n # Create and connect widgets\n self.label = QLabel(\"Hello, World!\")\n self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n countBtn = QPushButton(\"Click me!\")\n countBtn.clicked.connect(self.runTasks)\n # Set the layout\n layout = QVBoxLayout()\n layout.addWidget(self.label)\n layout.addWidget(countBtn)\n self.centralWidget.setLayout(layout)\n\n def runTasks(self):\n threadCount = QThreadPool.globalInstance().maxThreadCount()\n self.label.setText(f\"Running {threadCount} Threads\")\n pool = QThreadPool.globalInstance()\n for i in range(threadCount):\n # 2. Instantiate the subclass of QRunnable\n runnable = Runnable(i)\n # 3. Call start()\n pool.start(runnable)\n\napp = QApplication(sys.argv)\nwindow = Window()\nwindow.show()\nsys.exit(app.exec())","sub_path":"test/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":6917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"528441058","text":"import pygame\nimport math\n\npygame.init()\nwin = pygame.display.set_mode((500, 500))\nclock = pygame.time.Clock()\n# The correct method to solve for intersection points of two circles is algebraically.\n# NOT using points (x, y coordinates) because of infinite precision of coordinate system (real numbers).\n\n\ndef get_intersections(x0, y0, r0, x1, y1, r1):\n # circle 1: (x0, y0), radius r0\n # circle 2: (x1, y1), radius r1\n d = math.sqrt((x1-x0)**2 + (y1-y0)**2)\n # non intersecting\n if d > r0 + r1:\n return None\n # One circle within other\n if d < abs(r0-r1):\n return None\n # coincident circles\n if d == 0 and r0 == r1:\n return None\n else:\n a = (r0**2-r1**2+d**2)/(2*d)\n h = math.sqrt(r0**2-a**2)\n x2 = x0+a*(x1-x0)/d\n y2 = y0+a*(y1-y0)/d\n x3 = x2+h*(y1-y0)/d\n y3 = y2-h*(x1-x0)/d\n\n x4 = x2-h*(y1-y0)/d\n y4 = y2+h*(x1-x0)/d\n\n return (x3, y3, x4, y4)\n\n\nh, k = 200, 200\nr = 100\nrun = True\nwhile run:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n print(pygame.key.name(event.key))\n\n win.fill((66, 67, 69))\n x0, y0 = 0, 0\n r0 = 5\n x1, y1 = 2, 2\n r1 = 5\n\n # intersecting with (x1, y1) but not with (x0, y0)\n x2, y2 = -1, 0\n r2 = 2.5\n\n circle1 = plt.Circle((x0, y0), r0, color='b', fill=False)\n circle2 = plt.Circle((x1, y1), r1, color='b', fill=False)\n circle3 = plt.Circle((x2, y2), r2, color='b', fill=False)\n\n fig, ax = plt.subplots()\n ax.set_xlim((-10, 10))\n ax.set_ylim((-10, 10))\n ax.add_artist(circle1)\n ax.add_artist(circle2)\n ax.add_artist(circle3)\n\n intersections = get_intersections(x0, y0, r0, x1, y1, r1)\n if intersections is not None:\n i_x3, i_y3, i_x4, i_y4 = intersections\n plt.plot([i_x3, i_x4], [i_y3, i_y4], '.', color='r')\n\n intersections = get_intersections(x0, y0, r0, x2, y2, r2)\n if intersections is not None:\n i_x3, i_y3, i_x4, i_y4 = intersections\n plt.plot([i_x3, i_x4], [i_y3, i_y4], '.', color='r')\n\n intersections = get_intersections(x1, y1, r1, x2, y2, r2)\n if intersections is not None:\n i_x3, i_y3, i_x4, i_y4 = intersections\n plt.plot([i_x3, i_x4], [i_y3, i_y4], '.', color='r')\n\n plt.gca().set_aspect('equal', adjustable='box')\n\n pygame.display.flip()\n","sub_path":"Code/Visualize_Tools/test_pygame.py","file_name":"test_pygame.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"352424581","text":"import pandas as pd\n\n\n# Excelファイルを開く\nfilename = 'population.xlsx'\nsheet_name = 'list-sjis.csv'\nbook = pd.read_excel(filename, sheet_name=sheet_name)\n\n# データを人口順に表示\nbook.sort_values(by='法定人口', ascending=False)\nprint(book)\n","sub_path":"3_Data/3-1_excel_pandas.py","file_name":"3-1_excel_pandas.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"486283412","text":"\"\"\"eval URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\n\nfrom main.api import UserProfileResource, UserResource, RecipeResource, StepResource, AllergyResource, \\\n IngredientResource, RecipeFavouriteResource, StepIngredientResource\nfrom main.views import RecipeList, IndexView, RecipeDetail, IngredientList, AllergiesList, Recipe2Detail, RecipeNotView\nfrom tastypie.api import Api\n\nv1_api = Api(api_name='v1')\nv1_api.register(UserProfileResource())\nv1_api.register(UserResource())\nv1_api.register(RecipeResource())\nv1_api.register(StepResource())\nv1_api.register(AllergyResource())\nv1_api.register(IngredientResource())\nv1_api.register(RecipeFavouriteResource())\nv1_api.register(StepIngredientResource())\n\nurlpatterns = [\n # Auth\n url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),\n url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),\n url(r'^admin/', admin.site.urls),\n url(r'^admin', admin.site.urls),\n url(r'^$', IndexView.as_view(), name='index'),\n url(r'^recipes/$', RecipeList.as_view(), name='recipes'),\n url(r'^ingredients/$', IngredientList.as_view(), name='ingredients'),\n url(r'^allergies/$', AllergiesList.as_view(), name='allergies'),\n url(r'^recipe/(?P[-\\w]+)/$', RecipeDetail.as_view(), name='recipe-detail'),\n url(r'^recipe2/(?P[-\\w]+)/$', Recipe2Detail.as_view(), name='recipe-detail2'),\n url(r'^recipe-not/$', RecipeNotView.as_view(), name='recipe-not'),\n\n # API section\n url(r'^api/', include(v1_api.urls)),\n\n # Catch all non existent pages\n url(r'^.*$', IndexView.as_view(), name='index'),\n\n]\n","sub_path":"seku/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"137536712","text":"import re\nimport logging\n\n\nfrom model.dao.gym_dao import GymDAO\n\nfrom exceptions import Error, InvalidData\n\n\nclass GymController:\n\t\n\tdef __init__(self, database_engine):\n\t\tself._database_engine = database_engine\n\n\tdef create_gym(self, data):\n\t\ttry:\n\t\t\twith self._database_engine.new_session() as session:\n\t\t\t\tdao = GymDAO(session)\n\t\t\t\tgym = dao.create(data)\n\t\t\t\tgym_data = gym.to_dict()\n\t\t\t\treturn gym_data\n\t\texcept Error as error:\n\t\t\traise error\n\n\tdef list_gyms(self, person_type=None):\n\t\twith self._database_engine.new_session() as session:\n\t\t\tgyms = GymDAO(session).get_all()\n\t\t\tprint(gyms)\n\t\t\tgyms_data = [gyms.to_dict('dict') for gym in gyms]\n\t\treturn gyms_data\n\n\tdef get_gym(self, gym_id):\n\t\twith self._database_engine.new_session() as session:\n\t\t\tgym = GymDAO(session).get(gym_id)\n\t\t\tgym_data = gym.to_dict()\n\t\treturn gym_data\n\n\tdef update_gym(self, gym_id, gym_data):\n\t\twith self._database_engine.new_session() as session:\n\t\t\tdao = GymDAO(session)\n\t\t\tgym = dao.get(gym_data)\n\t\t\tgym = dao.update(gym, gym_data)\n\t\t\treturn gym.to_dict()\n\n\tdef delete_gym(self, gym_id):\n\t\twith self._database_engine.new_session() as session:\n\t\t\tdao = GymDAO(session)\n\t\t\tgym = dao.get(gym_id)\n\t\t\tdao.delete(gym)\n\n\tdef search_gym(self, name):\n\t\twith self._database_engine.new_session() as session:\n\t\t\tdao = GymDAO(session)\n\t\t\tgym = dao.get_by_name(name)\n\t\t\treturn gym.to_dict()","sub_path":"GLPOO_Project/controller/gym_controller.py","file_name":"gym_controller.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"397878486","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nimport os\nimport sys\nimport unittest\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nimport datetime\nfrom func.sprint4Func import *\nfrom func.loadData import readAndSaveToList\n\ndef load_data():\n file_name = 'nov10.ged'\n # create list for individual and families\n ilist = []\n flist = []\n\n # input sample\n filePath = os.path.join(os.getcwd(), \"Sample/\" + file_name)\n\n # read file to create individual and families\n if os.path.exists(filePath):\n readAndSaveToList(filePath, ilist, flist)\n else:\n print(\"File doesn't exist\")\n\n return ilist, flist\n\nclass TestSprint4Func(unittest.TestCase):\n \"\"\"Test mathfuc.py\"\"\"\n \n def test_US38_upcomingBirthdays(self):\n ilist, flist = load_data()\n for indi in ilist:\n if indi.ID == \"I10\":\n self.assertTrue(US38_upcomingBirthdays(indi))\n def test_US39_upcomingAnniversaries(self):\n ilist, flist = load_data()\n for fm in flist:\n if fm.ID == \"F3\":\n self.assertTrue(US39_upcomingAnniversaries(fm))\n \n def test_us29(self):\n ilist, flist = load_data()\n for pp in ilist:\n if US29(pp.ID, pp.Name ,pp.Alive)!=None:\n self.assertTrue(US29(pp.ID, pp.Name ,pp.Alive))\n \n def test_us30(self):\n ilist, flist = load_data()\n for fm in flist:\n if US30(fm.ID, fm.Divorced, fm.HusbandID, fm.WifeID,ilist)!=None:\n self.assertTrue(US30(fm.ID, fm.Divorced, fm.HusbandID, fm.WifeID,ilist))\n\n def test_ListMultipleBirths(self):\n ilist, flist = load_data()\n\n tp = ListMultipleBirths(ilist)\n \n self.assertEqual(len(tp), 8)\n\n def test_ListLivingSingle(self):\n\n ilist, flist = load_data()\n\n tp = ListLivingSingle(ilist)\n\n self.assertEqual(len(tp), 0) \n def test_US35(self):\n day= '2018-11-11'\n self.assertTrue(US35(day))\n def test_US36(self):\n day= '2018-11-11'\n self.assertTrue(US36(day))\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n\n tests = [TestSprint4Func(\"test_US38_upcomingBirthdays\"),TestSprint4Func(\"test_US39_upcomingAnniversaries\"),\\\n TestSprint4Func(\"test_us29\"),TestSprint4Func(\"test_us30\"),TestSprint4Func(\"test_US35\"),TestSprint4Func(\"test_US36\")]\n \n suite.addTests(tests)\n \n\n tests = [TestSprint4Func(\"test_ListMultipleBirths\"),TestSprint4Func(\"test_ListLivingSingle\")]\n suite.addTests(tests)\n\n runner = unittest.TextTestRunner(verbosity=2)\n runner.run(suite)\n\n","sub_path":"Project04/module/test/sprint4Test.py","file_name":"sprint4Test.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"506699922","text":"#!/usr/bin/env python3\n\nfrom player import Player\nfrom point_guard import PointGuard\nfrom center import Center\nfrom small_forward import SmallForward\nfrom shooting_guard import ShootingGuard\nfrom power_forward import PowerForward\n\ndef main():\n\n pg = PointGuard()\n c = Center()\n sf = SmallForward()\n sg = ShootingGuard()\n pf = PowerForward()\n pg.run_play(\"I'll dribble penetrate\")\n c.run_play(\"I'll cut to the corner\")\n sf.run_play(\"I'll set the first pick\")\n sg.run_play(\"I'll run to the wing\")\n pf.run_play(\"I'll set the second pick\")\n pg.run_play(\"I'll dribble past the screens to the post\")\n c.run_play(\"I'll cut to the top of the key\")\n sf.run_play(\"I'll set the first pick and roll to the basket\")\n sg.run_play(\"I'll maneuver to the low block and set a screen\")\n pf.run_play(\"I'll set the second pick and screen the shooting guard\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"P1/ex05/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"228650827","text":"\"\"\"\nVarious ways to plot lines with Matplotlib.\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4, 5, 6, 7, 8]\ny = [2, 3, 7, 6, 7, 8, 9, 4]\n\ndata_obj = {\n 'Items': x,\n 'Quantity': y\n}\n\n\ndef plt_lines(x, y, **kwargs):\n plt.figure()\n plt.plot(x, y)\n plt.xlabel(kwargs['xlabel'])\n plt.ylabel(kwargs['ylabel'])\n plt.title(kwargs['title'])\n plt.box(on=False)\n plt.grid(color='0.8')\n plt.tick_params(color='0.8')\n\n\nplt.close('all')\n\n# example 1\nplt.figure()\nplt.plot(x, y)\nplt.xlabel('Items')\nplt.ylabel('Quantity')\nplt.title('Example 1')\nplt.box(on=False)\nplt.grid(color='0.85')\nplt.tick_params(color='0.85')\n\n# example 2\nplt.figure()\nplt.plot('Items', 'Quantity', data=data_obj)\nplt.xlabel('Items')\nplt.ylabel('Quantity')\nplt.title('Example 2')\nplt.box(on=False)\nplt.grid(color='0.85')\nplt.tick_params(color='0.85')\n\n# example 3\nfig, ax = plt.subplots()\nax.plot(x, y)\nax.set_xlabel('Items')\nax.set_ylabel('Quantity')\nax.set_title('Example 3')\nplt.box(on=False)\nplt.grid(color='0.85')\nplt.tick_params(color='0.85')\n\n# example 4 that uses above function to plot x and y\nplt_lines(x, y, xlabel='Items', ylabel='Quantity', title='Example 4')\n\nplt.show()\n","sub_path":"matplotlib_lines.py","file_name":"matplotlib_lines.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"513798297","text":"import math\n\nclass Parametric:\n step = -1\n edges = None\n\n def __init__(self, edgeMatrix, step=0.01):\n self.edges = edgeMatrix\n self.step = step\n\n def arc(self, center, radius, angle=2*math.pi):\n x = lambda t: center[0] + radius * math.cos(angle * t)\n y = lambda t: center[1] + radius * math.sin(angle * t)\n z = lambda t: center[2]\n self.add(x, y, z)\n\n def hermite(self, p0, p1, r0, r1):\n f = lambda i: lambda t: (2 * p0[i] - 2 * p1[i] + r0[i] + r1[i]) * t ** 3 + (-3 * p0[i] + 3 * p1[i] - 2 * r0[i] - r1[i]) * t ** 2 + r0[i] * t + p0[i]\n x = f(0)\n y = f(1)\n self.add(x, y)\n\n def bezier(self, p0, p1, p2, p3):\n f = lambda i: lambda t: (-p0[i] + 3 * p1[i] - 3 * p2[i] + p3[i]) * t ** 3 + (3 * p0[i] - 6 * p1[i] + 3 * p2[i]) * t ** 2 + (-3 * p0[i] + 3 * p1[i]) * t + p0[i]\n x = f(0)\n y = f(1)\n self.add(x, y)\n\n def add(self, x, y, z=lambda t: 0):\n step = self.step\n t = 0\n while t < 1:\n self.edges.addEdge((x(t), y(t), 0), (x(min(t + step, 1)), y(min(t + step, 1)), 0))\n t += step\n","sub_path":"engine/parametric/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"39611888","text":"\"\"\"Creates a card object when passed a suit and rank.\"\"\"\n\nimport collections\n\n\nclass Card(object):\n \"\"\"A card object with two attributes, suit and rank.\n\n The suit and rank values are provided when the deck is constructed, since\n different decks have different ranks and values for the cards they contain.\n \"\"\"\n\n SUITS = ('Clubs', 'Diamonds', 'Hearts', 'Spades')\n RANK = collections.namedtuple('Rank', 'value name')\n RANKS = (\n RANK(2, '2'),\n RANK(3, '3'),\n RANK(4, '4'),\n RANK(5, '5'),\n RANK(6, '6'),\n RANK(7, '7'),\n RANK(8, '8'),\n RANK(9, '9'),\n RANK(10, '10'),\n RANK(11, 'Jack'),\n RANK(12, 'Queen'),\n RANK(13, 'King'),\n RANK(14, 'Ace')\n )\n\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __str__(self):\n return '{0:>7} of {1}'.format(self.rank.name, self.suit)\n","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"557795335","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nfrom diary import storage\nfrom os import path\n\nif __name__ == '__main__':\n \n storage.show_menu()\n db_name = 'diary.db'\n storage.conn = storage.connect(db_name)\n storage.initialize(storage.conn)\n \n #if path.exists(db_name) == False:\n # storage.initialize(conn)\n \n \n actions = {\n '1': storage.show_diary,\n '2': storage.add_activity,\n '3': storage.change_activity,\n '4': storage.finish_activity,\n '5': storage.return_activity,\n '6': storage.action_exit\n }\n \n #task = storage.show_diary()\n \n while True:\n cmd = input()\n \n action = actions.get(cmd)\n \n if action:\n action()","sub_path":"HW5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"17425058","text":"import uuid\n\n\nclass Objective:\n __objective_map = {}\n\n @staticmethod\n def get_by_id(objective_id):\n return Objective.__objective_map[objective_id]\n\n def __init__(self, location, name, description, gameKey):\n self.id = str(uuid.uuid1())\n self.location = location\n self.name = name\n self.description = description\n self.gameKey = gameKey\n self.players_completed = []\n\n Objective.__objective_map[self.id] = self\n\n def __del__(self):\n del Objective.__objective_map[self.id]\n\n def player_complete(self, player_id):\n self.players_completed.append(player_id)\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"description\": self.description,\n \"location\": self.location\n }\n","sub_path":"SH-server/app/library/Objective.py","file_name":"Objective.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"292256890","text":"import os\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.getOrCreate()\n\ndata_path = os.getcwd() + '\\\\data'\n\njson_df2_path = data_path + '\\\\example_5.json'\n# df1 = spark.read.format(\"json\").load(json_df1_path)\n\ndf2 = spark.read.json(json_df2_path, multiLine=True)\ndf2.count()\ndf2.show()\n\ndf2.columns\n\ndf2_sample = df2.sample(False, fraction=0.1)\n\ndf2_sample.show()\n\ndf2_sorted = df2.sort(\"color\")\ndf2_sorted.show()\n","sub_path":"03.03 - Reading json files 2.py","file_name":"03.03 - Reading json files 2.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"547356830","text":"# OmrCard\r\nclass OmrCard:\r\n # 생성자\r\n def __init__(self, name, school_id):\r\n self.name = name\r\n self.school_id = school_id\r\n self.answer_list = list()\r\n\r\n # 정답을 입력 받는 메소드\r\n def marking_answer(self, *answers):\r\n for answer in answers:\r\n self.answer_list.append(answer)\r\n\r\n# OmrCardReader\r\nclass OmrCardReader:\r\n # 정답\r\n def __init__(self, *answer):\r\n self.real_answer_list = list()\r\n for answer in answer:\r\n self.real_answer_list.append(answer)\r\n\r\n # 카드를 읽어서 그 안에 있는 이름, 학번, 점수 계산 => 출력\r\n def read_omr_card(self, omr_card):\r\n i = 0 # index\r\n score = 0\r\n for real_answer in self.real_answer_list: # 0 1 2 3 4\r\n if real_answer == omr_card.answer_list[i]: # 정답이면\r\n # 한 문제당 점수: 100 / 문제 개수\r\n score += 100 / len(self.real_answer_list)\r\n \r\n i += 1 # index 값을 1 증가\r\n\r\n print(\"이름:%s, 학번:%d, 점수:%g\" % (omr_card.name, omr_card.school_id, score))\r\n\r\n# 객체 생성\r\nomrCard1 = OmrCard(\"신보람\", 1)\r\nomrCard1.marking_answer(1, 2, 3, 4, 5)\r\nprint(omrCard1.answer_list)\r\n\r\nomrCardReader = OmrCardReader(1, 2, 2, 4, 5)\r\nprint(omrCardReader.real_answer_list)\r\nomrCardReader.read_omr_card(omrCard1)\r\n\r\nomrCard2 = OmrCard(\"김바다\", 2)\r\nomrCard2.marking_answer(1, 2, 2, 4, 5)\r\n\r\nomrCardReader.read_omr_card(omrCard2)\r\n","sub_path":"11_class/quiz04/Quiz04.py","file_name":"Quiz04.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"348390916","text":"# Disable warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport math\nfrom math import sqrt\nfrom scipy import stats\nfrom sklearn.metrics import mean_squared_error, r2_score, explained_variance_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.feature_selection import f_regression \nfrom pydataset import data\n\n##########################################################################\n\ndef plot_residuals(y, yhat):\n '''\n This function takes in a dataframe, the y target variable \n and the yhat (model predictions) and creates columns for residuals\n and baseline residuals. It returns a graph of both residual columns.\n '''\n\n # create a residual column\n df['residual'] = (yhat - y)\n\n # create a residual baseline column\n df['residual_baseline'] = (y.mean() - y)\n \n fig, ax = plt.subplots(figsize=(13,7))\n\n ax.hist(df.residual_baseline, label='baseline residuals', alpha=.6)\n ax.hist(df.residual, label='model residuals', alpha=.6)\n ax.legend()\n\n plt.show()\n\n###############################################################################\n\ndef regression_errors(df, y, yhat):\n '''\n \n '''\n \n SSE = mean_squared_error(y, yhat)*len(df)\n\n\n MSE = mean_squared_error(y, yhat)\n\n\n RMSE = sqrt(mean_squared_error(y, yhat))\n\n\n ESS = sum((yhat - y.mean())**2)\n TSS = sum((y - y.mean())**2)\n\n # compute explained variance\n R2 = ESS / TSS\n \n print('SSE is:', SSE)\n print('ESS is:', ESS)\n print('TSS is:', TSS)\n print('R2 is:', R2)\n print('MSE is:', MSE)\n print('RMSE is:', RMSE) \n\n######################################################################\n\n\ndef baseline_mean_errors(df, y, yhat_baseline):\n \n SSE_baseline = mean_squared_error(y, yhat_baseline)*len(df)\n \n MSE_baseline = mean_squared_error(y, yhat_baseline)\n \n RMSE_baseline = sqrt(mean_squared_error(y, yhat_baseline))\n \n \n print('Baseline SSE is:', SSE_baseline)\n print('Baseline MSE is:', MSE_baseline)\n print('Baseline RMSE is:', RMSE_baseline)\n\n#######################################################################\n\n\ndef better_than_baseline(df, y, yhat, yhat_baseline):\n\n RMSE = sqrt(mean_squared_error(y, yhat))\n \n RMSE_baseline = sqrt(mean_squared_error(y, yhat_baseline))\n \n if RMSE < RMSE_baseline:\n print('True - The model performs better than the baseline')\n \n elif RMSE > RMSE_baseline:\n print('False - The baseline performs better than the model')\n \n return RMSE, RMSE_baseline","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"152325324","text":"import pickle\nimport os\nimport sys\nimport uuid\nimport psycopg2\nfrom flask import Flask, request, redirect, send_from_directory, Response, render_template, url_for\nfrom Show_Objects import cartoon_show_object, anime_show_object, show_object\nfrom htmltemplate import Template\nfrom PIL import Image\nimport base64\n\napp = Flask(__name__)\napp.secret_key = os.getenv('cartoon_secret_key')\n\nParent_Object = show_object()\nParent_Object.cartoon_dict = {}\nParent_Object.anime_dict = {}\n\n\ndef save_database():\n conn = psycopg2.connect(os.getenv('cartoon_database_url'))\n\n cursor = conn.cursor()\n cursor.execute('truncate \"ShowPickle\"')\n conn.commit()\n\n cursor.execute('INSERT INTO \"ShowPickle\"(cartoon_pickle_data) VALUES (%s)',\n (psycopg2.Binary(pickle.dumps(Parent_Object)),))\n\n conn.commit()\n\n\n# Load the Player list database\ndef load_database():\n try:\n global Parent_Object\n\n conn = psycopg2.connect(os.getenv('cartoon_database_url'))\n\n cursor = conn.cursor()\n cursor.execute('select cartoon_pickle_data from \"ShowPickle\" LIMIT 1') #\n mypickle = cursor.fetchone()[0]\n Parent_Object = pickle.loads(mypickle)\n\n except TypeError as err:\n print(\"Unexpected error:\", err)\n pass # do nothing. no database to load\n except:\n pass #this might happen if there's no schema deployed\n\n\ndef shrink_image(file):\n if file is not None and file.filename != '':\n image_to_shrink = Image.open(file)\n image_to_shrink.thumbnail((300, 300))\n image_to_shrink.save(file.filename)\n image_to_shrink.close()\n image_to_shrink = open(file.filename, 'rb')\n read_image = image_to_shrink.read()\n os.remove(file.filename)\n return read_image\n else:\n return None\n\n\n@app.route('/initdb')\ndef setup_database():\n conn = psycopg2.connect(os.getenv('cartoon_database_url'))\n\n cursor = conn.cursor()\n cursor.execute('''\n CREATE TABLE public.\"ShowPickle\"\n (\n cartoon_pickle_data bytea, \n anime_pickle_data bytea\n )\n with (\n OIDS = FALSE\n );\n ''')\n conn.commit()\n\n\n@app.route('/cartoon_list', methods=['GET',])\ndef cartoon_list():\n load_database()\n cartoon_list_page = open(app.root_path + '/CartoonList.html').read()\n\n def render_Cartoon_template(node):\n node.Cartoon_Attribute.repeat(render_cartoonAtr, Parent_Object.cartoon_dict)\n\n\n\n def render_cartoonAtr(node, cartoonsection):\n\n if Parent_Object.cartoon_dict[cartoonsection].showimage is not None \\\n and Parent_Object.cartoon_dict[cartoonsection].showimage != '':\n data64 = u'data:%s;base64, %s' % (\n 'image/jpg', base64.encodebytes(Parent_Object.cartoon_dict[cartoonsection].showimage).decode('utf8'))\n else:\n data64 = None\n\n node.Cartoon_Title_Attribute.text = Parent_Object.cartoon_dict[cartoonsection].showname\n node.Cartoon_Title_Attribute.atts['href'] = Parent_Object.cartoon_dict[cartoonsection].showlink\n node.Cartoon_Edit_Attribute.atts['href'] = '/cartoon/' + str(Parent_Object.cartoon_dict[cartoonsection].id)\n node.Cartoon_Delete_Attribute.atts['href'] = '/cartoon/' + str(Parent_Object.cartoon_dict[cartoonsection].id) + '/delete'\n node.Cartoon_Logo_Attribute.atts['src'] = data64\n\n cartoon_list_template = Template(cartoon_list_page)\n return cartoon_list_template.render(render_Cartoon_template)\n\n\n@app.route('/anime_list', methods=['GET',])\ndef anime_list():\n load_database()\n anime_list_page = open(app.root_path + \"/AnimeList.html\").read()\n\n\n def render_anime_template(node):\n node.Anime_Attribute.repeat(render_animeAtr, Parent_Object.anime_dict)\n\n def render_animeAtr(node, animesection):\n if Parent_Object.anime_dict[animesection].showimage is not None \\\n and Parent_Object.anime_dict[animesection].showimage != '':\n data64 = u'data:%s;base64, %s' % (\n 'image/jpg', base64.encodebytes(Parent_Object.anime_dict[animesection].showimage).decode('utf8'))\n else:\n data64 = None\n\n node.Anime_Title_Attribute.text = Parent_Object.anime_dict[animesection].showname\n node.Anime_Title_Attribute.atts['href'] = Parent_Object.anime_dict[animesection].showlink\n node.Anime_Edit_Attribute.atts['href'] = '/anime/' + str(Parent_Object.anime_dict[animesection].id)\n node.Anime_Delete_Attribute.atts['href'] = '/anime/' +str(Parent_Object.anime_dict[animesection].id) + '/delete'\n node.Anime_Logo_Attribute.atts['src'] = data64\n\n\n anime_list_template = Template(anime_list_page)\n return anime_list_template.render(render_anime_template)\n\n\n@app.route('/')\ndef send_js(path):\n return send_from_directory('', path)\n\n\n@app.route('/cartoon/', methods=['GET',])\ndef get_cartoon(id):\n global Parent_Object\n load_database()\n\n id_as_uuid = uuid.UUID(id)\n cartoon_object_from_dictionary = Parent_Object.cartoon_dict[id_as_uuid]\n\n if cartoon_object_from_dictionary.showimage is not None\\\n and cartoon_object_from_dictionary.showimage != '':\n data64 = u'data:%s;base64, %s' % (\n 'image/jpg', base64.encodebytes(cartoon_object_from_dictionary.showimage).decode('utf8'))\n else:\n data64 = None\n\n edit_page = open('Cartoon_Edit.html').read()\n\n def render_cartoon(node, cartoon_object):\n node.ActionPathAtr.atts['action'] = '/cartoon/' + str(id_as_uuid) + '/update'\n node.ActionPathAtr.Cartoon_Link_Attribute.atts['value'] = cartoon_object.showlink\n node.ActionPathAtr.Cartoon_Title_Attribute.atts['value'] = cartoon_object.showname\n node.ActionPathAtr.DisplayImgAtr.atts['src'] = data64\n\n cartoon_template = Template(edit_page)\n return cartoon_template.render(render_cartoon, cartoon_object_from_dictionary)\n\n\n@app.route('/anime/', methods=['GET',])\ndef get_anime(id):\n global Parent_Object\n load_database()\n\n id_as_uuid = uuid.UUID(id)\n anime_object_from_dictionary = Parent_Object.anime_dict[id_as_uuid]\n\n if anime_object_from_dictionary.showimage is not None\\\n and anime_object_from_dictionary.showimage != '':\n data64 = u'data:%s;base64, %s' % (\n 'image/jpg', base64.encodebytes(anime_object_from_dictionary.showimage).decode('utf8'))\n\n else:\n data64 = None\n\n edit_page = open('Anime_Edit.html').read()\n\n def render_anime(node, anime_object):\n node.ActionPathAtr.atts['action'] = '/anime/' + str(id_as_uuid) + '/update'\n node.ActionPathAtr.Anime_Link_Attribute.atts['value'] = anime_object.showlink\n node.ActionPathAtr.Anime_Title_Attribute.atts['value'] = anime_object.showname\n node.ActionPathAtr.DisplayImgAtr.atts['src'] = data64\n\n cartoon_template = Template(edit_page)\n return cartoon_template.render(render_anime, anime_object_from_dictionary)\n\n\n@app.route('/cartoon//delete')\ndef delete_cartoon(id):\n global Parent_Object\n load_database()\n id_as_uuid = uuid.UUID(id)\n del Parent_Object.cartoon_dict[id_as_uuid]\n save_database()\n return redirect('/cartoon_list')\n\n\n@app.route('/anime//delete')\ndef delete_anime(id):\n global Parent_Object\n load_database()\n id_as_uuid = uuid.UUID(id)\n del Parent_Object.anime_dict[id_as_uuid]\n save_database()\n return redirect('/anime_list')\n\n\n@app.route('/cartoon//update', methods=['POST',])\ndef update_cartoon(id):\n global Parent_Object\n load_database()\n\n id_as_uuid = uuid.UUID(id)\n\n cartoon_to_update = Parent_Object.cartoon_dict[id_as_uuid]\n\n try:\n file = request.files['Image_Input']\n except:\n file = None\n\n cartoon_to_update.showname = request.form['Cartoon_Title_Input']\n\n if file is not None:\n cartoon_to_update.showimage = shrink_image(file)\n\n cartoon_to_update.showlink = request.form['Cartoon_Link_Input']\n\n Parent_Object.cartoon_dict[id_as_uuid] = cartoon_to_update\n save_database()\n return redirect('/')\n\n\n@app.route('/anime//update', methods=['POST',])\ndef update_anime(id):\n global Parent_Object\n load_database()\n\n id_as_uuid = uuid.UUID(id)\n\n anime_to_update = Parent_Object.anime_dict[id_as_uuid]\n\n try:\n file = request.files['Image_Input']\n except:\n file = None\n\n anime_to_update.showname = request.form['Anime_Title_Input']\n\n if file is not None:\n anime_to_update.showimage = shrink_image(file)\n anime_to_update.showlink=request.form['Anime_Link_Input']\n\n Parent_Object.anime_dict[id_as_uuid] = anime_to_update\n save_database()\n return redirect('/')\n\n\n@app.route('/')\ndef home():\n this_folder = os.path.dirname(os.path.abspath(__file__))\n home_page = os.path.join(this_folder, 'Home.html')\n with open(home_page) as home:\n list_page = open(home_page).read()\n return list_page\n\n\n@app.route('/cartoon/new/', methods=['POST',])\ndef add_cartooon():\n try:\n file = request.files['Image_Input']\n except:\n file = None\n\n # instantiate a new show object and populate it from request.form\n New_Cartoon = cartoon_show_object(\n showname=request.form['Cartoon_Title_Input'],\n showimage=shrink_image(file),\n showlink=request.form['Cartoon_Link_Input'])\n\n Parent_Object.cartoon_dict[New_Cartoon.id] = New_Cartoon\n save_database()\n return redirect('/')\n\n\n@app.route('/cartoon/new/', methods=['GET',])\ndef get_add_cartooon_form():\n\n def render_cartoon_page(node):\n node.ActionPathAtr.atts['action'] = '/cartoon/new/'\n\n this_folder = os.path.dirname(os.path.abspath(__file__))\n add_cartoon_page = os.path.join(this_folder, 'Cartoon_Edit.html')\n cartoon_template = Template(open(add_cartoon_page).read())\n return cartoon_template.render(render_cartoon_page)\n #return open(add_cartoon_page).read()\n\n\n@app.route('/anime/new/', methods=['GET',])\ndef get_add_anime_form():\n\n def render_anime_page(node):\n node.ActionPathAtr.atts['action'] = '/anime/new/'\n\n this_folder = os.path.dirname(os.path.abspath(__file__))\n add_anime_page = os.path.join(this_folder, 'Anime_Edit.html')\n anime_template = Template(open(add_anime_page).read())\n return anime_template.render(render_anime_page)\n #return open(add_anime_page).read()\n\n\n@app.route('/anime/new/', methods=['POST',])\ndef add_anime():\n try:\n file = request.files['Image_Input']\n except:\n file = None\n\n # instantiate a new show object and populate it from request.form\n New_Anime = anime_show_object(\n showname=request.form['Anime_Title_Input'],\n showimage=shrink_image(file),\n showlink=request.form['Anime_Link_Input'])\n\n Parent_Object.anime_dict[New_Anime.id] = New_Anime\n save_database()\n return redirect('/')\n\n\n@app.route('/search/', methods=['POST', ])\ndef search():\n load_database()\n search_result_list2 = {}\n\n for animekey, animeitem in Parent_Object.anime_dict.items():\n if animeitem.showname == request.form['searchbox']:\n search_result_list2[animekey] = animeitem\n\n for cartoonkey, cartoonitem in Parent_Object.cartoon_dict.items():\n if cartoonitem.showname == request.form['searchbox']:\n search_result_list2[cartoonkey] = cartoonitem\n\n this_folder = os.path.dirname(os.path.abspath(__file__))\n search_results_page = os.path.join(this_folder, 'Search_Results.html')\n\n def render_anime_template(node):\n node.Anime_Attribute.repeat(render_animeAtr, search_result_list2)\n\n def render_animeAtr(node, animesection):\n if search_result_list2[animesection].showimage is not None \\\n and search_result_list2[animesection].showimage != '':\n data64 = u'data:%s;base64, %s' % (\n 'image/jpg', base64.encodebytes(search_result_list2[animesection].showimage).decode('utf8'))\n else:\n data64 = None\n\n node.Anime_Logo_Attribute.atts['src'] = data64\n node.Anime_Title_Attribute.text = search_result_list2[animesection].showname\n node.Anime_Title_Attribute.atts['href'] = search_result_list2[animesection].showlink\n if type(search_result_list2[animesection]) == anime_show_object:\n node.Anime_Edit_Attribute.atts['href'] = '/anime/' + str(search_result_list2[animesection].id)\n elif type(search_result_list2[animesection]) == cartoon_show_object:\n node.Anime_Edit_Attribute.atts['href'] = '/cartoon/' + str(search_result_list2[animesection].id)\n\n\n search_template = Template(open(search_results_page).read())\n return search_template.render(render_anime_template)\n\n\nif __name__ == '__main__':\n load_database()\n app.run(debug=True)\n","sub_path":"Cartoon-main.py","file_name":"Cartoon-main.py","file_ext":"py","file_size_in_byte":12777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"200262894","text":"# -*- coding:utf-8 -*-\n# @Time:2021/4/13 20:20\n# @Author: explorespace\n# @Email: cyberspacecloner@qq.com\n# @File: model.py\n# software: PyCharm\n\nfrom tensorflow.keras import layers, models, Model, Sequential\n\n\ndef VGG(feature, im_height=224, im_width=224, num_classes=1000):\n # tensorflow 中 tensor 通道顺序为:N H W C\n input_image = layers.Input(shape=(im_height, im_width, 3), dtype=\"float32\")\n x = feature(input_image)\n x = layers.Flatten()(x)\n x = layers.Dropout(rate=0.5)(x)\n x = layers.Dense(2048, activation='relu')(x)\n x = layers.Dropout(rate=0.5)(x)\n x = layers.Dense(2048, activation='relu')(x)\n x = layers.Dense(num_classes)(x)\n output = layers.Softmax()(x)\n model = models.Model(inputs=input_image, outputs=output)\n return model\n\n\ndef features(cfg):\n feature_layers = []\n for v in cfg:\n if v == 'M':\n feature_layers.append(layers.MaxPool2D(pool_size=2, strides=2))\n else:\n conv2d = layers.Conv2D(v, kernel_size=3, padding='SAME', activation='relu')\n feature_layers.append(conv2d)\n return Sequential(feature_layers, name='feature')\n\n\ncfgs = {\n 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\ndef vgg(model_name='vgg16', **kwargs):\n assert model_name in cfgs.keys(), \"not support model {}\".format(model_name)\n cfg = cfgs[model_name]\n model = VGG(features(cfg), **kwargs)\n\n return model","sub_path":"CV/tf/VGG/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"174912693","text":"\"\"\"\nContains various utility functions for PyTorch model training and saving.\n\"\"\"\nimport torch\nfrom pathlib import Path\nfrom torch.utils.tensorboard import SummaryWriter\n\ndef save_model(model: torch.nn.Module,\n target_dir: str,\n model_name: str):\n \"\"\"Saves a PyTorch model to a target directory.\n\n Args:\n model: A target PyTorch model to save.\n target_dir: A directory for saving the model to.\n model_name: A filename for the saved model. Should include\n either \".pth\" or \".pt\" as the file extension.\n\n Example usage:\n save_model(model=model_0,\n target_dir=\"models\",\n model_name=\"05_going_modular_tingvgg_model.pth\")\n \"\"\"\n # Create target directory\n target_dir_path = Path(target_dir)\n target_dir_path.mkdir(parents=True,\n exist_ok=True)\n\n # Create model save path\n assert model_name.endswith(\".pth\") or model_name.endswith(\".pt\"), \"model_name should end with '.pt' or '.pth'\"\n model_save_path = target_dir_path / model_name\n\n # Save the model state_dict()\n print(f\"[INFO] Saving model to: {model_save_path}\")\n torch.save(obj=model.state_dict(),\n f=model_save_path)\n\ndef create_writer(experiment_name: str, \n model_name: str, \n extra: str=None) -> torch.utils.tensorboard.writer.SummaryWriter():\n \"\"\"Creates a torch.utils.tensorboard.writer.SummaryWriter() instance saving to a specific log_dir.\n\n log_dir is a combination of runs/timestamp/experiment_name/model_name/extra.\n\n Where timestamp is the current date in YYYY-MM-DD format.\n\n Args:\n experiment_name (str): Name of experiment.\n model_name (str): Name of model.\n extra (str, optional): Anything extra to add to the directory. Defaults to None.\n\n Returns:\n torch.utils.tensorboard.writer.SummaryWriter(): Instance of a writer saving to log_dir.\n\n Example usage:\n # Create a writer saving to \"runs/2022-06-04/data_10_percent/effnetb2/5_epochs/\"\n writer = create_writer(experiment_name=\"data_10_percent\",\n model_name=\"effnetb2\",\n extra=\"5_epochs\")\n # The above is the same as:\n writer = SummaryWriter(log_dir=\"runs/2022-06-04/data_10_percent/effnetb2/5_epochs/\")\n \"\"\"\n from datetime import datetime\n import os\n\n # Get timestamp of current date (all experiments on certain day live in same folder)\n timestamp = datetime.now().strftime(\"%Y-%m-%d\") # returns current date in YYYY-MM-DD format\n\n if extra:\n # Create log directory path\n log_dir = os.path.join(\"runs\", timestamp, experiment_name, model_name, extra)\n else:\n log_dir = os.path.join(\"runs\", timestamp, experiment_name, model_name)\n \n print(f\"[INFO] Created SummaryWriter, saving to: {log_dir}...\")\n return SummaryWriter(log_dir=log_dir)\n","sub_path":"ds_utils/pytorch_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"559963897","text":"import json\nimport csv\nimport re\nfrom bs4 import BeautifulSoup\nimport lxml.html\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\ndrugFiles = ['drug-label-0001-of-0006.json']##,'drug-label-0002-of-0006.json','drug-label-0002-of-0006.json','drug-label-0004-of-0006.json','drug-label-0005-of-0006.json','drug-label-0006-of-0006.json',]\n\t\t\nbody_system = ['Gastrointestinal','Central Nervous System', 'Gastrointestinal System','Cardiovascular System','Psychiatric and Paradoxical Reactions','Urogenital System','Skin and Appendages']\nproduct_data_array = []\nprod_dic_by_company = {}\ncompany_keys = prod_dic_by_company.keys()\nndc_keys = []\nunique_keys = {}\nmed_by_pharma = {}\ndrug_mono_array = []\ndrug_mono_dict = {}\n\nhtml_template_string = '\\nFDA Monographs\\n\\n\\nFDA Monograph list
'\n\nclass ProductSummary:\n\tdef __init__(self,prod_items):\n\t\tself.product_items = prod_items\n\t\tself.isValid = 'NO'\n\t\tif(len(self.product_items) > 0):\n\t\t\tself.isValid = 'YES'\n\t\t\tself.productID = self.product_items[0]\n\t\t\tself.companyID = self.productID.split('_')[1]\n\t\t\tself.productNDC = self.product_items[1]\n\t\t\tself.productTypeName = self.product_items[2]\n\t\t\tself.productProprietary = self.product_items[3]\n\t\t\tself.productProprietarySuffix = self.product_items[4]\n\t\t\tself.productNonProprietaryName = self.product_items[5]\n\t\t\t##added\n\t\t\tself.productDosageFormName = self.product_items[6]\n\t\t\t##added\n\t\t\tself.productRouteName = self.product_items[7]\n\t\t\t##added\n\t\t\tself.productLabelerName= self.product_items[12]\n\t\t\tself.productStartMarketingDate = self.product_items[8]\n\t\t\tself.productEndMarketingDate = self.product_items[9]\n\t\t\tself.productMarketingCategoryName= self.product_items[10]\n\t\t\tself.productApplicationNumber = self.product_items[11]\n\t\t\tself.productSubstanceName = self.product_items[13]\n\t\t\tself.productActiveNumeratorStrength = self.product_items[14]\n\t\t\tself.productActiveIngredientUnit = self.product_items[15]\n\t\t\tself.productPharmClasses = self.product_items[16]\n\n\t\t##DEASCHEDULE\n\t\t\nclass DrugMonograph:\n\tdef __init__(self,drug_info):\n\t\t\n\t\t\n\t\tdrug_keys= drug_info.keys()\n\t\tdrug_fda = drug_info['openfda']\n\t\tself.id = drug_info['id']\n\n\t\tdrug_monograph = drug_fda\n\t\tif len(drug_keys) < 5:\n\t\t\tprint(str(drug_monograph))\n\n\t\tself.product_ndc = 'No PRODUCT NDC'\n\t\tself.rxcui = 'No RXCUI'\n\t\tself.spl_id = 'No SPL id'\n\t\tself.spl_set_id = 'No SPL set id'\t\t\n\t\tself.product_id = 'No product_id'\n\t\tself.generic_name = 'No generic'\n\t\tself.brand_name = 'No brand name'\n\t\tself.pharm_class = 'No Pharma' \n\t\tself.pharm_class_pe = 'No Pharma PE'\n\t\tself.product_type = 'No Product Type'\n\t\tself.manufacturer_name = 'No Mfr'\n\t\tself.brand_name = 'No Brand Name'\n\t\tself.route = 'No Route'\n\t\tself.precautions = 'No Precautions'\n\t\tself.how_supplied = 'No supplied'\n\t\tself.contraindications = 'No contraindications'\n\t\tself.description = 'No description'\n\t\tself.indications_usage = 'No indications usage'\n\t\tself.patientInfo = 'No patient info'\n\t\tself.warnings = 'No warnings'\n\t\tself.mechanism = 'No mechanism'\n\t\tself.pharmacology = 'No pharmacology'\n\t\tself.boxedWarning = 'No warning'\n\t\tself.pharmacokinetics = 'No pharmacokinetics'\n\t\tself.pregnancy = 'No preggers'\n\t\tself.labor_delivery = 'No labor delivery'\n\t\tself.fertility = 'No fertility'\n\t\tself.adverse_reactions = 'No adverse'\n\n\t\tself.dosage_admin = []\n\t\tself.adverse_reactions_table = []\n\t\tself.drug_interactions = []\n\t\tself.pharmacokinetics_table = []\n\t\tself.manufacturers = []\n\t\tself.routes = []\n\n\t\tif 'product_ndc' in drug_fda:\n\t\t\tself.product_ndc = drug_fda['product_ndc'][0]\n\t\tif 'rxcui' in drug_fda:\n\t\t\tself.rxcui = drug_fda['rxcui'][0]\n\t\tif 'spl_id' in drug_fda:\n\t\t\tself.spl_id = drug_fda['spl_id'][0]\n\t\tif 'spl_set_id' in drug_fda:\n\t\t\tself.spl_set_id = drug_fda['spl_set_id'][0]\n\n\n\t\tif 'generic_name' in drug_fda or 'brand_name' in drug_fda:\n\t\t\tif 'generic_name' in drug_fda:\n\t\t\t\tgeneric_string = drug_monograph['generic_name'][0]\n\t\t\t\tself.generic_name = generic_string\n\t\t\telse: \n\t\t\t\tself.generic_name = 'No Generic Name'\n\n\t\t\tif 'brand_name' in drug_fda:\n\t\t\t\tself.brand_name = drug_fda['brand_name'][0]\n\n\t\t\tif 'pharm_class_epc' in drug_fda:\n\t\t\t\tself.pharm_class = drug_fda['pharm_class_epc'][0]\n\t\t\tif 'pharm_class_pe' in drug_fda:\n\t\t\t\tself.pharm_class_pe = drug_fda['pharm_class_pe'][0]\t\n\t\t\tif 'manufacturer_name' in drug_fda:\n\t\t\t\tself.manufacturer_name = drug_fda['manufacturer_name'][0]\t\n\t\t\tif 'product_type' in drug_fda:\n\t\t\t\tself.product_type = drug_fda['product_type'][0]\n\t\t\tif 'indications_and_usage' in drug_keys:\n\t\t\t\tself.indications_usage = drug_info['indications_and_usage'][0]\n\t\t\tif 'contraindications' in drug_keys:\n\t\t\t\tself.contraindications = drug_info['contraindications'][0]\n\t\t\tif 'precautions' in drug_keys:\n\t\t\t\tself.precautions = drug_info['precautions'][0]\n\t\t\tif 'description' in drug_keys:\n\t\t\t\tself.description = drug_info['description'][0]\n\t\t\tif 'how_supplied' in drug_keys:\n\t\t\t\tself.how_supplied = drug_info['how_supplied'][0]\n\n\n\t\t\tif 'information_for_patients' in drug_keys:\n\t\t\t\tself.patientInfo = drug_info['information_for_patients'][0]\n\t\t\tif 'warnings' in drug_keys:\n\t\t\t\tself.warnings = drug_info['warnings'][0]\n\t\t\tif 'pregnancy' in drug_keys:\n\t\t\t\tself.pregnancy = drug_info['pregnancy'][0]\n\t\t\tif 'labor_and_delivery' in drug_keys:\n\t\t\t\tself.labor_delivery = drug_info['labor_and_delivery'][0]\n\t\t\tif 'carcinogenesis_and_mutagenesis_and_impairment_of_fertility' in drug_keys:\n\t\t\t\tself.fertility = drug_info['carcinogenesis_and_mutagenesis_and_impairment_of_fertility'][0]\n\t\t\tif 'boxed_warning' in drug_keys:\n\t\t\t\tself.boxedWarning = drug_info['boxed_warning'][0]\t\n\t\t\tif 'route' in drug_fda:\n\t\t\t\tself.route = drug_fda['route'][0]\n\n\t\t\tif 'package_label_principal_display_panel' in drug_keys:\n\t\t\t\tself.package_label_display = drug_info['package_label_principal_display_panel'][0]\n\t\t\tif 'mechanism_of_action' in drug_keys:\n\t\t\t\tself.mechanism = drug_info['mechanism_of_action'][0]\n\t\t\tif 'clinical_pharmacology' in drug_keys:\n\t\t\t\tself.pharmacology = drug_info['clinical_pharmacology'][0]\n\t\t\tif 'pharmacokinetics' in drug_keys:\n\t\t\t\tself.pharmacokinetics = drug_info['pharmacokinetics'][0]\n\n\t\t\tif 'adverse_reactions' in drug_keys:\n\t\t\t\tself.adverse_reactions = drug_info['adverse_reactions'][0]\n\n\t\t\t## Arrays\n\t\t\t##-----------------------------------\n\t\t\tif 'dosage_and_administration_table' in drug_keys:\n\t\t\t\tself.dosage_admin = drug_info['dosage_and_administration_table']\n\t\t\tif 'adverse_reactions_table' in drug_keys:\n\t\t\t\tself.adverse_reactions_table = drug_info['adverse_reactions_table']\n\t\t\tif 'drug_interactions' in drug_keys:\n\t\t\t\tself.drug_interactions = drug_info['drug_interactions']\n\t\t\tif 'pharmacokinetic_table' in drug_keys:\n\t\t\t\tself.pharmacokinetics_table = drug_info['pharmacokinetics_table']\n\ndef checkMultipleArrayVal(drug_dic):\n\tdict_keys = drug_dic.keys()\n\tfor key in dict_keys:\n\t\tif type(drug_dic[key]) is list:\n\t\t\tif len(drug_dic[key]) > 1:\n\t\t\t\tprint('List contains multiple items')\n\ndef regexTableData(parse_text):\n\tfor text_parse in parse_text:\n\t\ttext_clean_1 = re.sub(r'<[A-Z,a-z,0-9\\s]+\\/>','####\\n',text_parse)\n\t\ttext_clean_2 = re.sub(r'<[A-Z,a-z,0-9\\s]+ \\= [A-Z,a-z,0-9\\\"]+>','####\\n',text_clean_1)\n\t\ttext_clean_3 = re.sub(r'<[A-Z,a-z,0-9\\s\\=]+>','####\\n',text_clean_2)\n\n\t\treturn text_clean_3\n\ndef write_med_mono(outfile, drug_mono, product):\n\toutfile.write('--------------------------------------------------------------\\n')\n\toutfile.write('******' + drug_mono.boxedWarning+'\\n')\n\toutfile.write('Drug ID: ' + drug_mono.id+ ', NDC: ' + drug_mono.product_ndc + '\\n')\n\toutfile.write(drug_mono.generic_name + '(' + drug_mono.brand_name + ')' '\\n' + 'Pharm class: ' + drug_mono.pharm_class + '\\n')\n\toutfile.write(product.productLabelerName + '(' + drug_mono.manufacturer_name + ')\\n')\n\toutfile.write(product.productDosageFormName + '\\nActive: ' + product.productActiveNumeratorStrength + '(' + product.productActiveIngredientUnit + ')\\n' + 'Route: ' + product.productRouteName + '\\n')\n\toutfile.write(drug_mono.how_supplied + '\\n')\n\toutfile.write(drug_mono.description + '\\n')\n\n\tindications = drug_mono.indications_usage.split('.')\n\tfor indication in indications:\n\t\toutfile.write(indication+'**')\n\toutfile.write(drug_mono.indications_usage + '\\n')\n\tprecautions = drug_mono.precautions.split(',')\n\tfor precaution in precautions:\n\t\toutfile.write(precaution+'**')\n\n\toutfile.write(drug_mono.precautions+'\\n')\n\toutfile.write(drug_mono.contraindications+'\\n')\n\toutfile.write(drug_mono.warnings+'\\n')\n\toutfile.write(drug_mono.patientInfo+'\\n')\n\toutfile.write(drug_mono.pregnancy+'\\n')\n\toutfile.write(drug_mono.labor_delivery+'\\n')\n\t\n\tif len(drug_mono.adverse_reactions) == 0:\n\t\toutfile.write('ADVERSE: 0\\n')\n\telse:\n\t\tfor reaction in drug_mono.adverse_reactions:\n\t\t\treaction_clean = re.sub(r'<[A-Z,a-z,0-9\\s]+\\/>','####\\n',reaction)\n\t\t\treaction_clean2 = re.sub(r'<[A-Z,a-z,0-9\\s\\\"]+ \\= [A-Z,a-z,0-9\\\"\\/]*>','####\\n',reaction_clean)\n\t\t\treaction_clean3 = re.sub(r'<[A-Z,a-z,0-9\\s\\=]+>', '####\\n', reaction)\n\t\t\treaction_clean4 = re.sub(r'<\\/[A-Z,a-z,0-9]>','****\\n',reaction_clean3)\n\t\t\treaction_clean5 = re.sub(r'<[A-Z,a-z,0-9\\s]+[A-Z,a-z,0-9]+\\=\\\"[A-Z,a-z,0-9]+\\\">','#*#*#*',reaction_clean4)\n\t\t\toutfile.write('ADVERSE:\\n ' + soup.prettify())\n\n\t\t\tsoup = BeautifulSoup(reaction,'xml')\n\t\t\ttable_tags = soup.find('table')\n\t\t\ttable_caption = table_tags.find('caption')\n\t\t\tif table_caption != None:\n\t\t\t\tprint (table_caption[0])\n\t\t\ttable_rows = table_tags.find_all('tr')\n\t\t\tprint('rows: ' + str(len(table_rows)))\n\n\t\t\tfor tableRow in table_rows:\n\t\t\t\ttableItem = tableRow.find_all('td')\n\t\t\t\tfor element in tableItem:\n\t\t\t\t\tif len(element) > 0:\n\t\t\t\t\t\titem = element.contents[0]\n\t\t\t\t\t\t##print (item)\n\n\t\t\ttable_items = table_row.find_all('td')\n\t\t\tprint('table items: ' + str(len(table_items)))\n\n\tif len(drug_mono.dosage_admin) == 0:\n\t\toutfile.write('DOSE ADMIN: 0\\n')\n\telse:\n\t\tfor doseAdmin in drug_mono.dosage_admin:\n\t\t\tcleanDose = regexTableData(doseAdmin)\n\t\t\t##outfile.write('DOSE: \\n' + cleanDose+'\\n')\n\n\tif len(drug_mono.drug_interactions) == 0:\n\t\toutfile.write('INTERACTIONS : 0 \\n')\n\telse:\n\t\tfor interactions in drug_mono.drug_interactions:\n\t\t\tre.sub('<[a-z, A-Z, 0-9]+>', '!!\\n!!', interactions)\n\t\t\toutfile.write('INTERACTIONS: \\n' +interactions+'\\n')\n\t\t\ndef read_product_data():\n\twith open('product.txt',encoding='ISO-8859-1') as csvDataFile:\n\t\tcsvReader = csv.reader(csvDataFile,delimiter='\\t')\n\t\trowCount = 0\n\t\tfor row in csvReader:\n\t\t\trowCount = rowCount + 1\n\t\t\tif len(row) < 16:\n\t\t\t\tprint('Less than 16')\n\t\t\t\tprint(str(rowCount))\n\t\t\telif len(row) < 15:\n\t\t\t\tprint('Less than 15')\n\t\t\t\tprint(str(rowCount))\n\t\t\tproduct_info = ProductSummary(row)\n\t\t\tif product_info.isValid == 'YES':\n\t\t\t\tproduct_data_array.append(product_info)\n\ndef write_html_detail_monograph(generic_med_name, monograph, toc_file):\n\tif len(monograph.generic_name) < 60:\n\t\t\tgeneric_name_init = re.sub(r'\\s+','',monograph.generic_name)\n\t\t\tgeneric_name = re.sub(r'\\/','',generic_name_init)\n\t\t\tdrug_filename = generic_name + '.html'\n\t\t\ttoc_file.write('Full monograph
\\n')\n\n\t\t\tdrug_file = open('./drugList/'+drug_filename,'w')\n\t\t\tif monograph.boxedWarning != 'No warning':\n\t\t\t\tdrug_file.write('BOXED WARNING
\\n' + monograph.boxedWarning)\n\t\t\t\n\t\t\tdrugName = '
' + generic_med_name + ' (' + monograph.brand_name + ')
'\n\t\t\tdrugIDinfo = 'SPL'+monograph.spl_id+'
\\nNDC:'+monograph.product_ndc+'
\\nRXCUI'+monograph.rxcui+'
'\n\t\t\tdrugPharma = '
' + monograph.pharm_class + ' -- ' + monograph.pharm_class_pe +'
\\n'\n\t\t\tdrug_file.write('Route: ' + monograph.route + '
')\n\t\t\tdrug_file.write(drugName)\n\t\t\tdrug_file.write(drugIDinfo)\n\t\t\tdrug_file.write(drugPharma)\n\t\t\tdrug_file.write('How supplied
\\n' + monograph.how_supplied)\n\t\t\tdrug_file.write('Indications and Usage
\\n' + monograph.indications_usage)\n\t\t\tdrug_file.write('Description
\\n' + monograph.description)\n\t\t\tdrug_file.write('Contraindications
\\n' + monograph.contraindications)\n\t\t\tdrug_file.write('Precautions
\\n' + monograph.precautions)\n\t\t\tdrug_file.write('Warnings
\\n' + monograph.warnings)\n\n\t\t\tdrug_file.write('Dosage Admin
')\n\t\t\tif len(monograph.dosage_admin) > 0:\n\t\t\t\tfor dose in monograph.dosage_admin:\n\t\t\t\t\tdrug_file.write(dose+'
\\n')\n\n\t\t\tdrug_file.write('Adverse Reactions
')\n\t\t\tdrug_file.write(monograph.adverse_reactions)\n\t\t\tif len(monograph.adverse_reactions) > 0:\n\n\n\t\t\t\tgastrointestinal_re = re.compile(r'Gastrointestinal (:)*', re.UNICODE)\n\n\t\t\t\tfor adverse in monograph.adverse_reactions_table:\n\t\t\t\t\tmatch = re.search('Gastrointestinal (:)*',adverse)\n\t\t\t\t\tif match != None:\n\t\t\t\t\t\tprint (generic_name + ' ' + str(match) + \"-->\" + adverse)\n\t\t\t\t\tgastrointestinal_re.sub(r'Gastrointestinal:
',adverse)\n\t\t\t\t\tre.sub(r'Central Nervous System:','
Central Nervous System:
',adverse)\n\t\t\t\t\tre.sub(r'Cardiovascular:','
Cardiovascular:
',adverse)\n\t\t\t\t\tre.sub(r'Skin:','
Skin:
',adverse)\n\t\t\t\t\tsubpoints = re.split(r'(\\d+\\.\\d+)',adverse)\n\t\t\t\t\tif subpoints != None:\n\t\t\t\t\t\tdrug_file.write('
\\n
\\n')\n\t\t\t\t\t\tfor point in subpoints:\n\t\t\t\t\t\t\tdrug_file.write('- ' + point + '
')\n\t\t\t\t\t\tdrug_file.write('
Gastrointestinal:
',adverse)\n\t\t\t\t\t\tre.sub(r'Central Nervous System:','Central Nervous System:
',adverse)\n\t\t\t\t\t\tre.sub(r'Cardiovascular:','
Cardiovascular:
',adverse)\n\t\t\t\t\t\tre.sub(r'Skin:','
Skin:
',adverse)\n\t\t\t\t\t\tdrug_file.write(adverse +'
\\n')\n\n\t\t\tdrug_file.write('
Drug Interactions
')\n\t\t\tif len(monograph.drug_interactions) > 0:\n\t\t\t\tfor interaction in monograph.drug_interactions:\n\t\t\t\t\tsubpoints = re.split(r'(\\d+\\.\\d+\\s)',interaction)\n\t\t\t\t\tif subpoints != None:\n\t\t\t\t\t\tdrug_file.write('\\n