diff --git "a/863.jsonl" "b/863.jsonl" new file mode 100644--- /dev/null +++ "b/863.jsonl" @@ -0,0 +1,732 @@ +{"seq_id":"209734693","text":"\"\"\"\nUser queries\n\"\"\"\n\nfrom typing import Generator, List, Optional, Union\nimport warnings\n\nfrom typeguard import typechecked\n\n\nfrom ...helpers import Compatible, format_result, fragment_builder\nfrom .queries import gql_users, GQL_USERS_COUNT\nfrom ...types import User\nfrom ...utils import row_generator_from_paginated_calls\n\n\nclass QueriesUser:\n \"\"\"\n Set of User queries\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n\n def __init__(self, auth):\n \"\"\"\n Initializes the subclass\n\n Parameters\n ----------\n auth : KiliAuth object\n \"\"\"\n self.auth = auth\n\n # pylint: disable=dangerous-default-value\n @Compatible(['v1', 'v2'])\n @typechecked\n def users(self,\n api_key: Optional[str] = None,\n email: Optional[str] = None,\n organization_id: Optional[str] = None,\n fields: List[str] = ['email', 'id', 'firstname', 'lastname'],\n first: int = 100,\n skip: int = 0,\n disable_tqdm: bool = False,\n as_generator: bool = False) -> Union[List[dict], Generator[dict, None, None]]:\n # pylint: disable=line-too-long\n \"\"\"\n Gets a generator or a list of users given a set of criteria\n\n Parameters\n ----------\n api_key :\n Query an user by its API KEY\n email :\n Email of the user\n organization_id :\n Identifier of the user's organization\n fields :\n All the fields to request among the possible fields for the users.\n See [the documentation](https://cloud.kili-technology.com/docs/python-graphql-api/graphql-api/#user) for all possible fields.\n first :\n Maximum number of users to return.\n skip :\n Number of skipped users (they are ordered by creation date)\n disable_tqdm :\n If True, the progress bar will be disabled\n as_generator:\n If True, a generator on the users is returned.\n\n Returns\n -------\n dict\n a result object which contains the query if it was successful, or an error message else.\n\n Examples\n -------\n ```\n # List all users in my organization\n >>> organization = kili.organizations()\n >>> organization_id = organizations[0]['id]\n >>> kili.users(organization_id=organization_id)\n ```\n \"\"\"\n if as_generator is False:\n warnings.warn(\"From 2022-05-18, the default return type will be a generator. Currently, the default return type is a list. \\n\"\n \"If you want to force the query return to be a list, you can already call this method with the argument as_generator=False\",\n DeprecationWarning)\n\n count_args = {\"organization_id\": organization_id}\n disable_tqdm = disable_tqdm or as_generator or (\n api_key or email) is not None\n payload_query = {\n 'where': {\n 'apiKey': api_key,\n 'email': email,\n 'organization': {\n 'id': organization_id,\n }\n }\n }\n\n users_generator = row_generator_from_paginated_calls(\n skip,\n first,\n self.count_users,\n count_args,\n self._query_users,\n payload_query,\n fields,\n disable_tqdm\n )\n\n if as_generator:\n return users_generator\n return list(users_generator)\n\n def _query_users(self,\n skip: int,\n first: int,\n payload: dict,\n fields: List[str]):\n\n payload.update({'skip': skip, 'first': first})\n _gql_users = gql_users(fragment_builder(fields, User))\n result = self.auth.client.execute(_gql_users, payload)\n return format_result('data', result)\n\n @Compatible(['v1', 'v2'])\n @typechecked\n def count_users(self,\n organization_id: Optional[str] = None) -> int:\n \"\"\"\n Get user count based on a set of constraints\n\n Parameters\n ----------\n organization_id :\n Identifier of the user's organization\n\n Returns\n -------\n dict\n the count of users whose organization ID matches the given ID\n \"\"\"\n variables = {\n 'where': {\n 'organization': {\n 'id': organization_id,\n }\n }\n }\n result = self.auth.client.execute(GQL_USERS_COUNT, variables)\n return format_result('data', result)\n","sub_path":"kili/queries/user/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"535317750","text":"# Copyright (c) 2014, Djaodjin Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport re\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.test.client import Client, RequestFactory\n\nfrom signup import settings as signup_settings\nfrom signup.auth import validate_redirect, validate_redirect_url\nfrom signup.models import ActivatedUser\n\nREGISTRATION_EMAIL = 'user@example.com'\n\n\nclass SignUpTests(TestCase):\n \"\"\"\n Tests signup functionality.\n \"\"\"\n\n def setUp(self):\n # By default it will end-up being '*' which breaks multitier tests.\n settings.ALLOWED_HOSTS = ('localhost',)\n # Every test needs access to the request factory.\n self.factory = RequestFactory()\n\n def test_redirect_ok(self):\n \"\"\"\n Tests to validate the redirect URL.\n \"\"\"\n request = self.factory.get('/?next=/example/')\n url = validate_redirect(request)\n self.assertTrue(url == \"/example/\")\n\n def test_redirect_fail1(self):\n \"\"\"\n Tests to validate the redirect URL.\n \"\"\"\n request = self.factory.get('/?next=http://example.com/example/')\n url = validate_redirect(request)\n if '*' in settings.ALLOWED_HOSTS:\n self.assertTrue(url == \"/example/\")\n else:\n self.assertTrue(url is None)\n\n def test_redirect_url_ok(self):\n \"\"\"\n Tests to validate the redirect URL.\n \"\"\"\n url = validate_redirect_url(\"/example/\")\n self.assertTrue(url == \"/example/\")\n\n def test_redirect_url_fail1(self):\n \"\"\"\n Tests to validate the redirect URL.\n \"\"\"\n url = validate_redirect_url(\"http://example.com/example/\")\n if '*' in settings.ALLOWED_HOSTS:\n self.assertTrue(url == \"/example/\")\n else:\n self.assertTrue(url is None)\n\n def test_activate_password(self):\n user = ActivatedUser.objects.create_inactive_user(REGISTRATION_EMAIL)\n client = Client()\n response = client.get(reverse('registration_activate',\n args=(user.email_verification_key,)),\n follow=True)\n # pylint: disable=maybe-no-member\n self.assertTrue(response.status_code == 200)\n self.assertTrue(re.match(\n r'\\S+/accounts/activate/(?P%s)/password/(?P.+)/$'\n % signup_settings.EMAIL_VERIFICATION_PAT,\n response.redirect_chain[-1][0]))\n\n def test_register(self):\n client = Client()\n response = client.post(reverse('registration_register'),\n {'full_name': 'John Smith', 'email': REGISTRATION_EMAIL},\n follow=True)\n # XXX Haven't found out how to get this assertion to pass,\n # status_code 302 vs 200 expected.\n # self.assertRedirects(response, settings.LOGIN_REDIRECT_URL)\n self.assertTrue(re.match(r'\\S+/app/[\\w.@+-]+/',\n response.redirect_chain[-1][0]))\n","sub_path":"signup/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"57515345","text":"import sys\nimport os\nimport urllib\nimport uuid\nimport logging\nimport requests\nimport datetime\nimport json\nimport base64\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom flask import request, render_template, redirect, make_response\nfrom flask import jsonify\nfrom flask import Blueprint\n\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\n\nfrom settings import *\n\ndashboard = Blueprint('dashboard', __name__)\nlogging.basicConfig(stream=sys.stderr)\nlogging.getLogger().setLevel(logging.DEBUG)\n\nlog = logging.getLogger()\n\n\n@dashboard.route(\"/\", methods=['GET'])\ndef home():\n token = request.cookies.get('Access-Token')\n if token == None:\n return redirect(LOGIN_PAGE_URL, code=302)\n\n # ---validate user---\n valid_user(token)\n\n # ---get user mail---\n headers = {\"Access-Token\": token, \"API-Token\" : IAM_CLIENT_SECRET}\n response = requests.get(IAM_USER, headers=headers)\n\n if response.status_code != 200:\n return redirect(LOGIN_PAGE_URL, code=302)\n\n name = response.json()['data']['name']\n user_id = response.json()['data']['uid']\n image = response.json()['data']['picture_url']\n\n response = requests.get(TRANSACTIONS_LIST.format(user_id))\n info = response.json()\n\n total_trans = len(info['to_uuid']) + len(info['from_uuid'])\n\n pending = 0\n ratings = 0\n for trans in info['to_uuid']:\n if (trans['state'] != \"COMPLETED\") and (trans['state'] != \"REFUND\"):\n pending += 1\n for trans in info['from_uuid']:\n if (trans['state'] != \"COMPLETED\") and (trans['state'] != \"REFUND\"):\n pending += 1\n\n for trans in info['from_uuid']:\n headers = {\"API-Token\": IAM_CLIENT_SECRET}\n resp = requests.get(IAM_USER + \"?id=\" + trans['to_uuid'], headers=headers)\n if resp.status_code != 200:\n return \"ID not found\", 400\n\n if (trans['state'] == \"COMPLETED\") or (trans['state'] == \"REFUND\"):\n resp_rate = requests.get(RATING_TRANSACTIONS + trans['id'])\n if resp_rate.status_code != 200:\n ratings += 1\n\n response = requests.get(RATING_RATE + user_id)\n info = response.json()\n rating = info['data']['rating_received']\n rating = (rating*5)/100\n log.debug(rating)\n\n return render_template('index.html', name=name, total_trans=total_trans, pending=pending, image=image, rating=round(rating,1), ratings=ratings)\n\n\ndef valid_user(token):\n # ---validate user---\n headers = {\"Access-Token\": token, \"API-Token\" : IAM_CLIENT_SECRET}\n response = requests.post(IAM_VALIDATE, headers=headers)\n\n if response.status_code != 200:\n return redirect(LOGIN_PAGE_URL, code=302)\n","sub_path":"views/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"391765795","text":"\n\n#calss header\nclass _ROTUND():\n\tdef __init__(self,): \n\t\tself.name = \"ROTUND\"\n\t\tself.definitions = [u'(especially of a person) round or rounded in shape']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_rotund.py","file_name":"_rotund.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"294453901","text":"from tkinter import *\nimport os\nfrom PIL import ImageTk, Image\nimport random\nfrom tkinter import messagebox\n\n\n# FRAME 3\n# flat, groove, raised, ridge, solid, or sunken\ndef a_btn(event=\"\"):\n letter = \"A\"\n check(letter)\n\n\ndef b_btn(event=\"\"):\n letter = \"B\"\n check(letter)\n\n\ndef c_btn(event=\"\"):\n letter = \"C\"\n check(letter)\n\n\ndef d_btn(event=\"\"):\n letter = \"D\"\n check(letter)\n\n\ndef e_btn(event=\"\"):\n letter = \"E\"\n check(letter)\n\n\ndef f_btn(event=\"\"):\n letter = \"F\"\n check(letter)\n\n\ndef g_btn(event=\"\"):\n letter = \"G\"\n check(letter)\n\n\ndef h_btn(event=\"\"):\n letter = \"H\"\n check(letter)\n\n\ndef i_btn(event=\"\"):\n letter = \"I\"\n check(letter)\n\n\ndef j_btn(event=\"\"):\n letter = \"J\"\n check(letter)\n\n\ndef k_btn(event=\"\"):\n letter = \"K\"\n check(letter)\n\n\ndef l_btn(event=\"\"):\n letter = \"L\"\n check(letter)\n\n\ndef m_btn(event=\"\"):\n letter = \"M\"\n check(letter)\n\n\ndef n_btn(event=\"\"):\n letter = \"N\"\n check(letter)\n\n\ndef o_btn(event=\"\"):\n letter = \"O\"\n check(letter)\n\n\ndef p_btn(event=\"\"):\n letter = \"P\"\n check(letter)\n\n\ndef q_btn(event=\"\"):\n letter = \"Q\"\n check(letter)\n\n\ndef r_btn(event=\"\"):\n letter = \"R\"\n check(letter)\n\n\ndef s_btn(event=\"\"):\n letter = \"S\"\n check(letter)\n\n\ndef t_btn(event=\"\"):\n letter = \"T\"\n check(letter)\n\n\ndef u_btn(event=\"\"):\n letter = \"U\"\n check(letter)\n\n\ndef v_btn(event=\"\"):\n letter = \"V\"\n check(letter)\n\n\ndef w_btn(event=\"\"):\n letter = \"W\"\n check(letter)\n\n\ndef x_btn(event=\"\"):\n letter = \"X\"\n check(letter)\n\n\ndef y_btn(event=\"\"):\n letter = \"Y\"\n check(letter)\n\n\ndef z_btn(event=\"\"):\n letter = \"Z\"\n check(letter)\n\n\nhint_chance = 2\n\n\ndef hint_btn():\n global hint_chance\n if 0 < hint_chance <= 2:\n reveal_word = random.randint(0, len(letter_into_word) - 1)\n check(letter_into_word[reveal_word])\n hint_chance -= 1\n else:\n messagebox.showerror(\"error\", \"you exceed the hint limit\")\n\n\nanswers = ['ANT', 'BABOON', 'BAT', 'CAMEL', 'DONKEY', 'EAGLE', 'GOOSE', 'HAWK', 'MONKEY', 'MOUSE', 'FISH',\n 'PYTHON', 'PIGEON', 'RHINOCEROS', 'HIPPOPOTAMUS', 'ZEBRA', 'PANDA', 'RAVEN', 'HUMAN', 'OWL', 'SHARK',\n 'PIZZA', 'BURGER', 'SAMOSA', 'BUTTER', 'CHUTNEY', 'NOODLES', 'DOSA',\n 'MANGO', 'BANANA', 'POMEGRANATE', 'PAPAYA', 'WATERMELON', 'MUSKMELON', 'DATES',\n 'MAGNETISM', 'ELECTRICITY']\n\nletter_into_word = [0]\nvariable = [0]\nchance = 1\ntotal_score = 0\n\n\ndef check(press_button):\n global chance, total_score, hangman_image\n if chance <= 6:\n numeric_val = ord(press_button) - 65\n\n try:\n no_of_times = letter_into_word.count(press_button)\n letter_into_word.index(press_button)\n for repeat in range(no_of_times):\n pos = letter_into_word.index(press_button)\n variable[pos].config(text=press_button)\n button_variable_list[numeric_val].config(state=\"disable\", bg=\"green\", fg=\"white\")\n letter_into_word.pop(pos)\n variable.pop(pos)\n\n if not letter_into_word:\n messagebox.showinfo(\"WIN!!!\", \"You Win!! :-)\")\n total_score += 5\n score.destroy()\n exitbutton.destroy()\n hangman_image_label.destroy()\n frame1.destroy()\n frame2.destroy()\n frame3.destroy()\n letter_into_word.clear()\n button_variable_list.clear()\n variable.clear()\n main()\n chance = 1\n\n except:\n chance += 1\n button_variable_list[numeric_val].config(state=\"disable\", bg=\"red\", fg=\"white\")\n hangman_imagelocation = os.path.abspath(f'hangman_visual\\\\{chance}.png')\n hangman_image_open = Image.open(hangman_imagelocation)\n hangman_image_resize = hangman_image_open.resize((300, 300))\n hangman_image = ImageTk.PhotoImage(hangman_image_resize)\n hangman_image_label.config(image=hangman_image)\n\n else:\n messagebox.showerror(\"LIMIT EXCEED\", \"you exceed the limit computer win the game\")\n\n score.destroy()\n exitbutton.destroy()\n hangman_image_label.destroy()\n frame1.destroy()\n frame2.destroy()\n frame3.destroy()\n chance = 1\n letter_into_word.clear()\n button_variable_list.clear()\n variable.clear()\n main()\n\n\ndef main_word():\n global hint_chance\n word_pos = random.randint(0, len(answers) - 1)\n words = answers[word_pos]\n hint_chance = 2\n\n letter_into_word.clear()\n variable.clear()\n\n for word in words:\n letter_into_word.append(word)\n\n for_column_start_pos = round((12 - len(letter_into_word)) / 2)\n for position in range(len(letter_into_word)):\n variable.append(chr(random.randint(65, 91)))\n variable[position] = Label(frame3, relief=\"solid\", width=8, bd=4)\n variable[position].grid(row=0, column=for_column_start_pos + position, ipady=5, pady=10)\n\n\ndef main():\n def frames():\n global frame1, frame2, frame3, left_side, right_side\n frame1 = Frame(root, bg=\"red\")\n frame1.pack()\n left_side = Frame(frame1, bg=\"red\")\n left_side.pack(side=LEFT, ipadx=128)\n right_side = Frame(frame1, bg=\"red\")\n right_side.pack(side=LEFT)\n frame2 = Frame(root)\n frame2.pack()\n frame3 = Frame(root, bg=\"white\")\n frame3.pack(pady=15)\n\n global score, exitbutton, hangman_image_label\n\n frames()\n main_word()\n # FRAME 1\n score = Label(left_side, text=f\"Score : {total_score}\", width=10)\n score.pack(padx=30, side=\"left\", ipady=5)\n\n billlogin_btn_image_location = os.path.abspath('hangman_visual\\\\Hangman.png')\n billlogin_btn_opened_image = Image.open(billlogin_btn_image_location)\n billlogin_btn_resize_image = billlogin_btn_opened_image.resize((400, 100))\n global bill_login_image\n bill_login_image = ImageTk.PhotoImage(billlogin_btn_resize_image)\n score = Label(left_side, image=bill_login_image, bg=\"white\")\n score.pack(ipadx=60, pady=10)\n\n exitbutton = Button(right_side, text=\"Exit\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=exit)\n exitbutton.pack(side=\"right\", ipady=5, padx=15)\n # FRAME 2\n hangman_imagelocation = os.path.abspath('hangman_visual\\\\1.png')\n hangman_image_open = Image.open(hangman_imagelocation)\n hangman_image_resize = hangman_image_open.resize((300, 300))\n global hangman_image\n hangman_image = ImageTk.PhotoImage(hangman_image_resize)\n hangman_image_label = Label(frame2, image=hangman_image)\n hangman_image_label.pack()\n\n a_button = Button(frame3, text=\"A\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=a_btn)\n a_button.grid(row=1, column=0, ipady=5)\n button_variable_list.append(a_button)\n b_button = Button(frame3, text=\"B\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=b_btn)\n b_button.grid(row=1, column=1, ipady=5)\n button_variable_list.append(b_button)\n c_button = Button(frame3, text=\"C\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=c_btn)\n c_button.grid(row=1, column=2, ipady=5)\n button_variable_list.append(c_button)\n d_button = Button(frame3, text=\"D\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=d_btn)\n d_button.grid(row=1, column=3, ipady=5)\n button_variable_list.append(d_button)\n e_button = Button(frame3, text=\"E\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=e_btn)\n e_button.grid(row=1, column=4, ipady=5)\n button_variable_list.append(e_button)\n f_button = Button(frame3, text=\"F\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=f_btn)\n f_button.grid(row=1, column=5, ipady=5)\n button_variable_list.append(f_button)\n g_button = Button(frame3, text=\"G\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=g_btn)\n g_button.grid(row=1, column=6, ipady=5)\n button_variable_list.append(g_button)\n h_button = Button(frame3, text=\"H\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=h_btn)\n h_button.grid(row=1, column=7, ipady=5)\n button_variable_list.append(h_button)\n i_button = Button(frame3, text=\"I\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=i_btn)\n i_button.grid(row=1, column=8, ipady=5)\n button_variable_list.append(i_button)\n j_button = Button(frame3, text=\"J\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=j_btn)\n j_button.grid(row=1, column=9, ipady=5)\n button_variable_list.append(j_button)\n k_button = Button(frame3, text=\"K\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=k_btn)\n k_button.grid(row=1, column=10, ipady=5)\n button_variable_list.append(k_button)\n l_button = Button(frame3, text=\"L\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=l_btn)\n l_button.grid(row=1, column=11, ipady=5)\n button_variable_list.append(l_button)\n m_button = Button(frame3, text=\"M\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=m_btn)\n m_button.grid(row=2, column=1, ipady=5)\n button_variable_list.append(m_button)\n n_button = Button(frame3, text=\"N\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=n_btn)\n n_button.grid(row=2, column=2, ipady=5)\n button_variable_list.append(n_button)\n o_button = Button(frame3, text=\"O\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=o_btn)\n o_button.grid(row=2, column=3, ipady=5)\n button_variable_list.append(o_button)\n p_button = Button(frame3, text=\"P\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=p_btn)\n p_button.grid(row=2, column=4, ipady=5)\n button_variable_list.append(p_button)\n q_button = Button(frame3, text=\"Q\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=q_btn)\n q_button.grid(row=2, column=5, ipady=5)\n button_variable_list.append(q_button)\n r_button = Button(frame3, text=\"R\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=r_btn)\n r_button.grid(row=2, column=6, ipady=5)\n button_variable_list.append(r_button)\n s_button = Button(frame3, text=\"S\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=s_btn)\n s_button.grid(row=2, column=7, ipady=5)\n button_variable_list.append(s_button)\n t_button = Button(frame3, text=\"T\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=t_btn)\n t_button.grid(row=2, column=8, ipady=5)\n button_variable_list.append(t_button)\n u_button = Button(frame3, text=\"U\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=u_btn)\n u_button.grid(row=2, column=9, ipady=5)\n button_variable_list.append(u_button)\n v_button = Button(frame3, text=\"V\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=v_btn)\n v_button.grid(row=3, column=3, ipady=5)\n button_variable_list.append(v_button)\n w_button = Button(frame3, text=\"W\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=w_btn)\n w_button.grid(row=3, column=4, ipady=5)\n button_variable_list.append(w_button)\n x_button = Button(frame3, text=\"X\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=x_btn)\n x_button.grid(row=3, column=5, ipady=5)\n button_variable_list.append(x_button)\n y_button = Button(frame3, text=\"Y\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=y_btn)\n y_button.grid(row=3, column=6, ipady=5)\n button_variable_list.append(y_button)\n z_button = Button(frame3, text=\"Z\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=z_btn)\n z_button.grid(row=3, column=7, ipady=5)\n button_variable_list.append(z_button)\n hint_button = Button(frame3, text=\"Hint\", bg=\"peachpuff\", relief=\"groove\", font=(\"century\",9,\"bold\"), bd=4, width=8, command=hint_btn)\n hint_button.grid(row=3, column=11, ipady=5)\n\n root.bind('', a_btn)\n root.bind('', a_btn)\n root.bind('', b_btn)\n root.bind('', b_btn)\n root.bind('', c_btn)\n root.bind('', c_btn)\n root.bind('', d_btn)\n root.bind('', d_btn)\n root.bind('', e_btn)\n root.bind('', e_btn)\n root.bind('', f_btn)\n root.bind('', f_btn)\n root.bind('', g_btn)\n root.bind('', g_btn)\n root.bind('', h_btn)\n root.bind('', h_btn)\n root.bind('', i_btn)\n root.bind('', i_btn)\n root.bind('', j_btn)\n root.bind('', j_btn)\n root.bind('', k_btn)\n root.bind('', k_btn)\n root.bind('', l_btn)\n root.bind('', l_btn)\n root.bind('', m_btn)\n root.bind('', m_btn)\n root.bind('', n_btn)\n root.bind('', n_btn)\n root.bind('', o_btn)\n root.bind('', o_btn)\n root.bind('

', p_btn)\n root.bind('

', p_btn)\n root.bind('', q_btn)\n root.bind('', q_btn)\n root.bind('', r_btn)\n root.bind('', r_btn)\n root.bind('', s_btn)\n root.bind('', s_btn)\n root.bind('', t_btn)\n root.bind('', t_btn)\n root.bind('', u_btn)\n root.bind('', u_btn)\n root.bind('', v_btn)\n root.bind('', v_btn)\n root.bind('', w_btn)\n root.bind('', w_btn)\n root.bind('', x_btn)\n root.bind('', x_btn)\n root.bind('', y_btn)\n root.bind('', y_btn)\n root.bind('', z_btn)\n root.bind('', z_btn)\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n root.config(bg=\"white\")\n root.resizable(0,0)\n\n button_variable_list = []\n\n main()\n root.mainloop()\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":14164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"558534606","text":"#!/usr/bin/env python\n\nfrom io import BytesIO, open\nimport struct\nimport hashlib\nfrom dbparse import DBParser\nimport sys\nimport jsonpickle\n\nif len(sys.argv) < 3:\n print('Usage: %s output-file input-file [key-file]' % sys.argv[0])\n sys.exit(2)\n\ndef create_rules(countries):\n result = {}\n for c in countries.values():\n for rule in c.permissions:\n result[rule] = 1\n return list(result)\n\ndef create_collections(countries):\n result = {}\n for c in countries.values():\n result[c.permissions] = 1\n return list(result)\n\np = DBParser()\ncountries = p.parse(open(sys.argv[2], 'r', encoding='utf-8'))\n\ncountrynames = list(countries)\ncountrynames.sort()\n\npower = []\nbands = []\nrules = create_rules(countries)\nrules.sort()\ncollections = create_collections(countries)\ncollections.sort()\n\njsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)\njson = jsonpickle.encode(countries, unpicklable=False)\noutput = open(sys.argv[1], mode='w', encoding='utf-8')\noutput.write(json)\noutput.close()\n","sub_path":"utils/db2json.py","file_name":"db2json.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"380628153","text":"# .-. coding=utf-8\nimport urllib2\nimport datetime\nimport urlparse\nfrom lxml import etree\nfrom kernel import collector\n\nLIST_URL = 'http://www.uniqlo.cn/search.htm?search=y&scid=%s&viewType=grid&orderType=_hotsell&pageNum=%d#anchor'\nXPATH = '//*/ul[@class=\"shop-list\"]/li/div[1]'\n\nclass UniqloCollector(collector.BaseCollector):\n def fetch(self):\n self.logger.info('Uniqlo started.')\n self.getData('138188203', 3, u'男装') #男装\n self.getData('138188209',3, u'女装') #女装\n self.getData('411880248',3,u'童装') #孩童\n self.getData('237719246',3, u'婴儿') #婴儿\n\n def getData(self, category, pages, leibie):\n parser = etree .HTMLParser(encoding='gbk')\n self.logger.info('Category: %s:' % category)\n for page in range(1,pages):\n self.logger.info('Page: %d:' % page)\n url = LIST_URL %(category, page)\n text = urllib2.urlopen(url).read()\n tree = etree.HTML(text, parser=parser)\n\n time = datetime.datetime.now().strftime('%Y-%m-%d')\n nodes = tree.xpath(XPATH)\n for node in nodes:\n #print etree.tostring(node, method='html', encoding='utf-8')\n sub_node = node.find('div[1]/a')\n url = sub_node.attrib['href']\n\n sub_node = sub_node.find('img')\n #print etree.tostring(sub_node, method='html', encoding='utf-8')\n image_url = sub_node.attrib['data-ks-lazyload']\n\n sub_node = node.find('div[2]/a')\n title = sub_node.text\n\n sub_node = node.find('div[3]/strong')\n price = sub_node.text.strip()\n price = u'¥' + price[0: price.index('.')]\n\n self.logger.info('%s(%s) - %s @ %s' % (title, price, url, image_url))\n collector.object_found.send(\n self,\n time = time, title = title, url = url,\n image_url = image_url,\n price = price,\n leibie = leibie\n )","sub_path":"collectors/shopping/uniqlo.py","file_name":"uniqlo.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"238197263","text":"import re\nimport os\nfrom setuptools import setup\n\n\nPKG = 'mpris_scrobbler'\nVERSIONFILE = os.path.join(PKG, \"__init__.py\")\nlong_description = \"\"\"Scrobbler that can use any MPRIS-enabled media players.\nThis requires Python 3. I have only tested it on Python 3.6, so far.\"\"\"\n\nverstr = \"unknown\"\ntry:\n verstrline = open(VERSIONFILE, \"rt\").read()\nexcept EnvironmentError:\n pass # Okay, there is no version file.\nelse:\n VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\n mo = re.search(VSRE, verstrline, re.M)\n if mo:\n __version__ = mo.group(1)\n else:\n msg = \"if %s.py exists, it is required to be well-formed\" % VERSIONFILE\n raise RuntimeError(msg)\n\nsetup(\n name=PKG,\n version=__version__,\n packages=['mpris_scrobbler'],\n package_dir={'mpris_scrobbler': 'mpris_scrobbler'},\n package_data={\n 'mpris_scrobbler': ['*.py', 'services/*.py'],\n },\n scripts=['scripts/mpris_scrobbler'],\n author='Sina Mashek',\n author_email='sina@mashek.xyz',\n maintainer='Sina Mashek',\n maintainer_email='sina@mashek.xyz',\n long_description=long_description,\n description=\"Scrobbler that can use any MPRIS-enabled media players.\",\n license='MIT',\n url='https://git.mashek.net/bottitytto/mpris_scrobbler',\n platforms=['any'],\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6'\n ],\n)\n","sub_path":"pypi_install_script/mpris_scrobbler-0.2.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"274695406","text":"import pytest\nfrom utilities.color_print import print_yel\nfrom base.webdriver_factory import WebdriverFactory\n@pytest.yield_fixture()\n\ndef setUp():\n print (\"\\nRunning method level setUp\")\n yield\n print(\"\\nOnce yield method level TEARDOWN after every method\")\n\n\n@pytest.yield_fixture(scope=\"class\")\ndef oneTimeSetUp(request,browser,os_type):\n print_yel(\"\\nRunning onetimesetUp test\")\n wdf = WebdriverFactory(browser)\n driver = wdf.get_driver_instance()\n driver_name = str(driver).split(\".\")\n print_yel(\"Running on <<{}>> browser\".format(driver_name[2]))\n if request.cls is not None:\n request.cls.driver = driver\n yield driver\n driver.quit()\n print_yel(\"\\nOnce yield after all tests are done\")\n\ndef pytest_addoption(parser):\n parser.addoption(\"--browser\")\n parser.addoption(\"--os_type\",help='operating system')\n\n@pytest.fixture(scope=\"module\")\ndef browser(request):\n return request.config.getoption(\"--browser\")\n\n@pytest.fixture(scope=\"module\")\ndef os_type(request):\n return request.config.getoption(\"--os_type\")","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"619559550","text":"\"\"\"\n<>\n模块方法: 含义:\n1. set_window_size()\t 设置浏览器的大小\n2. back()\t 控制浏览器后退\n3. forward()\t 控制浏览器前进\n4. refresh()\t 刷新当前页面\n5. clear()\t 清除文本\n6. send_keys (value)\t 模拟按键输入\n7. click()\t 单击元素\n8. submit()\t 用于提交表单\n9. get_attribute(name)\t 获取元素属性值\n10. is_displayed()\t 设置该元素是否用户可见\n11. size\t 返回元素的尺寸\n12. text\t 获取元素的文本\n\n<<定位元素>>\n定位一个元素: 定位多个元素: 含义:\n1. find_element_by_id\t find_elements_by_id\t 通过元素id定位\n2. find_element_by_name\t find_elements_by_name\t 通过元素name定位\n3. find_element_by_xpath\t find_elements_by_xpath\t 通过xpath表达式定位\n4. find_element_by_link_text\t find_elements_by_link_tex\t 通过完整超链接定位\n5. find_element_by_partial_link_text\t find_elements_by_partial_link_text\t 通过部分链接定位\n6. find_element_by_tag_name\t find_elements_by_tag_name\t 通过标签定位\n7. find_element_by_class_name\t find_elements_by_class_name\t 通过类名进行定位\n8. find_elements_by_css_selector\t find_elements_by_css_selector\t 通过css选择器进行定位\n\n<<等待条件函数>>\n等待条件: 含义:\n1. title_is 标题是某内容\n2. title_contains 标题包含某内容\n3. presence_of_element_located 节点加载出来,传入定位元组,如(By.ID, 'p')\n4. presence_of_all_elements_located 所有节点加载出来\n5. visibility_of_element_located 节点可见,传入定位元组\n6. visibility_of 可见,传入节点对象\n7. text_to_be_present_in_element 某个节点文本包含某文字\n8. text_to_be_present_in_element_value 某个节点值包含某文字\n9. frame_to_be_available_and_switch_to_it 加载并切换\n10. invisibility_of_element_located 节点不可见\n11. alert_is_present 是否出现警告\n12. element_to_be_clickable 节点可点击\n13. element_to_be_selected 节点可选择,传入节点对象\n14. element_located_to_be_selected 节点可选择,传入定位元组\n15. element_selection_state_to_be 传入节点对象以及状态,相等返回True,否则返回False\n16. element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False\n17. staleness_of 判断一个节点是否仍在DOM,可判断当前页面是否已经刷新\n\n<>\n================================================================================================================\n# 实例化配置选项\nchrome_options = webdriver.ChromeOptions()\n\n# 不加载图片,加快访问速度\nchrome_options.add_experimental_option(\"prefs\", {\"profile.managed_default_content_settings.images\": 2})\n\n# 设置为开发者模式,避免被识别\nchrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\n\n# 设置无界面模式\nchrome_options.add_argument('--headless')\n\n# 设置默认编码为utf-8\noptions.add_argument('lang=zh_CN.UTF-8')\n\n# 通过设置user-agent,用来模拟移动设备\n<模拟 Android QQ浏览器>\noptions.add_argument('user-agent=\"MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1\"')\n<模拟iPhone 6>\noptions.add_argument('user-agent=\"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1\"')\n\n# 设置selenium窗口大小\nbrowser.set_window_size(configure.windowHeight, configure.windowWidth) # configure为桌面分辨率实际大小\n\n# 阻止密码保存提示框的弹出\nprefs = {}\nprefs[“credentials_enable_service”] = False\nprefs[“profile.password_manager_enabled”] = False\noptions.add_experimental_option(“prefs”, prefs)\n\n# 添加应用扩展程序 (.crx文件)\nextension_path = 'D:/extension/XPath-Helper_v2.0.2.crx'\nchrome_options.add_extension(extension_path)\n\n# 启动配置选项\nself.driver = webdriver.Chrome(options=chrome_options)\n================================================================================================================\n\"\"\"\n# -*- coding:utf-8 -*-\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n__author__ = 'Evan'\n\n\nclass Crawler(object):\n\n def __init__(self, url=''):\n \"\"\"\n Chrome常用配置选项:\n 1. 不加载图片,加快访问速度\n 2. 设置为开发者模式,避免被识别\n 3. 设置无界面模式\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_experimental_option(\"prefs\", {\"profile.managed_default_content_settings.images\": 2})\n chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\n chrome_options.add_argument('--headless')\n self.driver = webdriver.Chrome(options=chrome_options)\n\n =============================================================\n # PhantomJS设置缓存和禁用图片加载\n service_args = ['--load-images=false', '--disk-cache=true']\n self.driver = webdriver.PhantomJS(service_args=service_args)\n \"\"\"\n self.source_url = url\n self.driver = webdriver.Chrome() # 选择浏览器驱动\n self.waiting = WebDriverWait(self.driver, 30) # 设置显示等待30秒\n self.driver.implicitly_wait(30) # 设置隐示等待30秒\n self.actions = webdriver.ActionChains(self.driver) # 动作链初始化\n\n def switch_to_windows(self, to_parent_windows=False):\n \"\"\"\n 切换到不同的windows窗口\n :param to_parent_windows: 默认为False,如果设置为True则回到主窗口\n :return:\n \"\"\"\n total = self.driver.window_handles\n if to_parent_windows:\n self.driver.switch_to.window(total[0])\n else:\n current_windows = self.driver.current_window_handle\n for window in total:\n if window != current_windows:\n self.driver.switch_to.window(window)\n\n def switch_to_frame(self, index=0, to_parent_frame=False, to_default_frame=False):\n \"\"\"\n 切换到不同的frame框架\n :param index: expect by frame index value or id or name or element\n :param to_parent_frame: 默认为False,如果设置为True则切换到上一个frame框架\n :param to_default_frame: 默认为False,如果设置为True则切换到最上层的frame框架\n :return:\n \"\"\"\n if to_parent_frame:\n self.driver.switch_to.parent_frame()\n elif to_default_frame:\n self.driver.switch_to.default_content()\n else:\n self.driver.switch_to.frame(index)\n\n def open_new_windows(self, new_url=''):\n \"\"\"\n 打开一个新的windows窗口\n :param new_url: 新的URL\n :return:\n \"\"\"\n js = \"window.open({})\".format(new_url)\n self.driver.execute_script(js)\n time.sleep(2)\n\n def page_scrolling(self, go_to_bottom=False, rolling_distance=(0, 1000)):\n \"\"\"\n 页面滚动,如果没有滚动效果,添加延时(页面需要全部加载完毕才能滚动)\n :param bool go_to_bottom: 默认为False,如果为True则滚动到当前页面的最底部\n :param tuple rolling_distance: 滚动距离,默认是向下滚动1000像素\n :return:\n \"\"\"\n time.sleep(5)\n if go_to_bottom:\n js = \"window.scrollTo(0, document.body.scrollHeight)\"\n else:\n js = \"window.scrollBy({}, {})\".format(rolling_distance[0], rolling_distance[1])\n self.driver.execute_script(js)\n\n def screen_shot(self, picture_name='example.jpg'):\n \"\"\"\n 截取当前网页并保存为图片\n :param picture_name: 保存的图片名称\n :return:\n \"\"\"\n self.driver.save_screenshot(picture_name)\n\n def action_chain(self, source, target):\n \"\"\"\n 执行鼠标拖曳\n :param source: 拖曳前位置\n :param target: 拖曳后位置\n :return:\n \"\"\"\n self.actions.drag_and_drop(source, target)\n self.actions.perform()\n\n def close_current_windows(self):\n # 关闭当前页面\n if self.driver:\n self.driver.close()\n\n def quit_browser(self):\n # 退出所有页面\n if self.driver:\n self.driver.quit()\n\n def main(self):\n # 访问页面\n self.driver.get(self.source_url)\n\n # 定位节点\n self.driver.find_element_by_xpath('//*[@id=\"kw\"]') # 通过xpath定位\n input_box = self.waiting.until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"kw\"]'))) # 通过等待条件定位\n\n # 获取节点信息\n print(input_box.get_attribute('class')) # 获取节点的class属性值\n print(input_box.id) # 获取节点的id值\n print(input_box.text) # 获取节点的文本值\n print(input_box.location) # 获取节点在页面中的相对位置\n print(input_box.tag_name) # 获取节点的标签名称\n print(input_box.size) # 获取节点的大小\n # 获取网页信息\n print(self.driver.current_url) # 获取当前的URL\n print(self.driver.get_cookies()) # 获取当前的Cookies\n print(self.driver.page_source) # 获取网页源代码\n\n # 节点交互\n input_box.clear() # 清空文本\n input_box.send_keys('python') # 输入文本\n input_box.send_keys(Keys.ENTER) # 执行输入\n # 网页交互\n self.driver.back() # 网页后退\n time.sleep(1)\n self.driver.forward() # 网页前进\n # 滚动页面\n self.page_scrolling() # 执行javascript\n # 动作链\n source = self.driver.find_element_by_xpath('//*[@id=\"result_logo\"]/img[1]')\n target = self.driver.find_element_by_xpath('//*[@id=\"kw\"]')\n self.action_chain(source=source, target=target) # 鼠标拖曳\n\n\nif __name__ == '__main__':\n crawler = Crawler(url='https://www.baidu.com')\n crawler.main()\n","sub_path":"python_learning/python_examples/crawler_example/selenium_sample.py","file_name":"selenium_sample.py","file_ext":"py","file_size_in_byte":11239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"584787407","text":"#!/usr/bin/env python3\n#-*- coding: Utf-8 -*-\n\n###########################################################\n# HEAD #\n###########################################################\nfrom statistics import mean \nimport sys, re, os\nos.system(\"clear\")\n\n###########################################################\n# FONCTIONS #\n###########################################################\n\n#__ Partie VERIFICATION DU FICHIER__#\n#####################################\n\ndef cheminFichier() :\n\tprint(\"Saisir le chemin du fichier :\")\n\tsaisir = input()\n\treturn saisir\n\n\ndef ouvertureFichierVCF() : \n\tformatVCF = False\n\trecommencer = 'o'\n\tfichier = None\n\tlisteFichier=[]\n\twhile formatVCF == False and recommencer == 'o' or recommencer == 'oui' :\n\t\tsaisi = cheminFichier()\n\t\ttabExtraction = saisi.split(\".\")\n\t\ttry :\n\t\t\tif tabExtraction[1] != 'vcf' : #Si le fichier n'est pas en format VCF\n\t\t\t\tprint(\"Erreur saisie : votre fichier n'est pas au format vcf\\nVoulez-vous ressaisir un fichier VCF ? (oui, o / non, n)\")\n\t\t\t\trecommencer = input()\n\t\t\telif tabExtraction[1] == 'vcf' and os.path.exists(saisi) : #Si le fichier est un VCF et qu'il existe, OK\n\t\t\t\tformatVCF = True\n\t\t\t\tfichier = open(saisi, 'r')\n\t\t\t\tprint(\"Ouverture du fichier VCF '\", saisi, \"' reussie !\")\n\t\t\t\tlisteFichier = verificationContenu(fichier)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Le fichier VCF n'existe pas...\\nVoulez-vous ressaisir un fichier VCF ? (oui, o / non, n) \")\n\t\t\t\trecommencer=input()\n\t\texcept :\n\t\t\tif formatVCF == False : #Ne pas demander une autre saisie si on a deja ouvert le VCF\n\t\t\t\tprint(\"Erreur saisie : vous n'avez pas saisi de fichier.\\nVoulez-vous ressaisir un fichier VCF ? (oui, o / non, n) \")\n\t\t\t\trecommencer = input()\n\treturn fichier, listeFichier\n\ndef verificationContenu(fichier) :\n\t#On lit le fichier ligne par ligne \n\t#(1) tant que la ligne ne comporte pas \"fileformat\" \n\t#(2) qu'il existe un header\n\t#(3) qu'il y a suffisament de donnees pour commencer\n\tligneFormat = False\n\t#Création liste fichier pour le manipuler\n\tlisteFichier=[]\n\tfor ligne in fichier.readlines() :\t\n#---------------------1 => verification de la version (VERSION 4)-----------------------\n\t\tligneVersion = re.search(\"#.*fileformat=VCF\", ligne)\n\t\tif ligneVersion : #Si cest la ligne version\n\t\t\tversion = re.search(\"#.*VCFv4\\.[0-9]\", ligne)\n\t\t\tif version : \n\t\t\t\tprint(\"Verification version : OK (4.)\")\n\t\t\telse : \n\t\t\t\tprint(\"Erreur, la version du fichier est trop ancienne...\\n\")\n\t\t\t\tfermetureFichierVCF(fichier)\n\t\t\t\tsys.exit(\"FIN DU PROGRAMME !\")\n#---------------------AJOUT DE LA LIGNE DANS LA LISTE-----------------------\n\t\tlisteFichier.append(ligne)\n#---------------------2 => verification du header-----------------------\n\tlisteHeader = extractionHeader(listeFichier)\n\tif len(listeHeader) < 10 :\n\t\tprint(\"Données insuffisantes dans le header\")\n\t\tfermetureFichierVCF(fichier)\n\t\tsys.exit(\"FIN DU PROGRAMME !\")\n\telse :\n\t\tprint(\"Verification header : OK\")\n#---------------------2 => verification des données-----------------------\n\tlisteDonnees = extractionDico(listeFichier)\n\tif len(listeDonnees) < 10 :\n\t\tprint(\"Il n'y a pas assez de données génomiques ...\")\n\t\tfermetureFichierVCF(fichier)\n\t\tsys.exit(\"FIN DU PROGRAMME !\")\n\telse :\n\t\tprint(\"Verification des données génomiques : OK\")\n\n\treturn listeFichier\n\n\ndef fermetureFichierVCF(fichier) :\n\tif fichier :\n\t\ttry :\n\t\t\tfichier.close()\n\t\t\tprint(\"Fermeture du fichier réussie\")\n\t\texcept :\n\t\t\tprint(\"Erreur dans l'ouverture du fichier\")\n\t\t\tsys.exit(\"FIN DU PROGRAMME !\")\n\n\t\t\t\t\n#__ Partie EXTRACTION et ANALYSE des DONNEES __#\n#################################################\n\ndef extractionDico(liste):\n\tdico_vcf={}\n\tfor lines in liste:\n\t\t#Recherche du header\n\t\tif re.search(\"^#\", lines):\n\t\t\tcontinue\n\t\t#Création du dictionnaire avec les infos importantes du VCF\n\t\telse:\n\t\t\ttab=lines.split(\"\\t\")\n\t\t\tchrm=tab[0]\n\t\t\tpos=tab[1]\n\t\t\tqual=tab[5]\n\t\t\tlongueur_temp=tab[7]\n\t\t\tif re.search(\"^SVLEN\", longueur_temp):\n\t\t\t\t# On recherche si la longueur est présente dans le VCF\n\t\t\t\tlongueur_split=longueur_temp.split(\";\")[0]\n\t\t\t\t# Si on trouve la longueur on split la colonne sur ; qui représente les différentes valeurs \n\t\t\t\tlongueur=longueur_split.split(\"=\")[1]\n\t\t\t\t# On split ensuite sur \"=\" pour n'obtenir que la valeur souhaitée \n\t\t\telse:\n\t\t\t\t# Si la longueur n'est pas renseignée on l'indique\n\t\t\t\tlongueur=\"Inconnue\"\n\t\t\tif chrm in dico_vcf:\n\t\t\t\t\tdico_vcf[chrm][pos]=[qual, longueur]\n\t\t\telse:\n\t\t\t\tdico_vcf[chrm]={pos:[qual, longueur]}\n\treturn dico_vcf\n\ndef extractionHeader(liste):\n\tlist_header=[]\n\tfor lines in liste:\n\t\t#Recherche du header\n\t\tif re.search(\"^#\", lines):\n\t\t\tlist_header.append(lines)\n\t\t#Création du dictionnaire avec les infos importantes du VCF\n\treturn list_header\n\n\ndef affichageHeader(list_header):\n\tprint(\"Affichage du header\")\n\tfor i in list_header:\n\t\tprint(i)\n\ndef affichageDico(dico_vcf):\n\tprint(\"Affichage du contenu biomoléculaire du VCF\")\n\tfor name_chr in dico_vcf :\n\t\tfor pos_chr in dico_vcf[name_chr]:\n\t\t\tprint(\"N°\",name_chr,\" Position : \",pos_chr,\" Qual : \", dico_vcf[name_chr][pos_chr][0], \" Longueur : \",dico_vcf[name_chr][pos_chr][1])\n\n\ndef statDico(dico_vcf):\n\t#On trouve combien il y a d'élements par chromosomes \n\tstatMEI={\"1\":[], \"2\":0, \"3\":0, \"4\":0, \"5\":0, \"6\":0, \"7\":0, \"8\":0, \"9\":0, \"10\":0, \"11\":0, \"12\":0, \"13\":0, \"14\":0, \"15\":0, \"16\":0, \"17\":0, \"18\":0, \"19\":0, \"20\":0, \"21\":0, \"22\":0, 'X':0, 'Y':0}\n\tfor name_chr in dico_vcf:\n\t\tres=0\n\t\tfor chromoMEI in statMEI:\n\t\t\tif name_chr!=chromoMEI:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tfor pos_chr in dico_vcf[name_chr]:\n\t\t\t\t\tres+=1\n\t\t\t\tstatMEI[chromoMEI]=res\n\t\t\tprint(\"On retrouve\", res, \"différences sur le chromosome\", chromoMEI)\n\tnombreMEI=[]\n\tfor chromoMEI in statMEI:\n\t\tnombreMEI.append(statMEI[chromoMEI])\n\tmoyenne=mean(nombreMEI)\n\tmaximum=max(nombreMEI)\n\tminimum=min(nombreMEI)\n\tchromoMax=\"\"\n\tchromoMin=\"\"\n\tfor chromoMEI in statMEI:\n\t\tif statMEI[chromoMEI]!=maximum:\n\t\t\tcontinue\n\t\telif statMEI[chromoMEI]==maximum:\n\t\t\tchromoMax=chromoMEI\n\t\telse:\n\t\t\tprint(\"Impossible de trouver le maximum\")\n\tfor chromoMEI in statMEI:\n\t\tif statMEI[chromoMEI] != minimum:\n\t\t\tcontinue\n\t\telif statMEI[chromoMEI]==minimum:\n\t\t\tchromoMin=chromoMEI\n\t\telse:\n\t\t\tprint(\"Impossible de trouver le minimum\")\n\tprint (\"La moyenne est de : \", moyenne,\". On retrouve le plus de MEI sur le chromosome \", chromoMax,\" (avec \",maximum,\" MEI) et le moins de MEI sur le chromosome \", chromoMin, \" (avec \",minimum,\" MEI).\")\n\n\ndef choix(fichier) :\n\tif fichier==[]:\n\t\tsys.exit(\"FERMETURE DU PROGRAMME !\")\n\telse:\n\t\t#HEADER\n\t\tcheck=False\n\t\twhile check==False:\n\t\t\tchoixHeader=input(\"Voulez-vous afficher le header du fichier VCF ? (Oui/Non)\")\n\t\t\tif choixHeader==\"Oui\":\n\t\t\t\tcheck=True\n\t\t\t\taffichageHeader(extractionHeader(fichier))\n\t\t\t\taffichageDico(extractionDico(fichier))\n\t\t\telif choixHeader==\"Non\":\n\t\t\t\tcheck=True\n\t\t\t\taffichageDico(extractionDico(fichier))\n\t\t\telse:\n\t\t\t\tprint(\"Veuillez choisir entre Oui ou Non !\")\n\t\t\t\tcheck=False\n\t\t#STAT\n\t\tcheck=False\n\t\twhile check==False:\n\t\t\tchoixStat=input(\"Voulez-vous afficher quelques stats sur les infos du VCF ? (Oui/Non)\")\n\t\t\tif choixStat==\"Oui\":\n\t\t\t\tcheck=True\n\t\t\t\tstatDico(extractionDico(fichier))\n\t\t\telif choixStat==\"Non\":\n\t\t\t\tbreak\n\t\t\telse: \n\t\t\t\tprint(\"Mauvaise saisie, veuillez écrire Oui ou Non.\")\n\n\n###########################################################\n# MAIN #\n###########################################################\nfichier, listeFichier = ouvertureFichierVCF()\nchoix(listeFichier)\nfermetureFichierVCF(fichier)","sub_path":"FichiersPrésentation/analyseVCF.py","file_name":"analyseVCF.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"576464207","text":"#!/usr/bin/env python\n\n# client.py\nimport socket\n# create a socket object\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# get local machine name\nhost = '127.0.1.1'\nport = raw_input(\"Digite a porta:\")\n\n# connection to hostname on the port.\ns.connect((host, int(port)))\n\ndef recvall(sock):\n\tBUFF_SIZE = 1024 # 4 KiB\n\tdata = \"\"\n\twhile True:\n\t\tpart = sock.recv(BUFF_SIZE)\n\t\tdata += part\n\t\tif '---' in part:\n\t\t\tbreak\n\treturn data\n\nwhile 1:\n\tprint('Digite:')\n\tprint(\"> 0 - listar as timezones disponiveis\")\n\tprint(\"> 'Nome da timezone' - consultar uma timezone\")\n\topc = raw_input(\">\")\n\ts.send(opc)\n\taux = recvall(s)\n\tprint(aux)\n\tbreak\n\n\t# chunk = s.recv(1024)\n\t# chunk = chunk\n\t# print chunk\n\ns.close()\n\n\n#fontes\n# http://stackoverflow.com/questions/17667903/python-socket-receive-large-amount-of-data\n","sub_path":"sockets/v1/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"643355549","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport lightgbm as lgb\nimport xgboost as xgb\nimport time\nfrom catboost import CatBoostRegressor\nfrom sklearn.metrics import mean_absolute_error\nimport seaborn as sns\nimport warnings\nfrom statsmodels import robust\nfrom sklearn.model_selection import KFold\nwarnings.filterwarnings(\"ignore\")\n\n\ndef train_model(X, Y, X_test=None, n_fold=10, params=None, model_type='sklearn', plot_feature_importance=False,\n model=None):\n \"\"\"Taken from the `Earthquakes FE. More features and samples` kaggle notebook\"\"\"\n oof = np.zeros(len(X))\n if X_test is not None:\n prediction = np.zeros(len(X_test))\n scores = []\n feature_importance = pd.DataFrame()\n if n_fold is None:\n if model_type == 'sklearn':\n model = model\n model.fit(X, Y)\n if X_test is not None:\n y_pred = model.predict(X_test).reshape(-1, )\n return model, y_pred\n else:\n raise ValueError(\"Models not supported\")\n folds = KFold(n_splits=n_fold, shuffle=True)\n for fold_n, (train_index, valid_index) in enumerate(folds.split(X)):\n print('Fold', fold_n, 'started at', time.ctime())\n X_train, X_valid = X.iloc[train_index], X.iloc[valid_index]\n y_train, y_valid = Y.iloc[train_index], Y.iloc[valid_index]\n\n if model_type == 'lgb':\n model = lgb.LGBMRegressor(**params, n_estimators=50000, n_jobs=-1)\n model.fit(X_train, y_train,\n eval_set=[(X_train, y_train), (X_valid, y_valid)], eval_metric='mae',\n verbose=10000, early_stopping_rounds=200)\n\n y_pred_valid = model.predict(X_valid)\n\n if X_test is not None:\n y_pred = model.predict(X_test, num_iteration=model.best_iteration_)\n\n if model_type == 'xgb':\n train_data = xgb.DMatrix(data=X_train, label=y_train, feature_names=X.columns)\n valid_data = xgb.DMatrix(data=X_valid, label=y_valid, feature_names=X.columns)\n\n watchlist = [(train_data, 'train'), (valid_data, 'valid_data')]\n model = xgb.train(dtrain=train_data, num_boost_round=20000, evals=watchlist, early_stopping_rounds=200,\n verbose_eval=500, params=params)\n y_pred_valid = model.predict(xgb.DMatrix(X_valid, feature_names=X.columns),\n ntree_limit=model.best_ntree_limit)\n if X_test is not None:\n y_pred = model.predict(xgb.DMatrix(X_test, feature_names=X.columns), ntree_limit=model.best_ntree_limit)\n\n if model_type == 'sklearn':\n model = model\n model.fit(X_train, y_train)\n\n y_pred_valid = model.predict(X_valid).reshape(-1, )\n score = mean_absolute_error(y_valid, y_pred_valid)\n print(f'Fold {fold_n}. MAE: {score:.4f}.')\n print('')\n if X_test is not None:\n y_pred = model.predict(X_test).reshape(-1, )\n if model_type == 'cat':\n model = CatBoostRegressor(iterations=20000, eval_metric='MAE', **params)\n model.fit(X_train, y_train, eval_set=(X_valid, y_valid), cat_features=[], use_best_model=True,\n verbose=False)\n y_pred_valid = model.predict(X_valid)\n if X_test is not None:\n y_pred = model.predict(X_test)\n oof[valid_index] = y_pred_valid.reshape(-1, )\n scores.append(mean_absolute_error(y_valid, y_pred_valid))\n if X_test is not None:\n prediction += y_pred\n if model_type == 'lgb':\n # feature importance\n fold_importance = pd.DataFrame()\n fold_importance[\"feature\"] = X.columns\n fold_importance[\"importance\"] = model.feature_importances_\n fold_importance[\"fold\"] = fold_n + 1\n feature_importance = pd.concat([feature_importance, fold_importance], axis=0)\n if X_test is not None:\n prediction /= n_fold\n\n print('CV mean score: {0:.4f}, mad: {1:.4f}.'.format(np.mean(scores), robust.mad(scores)))\n\n if model_type == 'lgb':\n feature_importance[\"importance\"] /= n_fold\n if plot_feature_importance:\n cols = feature_importance[[\"feature\", \"importance\"]].groupby(\"feature\").mean().sort_values(\n by=\"importance\", ascending=False)[:50].index\n\n best_features = feature_importance.loc[feature_importance.feature.isin(cols)]\n\n plt.figure(figsize=(16, 12));\n sns.barplot(x=\"importance\", y=\"feature\", data=best_features.sort_values(by=\"importance\", ascending=False));\n plt.title('LGB Features (avg over folds)');\n if X_test is not None:\n return np.mean(scores), robust.mad(scores), prediction\n else:\n return np.mean(scores), robust.mad(scores)\n","sub_path":"exp/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"158147779","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nbiothings_explorer.hint\n~~~~~~~~~~~~~~~~~~~~~~~\n\nDisplay bioentities in biothings explorer based on user specified input\n\"\"\"\nimport asyncio\nfrom aiohttp import ClientSession\nfrom .config import metadata\n\nBIOTHINGS = [k for k, v in metadata.items() if v.get(\"api_type\") == 'biothings']\n\n\nclass Hint():\n def __init__(self, size=5):\n \"\"\"Guess appropriate bio-entities based on user input\n\n params\n ------\n size: the max number of documents returned for each bioentity type\n \"\"\"\n self.clients = []\n self.types = []\n self.post_apis = []\n self.get_apis = []\n self.id_ranks = []\n self.size = size\n\n def get_primary_id(self, client, json_doc, _type):\n \"\"\"Get the primary id of a biological entity\"\"\"\n # parse the id rank info from metadata\n ranks = metadata[client]['id_ranks']\n res = {}\n # loop through the id rank list, e.g. ['chembl', 'drugbank', ...]\n # the id rank list is ranked based on priorirty\n for _id in ranks:\n # if an id of higher priority is found, set it as the primary id\n if _id in json_doc:\n res['identifier'] = _id\n res['cls'] = _type\n res['value'] = json_doc[_id]\n break\n return res\n\n async def call_api(self, _input, session):\n \"\"\"make asynchronous API calls\n\n params\n ------\n _input: str, user specified input\n session: aiohttp session object\n \"\"\"\n if _input['api'] in self.post_apis:\n async with session.post(_input['url'], data=_input['data']) as res:\n try:\n return await res.json()\n except:\n print(\"Unable to fetch results from {}\".format(_input['api']))\n return {}\n else:\n async with session.get(_input['url'], params=_input['data']) as res:\n try:\n return await res.json()\n except:\n print(\"Unable to fetch results from {}\".format(_input['api']))\n return {}\n\n async def run(self, _input):\n \"\"\"run API call tasks\n\n params\n ------\n _input: str, user typed text\n \"\"\"\n inputs = []\n for k, v in metadata.items():\n # check if an API can be used for hint\n if v.get('hint'):\n self.clients.append(k)\n self.types.append(v['doc_type'])\n if v['method'] == 'get':\n self.get_apis.append(k)\n elif v['method'] == 'post':\n self.post_apis.append(k)\n _item = {'url': v['url'],\n 'api': k,\n 'data': {'q': [\"'\" + _input + \"'\"],\n 'scopes': ','.join(v['scopes']),\n 'fields': ','.join(v['fields']),\n 'size': self.size,\n 'dotfield': 1\n }\n }\n if 'add' in v:\n _item['data']['q'] = '(_id:\"' + _input + '\" OR name:\"' + _input + '\")' + v[\"add\"]\n inputs.append(_item)\n tasks = []\n async with ClientSession( ) as session:\n for i in inputs:\n task = asyncio.ensure_future(self.call_api(i, session))\n tasks.append(task)\n responses = await asyncio.gather(*tasks)\n final_res = {}\n for j in self.types:\n final_res[j] = []\n for (k, v, j) in zip(self.clients, responses, self.types):\n # response could be from GET or POST, need to restructure\n if 'hits' in v:\n v = v['hits']\n for _v in v:\n if 'notfound' in _v:\n continue\n else:\n _res = {}\n display = ''\n for field_name in metadata[k]['fields']:\n if field_name in _v:\n if metadata[k]['fields'][field_name] not in _res:\n _res[metadata[k]['fields'][field_name]] = _v[field_name]\n display += metadata[k]['fields'][field_name] + '(' + str(_v[field_name]) + ')' + ' '\n _res['display'] = display\n _res['type'] = j\n primary = self.get_primary_id(k, _res, j)\n _res.update({'primary': primary})\n final_res[j].append(_res)\n return final_res\n\n def query(self, _input):\n \"\"\"Query APIs based on user input\n\n params\n ------\n _input: str, user specified input\n \"\"\"\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(self.run(_input))\n return loop.run_until_complete(future)\n","sub_path":"biothings_explorer/hint.py","file_name":"hint.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"638982445","text":"from django.urls import path, include\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name = 'usersapp'\n\nurlpatterns = [\n path('register/', views.register, name='register'),\n path('profile/', views.user_profile, name='user_profile'),\n path('login/', auth_views.LoginView.as_view(template_name='usersapp/login.html'), name='login'),\n path('logout/', auth_views.LogoutView.as_view(template_name='usersapp/logout.html'), name='logout'),\n\n]\n","sub_path":"usersapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"531385903","text":"import scipy.io as scio\ndataFile = \"/Users/liyong16/Downloads/pvn_ly.mat\"\ndata = scio.loadmat(dataFile)\n\n\nf = open(\"/Users/liyong16/Downloads/data_gE.txt\", 'a+')\nf.write(\"Value;Type;Height\\n\")\ngE= data['gE']\nfor i in range(len(gE)):\n f.write(str(gE[i][0]) + \";gE;High\\n\")\n f.write(str(gE[i][1]) + \";gE;Low\\n\")\n\nf.close()\n\nf = open(\"/Users/liyong16/Downloads/data_Cp.txt\", 'a+')\nf.write(\"Value;Type;Height\\n\")\nCp= data['Cp']\nfor i in range(len(Cp)):\n f.write(str(Cp[i][0]) + \";Cp;High\\n\")\n f.write(str(Cp[i][1]) + \";Cp;Low\\n\")\nf.close()\n\nf = open(\"/Users/liyong16/Downloads/data_locE.txt\", 'a+')\nf.write(\"Value;Type;Height\\n\")\nlocE= data['locE']\nfor i in range(len(locE)):\n f.write(str(locE[i][0]) + \";locE;High\\n\")\n f.write(str(locE[i][1]) + \";locE;Low\\n\")\nf.close()\n\nf = open(\"/Users/liyong16/Downloads/data_Lp.txt\", 'a+')\nf.write(\"Value;Type;Height\\n\")\nLp= data['Lp']\nfor i in range(len(Lp)):\n f.write(str(Lp[i][0]) + \";Lp;High\\n\")\n f.write(str(Lp[i][1]) + \";Lp;Low\\n\")\nf.close()\n\n","sub_path":"customizedExamples/Func1/code/writeFile.py","file_name":"writeFile.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"320103394","text":"import entities\nimport inventory\nimport input as key_input\nimport random\nimport string\nimport os, sys\nfrom main import save_settings\n\ngetch = key_input._GetchUnix()\n\nclass MonsterOrPlayer(entities.Entity):\n\tdef __init__(self, game, speed, armor, health, damage, strength, xPos=0, yPos=0):\n\t\tsuper(MonsterOrPlayer, self).__init__(xPos, yPos)\n\t\tself.speed = speed\n\t\tself.armor = armor\n\t\tself.health = health\n\t\tself.damage = damage\n\t\tself.strength = strength\n\n\n\n\n# right now this is only used for the title sequence\n# it's just a list of all the choices for characters\ncharlist = [\"Knight\", \"Wizard\", \"Soldier\", \"Rogue\"]\n\nclass Character(entities.Entity):\n\tdef __init__(self, name, game, speed, armor, health, damage, hunger, strength, xPos=0, yPos=0):\n\t\tself.name = name\n\t\tself.game = game\n\t\tself.speed = speed\n\t\tself.armor = armor\n\t\tself.health = health\n\t\tself.maxhealth = health\n\t\tself.damage = damage\n\t\tself.hunger = hunger\n\t\tself.maxhunger = hunger\n\t\tself.strength = strength\n\t\tself.xPos = xPos\n\t\tself.yPos = yPos\n\t\tself.level = 0\n\t\tself.inv = False\n\n\t\tself.type = \"Character\"\n\n\n\t\tself.icon = \"0\"\n\t\tself.walkable = False\n\t\tself.whackable = True\n\n\t\tself.controls = {\"a\": self.apply, \"t\": self.throw, \"d\": self.drop, \",\": self.pickup, \" \": self.wait, \"up\": self.move_up, \"down\": self.move_down, \"left\": self.move_left, \"right\": self.move_right, \"q\": self.quit, \"i\": self.show_inventory}\n\tdef attack(self,target,damage):\n\t\tdamage -= target.armor\n\t\ttarget.health -= damage\n\t\tif self.inventory.equips[4] == 0:\n\t\t\tself.game.say(\"You punch the \" + target.name + \" for \" + str(damage) + \" damage\")\n\t\telif self.inventory.equips[4].name == \"Sword\":\n\t\t\ttarget.health -= 5\n\t\t\tself.game.say(\"You slice the \" + target.name + \" for \" + str(damage + 5) + \" damage\")\n\n\tdef eat(self, item, satiation):\n\t\tself.hunger += satiation\n\t\tif self.hunger > self.maxhunger:\n\t\t\tself.hunger = self.maxhunger\n\t\tself.inventory.remove_item(item)\n\t\tself.game.say(\"You eat the \" + item.description + \" \" + item.name)\n\n\tdef pick_up(self, item):\n\t\tself.inventory.add_item(item)\n\t\tself.game.remove_entity(self.xPos, self.yPos, item)\n\n\tdef apply(self, game):\n\t\tif len(game.player.inventory.items) <= 0:\n\t\t\tgame.say(\"You ain't got nothin' to use or apply!\")\n\t\t\tgame.render()\n\n\t\telse:\n\t\t\t#inn = getch.__call__()\n\t\t\tgame.render_inventory(\"What do you want to use or apply?\")\n\t\t\tinn = False\n\t\t\twhile inn == False:\n\t\t\t\tinn = getch.__call__()\n\t\t\t\tgame.render_inventory(\"What do you want to use or apply?\")\n\t\t\tif inn in \"1234567890\":\n\t\t\t\ttry:\n\t\t\t\t\tgame.player.inventory.items[int(inn) - 1].apply(game)\n\t\t\t\t\tgame.render()\n\t\t\t\texcept IndexError:\n\t\t\t\t\tgame.say(\"You don't have that, silly\")\n\t\t\t\t\tgame.render()\n\t\t\telse:\n\t\t\t\tgame.say(\"You don't have that, silly\")\n\t\t\t\tgame.render()\n\n\tdef pickup(self, game):\n\t\tif game.get_entity_icon(game.player.xPos, game.player.yPos, -2) != \"0\" and game.get_entity_icon(game.player.xPos, game.player.yPos, -2) != \" \":\n\t\t\tgame.say(\"you picked up the \" + game.get_entity(game.player.xPos, game.player.yPos, -2).description + \" \" + game.get_entity(game.player.xPos, game.player.yPos, -2).name)\n\t\t\tgame.player.pick_up(game.get_entity(game.player.xPos, game.player.yPos, -2))\n\t\t\tgame.render()\n\n\tdef throw(self, game):\n\n\t\tif len(game.player.inventory.items) <= 0:\n\t\t\tgame.say(\"You ain't got nothin' to throw!\")\n\t\t\tgame.render()\n\n\t\telse:\n\t\t\t# this bit should probably be written into its own method\n\t\t\t# note: the drop method could be used, because you can set the xPos and yPos of where the item is dropped\n\t\t\t# this is not well written\n\n\t\t\tgame.render_inventory(\"What do you want to throw?\")\n\t\t\tinn = False\n\t\t\twhile inn == False:\n\t\t\t\tinn = getch.__call__()\n\t\t\t\tgame.render_inventory(\"What do you want to throw?\")\n\t\t\tif not inn in \"1234567890\":\n\t\t\t\tgame.say(\"You don't have that item, silly goose!\")\n\t\t\telse:\n\t\t\t\tnum = int(inn) - 1\n\t\t\t\tdum = None\n\t\t\t\twhile dum == None:\n\t\t\t\t\tgame.say(\"What direction do you want to throw the \" + game.player.inventory.items[num].description + \" \" + game.player.inventory.items[num].name + \"?\")\n\t\t\t\t\tgame.render()\n\t\t\t\t\tdum = getch.__call__()\n\n\t\t\t\t\tif dum == \"up\":\n\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tvariance = random.randint(-1, 2)\n\t\t\t\t\t\t\tif not (game.player.yPos - game.player.strength * 3 - variance) < 1:\n\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos, game.player.yPos - game.player.strength * 3 - variance, game.player.inventory.items[num])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# this bit is literally just put in to throw an error\n\t\t\t\t\t\t\t\tstupid = []\n\t\t\t\t\t\t\t\tprint(stupid[1])\n\t\t\t\t\t\texcept IndexError:\n\n\t\t\t\t\t\t\ttemp_list = range(game.player.yPos + game.player.strength * 3 + variance)\n\t\t\t\t\t\t\ttemp_list.reverse()\n\t\t\t\t\t\t\tfor i in temp_list:\n\t\t\t\t\t\t\t\t#game.say(\"HERE'S THE NUMBER \" + str(game.player.yPos - game.player.strength * 3 - variance + i))\n\t\t\t\t\t\t\t\tgame.render()\n\t\t\t\t\t\t\t\tif not (game.player.yPos - i) < 1:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos, game.player.yPos - i, game.player.inventory.items[num])\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t\t\t#game.add_entity(game.player.xPos, 1)\n\t\t\t\t\t\tgame.player.inventory.remove_item(game.player.inventory.items[num])\n\t\t\t\t\t\tgame.render()\n\n\n\t\t\t\t\tif dum == \"down\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tvariance = random.randint(-1, 2)\n\t\t\t\t\t\t\tif not (game.player.yPos + game.player.strength * 3 + variance) >= game.height - 1:\n\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos, game.player.yPos + game.player.strength * 3 + variance, game.player.inventory.items[num])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# see above if this confuses you\n\t\t\t\t\t\t\t\tstupid = []\n\t\t\t\t\t\t\t\tprint(stupid[1])\n\t\t\t\t\t\texcept IndexError:\n\n\t\t\t\t\t\t\ttemp_list = range(game.player.yPos + game.player.strength * 3 + variance)\n\t\t\t\t\t\t\ttemp_list.reverse()\n\t\t\t\t\t\t\tfor i in temp_list:\n\t\t\t\t\t\t\t\tif not (game.player.yPos + i) >= game.height - 1:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos, game.player.yPos + i, game.player.inventory.items[num])\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tgame.player.inventory.remove_item(game.player.inventory.items[num])\n\t\t\t\t\t\tgame.render()\n\n\n\t\t\t\t\tif dum == \"left\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tvariance = random.randint(-1, 2)\n\t\t\t\t\t\t\tif not (game.player.xPos - game.player.strength * 3 - variance) < 1:\n\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos - game.player.strength * 3 - variance, game.player.yPos, game.player.inventory.items[num])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tstupid = []\n\t\t\t\t\t\t\t\tprint(stupid[1])\n\t\t\t\t\t\texcept IndexError:\n\n\t\t\t\t\t\t\ttemp_list = range(game.player.yPos + game.player.strength * 3 + variance)\n\t\t\t\t\t\t\ttemp_list.reverse()\n\t\t\t\t\t\t\tfor i in temp_list:\n\t\t\t\t\t\t\t\tif not (game.player.xPos - i) < 1:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos - i, game.player.yPos, game.player.inventory.items[num])\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tgame.player.inventory.remove_item(game.player.inventory.items[num])\n\t\t\t\t\t\tgame.render()\n\n\n\t\t\t\t\tif dum == \"right\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tvariance = random.randint(-1, 2)\n\t\t\t\t\t\t\tif not (game.player.xPos + game.player.strength * 3 - variance) < 1:\n\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos + game.player.strength * 3 + variance, game.player.yPos, game.player.inventory.items[num])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tstupid = []\n\t\t\t\t\t\t\t\tprint(stupid[1])\n\t\t\t\t\t\texcept IndexError:\n\n\t\t\t\t\t\t\ttemp_list = range(game.player.xPos + game.player.strength * 3 + variance)\n\t\t\t\t\t\t\ttemp_list.reverse()\n\t\t\t\t\t\t\tfor i in temp_list:\n\t\t\t\t\t\t\t\tif not (game.player.xPos + i) >= game.width - 1:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tgame.add_entity(game.player.xPos + i, game.player.yPos, game.player.inventory.items[num])\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tgame.player.inventory.remove_item(game.player.inventory.items[num])\n\t\t\t\t\t\tgame.render()\n\n\tdef drop(self, game):\n\n\t\tgame.render_inventory(\"What do you want to drop?\")\n\t\tinn = False\n\t\twhile inn == False:\n\t\t\tinn = getch.__call__()\n\n\n\n\t\tif inn in string.lowercase + \"1234567890\":\n\t\t\ttry:\n\t\t\t\tgame.say(\"You drop a \" + game.player.inventory.items[int(inn) - 1].description + \" \" + game.player.inventory.items[int(inn) - 1].name)\n\t\t\t\tgame.render()\n\t\t\t\tsuper(Character, self).drop(game.player, game, game.player.inventory.items[int(inn) - 1])\n\t\t\texcept IndexError:\n\t\t\t\tgame.say(\"You don't have that item, silly!\")\n\t\t\t\tgame.render()\n\t\telse:\n\t\t\tgame.say(\"You don't have that item, silly!\")\n\t\t\tgame.render()\n\n\tdef wait(self, game):\n\t\tgame.tick()\n\t\treturn False\n\n\tdef move_up(self, game):\n\t\tsuper(Character, self).move(game, 0, -1)\n\n\tdef move_down(self, game):\n\t\tsuper(Character, self).move(game, 0, 1)\n\n\tdef move_left(self, game):\n\t\tsuper(Character, self).move(game, -1, 0)\n\n\tdef move_right(self, game):\n\t\tsuper(Character, self).move(game, 1, 0)\n\n\tdef quit(self, game):\n\t\tos.system(\"clear\")\n\t\tprint(\"bai\")\n\t\tsys.exit()\n\n\tdef show_inventory(self, game):\n\t\tif not self.inv:\n\t\t\tgame.render_inventory()\n\t\t\tself.inv = not self.inv\n\t\telse:\n\t\t\tgame.tick()\n\t\t\tself.inv = not self.inv\n\t\treturn False\n\n\n\t# def apply(self, item, game):\n\t# \tgame.say(\"This function has not been defined yet\")\n\n\nclass Developer(Character):\n\t\"\"\"This class is just made to be messed with in order to test out things about the game without having to worry about messing anything up\"\"\"\n\tdef __init__(self, name, game, xPos, yPos):\n\n\t\tspeed = 30\n\t\tarmor = 8\n\t\thealth = 100\n\t\tdamage = 40\n\t\thunger = 200\n\t\tstrength = 20\n\n\t\tsuper(Developer, self).__init__(name, game, speed, armor, health, damage, hunger, strength, xPos, yPos)\n\t\tself.inventory = inventory.Inventory([entities.Book(\"Python hand\")])\n\t\tself.title = \"Developer\"\n\n\nclass Knight(Character):\n\t\"\"\"docstring for Knight\"\"\"\n\tdef __init__(self, name, game, xPos, yPos):\n\n\t\tspeed = 3\n\t\tarmor = 8\n\t\thealth = 60\n\t\tdamage = 15\n\t\thunger = 200\n\t\tstrength = 20\n\n\t\tsuper(Knight, self).__init__(name, game, speed, armor, health, damage, hunger, strength, xPos, yPos)\n\t\tself.inventory = inventory.Inventory([entities.Book(\"Great\")])\n\t\tself.title = \"Knight\"\n\nclass Wizard(Character):\n\t\"\"\"docstring for Wizard\"\"\"\n\tdef __init__(self, name, game, xPos, yPos):\n\n\t\tspeed = 3\n\t\tarmor = 8\n\t\thealth = 60\n\t\tdamage = 15\n\t\thunger = 200\n\t\tstrength = 2\n\n\n\t\tsuper(Wizard, self).__init__(name, game, 5, 3, 8, 7, 1, 10)\n\t\tself.inventory = inventory.Inventory(\"Wand\")\n\t\tself.title = \"Wizard\"\n\nclass Gunner(Character):\n\t\"\"\"docstring for Gunner\"\"\"\n\tdef __init__(self, name, game, xPos, yPos):\n\n\t\tspeed = 3\n\t\tarmor = 8\n\t\thealth = 60\n\t\tdamage = 15\n\t\thunger = 200\n\t\tstrength = 2\n\n\n\t\tsuper(Gunner, self).__init__(name, game, 6, 5, 5, 8, 1, 10)\n\t\tself.inventory = inventory.Inventory(\"Gun\")\n\t\tself.title = \"Soldier\"\n\nclass Rogue(Character):\n\t\"\"\"docstring for Wizard\"\"\"\n\tdef __init__(self, name, game, xPos, yPos):\n\n\t\tspeed = 3\n\t\tarmor = 8\n\t\thealth = 60\n\t\tdamage = 15\n\t\thunger = 200\n\t\tstrength = 2\n\n\n\t\tsuper(Rogue, self).__init__(name, game, 10, 5, 8, 2, 0, 10)\n\t\tself.inventory = inventory.Inventory(\"Knife\")\n\t\tself.title = \"Rogue\"\n\n","sub_path":"characters.py","file_name":"characters.py","file_ext":"py","file_size_in_byte":10857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"80607252","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 18 14:04:08 2017\r\n\r\n@author: poaa\r\n\"\"\"\r\n\r\nimport re\r\n\r\ndef Find(expr,text):\r\n m=re.findall(expr,text)\r\n return m\r\n\r\ndef Read_tag_value(full_file,tag_label):\r\n tag_value_dic ={}\r\n tag_values=Find(r'<'+ tag_label +'>\\w+',full_file)\r\n for tag_value in tag_values:\r\n tag_value = tag_value.replace('<'+ tag_label +'>','')\r\n tag_value = tag_value.replace('','')\r\n tag_value = tag_value.upper()\r\n if not tag_value: continue\r\n if not tag_value in tag_value_dic:\r\n tag_value_dic[tag_value] = 1\r\n else:\r\n tag_value_dic[tag_value] += 1\r\n sorted_tags = sorted([(n, w) for w, n in tag_value_dic.items()], reverse=True)\r\n print('La lista de '+ tag_label +' es: ', sorted_tags)\r\n \r\ndef Read_tag_list(full_file,tag_label):\r\n tag_value_dic ={}\r\n tag_values=Find(r'<'+ tag_label +'>',full_file)\r\n for tag_value in tag_values:\r\n tag_value = tag_value.replace('<','')\r\n tag_value = tag_value.replace('>','')\r\n tag_value = tag_value.upper()\r\n if not tag_value: continue\r\n if not tag_value in tag_value_dic:\r\n tag_value_dic[tag_value] = 1\r\n else:\r\n tag_value_dic[tag_value] += 1\r\n sorted_tags = sorted([(n, w) for w, n in tag_value_dic.items()], reverse=True)\r\n print('La lista de '+ tag_label +' es: ', sorted_tags)\r\n\r\ndef main():\r\n path='C:\\\\Users\\\\poaa\\\\Documents\\\\Python Scripts\\\\sareb01_segundamano.xml'\r\n f = open(path,'r')\r\n full_file=f.read()\r\n promociones=Read_tag_content(full_file,'promocion')\r\n f.close\r\n for w in promociones:\r\n# print ('Obtenida la promoción:')\r\n# print(w)\r\n cod_promo=Read_tag_content(w,'codigo_promocion')[0]\r\n print('*****************************************************************')\r\n print('Codigo Promo:', Read_tag_label(cod_promo,'codigo_promocion'))\r\n propietario=Read_tag_content(w,'propietario')[0]\r\n print('propietario: ',Read_tag_label(propietario,'propietario'))\r\n provincia=Read_tag_content(w,'provincia')[0]\r\n print('Provincia: ',Read_tag_label(provincia,'provincia'))\r\n localidad=Read_tag_content(w,'localidad')[0]\r\n print('localidad: ',Read_tag_label(localidad,'localidad'))\r\n inmuebles=Read_tag_content(w,'inmueble')\r\n for inmueble in inmuebles:\r\n print ('Obtenidos los inmuebles:')\r\n# print(inmueble)\r\n id_inmueble=Read_tag_content(inmueble,'id_inmueble')[0]\r\n referencia=Read_tag_content(inmueble,'referencia')[0]\r\n tipo=Read_tag_content(inmueble,'tipo')[0]\r\n Direccion_inmueble=Read_tag_content(inmueble,'Direccion_inmueble')[0]\r\n precio_venta=Read_tag_content(inmueble,'precio_venta')[0]\r\n precio_alquiler=Read_tag_content(inmueble,'precio_alquiler')[0]\r\n# if tipo.strip()=='Piso':\r\n print('id_inmueble: ',Read_tag_label(id_inmueble,'id_inmueble'))\r\n print('Referencia: ',Read_tag_label(referencia,'referencia'))\r\n print('tipo: ',Read_tag_label(tipo,'tipo'))\r\n print('Direccion_inmueble: ',Read_tag_label(Direccion_inmueble,'Direccion_inmueble'))\r\n print('Precio Venta: ',Read_tag_label(precio_venta,'precio_venta'))\r\n print('Precio Alquiler: ',Read_tag_label(precio_alquiler,'precio_alquiler'))\r\n print('-----------------------------------------------------------------')\r\n \r\n \r\n\r\ndef Read_tag_content(full_file,tag_label):\r\n tag_content = []\r\n tag_end=''\r\n flag_guardar=False\r\n i=0\r\n for line in re.split(r'\\n',full_file):\r\n tag=Find(r'<'+ tag_label +'>',line)\r\n if tag : \r\n flag_guardar=True\r\n tag_content.append('')\r\n if flag_guardar:\r\n tag_content[i]= tag_content[i] + line + '\\n'\r\n tag_end=Find(r'',line)\r\n if tag_end: \r\n i +=1\r\n tag_end=''\r\n flag_guardar=False\r\n return tag_content\r\n\r\ndef Read_tag_label(texto,tag):\r\n value = texto.replace('<'+tag+ '>','')\r\n value = value.replace('','')\r\n return value\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Altamira_extraction.py","file_name":"Altamira_extraction.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"361639426","text":"from pygame import *\r\nfrom PIL import Image\r\nfrom setup import *\r\nfrom random import randint\r\nfrom classes import *\r\n\r\n\r\ndef dist(a, b):\r\n return max(abs(a[0] - b[0]), abs(a[1] - b[1]))\r\n\r\n\r\ndef are_all_green(i1, j1, i2, j2, img):\r\n for i in range(i1, i2):\r\n for j in range(j1, j2):\r\n if img[i, j] != GRASS:\r\n return False\r\n return True\r\n\r\n\r\ndef load_images(path):\r\n stand = [image.load(f'images/{path}/stay.png')] * 5\r\n stand_left = [image.load(f'images/{path}/stay2.png')] * 5\r\n move_right = [image.load(f'images/{path}/run1.png')] * 2 + \\\r\n [image.load(f'images/{path}/run2.png')] * 3\r\n move_left = [image.load(f'images/{path}/run1left.png')] * 2 + \\\r\n [image.load(f'images/{path}/run2left.png')] * 3\r\n attack_right = [stand[0]] + [image.load(f'images/{path}/attack.png')] + [stand[0]] * 3\r\n attack_left = [stand_left[0]] + [image.load(f'images/{path}/attackleft.png')] + [stand_left[0]] * 3\r\n dead = [image.load(f'images/{path}/dead.png')] * 5\r\n dead_left = [image.load(f'images/{path}/deadleft.png')] * 5\r\n return {'stand': stand, 'stand_left': stand_left, 'move_right': move_right, 'move_left': move_left, 'attack_right': attack_right, 'attack_left': attack_left, 'dead_right': dead, 'dead_left': dead_left}\r\n\r\n\r\ndef bfs(map, coords1, coords2):\r\n m = len(map)\r\n n = len(map[0])\r\n s = {i: [] for i in range(m * n)}\r\n used = [0] * n * m\r\n sum_used = 0\r\n for i in range(1, m):\r\n for j in range(1, n):\r\n for di in [-1, 0, 1]:\r\n for dj in [-1, 0, 1]:\r\n if map[i][j] == map[i + di][j + dj] is None:\r\n s[j + (i - 1) * n - 1].append(j + dj - 1 + (i + di - 1) * n)\r\n if map[i][j] is None and not used[j + (i - 1) * n - 1]:\r\n used[j + (i - 1) * n - 1] = 1\r\n sum_used += 1\r\n cur = [[coords1]]\r\n while cur:\r\n new = []\r\n for way in cur:\r\n for node in s[way[-1]]:\r\n if not used[node]:\r\n new.append(way + [node])\r\n used[node] = 1\r\n if node == coords2[0] + coords2[1] * n:\r\n return new[-1]\r\n cur = new\r\n\r\n\r\ndef menu():\r\n pass\r\n\r\n\r\ndef divide_line(coords1, coords2, n):\r\n dx = coords1[0] - coords2[0]\r\n dy = coords1[1] - coords2[1]\r\n if dx % n:\r\n dx += n - dx % n\r\n if dy % n:\r\n dy += n - dy % n\r\n return [(coords1[0] + dx // n * i, coords1[1] + dy // n * i) for i in range(n)][::-1]\r\n\r\n\r\ndef lin2(x, d1, d2):\r\n # прямая, проходящая через 2 заданные точки\r\n x1, y1 = d1\r\n x2, y2 = d2\r\n return ((y1 - y2) * x + x1 * y2 - x2 * y1) / (x1 - x2)\r\n\r\n\r\ndef arrow(st, fn):\r\n # переделывает прямую в \"змейку\" от st до fn\r\n x = st[0]\r\n y = st[1]\r\n res = []\r\n x_w = -1 if fn[0] - x < 0 else 1 # полуплоскость по x\r\n y_w = -1 if fn[1] - y < 0 else 1 # по y\r\n while (x, y) != fn:\r\n # двигаемся от % к @\r\n print(x, y)\r\n dirr = [0, 0]\r\n \"\"\"\r\n ###\r\n @%@\r\n ###\r\n \"\"\"\r\n if y - 0.5 <= lin2(x + 0.5, fn, st) <= y + 0.5:\r\n dirr[0] += 1\r\n\r\n \"\"\"\r\n #@#\r\n #%#\r\n #@#\r\n \"\"\"\r\n if x - 0.5 <= lin2(y + 0.5, fn[::-1], st[::-1]) <= x + 0.5:\r\n dirr[1] += 1\r\n\r\n res += [(x, y)]\r\n x += dirr[0] * x_w\r\n y += dirr[1] * y_w\r\n return res + [(x, y)]\r\n\r\n\r\ndef key_pressed(inputKey):\r\n keysPressed = key.get_pressed()\r\n if keysPressed[inputKey]:\r\n return True\r\n else:\r\n return False","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"529432550","text":"#!/usr/bin/env python3\n\nimport sys\nimport copy\nimport os\n\n\nimport finisher as fin\nfrom cli import Cli\nfrom gamestate import GameState\n\n\n# List of values that can possibly be scored with a single dart\nVALID_INPUTS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,\\\n 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 36,\\\n 38, 39, 40, 42, 45, 48, 50, 51, 54, 57, 60]\n\nclass Player:\n \"\"\"\n Class Player\n \"\"\"\n\n def __init__(self, name, start_points):\n \"\"\"\n inits player, sets name to name and points to start_points\n \"\"\"\n self.name = name\n self.points = start_points\n\n def reduce_points(self, points):\n \"\"\"\n reduces points except the player underflows\n \"\"\"\n if self.points - points >= 0:\n self.points -= points\n\n\ndef print_points(players, finish_func=fin.finish_single):\n \"\"\"\n prints tableish representation of points\n \"\"\"\n print(\"\\n\")\n max_name_length = 0\n for player in players:\n max_name_length = max(max_name_length, len(player.name))\n\n size_of_first_column = max_name_length + 10\n\n print(\" Name\" + (\" \"*(size_of_first_column - 6)) + \"| Points remaining\")\n print((\"=\" * (size_of_first_column + 22)))\n for player in players:\n print(\" \" + player.name\\\n + (\" \" * (size_of_first_column - len(player.name) - 2))\\\n + \"| \" + str(player.points)\\\n + (\" \" * (10 - len(str(player.points))))\\\n + \"| \" + str(fin.finish_to_string(finish_func(player.points))))\n\n\ndef get_players(points):\n \"\"\"\n reads player names until user enters 'stop' and returns list of players\n with player.points set to start_points\n \"\"\"\n players = []\n names = []\n more = True\n num = 1\n while more:\n name = input(\"Enter player number {} or press\".format(num)\\\n + \" enter without entering anything to start playing \")\n if name == \"\":\n if len(players) > 0:\n return copy.deepcopy(players)\n else:\n print(\"You need at least one player\")\n elif name in names:\n print(\"You already entered a player with this name!\")\n else:\n names.append(name)\n players.append(Player(name, points))\n num += 1\n\n\n\ndef check_playernames(players):\n \"\"\"\n checks if given array of names contains one name multiple times\n returns True if no duplicates are contained, False otherwise\n \"\"\"\n names = [p.name for p in players]\n for name in names:\n if names.count(name) > 1:\n print(\"You have entered at least 2 players with the same name.\"\\\n + \" Try again.\")\n return False\n return True\n\n\n\ndef get_start_points(i=0):\n \"\"\"\n input: optional number of supposed points\n returns valid value for startpoints as int\n \"\"\"\n tmp = str(i)\n while tmp not in [\"501\", \"301\"]:\n tmp = input(\"501 or 301 points? \")\n return int(tmp)\n\n\ndef init_game(s_args):\n \"\"\"\n s_args: commandline parameters\n Function parses commandline parameters and returns players and points\n \"\"\"\n players = []\n start_points = 0\n if len(s_args) == 1:\n start_points = get_start_points()\n players = get_players(start_points)\n elif len(s_args) == 2:\n start_points = get_start_points(s_args[1])\n players = get_players(start_points)\n elif len(s_args) > 2:\n start_points = get_start_points(s_args[1])\n if str(start_points) == s_args[1]:\n for i in range(2, len(s_args)):\n players.append(Player(s_args[i], start_points))\n if not check_playernames(players):\n players = get_players(start_points)\n else:\n players = get_players(start_points)\n else:\n print(\"You broke Python!\")\n\n return (copy.deepcopy(players), start_points)\n\ndef print_unnatural_playerchange():\n \"\"\"\n print colorful caps lock messages that the player has changed du to either\n overshooting or skipping\n \"\"\"\n print(\"\\n\\033[91mPLAYER CHANGED DUE TO EITHER\"\\\n + \" OVERSHOOTING OR SKIPPING!!!\\033[0m\")\n print(\"\\n\\033[93mPLAYER CHANGED DUE TO EITHER\"\\\n + \" OVERSHOOTING OR SKIPPING!!!\\033[0m\")\n\n\ndef clear_screen():\n \"\"\"\n clears the screen by scrolling down\n \"\"\"\n os.system('clear')\n os.system('clear')\n\n\ndef main():\n \"\"\"\n main function, ugliest function evaa\n \"\"\"\n\n # init important game variables\n (players, start_points) = init_game(sys.argv)\n finished = False\n round_num = 0\n player_changed_natural = True\n finish_func = fin.finish_double_out\n cli = Cli()\n gamestate = GameState()\n\n # main loop\n while not finished:\n round_num += 1\n\n # loop over players and let them throw their darts\n for player in players:\n clear_screen()\n print(\"Round:\", round_num)\n print_points(players, finish_func)\n skip_player = False\n points = 0\n\n # check if play has either overshooted or was skipped and give\n # visual feedback\n if not player_changed_natural:\n print_unnatural_playerchange()\n player_changed_natural = True\n\n # tell the current player to throw his darts and register his 3\n # throws\n print(\"\\n\\nPlayer:\", player.name)\n dart_nr = 1\n while dart_nr <= 3:\n\n gamestate.set_dart_nr(dart_nr)\n\n # init important round variables\n input_valid = False\n while not input_valid:\n print(\"\\tPoints remaining: \", (player.points - points))\n finish = finish_func(player.points - points, 4 - dart_nr)\n if finish[0]:\n print(\"\\tPossible Finish: {}\".format(fin.finish_to_string(finish)))\n move = cli.get_move(gamestate)\n new_points = -1\n\n if move.is_hit():\n new_points = move.get_point_value()\n if new_points in VALID_INPUTS:\n points += new_points\n input_valid = True\n else:\n # Inform user of invalid input\n print(\"You can not get {} points!\".format(move.get_point_value()))\n dart_nr += 1\n\n elif move.is_skip():\n\n print(\"Skipping player {}\".format(player.name))\n input_valid = True\n skip_player = True\n player_changed_natural = False\n break\n\n elif move.is_help():\n # h means the user needs help\n print_help()\n continue\n\n elif move.is_correction():\n # c means the user wants to correct the points of\n # one of the players\n if correct_points(players) == 1:\n clear_screen()\n print_points(players, finish_func)\n print(\"\\n\\nPlayer:\", player.name)\n else:\n finished = True\n break\n\n else:\n raise Exception(\"Unhandled move {}\".format(move))\n\n\n if finished:\n break\n\n # skip player if needed\n if skip_player:\n break\n\n #check if player has won\n if player.points - points == 0:\n print(player.name, \"won!!!\")\n finished = True\n break\n elif player.points - points < 0:\n # check if player overshot\n print(\"Too much, next player.\\nPoints remaining for {}: {}\"\\\n .format(player.name, player.points))\n player_changed_natural = False\n break\n\n # number of points is valid --> reduce players points\n player.reduce_points(points)\n\n # check if game is over and print points if so\n if finished:\n print_points(players)\n break\n\n print(\"\\tPoints remaining for player {}: {} \".format(player.name, player.points))\n\n\ndef print_help():\n \"\"\"\n prints help for entering points\n \"\"\"\n print(\"\\n\\tx: x points\")\n print(\"\\tdx: double x points\")\n print(\"\\ttx: triple x points\")\n print(\"\\tc: correct points of arbitrary player.\"\\\n + \" Only possible on first darts\")\n print(\"\\th: print help\\n\")\n\ndef correct_points(players):\n \"\"\"\n Enables User to correct points of arbitrary player. (additive)\n \"\"\"\n inp = input(\"\\nChange any player's points?\"\\\n + \" Press Enter for no further changes.\\n\")\n # as long as inp is not empty string\n while inp:\n for p in players:\n if p.name == inp:\n change = input(\"Change how much?\\n\")\n try:\n points = int(change)\n except ValueError:\n print(\"The input needs to be numerical!\")\n else:\n if p.points + points >= 0:\n p.points += points\n if p.points == 0:\n print(\"Player {} has won!\".format(p.name))\n # return 0, means that player has won due to changes\n return 0\n else:\n print(\"Can't change players points below 0\")\n break\n else:\n print(\"No player with name {}\".format(inp))\n print_points(players)\n\n inp = input(\"\\nChange any player's points?\"\\\n + \" Press Enter for no further changes.\\n\")\n\n # return 1, means no player won due to changes\n return 1\n\nif __name__ == '__main__':\n main()\n","sub_path":"dart.py","file_name":"dart.py","file_ext":"py","file_size_in_byte":10242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"262428714","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2012 splinter authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport warnings\n\nfrom fake_webapp import EXAMPLE_APP\n\n\nclass MouseInteractionTest(object):\n\n def test_mouse_over(self):\n \"Should be able to perform a mouse over on an element\"\n self.browser.visit(EXAMPLE_APP)\n self.browser.find_by_css(\".add-element-mouseover\").mouse_over()\n assert self.browser.is_element_present_by_id('what-is-your-name')\n self.browser.find_by_css(\".add-element-mouseover\").mouse_out()\n\n def test_mouse_out(self):\n \"Should be able to perform a mouse out on an element\"\n self.browser.visit(EXAMPLE_APP)\n element = self.browser.find_by_css(\".add-element-mouseover\")\n element.mouse_over()\n element.mouse_out()\n assert not self.browser.is_element_present_by_id('what-is-your-name')\n\n def test_double_click(self):\n \"double click should shows a hidden element\"\n self.browser.visit(EXAMPLE_APP)\n button = self.browser.find_by_css(\".db-button\")\n button.double_click()\n element = self.browser.find_by_css(\n \".should-be-visible-after-double-click\"\n )\n assert element.visible\n assert self.browser.is_element_not_present_by_id('what-is-your-name')\n\n def test_right_click(self):\n \"should be able to perform a right click on an element\"\n self.browser.visit(EXAMPLE_APP)\n element = self.browser.find_by_css(\".right-clicable\")\n element.right_click()\n self.assertEqual(\n self.browser.find_by_css('.right-clicable').text,\n 'right clicked'\n )\n\n def test_drag_and_drop(self):\n \"\"\"\n should be able to perform a drag an element and drop in another element\n \"\"\"\n droppable = self.browser.find_by_css('.droppable')\n draggable = self.browser.find_by_css('.draggable')\n draggable.drag_and_drop(droppable)\n assert self.browser.find_by_css('.dragged').text == 'yes'\n\n def test_mouseover_should_be_an_alias_to_mouse_over(self):\n \"mouseover should be an alias to mouse_over and be deprecated\"\n with warnings.catch_warnings(record=True) as warnings_list:\n self.browser.visit(EXAMPLE_APP)\n warnings.simplefilter(\"always\")\n element = self.browser.find_by_css(\".add-element-mouseover\")\n element.mouseover()\n warn_message = warnings_list[-1].message\n assert type(warn_message) is DeprecationWarning\n assert 'mouse_over' in warn_message.args[0]\n\n def test_mouseout_should_be_an_alias_to_mouse_out_and_be_deprecated(self):\n \"mouseout should be an alias do mouse_out and be deprecated\"\n with warnings.catch_warnings(record=True) as warnings_list:\n self.browser.visit(EXAMPLE_APP)\n warnings.simplefilter(\"always\")\n self.browser.find_by_css(\".add-element-mouseover\").mouseout()\n warn_message = warnings_list[-1].message\n assert type(warn_message) is DeprecationWarning\n assert 'mouse_out' in warn_message.args[0]\n","sub_path":"tests/mouse_interaction.py","file_name":"mouse_interaction.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"233802909","text":"import os\nimport sys\nimport logging\nfrom typing import Optional, List, Tuple\nfrom datetime import datetime\nfrom logging.config import dictConfig as loggingDictConfig\nfrom pathlib import Path\n\nfrom flask import Flask\nfrom inflection import camelize\n\nfrom flexmeasures.utils.config_defaults import (\n Config as DefaultConfig,\n required,\n warnable,\n)\n\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nflexmeasures_logging_config = {\n \"version\": 1,\n \"formatters\": {\n \"default\": {\"format\": \"[FLEXMEASURES][%(asctime)s] %(levelname)s: %(message)s\"},\n \"detail\": {\n \"format\": \"[FLEXMEASURES][%(asctime)s] %(levelname)s: %(message)s [log made in %(pathname)s:%(lineno)d]\"\n },\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n \"formatter\": \"default\",\n },\n \"file\": {\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"level\": \"INFO\",\n \"formatter\": \"detail\",\n \"filename\": basedir + \"/../../flexmeasures.log\",\n \"maxBytes\": 10_000_000,\n \"backupCount\": 6,\n },\n },\n \"root\": {\"level\": \"INFO\", \"handlers\": [\"console\", \"file\"], \"propagate\": True},\n}\n\n\ndef configure_logging():\n \"\"\"Configure and register logging\"\"\"\n loggingDictConfig(flexmeasures_logging_config)\n\n\ndef read_config(app: Flask, path_to_config: Optional[str]):\n \"\"\"Read configuration from various expected sources, complain if not setup correctly. \"\"\"\n\n if app.env not in (\n \"documentation\",\n \"development\",\n \"testing\",\n \"staging\",\n \"production\",\n ):\n print(\n 'Flask(flexmeasures) environment needs to be either \"documentation\", \"development\", \"testing\", \"staging\" or \"production\".'\n )\n sys.exit(2)\n\n # Load default config settings\n app.config.from_object(\n \"flexmeasures.utils.config_defaults.%sConfig\" % camelize(app.env)\n )\n\n # Now read user config, if possible. If no explicit path is given, try home dir first, then instance dir\n path_to_config_home = str(Path.home().joinpath(\".flexmeasures.cfg\"))\n path_to_config_instance = os.path.join(app.instance_path, \"flexmeasures.cfg\")\n if not app.testing:\n used_path_to_config = read_custom_config(\n app, path_to_config, path_to_config_home, path_to_config_instance\n )\n\n # Check for missing values.\n # Testing might affect only specific functionality (-> dev's responsibility)\n # Documentation runs fine without them.\n if not app.testing and app.env != \"documentation\":\n if not are_required_settings_complete(app):\n if not os.path.exists(used_path_to_config):\n print(\n f\"You can provide these settings ― as environment variables or in your config file (e.g. {path_to_config_home} or {path_to_config_instance}).\"\n )\n else:\n print(\n f\"Please provide these settings ― as environment variables or in your config file ({used_path_to_config}).\"\n )\n sys.exit(2)\n missing_fields, config_warnings = get_config_warnings(app)\n if len(config_warnings) > 0:\n for warning in config_warnings:\n print(f\"Warning: {warning}\")\n print(f\"You might consider setting {', '.join(missing_fields)}.\")\n\n # Set the desired logging level on the root logger (controlling extension logging level)\n # and this app's logger.\n logging.getLogger().setLevel(app.config.get(\"LOGGING_LEVEL\", \"INFO\"))\n app.logger.setLevel(app.config.get(\"LOGGING_LEVEL\", \"INFO\"))\n # print(\"Logging level is %s\" % logging.getLevelName(app.logger.level))\n\n app.config[\"START_TIME\"] = datetime.utcnow()\n\n\ndef read_custom_config(\n app, suggested_path_to_config, path_to_config_home, path_to_config_instance\n) -> str:\n \"\"\" read in a custom config file or env vars. Return the path to the config file.\"\"\"\n if suggested_path_to_config is not None and not os.path.exists(\n suggested_path_to_config\n ):\n print(f\"Cannot find config file {suggested_path_to_config}!\")\n sys.exit(2)\n if suggested_path_to_config is None:\n path_to_config = path_to_config_home\n if not os.path.exists(path_to_config):\n path_to_config = path_to_config_instance\n else:\n path_to_config = suggested_path_to_config\n try:\n app.config.from_pyfile(path_to_config)\n except FileNotFoundError:\n pass\n # Finally, all required varaiables can be set as env var:\n for req_var in required:\n app.config[req_var] = os.getenv(req_var, app.config.get(req_var, None))\n return path_to_config\n\n\ndef are_required_settings_complete(app) -> bool:\n \"\"\"\n Check if all settings we expect are not None. Return False if they are not.\n Printout helpful advice.\n \"\"\"\n expected_settings = [s for s in get_configuration_keys(app) if s in required]\n missing_settings = [s for s in expected_settings if app.config.get(s) is None]\n if len(missing_settings) > 0:\n print(\n f\"Missing the required configuration settings: {', '.join(missing_settings)}\"\n )\n return False\n return True\n\n\ndef get_config_warnings(app) -> Tuple[List[str], List[str]]:\n \"\"\"return missing settings and the warnings for them.\"\"\"\n missing_settings = []\n config_warnings = []\n for setting, warning in warnable.items():\n if app.config.get(setting) is None:\n missing_settings.append(setting)\n config_warnings.append(warning)\n config_warnings = list(set(config_warnings))\n return missing_settings, config_warnings\n\n\ndef get_configuration_keys(app) -> List[str]:\n \"\"\"\n Collect all members of DefaultConfig who are not in-built fields or callables.\n \"\"\"\n return [\n a\n for a in DefaultConfig.__dict__\n if not a.startswith(\"__\") and not callable(getattr(DefaultConfig, a))\n ]\n","sub_path":"flexmeasures/utils/config_utils.py","file_name":"config_utils.py","file_ext":"py","file_size_in_byte":6045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"177695505","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: qingwww\n@Problem: http://www.lintcode.com/problem/evaluate-reverse-polish-notation\n@Language: Python\n@Datetime: 16-09-12 03:48\n'''\n\nclass Solution:\n # @param {string[]} tokens The Reverse Polish Notation\n # @return {int} the value\n def evalRPN(self, tokens):\n # Write your code here\n numbers = []\n for letter in tokens:\n if letter == '+' or letter == '-' or letter == '*' or letter == '/':\n a = numbers.pop()\n b = numbers.pop()\n if letter == '+':\n numbers.append(a + b)\n elif letter == '-':\n numbers.append(b - a)\n elif letter == '*':\n numbers.append(a * b)\n else:\n numbers.append(int(b * 1.0 / a))\n else:\n numbers.append(int(letter))\n return numbers[0]","sub_path":"424_evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.py","file_name":"evaluate-reverse-polish-notation.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"465043812","text":"import pandas as pd\nimport tensorflow as tf\nfrom lib.utils import plot_series\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\npath = \"/home/shravan/python_programs/time_series/test_time_series.csv\"\n\n\n\n\ndf = pd.read_csv(path, names=[\"series\"])\ndf['series'] = df['series'] +1\nseries = df['series'].values\ntime = list(range(0, len(series)))\n\n\nsplit_time = 600\ntime_train = time[:split_time]\nx_train = series[:split_time]\ntime_valid = time[split_time:]\nx_valid = series[split_time:]\n\nfrom sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler, Normalizer\nscaler = StandardScaler()\nscaler = RobustScaler()\nscaler = MinMaxScaler()\nscaler = Normalizer()\n\nprint(x_train)\nprint(x_valid)\nx_train = scaler.fit_transform([x_train])[0]\nx_valid = scaler.fit_transform([x_valid])[0]\n\n\nplot_series(time_train, x_train)\nplot_series(time_valid, x_valid)\nprint(x_train)\nprint(x_valid)\n# Hyper parameters\nwindow_size = 24\nbatch_size = 32\nshuffle_buffer_size = 500\n\n\ndef windowed_dataset(series, window_size, batch_size, shuffle_buffer):\n dataset = tf.data.Dataset.from_tensor_slices(series)\n dataset = dataset.window(window_size+1, shift=1, drop_remainder=True)\n dataset = dataset.flat_map(lambda window: window.batch(window_size+1))\n dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1:]))\n dataset = dataset.batch(batch_size).prefetch(1)\n return dataset\n\n\n\n\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nl0 = tf.keras.layers.Dense(1, input_shape=[window_size])\nmodel = tf.keras.models.Sequential([l0])\n\n\nmodel.compile(loss=\"mse\", optimizer=tf.keras.optimizers.SGD(lr=1e-6, momentum=0.9))\nmodel.fit(dataset,epochs=100,verbose=0)\n\nprint(\"Layer weights {}\".format(l0.get_weights()))\n\nforecast = []\n\nfor time in range(len(series) - window_size):\n pr = series[time: time+window_size][np.newaxis]\n pr = scaler.fit_transform(pr)\n forecast.append( model.predict(pr) )\n #forecast.append(model.predict(series[time:time + window_size][np.newaxis]))\n\nforecast = forecast[split_time-window_size:]\nresults = np.array(forecast)[:, 0, 0]\n\n\nplt.figure(figsize=(10, 6))\n\nplot_series(time_valid, x_valid)\nplot_series(time_valid, results)\nplt.show()\n\nprint(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())\n","sub_path":"timeseries/week2/exp/simple_linear_reg.py","file_name":"simple_linear_reg.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469438812","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseSubList(self, beforeHead, tail): \n #rhead is the head of the reversed list\n rhead = beforeHead.next\n rtail = beforeHead.next \n while rhead is not tail:\n tmp = rtail.next\n rtail.next = rtail.next.next\n beforeHead.next = tmp\n tmp.next = rhead\n rhead = tmp\n return \n \n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n if k < 2:\n return head\n cnt = 0\n dummy = ListNode(0)\n dummy.next = head\n l = dummy\n r = dummy\n while r:\n while r and cnt < k:\n cnt += 1\n r = r.next\n if cnt == k and r:\n tmpl, tmpr = l.next, l.next\n self.reverseSubList(l,r)\n l, r = tmpl, tmpr\n cnt = 0 \n return dummy.next","sub_path":"25. Reverse Nodes in k-Group.py","file_name":"25. Reverse Nodes in k-Group.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"276016583","text":"my_list = [6, 3, 5, 2, 9]\n\ntotal = 0\ni = 0\n\nwhile i < len(my_list) and my_list[i] > 0: # len это длина списка, или чего-то другого\n total += my_list[i]\n i += 1\n\nprint(total)\n\n\ni6 = 0\n\nwhile True:\n if i6 == 100:\n break\n print(i6)\n i6 += 1\n","sub_path":"Обучение/While2.py","file_name":"While2.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"399624995","text":"# Copyright 2017 Rice University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tensorflow as tf\nfrom tensorflow.python.ops.rnn_cell_impl import _RNNCell\nimport os\n\n\nclass PretrainedEmbeddingWrapper(_RNNCell):\n def __init__(self, cell, evidence):\n self.cell = cell\n self.evidence = evidence\n self.embedding = tf.get_variable('embedding', [evidence.vocab_size, evidence.units],\n dtype=tf.float32, trainable=False)\n norm = tf.sqrt(tf.reduce_sum(tf.square(self.embedding), 1, keep_dims=True))\n self.norm_embedding = self.embedding / norm\n\n @property\n def state_size(self):\n return self.cell.state_size\n\n @property\n def output_size(self):\n return self.cell.output_size\n\n def __call__(self, inputs, state, scope=None):\n with tf.variable_scope(scope or 'pretrained_embedding_wrapper'):\n with tf.device('/cpu:0'):\n emb_inputs = tf.nn.embedding_lookup(self.norm_embedding, tf.reshape(inputs, [-1]))\n return self.cell(emb_inputs, state)\n\n def load_from(self, sess, save_dir):\n saver = tf.train.Saver({'embedding': self.embedding})\n save = os.path.join(save_dir, 'embed_' + self.evidence.name)\n ckpt = tf.train.get_checkpoint_state(save)\n assert ckpt and ckpt.model_checkpoint_path, 'Could not find embeddings in {}'.format(save)\n saver.restore(sess, ckpt.model_checkpoint_path)\n print('Loaded embeddings for {} from {}'.format(self.evidence.name, save))\n","sub_path":"src/main/python/bayou/core/cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"71383373","text":"import itertools\n\nimport pytest\n\nimport ahpy\n\n# Example from Saaty, Thomas L., 'Decision making with the analytic hierarchy process,'\n# Int. J. Services Sciences, 1:1, 2008, pp. 83-98.\n\ndrinks = {('coffee', 'wine'): 9, ('coffee', 'tea'): 5, ('coffee', 'beer'): 2, ('coffee', 'soda'): 1,\n ('coffee', 'milk'): 1,\n ('water', 'coffee'): 2, ('water', 'wine'): 9, ('water', 'tea'): 9,\n ('water', 'beer'): 3, ('water', 'soda'): 2, ('water', 'milk'): 3,\n ('tea', 'wine'): 3,\n ('beer', 'wine'): 9, ('beer', 'tea'): 3, ('beer', 'milk'): 1,\n ('soda', 'wine'): 9, ('soda', 'tea'): 4, ('soda', 'beer'): 2, ('soda', 'milk'): 2,\n ('milk', 'wine'): 9, ('milk', 'tea'): 3}\n\n\ndef test_drinks_cr_saaty():\n c = ahpy.Compare('Drinks', drinks, precision=3, random_index='saaty')\n assert c.consistency_ratio == 0.022\n\n\ndef test_drinks_cr_dd():\n c = ahpy.Compare('Drinks', drinks, precision=4, random_index='dd')\n assert c.consistency_ratio == 0.0235\n\n\ndef test_drinks_weights_precision_3_saaty():\n c = ahpy.Compare('Drinks', drinks, precision=3, random_index='saaty')\n assert c.local_weights == {'beer': 0.116, 'coffee': 0.177, 'milk': 0.129, 'soda': 0.190,\n 'tea': 0.042, 'water': 0.327, 'wine': 0.019}\n\n\ndef test_drinks_weights_precision_4_dd():\n c = ahpy.Compare('Drinks', drinks, precision=4, random_index='dd')\n assert c.local_weights == {'beer': 0.1164, 'coffee': 0.1775, 'milk': 0.1288, 'soda': 0.1896,\n 'tea': 0.0418, 'water': 0.3268, 'wine': 0.0191}\n\n\n# Example from Saaty, Thomas, L., Theory and Applications of the Analytic Network Process, 2005.\n\ncriteria = {('Culture', 'Housing'): 3, ('Culture', 'Transportation'): 5,\n ('Family', 'Culture'): 5, ('Family', 'Housing'): 7, ('Family', 'Transportation'): 7,\n ('Housing', 'Transportation'): 3,\n ('Jobs', 'Culture'): 2, ('Jobs', 'Housing'): 4, ('Jobs', 'Transportation'): 7,\n ('Family', 'Jobs'): 1}\n\nculture = {('Bethesda', 'Pittsburgh'): 1,\n ('Boston', 'Bethesda'): 2, ('Boston', 'Pittsburgh'): 2.5, ('Boston', 'Santa Fe'): 1,\n ('Pittsburgh', 'Bethesda'): 1,\n ('Santa Fe', 'Bethesda'): 2, ('Santa Fe', 'Pittsburgh'): 2.5}\n\nfamily = {('Bethesda', 'Boston'): 2, ('Bethesda', 'Santa Fe'): 4,\n ('Boston', 'Santa Fe'): 2,\n ('Pittsburgh', 'Bethesda'): 3, ('Pittsburgh', 'Boston'): 8, ('Pittsburgh', 'Santa Fe'): 9}\n\nhousing = {('Bethesda', 'Boston'): 5, ('Bethesda', 'Santa Fe'): 2.5,\n ('Pittsburgh', 'Bethesda'): 2, ('Pittsburgh', 'Boston'): 9, ('Pittsburgh', 'Santa Fe'): 7,\n ('Santa Fe', 'Boston'): 4}\n\njobs = {('Bethesda', 'Pittsburgh'): 3, ('Bethesda', 'Santa Fe'): 4,\n ('Boston', 'Bethesda'): 2, ('Boston', 'Pittsburgh'): 6, ('Boston', 'Santa Fe'): 8,\n ('Pittsburgh', 'Santa Fe'): 1}\n\ntransportation = {('Bethesda', 'Boston'): 1.5,\n ('Bethesda', 'Santa Fe'): 4,\n ('Boston', 'Santa Fe'): 2.5,\n ('Pittsburgh', 'Bethesda'): 2,\n ('Pittsburgh', 'Boston'): 3.5,\n ('Pittsburgh', 'Santa Fe'): 9}\n\n\ndef test_cities_weights_saaty_precision_3():\n cu = ahpy.Compare('Culture', culture, precision=3, random_index='Saaty')\n f = ahpy.Compare('Family', family, precision=3, random_index='Saaty')\n h = ahpy.Compare('Housing', housing, precision=3, random_index='Saaty')\n j = ahpy.Compare('Jobs', jobs, precision=3, random_index='Saaty')\n t = ahpy.Compare('Transportation', transportation, precision=3, random_index='Saaty')\n\n cr = ahpy.Compare('Goal', criteria, precision=3, random_index='Saaty')\n cr.add_children([cu, f, h, j, t])\n\n assert cr.target_weights == {'Bethesda': 0.229, 'Boston': 0.275, 'Pittsburgh': 0.385, 'Santa Fe': 0.111}\n\n\ndef test_cities_weights_dd_precision_4():\n cu = ahpy.Compare('Culture', culture, precision=4)\n f = ahpy.Compare('Family', family, precision=4)\n h = ahpy.Compare('Housing', housing, precision=4)\n j = ahpy.Compare('Jobs', jobs, precision=4)\n t = ahpy.Compare('Transportation', transportation, precision=4)\n\n cr = ahpy.Compare('Goal', criteria, precision=4)\n cr.add_children([cu, f, h, j, t])\n\n assert cr.target_weights == {'Bethesda': 0.2291, 'Boston': 0.2748, 'Pittsburgh': 0.3852, 'Santa Fe': 0.1110}\n\n\ndef test_cities_target_weights():\n cu = ahpy.Compare('Culture', culture, precision=4)\n f = ahpy.Compare('Family', family, precision=4)\n h = ahpy.Compare('Housing', housing, precision=4)\n j = ahpy.Compare('Jobs', jobs, precision=4)\n t = ahpy.Compare('Transportation', transportation, precision=4)\n\n cr = ahpy.Compare('Goal', criteria, precision=4)\n cr.add_children([cu, f, h, j, t])\n\n assert t.target_weights is None\n\n# Examples from Bozóki, S., Fülöp, J. and Rónyai, L., 'On optimal completion of incomplete\n# pairwise comparison matrices,' Mathematical and Computer Modelling, 52:1–2, 2010, pp. 318-333.\n# https://doi.org/10.1016/j.mcm.2010.02.047\n\nu = {('a', 'b'): 1, ('a', 'c'): 5, ('a', 'd'): 2,\n ('b', 'c'): 3, ('b', 'd'): 4}\n\n\ndef test_incomplete_example_missing_comparisons():\n cu = ahpy.Compare('Incomplete Example', u)\n assert cu._missing_comparisons == pytest.approx({('c', 'd'): 0.730297106886979})\n\n\ndef test_incomplete_example_weights():\n cu = ahpy.Compare('Incomplete Example', u)\n assert cu.local_weights == {'a': 0.3738, 'b': 0.392, 'c': 0.0985, 'd': 0.1357}\n\n\ndef test_incomplete_example_cr():\n cu = ahpy.Compare('Incomplete Example', u)\n assert cu.consistency_ratio == 0.0372\n\n\ndef test_incomplete_housing_missing_comparisons():\n m = {('a', 'b'): 5, ('a', 'c'): 3, ('a', 'd'): 7, ('a', 'e'): 6, ('a', 'f'): 6,\n ('b', 'd'): 5, ('b', 'f'): 3,\n ('c', 'e'): 3, ('c', 'g'): 6,\n ('f', 'd'): 4,\n ('g', 'a'): 3, ('g', 'e'): 5,\n ('h', 'a'): 4, ('h', 'b'): 7, ('h', 'd'): 8, ('h', 'f'): 6}\n cm = ahpy.Compare('Incomplete Housing', m)\n assert (cm._missing_comparisons ==\n pytest.approx({('b', 'c'): 0.3300187496240363, ('b', 'e'): 1.7197409185349517,\n ('b', 'g'): 0.4663515002203321, ('c', 'd'): 9.920512661898753,\n ('c', 'f'): 4.852486449214693, ('c', 'h'): 0.5696073301509899,\n ('d', 'e'): 0.5252768142894285, ('d', 'g'): 0.1424438146531802,\n ('e', 'f'): 0.9311973564754218, ('e', 'h'): 0.10930828182051665,\n ('f', 'g'): 0.2912120796181874, ('g', 'h'): 0.4030898885178746}))\n\n\n# Example from Haas, R. and Meixner, L., 'An Illustrated Guide to the Analytic Hierarchy Process,'\n# http://www.inbest.co.il/NGO/ahptutorial.pdf\n\ndef test_normalized_weights():\n fuel = {'civic': 34, 'saturn': 27, 'escort': 24, 'clio': 28}\n cf = ahpy.Compare('Fuel Economy', fuel)\n assert cf.local_weights == {'civic': 0.3009, 'saturn': 0.2389, 'escort': 0.2124, 'clio': 0.2478}\n\n\nalphabet = 'abcdefghijklmnopqrstuvwxyz'\nvalues = {'a': 0.0385, 'b': 0.0385, 'c': 0.0385, 'd': 0.0385, 'e': 0.0385, 'f': 0.0385, 'g': 0.0385, 'h': 0.0385,\n 'i': 0.0385, 'j': 0.0385, 'k': 0.0385, 'l': 0.0385, 'm': 0.0385, 'n': 0.0385, 'o': 0.0385, 'p': 0.0385,\n 'q': 0.0385, 'r': 0.0385, 's': 0.0385, 't': 0.0385, 'u': 0.0385, 'v': 0.0385, 'w': 0.0385, 'x': 0.0385,\n 'y': 0.0385, 'z': 0.0385}\n\n\ndef test_size_limit_saaty():\n with pytest.raises(ValueError):\n x = dict.fromkeys(itertools.permutations(alphabet, 2), 1)\n ahpy.Compare('CR Test', x, random_index='saaty')\n\n\ndef test_size_limit_override_saaty():\n x = dict.fromkeys(itertools.permutations(alphabet, 2), 1)\n cx = ahpy.Compare('CR Test', x, random_index='saaty', cr=False)\n assert cx.local_weights == values\n\n\ndef test_size_limit_normalize_saaty():\n y = dict.fromkeys([i[0] for i in itertools.combinations(alphabet, 1)], 1)\n cy = ahpy.Compare('CR Test', y, random_index='saaty')\n assert cy.local_weights == values\n\n\na_m = {('b', 'c'): 1}\nb_m = {('d', 'e'): 4}\nd_m = {('f', 'g'): 2}\n\nc_m = {'x': 2, 'y': 4, 'z': 4}\ne_m = {'x': 1, 'y': 2, 'z': 3}\nf_m = {'x': 2, 'y': 4, 'z': 4}\ng_m = {'x': 1, 'y': 2, 'z': 3}\n\na = ahpy.Compare('a', a_m)\nb = ahpy.Compare('b', b_m)\nc = ahpy.Compare('c', c_m)\nd = ahpy.Compare('d', d_m)\ne = ahpy.Compare('e', e_m)\nf = ahpy.Compare('f', f_m)\ng = ahpy.Compare('g', g_m)\n\na.add_children([b, c])\nb.add_children([d, e])\nd.add_children([f, g])\n\n\ndef test_master_a():\n assert a.report() == {'name': 'a', 'weight': 1.0, 'weights': {'local': {'b': 0.5, 'c': 0.5}, 'global': {'b': 0.5, 'c': 0.5}, 'target': {'z': 0.4233, 'y': 0.3844, 'x': 0.1922}}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 2, 'names': ['b', 'c']}, 'children': {'count': 2, 'names': ['b', 'c']}, 'comparisons': {'count': 1, 'input': {('b', 'c'): 1}, 'computed': None}}\n\n\ndef test_master_b():\n assert b.report() == {'name': 'b', 'weight': 0.5, 'weights': {'local': {'d': 0.8, 'e': 0.2}, 'global': {'d': 0.4, 'e': 0.1}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 2, 'names': ['d', 'e']}, 'children': {'count': 2, 'names': ['d', 'e']}, 'comparisons': {'count': 1, 'input': {('d', 'e'): 4}, 'computed': None}}\n\n\ndef test_master_c():\n assert c.report() == {'name': 'c', 'weight': 0.5, 'weights': {'local': {'y': 0.4, 'z': 0.4, 'x': 0.2}, 'global': {'y': 0.2, 'z': 0.2, 'x': 0.1}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 3, 'names': ['x', 'y', 'z']}, 'children': None, 'comparisons': {'count': 3, 'input': {'x': 2, 'y': 4, 'z': 4}, 'computed': None}}\n\n\ndef test_master_d():\n assert d.report() == {'name': 'd', 'weight': 0.4, 'weights': {'local': {'f': 0.6667, 'g': 0.3333}, 'global': {'f': 0.2667, 'g': 0.1333}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 2, 'names': ['f', 'g']}, 'children': {'count': 2, 'names': ['f', 'g']}, 'comparisons': {'count': 1, 'input': {('f', 'g'): 2}, 'computed': None}}\n\n\ndef test_master_e():\n assert e.report() == {'name': 'e', 'weight': 0.1, 'weights': {'local': {'z': 0.5, 'y': 0.3333, 'x': 0.1667}, 'global': {'z': 0.05, 'y': 0.0333, 'x': 0.0167}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 3, 'names': ['x', 'y', 'z']}, 'children': None, 'comparisons': {'count': 3, 'input': {'x': 1, 'y': 2, 'z': 3}, 'computed': None}}\n\n\ndef test_master_f():\n assert f.report() == {'name': 'f', 'weight': 0.2667, 'weights': {'local': {'y': 0.4, 'z': 0.4, 'x': 0.2}, 'global': {'y': 0.1067, 'z': 0.1067, 'x': 0.0533}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 3, 'names': ['x', 'y', 'z']}, 'children': None, 'comparisons': {'count': 3, 'input': {'x': 2, 'y': 4, 'z': 4}, 'computed': None}}\n\n\ndef test_master_g():\n assert g.report() == {'name': 'g', 'weight': 0.1333, 'weights': {'local': {'z': 0.5, 'y': 0.3333, 'x': 0.1667}, 'global': {'z': 0.0666, 'y': 0.0444, 'x': 0.0222}, 'target': None}, 'consistency_ratio': 0.0, 'random_index': 'Donegan & Dodd', 'elements': {'count': 3, 'names': ['x', 'y', 'z']}, 'children': None, 'comparisons': {'count': 3, 'input': {'x': 1, 'y': 2, 'z': 3}, 'computed': None}}\n","sub_path":"tests/test_ahp.py","file_name":"test_ahp.py","file_ext":"py","file_size_in_byte":11337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"343055381","text":"import logging, arcpy, ntpath\nfrom CommonUtils import CustomException, removeWhenExist, printInfo\nfrom mapPublishingUtils.basePublisher import basePublisher\nimport xml.dom.minidom as DOM\n\n__author__ = 'ghassan_karwchan'\nclass DraftCreator(basePublisher):\n def createDraft(self, connectionFile):\n try:\n removeWhenExist(self.draftPath)\n analysis = arcpy.mapping.CreateMapSDDraft(self.mapDocument, self.draftPath, self.serviceName, 'ARCGIS_SERVER', connectionFile, False, self.serviceFolder)\n if analysis['errors'] != {}:\n raise CustomException('createDraft: creating draft')\n logging.debug('\\t\\tcreated initial draft')\n self.xmlDocument = DOM.parse(self.draftPath)\n if self.serviceExist(self.serviceName, self.serviceFolder):\n self.__setPublishToOverwrite()\n logging.debug('\\t\\tchanged draft definition to overwrite')\n self.__disableKml()\n if self.serviceFolder.upper() == 'BASEMAP':\n self.__setServiceProperty('textAntialiasingMode', 'None')\n else:\n self.__setServiceProperty('antialiasingMode', 'Best')\n logging.debug('\\t\\tchanged draft definition to not publish kml')\n fileWriter = open(self.draftPath, 'w')\n self.xmlDocument.writexml(fileWriter)\n fileWriter.close()\n printInfo ('\\t\\tcreated draft')\n except Exception as e:\n logging.error('error creating draft: ' + e.message)\n raise CustomException('createDraft: creating draft')\n def __setPublishToOverwrite(self):\n descriptions = self.xmlDocument.getElementsByTagName('Type')\n for desc in descriptions:\n if desc.parentNode.tagName == 'SVCManifest':\n if desc.hasChildNodes():\n desc.firstChild.data = 'esriServiceDefinitionType_Replacement'\n def __disableKml(self):\n typeNames = self.xmlDocument.getElementsByTagName('TypeName')\n for typeName in typeNames:\n if typeName.firstChild.data == 'KmlServer':\n extension = typeName.parentNode\n for extElement in extension.childNodes:\n if extElement.tagName == 'Enabled':\n extElement.firstChild.data = 'false'\n def __setServiceProperty(self, key, value):\n configuration = self.xmlDocument.getElementsByTagName('ConfigurationProperties').item(0)\n properties = configuration.getElementsByTagName('PropertySetProperty')\n for property in properties:\n if property.getElementsByTagName('Key').item(0).firstChild.nodeValue == key:\n property.getElementsByTagName('Value').item(0).firstChild.data = value\n logging.debug('\\t\\tchanged service property {0} to {1}'.format(key, value))\n\n\n","sub_path":"mapPublishingUtils/DraftCreator.py","file_name":"DraftCreator.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"401207624","text":"__doc__ = r\"\"\"\n.. _dumper\n:mod:`dumper` -- CAMxtools dump module\n============================================\n\n... module:: projection\n :platform: Unix, Windows\n :synopsis: It returns arrays of latitudes and longitudes\n at the center of grid cells either form latlon\n (ll2latlon) or lambert (lcp2latlon)\n :history: Original version - zliu 10/24/2016\n Formatted for CAMxtools - jjung 1/5/2018\n... moduleauthor:: Jaegun Jung \n\"\"\"\n\n__all__=['ll2latlon','lcp2latlon',]\nimport numpy as np\n\ndef ll2latlon (x0, y0, dxy, nx, ny, *, lno_edges=True):\n xcoords = x0 + np.arange(nx) * dxy + dxy/2\n ycoords = y0 + np.arange(ny) * dxy + dxy/2\n lons = np.zeros ((ny, nx)) ; lats = np.zeros ((ny, nx))\n for i in range ( nx ) :\n for j in range ( ny ) :\n lons[j,i]=xcoords[i]\n lats[j,i]=ycoords[j]\n\n if lno_edges:\n lats_ctr = lats[1:ny-1,1:nx-1]; lons_ctr = lons[1:ny-1,1:nx-1] \n else:\n lats_ctr = lats[:,:]; lons_ctr = lons[:,:]\n\n return lats_ctr, lons_ctr\n\ndef lcp2latlon (lcc, dxy, nx, ny, *, lno_edges=True):\n xcoords = np.arange(nx) * dxy + dxy/2\n ycoords = np.arange(ny) * dxy + dxy/2\n lons = np.zeros ((ny, nx)) ; lats = np.zeros ((ny, nx))\n for i in range ( nx ) :\n for j in range ( ny ) :\n lon,lat = lcc ( xcoords[i],ycoords[j],inverse = 'true')\n lons[j,i]=lon ; lats[j,i]=lat\n\n if lno_edges:\n lats_ctr = lats[1:ny-1,1:nx-1]; lons_ctr = lons[1:ny-1,1:nx-1] \n else:\n lats_ctr = lats[:,:]; lons_ctr = lons[:,:]\n\n return lats_ctr, lons_ctr\n","sub_path":"src/CAMxtools/tzone/projection.py","file_name":"projection.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"234871874","text":"import numpy as np\ndef find_diff(a, b):\n diff_index = np.array(list(a)) != np.array(list(b))\n a=np.array(list(a))\n diff = list(a[diff_index])\n result_str = \"\".join(diff)\n return result_str\ntwo = input()\ntwolist = list(two)\nthree = input()\ntruenum=\"\"\ndef toStr(n, base):\n convertString = \"0123456789ABCDEF\"\n if n < base:\n return convertString[n]\n else:\n return toStr(n // base, base) + convertString[n % base]\nfor i in range(len(twolist)):\n temp = twolist.copy()\n if temp[i] == \"1\":\n temp[i] = \"0\"\n else:\n temp[i] = \"1\"\n temptwostr=\"\".join(temp)\n twotoTen = int(temptwostr, 2)\n twotoThree = toStr(twotoTen, 3)\n if len(twotoThree)>len(three):continue\n if len(three)-len(twotoThree)>1:continue\n if len(three)-len(twotoThree)==1:\n threetemp=list(twotoThree)\n threetemp.insert(0,\"0\")\n twotoThree=\"\".join(threetemp)\n temdiffstr=find_diff(twotoThree,three)\n if len(temdiffstr)==1:\n truenum=twotoTen\n break\n else:continue\nprint(truenum,end=\"\")","sub_path":"Code/CodeRecords/2951/61135/311541.py","file_name":"311541.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"472070482","text":"def PrintArray(arr): # 배열 출력 함수\n for i in range(len(arr)):\n print(arr[i], end=\" \")\n\narr=[30, 60, 90, 10, 40, 80, 40, 20, 10, 60, 50, 30, 40, 90, 80]\nn = len(arr) # 배열 길이\ngap = 5 # 배열 내 비교대상의 간격\ncount=1 # 회전 출력을 위한 변수\n\nprint(\"Default : \", end=\"\") # 기본 배열 출력\nPrintArray(arr)\n\nwhile(gap>=1):\n i=gap\n print(\"\\n\\ngap = %d\" % gap, end=\"\") # gap값 출력\n while(i=0 and value 200:\r\n print(\"Es Seguro Proceder!!!\")\r\nelse:\r\n print(\"Consigue Gas!!!\")\r\n","sub_path":"Repaso Python Desarrollo App Web/2 - Gas De Ultima Oportunidad.py","file_name":"2 - Gas De Ultima Oportunidad.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"2117802","text":"import discord\nfrom discord.ext import commands\nimport cv2\nimport tensorflow as tf\nimport numpy as np\nimport requests\nCATEGORIES = [\"Dog\", \"Cat\"]\n\n\nasync def prepare(response):\n IMG_SIZE = 100 # 50 in txt-based\n image = np.asarray(bytearray(response.content), dtype=\"uint8\")\n img_array = cv2.imdecode(image, cv2.cv2.IMREAD_GRAYSCALE)\n new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\n return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n\n\nmodel = tf.keras.models.load_model(\"C:/Users/Lukas/PycharmProjects/\"\n \"DiscordBot/3-conv-64-nodes-0-dense-1540176132.model\")\n\n\nclass CatOrDog:\n def __init__(self, client):\n self.client = client\n\n async def on_message(self, pic):\n if pic.attachments:\n for attachment in pic.attachments:\n print(attachment['url'])\n r = requests.get(attachment['url'], allow_redirects=True)\n x = await prepare(r)\n prediction = model.predict([x])\n print(prediction[0])\n obj = 'Nicht Vorhanden'\n num1, num2 = prediction[0]\n if num1 < 1 and num2 < 1:\n obj = ' Hund'\n if num1 < 1 and num2 >= 1:\n obj = 'e Katze'\n if num1 >=1 and num2 >=1:\n obj = ' HaydeKlum'\n if num1 >=1 and num2 < 1:\n obj = ' Julian'\n await self.client.send_message(pic.channel, f\"Das ist ein{obj}\")\n await self.client.send_message(pic.channel, f\"Debug Log prediction werte {prediction[0]}\")\n\n\ndef setup(client):\n client.add_cog(CatOrDog(client))\n","sub_path":"CatOrDog.py","file_name":"CatOrDog.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"461006311","text":"import numpy as np\nfrom calc_gini import calc_gini2\n\nclass Node2():\n def __init__(self,data,labels,parent = None,left=None,right=None,depth=0):\n self.data = data\n self.labels = labels\n self.left = left\n self.right = right\n self.depth = depth\n self.gini = calc_gini2(self)\n self.leaf_list = np.array([])\n\n def classify(self,threshold):\n left_index = np.where(self.data[:,self.depth] < threshold)[0]\n right_index = np.where(self.data[:,self.depth] >= threshold)[0]\n self.left = self.data[left_index],self.labels[left_index]\n self.right = self.data[right_index],self.labels[right_index]\n\n def set_node(self):\n left = self.left\n right = self.right\n self.left_node = Node2(left[0],left[1],parent=self,depth=self.depth+1)\n self.right_node = Node2(right[0],right[1],parent=self,depth=self.depth+1)\n\n def calc_info_gain(self):\n parent = self\n left = parent.left_node\n right = parent.right_node\n if len(parent.labels)==0:\n total_gini = parent.gini\n else:\n #print(left.gini)\n total_gini = (len(left.labels)/len(parent.labels))*left.gini + (len(right.labels)/len(parent.labels))*right.gini\n return parent.gini - total_gini\n","sub_path":"Decision_Tree/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"531785422","text":"def subsequence_subs(first, second): \n\tlen_first = len(first) \n\tlen_sec = len(second) \n\n\tdp = [[0] * (len_sec + 1) for i in range(len_first + 1)]\n\n\tfor i in range(len_first + 1): \n\t\tdp[i][0] = 1\n\n\tfor i in range(1, len_first + 1): \n\t\tfor j in range(1, len_sec + 1): \n\t\t\t\n\t\t\tif first[i - 1] == second[j - 1]: \n\t\t\t\tdp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] \n\t\t\t\t\n\t\t\telse: \n\t\t\t\tdp[i][j] = dp[i - 1][j] \n\t#print(dp)\n\treturn dp[len_first][len_sec] \n\ncases = int(input())\nfor i in range(cases):\n\tletters = int(input())\n\tline = input().rstrip()\n\tprint(subsequence_subs(line, \"COW\"))","sub_path":"programming-team/First Semester/Eigth/cow.py","file_name":"cow.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"13856398","text":"import torchvision\nimport os\nimport ujson as json\nimport numpy as np\nfrom tqdm import tqdm\nfrom PIL import Image\n\n\n# TuSimple direct loading\nclass TuSimple(torchvision.datasets.VisionDataset):\n def __init__(self, root, image_set, transforms=None, transform=None, target_transform=None,\n ppl=56, gap=10, start=160):\n super().__init__(root, transforms, transform, target_transform)\n self.ppl = ppl\n self.gap = gap\n self.start = start # y coordinate to start annotation\n\n # Checks\n if not os.path.exists('./output'):\n os.makedirs('./output')\n if image_set not in ['train', 'val', 'test']:\n raise ValueError\n\n # Data list\n with open(os.path.join(root, 'lists', image_set + '.txt'), \"r\") as f:\n contents = [x.strip() for x in f.readlines()]\n\n # Load image filenames and lanes\n if image_set == 'test' or image_set == 'val': # Test\n self.images = [os.path.join(root, 'clips', x + '.jpg') for x in contents]\n self.targets = [os.path.join(root, 'clips', x + '.jpg') for x in contents]\n else: # Train\n self.images = [os.path.join(root, 'clips', x[:x.find(' ')] + '.jpg') for x in contents]\n\n # Load target lanes (small dataset, directly load all of them in the memory)\n print('Loading targets into memory...')\n target_files = [os.path.join(root, 'label_data_0313.json'),\n os.path.join(root, 'label_data_0601.json')]\n json_contents = self.concat_jsons(target_files)\n self.targets = []\n for i in tqdm(range(len(json_contents))):\n lines = json_contents[i]['lanes']\n h_samples = json_contents[i]['h_samples']\n temp = np.array([[[-2.0, self.start + j * self.gap] for j in range(self.ppl)]\n for _ in range(len(lines))], dtype=np.float32)\n for j in range(len(h_samples)):\n for k in range(len(lines)):\n temp[k][temp[k][:, 1] == h_samples[j]] = [float(lines[k][j]), h_samples[j]]\n self.targets.append(temp)\n\n assert len(self.targets) == len(self.images)\n\n def __getitem__(self, index):\n # Return x (input image) & y (L lane with N coordinates (x, y) as np.array (L x N x 2))\n # Empty coordinates are marked by (-2, y)\n # If just testing,\n # y is the filename to store prediction\n img = Image.open(self.images[index]).convert('RGB')\n target = self.targets[index]\n\n # Transforms\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n\n return img, target\n\n def __len__(self):\n return len(self.images)\n\n @staticmethod\n def concat_jsons(filenames):\n # Concat tusimple lists in jsons (actually only each line is json)\n results = []\n for filename in filenames:\n with open(filename, 'r') as f:\n results += [json.loads(x.strip()) for x in f.readlines()]\n\n return results\n","sub_path":"utils/datasets/tusimple.py","file_name":"tusimple.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469241231","text":"import esphome.codegen as cg\nimport esphome.config_validation as cv\nfrom esphome.components import display\nfrom esphome.const import CONF_ID, CONF_LAMBDA\n\nadafruitlcd_ns = cg.esphome_ns.namespace('adafruitlcd')\nAdafruitLCDComponent = adafruitlcd_ns.class_('AdafruitLCDComponent', cg.PollingComponent)\n \nCONFIG_SCHEMA = display.BASIC_DISPLAY_SCHEMA.extend({\n cv.GenerateID(): cv.declare_id(AdafruitLCDComponent),\n}).extend(cv.polling_component_schema('1s'))\n\ndef to_code(config):\n var = cg.new_Pvariable(config[CONF_ID])\n yield cg.register_component(var, config)\n\n if CONF_LAMBDA in config:\n lambda_ = yield cg.process_lambda(config[CONF_LAMBDA],\n [(AdafruitLCDComponent.operator('ref'), 'it')],\n return_type=cg.void)\n cg.add(var.set_writer(lambda_))\n\n","sub_path":"custom_components/adafruitlcd/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"26211176","text":"\"\"\" A custom dialog for introspection of search paths.\"\"\"\n\nimport numpy as np\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar\nfrom matplotlib.figure import Figure\n\nfrom PyQt4 import QtCore, QtGui\n\n#===============================================================================\n# Custom dialog generated by qt-designer.\n#===============================================================================\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n _fromUtf8 = lambda s: s\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(_fromUtf8(\"Dialog\"))\n Dialog.resize(1233, 624)\n Dialog.setWindowTitle(QtGui.QApplication.translate(\"Dialog\", \"Dialog\", None, QtGui.QApplication.UnicodeUTF8))\n self.horizontalLayout = QtGui.QHBoxLayout(Dialog)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.splitter = QtGui.QSplitter(Dialog)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())\n self.splitter.setSizePolicy(sizePolicy)\n self.splitter.setMinimumSize(QtCore.QSize(400, 0))\n self.splitter.setOrientation(QtCore.Qt.Horizontal)\n self.splitter.setObjectName(_fromUtf8(\"splitter\"))\n self.widget = MyDynamicMplCanvas(self.splitter)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())\n self.widget.setSizePolicy(sizePolicy)\n self.widget.setMinimumSize(QtCore.QSize(1000, 600))\n self.widget.setObjectName(_fromUtf8(\"widget\"))\n \n self.layoutWidget = QtGui.QWidget(self.splitter)\n self.layoutWidget.setObjectName(_fromUtf8(\"layoutWidget\"))\n self.verticalLayout_2 = QtGui.QVBoxLayout(self.layoutWidget)\n self.verticalLayout_2.setSpacing(10)\n self.verticalLayout_2.setContentsMargins(-1, 6, -1, -1)\n self.verticalLayout_2.setObjectName(_fromUtf8(\"verticalLayout_2\"))\n self.label = QtGui.QLabel(self.layoutWidget)\n self.label.setMaximumSize(QtCore.QSize(200, 16777215))\n self.label.setText(QtGui.QApplication.translate(\"Dialog\", \"Fittings\", None, QtGui.QApplication.UnicodeUTF8))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.verticalLayout_2.addWidget(self.label)\n self.listWidget = QtGui.QListWidget(self.layoutWidget)\n self.listWidget.setObjectName(_fromUtf8(\"listWidget\"))\n self.verticalLayout_2.addWidget(self.listWidget)\n self.horizontalLayout.addWidget(self.splitter)\n self.verticalLayout_2.addWidget(NavigationToolbar(self.widget, Dialog))\n \n self.listWidget.connect(\n self.listWidget, \n QtCore.SIGNAL(\"currentItemChanged (QListWidgetItem *,QListWidgetItem *)\"), \n self.itemChangedSlot)\n \n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n \n def itemChangedSlot(self, item, item2):\n self.widget.formPlot(self.searchMap[item])\n \n def updateList(self, search):\n \"\"\"\n Takes the search datastructure and makes a list of it.\n \"\"\"\n \n self.searchMap = {}\n for index, step in enumerate(search):\n item = QtGui.QListWidgetItem(self.listWidget)\n item.setText(\n \"#{0}, e: {1}\".format(\n index,\n step.error\n )\n )\n \n if not step.decreasing:\n item.setBackgroundColor(QtGui.QColor(\"red\"))\n self.searchMap[item] = step\n \n def retranslateUi(self, Dialog):\n pass\n\n###############################################################################\n# MPL widget \n###############################################################################\n\nclass MyMplCanvas(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\n def __init__(self, parent=None, step=None):\n self.fig = Figure()\n \n self.ax1 = self.fig.add_subplot(1,3,1)\n self.ax2 = self.fig.add_subplot(1,3,2)\n self.ax3 = self.fig.add_subplot(1,3,3)#, sharex=self.ax1, sharey=self.ax1)\n \n if step is not None:\n self.formPlot(step)\n \n FigureCanvas.__init__(self, self.fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(\n self,\n QtGui.QSizePolicy.Expanding,\n QtGui.QSizePolicy.Expanding)\n \n FigureCanvas.updateGeometry(self)\n\nclass MyDynamicMplCanvas(MyMplCanvas):\n \"\"\"A canvas that updates itself every second with a new plot.\"\"\"\n def __init__(self, *args, **kwargs):\n MyMplCanvas.__init__(self, *args, **kwargs)\n\n def formPlot(self, step):\n \"\"\"\n A graphical representation of an optimization step. \n \n Parameters\n ----------\n step: Register.optstep\n A step in the registration.\n \"\"\"\n self.ax1.cla()\n self.img1 = self.ax1.imshow(\n step.image, \n interpolation='nearest',\n cmap='gray'\n )\n self.ax1.axis('image')\n \n self.ax2.cla()\n self.img2 = self.ax2.imshow(\n step.warpedImage, \n interpolation='nearest',\n cmap='gray'\n )\n self.ax2.axis('image')\n \n self.ax3.cla()\n self.img3 = self.ax3.imshow(\n step.template, \n interpolation='nearest',\n cmap='gray'\n )\n self.ax2.axis('image')\n \n self.draw()\n","sub_path":"imreg/visualize/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"132609402","text":"from itertools import groupby\n\nentities = [\"Mr\",\n \".\",\n \"Trump\",\n \"’\",\n \"s\",\n \"tweets \",\n \"began\",\n \"just \",\n \"moments\",\n \"after\",\n \"a\",\n \"Fox\",\n \"News \",\n \"report \",\n \"by\",\n \"Mike\",\n \"Tobin\",\n \",\",\n \"a\",\n \"reporter\",\n \"for\",\n \"the\",\n \"network\",\n \",\",\n \"about\",\n \"protests\",\n \"in\",\n \"Minnesota \",\n \"and\",\n \"elsewhere \",\n \".\",\n \"India\",\n \"and\",\n \"China\",\n \"have \",\n \"agreed \",\n \"to\",\n \"peacefully\"\n \"resolve\",\n \"a\",\n \"simmering \",\n \"border \",\n \"dispute\",\n \"between\",\n \"the\",\n \"world\",\n \"'\",\n \"s\",\n \"two\",\n \"most\",\n \"populous\",\n \"nations\",\n \",\",\n \"officials \",\n \"in\",\n \"New\",\n \"Delhi\",\n \"said\",\n \".\",\n ]\n\n\nlabels = [\"O\",\n \"O\",\n \"B-PER\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"B-ORG\",\n \"B-ORG\",\n \"O\",\n \"O\",\n \"B-PER\",\n \"B-PER\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"B-ORG\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"B-LOC\",\n \"O\",\n \"O\",\n \"O\",\n \"B-LOC\",\n \"O\",\n \"B-LOC\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"O\",\n \"B-LOC\",\n \"B-LOC\",\n \"O\",\n \"O\",\n ]\n\n\n\ndef format_2(entity_names, entity_types):\n\n entity_names_2 = []\n entity_types_2 = []\n [(entity_names_2.append(n), entity_types_2.append(t)) for n, t in zip(entity_names, entity_types) if n != \"[PAD]\"]\n\n assert len(entity_names_2) == len(entity_types_2)\n\n # Group same Entity-Types\n groupedLabels = [list(y) for x, y in groupby(entity_types_2)]\n entity_names_2.reverse()\n\n # Group Entity_Names by Entity-Types\n groupedEntities = []\n for g in groupedLabels:\n groupLocals = []\n for e in g:\n groupLocals.append(entity_names_2.pop())\n groupedEntities.append(groupLocals)\n assert len(groupedEntities) == len(groupedLabels)\n\n result_dict = {}\n for ent_list, lbl_list in zip(groupedEntities, groupedLabels):\n # print(lbl_list , \" >>> \" , \" \".join(ent_list) )\n if lbl_list[0] not in 'O':\n if lbl_list[0] not in result_dict:\n result_dict[lbl_list[0]] = []\n\n result_dict[lbl_list[0]].append(\" \".join(ent_list))\n # print(result_dict)\n return(result_dict)\n\n\ndef format_1(entity_names, entity_types):\n # Remove the [PAD]s'\n entity_names_2 = []\n entity_types_2 = []\n [(entity_names_2.append(n), entity_types_2.append(t)) for n, t in zip(entity_names, entity_types) if n != \"[PAD]\"]\n assert len(entity_names_2) == len(entity_types_2)\n\n # Group same Entity-Types\n groupedEntity = [list(y) for x, y in groupby(entity_types_2)]\n entity_names_2.reverse()\n\n # Group Entity_Names by Entity-Types\n groupedNames = []\n for g in groupedEntity:\n groupLocals = []\n for e in g:\n groupLocals.append(entity_names_2.pop())\n groupedNames.append(groupLocals)\n assert len(groupedNames) == len(groupedEntity)\n\n # Prepare the dictionary\n nameEntityDict = {}\n for nms, ent in zip(groupedNames, groupedEntity):\n if ent[0] != \"O\":\n # nameEntityDict[tuple(nms)] = ent[0]\n nameEntityDict[\", \".join(nms)] = ent[0]\n\n return nameEntityDict\n\n\nif __name__ == \"__main__\":\n for e, l in zip(entities, labels):\n print(\"{:5} {}\".format(l, e))\n\n print(format_1(entities, labels))\n print(format_2(entities, labels))\n","sub_path":"Python-Course/py-streamlit/fix_pred.py","file_name":"fix_pred.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"177053251","text":"#!/usr/bin/env python2.5\n#\n# JavaScript depender. Loads and concatenates necessary\n# JavaScript files.\n\nimport logging\nimport datetime\nimport re\n\nfrom django.http import HttpResponse, HttpResponseNotModified\nfrom django.conf import settings\n\nfrom depender.core import Depender\n\nLOG = logging.getLogger(__name__)\n\ndef make_depender():\n depender = Depender(settings.DEPENDER_ROOT, settings.DEPENDER_CONFIG_JSON, settings.DEPENDER_DEBUG)\n return depender\n\ndepender = make_depender()\n\ndef build(request):\n \"\"\"\n builds a library given required scripts to includes and other arguments\n accepted URL arguments:\n\n require - a comma separated list of *files* to require; can also be specified in the php style as \"require[]=foo&require[]=bar\"\n requireLibs - a comma separated list of *libraries* to require - these are the names defined in our *congfig.json* in the *libs* section. So, for example, *requireLibs=mootools-core,mootools-more* using the default config would include both the complete inventories of MooTools Core and More. This can also be specified as a comma separated list or the php style (*requireLibs[]=mootools-core&requireLibs[]=mootools-more*).\n exclude - exactly like the *require* value, except it's a list of files to exclude. This is useful if you have already loaded some scripts and now you require another. You can specify the scripts you already have and the one you now need, and the library will return only those you do not have.\n excludeLibs - just like the *exclude* option but instead you can specify entire libraries.\n cache - if set to *true* you'll be returned a cached version of the script even if the server is set to *false* and vice versa.\n compression - you'll be returned the compression type you specify regardless of the server default. Note that if you specify a compression type that the server does not allow, you'll be returned which ever one it does. If it does not support compression at all, you will not be returned a compressed file. You can also specify \"none\" which is useful for development and debugging.\n \n \"\"\"\n \n def get(name):\n return request.GET.get(name)\n def get_arr(name):\n val = get(name)\n if val:\n return val.split(\",\")\n else:\n return []\n\n require = get_arr(\"require\")\n exclude = get_arr(\"exclude\")\n excludeLibs = get_arr(\"excludeLibs\")\n requireLibs = get_arr(\"requireLibs\")\n download = get(\"download\")\n reset = get(\"reset\")\n client = get(\"client\")\n compression = get(\"compression\")\n\n dpdr = None\n global depender\n if settings.DEPENDER_DEBUG:\n dpdr = make_depender()\n else:\n dpdr = depender\n if reset == \"true\":\n depender = dpdr\n \n if compression is None:\n compression = dpdr.default_compression\n if settings.DEPENDER_DEBUG:\n compression = \"none\"\n\n if client == \"true\" and require.count(\"Depender.Client\") == 0:\n require.append(\"Depender.Client\")\n \n includes = dpdr.get_dependencies(require, exclude, requireLibs, excludeLibs)\n output = \"//No files included for build\"\n if len(includes) > 0:\n \n libraries_and_copyrights = dict()\n for i in includes:\n libraries_and_copyrights[i.library] = i.copyright\n\n output = \"\"\n for lib, copy in libraries_and_copyrights.iteritems():\n if len(copy) > 0:\n output += copy + \"\\n\"\n\n output += \"\\n//Contents: \"\n output += \", \".join([ i.name for i in includes ])\n output += \"\\n\\n\"\n \n location = request.META[\"SERVER_PROTOCOL\"].split(\"/\")[0].lower() + \"://\" + request.META[\"HTTP_HOST\"] + request.path\n args = request.META[\"QUERY_STRING\"]\n if args.find(\"download=\") >= 0:\n clean = []\n for arg in args.split(\"&\"):\n if arg.find(\"download=\") == -1:\n clean.append(arg)\n args = '&'.join(clean)\n\n output += \"//This lib: \" + location + '?' + args\n output += \"\\n\\n\"\n\n for i in includes:\n output += i.compressed_content[compression] + \"\\n\\n\"\n\n if client == \"true\":\n output += dpdr.get_client_js(includes, location)\n\n response = HttpResponse(output, content_type=\"application/x-javascript\")\n \n if (download == \"true\"):\n response['Content-Disposition'] = 'attachment; filename=built.js'\n return response\n\nbuild.login_notrequired = True\n\ndef test(request):\n #this seems silly\n return HttpResponse(file(settings.DEPENDER_ROOT + '/mootools/depender/static/test.html').read())\n","sub_path":"django/mootools/depender/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"395701089","text":"from app import db\nfrom app.schemas.user import User\nfrom flask_login import current_user\nimport datetime\n\nclass Post( db.Model ):\n id = db.Column( db.Integer, primary_key = True )\n titulo = db.Column( db.String )\n sub_titulo = db.Column( db.String )\n fecha = db.Column( db.Date )\n document = db.Column( db.Text )\n owner = db.Column( db.Integer, db.ForeignKey('user.id'))\n\ndef ReturnIndexPost():\n x = Post.query.all()\n x.sort( key = lambda y: y.fecha )\n x.reverse()\n list = []\n if len(x) > 3 and x is not None:\n x = x[:3]\n for i in x:\n list.append( [i, User.query.get( i.owner )] )\n return list\n\ndef New_post(titulo, sub_titulo, document):\n new_post = Post(\n titulo = titulo,\n sub_titulo = sub_titulo,\n fecha = datetime.date.today(),\n document = document,\n owner = current_user.id\n )\n db.session.add( new_post )\n db.session.commit()\n print(\" [*] Post, {}, subido correctamente\".format(new_post.titulo))\n\n\ndef Select_post( id ):\n x = Post.query.get( id )\n y = User.query.get( x.id )\n return x, y\n","sub_path":"app/schemas/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324542381","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# extract accuracy from logs\n\nlog_dir = \"/home/diwu/Project/UnarySim/app/uBrain/model_eval/mi/\"\nbitwidth_list = [8, 9, 10, 11, 12]\nflag = \"Test Accuracy:\"\n\n\n# extract fp log\nlog_file = log_dir + \"log_fp.log\"\nfp = open(log_file, \"r\")\nfor line in fp:\n line = line.rstrip() # remove '\\n' at end of line\n if flag in line:\n line_list = line.split()\n acc_fp = float(line_list[2])\n print(\"FP accuracy: \", acc_fp, \"%\")\n break\nfp.close()\n\n\n# extract fxp log\nacc_fxp = []\nfor bitwidth in bitwidth_list:\n log_file = log_dir + \"log_fxp_\"+str(bitwidth)+\".log\"\n fp = open(log_file, \"r\")\n for line in fp:\n line = line.rstrip() # remove '\\n' at end of line\n if flag in line:\n line_list = line.split()\n acc_fxp.append(float(line_list[2]))\n print(bitwidth, \"-bit FXP accuracy: \", acc_fxp[-1], \"%\")\n break\n fp.close()\n\n\n# extract sc log\nacc_sc = []\nfor bitwidth in bitwidth_list:\n log_file = log_dir + \"log_sc_bwrc_\"+str(bitwidth+1)+\"_bwtc_\"+str(bitwidth)+\".log\"\n fp = open(log_file, \"r\")\n for line in fp:\n line = line.rstrip() # remove '\\n' at end of line\n if flag in line:\n line_list = line.split()\n acc_sc.append(float(line_list[2]))\n print(bitwidth, \"-bit SC accuracy: \", acc_sc[-1], \"%\")\n break\n fp.close()\n\n\n# extract hub log\nacc_hub = []\nfor bitwidth in bitwidth_list:\n log_file = log_dir + \"log_hub_\"+str(bitwidth)+\".log\"\n fp = open(log_file, \"r\")\n for line in fp:\n line = line.rstrip() # remove '\\n' at end of line\n if flag in line:\n line_list = line.split()\n acc_hub.append(float(line_list[2]))\n print(bitwidth, \"-bit HUB accuracy: \", acc_hub[-1], \"%\")\n break\n fp.close()\n\n\n\nfont = {'family':'Times New Roman', 'size': 6}\nmatplotlib.rc('font', **font)\n\nmy_dpi = 300\nfig_h = 0.8\nfig_w = 3.6\nalpha = 1\n\nlabels = [str(bitwidth) for bitwidth in bitwidth_list]\nlabels.append(\"FP32\")\nx = np.arange(len(labels)) # the label locations\n\nfig, ax = plt.subplots(figsize=(fig_w, fig_h), dpi=my_dpi)\n\nx_axe = x[0:-1]\nax.plot(x[-1], acc_fp, \"o\", label=\"CPU\", alpha=alpha, color=\"#888888\", lw=0.5, ms=1.5)\nax.plot(x_axe, acc_fxp, \"-^\", label=\"Systolic\", alpha=alpha, color=\"#7A81FF\", lw=0.5, ms=1.5)\nax.plot(x_axe, acc_sc, \"-P\", label=\"SC\", alpha=alpha, color=\"#D783FF\", lw=0.5, ms=1.5)\nax.plot(x_axe, acc_hub, \"-s\", label=\"uBrain\", alpha=alpha, color=\"#FF7F7F\", lw=0.5, ms=1.5)\n\nlocs = [80, 90, 100]\nax.set_yticks(locs)\n\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.set_ylabel('Accuracy (%)\\n')\nax.legend(ncol=4, frameon=True)\nfig.tight_layout()\nfig.savefig(log_dir+\"model_eval_acc_mi.pdf\", bbox_inches='tight', dpi=my_dpi, pad_inches=0.02)\n","sub_path":"app/uBrain/model_eval/mi/model_eval_acc_plot.py","file_name":"model_eval_acc_plot.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"169875881","text":"\"\"\"\r\nAuthor: Scott Henderson\r\nLast Updated: Nov 16, 2020\r\n\r\nPurpose: Combine weekend ER reports to save time and potential manual copy/paste mistakes\r\n\r\nInput: Raw ER reports (.xls) from project 'data/raw' folder\r\nOutput: Combined (appended) ER reports (.xlsx) into 'data/exports' folder\r\n\"\"\"\r\n\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport openpyxl\r\nimport glob\r\nimport datetime\r\nfrom datetime import timedelta\r\nimport pandas.io.formats.excel\r\n\r\n# Remove pandas excel header formatting\r\npandas.io.formats.excel.ExcelFormatter.header_style = None\r\n\r\n#--------------- PURPOSE ---------------#\r\n\r\nprint(\"Purpose: Combine weekend ER reports to save time and potential manual copy/paste mistakes\")\r\n\r\nprint(\"----------------------------------------------------------------------------------------------------\")\r\n\r\n#--------------- ASCII ART ---------------#\r\n\r\nprint(r\"\"\"\r\n_________ ___. .__ _____________________ __________ __ \r\n\\_ ___ \\ ____ _____\\_ |__ |__| ____ ____ \\_ _____/\\______ \\ \\______ \\ ____ ______ ____________/ |_ ______\r\n/ \\ \\/ / _ \\ / \\| __ \\| |/ \\_/ __ \\ | __)_ | _/ | _// __ \\\\____ \\ / _ \\_ __ \\ __\\/ ___/\r\n\\ \\___( <_> ) Y Y \\ \\_\\ \\ | | \\ ___/ | \\ | | \\ | | \\ ___/| |_> > <_> ) | \\/| | \\___ \\ \r\n \\______ /\\____/|__|_| /___ /__|___| /\\___ > /_______ / |____|_ / |____|_ /\\___ > __/ \\____/|__| |__| /____ >\r\n \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/|__| \\/ \r\n\"\"\")\r\n\r\nprint(\"----------------------------------------------------------------------------------------------------\")\r\n\r\n#--------------- SOURCE AND DESTINATION PATHS ---------------#\r\n\r\n# Source directory where ER reports are saved\r\nsrc_dir = os.path.join(os.path.expanduser(\"~\"), \"Desktop\", \"python_projects\", \"combine_er_reports\", \"data\", \"raw\")\r\n\r\n# Destination directory where ER reports are exported to\r\ndst_dir = os.path.join(os.path.expanduser(\"~\"), \"Desktop\", \"python_projects\", \"combine_er_reports\", \"data\", \"exports\")\r\n\r\n#--------------- LIST FILES ---------------#\r\n\r\n# Get basename of each file\r\nfile_list = [os.path.basename(file) for file in glob.glob(f\"{src_dir}/Fraud Results for*.xls\")]\r\n\r\nprint(*file_list, sep='\\n')\r\n\r\nnum_of_files = len(file_list)\r\nprint(f\"There are {num_of_files} files\")\r\n\r\nprint(\"----------------------------------------------------------------------------------------------------\")\r\n\r\n#--------------- FIND UNIQUE CLIENTS ---------------#\r\n\r\n# Empty list to store unique client names\r\nclient_list =[]\r\n\r\n# Split file_name, grab client name, append unique values to list\r\nfor filename in file_list:\r\n \r\n # String split\r\n type = filename.split(\" \")\r\n \r\n # Grab 4th word -> client name\r\n client = type[3]\r\n \r\n # Check if exists in client_list\r\n if client not in client_list: \r\n client_list.append(client) \r\n\t\t\r\n\t\t\r\n# List of unique client names\r\nprint(*client_list, sep='\\n')\r\n\r\nnum_of_clients = len(client_list)\r\nprint(f\"There are {num_of_clients} unique clients\")\r\n\r\nprint(\"----------------------------------------------------------------------------------------------------\")\r\n\r\n#--------------- DATAFRAME PREP ---------------#\r\n\r\n# Column headers for ER file\r\ncolumns = [\"Session\", \r\n \"Client Code\", \r\n \"Module\", \r\n \"First Name\", \r\n \"Last Name\", \r\n \"Address\", \r\n \"City\", \r\n \"State\", \r\n \"Zip\", \r\n \"Email\", \r\n \"Dealer\", \r\n \"SPCode\", \r\n \"Invoice\", \r\n \"Brand\", \r\n \"Product Line\", \r\n \"Models\", \r\n \"Model QTY\", \r\n \"SerialNumber\", \r\n \"SPDescription\", \r\n \"Process ID\", \r\n \"LevSessionNumber\", \r\n \"Status\", \r\n \"Date of Sale\", \r\n \"Created Date\", \r\n \"Modified Date\", \r\n \"Lev Score\", \r\n \"Comments\", \r\n \"Patient First Name\", \r\n \"Patient Last Name\"]\r\n\r\n#--------------- CHANGE WORKING DIRECTORY ---------------#\r\n\r\n# To save combined ER files to exports folder\r\nos.chdir(dst_dir)\r\n\r\n#--------------- APPENDING & SAVING FILES ---------------#\r\n\r\ndef append_files():\r\n \"\"\"\r\n Takes client -> creates empty df for client -> finds all files matching that client and appends data to empty df -> moves to next client match\r\n \"\"\"\r\n \r\n # Create blank df for each client\r\n for client in client_list:\r\n \r\n print(client)\r\n \r\n # Find the files associated with each client\r\n files = glob.glob(f\"{src_dir}/*{str(client)}*.xls\")\r\n \r\n # Optional -> print list of client group of files\r\n #print(files)\r\n \r\n # Create a blank dataframe to store each client's data\r\n print(\"Creating blank dataframe...\")\r\n \r\n # Create df with column headers\r\n df_blank = pd.DataFrame(columns = columns)\r\n \r\n # Appends all the files for the relevant client into one df and saves it \r\n for file in files:\r\n \r\n print(\"Reading file...\")\r\n \r\n df_er_file = pd.read_excel(file,\r\n sheet_name = \"AllSessionSorted\")\r\n \r\n print(\"Sucessfully read file...\")\r\n \r\n # Optional -> print each df to check\r\n #print(df_er_file.head(5))\r\n \r\n # Append data to client blank df\r\n df_blank = df_blank.append(df_er_file, \r\n ignore_index = True)\r\n \r\n # Set filename\r\n \r\n # For Mondays - add together weekend + Monday (past 3 days) & modified date is that Friday-Sat-Sun (past 3 days minus 1 etc)\r\n \r\n # Month/Year\r\n month = datetime.datetime.now().strftime('%m')\r\n year = datetime.datetime.now().strftime('%Y')\r\n \r\n # Days\r\n d = datetime.datetime.now().strftime('%d')\r\n d1 = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%d')\r\n d2 = (datetime.datetime.now() - datetime.timedelta(days=2)).strftime('%d')\r\n d3 = (datetime.datetime.now() - datetime.timedelta(days=3)).strftime('%d')\r\n\r\n # Filename\r\n filename = f\"Fraud Results for {client} P-Date {month}.{d2}.{d1}.{d}-{year}_M-Date {month}.{d3}.{d2}.{d1}-{year}.xlsx\"\r\n \r\n # Edit-able filename\r\n #filename = f\"Fraud Results for {client} P-Date 11.07.08.09-2020_M-Date 11.06.07.08-2020.xlsx\"\r\n \r\n print(f\"Appending to file -> {filename}\")\r\n \r\n # Write data\r\n writer = pd.ExcelWriter(filename, \r\n engine = \"openpyxl\")\r\n \r\n df_blank.to_excel(writer, \r\n sheet_name = \"AllSessionSorted\",\r\n index = False)\r\n \r\n print(\"Exporting file...\")\r\n \r\n writer.save()\r\n \r\n print(f\"Successfully exported file for: {client}\")\r\n \r\n print(\"----------------------------------------------------------------------------------------------------\")\r\n\r\n# Call loop function\r\nappend_files()\r\n\r\n#--------------- SCRIPT COMPLETED ---------------#\r\n\r\nprint(\"----------------------------------------------------------------------------------------------------\")\r\n\r\nprint(\"Script Successfully Completed\")\r\n\r\ninput(\"Press Enter to Continue...\")","sub_path":"scripts/combine_er_reports.py","file_name":"combine_er_reports.py","file_ext":"py","file_size_in_byte":7704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"338919500","text":"import filecmp\nimport glob\nimport json\nimport os\nimport sys\nimport subprocess\nfrom typing import List\nfrom subprocess import TimeoutExpired\nfrom judge_result import JudgeResult\n\n\ndef compile_process():\n p = None\n try:\n p = subprocess.run(\n [\"g++\", \"/problem/code.cpp\", \"-o\", \"/problem/main\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n except:\n return {\n \"isError\": True,\n \"status\": \"CE\",\n \"stdout\": p.stdout,\n \"stderr\": p.stderr\n }\n \n if p.returncode != 0:\n return {\n \"isError\": True,\n \"status\": \"CE\",\n \"stdout\": p.stdout,\n \"stderr\": p.stderr\n }\n \n return {\n \"isError\": False,\n \"status\": \"\",\n \"stdout\": p.stdout,\n \"stderr\": p.stderr\n }\n\n\ndef run_process(input_):\n p = None\n try:\n p = subprocess.run(\n [\"/problem/main\"],\n input=input_.encode(),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=2\n )\n except TimeoutExpired:\n return {\n \"isError\": True,\n \"status\": \"TLE\",\n \"stdout\": \"\",\n \"stderr\": \"\"\n }\n \n return {\n \"isError\": False,\n \"status\": \"\",\n \"stdout\": p.stdout,\n \"stderr\": p.stderr\n }\n\n\ndef get_test_filenames():\n return {\n \"input_files\": glob.glob('/problem/testcases/in/*'),\n \"output_files\": glob.glob('/problem/testcases/out/*')\n }\n\n\ndef diff():\n filenames = get_test_filenames()\n input_file_paths = filenames[\"input_files\"]\n output_file_paths = filenames[\"output_files\"]\n\n judge_results: List[JudgeResult] = []\n\n for i, input_file_path in enumerate(input_file_paths):\n input_: str = \"\"\n output_: str = \"\"\n with open(input_file_path) as input_file:\n input_ = input_file.read()\n \n run_result = run_process(input_)\n if run_result[\"isError\"]:\n judge_results.append(\n JudgeResult(\n status=run_result[\"status\"],\n error=run_result[\"stdout\"]\n ).export_dict()\n )\n else:\n with open('./tmp.txt', 'w') as tmp_file:\n tmp_file.write(run_result[\"stdout\"].decode())\n import filecmp\n res = filecmp.cmp('tmp.txt', output_file_paths[i])\n judge_results.append(\n JudgeResult(\n status=\"AC\" if res else \"WA\",\n ).export_dict()\n )\n \n return judge_results\n\n\ndef check_status(statuses):\n if \"WA\" in statuses:\n return \"WA\"\n elif \"TLE\" in statuses:\n return \"TLE\"\n else:\n return \"AC\"\n\n\ndef main():\n compile_result = compile_process()\n if compile_result[\"isError\"]:\n print(json.dumps({\n \"status\": compile_result[\"status\"],\n \"ac_count\": 0,\n \"output\": compile_result[\"stderr\"].decode()\n }))\n return\n\n judge_results = diff()\n\n statuses = [judge_result[\"status\"] for judge_result in judge_results]\n res = {\n \"status\": check_status(statuses),\n \"ac_count\": statuses.count(\"AC\"),\n \"output\": \"\"\n }\n\n print(json.dumps(res))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"judge_server/containers/cpp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"589042273","text":"import numpy as np\nimport random\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optimf\nfrom torch.nn.parameter import Parameter\n\ndevice = \"cpu\"\nSEQ_NUM = 800\nTRAINING_SIZE = SEQ_NUM\nTEACHER_FORCING = True\ndef generateIsh(seqNum,seqLen,vocab,alpha,maxLen,minLen):\n \"\"\"\n Documentation here.\n \"\"\"\n target = ['zero','one','two','three','four','five','six','seven','eight','nine']\n #EOS = '#'\n EOSNum = len(vocab)\n\n length=len(vocab)\n \n t1 = torch.zeros(seqNum,seqLen).type(torch.IntTensor)\n t2 = torch.zeros(seqNum,maxLen).type(torch.IntTensor)\n t3 = torch.zeros(seqNum,maxLen).type(torch.IntTensor)\n lenT = torch.zeros(seqNum,1).type(torch.IntTensor)\n listFull = []\n listShort = []\n for i in range(seqNum):\n listFull.append('')\n listShort.append('')\n i1=0\n i2=0\n numNums = 0\n while (len(listFull[i])+5)<(seqLen):\n rndNum = np.random.randint(i1,maxLen)\n #if rndNum > minLen \n print('Everything is going wrong!!!!!!')\n\n if random.uniform(0,1)

', webpage)\n\t\t\tfor element in links:\n\t\t\t\tlink_list.append(element)\n\t\t\tinitial = int(initial)\n\t\t\tinitial+=1\n\t\texcept:\n\t\t\tprint('Произошла ошибка при обработке '+website+str(initial)+'.html :(')\n\t\t\tinitial+=1\n\tprint(len(link_list))\n\ttext_file = open('linghsecorporalinks.py', 'a', encoding = 'UTF-8')\n\ttext_file.write('links = ')\n\ttext_file.write(str(link_list))\n\ttext_file.close()\n\t\t\n\ndef main ():\n\tfunction_2()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"final_project/news_links.py","file_name":"news_links.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"323307177","text":"#!/usr/bin/python\n\n__author__ = \"Ellen Fu\"\n__date__ = \"Feb 24, 2017\"\n\n# This class is for storing each image's camera viewpoint's x, y, z and yaw, pitch,\n# roll. The GraphicOutputter class can then access these attributes for visualizing\n# the camera's position and pose relative to the pattern.\n\nclass Camera:\n def __init__(self):\n self.x = 0\n self.y = 0\n self.z = 0\n self.yaw = 0\n self.pitch = 0\n self.roll = 0\n","sub_path":"Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"246682639","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom parsel import Selector\nimport re\nfrom urllib.parse import unquote\n\n\nclass BishunSpider(scrapy.Spider):\n name = 'bishun'\n allowed_domains = ['baidu.com']\n # 从‘王’开始\n start_urls = ['https://hanyu.baidu.com/zici/s?wd=王&query=王']\n\n def parse(self, response):\n # 提取图片网址\n selector = Selector(text=response.text)\n img_url = selector.xpath('//img[@class=\"bishun\"]/@data-gif').get()\n\n chinese_character = re.search('wd=(.*?)&',response.url).group(1)\n \n item = {\n 'img_url': img_url,\n 'response_url': response.url,\n 'chinese_character': unquote(chinese_character)\n }\n\n yield item\n # 提取相关字 提取热搜字 进行迭代\n new_character = selector.xpath('//a[@class=\"img-link\"]/@href').getall()\n \n for character in new_character:\n # 拼接\n new_url = response.urljoin(character) \n # 发送请求\n yield scrapy.Request(new_url, callback=self.parse)","sub_path":"2019-11-11-百度笔顺图片全站采集/bishunSpider/bishunSpider/spiders/bishun.py","file_name":"bishun.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"32173784","text":"import radical.utils as ru\nfrom ..entities.task import Task\nfrom ..entities.core import Core\nfrom yaml import load\nimport pika\nimport json\nimport os\n\n\nclass Executor(object):\n\n def __init__(self, cfg_path):\n\n self._uid = ru.generate_id('executor', mode=ru.ID_UNIQUE)\n self._logger = ru.Logger('radical.executor.%s' % self._uid)\n\n self._schedule = None\n self._profile = dict()\n self._engine_uid = None\n\n with open(cfg_path, 'r') as stream:\n cfg = load(stream)\n self._parse_cfg(cfg)\n\n self._setup_msg_sys()\n\n def _parse_cfg(self, cfg):\n\n self._host = cfg['rmq']['host']\n self._port = cfg['rmq']['port']\n self._exchange = cfg['rmq']['executor']['exchange']\n self._wlms_exchange = cfg['rmq']['wlms']['exchange']\n self._queue_schedule = cfg['rmq']['executor']['queues']['schedule']\n self._queue_cfg = cfg['rmq']['executor']['queues']['config']\n self._profile_loc = cfg['rmq']['executor']['profile_loc']\n self._logger.info('Configuration parsed')\n\n def _setup_msg_sys(self):\n\n credentials = pika.PlainCredentials('krb09', 'yZtTe9FXyhXKxzKC')\n connParam = pika.connection.ConnectionParameters(host='129.114.17.185', port=5672, credentials=credentials)\n conn = pika.BlockingConnection(connParam)\n chan = conn.channel()\n\n chan.exchange_declare(exchange=self._exchange, exchange_type='direct')\n\n chan.queue_declare(queue=self._queue_schedule)\n chan.queue_bind(queue=self._queue_schedule,\n exchange=self._exchange, routing_key='schedule')\n\n chan.queue_declare(queue=self._queue_cfg)\n chan.queue_bind(queue=self._queue_cfg,\n exchange=self._exchange, routing_key='cfg')\n\n self._logger.info('Messaging system established')\n\n def run(self):\n\n conn = None\n\n try:\n credentials = pika.PlainCredentials('krb09', 'yZtTe9FXyhXKxzKC')\n connParam = pika.connection.ConnectionParameters(host='129.114.17.185', port=5672, credentials=credentials)\n conn = pika.BlockingConnection(connParam)\n chan = conn.channel()\n\n cfg_msg = None\n cfg = None\n\n while True:\n\n method_frame, header_frame, cfg_msg = chan.basic_get(queue=self._queue_cfg,\n auto_ack=True)\n if cfg_msg:\n\n tasks = list()\n cfg = cfg_msg\n cfg_as_dict = json.loads(cfg)\n if 'engine_uid' in cfg_as_dict.keys():\n self._engine_uid = cfg_as_dict['engine_uid']\n\n self._logger.info('Engine uid received')\n\n method_frame, header_frame, schedule = chan.basic_get(queue=self._queue_schedule,\n auto_ack=True)\n if schedule:\n\n tasks = list()\n schedule_as_dict = json.loads(schedule)\n cores_as_dict = dict()\n\n for s in schedule_as_dict:\n task = Task(no_uid=True)\n task.from_dict(s['task'])\n\n if s['core']['uid'] not in cores_as_dict.keys():\n core = Core(no_uid=True)\n core.from_dict(s['core'])\n cores_as_dict[s['core']['uid']] = core\n else:\n core = cores_as_dict[s['core']['uid']]\n\n core.execute(task)\n tasks.append(task)\n \n cores_as_list = [core.to_dict() for core in cores_as_dict.values()]\n chan.basic_publish( exchange=self._wlms_exchange,\n routing_key='exec',\n body=json.dumps(cores_as_list)\n )\n\n self._logger.info('Schedule executed')\n if schedule and cfg:\n\n self._record_profile(\n tasks=tasks, engine_uid=self._engine_uid)\n self._logger.info('Execution profile recorded')\n\n except KeyboardInterrupt:\n\n if conn:\n conn.close()\n self._write_profile()\n\n self._logger.info('Closing %s' % self._uid)\n\n except Exception as ex:\n\n if conn:\n conn.close()\n\n self._logger.exception('Executor failed with %s' % ex)\n\n def _record_profile(self, tasks, engine_uid):\n\n if engine_uid not in self._profile.keys():\n self._profile[engine_uid] = list()\n\n for task in tasks:\n prof = {\n 'task': task.uid,\n 'ops': task.ops,\n 'core': task.exec_core,\n 'start_time': task.start_time,\n 'end_time': task.end_time,\n 'exec_time': task.end_time - task.start_time\n }\n self._profile[engine_uid].append(prof)\n\n def _write_profile(self):\n\n base = os.path.dirname(self._profile_loc)\n fname, ext = os.path.basename(self._profile_loc).split('.')\n op_name = base + '/' + fname + '.%s.' % self._uid + ext\n\n ru.write_json(data=self._profile, filename=op_name)\n self._logger.info(\n 'Profiles from executor %s written to %s' % (self._uid, op_name))\n","sub_path":"components/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"302646340","text":"from django.shortcuts import render\nfrom portfolio.models import Album, Photo\n\n\n# grab all photos from a particular model\ndef grab_photos(request, album_model, limit=None):\n album_photos = Photo.objects.filter(album=album_model)\n if limit > 0:\n photos = album_photos[:limit]\n else:\n photos = album_photos[:-1]\n return render(request, \"portfolio.html\", photos)\n\n\n\n\n\n","sub_path":"portfolio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"513019109","text":"import time\r\nimport datetime\r\nfrom random import randint\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as ec\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n\r\n\r\nclass TimeClock:\r\n def __init__(self, driver, log_list, wait_time=60):\r\n self.driver = driver\r\n self.log_list = log_list\r\n self.wait_time = wait_time\r\n self.clock_in_time = None\r\n self.clock_out_time = None\r\n self.break_time_start = None\r\n self.break_time_stop = None\r\n self.current_date = None\r\n\r\n def opening_time_clock_section(self):\r\n WebDriverWait(self.driver, self.wait_time).until(ec.element_to_be_clickable((By.ID, 'sn_timeclock')))\r\n self.driver.find_element_by_id('sn_timeclock').click()\r\n WebDriverWait(self.driver, self.wait_time).until(ec.element_to_be_clickable((By.CSS_SELECTOR, '.hum_box')))\r\n\r\n def clock_in(self):\r\n self.check_current_clock_status('clock_in')\r\n WebDriverWait(self.driver, self.wait_time).until(ec.element_to_be_clickable((By.ID, 'tc_tl_ci')))\r\n self.driver.find_element_by_id('tc_tl_ci').click()\r\n self.clock_in_time = self.calculate_time()\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_co')))\r\n\r\n def clock_out(self):\r\n self.check_current_clock_status('clock_out')\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_co')))\r\n self.driver.find_element_by_id('tc_tl_co').click()\r\n self.clock_out_time = self.calculate_time()\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_ci')))\r\n\r\n def start_break_time(self):\r\n WebDriverWait(self.driver, self.wait_time).until(ec.element_to_be_clickable((By.ID, 'tc_tl_br_s')))\r\n self.driver.find_element_by_id('tc_tl_br_s').click()\r\n self.break_time_start = time.time()\r\n\r\n def stop_break_time(self):\r\n WebDriverWait(self.driver, self.wait_time).until(ec.element_to_be_clickable((By.ID, 'tc_tl_br_e')))\r\n self.driver.find_element_by_id('tc_tl_br_e').click()\r\n self.break_time_stop = time.time()\r\n\r\n def add_note(self, note_text='Default note {}'.format(randint(100, 999))):\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_no')))\r\n self.driver.find_element_by_id('tc_tl_no').send_keys(note_text)\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_no_a')))\r\n self.driver.find_element_by_id('tc_tl_no_a').click()\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located(\r\n (By.XPATH, '//span[@class=\"tcnote\"][text() = \"{}\"]'.format(note_text))))\r\n\r\n def check_current_clock_status(self, expected):\r\n WebDriverWait(self.driver, self.wait_time).until(ec.visibility_of_element_located((By.ID, 'tc_tl_overview')))\r\n try:\r\n WebDriverWait(self.driver, 3).until(ec.visibility_of_element_located((By.ID, 'tc_tl_ci')))\r\n if expected == 'clock_out':\r\n self.driver.find_element_by_id('tc_tl_ci').click()\r\n except:\r\n try:\r\n WebDriverWait(self.driver, 2).until(ec.visibility_of_element_located((By.ID, 'tc_tl_co')))\r\n if expected == 'clock_in':\r\n self.driver.find_element_by_id('tc_tl_co').click()\r\n except:\r\n raise Exception('{} button status is not correct'.format(expected))\r\n\r\n def calculate_values(self):\r\n return {\r\n 'lenght': str(self.time_diff(self.clock_in_time[:5], self.clock_out_time[:5])),\r\n 'clock_in': self.clock_in_time[:5],\r\n 'clock_out': self.clock_out_time[:5],\r\n 'date': self.calculate_date(),\r\n 'break': str(int(self.break_time_stop - self.break_time_start))\r\n }\r\n\r\n def read_values_from_table(self):\r\n return {\r\n 'lenght': self.driver.find_element_by_css_selector(\r\n '.timeSList li:nth-child(2) > span:nth-child(1)').text.lstrip().replace('m', ''),\r\n 'clock_in': self.driver.find_element_by_css_selector(\r\n '.timeSList li:nth-child(2) > span:nth-child(2)').text.lstrip(),\r\n 'clock_out': self.driver.find_element_by_css_selector(\r\n '.timeSList li:nth-child(2) > span:nth-child(3)').text.lstrip(),\r\n 'date': self.driver.find_element_by_css_selector(\r\n '.timeSList li:nth-child(2) > span:nth-child(4)').text.lstrip(),\r\n 'break': self.driver.find_element_by_css_selector(\r\n '.timeSList li:nth-child(2) > span:nth-child(5)').text.lstrip().replace('s', ''),\r\n }\r\n\r\n def verify_my_time_sheet(self):\r\n calculated_values = self.calculate_values()\r\n values_from_table = self.read_values_from_table()\r\n\r\n for key, value in calculated_values.items():\r\n for key2, value2 in values_from_table.items():\r\n if key == key2:\r\n if 'clock' in key:\r\n if not self.time_diff(calculated_values[key], values_from_table[key][:5]) > 1:\r\n self.log_list.append('OK - \"{}\" is correct in my timesheets table {}'.format(key, value2))\r\n else:\r\n self.log_list.append('ERROR - \"{}\" is NOT correct in my timesheets table {} not in {}'\r\n .format(key, value2, value))\r\n else:\r\n cv = [int(s) for s in value.split() if s.isdigit()][0]\r\n if value == value2 or value2 in (str(cv-1), str(cv), str(cv+1)):\r\n self.log_list.append('OK - \"{}\" is correct in my timesheets table {}'.format(key, value2))\r\n else:\r\n self.log_list.append(\r\n 'ERROR - \"{}\" is NOT correct in my timesheets table {} vs {}'.format(key, value2, value))\r\n\r\n @staticmethod\r\n def calculate_time():\r\n return time.strftime('%I:%M:%S %p')\r\n\r\n @staticmethod\r\n def calculate_date():\r\n return time.strftime('%b %d')\r\n\r\n @staticmethod\r\n def time_diff(time1, time2):\r\n for i in ('a', 'm', 'p'):\r\n if i in time1:\r\n time1 = time1.replace(i, '')\r\n if i in time2:\r\n time2 = time2.replace(i, '')\r\n\r\n time_a = datetime.datetime.strptime(time1, \"%H:%M\")\r\n time_b = datetime.datetime.strptime(time2, \"%H:%M\")\r\n new_time = time_b - time_a\r\n return int(new_time.seconds/60)\r\n\r\n\r\n","sub_path":"modules/time_clock_module.py","file_name":"time_clock_module.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189706544","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyams_utils/tales.py\n# Compiled at: 2020-02-18 19:11:13\n# Size of source mod 2**32: 4460 bytes\n__doc__ = 'PyAMS_utils.tales module\\n\\nThis module provides a custom TALES extension engine, which allows you to define custom\\nTALES expressions which can be used from Chameleon or Zope templates.\\n'\nimport re\nfrom chameleon.astutil import Symbol\nfrom chameleon.codegen import template\nfrom chameleon.tales import StringExpr\nfrom zope.contentprovider.tales import addTALNamespaceData\nfrom pyams_utils.interfaces.tales import ITALESExtension\n__docformat__ = 'restructuredtext'\n\nclass ContextExprMixin:\n \"\"\"ContextExprMixin\"\"\"\n transform = None\n\n def __call__(self, target, engine):\n assignment = super(ContextExprMixin, self).__call__(target, engine)\n transform = template('target = transform(econtext, target)', target=target, transform=self.transform)\n return assignment + transform\n\n\nFUNCTION_EXPRESSION = re.compile('(.+)\\\\((.+)\\\\)', re.MULTILINE | re.DOTALL)\nARGUMENTS_EXPRESSION = re.compile('[^(,)]+')\n\ndef render_extension(econtext, name):\n \"\"\"TALES extension renderer\n\n See :ref:`tales` for complete description.\n\n The requested extension can be called with our without arguments, like in\n ${structure:tales:my_expression} or ${structure:tales:my_expression(arg1, arg2)}.\n In the second form, arguments will be passed to the \"render\" method; arguments can be\n static (like strings or integers), or can be variables defined into current template\n context; other Python expressions including computations or functions calls are actually\n not supported, but dotted syntax is supported to access inner attributes of variables.\n \"\"\"\n\n def get_value(econtext, arg):\n \"\"\"Extract argument value from context\n\n Extension expression language is quite simple. Values can be given as\n positioned strings, integers or named arguments of the same types.\n \"\"\"\n arg = arg.strip()\n if arg.startswith('\"') or arg.startswith(\"'\"):\n return arg[1:-1]\n if '=' in arg:\n key, value = arg.split('=', 1)\n value = get_value(econtext, value)\n return {key.strip(): value}\n try:\n arg = int(arg)\n except ValueError:\n args = arg.split('.')\n result = econtext.get(args.pop(0))\n for arg in args:\n result = getattr(result, arg)\n\n return result\n else:\n return arg\n\n name = name.strip()\n context = econtext.get('context')\n request = econtext.get('request')\n view = econtext.get('view')\n args, kwargs = [], {}\n func_match = FUNCTION_EXPRESSION.match(name)\n if func_match:\n name, arguments = func_match.groups()\n for arg in map(lambda x: get_value(econtext, x), ARGUMENTS_EXPRESSION.findall(arguments)):\n if isinstance(arg, dict):\n kwargs.update(arg)\n else:\n args.append(arg)\n\n registry = request.registry\n extension = registry.queryMultiAdapter((context, request, view), ITALESExtension, name=name)\n if extension is None:\n extension = registry.queryMultiAdapter((context, request), ITALESExtension, name=name)\n if extension is None:\n extension = registry.queryAdapter(context, ITALESExtension, name=name)\n if extension is None:\n return ''\n addTALNamespaceData(extension, econtext)\n return extension.render(*args, **kwargs)\n\n\nclass ExtensionExpr(ContextExprMixin, StringExpr):\n \"\"\"ExtensionExpr\"\"\"\n transform = Symbol(render_extension)","sub_path":"pycfiles/pyamtrack-0.1.4-py3-none-manylinux1_x86_64/tales.cpython-35.py","file_name":"tales.cpython-35.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"386967591","text":"import SensorManager as Sm\nimport serial\nfrom threading import Thread\nfrom pyACS import *\nimport time\nimport dataManager as dm\nimport FileManager as fm\nimport socket\n\nsensorManager = Sm.SensorManager()\nFileManager = fm.FileManager()\n\nclass DataCollector():\n def __init__(self):\n self.updateSensors()\n\n def updateSensors(self):\n self.sensors = sensorManager.get()\n self.flags = {}\n self.serialPorts = {}\n\n for sensor in self.sensors:\n\n sensor.status = \"off\"\n sensorManager.update(sensor)\n\n def start(self, sensor):\n print(\"Start Data Collection\")\n sensor.status = \"on\"\n sensorManager.update(sensor)\n\n self.flags[sensor.serial] = True\n\n serialPort = serial.Serial()\n serialPort.baudrate = sensor.baudRate # 115200\n serialPort.port = sensor.port # \"/dev/cu.usbmodem14101\"#\n self.serialPorts[sensor.serial] = serialPort\n\n try:\n serialPort.open()\n except:\n print(\"Couldnt open port\")\n\n if(sensor.name == \"ACS\"):\n thread = Thread(target = self.ACS, kwargs = dict(serialPort=serialPort, sensor=sensor))\n thread.start()\n elif(sensor.name == \"BB3\"):\n thread = Thread(target = self.BB3, kwargs = dict(serialPort=serialPort, sensor=sensor))\n thread.start()\n else:\n print(\"Sensor not available\")\n\n\n\n\n def startAll(self):\n for sensor in self.sensors:\n self.start(sensor)\n\n def stop(self, sensor):\n sensor.status = \"off\"\n sensorManager.update(sensor)\n self.flags[sensor.serial] = False\n\n serialPort = self.serialPorts[sensor.serial]\n serialPort.close()\n\n\n # close port\n\n # serialPort = self.serialPorts[sensor]\n # thread = self.threads[sensor]\n\n # terminate tread\n\n def stopAll(self):\n for sensor in self.sensors:\n self.stop(sensor)\n\n\n def ACS(self, serialPort, sensor):\n\n # connected = False\n # while(not connected):\n # print(\"test\")\n # try:\n # # host = socket.gethostname() # as both code is running on same pc\n # # port = 5000 # socket server port number\n # #\n # # client_socket = socket.socket() # instantiate\n # # client_socket.connect((host, port)) # connect to the server\n #\n # sio.emit('my event', {'data': 'foobar'})\n #\n # connected = True\n # except:\n # print(\"connection failed, trying again in 5 seconds\")\n # time.sleep(5)\n\n #file = open(files[i] + \"Bytes.txt\", \"a\")\n #decodedFile = open(files[i] + \".txt\", \"a\")\n newACS = acs.ACS(\"acs301.dev\")\n byteString = b\"\"#keeps track of all bytes in current frame\n while(self.flags[sensor.serial]):\n try:\n byteString += serialPort.readline()#read incoming bytes\n except:\n try:\n serialPort.close()\n serialPort = serial.Serial()\n serialPort.baudrate = sensor.baudRate # 115200\n serialPort.port = sensor.port # \"/dev/cu.usbmodem14101\"#\n self.serialPorts[sensor.serial] = serialPort\n serialPort.open()\n except:\n print(\"Error: could not connect to sensor\")\n bitEnd = byteString.find(b'\\xff\\x00\\xff\\x00')#checks for beginning of next frame\n if not (bitEnd == -1):\n try:\n # print(str(newACS.unpack_frame(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd]))+ \"\\n\")\n # dm.addData(sensor.name + \"_bin\", byteString.hex(), \"bin\")\n # print(newACS.unpack_frame(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd]).c_ref[0])\n\n unpacked = newACS.unpack_frame(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd])\n\n jsonData = {\"data\": {\"sig\": [unpacked.a_sig.tolist(), unpacked.c_sig.tolist()], \"ref\": [unpacked.a_ref.tolist(), unpacked.c_ref.tolist()]}}\n\n # {\"frame_len\": unpacked.frame_len, \"frame_type\": unpacked.frame_type, \"serial_number\": unpacked.serial_number, \"a_ref_dark\": unpacked.a_ref_dark, \"p\": unpacked.p, \"a_sig_dark\": unpacked.a_sig_dark, \"t_ext\": unpacked.t_ext, \"t_int\": unpacked.t_int, \"c_ref_dark\": unpacked.c_ref_dark, \"c_sig_dark\": unpacked.c_sig_dark, \"time_stamp\": unpacked.time_stamp, \"output_wavelength\": unpacked.output_wavelength, \"c_ref\": unpacked.c_ref.tolist(), \"a_ref\": unpacked.a_ref.tolist(), \"c_sig\": unpacked.c_sig.tolist(), \"a_sig\": unpacked.a_sig.tolist()}\n\n # [a, unpacked.a_sig_dark, unpacked.c_ref_dark, unpacked.c_sig_dark]}\n\n try:\n dm.addData(sensor, jsonData, \"txt\")\n dm.sendData(sensor, \"txt\")\n except Exception as e:\n print(\"Error Could not send data to server\")\n try:\n FileManager.addData(sensor, str(unpacked) + \"\\n\")\n except:\n print(\"cannot store data\")\n # FileManager.addData(sensor, \"this is a test\\n\")\n # if(dm.status == 1):\n # thread = Thread(target = dm.sendData, args = {sensorName + \"_bin\", \"bin\"})\n # thread.start()\n # thread = Thread(target = dm.sendData, args = {sensorName, \"txt\"})\n # thread.start()\n # client_socket.send(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd])\n #print(\"Writing Data For: \", str(sensor.serial))\n except:\n print(\"something went wrong\")\n byteString = byteString[bitEnd + 4:]#deletes old frame\n\n def BB3(self, serialPort, sensor):\n\n # connected = False\n # while(not connected):\n # print(\"test\")\n # try:\n # # host = socket.gethostname() # as both code is running on same pc\n # # port = 5000 # socket server port number\n # #\n # # client_socket = socket.socket() # instantiate\n # # client_socket.connect((host, port)) # connect to the server\n #\n # sio.emit('my event', {'data': 'foobar'})\n #\n # connected = True\n # except:\n # print(\"connection failed, trying again in 5 seconds\")\n # time.sleep(5)\n\n #file = open(files[i] + \"Bytes.txt\", \"a\")\n #decodedFile = open(files[i] + \".txt\", \"a\")\n while(self.flags[sensor.serial]):\n try:\n byteString = str(serialPort.readline())[1:-5].split(\"\\\\t\")[2:]#read incoming bytes\n except:\n try:\n serialPort.close()\n serialPort = serial.Serial()\n serialPort.baudrate = sensor.baudRate # 115200\n serialPort.port = sensor.port # \"/dev/cu.usbmodem14101\"#\n self.serialPorts[sensor.serial] = serialPort\n serialPort.open()\n except:\n print(\"Error: could not connect to sensor\")\n #for i in byteString:\n # print(i + \"test,\")\n try:\n # print(str(newACS.unpack_frame(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd]))+ \"\\n\")\n # dm.addData(sensor.name + \"_bin\", byteString.hex(), \"bin\")\n # print(newACS.unpack_frame(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd]).c_ref[0])\n\n\n try:\n dm.addData(sensor, byteString, \"txt\")\n dm.sendData(sensor, \"txt\")\n except:\n print(\"Error Could not send data to server\")\n try:\n FileManager.addData(sensor, byteString)\n except:\n print(\"cannot store data\")\n # if(dm.status == 1):\n # thread = Thread(target = dm.sendData, args = {sensorName + \"_bin\", \"bin\"})\n # thread.start()\n # thread = Thread(target = dm.sendData, args = {sensorName, \"txt\"})\n # thread.start()\n # client_socket.send(b'\\xff\\x00\\xff\\x00' + byteString[0:bitEnd])\n print(\"Writing Data For: \", str(sensor.serial))\n except:\n print(\"something went wrong\")\n","sub_path":"datacollection/datacollection/DataCollector.py","file_name":"DataCollector.py","file_ext":"py","file_size_in_byte":8597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"205719418","text":"#!/usr/bin/ipy\n\nimport clr\n\nclr.AddReference(\"System.Windows.Forms\")\nclr.AddReference(\"System.Drawing\")\n\nfrom System.Windows.Forms import Application, Form\nfrom System.Windows.Forms import Button, ToolTip\nfrom System.Drawing import Point, Size\n\nclass IForm(Form):\n\n def __init__(self):\n self.Text = 'Tooltips'\n self.CenterToScreen()\n xsize,ysize=300,200\n self.Size = Size(xsize, ysize)\n\n tooltip = ToolTip()\n tooltip.SetToolTip(self, \"This is a Form\")\n\n button = Button()\n button.Parent = self\n button.Text = \"Button\"\n xloc,yloc=50,70\n button.Location = Point(xloc,yloc)\n\n tooltip.SetToolTip(button, \"This is a Button\")\n\ndef main():\n form=IForm()\n Application.Run(form)\nif __name__ == '__main__':\n main()\n","sub_path":"ironPython/mono/tooltips.py","file_name":"tooltips.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"214899714","text":"if __name__ == \"__main__\":\n raise Exception(\"This file cannot be invoked on its own.\")\n\n\nimport psi4\nimport numpy as np\n\n\nclass Hamiltonian(object):\n\n def __init__(self, ref, local=False):\n self.ref = ref\n\n # Get MOs\n C = self.ref.Ca_subset(\"AO\", \"ACTIVE\")\n npC = np.asarray(C) # as numpy array\n self.C = C\n\n # Localize occupied MOs if requested\n if (local is not False):\n C_occ = self.ref.Ca_subset(\"AO\", \"ACTIVE_OCC\")\n no = self.ref.doccpi()[0] - self.ref.frzcpi()[0] # assumes symmetry c1\n Local = psi4.core.Localizer.build(\"PIPEK_MEZEY\", ref.basisset(), C_occ)\n Local.localize()\n npL = np.asarray(Local.L)\n npC[:,:no] = npL\n C = psi4.core.Matrix.from_array(npC)\n self.C = C\n\n # Generate MO Fock matrix\n self.F = np.asarray(self.ref.Fa())\n # self.F = np.einsum('uj,vi,uv', npC, npC, self.F)\n self.F = npC.T @ self.F @ npC\n\n # Get MO two-electron integrals in Dirac notation\n mints = psi4.core.MintsHelper(self.ref.basisset())\n self.ERI = np.asarray(mints.mo_eri(C, C, C, C)) # (pr|qs)\n self.ERI = self.ERI.swapaxes(1,2) # \n self.L = 2.0 * self.ERI - self.ERI.swapaxes(2,3) # 2 - \n","sub_path":"pycc/hamiltonian.py","file_name":"hamiltonian.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"525878019","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n \n if root == None:\n return []\n \n queue = collections.deque()\n \n queue.appendleft((root,0))\n \n lvl_ord = []\n depth = -1\n \n while queue:\n curr_node,curr_depth = queue.pop()\n if curr_depth > depth:\n lvl_ord.append([])\n depth = curr_depth\n \n lvl_ord[depth].append(curr_node.val)\n \n if (curr_node.left != None):\n queue.appendleft((curr_node.left,depth+1))\n if (curr_node.right != None):\n queue.appendleft((curr_node.right,depth+1))\n \n return lvl_ord\n","sub_path":"BinaryTreeLevelOrder.py","file_name":"BinaryTreeLevelOrder.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"623770388","text":"#!/usr/bin/env python\n#53\n\"\"\"File reads the geometry of active terminal from /tmp/win_geo.txt\n and creates a simple Header fitting the size for each folder \"\"\"\n\nimport sys\npath = '/tmp/win_geo.txt'\n\n#FORMAT: -geometry 827x993+192-9\ntry:\n geo = open(path).read()\nexcept:\n geo = \"-geometry 879x969-3-10\"\n\ntitle = sys.argv[1]\n\n#oldschool code ...\nstart, ende = 0,0\nfor index, val in enumerate(geo):\n if geo[index] == ' ':\n start = index + 1\n if geo[index] == 'x':\n ende = index\n\n#just use x-koordinates\nsize = round(float(geo[start:ende])/9.1)\nhalf = round((size - len(title))/2)\n\nprint(size*'_'+'\\n')\nprint(half*' '+title)\nprint(size*'_'+'\\n')\n\n#cat << EOD\n#___________________________________________________________________________________________\n#\n# gnome\n#___________________________________________________________________________________________\n#\n#EOD\n","sub_path":"1xScripts/generate_index.py","file_name":"generate_index.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"219592673","text":"import glob\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\nif sys.version_info >= (3, 5):\n import urllib.request\n urlopen = urllib.request.urlopen\nelse:\n import urllib\n urlopen = urllib.urlopen\n\ndef setup_python(version):\n if sys.platform.startswith(\"linux\"):\n return setup_linux(version)\n elif sys.platform == \"darwin\":\n return setup_macos(version)\n elif sys.platform == \"win32\":\n return setup_windows(version)\n else:\n raise NotImplementedError(sys.platform)\n\ndef setup_linux(version):\n # Assume we are running in manylinux\n roots = {\n \"3.6\": \"/opt/python/cp36-cp36m/bin\",\n \"3.7\": \"/opt/python/cp37-cp37m/bin\",\n \"3.8\": \"/opt/python/cp38-cp38/bin\",\n \"3.9\": \"/opt/python/cp39-cp39/bin\",\n \"3.10\": \"/opt/python/cp310-cp310/bin\",\n }\n if version not in roots:\n raise NotImplementedError(\n \"Unknown interpreter version: {0}\".format(version))\n \n return glob.glob(os.path.join(roots[version], \"python\"))[0]\n\ndef setup_macos(version):\n # Assume x86_64\n \n root = \"https://www.python.org/ftp/python\"\n urls = {\n \"3.6\": root+\"/3.6.8/python-3.6.8-macosx10.9.pkg\",\n \"3.7\": root+\"/3.7.9/python-3.7.9-macosx10.9.pkg\",\n \"3.8\": root+\"/3.8.10/python-3.8.10-macosx10.9.pkg\",\n \"3.9\": root+\"/3.9.5/python-3.9.5-macos11.pkg\",\n \"3.10\": root+\"/3.10.0/python-3.10.0-macos11.pkg\",\n }\n if version not in urls:\n raise NotImplementedError(\n \"Unknown interpreter version: {0}\".format(version))\n \n directory = tempfile.mkdtemp()\n try:\n data = urlopen(urls[version]).read()\n path = os.path.join(directory, urls[version].split(\"/\")[-1])\n # NOTE: manylinux1 has Python 2.4, causing a syntax error when using\n # \"with open(...) as fd\".\n fd = open(path, \"wb\")\n fd.write(data)\n fd.close()\n \n subprocess.check_call([\n \"sudo\", \"installer\", \"-pkg\", path, \"-target\", \"/\"])\n finally:\n shutil.rmtree(directory)\n \n frameworks = \"/Library/Frameworks/Python.framework/Versions\"\n return glob.glob(os.path.join(frameworks, version, \"bin/python3\"))[0]\n\ndef setup_windows(version):\n versions = {\n \"3.6\": \"3.6.8\",\n \"3.7\": \"3.7.9\",\n \"3.8\": \"3.8.10\",\n \"3.9\": \"3.9.5\",\n \"3.10\": \"3.10.0\",\n }\n if version not in versions:\n raise NotImplementedError(\n \"Unknown interpreter version: {0}\".format(version))\n \n subprocess.check_call([\n \"nuget\", \"install\", \"python\", \n \"-Version\", version, \"-OutputDirectory\", \"C:\\\\wheel_python\", \n \"-Verbosity\", \"quiet\"])\n \n return glob.glob(\"C:\\\\wheel_python\\\\*\\\\tools\\\\python.exe\")[0]\n","sub_path":".ci/wheels/setup_python.py","file_name":"setup_python.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"424501425","text":"#######################################################################################\n#\n#\tCopyright (c) 2018, Wiphoo (Terng) Methachawalit, All rights reserved.\n#\n#######################################################################################\n\n\n#######################################################################################\n#\n#\tSTANDARD IMPORTS\n#\n\nimport numpy\n\n#######################################################################################\n#\n#\tLOCAL IMPORTS\n#\n\n#\tactivation function\nfrom ActivationFuncs import ActivationFuncs\n\n#######################################################################################\n#\n#\tGLOBAL VARIABLES\n#\n\n\n#######################################################################################\n#\n#\tHELPER FUNCTIONS\n#\n\n\n#######################################################################################\n#\n#\tCLASS DEFINITIONS\n#\n\nclass ForwardPropagator:\n\t''' this class is designed for storing the inputs matrix\n\t\t\tinputs matrix for a hidden layer neurons and inputs matrix for a output layer\n\t'''\n\t\n\tdef __init__( self, inputsMatrix ):\n\t\t\n\t\t#\tinputs matrix\n\t\tself.inputsMatrix = inputsMatrix\n\t\t\n\t\t#\toutputs matrix for a hidden layer neurons\n\t\tself.outputsMatrixHiddenLayerNeurons = None\n\t\t\n\t\t#\toutputs for a output layer\n\t\tself.outputsMatrixOutputsLayer = None\n\t\t\n\tdef propagate( self, perceptron ):\n\t\t''' do a forward propagate changes from inputs matrix through \n\t\t\t\toutputs matrix for a hidden layer neurons then through\n\t\t\t\toutputs matrix for outputs layer\n\t\t'''\n\t\t\n#\t\tprint( 'ForwardPropagator.propagate()...............' )\n#\t\tprint( ' self.inputsMatrix = {}'.format( self.inputsMatrix ) )\n#\t\tprint( ' type( self.inputsMatrix ) = {}'.format( type( self.inputsMatrix ) ) )\n#\t\tprint( ' self.inputsMatrix.shape = {}'.format( self.inputsMatrix.shape ) )\n#\n#\t\tprint( ' perceptron.hiddenLayerWeightsMatrix = {}'.format( perceptron.hiddenLayerWeightsMatrix ) )\n#\t\tprint( ' perceptron.hiddenLayerWeightsMatrix.shape = {}'.format( perceptron.hiddenLayerWeightsMatrix.shape ) )\n#\t\tprint( ' perceptron.outputLayerWeightsMatrix = {}'.format( perceptron.outputLayerWeightsMatrix ) )\n#\t\tprint( ' perceptron.outputLayerWeightsMatrix.shape = {}'.format( perceptron.outputLayerWeightsMatrix.shape ) )\n\t\t\n\t\t#\tpropagate inputs matrix and weight and bias on hidden layer neurons and\n\t\t#\t\tthis will be came ouputs matrix on hidden layer neurons\n\t\tself.outputsMatrixHiddenLayerNeurons = ActivationFuncs.activationFunc( numpy.dot( self.inputsMatrix,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tperceptron.hiddenLayerWeightsMatrix ) \\\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ perceptron.hiddenLayerBiasMatrix )\n)\n\t\t\n\t\t#\tpropagate outputs matrix on hidden layer neurons and weight and bias on output layer and\n\t\t#\t\tthis will be came ouputs matrix on outputs layer\n\t\tself.outputsMatrixOutputsLayer = ActivationFuncs.activationFunc( numpy.dot( self.outputsMatrixHiddenLayerNeurons,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tperceptron.outputLayerWeightsMatrix ) \\\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ perceptron.outputLayerBiasMatrix )\n)\n\t\t\n\t\t\n#\t\tprint( ' self.outputsMatrixHiddenLayerNeurons = {}'.format( self.outputsMatrixHiddenLayerNeurons ) )\n#\t\tprint( ' self.outputsMatrixOutputsLayer = {}'.format( self.outputsMatrixOutputsLayer ) )\n#\t\tprint( 'DONE :: ForwardPropagator.propagate()...............' )\n\t\t\n\t\t\n\t\t\n\n","sub_path":"simpleperceptron/ForwardPropagator.py","file_name":"ForwardPropagator.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"380566560","text":"#!/usr/bin/env python3\n#\n# Author: Wade Wells github/Pack3tL0ss\n\nfrom pathlib import Path\nfrom typing import Any, List, Union\nimport yaml\nimport json\nimport tablib\nimport sys\nimport time\n\n# try:\n# from icecream import ic\n# except Exception:\n# def ic(*_, **__):\n# pass\n\nvalid_ext = ['.yaml', '.yml', '.json', '.csv', '.tsv', '.dbf', '.xls', '.xlsx']\nNOT_ACCOUNT_KEYS = [\n \"central_info\",\n \"ssl_verify\",\n \"token_store\",\n \"forget_account_after\",\n \"debug\",\n \"debugv\",\n \"limit\",\n \"no_pager\",\n \"sanitize\",\n]\n\n\ndef _get_config_file(dirs: List[Path]) -> Path:\n dirs = [dirs] if not isinstance(dirs, list) else dirs\n for _dir in dirs:\n for f in list(Path.glob(_dir, \"config.*\")):\n if f.suffix in valid_ext and 'client_id' in f.read_text():\n return f\n\n\nclass Config:\n def __init__(self, base_dir: Path = None):\n if base_dir and isinstance(base_dir, str):\n base_dir = Path(base_dir)\n self.base_dir = base_dir or Path(__file__).parent.parent\n cwd = Path().cwd()\n self.file = _get_config_file(\n [\n Path().home() / \".config\" / \"centralcli\",\n Path().home() / \".centralcli\",\n cwd / \"config\",\n cwd,\n Path().home() / \".config\" / \"centralcli\" / \"config\",\n ]\n )\n if self.file:\n self.dir = self.file.parent\n self.base_dir = self.dir.parent if self.dir.name != \"centralcli\" else self.dir\n if Path.joinpath(cwd, \"out\").is_dir():\n self.outdir = cwd / \"out\"\n else:\n self.outdir = cwd\n else:\n if str(Path('.config/centralcli')) in str(self.base_dir):\n self.dir = self.base_dir\n self.outdir = cwd / \"out\"\n else:\n if 'site-packages' in str(self.base_dir):\n self.base_dir = self.dir = Path().home() / \".centralcli\"\n else:\n self.dir = self.base_dir / \"config\"\n self.outdir = self.base_dir / \"out\"\n self.file = self.dir / \"config.yaml\"\n\n for ext in [\"yml\", \"json\"]:\n if self.dir.joinpath(f\"config.{ext}\").exists():\n self.file = self.dir / f\"config.{ext}\"\n break\n self.bulk_edit_file = self.dir / \"bulkedit.csv\"\n self.stored_tasks_file = self.dir / \"stored-tasks.yaml\"\n self.cache_dir = self.dir / \".cache\"\n self.default_cache_file = self.cache_dir / \"db.json\"\n self.sticky_account_file = self.cache_dir / \"last_account\"\n self.sanatize_file = self.dir / \"redact.yaml\"\n\n self.data = self.get_file_data(self.file) or {}\n self.forget: Union[int, None] = self.data.get(\"forget_account_after\")\n self.debug = self.data.get(\"debug\", False)\n self.debugv = self.data.get(\"debugv\", False)\n self.account = self.get_account_from_args()\n self.defined_accounts: List[str] = [k for k in self.data if k not in NOT_ACCOUNT_KEYS]\n\n def __bool__(self):\n return len(self.data) > 0\n\n def __len__(self):\n return len(self.data)\n\n def __getattr__(self, item: str, default: Any = None) -> Any:\n if item in self.data:\n return self.data.get(item, default)\n elif self.data.get(self.account):\n return self.data[self.account].get(item, default)\n else:\n return self.data.get(\"central_info\", {}).get(item, default)\n\n # not used but may be handy\n @property\n def tokens(self):\n return self.data.get(self.account, {}).get(\"token\", {})\n\n @property\n def valid(self):\n return self.account in self.data\n\n @property\n def token_store(self):\n return self.data.get(\n \"token_store\",\n {\"type\": \"local\", \"path\": f\"{self.dir.joinpath('.cache')}\"}\n )\n\n @property\n def cache_file(self):\n return self.default_cache_file if self.account in [\"central_info\", \"default\"] else self.cache_dir / f\"{self.account}.json\"\n\n def get(self, key: str, default: Any = None) -> Any:\n if key in self.data:\n return self.data.get(key, default)\n elif self.account and key in self.data[self.account]:\n return self.data[self.account].get(key, default)\n\n @staticmethod\n def get_file_data(import_file: Path) -> dict:\n '''Return dict from yaml/json/csv... file.'''\n if import_file.exists() and import_file.stat().st_size > 0:\n with import_file.open() as f:\n try:\n if import_file.suffix == \".json\":\n return json.loads(f.read())\n elif import_file.suffix in [\".yaml\", \".yml\"]:\n return yaml.load(f, Loader=yaml.SafeLoader)\n elif import_file.suffix in ['.csv', '.tsv', '.dbf', '.xls', '.xlsx']:\n with import_file.open('r') as fh:\n return tablib.Dataset().load(fh)\n else:\n raise UserWarning(\n \"Provide valid file with format/extension [.json/.yaml/.yml/.csv]!\"\n )\n except Exception as e:\n raise UserWarning(f'Unable to load configuration from {import_file}\\n{e.__class__}\\n\\n{e}')\n\n def get_account_from_args(self) -> str:\n \"\"\"Determine account to use based on arguments & last_account file.\n\n Method does no harm / triggers no errors. Any errors are handled\n in account_name_callback after cli is loaded. We need to determine the\n account during init to load the cache for auto completion.\n\n Returns:\n str: The account to use based on --account -d flags and last_account file.\n \"\"\"\n if \"--account\" in sys.argv:\n account = sys.argv[sys.argv.index(\"--account\") + 1]\n elif \"--account\" in str(sys.argv): # vscode debug workaround\n args = [a.split(\" \") for a in sys.argv if \"--account \" in a][0]\n account = args[args.index(\"--account\") + 1]\n elif \"-d\" in sys.argv or \" -d \" in str(sys.argv) or str(sys.argv).endswith(\"-d\"):\n return \"central_info\"\n else:\n account = \"central_info\"\n\n if account in [\"central_info\", \"default\"]:\n if self.sticky_account_file.is_file():\n last_account, last_cmd_ts = self.sticky_account_file.read_text().split(\"\\n\")\n last_cmd_ts = float(last_cmd_ts)\n\n # last account sticky file handling -- messaging is in cli callback --\n if self.forget:\n if time.time() > last_cmd_ts + (self.forget * 60):\n self.sticky_account_file.unlink(missing_ok=True)\n # typer.echo(self.AcctMsg(msg=\"forgot\"))\n else:\n account = last_account\n # typer.echo(self.AcctMsg(account, msg=\"previous_will_forget\"))\n else:\n account = last_account\n # typer.echo(self.AcctMsg(account, msg=\"previous\"))\n else:\n if account in self.data:\n self.sticky_account_file.parent.mkdir(exist_ok=True)\n self.sticky_account_file.write_text(f\"{account}\\n{round(time.time(), 2)}\")\n # typer.echo(self.AcctMsg(account))\n return account\n","sub_path":"centralcli/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"550554144","text":"##\n## Construya una tabla que contenga _c0 y una lista\n## separada por ',' de los valores de la columna _c5a\n## y _c5b (unidos por ':') de la tabla tbl2.tsv\n## \nimport pandas as pd\nimport numpy as np\nx = pd.read_csv('tbl2.tsv', sep = '\\t',thousands = None, decimal = '.')\ntbl2 = pd.DataFrame(x)\n\nordenados = tbl2.sort_values(by=['_c0','_c5a','_c5b'])\nordenados['union_c5a_c5b'] = ordenados['_c5a'] +':'+ ordenados['_c5b'].map(str)\ndflista = ordenados[['_c0','union_c5a_c5b']]\ngrupo_dflista = dflista.groupby('_c0')['union_c5a_c5b'].apply(list)\nmerge_dflista = pd.merge(dflista[['_c0']],grupo_dflista,on='_c0')\n\ndef concatenar(list):\n result= ''\n for index, value in enumerate(list,1):\n if index < len(list):\n result += str(value)+','\n else:\n result += str(value)\n return result\n\nmerge_dflista['lista']= merge_dflista['union_c5a_c5b'].map(lambda x: concatenar(x))\nfilasunicas = merge_dflista[['_c0','lista']].drop_duplicates()\nfilasunicas = filasunicas.reset_index(drop=True)\nprint(filasunicas)\n","sub_path":"q11.py","file_name":"q11.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"367524232","text":"#!/usr/bin/python\n\nimport subprocess,socket,sys,os\nhost = \"127.0.0.1\"\nport = 1338\nsecret = \"!@$b\"\nwhile True:\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n sock.bind((host,port))\n sock.listen(100)\n Data = 1\n while Data == 1:\n client,address=sock.accept()\n DD = str(client.recv(1024)).strip(\"\\n\")\n if DD == secret:\n client.send('[+] Hi Boss :D\\n')\n while True:\n data=client.recv(1024)\n for line in os.popen(data):\n client.send(line)\n else:\n None\n","sub_path":"python-protected-backdoor.py","file_name":"python-protected-backdoor.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"114446501","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# contact company education work language etc. field\n# Copyright 2015 ITGeeker \n#\n##############################################################################\n\nfrom openerp import models, fields, api, _\n\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n\n task_count = fields.Integer(compute='_task_count', string='# of Position')\n position_task_ids = fields.One2many('geeker.shortlisted', 'partner_id', '推荐的职位')\n\n @api.one\n @api.depends('position_task_ids')\n def _task_count(self):\n tasks = self.env['geeker.shortlisted'].search([('partner_id', '=', self.id)])\n self.task_count = len(tasks) \n","sub_path":"geeker_partner_link/models/partner_link.py","file_name":"partner_link.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"483635365","text":"import numpy as np\n\n# Creating a variable that contains the training data for email filter\ntraining_spam = np.loadtxt(open(\"venv/data/training_spam.csv\"), delimiter=\",\")\n\n\n# input = data set with binary response variable (0s and 1s) in the left-most column\n# output = numpy array containing the logs of the class priors for the spam & ham classes\ndef estimate_log_class_priors(data):\n # Calculating the number of spam and ham emails\n spam_count = 0\n for i in range(len(data)):\n if data[i][0] == 1:\n spam_count += 1\n ham_count = len(data) - spam_count\n\n # Calculating the probabilities of spam and ham emails\n prob_of_spam = (spam_count / len(data))\n prob_of_ham = 1 - prob_of_spam\n\n log_class_priors = np.array([np.log(prob_of_ham), np.log(prob_of_spam)])\n\n return log_class_priors\n\n\nlog_class_priors = estimate_log_class_priors(training_spam)\n\n\n# input = data set with binary response variable (0s and 1s) in the left-most column\n# output = 2D numpy-array containing logs of the class-conditional likelihoods for all words in the spam & ham classes\ndef estimate_log_class_conditional_likelihoods(data, alpha=1.0):\n no_of_columns = len(data[0])\n theta = np.array([[], []]) # 2d array to return\n total_spamw = 0\n total_hamw = 0\n\n for i in range(no_of_columns - 1): # this loops along the columns\n spamw_count = 0\n hamw_count = 0\n for j in range(len(data)): # this loops along the rows\n if data[j][0] == 1: # checks for for features present in spam email\n if data[j][i + 1] == 1:\n spamw_count += 1\n total_spamw += 1\n else: # checks for features present in ham email\n if data[j][i + 1] == 1:\n hamw_count += 1\n total_hamw += 1\n theta = np.append(theta, [[(spamw_count + alpha)], [(hamw_count + alpha)]], axis=1)\n\n for i in range(len(theta[0])):\n theta[0][i] = np.log(((theta[0][i]) / (total_spamw + ((no_of_columns - 1) * alpha))))\n theta[1][i] = np.log(((theta[1][i]) / (total_hamw + ((no_of_columns - 1) * alpha))))\n\n return theta\n\n\nlog_class_conditional_likelihoods = estimate_log_class_conditional_likelihoods(training_spam, alpha=1.0)\n\n\n# input = a data set of new emails\n# output = numpy array containing prediction of whether emails are spam(1) or ham(0)\ndef predict(new_data, log_class_priors, log_class_conditional_likelihoods):\n class_predictions = np.array([])\n\n for i in range(len(new_data)):\n sum_of_spamWordLogs = log_class_priors[1]\n sum_of_hamWordLogs = log_class_priors[0]\n for j in range(len(log_class_conditional_likelihoods[0])):\n sum_of_spamWordLogs += (new_data[i][j] * log_class_conditional_likelihoods[0][j])\n sum_of_hamWordLogs += (new_data[i][j] * log_class_conditional_likelihoods[1][j])\n if (sum_of_spamWordLogs >= sum_of_hamWordLogs):\n class_predictions = np.append(class_predictions, 1)\n else:\n class_predictions = np.append(class_predictions, 0)\n return class_predictions\n\n\n# determine accuracy based on the proportion of true predictions made by the classifier.\ndef accuracy(y_predictions, y_true):\n count = 0\n for i in range(len(y_true)):\n if y_true[i] == y_predictions[i]:\n count += 1\n acc = count / len(y_true)\n return acc\n\n\n# Creating a variable that contains the training data for email filter\ntesting_spam = np.loadtxt(open(\"venv/data/testing_spam.csv\"), delimiter=\",\")\nclass_predictions = predict(testing_spam[:, 1:], log_class_priors, log_class_conditional_likelihoods)\ntrue_classes = testing_spam[:, 0]\ntesting_set_accuracy = accuracy(class_predictions, true_classes)\n\n# The predictions made on the testing data and the accuracy of the models predictions\nprint(class_predictions)\nprint(\"\\n\")\nprint(testing_set_accuracy)\n","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"278007322","text":"import json\r\nimport re\r\n\r\n\r\nclass TweetCleaner:\r\n def __init__(self, file, emotion):\r\n self.emotion = emotion\r\n self.tweets = self.get_tweets(file)\r\n # self.loc_tweets = self.get_loc_tweets(file)\r\n\r\n self.acronyms = open('word_banks/acronyms.txt', 'r').readlines()\r\n self.acr = {}\r\n for acronym in self.acronyms:\r\n pair = acronym.split(':')\r\n self.acr[pair[0]] = pair[1].rstrip('\\n')\r\n self.acronyms = self.acr\r\n del self.acr\r\n\r\n self.contractions = open('word_banks/contractions.txt', 'r').readlines()\r\n self.cnt = {}\r\n for contraction in self.contractions:\r\n pair = contraction.split('=')\r\n self.cnt[pair[0]] = pair[1].rstrip('\\n')\r\n self.contractions = self.cnt\r\n del self.cnt\r\n\r\n self.stopwords = open('word_banks/stopwords.txt', 'r').readlines()\r\n self.stp = []\r\n for word in self.stopwords:\r\n self.stp.append(word.rstrip('\\n'))\r\n self.stopwords = self.stp\r\n del self.stp\r\n\r\n self.names = open('word_banks/names.txt', 'r').readlines()\r\n self.nms = []\r\n for word in self.names:\r\n self.nms.append(word.rstrip('\\n'))\r\n self.names = self.nms\r\n del self.nms\r\n\r\n def get_tweets(self, file_name):\r\n tweet_array = []\r\n emoji_pattern = re.compile(\"[\"\r\n u\"\\U0001F600-\\U0001F64F\" # emoticons\r\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\r\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\r\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\r\n \"]+\", flags=re.UNICODE)\r\n with open(file_name, 'rb') as f:\r\n for line in f:\r\n if not line.isspace():\r\n data = json.loads(line, encoding='utf-8')\r\n if not str(data).startswith(\"{'limit\"):\r\n tweet = emoji_pattern.sub(r'', data['text'])\r\n tweet_array.append(tweet.lower())\r\n f.close()\r\n return tweet_array\r\n\r\n\r\n\r\n # pre-processing method\r\n def clean(self):\r\n self.tweets = self.cut_fluff(self.tweets, self.emotion)\r\n # print('\\n'.join(self.tweets))\r\n\r\n # remove #, stopwords, http, numbers, and punctuation\r\n def cut_fluff(self, array, emotion):\r\n cleaned_tweets = []\r\n tweet_tuples = []\r\n duplicates = 0\r\n short = 0\r\n for tweet in array:\r\n word_map = {}\r\n init_split = tweet.split() # temp is the array of words in the tweet\r\n for word in init_split:\r\n word_map[word] = word\r\n for key in word_map.keys():\r\n word_map[key] = self.map_value(key)\r\n final_words = []\r\n for value in word_map.values():\r\n if value != '' and value != 'retweet' and value != '@user':\r\n final_words.append(value)\r\n tweet = ' '.join(final_words)\r\n if len(tweet.split()) > 3 and tweet not in cleaned_tweets:\r\n cleaned_tweets.append(tweet)\r\n tt = (tweet, emotion)\r\n tweet_tuples.append('$$'.join(tt))\r\n elif tweet not in cleaned_tweets:\r\n short += 1\r\n else:\r\n duplicates += 1\r\n print('Short: {}\\nDuplicate: {}'.format(short, duplicates))\r\n return tweet_tuples\r\n\r\n def map_value(self, key):\r\n key = key.replace('\\u2019', \"'\")\r\n key = key.replace('\\u2026', '')\r\n key = key.replace('\\u201c', '\"')\r\n key = key.replace('\\u201d', '\"')\r\n punctuation = \"!\\\"$%&()*+,-/:;<=>?[\\]^_`{|}~.0123456789#\"\r\n translator = str.maketrans('', '', punctuation)\r\n new_key = key.translate(translator)\r\n if key.startswith('http'):\r\n value = ''\r\n elif key.startswith('@'):\r\n value = '@user'\r\n elif key in self.contractions.keys():\r\n value = self.contractions[key]\r\n elif key in self.acronyms.keys():\r\n value = self.acronyms[key]\r\n elif key in self.stopwords or len(key) < 3:\r\n value = ''\r\n elif key in self.names:\r\n value = ''\r\n # elif not re.match(\"^[A-Za-z0-9_-]+$\", key):\r\n # value = ''\r\n elif not re.match(\"^[A-Za-z]+$\", key):\r\n value = ''\r\n else:\r\n value = new_key\r\n return value\r\n\r\n\r\n def export_to_txt(self, file_name):\r\n with open(file_name, 'a', encoding='utf8') as f:\r\n for tweet in self.tweets:\r\n f.write(tweet+'\\n')\r\n return True\r\n\r\n\r\n# test = TweetCleaner('tweet_jsons/angry_tweets.json', 'angry')\r\n# test.clean()\r\n\r\n# del test\r\n#\r\n# test = TweetCleaner('tweet_jsons/disgust_tweets.json', 'disgust')\r\n# test.clean()\r\n\r\n# del test\r\n# #\r\n# test = TweetCleaner('tweet_jsons/fear_tweets.json', 'fear')\r\n# test.clean()\r\n\r\n# del test\r\n# #\r\n# test = TweetCleaner('tweet_jsons/guilt_tweets.json', 'guilt')\r\n# test.clean()\r\n\r\n# del test\r\n# #\r\n# test = TweetCleaner('tweet_jsons/joy_tweets.json', 'joy')\r\n# test.clean()\r\n\r\n# del test\r\n# #\r\n# test = TweetCleaner('tweet_jsons/sad_tweets.json', 'sad')\r\n# test.clean()\r\n\r\n# del test\r\n# #\r\n# test = TweetCleaner('tweet_jsons/surprise_tweets.json', 'surprise')\r\n# test.clean()\r\n# test.export_to_txt('angry.txt')\r\n\r\n# del test\r\n\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nimport random\r\n\r\n\r\ndef reduce(in_file, out_file, emotion):\r\n tweets = []\r\n with open(in_file, 'r') as file:\r\n for line in file:\r\n tweets.append(line.split('$$')[0])\r\n file.close()\r\n print(len(tweets))\r\n vect = TfidfVectorizer(min_df=1)\r\n tfidf = vect.fit_transform(tweets)\r\n matrix = (tfidf * tfidf.T).A\r\n reduced_set = set(tweets)\r\n similar_sets = []\r\n\r\n for i in range(len(tweets)):\r\n too_similar = []\r\n for j in range(len(tweets)):\r\n if matrix[i][j] > 0.4 and not j == i:\r\n too_similar.append(tweets[j])\r\n similar_sets.append(too_similar)\r\n\r\n for item in similar_sets:\r\n reduced_set = reduced_set.difference(set(item))\r\n reduced_set = list(reduced_set)\r\n pairs = []\r\n for item in reduced_set:\r\n print(item + '$${}'.format(emotion))\r\n pairs.append(item + '$${}'.format(emotion))\r\n random.shuffle(pairs)\r\n with open(out_file, 'a') as file:\r\n for item in pairs[:3000]:\r\n file.write(str(item))\r\n file.write('\\n')\r\n file.close()\r\n return True\r\n\r\n\r\nfiles = ['tweet_txts/angry.txt', 'tweet_txts/disgust.txt', 'tweet_txts/fear.txt',\r\n 'tweet_txts/guilt.txt', 'tweet_txts/joy.txt', 'tweet_txts/sad.txt', 'tweet_txts/surprise.txt']\r\n\r\nemotions = ['angry', 'disgust', 'fear', 'guilt', 'joy', 'sad', 'surprise']\r\n\r\nindex = 0\r\nfor file in files:\r\n reduce(file, 'all_reduced_tweets.txt', emotions[index])\r\n index += 1\r\n\r\n\r\n\r\n","sub_path":"tweet_cleaner.py","file_name":"tweet_cleaner.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"295160050","text":"import threading\nimport time\n\nfrom multiprocessing import Pipe\nfrom multiprocessing.dummy.connection import Connection\nfrom aplicaciones.aplicaciones import Aplicaciones\nfrom GUI.GUI import GUI\nfrom archivos.archivos import Archivos\n\n\nclass Kernel:\n __GUI_hilo = None\n __archivos_hilo = None\n __aplicacion_hilo = None\n __pipe_GUI, __pipe_GUI2 = None, None\n __pipe_archivos, __pipe_archivos2 = None, None\n __pipe_aplicaciones, __pipe_aplicaciones2 = None, None\n _kernel = True\n\n def sistema(self):\n self.__pipe_GUI, self.__pipe_GUI2 = Pipe()\n self.__pipe_aplicaciones, self.__pipe_aplicaciones2 = Pipe()\n self.__pipe_archivos, self.__pipe_archivos2 = Pipe()\n\n gui = GUI(self.__pipe_GUI2)\n archivos = Archivos(self.__pipe_archivos2)\n aplicaciones = Aplicaciones(self.__pipe_aplicaciones2)\n\n self.__GUI_hilo = threading.Thread(target=gui.escuchar)\n self.__archivos_hilo = threading.Thread(target=archivos.escuchar)\n self.__aplicacion_hilo = threading.Thread(target=aplicaciones.escuchar)\n\n self.__archivos_hilo.start()\n self.__aplicacion_hilo.start()\n self.__GUI_hilo.start()\n\n self.sistema_interno()\n\n def escuchar_pipes(self, conexion: Connection):\n while True:\n if not conexion.poll(3):\n time.sleep(0.2)\n continue\n\n message = conexion.recv()\n\n if 'cmd' in message:\n if message['cmd'] == \"send\":\n pass\n elif message['cmd'] == \"info\":\n pass\n elif message['cmd'] == \"stop\":\n pass\n\n elif 'codterm' in message:\n if message['codterm'] == 0:\n print(\"Operación exitosa\")\n elif message['codterm'] == 1:\n print(\"Modulo ocupado\")\n elif message['codterm'] == 2:\n print(\"\")\n\n def encontrar_destino(self, message, action=None):\n if message['dst'] == \"archivos\":\n self.__pipe_archivos.send(message['msg'])\n elif message['dst'] == \"GUI\":\n self.__pipe_GUI.send(message['msg'])\n elif message['dst'] == \"aplicaciones\":\n self.__pipe_aplicaciones.send(message['msg'])\n elif message['dst'] == \"kernel\":\n if action == \"stop\":\n self.terminar(message['src'])\n\n if not action:\n if message['msg'] == \"sysinfo\":\n self.__pipe_GUI.send({\n \"cmd\": 'info',\n \"src\": \"kernel\",\n \"dst\": 'GUI',\n \"msg\": {\n \"GUI\": self.__GUI_hilo.is_alive(),\n \"files_manager\": self.__archivos_hilo.is_alive(),\n \"applications\": self.__aplicacion_hilo.is_alive(),\n \"kernel\": self._kernel_status\n }\n\n }) \n\n else:\n print(\"Destino no encontrado\")\n\n def terminar(self, instancia):\n if instancia == \"GUI\":\n self.__GUI_hilo._stop()\n self.__GUI_hilo.join()\n elif instancia == \"aplicaciones\":\n self.__aplicacion_hilo._stop()\n self.__aplicacion_hilo.join()\n elif instancia == \"archivos\":\n self.__archivos_hilo._stop()\n self.__archivos_hilo.join()\n\n def sistema_interno(self):\n mensajes_gui = threading.Thread(target=self.escuchar_pipes, args=[self.__pipe_GUI])\n mensajes_archivos = threading.Thread(target=self.escuchar_pipes, args=[self.__pipe_archivos])\n mensajes_aplicacion = threading.Thread(target=self.escuchar_pipes, args=[self.__pipe_aplicaciones])\n\n mensajes_gui.start()\n mensajes_archivos.start()\n mensajes_aplicacion.start()\n\n while self._kernel:\n time.sleep(0.2)\n\n mensajes_gui._stop()\n mensajes_archivos._stop()\n mensajes_aplicacion._stop()\n","sub_path":"kernel/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"178683806","text":"import os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nimport NewsCore.dao.EmployeeDAOImpl as dao\nimport KAFKA.Consumer as consumer\nimport settings as settings\n\n\nif __name__ == \"__main__\":\n #variables\n ip_DCOS_cassandra = settings.ip_DCOS_cassandra\n keyspace = settings.keyspace_cassandra\n topic = 'cyberops_HR'\n field2Extract = 'hr'\n #loading of the cassandra seesion, creatiopn of table (if needded)\n daoStatus = dao.EmployeeDAOImpl()\n daoStatus.createsession(ip_DCOS_cassandra)\n daoStatus.setlogger()\n daoStatus.loadkeyspace(keyspace)\n daoStatus.create_table() #only if table is not created previously\n #Run consumer for HR:\n consumer_hr = consumer.Consumer(topic=topic, field2Extract=field2Extract, DAO=daoStatus, ip_kafka_DCOS=settings.ip_kafka_DCOS)\n consumer_hr.run()\n","sub_path":"BACK/CYBEROPS-master/KAFKA/main_consumer_hr.py","file_name":"main_consumer_hr.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588066848","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport argparse\nimport datetime\nimport colorama\n\nimport backtrader as bt\n\n\nclass NYSE_2016(bt.TradingCalendar):\n params = dict(\n holidays=[\n datetime.date(2016, 1, 1),\n datetime.date(2016, 1, 18),\n datetime.date(2016, 2, 15),\n datetime.date(2016, 3, 25),\n datetime.date(2016, 5, 30),\n datetime.date(2016, 7, 4),\n datetime.date(2016, 9, 5),\n datetime.date(2016, 11, 24),\n datetime.date(2016, 12, 26),\n ]\n )\n\n\nclass St(bt.Strategy):\n params = dict(\n )\n\n def __init__(self):\n pass\n\n def start(self):\n self.t0 = datetime.datetime.utcnow()\n\n def stop(self):\n t1 = datetime.datetime.utcnow()\n print('Duration:', t1 - self.t0)\n\n def prenext(self):\n self.next()\n\n def next(self):\n print('Strategy len {} datetime {}'.format(\n len(self), self.datetime.date()), end=' ')\n\n print(colorama.Fore.GREEN + 'Data0 len {} datetime {}'.format(\n len(self.data0), self.data0.datetime.date()) + colorama.Fore.RESET, end=' ')\n\n if len(self.data1):\n print(colorama.Fore.YELLOW + 'Data1 len {} datetime {}'.format(\n len(self.data1), self.data1.datetime.date()) + colorama.Fore.RESET)\n else:\n print()\n\n\ndef runstrat(args=None):\n args = parse_args(args)\n\n cerebro = bt.Cerebro()\n\n # Data feed kwargs\n kwargs = dict()\n\n # Parse from/to-date\n dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'\n for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):\n if a:\n strpfmt = dtfmt + tmfmt * ('T' in a)\n kwargs[d] = datetime.datetime.strptime(a, strpfmt)\n\n # Data feed\n data = bt.feeds.GenericCSVData(dataname='../datas/GOOG_D1.csv', dtformat='%Y-%m-%d', openinterest=-1, **kwargs)\n\n cerebro.adddata(data)\n\n d1 = cerebro.resampledata(data,\n timeframe=getattr(bt.TimeFrame, args.timeframe))\n d1.plotinfo.plotmaster = data\n d1.plotinfo.sameaxis = True\n\n if args.pandascal:\n cerebro.addcalendar(args.pandascal)\n elif args.owncal:\n cerebro.addcalendar(NYSE_2016)\n\n # Broker\n cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))\n\n # Sizer\n cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))\n\n # Strategy\n cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))\n\n # Execute\n cerebro.run(**eval('dict(' + args.cerebro + ')'))\n\n if args.plot: # Plot if requested to\n cerebro.plot(**eval('dict(' + args.plot + ')'))\n\n\ndef parse_args(pargs=None):\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description=(\n 'Trading Calendar Sample'\n )\n )\n\n # Defaults for dates\n parser.add_argument('--fromdate', required=False, default='2016-01-01',\n help='Date[time] in YYYY-MM-DD[THH:MM:SS] format')\n\n parser.add_argument('--todate', required=False, default='2016-12-31',\n help='Date[time] in YYYY-MM-DD[THH:MM:SS] format')\n\n parser.add_argument('--cerebro', required=False, default='',\n metavar='kwargs', help='kwargs in key=value format')\n\n parser.add_argument('--broker', required=False, default='',\n metavar='kwargs', help='kwargs in key=value format')\n\n parser.add_argument('--sizer', required=False, default='',\n metavar='kwargs', help='kwargs in key=value format')\n\n parser.add_argument('--strat', required=False, default='',\n metavar='kwargs', help='kwargs in key=value format')\n\n parser.add_argument('--plot', required=False, default='',\n nargs='?', const='{}',\n metavar='kwargs', help='kwargs in key=value format')\n\n pgroup = parser.add_mutually_exclusive_group(required=False)\n pgroup.add_argument('--pandascal', required=False, action='store',\n default='', help='Name of trading calendar to use')\n\n pgroup.add_argument('--owncal', required=False, action='store_true',\n help='Apply custom NYSE 2016 calendar')\n\n parser.add_argument('--timeframe', required=False, action='store',\n default='Weeks', choices=['Weeks', 'Months', 'Years'],\n help='Timeframe to resample to')\n\n return parser.parse_args(pargs)\n\n\nif __name__ == '__main__':\n runstrat()\n","sub_path":"cerebro/02_calendar.py","file_name":"02_calendar.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"638479227","text":"################################### LICENSE ####################################\n# Copyright 2016 Morphux #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"); #\n# you may not use this file except in compliance with the License. #\n# You may obtain a copy of the License at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# Unless required by applicable law or agreed to in writing, software #\n# distributed under the License is distributed on an \"AS IS\" BASIS, #\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\n# See the License for the specific language governing permissions and #\n# limitations under the License. #\n################################################################################\n\n##\n# xz_p2.py\n# Created: 21/12/2016\n# By: Louis Solofrizzo \n##\n\nimport os\n\nclass Xz_P2:\n\n conf_lst = {}\n e = False\n root_dir = \"\"\n\n def init(self, c_lst, ex, root_dir):\n self.conf_lst = c_lst\n self.e = ex\n self.root_dir = root_dir\n self.config = {\n \"name\": \"xz\", # Name of the package\n \"version\": \"5.2.2\", # Version of the package\n \"size\": 15, # Size of the installed package (MB)\n \"archive\": \"xz-5.2.2.tar.xz\", # Archive name\n \"SBU\": 0.2, # SBU (Compilation time)\n \"tmp_install\": False, # Is this package part of the temporary install\n \"next\": \"kmod\", # Next package to install\n \"after\": False,\n \"urls\": [ # Url to download the package. The first one must be morphux servers\n \"https://install.morphux.org/packages/xz-5.2.2.tar.xz\"\n ]\n }\n return self.config\n\n def before(self):\n return self.e([\"sed -e '/mf\\.buffer = NULL/a next->coder->mf.size = 0;' -i src/liblzma/lz/lz_encoder.c\"], shell=True)\n\n def configure(self):\n return self.e([\"./configure\",\n \"--prefix=/usr\",\n \"--disable-static\",\n \"--docdir=/usr/share/doc/xz-5.2.2\"\n ])\n\n def make(self):\n return self.e([\"make\", \"-j\", self.conf_lst[\"cpus\"]])\n\n def install(self):\n self.e([\"make\", \"install\"])\n if \"MERGE_USR\" in self.conf_lst[\"config\"] and self.conf_lst[\"config\"][\"MERGE_USR\"] != True:\n self.e([\"mv -v /usr/bin/{lzma,unlzma,lzcat,xz,unxz,xzcat} /bin\"], shell=True)\n self.e([\"mv -v /usr/lib/liblzma.so.* /lib\"], shell=True)\n return self.e([\"ln -svf ../../lib/$(readlink /usr/lib/liblzma.so) /usr/lib/liblzma.so\"], shell=True)\n","sub_path":"pkgs/xz_p2/xz_p2.py","file_name":"xz_p2.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"8340666","text":"\"\"\"Module to convert a number, represented as a sequence of digits in one base, to any other base.\"\"\"\n\n\ndef rebase(input_base: int, digits: list, output_base: int) -> list:\n \"\"\"Rebase the given input value to a different base.\n\n :param input_base: int - initial base of the series of digits.\n :param digits: list - series of digits to convert from `input_base` to `output_base`.\n :param output_base: int - output base of the series of digits.\n :return: list - series of digits in the `output_base`\n\n Function to convert the given series of `digits` from `input_base` to `output_base`.\n \"\"\"\n\n if input_base < 2:\n raise ValueError(\"input base must be >= 2\")\n\n if output_base < 2:\n raise ValueError(\"output base must be >= 2\")\n\n if sum(digits) == 0:\n return [0]\n\n if not all(0 <= digit < input_base for digit in digits):\n raise ValueError(\"all digits must satisfy 0 <= d < input base\")\n\n # convert to decimal\n input_sum = sum(digit * pow(input_base, idx) for idx, digit in enumerate(digits[::-1]))\n\n # convert from decimal\n quotient, remainder = input_sum, 0\n output_digits = []\n\n while quotient != 0:\n quotient, remainder = divmod(quotient, output_base)\n output_digits.append(remainder)\n\n return output_digits[::-1]\n","sub_path":"exercism/python/archive/all-your-base/all_your_base.py","file_name":"all_your_base.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"583236646","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse\nfrom django.db import connection\nfrom django.conf import settings\n\nfrom ..document.models import Annotation, View\nfrom ..task.models import Level, UserQuestRelationship\n\nfrom .serializers import QuestSerializer, LeaderboardSerializer, NERGroupSerializer, TeamLeaderboardSerializer, DocumentRelationSerializer\nfrom ..userprofile.models import Team\nfrom ..common.models import Group\nfrom ..analysis.models import Report\nfrom ..task.models import Task\nfrom ..score.models import Point\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom itertools import chain\n# from itertools import count\nimport networkx as nx\nimport datetime\nimport json\n\n\n_attrs = dict(id='id', source='source', target='target', key='key')\n\n\ndef node_link_data(G, attrs=_attrs):\n multigraph = G.is_multigraph()\n id_ = attrs['id']\n\n source = attrs['source']\n target = attrs['target']\n\n # Allow 'key' to be omitted from attrs if the graph is not a multigraph.\n key = None if not multigraph else attrs['key']\n\n if len(set([source, target, key])) < 3:\n raise nx.NetworkXError('Attribute names are not unique.')\n\n data = {}\n data['directed'] = G.is_directed()\n data['multigraph'] = multigraph\n data['graph'] = list(G.graph.items())\n data['nodes'] = [dict(chain(G.node[n].items(), [(id_, n)])) for n in G]\n data['edges'] = [dict(chain(d.items(), [(source, u), (target, v), ('id', k)])) for u, v, k, d in G.edges_iter(keys=True, data=True)] # N1, N2, IDX, ATTRS\n return data\n\n\ndef group_network(request, group_pk):\n group = get_object_or_404(Group, pk=group_pk)\n\n from ..analysis.tasks import generate_network\n G = generate_network(group.pk, spring_force=8)\n d = node_link_data(G)\n\n return HttpResponse(json.dumps(d), content_type='application/json')\n\n\n@login_required\n@api_view(['GET'])\ndef analysis_group_user(request, group_pk, user_pk=None):\n group = get_object_or_404(Group, pk=group_pk)\n\n response = []\n reports = group.report_set.filter(report_type=Report.AVERAGE).order_by('-created').all()\n user_id = int(user_pk) if user_pk else int(request.user.pk)\n\n for report in reports:\n df = report.dataframe\n df = df[df['user_id'] == user_id]\n\n if df.shape[0] > 0:\n row = df.iloc[0]\n response.append({\n 'created': report.created,\n 'f-score': row['f-score'],\n 'pairings': row['pairings']})\n\n return Response(response)\n\n\n@login_required\n@api_view(['GET'])\ndef analysis_group(request, group_pk):\n group = get_object_or_404(Group, pk=group_pk)\n weighted = True\n\n response = []\n reports = group.report_set.filter(report_type=1).order_by('-created').all()\n for report in reports:\n df = report.dataframe\n\n if weighted:\n df['wf'] = df['pairings'] * df['f-score']\n response.append({\n 'created': report.created,\n 'f-score': df['wf'].sum() / df['pairings'].sum(),\n 'pairings': df['pairings'].sum()})\n\n else:\n response.append({\n 'created': report.created,\n 'f-score': df['f-score'].mean(),\n 'pairings': df['pairings'].sum()})\n\n return Response(response)\n\n\n@login_required\n@api_view(['GET'])\ndef user_task_stats(request):\n ner_level = Level.objects.filter(user=request.user, task_type='e').first()\n re_level = Level.objects.filter(user=request.user, task_type='r').first()\n\n return Response({\n 'ner': ner_level.level if ner_level else 0,\n 're': re_level.level if re_level else 0\n })\n\n\n@login_required\n@api_view(['GET'])\ndef ner_stats(request):\n return Response({\n 'total_score': request.user.profile.score(task='entity_recognition'),\n 'quests_completed': UserQuestRelationship.objects.filter(user=request.user, completed=True).count(),\n 'papers_reviewed': View.objects.filter(user=request.user, completed=True, task_type='cr').count(),\n 'annotations': Annotation.objects.filter(kind='e', view__user=request.user).count()\n })\n\n\n@login_required\n@api_view(['GET'])\ndef re_stats(request):\n return Response({\n 'total_score': request.user.profile.score(task='relation'),\n 'quests_completed': View.objects.filter(user=request.user, completed=True, task_type='ri').count(),\n 'annotations': Annotation.objects.filter(kind='r', view__user=request.user).count()\n })\n\n\n# @login_required\n@api_view(['GET'])\ndef ner_quest(request, group_pk):\n group = get_object_or_404(Group, pk=group_pk)\n\n # we now allow users to see a group 'home page' for detailed information whether or\n # not they are logged in\n if request.user.is_authenticated():\n queryset = Task.objects.filter(kind=Task.QUEST, group=group).extra(select={\n \"current_submissions_count\": \"\"\"\n SELECT COUNT(*) AS current_submissions_count\n FROM task_userquestrelationship\n WHERE (task_userquestrelationship.completed = 1\n AND task_userquestrelationship.task_id = task_task.id)\"\"\",\n \"user_completed\": \"\"\"\n SELECT COUNT(*) AS user_completed\n FROM task_userquestrelationship\n WHERE (task_userquestrelationship.completed = 1\n AND task_userquestrelationship.user_id = %d\n AND task_userquestrelationship.task_id = task_task.id)\"\"\" % (request.user.pk,)\n }).prefetch_related('documents')\n else:\n queryset = Task.objects.filter(kind=Task.QUEST, group=group).extra(select={\n \"current_submissions_count\": \"\"\"\n SELECT COUNT(*) AS current_submissions_count\n FROM task_userquestrelationship\n WHERE (task_userquestrelationship.completed = 1\n AND task_userquestrelationship.task_id = task_task.id)\"\"\"\n }).prefetch_related('documents')\n\n serializer = QuestSerializer(queryset, many=True, context={'user': request.user})\n return Response(serializer.data)\n\n\n# @login_required\n@api_view(['GET'])\ndef ner_list(request):\n queryset = Group.objects.exclude(stub='training').order_by('-order')\n serializer = NERGroupSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n@login_required\n@api_view(['GET'])\ndef re_list(request):\n \"\"\" Returns the available relation tasks for a specific user\n Accessed through a JSON API endpoint\n \"\"\"\n cmd_str = \"\"\n with open('mark2cure/api/commands/get-relations.sql', 'r') as f:\n cmd_str = f.read()\n\n # Start the DB Connection\n c = connection.cursor()\n\n c.execute('SET @user_work_max = {rel_work_size};'.format(rel_work_size=20))\n c.execute('SET @k_max = {completions};'.format(completions=settings.ENTITY_RECOGNITION_K))\n c.execute('SET @user_id = {user_id};'.format(user_id=request.user.pk))\n c.execute('SET @rel_ann_content_type_id = 56;')\n c.execute(cmd_str)\n\n queryset = [{'id': x[0],\n 'document_id': x[1],\n 'title': x[2],\n\n 'total_document_relationships': x[3],\n 'user_document_relationships': x[4],\n\n 'community_answered': x[5],\n 'community_completed': x[6],\n 'community_progress': x[7],\n\n 'user_completed': x[8],\n 'user_progress': x[9],\n 'user_answered': x[10],\n 'user_view_completed': x[11]} for x in c.fetchall()]\n\n # Close the connection\n c.close()\n\n serializer = DocumentRelationSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\ndef users_with_score(days=30):\n today = datetime.datetime.now()\n since = today - datetime.timedelta(days=days)\n\n res = Point.objects.raw(\"\"\"\n SELECT ANY_VALUE(`score_point`.`id`) as `id`,\n SUM(score_point.amount) as score,\n `auth_user`.`username`,\n `auth_user`.`id`\n FROM `score_point`\n LEFT OUTER JOIN `auth_user`\n ON `auth_user`.`id` = `score_point`.`user_id`\n WHERE ( `score_point`.`created` > '{since}'\n AND `score_point`.`created` <= '{today}'\n AND `auth_user`.`id` NOT IN ({excluded_users}) )\n GROUP BY `auth_user`.`id` ORDER BY score DESC;\"\"\".format(\n since=since,\n today=today,\n excluded_users=', '.join('\\'' + str(item) + '\\'' for item in [5, 160]))\n )\n\n return [row for row in res if row.score is not None]\n\n\ndef get_annotated_teams(days=30):\n # (TODO) This could be smaller by only being UserProfiles that\n # we know are part of a Team\n users_queryset = users_with_score(days=days)\n\n teams = Team.objects.all()\n for team in teams:\n team_user_profile_pks = team.userprofile_set.values_list('pk', flat=True)\n team.score = sum(filter(None, [row.score for row in filter(lambda x: x.id in team_user_profile_pks, users_queryset)]))\n teams = list(teams)\n teams.sort(key=lambda x: x.score, reverse=True)\n return teams\n\n\n@login_required\n@api_view(['GET'])\ndef leaderboard_users(request, day_window):\n queryset = users_with_score(days=int(day_window))[:25]\n serializer = LeaderboardSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n@login_required\n@api_view(['GET'])\ndef leaderboard_teams(request, day_window):\n queryset = list(get_annotated_teams(days=int(day_window)))[:25]\n queryset = [team for team in queryset if team.score is not 0]\n serializer = TeamLeaderboardSerializer(queryset, many=True)\n return Response(serializer.data)\n\n","sub_path":"mark2cure/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"335082468","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\nversion = '2020.4.9'\n\nsetup(\n name='django-webpay-soap',\n version=version,\n description='Aplicación Django para integrar WebPay mediante Webservices',\n author='FyF',\n author_email=\"dev@felicesyforrados.cl\",\n url='https://github.com/felicesyforrados/django-webpay-soap',\n license='MIT license',\n platforms=['any'],\n packages=find_packages(),\n classifiers=[\n \"Framework :: Django\",\n \"Environment :: Web Environment\",\n \"Programming Language :: Python\",\n \"Topic :: Utilities\",\n ],\n include_package_data=True,\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"69748039","text":"from linked_list import Node, LinkedList\nfrom blossom_lib import flower_definitions \n\nclass HashMap:\n \n def __init__(self,size):\n self.array_size = size\n self.array = [ LinkedList() for i in range(size)]\n \n def hash(self, key):\n hash_code = sum(key.encode())\n return hash_code\n \n def compress(self, hash_code):\n return hash_code % self.array_size\n \n def assign(self,key,value):\n hash_code = self.hash(key)\n array_index = self.compress(hash_code)\n payload = Node([key,value]) \n\n list_at_array = self.array[array_index]\n for nod in list_at_array:\n if nod[0] == key:\n nod.value = [key,value]\n list_at_array.insert(payload)\n\n def retrieve(self, key):\n hash_code = self.hash(key)\n array_index = self.compress(hash_code)\n list_at_array = self.array[array_index]\n\n for node in list_at_array:\n if node[0] == key:\n return node[1]\n return None\n\nblossom = HashMap(len(flower_definitions))\n\nfor key, value in flower_definitions:\n blossom.assign(key,value)\n\nprint(blossom.retrieve('daisy'))\n\n ","sub_path":"Blossom_Prog_App/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"22153004","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom xml.sax.handler import ContentHandler\nimport sys\nfrom .models import Museo\nfrom xml.sax import make_parser\n\n\ndef normalize_whitespace(text):\n\treturn string.join(string.split(text), ' ')\n\n\nclass myContentHandler(ContentHandler):\n\tdef __init__ (self):\n\t\tself.atributo = \"\"\n\t\tself.inContent = False\n\t\tself.theContent = \"\"\n\t\tself.name = \"\"\n\t\tself.descripcion = \"\"\n\t\tself.accesibilidad = \"\"\n\t\tself.link = \"\"\n\t\tself.direccion = \"\"\n\t\tself.barrio = \"\"\n\t\tself.distrito = \"\"\n\t\tself.telefono = \"\"\n\t\tself.email = \"\"\n\n\n\tdef startElement (self, name, attrs):\n\t\tif name == 'atributo':\n\t\t\tself.atributo = attrs.get('nombre')\n\t\tif self.atributo in ['NOMBRE', 'DESCRIPCION-ENTIDAD',\n\t\t\t\t\t\t\t'ACCESIBILIDAD', 'CONTENT-URL', 'NOMBRE-VIA',\n\t\t\t\t\t\t\t'CLASE-VIAL', 'NUM', 'BARRIO', 'DISTRITO', \n\t\t\t\t\t\t\t'TELEFONO', 'EMAIL']:\n\t\t\tself.inContent = True\n\n \n\tdef endElement (self, name):\n\t\tif self.atributo == 'NOMBRE':\n\t\t\tself.name = self.theContent\n\t\telif self.atributo == 'DESCRIPCION-ENTIDAD':\n\t\t\tself.descripcion = self.theContent\t\t\t\n\t\telif self.atributo == 'ACCESIBILIDAD':\n\t\t\tself.accesibilidad = self.theContent\n\t\telif self.atributo == 'CONTENT-URL':\n\t\t\tself.link = self.theContent\n\t\telif self.atributo == 'NOMBRE-VIA': # direccion\n\t\t\tglobal via\n\t\t\tvia = self.theContent\n\t\telif self.atributo == 'CLASE-VIAL':\n\t\t\tself.direccion = self.theContent\n\t\telif self.atributo == 'NUM':\n\t\t\tself.direccion = self.direccion + \" \" + via + \", \" + self.theContent\n\t\t\tprint(self.direccion)\n\t\telif self.atributo == 'BARRIO':\n\t\t\tself.barrio = self.theContent\n\t\telif self.atributo == 'DISTRITO':\n\t\t\tself.distrito = self.theContent\t\n\t\telif self.atributo == 'TELEFONO':\n\t\t\tself.telefono = self.theContent\t\n\t\telif self.atributo == 'EMAIL':\n\t\t\tself.email = self.theContent\n\t\t\n\t\tself.inContent = False\n\t\tself.theContent = \"\"\t\n\t\tself.atributo = \"\"\n\t\t\n\t\tif name == 'contenido':\n\t\t\tmuseo = Museo(name = self.name, descrip = self.descripcion, \n\t\t\taccess = self.accesibilidad, link = self.link, \n\t\t\tdireccion = self.direccion, barrio = self.barrio, \n\t\t\tdistrito = self.distrito, telefono = self.telefono, email = self.email)\n\t\t\t\n\t\t\tmuseo.save()\n\n\t\t\tself.inContent = False\n\t\t\tself.theContent = \"\"\t\t\n\t\t\tself.atributo = \"\" # inicializamos nuevamente\n\t\t\tself.name = \"\"\n\t\t\tself.descripcion = \"\"\n\t\t\tself.accesibilidad = \"\"\n\t\t\tself.link = \"\"\n\t\t\tself.direccion = \"\"\n\t\t\tself.barrio = \"\"\n\t\t\tself.distrito = \"\"\n\t\t\tself.telefono = \"\"\n\t\t\tself.email = \"\"\n\t\t\t\n\t\t\t\t\t\t\t\t\n\tdef characters (self, chars):\n\t\tif self.inContent:\n\t\t\tself.theContent = self.theContent + chars\n\ndef parsear():\n\t# Load parser and driver\n\ttheParser = make_parser()\n\ttheHandler = myContentHandler()\n\ttheParser.setContentHandler(theHandler)\n\t# Ready, set, go!\n\ttheParser.parse(\"https://datos.madrid.es/egob/catalogo/201132-0-museos.xml\")\n","sub_path":"myproject/museos_app/xml_parser_museos.py","file_name":"xml_parser_museos.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"506963639","text":"import numpy as np\nfrom numpy import *\nimport sys\n\ndef mk_nonlin_comb(a3tb):\n ny,nx,ntb = a3tb.shape \n dtype = a3tb.dtype\n ncomb = ntb + (ntb+1)*ntb/2 + (ntb-1)\n a3out = np.zeros([ny,nx,ncomb],dtype=dtype)\n\n #-- Tb :ntb ----\n a3out[:,:,:ntb] = a3tb\n kt = ntb-1\n\n #-- Tbi * Tbj : (ntb+1)*(ntb)/2 --- \n for i in range(ntb):\n for j in range(i,ntb):\n kt = kt + 1\n a2x = a3tb[:,:,i] * a3tb[:,:,j]\n a3out[:,:,kt] = a2x\n\n #-- (Tbi-Tbi+1)/(Tbi+Tbi+1) : (ntb-1) ---\n for i in range(ntb-1):\n kt = kt + 1\n a2x = (a3tb[:,:,i]-a3tb[:,:,i+1])/(a3tb[:,:,i]+a3tb[:,:,i+1])\n a3out[:,:,kt] = a2x\n\n return a3out\n\n\n\ndef mk_epc_id_nbins(a3epc, a2pc_edge, nbins):\n NEM_USE = 3\n ny,nx,nz = a3epc.shape\n a2id_db = np.zeros([ny,nx],np.int32)\n for iem in range(NEM_USE):\n a1bin = a2pc_edge[iem]\n a2idTmp = np.digitize(a3epc[:,:,iem], a1bin, right=False) - 1\n\n a2idTmp = ma.masked_outside(a2idTmp,0,nbins-1)\n a2id_db = a2id_db + a2idTmp*pow(nbins, NEM_USE-1-iem)\n\n a2id_db = a2id_db.filled(-9999)\n return a2id_db\n\n\n","sub_path":"mkdb/mkdbfunc.py","file_name":"mkdbfunc.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217529899","text":"#################################################################\r\n# Import and Read.me and TO DO #\r\n#################################################################\r\nimport os, time # voor bekijken van foto's nieuwe te plaatsen in de dir en oude te verwijderen\r\nimport sys # zelfde als OS\r\nimport tkinter as tk # TODO nog een frame voor HURRY mode en eentje voor chill mode\r\nfrom PIL import ImageTk,Image # pil is de MAIN functie voor BGRWHITE\r\nimport numpy as np # voor beide BGR2WHITE\r\nimport cv2 # Dit is voor BGR2WHITE\r\n\r\nHEIGHT = 600 # Voor TKinter frames\r\nWIDTH = 800 # Voor TKinter frames\r\n#################################################################\r\n# Read.me #\r\n# bgrwhite heeft een 80% success rate op foto die niet witte #\r\n# Product kleur hebben heeft het plaatje een witte achtergrond #\r\n# dan is het best om de andere mogelijkhijd te gebruiken #\r\n# Bgr2White, deze heeft een 20% maar dit werkt geweldig op #\r\n# plaatjes met een witte product kleur #\r\n# #\r\n# Copyright Hugo van Geijn 06-05-2020 #\r\n#################################################################\r\n\r\n#################################################################\r\n# 80% success rate #\r\n#################################################################\r\n\r\n\r\ndef bgrwhite(foto):\r\n # vars voor de input output maken van de foto's \r\n text = \"./input/\" + foto\r\n temp = \"./TEMP/\" + foto\r\n img = Image.open(text).convert(\"RGB\")\r\n img.save(temp)\r\n pixels = img.load() # maak de pixel map om te zoeken voor de pixel\r\n #if r > 233 and g > 233 and b > 233:\r\n for i in range(img.size[0]): # voor elke pixel in de foto doe:\r\n for j in range(img.size[1]):\r\n # hier splitmatrix naar RGB dan evalueer elke pixel of ze hoger zijn dan VAR\r\n if pixels[i,j][0] >220 and pixels[i,j][1] > 220 and pixels[i,j][2] > 220:\r\n # verander deze RGB voor een andere kleur\r\n pixels[i,j] = (256, 256 ,256)\r\n \r\n nfoto = \"./output/\" + foto \r\n img.save(nfoto)\r\n os.remove(\"./input/\" + foto)\r\n\r\ndef doOnePicture(picture):\r\n bgrwhite(\"./input/\")\r\n\r\ndef allpicslazy():\r\n for geladenfile in os.listdir(\"./input\"):\r\n print(geladenfile)\r\n bgrwhite(geladenfile)\r\n\r\n#########################################################\r\n### 20% success rate vooral bij model foto's ###\r\n#########################################################\r\n\r\ndef bgr2white(foto):\r\n \r\n text = \"./input/\" + foto\r\n #== Parameters niet aan kloten ===================================================\r\n BLUR = 21\r\n CANNY_THRESH_1 = 10\r\n CANNY_THRESH_2 = 200\r\n MASK_DILATE_ITER = 10\r\n MASK_ERODE_ITER = 10\r\n MASK_COLOR = (1.0,1.0,1.0) # In BGR format < (1.0,1.0,1.0) voor wit (0.1, 0.1, 0.1) voor zwart\r\n #####################################################################################\r\n # Processing image to mask #\r\n\r\n #-- lees foto ---------------------------------------------------------------------\r\n img = cv2.imread(text)\r\n #maakt snel een TEMP foto\r\n temp = cv2.imwrite(\"./TEMP/\" + foto, img)\r\n print(\"foto \" + foto + \" geladen\")\r\n row,col = img.shape[:2]\r\n bottom = img[row-2:row, 0:col]\r\n mean = cv2.mean(bottom)[0]\r\n\r\n bordersize = 100\r\n border = cv2.copyMakeBorder(img, top=bordersize, bottom=bordersize, left=bordersize, right=bordersize, borderType=cv2.BORDER_CONSTANT, value=[255, 255, 255])\r\n gray = cv2.cvtColor(border,cv2.COLOR_BGR2GRAY)\r\n\r\n #-- Edge Detectie -------------------------------------------------------------------\r\n edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)\r\n edges = cv2.dilate(edges, None)\r\n edges = cv2.erode(edges, None)\r\n\r\n \r\n #-- vind contouren in edges, sorteer via area ----------------------------------------\r\n contour_info = []\r\n contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\r\n # als je oude CV2 Gebruikt werkt dit niet\r\n\r\n for c in contours:\r\n contour_info.append((\r\n c,\r\n cv2.isContourConvex(c),\r\n cv2.contourArea(c),\r\n ))\r\n contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)\r\n max_contour = contour_info[0]\r\n\r\n #-- maakt een lege MASK, maakt polygons in de MASK ----\r\n # Mask is zwart, polygon is wit\r\n mask = np.zeros(edges.shape)\r\n cv2.fillConvexPoly(mask, max_contour[0], (255))\r\n\r\n #-- Smooth mask, dan blur --------------------------------------------------------\r\n mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)\r\n mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)\r\n mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)\r\n mask_stack = np.dstack([mask]*3) # Create 3-channel alpha mask\r\n\r\n mask_stack = mask_stack.astype('float32') / 255.0 # Use float matrices, \r\n border = border.astype('float32') / 255.0 # for easy blending\r\n\r\n masked = (mask_stack * border) + ((1-mask_stack) * MASK_COLOR) # Blend\r\n masked = (masked * 255).astype('uint8') # Convert back to 8-bit \r\n \r\n badstring = \"./input/\"\r\n foto.replace(\".\", \"\")\r\n foto.replace(\"/\", \"\")\r\n foto.replace(\"input\", \"\")\r\n\r\n #zet de nieuwe foto in de output\r\n newfoto = \"./output/\" + foto\r\n newfile = cv2.imwrite(newfoto, masked)\r\n \r\n # verwijder img van input \r\n os.remove(\"./input/\" + foto)\r\n\r\ndef allpicsexp():\r\n for geladenfile in os.listdir(\"./input\"):\r\n print(geladenfile)\r\n bgrwhite(geladenfile)\r\n\r\n \r\nfilearray = []\r\n#Loop\r\n#TODO frame voor SNELHEIDDDDDDDD\r\n\r\n\r\ni = 0\r\ndef dysWindow():\r\n def refreshimg():\r\n global i\r\n load = Image.open(\"./input/\" + filearray[i])\r\n render = ImageTk.PhotoImage(load)\r\n img = tk.Label(root, image=render)\r\n img.image = render\r\n img.place(relx=0.05, rely=0.25, relwidth=0.9 )\r\n i = i + 1\r\n print(i)\r\n\r\n\r\n root = tk.Toplevel(app)\r\n root.title(\"keuzemenu\")\r\n #laad de foto in\r\n\r\n for geladenfile in os.listdir(\"./input\"):\r\n filearray.append(geladenfile)\r\n load = Image.open(\"./input/\" + filearray[0])\r\n render = ImageTk.PhotoImage(load)\r\n canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, bg=\"#80c1ff\")\r\n canvas.pack()\r\n frame = tk.Frame(root, bg=\"#80c1ff\",bd=5, cursor=\"arrow\")\r\n frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor=\"n\")\r\n\r\n entry = tk.Entry(frame,bg=\"white\", font=40)\r\n entry.place(relwidth=0.65,relheight=1)\r\n\r\n but1 = tk.Button(frame, text=\"grijs naar wit\",font=1,command=lambda: bgrwhite(geladenfile))\r\n but1.place(relx=0.7,relheight=1,relwidth=0.3)\r\n but2 = tk.Button(frame, text=\"MASK\",font=1,command=lambda: bgr2white(geladenfile))\r\n but2.place(relx=0.4,relheight=1,relwidth=0.3)\r\n but3 = tk.Button(frame, text=\"Refresg\",font=1,command=lambda: refreshimg())\r\n but3.place(relx=0.1,relheight=1,relwidth=0.3)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#############################################################################\r\n# TKinter frame voor keuze menu #\r\n#############################################################################\r\napp = tk.Tk()\r\napp.title(\"Grey2White\")\r\ncanvas = tk.Canvas(app, width=500, height=600)\r\ncanvas.pack()\r\nframe = tk.Frame(canvas, bg=\"#80c1ff\",bd=5, cursor=\"arrow\", width=1000, height=1200)\r\nframe.pack()\r\n\r\nlabelExample = tk.Label(frame,bg=\"#80c1ff\", text = \"Lazy Mode Succes:80%\")\r\nlabelExample.pack()\r\nbuttonhint = tk.Label(frame,bg=\"#80c1ff\", text = \"zorg dat er geen witte producten in de INPUT folder staan\")\r\nbuttonhint.pack()\r\nbuttonExample = tk.Button(frame, text=\"Lazy button\", command=allpicslazy)\r\nbuttonExample.pack()\r\nlabelwhite = tk.Label(frame,bg=\"#80c1ff\", text= \"\")\r\nlabelwhite.pack()\r\nlabelexperimental = tk.Label(frame,bg=\"#80c1ff\", text=\"Expirimentele modus Succes: 20%\")\r\nlabelexperimental.pack()\r\nlabelexperimental2 =tk.Label(frame,bg=\"#80c1ff\", text=\"te gebruiken bij foto's met model van ver\")\r\nlabelexperimental2.pack()\r\nbuttonExp = tk.Button(frame, text=\"zorg dat er model foto's van afstand in staan\", command=allpicsexp)\r\nbuttonExp.pack()\r\nlabelwhite2 = tk.Label(frame,bg=\"#80c1ff\", text= \"\")\r\nlabelwhite2.pack()\r\nlabelDYS = tk.Label(frame,bg=\"#80c1ff\", text=\"zelf kiezen per foto\")\r\nlabelDYS.pack()\r\nbuttonDYS = tk.Button(frame, text=\" DYS \", command=dysWindow)\r\nbuttonDYS.pack()\r\n\r\napp.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# roep de functie uit\r\n#bgrwhite(\"front-2.jpg\")\r\n\r\n\r\n\r\n","sub_path":"Removerv2.py","file_name":"Removerv2.py","file_ext":"py","file_size_in_byte":8856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"110178984","text":"from SBaaS_base.postgresql_orm_base import *\nclass data_stage03_quantification_analysis(Base):\n __tablename__ = 'data_stage03_quantification_analysis'\n id = Column(Integer, Sequence('data_stage03_quantification_analysis_id_seq'), primary_key=True)\n analysis_id = Column(String(500))\n simulation_id = Column(String(500))\n used_ = Column(Boolean);\n comment_ = Column(Text);\n\n __table_args__ = (\n UniqueConstraint('analysis_id','simulation_id'),\n )\n\n def __init__(self, \n row_dict_I,\n ):\n self.used_=row_dict_I['used_'];\n self.comment_=row_dict_I['comment_'];\n self.analysis_id=row_dict_I['analysis_id'];\n self.simulation_id=row_dict_I['simulation_id'];\n\n def __set__row__(self,\n analysis_id_I,\n simulation_id_I,\n used__I,\n comment__I):\n self.analysis_id=analysis_id_I\n self.simulation_id=simulation_id_I\n self.used_=used__I\n self.comment_=comment__I\n\n def __repr__dict__(self):\n return {'id':self.id,\n 'analysis_id':self.analysis_id,\n 'simulation_id':self.simulation_id,\n 'used_':self.used_,\n 'comment_':self.comment_}\n \n def __repr__json__(self):\n return json.dumps(self.__repr__dict__())\n\n","sub_path":"SBaaS_thermodynamics/stage03_quantification_analysis_postgresql_models.py","file_name":"stage03_quantification_analysis_postgresql_models.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"298027411","text":"from datetime import datetime\nfrom unittest import TestCase\n\nfrom market.market import StockMarket\n\n\nclass TestStockMarket(TestCase):\n def test_safe_and_load(self):\n tst = StockMarket(['AAPL'], 1000.0, datetime(2018, 5, 5))\n tst.safe_market()\n res = StockMarket.load_market()\n self.assertTrue('AAPL' in res.get_stocks() and len(res.get_stocks()) == 1 and res.today() == datetime(2018, 5, 5))\n\n def test_update_market(self):\n tst = StockMarket(['AAPL'], 1000.0, datetime(2018, 8, 10))\n del tst._StockMarket__stocks['AAPL'].historical_vals[datetime(2018, 8, 10)]\n assert datetime(2018, 8, 10) not in tst.get_stocks()['AAPL'].historical_vals\n tst.update_market()\n self.assertTrue(datetime(2018, 8, 10) in tst.get_stocks()['AAPL'].historical_vals)\n\n def test_buy_amount(self):\n tst = StockMarket(['AAPL'], 1000.0, datetime(2018, 8, 10))\n tst.buy_amount('AAPL', 2)\n self.assertTrue(tst.get_own_capital() < 1000 and tst.get_own_shares()['AAPL'] == 2\n and len(tst.get_own_shares()) == 1)\n\n def test_sell_amount(self):\n tst = StockMarket(['AAPL'], 1000.0, datetime(2018, 8, 10))\n tst.buy_amount('AAPL', 2)\n tst.sell_amount('AAPL', 2)\n self.assertFalse(tst.get_own_shares())\n","sub_path":"test_market/test_stockMarket.py","file_name":"test_stockMarket.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"574983893","text":"import re\nimport exception\nimport utils\n\n\nclass Type(object):\n IGNORE = None\n EOF = 'EOF'\n LEFT_CURLY_BRACKET = 'LEFT_CURLY_BRACKET'\n RIGHT_CURLY_BRACKET = 'RIGHT_CURLY_BRACKET'\n LEFT_SQUARE_BRACKET = 'LEFT_SQUARE_BRACKET'\n RIGHT_SQUARE_BRACKET = 'RIGHT_SQUARE_BRACKET'\n DOLLAR = 'DOLLAR'\n COLON = 'COLON'\n COMMA = 'COMMA'\n KEYWORD = 'KEYWORD'\n STRING = 'STRING'\n NUMBER = 'NUMBER'\n ID = 'ID'\n\n\nclass JSONxToken(object):\n def __init__(self, token_type, value, pos, source=''):\n self.type = token_type\n self.value = value\n self.position = pos\n self.source = source\n self.__line_cache = ()\n\n @property\n def line_col(self):\n if not self.__line_cache:\n self.__line_cache = utils.get_position(self.source, self.position)\n return self.__line_cache\n\n def __eq__(self, other):\n if not isinstance(other, JSONxToken):\n return False\n return self.type == other.type and \\\n self.value == other.value and \\\n self.position == other.position\n\n def __str__(self):\n return repr(self)\n\n def __repr__(self):\n return \"JSONxToken(type={} value='{:.50s}' pos={})\" \\\n .format(self.type, self.value.encode('unicode-escape'), self.position)\n\n\nclass JSONxLexer(object):\n def __init__(self, patterns):\n self.groups = {}\n regex_parts = []\n for i, args in enumerate(patterns):\n pattern, tag, handler = (args[0], args[1], args[2]) if len(args) == 3 else (args[0], args[1], None)\n group_name = 'GROUP_{0}_{1}'.format(i, tag)\n self.groups[group_name] = tag, handler\n regex_parts.append('(?P<{0}>{1})'.format(group_name, pattern))\n self.parser_regex = re.compile('|'.join(regex_parts), re.UNICODE)\n\n def parse(self, source):\n result = []\n source = source\n length = len(source)\n index = 0\n\n while index < length:\n match = self.parser_regex.match(source, index)\n if match:\n group_name = match.lastgroup\n tag, handler = self.groups[group_name]\n text = match.group(group_name)\n if handler:\n text = handler(text)\n if tag:\n result += JSONxToken(tag, text, index, source),\n else:\n raise exception.LexerException('Illegal character \"{0}\"'\n .format(source[index].encode('unicode-escape')),\n utils.get_position(source, index))\n\n index = match.end()\n result += JSONxToken(Type.EOF, 'EOF', index, source),\n return result\n\n_patterns = [\n (r'[ \\t\\r\\n]+', Type.IGNORE),\n (r'//[^\\n]*', Type.IGNORE),\n (r'{', Type.LEFT_CURLY_BRACKET),\n (r'}', Type.RIGHT_CURLY_BRACKET),\n (r'\\[', Type.LEFT_SQUARE_BRACKET),\n (r'\\]', Type.RIGHT_SQUARE_BRACKET),\n (r'\\$', Type.DOLLAR),\n (r'\\:', Type.COLON),\n (r',', Type.COMMA),\n (r'([+-]?(0|[1-9][0-9]*)(\\.[0-9]*)?([eE][+-]?[0-9]+)?)', Type.NUMBER),\n (r'\\b(true|false|null)\\b', Type.KEYWORD),\n # (r'[A-Za-z_][A-Za-z0-9_]*', Type.ID),\n (r'(\"(?:[^\"\\\\]|\\\\.)*\")', Type.STRING, lambda text:utils.decode_escapes(text)[1:-1] if '\\\\' in text else text[1:-1]),\n (r'/\\*(.|\\n)*?\\*/', Type.IGNORE)\n]\n_lexer = JSONxLexer(_patterns)\n\n\ndef tokenize(source):\n return _lexer.parse(source)\n","sub_path":"JSONx/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"159704470","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport random\r\n\r\n# img = cv2.imread(r'C:\\Users\\songwendong\\Desktop\\pic\\a.jpg')\r\n# rows, cols, ch = img.shape\r\n#\r\n# print(rows,cols)\r\n#\r\n# pts1 = np.float32([[ 102,68], [691,67], [97,448 ] ,[700,450]])\r\n# pts2 = np.float32([[0, 0], [800, 0], [0, 508], [800, 508]])\r\n#\r\n#\r\n# M = cv2.getPerspectiveTransform(pts1, pts2)\r\n#\r\n# d=np.array([[224],[208],[1]])\r\n# r=np.dot(M,d)\r\n# print(M)\r\n# print(r)\r\n#\r\n# dst = cv2.warpPerspective(img, M, (800, 508))\r\n# cv2.circle(dst,(r[0],r[1]),3,(0,0,255),-1)\r\n#\r\n# cv2.imwrite(r'C:\\Users\\songwendong\\Desktop\\pic\\axxx.jpg',dst)\r\n#\r\n# cv2.circle(img,(d[0],d[1]),3,(0,0,255),-1)\r\n# cv2.imwrite(r'C:\\Users\\songwendong\\Desktop\\pic\\axxx11111.jpg',img)\r\n#\r\n# plt.subplot(121), plt.imshow(img), plt.title('Input')\r\n# plt.subplot(122), plt.imshow(dst), plt.title('Output')\r\n# plt.show()\r\n\r\n\r\nimg = cv2.imread(r'C:\\Users\\songwendong\\Desktop\\new\\a.jpg')\r\n\r\nrows, cols, ch = img.shape\r\n\r\nrand_range=60\r\ndef generate_rand():\r\n return random.randint(1,rand_range)\r\n\r\n\r\npts1 = np.float32([[ generate_rand(),generate_rand()], [cols-generate_rand(),generate_rand()], [generate_rand(),rows-generate_rand() ] ,[cols-generate_rand(),rows-generate_rand()]])\r\npts2 = np.float32([[generate_rand(), generate_rand()], [cols-generate_rand(), generate_rand()], [generate_rand(), rows-generate_rand()], [cols-generate_rand(), rows-generate_rand()]])\r\n# pts2 = np.float32([[20, 20], [cols-rand_range, 20], [20, rows-rand_range], [cols-rand_range, rows-rand_range]])\r\n\r\n\r\nM = cv2.getPerspectiveTransform(pts1, pts2)\r\n\r\nd=[224,208,1]\r\nr=np.dot(M,d)\r\n\r\n\r\ndst = cv2.warpPerspective(img, M, (cols-10, rows-10))\r\ncv2.circle(dst,(int(r[0]),int(r[1])),3,(0,0,255),-1)\r\ncv2.imwrite(r'C:\\Users\\songwendong\\Desktop\\pic\\axxx.jpg',dst)\r\n\r\ncv2.circle(img,(d[0],d[1]),3,(0,0,255),-1)\r\ncv2.imwrite(r'C:\\Users\\songwendong\\Desktop\\pic\\axxx11111.jpg',img)\r\n\r\n\r\n","sub_path":"PycharmProjects/tensorflowLIANXI/id_card_perspective.py","file_name":"id_card_perspective.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"119530192","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport time\r\nfrom random import randint\r\n\r\n# this is going to be the main class for Tic Tac Toe Game\r\n# All the objects will be inside the class\r\nclass TicTacToe:\r\n def __init__(self):\r\n self.player1 = \"Player1\"\r\n self.player2 = \"Player2\"\r\n self.vsAI = False\r\n self.currentPlayer = \"Player 1\"\r\n self.currentTurn = 0\r\n self.p1 = []\r\n self.p2 = []\r\n self.ai = []\r\n self.root = Tk()\r\n self.main = \"\"\r\n self.gamePage = \"\"\r\n self.gamePad = {}\r\n self.movedTics = []\r\n self.lblDispTurn = \"\"\r\n self.initializeGraphics()\r\n\r\n# Method to set basic properties of the TKINTER Window\r\n def initializeGraphics(self):\r\n # self.root.geometry(\"270x110+500+300\") #Define the size of the window of TKINTER\r\n self.root.title(\"Tic Tac Toe\")\r\n self.homePage()\r\n\r\n# Method to define Main page of the Game\r\n def homePage(self):\r\n self.root.geometry(\"270x110+500+300\")\r\n self.main = LabelFrame(self.root, text=\"Welcome\")\r\n self.main.grid(row=0, columnspan=7, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)\r\n Label(self.main, text=\"Select an Opponent to begin\", font=\"Arial 8 italic\").grid(row=0, sticky='E', padx=5, pady=2)\r\n Button(self.main, text=\"vs AI\", width=10, activebackground=\"red\", command=self.playWithAI).grid(row=3, column=0, sticky=W, pady=4, padx=5)\r\n Button(self.main, text=\"vs Player\", width=10, activebackground=\"green\", command=self.playVS).grid(row=3, column=2, sticky=W, pady=4,padx=5)\r\n\r\n def createGamePad(self):\r\n self.currentTurn = 0\r\n self.currentPlayer = \"Player 1\"\r\n self.p1 = []\r\n self.p2 = []\r\n self.ai = []\r\n self.movedTics = []\r\n self.root.geometry(\"450x225+500+300\")\r\n txt = \"VS AI\" if self.vsAI == True else \"Player 1 vs Player 2\"\r\n self.gamePage = LabelFrame(self.root, text=txt)\r\n self.gamePage.grid(row=3, columnspan=36, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)\r\n Button(self.gamePage, text=\"HOME\", width=10, activebackground=\"blue\", command=self.goHome).grid(row=3, column=2,sticky=W,pady=4,padx=5)\r\n self.lblDispTurn = Label(self.gamePage, text=\" \", font=\"Arial 8 italic\").grid(row=4, sticky='E', ipadx=5, ipady=5)\r\n self.createMatrix()\r\n\r\n def createMatrix(self):\r\n self.root.title(\"Tic Tac Toe: Player 1's Turn\")\r\n self.gamePad[11] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[11].grid(row=7, column=5, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[11].config(command=lambda: self.btnClick(11))\r\n\r\n self.gamePad[12] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[12].grid(row=7, column=10, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[12].config(command=lambda: self.btnClick(12))\r\n\r\n self.gamePad[13] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[13].grid(row=7, column=15, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[13].config(command=lambda: self.btnClick(13))\r\n\r\n self.gamePad[21] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[21].grid(row=12, column=5, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[21].config(command=lambda: self.btnClick(21))\r\n\r\n self.gamePad[22] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[22].grid(row=12, column=10, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[22].config(command=lambda: self.btnClick(22))\r\n\r\n self.gamePad[23] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[23].grid(row=12, column=15, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[23].config(command=lambda: self.btnClick(23))\r\n\r\n self.gamePad[31] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[31].grid(row=17, column=5, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[31].config(command=lambda: self.btnClick(31))\r\n\r\n self.gamePad[32] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[32].grid(row=17, column=10, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[32].config(command=lambda: self.btnClick(32))\r\n\r\n self.gamePad[33] = ttk.Button(self.gamePage, text=\"\")\r\n self.gamePad[33].grid(row=17, column=15, sticky='nsew', ipadx=5, ipady=5)\r\n self.gamePad[33].config(command=lambda: self.btnClick(33))\r\n\r\n def btnClick(self, id):\r\n self.currentTurn += 1\r\n self.movedTics.append(id)\r\n if(self.currentPlayer == \"Player 1\"):\r\n self.setLayout(id, 'X')\r\n self.p1.append(id)\r\n self.checkWinner(self.p1, self.currentPlayer)\r\n if self.vsAI == True:\r\n self.currentPlayer = \"AI\"\r\n self.root.title(\"Tic Tac Toe: AI's Turn\")\r\n time.sleep(2)\r\n self.movesForAI()\r\n else:\r\n self.currentPlayer = \"Player 2\"\r\n self.root.title(\"Tic Tac Toe: Player 2's Turn\")\r\n elif(self.currentPlayer==\"Player 2\"):\r\n self.setLayout(id, 'O')\r\n self.p2.append(id)\r\n self.checkWinner(self.p2, self.currentPlayer)\r\n self.currentPlayer = \"Player 1\"\r\n self.root.title(\"Tic Tac Toe: Player 1's Turn\")\r\n # elif(self.currentPlayer==\"AI\" and self.vsAI==True):\r\n # self.setLayout(id, 'A')\r\n # self.ai.append(id)\r\n # self.checkWinner(self.ai, self.currentPlayer)\r\n # self.currentPlayer = \"Player 1\"\r\n # self.root.title(\"Tic Tac Toe: Player 1's Turn\")\r\n # print(\"AI: {}\".format(self.ai))\r\n\r\n if (self.currentTurn >= 9):\r\n ms = messagebox.askquestion(title=\"Tie: Game Over\", message=\"Have another round?\")\r\n print(ms)\r\n self.goHome() if ms == 'no' else self.createGamePad()\r\n\r\n def movesForAI(self):\r\n allMoves = {\r\n 1:11, 2:12, 3:13,\r\n 4:21, 5:22, 6:23,\r\n 7:31, 8:32, 9:33\r\n }\r\n aiMoved = False\r\n while aiMoved != True:\r\n ranNum = randint(1, 9)\r\n if allMoves[ranNum] in self.movedTics:\r\n continue\r\n aiMoved = True\r\n self.setLayout(allMoves[ranNum], 'A')\r\n self.ai.append(allMoves[ranNum])\r\n self.movedTics.append(allMoves[ranNum])\r\n self.checkWinner(self.ai, self.currentPlayer)\r\n self.currentPlayer = \"Player 1\"\r\n self.root.title(\"Tic Tac Toe: Player 1's Turn\")\r\n\r\n def checkWinner(self, movesList, player):\r\n movesList.sort()\r\n if (list(filter(lambda x: x in [11, 12, 13], movesList)) == [11, 12, 13]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [21, 22, 23], movesList)) == [21, 22, 23]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [31, 32, 33], movesList)) == [31, 32, 33]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [11, 21, 31], movesList)) == [11, 21, 31]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [12, 22, 32], movesList)) == [12, 22, 32]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [13, 23, 33], movesList)) == [13, 23, 33]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [11, 22, 33], movesList)) == [11, 22, 33]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n elif (list(filter(lambda x: x in [13, 22, 31], movesList)) == [13, 22, 31]):\r\n ms = messagebox.askquestion(title=\"{} Won.\".format(player),message=\"Have another round?\")\r\n else:\r\n ms = \"Continue\"\r\n\r\n if ms == 'no':\r\n self.goHome()\r\n elif ms == 'yes':\r\n self.createGamePad()\r\n\r\n def setLayout(self, id, playerSymbol):\r\n self.gamePad[id].config(text=playerSymbol)\r\n self.gamePad[id].state(['disabled'])\r\n self.movedTics.append(id)\r\n\r\n def playWithAI(self):\r\n self.main.grid_forget()\r\n self.vsAI = True\r\n self.createGamePad()\r\n\r\n def playVS(self):\r\n self.main.grid_forget()\r\n self.vsAI = False\r\n self.createGamePad()\r\n\r\n def goHome(self):\r\n self.gamePage.grid_forget()\r\n self.root.title(\"Tic Tac Toe: New Game\")\r\n self.currentTurn = 0\r\n self.currentPlayer = \"Player 1\"\r\n self.p1 = []\r\n self.p2 = []\r\n self.ai = []\r\n self.movedTics = []\r\n self.homePage()\r\n\r\n\r\n def getPlayer1(self):\r\n pass\r\n\r\n def getPlayer2(self):\r\n pass\r\n\r\n def setPlayer1(self):\r\n pass\r\n\r\n def setPlayer2(self):\r\n pass\r\n\r\n def startGame(self):\r\n pass\r\n\r\n\r\n# call the method to start the game.\r\n# If the python program in getting executed directly then only the game would start\r\nif __name__ == \"__main__\":\r\n objTicTacToe = TicTacToe() #Call Class method -> Start Game\r\n objTicTacToe.root.mainloop()","sub_path":"ticTacToe.py","file_name":"ticTacToe.py","file_ext":"py","file_size_in_byte":9504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51930975","text":"from fastapi import APIRouter, Depends\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy.orm import Session\nimport sys\n\nsys.path.append(\"..\")\nfrom utils import deps, schemas\nfrom db import crud\nfrom utils import response_schemas\n\nrouter = APIRouter()\n\n\n@router.post(\"\", responses=response_schemas.general_responses)\ndef create_post(post: schemas.PostCreate,\n db: Session = Depends(deps.get_db),\n current_user: schemas.UserVerify = Depends(\n deps.get_current_user)) -> JSONResponse:\n data = crud.create_post(db=db, user_id=current_user.id, post=post)\n if data is None:\n return JSONResponse(status_code=500,\n content={\"message\": \"Internal Server Error\"})\n return JSONResponse(status_code=200,\n content={\"message\": \"success\"})\n\n\n@router.put(\"{post_id}\", responses=response_schemas.general_responses)\ndef update_post(post_id: int, post: schemas.PostUpdate,\n db: Session = Depends(deps.get_db),\n current_user: schemas.UserVerify = Depends(\n deps.get_current_user)) -> JSONResponse:\n data = crud.update_post(db, post_id=post_id, post=post)\n if data is None:\n return JSONResponse(status_code=500,\n content={\"message\": \"Internal Server Error\"})\n return JSONResponse(status_code=200,\n content={\"message\": \"success\"})\n\n\n@router.delete(\"{post_id}\",\n responses=response_schemas.general_responses)\ndef delete_post(post_id: int, db: Session = Depends(deps.get_db),\n current_user: schemas.UserVerify = Depends(\n deps.get_current_user)) -> JSONResponse:\n data = crud.delete_post(db, post_id=post_id)\n if data is None:\n return JSONResponse(status_code=500,\n content={\"message\": \"Internal Server Error\"})\n return JSONResponse(status_code=200,\n content={\"message\": \"success\"})\n\n\n@router.get(\"{post_id}\",\n responses=response_schemas.single_post_responses)\ndef single_post(post_id: int, db: Session = Depends(deps.get_db),\n current_user: schemas.UserVerify = Depends(\n deps.get_current_user)) -> JSONResponse:\n db_post = crud.get_post(db, post_id=post_id)\n if db_post is None:\n return JSONResponse(status_code=500,\n content={\"message\": \"Internal Server Error\"})\n json_compatible_item_data = jsonable_encoder(db_post)\n return JSONResponse(status_code=200, content=json_compatible_item_data)\n\n\n@router.get(\"{user_id}/all\", responses=response_schemas.all_posts_responses)\ndef all_posts(user_id: int, page_num: int = 1,\n db: Session = Depends(deps.get_db),\n current_user: schemas.UserVerify = Depends(\n deps.get_current_user)) -> JSONResponse:\n\n db_post = crud.get_all_posts(user_id, page_num, db)\n if db_post is None:\n return JSONResponse(status_code=500,\n content={\"message\": \"Internal Server Error\"})\n json_compatible_item_data = jsonable_encoder(db_post.items)\n return JSONResponse(status_code=200,\n content={\"total_pages\": db_post.pages,\n \"total_items\": db_post.total_items,\n \"page_data\": {\"page_num\": page_num,\n \"items_count\": db_post.page_size,\n \"items\":\n json_compatible_item_data}})\n","sub_path":"BlogApp/app/routes/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"325073602","text":"def czytaj(sciezka):\r\n with open(sciezka) as f:\r\n n, kolumny = [int(x) for x in next(f).split()]\r\n data = [[int(x) for x in line.split()] for line in f]\r\n return n, data\r\n\r\n\r\ndef modifyBit(n, p, b):\r\n mask = 1 << p\r\n return (n & ~mask) | ((b << p) & mask)\r\n\r\n\r\ndef decimalToBinary(num):\r\n return bin(num).replace(\"0b\", \"\")\r\n\r\n\r\ndef binaryToDecimal(num):\r\n return int(num, 2)\r\n\r\n\r\ndef PD_rekurencyjny(I, d, F):\r\n bin = decimalToBinary(I)\r\n max_val_tab = []\r\n for j in range(0, len(bin)):\r\n modified = modifyBit(I, j, 0)\r\n modified_binary = decimalToBinary(modified)\r\n reversedstring = ''.join(reversed(bin))\r\n p = [pos for pos, char in enumerate(reversedstring) if char == '1']\r\n if bin != modified_binary:\r\n ile = 0\r\n for m in range(0, len(p)):\r\n ile += d[p[m]][0]\r\n current_F = F[modified]\r\n if current_F == -1:\r\n current_F = PD_rekurencyjny(modified, d, F)\r\n max_val = max(ile - d[j][2], 0) * d[j][1] + current_F\r\n max_val_tab.append(max_val)\r\n min_val = min(max_val_tab)\r\n F[I] = min_val\r\n return min_val\r\n\r\n\r\ndef PD_itreacyjny(n, d):\r\n F = []\r\n max_val_tab = []\r\n\r\n F.append(max(d[0][0] - d[0][2], 0) * d[0][1])\r\n for i in range(1, 2 ** n):\r\n bin = decimalToBinary(i)\r\n for j in range(0, len(bin)):\r\n modified = modifyBit(i, j, 0)\r\n modified_binary = decimalToBinary(modified)\r\n reversedstring = ''.join(reversed(bin))\r\n p = [pos for pos, char in enumerate(reversedstring) if char == '1']\r\n if bin != modified_binary:\r\n ile = 0\r\n for m in range(0, len(p)):\r\n ile += d[p[m]][0]\r\n max_val = max(ile - d[j][2], 0) * d[j][1] + F[modified]\r\n max_val_tab.append(max_val)\r\n min_val = min(max_val_tab)\r\n F.append(min_val)\r\n max_val_tab = []\r\n return F.pop()\r\n\r\n\r\ndef main():\r\n iteracyjne = []\r\n rekurencyjne = []\r\n pliki = ['data10.txt', 'data11.txt', 'data12.txt', 'data13.txt', 'data14.txt', 'data15.txt']\r\n #pliki = ['data10.txt', 'data11.txt', 'data12.txt', 'data13.txt', 'data14.txt', 'data15.txt', 'data16.txt', 'data17.txt', 'data18.txt', 'data19.txt', 'data20.txt']\r\n\r\n for f in pliki:\r\n n, d = czytaj(f)\r\n iteracyjne.append(PD_itreacyjny(n, d))\r\n F = [0]\r\n for i in range(0, 2 ** n - 1):\r\n F.append(-1)\r\n I = 2 ** n - 1\r\n PD_rekurencyjny(I, d, F)\r\n rekurencyjne.append(F.pop())\r\n print(iteracyjne)\r\n print(rekurencyjne)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n","sub_path":"WiTi/PD.py","file_name":"PD.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"23737000","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\nfrom setuptools import setup\nimport os\n\nhere = os.path.abspath(os.path.dirname(__file__))\nabout = {}\nwith open(os.path.join(here, '__version__.py'), 'r') as f:\n exec(f.read(), about)\n\nwith open(os.path.join(here, 'README.md'), 'r') as f:\n readme = f.read()\n\n\nsetup(\n name=about['__title__'],\n description=about['__description__'],\n version=about['__version__'],\n author=about['__author__'],\n author_email=about['__author_email__'],\n url=about['__url__'],\n long_description=readme,\n long_description_content_type='text/markdown',\n packages=[\"oef\"],\n cmdclass={},\n classifiers=[\n \"Development Status :: 3 - Alpha\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI Approved :: Apache Software License\", \"Programming Language :: Python :: 3.6\", \"Programming Language :: Python :: 3.7\"\n ],\n install_requires=[\"protobuf\", \"graphviz\"],\n tests_require=[\"tox\"],\n python_requires='>=3.6',\n license=about['__license__'],\n zip_safe=False\n)\n","sub_path":"pypi_install_script/oef-0.8.1-py3-none-any/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"471209346","text":"from datetime import timedelta, datetime\nfrom collections import OrderedDict\nfrom pymongo import MongoClient\nfrom gridfs import GridFS\nfrom django.utils.timezone import now\nfrom psimonitor.asoup import parse_section_filename, parse_section_id\nfrom bson.objectid import ObjectId\nfrom psimonitor.iso8601 import parse_date\nfrom psimonitor.tz import astana\nimport re\n\n\nclass HeartbeatDAO(object):\n def __init__(self):\n self.client = MongoClient(tz_aware=True)\n self.db = self.client.psimonitor\n self.coll = self.db.heartbeat\n self.status_coll = self.db.processor_status\n\n @staticmethod\n def parse_vaska(data):\n vaska = data.get('vaska_raw_contents', '')\n parsed = {}\n actions = {'in': 1, 'out': 0}\n uid = data.get('uid')\n if not uid:\n return parsed\n for l in filter(None, vaska.split('\\n')):\n actionstr, timestampstr, sections_str = l.split(' ', 2)\n section_ids = map(int, filter(None, sections_str.split(' ')))\n timestamp = parse_date(timestampstr)\n action = actions[actionstr]\n for sid in section_ids:\n v = [timestamp, action, uid]\n try:\n parsed[sid].append(v)\n except KeyError:\n parsed.setdefault(sid, list()).append(v)\n for v in parsed.values():\n v.sort(key=lambda x: x[0])\n return parsed\n\n @staticmethod\n def parse_auth(data, apply_uid_filter=False, min_date=None):\n auth = data.get('driver_auth', {})\n data_uid = data.get('uid')\n if not data_uid:\n return {}\n parsed = {}\n for k, v in auth.items():\n int_sec = int(k)\n for str_timestamp, action, uid in v:\n timestamp = parse_date(str_timestamp, default_timezone=astana)\n if apply_uid_filter and data_uid != uid:\n continue\n if min_date and timestamp < min_date:\n continue\n auth_tuple = [timestamp, action, uid]\n try:\n parsed[int_sec].append(auth_tuple)\n except KeyError:\n parsed.setdefault(int_sec, list()).append(auth_tuple)\n for v in parsed.values():\n v.sort(key=lambda x: x[0])\n return parsed\n\n @staticmethod\n def compare_vaska_auth(data):\n time_treshold = timedelta(minutes=3)\n unique_for = {'auth': {}, 'vaska': {}}\n vaska = HeartbeatDAO.parse_vaska(data)\n if not vaska:\n return unique_for\n min_vaska_timestamp = (\n min(v[0][0] for v in vaska.values()) - time_treshold)\n auth = HeartbeatDAO.parse_auth(\n data, apply_uid_filter=True, min_date=min_vaska_timestamp)\n sections = set(vaska.keys())\n sections.update(auth.keys())\n for k in sections:\n if k not in vaska:\n unique_for['auth'][k] = auth[k]\n continue\n if k not in auth:\n unique_for['vaska'][k] = vaska[k]\n continue\n ufa = unique_for['auth'][k] = []\n ufv = unique_for['vaska'][k] = []\n vaska_list, auth_list = vaska[k][:], auth[k][:]\n i = j = 0\n while True:\n if i >= len(vaska_list) and j >= len(auth_list):\n break\n if i >= len(vaska_list):\n for t in range(j, len(auth_list)):\n ufa.append(auth_list[t])\n break\n if j >= len(auth_list):\n for t in range(i, len(vaska_list) - 1):\n ufv.append(vaska_list[t])\n last = vaska_list[-1]\n # Ignore vaska's last out. Append only if it is `in`\n if last[1] != 0:\n ufv.append(last)\n break\n vts, va = vaska_list[i][:2]\n ats, aa = auth_list[j][:2]\n if (abs(vts - ats) < time_treshold) and (va == aa):\n i += 1\n j += 1\n elif vts < ats:\n ufv.append(vaska_list[i])\n i += 1\n elif vts > ats:\n ufa.append(auth_list[j])\n j += 1\n elif aa == 0:\n ufa.append(auth_list[j])\n j += 1\n elif va == 0:\n ufv.append(vaska_list[j])\n i += 1\n res = {'auth': {}, 'vaska': {}}\n for k, v in unique_for.items():\n items = list(v.items())\n for k1, v1 in items:\n if v1:\n res[k][str(k1)] = v1\n return res\n\n @staticmethod\n def cleanup_data(data):\n keys_to_delete = []\n for k in data.keys():\n if '.' in k:\n keys_to_delete.append(k)\n for k in keys_to_delete:\n del data[k]\n for v in data.values():\n if isinstance(v, dict):\n HeartbeatDAO.cleanup_data(v)\n\n @staticmethod\n def process_data(data):\n try:\n section_ids = [\n parse_section_filename(d) for d in data['dat_files']]\n data['section_ids'] = section_ids\n data['loco_numbers'] = list(set(\n parse_section_id(sid)[1] for sid in section_ids))\n except KeyError:\n pass\n try:\n uid = int(data['aladdin_data']['uid'][1:])\n data['uid'] = uid\n data['tab_num'] = uid % 10000\n except KeyError:\n pass\n try:\n va_comp = HeartbeatDAO.compare_vaska_auth(data)\n data['vaska_auth_compare'] = va_comp\n data['vaska_auth_differ'] = (\n bool(va_comp['vaska']) or bool(va_comp['auth']))\n except (ValueError, KeyError, TypeError, IndexError):\n pass\n\n def update_heartbeat(self, ip_address, data):\n self.coll.update({'_id': ip_address}, {'$set': data}, True)\n\n def get_heartbeats(self):\n heartbeats = {}\n for doc in self.coll.find():\n heartbeats[doc['_id']] = doc\n return heartbeats\n\n def get_heartbeat(self, ip_address):\n return self.coll.find_one({'_id': ip_address})\n\n def add_nmp_insertion_status(self, status):\n cpid = status.pop('cpid')\n timestamp = status.pop('timestamp')\n query = {'cpid': cpid, 'timestamp': timestamp}\n self.db.processor_status.update(query, {'$set': status}, upsert=True)\n\n def status_objects(self, driver=None, cpid=None, section=None, date=None,\n problem_type=None):\n req_param = {}\n try:\n intcn = int(driver)\n if intcn < 10000:\n req_param['tab_num'] = intcn\n else:\n req_param['uid'] = intcn\n except (ValueError, TypeError):\n if driver:\n req_param['aladdin_data.cn'] = re.compile(\n u\"^%s\" % (re.escape(driver), ), re.IGNORECASE | re.U)\n if cpid:\n try:\n req_param['cpid'] = int(cpid)\n except ValueError:\n pass\n if section:\n try:\n intsection = int(section)\n if intsection < 100000:\n req_param['loco_numbers'] = intsection\n else:\n req_param['section_ids'] = intsection\n except (ValueError, TypeError):\n pass\n if date:\n try:\n d = datetime.strptime(date, '%Y-%m-%d').replace(tzinfo=astana)\n req_param['timestamp'] = {\"$gte\": d,\n \"$lt\": d + timedelta(days=1)}\n except (ValueError, TypeError):\n pass\n if problem_type:\n if problem_type == 'no_dat':\n req_param['$and'] = [\n {\"dat_files\": {\"$size\": 0}}, {\"vaska_present\": True}]\n elif problem_type == 'dat_vaska_diff':\n req_param['vaska_auth_differ'] = True\n elif problem_type == 'has_dat_but_not_receipt':\n req_param['$and'] = [\n {\"dat_files\": {\"$exists\": True, \"$not\": {\"$size\": 0}}},\n {\"$or\": [\n {\"receipts\": {\"$size\": 0}},\n {\"receipts\": {\"$exists\": False}}\n ]\n }\n ]\n return (\n self.db.processor_status\n .find(req_param)\n .sort([('timestamp', -1)])\n )\n\n def get_status_object(self, pk):\n return self.db.processor_status.find_one({'_id': ObjectId(pk)})\n\n def set_value(self, domain, key, value):\n self.db.cache.update(\n {'_id': domain},\n {'$set': {key: value}}, upsert=True)\n\n def get_value(self, domain, key):\n r = self.db.cache.find_one({'_id': domain}, {key: 1})\n if r:\n return r[key]\n return None\n\n def get_cache_domain(self, domain):\n return self.db.cache.find_one({'_id': domain})\n\n def store_tarball(self, cpid, timestamp, tarball_file):\n query = {'cpid': cpid, 'timestamp': timestamp}\n fs = GridFS(self.db)\n _id = fs.put(tarball_file)\n self.db.processor_status.update(\n query, {'$set': {'tarball': _id}})\n\n def load_tarball(self, file_id):\n fs = GridFS(self.db)\n gridout = fs.get(ObjectId(file_id))\n return gridout\n\n def weekly_statistics(self):\n raw_week_ago = (now() - timedelta(days=7)).astimezone(astana)\n week_ago = raw_week_ago.replace(\n hour=0, minute=0, second=0, microsecond=0)\n days = [(week_ago + timedelta(days=i)).date() for i in range(8)]\n results = {\n d: {'total': 0, 'no_dat': 0, 'dat_vaska_diff': 0,\n 'has_dat_but_not_receipt': 0} for d in days}\n cursor = self.status_coll.find({'timestamp': {'$gt': week_ago}})\n for o in cursor:\n d = results[o['timestamp'].astimezone(astana).date()]\n d['total'] += 1\n if not o.get('dat_files') and o.get('vaska_present'):\n d['no_dat'] += 1\n if o.get('vaska_auth_differ'):\n d['dat_vaska_diff'] += 1\n if o.get('dat_files') and not o.get('receipts'):\n d['has_dat_but_not_receipt'] += 1\n return OrderedDict(\n sorted(results.items(), key=lambda x: x[0], reverse=True))","sub_path":"monitor/heartbeat.py","file_name":"heartbeat.py","file_ext":"py","file_size_in_byte":10631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"397094224","text":"import requests\nimport json\n\ndef parse_page(url):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 QIHU 360EE'}\n\n response = requests.get(url, headers=headers)\n texts = response.content.decode('utf-8')\n print(texts)\n state = json.loads(response.content)\n\n with open(\"feiyan.json\", \"w\", encoding='utf-8') as f:\n f.write(json.dumps(state, indent=2, ensure_ascii=False))\n print(\"保存成功\")\n\n provincelen = len(state['data'])\n i = 0\n j = 0\n for i in range(provincelen):\n if state['data'][i]['cities'] is None:\n continue\n citylen = len(state['data'][i]['cities'])\n provincename = state['data'][i]['data']['provinceName']\n confirmedCount = state['data'][i]['data']['confirmedCount']\n curedCount = state['data'][i]['data']['curedCount']\n deadCount = state['data'][i]['data']['deadCount']\n provincecontent = str(provincename) + \"确诊病例:\" + str(confirmedCount) + \"已治愈\" + str(curedCount) + \"死亡人数\" + str(\n deadCount)\n with open(\"feiyan.txt\", \"a\") as f:\n f.write(str(provincecontent) + '\\n')\n print(\" \")\n print(provincename, \" 确诊病例:\", confirmedCount, \" 已治愈:\", curedCount, \" 死亡人数:\", deadCount)\n print(\" \")\n for j in range(citylen):\n cityName = state['data'][i]['cities'][j]['cityName']\n diagnosed = state['data'][i]['cities'][j]['diagnosed']\n cured = state['data'][i]['cities'][j]['cured']\n died = state['data'][i]['cities'][j]['died']\n print(cityName, \" 确诊病例:\", diagnosed, \" 已治愈:\", cured, \" 死亡人数:\", died)\n citycontent = str(cityName) + \" 确诊病例:\" + str(diagnosed) + \"已治愈\" + str(cured) + \"死亡人数\" + str(died)\n with open(\"feiyan.txt\", \"a\") as f:\n f.write(str(citycontent) + '\\n')\n\n countrylen = len(state['country'])\n c = 0\n for c in range(countrylen):\n countryname = state['country'][c]['provinceName']\n diagnosed = state['country'][c]['diagnosed']\n cured = state['country'][c]['cured']\n died = state['country'][c]['died']\n print(countryname, \" 确诊病例:\", diagnosed, \" 已治愈:\", cured, \" 死亡人数:\", died)\n\n\ndef main():\n url = 'https://m.look.360.cn/events/feiyan'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 QIHU 360EE'}\n parse_page(url)\n\n\nif __name__ == '__main__':\n main()","sub_path":"examples/肺炎数据解析并存储.py","file_name":"肺炎数据解析并存储.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"610235153","text":"import tkinter as tk\n\nroot = tk.Tk()\n\nswitch_frame = tk.Frame(root)\nswitch_frame.pack()\n\nswitch_variable = tk.StringVar(value=\"off\")\non_button = tk.Radiobutton(switch_frame, text=\"Not a Sharp\", variable=switch_variable,\n indicatoron=False, value=\"off\", width=20)\noff_button = tk.Radiobutton(switch_frame, text=\"Sharp Not Detected\", variable=switch_variable,\n indicatoron=False, value=\"low\", width=20)\non_button.pack(side=\"left\")\noff_button.pack(side=\"left\")\n\n\nroot.mainloop()\n","sub_path":"toggle_button.py","file_name":"toggle_button.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609982904","text":"#coding=utf8\nimport queue\nimport threading\n\nclass ThreadPool(object):\n\n def __init__(self, max_t_count=16):\n self.q = queue.Queue()\n self.max_t_count = max_t_count\n\n self.kill_signal = False\n self.stop_signal = False\n self.pool = []\n self.th_count = 0\n self.locker = threading.Lock()\n # add Thread\n while len(self.pool) < self.max_t_count:\n t = threading.Thread(target=self.event_loop)\n self.pool.append(t)\n # begin Thread\n for t in self.pool:\n t.start()\n self.th_count += 1\n # 添加任务 参数:函数,参数包,回调函数 \n def add_task(self, func, args, callback=None):\n w = (func, args, callback,)\n self.q.put(w)\n # 事件循环,处理任务\n # 多线程重入\n def event_loop(self):\n event = self.q.get()\n while event:\n func, arguments, callback = event # 解开任务包\n try:\n result = func(*arguments) # 执行任务\n status = True # 执行正常\n except Exception as e:\n status = False # 执行不正常\n result = e # 返回错误\n print(\"ERROR Exception\" ,e)\n\n if callback is not None: # 处理回调\n try:\n callback(status, result)\n except Exception as e:\n print(\"ERROR Exception\" ,e)\n\n if self.kill_signal: # 处理信号\n break\n else:\n event = self.q.get()\n with self.locker:\n self.th_count -= 1\n if not self.kill_signal:\n print(\"Thread exit\")\n else:\n print(\"Thread killed\")\n \n # 线程数\n def t_size(self):\n return len(self.pool)\n \n # 队列大小\n def q_size(self):\n return self.q.qsize()\n \n # 发送结束信号\n def stop_all(self):\n self.stop_signal = True\n for i in range(self.th_count):\n self.q.put(None)\n print('Stop signal send')\n \n # 线程执行完当前任务后立即结束\n def kill_all(self):\n self.kill_signal = True\n print('Kill signal send')\n \n # 等待所有任务结束\n # 允许外部直接中断\n def wait(self, cond=True):\n while True:\n if not cond and not self.kill_signal:\n self.kill_all()\n if self.q_size() == 0 and not self.stop_signal:\n self.stop_all()\n if self.th_count == 0:\n break\n\nfrom time import sleep\ndef work(i):\n print(i,'start')\n for j in range(1,i+1):\n sleep(1)\n print(str(i) + 'tick %d' % j)\n print(str(i) + ' Done')\n\nif __name__ == \"__main__\":\n pool = ThreadPool(2)\n print('pool init succ')\n pool.add_task(func=work, args=(2,))\n pool.add_task(func=work, args=(5,))\n pool.add_task(func=work, args=(3,))\n \n print('TH size: ' , len(pool.pool))\n pool.wait(False)\n #sleep(2)\n #pool.kill_all()\n print(pool.q_size(), pool.th_count,pool.t_size())\n\n","sub_path":"libs/ThreadPoolv3.py","file_name":"ThreadPoolv3.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42986435","text":"import sys, os\nsys.path.append(\"/Users/maxime/IndividualProject/code/Data_Assimilation/src/\")\n\nfrom UnstructuredCAEDA.settings.models.resNeXt import ResStack3\nfrom UnstructuredCAEDA.settings.models.CLIC import CLIC\nfrom UnstructuredCAEDA.train import TrainAE\nfrom UnstructuredCAEDA.VarDA import BatchDA\n\nfrom UnstructuredCAEDA.utils.expt_config import ExptConfigTest\nfrom datetime import datetime\nimport argparse\n\nTEST = True\nGPU_DEVICE = 0\nexp_base = \"\"\n\n#global variables for DA and training:\nclass ExptConfig():\n EPOCHS = 5\n SMALL_DEBUG_DOM = False #For training\n calc_DA_MAE = True\n num_epochs_cv = 0\n LR = 0.0002\n print_every = 10\n test_every = 10\n\ndef main():\n print(\"\\n-------------------------Started at {} ------------------- \\n\".format(datetime.now()))\n if TEST:\n expt = ExptConfigTest()\n else:\n expt = ExptConfig()\n\n expdir = \"experiments/structuredCAE/\"\n CLIC_kwargs = {\"model_name\": \"Tucodec\", \"block_type\": \"NeXt\", \"Cstd\": 64, \"dim\": 3, \"clusterInputSize\": 0, \"name\": None}\n\n settings = CLIC(**CLIC_kwargs)\n settings.GPU_DEVICE = GPU_DEVICE\n settings.export_env_vars()\n print(\"settings data path \", settings.DATA_FP)\n \n print(\"------------------------- Simulation started at {} ------------------- \\n\\n\".format(datetime.now()))\n trainer = TrainAE(settings, expdir)\n expdir = trainer.expdir #get full path\n model = trainer.train(num_epochs=expt.EPOCHS, num_workers=0, test_every=expt.test_every,\n num_epochs_cv=expt.num_epochs_cv,\n learning_rate = expt.LR,\n small_debug=expt.SMALL_DEBUG_DOM) #this will take approximately 8 hrs on a K80\n\n # #evaluate DA on the test set:\n results_df = BatchDA(settings, AEModel=model).run()\n\n print(\"------------------------- Ended at {} -------------------- \\n\".format(datetime.now()))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"StructuredCAE.py","file_name":"StructuredCAE.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605823057","text":"import os\nimport re\nimport json\nimport string\nimport random\n\n\nfrom .utils.kfrozendict import kfrozendict\nfrom .utils.yparse import yparse, yload_file, invert, yload_definition\n\nfrom .exceptions import SchemaError\n\n# components\nfrom .components import Surv\nfrom .components import ChoiceLists, Choice\nfrom .components import TxList, Translation\nfrom .components import Settings\nfrom .components import Metas\n\nfrom .components.base_component import SurveyComponentWithTuple, SurveyComponentWithDict\n\nfrom .transformations import TRANSFORMERS\n\nSCHEMAS = [\n '1',\n '2',\n]\n\nSCHEMA_ALIASES = {\n '1+::': '1+flattened_translations',\n '1::': '1+flattened_translations',\n 'xlsform': '1+flattened_translations',\n}\nSCHEMA_ALIASES_REVERSE = dict([(v, k) for (k, v) in SCHEMA_ALIASES.items()])\n\ndef unpack_schema_string(schema):\n schema = SCHEMA_ALIASES.get(schema, schema)\n [schema, *transformations] = [ss.strip()\n for ss in re.split(r'\\++', schema)]\n return (schema, transformations)\n\n\n\n\nMETAS = yload_file('defs/_settingsMetas')\n\nDEPTH = 0\n\n\ndef _unpack_v1_settings(_dsetts=None):\n # pulls first item from an array, defaults to an empty object\n if _dsetts is None:\n return {}\n if isinstance(_dsetts, (list, tuple)):\n if len(_dsetts) > 0:\n return _unpack_v1_settings(_dsetts[0])\n else:\n return {}\n return _dsetts\n\n\ndef _sans_empty_values(obj):\n # remove keys with 'None' as a value in the returned dict\n for delete_key in [k for (k, v) in obj.items() if v is None]:\n del obj[delete_key]\n return obj\n\n\nclass Content:\n # is this the right place for these properties? 🤔\n META_TYPES = set(METAS['properties'].keys())\n ANCHOR_KEY = '$anchor'\n\n def __init__(self,\n content,\n perform_validation=False,\n generate_anchors=False,\n anchor_generator=False,\n exports_include_defaults=False,\n strip_unknown=False,\n ):\n content = kfrozendict.freeze(content)\n self._translated_columns = None\n self.perform_renames = True\n self.perform_transformations = True\n\n self.generate_anchors = generate_anchors\n if anchor_generator:\n self.anchor_generator = anchor_generator\n\n self.remove_nulls = not exports_include_defaults\n self.strip_unknown = strip_unknown\n\n self.perform_validation = perform_validation\n\n self.default_tx = False\n\n try:\n schema = content['schema']\n except KeyError as err:\n raise ValueError('content.schema not found')\n\n\n (schema, transformations) = unpack_schema_string(schema)\n\n if len(transformations) > 0:\n for transformation in transformations:\n content = TRANSFORMERS[transformation].rw(content)\n\n self._v = schema\n self.schema = self._v\n\n self.data = kfrozendict.freeze(content)\n\n if self._v == '1':\n self.load_content_schema_1()\n elif self._v == '2':\n self.load_content_schema_2()\n\n if self.generate_anchors:\n for row in self.survey:\n if not row.has('$anchor'):\n _anchor = self.anchor_generator()\n row.set_untranslated('$anchor', _anchor)\n for (cname, clist) in self.choices.items():\n for choice in clist:\n has_anchor = False\n for kv in choice:\n if kv.key == '$anchor':\n has_anchor = True\n if not has_anchor:\n _anchor = self.anchor_generator()\n choice.set_untranslated('$anchor', _anchor)\n\n if self.perform_validation:\n self._validate_export()\n\n def _validate_export(self):\n validate(self.export(schema='2'), JSONSCHEMA)\n\n def anchor_generator(self):\n length = 9\n alphabet = string.ascii_lowercase + string.digits\n return ''.join([\n random.choice(string.ascii_lowercase),\n ] + [\n random.choice(alphabet) for _ in range(length - 1)\n ])\n\n def ensure_default_language(self):\n _from_setting = self._data_settings.get('default_language')\n if not self.default_tx:\n dtx_index = 0\n if _from_setting:\n names = [tx.as_string_or_null() for tx in self.txs]\n if _from_setting in names:\n dtx_index = names.index(_from_setting)\n if len(self.txs) > 0:\n self.default_tx = self.txs._tuple[dtx_index]\n\n def export(self, schema='2'):\n result = None\n\n # completed_transformations = []\n (schema, transformations) = unpack_schema_string(schema)\n\n if schema == '1':\n result = self.to_v1_structure()\n else:\n result = self.to_structure(schema=schema)\n\n\n result = kfrozendict.freeze(result)\n schemas = [schema]\n for transformation in transformations:\n result = TRANSFORMERS[transformation].fw(result)\n schemas.append(transformation)\n # result = kfrozendict.unfreeze(result)\n\n return kfrozendict.unfreeze(\n result.copy(schema='+'.join(schemas))\n )\n\n def value_has_tx_keys(self, val):\n if not isinstance(val, (dict, kfrozendict)):\n return False\n valkeys = set(val.keys())\n _has_tx_keys = len(valkeys) > 0 and valkeys.issubset(self.txs.codes)\n if not _has_tx_keys and 'tx0' in valkeys:\n raise Exception('missing tx key?')\n return _has_tx_keys\n\n def to_structure(self, schema='2'):\n return _sans_empty_values(kfrozendict.unfreeze({\n 'schema': schema,\n 'translations': self.txs.to_list(schema=schema),\n 'survey': self.survey.to_list(schema=schema),\n 'choices': self.choices.to_dict(schema=schema),\n 'settings': self.settings.to_dict(schema=schema),\n }))\n\n def load_content_schema_2(self):\n content = self.data\n self._data_settings = self.data.get('settings', {})\n\n self.metas = Metas(content=self)\n self.txs = TxList(content=self)\n\n self.ensure_default_language()\n\n _ctmp = content.get('choices', {})\n self.choices = ChoiceLists(content=self)\n\n self.survey = Surv(content=self)\n self.settings = Settings(content=self)\n\n\n def load_content_schema_1(self):\n content = self.data\n self._data_settings = _unpack_v1_settings(self.data.get('settings'))\n\n if 'choices' not in content:\n self.data = self.data.copy(choices=[])\n\n _tcols = self.data.get('translated', [])\n self._translated_columns = _tcols\n self.metas = Metas(content=self)\n self.txs = TxList(content=self)\n self.ensure_default_language()\n self.choices = ChoiceLists(content=self)\n self.survey = Surv(content=self)\n self.settings = Settings(content=self)\n\n def to_v1_structure(self):\n colnames = self.survey.get_tx_col_names_for_v1().union(\n self.choices.get_tx_col_names_for_v1()\n )\n return kfrozendict.unfreeze({\n 'schema': '1',\n 'translated': sorted(colnames),\n 'translations': self.txs.to_v1_strings(),\n 'survey': self.survey.to_list(schema='1'),\n 'choices': self.choices.to_old_arr(),\n 'settings': self.settings.to_dict(schema='1'),\n })\n","sub_path":"a1d05eba1/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":7609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"175421065","text":"\"\"\"\nDefines features for the Peewee ORM.\n\"\"\"\n\nfrom peewee import CompositeKey\n\nfrom ..bases import BasePartitionFeature, BaseOperationFeature\n\n\nclass OperationFeature(BaseOperationFeature):\n def execute(self, sql, autocommit=True):\n return self.model_cls._meta.database.execute_sql(sql.replace('%', '%%'), require_commit=autocommit)\n\n\nclass PartitionFeature(BasePartitionFeature):\n decorate = ('save',)\n\n @property\n def model_meta(self):\n meta = self.model_cls._meta\n pk = meta.primary_key\n\n return {\n 'table': meta.db_table,\n 'pk': list(pk.field_names) if isinstance(pk, CompositeKey) else pk.name,\n 'dialect': meta.database.__class__.__name__.lower().replace('database', ''),\n 'column_value': self._column_value(meta.get_field_names()),\n }\n\n @staticmethod\n def _decorate_save(method):\n \"\"\"\n Checks if partition exists and creates it if needed before saving model instance.\n \"\"\"\n def wrapper(instance, *args, **kwargs):\n partition = instance.architect.partition.get_partition()\n\n if not partition.exists():\n partition.create()\n\n method(instance, *args, **kwargs)\n return wrapper\n","sub_path":"stockenv/lib/python3.4/site-packages/architect/orms/peewee/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"310313598","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport math\nimport serial\nimport urllib.request\nimport urllib\nimport random\nimport json\nimport time\n\n\ns = serial.Serial('/dev/ttyACM0', 9600)\n\nif(len(sys.argv) != 3):\n print('Usage: python3 navigate.py ')\n exit(-127)\n\nlongitude = float(sys.argv[1])\nlatitude = float(sys.argv[2])\n\ndef get_message():\n url = 'http://onns.xyz/api/info'\n #url = 'http://192.168.8.102/api/info'\n post_data = {}\n f = urllib.request.urlopen(url, urllib.parse.urlencode(post_data).encode('ascii'))\n data = json.loads(f.read().decode('utf-8'))\n return data\n\ndef send_message(content):\n print(content)\n s.write(content.encode())\n time.sleep(0.1)\n return 0\n\ndef get_degree(lonA, latA, lonB, latB): \n radLatA = math.radians(latA) \n radLonA = math.radians(lonA) \n radLatB = math.radians(latB) \n radLonB = math.radians(lonB) \n dLon = radLonB - radLonA \n y = math.sin(dLon) * math.cos(radLatB) \n x = math.cos(radLatA) * math.sin(radLatB) - math.sin(radLatA) * math.cos(radLatB) * math.cos(dLon) \n brng = math.degrees(math.atan2(y, x)) \n brng = (brng + 360) % 360 \n return brng\n\ndef get_angle():\n while(True):\n send_message('4')\n time.sleep(1)\n if(s.inWaiting() != 0):\n data = s.read(s.inWaiting()).decode('ascii')\n break\n return float(data[15:-1])\n\ndef change_speed(angle1, angle2):\n deta = (angle2 - angle1 + 360) % 360\n if(0 <= deta and deta < 180):\n send_message('0175255335')\n if(180 <= deta and deta < 360):\n send_message('0335255175')\n time.sleep(0.5)\n send_message('0255255255')\n\ndef go_straight():\n send_message('0355355355')\n time.sleep(5)\n send_message('0255255255')\n\nif __name__ == \"__main__\":\n try:\n # while(True):\n # info = get_message()\n # target_angle = get_degree(info['longitude'], info['latitude'], longitude, latitude)\n # print('target_angle: ', target_angle)\n # now_angle = get_angle()\n # print('now_angle: ', now_angle)\n # if(info['longitude'] == longitude and info['latitude'] == latitude):\n # print('Done!')\n # break\n # if(abs(int(now_angle) - int(target_angle)) < 20):\n # print('go straight 5s')\n # go_straight()\n # else:\n # change_speed(target_angle, now_angle)\n # time.sleep(0.5)\n while True:\n print(get_angle())\n except KeyboardInterrupt:\n print('Bye~')\n","sub_path":"core/navigate.py","file_name":"navigate.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"151300574","text":"import random\r\nimport math\r\n\r\n'''\r\n This class represents a vector, which is a kind of object which has both a size and a direction, like when you move your body,\r\n your delta-x vector has two things: your direction, which is from the first point to the second, and the size which is the\r\n distance between the two points.\r\n'''\r\nclass Vector: \r\n x = 0\r\n y = 0\r\n angle = None\r\n size = None\r\n\r\n\r\n def __init__(self, size = random.uniform(1, 10), angle = random.uniform(0, 2 * math.pi)):\r\n '''\r\n This function is the constructor function of the class Vector, it will initiallize all the fields of the vector\r\n object. the angle, and the size.\r\n '''\r\n self.x = math.cos(angle) * size\r\n self.y = math.sin(angle) * size\r\n self.angle = angle\r\n self.size = size\r\n\r\n def set_xy(self, x, y):\r\n '''\r\n This function will let the programmer change the x and y variables of the vector, which in turn will change the\r\n size and angle of the vector.\r\n '''\r\n size = math.sqrt(x ** 2 + y ** 2)\r\n angle = math.atan2(y, x)\r\n self.__init__(size = size, angle = angle)\r\n\r\n def get_values(self):\r\n # This function will return the x and y variables of the vector.\r\n return (self.x, self.y)\r\n\r\n def change_angle(self, new_angle):\r\n '''\r\n This function will change the angle of the vecot,r which in turn will change the x and y variables of it and\r\n The size of the vector.\r\n '''\r\n self.angle = new_angle\r\n self.x = math.cos(self.angle) * self.size\r\n self.y = math.sin(self.angle) * self.size\r\n\r\n def change_y(self, new_y):\r\n '''\r\n This function will change the y variable of the vector, which in turn will change the size and angle of the\r\n vector.\r\n '''\r\n if self.x == 0:\r\n # If x = 0, then the angle of the vector must be 90 or 270 degrees but in radians.\r\n if new_y > 0:\r\n self.angle = math.pi / 2\r\n else:\r\n self.angle = math.pi * 1.5\r\n self.size = new_y\r\n self.y = new_y\r\n else:\r\n self.y = new_y\r\n self.angle = math.atan2(self.y, self.x)\r\n self.size = math.sqrt(self.x ** 2 + self.y ** 2)\r\n\r\n def change_x(self, new_x):\r\n '''\r\n This function will change the x variable of the vector, which in turn will change the size and angle of the \r\n vector.\r\n '''\r\n if new_x == 0:\r\n if self.y > 0:\r\n self.angle = math.pi / 2\r\n else:\r\n self.angle = math.pi * 1.5\r\n self.size = self.y\r\n self.x = new_x\r\n else:\r\n self.x = new_x\r\n self.angle = math.atan2(self.y, self.x)\r\n self.size = math.sqrt(self.x ** 2 + self.y ** 2)","sub_path":"vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"490652619","text":"def collatz(num):\n term = 0\n while True:\n # print(num)\n term += 1\n # print(num)\n if num <= 1:\n break\n elif num % 2 == 0:\n num /= 2\n elif num % 2 != 0:\n num = (3 * num) + 1\n # print(\"terms:\", term)\n return term\n\n\n# collatz(13)\n\nmaxterm = 0\nterm = 0\nfor x in range(1, 1000):\n # print(\"x: \",x)\n term = collatz(x)\n # print(\"term: \",term)\n if term > maxterm:\n maxterm = term\n\nprint(maxterm)\n","sub_path":"Problem014.py","file_name":"Problem014.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"589814809","text":"import os, shutil\nimport calendar\nfrom datetime import datetime, date\n\ndef timeformat(x=datetime.now(), typ='DATE'):\n if type(x) != type(datetime.now()):\n x = datetime(x)\n if typ == 'DATE':\n return x.strftime('%Y-%m-%d')\n elif typ =='HOUR':\n return x.strftime('%H:%M:%S')\n elif typ=='BOTH':\n return x.strftime('%Y-%m-%d')+'%20'+x.strftime('%H:%M:%S')\n\ndef utc(x, totimestamp=False):\n if totimestamp == False:\n return timeformat(datetime.utcfromtimestamp(x))\n else:\n d = datetime(*x)\n epoch = datetime(1970,1,1)\n return int((d - epoch).total_seconds())\n\n\ndef zipit(path):\n try:\n shutil.make_archive(path, 'zip', path)\n return path + '.zip'\n except Exception as e:\n print(e)\n\ndef clean(path = 'temp/', log = False):\n for file in os.listdir(path):\n if file == '.gitkeep':\n continue\n file_path = os.path.join(path, file)\n# print(file_path)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print(e)\n if log == True:\n return '\\n'.join(os.listdir(path))\n\nif __name__ == '__main__':\n print(utc(1546300800))\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"337361046","text":"from dotenv import load_dotenv\nimport os\nimport requests\nimport json\n\n# Import authentication class\nfrom modules.azure_rest_api import AuthenticatorMSALAPIRequests\n\n\n# Load .env file\nload_dotenv()\n\n# Get .env variables or declare variables here with according inputs\nCLIENT_ID = os.getenv(\"CLIENT_ID\")\nCLIENT_SECRET = os.getenv(\"CLIENT_SECRET\")\nTENANT_ID = os.getenv(\"TENANT_ID\")\nSUBSCRIPTION_ID = os.getenv(\"SUBSCRIPTION_ID\")\n\n\n# Create a class with desired API calls which inherits from AuthenticatorMSALAPIRequests.\nclass MyAzureAPICallerClass(AuthenticatorMSALAPIRequests):\n \"\"\"\n Class with all required methods to call the desired Azure API endpoints.\n \"\"\"\n\n # Define desired methods here\n # EXAMPLES:\n\n def get_call(self, url):\n \"\"\"\n Simple example GET call. \n Takes the desired GET URL.\n Returns json data.\n \"\"\"\n r = requests.get(url=url, headers=self.headers)\n data = json.loads(json.dumps(r.json()))\n return data\n\n def get_all_resource_groups(self):\n \"\"\"\n Get all resource groups within the subscription.\n \"\"\"\n url = f\"https://management.azure.com/subscriptions/{self.subscription_id}/resourceGroups/\"\n params = {'api-version': '2020-10-01'}\n headers = self.headers\n r = requests.get(url, headers=headers, params=params)\n data_rgs = json.loads(json.dumps(r.json()))\n return data_rgs\n\n\n# Instantiate the class\napi_caller = MyAzureAPICallerClass(CLIENT_ID,\n CLIENT_SECRET,\n TENANT_ID,\n SUBSCRIPTION_ID,\n scope_list=[\"https://management.azure.com/.default\"])\n\n# Simple get call with URL as parameter\nprices_data = api_caller.get_call(\n \"https://prices.azure.com/api/retail/prices?$filter=priceType eq 'Reservation' and location eq 'EU West'&$top=50\"\n)\n\n# Get all resource groups within the subscription\nresource_group_data = api_caller.get_all_resource_groups()\n","sub_path":"example_app.py","file_name":"example_app.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"441002653","text":"#!/usr/bin/python3\n\"\"\"\nAdds two integers\na and b must be integers or float\notherwise raise TypeError\nfloat must be converted to int\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n Add two integers\n Parameters:\n a is the first parameter\n b is the second parameter, if is empty takes the value of 98\n Return: The addition of the two integers\n \"\"\"\n if not isinstance(a, (int, float)):\n raise TypeError(\"a must be an integer\")\n if not isinstance(b, (int, float)):\n raise TypeError(\"b must be an integer\")\n if type(a) is float:\n a = int(a)\n if type(b) is float:\n b = int(b)\n return a + b\n","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"213344212","text":"import tweepy\r\n\r\nckey = 'njD0kW0BVIIzixHVJ1aFuiTpF'\r\ncsecret = 'gBCbfupgnbJ2Sx23g6DlpsX6sTSATE31mBiM24pAeVwOIhHICC' \r\natoken = '435458877-XQYTGqw7BoIxVjn7Al8hvefzcCMxtRLtfrBmltmd' \r\nasecret = 'XOf0GJxiYiWRslfjT1XRB9UHVQ3maXckLeTeUiBgQ5NOK'\r\n\r\nauth = tweepy.OAuthHandler(ckey, csecret)\r\nauth.set_access_token(atoken, asecret)\r\n\r\napi = tweepy.API(auth)\r\n\r\nnames = []\r\nfollowers = []\r\ncount = 0\r\nfor user in tweepy.Cursor(api.friends).items(50):\r\n\ttry:\r\n\t\t#print(count)\r\n\t\tprint(user.screen_name)\r\n\t\tnames.append(str(user.screen_name))\r\n\t\tprocess_status(user)\r\n\t\tcount+=1\r\n\texcept:\r\n\t\tpass\r\n\t\tcount+=1\r\nprint(len(names))\r\nprint(len(followers))\r\n\r\nfilename = r\"C:\\Users\\Ryan\\Documents\\WebScience\\Assignment6\\List.txt\"\r\noutfile = open(filename, 'w')\r\noutfile.write(\"\\n\".join(names))\r\noutfile.close()\r\nfilename = r\"C:\\Users\\Ryan\\Documents\\WebScience\\Assignment6\\List1.txt\"\r\noutfile = open(filename, 'w')\r\noutfile.write(\"\\n\".join(names))\r\noutfile.close()\r\n\r\nfilename = r\"C:\\Users\\Ryan\\Documents\\WebScience\\Assignment6\\List.txt\"\r\ninfile = open(filename, 'r')\r\nnames = []\r\nnames1 = []\r\n\r\nfor line in infile:\r\n\tnames.append(line)\r\nprint(len(names))\r\n\r\nfilename = r\"C:\\Users\\Ryan\\Documents\\WebScience\\Assignment6\\List1.txt\"\r\ninfile1 = open(filename, 'r')\r\nfor line1 in infile1:\r\n\tnames1.append(line1)\r\nprint(len(names1))\r\n\r\n\r\nfor person in names:\r\n\tfor peeps in names1:\r\n\t\tif person == peeps:\r\n\t\t\tpass\r\n\t\telse:\r\n\t\t\t#statement = api.exists_friendship(person, peeps)\r\n\t\t\t#print(statement)\r\n\t\t\trelationship = api.show_friendship(source_screen_name=person, target_screen_name=peeps)\r\n\t\t\tsource, destination = relationship\r\n\t\t\tprint(source.followed_by, destination.screen_name)\r\n\t\t\tprint(destination.followed_by, source.screen_name)\r\n\t\t\tprint(\"\\n\")\r\n\t\t\tif source.followed_by == true:\r\n\t\t\t\tfilename = r\"C:\\Users\\Ryan\\Documents\\WebScience\\Assignment6\\Relationships\\'\"+source.screen_name + \".txt\"\r\n\t\t\t\toutfile = open(filename, 'a')\r\n\t\t\t\toutfile.write(source.screen_name + \" \"+str(source.followed_by) +\" \"+ destination.screen_name+\"\\n\")\r\n\t\t\t\toutfile.close()","sub_path":"Assignment6/A6Q1.py","file_name":"A6Q1.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"408127268","text":"from descarteslabs.common.graft import client\n\nfrom descarteslabs.workflows.types.core import typecheck_promote\nfrom descarteslabs.workflows.types.primitives import Bool\nfrom descarteslabs.workflows.types.proxify import proxify\n\n\n@typecheck_promote(Bool, None, None)\ndef ifelse(condition, true_value, false_value):\n \"\"\"\n An if-else statement: returns ``true_value`` if ``condition`` is True, otherwise ``false_value``.\n\n ``true_value`` and ``false_value`` must be the same type. (Note this is different from a Python\n if-else statement.)\n\n `ifelse` \"short-circuits\" like a Python conditional: only one of ``true_value`` or ``false_value``\n will actually get computed.\n\n Note\n ----\n Since Workflows objects cannot be used in Python ``if`` statements (their actual\n values aren't known until they're computed), the `ifelse` function lets you express\n conditional logic in Workflows operations.\n\n However, `ifelse` should be a last resort for large blocks of logic: in most cases,\n you can write code that is more efficient and easier to read using functionality\n like ``filter``, ``map``, :ref:`empty Image/ImageCollection handling `,\n ``pick_bands(allow_missing=True)``, `.Dict.get`, etc.\n\n Parameters\n ----------\n condition: Bool\n The condition\n true_value:\n Value returned if ``condition`` is True. Must be the same type as ``false_value``\n false_value:\n Value returned if ``condition`` is False. Must be the same type as ``true_value``\n\n Returns\n -------\n result: same as ``true_value`` and ``false_value``\n ``true_value`` if ``condition`` is True, otherwise ``false_value``\n\n Example\n -------\n >>> import descarteslabs.workflows as wf\n >>> wf.ifelse(True, \"yep!\", \"nope\").inspect() # doctest: +SKIP\n \"yep!\"\n >>> wf.ifelse(False, \"yep!\", \"nope\").inspect() # doctest: +SKIP\n \"nope\"\n \"\"\"\n true_value = proxify(true_value)\n false_value = proxify(false_value)\n\n if type(true_value) is not type(false_value):\n raise TypeError(\n \"Both cases of `ifelse` must be the same type. \"\n \"Got type {} for the true case, and type {} for the false case.\".format(\n type(true_value).__name__, type(false_value).__name__\n )\n )\n\n first_guid = client.guid()\n delayed_true = client.function_graft(true_value, first_guid=first_guid)\n delayed_false = client.function_graft(false_value, first_guid=first_guid)\n\n return true_value._from_apply(\"wf.ifelse\", condition, delayed_true, delayed_false)\n","sub_path":"descarteslabs/workflows/types/conditional/ifelse.py","file_name":"ifelse.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"346723682","text":"def number_text(text):\t\n\n\twith open(text) as f_in:\n\t\tf1_2 = open(\"new_small.txt\", \"w\")\n\t\tcount = 1\n\t\tfor line in f_in:\n\t\t\tf1_2.write(str(count) + \" \" + line )\n\t\t\tcount += 1\n\nnumber_text(\"small.txt\")","sub_path":"number_text.py","file_name":"number_text.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"387558533","text":"class Production:\n def __init__(self, left, *right):\n self.left = left\n self.right = right\n self.check_valid()\n\n def check_valid(self):\n if not isinstance(self.left, str) or not all(isinstance(x, str) for x in self.right):\n raise ValueError(\n \"Invalid production. All symbols of the production should be of type string: {} -> {}\".format(self.left, self.right))\n\n def __str__(self):\n return \"{} -> {}\".format(self.left, \" \".join(self.right))\n\n def __eq__(self, other):\n if not isinstance(other, Production):\n return False\n return self.left == other.left and self.right == other.right\n\n def __hash__(self):\n return hash((self.left, tuple(self.right)))\n\n def __lt__(self, other):\n return (self.left, self.right) < (other.left, other.right)\n\n\nclass Context_Free_Grammar:\n def __init__(self, alphabet, non_terminals, productions, start_symbol):\n self.alphabet = alphabet\n self.non_terminals = non_terminals\n self.productions = productions\n self.start_symbol = start_symbol\n self.check_valid_grammar()\n\n self.production_map = dict()\n self.reverse_production_map = dict()\n for c in non_terminals:\n self.production_map[c] = set()\n for p in productions:\n self.production_map[p.left].add(p.right)\n s = set()\n if not p.right in self.reverse_production_map:\n self.reverse_production_map[p.right] = s\n else:\n s = self.reverse_production_map[p.right]\n s.add(p.left)\n\n def check_valid_grammar(self):\n if any(terminal in self.non_terminals for terminal in self.alphabet):\n raise ValueError(\"Terminals and non-terminals must be disjoint!\")\n if not self.start_symbol in self.non_terminals:\n raise ValueError(\"Start symbol must be part of the non-terminals\")\n atoms = set(self.non_terminals) | set(self.alphabet)\n for production in self.productions:\n if not production.left in atoms:\n raise ValueError(\n \"{} is not in the grammar\".format(production.left))\n for symbol in production.right:\n if not symbol in atoms:\n raise ValueError(\"{} is not in the grammar\".format(symbol))\n\n @staticmethod\n def parse(lines):\n lines = lines[::-1]\n if lines.pop().strip() != \"Grammar\":\n raise ValueError(\"Parsed grammar does not start with 'Grammar'.\")\n\n line = lines.pop()\n if not line.startswith(\"Nonterminals:\"):\n raise ValueError(\n \"Parsed grammar does not declare Nonterminals first.\")\n non_terminals = set(line.strip(\"Nonterminals:\").strip().split(\",\"))\n\n line = lines.pop()\n if not line.startswith(\"Alphabet:\"):\n raise ValueError(\n \"Parsed grammar does not declare Alphabet second.\")\n alphabet = set(line.strip(\"Alphabet:\").strip().split(\",\"))\n for alpha in alphabet:\n if len(alpha) != 1:\n raise ValueError(\n \"Alphabet has to be input as a comma separated list without spaces. Terminals may only be chars.\")\n\n line = lines.pop()\n if not line.startswith(\"Startsymbol:\"):\n raise ValueError(\n \"Parsed grammar does not declare start symbol third.\")\n start_symbol = line.strip(\"Startsymbol:\").strip()\n\n line = lines.pop()\n if not line.strip() == \"Productions:\":\n raise ValueError(\"Parsed grammar does not declare productions\")\n\n productions = set()\n line = lines.pop().strip()\n while line != \"END\":\n if not '->' in line:\n raise ValueError(\n \"Production {} does not contain '->'\".format(line))\n left, rights = line.split('->')\n left = left.strip()\n if \" \" in left:\n raise ValueError(\n \"Left-hand side must contain exactly one symbol.\")\n rights = rights.strip().split(\"|\")\n for right in rights:\n right = right.strip().split()\n right = (atom.strip()\n for atom in right if not atom.isspace())\n productions.add(Production(left, *right))\n if len(lines) > 0:\n line = lines.pop().strip()\n else:\n raise ValueError(\"Input was not terminated with END\")\n\n return Context_Free_Grammar(alphabet, non_terminals, productions, start_symbol)\n\n def get_productions_by_lhs(self, lhs):\n if lhs in self.production_map:\n return self.production_map[lhs]\n else:\n return set()\n\n def get_productions_by_rhs(self, *rhs):\n if rhs in self.reverse_production_map:\n return self.reverse_production_map[rhs]\n else:\n return set()\n\n def __str__(self):\n template = \"\\n\".join([\n \"Grammar\",\n \"Nonterminals: {}\",\n \"Alphabet: {}\",\n \"Startsymbol: {}\",\n \"Productions:{}\",\n \"END\"\n ])\n return template.format(\n \",\".join(sorted(self.non_terminals)),\n \",\".join(sorted(self.alphabet)), self.start_symbol,\n \"\\n\" + \"\\n\".join(sorted(map(str, self.productions))) if len(self.productions) > 0 else \"\")\n","sub_path":"exercise-07/angabe/Templates/Python/D/context_free_grammar.py","file_name":"context_free_grammar.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"47222502","text":"# coding=utf8\n\n'''\n run the tranform.\n'''\nimport sys\nfrom os.path import realpath, dirname\nfrom os.path import join as path_join\nsys.path.insert(0, realpath(path_join(dirname(__file__), '../')))\n\nfrom multiprocessing import Process\n\nimport happybase\nimport pymongo\n\nfrom models import HBaseClient\n\nfrom config import HBASE_HOST\nfrom config import MONGODB_HOST\nfrom config import MONGODB_PORT\nfrom config import MONGODB_NAME\n\nfrom parser.parser import ModelParser\n\nTABLE_DCT = {\n 'followers': '%(id)s',\n 'follow_relations': '%(user_id)s_%(follower_id)s',\n 'comments': '%(sm_user_id)s_%(status_id)s_%(id)s',\n 'reposts': '%(sm_user_id)s_%(retweeted_status_id)s_%(id)s',\n 'mentions': '%(sm_user_id)s_%(_id)s',\n 'mention_users': '%(sm_user_id)s_%(id)s',\n 'status': '%(user_id)s_%(id)s',\n}\n\n\nconnection = happybase.Connection(\n host=HBASE_HOST,\n)\nconnection.open()\n\ndef get_hbase_connection():\n ''' get a hbase conn instance '''\n return HBaseClient(HBASE_HOST)\n\n\nHBASE_CLIENT = HBaseClient(HBASE_HOST)\nMONGO_INSTANCE = pymongo.Connection(MONGODB_HOST, MONGODB_PORT)[MONGODB_NAME]\n\n\ndef init_tables():\n ''' init whole hbase tables. '''\n HBASE_CLIENT.init_all_tables()\n\n\ndef insert_data(table_name, row_format):\n ''' insert test data '''\n model_parser = ModelParser()\n table = connection.table(table_name)\n cursor = MONGO_INSTANCE[table_name].find().limit(10)\n for cur_item in cursor:\n table.put(\n row_format % cur_item,\n model_parser.deserialized(\n table_name,\n cur_item, \n )\n )\n\n\ndef insert_all_data():\n ''' insert whole data '''\n for cur_table, row_format in TABLE_DCT.iteritems():\n insert_data(cur_table, row_format)\n p = Process(target=insert_data, args=[cur_table, row_format])\n p.start()\n p.join()\n\nif __name__ == '__main__':\n init_tables()\n insert_all_data()\n","sub_path":"transform/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"455239421","text":"#coding=utf-8\nimport json\nfrom psutil import *\nfrom util import getHumanSize\nimport datetime\nimport web\n\nclass Sysinfo():\n def __init__(self):\n self.data=json.loads(web.data())\n\n def POST(self):\n action=self.data['action']\n try:\n res=Sysinfo.__dict__[action](self)\n return json.dumps(res)\n except:\n from traceback import format_exc\n\n return json.dumps({'rescode':404,'err':format_exc()})\n def getSysInfo(self):\n mem = virtual_memory()\n disk = disk_usage('/home')\n\n data = dict(\n rescode = 200,\n logical_cpu_num = cpu_count(),\n mem_total = getHumanSize(mem.total),\n mem_free = getHumanSize(mem.free),\n mem_percent = '%0.2f%%' % mem.percent,\n boot_time = datetime.datetime.fromtimestamp(boot_time()).strftime(\"%Y-%m-%d %H:%M:%S\"),\n cpu_num = cpu_count(logical = False),\n disk_total = getHumanSize(disk.total),\n disk_free = getHumanSize(disk.free),\n disk_percent = '%0.2f%%' % disk.percent\n )\n\n # disk_info=disk_partitions()\n # data['diskpart']=[]\n # for item in disk_info:\n # disk=disk_usage(item.mountpoint)\n # data['diskpart'].append(\n # dict(device=item.device,\n # mountpoint=item.mountpoint,\n # fstype=item.fstype,\n # opts=item.opts,\n # disk_total = getHumanSize(disk.total),\n # disk_free = getHumanSize(disk.free),\n # disk_percent = '%0.2f%%' % disk.percent,\n # )\n # )\n\n return data\n def TermOnlineTime(self):\n\n pass\n","sub_path":"backend_mgt/controllers/Sysinfo.py","file_name":"Sysinfo.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"202935525","text":"# Autor: Juan Sebastián Lozano Derbez\n# Se calcula el área y perímetro de un trapecio\n\ndef calcularArea(basemenor, basemayor, altura): #Se calcula el área\n area = (((basemayor + basemenor)*altura))/2\n\n return area\n\ndef calcularPerimetro(basemenor, basemayor, altura): #Se calcula el perímetro\n basetriangulo = (basemayor - basemenor)/2\n lado = (basetriangulo**2 + altura**2)**.5\n\n perimetro = basemenor + basemayor + lado*2\n\n return perimetro\n\n#Se reciben los valores de entrada y se imprime\ndef main():\n basemenor = int(input(\"Valor de la base menor: \"))\n basemayor = int(input(\"Valor de la base mayor: \"))\n altura = int(input(\"Valor de la altura: \"))\n\n area = calcularArea(basemenor, basemayor, altura)\n perimetro = calcularPerimetro(basemenor, basemayor, altura)\n\n print(\"El valor del area es: %.2f\" % area)\n print(\"El valor del perimetro es: %.2f\" % perimetro)\n\nmain()\n\n","sub_path":"trapecio.py","file_name":"trapecio.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"252973971","text":"import sys\nimport random\nimport argparse\nimport tensorflow as tf\nimport sentencepiece as spm\nimport tensorflow_hub as hub\nfrom annoy import AnnoyIndex\nfrom utils import MODULE_PATH, process_to_IDs_in_sparse_format\n\n\ndef main(arguments):\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('--verbose', dest='verbose',\n help=\"Verbose\", action='store_true')\n parser.add_argument('--num_neighbors', type=int,\n help='number of nearest neighbors to return')\n parser.add_argument('--search_k', type=int,\n help='runtime tradeoff between accuracy and speed')\n parser.add_argument('--path_to_text',\n help=\"path to original text file\")\n\n parser.set_defaults(\n verbose=True,\n num_neighbors=10,\n search_k=100\n )\n args = parser.parse_args(arguments)\n\n # Reduce logging output.\n if args.verbose:\n tf.logging.set_verbosity(tf.logging.DEBUG)\n else:\n tf.logging.set_verbosity(tf.logging.INFO)\n\n tf.logging.info('Loading unique strings.')\n unique_strings_path = args.path_to_text + '.embedded.pkl_unique_strings.csv'\n # load the unique lines\n with open(unique_strings_path) as f:\n unique_strings = [line.rstrip() for line in f]\n\n tf.logging.info('Lodaded {} unique strings'.format(len(unique_strings)))\n\n # Length of item vector that will be indexed\n nn_forest = AnnoyIndex(512)\n\n # Reload approximate nearest neighbor forest\n output_path = args.path_to_text + '.ann'\n nn_forest.load(output_path)\n\n tf.logging.info('Index forest rebuilt {}'.format(output_path))\n\n # Reload the embedding module\n module = hub.Module(MODULE_PATH, trainable=False)\n\n # Start the tensorflow session\n with tf.Session() as session:\n\n # Initialize the variables\n session.run([tf.global_variables_initializer(), tf.tables_initializer()])\n tf.logging.info('Interactive session is initialized...')\n\n # spm_path now contains a path to the SentencePiece\n # model stored inside the TF-Hub module\n spm_path = session.run(module(signature=\"spm_path\"))\n sp = spm.SentencePieceProcessor()\n sp.Load(spm_path)\n\n # build an input placeholder\n input_placeholder = tf.sparse_placeholder(tf.int64, shape=[None, None])\n\n # build an input / output from the placeholders\n embeddings = module(inputs=dict(\n values=input_placeholder.values,\n indices=input_placeholder.indices,\n dense_shape=input_placeholder.dense_shape\n )\n )\n\n # build a loop for interactive mode\n while True:\n # get user input\n user_input = [input('\\nQuery Text: ')]\n\n # process unencoded lines to values and IDs in sparse format\n values, indices, dense_shape = process_to_IDs_in_sparse_format(sp=sp,\n sentences=user_input)\n\n # run the session\n line_embeddings = session.run(\n embeddings,\n feed_dict={\n input_placeholder.values: values,\n input_placeholder.indices: indices,\n input_placeholder.dense_shape: dense_shape\n }\n )\n\n # extract the query vector of interest\n query_vector = line_embeddings[0]\n\n # get nearest neighbors\n (nns, distances) = nn_forest.get_nns_by_vector(\n query_vector,\n int(args.num_neighbors),\n search_k=1000,\n include_distances=True)\n\n for i,nn in enumerate(nns):\n tf.logging.info('{}, d: {}, {}'.format(i, round(distances[i], 3), unique_strings[nn]))\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n\n\n\n\n\n\n\n\n\n","sub_path":"interact_with_model.py","file_name":"interact_with_model.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"168034410","text":"from functions import *\r\nfrom tkinter import *\r\n\r\nroot=Tk()\r\nroot.wm_title(\"Truth And Dare\")\r\nroundNumber=0\r\nname=\" \"\r\nTorD=\"It's your truth or your dare\"\r\nroot.geometry(\"1200x800\")\r\nTruth=[\"Truth 1\",\"Truth 2\",\"Truth 3\",\"Truth 4\",\"Truth 5\",\"Truth 6\",\"Truth 7\",\"Truth 8\",\"Truth 9\",\"Truth 10\",\"Truth 11\",\"Truth 12\"]\r\nDare=[\"Dare 1\",\"Dare 2\",\"Dare 3\",\"Dare 4\",\"Dare 5\",\"Dare 6\",\"Dare 7\",\"Dare 8\",\"Dare 9\",\"Dare 10\",\"Dare 11\",\"Dare 12\"]\r\n\r\ndef addDare():\r\n addDarePopup = Tk()\r\n addDarePopup.wm_title(\"Add Player\")\r\n label = Label(addDarePopup, text=\"Enter Dare in the TextBox\").grid(row=0, column=0)\r\n namee = Entry(addDarePopup)\r\n namee.grid(row=1, column=0)\r\n add = Button(addDarePopup, text=\"ADD\", command=lambda: d(namee))\r\n add.grid(row=0, column=4)\r\n close = Button(addDarePopup, text=\"Close\", command=addDarePopup.destroy)\r\n close.grid(row=1, column=4)\r\n addDarePopup.mainloop()\r\n\r\ndef d(namee):\r\n Dare.append(namee.get())\r\n\r\ndef addTruth():\r\n addTruthPopup = Tk()\r\n addTruthPopup.wm_title(\"Add Player\")\r\n label = Label(addTruthPopup, text=\"Enter Truth in the TextBox\").grid(row=0, column=0)\r\n nameee = Entry(addTruthPopup)\r\n nameee.grid(row=1, column=0)\r\n add = Button(addTruthPopup, text=\"ADD\", command=lambda: t(nameee))\r\n add.grid(row=0, column=4)\r\n close = Button(addTruthPopup, text=\"Close\", command=addTruthPopup.destroy)\r\n close.grid(row=1, column=4)\r\n addTruthPopup.mainloop()\r\n\r\ndef t(nameee):\r\n Truth.append(nameee.get())\r\n\r\ndef dares():\r\n dLen=len(Dare)\r\n num=random.randint(0,dLen-1)\r\n truthOrDare.config(text=Dare[num])\r\n\r\ndef truths():\r\n tLen=len(Truth)\r\n num=random.randint(0,tLen-1)\r\n truthOrDare.config(text=Truth[num])\r\n\r\ndef show():\r\n #Y=500\r\n #for i in range(playerCount+1):\r\n # Y = Y + 20\r\n # Label(root, text=\" \", font='Helvetica 13').place(width=100, x=100, y=Y)\r\n # Label(root, text=\" \", font='Helvetica 13').place(width=100, x=230, y=Y)\r\n Y = 450\r\n shw = 'SELECT Name, Score From players;'\r\n cursor.execute(shw)\r\n result=cursor.fetchall()\r\n for row in result:\r\n Y = Y + 20\r\n Label(root,text=row[0],font='Helvetica 11').place(width=100,x=100,y=Y)\r\n Label(root, text=row[1], font='Helvetica 11').place(width=100, x=230, y=Y)\r\n \r\ndef donee():\r\n don='UPDATE players SET Score=Score+1 Where Name=\"%s\";' % (name)\r\n cursor.execute(don)\r\n plG()\r\n\r\ndef plG():\r\n global roundNumber\r\n global name\r\n name=playerGenerator()\r\n playerN.config(text=name)\r\n roundNumber=roundNumber+1\r\n count.config(text=roundNumber)\r\n show()\r\n\r\n#Game Console:\r\n\r\n#Player Label\r\npl=Label(root,text=\"It's Your Turn ;)\",font='Helvetica 18')\r\npl.place(width=200,x=250,y=50)\r\n\r\n#Player Name Label\r\nplayerN=Label(root,text=\"Player's Name\",font='Helvetica 18 bold')\r\nplayerN.place(width=200,x=250,y=100)\r\n\r\n#TruthOrDare Label\r\ntruthOrDare=Label(root,text=TorD,font='Helvetica 18')\r\ntruthOrDare.place(width=300,x=200,y=175)\r\n\r\n#Truth Button\r\ntruth=Button(root,text=\"Truth\",command=lambda: truths())\r\ntruth.place(width=200,height=60,x=125,y=250)\r\n\r\n#Dare Button\r\ndare=Button(root,text=\"Dare\",command=lambda: dares())\r\ndare.place(width=200,height=60,x=400,y=250)\r\n\r\n#Forfeit Button\r\nforfeit=Button(root,text=\"Forfeit\",font=\"15\",command=lambda:plG())\r\nforfeit.place(width=200,height=60,x=125,y=350)\r\n\r\n#Done Button\r\nforfeit=Button(root,text=\"Done\",font=\"15\",command=lambda:donee())\r\nforfeit.place(width=200,height=60,x=400,y=350)\r\n\r\n\r\n#ScoreBoard :\r\n\r\n#Score Label\r\nscore=Label(root,text=\"Score-\",font='Helvetica 14')\r\nscore.place(width=200,x=0,y=450)\r\n\r\n\r\n#Side Console:\r\n\r\n#Round Label\r\nround=Label(root,text=\"Round\",font='Helvetica 15')\r\nround.place(width=100,x=900,y=50)\r\n\r\n#Round Count Label\r\ncount=Label(root,text=roundNumber,font='Helvetica 15 bold')\r\ncount.place(width=100,x=1000,y=50)\r\n\r\n#AddDare Button\r\naddDaree=Button(root,text=\"Add Dare\",command=lambda: addDare())\r\naddDaree.place(width=100,height=60,x=800,y=200)\r\n\r\n#AddTruth Button\r\naddTruthh=Button(root,text=\"Add Truth\",command=lambda: addTruth())\r\naddTruthh.place(width=100,height=60,x=1000,y=200)\r\n\r\n#AddPlayer Button\r\naddPlayer=Button(root,text=\"Add Player\",command=lambda:addPlayers())\r\naddPlayer.place(width=100,height=60,x=800,y=350)\r\n\r\n#DeletePlayer Button\r\ndeletePlayer=Button(root,text=\"Delete Player\",command=lambda:deletePlayers())\r\ndeletePlayer.place(width=100,height=60,x=1000,y=350)\r\n\r\n#NewGame Button\r\n#newGame=Button(root,text=\"New Game\")\r\n#newGame.place(width=100,height=60,x=800,y=500)\r\n\r\n#Close Button\r\ncloseGame=Button(root,text=\"Close\",command=root.destroy)\r\ncloseGame.place(width=200,height=60,x=850,y=500)\r\n\r\nroot.mainloop()\r\n","sub_path":"Python-TDS/newGame.py","file_name":"newGame.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"93630669","text":"import logging\nimport azure.functions as func\nfrom swnamer import NameGenerator\n\ndef main(request: func.HttpRequest) -> func.HttpResponse:\n logging.info('Python SWNAMER function started...')\n\n return_name = None\n sw_generator = NameGenerator(lowercase=False, separator=' ', use_characters=False)\n\n user_name = request.params.get('web_user_name')\n if not user_name:\n try:\n req_body = request.get_json()\n except ValueError:\n return_name = sw_generator.generate()\n pass\n else:\n user_name = req_body.get('web_user_name')\n return_name = sw_generator.generate()\n\n if user_name:\n return_name = user_name + ' ' + sw_generator.generate()\n return func.HttpResponse(return_name, status_code=200)\n else:\n return func.HttpResponse(\n 'Your Star Wars name is ' + return_name + ' was returned, but if you supply \\\n a name, your SW name can be more personalized.',\n status_code=200\n )\n","sub_path":"Star Wars Namer II/star_wars.py","file_name":"star_wars.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"378295682","text":"import matplotlib.pyplot as plt\nimport networkx as nx\nfrom functions import *\n\n# We load Zakary's Karate Club Graph\nG = nx.karate_club_graph()\nB = nx.adjacency_matrix(G).toarray()\n\n# For reproducibility\nseed(42)\n\nplot = True\nn = 500\n\n# We compute the first and second order centrality for the graph we loaded\neps, m, s = second_order_centrality(B, n)\n\ncolors_m = [l[-1] for l in m]\ncolors_s = [l[-1] for l in s]\n\n#nx.draw_networkx(G, node_color=colors_m, alpha=0.5, cmap=plt.get_cmap('bwr'))\nnx.draw_networkx(G, node_color=colors_s, alpha=0.5, cmap=plt.get_cmap('bwr'))\n\n\nif plot:\n x = [i for i in range(n-2)]\n\n plt.subplots(nrows=5, ncols=2, sharex=True, figsize=(6, 6))\n\n print('Plotting')\n\n for i in range(10):\n ax = plt.subplot(5, 2, i + 1)\n ax.yaxis.tick_right()\n ax.title.set_text('Centralité de second ordre du noeud {}'.format(i))\n ax.plot(x, s[i][:n - 2])\n\n plt.tight_layout()\n plt.show()\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"545421331","text":"from WMCore.Configuration import Configuration\nconfig = Configuration()\n\nconfig.section_('General')\nconfig.General.requestName = 'RunB'\nconfig.General.workArea = '2018v04'\n\nconfig.section_('JobType')\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'miniAOD_RunB.py'\nconfig.JobType.sendExternalFolder = True\nconfig.section_('Data')\nconfig.Data.inputDataset = '/MET/Run2018B-17Sep2018-v1/MINIAOD'\nconfig.Data.inputDBS = 'global'\n#config.Data.splitting = 'Automatic'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 10\nconfig.Data.lumiMask = '/afs/cern.ch/work/a/aspiezia/Ntuplizer/2018/CMSSW_10_2_10/src/BSMFramework/BSM3G_TNT_Maker/data/JSON/Cert_314472-325175_13TeV_17SeptEarlyReReco2018ABC_PromptEraD_Collisions18_JSON.txt'\nconfig.Data.outLFNDirBase = '/store/user/aspiezia/'\nconfig.Data.allowNonValidInputDataset = True\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_CN_Beijing'\n\n","sub_path":"BSM3G_TNT_Maker/python/DATA2018/crab_RunB_cfg.py","file_name":"crab_RunB_cfg.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"305872070","text":"def prime_number(n):\n if n==1:\n return False\n if n==2:\n return True\n else:\n for i in range(2,n-1):\n if n%i == 0:\n return False\n else:\n return True\n \nplist = []\nfor n in range(1,100):\n if prime_number(n):\n plist.append(n)\n\nprint(plist)\n","sub_path":"CT_python/HW06/lab01.py","file_name":"lab01.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"400944308","text":"from random import choice\n\n\nbinary = [0, 1]\nfour_bit_binary = []\n\nfor bit1 in binary:\n for bit2 in binary:\n for bit3 in binary:\n for bit4 in binary:\n four_bit_binary.append([bit1, bit2, bit3, bit4])\n\n# for bin_ in four_bit_binary:\n# print(bin_)\n\ndef dec_to_bin(dec, n_bits=8):\n bit_list = []\n x = dec\n\n for _ in range(n_bits):\n bit = x % 2\n bit_list.append(bit)\n x //= 2\n\n return bit_list[::-1]\n\n# print(dec_to_bin(43, n_bits=8))\n\n\ndef get_binary(n_bits=8):\n bins_d = dict()\n\n for dec in range(2**n_bits):\n bins_d[dec] = dec_to_bin(dec, n_bits)\n # print(f'{dec}: {bins_d[dec]}')\n return bins_d\n\n# for dec, bin_ in get_binary(n_bits=8).items():\n# print(f'{dec}: {bin_}')\n\n\n\ndef binomial_distr(n_trials=8):\n binomial_dict = dict()\n\n bin_dict = get_binary(n_bits=n_trials)\n\n for _, bin_list in bin_dict.items():\n sum_bits = sum(bin_list)\n if sum_bits not in binomial_dict:\n binomial_dict[sum_bits] = 0\n binomial_dict[sum_bits] += 1\n\n return binomial_dict\n\nd = binomial_distr(n_trials=12)\n\n# for k, cnt in d.items():\n# print(f'{k}: {cnt}')\n\n'''\nWhat is the probability of 5 heads in 12 coin flips of a fair coin?\nn = 12\np = 0.5\n'''\n# print(d[5] / sum(d.values()))\n\n# for k, cnt in d.items():\n# print(f'{k}: {round(cnt / sum(d.values()), 5)}')\n\n\n# n = 12\n# k = 9\n# p = 0.5\n\n# # print(d[9] / sum(d.values()))\n\n# accum = 0.0\n# for k in range(0, 4+1):\n# accum += d[k] / sum(d.values())\n# print(accum)\n\n\n\ndef get_bit():\n return choice([0,1])\n\ndef generate_n_bits(n=8):\n return [get_bit() for _ in range(n)]\n \n # lst = []\n # for _ in range(n):\n # lst.append(get_bit())\n # return lst\n\n# print(generate_n_bits(n=8))\n\n\ndef binary_sampling_dict(num_bits=8, num_samples=1000):\n d = dict()\n\n for _ in range(num_samples):\n binary = generate_n_bits(num_bits)\n num_successes = sum(binary)\n\n if num_successes not in d:\n d[num_successes] = 1\n else:\n d[num_successes] += 1\n \n return d\n\nd = binary_sampling_dict(num_bits=8, num_samples=1000)\n\nfor k, cnt in sorted(d.items()):\n print(f'{k}: {cnt}')","sub_path":"src/stats/06_discrete_distributions/binomial.py","file_name":"binomial.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"185171607","text":"# a simple implementation without unify-by-rank\nclass UnifyFind:\n def __init__(self):\n self.parent = dict()\n\n def unify(self, *arg):\n #assert len(arg) >= 2\n\n for x in arg:\n self._ensure(x)\n\n rep, *rest = arg\n frep = self.find(rep)\n for x in rest:\n self.parent[self.find(x)] = frep\n\n #def unify(self, x, y):\n #self._ensure(x)\n #self._ensure(y)\n #self.parent[self.find(x)] = self.find(y)\n\n def find(self, x):\n p = self.parent[x]\n # compress paths\n if p != x:\n p = self.parent[x] = self.find(p)\n\n return p\n\n def _ensure(self, x):\n if x not in self.parent:\n self.parent[x] = x\n\n def sets(self):\n res = dict()\n\n for x in self.parent:\n p = self.find(x)\n if p not in res:\n res[p] = set()\n res[p].add(x)\n\n for p in res:\n yield res[p]\n\nclass zerodict(dict):\n def __init__(self, *arg, **kwarg):\n super().__init__(*arg, **kwarg)\n def __missing__(self, key):\n return 0\n\nif __name__ == \"__main__\":\n uf = UnifyFind()\n uf.unify(1, 2)\n uf.unify(1, 3)\n uf.unify(2, 4)\n uf.unify(5, 7)\n uf.unify(6, 8)\n print(*uf.sets())\n","sub_path":"jao/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"197959819","text":"import chainer\nfrom chainer import links as L\nfrom chainer import initializers\n\n\nclass ResNet101(chainer.Chain):\n def __init__(self, n_out, pretrained_model='auto', layers=None):\n super(ResNet101, self).__init__()\n init_param = initializers.HeNormal()\n self.n_out = n_out\n if layers:\n self.layers = layers\n else:\n self.layers = ['pool5']\n\n with self.init_scope():\n self.base = L.ResNet101Layers(pretrained_model=pretrained_model)\n self.fc = L.Linear(None, n_out, initialW=init_param)\n\n def __call__(self, x):\n h = self.base(x, layers=self.layers)\n y = self.fc(h.pop(self.layers[-1]))\n if h:\n return y, h\n return y\n\n\nclass ResNet152(chainer.Chain):\n def __init__(self, n_out, init_param=None, pretrained_model='auto'):\n super(ResNet152, self).__init__()\n self.n_out = n_out\n\n with self.init_scope():\n self.base = L.ResNet152Layers(pretrained_model=pretrained_model)\n self.fc = L.Linear(None, n_out, initialW=init_param)\n\n def __call__(self, x):\n h = self.base(x, layers=['pool5'])['pool5']\n y = self.fc(h)\n return y\n","sub_path":"models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"583630513","text":"\"\"\"Stream type classes for tap-dynamodb.\"\"\"\n\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Union, List, Iterable\n\nfrom singer_sdk import typing as th\n\nfrom tap_dynamodb.client import DynamoDBStream\n\n\nclass DynamicStream(DynamoDBStream):\n \"\"\"Define dynamic stream.\"\"\"\n\n def __init__(self,\n tap,\n name,\n primary_keys=None,\n replication_key=None,\n except_keys=None,\n records_path=None,\n schema=None,\n client=None,\n orig_projection=None,\n ):\n super().__init__(tap=tap, name=tap.name, schema=schema)\n if primary_keys is None:\n primary_keys = []\n\n self.name = name\n self.primary_keys = primary_keys\n self.replication_key = replication_key\n self.except_keys = except_keys\n self.records_path = records_path\n self.client = client\n self.orig_projection = orig_projection\n","sub_path":"tap_dynamodb/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68204607","text":"from openmdao.api import Problem, Group, IndepVarComp, view_model\n\nfrom six import iteritems\nfrom numpy.testing import assert_almost_equal\nimport numpy as np\nfrom openaerostruct.geometry.utils import generate_mesh\n\n\ndef view_mat(mat):\n \"\"\" Helper function used to visually examine matrices. \"\"\"\n import matplotlib.pyplot as plt\n if len(mat.shape) > 2:\n mat = np.sum(mat, axis=2)\n im = plt.imshow(mat.real, interpolation='none')\n plt.colorbar(im, orientation='horizontal')\n plt.show()\n\ndef run_test(obj, comp, decimal=3, complex_flag=False):\n prob = Problem()\n prob.model.add_subsystem('comp', comp)\n prob.setup(force_alloc_complex=complex_flag)\n\n prob.run_model()\n check = prob.check_partials(compact_print=True)\n for key, subjac in iteritems(check[list(check.keys())[0]]):\n if subjac['magnitude'].fd > 1e-6:\n assert_almost_equal(\n subjac['rel error'].forward, 0., decimal=decimal, err_msg='deriv of %s wrt %s' % key)\n assert_almost_equal(\n subjac['rel error'].reverse, 0., decimal=decimal, err_msg='deriv of %s wrt %s' % key)\n\ndef get_default_surfaces():\n # Create a dictionary to store options about the mesh\n mesh_dict = {'num_y' : 7,\n 'num_x' : 2,\n 'wing_type' : 'CRM',\n 'symmetry' : True,\n 'num_twist_cp' : 5}\n\n # Generate the aerodynamic mesh based on the previous dictionary\n mesh, twist_cp = generate_mesh(mesh_dict)\n\n wing_dict = {'name' : 'wing',\n 'num_y' : 4,\n 'num_x' : 2,\n 'symmetry' : True,\n 'S_ref_type' : 'wetted',\n 'CL0' : 0.1,\n 'CD0' : 0.1,\n 'mesh' : mesh,\n\n # Airfoil properties for viscous drag calculation\n 'k_lam' : 0.05, # percentage of chord with laminar\n # flow, used for viscous drag\n 't_over_c' : 0.15, # thickness over chord ratio (NACA0015)\n 'c_max_t' : .303, # chordwise location of maximum (NACA0015)\n # thickness\n 'with_viscous' : True, # if true, compute viscous drag\n 'fem_model_type' : 'tube',\n\n # Structural values are based on aluminum 7075\n 'E' : 70.e9, # [Pa] Young's modulus of the spar\n 'G' : 30.e9, # [Pa] shear modulus of the spar\n 'yield' : 500.e6 / 2.5, # [Pa] yield stress divided by 2.5 for limiting case\n 'mrho' : 3.e3, # [kg/m^3] material density\n 'fem_origin' : 0.35, # normalized chordwise location of the spar\n 't_over_c' : 0.15, # maximum airfoil thickness\n 'wing_weight_ratio' : 2.,\n\n }\n\n # Create a dictionary to store options about the mesh\n mesh_dict = {'num_y' : 5,\n 'num_x' : 3,\n 'wing_type' : 'rect',\n 'symmetry' : False}\n\n # Generate the aerodynamic mesh based on the previous dictionary\n mesh = generate_mesh(mesh_dict)\n\n tail_dict = {'name' : 'tail',\n 'num_y' : 5,\n 'num_x' : 3,\n 'symmetry' : False,\n 'mesh' : mesh}\n\n surfaces = [wing_dict, tail_dict]\n\n return surfaces\n","sub_path":"openaerostruct/utils/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"409459651","text":"#!/usr/bin/env python3\n\n\n# For command line usage, include the token and chat ids in advance in the script.\n# If you want to use only the functions, there's no need to include this.\n\"\"\"\ntelegram_token = \"\"\ntelegram_chat_ids = [\"\"]\n\"\"\"\n\n# For command line usage, include the token and chat ids in the INI file.\n# If you want to use only the functions, there's no need to include this.\n# The file format has to be\n#\n# [Telegram]\n# token = ABCDEF\n# chat_ids = 1234567,2345678\n# \n\"\"\"\nimport os\nimport configparser\n_SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\nconfig_ini_path = os.path.join(_SCRIPT_DIR, 'telegram_key.ini')\n\"\"\"\n\ntry:\n from PIL import Image\nexcept ImportError:\n # backward compatibility for the ones who don't need sending numpy photos\n pass\n\nimport requests\nimport io\nimport argparse\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"Send Telegram message\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--title\", help=\"Title\")\n parser.add_argument(\"--body\", help=\"Body\", required=True)\n return parser\n\n\ndef send_text(telegram_token, chat_id, text, parse_mode=None):\n telegram_request_url = \"https://api.telegram.org/bot{0}/sendMessage\".format(telegram_token)\n return requests.post(telegram_request_url, data={\n 'chat_id': chat_id,\n 'text': text,\n 'parse_mode': parse_mode\n })\n\ndef send_text_with_title(telegram_token, chat_id, title, body):\n if title:\n text = '' + title + '\\n\\n' + body\n tg_request = send_text(telegram_token, chat_id, text, parse_mode = 'HTML')\n if not tg_request.ok:\n # If failed, try send normal text instead of HTML parsing\n text = title + '\\n\\n' + body\n tg_request = send_text(telegram_token, chat_id, text, parse_mode = None)\n else:\n text = body\n tg_request = send_text(telegram_token, chat_id, text, parse_mode = None)\n\n return tg_request\n\n\ndef _send_photo_bytes(telegram_token, chat_id, bytes_io, caption=None):\n \"\"\"Send photo in open() or io.BytesIO form.\n \"\"\"\n url = \"https://api.telegram.org/bot{}/sendPhoto\".format(telegram_token);\n files = {'photo': bytes_io}\n data = {'chat_id' : chat_id}\n if caption is not None:\n data['caption'] = caption\n r= requests.post(url, files=files, data=data)\n return r\n\n\ndef send_photo(telegram_token, chat_id, img_path, caption=None):\n photo = open(img_path, 'rb')\n return _send_photo_bytes(telegram_token, chat_id, photo, caption)\n\ndef send_numpy_photo(telegram_token, chat_id, numpy_photo, caption=None):\n image = Image.fromarray(numpy_photo)\n photo = io.BytesIO()\n image.save(photo, format='jpeg')\n photo.seek(0) # to start reading from the beginning. (After writing, the cursor is at the end)\n photo.name = 'img.jpg'\n return _send_photo_bytes(telegram_token, chat_id, photo, caption)\n\ndef send_remote_photo(telegram_token, chat_id, img_url, caption):\n remote_image = requests.get(img_url)\n photo = io.BytesIO(remote_image.content)\n photo.name = 'img.png'\n return _send_photo_bytes(telegram_token, chat_id, photo, caption)\n\n\ndef send_matplotlib_fig(telegram_token, chat_id, fig, caption=None):\n photo = io.BytesIO()\n fig.savefig(photo, format='png')\n photo.seek(0) # to start reading from the beginning. (After writing, the cursor is at the end)\n photo.name = 'img.png'\n return _send_photo_bytes(telegram_token, chat_id, photo, caption)\n\ndef _send_gif_bytes(telegram_token, chat_id, bytes_io, caption=None):\n \"\"\"Send GIF in open() or io.BytesIO form.\n \"\"\"\n url = \"https://api.telegram.org/bot{}/sendAnimation\".format(telegram_token);\n files = {'animation': bytes_io}\n data = {'chat_id' : chat_id}\n if caption is not None:\n data['caption'] = caption\n\n r= requests.post(url, files=files, data=data)\n return r\n\ndef send_numpy_video_as_gif(telegram_token, chat_id, video, caption=None, optimize=True, duration=100, loop=0 ):\n # T, H, W, C = video.shape\n gif_frames = []\n for gif_frame in video:\n gif_frames.append(Image.fromarray(gif_frame))\n\n gif_bytes = io.BytesIO()\n gif_frames[0].save(gif_bytes, format='gif', save_all=True, append_images=gif_frames[1:], optimize=optimize, duration=duration, loop=loop) \n gif_bytes.seek(0) # to start reading from the beginning. (After writing, the cursor is at the end)\n gif_bytes.name = 'img.gif'\n\n return _send_gif_bytes(telegram_token, chat_id, gif_bytes, caption)\n\ndef send_document(telegram_token, chat_id, file_path):\n file_to_send = open(file_path, 'rb')\n url = \"https://api.telegram.org/bot{}/sendDocument\".format(telegram_token);\n files = {'document': file_to_send}\n data = {'chat_id': chat_id}\n r= requests.post(url, files=files, data=data)\n return r\n\nif __name__ == '__main__':\n parser = get_parser()\n args = parser.parse_args()\n\n if 'telegram_token' in globals().keys():\n for chat_id in telegram_chat_ids:\n print(send_text_with_title(telegram_token, chat_id, args.title, args.body))\n elif 'config_ini_path' in globals().keys():\n config = configparser.ConfigParser()\n config.read(config_ini_path)\n chat_ids = config['Telegram']['chat_ids'].split(',')\n for chat_id in chat_ids:\n print(send_text_with_title(config['Telegram']['token'], chat_id, args.title, args.body))\n else:\n raise ValueError('None of the Telegram token is specified but trying to send a message. Edit this file.')\n","sub_path":"experiment_utils/telegram_post.py","file_name":"telegram_post.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"433505046","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nwith open('requirements.txt', 'r') as f:\n install_requires = [i.strip() for i in f.readlines()]\n\n\nsetup(name='msgQ',\n version='0.0.1',\n description='System wide message queue',\n author='hbc',\n author_email='bcxxxxxx@gmail.com',\n packages=[\n 'msgQ',\n 'msgQ.server',\n 'msgQ.scripts',\n 'msgQ.tests',\n ],\n entry_points={\n 'console_scripts': [\n 'msgq-guardd=msgQ.scripts.guard:main',\n 'msgq-guard=msgQ.scripts.guard:serve',\n ]\n },\n install_requires=install_requires)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"571765341","text":"\"\"\"\nThis function is a solution to the 6kyu Kata on codewars.com: https://www.codewars.com/kata/multiples-of-3-or-5/train/python \n\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n\nFinish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.\n\nNote: If the number is a multiple of both 3 and 5, only count it once.\n\"\"\"\ndef solution(number):\n # Plan = loop from 1 to the number, and if i is divisble by 3 or 5, add it \n # to sum_of_multiples\n sum_of_multiples = 0\n \n for i in range(1, number):\n if i%3==0 or i%5==0:\n sum_of_multiples = sum_of_multiples + i\n \n return sum_of_multiples\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"442150487","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom jnpr.junos import Device\nfrom lxml import etree\nimport xmltodict\n\nfrom my_devices import juniper2 as juniper_mx\n\n\nif __name__ == \"__main__\":\n a_device = Device(**juniper_mx)\n a_device.open()\n\n xml_out = a_device.rpc.get_lldp_neighbors_information()\n my_dict = xmltodict.parse(etree.tostring(xml_out, encoding='unicode'))\n\n lldp_list = my_dict['lldp-neighbors-information']['lldp-neighbor-information']\n for lldp in lldp_list:\n local_port = base_dict['lldp-local-port-id']\n remote_port = base_dict['lldp-remote-port-id']\n remote_system_name = base_dict['lldp-remote-system-name']\n\n print()\n print(\"Local Port: {}\".format(local_port))\n print(\"Remote Port: {}\".format(remote_port))\n print(\"Remote System: {}\".format(remote_system_name))\n print()\n","sub_path":"pyez3.py","file_name":"pyez3.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232550851","text":"\"\"\"\n Date: 03/01/2015\n Author: Martin Lellep\n What: Data evaluation by plotting of problem3-turb\n data.\n\"\"\"\n\nimport sys\nsys.path.insert(0,\"../../..\")\n\nimport wrapperModules.files as f\nfrom wrapperModules.plotting import ProblemProfilePlot as PPP\n\npathOf = \"../../data/problem3_turb/Res{nr}k/problem3__turb_Res{nr}k_nout00{n}_lowRes_nsym.output\"\npathPr = \"../../data/problem3_turb/Res{nr}k/r-uth-dr_uth.debug\"\n\nfor res in [1,5,10,20,]:\n labels=[]\n ofs=[]\n for n in [5,4,3,2,1,0]:\n of = f.OutputFile(pathOf.format(nr=res,n=n))\n ofs.append(of)\n labels.append(r\"$Re_s={0}k,n={1}$\".format(res,n))\n\n prof = f.R_Uth_Dr_Uth(path=pathPr.format(nr=res))\n\n rData = prof.data[\"r\"]\n uthData = prof.data[\"uth\"]\n druthData = prof.data[\"dr_uth\"]\n\n plot = PPP(outputFilePairs=(ofs,labels),profileData=(rData,[uthData],[druthData],[r\"$Re_s={res}k\".format(res=res)]),\n title=r\"Profile \\& eigenvalue (turb): $Re_s={res}k ~ \\& ~ n\\in ( 0,\\dots,5 ) $\".format(res=res))\n plot.getAxis()[0].legend(loc=3)\n plot.save(\"../../output/max_eigenvalue/problem3_turb/04062015_cookmans_turb_Res{res}k.pdf\".format(res=res))\n","sub_path":"assistance/code/max_eigenvalue/03012015_cookmans_evaluateProblem3turb.py","file_name":"03012015_cookmans_evaluateProblem3turb.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"449333722","text":"import requests\nfrom flask import Flask, request\nfrom pymessenger.bot import Bot\n\n\napp = Flask(__name__)\nACCESS_TOKEN = \"MY TOKEN\"\nVERIFY_TOKEN = \"hello\"\nbot = Bot(ACCESS_TOKEN)\n\n\n# get_request()\n# @parameters: None\n# @return: verified fb token\n# Called whenever it receives a get request and verifies its a valid fb token\n\n\n@app.route(\"/\", methods=['GET'])\ndef get_request():\n token_sent = request.args.get(\"hub.verify_token\")\n return verify_fb_token(token_sent)\n\n\n# post_request()\n# @parameters: None\n# @return: \"ok\", 200\n# Handles a post request when received\n\n\n@app.route(\"/\", methods=['POST'])\ndef post_request():\n output = request.get_json()\n print(output)\n for event in output['entry']:\n messaging = event['messaging']\n for message in messaging:\n if message.get('message'):\n recipient_id = message['sender']['id']\n\n # Determining if its text or attachment\n if message['message'].get('text'):\n response_sent_text = get_message(message['message'].get('text'))\n send_message(recipient_id, response_sent_text)\n if message['message'].get('attachments'):\n response_sent_nontext = \"Can't reply to attachments yet... :(\"\n send_message(recipient_id, response_sent_nontext)\n return \"ok\", 200\n\n\n# verify_fb_token(token_sent)\n# @parameters: token\n# @return: success/failure\n# Verifies the token that fb sent\n\n\ndef verify_fb_token(token_sent):\n if token_sent == VERIFY_TOKEN:\n return request.args.get(\"hub.challenge\")\n return \"Invalid token\"\n\n\ndef representsInt(x):\n try:\n int(x)\n return True\n except ValueError:\n return False\n\n\n# get_message(message)\n# @parameters: message\n# @return: result\n# Replies to the message sent by parsing it and returning its translation\n\n\ndef validStop(stop):\n jsonFile = requests.get(\n f\"https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid={stop}&format=json\"\n )\n\n if jsonFile.json()['errorcode'] != \"0\":\n return False\n\n return True\n\n\ndef setKeyword(message):\n stopNumber = -1\n\n splice = message.split()\n for index in range(len(splice)):\n if representsInt(splice[index]):\n if validStop(splice[index]):\n stopNumber = int(splice[index])\n else:\n return f\"{splice[index]} isn't a valid stop \"\n\n if stopNumber == -1:\n return \"I couldn't find a stop number.\"\n\n word = splice[len(splice) - 1]\n\n return f\"Stop {stopNumber} is now set to the word {word}\"\n\n\ndef dueTime(data):\n finalMessage = \"\"\n\n for result in data['results']:\n if result['duetime'] == \"Due\":\n finalMessage += f\"{result['route']} -> {result['destination']} is due now\\n\"\n elif result['duetime'] == \"1\":\n finalMessage += f\"{result['route']} -> {result['destination']} is due in {result['duetime']} minute\\n\"\n else:\n finalMessage += f\"{result['route']} -> {result['destination']} is due in {result['duetime']} minutes\\n\"\n\n return finalMessage\n\n\ndef getData(stop):\n jsonFile = requests.get(\n f\"https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid={stop}&format=json\"\n )\n return jsonFile.json()\n\n\ndef get_message(message):\n global data\n\n if message.casefold().startswith('set '):\n return setKeyword(message)\n\n if representsInt(message):\n stop = int(message)\n else:\n return \"Please enter a stop number.\"\n\n if validStop(stop):\n data = getData(stop)\n if data['errorcode'] != \"0\":\n return \"Please enter a valid stop number\"\n else:\n return f\"{stop} is not a valid stop\"\n\n return dueTime(data)\n\n\n\n\n# send_message(recipient_id, response)\n# @parameters: recipient_id, response\n# @return: success\n# Sends the message to the recipient of the message\n\n\ndef send_message(recipient_id, response):\n bot.send_text_message(recipient_id, response)\n return \"success\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"489679663","text":"import numpy as np\nimport matplotlib.pyplot as mp\nimport datetime as dt\n\n\ndef dmy2ymd(dmy):\n dmy = str(dmy, encoding='utf-8')\n time = dt.datetime.strptime(dmy, '%d-%m-%Y').date()\n t = time.strftime('%Y-%m-%d')\n return t\n\n\ndates, opening_prices, highest_prices, \\\nlowest_prices, closing_prices, volumes = \\\n np.loadtxt('./da_data/aapl.csv',\n delimiter=',', usecols=(1, 3, 4, 5, 6, 7),\n unpack=True, dtype='M8[D],f8,f8,f8,f8,f8',\n converters={1: dmy2ymd})\n\n# 绘制收盘价折线图\nmp.figure('AAPL', facecolor='lightgray')\nmp.title('AAPL', fontsize=18)\nmp.xlabel('Date', fontsize=14)\nmp.ylabel('Price', fontsize=14)\nmp.grid(linestyle=':')\n# 设置刻度定位器\nimport matplotlib.dates as md\n\nax = mp.gca()\n# 每周一为主刻度\nax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))\n# 每天一个次刻度\nax.xaxis.set_minor_locator(md.DayLocator())\n# 设置主刻度文本格式\nax.xaxis.set_major_formatter(md.DateFormatter('%Y/%m/%d'))\ndates = dates.astype(md.datetime.datetime)\nmp.plot(dates, closing_prices, color='dodgerblue',\n label='Closing Price', linewidth=2, linestyle='--')\n\n# 评估波动性\nmin_val = np.min(lowest_prices)\nmax_val = np.max(highest_prices)\nprint(min_val, '-', max_val)\n\n# 最高价与最低价的日期,arg+.. 相当于获取一个点对象\nmin_ind = np.argmin(lowest_prices)\nmax_ind = np.argmax(highest_prices)\nprint('min:', dates[min_ind])\nprint(('max:', dates[max_ind]))\n\n# maximum minimum\na=np.arange(1,10).reshape(3,3)\nb=np.arange(1,10)[::-1].reshape(3,3)\nprint(a,b)\nprint(np.maximum(a,b)) # 相比较保留较大的数\nprint(np.minimum(a,b))\n\n","sub_path":"day04_func/04最值.py","file_name":"04最值.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42768123","text":"from __future__ import absolute_import\nimport sys\n\nfrom rpython.rlib.rarithmetic import intmask\n\nfrom topaz.module import ModuleDef\nfrom topaz.objects.classobject import W_ClassObject\n\n\nclass Topaz(object):\n moduledef = ModuleDef(\"Topaz\")\n\n @moduledef.setup_module\n def setup_module(space, w_mod):\n space.set_const(w_mod, \"FIXNUM_MAX\", space.newint(sys.maxint))\n\n @moduledef.function(\"intmask\")\n def method_intmask(self, space, w_int):\n if space.is_kind_of(w_int, space.w_fixnum):\n return w_int\n elif space.is_kind_of(w_int, space.w_bignum):\n bigint = space.bigint_w(w_int)\n return space.newint(intmask(bigint.uintmask()))\n\n @moduledef.function(\"convert_type\", method=\"symbol\")\n def method_convert_type(self, space, w_obj, w_type, method):\n if not isinstance(w_type, W_ClassObject):\n raise space.error(space.w_TypeError, \"type argument must be a class\")\n return space.convert_type(w_obj, w_type, method)\n\n @moduledef.function(\"try_convert_type\", method=\"symbol\")\n def method_try_convert_type(self, space, w_obj, w_type, method):\n if not isinstance(w_type, W_ClassObject):\n raise space.error(space.w_TypeError, \"type argument must be a class\")\n return space.convert_type(w_obj, w_type, method, raise_error=False)\n\n @moduledef.function(\"compare\")\n def method_compare(self, space, w_a, w_b, block=None):\n return space.compare(w_a, w_b, block)\n\n @moduledef.function(\"infect\", taint=\"bool\", untrust=\"bool\", freeze=\"bool\")\n def method_infect(self, space, w_dest, w_src, taint=True, untrust=True, freeze=False):\n space.infect(w_dest, w_src, taint=taint, untrust=untrust, freeze=freeze)\n return self\n","sub_path":"topaz/modules/topaz.py","file_name":"topaz.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"639544917","text":"\"\"\"\n NumPyVectorSpace: An example concrete implementation of HilbertSpaceAbstract in which\n data is represented in the form of type np.ndarray\n\"\"\"\n\n\n# General Imports\nimport numpy as np\n\n# Local Imports\nfrom eigenvectorcontinuation.hilbertspaces.hilbert_space_abstract import HilbertSpaceAbstract\n\n__author__ = \"Jack H. Howard, Akhil Francis, Alexander F. Kemper\"\n__citation__ = \"\" # TODO Arxiv or doi\n__copyright__ = \"Copyright (c) 2022 Kemper Lab\"\n__credits__ = [\"Jack H. Howard\", \"Akhil Francis\", \"Alexander F. Kemper\",\n \"Anjali A. Agrawal\", \"Efekan Kökcü\"]\n__license__ = \"BSD-2-Clause-Patent\"\n__version__ = \"1.0\"\n__maintainer__ = \"Jack H. Howard\"\n__email__ = \"jhhoward@ncsu.edu\"\n__status__ = \"Development\"\n\n\nclass NumPyVectorSpace(HilbertSpaceAbstract):\n \"\"\" defines Hilbert Space behavior for numpy arrays\n\n contains inner class to help construct hamiltonian\n \"\"\"\n\n @property\n def implementation_type(self):\n \"\"\" I'm the current space's implementation type \"\"\"\n return np.ndarray\n\n @property\n def num_qubits(self):\n \"\"\" I'm the current space's number of qubits \"\"\"\n return self._num_qubits\n\n def __init__(self, training_points, num_qubits):\n \"\"\" initializes an instance of a NumPyVectorSpace and sets state variables\n\n :param points: the sets of points to use to construct the Hilbert Space\n :param num_qubits: the number of qubits in the space\n \"\"\"\n\n self._num_qubits = num_qubits\n\n super().__init__(training_points)\n\n def calc_basis_vecs(self):\n \"\"\" calculates the basis vectors for the given space\n creates a hamiltonian for each point, and determines eigenvecs for each hamiltonian\n\n :returns: the calculated basis vecs\n \"\"\"\n\n # number of points used to construct the Hilbert Space\n num_points = len(self.training_points)\n\n # initialize hamiltonians\n hamiltonian_initializer = self.HamiltonianInitializer()\n hams = [None] * num_points\n for idx, training_points in enumerate(self.training_points):\n hams[idx] = hamiltonian_initializer.xxztype_hamiltonian(training_points,\n self.num_qubits)\n\n # calculate evecs for each ham; selects lowest energy evec to go in evec_set\n evec_set = [None] * num_points\n for idx, ham in enumerate(hams):\n current_evecs = hamiltonian_initializer.calc_eigenpairs(ham)[1]\n evec_set[idx] = self.select_vec(current_evecs)\n\n self._basis_vecs = evec_set\n\n def inner_product(self, vec1, vec2):\n \"\"\" defines inner product for numpy array space\n\n :param vec1: the left vector of the inner product\n :param vec2: the right vector of the inner product\n\n :returns: inner product of vec1 & vec2\n \"\"\"\n\n # Raises error if argument argument types are not np.ndarray (np.matrix is allowed)\n if (not isinstance(vec1, np.ndarray) or not isinstance(vec2, np.ndarray)):\n raise ValueError(\"both vec1 and vec2 should be of type np.ndarray\")\n\n return vec1.conj() @ vec2\n\n def expectation_value(self, vec1, ham, vec2):\n \"\"\" defines expectation value calculation for numpy array space\n\n :param vec1: the left vector of the expectation value calculation\n :param ham: retrieve the expectation value w.r.t. this hamiltonian\n :param vec2: the right vector of the expectation value calculation\n\n :returns: the expectation value of the system\n \"\"\"\n\n # Raises error if argument types are not np.ndarray (np.matrix is allowed)\n if (not isinstance(vec1, np.ndarray) or\n not isinstance(ham, np.ndarray) or\n not isinstance(vec2, np.ndarray)):\n raise ValueError(\"both vec1 and vec2 should be of type np.ndarray\")\n\n return vec1.conj() @ ham @ vec2\n\n def calc_overlap_matrix(self, points=None):\n \"\"\" defines the overlap matrix for a NumPyVectorSpace\n\n if points are passed in, these become the new training points of the space\n otherwise, the existing training points are used\n\n For an overlap matrix S:\n S[i,j] = inner_product(basis_vec_i, basis_vec_j)\n\n :param points: points to use as training points (optional)\n\n :returns: the calculated overlap matrix\n \"\"\"\n\n if points is not None:\n self._training_points = points\n self.calc_basis_vecs()\n\n # dimensions of square matrix will be number of basis vectors\n dim = len(self.basis_vecs)\n overlap_s = np.zeros([dim, dim], dtype=complex)\n\n # S[i,j] = inner_product(basis_vec_i, basis_vec_j)\n for idx_i, vec_i in enumerate(self.basis_vecs):\n for idx_j, vec_j in enumerate(self.basis_vecs):\n overlap_s[idx_i, idx_j] = self.inner_product(vec_i, vec_j)\n\n return overlap_s\n\n def calc_sub_ham(self, ham):\n \"\"\" defines a subspace hamiltonian for space given a hamiltonian in the space and\n a set of spanning vectors (basis_vecs)\n\n NB: ham cannot be constructed using the same points used to calc basis_vecs\n\n Subspace Ham[i,j] = expectation_value(basis_vec_i, ham, basis_vec_j)\n\n :param ham: the hamiltonian used to find the subspace of\n\n :returns: the subspace hamiltonian\n \"\"\"\n\n # dimensions of square matrix will be number of basis vectors\n dim = len(self.basis_vecs)\n sub_ham = np.zeros([dim, dim], dtype=complex)\n\n # SubspaceHam[i,j] = expectation_value(basis_vec_i, ham, basis_vec_j)\n for idx_i, vec_i in enumerate(self.basis_vecs):\n for idx_j, vec_j in enumerate(self.basis_vecs):\n sub_ham[idx_i, idx_j] = self.expectation_value(vec_i, ham, vec_j)\n\n return sub_ham\n\n def select_vec(self, evecs):\n \"\"\" returns the lowest energy evec\n\n :param evecs: the set of evecs\n\n :returns: the selected vector\n \"\"\"\n\n if len(evecs) == 0:\n pass\n\n return evecs[:,0]\n\n class HamiltonianInitializer:\n \"\"\" initializes the hamiltonian \"\"\"\n\n _PAULIS = {}\n \"\"\" defines dict of Paulis to use below \"\"\"\n\n # ParamSet = namedtuple(\"ParamSet\", \"j_x j_z b_x b_z\")\n # \"\"\"\" useful tuple when dealing with param sets in this space \"\"\"\n\n def __init__(self):\n \"\"\" initializes class instance and Paulis dict \"\"\"\n self._PAULIS['X'] = np.array([[0,1],[1,0]], dtype=complex)\n self._PAULIS['Y'] = np.array([[0,-1.j],[1.j,0]], dtype=complex)\n self._PAULIS['Z'] = np.array([[1,0],[0,-1]], dtype=complex)\n self._PAULIS['I'] = np.array([[1,0], [0,1]], dtype=complex)\n\n def many_kron(self, ops):\n \"\"\" produces Kronecker (Tensor) product from list of Pauli charaters\n\n :param ops: the operations [as characters] to apply to a matrix\n \"\"\"\n\n result = self._PAULIS[ops[0]] # set result equal to first pauli given by the param\n if len(ops) == 1:\n return result\n\n for opj in ops[1:]: # for all the operations in the parameter\n result = np.kron(result, self._PAULIS[opj]) # tensor product the current matrix w/\n # the next pauli in the parameter list\n return result\n\n def xxztype_hamiltonian(self, param_set, n_qubits, pbc=False):\n \"\"\" produces the hamiltonian for a system where j_x = j_y and b_x = b_y\n\n :param param_set: the set of parameters: j_x, j_z, b_x, b_z\n :param n_qubits: the number of quibits\n :param pbc: periodic boundary condition wrap around logic boolean\n :returns: hamiltonian of the system\n \"\"\"\n\n j_x = param_set.j_x\n j_z = param_set.j_z\n b_x = param_set.b_x\n b_z = param_set.b_z\n\n ham = np.zeros([2**n_qubits, 2**n_qubits], dtype=complex) # initializes the hamiltonian\n\n # build hamiltonian matrix\n for isite in range(n_qubits):\n\n # Apply the Bz information to the hamiltonian matrix\n oplist = ['I']*n_qubits # makes list of operators (default = identity matrix)\n oplist[isite] = 'Z' # sets the isite-th entry to Z\n ham += b_z * self.many_kron(oplist) # applies the operations specified to the ham\n\n # Apply the Bx information to the hamiltonian matrix\n oplist = ['I']*n_qubits # makes list of operators (default = identity matrix)\n oplist[isite] = 'X' # sets the isite-th entry to X\n ham += b_x * self.many_kron(oplist) # applies the operations specified to the ham\n\n # checks whether to apply wrap-around rules\n jsite = (isite + 1) % n_qubits\n if (jsite != isite + 1 ) and not pbc:\n continue # skips the XX, YY, ZZ\n\n # Apply the XX information to the hamiltonian\n oplist = ['I']*n_qubits # makes list of operators (default = identity matrix)\n oplist[isite] = 'X' # sets the isite-th entry to X\n oplist[jsite] = 'X' # sets the jsite-th entry to X\n ham += j_x * self.many_kron(oplist) # applies the operations specified to ham\n\n # Apply the YY information to the hamiltonian\n oplist = ['I']*n_qubits # makes list of operators (default = identity matrix)\n oplist[isite] = 'Y' # sets the isite-th entry to Y\n oplist[jsite] = 'Y' # sets the jsite-th entry to Y\n ham += j_x * self.many_kron(oplist) # applies the operations specified to ham\n\n # Apply the Z information to the hamiltonian\n oplist = ['I']*n_qubits # makes list of operators (default = identity matrix)\n oplist[isite] = 'Z' # sets the isite-th entry to Z\n oplist[jsite] = 'Z' # sets the jsite-th entry to Z\n ham += j_z * self.many_kron(oplist) # applies the operations specified to ham\n\n return ham\n\n def calc_eigenpairs(self, ham):\n \"\"\" calcs the eigenpairs for a given param_setinate in a system\n\n :param ham: the hamiltonian to get the eigenpairs from\n\n :returns: the eigenpairs as: evals, evecs\n \"\"\"\n\n evals, evecs = np.linalg.eigh(ham)\n\n return evals, evecs\n","sub_path":"eigenvectorcontinuation/hilbertspaces/numpy_vector_space.py","file_name":"numpy_vector_space.py","file_ext":"py","file_size_in_byte":10948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"512664325","text":"from django.conf.urls import *\nimport views\n\nurlpatterns=patterns(' ',url(r'^image_text/$',views.image_text),url(r'^text_image/$',views.text_image),url(r'^classify_submit/$',views.classify_submit),url(r'^test/$',views.test),\nurl(r'^classify_add_picture/$',views.classify_add_picture),\nurl(r'^add_picture_android/$',views.add_picture_android),\nurl(r'^classify_add_picture_by_url/$',views.classify_add_picture_by_url),\nurl(r'^solve_text/$',views.solve_text),\nurl(r'^solve_text_android/$',views.solve_text_android),\nurl(r'^image_image/$',views.image_image),\nurl(r'^image_image_android/$',views.image_image_android),)\n","sub_path":"mysite/deeplearning/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"634279092","text":"from django.conf.urls import url\nfrom django.shortcuts import render\n\nfrom accounting.views import add_income, add_outgoing, list_transactions, filter_by_date, remove_transaction\n\nurlpatterns = [\n url(r'^$', list_transactions),\n url(r'add_income_transaction$', add_income),\n url(r'add_outgoing_transaction$', add_outgoing),\n url(r'filter_by_date$', filter_by_date),\n url(r'remove_transaction/(?P\\d+)', remove_transaction),\n]\n","sub_path":"accounting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"85095356","text":"'''\nThis program is used to fetch all the versions of library which user wants.\nProgram used in the following way:\npython3 cdnjsFetch.py ${library name}\nAfter exec it, the program will create a new folder with the name of that library\nand include all the files in the subfolder named with version number.\n'''\nimport os\nimport progressbar\nimport requests\nimport sys\nimport json\nimport urllib.request\n\nif(len(sys.argv) != 2):\n print(\"Parameter Error\")\n print(\"Use this program in the following way:\\r\\n\")\n print(\"python3 cdnjsFetch.py ${library name}\")\nelse:\n libname = sys.argv[1]\n print('Installing library \"%s\"' %(libname))\n\nbar = progressbar.ProgressBar()\n\n#libname='10up-sanitize.css'\n\nprint(\"Getting lib info through cdnjs API...\")\nbar.update(0)\nget = requests.get('https://api.cdnjs.com/libraries/%s' %(libname))\nresponse=''\nfor i in range(len(get.text)):\n response += get.text[i]\n#print(response)\nprint(\"\\r\\nFinding download URLs...\")\nbar.update(10)\napidict = json.loads(response)\nvnum = len(apidict['assets'])\nprint(\"\\r\\n%s versions of %s found in cdnjs.\" %(vnum, libname))\nbar.update(20)\n\nlist = {}\n\nverList = []\nfor ver in range(vnum):\n v = apidict['assets'][ver]['version']\n verList.append(v)\n urlList = []\n for fileList in apidict['assets'][ver]['files']:\n urlList.append(\"https://cdnjs.cloudflare.com/ajax/libs/\" + libname + \"/\" + apidict['assets'][ver]['version'] + \"/\" + fileList)\n list[v] = urlList\n\nprint(list)\nbar.update(50)\n#print(urlList)\nprint(os.path.abspath(__file__))\nif not os.path.exists(\"libs\"):\n os.mkdir(\"libs\")\nos.chdir(os.path.dirname(os.path.abspath(__file__)) + \"/libs\")\nif not os.path.exists(libname):\n os.makedirs(libname)\nelse:\n print(\"A folder named %s already exist in ./lib folder. Program terminated.\" %(libname))\n exit(2)\nos.chdir(os.path.dirname(os.path.abspath(__file__)) + \"/\" + libname)\n\nfor v in verList:\n os.mkdir(v)\n print(os.path.dirname(os.path.abspath(__file__)))\n os.chdir(os.path.dirname(os.path.abspath(__file__)) + \"/\" + v)\n print(os.path.dirname(os.path.abspath(__file__)))\n for url in list[v]:\n index = url.rfind(\"/\")\n name = url[index + 1:]\n print(url)\n print(name)\n urllib.request.urlretrieve(url, name)\n os.chdir(\"../\")\nbar.update(100)","sub_path":"cdnjsFetch.py","file_name":"cdnjsFetch.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"509244423","text":"import csv\nfrom SPARQLWrapper import SPARQLWrapper,JSON\nfrom urllib.parse import quote\nimport time\nimport re\n#note: please remove any \" marks in the song names before put them into the query\nquery =\"\"\"\n PREFIX prov: \n PREFIX mid: \n SELECT ?filename ?pattern\n WHERE {{ ?pattern prov:wasDerivedFrom ?filename .FILTER(regex(?filename, \"{0}\", \"i\"))}}\n \"\"\"\n\n#SPARQL query\nwith open('/Users/hu/Desktop/Index.csv', 'r') as db:\n reader = csv.DictReader(db)\n trackList=[]\n urlList=[]\n for row in reader:\n if not row['artist'] == '':\n artistUrl = quote(row['artist'], safe='')\n #urlList.append(artistUrl)\n trackName = row['title']\n #print(trackName)\n sparql = SPARQLWrapper(\"http://virtuoso-midi.amp.ops.labs.vu.nl/sparql\")\n sparql.setQuery(query.format(trackName))\n #print(query.format(trackName.strip(' ')))\n sparql.setReturnFormat(JSON)\n result = sparql.query().convert()\n pattern = re.compile(r'http\\S*\\'')\n text=str(result)\n m = pattern.findall(text)\n detectLength=(m.__len__())\n if not detectLength==0:\n for n in range(detectLength):\n subm=m[n]\n subm = subm.rstrip('\"]')\n subm = subm.rstrip(\"'\")\n print(\"\") # \"\"\n print(\"mo:published_as\")\n print(\"<\" + subm + \">\" + '.' + \"\\n\")\n\n else:\n #print(\"\" + \":no MIDI match found\"+ \"\\n\")\n pass\n time.sleep(0.5)\n # \", \" mo:published_as\",\n","sub_path":"python scripts/Bridging Billboard&MIDI-LD.py","file_name":"Bridging Billboard&MIDI-LD.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"227680147","text":"from django.contrib import admin\n\nfrom .models import Road, Image, Issue, IssueDetail\n\n# Register your models here.\n@admin.register(Road)\nclass Roadadmin(admin.ModelAdmin):\n list_display = ('road_id', 'pci', 'state', 'district', 'block')\n search_fields = ('road_id', 'state', 'district', 'block')\n ordering = ('state', 'district', 'block', 'road_id',)\n\n@admin.register(Image)\nclass ImageAdmin(admin.ModelAdmin):\n list_display = ('get_road_id', 'image_id')\n search_fields = ('road__road_id', 'image_id')\n ordering = ('road__road_id', 'image_id')\n\n def get_road_id(self, obj):\n return f'{obj.road.road_id}'\n get_road_id.short_description = 'Road ID'\n get_road_id.admin_order_field = 'road__road_id'\n\n # def get_location(self, obj):\n # return f'{obj.road.location}'\n # get_location.short_description = 'Location'\n # get_location.admin_order_field = 'road__location'\n\n@admin.register(Issue)\nclass IssueAdmin(admin.ModelAdmin):\n list_display = ('issue_id', 'name')\n search_fields = ('issue_id', 'name')\n ordering = ('issue_id',)\n\n@admin.register(IssueDetail)\nclass IssueDetailAdmin(admin.ModelAdmin):\n list_display = ('get_image_id', 'get_issue_name', 'count', 'quality')\n search_fields = ('image__image_id', 'issue__name')\n list_filter = ('issue__name', 'quality')\n ordering = ('image__image_id', 'issue__issue_id')\n\n def get_image_id(self, obj):\n return f'{obj.image.image_id}'\n get_image_id.short_description = 'Image ID'\n get_image_id.admin_order_field = 'image__image_id'\n\n def get_issue_name(self, obj):\n return f'{obj.issue.name}'\n get_issue_name.short_description = 'Issue'\n get_issue_name.admin_order_field = 'issue__name'\n","sub_path":"home/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"419760662","text":"class Blood:\n def __init__(self,bloodGroup,unitInHand):\n self.bloodGroup=bloodGroup\n self.unitInHand=unitInHand\nclass BloodBank(Blood):\n def __init__(self,bloodG4roup,unitInHand,bloodList):\n super().__init__(bloodGroup,unitInHand)\n self.bloodList=bloodList\n\n def isBloodAvailable(self,bloodGroup,unitInHand):\n for i in range(len(self.bloodList)):\n if self.bloodList[i][0] == self.bloodGroup:\n if self.bloodList[i][1] >= self.unitInHand:\n return \"Blood Available\"\n return \"Blood not Available\"\n def finMinBloodStock(self):\n find_min=[]\n for i in range(len(self.bloodList)):\n find_min.append(self.bloodList[i][1])\n minimum_blood = min(find_min)\n for i in range(len(self.bloodList)):\n if self.bloodList[i][1] == minimum_blood:\n print(self.bloodList[i][0])\n\nNumber_of_bloodobjects = int(input())\nlist_of_blood=[]\nfor i in range(Number_of_bloodobjects):\n blood = input().upper()\n unit = int(input())\n list_of_blood.append([blood,unit])\nbloodGroup = input().upper()\nunitInHand = int(input())\nobj1 = BloodBank(bloodGroup,unitInHand,list_of_blood)\nprint(obj1.isBloodAvailable(bloodGroup,unitInHand))\nobj1.finMinBloodStock()\n\n\n","sub_path":"Basics/JS_udemy/110.py","file_name":"110.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"524303464","text":"import cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0,cv2.CAP_DSHOW)\r\n\r\ncap.set(CV_CAP_PROP_EXPOSURE, 160)\r\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 120)\r\n\r\n# 160 x 120\r\n# 320 x 240\r\n# 640 x 480\r\n# 1280 x 720\r\n# 1280 x 1024\r\n\r\nwhile(True):\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n\r\n #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n \r\n # Display the resulting frame\r\n cv2.imshow('Ventana',frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n# When everything done, release the capture\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"2_3_WebCam.py","file_name":"2_3_WebCam.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"540071005","text":"import os\n\ndef build_sql(directory=\".\"):\n for root, dirs, files in os.walk(directory):\n for dir_name in dirs:\n out_str = ''\n dir_path = os.path.join(root, dir_name)\n for file_name in os.listdir(dir_path):\n if file_name.endswith('.sql'):\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'r') as sql_file:\n out_str += \"{} = '''{}'''\\n\\n\".format(''.join(file_name.split('.')[:-1]), sql_file.read())\n\n with open(os.path.join(dir_path, '__init__.py'), 'w') as out_file:\n out_file.write(out_str)\n\nif __name__ == '__main__':\n build_sql()\n\n\n","sub_path":"big_query/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"330615790","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import HttpResponse, render, redirect\n\n\ndef yimi(request):\n # request参数保存了所有和用户浏览器请求相关的数据\n # with open('templates/yimi.html', 'r', encoding='utf-8') as f:\n # data = f.read()\n # return HttpResponse(data)\n return render(request, 'yimi.html')\n\n\ndef xiaohei(request):\n return HttpResponse('hello, xiaohei!小黑真黑啊')\n\n\ndef login(request):\n err_msg = ''\n # 如果是POST请求,就取出提交的数据,做登录判断\n if request.method == \"POST\":\n # 获取用户提交的数据\n # print(request.POST)\n email = request.POST.get('email', None)\n pwd = request.POST.get('pwd', None)\n # 做是否登录成功的判断\n if email == 'alex@test.com' and pwd == '1234':\n # 登录成功\n return redirect('http://www.luffycity.com')\n else:\n # 登录失败\n err_msg = '邮箱或密码错误'\n # 如果是GET请求\n return render(request, 'login.html', {'error':err_msg})\n\n\ndef baobao(request):\n # 获取用户提交的数据\n # print(request.POST)\n email = request.POST.get('email', None)\n pwd = request.POST.get('pwd', None)\n # 做是否登录成功的判断\n if email == 'alex@test.com' and pwd == '1234':\n return redirect('http://www.luffycity.com')\n else:\n return HttpResponse('登录失败')\n","sub_path":"DjangoProjects_bak/mysite/mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"89740791","text":"class Solution(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n if not nums or target < nums[0]:\n return 0\n \n if len(nums) == 1 and target > nums[0]:\n return 1\n elif len(nums) == 1 and target <= nums[0]:\n return 0\n \n position = 0\n \n if target > nums[:len(nums)//2][-1] and target <= nums[len(nums)//2:][0]:\n return len(nums)//2\n # elif target == nums[:len(nums)//2][-1]:\n # return \n elif target > nums[:len(nums)//2][-1]:\n position = self.searchInsert(nums[len(nums)//2:], target)\n return len(nums)//2 + position\n elif target < nums[len(nums)//2:][0]:\n position = self.searchInsert(nums[:len(nums)//2], target)\n if position == 0:\n position -= 1\n return (len(nums)//2) + position\n print(position, len(nums))\n return (len(nums)//2) - position\n\na = Solution()\nprint(a.searchInsert([1,3], 1))","sub_path":"leetcode/arrays/searchInsert.py","file_name":"searchInsert.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"152828479","text":"from flask import flash,redirect,render_template,request,session,url_for,send_from_directory\nfrom first import app\nfrom first.forms import institute_update_form,authentications,personal_update_form\nimport mysql.connector\nimport pandas as pd\nfrom datetime import datetime\nimport numpy as np\nimport csv\nimport os\n\n\nmydb=mysql.connector.connect(host='localhost',user='root',passwd='1234',database='ridham')\nmycursor = mydb.cursor(buffered=True)\n\nmydb2=mysql.connector.connect(host='localhost',user='root',passwd='1234',database='ridham_2')\nmycursor2 = mydb2.cursor(buffered=True)\n\n\n# mydb=mysql.connector.connect(host='localhost',user='root',passwd='drivekraft',database='7SfpY1qGtT')\n# mycursor = mydb.cursor(buffered=True)\n\n# mydb2=mysql.connector.connect(host='remotemysql.com',user='cVTsksiGpK',passwd='5lxL6XRUOE',database='cVTsksiGpK')\n# mycursor2 = mydb2.cursor(buffered=True)\n\n \nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n\n\n@app.route('/')\ndef index99():\n \n return (\"hehehehe\")\n\n@app.route('/admin')\ndef index():\n lf=authentications()\n return render_template('authentication.html',lf=lf)\n\n\n\n@app.route('/authentication.py')\ndef index1():\n # scheduler = apscheduler.schedulers.blocking.BackgroundScheduler('apscheduler.job_defaults.max_instances': '2')\n name=request.values.get('name')\n passw=request.values.get('password')\n\n if str(name)=='drivekraft' and str(passw)=='elon':\n return render_template('front_pg_admin.html')\n else:\n return('some thing is worng')\n\n\n\n@app.route('/front_pg_admin.html')\ndef index2():\n return render_template('front_pg_admin.html')\n\n\n\n\n@app.route('/update_institute.html')\ndef index3():\n lf=institute_update_form()\n return render_template('update_institute.html',lf=lf)\n\n\n@app.route('/update_institute.py')\ndef index4():\n identity=request.values.get('identity')\n i_name=request.values.get('Institute_name')\n address=request.values.get('address')\n contact=request.values.get('contact') \n\n sql=\"insert into institute(i_id,name,address,contact) values(%s,%s,%s,%s)\"\n val =(identity,i_name,address,contact) \n \n mycursor.execute(sql, val) \n mydb.commit()\n return (\"done\") \n\n\n\n@app.route('/update_teacher.html')\ndef index5():\n pf=personal_update_form()\n return render_template('update_teacher.html',pf=pf)\n\n\n\n@app.route('/update_teacher.py') \ndef index6():\n id_institute=request.values.get('id_institute')\n file_name=request.values.get('file_name') \n\n dataset=pd.read_csv(str(file_name))\n credentilals=dataset[:].values\n\n for i in credentilals:\n sql=\"insert into teacher(name,i_id) values(%s,%s)\"\n val =(i[0],id_institute)\n mycursor = mydb.cursor()\n mycursor.execute(sql, val)\n mydb.commit()\n\n return('done') \n\n\n\n\n@app.route('/update_student.html')\ndef index7():\n pf=personal_update_form()\n return render_template('update_student.html',pf=pf)\n\n\n@app.route('/update_student.py')\ndef index8():\n standard=request.values.get('standard')\n id_institute=request.values.get('id_institute')\n batch=request.values.get('batch')\n file_name=request.values.get('file_name')\n\n dataset=pd.read_csv(str(file_name))\n credentilals=dataset[:].values\n\n for i in credentilals:\n sql=\"insert into student(name,standard,batch,institute_personal_id,email,contact,i_id) values(%s,%s,%s,%s,%s,%s,%s)\"\n val =(i[1],standard,batch,i[0],i[2],i[3],id_institute)\n print(i[1])\n\n mycursor = mydb.cursor()\n mycursor.execute(sql, val)\n mydb.commit()\n\n\n sql=\"insert into rel_student_institute(i_id,s_id) values(\" + str(id_institute) + \" , (select s_id from student where institute_personal_id = \" + str(i[0]) + \" and i_id = \" + str(id_institute) + \") )\"\n \n\n mycursor = mydb.cursor()\n mycursor.execute(sql)\n mydb.commit()\n\n return (\"done\") \n\n\n\n\n\n@app.route('/teacher/')\ndef index9(id1):\n session['check_it']='PASS_word'\n session['t_id']=str(id1)\n\n sql=\"select i_id from teacher where t_id =\" + str(id1)\n mycursor.execute(sql)\n result=mycursor.fetchone()\n session['i_id'] =str(result[0])\n\n return render_template('teacher_initiaal_template.html')\n\n\n\n@app.route('/make_test.html')\ndef index10():\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n session['j']=0\n return render_template('make_test1.html')\n\n\n@app.route('/date_number.py')\ndef index11():\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n\n date=request.values.get('date')\n ques=request.values.get('ques')\n\n session['date']=date\n session['ques']=ques\n\n return render_template('make_test2.html')\n\n\n@app.route('/time_time.py')\ndef index12():\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n stime=request.values.get('starting_time')\n etime=request.values.get('ending_time')\n\n sql=\"insert into exam(s_time,e_time,date,active) values('\" + str(stime) +\"','\" + str(etime) + \"','\" + str(session['date']) + \"',\" + \"0)\";\n mycursor.execute(sql)\n mydb.commit()\n\n mycursor2.execute(sql)\n mydb2.commit()\n\n sql= \"select * from exam\"\n mycursor.execute(sql)\n result=mycursor.fetchall()\n\n test_id= result[-1][0]\n session['exam_id']=test_id\n\n sql= \"insert into rel_institute_exam values(\" + str(test_id) + \",\"+ str(session['t_id']) + \",\" + \"NULL)\";\n mycursor.execute(sql)\n mydb.commit()\n\n le = session['ques']\n return render_template('make_batch.html')\n\n\n@app.route('/batch.py')\ndef index13():\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n batch=request.values.get('batches')\n you=batch.split(',') \n\n ki=''\n for i in you:\n ki= ki+ str(i) \n if str(i) in you[:-1]:\n ki= ki + \",\"\n\n sql=\"update rel_institute_exam set batches= '\" + str(ki) +\"' where e_id ='\" + str(session['exam_id']) + \"'\"\n mycursor.execute(sql)\n mydb.commit()\n\n return render_template('make_test3.html',le=str(session['ques']),test_id=session['exam_id'])\n\n\n@app.route('/es.html',methods=[\"POST\"])\ndef index14():\n target=os.path.join(APP_ROOT,'images/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n # j=0\n # for file in request.files.getlist(\"picq\"):\n # filename=file.name + str(j) + \".png\"\n # j=j+1\n # destination= \"/\".join([target,filename])\n # print(destination)\n # file.save(destination) \n\n \n final=request.values.get('final')\n detail=list();\n detail=final.split('//')\n \n for i in detail[:-1]: \n esh=i.split('@')\n ques_no=str(esh[0])\n ques=esh[1]\n oa=esh[2]\n ob=esh[3]\n oc=esh[4]\n od=esh[5]\n corr=esh[6]\n subj=esh[7]\n maxi=esh[8]\n negi=esh[9]\n\n\n if esh[10] !='':\n qi=esh[10]\n else:\n qi='-1'\n\n if esh[11] !='':\n oai=esh[11]\n else:\n oai='-1'\n \n if esh[12] !='':\n obi=esh[12]\n else:\n obi='-1' \n\n if esh[13] !='':\n oci=esh[13]\n else:\n oci='-1' \n\n if esh[14] !='':\n odi=esh[14]\n else:\n odi='-1' \n\n\n\n\n\n \n\n sql=\"insert into question(ques_statement,option_a,option_b,option_c,option_d,correct,sub,max_mark,nega_marks) values('\"+ str(ques) +\"','\" + str(oa) +\"','\"+ str(ob)+ \"','\" + str(oc) + \"','\" + str(od) +\"','\" + str(corr) +\"','\"+ str(subj) + \"','\" +str(maxi) +\"','\" + str(negi) + \"')\"\n mycursor.execute(sql)\n mydb.commit() \n \n \n sql= \"select q_id from question where ques_statement ='\"+ str(ques) + \"' and option_a ='\" + str(oa) + \"'\"\n mycursor.execute(sql)\n result=mycursor.fetchall()\n \n test_id= session['exam_id']\n qu=result[0][0];\n \n sql=\"insert into rel_question_exam values (\" + str(qu) + \",\" + str(test_id) + \")\";\n mycursor.execute(sql)\n mydb.commit() \n\n sql=\"insert into rel_image_question values (\" + str(qu) +\",\" +str(qi) +\",\" +str(oai) + \",\" + str(obi) + \",\" + str(oci) + \",\" + str(odi)+ \")\";\n mycursor.execute(sql)\n mydb.commit() \n\n \n \n return render_template('final_interface_t.html')\n\n\n\n@app.route('/student_init/')\ndef index97(id2):\n session['check_it']='PASS_word'\n\n print(\"hello\")\n sensor()\n return redirect(\"/student/\" + str(id2))\n #return str(\"/student/\" + str(id2))\n\n\n\n\n\n@app.route('/student/')\ndef index15(id2):\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n print(\"hello\")\n sql=\"select batch ,i_id from student where s_id =\"+ str(id2)\n mycursor.execute(sql)\n result=mycursor.fetchone()\n\n session['batch']=result[0]\n session['i_id']= result[1]\n session['student_id']= str(id2)\n\n\n sql=\" select rel_institute_exam.e_id from rel_institute_exam join teacher on teacher.t_id = rel_institute_exam.t_id where teacher.i_id= \"+ str(session['i_id']) + \" and rel_institute_exam.batches like '%\" + str(session['batch']) + \"%'\"\n mycursor.execute(sql)\n results=mycursor.fetchall()\n\n\n ki='-1'\n for i in results:\n ki= ki+ \",\" + str(i[0]) \n \n \n sql=\" select e_id from exam where e_id in (\" + str(ki) + \") and active=1 \"\n mycursor.execute(sql)\n re=mycursor.fetchone()\n\n\n if re==None:\n return render_template('error_404_2.html')\n\n\n session['exam_id']=str(re[0])\n sql=\" select q_id from rel_question_exam where e_id =\" + str(re[0])\n mycursor.execute(sql)\n re=mycursor.fetchall()\n \n \n\n ki=''\n\n for i in re:\n ki= ki+ str(i[0]) \n if i in re[:-1]:\n ki= ki + \",\"\n\n\n que= str(ki)\n\n sql= \" select * from question where q_id in (\" + que + \")\";\n mycursor.execute(sql)\n results=mycursor.fetchall()\n\n\n\n sql=\" select * from rel_image_question where q_id in (\" + que + \")\";\n mycursor.execute(sql)\n imgs=mycursor.fetchall()\n\n session['magic']= results\n\n\n\n\n sql=\" select e_time,date from exam where e_id = \" + str(session['exam_id']);\n mycursor.execute(sql)\n etime=mycursor.fetchone()\n\n # ki=etime[0].split(\":\")\n\n est=str(etime[0])\n dt = str(etime[1])\n et=est.split(\":\")\n ed=dt.split(\"-\")\n\n le=len(results)\n\n\n\n re_write=list()\n\n for i in range(0,len(results)):\n local=list()\n\n for j in results[i]:\n local.append(j)\n\n for j in imgs[i]:\n local.append(j)\n\n re_write.append(local)\n\n\n \n return render_template('std_test.html',le=le,results=re_write,et=et,ed=ed,imgs=imgs,exid=str(session['exam_id']))\n\n@app.route('/we.html')\ndef index16():\n final=request.values.get('final')\n \n correct_answer=session['magic']\n\n # return str(final)\n\n st= str(session['student_id'])\n st= st + \", \" + str(final)\n\n\n st=st + '\\n';\n\n file = open(str(session['exam_id']) + '.csv','a')\n file.write(st) \n file.close()\n\n session.clear()\n return render_template('final_interface_s.html')\n\n ca=list()\n for i in correct_answer:\n ca.append(i[6])\n\n # correct options are and responses are here\n\n return str(ca)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef sensor():\n \"\"\" Function for test purposes. \"\"\"\n now = datetime.now()\n print(\"now =\", now.time())\n c_date=now.date()\n c_time=now.time()\n\n sql=\"select e_id from exam where date= '\"+ str(c_date) + \"' and s_time <= '\" + str(c_time) + \"' and e_time >= '\" +str(c_time) + \"' and active='0' \"\n print(sql)\n mycursor2.execute(sql)\n exam_identity=mycursor2.fetchall()\n\n\n print(exam_identity)\n\n for i in exam_identity:\n sql=\"update exam set active='1' where e_id = \" + str(i[0]) \n mycursor2.execute(sql)\n mydb2.commit()\n mycursor.execute(sql)\n mydb.commit()\n print(\"test_started\")\n\n\n\n\n \n sql=\"select e_id from exam where active='1' and date <= '\"+ str(c_date) + \"' and e_time <= '\" +str(c_time) + \"'\"\n print(str(sql))\n mycursor2.execute(sql)\n exam_identity=mycursor2.fetchall()\n\n\n sql=\"select e_id from exam where active='1' and date < '\"+ str(c_date) + \"'\"\n print(str(sql))\n mycursor2.execute(sql)\n exam_identity2=mycursor2.fetchall()\n\n print(exam_identity)\n\n\n\n for i in exam_identity:\n sql=\"update exam set active='0' where e_id =\" + str(i[0]) \n print(sql)\n mycursor2.execute(sql)\n mydb2.commit()\n\n mycursor.execute(sql)\n mydb.commit()\n\n\n for i in exam_identity2:\n sql=\"update exam set active='0' where e_id =\" + str(i[0]) \n print(sql)\n mycursor2.execute(sql)\n mydb2.commit()\n\n mycursor.execute(sql)\n mydb.commit()\n\n\n print(\"test_completed\")\n\n \n\n\n# job_defaults = {\n# 'coalesce': False,\n# 'max_instances': 3\n# }\n\n# sched = BackgroundScheduler(job_defaults=job_defaults)\n# sched.add_job(sensor,'interval',seconds=10)\n# sched.start()\n\n\n\n\n# @app.route(\"/home\")\n# def home():\n# \"\"\" Function for test purposes. \"\"\"\n# return \"Welcome Home :) !\"\n\n\n\n\n@app.route('/six/') \ndef upload(test_id): \n #return (\"hello\")\n return render_template(\"file_upload_form.html\",test_id=test_id) \n \n@app.route('/success/', methods = ['POST']) \ndef success(test_id): \n if request.method == 'POST': \n f = request.files['file'] \n f.save(f.filename) \n\n\n sql=\"insert into img(image,test_id) values \"\n\n\n\n val= str(\"'D:\\\\template\") + str('@') +str(f.filename) +\"'\"\n val = val.replace(\"@\", \"\\\\\")\n\n sql = sql + \"(\" + val + \",\" + str(test_id) + \")\"\n\n mycursor.execute(sql) \n mydb.commit()\n\n return render_template(\"success.html\", name = f.filename)\n\n\n\n\n@app.route('/ques_img.html')\ndef index25():\n return render_template('ques_img.html')\n\n\n@app.route('/oa_img.html')\ndef index26():\n return render_template('oa_image.html')\n\n\n@app.route('/ob_img.html')\ndef index27():\n return render_template('ob_image.html')\n\n\n@app.route('/oc_img.html')\ndef index28():\n return render_template('oc_image.html')\n\n\n\n@app.route('/od_img.html')\ndef index29():\n return render_template('od_image.html')\n\n\n \n@app.route('/img_ques.html',methods=[\"POST\"])\ndef index44():\n target=os.path.join(APP_ROOT,'static/ques_img/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n j=session['j']\n session['j']= session['j']+1\n for file in request.files.getlist(\"picq\"):\n filename=str(session['exam_id']) +\"-\" + file.name + str(j) + \".png\"\n destination= \"/\".join([target,filename])\n print(destination)\n file.save(destination) \n \n flash(\"Image Submitted\") \n\n return redirect('/ques_img.html')\n\n\n@app.route('/img_oa.html',methods=[\"POST\",\"GET\"])\ndef index45():\n target=os.path.join(APP_ROOT,'static/ques_img/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n j=session['j']\n session['j']= session['j']+1\n for file in request.files.getlist(\"picq\"):\n filename=str(session['exam_id']) +\"-\" + file.name + str(j) + \".png\"\n destination= \"/\".join([target,filename])\n print(destination)\n file.save(destination) \n\n flash(\"Image Submitted\") \n\n return redirect('/oa_img.html') \n\n\n@app.route('/img_ob.html',methods=[\"POST\"])\ndef index46():\n target=os.path.join(APP_ROOT,'static/ques_img/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n j=session['j']\n session['j']= session['j']+1\n for file in request.files.getlist(\"picq\"):\n filename=str(session['exam_id']) +\"-\" + file.name + str(j) + \".png\"\n destination= \"/\".join([target,filename])\n print(destination)\n file.save(destination) \n\n flash(\"Image Submitted\")\n\n return redirect('/ob_img.html') \n\n\n\n\n@app.route('/img_oc.html',methods=[\"POST\"])\ndef index47():\n target=os.path.join(APP_ROOT,'static/ques_img/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n j=session['j']\n session['j']= session['j']+1\n for file in request.files.getlist(\"picq\"):\n filename=str(session['exam_id']) +\"-\" + file.name + str(j) + \".png\"\n destination= \"/\".join([target,filename])\n print(destination)\n file.save(destination) \n\n flash(\"Image Submitted\")\n\n return redirect('/oc_img.html') \n\n\n\n@app.route('/img_od.html',methods=[\"POST\"])\ndef index48():\n target=os.path.join(APP_ROOT,'static/ques_img/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n\n if(session.get('check_it')==None):\n return render_template('error_404_1.html')\n\n\n j=session['j']\n session['j']= session['j']+1\n for file in request.files.getlist(\"picq\"):\n filename=str(session['exam_id']) +\"-\" + file.name + str(j) + \".png\"\n destination= \"/\".join([target,filename])\n print(destination)\n file.save(destination) \n\n flash(\"Image Submitted\") \n\n return redirect('/od_img.html') ","sub_path":"first/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":17122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"490201708","text":"# -*- coding: utf-8 -*-\n\nfrom pygments import highlight\nfrom pygments.lexers import *\nfrom pygments.formatters import HtmlFormatter\n\nfrom .conf import settings\n\n\"\"\"\n# Get a list of all lexer, and then remove all lexer which have '-' or '+'\n# or 'with' in the name. Those are too specific and never used. This produces a\n# tuple list of [(lexer, Lexer Display Name) ...] lexers.\nfrom pygments.lexers import get_all_lexers\nALL_LEXER = set([(i[1][0], i[0]) for i in get_all_lexers()])\nLEXER_LIST = [l for l in ALL_LEXER if not (\n '-' in l[0]\n or '+' in l[0]\n or '+' in l[1]\n or 'with' in l[1].lower()\n or ' ' in l[1]\n or l[0] in IGNORE_LEXER\n)]\nLEXER_LIST = sorted(LEXER_LIST)\n\"\"\"\n\n# The list of lexers. Its not worth to autogenerate this. See above how to\n# retrieve this.\nLEXER_LIST = settings.LIBPASTE_LEXER_LIST\n\nLEXER_KEYS = dict(LEXER_LIST).keys()\n\n# The default lexer is python\nLEXER_DEFAULT = settings.LIBPASTE_LEXER_DEFAULT\n\n# Lexers which have wordwrap enabled by default\nLEXER_WORDWRAP = settings.LIBPASTE_LEXER_WORDWRAP\n\n\nclass NakedHtmlFormatter(HtmlFormatter):\n def wrap(self, source, outfile=None):\n return self._wrap_code(source)\n\n def _wrap_code(self, source):\n for i, t in source:\n yield i, t\n\ndef pygmentize(code_string, lexer_name=LEXER_DEFAULT):\n try:\n lexer = lexer_name and get_lexer_by_name(lexer_name) \\\n or PythonLexer()\n except Exception:\n lexer = PythonLexer()\n return highlight(code_string, lexer, NakedHtmlFormatter())\n","sub_path":"libpaste/highlight.py","file_name":"highlight.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"462198023","text":"#\n# Copyright (c) 2021 Airbyte, Inc., all rights reserved.\n#\n\n\nfrom setuptools import find_packages, setup\n\nMAIN_REQUIREMENTS = [\n \"airbyte-protocol\",\n \"base-python\",\n \"gcsfs==0.7.1\",\n \"genson==1.2.2\",\n \"google-cloud-storage==1.35.0\",\n \"pandas==1.2.0\",\n \"paramiko==2.7.2\",\n \"s3fs==0.4.2\",\n \"smart-open[all]==4.1.2\",\n \"lxml==4.6.3\",\n \"html5lib==1.1\",\n \"beautifulsoup4==4.9.3\",\n \"pyarrow==3.0.0\",\n \"xlrd==2.0.1\",\n \"openpyxl==3.0.6\",\n \"pyxlsb==1.0.8\",\n]\n\nTEST_REQUIREMENTS = [\n \"boto3==1.16.57\",\n \"pytest==6.1.2\",\n \"pytest-docker==0.10.1\",\n]\n\nsetup(\n name=\"source_file\",\n description=\"Source implementation for File\",\n author=\"Airbyte\",\n author_email=\"contact@airbyte.io\",\n packages=find_packages(),\n install_requires=MAIN_REQUIREMENTS,\n package_data={\"\": [\"*.json\"]},\n extras_require={\n \"tests\": TEST_REQUIREMENTS,\n },\n)\n","sub_path":"airbyte-integrations/connectors/source-file/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"501069494","text":"#!/usr/bin/env python3\n\nimport socket\nimport signal\nimport time\nimport sys\nimport matplotlib.pyplot as plt\nfrom cmath import phase as phase\n\ndef final_words():\n #print('closing socket')\n #sock.close()\n print(\"Exiting...\")\n sys.exit(1)\n\ndef exit_gracefully(signum, frame):\n # restore the original signal handler as otherwise evil things will happen\n # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant\n signal.signal(signal.SIGINT, original_sigint)\n\n # Exit the program\n final_words()\n\n # restore the exit gracefully handler here (probably this won't happen)\n signal.signal(signal.SIGINT, exit_gracefully)\n\n\ndef get_constants(prefix):\n \"\"\"Create a dictionary mapping socket module constants to their names.\"\"\"\n return dict( (getattr(socket, n), n)\n for n in dir(socket)\n if n.startswith(prefix)\n )\n\n\ndef open_socket(port_number):\n \"\"\"Opens and returns the socket.\"\"\"\n\n families = get_constants('AF_')\n types = get_constants('SOCK_')\n protocols = get_constants('IPPROTO_')\n\n # Create a TCP/IP socket\n try:\n sock = socket.create_connection(('localhost', port_number))\n except ConnectionRefusedError:\n print( f\"No connection in port #{port_number!s}.\" )\n final_words()\n\n print('Family : ', families[sock.family])\n print('Type : ', types[sock.type])\n print('Protocol: ', protocols[sock.proto])\n\n sock.settimeout(1) # 1 second timeout\n return sock\n\n\ndef parse_line(received_line):\n \"\"\"This method decodes the line received via the socket, parses it, and\n return a list with the channel coefficients.\"\"\"\n\n # Parse the line\n line = received_line.decode(\"utf-8\")\n fields = line.split(',')\n # Convert to complex values\n csi_values = [ complex( f.replace('i','j') ) for f in fields[8:] ]\n return csi_values\n\n\ndef run_program(sock_data, sock_csi):\n\n # Create two subplots\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1)\n # Information\n ax1.set_xlabel('channel')\n ax1.set_ylabel('abs')\n ax2.set_xlabel('channel')\n ax2.set_ylabel('phase')\n ax3.set_xlabel('abs')\n ax3.set_ylabel('# of times')\n # make a little extra space between the subplots\n fig.subplots_adjust(hspace=0.5)\n # Start interactive plot and show it\n plt.ion()\n plt.show()\n\n # Number of timeouts\n num_timeouts = 0\n\n while True:\n # Small delay\n time.sleep(.5)\n\n # Send ping\n message = \"Ping\"\n sock_data.sendall(bytes(message+\"\\n\",\"utf-8\"))\n\n # Receive pong with CSI data from other terminal and own CSI\n try:\n csi_other = sock_data.recv(2048)\n csi_own = sock_csi.recv(2048)\n except socket.timeout:\n num_timeouts += 1\n print( f\"Timeouts since last reception = {num_timeouts!s}\" )\n continue\n\n # Reset timeout counter\n num_timeouts = 0\n\n if len(csi_other) == 0 or len(csi_own) == 0:\n # One port was probably closed\n final_words()\n\n # Parse the line\n csi_values_other = parse_line(csi_other)\n csi_values_own = parse_line(csi_own)\n #print(csi_values)\n\n # Plot 1 (Magnitude)\n abs_values_1 = [ abs(c) for c in csi_values_other ]\n abs_values_2 = [ abs(c) for c in csi_values_own ]\n ax1.cla() # Clear the plot\n ax1.plot(abs_values_1, label=\"Remote\") # Add the new line\n ax1.plot(abs_values_2, label=\"Local\") # Add the new line\n ax1.legend()\n\n # Plot 2 (Phase)\n pha_values_1 = [ phase(c) for c in csi_values_other ]\n pha_values_2 = [ phase(c) for c in csi_values_own ]\n ax2.cla() # Clear the plot\n ax2.plot(pha_values_1, label=\"Remote\") # Add the new line\n ax2.plot(pha_values_2, label=\"Local\") # Add the new line\n ax2.legend()\n\n # Plot 3 (Histogram)\n ax3.cla()\n ax3.hist(abs_values_1, 10, alpha=0.5, label=\"Remote\")\n ax3.hist(abs_values_2, 10, alpha=0.5, label=\"Local\")\n ax3.legend()\n\n # Information\n ax1.set_xlabel('channel')\n ax1.set_ylabel('abs')\n ax2.set_xlabel('channel')\n ax2.set_ylabel('phase')\n ax3.set_xlabel('abs')\n ax3.set_ylabel('# of times')\n plt.pause(0.00001) # Pause needed for redrawing\n\n ## Send data\n #message = 'This is the message. It will be repeated.'\n #print('sending :', message)\n #sock.sendall(bytes(message+\"\\n\",\"utf-8\"))\n\n\n\n# Main\nif __name__ == '__main__':\n # store the original SIGINT handler\n original_sigint = signal.getsignal(signal.SIGINT)\n signal.signal(signal.SIGINT, exit_gracefully)\n # Open the sockets and run the main loop\n s_data = open_socket(52001)\n s_csi = open_socket(52002)\n run_program(s_data, s_csi)\n\n\n\n\n\n\n\n\n","sub_path":"Collecting_data/csi_plot.py","file_name":"csi_plot.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"132683165","text":"\n\n#calss header\nclass _NEBULA():\n\tdef __init__(self,): \n\t\tself.name = \"NEBULA\"\n\t\tself.definitions = [u'a cloud of gas or dust in space, appearing either bright or dark']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_nebula.py","file_name":"_nebula.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"69262765","text":"import requests\nimport json\n\nclass Dictionary(): ## class for get description of word\n\tdef __init__(self, word):\n\t\tif word == \"\":\n\t\t\treturn \"Invaild word\"\n\t\tself.word = word\n\t\tself.data = self.__get_data()\n\n\tdef _find(self,val, query, next_val=0, start=0):\n\t\tfor x in range(start, len(query)-len(val)+1):\n\t\t\tif query[x:(x+len(val))] == val:\n\t\t\t\tif next_val > 0:\n\t\t\t\t\tnext_val -= 1\n\t\t\t\t\tcontinue\n\t\t\t\treturn x\n\t\treturn False\n\tdef _get_value(self,start, end, query, delay=0):\n\t\t\tstart_index = self._find(start, query)\n\t\t\tend_index = self._find(end, query, start=start_index, next_val=delay) + len(end)\n\t\t\treturn [query[start_index:end_index],end_index] ## second object is to make right query cut\n\n\n\tdef __get_data(self): ## function for get request to dictionary\n\t\trequest = requests.get(f'https://www.merriam-webster.com/dictionary/{self.word}')\n\t\tif f\"The word you\\'ve entered isn\\'t in the dictionary.\" in request.text:\n\t\t\treturn False\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tres, i = self._get_value('', '', request.text)\n\t\t\t\trequest = request.text[i:]\n\t\t\texcept AttributeError:\n\t\t\t\tres, i = self._get_value('', '', request)\n\t\t\t\trequest = request[i:]\n\t\t\tif not self.word[:3] in res:\n\t\t\t\tres = res.replace('<', \"`#\")\n\t\t\t\tres = res.replace('>', \"`\")\n\t\t\t\tres = res.split(\"`\")\n\t\t\t\tfor x in range(len(res)-1, -1, -1):\n\t\t\t\t\tif '#' in res[x] or res[x] == '' or res[x] == \": \":\n\t\t\t\t\t\tdel res[x]\n\t\t\t\tres = ''.join(res) # end value\n\t\t\t\treturn res\n\nclass RandomWord(Dictionary): ## class to get random word from site https://randomword.com\n\tdef __init__(self):\n\t\tself.rand_word, self.description = self.__get_data()\n\n\tdef get_word(self):\n\t\treturn {\"word\": self.rand_word, 'description': self.description}\n\n\tdef __get_data(self):\n\t\trequest = requests.get('https://randomword.com/')\n\t\tres, i = super()._get_value('
', '
', request.text, delay=2)\n\t\trequest = request.text[i:]\n\t\tres = res.replace('<', \"`#\")\n\t\tres = res.replace('>', \"`\")\n\t\tres = res.split(\"`\")\n\t\tfor x in range(len(res)-1, -1, -1):\n\t\t\tif '#' in res[x] or res[x] == '' or '\\n\\t\\t' in res[x]:\n\t\t\t\tdel res[x]\n\t\tres[1] = res[1][:len(res[1])-2]\n\t\treturn res# end value\n\nclass RandomRightWord():\t## class to get random word from site https://random-word-api.herokuapp.com\n\tdef __init__(self):\n\t\tself.rand_word, self.description = self.__get_data()\n\n\tdef get_word(self):\n\t\treturn {\"word\": self.rand_word, 'description': self.description}\n\n\tdef __get_data(self):\n\t\tapi_key = requests.get('https://random-word-api.herokuapp.com/key').text\n\t\tword = requests.get(f'https://random-word-api.herokuapp.com/word?key={api_key}')\n\t\tword = json.loads(word.text)[0]\n\t\tdes = Dictionary(word) ## get description of word\n\t\tdes = des.data\n\t\treturn [word, des]\n","sub_path":"graphical/src/main/python/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"326592263","text":"import cookielib\nimport datetime\nimport urllib\nimport urllib2\nfrom collections import namedtuple\nfrom contextlib import closing\nfrom lxml import html\n\n\nSchedule = namedtuple('Schedule', ('title', 'start', 'end', 'depart'))\n\n\nclass DjuAgent(object):\n URL_LOGIN = 'http://intra.dju.kr/servlet/sys.syd.syd01Svl03'\n URL_SCHEDULE = ('http://intra.dju.kr/servlet/sys.syc.syc01Svl15'\n '?pgm_id=W_SYS032PQ&pass_gbn=&dpt_ck=')\n DATE_FORMAT = '%Y-%m-%d %H-%M-%S'\n\n def __init__(self, userid=None, userpw=None):\n cookiejar = cookielib.CookieJar()\n self.opener = urllib2.build_opener(\n urllib2.HTTPCookieProcessor(cookiejar))\n\n if userid and userpw:\n self.login(userid, userpw)\n\n def login(self, userid, userpw):\n login_data = urllib.urlencode({\n 'proc_gubun': '1',\n 'pgm_id': 'SYS200PE',\n 'id': userid,\n 'pwd': userpw,\n })\n\n with closing(self.opener.open(self.URL_LOGIN, login_data)) as fp:\n content = fp.read()\n if 'self.location' not in content:\n tree = html.fromstring(content)\n msg = tree.xpath('//td')[3].text_content().strip()\n raise ValueError(msg.encode('utf-8'))\n\n def get_schedules(self):\n with closing(self.opener.open(self.URL_SCHEDULE)) as fp:\n content = fp.read()\n tree = html.fromstring(content)\n trs = tree.xpath('//tr')[6:]\n\n for tr in trs:\n title = tr.find('td[1]').text_content().strip()\n start = datetime.datetime.strptime(\n tr.find('td[2]').text_content().strip(),\n self.DATE_FORMAT)\n try:\n end = datetime.datetime.strptime(\n tr.find('td[3]').text_content().strip(),\n self.DATE_FORMAT)\n except ValueError:\n end = None\n\n depart = tr.find('td[4]').text_content().strip()\n\n yield Schedule(title, start, end, depart)\n","sub_path":"djucal.py","file_name":"djucal.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"74967347","text":"\"\"\"PytSite Tumblr Content Export Driver\n\"\"\"\n__author__ = 'Oleksandr Shepetko'\n__email__ = 'a@shepetko.com'\n__license__ = 'MIT'\n\nfrom frozendict import frozendict as _frozendict\nfrom pytsite import logger as _logger\nfrom plugins import widget as _widget, content_export as _content_export, content as _content, tumblr as _tumblr\n\n\nclass Driver(_content_export.AbstractDriver):\n \"\"\"Content Export Driver.\n \"\"\"\n\n def get_name(self) -> str:\n \"\"\"Get system name of the driver.\n \"\"\"\n return 'tumblr'\n\n def get_description(self) -> str:\n \"\"\"Get human readable description of the driver.\n \"\"\"\n return 'content_export_tumblr@tumblr'\n\n def get_options_description(self, driver_options: _frozendict) -> str:\n \"\"\"Get human readable driver options.\n \"\"\"\n return driver_options.get('user_blog')\n\n def get_settings_widget(self, driver_opts: _frozendict, form_url: str) -> _widget.Abstract:\n \"\"\"Add widgets to the settings form of the driver.\n \"\"\"\n return _tumblr.widget.Auth(\n uid='driver_opts',\n oauth_token=driver_opts.get('oauth_token'),\n oauth_token_secret=driver_opts.get('oauth_token_secret'),\n screen_name=driver_opts.get('screen_name'),\n user_blog=driver_opts.get('user_blog'),\n callback_uri=form_url,\n )\n\n def export(self, entity: _content.model.Content, exporter=_content_export.model.ContentExport):\n \"\"\"Export data.\n \"\"\"\n _logger.info(\"Export started. '{}'\".format(entity.title))\n\n try:\n opts = exporter.driver_opts # type: _frozendict\n oauth_token = opts.get('oauth_token')\n oauth_token_secret = opts.get('oauth_token_secret')\n\n s = _tumblr.session.Session(oauth_token, oauth_token_secret)\n\n tags = exporter.add_tags # type: tuple\n\n if entity.has_field('tags'):\n tags += tuple(t.title for t in entity.f_get('tags'))\n\n thumb_url = entity.images[0].get_url(width=640) if entity.images else None\n author = entity.author.first_last_name\n description = entity.f_get('description') if entity.has_field('description') else ''\n s.blog_post_link(opts['user_blog'], entity.url, entity.title, description, thumb_url,\n author=author, tags=','.join(tags))\n except Exception as e:\n raise _content_export.error.ExportError(e)\n\n _logger.info(\"Export finished. '{}'\".format(entity.title))\n","sub_path":"_driver.py","file_name":"_driver.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253730352","text":"\"\"\"Configuration classes\"\"\"\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Type, Tuple\n\nimport boto3\nimport toml\n\nfrom altimeter.aws.auth.accessor import Accessor\nfrom altimeter.core.artifact_io import is_s3_uri, parse_s3_uri\n\n\nclass InvalidConfigException(Exception):\n \"\"\"Indicates an invalid configuration\"\"\"\n\n\ndef _get_required_param(key: str, config_dict: Dict[str, Any]) -> Any:\n \"\"\"Get a parameter by key from a config dict. Raise InvalidConfigException if it does\n not exist.\"\"\"\n value = config_dict.get(key)\n if value is None:\n raise InvalidConfigException(f\"Missing parameter '{key}'\")\n return value\n\n\ndef _get_optional_param(key: str, config_dict: Dict[str, Any]) -> Any:\n \"\"\"Get a parameter by key from a config dict. Return None if it does not exist.\"\"\"\n return config_dict.get(key)\n\n\ndef get_required_list_param(key: str, config_dict: Dict[str, Any]) -> Tuple[Any, ...]:\n \"\"\"Get a list parameter by key from a config dict. Raise InvalidConfigException if it does\n not exist or its value is not a list. Return as a tuple.\"\"\"\n value = _get_required_param(key, config_dict)\n if isinstance(value, tuple):\n return value\n if not isinstance(value, list):\n raise InvalidConfigException(\n f\"Parameter '{key}' should be a list or tuple. Is {type(value)}\"\n )\n return tuple(value)\n\n\ndef get_required_bool_param(key: str, config_dict: Dict[str, Any]) -> bool:\n \"\"\"Get a bool parameter by key from a config dict. Raise InvalidConfigException if it does\n not exist or its value is not a bool.\"\"\"\n value = _get_required_param(key, config_dict)\n if not isinstance(value, bool):\n raise InvalidConfigException(f\"Parameter '{key}' should be a bool. Is {type(value)}\")\n return value\n\n\ndef get_optional_bool_param(key: str, config_dict: Dict[str, Any]) -> Optional[bool]:\n \"\"\"Get a bool parameter by key from a config dict. Return None if it does not exist,\n raise InvalidConfigException if its value is not a bool.\"\"\"\n value = _get_optional_param(key, config_dict)\n if value is None:\n return None\n if not isinstance(value, bool):\n raise InvalidConfigException(f\"Parameter '{key}' should be a bool. Is {type(value)}\")\n return value\n\n\ndef get_optional_str_param(key: str, config_dict: Dict[str, Any]) -> Optional[str]:\n \"\"\"Get a str parameter by key from a config dict. Return None if it does not exist,\n raise InvalidConfigException if its value is not a bool.\"\"\"\n value = _get_optional_param(key, config_dict)\n if value is None:\n return None\n if not isinstance(value, str):\n raise InvalidConfigException(f\"Parameter '{key}' should be a str. Is {type(value)}\")\n return value\n\n\ndef get_required_int_param(key: str, config_dict: Dict[str, Any]) -> int:\n \"\"\"Get a int parameter by key from a config dict. Raise InvalidConfigException if it does\n not exist or its value is not a int.\"\"\"\n value = _get_required_param(key, config_dict)\n if not isinstance(value, int):\n raise InvalidConfigException(f\"Parameter '{key}' should be a int. Is {type(value)}\")\n return value\n\n\ndef get_required_str_param(key: str, config_dict: Dict[str, Any]) -> str:\n \"\"\"Get a str parameter by key from a config dict. Raise InvalidConfigException if it does\n not exist or its value is not a str.\"\"\"\n value = _get_required_param(key, config_dict)\n if not isinstance(value, str):\n raise InvalidConfigException(f\"Parameter '{key}' should be a str. Is {type(value)}\")\n return value\n\n\ndef get_required_section(key: str, config_dict: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Get a section from a config dict. Raise InvalidConfigException if it does not exist.\"\"\"\n value = config_dict.get(key)\n if value is None:\n raise InvalidConfigException(f\"Missing section '{key}'\")\n if not isinstance(value, dict):\n raise InvalidConfigException(f\"'{key}' does not appear to be a section. Is {type(value)}\")\n return value\n\n\ndef get_optional_section(key: str, config_dict: Dict[str, Any]) -> Optional[Dict[str, Any]]:\n \"\"\"Get a section from a config dict. Return None if it does not exist.\"\"\"\n value = config_dict.get(key)\n if value is not None:\n if not isinstance(value, dict):\n raise InvalidConfigException(\n f\"'{key}' does not appear to be a section. Is {type(value)}\"\n )\n return value\n\n\n@dataclass(frozen=True)\nclass AccessConfig:\n \"\"\"Access configuration class\"\"\"\n\n accessor: Accessor\n\n @classmethod\n def from_dict(cls: Type[\"AccessConfig\"], config_dict: Dict[str, Any]) -> \"AccessConfig\":\n \"\"\"Build an AccessConfig from a dict\"\"\"\n cache_creds = get_optional_bool_param(\"cache_creds\", config_dict)\n if cache_creds is not None:\n accessor = Accessor.from_dict(config_dict, cache_creds=cache_creds)\n else:\n accessor = Accessor.from_dict(config_dict)\n return AccessConfig(accessor=accessor)\n\n\n@dataclass(frozen=True)\nclass ScanConfig:\n \"\"\"Scan configuration class\"\"\"\n\n accounts: Tuple[str, ...]\n regions: Tuple[str, ...]\n scan_sub_accounts: bool\n preferred_account_scan_regions: Tuple[str, ...]\n single_account_mode: bool\n scan_lambda_tcp_keepalive: Optional[bool] = False\n\n @classmethod\n def from_dict(cls: Type[\"ScanConfig\"], config_dict: Dict[str, Any]) -> \"ScanConfig\":\n \"\"\"Build a ScanConfig from a dict\"\"\"\n preferred_account_scan_regions = get_required_list_param(\n \"preferred_account_scan_regions\", config_dict\n )\n accounts = get_required_list_param(\"accounts\", config_dict)\n regions = get_required_list_param(\"regions\", config_dict)\n scan_sub_accounts = get_required_bool_param(\"scan_sub_accounts\", config_dict)\n if accounts:\n single_account_mode = False\n else:\n single_account_mode = True\n if not accounts:\n sts_client = boto3.client(\"sts\")\n account_id = sts_client.get_caller_identity()[\"Account\"]\n accounts = (account_id,)\n\n return ScanConfig(\n accounts=accounts,\n regions=regions,\n scan_sub_accounts=scan_sub_accounts,\n preferred_account_scan_regions=preferred_account_scan_regions,\n single_account_mode=single_account_mode,\n )\n\n\n@dataclass(frozen=True)\nclass ConcurrencyConfig:\n \"\"\"Concurrency configuration class\"\"\"\n\n max_account_scan_threads: int\n max_accounts_per_thread: int\n max_svc_scan_threads: int\n\n @classmethod\n def from_dict(\n cls: Type[\"ConcurrencyConfig\"], config_dict: Dict[str, Any]\n ) -> \"ConcurrencyConfig\":\n \"\"\"Build a ConcurrencyConfig from a dict\"\"\"\n max_account_scan_threads = get_required_int_param(\"max_account_scan_threads\", config_dict)\n max_accounts_per_thread = get_required_int_param(\"max_accounts_per_thread\", config_dict)\n max_svc_scan_threads = get_required_int_param(\"max_svc_scan_threads\", config_dict)\n return ConcurrencyConfig(\n max_account_scan_threads=max_account_scan_threads,\n max_accounts_per_thread=max_accounts_per_thread,\n max_svc_scan_threads=max_svc_scan_threads,\n )\n\n\n@dataclass(frozen=True)\nclass NeptuneConfig:\n \"\"\"Neptune configuration class\"\"\"\n\n host: str\n port: int\n region: str\n iam_role_arn: Optional[str] = \"\"\n graph_load_sns_topic_arn: Optional[str] = \"\"\n ssl: Optional[bool] = True\n use_lpg: Optional[bool] = False\n iam_credentials_provider_type: Optional[str] = \"\"\n auth_mode: Optional[str] = \"\"\n\n @classmethod\n def from_dict(cls: Type[\"NeptuneConfig\"], config_dict: Dict[str, Any]) -> \"NeptuneConfig\":\n \"\"\"Build a NeptuneConfig from a dict\"\"\"\n host = get_required_str_param(\"host\", config_dict)\n port = get_required_int_param(\"port\", config_dict)\n region = get_required_str_param(\"region\", config_dict)\n ssl = get_optional_bool_param(\"ssl\", config_dict)\n use_lpg = get_optional_bool_param(\"use_lpg\", config_dict)\n iam_role_arn = get_optional_str_param(\"iam_role_arn\", config_dict)\n auth_mode = get_optional_str_param(\"auth_mode\", config_dict)\n graph_load_sns_topic_arn = get_optional_str_param(\"graph_load_sns_topic_arn\", config_dict)\n return NeptuneConfig(\n host=host,\n port=port,\n region=region,\n ssl=ssl,\n use_lpg=use_lpg,\n iam_role_arn=iam_role_arn,\n graph_load_sns_topic_arn=graph_load_sns_topic_arn,\n auth_mode=auth_mode,\n )\n\n\n@dataclass(frozen=True)\nclass Config:\n \"\"\"Top level configuration class\"\"\"\n\n artifact_path: str\n pruner_max_age_min: int\n graph_name: str\n access: AccessConfig\n concurrency: ConcurrencyConfig\n scan: ScanConfig\n neptune: Optional[NeptuneConfig] = None\n\n def __post_init__(self) -> None:\n if (\n self.scan.single_account_mode\n and not self.scan.scan_sub_accounts\n and self.access.accessor.multi_hop_accessors\n ):\n raise InvalidConfigException(\"Accessor config not supported for single account mode\")\n if is_s3_uri(self.artifact_path):\n bucket, key_prefix = parse_s3_uri(self.artifact_path)\n if key_prefix is not None:\n raise InvalidConfigException(\n f\"S3 artifact_path should be s3://, no key - got {self.artifact_path}\"\n )\n\n @classmethod\n def from_dict(cls: Type[\"Config\"], config_dict: Dict[str, Any]) -> \"Config\":\n \"\"\"Build a Config from a dict\"\"\"\n artifact_path = get_required_str_param(\"artifact_path\", config_dict)\n pruner_max_age_min = get_required_int_param(\"pruner_max_age_min\", config_dict)\n graph_name = get_required_str_param(\"graph_name\", config_dict)\n\n scan_dict = get_required_section(\"scan\", config_dict)\n try:\n scan = ScanConfig.from_dict(scan_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"{str(ice)} in section 'scan'\")\n\n concurrency_dict = get_required_section(\"concurrency\", config_dict)\n try:\n concurrency = ConcurrencyConfig.from_dict(concurrency_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"{str(ice)} in section 'concurrency'\")\n\n access_dict = get_required_section(\"access\", config_dict)\n try:\n access = AccessConfig.from_dict(access_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"{str(ice)} in section 'access'\")\n\n neptune_dict = get_optional_section(\"neptune\", config_dict)\n neptune: Optional[NeptuneConfig] = None\n if neptune_dict:\n try:\n neptune = NeptuneConfig.from_dict(neptune_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"{str(ice)} in section 'neptune'\")\n return Config(\n artifact_path=artifact_path,\n pruner_max_age_min=pruner_max_age_min,\n graph_name=graph_name,\n access=access,\n concurrency=concurrency,\n scan=scan,\n neptune=neptune,\n )\n\n @classmethod\n def from_path(cls: Type[\"Config\"], path: str) -> \"Config\":\n \"\"\"Load a Config from an s3 uri or a file\"\"\"\n if is_s3_uri(path):\n return cls.from_s3(s3_uri=path)\n return cls.from_file(filepath=Path(path))\n\n @classmethod\n def from_file(cls: Type[\"Config\"], filepath: Path) -> \"Config\":\n \"\"\"Load a Config from a file\"\"\"\n with open(filepath, \"r\") as fp:\n config_str = fp.read()\n config_dict = dict(toml.loads(config_str))\n try:\n return cls.from_dict(config_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"Error in conf file {filepath}: {str(ice)}\")\n\n @classmethod\n def from_s3(cls: Type[\"Config\"], s3_uri: str) -> \"Config\":\n \"\"\"Load a Config from an s3 object\"\"\"\n bucket, key = parse_s3_uri(s3_uri)\n s3_client = boto3.client(\"s3\")\n resp = s3_client.get_object(Bucket=bucket, Key=key,)\n config_str = resp[\"Body\"].read().decode(\"utf-8\")\n config_dict = dict(toml.loads(config_str))\n try:\n return cls.from_dict(config_dict)\n except InvalidConfigException as ice:\n raise InvalidConfigException(f\"Error in conf file {s3_uri}: {str(ice)}\")\n","sub_path":"altimeter/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":12652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"532354711","text":"import nltk\nimport re\nimport string\nfrom constants import contractions\nfrom guess_language import guess_language\nfrom nltk.tokenize import RegexpTokenizer \n\n\nsentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')\ntext_tokenizer = RegexpTokenizer(\"[a-zA-Z']+|[^\\w\\s]{2,}|[\\d]+|[\\d\\-\\+]{2,}\")\n\n\ndef replace_contractions(x):\n for k,v in contractions.iteritems():\n x = x.replace(k, v)\n return x\n\n\ndef guess_lang(text):\n try:\n return guess_language(text.decode('utf-8'))\n except:\n return 'UNKOWN'\n\n\ndef tokenize_text(text_str, ex_word_set, pattern, control):\n MIN_N = 1\n MAX_N = 3\n text_str = text_str.lower()\n text_str = replace_contractions(text_str)\n text_str = text_str.replace(',', '.')\n text_str = ''.join([c for c in text_str if c in control])\n text_str = pattern.sub(' ', text_str)\n text_sentences = sentence_detector.tokenize(text_str) \n n_grams = []\n for sentence in text_sentences:\n sentence_tokens = text_tokenizer.tokenize(sentence)\n sentence_tokens = [w for w in sentence_tokens if len(w)>1]\n sentence_tokens = [w for w in sentence_tokens if not w in ex_word_set]\n n_tokens = len(sentence_tokens)\n for i in xrange(n_tokens):\n for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):\n n = sentence_tokens[i:j]\n #n = [re.sub(r'[^\\s](.)\\1\\1\\1+ ', r' \\1\\1\\1 ',w) for w in n]\n n_grams.append(' '.join(n))\n n_grams = list(set(n_grams))\n return n_grams\n\n\ndef tokenize_chain(review_chain, ex_word_set, pattern, control):\n p = re.compile(r'<>')\n review_chain = p.split(review_chain)\n text_t = []\n for i, val in enumerate(review_chain):\n text_t = text_t + tokenize_text(val, ex_word_set, pattern, control) \n return set(text_t)\n","sub_path":"audience/demographics-review/lib/text_processing.py","file_name":"text_processing.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"92860907","text":"from models.schema import *\nimport os,time,random\nfrom flask_mail import Mail,Message\nfrom datetime import datetime,timedelta\nfrom flask import Flask, render_template, request,url_for ,redirect\n\napp = Flask(__name__)\napp.secret_key = 'my-secret-key'\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n@app.before_first_request\ndef create_table():\n\tdb.create_all()\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n@app.route('/subscribe')\ndef subscribe():\n\treturn render_template('subscribe.html')\n\n@app.route('/result',methods=['GET','POST'])\ndef result():\n\tpresTime=datetime.today()\n\tuser = User(name=request.form['username'],\n\t\t\t\temail=request.form['email_id'],\n\t\t\t\tstart_datetime=presTime,\n\t\t\t\tinterval=request.form['time'],\n\t\t\t\tnext_feed=presTime+timedelta(minutes=int(request.form['time'])),\n\t\t\t\tsubscribe=True,\n\t\t\t\ttag=request.form['tag'],\n\t)\n\tdb.session.add(user)\n\tdb.session.commit()\n\treturn render_template('result.html')\t\n\n@app.route('/send')\ndef send():\n\treturn \"thank you\"\n\n@app.route('/admin/')\ndef admin():\n\treturn render_template('adminSignin.html')\n\n@app.route('/admin/j_acegi_security_check',methods=['GET','POST'])\ndef Check():\n\tif request.form['j_username']=='admin' and request.form['j_password']=='admin':\n\t\tdata=Feed.query.all()\n\t\treturn render_template('db_table.html',data=data)\n\telse:\n\t\treturn render_template('adminSignin.html',info=\"please check username or password\")\n\n@app.route('/save',methods=['GET','POST'])\t\ndef add():\n\topt=request.form['opt']\n\tif opt == 'add':\n\t\ttest = Feed.query.filter_by(feed_links=request.form['feedLinks']).all() #Data.execute(\"\"\"select * from feed where feed_links = ?\"\"\",[request.form['feedLinks']])\n\t\tif len(test) == 0:\n\t\t\tfeed = Feed(feed_links=request.form['feedLinks'],\n\t\t\t\t\t\ttags=request.form['tags'],\n\t\t\t\t\t\ttitles=request.form['titles'],\n\t\t\t\t\t\tsummary=request.form['summary'],\n\t\t\t)\n\t\t\tdb.session.add(feed)\n\t\t\tinfo = \"new feed inserted\"\n\t\telse:\n\t\t\treturn render_template('db_table.html',info=\"feed link already existing\",data=Feed.query.all()) #retrive(Data,'techfeeds'))\n\n\telif opt=='delete':\n\t\tFeed.query.filter_by(feed_no=request.form['feedNo']).delete()\n\t\tinfo = \"feed deleted\"\n\n\telif opt=='update':\n\t\tfeed = Feed.query.filter_by(feed_no=request.form['feedNo']).first()\n\t\tfeed.feed_links = request.form['feedLinks']\n\t\tfeed.tags = request.form['tags']\n\t\tfeed.titles = request.form['titles']\n\t\tfeed.summary = request.form['summary']\n\t\tdb.session.add(feed)\n\t\tinfo = \"feed updated\"\n\tdb.session.commit()\n\treturn render_template('db_table.html',data=Feed.query.all(),info=info)\n\nif __name__== \"__main__\":\n\tfrom db import db\n\tdb.init_app(app)\n\tapp.run(port=5000)\n","sub_path":"guest_book.py","file_name":"guest_book.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"400194839","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n学习关键字:\r\npip3 install selenium 安装selenium\r\nselenium 保存iframe中文\r\nselenium js\r\n\"\"\"\r\nfrom selenium import webdriver\r\nfrom storage import baidu_cloud as bdc\r\nfrom time import sleep\r\nfrom lxml import etree\r\nimport csv\r\n\r\n\r\n'''一、设置浏览器参数并打开一个新的浏览器窗口\r\nsudo mv chromedriver /usr/bin/ 移动到/usr/bin/文件夹下(复制则将mv改为cp),不需要加上执行权限 chmod +x chromedriver\r\n\r\n'''\r\ndef chrome():\r\n chrome_options = webdriver.ChromeOptions()#继承源码中的类,详情搜索:selenium配置chrome选项\r\n chrome_options.add_extension(bdc.externalPaths[0]+\"/can_google.crx\")\r\n browser = webdriver.Chrome(options=chrome_options)\r\n return browser \r\n#c=chrome()\r\n#c.get(\"http://360.hao245.com\")#当网页完全打开加载完成时才会继续下一步\r\n \r\n\r\nclass test(object):#虽然括号里没有写参数,但是建立实例时要把init中的参数都传入\r\n def __init__(self,url):\r\n self.url=\"https://www.baidu.com\"#\"http://360.hao245.com\"\r\n def a_chrome(self,url2):#加上self才能使用init中的参数\r\n chrome_options = webdriver.ChromeOptions()#继承源码中的类,详情搜索:selenium配置chrome选项\r\n chrome_options.add_extension(bdc.externalPaths[0]+\"/can_google.crx\")\r\n browser = webdriver.Chrome(options=chrome_options)\r\n #return browser.get(url)\r\n browser.get(self.url)\r\n sleep(10)\r\n browser.get(url2) \r\n#scan=test(\"随便输入一个,但必须有对应的参数\")\r\n#a=scan.a_chrome(\"https://pan.baidu.com/\")\r\n#b=scan.a_chrome(\"https://www.baidu.com\")#会新打开窗口\r\n\r\n'''二、登陆上之后可以���下边做任意控制操作\r\n在火狐浏览器上安装katalon recorder,并录制导出动作,注意导出时可以选择各种程序语言环境、如选择python2'''\r\ndef test_question_ans():#目前只能操控固定的窗口\r\n url=\"https://nexam.cmbc.com.cn/wis18/usermain/paper/userpaper.answeruserpapercurr.flow?sid=5851745584847088\"\r\n url=\"https://nexam.cmbc.com.cn/wis18/userpaper.viewuserhispaperqueslist.flow?p_id=6094126582324386&trys=2\"\r\n #\"https://nexam.cmbc.com.cn/wis18/usermain/paper/userpaper.answeruserpapercurr.flow?sid=5851745584847088\"\r\n browser=chrome()\r\n browser.get(url)\r\n #对于嵌套frame的网页,要先转换到相应层的frame、然后处理里边包含的html\r\n browser.switch_to.frame(0)#通过index索引号逐个尝试目标信息在哪一层,\r\n #每次都要重新打开首页 \r\n for i in range(0,100):#开始下载目标信息保存到html文件,用于后续提取\r\n sleep(0.5)\r\n with open(\"question_ans/probe12_%s.html\"%i,\"w\") as f:\r\n f.write(browser.page_source) \r\n browser.find_element_by_xpath('//*[@id=\"next\"]').click() \r\n #后续从离线网页提取信息,\r\n questions=[]\r\n for i in range(2,5):\r\n for j in range(100):\r\n htmlfile=open(\"/media/bdai/LENOVO/Databases/question_ans/probe%s_%s.html\"%(i,j),'r')\r\n htmlhandle = htmlfile.read()\r\n html_data=etree.HTML(htmlhandle,parser=etree.HTMLParser(encoding='utf-8')) \r\n question_ans=html_data.xpath('//*[@id=\"maindiv\"]/table/tbody/tr/td/table/tbody/tr[2]/td/div/table/tbody/tr/th[3]/div/form/table[2]/tbody/tr/th/table/tbody/tr/th/div//text()')\r\n questions.append(question_ans)\r\n #并保存到csv文件中 \r\n questions_file = open(\"test.csv\",'w')\r\n writer = csv.writer(questions_file)\r\n writer.writerows(questions)\r\n questions_file.close()\r\n\r\n'''三、无框架的情况'''\r\nbrowser=chrome()\r\nurl=\"https://nexam.cmbc.com.cn/wis18/userpaper.viewuserhispaperqueslist.flow?p_id=6094126582324386&trys=10\"\r\nbrowser.get(url)\r\n\r\nquestions=[]\r\nfor i in range(0, 155): # 开始下载目标信息保存到html文件,用于后续提取\r\n sleep(0.5)\r\n questions.append( browser.find_element_by_xpath('//*[@id=\"mainfrm\"]/table[1]/tbody/tr[3]/td/table/tbody/tr[2]'\r\n ).get_attribute('textContent') )\r\n browser.find_element_by_xpath('//*[@id=\"mainfrm\"]/table[2]/tbody/tr/td/p/input[2]').click()\r\n\r\n#并保存到csv文件中\r\nquestions_file = open(\"test.csv\",'w')\r\nwriter = csv.writer(questions_file)\r\nwriter.writerow(questions)\r\nquestions_file.close()","sub_path":"data/selenium_ubuntu_tiku.py","file_name":"selenium_ubuntu_tiku.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"320850220","text":"from PyQt5.QtWidgets import QWidget, QTabWidget,QVBoxLayout, QCheckBox, QButtonGroup, QLabel, QTableWidget, QHeaderView\nfrom PyQt5.QtGui import QPixmap, QIcon, QFont\nfrom PyQt5.QtCore import Qt\nfrom AddFunctionWidget import AddFunctionWidget\nfrom FunctionPlotWidget import FunctionPlotWidget\nfrom SolidRevWidget import SolidRevWidget\nfrom CalculateVolumeWidget import CalculateVolumeWidget\nfrom GlobalVariables import GlobalVariables\nfrom sympy import latex\nfrom LatexFormulas import createLatexFormula\n\nclass MainTableWidget(QWidget): \n \n def __init__(self, parent): \n super(QWidget, self).__init__(parent)\n \n self.layout = QVBoxLayout(self)\n self.layout.setDirection(QVBoxLayout.Direction.LeftToRight)\n \n # Initialize tab screen\n self.tabs = QTabWidget()\n self.tab1 = AddFunctionWidget(self)\n self.tab2 = FunctionPlotWidget(self)\n self.tab3 = SolidRevWidget(self)\n self.tab4 = CalculateVolumeWidget(self)\n \n # Array of indices of tabs with plots (for making updates when switching to them)\n self.tabsWithPlots = [1,2,3]\n \n # Function whenever a new tab is clicked\n self.tabs.currentChanged.connect(self.updatePlot)\n \n # Add tabs\n self.tabs.addTab(self.tab1,\"Agrega Funciones\")\n self.tabs.addTab(self.tab2,\"Ver Función\")\n self.tabs.addTab(self.tab3,\"Ver Sólido de Revolución\")\n self.tabs.addTab(self.tab4,\"Cálculo de Volumen\")\n \n # Add tabs to widget \n self.layout.addWidget(self.tabs)\n self.tableWidget = None\n \n #self.checkBoxLayout = QVBoxLayout()\n self.checkBoxGroup = QButtonGroup()\n self.updateListWidget()\n \n # Function to be used for function titles\n self.functionTitleFont = QFont()\n self.functionTitleFont.setBold(True)\n self.functionTitleFont.setPointSize(14)\n \n # Function for updatting math functions widget when new functions are added\n def updateListWidget(self, addCheckBox = False):\n \n # Delete existing layouts\n if(self.tableWidget != None):\n self.layout.removeWidget(self.tableWidget)\n \n listLength = len(GlobalVariables.mathFunctionsList)\n # Row added for each function, and row added for each function part\n rowAmount = listLength\n \n for mathFunction in GlobalVariables.mathFunctionsList:\n rowAmount += len(mathFunction)\n \n \n self.tableWidget = QTableWidget(rowAmount, 3, self)\n header = self.tableWidget.horizontalHeader() \n header.setSectionResizeMode(0, QHeaderView.Stretch)\n header.setSectionResizeMode(1, QHeaderView.ResizeToContents)\n header.setSectionResizeMode(2, QHeaderView.ResizeToContents)\n \n rowIndex = 0\n for i in range(listLength):\n mathFunction = GlobalVariables.mathFunctionsList[i]\n \n rowLabel = QLabel()\n self.tableWidget.setSpan(rowIndex, 0, 1, 2) # Mix 2 columns for function title\n \n rowLabel.setText(\"Función \" + str(i+1))\n rowLabel.setFont(self.functionTitleFont)\n rowLabel.setAlignment(Qt.AlignCenter)\n self.tableWidget.setCellWidget(rowIndex, 0, rowLabel) # Add name of this function as a whole\n self.tableWidget.setSpan(rowIndex, 2, len(mathFunction) + 1, 1) # Mix rows depending on number of parts of this function\n \n # Add Checkbox for this function\n newCheckBox = QCheckBox(\"F\" + str(i+1))\n newCheckBox.released.connect(self.selectFunction)\n \n # Set first checkbox to be on\n if(listLength==1):\n newCheckBox.setChecked(True)\n GlobalVariables.selectedIndex = 0\n \n # Set the currently selected Checkbox\n if(GlobalVariables.selectedIndex == i):\n newCheckBox.setChecked(True)\n \n self.tableWidget.setCellWidget(rowIndex, 2, newCheckBox)\n self.checkBoxGroup.addButton(newCheckBox, i)\n \n \n rowIndex += 1\n\n for j in range(rowIndex, rowIndex + len(mathFunction)):\n part = mathFunction[j-rowIndex]\n createLatexFormula(r'$f(x) = '+ latex(part.f_expression) +'$', 'equations/function_part_' + str(j), 90)\n createLatexFormula(r'$ x \\in ('+str(part.x0)+', '+str(part.x1)+')$', 'equations/interval_' + str(j), 90)\n \n partLabel = QLabel()\n partLabel.setPixmap(QPixmap('equations/function_part_' + str(j)))\n self.tableWidget.setCellWidget(j, 0, partLabel)\n \n partInterval = QLabel()\n partInterval.setPixmap(QPixmap('equations/interval_' + str(j)))\n self.tableWidget.setCellWidget(j, 1, partInterval)\n \n \n rowIndex += len(mathFunction)\n \n self.tableWidget.setMaximumWidth(0.4 * GlobalVariables.screenWidth)\n self.layout.addWidget(self.tableWidget)\n self.setLayout(self.layout)\n\n\n\n\n # Function to set index of the selected function\n def selectFunction(self):\n GlobalVariables.selectedIndex = self.checkBoxGroup.checkedId()\n if(self.tabs.currentIndex() in self.tabsWithPlots):\n self.tabs.currentWidget().updatePlot()\n\n # Function to update Plot of the current tab (must have at least one function added)\n def updatePlot(self, index):\n if(index in self.tabsWithPlots and GlobalVariables.selectedIndex != -1):\n self.tabs.widget(index).updatePlot()\n","sub_path":"MainTableWidget.py","file_name":"MainTableWidget.py","file_ext":"py","file_size_in_byte":5850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"584885009","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n__author__ = 'ghost'\n\nimport tornado.web\nfrom app import router\nfrom app.helper import BaseAuthHandler\nfrom app.models.auth import User\n\n\n\n@router.Route('/auth/login')\nclass AuthLoginHandler(BaseAuthHandler):\n\n def get(self, *args, **kwargs):\n\n html = ('
'\n '
\r\n

{today_html}

\r\n

{scripture_html}

\r\n

{bodyText_html}

\r\n

{title_html}

\r\n
\r\n \r\n \r\n

\r\n

\r\n
\r\n
    \r\n {listStr_html}\r\n
\r\n\r\n\r\n'''.format(today_html=RealDay, scripture_html=scripture, bodyText_html=bodyText, title_html=title, form_pageId=pageId, form_title=title, form_default_meditation=meditation, listStr_html=view.getDir()))\r\n","sub_path":"htdocs/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"433007039","text":"\n\nfrom xai.brain.wordbase.nouns._pity import _PITY\n\n#calss header\nclass _PITYING(_PITY, ):\n\tdef __init__(self,): \n\t\t_PITY.__init__(self)\n\t\tself.name = \"PITYING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"pity\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_pitying.py","file_name":"_pitying.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"185957035","text":"import datetime\n\nfrom global_utils.connect import TelegramConnection\nfrom global_utils.save import MessageSaver\nfrom telethon.tl.functions.messages import (GetHistoryRequest)\nfrom telethon.tl.types import (PeerChannel)\n\ntoday = str(datetime.datetime.now())[:10]\n\n\nclass TelegramPostCollector:\n def __init__(self,finish_date_time=today):\n self.limit = 100\n self.telegram_connection = TelegramConnection()\n self.client = None\n self.finish_date_time = finish_date_time\n\n async def get_client(self):\n return await self.telegram_connection.get_client()\n\n def close_client_session(self):\n self.client.session.close()\n\n async def get_channel(self, channel_identifier):\n if channel_identifier.isdigit():\n entity = PeerChannel(int(channel_identifier))\n else:\n entity = channel_identifier\n channel = await self.client.get_entity(entity)\n return channel\n\n async def collect_posts(self,channel_identifier_list):\n result = []\n url = \"http://194.5.192.130/telegram_files/{date}/{channel_addr}.csv\"\n for channel_identifier in channel_identifier_list:\n success = await self._collect_post(channel_identifier)\n if success:\n result.append(url.format(\n date=str(datetime.datetime.date(datetime.datetime.now())),\n channel_addr=channel_identifier.split('/')[\n -1]))\n return result\n\n async def _collect_post(self, channel_identifier):\n try:\n self.client = await self.get_client()\n message_saver = MessageSaver(channel_identifier)\n channel = await self.get_channel(channel_identifier)\n offset_id = 0\n total_message = 0\n while True:\n history = await (\n self.client(\n GetHistoryRequest(\n peer=channel,\n offset_id=offset_id,\n offset_date=None,\n add_offset=0,\n limit=100,\n max_id=0,\n min_id=0,\n hash=0\n )\n )\n )\n if not history.messages or len(history.messages) == 0:\n break\n messages = history.messages\n offset_id = messages[len(messages) - 1].id\n total_message += len(messages)\n print(\"{} message fetched.\".format(total_message))\n messages_before_finish_datetime = []\n finish = False\n for message in messages:\n if self.finish_date_time is not None and str(message.date)[\n :10] >= self.finish_date_time: # it should go to upper layer\n messages_before_finish_datetime.append(message)\n else:\n finish = True\n break\n message_saver.save_messages(messages_before_finish_datetime)\n if finish:\n return True\n except Exception as e:\n print(e)\n return False\n","sub_path":"gathering/gathering_posts.py","file_name":"gathering_posts.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345823518","text":"import os, sys\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\ngrandparentdir = os.path.dirname(parentdir)\nsys.path.append(grandparentdir)\nfrom Py5 import Py5\nfrom Vector import Vector\npy5 = Py5()\n\nclass Mover():\n def __init__(self, py5inst, m, x, y):\n self.py5 = py5inst\n self.location = Py5.create_vector(x, y)\n self.velocity = Py5.create_vector(0, 0)\n self.acceleration = Py5.create_vector(0, 0)\n self.mass = m\n\n def apply_force(self, force):\n f = Vector.static_div(force, self.mass)\n self.acceleration.add(f)\n\n def check_edges(self):\n if self.location.x > self.py5.width:\n self.location.x = self.py5.width\n self.velocity.x *= -1\n elif self.location.x < 0:\n self.velocity.x *= -1\n self.location.x = 0\n\n if self.location.y > self.py5.height:\n self.location.y = self.py5.height\n self.velocity.y *= -1\n\n def update(self):\n self.velocity.add(self.acceleration)\n self.location.add(self.velocity)\n self.acceleration.mult(0)\n\n def display(self):\n self.py5.stroke(0)\n self.py5.fill(175)\n self.py5.ellipse(self.location.x, self.location.y, self.mass*16, self.mass*16)\n\nmovers = []\n\ndef setup():\n py5.create_screen(640, 360)\n for i in range(100):\n mass = Py5.random_float_range(0.1, 5)\n movers.append(Mover(py5, mass, 0, 0))\n\n@py5.draw\ndef draw():\n py5.background(255)\n\n wind = Vector(0.01, 0)\n gravity = Vector(0, 0.1)\n\n for m in movers:\n m.apply_force(wind)\n m.apply_force(gravity)\n m.update()\n m.check_edges()\n m.display()\n\nsetup()\ndraw()\n","sub_path":"NOC/Chapter 2/2_2.py","file_name":"2_2.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"418393128","text":"'''\n# Sample code to perform I/O:\n\nname = input() # Reading input from STDIN\nprint('Hi, %s.' % name) # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n'''\n\n# Write your code here\nn = int(input())\nm = int(input())\nfor _ in range(n):\n numc=0\n namc=\"\"\n for i in range(m):\n nam,num=input().split()\n c = 0\n for j in range(len(num)):\n if(num[j]==','):\n c=c+1\n if(c>=numc):\n numc=c\n namc=nam\n print(namc,numc)\n\n","sub_path":"Breaking Bad.py","file_name":"Breaking Bad.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"385852525","text":"def split(file, delim):\n f = open(file, \"r\")\n return [int(x.strip()) for x in f.read().split(delim)]\n\ndef process(ops, noun, verb):\n newOps = ops[:]\n newOps[1] = noun\n newOps[2] = verb\n for i in range(0, len(newOps), 4):\n x = newOps[i]\n if x in [1,2]:\n a = newOps[i+1]\n b = newOps[i+2]\n c = newOps[i+3]\n if x == 1:\n newOps[c] = newOps[a] + newOps[b]\n if x == 2:\n newOps[c] = newOps[a] * newOps[b]\n if x == 99:\n break\n return newOps\n\nops = split(\"02.txt\", \",\")\n\nfor i in range(100):\n for j in range(100):\n if process(ops, i, j)[0] == 19690720:\n print(str(i)+str(j))\n break","sub_path":"02b.py","file_name":"02b.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"222233338","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.views import generic\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom django.contrib.auth import authenticate, login, logout\n\n# Create your views here.\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import ProjectRisk\nfrom .forms import ProjectRiskForm\nfrom project.models import Project\n\n@login_required\ndef project_risk_new(request,project_id):\n project_risk = ProjectRisk()\n project_risk.project = Project.objects.get(pk=project_id)\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = ProjectRiskForm(instance=project_risk, data=request.POST)\n # check whether it's valid:\n if form.is_valid():\n form.save()\n\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = ProjectRiskForm(instance=project_risk)\n\n previous_path = get_previous_url(request,1)\n return render(request, 'project_risk/project_risk_new.html', {'form':form,'previousPath': previous_path})\n\n@login_required\ndef project_risk_edit(request, project_id, project_risk_id):\n project_risk = get_object_or_404(ProjectRisk, pk=project_risk_id)\n project = Project.objects.get(pk=project_id)\n #SAVE METHOD#\n if request.method == 'POST':\n form = ProjectRiskForm(instance=project_risk, data=request.POST)\n if form.is_valid():\n obj = form.save(commit=False)\n obj.project = project\n obj.save()\n else:\n form = ProjectRiskForm(instance=project_risk)\n\n previous_path =get_previous_url(request,2) \n return render(request, 'project_risk/project_risk_edit.html', {'form':form,'previousPath': previous_path})\n\n\ndef get_previous_url(request,stepback):\n full_path = request.get_full_path()\n previous_index_pos = len(full_path) - find_nth(full_path[::-1],'/',stepback)\n previous_url = full_path[:previous_index_pos-1] + \"/gate\"\n\n return previous_url\n\ndef find_nth(haystack, needle, n):\n start = haystack.find(needle)\n while start >= 0 and n > 1:\n start = haystack.find(needle, start+len(needle))\n n -= 1\n return start\n","sub_path":"mysite/project_risk/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"529375043","text":"\nimport webapp2, cgi, jinja2, os, re\nfrom google.appengine.ext import db\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir))\n\nclass Post(db.Model):\n title = db.StringProperty(required = True)\n posttext = db.TextProperty(required = True )\n created = db.DateTimeProperty(auto_now_add = True)\n\n\n\nclass BlogHandler(webapp2.RequestHandler):\n def get(self):\n posts = db.GqlQuery(\"SELECT * FROM Post ORDER BY created DESC LIMIT 5\")\n t = jinja_env.get_template(\"blog.html\")\n content = t.render(posts=posts)\n self.response.write(content)\n\n\n\nclass NewPostHandler(webapp2.RequestHandler):\n def get(self):\n t = jinja_env.get_template(\"newpost.html\")\n content = t.render()\n self.response.write(content)\n\n def post(self):\n title = self.request.get(\"title\")\n posttext = self.request.get(\"posttext\")\n\n if title and posttext:\n p = Post(title = title, posttext = posttext)\n p.put()\n post = str(p.key().id())\n self.redirect(\"/blog/\" + post)\n else:\n t = jinja_env.get_template(\"newpost.html\")\n content = t.render(title = title, posttext = posttext, error = \"Both a title and post text are required\")\n self.response.write(content)\n\nclass ViewPostHandler(webapp2.RequestHandler):\n def get(self, id):\n id = int(id)\n post = Post.get_by_id(id)\n if post:\n content = \"

\" + post.title + \"

\" + \"

\" + post.posttext + \"

\" + \"
\" + 'Go back to blog'\n self.response.write(content)\n else:\n content = \"

\" + \"There is no post with this ID\" + \"

\"\n self.response.write(content)\n\napp = webapp2.WSGIApplication([\n ('/blog', BlogHandler),\n ('/', BlogHandler),\n ('/newpost', NewPostHandler),\n webapp2.Route('/blog/', ViewPostHandler)\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"116673842","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom .models import User\nfrom profiles.models import manager, tenant\n\n@receiver(post_save, sender=User)\ndef create_profile(sender, instance, created, **kwargs):\n if created:\n if instance.is_tenant==True:\n tenant.objects.create(user=instance)\n elif instance.is_tenant==False:\n manager.objects.create(user=instance)\n\n\n@receiver(post_save, sender=User)\ndef save_profile(sender, instance, **kwargs):\n if instance.is_tenant==True:\n instance.tenant.save()\n elif instance.is_tenant==False:\n instance.manager.save()\n","sub_path":"eitroom_/accounts/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"20936127","text":"'''\nCreated on 4/2/2015\n\n@author: Psilocibino\n'''\nimport cv2\nimport numpy as np\n\ndef get_hist(img,msk):\n h = np.zeros((300,256,3))\n b,g,r = cv2.split(img)\n bins = np.arange(256).reshape(256,1)\n color = [(255,0,0),(0,255,0),(0,0,255)]\n hist_item = []\n \n for item,col in zip([b,g,r],color):\n hist_item = cv2.calcHist([item],[0],msk,[256],[0,255])\n cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)\n hist=np.int32(np.around(hist_item))\n pts = np.column_stack((bins,hist))\n cv2.polylines(h,[pts],False,col)\n \n h=np.flipud(h)\n return h, hist_item\n\n#Cuanto mas cercano a 0 mas parecido tendran\ndef compare_hist(img1,msk1,img2,msk2): \n \n b,g,r = cv2.split(img1)\n \n histB = cv2.calcHist([b],[0],msk1,[256],[0,255])\n cv2.normalize(histB,histB,0,1,cv2.NORM_MINMAX)\n histG = cv2.calcHist([g],[0],msk1,[256],[0,255])\n cv2.normalize(histG,histG,0,1,cv2.NORM_MINMAX)\n histR = cv2.calcHist([r],[0],msk1,[256],[0,255])\n cv2.normalize(histR,histR,0,1,cv2.NORM_MINMAX) \n \n #Calculos de los histogramas de la segunda img \n b,g,r = cv2.split(img2)\n \n histB1 = cv2.calcHist([b],[0],msk2,[256],[0,255])\n cv2.normalize(histB1,histB1,0,1,cv2.NORM_MINMAX)\n histG1 = cv2.calcHist([g],[0],msk2,[256],[0,255])\n cv2.normalize(histG1,histG1,0,1,cv2.NORM_MINMAX)\n histR1 = cv2.calcHist([r],[0],msk2,[256],[0,255])\n cv2.normalize(histR1,histR1,0,1,cv2.NORM_MINMAX)\n \n \n v1 = cv2.compareHist(histB, histB1, cv2.cv.CV_COMP_CHISQR)\n v2 = cv2.compareHist(histG, histG1, cv2.cv.CV_COMP_CHISQR)\n v3 = cv2.compareHist(histR, histR1, cv2.cv.CV_COMP_CHISQR) \n \n return v1, v2, v3\n \n\n'''path1 = 'ima/img (18).jpg'\nimg1 = cv2.imread(path1)\n\npath2 = 'ima/img (5).jpg'\nimg2 = cv2.imread(path2)\n\npath3 = 'mask (3)'\nmsk = cv2.imread(path3)\n\nv1, v2, v3 = compare_hist(img1,msk, img2, msk)\nprint str(v1)\nprint str(v2)\nprint str(v3)'''\n\n","sub_path":"Proyecto/get_histogram.py","file_name":"get_histogram.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"651989015","text":"import numpy as np\r\nimport scipy \r\nfrom scipy import sparse\r\nfrom sklearn.metrics import roc_curve\r\n\r\nprint(\"Changing raw probabilities to values\")\r\nPredictedRawProbabilities=np.genfromtxt(\"C:/Users/Apoorva.Radhakrishna/Desktop/Shareernalam/validation/3L_Best_PredictedRawProbabilities.csv\",delimiter=\",\")\r\nProb_target=np.genfromtxt(\"C:/Users/Apoorva.Radhakrishna/Desktop/Shareernalam/validation/batch_Target.csv\",delimiter=\",\")\r\n\r\nPredicted_Pianoroll= np.zeros((PredictedRawProbabilities.shape[0], PredictedRawProbabilities.shape[1]))\r\ntesty=Prob_target.flatten()\r\npred=PredictedRawProbabilities.flatten()\r\nfpr, tpr, thresholds = roc_curve(testy, pred)\r\noptimal_idx = np.argmax(tpr - fpr)\r\noptimal_threshold = thresholds[optimal_idx]\r\n\r\nfor l in range(0,PredictedRawProbabilities.shape[0]):\r\n #p = np.argmax(PredictedRawProbabilities[l,:])\r\n #if p>optimal_threshold:\r\n # Predicted_Pianoroll[l,p]=1\r\n temp=PredictedRawProbabilities[l,:]>0.13\r\n Predicted_Pianoroll[l,:]=temp.astype(int)\r\nPianoroll=sparse.csr_matrix(Predicted_Pianoroll)\r\nscipy.sparse.save_npz(\"C:/Users/Apoorva.Radhakrishna/Desktop/Shareernalam/validation/PianoRolls/Depth/3/3L_Best_PredictedRoll.npz\", Pianoroll, compressed=True)\r\n\r\n#***********************************************************************************************************************\r\n# SWARA PARINAMA \r\n# *********************************************************************************************************************** \r\n# Maintain Varna(syllable) Swara(accent) Maatra(duration) \r\n# Balam(time-duration) Sama(even tone ) Santana(continuity)\r\n#***********************************************************************************************************************\r\n\r\n# import MIDO music library\r\n\r\nfrom mido import MidiFile, MidiTrack, Message\r\nfrom mido import MetaMessage\r\nimport numpy as np\r\nimport mido\r\nimport csv\r\nimport glob\r\nimport time\r\nimport scipy\r\nfrom scipy import sparse\r\nnp.set_printoptions(threshold=np.nan)\r\n\r\n#***************************************************************************************************************************************************************\r\n# MIDI TO MATRICE ! \r\n# GET PIANO ROLL\r\n#***************************************************************************************************************************************************************\r\n\r\n# 1) Decide Sampling\r\ntime = float(0)\r\nprev = float(0)\r\n\r\n#***************************************************************************************************************************************************************\r\n# NOW REVERSE ENGINEERING!!!! \r\n# GET BACK Note_Start_End FROM PIANO ROLL\r\n#***************************************************************************************************************************************************************\r\n#PianoRoll_sparse =scipy.sparse.load_npz(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Results/p5Sequence_Predictionp1/Simple_500Epoch_1Layer_200Neurons/Mod_PredictedPianoroll.npz\") \r\nPianoRoll_sparse=scipy.sparse.load_npz(\"C:/Users/Apoorva.Radhakrishna/Desktop/Shareernalam/validation/PianoRolls/Depth/3/3L_Best_PredictedRoll.npz\")\r\n#piano_roll=np.genfromtxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Results/Context/p1sec_Simple_250Epoch_1Layer_200Neurons/PianorollTestTarget.csv\",delimiter=\",\") \r\npiano_roll = PianoRoll_sparse.toarray()\r\n\r\n\r\n# 1) Find ON indices, transpose and sort by Note\r\n\r\nindices=np.where(piano_roll>0)\r\n#np.savetxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Testing/indices_Big.csv\", indices, delimiter=\",\") \r\nindices_trans=np.transpose(indices)\r\n#np.savetxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Testing/indices_trans_Big.csv\", indices_trans, delimiter=\",\") \r\nindices_sort=indices_trans[indices_trans[:,1].argsort()]\r\n#np.savetxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Testing/indices_sort_Big.csv\", indices_sort, delimiter=\",\") \r\nNotesOn=np.unique(indices_sort[:,1])\r\n#np.savetxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Testing/NotesOn.csv\", NotesOn, delimiter=\",\") \r\n\r\nprint(333)\r\n#***********************************************************************************************************************\r\n# 2) Sort within notes sort in Ascending\r\n\r\nMain=np.empty((0,2), int)\r\nfor noteNum in range(0,len(NotesOn)):\r\n temp=np.empty((0,1), int)\r\n for indexNum in range(0,len(indices_sort)):\r\n if indices_sort[indexNum][1]==NotesOn[noteNum]:\r\n temp=np.vstack((temp,indices_sort[indexNum][0]))\r\n Temp=sorted(temp)\r\n main=np.column_stack((Temp,(NotesOn[noteNum]*np.ones((len(Temp),1)))))\r\n Main=np.vstack((Main,main))\r\n#np.savetxt(\"C:/Users/Poori/Desktop/Parinama/MakePianoRoll/SmallDataSet/Testing/WhichRow_Note_Big.csv\", Main, delimiter=\",\") \r\nprint(444)\r\n#***********************************************************************************************************************\r\n# 3) Find Start End and Sequences within ON notes\r\nlowNote=22\r\nNote_Start_End=np.zeros((1,3))\r\nnote_Start_End=np.zeros((1,3))\r\nindices_trans=Main\r\n\r\ni=0\r\nwhile i?@[\\\\]^_`{|}~'\n\n ALPHABET_LOWERCASE = __ALPHABET.lower()\n ALPHABET_UPPERCASE = __ALPHABET.upper()\n ALPHABET_ALL_CASE = ALPHABET_LOWERCASE + ALPHABET_UPPERCASE\n\n ALPHABET_LOWERCASE_WITH_SYMBOLS = __ALPHABET.lower() + SYMBOLS\n ALPHABET_UPPERCASE_WITH_SYMBOLS = __ALPHABET.upper() + SYMBOLS\n ALPHABET_ALL_CASE_WITH_SYMBOLS = ALPHABET_LOWERCASE + ALPHABET_UPPERCASE + SYMBOLS\n\n ALPHA_NUMERIC_LOWERCASE = ALPHABET_LOWERCASE + NUMERIC\n ALPHA_NUMERIC_UPPERCASE = ALPHABET_UPPERCASE + NUMERIC\n ALPHA_NUMERIC_ALL_CASE = ALPHABET_ALL_CASE + NUMERIC\n\n ALPHA_NUMERIC_LOWERCASE_WITH_SYMBOLS = ALPHABET_LOWERCASE + NUMERIC + SYMBOLS\n ALPHA_NUMERIC_UPPERCASE_WITH_SYMBOLS = ALPHABET_UPPERCASE + NUMERIC + SYMBOLS\n ALPHA_NUMERIC_ALL_CASE_WITH_SYMBOLS = ALPHABET_ALL_CASE + NUMERIC + SYMBOLS\n\n\nclass UnsupportedTypeException(Exception):\n \"\"\"\n Exception class for UnsupportedTypeException. It is supposed to be raised if parameter is not of expected type\n \"\"\"\n\n def __init__(self, parameter_name: str, message: str = None):\n print('Unsupported type exception for {}. {}'.format(parameter_name, message if message else \"\"))\n\n\nclass InvalidInputSymbolsException(Exception):\n \"\"\"\n Exception class for InvalidInputSymbolsException. It is supposed to be when the custom symbol is not a subset of pre-defined symbols\n \"\"\"\n\n def __init__(self, input_symbols: str):\n print('Input symbols \"{}\" are invalid. Input symbols should be a subset of available symbols {}'.format(input_symbols, StringType.SYMBOLS.value))\n\n\nclass RandomString():\n \"\"\"\n Actual class containing methods to generate random strings\n \"\"\"\n\n def __init__(self):\n pass\n\n def get_string(self, max_length: int = 10, random_length: bool = False, string_type: str = StringType.ALPHA_NUMERIC_ALL_CASE, symbols: str = None, must_include_all_type: bool = False):\n \"\"\" Generate a random string based on the input parameters.\n\n :param max_length: Maximum length of each generated string (default is 10).\n :param random_length: If True, the length of each word will be randomly chosen up to the maximum value (default is False).\n :param string_type: Type of characters to use for generating the strings.\n :param symbols: Custom symbols to use for generating the strings (applicable only when string_type is set to SYMBOLS or WITH_SYMBOLS).\n :param must_include_all_type: If True, characters from each type will be used in each generated string.\n :return: A random strings.\n \"\"\"\n self.__validate_input(1, max_length, random_length, string_type, symbols)\n return self.get_strings(count=1,\n max_length=max_length,\n random_length=random_length,\n string_type=string_type,\n symbols=symbols,\n must_include_all_type=must_include_all_type\n )[0] if max_length > 0 else ''\n\n def get_strings(self, count: int = 10, max_length: int = 10, random_length: bool = False, string_type: str = StringType.ALPHA_NUMERIC_ALL_CASE, symbols: str = None, must_include_all_type: bool = False) -> list:\n \"\"\" Generate a list of random strings based on the input parameters.\n\n :param count: Total number of strings to generate (default is 10).\n :param max_length: Maximum length of each generated string (default is 10).\n :param random_length: If True, the length of each word will be randomly chosen up to the maximum value (default is False).\n :param string_type: Type of characters to use for generating the strings.\n :param symbols: Custom symbols to use for generating the strings (applicable only when string_type is set to SYMBOLS or WITH_SYMBOLS).\n :param must_include_all_type: If True, characters from each type will be used in each generated string.\n :return: A list of random strings.\n \"\"\"\n self.__validate_input(count, max_length, random_length, string_type, symbols)\n list_of_strings = []\n if count > 0 and max_length > 0:\n list_of_input_strings = self.__get_input_strings_from_string_type(string_type)\n\n if symbols:\n # checking if user have specified any custom symbols, then the default symbols will be overridden\n list_of_input_strings = [symbols if '@' in entry else entry for entry in list_of_input_strings]\n\n input_characters = list_of_input_strings if must_include_all_type else ''.join(list_of_input_strings)\n list_of_strings = self.__get_strings(count, max_length, random_length, input_characters)\n return list_of_strings\n\n def __get_strings(self, count: int, max_length: int, random_length: bool, input_characters) -> list:\n \"\"\"\n Generate a list of random strings from a single string of characters.\n\n :param count: Total number of strings to generate.\n :param max_length: Maximum length of each generated string.\n :param random_length: If True, the length of each word will be randomly chosen up to the maximum value.\n :param input_characters: String of characters or a list of strings of character to use for generating the strings.\n :return: A list of random strings.\n \"\"\"\n strings = []\n if isinstance(input_characters, str):\n for _ in range(count):\n current_word = ''\n length = max_length if not random_length else random.randint(1, max_length)\n for _ in range(length):\n current_word += random.SystemRandom().choice(input_characters)\n strings.append(str(current_word))\n elif isinstance(input_characters, list):\n for _ in range(count):\n current_word = ''\n length = max_length if not random_length else random.randint(1, max_length)\n for _ in range(length):\n random_character_set = random.choice(input_characters)\n current_word += random.SystemRandom().choice(random_character_set)\n strings.append(str(current_word))\n return strings\n\n def __validate_input(self, count: int, max_length: int, random_length: bool, string_type: StringType, symbols: str):\n \"\"\"\n Validate the input parameters for correctness and compatibility.\n\n :param count: Total number of strings to generate.\n :param max_length: Maximum length of each generated string.\n :param random_length: If True, the length of each word will be randomly chosen up to the maximum value.\n :param string_type: Type of characters to use for generating the strings.\n :param symbols: Custom symbols to use for generating the strings (applicable only when string_type is set to SYMBOLS or WITH_SYMBOLS).\n \"\"\"\n if not isinstance(count, int):\n raise UnsupportedTypeException('count', 'count should be of integer type instead of current {} type'.format(type(count)))\n\n if not isinstance(max_length, int):\n raise UnsupportedTypeException('max_length', 'max_length should be of integer type instead of current {} type'.format(type(max_length)))\n\n if not isinstance(random_length, bool):\n raise UnsupportedTypeException('random_length', 'random_length should be of boolean type instead of current {} type'.format(type(random_length)))\n\n if not isinstance(string_type, StringType):\n raise UnsupportedTypeException('string_type', 'string_type should be of StringType type instead of current {} type'.format(type(string_type)))\n\n if symbols and not isinstance(symbols, str):\n raise UnsupportedTypeException('symbols', 'symbols should be either None or of string type instead of current {} type'.format(type(symbols)))\n\n if symbols and not re.match('[{}]'.format(StringType.SYMBOLS.value), symbols):\n raise InvalidInputSymbolsException(symbols)\n\n def __get_input_strings_from_string_type(self, string_type: StringType) -> list:\n \"\"\"\n Get a list of characters based on input string_type\n \"\"\"\n strings = []\n if string_type == StringType.ALPHABET_LOWERCASE:\n strings = [StringType.ALPHABET_LOWERCASE.value]\n elif string_type == StringType.ALPHABET_UPPERCASE:\n strings = [StringType.ALPHABET_UPPERCASE.value]\n elif string_type == StringType.ALPHABET_ALL_CASE:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.ALPHABET_UPPERCASE.value]\n elif string_type == StringType.ALPHABET_LOWERCASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.SYMBOLS.value]\n elif string_type == StringType.ALPHABET_UPPERCASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_UPPERCASE.value, StringType.SYMBOLS.value]\n elif string_type == StringType.ALPHABET_ALL_CASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.ALPHABET_UPPERCASE.value, StringType.SYMBOLS.value]\n elif string_type == StringType.ALPHA_NUMERIC_LOWERCASE:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.NUMERIC.value]\n elif string_type == StringType.ALPHA_NUMERIC_UPPERCASE:\n strings = [StringType.ALPHABET_UPPERCASE.value, StringType.NUMERIC.value]\n elif string_type == StringType.ALPHA_NUMERIC_ALL_CASE:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.ALPHABET_UPPERCASE.value, StringType.NUMERIC.value]\n elif string_type == StringType.ALPHA_NUMERIC_LOWERCASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.NUMERIC.value, StringType.SYMBOLS.value]\n elif string_type == StringType.ALPHA_NUMERIC_UPPERCASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_UPPERCASE.value, StringType.NUMERIC.value, StringType.SYMBOLS.value]\n elif string_type == StringType.ALPHA_NUMERIC_ALL_CASE_WITH_SYMBOLS:\n strings = [StringType.ALPHABET_LOWERCASE.value, StringType.ALPHABET_UPPERCASE.value, StringType.NUMERIC.value, StringType.SYMBOLS.value]\n return strings\n","sub_path":"PyRandomString/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"290225630","text":"\"\"\"\nTrain the MobileNet V2 model\n\"\"\"\nimport os\nimport sys\nimport time\nimport argparse\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom octa_mobilenet_v2 import OctaveMobileNetv2\nfrom keras.optimizers import RMSprop\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Conv2D, Reshape, Activation\nfrom keras.models import Model\nfrom keras.datasets import mnist\n\n\ndef get_mnist_dataset():\n #download mnist data and split into train and test sets\n (X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n #reshape data to fit model\n X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\n X_val = X_train[:800]\n y_val = y_train[:800]\n\n X_train = X_train[800:]\n y_train = y_train[800:]\n\n from keras.utils import to_categorical\n # convert class vectors to binary class matrices (https://github.com/keras-team/keras/blob/7a39b6c62d43c25472b2c2476bd2a8983ae4f682/examples/mnist_cnn.py#L43)\n y_train = to_categorical(y_train)\n y_test = to_categorical(y_test)\n y_val = to_categorical(y_val)\n return (X_train, y_train), (X_val, y_val), (X_test, y_test)\n\n\ndef fine_tune(num_classes, weights, model):\n \"\"\"Re-build model with current num_classes.\n\n # Arguments\n num_classes, Integer, The number of classes of dataset.\n tune, String, The pre_trained model weights.\n model, Model, The model structure.\n \"\"\"\n model.load_weights(weights)\n\n x = model.get_layer('Dropout').output\n x = Conv2D(num_classes, (1, 1), padding='same')(x)\n x = Activation('softmax', name='softmax')(x)\n output = Reshape((num_classes,))(x)\n\n model = Model(inputs=model.input, outputs=output)\n\n return model\n\n\ndef train(batch, epochs, num_classes, size, weights, tclasses):\n \"\"\"Train the model.\n\n # Arguments\n batch: Integer, The number of train samples per batch.\n epochs: Integer, The number of train iterations.\n num_classes, Integer, The number of classes of dataset.\n size: Integer, image size.\n weights, String, The pre_trained model weights.\n tclasses, Integer, The number of classes of pre-trained model.\n \"\"\"\n\n train_data, validation_data, test_data = get_mnist_dataset()\n\n if weights:\n model = OctaveMobileNetv2((size, size, 1), tclasses)\n model = fine_tune(num_classes, weights, model)\n else:\n model = OctaveMobileNetv2((size, size, 1), num_classes)\n\n opt = RMSprop()\n earlystop = EarlyStopping(monitor='val_acc', patience=10, verbose=1, mode='auto')\n model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n history = model.fit(\n train_data[0], train_data[1],\n validation_data=validation_data,\n batch_size= 500,\n epochs=epochs,\n shuffle=True,\n callbacks=[earlystop])\n\n if not os.path.exists('model'):\n os.makedirs('model')\n df = pd.DataFrame.from_dict(history.history)\n df.to_csv('model/history.csv', encoding='utf-8', index=False)\n model.save_weights('model/weights.h5')\n\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n\n # Plot training & validation loss values\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n\n print(model.evaluate(test_data[0], test_data[1]))\n\n return history\n","sub_path":"octave_mobilenetv2/train_octa_mobilenetv2.py","file_name":"train_octa_mobilenetv2.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"546451750","text":"# Populate a list of random numbers. Find and print the max element and the index of this element\n\nimport sys\nfrom random import randint\nlowest = int(input('From number'))\ngreatest = int(input('To number'))\n\n\nlength = int(input(f\"Enter a list length \"))\narray_1 = []\n\nfor i in range(length):\n item = randint(lowest, greatest)\n array_1.append(item)\n\n\n\ndef find_max_item_and_its_index_in_list(array):\n max_value = array[0]\n max_index = 0\n index = 0\n while index < len(array):\n if max_value <= array[index]:\n max_value = array[index]\n max_index = index\n index += 1\n return {\n 'array': array,\n 'max_value': max_value,\n 'max_index': max_index\n }\n\nprint(find_max_item_and_its_index_in_list(array_1))","sub_path":"lesson_7/Max_item_and_index_in_a_list.py","file_name":"Max_item_and_index_in_a_list.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"318455485","text":"# -*- coding: utf-8 -*-\n# @Time :2018/4/4 下午3:39\n# @Author :李二狗\n# @Site :\n# @File :demo.py\n# @Software :PyCharm\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.externals import joblib\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nimport time\n\nmpl.rcParams['font.family'] = 'sans-serif'\nmpl.rcParams['font.sans-serif'] = 'SimHei'\nmpl.rcParams['axes.unicode_minus'] = False\n\npath = 'brain_body.txt'\n\n# 加载数据\ndf = pd.read_fwf(path)\n\n# 异常数据处理\n\n#特征值选择\n\nX = df.iloc[:, 0:1]\nY = df.iloc[:, 1:2]\n\n# 划分数据集\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\n\n# 数据模型建立\nss = StandardScaler()\nX_train = ss.fit_transform(X_train)\nX_test = ss.transform(X_test)\n\n# 模型训练\nlr = LinearRegression(fit_intercept=True)\nlr.fit(X_train, Y_train)\n\n# 测试模型预测\nY_predict = lr.predict(X_test)\n\n# 输出模型训练得到的相关参数\n# 注意:第1、2、6个系数为0\nprint(\"模型的系数(θ):\", end=\"\")\nprint(lr.coef_)\nprint(\"模型的截距:\", end='')\nprint(lr.intercept_)\n\nprint(\"训练集上R^2:\", lr.score(X_train, Y_train))\nprint(\"测试集上R^2:\", lr.score(X_test, Y_test))\n\n\n# 预测值和实际值画图比较\nt = np.arange(len(X_test))\n# 建一个画布,facecolor是背景色\nplt.figure(facecolor='w')\nplt.plot(t, Y_test, 'r-', linewidth=2, label='真实值')\nplt.plot(t, Y_predict, 'g-', linewidth=2, label='预测值')\nplt.plot(X_test, Y_predict)\nplt.scatter(X_train, Y_train)\n# 显示图例,设置图例的位置\nplt.legend(loc = 'upper left')\nplt.title(\"线性回归预测身体和脑重之间的关系\", fontsize=20)\n# 加网格\nplt.grid(b=True)\n# 保存图片\nplt.savefig('demo.png', dpi=200)\nplt.show()","sub_path":"linear_regression_demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"354568982","text":"from PIL import Image\nimport base64\nimport urllib\nimport io\ndef byteify(input, encoding='utf-8'):\n \"\"\"\n Encode all the values in the input data\n :param input: input data, can be nested dict and list data structure\n :param encoding: encoding format\n :return: encoded data\n \"\"\"\n if isinstance(input, dict):\n return {byteify(key): byteify(value) for key, value in input.iteritems()}\n elif isinstance(input, list):\n return [byteify(element) for element in input]\n elif isinstance(input, unicode):\n return input.encode(encoding)\n else:\n return input\n\ndef get_image_uri(image_bytes):\n image_base64 = base64.b64encode(image_bytes)\n image_type = Image.open(io.BytesIO(image_bytes)).format\n url = \"data:image/\" + image_type + \";base64,\" + image_base64\n return url\n\ndef get_image_thumbnail(image_bytes, size = (224,224)):\n image = Image.open(io.BytesIO(image_bytes)).convert('RGB')\n image.thumbnail(size, Image.ANTIALIAS)\n imgByteArr = io.BytesIO()\n image.save(imgByteArr, format='jpeg')\n return imgByteArr.getvalue()\n\n\n\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"391438306","text":"\n#============================================================\n\"\"\"경로잡기, 자주사용하는 개발용 모듈.\"\"\"\n#============================================================\n\nimport sys\nsys.path.append(\"/Users/sambong/pjts/career/env/lib/python3.7/site-packages\")\nother_pjts = ['stock']\nfor other in other_pjts:\n path = f\"/Users/sambong/pjts/{other}/env/lib/python3.7/site-packages\"\n if path in sys.path:\n sys.path.remove(path)\nimport pprint\npp = pprint.PrettyPrinter(indent=2)\nimport importlib\n","sub_path":"jupyter/hydrogen.py","file_name":"hydrogen.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68144853","text":"import math\nfrom torch.optim.lr_scheduler import _LRScheduler\nimport numpy as np\nimport os\nimport torch.utils.data as data_utils\nimport torch\nimport torchnet as tnt\nfrom torchnet.logger import VisdomPlotLogger\nfrom torch.autograd import Variable\nimport visdom\nfrom scipy.signal import medfilt\nfrom scipy.signal import savgol_filter\nfrom scipy.ndimage.filters import gaussian_filter\n\n\nclass meter_logger():\n # class to store all relevant meter, oggind and plotting objects\n def __init__(self, args):\n self.loss_meter = tnt.meter.AverageValueMeter()\n self.time_meter = tnt.meter.TimeMeter(unit=False)\n port = 8097\n self.train_loss_logger = VisdomPlotLogger(\n 'line', port=port, opts={'title': 'Train Loss'})\n\n self.valid_loss_logger = VisdomPlotLogger(\n 'line', port=port, opts={'title': 'Test Loss'})\n if args.p:\n self.vis = visdom.Visdom()\n self.vis.close(None)\n \n def save_snr(self, snr_single, snr_folded):\n self.snr = (snr_single, snr_folded)\n\n\ndef create_data(path, samples, repetitions=100, noise=0.1, normalize=0, roll=0):\n # create data by concatenating pulsar profiles and adding noise\n\n profiles = []\n prof_lengths = []\n\n for (dirpath, dirnames, filenames) in os.walk(path):\n if filenames:\n for file in filenames:\n if '.asc' in file:\n print(file)\n profile = np.loadtxt(f\"{path}/{file}\")\n profile = profile / np.max(profile)\n profiles.append(profile)\n prof_lengths.append(len(profile))\n\n profiles_array = np.asarray(profiles)\n # min_length = np.min(prof_lengths)\n max_length = np.max(prof_lengths)\n total_length = max_length * repetitions\n\n data = np.zeros((samples, total_length, 1))\n target = np.zeros((samples, total_length))\n\n for i in range(samples):\n # amp = np.random.uniform(0.1, 5)\n phase = np.random.randint(0, 128)\n choice = np.random.randint(0, np.shape(profiles_array)[0])\n used_prof = profiles_array[choice, :]\n needed_reps = int(np.ceil(total_length/len(used_prof)) + 1)\n initial_data = np.tile(used_prof, needed_reps)\n initial_data = initial_data[phase:phase+total_length]\n noisy_data = initial_data + np.random.normal(0, noise, total_length)\n noisy_data = np.abs(noisy_data)\n if normalize:\n noisy_data = noisy_data - np.mean(noisy_data)\n noisy_data = noisy_data / np.std(noisy_data)\n data[i, :, 0] = noisy_data\n target[i, :] = np.roll(initial_data, roll)\n\n return data, target\n\n\ndef create_data_loader(data, target, batch_size=50, val_frac=0.2):\n # split data set into training and validation and create data loaders\n\n all_indices = np.arange(data.shape[0])\n\n val_size = int(val_frac * len(all_indices))\n\n valid_indices = np.random.choice(all_indices, val_size, replace=False)\n train_indices = np.delete(all_indices, valid_indices)\n train_data_tensor = torch.from_numpy(data[train_indices,:,:])\n train_labels_tensor = torch.from_numpy(target[train_indices,:])\n valid_data_tensor = torch.from_numpy(data[valid_indices,:,:])\n valid_labels_tensor = torch.from_numpy(target[valid_indices,:])\n\n train_dataset = data_utils.TensorDataset(train_data_tensor, train_labels_tensor)\n valid_dataset = data_utils.TensorDataset(valid_data_tensor, valid_labels_tensor)\n\n print(f\"Batch Size: {batch_size}\")\n\n\n train_loader = data_utils.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=1)\n valid_loader = data_utils.DataLoader(dataset=valid_dataset, batch_size=batch_size, shuffle=0)\n\n return train_loader, valid_loader, valid_indices\n\n\ndef apply_net(net, loader, logging, args, train=1):\n if args.model=='lstm':\n apply_rnn(net, loader, logging, args, train)\n if args.model=='tcn':\n apply_tcn(net, loader, logging, args, train)\n\n\ndef apply_tcn(net, loader, logging, args, train=1):\n # training/validation loop with logging/plotting the performance\n dtype = torch.FloatTensor\n if next(net.parameters()).is_cuda:\n dtype = torch.cuda.FloatTensor\n else:\n dtype = torch.FloatTensor\n\n if train:\n net.train()\n else:\n net.eval()\n for step, (x, y) in enumerate(loader): # gives batch data\n var_x = Variable(x.type(dtype).permute(0,2,1), requires_grad = True) # reshape x to (batch, time_step, input_size)\n var_y = Variable(y.type(dtype)) # batch y\n output = net(var_x) # net output\n loss = net.loss(output, var_y.squeeze()) # cross entropy loss\n if train:\n net.optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n net.optimizer.step() # apply gradients\n try:\n logging.loss_meter.add(loss.data.cpu().numpy()) # average metric over each epoch\n except ValueError:\n print('error with loss meter')\n pass\n if not train:\n net_snr_single = compute_snr(output.data.cpu().numpy())\n net_out_folded = fold_array(output.data.cpu().numpy())\n net_snr_folded = compute_snr(net_out_folded)\n logging.save_snr(net_snr_single, net_snr_folded)\n\n if args.p:\n plot_graphs(net.epoch, logging, var_x.data.cpu().numpy().squeeze(), var_y.data.cpu().numpy().squeeze(), output.data.cpu().numpy(), train)\n\n\ndef apply_rnn(net, loader, logging, args, train=1):\n # training/validation loop with logging/plotting the performance\n dtype = torch.FloatTensor\n if next(net.parameters()).is_cuda:\n dtype = torch.cuda.FloatTensor\n else:\n dtype = torch.FloatTensor\n\n if train:\n net.train()\n else:\n net.eval()\n stacked_result = []\n for step, (x, y) in enumerate(loader): # gives batch data\n tbptt_cycles = int(np.ceil(np.shape(x)[1]/args.b))\n net.init_hidden()\n for k in range(tbptt_cycles):\n x_trunc = x[:,k*args.b:(k+1)*args.b,:]\n y_trunc = y[:,k*args.b:(k+1)*args.b]\n var_x = Variable(x_trunc.type(dtype).permute(1, 0, 2), requires_grad = True) # reshape x to (batch, time_step, input_size)\n var_y = Variable(y_trunc.type(dtype)) # batch y\n output = net(var_x) # net output\n loss = net.loss(output, var_y.squeeze()) # cross entropy loss\n if train:\n net.optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n net.optimizer.step() # apply gradients\n else:\n stacked_result.extend(output.data.cpu().numpy().T)\n try:\n logging.loss_meter.add(loss.data.cpu().numpy()) # average metric over each epoch\n except ValueError:\n print('error with loss meter')\n pass\n if not train:\n net_snr_single = compute_snr(output.data.cpu().numpy())\n net_out_folded = fold_array(np.asarray(stacked_result).T)\n net_snr_folded = compute_snr(net_out_folded)\n logging.save_snr(net_snr_single, net_snr_folded)\n\n if args.p:\n plot_graphs(net.epoch, logging, var_x.data.cpu().numpy().T.squeeze(), var_y.data.cpu().numpy().squeeze(), output.data.cpu().numpy(), train)\n\n\ndef print_performance_train(net, logging):\n # print training performance\n print(f\"Epoch: {net.epoch:3.0f} LR: {net.scheduler.get_lr()[0]:.5f} Train: {logging.loss_meter.value()[0]:.4f} \", end=\"\")\n logging.loss_meter.reset()\n\n\ndef print_performance_valid(logging):\n # print validation performance\n print(f\"Validation: {logging.loss_meter.value()[0]:.4f} SNR_single: {logging.snr[0]:.4f} \\\nSNR_folded: {logging.snr[1]:.4f} Duration: {logging.time_meter.value():.2f}\")\n logging.loss_meter.reset()\n\n\ndef plot_graphs(epoch, logging, noisy_data, target, output, mode):\n # plot the evolution of the loss and the resulting pulse profiles at various steps\n if mode:\n logging.train_loss_logger.log(epoch, logging.loss_meter.value()[0])\n else:\n logging.valid_loss_logger.log(epoch, logging.loss_meter.value()[0])\n if epoch % 5 == 0:\n # x_vals = np.arange(np.shape(target)[1])\n x_vals = np.arange(128)\n diff = target - output\n plotted_profile = epoch % target.shape[0]\n added = np.stack((noisy_data[plotted_profile,-128:], target[plotted_profile,-128:], output[plotted_profile,-128:]), axis=-1)\n # added = np.stack((target[plotted_profile,-128:], output[plotted_profile,-128:]), axis=-1)\n logging.vis.line(added[:,:], X=x_vals)\n logging.vis.line(diff.T[-128:, ::50], X=x_vals)\n\ndef compute_snr(array, trunc=128):\n # crude computation of the signal to noise ratio\n medians = np.median(array[:,-trunc:], axis=1)\n array = array - medians[:, None]\n max_vals = np.max(array[:,-trunc:], axis=1)\n std_vals = np.std(array[:,-trunc:], axis=1)\n snrs = max_vals[std_vals!=0] / std_vals[std_vals!=0]\n if snrs.size != 0:\n mean_snr = np.mean(snrs)\n else:\n mean_snr = 0\n return mean_snr\n\n\ndef smooth_array(array, kernel=4):\n # smooth the data as a benchmark for the net method\n # smoothed = medfilt(array[:,-trunc:], kernel_size=(1, kernel))\n # smoothed = savgol_filter(array[:,:], kernel, 2)\n smoothed = gaussian_filter(array[:,:], (0,kernel))\n\n return smoothed\n\n\ndef fold_array(array, period=128):\n # fold the data with a certain period\n folded_array = np.zeros((array.shape[0], period))\n for i in range(period):\n folded_array[:,i] = np.sum(array[:,i::period], axis=1)\n return folded_array\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605510110","text":"import torchvision\nfrom torch.utils.data import DataLoader\n\nfrom torch.utils.tensorboard import SummaryWriter\n\ntest_data = torchvision.datasets.CIFAR10(\"./dataset\",\n train=False,\n transform=torchvision.transforms.ToTensor(),\n download=True)\ntest_loader = DataLoader(test_data, batch_size=64,\n shuffle=False,\n num_workers=0, drop_last=True)\n\n# # 第一张图片\n# img, target = test_data[0]\n\n# print(img.shape)\n# print(target)\n\nwriter = SummaryWriter(\"dataloader\")\nfor epoch in range(2):\n step = 0\n for data in test_loader:\n imgs, targets = data\n # print(imgs.shape)\n # print(targets)\n writer.add_images(\"Epoch: {}\".format(epoch), imgs, step)\n step += 1\nwriter.close()","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"642581810","text":"from datetime import datetime\r\nimport time\r\nimport random\r\nimport base64\r\nimport binascii\r\n\r\nclass MT19937:\r\n \r\n def __init__(self):\r\n self.MT = [None] * 624\r\n self.index = 0\r\n def initialize_generator(self, seed):\r\n index = self.index\r\n MT = self.MT\r\n index = 0\r\n MT[0] = seed\r\n for i in range(1, 624):\r\n MT[i] = 0x00000000ffffffff & (1812433253 * (MT[i - 1] ^ (MT[i - 1] >> 30)) + i)\r\n\r\n def extract_number(self):\r\n index = self.index\r\n MT = self.MT\r\n if index == 0:\r\n self.generate_numbers()\r\n\r\n y = MT[index]\r\n y = y ^ (y >> 11)\r\n y = y ^ (y << 7 & (2636928640))\r\n y = y ^ (y << 15 & (4022730752))\r\n y = y ^ (y >> 18)\r\n\r\n index = (index + 1) % 624\r\n return y\r\n\r\n def generate_numbers(self):\r\n MT = self.MT\r\n for i in range(0, 624):\r\n y = (MT[i] & 0x80000000) + (MT[(i + 1) % 624] & 0x7fffffff)\r\n MT[i] = MT[(i + 397) % 624] ^ (y >> 1)\r\n if (y % 2) != 0:\r\n MT[i] = (MT[i] ^ 2567483615)\r\n\r\ndef oracle():\r\n random_sec = random.randint(5, 60)\r\n time.sleep(random_sec)\r\n timestamp = int(time.time())\r\n ex = MT19937()\r\n print(\"The time stamp/seed is %d\" % timestamp)\r\n ex.initialize_generator(timestamp)\r\n output = ex.extract_number()\r\n #print(output)\r\n random_sec = random.randint(5, 60)\r\n time.sleep(random_sec)\r\n b64output = bin(output).encode('base64','strict')\r\n return b64output\r\n\r\ndef findSeed(b64output):\r\n mt = MT19937()\r\n timestamp = int(time.time())\r\n for x in range(1, 200):\r\n mt.initialize_generator((timestamp - x))\r\n print(\"Trying %d ....\" % (timestamp - x))\r\n guess = mt.extract_number()\r\n #print(guess)\r\n b64guess = bin(guess).encode('base64','strict')\r\n if (b64guess == b64output):\r\n return (\"Seed is %d\" % (timestamp - x))\r\n\r\n return \"Seed could not be found\"\r\n\r\ndef main():\r\n print(findSeed(oracle()))\r\nmain()\r\n","sub_path":"458Lab1/458Lab1old.py","file_name":"458Lab1old.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"302817350","text":"\"\"\"\nCopyright 2008 Free Software Foundation, Inc.\nThis file is part of GNU Radio\n\nGNU Radio Companion is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nGNU Radio Companion is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\"\"\"\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\n_COLORMAP = gtk.gdk.colormap_get_system() #create all of the colors\ndef get_color(color_code): return _COLORMAP.alloc_color(color_code, True, True)\n#colour for the block when highlighted\nHIGHLIGHT_COLOR_BLOCK = get_color('#e2252d')\n#colour when right-click and highlight\nHIGHLIGHT_COLOR = get_color('#b5cbbb')\nBORDER_COLOR = get_color('black')\n#param entry boxes\nPARAM_ENTRY_TEXT_COLOR = get_color('white')\nENTRYENUM_CUSTOM_COLOR = get_color('black')\n#flow graph color constants\nFLOWGRAPH_BACKGROUND_COLOR = get_color('#b5cbbb')\n#block color constants\nBLOCK_ENABLED_COLOR = get_color('white')\nBLOCK_DISABLED_COLOR = get_color('#ffff00')\n#connection color constants\nCONNECTION_ENABLED_COLOR = get_color('black')\nCONNECTION_DISABLED_COLOR = get_color('#999999')\nCONNECTION_ERROR_COLOR = get_color('red')\n","sub_path":"gui/Colors.py","file_name":"Colors.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"375640572","text":"\"\"\"\nBased on Deit: Facebook, Inc.\nhttps://github.com/facebookresearch/deit/blob/main/main.py\n\"\"\"\n\nimport argparse\nimport datetime\nimport time\nimport os\nimport logging\nimport torch.backends.cudnn as cudnn\nimport json\nimport torch\nimport numpy as np\nfrom pathlib import Path\n\nfrom timm.data import Mixup\nfrom timm.models import create_model\nfrom timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\nfrom timm.scheduler import create_scheduler\nfrom timm.optim import create_optimizer\nfrom timm.utils import get_state_dict\n\nfrom tlt.utils import load_pretrained_weights\n\nfrom datasets import build_dataset\nfrom engine import train_one_epoch, evaluate\nfrom samplers import RASampler\nimport models\nimport utils_custom as utils\n\nimport ipdb\n\n_logger = logging.getLogger('train')\n\ndef get_args_parser():\n parser = argparse.ArgumentParser('DeiT training and evaluation script', add_help=False)\n parser.add_argument('--batch-size', default=8, type=int)\n parser.add_argument('--epochs', default=30, type=int)\n\n # Model parameters\n parser.add_argument('--model', default='volo_d1', type=str, metavar='MODEL',\n help='Name of model to train')\n parser.add_argument('--pretrained', action='store_true', default=False,\n help='Start with pretrained version of specified network (if avail)')\n parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH',\n help='Initialize model from this checkpoint (default: none)')\n\n parser.add_argument('--num-classes', type=int, default=None, metavar='N',\n help='number of label classes (Model default if None)')\n parser.add_argument('--gp', default=None, type=str, metavar='POOL',\n help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')\n parser.add_argument('--img-size', type=int, default=224, metavar='N',\n help='Image patch size (default: None => model default)')\n parser.add_argument('--input-size', default=None, nargs=3, type=int,\n metavar='N N N',\n help='Input all image dimensions (d h w, e.g. --input-size 3 224 224),'\n ' uses model default if empty')\n parser.add_argument('--drop', type=float, default=0.0, metavar='PCT',\n help='Dropout rate (default: 0.)')\n parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT',\n help='Drop connect rate, DEPRECATED, use drop-path (default: None)')\n parser.add_argument('--drop-path', type=float, default=None, metavar='PCT',\n help='Drop path rate (default: None)')\n parser.add_argument('--drop-block', type=float, default=None, metavar='PCT',\n help='Drop block rate (default: None)')\n\n # Optimizer parameters\n parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"adamw\"')\n parser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\n parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',\n help='Optimizer Betas (default: None, use opt default)')\n parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\n parser.add_argument('--weight-decay', type=float, default=0.05,\n help='weight decay (default: 0.05)')\n # Learning rate schedule parameters\n parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"cosine\"')\n parser.add_argument('--lr', type=float, default=5e-4, metavar='LR',\n help='learning rate (default: 5e-4)')\n parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR',\n help='warmup learning rate (default: 1e-6)')\n parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR',\n help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')\n\n parser.add_argument('--decay-epochs', type=float, default=30, metavar='N',\n help='epoch interval to decay LR')\n parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N',\n help='epochs to warmup LR, if scheduler supports')\n\n parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',\n help='epochs to cooldown LR at min_lr, after cyclic schedule ends')\n #parser.add_argument('--patience-epochs', type=int, default=10, metavar='N',\n # help='patience epochs for Plateau LR scheduler (default: 10')\n parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',\n help='LR decay rate (default: 0.1)')\n\n # Augmentation parameters\n parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT',\n help='Color jitter factor (default: 0.4)')\n parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME',\n help='Use AutoAugment policy. \"v0\" or \"original\". \" + \\\n \"(default: rand-m9-mstd0.5-inc1)'),\n parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)')\n parser.add_argument('--train-interpolation', type=str, default='bicubic',\n help='Training interpolation (random, bilinear, bicubic default: \"bicubic\")')\n\n parser.add_argument('--std-aug', action='store_true', default=False)\n parser.add_argument('--repeated-aug', action='store_true')\n parser.add_argument('--no-repeated-aug', action='store_false', dest='repeated_aug')\n parser.set_defaults(repeated_aug=True)\n\n # * Random Erase params\n parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT',\n help='Random erase prob (default: 0.25)')\n parser.add_argument('--remode', type=str, default='pixel',\n help='Random erase mode (default: \"pixel\")')\n parser.add_argument('--recount', type=int, default=1,\n help='Random erase count (default: 1)')\n parser.add_argument('--resplit', action='store_true', default=False,\n help='Do not random erase first (clean) augmentation split')\n\n # * Mixup params\n parser.add_argument('--mixup', type=float, default=0.8,\n help='mixup alpha, mixup enabled if > 0. (default: 0.8)')\n parser.add_argument('--cutmix', type=float, default=1.0,\n help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)')\n parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None,\n help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')\n parser.add_argument('--mixup-prob', type=float, default=1.0,\n help='Probability of performing mixup or cutmix when either/both is enabled')\n parser.add_argument('--mixup-switch-prob', type=float, default=0.5,\n help='Probability of switching to cutmix when both mixup and cutmix enabled')\n parser.add_argument('--mixup-mode', type=str, default='batch',\n help='How to apply mixup/cutmix params. Per \"batch\", \"pair\", or \"elem\"')\n\n # Batch norm parameters (only works with gen_efficientnet based models currently)\n parser.add_argument('--bn-tf', action='store_true', default=False,\n help='Use Tensorflow BatchNorm defaults for models that support it (default: False)')\n parser.add_argument('--bn-momentum', type=float, default=None,\n help='BatchNorm momentum override (if not None)')\n parser.add_argument('--bn-eps', type=float, default=None,\n help='BatchNorm epsilon override (if not None)')\n parser.add_argument('--sync-bn', action='store_true',\n help='Enable NVIDIA Apex or Torch synchronized BatchNorm.')\n parser.add_argument('--dist-bn', type=str, default='',\n help='Distribute BatchNorm stats between nodes after each epoch (\"broadcast\", \"reduce\", or \"\")')\n parser.add_argument('--split-bn', action='store_true',\n help='Enable separate BN layers per augmentation split.')\n\n # Model Exponential Moving Average\n parser.add_argument('--model-ema', action='store_true', default=False,\n help='Enable tracking moving average of model weights')\n parser.add_argument('--model-ema-force-cpu', action='store_true', default=False,\n help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')\n parser.add_argument('--model-ema-decay', type=float, default=0.99992,\n help='decay factor for model weights moving average (default: 0.99992)')\n \n # Misc\n parser.add_argument(\"--local_rank\", default=0, type=int)\n parser.add_argument('--torchscript', dest='torchscript', action='store_true',\n help='convert model torchscript for inference')\n\n # * Finetuning params\n parser.add_argument('--finetune', default='weights/d1_224_84.2.pth.tar', help='finetune from checkpoint')\n\n # Dataset parameters\n parser.add_argument('--data-path', default='D:/AI/AIData/cat-dog-panda/', type=str,\n help='dataset path')\n parser.add_argument('--data-set', default='cat-dog-panda', choices=['CIFAR', 'IMNET', 'IMNET100', 'IMNET10'],\n type=str, help='Image Net dataset path')\n\n\n parser.add_argument('--output_dir', default='output/',\n help='path where to save, empty for no saving')\n parser.add_argument('--device', default='cuda',\n help='device to use for training / testing')\n parser.add_argument('--seed', default=0, type=int)\n parser.add_argument('--resume', default='', help='resume from checkpoint')\n parser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n help='start epoch')\n parser.add_argument('--eval', action='store_true', help='Perform evaluation only')\n parser.add_argument('--dist-eval', action='store_true', default=False, help='Enabling distributed evaluation')\n parser.add_argument('--num_workers', default=0, type=int)\n parser.add_argument('--pin-mem', action='store_true',\n help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')\n parser.add_argument('--no-pin-mem', action='store_false', dest='pin_mem',\n help='')\n parser.set_defaults(pin_mem=True)\n\n # distributed training parameters\n parser.add_argument('--world_size', default=1, type=int,\n help='number of distributed processes')\n parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')\n return parser\n\n\ndef main(args):\n utils.init_distributed_mode(args)\n\n print(args)\n\n device = torch.device(args.device)\n\n # fix the seed for reproducibility\n seed = args.seed + utils.get_rank()\n torch.manual_seed(seed)\n np.random.seed(seed)\n # random.seed(seed)\n\n cudnn.benchmark = True\n\n dataset_train, args.num_classes = build_dataset(is_train=True, args=args)\n dataset_val, _ = build_dataset(is_train=False, args=args)\n\n if True: # args.distributed:\n num_tasks = utils.get_world_size()\n global_rank = utils.get_rank()\n if args.repeated_aug:\n sampler_train = RASampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n else:\n sampler_train = torch.utils.data.DistributedSampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n if args.dist_eval:\n if len(dataset_val) % num_tasks != 0:\n print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. '\n 'This will slightly alter validation results as extra duplicate entries are added to achieve '\n 'equal num of samples per-process.')\n sampler_val = torch.utils.data.DistributedSampler(\n dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False)\n else:\n sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n else:\n sampler_train = torch.utils.data.RandomSampler(dataset_train)\n sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train, sampler=sampler_train,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=True,\n )\n\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val, sampler=sampler_val,\n batch_size=int(1.5 * args.batch_size),\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=False\n )\n\n mixup_fn = None\n mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None\n if mixup_active:\n mixup_fn = Mixup(\n mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,\n prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,\n label_smoothing=args.smoothing, num_classes=args.num_classes)\n\n print(f\"Creating model: {args.model}\")\n\n model = create_model(\n args.model,\n ##注意:action='store_true', default=False\n pretrained=args.pretrained,\n num_classes=args.num_classes,\n drop_rate=args.drop,\n drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path\n drop_path_rate=args.drop_path,\n drop_block_rate=args.drop_block,\n global_pool=args.gp,\n bn_tf=args.bn_tf,\n bn_momentum=args.bn_momentum,\n bn_eps=args.bn_eps,\n scriptable=args.torchscript,\n ##注意:不是加载预训练模型,预训练模型与custom任务的num_classes可能不一样\n checkpoint_path=args.initial_checkpoint,\n img_size=args.img_size)\n\n # ipdb.set_trace()\n\n if args.num_classes is None:\n assert hasattr(\n model, 'num_classes'\n ), 'Model must have `num_classes` attr if not set on cmd line/config.'\n args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly\n\n if args.finetune:\n load_pretrained_weights(model=model,\n checkpoint_path=args.finetune,\n use_ema=args.model_ema,\n strict=False,\n num_classes=args.num_classes)\n\n # ipdb.set_trace()\n\n if args.local_rank == 0:\n _logger.info('Model %s created, param count: %d' %\n (args.model, sum([m.numel()\n for m in model.parameters()])))\n\n model.to(device)\n\n model_without_ddp = model\n if args.distributed:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n model_without_ddp = model.module\n n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print('number of params:', n_parameters)\n\n linear_scaled_lr = args.lr * args.batch_size * utils.get_world_size() / 512.0\n args.lr = linear_scaled_lr\n optimizer = create_optimizer(args, model_without_ddp)\n\n lr_scheduler, _ = create_scheduler(args, optimizer)\n\n criterion = LabelSmoothingCrossEntropy()\n\n if args.mixup > 0.:\n # smoothing is handled with mixup label transform\n criterion = SoftTargetCrossEntropy()\n elif args.smoothing:\n criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing)\n else:\n criterion = torch.nn.CrossEntropyLoss()\n\n output_dir = Path(args.output_dir)\n if args.resume:\n if args.resume.startswith('https'):\n checkpoint = torch.hub.load_state_dict_from_url(\n args.resume, map_location='cpu', check_hash=True)\n else:\n checkpoint = torch.load(args.resume, map_location='cpu')\n model_without_ddp.load_state_dict(checkpoint['model'])\n if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint:\n optimizer.load_state_dict(checkpoint['optimizer'])\n lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n args.start_epoch = checkpoint['epoch'] + 1\n\n if args.eval:\n test_stats = evaluate(data_loader_val, model, device)\n print(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n return\n\n print(f\"Start training for {args.epochs} epochs\")\n start_time = time.time()\n max_accuracy = 0.0\n for epoch in range(args.start_epoch, args.epochs):\n if args.distributed:\n data_loader_train.sampler.set_epoch(epoch)\n\n train_stats = train_one_epoch(\n model, criterion, data_loader_train,\n optimizer, device, epoch, mixup_fn\n )\n\n lr_scheduler.step(epoch)\n if args.output_dir:\n checkpoint_paths = [output_dir / 'checkpoint.pth']\n for checkpoint_path in checkpoint_paths:\n utils.save_on_master({\n 'model': model_without_ddp.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'lr_scheduler': lr_scheduler.state_dict(),\n 'epoch': epoch,\n #'model_ema': get_state_dict(model_ema),\n #'scaler': loss_scaler.state_dict(),\n 'args': args,\n }, checkpoint_path)\n\n test_stats = evaluate(data_loader_val, model, device)\n print(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n if test_stats[\"acc1\"] > max_accuracy:\n if args.output_dir:\n utils.save_on_master({\n 'model': model_without_ddp.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'lr_scheduler': lr_scheduler.state_dict(),\n 'epoch': epoch,\n #'model_ema': get_state_dict(model_ema),\n #'scaler': loss_scaler.state_dict(),\n 'args': args,\n }, output_dir / 'model_best.pth')\n max_accuracy = max(max_accuracy, test_stats[\"acc1\"])\n print(f'Max accuracy: {max_accuracy:.2f}%')\n\n log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},\n **{f'test_{k}': v for k, v in test_stats.items()},\n 'epoch': epoch,\n 'n_parameters': n_parameters}\n\n if args.output_dir and utils.is_main_process():\n with (output_dir / \"log.txt\").open(\"a\") as f:\n f.write(json.dumps(log_stats) + \"\\n\")\n\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n print('Training time {}'.format(total_time_str))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])\n args = parser.parse_args()\n if args.output_dir:\n Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n main(args)","sub_path":"main_train_custom.py","file_name":"main_train_custom.py","file_ext":"py","file_size_in_byte":20032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573814587","text":"s = \"foo(bar(baz))blim\"\n\ndef reverseInParentheses(inputString):\n for i in range(0, inputString.count(\"(\")):\n first_p = inputString.index(\")\")\n last_p = len(inputString) - (inputString[::-1]).index(\"(\")-1\n old = inputString[last_p+1:first_p]\n new = inputString[last_p+1:first_p][::-1]\n inputString = inputString.replace(old, new)\n inputString = list(inputString)\n inputString.pop(first_p)\n inputString.pop(last_p)\n inputString = \"\".join(inputString)\n print(inputString)\n return inputString\n\nprint(reverseInParentheses(s))","sub_path":"Python3/CodeSignal/Arcade/Intro/13 - reverseParentheses.py","file_name":"13 - reverseParentheses.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"613017549","text":"import yaml\n\nfrom graph_ter_seg.runner import BackboneRunner\nfrom graph_ter_seg.runner import ClassifierRunner\nfrom graph_ter_seg.runner import EvaluationRunner\nfrom graph_ter_seg.tools.configuration import get_parser\n\n\ndef main():\n parser = get_parser()\n args = parser.parse_args()\n if args.config is not None:\n with open(args.config, 'r') as f:\n default_arg = yaml.load(f, Loader=yaml.FullLoader)\n key = vars(args).keys()\n for k in default_arg.keys():\n if k not in key:\n print('WRONG ARG: {}'.format(k))\n assert (k in key)\n parser.set_defaults(**default_arg)\n args = parser.parse_args()\n\n if args.phase == 'backbone':\n runner = BackboneRunner(args)\n elif args.phase == 'classifier':\n runner = ClassifierRunner(args)\n elif args.phase == 'test':\n runner = EvaluationRunner(args)\n else:\n raise ValueError('Unknown phase.')\n\n runner.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main_segmentation.py","file_name":"main_segmentation.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"140634795","text":"# -*- coding: utf-8 -*-\n# See LICENSE file for full copyright and licensing details.\n\nfrom odoo import models, fields, api\n\n\nclass PurchaseOrderLine(models.Model):\n _inherit = 'purchase.order.line'\n\n origin = fields.Char('Origin')\n production_lot_id = fields.Many2one('stock.production.lot',\n 'Production Lot')\n customer_ref = fields.Char('Customer reference')\n origin_ref = fields.Char('Origin')\n\n\nclass PurchaseOrder(models.Model):\n _inherit = 'purchase.order'\n _order = \"create_date desc\"\n\n @api.multi\n def action_picking_create(self):\n picking_obj = self.env['stock.picking']\n move_obj = self.env['stock.move']\n picking_id = False\n for order in self:\n loc_id = order.partner_id.property_stock_supplier.id,\n istate = 'none'\n if order.invoice_method == 'picking':\n istate = '2binvoiced'\n address_id = order.dest_address_id.id or order.partner_id.id\n vals = {'origin': 'PO:%d:%s' % (order.id, order.name),\n 'type': 'in',\n 'address_id': address_id,\n 'invoice_state': istate,\n 'purchase_id': order.id or False,\n 'picking_type_id': order.picking_type_id.id or False}\n picking_id = picking_obj.create(vals)\n for order_line in order.order_line:\n if not order_line.product_id:\n continue\n if order_line.product_id.product_tmpl_id.type in ('product',\n 'consu'):\n dest = order.location_id.id\n prodlot_id = order_line.production_lot_id.id\n move_obj.create({'name': 'PO:' + order_line.name[:50],\n 'product_id': order_line.product_id.id,\n 'origin_ref': order.name,\n 'product_uos_qty': order_line.product_qty,\n 'product_uom': order_line.product_uom.id,\n 'date_planned': order_line.date_planned,\n 'location_id': loc_id,\n 'location_dest_id': dest,\n 'picking_id': picking_id.id,\n 'move_dest_id': order.location_id and\n order.location_id.id,\n 'state': 'assigned',\n 'prodlot_id': prodlot_id,\n 'customer_ref': order_line.customer_ref,\n 'purchase_line_id': order_line.id})\n purchase_order_dict = {'picking_ids': [(4, picking_id.id)]}\n order.write(purchase_order_dict)\n picking_id.signal_workflow('button_confirm')\n return picking_id.id\n\n @api.multi\n def wkf_confirm_order(self):\n production_obj = self.env['stock.production.lot']\n for order in self:\n l_id = 0\n for line in order.order_line:\n if line.production_lot_id:\n continue\n l_id += 1\n name = line.order_id and (str(line.order_id.name) + '/Line' +\n str(l_id)) or False\n production_lot_dict = {'product_id': line.product_id.id,\n 'name': name}\n production_lot_id = production_obj.create(production_lot_dict)\n line.write({'production_lot_id': production_lot_id.id})\n super(PurchaseOrder, self).wkf_confirm_order()\n return True\n\n @api.model\n def default_get(self, fields_list):\n res = super(PurchaseOrder, self).default_get(fields_list)\n return res\n","sub_path":"library/models/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"70807276","text":"import argparse\nimport sys\nimport json\nfrom datetime import datetime\nfrom datetime import timedelta\nimport os\n\n\ndef last_updated_date_added_1_second(RFC3339_format):\n \"\"\"add 1 second to final last updated date (state.json file)\"\"\"\n\n # standardizing to normal datetime\n standardized_datetime = datetime.strptime(\n str(RFC3339_format), \"%Y-%m-%dT%H:%M:%SZ\")\n\n # add 1 second\n added_1_second = standardized_datetime + timedelta(seconds=1)\n\n # convert back to RFC3339 date format\n converted_to_is_datetime = datetime.strftime(\n added_1_second, \"%Y-%m-%dT%H:%M:%SZ\")\n\n return converted_to_is_datetime\n\n\ndef access_config_and_state():\n \"\"\"retrieve the config & state items from config.json & state.json\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', help='Config file')\n parser.add_argument('-s', '--state', help='State file')\n args = parser.parse_args()\n\n if args.config and args.state:\n with open(args.config) as config_input, open(args.state) as state_input:\n config = json.load(config_input)\n state = json.load(state_input)\n else:\n print(\"Missing config or state file\")\n sys.exit(1)\n\n return config, state\n\n\ndef get_config_item(item):\n config_items, _ = access_config_and_state()\n return config_items[item]\n\n\ndef get_state_item(endpoint, item):\n _, state_items = access_config_and_state()\n return state_items[\"bookmarks\"][endpoint][item]\n\n\ndef get_last_updated_attribute(endpoint):\n \"\"\"get the attribute name in each endpoint data that represent the last_updated timestamp\"\"\"\n\n # emulating switch/case statement\n return {\n 'repositories': lambda: 'updated_at',\n 'branches': lambda: '',\n 'commits': lambda: 'committer_date'\n }.get(endpoint, lambda: None)()\n\n\ndef update_final_state_file(endpoint):\n\n # retrieve state items from state.json\n _, state_items = access_config_and_state()\n\n last_updated_staging_item = get_state_item(\n endpoint, 'last_updated_staging')\n\n path_to_state = os.path.join(os.path.dirname(__file__), '../state.json')\n\n with open(path_to_state, 'w+') as state_file:\n state_items[\"bookmarks\"][endpoint]['last_updated_final'] = last_updated_date_added_1_second(\n last_updated_staging_item)\n state_file.write(json.dumps(state_items))\n\n return None\n\n\ndef update_staging_state_file(endpoint, row_data):\n \"\"\"to update the last_updated attribute value in state.json\"\"\"\n\n # retrieve state items from state.json\n _, state_items = access_config_and_state()\n\n # retrieve last_updated attribute name for selected endpoint\n last_updated = get_last_updated_attribute(endpoint)\n\n path_to_state = os.path.join(os.path.dirname(__file__), '../state.json')\n\n if last_updated in row_data:\n if row_data[last_updated] > get_state_item(endpoint, \"last_updated_staging\"):\n with open(path_to_state, 'w+') as state_file:\n state_items[\"bookmarks\"][endpoint]['last_updated_staging'] = row_data[last_updated]\n state_file.write(json.dumps(state_items))\n\n return None\n","sub_path":"tap-github/src/config_and_state.py","file_name":"config_and_state.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"88055394","text":"import torch\nimport nibabel as nib\nimport numpy as np\nfrom nilearn.image import resample_img\nfrom torchvision import transforms\nimport scipy.misc\nfrom .options import Options\nfrom .model import Model\nfrom PIL import Image\n\ndef _toTensor(nibImg):\n\n img = Image.fromarray(nibImg).convert('RGB') \n img = transforms.ToTensor()(img)\n img = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(img)\n img = img.view(1, img.shape[0], img.shape[1], img.shape[2])\n return img\n\ndef _RGBtoGray(A):\n gray = A[:,0, ...] * 0.299 + A[:,1, ...] * 0.587 + A[:,2, ...] * 0.114\n return gray\n\ndef main():\n opt = Options().parse()\n assert(opt.input.endswith('nii.gz'))\n inputVolume = nib.load(opt.input)\n N = inputVolume.shape[2]\n target_shape = (opt.fineSize, opt.fineSize, N)\n data = resample_img(inputVolume, inputVolume.affine, target_shape=target_shape).get_data()\n\n model = Model()\n model.initialize(opt)\n output = torch.FloatTensor(N, 3, opt.fineSize, opt.fineSize)\n for i in range(N):\n if opt.verbose:\n print('process slice %d' % i)\n model.set_input({'A': _toTensor(data[:,:,i])})\n model.forward()\n output[i] = model.fake_B.detach().cpu()\n\n output = _RGBtoGray(output)\n outputImg = nib.Nifti1Image(output.permute(1,2,0).numpy(), inputVolume.affine)\n outputfile = opt.output\n if not outputfile.endswith(\"nii.gz\"):\n outputfile = \"%s.nii.gz\" % (outputfile)\n print('save output as %s' % outputfile)\n nib.save(outputImg, outputfile)\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","sub_path":"mri2mri/mri2mri.py","file_name":"mri2mri.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"25130210","text":"import math\r\nimport cmath\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.spines as sp\r\n\r\nphi = ((1 + math.sqrt(5))/2)\r\nx = 0\r\ny = 0\r\nz = complex(x, y)\r\nn = 500\r\n\r\n# Initialising lists to store the real and complex values\r\nreal = []\r\nimag = []\r\n\r\n# Calculating and storing the real and imaginary parts of the complex numbers\r\nfor i in range(0, n):\r\n z = ((phi**(i/100))-((-1/phi)**(i/100)))/math.sqrt(5)\r\n real.append(z.real)\r\n imag.append(z.imag)\r\n\r\n# Turn the data into a format that can be stored inside of a pandas dataframe\r\ndata = {'Real': real,\r\n 'Imaginary': imag\r\n }\r\n\r\n# Create a dataframe and store the data inside it\r\ndf = pd.DataFrame(data, columns = ['Real', 'Imaginary'])\r\n\r\n# Retrieve the values for plotting\r\nx_vals = df['Real']\r\ny_vals = df['Imaginary']\r\n\r\n# Change the position of the x-axis to be centred on zero\r\n# and hide the now-redundant spines.\r\nfig = plt.figure(figsize=(8, 6))\r\nax = fig.add_subplot(1, 1, 1)\r\nax.spines['bottom'].set_position(('data', 0))\r\nax.spines['top'].set_visible(False)\r\nax.spines['right'].set_visible(False)\r\n\r\nplt.xlabel(\"Re(z)\")\r\nplt.ylabel(\"Im(z)\")\r\n\r\n# Plot and show the graph\r\nplt.plot(x_vals, y_vals)\r\nplt.show()\r\n","sub_path":"complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"143441704","text":"## Script (Python) \"createDoc\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=model='', grp='', field='', workflow_action=''\n##title=copiato in gisweb.iol, DA CANCELLARE\n##\nfrom Products.CMFPlomino.PlominoUtils import json_loads, json_dumps, DateToString, Now, open_url\nfrom gisweb.utils import serialDoc, report, Type, requests_post, attachThis, os_path_join\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.utils import normalizeString\n\nprintServer = 'iol.vmserver'\n\nif context.portal_type != 'PlominoDocument':\n return ''\n\ndoc = context\n\nurl = context.appProperties('ws_createdocx_URL')\nurl1 = context.appProperties('ws_readdocument_URL')\nfilename = model\n\nif \"\"\"\\\\\"\"\" in filename:\n filename = filename.split(\"\\\\\")[-1]\nfilename = '.'.join(\n [normalizeString(s, encoding='utf-8') \n for s in filename.split('.')])\n\ndocurl = \"%s?app=%s&id=%s&filename=%s\" %(url1,doc.getItem('tipo_app',''),doc.getId(),filename)\n\nquery = dict(\n app = context.REQUEST.get('test_app') or doc.getItem('tipo_app'),\n model = model,\n group = grp,\n dataType = 'JSON',\n #mode = 'show',\n data = serialDoc(context, serial_as='json'),\n id = context.id,\n filename = filename,\n download = 'false'\n)\n\n\ntry:\n result = requests_post(url,query, 'json', timeout=30)\nexcept Exception as error:\n plone_tools = getToolByName(context.getParentDatabase().aq_inner, 'plone_utils')\n msg = ('%s: %s' % (Type(error), error), 'error')\n context.setItem('test',msg)\n plone_tools.addPortalMessage(*msg, request=context.REQUEST)\n doc.REQUEST.RESPONSE.redirect(context.absolute_url())\nelse:\n valueToSubmit = result['json']['filename']\n\n\n#dummy = attachThis(context, valueToSubmit, field, filename=model, overwrite=True)\nres = open_url(docurl,asFile=False)\n(f,c) = doc.setfile(res,filename=filename,overwrite=True,contenttype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')\nif f and c:\n doc.setItem(field,{filename:c})\n#dummy = attachThis(context, res, field, filename=model, overwrite=True)\nif workflow_action:\n #wf = getToolByName(context, 'portal_workflow')\n #wf.doActionFor(context, workflow_action)\n context.REQUEST.RESPONSE.redirect(context.absolute_url()+'/content_status_modify?workflow_action='+workflow_action)\nelse:\n context.REQUEST.RESPONSE.redirect(context.absolute_url())\n","sub_path":"src/gisweb/iol/skins/iol_templates/iol_old/createDoc.py","file_name":"createDoc.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453741050","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"basket\", \"0005_auto_20150604_1450\"),\n (\"order\", \"0003_auto_20150113_1629\"),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name=\"line\",\n options={},\n ),\n migrations.AlterModelOptions(\n name=\"order\",\n options={},\n ),\n migrations.AddField(\n model_name=\"line\",\n name=\"basket_line\",\n field=models.OneToOneField(\n to=\"basket.Line\",\n null=True,\n related_name=\"order_line\",\n on_delete=models.CASCADE,\n ),\n ),\n migrations.AddField(\n model_name=\"order\",\n name=\"is_tax_known\",\n field=models.BooleanField(default=True),\n ),\n ]\n","sub_path":"sandbox/order/migrations/0004_auto_20160325_1012.py","file_name":"0004_auto_20160325_1012.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"459450323","text":"from dt_shell import DTCommandAbs, DTShell, dtslogger\nfrom dt_shell.commands_ import _get_commands\n\n\nclass DTCommand(DTCommandAbs):\n help = \"Installs a new command.\"\n\n @staticmethod\n def command(shell: DTShell, args):\n # get installed commands\n installed = set(shell.commands.keys())\n # get the commands that are available but not installed\n res = _get_commands(shell.commands_path, all_commands=True)\n all_commands = set(res.keys()) if res is not None else set()\n not_installed = all_commands.difference(installed)\n # get list of commands to install / already-installed / not-installable\n requested_to_install = set(args)\n not_installable = requested_to_install.difference(all_commands)\n already_installed = requested_to_install.intersection(installed)\n to_install = requested_to_install.intersection(all_commands).difference(installed)\n need_reload = False\n # already installed\n for cmd in already_installed:\n dtslogger.info(\"The command `%s` is already installed.\" % cmd)\n # not installable\n for cmd in not_installable:\n dtslogger.info(\"The command `%s` cannot be found.\" % cmd)\n # install\n for cmd in to_install:\n dtslogger.info(\"Installing command `%s`...\" % cmd)\n shell.enable_command(cmd)\n need_reload = True\n dtslogger.info(\"Done!\")\n # update list of commands\n if need_reload:\n dtslogger.info(\"Updating index...\")\n shell.reload_commands()\n dtslogger.info(\"Done!\")\n else:\n dtslogger.info(\"Nothing to do.\")\n return True\n\n @staticmethod\n def complete(shell, word, line):\n # get installed commands\n installed = set(shell.commands.keys())\n # get the commands that are available but not installed\n res = shell._get_commands(shell.commands_path, all_commands=True)\n all_commands = set(res.keys()) if res is not None else set()\n not_installed = all_commands.difference(installed)\n # remove the core commands\n installable = not_installed.difference(shell.core_commands)\n # return not installed commands\n return list(installable)\n","sub_path":"install/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"77195233","text":"import os\nfrom pprint import pprint\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom basic.evaluator import ForwardEvaluator\nfrom basic.graph_handler import GraphHandler\nfrom basic.model import get_multi_gpu_models\n\nfrom basic.main import set_dirs\nfrom basic.read_data import read_data, update_config, DataSet\nfrom squad.prepro import prepro_single_question_with_context\n\nflags = tf.app.flags\n\n# Names and directories\nflags.DEFINE_string(\"model_name\", \"basic\", \"Model name [basic]\")\nflags.DEFINE_string(\"dataset\", \"dev\", \"Dataset [test]\")\n#flags.DEFINE_string(\"data_dir\", \"/Applications/MAMP/htdocs/bi-att-flow/data/squad\", \"Data dir [data/squad]\")\nflags.DEFINE_string(\"data_dir\", \"\", \"Data dir [data/squad]\")\nflags.DEFINE_string(\"run_id\", \"0\", \"Run ID [0]\")\nflags.DEFINE_string(\"out_base_dir\", \"out\", \"out base dir [out]\")\nflags.DEFINE_string(\"forward_name\", \"single\", \"Forward name [single]\")\nflags.DEFINE_string(\"answer_path\", \"\", \"Answer path []\")\nflags.DEFINE_string(\"eval_path\", \"data/squad\", \"Eval path []\")\n# flags.DEFINE_string(\"load_path\", \"\", \"Load path []\")\n# flags.DEFINE_string(\"load_path\", \"/Applications/MAMP/htdocs/bi-att-flow/save/40/save\", \"Load path []\")\nflags.DEFINE_string(\"load_path\", \"\", \"Load path []\")\n#flags.DEFINE_string(\"load_path\", \"out/basic/00/save/basic-20000\", \"Load path []\")\n# \"$root_dir/$num/shared.json\"\n#flags.DEFINE_string(\"shared_path\", \"/Applications/MAMP/htdocs/bi-att-flow/save/40/shared.json\", \"Shared path []\")\nflags.DEFINE_string(\"shared_path\", \"\", \"Shared path []\")\nflags.DEFINE_integer(\"eval_num_batches\", 0, \"eval num batches [100]\")\n\n# Device placement\nflags.DEFINE_string(\"device\", \"/cpu:0\", \"default device for summing gradients. [/cpu:0]\")\nflags.DEFINE_string(\"device_type\", \"gpu\", \"device for computing gradients (parallelization). cpu | gpu [gpu]\")\nflags.DEFINE_integer(\"num_gpus\", 1, \"num of gpus or cpus for computing gradients [1]\")\n\n# Essential training and test options\n#flags.DEFINE_string(\"mode\", \"test\", \"trains | test | forward [test]\")\nflags.DEFINE_string(\"mode\", \"forward\", \"trains | test | forward [test]\")\nflags.DEFINE_boolean(\"load\", True, \"load saved data? [True]\")\nflags.DEFINE_bool(\"single\", False, \"supervise only the answer sentence? [False]\")\nflags.DEFINE_boolean(\"debug\", False, \"Debugging mode? [False]\")\nflags.DEFINE_bool('load_ema', True, \"load exponential average of variables when testing? [True]\")\nflags.DEFINE_bool(\"eval\", True, \"eval? [True]\")\n\n# Training / test parameters\nflags.DEFINE_integer(\"batch_size\", 1, \"Batch size [60]\")\nflags.DEFINE_integer(\"val_num_batches\", 100, \"validation num batches [100]\")\nflags.DEFINE_integer(\"test_num_batches\", 0, \"test num batches [0]\")\nflags.DEFINE_integer(\"num_epochs\", 12, \"Total number of epochs for training [12]\")\nflags.DEFINE_integer(\"num_steps\", 20000, \"Number of steps [20000]\")\nflags.DEFINE_integer(\"load_step\", 0, \"load step [0]\")\nflags.DEFINE_float(\"init_lr\", 0.5, \"Initial learning rate [0.5]\")\nflags.DEFINE_float(\"input_keep_prob\", 0.8, \"Input keep prob for the dropout of LSTM weights [0.8]\")\nflags.DEFINE_float(\"keep_prob\", 0.8, \"Keep prob for the dropout of Char-CNN weights [0.8]\")\nflags.DEFINE_float(\"wd\", 0.0, \"L2 weight decay for regularization [0.0]\")\nflags.DEFINE_integer(\"hidden_size\", 100, \"Hidden size [100]\")\nflags.DEFINE_integer(\"char_out_size\", 100, \"char-level word embedding size [100]\")\nflags.DEFINE_integer(\"char_emb_size\", 8, \"Char emb size [8]\")\nflags.DEFINE_string(\"out_channel_dims\", \"100\", \"Out channel dims of Char-CNN, separated by commas [100]\")\nflags.DEFINE_string(\"filter_heights\", \"5\", \"Filter heights of Char-CNN, separated by commas [5]\")\nflags.DEFINE_bool(\"finetune\", False, \"Finetune word embeddings? [False]\")\nflags.DEFINE_bool(\"highway\", True, \"Use highway? [True]\")\nflags.DEFINE_integer(\"highway_num_layers\", 2, \"highway num layers [2]\")\nflags.DEFINE_bool(\"share_cnn_weights\", True, \"Share Char-CNN weights [True]\")\nflags.DEFINE_bool(\"share_lstm_weights\", True, \"Share pre-processing (phrase-level) LSTM weights [True]\")\nflags.DEFINE_float(\"var_decay\", 0.999, \"Exponential moving average decay for variables [0.999]\")\n\n# Optimizations\nflags.DEFINE_bool(\"cluster\", True, \"Cluster data for faster training [False]\")\nflags.DEFINE_bool(\"len_opt\", True, \"Length optimization? [False]\")\nflags.DEFINE_bool(\"cpu_opt\", True, \"CPU optimization? GPU computation can be slower [False]\")\n\n# Logging and saving options\nflags.DEFINE_boolean(\"progress\", True, \"Show progress? [True]\")\nflags.DEFINE_integer(\"log_period\", 100, \"Log period [100]\")\nflags.DEFINE_integer(\"eval_period\", 1000, \"Eval period [1000]\")\nflags.DEFINE_integer(\"save_period\", 1000, \"Save Period [1000]\")\nflags.DEFINE_integer(\"max_to_keep\", 20, \"Max recent saves to keep [20]\")\nflags.DEFINE_bool(\"dump_eval\", True, \"dump eval? [True]\")\nflags.DEFINE_bool(\"dump_answer\", True, \"dump answer? [True]\")\nflags.DEFINE_bool(\"vis\", False, \"output visualization numbers? [False]\")\nflags.DEFINE_bool(\"dump_pickle\", True, \"Dump pickle instead of json? [True]\")\nflags.DEFINE_float(\"decay\", 0.9, \"Exponential moving average decay for logging values [0.9]\")\n\n# Thresholds for speed and less memory usage\nflags.DEFINE_integer(\"word_count_th\", 10, \"word count th [100]\")\nflags.DEFINE_integer(\"char_count_th\", 50, \"char count th [500]\")\nflags.DEFINE_integer(\"sent_size_th\", 400, \"sent size th [64]\")\nflags.DEFINE_integer(\"num_sents_th\", 8, \"num sents th [8]\")\nflags.DEFINE_integer(\"ques_size_th\", 30, \"ques size th [32]\")\nflags.DEFINE_integer(\"word_size_th\", 16, \"word size th [16]\")\nflags.DEFINE_integer(\"para_size_th\", 256, \"para size th [256]\")\n\n# Advanced training options\nflags.DEFINE_bool(\"lower_word\", True, \"lower word [True]\")\nflags.DEFINE_bool(\"squash\", False, \"squash the sentences into one? [False]\")\nflags.DEFINE_bool(\"swap_memory\", True, \"swap memory? [True]\")\nflags.DEFINE_string(\"data_filter\", \"max\", \"max | valid | semi [max]\")\nflags.DEFINE_bool(\"use_glove_for_unk\", True, \"use glove for unk [False]\")\nflags.DEFINE_bool(\"known_if_glove\", True, \"consider as known if present in glove [False]\")\nflags.DEFINE_string(\"logit_func\", \"tri_linear\", \"logit func [tri_linear]\")\nflags.DEFINE_string(\"answer_func\", \"linear\", \"answer logit func [linear]\")\nflags.DEFINE_string(\"sh_logit_func\", \"tri_linear\", \"sh logit func [tri_linear]\")\n\n# Ablation options\nflags.DEFINE_bool(\"use_char_emb\", True, \"use char emb? [True]\")\nflags.DEFINE_bool(\"use_word_emb\", True, \"use word embedding? [True]\")\nflags.DEFINE_bool(\"q2c_att\", True, \"question-to-context attention? [True]\")\nflags.DEFINE_bool(\"c2q_att\", True, \"context-to-question attention? [True]\")\nflags.DEFINE_bool(\"dynamic_att\", False, \"Dynamic attention [False]\")\n\n\nclass Inference(object):\n def __init__(self):\n self.config = flags.FLAGS\n\n # Set directories for temporary files\n self.config.out_dir = os.path.join(self.config.out_base_dir, self.config.model_name, str(self.config.run_id).zfill(2))\n set_dirs(self.config)\n\n # TODO: Can we refactor this?\n self.config.max_sent_size = self.config.sent_size_th\n self.config.max_num_sents = self.config.num_sents_th\n self.config.max_ques_size = self.config.ques_size_th\n self.config.max_word_size = self.config.word_size_th\n self.config.max_para_size = self.config.para_size_th\n\n # Read trained dataset and update word embedding matrix.\n # We only really need this to get word2idx, idx2word\n # and the word embedding matrix\n self.data = read_data(self.config, self.config.dataset, True)\n self.update_embedding_matrix()\n\n # Get the models and the evaluator to get predictions\n self.model = get_multi_gpu_models(self.config)[0]\n self.evaluator = ForwardEvaluator(\n config=self.config,\n model=self.model,\n tensor_dict=models.tensor_dict if self.config.vis else None\n )\n\n # Initialize TF session and graph handler\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n self.graph_handler = GraphHandler(self.config, self.model)\n self.graph_handler.initialize(self.sess)\n\n pprint(flags.FLAGS.__dict__, indent=2)\n\n def update_embedding_matrix(self):\n update_config(self.config, [self.data])\n if self.config.use_glove_for_unk:\n # Get the word2vec or lower_word2vec\n word2vec_dict = self.data.shared['lower_word2vec'] if self.config.lower_word else self.data.shared['word2vec']\n new_word2idx_dict = self.data.shared['new_word2idx']\n idx2vec_dict = {idx: word2vec_dict[word] for word, idx in new_word2idx_dict.items()}\n new_emb_mat = np.array([idx2vec_dict[idx] for idx in range(len(idx2vec_dict))], dtype='float32')\n self.config.new_emb_mat = new_emb_mat\n\n def predict(self, context, question):\n\n batch_data_prepro = prepro_single_question_with_context(context, question)\n pprint(batch_data_prepro)\n\n batch_data = ((0,), DataSet(\n data=batch_data_prepro,\n data_type=self.config.dataset,\n shared=self.data.shared\n ))\n prediction = self.evaluator.get_evaluation(self.sess, batch_data)\n\n p = prediction.id2answer_dict[\n list(prediction.id2answer_dict.keys())[0]\n ]\n s = prediction.id2answer_dict['scores'][\n list(prediction.id2answer_dict['scores'].keys())[0]\n ]\n\n return p, s\n\nif __name__ == \"__main__\":\n\n inference = Inference()\n context = 'More than 26,000 square kilometres (10,000 sq mi) of Victorian farmland are sown for grain, mostly in the state west. More than 50% of this area is sown for wheat, 33% is sown for barley and 7% is sown for oats. A further 6,000 square kilometres (2,300 sq mi) is sown for hay. In 2003–04, Victorian farmers produced more than 3 million tonnes of wheat and 2 million tonnes of barley. Victorian farms produce nearly 90% of Australian pears and third of apples. It is also a leader in stone fruit production. The main vegetable crops include asparagus, broccoli, carrots, potatoes and tomatoes. Last year, 121,200 tonnes of pears and 270,000 tonnes of tomatoes were produced.'\n question = 'What percentage of farmland grows wheat? '\n print(inference.predict(context, question))","sub_path":"basic/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":10265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"90802181","text":"\n\nclass UtilTransformation:\n def __init__(self):\n pass\n\n def sort_document_array(self, array=None, array_to_sort='', ascend=True):\n \"\"\"\n Sort the input array by dict \n :param array: the list to manipulate.\n :param array_to_sort: the item name to sort, which must be array type.\n :param ascend: default to True, set False to sort descend.\n :return: the sorted array\n \"\"\"\n if array is None:\n return None\n else:\n result = []\n l = 0\n for i in array:\n l = len(i[array_to_sort])\n offset = 0\n flag_quit = False\n\n if len(result) == 0:\n # Empty list, just append\n result.append(i)\n # print_array_order(result,array_to_sort,'append at empty')\n else:\n\n for ii in result:\n len_of_result = len(ii[array_to_sort])\n # print('comparing array item(%s) > result array(%s):%s' %(l,len_of_result,l>len_of_result))\n if ascend:\n if len_of_result > l and not quit:\n result.insert(offset, i)\n flag_quit = True\n # print_array_order(result,array_to_sort,'insert')\n offset += 1\n\n if not flag_quit:\n # Still no quit means no small array found, just append\n result.append(i)\n # print_array_order(result,array_to_sort,'append at last')\n\n return result\n\n def print_array_order(self, array=None, array_to_sort='', action=''):\n print('============= %s' % action)\n for i in array:\n print(len(i[array_to_sort]))\n","sub_path":"CME/Utilities/utilTransformation.py","file_name":"utilTransformation.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68552527","text":"#!/usr/bin/env python3\n\nimport os, re, random, copy, time, sys\nimport numpy as np\nimport matplotlib.pyplot as plt # for output generalization error graphs\nfrom myClass import Theta # for classifier's parameters\nfrom functions import func_s # for classifier\nfrom adam import adam # defines adam algorithm\nfrom hyperParameters import hyperParameters # defines hyperParameters\n\n# hyperParameters\nT = hyperParameters.T\nD = hyperParameters.D\nbatch_size = hyperParameters.batch_size\nnum_of_epochs = hyperParameters.num_of_epochs\n\n# directory\ndir = os.getcwd() + '/train/'\n\n# train files\nfiles = [file for file in os.listdir(dir) if re.search('_graph.txt', file)]\nnum_of_files = len(files)\n\ntrain_size = num_of_files//2\nvalid_size = num_of_files - train_size\n\n# normal_form_matrix\n# This is the (m, n) matrix whose elements are Gaussian normal.\ndef normal_form_matrix(mu, sigma, m, n):\n if n == 1:\n return np.random.normal(loc = mu, scale = sigma, size = m).T\n else:\n return np.random.normal(loc = mu, scale = sigma, size = m*n).reshape((m,n))\n\n# initialization\ntheta = Theta(\n normal_form_matrix(0, 0.4, D, D),\n normal_form_matrix(0, 0.4, D, 1),\n 0\n)\nmoment_1 = Theta(\n np.zeros((D,D)),\n np.zeros(D).T,\n 0\n)\nmoment_2 = Theta(\n np.zeros((D,D)),\n np.zeros(D).T,\n 0\n)\n\n# classifier\ndef classifier(graph_file, theta):\n file = open(graph_file)\n N, adj = int(file.readline()), []\n for i in range(N):\n adj.append([int(x) for x in file.readline().split()])\n adj = np.array(adj)\n file.close()\n\n s = func_s(adj, theta)\n p = 1/(1+np.exp(-s))\n\n if p > 1/2:\n return 1\n else:\n return 0\n\n# average loss\ndef avg_loss(b_files, theta):\n tmp_loss = 0\n batch_size = len(b_files)\n for graph_file in b_files:\n label_file = graph_file.rstrip('_graph.txt') + '_label.txt'\n\n file = open(dir+graph_file)\n N, adj = int(file.readline()), []\n for i in range(N):\n adj.append([int(x) for x in file.readline().split()])\n adj = np.array(adj)\n file.close()\n\n file = open(dir+label_file)\n y = int(file.readline())\n file.close()\n\n tmp_loss += loss(adj, y, theta)\n\n return tmp_loss/batch_size\n\n# validation\ndef avg_accuracy(v_files, theta):\n hit_counter = 0\n for graph_file in v_files:\n label_file = graph_file.rstrip('_graph.txt') + '_label.txt'\n\n file = open(dir+label_file)\n y = int(file.readline())\n file.close()\n\n if classifier(graph_file, theta) == y:\n hit_counter += 1\n\n return hit_counter/len(v_files)\n\n# main\nif __name__ == '__main__':\n # output list\n loss_list_for_train, loss_list_for_valid = [], []\n accuracy_list_for_train, accuracy_list_for_valid = [], []\n\n # split the dataset to training dataset and validation dataset\n train_files = random.sample(files, train_size)\n valid_files = [x for x in files if x not in train_files]\n\n # momentum_sgd\n toolbar_width = train_size//batch_size # progress bar\n for i in range(num_of_epochs):\n tmp_train_files = copy.copy(train_files)\n\n # progress bar (begin)\n sys.stdout.write(\"Epoch {}: \".format(i+1))\n sys.stdout.write(\"[%s]\" % (\" \" * toolbar_width))\n sys.stdout.flush()\n sys.stdout.write(\"\\b\" * (toolbar_width+1))\n\n # an epoch\n for j in range(train_size//batch_size):\n batch_files = random.sample(tmp_train_files, batch_size)\n for file in batch_files:\n tmp_train_files.remove(file)\n \n theta, moment_1, moment_2 = adam(batch_files, theta, moment_1, moment_2)\n\n # progress bar\n sys.stdout.write(\"#\")\n sys.stdout.flush()\n\n # progress bar (end)\n sys.stdout.write(\"] Done.\\n\")\n\n loss_list_for_train.append(avg_loss(train_files, theta))\n loss_list_for_valid.append(avg_loss(valid_files, theta))\n accuracy_list_for_train.append(avg_accuracy(train_files, theta))\n accuracy_list_for_valid.append(avg_accuracy(valid_files, theta))\n\n # plot graphs\n title = \"SGD loss on train_data\"\n title = \"M \" + title\n list = loss_list_for_train\n plt.subplot(2,2,1)\n plt.title(title)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.plot(range(num_of_epochs), list)\n\n title = \"SGD loss on valid_data\"\n title = \"M \" + title\n list = loss_list_for_valid\n plt.subplot(2,2,2)\n plt.title(title)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.plot(range(num_of_epochs), list)\n\n title = \"Accuracy on train_data\"\n list = accuracy_list_for_train\n plt.subplot(2,2,3)\n plt.title(title)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.ylim(0,1)\n plt.plot(range(num_of_epochs), list)\n\n title = \"Accuracy on valid_data\"\n list = accuracy_list_for_valid\n plt.subplot(2,2,4)\n plt.title(title)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.ylim(0,1)\n plt.plot(range(num_of_epochs), list)\n\n plt.show()\n","sub_path":"src/testAdam.py","file_name":"testAdam.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"159855385","text":"from django.db import models\nfrom .product import Product\nfrom .category import Category\nfrom datetime import date\n# from simple_history.models import HistoricalRecords\n\n\nclass CatalogChange(models.Model):\n\n STR_PATTERN = \"Producte: {} Categoria:{} Unitats Modificades: {}\"\n\n product_id_change = models.ForeignKey(Product, related_name='product_id_change', on_delete=models.SET_NULL, null=True, verbose_name='Producte')\n category_id_change = models.ForeignKey(Category, related_name='category_product_change', on_delete=models.SET_NULL, null=True,\n verbose_name='Categoria producte')\n quantity_modify = models.PositiveIntegerField(default=0, verbose_name='Quantitat modificada')\n\n date = models.DateField(default=date.today)\n\n # Contains all the changes of the object\n # history = HistoricalRecords()\n\n class Meta:\n unique_together = (\"product_id_change\", \"category_id_change\")\n\n def __str__(self):\n return CatalogChange.STR_PATTERN.format(self.product_id_change, self.category_id_change, self.quantity_modify)\n\n# Aqui el que sols fem es guardar la cantitad del prudcte, pero a la vegada es utilitzar per relaciona la informació del\n# producte amb la de la seva categoria, així fent els querrys possibles més sencills i sense trencarnos el cap\n\n","sub_path":"warehouseapp/models/catalogchange.py","file_name":"catalogchange.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"123660437","text":"import pandas as pd\nimport numpy as np\nimport random\nimport heapq\n\nfrom surprise import AlgoBase\nfrom surprise import Dataset\nfrom surprise import Reader\nfrom surprise import PredictionImpossible\nfrom surprise.prediction_algorithms.knns import SymmetricAlgo\n\n\ntraining_set = pd.read_csv('additional_files/train.dat',delim_whitespace=True)\ntest_set = pd.read_csv('1540226926_0229266_test.dat',delim_whitespace=True)\n\n\nclass customRecommender(SymmetricAlgo):\n def __init__(self):\n SymmetricAlgo.__init__(self)\n self.k = 21\n self.min_k = 1\n\n def fit(self, trainset):\n SymmetricAlgo.fit(self, trainset)\n self.sim = self.compute_similarities()\n return self\n\n def estimate(self, u, i):\n # checks if there is data for given user and movie IDs\n if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):\n raise PredictionImpossible('User and/or item is unkown.')\n\n x, y = self.switch(u, i)\n # gets the nearest neighbors for each user\n neighbors = [(self.sim[x, x2], r) for (x2, r) in self.yr[y]]\n k_neighbors = heapq.nlargest(self.k, neighbors, key=lambda t: t[0])\n\n total_similarity = 0\n total_ratings = 0\n current_k = 0\n for (sim, r) in k_neighbors:\n if sim > 0:\n total_similarity += sim\n total_ratings += sim * r\n current_k += 1\n\n unknown_user_rating = total_ratings / total_similarity\n\n return unknown_user_rating\n\nrecommender = customRecommender()\nreader = Reader(rating_scale=(0, 5)) # sets min and max of rating system\n\n# reads in training set and configes it for recommending\ndata = Dataset.load_from_df(training_set[['userID', 'movieID', 'rating']], reader)\ntrainset = data.build_full_trainset()\nrecommender.fit(trainset)\n\nresults = []\nprint('🎯 Working... 🎯')\n# rates each test input\nfor i, test_row in test_set.iterrows():\n test_userID = test_row['userID']\n test_movieID = test_row['movieID']\n pred = recommender.predict(test_userID, test_movieID).est\n results.append(pred)\n\n\noutput_file = str('rating_output'+str(random.randint(1,1001))+'.dat')\nfile = open(output_file,'w')\nfor i in range(0,len(results)):\n file.write(str(results[i]) + '\\n')\nprint('Finished! Results in ➡️',output_file)\n","sub_path":"boisseau_perez-isla_hw4/src/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362473814","text":"from sklearn.datasets import load_iris\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import metrics\r\nimport xgboost as xgb\r\n\r\niris = load_iris()\r\nX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=0)\r\n\r\n# XGBoost need DMatrix instead of numpy arrays\r\ntrain_data = xgb.DMatrix(X_train, label=y_train)\r\ntest_data = xgb.DMatrix(X_test, label=y_test)\r\n\r\nparam = {\r\n 'max_depth': 4,\r\n 'eta': 0.3,\r\n 'objective': 'multi:softmax', # softmax=categorical, sigmoid=binary classification\r\n 'num_class': 3} \r\nepochs = 20\r\n\r\nmodel = xgb.train(param, train_data, epochs)\r\npredictions = model.predict(test_data)\r\n\r\nacc = metrics.accuracy_score(y_test, predictions)\r\nprint(\"Accuracy: {}\".format(acc))","sub_path":"XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"32840819","text":"import tweepy\nimport urllib.request\nimport re\nimport time\nimport datetime\nimport sys\nimport pymysql\n\n\n# 初期変数設定\n# 今の時間を定義\nnow = datetime.datetime.now()\n# 各種キーをセット\nSCREEN_NAME = 'MsContest_'\nCONSUMER_KEY = 'uE4aWwteDqIWrjGdghu1MVQPg'\nCONSUMER_SECRET = 'X2S8yWjXndq0pMbgtk4VyLbZ4AcsFum7oyFZmz9nMrDP4LJ0ii'\nACCESS_TOKEN = '1040912339061497856-ttMXdsDt7CT2WfZQiNkYPMrlN2BQEp'\nACCESS_SECRET = 'seGuv2O60qV19ue9GJMWd18PaLqOi191RP3BIbLAK3DeN'\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\n\n# APIインスタンスを作成\napi = tweepy.API(auth)\n\n# SQLのログイン情報を記載\nconnector = pymysql.connect(\n host='127.0.0.1',\n db='mscolle',\n user='root',\n passwd='root',\n charset='utf8',\n)\n\n\n# get_favorittersを定義\ndef get_favoritters(post_id):\n try:\n json_data = urllib.request.urlopen('https://twitter.com/i/activity/favorited_popup?id=' + str(post_id)).read()\n json_data = json_data.decode(\"utf8\")\n found_ids = re.findall(r'data-user-id=\\\\\"+\\d+', json_data)\n unique_ids = list(set([re.findall(r'\\d+', match)[0] for match in found_ids]))\n return unique_ids\n except urllib.request.HTTPError:\n return False\n\n\n# TwitterのIDをデータベースから取得し、twitter_idsに保存\ndef get_twitter_ids():\n twitter_ids = []\n with connector.cursor() as cursor:\n sql = \"select twitter_url from mom_user_info2018 where twitter_url != 'NULL'\"\n cursor.execute(sql)\n results = cursor.fetchall()\n\n for result in results:\n for res in result:\n twitter_id = res.replace(\"https://twitter.com/\", \"\")\n twitter_ids.append(twitter_id)\n return twitter_ids\n\n\n# データベースにフォローをしたというログを保存する。\ndef twitter_follow_log(screen_name, follow_type, follow_keyword=None):\n log_data = []\n # idをデータベー��から出す。\n with connector.cursor() as cursor:\n\n id_select_sql = \"\"\"select id, follow_count from twitter_follow_log where screen_name = %s\"\"\"\n cursor.execute(id_select_sql, screen_name)\n log_id = cursor.fetchall()\n if log_id:\n # follow_count更新?\n # refollow?\n log_data.append(log_id[0][1] + 1) # follow_count追加\n log_data.append(1) # refollow_flg\n log_data.append(now) # refollow_at\n log_data.append(log_id[0][0]) # id保持\n update_sql = \"\"\"\n update mscolle.twitter_follow_log set follow_count = %s, refollow_flg = %s, refollow_at = %s where id = %s \n \"\"\"\n cursor.execute(update_sql, log_data)\n connector.commit()\n else:\n # 新規追加\n max_id_select_sql = \"\"\"select max(id) + 1 from twitter_follow_log\"\"\"\n cursor.execute(max_id_select_sql)\n max_id = cursor.fetchall()\n log_data.append(max_id[0][0]) # id保持\n log_data.append(1) # follow_count\n log_data.append(screen_name) # screen_name\n log_data.append(now) # follow_at\n log_data.append(follow_type) # follow_type\n log_data.append(follow_keyword) # follow_keyword\n insert_sql = \"\"\"\n insert into mscolle.twitter_follow_log (id, follow_count, screen_name, follow_at, follow_type, follow_keyword)\n values(%s,%s,%s,%s,%s,%s)\n \"\"\"\n cursor.execute(insert_sql, log_data)\n connector.commit()\n print(\"ログ登録が完了しました。\")\n\n\n# follow_countが、borderに達していたら、フォローの処理を飛ばす\ndef follow_border_skip(screen_name):\n # borderを定義\n border = 1\n # idをデータベースから出す。\n with connector.cursor() as cursor:\n follow_count_select_sql = \"select follow_count from twitter_follow_log where screen_name = %s\"\n cursor.execute(follow_count_select_sql, screen_name)\n follow_count = cursor.fetchall()\n if len(follow_count) == 0:\n print(\"follow_border_skip\", \"初回フォロー:継続\")\n return False\n elif border <= follow_count[0][0]:\n print(\"follow_border_skip\", \"飛ばします\")\n return True\n else:\n print(\"follow_border_skip\", \"border以下:継続\")\n return False\n\n# # followerとfollowを定義\n# followers = api.followers_ids(SCREEN_NAME)\n# friends = api.friends_ids(SCREEN_NAME)\n\n\n# ****************************検索キーワードでフォロー&Fav***********************\n# 検索ワードと検索数をセット\ndef search_follow():\n follow_type = 1\n print(\"検索キーワードでフォローを開始します。\")\n keywords = [\"ミスオブミス\", \"ミスコレ\", \"ミスコン\", \"@Mscolle_\"]\n for keyword in keywords:\n count = 50\n # 検索実行。search_resultsにpost_idを保存\n search_results = api.search(q=keyword, count=count)\n # 結果をフォロー\n for result in search_results:\n screen_id = result.user._json[\"screen_name\"]\n if follow_border_skip(str(screen_id)):\n continue\n else:\n try:\n api.create_friendship(screen_id)\n print(screen_id + 'をフォローしました')\n time.sleep(2)\n twitter_follow_log(screen_id, follow_type, keyword)\n # 結果をfav\n tweet_id = result.id # ツイートのstatusオブジェクトから、ツイートidを取得\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"検索キーワードでフォローが終了しました。\")\n\n\n# ****************似たようなアカウントをフォローしている人をフォロー***************\n# 自分に似たようなアカウントを指定\ndef similar_acount_followers_follow():\n follow_type = 2\n print(\"指定アカウントのフォロワーのフォローを開始します。\")\n accounts = [\"MISSMRCOLLE\", \"_sute2013081503\", \"misscon_bot\", \"UTsweetheart\"]\n for account in accounts:\n count = 50\n account_followers = api.followers(id=account, count=count)\n\n # 自分に似たようなアカウントのフォロワーをフォロー\n for account_follower in account_followers:\n screen_id = account_follower._json[\"screen_name\"]\n if screen_id == \"\":\n continue\n if follow_border_skip(screen_id):\n continue\n else:\n try:\n print(screen_id + 'をフォロー���ました')\n api.create_friendship(screen_id)\n time.sleep(2)\n twitter_follow_log(screen_id, follow_type)\n # フォローした人の一番上の投稿をfav\n result = api.user_timeline(id=screen_id, count=1, exclude_replies=True, exclude_retweets=True)\n tweet_id = result[0].id\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"指定アカウントのフォロワーのフォローが終了しました。\")\n\n\n# *******************自分のツイートにfavしてくれている人をフォロー******************\n# 自分のツイートをfavしてくれている人のUSER_IDを取得\ndef my_favoritters_follow():\n follow_type = 3\n print(\"自分にfavしてくれている人のフォローを開始します。\")\n count = 10\n my_tweets = api.user_timeline(count=count, id='MsContest_')\n for my_tweet in my_tweets:\n screen_id = my_tweet._json[\"id\"]\n favoritters_id = get_favoritters(screen_id)\n if follow_border_skip(favoritters_id):\n continue\n else:\n # 自分の投稿にfavしている人をfollow\n for favoritter_id in favoritters_id:\n try:\n api.create_friendship(favoritter_id)\n print(favoritter_id + 'をフォローしました')\n time.sleep(2)\n twitter_follow_log(screen_id, follow_type)\n # フォローした人の一番上の投稿をfav\n result = api.user_timeline(id=favoritter_id, count=1, exclude_replies=True, exclude_retweets=True)\n tweet_id = result[0].id\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"自分にfavしてくれている人のフォローが終了しました。\")\n\n\n# *******************自分のツイートにRTしてくれている人をフォロー******************\n# 自分のツイートをRTしてくれている人のUSER_IDを取得\ndef my_retweeters_follow():\n follow_type = 4\n print(\"自分にRTしてくれている人のフォローを開始します。\")\n count = 10\n my_tweets = api.user_timeline(count=count, id='MsContest_')\n\n for my_tweet in my_tweets:\n retweeters = api.retweets(id=my_tweet.id_str)\n for retweeter in retweeters:\n retweeter_id = retweeter.user.id\n if follow_border_skip(retweeter_id):\n continue\n else:\n # 自分の投稿にRTしている人をfollow\n try:\n api.create_friendship(retweeter_id)\n print(retweeter.user.screen_name + 'をフォローしました')\n time.sleep(2)\n twitter_follow_log(retweeter_id, follow_type)\n # RTした人の一番上の投稿をfav\n result = api.user_timeline(id=retweeter_id, count=1, exclude_replies=True, exclude_retweets=True)\n tweet_id = result[0].id\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"自分にRTしてくれている人のフォローが終了しました。\")\n\n\n# *********************ミスコレの人にfavしている人をフォロー********************\ndef mscolle_favoritters_follow(twitter_ids):\n follow_type = 5\n print(\"ミスコレ出場者にfavしてくれている人のフォローを開始します。\")\n for twitter_id in twitter_ids:\n count = 10\n ms_tweets = api.user_timeline(count=count, screen_name=twitter_id)\n for ms_tweet in ms_tweets:\n screen_id = ms_tweet._json[\"id\"]\n favoritters_id = get_favoritters(screen_id)\n if follow_border_skip(favoritters_id):\n continue\n else:\n # ミスコレの投稿にfavしている人をfollow\n for favoritter_id in favoritters_id:\n try:\n api.create_friendship(favoritter_id)\n print(favoritter_id + 'をフォローしました')\n time.sleep(2)\n twitter_follow_log(favoritter_id, follow_type)\n # フォローした人の一番上の投稿をfav\n result = api.user_timeline(id=favoritter_id, count=1, exclude_replies=True, exclude_retweets=True)\n tweet_id = result[0].id\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"ミスコレ出場者にfavしてくれている人のフォローが終了しました。\")\n\n\n# *********************ミスコレの人にRTしている人をフォロー*********************\ndef mscolle_retweeters_follow(twitter_ids):\n follow_type = 6\n print(\"ミスコレ出場者にRTしてくれている人のフォローを開始します。\")\n for twitter_id in twitter_ids:\n count = 10\n ms_tweets = api.user_timeline(count=count, screen_name=twitter_id)\n for ms_tweet in ms_tweets:\n retweeters = api.retweets(id=ms_tweet.id_str)\n for retweeter in retweeters:\n retweeter_id = retweeter.user.id\n if follow_border_skip(retweeter_id):\n continue\n else:\n # 自分の投稿にRTしている人をfollow\n try:\n api.create_friendship(retweeter_id)\n print(retweeter.user.screen_name + 'をフォローしました')\n time.sleep(2)\n twitter_follow_log(retweeter_id, follow_type)\n # RTした人の一番上の投稿をfav\n result = api.user_timeline(id=retweeter_id, count=1, exclude_replies=True, exclude_retweets=True)\n tweet_id = result[0].id\n try:\n api.create_favorite(tweet_id) # favする\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n print(\"ミスコレ出場者にRTしてくれている人のフォローが終了しました。\")\n\n# *********************自分の投稿の一番上のUserの投稿にfavしている人をフォロー********************\n\n# *********************自分の投稿の一番上のUserの投稿にRTしている人をフォロー********************\n\n# search_follow()\n# similar_acount_followers_follow()\n# my_favoritters_follow()\n# my_retweeters_follow()\n# mscolle_favoritters_follow()\n# mscolle_retweeters_follow()\n\n\ndef main():\n # 検証用\n # twitter_follow_log('test', 2)\n # follow_border_skip(\"testtest\")\n # twitter_ids = get_twitter_ids()\n search_follow()\n # similar_acount_followers_follow()\n # my_favoritters_follow()\n # my_retweeters_follow()\n # mscolle_favoritters_follow(twitter_ids)\n # mscolle_retweeters_follow(twitter_ids)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mizushima_yusuke/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":14842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345143497","text":"import os\nimport scipy.io\nimport numpy as np\nfrom collections import OrderedDict\nfrom scipy import io\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch\n\nimport time\n\nimport sys\nsys.path.insert(0,'./roi_align')\nfrom roi_align.modules.roi_align import RoIAlignAvg,RoIAlignMax\nimport pdb\n\n\ndef append_params(params, module, prefix):\n for child in module.children():\n for k,p in child._parameters.iteritems():\n if p is None: continue\n\n if isinstance(child, nn.BatchNorm2d):\n name = prefix + '_bn_' + k\n else:\n name = prefix + '_' + k\n\n if name not in params:\n params[name] = p\n else:\n raise RuntimeError(\"Duplicated param name: %s\" % (name))\n\nclass LRN(nn.Module):\n def __init__(self, local_size=1, alpha=0.0001, beta=0.75, ACROSS_CHANNELS=False):\n super(LRN, self).__init__()\n self.ACROSS_CHANNELS = ACROSS_CHANNELS\n if self.ACROSS_CHANNELS:\n self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1),\n stride=1,\n padding=(int((local_size - 1.0) / 2), 0, 0))\n else:\n self.average = nn.AvgPool2d(kernel_size=local_size,\n stride=1,\n padding=int((local_size - 1.0) / 2))\n self.alpha = alpha\n self.beta = beta\n\n def forward(self, x):\n if self.ACROSS_CHANNELS:\n div = x.pow(2).unsqueeze(1)\n div = self.average(div).squeeze(1)\n div = div.mul(self.alpha).add(2.0).pow(self.beta)\n else:\n div = x.pow(2)\n div = self.average(div)\n div = div.mul(self.alpha).add(2.0).pow(self.beta)\n x = x.div(div)\n return x\n\n\nclass MDNet(nn.Module):\n def __init__(self, model_path=None,model_path2=None,model_path4=None,model_path5=None,model_path_sk_fc1=None,model_path_sk_fcs1=None,\n model_path_sk_fc2=None,model_path_sk_fcs2=None,model_path_sk_fc3=None,model_path_sk_fcs3=None,K=1):\n super(MDNet, self).__init__()\n self.K = K\n self.layers = nn.Sequential(OrderedDict([\n ('conv1', nn.Sequential(nn.Conv2d(3, 96, kernel_size=7, stride=2),\n nn.ReLU(),\n LRN(),\n nn.MaxPool2d(kernel_size=3, stride=2)\n )),\n ('conv2', nn.Sequential(nn.Conv2d(96, 256, kernel_size=5, stride=2, dilation=1),\n nn.ReLU(),\n LRN(),\n )),\n\n ('conv3', nn.Sequential(nn.Conv2d(256, 512, kernel_size=3, stride=1, dilation=3),\n nn.ReLU(),\n ))]))\n self.layers2 = nn.Sequential(OrderedDict([\n ('fc4', nn.Sequential(\n nn.Linear(512 * 3 * 3, 512),\n nn.ReLU())),\n ('fc5', nn.Sequential(nn.Dropout(0.5),\n nn.Linear(512, 512),\n nn.ReLU()))]))\n self.conv4 = nn.Sequential(OrderedDict([\n ('conv4', nn.Sequential(nn.Conv2d(96, 256, kernel_size=1, stride=1),\n nn.ReLU(),\n LRN()))]))\n self.conv5 = nn.Sequential(OrderedDict([\n ('conv5', nn.Sequential(nn.Conv2d(256, 512, kernel_size=1, stride=1),\n nn.ReLU(),\n LRN()))]))\n self.L = 32\n self.r = 4\n # d = max(int(features / r), self.L)\n # sk1\n self.sk_fc1 = nn.Sequential(OrderedDict([\n ('sk_fc11', nn.Sequential(\n nn.Linear(96, self.L)))]))\n self.sk_fcs1 = nn.Sequential(OrderedDict([\n ('sk_fcs11', nn.Sequential(\n nn.Linear(self.L, 96))),\n ('sk_fcs12', nn.Sequential(\n nn.Linear(self.L, 96)))]))\n\n # sk2\n self.sk_fc2 = nn.Sequential(OrderedDict([\n ('sk_fc22', nn.Sequential(\n nn.Linear(256, self.L)))]))\n self.sk_fcs2 = nn.Sequential(OrderedDict([\n ('sk_fcs21', nn.Sequential(\n nn.Linear(self.L, 256))),\n ('sk_fcs22', nn.Sequential(\n nn.Linear(self.L, 256))),\n ('sk_fcs23', nn.Sequential(\n nn.Linear(self.L, 256)))]))\n\n # sk3\n self.sk_fc3 = nn.Sequential(OrderedDict([\n ('sk_fc33', nn.Sequential(\n nn.Linear(512, self.L)))]))\n self.sk_fcs3 = nn.Sequential(OrderedDict([\n ('sk_fcs31', nn.Sequential(\n nn.Linear(self.L, 512))),\n ('sk_fcs32', nn.Sequential(\n nn.Linear(self.L, 512))),\n ('sk_fcs33', nn.Sequential(\n nn.Linear(self.L, 512)))]))\n\n self.softmax = nn.Softmax(dim=1)\n\n self.branches = nn.ModuleList([nn.Sequential(nn.Dropout(0.5),\n nn.Linear(512, 2)) for _ in range(K)])\n\n self.roi_align_model = RoIAlignMax(3, 3, 1. / 8)\n\n self.receptive_field = 75. # it is receptive fieald that a element of feat_map covers. feat_map is bottom layer of ROI_align_layer\n\n if model_path is not None:\n if os.path.splitext(model_path)[1] == '.pth':\n self.load_model(model_path,model_path2,model_path4,model_path5,model_path_sk_fc1,model_path_sk_fcs1,\n model_path_sk_fc2,model_path_sk_fcs2,model_path_sk_fc3,model_path_sk_fcs3)\n elif os.path.splitext(model_path)[1] == '.mat':\n self.load_mat_model(model_path)\n else:\n raise RuntimeError(\"Unkown model format: %s\" % (model_path))\n self.build_param_dict()\n\n def build_param_dict(self):\n self.params = OrderedDict()\n self.params = OrderedDict()\n for name, module in self.layers.named_children():\n append_params(self.params, module, name)\n for name, module in self.layers2.named_children():\n append_params(self.params, module, name)\n for name, module in self.conv4.named_children():\n append_params(self.params, module, name)\n for name, module in self.conv5.named_children():\n append_params(self.params, module, name)\n #sk\n for name, module in self.sk_fc1.named_children():\n append_params(self.params, module, name)\n for name, module in self.sk_fcs1.named_children():\n append_params(self.params, module, name)\n for name, module in self.sk_fc2.named_children():\n append_params(self.params, module, name)\n for name, module in self.sk_fcs2.named_children():\n append_params(self.params, module, name)\n for name, module in self.sk_fc3.named_children():\n append_params(self.params, module, name)\n for name, module in self.sk_fcs3.named_children():\n append_params(self.params, module, name)\n\n for k, module in enumerate(self.branches):\n append_params(self.params, module, 'fc6_%d'%(k))\n\n def set_learnable_params(self, layers):\n for k, p in self.params.iteritems():\n if any([k.startswith(l) for l in layers]):\n p.requires_grad = True\n else:\n p.requires_grad = False\n\n\n def get_learnable_params(self):\n params = OrderedDict()\n for k, p in self.params.iteritems():\n if p.requires_grad:\n params[k] = p\n return params\n\n def forward(self, x1,x2, k=0, in_layer='conv1', out_layer='fc6'):\n run = False\n for name, module in self.layers.named_children():\n if name == in_layer:\n run = True\n if run:\n x1 = module(x1)\n x2 = module(x2)\n if name == 'conv1':\n x1_down = F.max_pool2d(x1, kernel_size=(5, 5), stride=2)\n x2_down = F.max_pool2d(x2, kernel_size=(5, 5), stride=2)\n gaoyuan11 = x1_down.unsqueeze(dim=1)\n gaoyuan12 = x2_down.unsqueeze(dim=1)\n feas_1 = torch.cat([gaoyuan11,gaoyuan12],dim=1)\n fea_U1 = torch.sum(feas_1,dim=1)\n fea_s1 = fea_U1.mean(-1).mean(-1)\n fea_z1 = self.sk_fc1(fea_s1)\n for i, fc in enumerate(self.sk_fcs1):\n vector1 = fc(fea_z1).unsqueeze_(dim=1)\n if i == 0:\n attention_vectors1 = vector1\n else:\n attention_vectors1 = torch.cat([attention_vectors1, vector1], dim=1)\n attention_vectors1 = self.softmax(attention_vectors1)\n attention_vectors1 = attention_vectors1.unsqueeze(-1).unsqueeze(-1)\n fea_v1 = (feas_1 * attention_vectors1).sum(dim=1)\n fea_v11 = self.conv4(fea_v1)\n #fea_v11 = F.max_pool2d(fea_v1, kernel_size=(5, 5), stride=2)\n if name == 'conv2':\n gaoyuan21 = x1.unsqueeze(dim=1)\n gaoyuan22 = x2.unsqueeze(dim=1)\n gaoyuan23 = fea_v11.unsqueeze(dim=1)\n feas_2 = torch.cat([gaoyuan21,gaoyuan22,gaoyuan23],dim=1)\n fea_U2 = torch.sum(feas_2,dim=1)\n fea_s2 = fea_U2.mean(-1).mean(-1)\n fea_z2 = self.sk_fc2(fea_s2)\n for i, fc in enumerate(self.sk_fcs2):\n vector2 = fc(fea_z2).unsqueeze_(dim=1)\n if i == 0:\n attention_vectors2 = vector2\n else:\n attention_vectors2 = torch.cat([attention_vectors2, vector2], dim=1)\n attention_vectors2 = self.softmax(attention_vectors2)\n attention_vectors2 = attention_vectors2.unsqueeze(-1).unsqueeze(-1)\n fea_v2 = (feas_2 * attention_vectors2).sum(dim=1)\n #fea_v22 = F.max_pool2d(fea_v2, kernel_size=(5, 5), stride=2)\n #x11 = F.max_pool2d(x1, kernel_size=(5, 5), stride=2)\n #x21 = F.max_pool2d(x2, kernel_size=(5, 5), stride=2)\n #x12 = torch.cat([x11, x21, x1, x2], 1)\n #pdb.set_trace()\n #x12 = torch.cat([fea_v11, fea_v2], 1)\n x12 = F.max_pool2d(fea_v2, kernel_size=(3, 3), stride=1, padding=0, dilation=3)\n x12 = self.conv5(x12)\n if name == 'conv3':\n gaoyuan31 = x1.unsqueeze(dim=1)\n gaoyuan32 = x2.unsqueeze(dim=1)\n gaoyuan33 = x12.unsqueeze(dim=1)\n feas_3 = torch.cat([gaoyuan31,gaoyuan32,gaoyuan33],dim=1)\n fea_U3 = torch.sum(feas_3,dim=1)\n fea_s3 = fea_U3.mean(-1).mean(-1)\n fea_z3 = self.sk_fc3(fea_s3)\n for i, fc in enumerate(self.sk_fcs3):\n vector3 = fc(fea_z3).unsqueeze_(dim=1)\n if i == 0:\n attention_vectors3 = vector3\n else:\n attention_vectors3 = torch.cat([attention_vectors3, vector3], dim=1)\n attention_vectors3 = self.softmax(attention_vectors3)\n attention_vectors3 = attention_vectors3.unsqueeze(-1).unsqueeze(-1)\n fea_v3 = (feas_3 * attention_vectors3).sum(dim=1)\n #x13 = torch.cat([x12, fea_v3], 1)\n x = fea_v3\n #x = self.conv5(fea_v3)\n if name == out_layer:\n return x\n\n for name, module in self.layers2.named_children():\n if name == in_layer:\n x=x1\n run2 = True\n if run2:\n x = module(x)\n if name == out_layer:\n return x\n x = self.branches[k](x)\n if out_layer=='fc6':\n return x\n elif out_layer=='fc6_softmax':\n return F.softmax(x)\n\n def load_model(self, model_path,model_path2,model_path4,model_path5,model_path_sk_fc1,model_path_sk_fcs1,\n model_path_sk_fc2,model_path_sk_fcs2,model_path_sk_fc3,model_path_sk_fcs3):\n states = torch.load(model_path)\n layers = states['layers']\n self.layers.load_state_dict(layers)\n\t\t\n states2 = torch.load(model_path2)\n layers2 = states2['layers2']\n self.layers2.load_state_dict(layers2)\n\t\t\n states4 = torch.load(model_path4)\n conv4 = states4['conv4']\n self.conv4.load_state_dict(conv4)\n\t\t\n states5 = torch.load(model_path5)\n conv5 = states5['conv5']\n self.conv5.load_state_dict(conv5)\n #sk\n states_sk_fc1 = torch.load(model_path_sk_fc1)\n sk_fc1 = states_sk_fc1['sk_fc1']\n self.sk_fc1.load_state_dict(sk_fc1)\n states_sk_fcs1 = torch.load(model_path_sk_fcs1)\n sk_fcs1 = states_sk_fcs1['sk_fcs1']\n self.sk_fcs1.load_state_dict(sk_fcs1)\n\n states_sk_fc2 = torch.load(model_path_sk_fc2)\n sk_fc2 = states_sk_fc2['sk_fc2']\n self.sk_fc2.load_state_dict(sk_fc2)\n states_sk_fcs2 = torch.load(model_path_sk_fcs2)\n sk_fcs2 = states_sk_fcs2['sk_fcs2']\n self.sk_fcs2.load_state_dict(sk_fcs2)\n\n states_sk_fc3 = torch.load(model_path_sk_fc3)\n sk_fc3 = states_sk_fc3['sk_fc3']\n self.sk_fc3.load_state_dict(sk_fc3)\n states_sk_fcs3 = torch.load(model_path_sk_fcs3)\n sk_fcs3 = states_sk_fcs3['sk_fcs3']\n self.sk_fcs3.load_state_dict(sk_fcs3)\n\n def load_mat_model(self, matfile):\n mat = scipy.io.loadmat(matfile)\n mat_layers = list(mat['layers'])[0]\n\n # copy conv weights\n for i in range(3):\t\t\n weight, bias = mat_layers[i*4]['weights'].item()[0]\n self.layers[i][0].weight.data = torch.from_numpy(np.transpose(weight, (3,2,0,1)))\n self.layers[i][0].bias.data = torch.from_numpy(bias[:,0])\n\n def trainSpatialTransform(self, image, bb):\n\n return\n\n\nclass BinaryLoss(nn.Module):\n def __init__(self):\n super(BinaryLoss, self).__init__()\n\n def forward(self, pos_score, neg_score):\n pos_loss = -F.log_softmax(pos_score)[:,1]\n neg_loss = -F.log_softmax(neg_score)[:,0]\n\n loss = (pos_loss.sum() + neg_loss.sum())/(pos_loss.size(0) + neg_loss.size(0))\n return loss\n\n\nclass Accuracy():\n def __call__(self, pos_score, neg_score):\n\n pos_correct = (pos_score[:,1] > pos_score[:,0]).sum().float()\n neg_correct = (neg_score[:,1] < neg_score[:,0]).sum().float()\n\n pos_acc = pos_correct / (pos_score.size(0) + 1e-8)\n neg_acc = neg_correct / (neg_score.size(0) + 1e-8)\n\n return pos_acc.data[0], neg_acc.data[0]\n\n\nclass Precision():\n def __call__(self, pos_score, neg_score):\n\n scores = torch.cat((pos_score[:,1], neg_score[:,1]), 0)\n topk = torch.topk(scores, pos_score.size(0))[1]\n prec = (topk < pos_score.size(0)).float().sum() / (pos_score.size(0)+1e-8)\n\n return prec.data[0]\n\n\n\n","sub_path":"modules/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"554819110","text":"import math\nimport random\nimport numpy as np\nimport loadParametersP1\nfrom matplotlib import pyplot as plt\n\ndef grad_desc(func, d_func, init=np.zeros(2)):\n x = init\n values = []\n epoch = 0\n while True:\n epoch += 1\n x -= 100 * d_func(x)\n values += [func(x)]\n if np.linalg.norm(d_func(x)) < 0.000001:\n print(x)\n return epoch\n\ngaussMean,gaussCov,quadBowlA,quadBowlb = loadParametersP1.getData()\ndef gfunc(x):\n diff = (x - gaussMean)\n icov = np.linalg.inv(gaussCov)\n norm = - 1.0 / math.sqrt((2 * 3.1415)**len(gaussMean) * np.linalg.norm(gaussCov))\n return norm * np.exp(- 0.5 * diff.transpose().dot(icov.dot(diff)))\ndef d_gfunc(x):\n diff = (x - gaussMean)\n icov = np.linalg.inv(gaussCov)\n return -gfunc(x) * icov.dot(diff)\ndef qfunc(x):\n return 0.5 * x.transpose().dot(quadBowlA.dot(x)) - x.transpose().dot(quadBowlb)\ndef d_qfunc(x):\n return quadBowlA.dot(x) - quadBowlb\ndef ad_qfunc(x):\n result = [\n (qfunc(x+np.array([0.1,0])) - qfunc(x-np.array([0.1,0]))) / 0.2,\n (qfunc(x+np.array([0,0.1])) - qfunc(x-np.array([0,0.1]))) / 0.2\n ]\n return np.array(result)\n\npairs = [\n (np.array([-70.0,10.0]), 'r-'),\n (np.array([-60.0,10.0]), 'r-'),\n (np.array([-50.0,10.0]), 'r-'),\n (np.array([-40.0,10.0]), 'r-'),\n (np.array([-30.0,10.0]), 'r-'),\n (np.array([-20.0,10.0]), 'r-'),\n (np.array([-10.0,10.0]), 'r-'),\n (np.array([-8.0,10.0]), 'r-'),\n (np.array([-6.0,10.0]), 'r-'),\n (np.array([-4.0,10.0]), 'r-'),\n (np.array([-2.0,10.0]), 'r-'),\n (np.array([0.0,10.0]), 'r-'),\n (np.array([2.0,10.0]), 'g-'),\n (np.array([4.0,10.0]), 'b-'),\n (np.array([6.0,10.0]), 'c-'),\n (np.array([8.0,10.0]), 'm-'),\n (np.array([10.0,10.0]), 'y-')\n]\n\ny_values = []\nfor pair in pairs[::-1]:\n init, color = pair\n val = str(list(map(int, init)))\n y_values += [grad_desc(gfunc, d_gfunc, init=init)]\nplt.plot([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70, 80], y_values, 'b-', label=val)\nplt.title('Gradient Descent: Gaussian')\nplt.xlabel('distance')\nplt.ylabel('# epochs')\nplt.show()\n","sub_path":"P1/figure2.py","file_name":"figure2.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"388289469","text":"from pathlib import Path\nfrom datetime import datetime\nimport subprocess\n\nfrom .task_event_tracker import TaskEventTracker\n\nfrom sayn import __version__ as sayn_version\n\n\nclass EventTracker:\n loggers = list()\n run_id = None\n current_stage = None\n current_stage_start_ts = None\n tasks = list()\n current_task = None\n current_task_n = 0\n sayn_version = sayn_version\n project_git_commit = None\n project_name = Path(\".\").absolute().name\n\n def __init__(self, run_id, loggers, run_arguments):\n self.run_id = run_id\n self.loggers = loggers\n try:\n self.project_git_commit = (\n subprocess.check_output(\n [\"git\", \"rev-parse\", \"HEAD\"], stderr=subprocess.STDOUT\n )\n .split()[0]\n .decode(\"utf-8\")\n )\n except:\n pass\n\n self.report_event(context=\"app\", event=\"start_app\", run_arguments=run_arguments)\n\n def register_logger(self, logger):\n self.loggers.append(logger)\n\n def start_stage(self, stage, **details):\n self.current_stage = stage\n self.current_stage_start_ts = datetime.now()\n self.report_event(context=\"app\", event=\"start_stage\", stage=stage, **details)\n\n def finish_current_stage(self, **details):\n duration = datetime.now() - self.current_stage_start_ts\n self.report_event(\n context=\"app\",\n event=\"finish_stage\",\n stage=self.current_stage,\n duration=duration,\n **details\n )\n self.current_stage = None\n self.current_stage_start_ts = None\n\n def set_tasks(self, tasks):\n self.tasks = tasks\n\n def get_task_tracker(self, task_name):\n if task_name in self.tasks:\n task_order = self.tasks.index(task_name) + 1\n else:\n task_order = None\n\n return TaskEventTracker(self, task_name, task_order)\n\n def report_event(self, **event):\n if \"context\" not in event:\n event[\"context\"] = \"app\"\n\n elif event[\"context\"] == \"task\":\n event[\"total_tasks\"] = len(self.tasks)\n\n if \"event\" not in event:\n event[\"event\"] = \"unknown\"\n\n event.update(\n dict(\n run_id=self.run_id,\n stage=self.current_stage,\n sayn_version=self.sayn_version,\n project_git_commit=self.project_git_commit,\n project_name=self.project_name,\n ts=datetime.now(),\n )\n )\n\n for logger in self.loggers:\n logger.report_event(**event)\n","sub_path":"sayn/logging/event_tracker.py","file_name":"event_tracker.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"244632812","text":"__author__ = 'mikhail.pogrebnoy'\nfrom tkinter import *\n\ndef greeting():\n print('Hello')\n\nwin = Frame()\nwin.pack()\n\n\ntitle = Label(win, text=\"Привет, Паша\")\ntitle.config(height=10, width=50)\ntitle.pack(side=TOP, fill=BOTH)\n\n\nwin.mainloop()\n","sub_path":"tests/gui_test.py","file_name":"gui_test.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"290165416","text":"#!/usr/bin/python3.4\n\n\"\"\"\nauthor: Silvia Turrion\nwebsite: sturmwork.eu\n\"\"\"\n\nimport sys\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QComboBox, QApplication)\n\nimport db_ops.db_interface as db\n\nclass DbBrowser(QWidget):\n \n def __init__(self):\n super().__init__()\n \n self.db_list = db.get_databases()\n \n self.initUI()\n \n \n def initUI(self): \n\n self.lbl = QLabel(self.db_list[0], self)\n\n combo = QComboBox(self)\n \n for database in self.db_list: \n combo.addItem(database)\n\n combo.move(50, 50)\n self.lbl.move(50, 150)\n\n combo.activated[str].connect(self.onActivated) \n \n self.resize(800, 600)\n self.setWindowTitle('Mary Browser')\n self.show()\n \n \n def onActivated(self, text):\n \n self.lbl.setText(text)\n self.lbl.adjustSize() \n \n\nif __name__ == '__main__':\n \n app = QApplication(sys.argv)\n ex = DbBrowser()\n sys.exit(app.exec_())\n \n \n","sub_path":"pyqt5_mary_browser.py","file_name":"pyqt5_mary_browser.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"261520380","text":"import rhinoscriptsyntax as r\nimport copy\n\ndef SelClosePoints():\n points = r.GetObjects(\"Points to search\")\n tolerance = r.GetReal(\"Tolerance\", 0.5, 0)\n sel_points = copy.copy(points)\n check = []\n search_points = copy.copy(points)\n for point in points:\n search_points.remove(point)\n if len(search_points) > 0:\n n_close = r.PointArrayClosestPoint(search_points, point)\n d = r.Distance(point, search_points[n_close])\n if d < tolerance:\n sel_points.remove(point)\n check.append(search_points[n_close])\n \n r.SelectObjects(sel_points)\n print(len(sel_points))\n\nSelClosePoints()","sub_path":"SelClosePoints.py","file_name":"SelClosePoints.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"371008504","text":"\"\"\"SafeWork Server\"\"\"\n\nfrom __future__ import absolute_import\nfrom send_alerts import send_message, send_email\nimport flask\nimport bcrypt\nimport bcrypt\nimport math\nimport time\nimport json\nimport datetime\nimport threading\nimport secrets\nfrom jinja2 import StrictUndefined\nfrom flask import (Flask, render_template, redirect, request, flash,\n session, jsonify)\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import (update, asc, desc)\nfrom model import Forum, Post, User, Incident, Police, Source, Like, Flag, Contact, AlertSet, Alert, CheckIn, ReqCheck, connect_to_db, db, app\nimport requests\n# from secrets_env import CLIENT_ID\nimport asyncio\n\n\ndb.init_app(app)\n\n# Required to use Flask sessions and the debug toolbar\napp.secret_key = \"ABC\"\n\n# Causes error messages for undefined variables in jinja\napp.jinja_env.undefined = StrictUndefined\n\n\n\n####################################################################\n\ndef create_alert(alert_id):\n alert = Alert.query.filter_by(alert_id=alert_id).one()\n events = {} \n user = User.query.filter_by(user_id=alert.user_id).one()\n alert_set = AlertSet.query.filter_by(alert_set_id=alert.alert_set_id).one()\n all_alerts = Alert.query.filter(alert.alert_set_id == alert.alert_set_id, alert.datetime > alert_set.start_datetime).all()\n check_ins = CheckIn.query.filter_by(user_id=user.user_id).all()\n message_body = \"\"\"This is a Safety Alert sent by {} {} through the SafeWork Project SafeWalk Alert system, \n found at safeworkproject.org \\n \\n\"\"\".format(user.fname, user.lname)\n if alert_set.notes:\n message_body += \"\"\"The user has included the following messages when they made this alert and checked in \\n \\n {}\"\"\".format(alert_set.message)\n for a_a in all_alerts:\n if len(a_a.message) > 2:\n events[a_a.datetime] = a_a\n for chks in check_ins:\n events[chks.datetime] = chks\n for key in sorted(events.keys()):\n if events[key].alert_set_id and events[key].checked_in == True:\n message_body += \"An alarm was scheduled for {} which {} checked-in for.\".format(key, user.fname)\n if events[key].message:\n message_body += \"The Alarm included the following notes: {} \\n \\n\".format(events[key].message)\n else:\n message_body += \"\\n \\n\" \n elif alert.datetime >= datetime.datetime.now() and events[key].message:\n message_body += \"A future alarm is scheduled for {} and includes the notes: {}.\".format(alert.datetime, events[key].message)\n elif events[key].alert_set_id:\n message_body += \"An alarm was scheduled for {} which {} MISSED the checked-in for.\".format(key, user.fname)\n if events[key].message:\n message_body += \"The Alarm included the following notes: {} \\n \\n\".format(events[key].message)\n else:\n message_body += \"\\n \\n\" \n else:\n message_body += \"{} checked in with the app at {} and included the following message: {}\".format(user.fname, key, events[key].notes)\n if alert.contact_id3:\n message_body += \"\"\"Two other contacts have been sent this alert. If you know who it might be,\n consider reaching out and co-ordinating your effort to help {}.\"\"\".format(user.fname)\n elif alert.contact_id2:\n message_body += \"\"\"One other contact has been sent this alert. If you know who it might be,\n consider reaching out and co-ordinating your effort to help {}.\"\"\".format(user.fname)\n else:\n message_body += \"\"\"You were the only person sent this alert, so if anything can be done\n to help {}, it is up to you! Good luck!!!\"\"\".format(user.fname)\n return message_body\n\ndef send_alert(alert_id, message_body):\n alert = Alert.query.filter_by(alert_id=alert_id).one()\n user = User.query.filter_by(user_id=alert.user_id).one()\n if user.email2:\n send_email(user.email2, message_body)\n print('Sending to email2')\n elif user.email:\n send_email(user.email, message_body)\n print('Sending to email1')\n if user.phone:\n send_message(user.phone, message_body)\n print('Sending to phone')\n return \"Messages Sent\"\n\n\ndef check_alerts():\n with app.app_context():\n print(\"Checking for Alerts Now: \" + str(datetime.datetime.now()))\n alerts = Alert.query.filter_by(active=True).all()\n # print(alerts)\n if len(alerts) > 0:\n for alert in alerts:\n difference = alert.datetime - datetime.datetime.now()\n checks = 0\n check_ins = CheckIn.query.filter_by(user_id=alert.user_id).all()\n for ch in check_ins:\n dif = datetime.datetime.now() - alert.datetime\n if dif <= timedelta(hours=1) and difference > timedelta(seconds=0):\n checks += 1\n if difference <= datetime.timedelta(minutes=1) and difference > datetime.timedelta(seconds=0) and checks == 0:\n print('A CHECK-IN WAS MISSED AND AN ALERT IS BEING SENT NOW!')\n message_body = create_alert(alert.alert_id)\n send_alert(alert.alert_id, message_body)\n elif difference <= datetime.timedelta(minutes=15) and difference > datetime.timedelta(minutes=14) and checks == 0:\n print('A CHECK-IN REMINDER IS BEING SENT NOW!')\n message_body = \"\"\"Reminder! You have a Check-In Scheduled in 15 minutes. If you don't check-in\n by responding to this text, emailing 'safe@safeworkproject.org', or checking in on the site at\n 'www.safeworkproject.org/check_ins', your pre-set alerts will be sent to your contact(s)!\"\"\"\n send_alert(alert.alert_id, message_body)\n return\n\n#below is modified code from https://networklore.com/start-task-with-flask/\n@app.before_first_request\ndef activate_job():\n def run_job():\n while True:\n check_alerts()\n time.sleep(60)\n\n thread = threading.Thread(target=run_job)\n thread.start()\n\ndef start_runner():\n def start_loop():\n not_started = True\n while not_started:\n print('In start loop')\n try:\n r = requests.get('http://127.0.0.1:5000/')\n if r.status_code == 200:\n print('Server started, quiting start_loop')\n not_started = False\n print(r.status_code)\n except:\n print('Server not yet started')\n time.sleep(2)\n print('Started runner')\n thread = threading.Thread(target=start_loop)\n thread.start()\n\n\n\n@app.route(\"/\")\ndef go_home():\n \"\"\"Renders the safework homepage. (Tested)\"\"\"\n \n return render_template(\"homepage.html\")\n\n\n@app.route(\"/map\")\ndef get_map():\n \"\"\"Renders safework's arrest map. (Tested)\"\"\"\n return render_template(\"map_page.html\")\n\n\n@app.route(\"/incidents.json\")\ndef get_points():\n \"\"\"Gets the incident/marker points as JSON to be plotted on the map.\"\"\"\n\n #Initializes empty dictionary which is then filled with the marker data\n incidents = {}\n ind = 0\n for inc in Incident.query.all():\n ind += 1\n lat = float(inc.latitude)\n lng = float(inc.longitude)\n incidents[ind] = {\n \"latitude\": lat,\n \"longitude\": lng,\n \"address\": inc.address,\n \"city\": inc.city,\n \"state\": inc.state,\n \"year\": inc.year,\n \"date\": inc.date,\n \"time\": inc.time,\n \"description\": inc.description,\n \"source_id\": inc.source_id,\n \"incident_id\": inc.incident_id,\n \"rec_number\": inc.police_rec_num}\n\n #The marker dictionary is jsonified and sent to the google maps API through JavaScript\n return jsonify(incidents)\n\n\n\n@app.route(\"/register\", methods=[\"GET\"])\ndef register_form():\n \"\"\"Goes to registration Form. (Tested)\"\"\"\n\n \"\"\"Creating empty strings to send through jinja so that if someone is redirected\n from /register(POST), their data will still be in the registration form\"\"\"\n email_input = \"\"\n username = \"\"\n fname = \"\"\n lname = \"\"\n about_me = \"\"\n\n #Renders registration page with empty form variables\n return render_template(\"register.html\", email=email_input, username=username,\n fname=fname, lname=lname, about_me=about_me)\n\n\n@app.route(\"/register\", methods=[\"POST\"])\ndef register_process():\n \"\"\"Registration Form. (Tested)\"\"\"\n\n \"\"\"Creating empty strings in case there aren't already\n data being passed from the registration redirect\"\"\"\n fname = \"\"\n lname = \"\"\n about_me = \"\"\n tagline = \"\"\n location = \"\"\n #Sets variables equal to the form values\n email_input = request.form['email_input']\n email2 = request.form['email_input2']\n phone = request.form['phone']\n pw_input = request.form['password'].encode('utf-8')\n username = request.form['username']\n tagline = request.form['tagline']\n location = request.form['location']\n hashed_word = bcrypt.hashpw(pw_input, bcrypt.gensalt())\n user_type = request.form['user_type']\n second_type = request.form['2nd']\n timezone = request.form['timezone']\n\n \"\"\"Checks to make sure values exist in the optional fields\n before setting the variables equal to the form values\"\"\"\n if len(request.form['fname']) >= 1:\n fname = request.form['fname']\n if len(request.form['lname']) >= 1:\n lname = request.form['lname']\n if len(request.form['about_me']) >= 1:\n about_me = request.form['about_me']\n\n #Checking that the e-mail address field at least includes a \".\" and a \"@\"\n if \".\" not in email_input or \"@\" not in email_input:\n flash(email_input + \" is not a valid e-mail address!\")\n return render_template(\"register.html\", email=email_input, username=username,\n fname=fname, lname=lname, about_me=about_me)\n\n #Checking that the e-mail address hasn't already been registered\n elif User.query.filter_by(email=email_input).all() != []:\n flash(email_input + \"\"\"This e-mail has already been registered! Either sign in with it,\n use a different e-mail address, or reset your password if you forgot it.\"\"\")\n return render_template(\"register.html\", email=email_input, username=username, fname=fname,\n lname=lname, about_me=about_me)\n\n #Checking that the username is available\n elif User.query.filter_by(username=username).all() != []:\n flash(email_input + \"This username is already in use! Please try another one!\")\n return render_template(\"register.html\", email=email_input, username=username, fname=fname,\n lname=lname, about_me=about_me)\n\n #Checking that the password length is at least 6\n elif len(pw_input) < 6:\n flash(\"Your password must be at least 5 characters long! Try again.\")\n return render_template(\"register.html\", email=email_input, username=username, fname=fname,\n lname=lname, about_me=about_me)\n\n #Otherwise, the new user's information is added to the database\n else:\n new_user = User(email=email_input, password=hashed_word, username=username, fname=fname,\n lname=lname, description=about_me, user_type_main=user_type,\n user_type_secondary=second_type, tagline=tagline, location=location,\n email2=email2, phone=phone, timezone=timezone)\n db.session.add(new_user)\n db.session.commit()\n #Code isn't working:\n # if user_type == \"other\":\n # flash(\"\"\"While you may enter the discussion forums if you are not a sex worker,\n # keep in mind that this website is not intended for you. Do your best to respect\n # the sex workers on this site as well as their experiences and thoughts. Also,\n # please note that pimps and human traffickers are NOT welcome on this site. This\n # site is intended for consensual sex workers working on their own\n # volition ONLY.\"\"\")\n return redirect('/login')\n\n\n@app.route(\"/login\", methods=[\"GET\"])\ndef log_in():\n \"\"\"Render's the log-in page if user not in session,\n otherwise redirects to the homepage (Tested)\"\"\"\n\n if 'current_user' in list(session.keys()):\n return redirect(\"/\")\n else:\n return render_template(\"login.html\")\n\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef login():\n \"\"\"Gets login info, verifies it, & either redirects to the forums or \n gives an error message (Tested)\"\"\"\n\n #Sets variable equal to the login form inputs\n email_input = request.form['email_input']\n pw_input = request.form['pw_input'].encode('utf-8')\n user_query = User.query.filter(User.email == email_input).all()\n\n if user_query == []:\n flash('There is no record of your e-mail address! Please try again or Register.')\n return render_template(\"login.html\")\n\n\n #Queries to see if the email and pword match the database. If so, redirects to forums.\n elif bcrypt.checkpw(pw_input, user_query[0].password.encode('utf-8')):\n session['current_user'] = email_input\n flash('You were successfully logged in')\n return redirect(\"/forums\")\n\n #Otherwise, it re-renders the page and throws an error message to the user\n else:\n flash('Your e-mail or password was incorrect! Please try again or Register.')\n return render_template(\"login.html\")\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Logs user out and deletes them from the session (Tested)\"\"\"\n\n del session['current_user']\n\n flash('Bye! You have been succesfully logged out!')\n return redirect(\"/login\")\n\n\n@app.route(\"/forums\")\ndef go_forums():\n \"\"\"Renders the central forum page (Tested)\"\"\"\n\n #Defining the central forums (within app context) to be rendered\n cam = Forum.query.filter_by(forum_id=1).one()\n dom = Forum.query.filter_by(forum_id=2).one()\n escort = Forum.query.filter_by(forum_id=3).one()\n porn = Forum.query.filter_by(forum_id=4).one()\n dance = Forum.query.filter_by(forum_id=5).one()\n phone = Forum.query.filter_by(forum_id=6).one()\n sugar = Forum.query.filter_by(forum_id=7).one()\n other = Forum.query.filter_by(forum_id=8).one()\n\n #Creates lists for all of the children forums of the main 8 forums\n cam_query = Forum.query.filter_by(parent_forum_id=1).all()\n dom_query = Forum.query.filter_by(parent_forum_id=2).all()\n escort_query = Forum.query.filter_by(parent_forum_id=3).all()\n porn_query = Forum.query.filter_by(parent_forum_id=4).all()\n dance_query = Forum.query.filter_by(parent_forum_id=5).all()\n phone_query = Forum.query.filter_by(parent_forum_id=6).all()\n sugar_query = Forum.query.filter_by(parent_forum_id=7).all()\n other_query = Forum.query.filter_by(parent_forum_id=8).all()\n\n # group_forums = Forum.query.group_by(Forum.parent_forum_id).all()\n\n # \"\"\"Creates a list of dictionaries, each of which has all 8 forum_ids as keys with corresponding \n # children forums (or a blank string if there are no more children of a parent forum) which\n # can then be iterated through\"\"\"\n # all_forums = []\n # while (cam_query + dom_query + escort_query + porn_query +\n # dance_query + phone_query + sugar_query + other_query) != []:\n # row = {}\n # if cam_query == []:\n # row[1] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = cam_query.pop(0)\n # row[1] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if dom_query == []:\n # row[2] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = dom_query.pop(0)\n # row[2] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if escort_query == []:\n # row[3] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = escort_query.pop(0)\n # row[3] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if porn_query == []:\n # row[4] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = porn_query.pop(0)\n # row[4] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if dance_query == []:\n # row[5] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = dance_query.pop(0)\n # row[5] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if phone_query == []:\n # row[6] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = phone_query.pop(0)\n # row[6] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if sugar_query == []:\n # row[7] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = sugar_query.pop(0)\n # row[7] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # if other_query == []:\n # row[8] = {\"forum_id\": \"\", \"forum_name\": \"\"}\n # else:\n # q_object = other_query.pop(0)\n # row[8] = {\"forum_id\": q_object.forum_id, \"forum_name\": q_object.forum_name}\n # all_forums.append(row)\n\n\n #Checks to see if the user is logged in. If so, renders forums\n if 'current_user' in list(session.keys()):\n return render_template(\"forums.html\", cam=cam, dom=dom, escort=escort,\n porn=porn, dance=dance, phone=phone, other=other, sugar=sugar,\n cam_query=cam_query, dom_query=dom_query, escort_query=escort_query,\n porn_query=porn_query, dance_query=dance_query, phone_query=phone_query,\n sugar_query=sugar_query, other_query=other_query)\n \n #Otherwise it redirects to the login page\n else:\n flash(\"Please login before entering the forums.\")\n return redirect(\"/login\")\n\n\n@app.route(\"/forums/parent//\", methods=[\"POST\"])\ndef add_post(forum_id, page_num=1):\n \"\"\"Uses POST request to create a new post within a forum (Tested)\"\"\"\n\n #Defining the central forums (within app context) to be rendered\n cam = Forum.query.filter_by(forum_id=1).one()\n dom = Forum.query.filter_by(forum_id=2).one()\n escort = Forum.query.filter_by(forum_id=3).one()\n porn = Forum.query.filter_by(forum_id=4).one()\n dance = Forum.query.filter_by(forum_id=5).one()\n phone = Forum.query.filter_by(forum_id=6).one()\n sugar = Forum.query.filter_by(forum_id=7).one()\n other = Forum.query.filter_by(forum_id=8).one()\n\n #Creates lists for all of the children forums of the main 8 forums\n cam_query = Forum.query.filter_by(parent_forum_id=1).all()\n dom_query = Forum.query.filter_by(parent_forum_id=2).all()\n escort_query = Forum.query.filter_by(parent_forum_id=3).all()\n porn_query = Forum.query.filter_by(parent_forum_id=4).all()\n dance_query = Forum.query.filter_by(parent_forum_id=5).all()\n phone_query = Forum.query.filter_by(parent_forum_id=6).all()\n sugar_query = Forum.query.filter_by(parent_forum_id=7).all()\n other_query = Forum.query.filter_by(parent_forum_id=8).all()\n\n #Gets the new posts content\n post_content = request.form['content']\n\n #Checks to see the users info and which posts they have flagged\n user = User.query.filter_by(email=session['current_user']).one()\n flag_query = Flag.query.filter(Flag.user_id == User.user_id).all()\n flags = []\n if len(flag_query) > 0:\n for item in flag_query:\n\n flags.append(item.post_id)\n\n #Adds the new post to the database\n new_post = Post(parent_post_id=0, user_id=user.user_id, username=user.username,\n forum_id=forum_id, content=post_content, p_datetime=datetime.now(),\n date_posted=(str(datetime.now())[:16]))\n\n #Doublechecks that the user isn't creating a duplicate post\n if Post.query.filter(Post.content == new_post.content,\n Post.username == new_post.username).all() == []:\n db.session.add(new_post)\n db.session.commit()\n\n #Redirects everything back to the same forum page\n return redirect(\"/forums/order_by_date/\" + str(forum_id) + \"/\" + str(page_num))\n\n\n@app.route(\"/forums/child/\", methods=[\"POST\"])\ndef add_child_post(post_id, page_num=1):\n \"\"\"Uses POST request to create a new child (response) post within a forum (Tested)\"\"\"\n\n #Defining the central forums (within app context) to be rendered\n cam = Forum.query.filter_by(forum_id=1).one()\n dom = Forum.query.filter_by(forum_id=2).one()\n escort = Forum.query.filter_by(forum_id=3).one()\n porn = Forum.query.filter_by(forum_id=4).one()\n dance = Forum.query.filter_by(forum_id=5).one()\n phone = Forum.query.filter_by(forum_id=6).one()\n sugar = Forum.query.filter_by(forum_id=7).one()\n other = Forum.query.filter_by(forum_id=8).one()\n\n #Creates lists for all of the children forums of the main 8 forums\n cam_query = Forum.query.filter_by(parent_forum_id=1).all()\n dom_query = Forum.query.filter_by(parent_forum_id=2).all()\n escort_query = Forum.query.filter_by(parent_forum_id=3).all()\n porn_query = Forum.query.filter_by(parent_forum_id=4).all()\n dance_query = Forum.query.filter_by(parent_forum_id=5).all()\n phone_query = Forum.query.filter_by(parent_forum_id=6).all()\n sugar_query = Forum.query.filter_by(parent_forum_id=7).all()\n other_query = Forum.query.filter_by(parent_forum_id=8).all()\n\n #Gets the new posts content\n post_content = request.form['child_content']\n\n #Checks to see the users info and which posts they have flagged\n user = User.query.filter_by(email=session['current_user']).one()\n flag_query = Flag.query.filter(Flag.user_id == User.user_id).all()\n flags = []\n if len(flag_query) > 0:\n for item in flag_query:\n flags.append(item.post_id)\n\n #Queries the data for the parent post\n parent_post = Post.query.filter_by(post_id=post_id).one()\n\n #Adds the new post to the database\n new_post = Post(user_id=user.user_id, username=user.username, forum_id=parent_post.forum_id,\n parent_post_id=post_id, content=post_content, p_datetime=datetime.now(),\n date_posted=(str(datetime.now())[:16]))\n\n #Doublechecks that the user isn't creating a duplicate post\n if Post.query.filter(Post.content == post_content, Post.username == user.username).all() == []:\n db.session.add(new_post)\n db.session.commit()\n\n #Redirects everything back to the same forum page\n return redirect(\"/forums/order_by_date/\" + str(parent_post.forum_id) + \"/\" + str(page_num))\n\n\n@app.route(\"/forums/edit/\", methods=[\"POST\"])\ndef edit_post(post_id):\n \"\"\"Uses POST request edit an already-existing dicsussion post (Tested)\"\"\"\n\n\n #Gets the post's new content\n post_content = request.form['child_content']\n\n #Updates post content\n (db.session.query(Post).filter_by(post_id=post_id).update(\n {'content': post_content, 'edit_datetime': datetime.now()}))\n db.session.commit()\n\n #Queries the parent post to double-check the forum_id\n parent_post = Post.query.filter_by(post_id=post_id).one()\n\n #Redirects everything back to the same forum page\n return redirect('/forums/order_by_date/' + str(parent_post.forum_id) + \"/1\")\n\n\n@app.route(\"/forums/delete/\", methods=[\"POST\"])\ndef delete_post(post_id):\n \"\"\"Uses POST request to create a new post within a forum (Tested)\"\"\"\n\n #Gets the new posts content\n post_content = str(request.form['delete_check'])\n #Updates post content\n if post_content == \"Yes\":\n (db.session.query(Post).filter_by(post_id=post_id).update(\n {'content': 'This post has been deleted by its poster.',\n 'edit_datetime': datetime.now(), 'deleted': True}))\n db.session.commit()\n\n #Queries the parent post to double-check the forum_id\n parent_post = Post.query.filter_by(post_id=post_id).one()\n\n #Redirects everything back to the same forum page\n return redirect('/forums/order_by_date/' + str(parent_post.forum_id) + \"/1\")\n\n\n\n@app.route(\"/forums/like/\", methods=[\"GET\"])\ndef add_like(post_id):\n \"\"\"When the user \"likes\" a post, it adds it to the dbase and updates page with new\n like info (Tested)\"\"\"\n\n #Queries from all of the dbase tables that need to be updated and/or rendered\n user_id = User.query.filter_by(email=session['current_user']).one().user_id\n forum_id = Post.query.filter_by(post_id=post_id).one().forum_id\n like_query = Like.query.filter(Like.post_id == post_id, Like.user_id == user_id).all()\n post_query = db.session.query(Post).filter_by(post_id=post_id).one()\n\n #If the user hasn't already liked/disliked the post, it adds the like to the dbase\n if like_query == []:\n new_like = Like(user_id=user_id, post_id=post_id, like_dislike=\"like\")\n db.session.query(Post).filter_by(post_id=\n post_id).update({\"like_num\": (post_query.like_num + 1)})\n db.session.add(new_like)\n db.session.commit()\n\n #If the user previously disliked the comment, it updates it to a like\n elif like_query[0].like_dislike == \"dislike\":\n db.session.query(Like).filter(Like.post_id == post_id,\n Like.user_id == user_id).update({\"user_id\": user_id,\n \"post_id\": post_id,\n \"like_dislike\": \"like\"})\n (db.session.query(Post).filter_by(post_id=post_id).update(\n {\"like_num\": (post_query.like_num + 1), \"dislike_num\": (post_query.dislike_num - 1)}))\n db.session.commit()\n\n #Re-renders the forum page with the updated like info\n return redirect(\"/forums/order_by_date/{}/1\".format(forum_id))\n\n\n@app.route(\"/forums/dislike/\", methods=[\"GET\"])\ndef add_dislike(post_id):\n \"\"\"When the user \"dislikes\" a post, it adds it to the dbase & updates page with new like info (Tested)\"\"\"\n\n #Queries from all of the dbase tables that need to be updated and/or rendered\n user_id = User.query.filter_by(email=session['current_user']).one().user_id\n forum_id = Post.query.filter_by(post_id=post_id).one().forum_id\n like_query = Like.query.filter(Like.post_id == post_id, Like.user_id == user_id).all()\n post_query = db.session.query(Post).filter_by(post_id=post_id).one()\n\n #If the user hasn't already liked/disliked the post, it adds the dislike to the dbase\n if like_query == []:\n new_dislike = Like(user_id=user_id, post_id=post_id, like_dislike=\"dislike\")\n (db.session.query(Post).filter_by(post_id=post_id).update(\n {\"dislike_num\": (post_query.dislike_num + 1)}))\n db.session.add(new_dislike)\n db.session.commit()\n\n #If the user previously liked the comment, it updates it to a dislike\n else:\n (db.session.query(Like).filter(Like.post_id == post_id, Like.user_id == user_id).update(\n {\"user_id\": user_id, \"post_id\": post_id, \"like_dislike\": \"dislike\"}))\n (db.session.query(Post).filter_by(post_id=post_id).update(\n {\"dislike_num\": (post_query.dislike_num + 1), \"like_num\": (post_query.like_num - 1)}))\n db.session.commit()\n\n #Re-renders the forum page with the updated dislike info\n return redirect(\"/forums/order_by_date/{}/1\".format(forum_id))\n\n\n@app.route(\"/forums/flag/\", methods=[\"POST\"])\ndef flag_post(post_id):\n \"\"\"When a user submitts a flag for removal, adds it to the dbase and refreshes page (Tested)\"\"\"\n\n #Queries from all of the dbase tables that need to be updated and/or rendered\n user_id = User.query.filter_by(email=session['current_user']).one().user_id\n forum_id = Post.query.filter_by(post_id=post_id).one().forum_id\n flag_query = Flag.query.filter(Flag.post_id == post_id, Flag.user_id == user_id).all()\n post_query = db.session.query(Post).filter_by(post_id=post_id).one()\n\n #Gets the flag type from the flag form submission\n f_type = request.form['flag_rad']\n\n #Doublecheck the user hasn't already liked the post and then updates the dbase\n if flag_query == []:\n new_flag = Flag(user_id=user_id, post_id=post_id, flag_type=f_type)\n db.session.query(Post).filter_by(post_id=\n post_id).update({\"flag_num\": (post_query.flag_num + 1)})\n db.session.add(new_flag)\n db.session.commit()\n\n #Flashes message and re-renders the forum page\n flash('Your report has been submitted!')\n return redirect(\"/forums/order_by_date/{}/1\".format(forum_id))\n\n\n@app.route(\"/forums/order_by_date//\")\ndef date_order(forum_id, page_num=1):\n \"\"\"Renders forum page with posts ordered by date (Tested, but not the actual order)\"\"\"\n\n #Defining the central forums (within app context) to be rendered\n cam = Forum.query.filter_by(forum_id=1).one()\n dom = Forum.query.filter_by(forum_id=2).one()\n escort = Forum.query.filter_by(forum_id=3).one()\n porn = Forum.query.filter_by(forum_id=4).one()\n dance = Forum.query.filter_by(forum_id=5).one()\n phone = Forum.query.filter_by(forum_id=6).one()\n sugar = Forum.query.filter_by(forum_id=7).one()\n other = Forum.query.filter_by(forum_id=8).one()\n\n #Creates lists for all of the children forums of the main 8 forums\n cam_query = Forum.query.filter_by(parent_forum_id=1).all()\n dom_query = Forum.query.filter_by(parent_forum_id=2).all()\n escort_query = Forum.query.filter_by(parent_forum_id=3).all()\n porn_query = Forum.query.filter_by(parent_forum_id=4).all()\n dance_query = Forum.query.filter_by(parent_forum_id=5).all()\n phone_query = Forum.query.filter_by(parent_forum_id=6).all()\n sugar_query = Forum.query.filter_by(parent_forum_id=7).all()\n other_query = Forum.query.filter_by(parent_forum_id=8).all()\n\n #Queries from all of the dbase tables that need to be updated and/or rendered\n posts = Post.query.filter(Post.forum_id == forum_id, Post.parent_post_id == 0, Post.deleted == False).order_by(asc(Post.post_id)).all()\n child_posts = Post.query.filter(Post.forum_id == forum_id, Post.parent_post_id != 0).order_by(asc(Post.post_id)).all()\n users = Post.query.all()\n user = User.query.filter_by(email=session['current_user']).one()\n flag_query = Flag.query.filter(Flag.user_id == User.user_id).all()\n forum = Forum.query.filter_by(forum_id=forum_id).one()\n post_index=int(math.ceil((len(posts)/float(10))))\n\n print(posts)\n if posts:\n print(posts[0].forum_id)\n\n #Defines empty flag list to be filled with user's flags\n flags = []\n if len(flag_query) > 0:\n for item in flag_query:\n flags.append(item.post_id)\n\n #Renders Page\n return render_template(\"forum_page.html\", users=users, forum=forum, cam=cam, dom=dom, escort=escort,\n porn=porn, dance=dance, phone=phone, posts=posts, user=user,\n child_posts=child_posts, flags=flags, flagnum=0, other=other, sugar=sugar, post_index=post_index, current_page=int(page_num),\n cam_query=cam_query, dom_query=dom_query, escort_query=escort_query,\n porn_query=porn_query, dance_query=dance_query, phone_query=phone_query,\n sugar_query=sugar_query, other_query=other_query)\n\n\n@app.route(\"/forums/order_by_pop//\")\ndef pop_order(forum_id, page_num=1):\n \"\"\"Renders forum page with posts ordered by popularity (Tested, but not the actual order)\"\"\"\n\n #Defining the central forums (within app context) to be rendered\n cam = Forum.query.filter_by(forum_id=1).one()\n dom = Forum.query.filter_by(forum_id=2).one()\n escort = Forum.query.filter_by(forum_id=3).one()\n porn = Forum.query.filter_by(forum_id=4).one()\n dance = Forum.query.filter_by(forum_id=5).one()\n phone = Forum.query.filter_by(forum_id=6).one()\n sugar = Forum.query.filter_by(forum_id=7).one()\n other = Forum.query.filter_by(forum_id=8).one()\n \n #Creates lists for all of the children forums of the main 8 forums\n cam_query = Forum.query.filter_by(parent_forum_id=1).all()\n dom_query = Forum.query.filter_by(parent_forum_id=2).all()\n escort_query = Forum.query.filter_by(parent_forum_id=3).all()\n porn_query = Forum.query.filter_by(parent_forum_id=4).all()\n dance_query = Forum.query.filter_by(parent_forum_id=5).all()\n phone_query = Forum.query.filter_by(parent_forum_id=6).all()\n sugar_query = Forum.query.filter_by(parent_forum_id=7).all()\n other_query = Forum.query.filter_by(parent_forum_id=8).all()\n\n #Queries from all of the dbase tables that need to be updated and/or rendered\n posts = Post.query.filter(Post.forum_id == forum_id, Post.parent_post_id == 0, Post.deleted == False).order_by(desc(Post.like_num)).all()\n child_posts = Post.query.filter(Post.forum_id == forum_id, Post.parent_post_id != 0).order_by(desc(Post.like_num)).all()\n user = User.query.filter_by(email=session['current_user']).one()\n flag_query = Flag.query.filter(Flag.user_id == User.user_id).all()\n forum = Forum.query.filter_by(forum_id=forum_id).one()\n post_index=int(math.ceil((len(posts)/float(10))))\n #Defines empty flag list to be filled with user's flags\n flags = []\n if len(flag_query) > 0:\n for item in flag_query:\n flags.append(item.post_id)\n\n #Renders Page\n return render_template(\"forum_page.html\", forum=forum, cam=cam, dom=dom, escort=escort, user=user,\n porn=porn, dance=dance, phone=phone, posts=posts, \n child_posts=child_posts, flags=flags, flagnum=0, other=other, sugar=sugar,\n post_index=post_index, current_page=1,\n cam_query=cam_query, dom_query=dom_query, escort_query=escort_query,\n porn_query=porn_query, dance_query=dance_query, phone_query=phone_query,\n sugar_query=sugar_query, other_query=other_query)\n\n\n@app.route(\"/report\", methods=[\"GET\"])\ndef report_page():\n \"\"\"If user logged in, renders report form page, otherwise redirects to login\"\"\"\n\n if 'current_user' in list(session.keys()):\n return render_template(\"report_form.html\")\n else:\n flash('You must sign in before making a report.')\n return redirect(\"/login\")\n\n\n\n@app.route(\"/report\", methods=[\"POST\"])\ndef submit_form():\n \"\"\"Submits the report form and saves incident to database\"\"\"\n\n #Queries dBase and gets info from form to be saves as new incident\n user_id = (User.query.filter(User.email == session['current_user']).first()).user_id\n inc_type = request.form['inc_type']\n address = request.form['address']\n city = request.form['city']\n state = request.form['state']\n lat = str(request.form['lat'])\n lng = str(request.form['lng'])\n date = request.form['date']\n time = str(request.form['time'])\n description = request.form['description']\n p_name = request.form['p_name']\n badge = request.form['badge']\n p_description = request.form['p_description']\n sting = request.form['sting']\n avoid = request.form['avoid']\n other = request.form['other']\n year = date[0:4]\n\n #Creates new incident and commits it to dBase\n new_report = Incident(year=year, user_id=user_id, police_dept_id=3, source_id=3,\n inc_type=inc_type, address=address, city=city, state=state, latitude=lat,\n longitude=lng, date=date, time=time, description=description,\n sting_strat=sting, avoidance=avoid, other=other)\n new_cop = Cop(user_id=user_id, police_dept_id=3, cop_name=p_name, cop_badge=badge, cop_desc=p_description)\n db.session.add(new_report)\n db.session.add(new_cop)\n db.session.commit()\n\n #Redirects to homepage sudo apt-get install build-essential libffi-dev python-dev\n flash('Your report has been filed and should be added to the map soon!')\n return redirect(\"/\")\n\n\n\n@app.route(\"/profile\")\ndef user_profile():\n \"\"\"Renders user's profile\"\"\"\n\n user = User.query.filter_by(email=session['current_user']).one()\n\n return render_template(\"user_page.html\", email=user.email, username=user.username,\n fname=user.fname, lname=user.lname, about_me=user.description, tagline=user.tagline, location=user.location)\n\n\n\n@app.route(\"/edit_profile\", methods=[\"GET\"])\ndef edit_page():\n \"\"\"Renders the edit profile page\"\"\"\n\n user = User.query.filter_by(email=session['current_user']).one()\n\n return render_template(\"edit_profile.html\", email=user.email, username=user.username,\n fname=user.fname, lname=user.lname, about_me=user.description, user=user)\n\n\n\n@app.route(\"/edit_profile\", methods=[\"POST\"])\ndef edit_profile():\n \"\"\"Submits the profile edits\"\"\"\n\n #Gets info from html form and dbase\n email_input = request.form['email_input']\n pw_input = request.form['old_password']\n new_password = request.form['new_password']\n username = request.form['username']\n fname = request.form['fname']\n tagline = request.form['tagline']\n location = request.form['location']\n lname = request.form['lname']\n about_me = request.form['about_me']\n email2 = request.form['email_input2']\n phone = request.form['phone']\n timezone = request.form['timezone']\n user = User.query.filter_by(email=session['current_user']).one()\n\n #Checks that the password matches the user's password. If so, updates the user's info\n if User.query.filter(User.email == email_input, User.password == pw_input).all() != []:\n (db.session.query(User).filter(\n User.email == session['current_user'], User.password == pw_input).update(\n {'fname': fname, 'lname': lname, 'email': email_input, 'password': new_password,\n 'username': username, 'description': about_me, 'email2': email2, 'phone': phone,\n 'timezone': timezone}))\n db.session.commit()\n flash('Your Profile was Updated!')\n return redirect(\"/profile\")\n\n #Otherwise, it flashes a message and redirects to the login page\n else:\n flash('Your e-mail or password was incorrect! Please try again or Register.')\n return redirect(\"/edit_profile\")\n\n@app.route(\"/contact\")\ndef contact_us():\n return render_template(\"contact.html\")\n\n@app.route(\"/resources\")\ndef resources():\n return render_template(\"resources.html\")\n\n@app.route(\"/sw_main\")\ndef safewalk_main():\n time = datetime.datetime.now().time()\n date = (datetime.datetime.today())\n now = datetime.datetime.now()\n user = User.query.filter_by(email=session['current_user']).one()\n alert_sets = AlertSet.query.filter_by(user_id=user.user_id).all()\n al_sets = []\n alerts = Alert.query.filter_by(user_id=user.user_id).all()\n for a_set in alert_sets:\n aset_alerts = []\n a_set.total = 0\n for alert in alerts:\n if a_set.alert_set_id == alert.alert_set_id and a_set.interval:\n aset_alerts.append(alert.datetime)\n elif a_set.alert_set_id == alert.alert_set_id:\n dtime = datetime.datetime.now()\n if time >= alert.time:\n tomorrow = date + datetime.timedelta(days=1)\n dtime = datetime.datetime.combine(tomorrow, alert.time)\n else: \n dtime = datetime.datetime.combine(date, alert.time)\n aset_alerts.append(dtime)\n if len(aset_alerts) >= 1: \n aset_alerts.sort()\n print('aset_alerts:')\n print(aset_alerts[0])\n a_set.next_alarm = aset_alerts[0]\n a_set.next_alarm_dis = aset_alerts[0].strftime(\"%I:%M %p, %Y/%m/%d\")\n d1 = abs(now - aset_alerts[0])\n d2 = float(d1.total_seconds())\n days = math.floor(d2 / 86400)\n hours = math.floor((d2 - (days * 86400)) / 3600)\n minutes = math.floor((d2 - (days * 86400) - (hours * 3600)) / 60)\n seconds = math.floor(d2 - (days * 86400) - (hours * 3600) - (minutes * 60))\n print(minutes)\n a_set.countdown = datetime.time(int(hours), int(minutes), int(seconds))\n a_set.days = int(days)\n a_set.hours = int(hours)\n a_set.minutes = int(minutes)\n a_set.seconds = int(seconds)\n a_set.total =int(d2)\n print(a_set.total)\n\n return render_template(\"safewalk_main.html\", alert_sets=alert_sets, timezone=user.timezone)\n\n\n@app.route(\"/rec_alerts\")\ndef recurring_alerts():\n user = User.query.filter_by(email=session['current_user']).one()\n contacts = Contact.query.filter_by(user_id=user.user_id).order_by(asc(Contact.contact_id)).all()\n return render_template(\"recurring_alerts.html\", contacts=contacts)\n\n@app.route(\"/sched_alerts\")\ndef scheduled_alerts():\n user = User.query.filter_by(email=session['current_user']).one()\n contacts = Contact.query.filter_by(user_id=user.user_id).order_by(asc(Contact.contact_id)).all()\n return render_template(\"scheduled_alerts.html\", contacts=contacts)\n\n\n@app.route(\"/contacts\")\ndef user_contacts():\n user = User.query.filter_by(email=session['current_user']).one()\n contacts = Contact.query.filter_by(user_id=user.user_id).order_by(asc(Contact.contact_id)).all()\n return render_template(\"contacts.html\", contacts=contacts)\n\n@app.route(\"/contacts\", methods=[\"POST\"])\ndef add_contact():\n name = request.form['name']\n phone = request.form['phone']\n email = request.form['email']\n c_type = request.form['c_type']\n message = request.form['message']\n user = User.query.filter_by(email=session['current_user']).one()\n new_contact = Contact(user_id=user.user_id, name=name, email=email, phone=phone, c_type=c_type, c_message=message)\n db.session.add(new_contact)\n db.session.commit()\n return redirect(\"/contacts\")\n\n@app.route(\"/del_contact/\")\ndef delete_contact(contact_num):\n contact = Contact.query.filter_by(contact_id=contact_num).one()\n db.session.delete(contact)\n db.session.commit()\n return redirect(\"/contacts\")\n\n@app.route(\"/edit_contact/\", methods=[\"POST\"])\ndef edit_contact(contact_num):\n name = request.form['name']\n phone = request.form['phone']\n email = request.form['email']\n c_type = request.form['c_type']\n message = request.form['message']\n contact = Contact.query.filter_by(contact_id=contact_num).one()\n ((db.session.query(Contact).filter_by(contact_id=contact_num)).update(\n {'name':name, 'email':email, 'phone':phone, 'c_type':c_type, 'c_message':message}))\n db.session.commit()\n return redirect(\"/contacts\")\n\n@app.route(\"/add_recset\", methods=[\"POST\"])\ndef add_rec_alertset():\n name = request.form['set_name']\n desc = request.form['descri']\n interval = request.form['interval']\n contacts = request.form.getlist('contact')\n user = User.query.filter_by(email=session['current_user']).one()\n new_alert_set = AlertSet(user_id=user.user_id, a_name=name, a_desc=desc, interval=interval)\n db.session.add(new_alert_set)\n db.session.commit()\n alert_set = AlertSet.query.filter(AlertSet.user_id == user.user_id, AlertSet.a_name == name).first()\n contact1 = int(contacts[0])\n contact2 = None\n contact3 = None\n if len(contacts) > 1:\n contact2 = int(contacts[1])\n if len(contacts) > 2:\n contact3 = int(contacts[2]) \n new_alert = Alert(alert_set_id=alert_set.alert_set_id, user_id=user.user_id, contact_id1=contact1,\n contact_id2=contact2, contact_id3=contact3, interval=interval, message=desc)\n db.session.add(new_alert)\n db.session.commit()\n alert_set = AlertSet.query.filter(AlertSet.user_id == user.user_id, AlertSet.a_name == name).first()\n return redirect(\"/sw_main\")\n\n@app.route(\"/edit_recset/\")\ndef edit_recset_page(alert_set_id):\n user = User.query.filter_by(email=session['current_user']).one()\n alert_set = AlertSet.query.filter_by(alert_set_id=alert_set_id).one()\n contacts = Contact.query.filter_by(user_id=user.user_id).order_by(asc(Contact.contact_id)).all()\n alert = Alert.query.filter_by(alert_set_id=alert_set_id).one()\n return render_template(\"edit_recurring_alerts.html\", alert_set=alert_set, contacts=contacts, alert=alert)\n\n@app.route(\"/save_recset/\", methods=[\"POST\"])\ndef save_recset(alert_set_id):\n name = request.form['set_name']\n desc = request.form['descri']\n interval = request.form['interval']\n contacts = request.form.getlist('contact')\n (db.session.query(AlertSet).filter_by(alert_set_id=alert_set_id)).update(\n {'a_name': name, 'a_desc': desc, 'interval': interval})\n contact1 = int(contacts[0])\n contact2 = None\n contact3 = None\n if len(contacts) > 1:\n contact2 = int(contacts[1])\n if len(contacts) > 2:\n contact3 = int(contacts[2])\n (db.session.query(Alert).filter_by(alert_set_id=alert_set_id)).update(\n {'message': desc, 'interval': interval, 'contact_id1': contact1, 'contact_id2': contact2, 'contact_id3': contact3})\n db.session.commit()\n return redirect(\"/sw_main\")\n\n@app.route(\"/add_schedset\", methods=[\"POST\"])\ndef add_sched_alertset():\n date = None\n end_date = None\n if len(request.form['date']) > 2:\n date = request.form['date']\n if len(request.form['end_date']) > 2:\n end_date = request.form['end_date']\n name = request.form['set_name']\n desc = request.form['descri']\n user = User.query.filter_by(email=session['current_user']).one()\n new_alert_set = AlertSet(user_id=user.user_id, a_name=name, a_desc=desc, date=date, end_date=end_date)\n db.session.add(new_alert_set)\n db.session.commit()\n alert_set = AlertSet.query.filter(AlertSet.user_id == user.user_id, AlertSet.a_name == name).first()\n return redirect(\"/edit_schedset/\" + str(alert_set.alert_set_id))\n # return redirect(\"/sw_main\")\n\n@app.route(\"/edit_schedset/\")\ndef edit_schedset_page(alert_set_id):\n user = User.query.filter_by(email=session['current_user']).one()\n alert_set = AlertSet.query.filter_by(alert_set_id=alert_set_id).one()\n alerts = Alert.query.filter_by(alert_set_id=alert_set_id).all()\n contacts = Contact.query.filter_by(user_id=user.user_id).order_by(asc(Contact.contact_id)).all()\n return render_template(\"edit_sched_alerts.html\", alert_set=alert_set, contacts=contacts, alerts=alerts)\n\n@app.route(\"/edit_set/\", methods=[\"POST\"])\ndef save_schedset(alert_set_id):\n date = request.form['date']\n end_date = request.form['end_date']\n name = request.form['set_name']\n desc = request.form['descri']\n (db.session.query(AlertSet).filter_by(alert_set_id=alert_set_id)).update(\n {'date': date, 'end_date': end_date, 'a_name': name, 'a_desc': desc}) \n db.session.commit()\n return redirect(\"/edit_schedset/\" + str(alert_set_id))\n\n@app.route(\"/add_alert/\", methods=[\"POST\"])\ndef add_sched_alert(alert_set_id):\n user = User.query.filter_by(email=session['current_user']).one()\n time = request.form['time']\n contacts = request.form.getlist('contact')\n contact1 = int(contacts[0])\n contact2 = None\n contact3 = None\n if len(contacts) > 1:\n contact2 = int(contacts[1])\n if len(contacts) > 2:\n contact3 = int(contacts[2])\n message = request.form['check_mess']\n new_alert = Alert(alert_set_id=alert_set_id, user_id=user.user_id, contact_id1=contact1,\n contact_id2=contact2, contact_id3=contact3, message=message, time=time)\n db.session.add(new_alert)\n db.session.commit()\n return redirect(\"/edit_schedset/\" + str(alert_set_id))\n\n@app.route(\"/activate/\")\ndef activate_alertset(alert_set_id):\n print(alert_set_id)\n alert_set = AlertSet.query.filter_by(alert_set_id=alert_set_id).one()\n time = datetime.datetime.now().time()\n date = (datetime.datetime.today())\n dt = datetime.datetime.now()\n if alert_set.date == None:\n db.session.query(AlertSet).filter_by(alert_set_id=alert_set_id).update({'date': date, 'start_datetime': dt})\n if alert_set.interval == None:\n print(\"step 1\")\n alerts = Alert.query.filter_by(alert_set_id=alert_set_id).all()\n for alert in alerts:\n print(\"step 2\")\n db.session.query(Alert).filter_by(alert_id=alert.alert_id).update({'active': True, 'start_time': time})\n if alert.date == None:\n print(\"step3a\")\n print(time)\n print(alert.time)\n print(type(alert.time))\n dtime = datetime.datetime.combine(date, alert.time)\n print(dtime)\n db.session.query(Alert).filter_by(alert_id=alert.alert_id).update({'date': date, 'datetime': dtime})\n else:\n print(\"step 3b\")\n dtime = datetime.datetime.combine(alert.date, alert.time)\n db.session.query(Alert).filter_by(alert_id=alert.alert_id).update({'datetime': dtime})\n else:\n print(\"Interval = \" + str(alert_set.interval))\n print(\"Rec Activated\")\n dtime = datetime.datetime.combine(date, time)\n dtime_int = dtime + datetime.timedelta(minutes=alert_set.interval)\n alert = Alert.query.filter_by(alert_set_id=alert_set_id).one()\n db.session.query(Alert).filter_by(alert_id=alert.alert_id).update({'active': True, 'start_time': time, 'start_time': time, 'datetime': dtime_int})\n db.session.query(AlertSet).filter_by(alert_set_id=alert_set_id).update({'active': True, 'start_time': time, 'start_datetime': dt})\n db.session.commit()\n return \"Alert Set Activated\"\n\n@app.route(\"/deactivate/\")\ndef deactivate_alertset(alert_set_id):\n (db.session.query(AlertSet).filter_by(alert_set_id=alert_set_id)).update(\n {'active': False})\n alerts = Alert.query.filter_by(alert_set_id=alert_set_id).all()\n for alert in alerts:\n db.session.query(Alert).filter_by(alert_id=alert.alert_id).update(\n {'active': False})\n db.session.commit()\n return \"Alert Set Deactivated\"\n\n@app.route(\"/check_ins\")\ndef checkin_page():\n user = User.query.filter_by(email=session['current_user']).one()\n check_ins = CheckIn.query.filter_by(user_id=user.user_id).all()\n return render_template(\"checkins_page.html\", check_ins=check_ins)\n\n@app.route(\"/add_check_in\", methods=[\"POST\"])\ndef add_new_checkin():\n text = request.form['check_text']\n user = User.query.filter_by(email=session['current_user']).one()\n time = datetime.datetime.now().time()\n date = (datetime.datetime.today())\n datetim = datetime.datetime.now()\n new_check = CheckIn(user_id=user.user_id, notes=text, time=time, date=date, datetime=datetim)\n db.session.add(new_check)\n db.session.commit()\n return redirect(\"/check_ins\")\n\n@app.route(\"/incoming_mail\", methods=[\"POST\"]) \ndef mailin(): \n \n # access some of the email parsed values:\n sender = request.form['From']\n send_email = request.form['sender']\n subject = request.form['subject']\n text = request.form['body-plain']\n time = datetime.datetime.now().time()\n date = (datetime.datetime.today())\n datetim = datetime.datetime.now()\n user = User.query.filter_by(email=str.strip(send_email)).all()\n if len(user) >= 1: \n new_check = CheckIn(user_id=user.user_id, notes=text, time=time, date=date, datetime=datetim)\n db.session.add(new_check)\n db.session.commit()\n print(send_email)\n print(\"Email Message Received\")\n return \"Email Message Received\"\n\n@app.route('/incoming_sms', methods=['POST'])\ndef smsin():\n dat = request.data\n data = json.loads(dat.decode(encoding=\"utf-8\", errors=\"strict\"))\n message_body = data['text']\n phone = data['from']\n time = datetime.datetime.now().time()\n date = (datetime.datetime.today())\n datetim = datetime.datetime.now()\n user = User.query.filter_by(phone=str(phone[-10:])).all()\n u_id = user[0].user_id\n if len(user) >= 1: \n new_check = CheckIn(user_id=u_id, notes=message_body, time=time, date=date, datetime=datetim)\n db.session.add(new_check)\n db.session.commit()\n print(phone[-10:])\n print(user)\n print(\"SMS Received\")\n return \"SMS Received\"\n\n\n#####################################################\n\nif __name__ == \"__main__\":\n start_runner()\n print(\"should be working\")\n connect_to_db(app, 'postgresql:///safework')\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n print(\"Connected to DB.\")\n app.run(host='0.0.0.0')\n \n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":53226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"283703285","text":"from keras.applications import ResNet50\nfrom keras.applications.densenet import DenseNet\nfrom keras.engine import Model\nfrom keras.layers import Activation, Convolution2D, GlobalAveragePooling2D, Dense, Flatten, Dropout\nfrom keras.utils import plot_model\n\nfrom models.TrainingConfiguration import TrainingConfiguration\n\n\nclass DenseNetConfiguration(TrainingConfiguration):\n \"\"\" A network with residual modules \"\"\"\n\n def __init__(self, width: int, height: int):\n super().__init__(data_shape=(height, width, 3))\n\n def classifier(self) -> Model:\n \"\"\" Returns the model of this configuration \"\"\"\n base_model = DenseNet([6, 12, 24, 16], include_top=False, weights='imagenet', input_shape=self.data_shape, pooling=None)\n x = base_model.output\n x = Flatten()(x)\n x = Dense(500)(x)\n x = Dropout(0.5)(x)\n x = Dense(500)(x)\n x = Dropout(0.5)(x)\n x = Dense(8, activation='linear', name='output_class')(x)\n model = Model(inputs=base_model.inputs, outputs=x)\n model.compile(self.get_optimizer(), loss=\"mean_squared_error\", metrics=[\"mae\"])\n\n return model\n\n def name(self) -> str:\n \"\"\" Returns the name of this configuration \"\"\"\n return \"dense_net\"\n\n\nif __name__ == \"__main__\":\n configuration = DenseNetConfiguration(400, 224)\n classifier = configuration.classifier()\n classifier.summary()\n plot_model(classifier, to_file=\"res_net_50.png\")\n print(configuration.summary())\n","sub_path":"assignment1/models/DenseNetConfiguration.py","file_name":"DenseNetConfiguration.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"576803906","text":"# coding : utf-8\n\nimport RPi.GPIO as GPIO\n\nKEYPADlist = [4,23,18,17,27,22,24]\n\ndef KeypadRead():\n\tkeypadnum = -1\n\tfor i in range(7):\n\t\tif(not GPIO.input(KEYPADlist[i])):\n\t\t\tkeypadnum = i\n\t\t\tbreak\n\treturn keypadnum\n\nGPIO.setmode(GPIO.BCM)\n\ndef init():\n\tfor i in KEYPADlist:\n\t\tGPIO.setup(i, GPIO.IN)\n\ndef read():\n\tkeypadnum = KeypadRead()\n\treturn keypadnum\n\n","sub_path":"GPIO_KEYPAD.py","file_name":"GPIO_KEYPAD.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"392143342","text":"import os, unittest\nimport numpy as np\nfrom astropy.io.fits import getheader\n\nfrom lsst.sims.utils import ObservationMetaData\n\nfrom lsst.ts.wep.bsc.BrightStarDatabase import BrightStarDatabase\nfrom lsst.ts.wep.bsc.CameraData import LsstCamera, ComCam \nfrom lsst.ts.wep.bsc.Filter import Filter\nfrom lsst.ts.wep.LocalDatabaseDecorator import LocalDatabaseDecorator\nfrom lsst.ts.wep.Utility import getModulePath\n\nclass SourceSelector(object):\n\n UWdb = \"UWdb\"\n LocalDb = \"LocalDb\"\n\n LSST = \"lsst\"\n COMCAM = \"comcam\"\n\n def __init__(self):\n \"\"\"\n \n Initialize the SourceSelector class.\n \"\"\"\n\n self.db = None\n self.tableName = None\n self.name = None\n\n self.camera = None\n self.cameraMJD = None\n\n self.maxDistance = np.nan\n self.maxNeighboringStar = np.nan\n\n self.filter = Filter()\n\n def setDb(self, dbType):\n \"\"\"\n \n Set the database.\n \n Arguments:\n dbType {[str]} -- Type of database (\"UWdb\" or \"LocalDb\").\n \"\"\"\n\n if (dbType == self.UWdb):\n db = BrightStarDatabase()\n tableName = \"bright_stars\"\n \n elif (dbType == self.LocalDb):\n db = LocalDatabaseDecorator()\n tableName = \"BrightStarCatalog\"\n else:\n raise ValueError(\"No '%s' database.\" % dbType)\n\n self.db = db\n self.tableName = tableName\n self.name = dbType\n\n def setCamera(self, cameraType, cameraMJD=59580.0):\n \"\"\"\n \n Set the camera.\n \n Arguments:\n cameraType {[str]} -- Type of camera (\"lsst\" or \"comcam\"). (default: {None})\n \n Keyword Arguments:\n cameraMJD {float} -- Camera MJD. (default: {59580.0})\n \"\"\"\n\n # Set the camera and do the initialization\n if (cameraType == self.LSST):\n camera = LsstCamera()\n elif (cameraType == self.COMCAM):\n camera = ComCam()\n else:\n raise ValueError(\"No '%s' camera.\" % cameraType)\n\n self.camera = camera\n self.camera.initializeDetectors()\n\n # Set the camera MJD\n self.cameraMJD = cameraMJD\n\n def configSelector(self, cameraType=None, dbType=None, aFilter=None, cameraMJD=59580.0):\n \"\"\"\n \n Configurate the source selector.\n \n Keyword Arguments:\n cameraType {[str]} -- Type of camera (\"lsst\" or \"comcam\"). (default: {None})\n dbType {[str]} -- Type of database (\"UWdb\" or \"LocalDb\"). (default: {None})\n aFilter {[str]} -- Active filter type (\"u\", \"g\", \"r\", \"i\", \"z\", \"y\"). \n (default: {None})\n cameraMJD {float} -- Camera MJD. (default: {59580.0})\n \n Raises:\n ValueError -- No database type.\n ValueError -- No camera type.\n \"\"\"\n\n # Set the data base\n if (dbType is not None):\n self.setDb(dbType)\n\n # Set the camera mapper\n if (cameraType is not None):\n self.setCamera(cameraType, cameraMJD=cameraMJD)\n\n # Set the filter\n if (aFilter is not None):\n self.setFilter(aFilter)\n\n def connect(self, *kwargs):\n \"\"\"\n \n Connect the database.\n \n Arguments:\n *kwargs {[string]} -- Information to connect to the database.\n \"\"\"\n\n self.db.connect(*kwargs)\n\n def disconnect(self):\n \"\"\"\n \n Disconnect the database.\n \"\"\"\n\n self.db.disconnect()\n\n def getTargetStar(self, pointing, cameraRotation, orientation=None, offset=0, tableName=None):\n \"\"\"\n \n Get the target stars by querying the database.\n \n Arguments:\n pointing {[tuple]} -- Camera boresight (RA, Decl) in degree.\n cameraRotation {[float]} -- Camera rotation angle in degree.\n \n Keyword Arguments:\n orientation {[str]} -- Orientation of wavefront sensor(s) on camera. (default: {None})\n offset {[float]} -- Add offset in pixel to sensor dimension for judging stars on detector or not. \n offset=0 for normal use. \n offset=maxDistance to generate the local database. (default: {0})\n tableName {[str]} -- Table name. (default: {None})\n \n Returns:\n {[dict]} -- Information of neighboring stars and candidate stars with the name of \n sensor as a dictionary.\n {[dict]} -- Information of stars with the name of sensor as a dictionary.\n {[dict]} -- Corners of sensor with the name of sensor as a dictionary.\n \"\"\"\n\n # Filter type\n cameraFilter = self.filter.getFilter()\n\n # Regenerate the table name for local database\n if (tableName is None):\n if (self.name == self.LocalDb):\n tableName = self.tableName + self.filter.getFilter().upper()\n # Keep the same table name\n else:\n tableName = self.tableName\n\n # Setup the boundary of magnitude based on the filter\n lowMagnitude, highMagnitude = self.filter.getMagBoundary()\n\n # Get corners of wavefront sensors for this observation field\n obs = self.__getObs(pointing, cameraRotation, self.cameraMJD)\n\n # Assign the wavefront sensors \n wavefrontSensors = []\n if (self.camera.name == self.camera.COMCAM):\n if orientation in (\"corner\", \"center\", \"all\"):\n wavefrontSensors = self.camera.getSensor(obs, orientation)\n elif (self.camera.name == self.camera.LSST):\n if (orientation == \"corner\"):\n wavefrontSensors = self.camera.getWavefrontSensor(obs)\n elif (orientation == \"all\"):\n wavefrontSensors = self.camera.getScineceSensor(obs)\n\n if not (wavefrontSensors):\n print(\"No wavefront sensor is allocated.\")\n\n print(\"Boresight: (RA, Decl) = (%f, %f) \" % (pointing[0], pointing[1]))\n\n # Query the star database\n starMap = {}\n neighborStarMap = {}\n for detector in wavefrontSensors:\n\n print(\"Processing detector %s\" % detector)\n wavefrontSensor = wavefrontSensors[detector]\n\n # Get stars in this wavefront sensor for this observation field\n stars = self.db.query(tableName, cameraFilter, wavefrontSensor[0], wavefrontSensor[1], \n wavefrontSensor[2], wavefrontSensor[3])\n\n starsQueried = len(stars.RA)\n print(\"\\t\\tStars queried: %d\" % starsQueried)\n\n # Populate detector information for the stars\n stars.populateDetector(detector)\n\n # Populate pixel information for stars\n self.camera.populatePixelFromRADecl(stars, obs)\n\n # Remove stars that are not on the detector\n self.camera.removeStarsNotOnDetectorSimple(stars, obs, offset)\n starMap[detector] = stars\n\n starsOnDetector = len(stars.RA)\n print(\"\\t\\tStars on detector: %d\" % starsOnDetector)\n\n # Check the candidate of bright stars based on the magnitude\n indexCandidate = stars.checkCandidateStars(cameraFilter, lowMagnitude, highMagnitude)\n\n # Determine the neighboring stars based on the distance and allowed number \n # of neighboring stars\n neighborStar = stars.getNeighboringStar(indexCandidate, self.maxDistance, \n cameraFilter, self.maxNeighboringStar)\n neighborStarMap[detector] = neighborStar\n\n print(\"\\t\\tAvailable candidate stars: %d\" % len(neighborStar.SimobjID))\n\n return neighborStarMap, starMap, wavefrontSensors\n\n def __getObs(self, pointing, cameraRotation, mjd):\n \"\"\"\n \n Get the observation metadata.\n \n Arguments:\n pointing {[tuple]} -- Camera boresight (RA, Decl) in degree.\n cameraRotation {[float]} -- Camera rotation angle in degree.\n mjd {[float]} -- Camera mjd.\n \n Returns:\n [metadata] -- The observation meta data (found in the lsst-sims stack) that defines \n the pointing.\n \"\"\"\n\n # Get Ra, Decl\n RA, Dec = pointing\n\n obs = []\n obs = ObservationMetaData(pointingRA = RA, pointingDec = Dec, \n rotSkyPos = cameraRotation, mjd = mjd)\n if (not obs):\n print(\"No observation metadata.\")\n\n return obs\n\n def insertToBSC(self, neighborStarMap):\n \"\"\"\n \n Insert the neighboring star data into the local database.\n \n Arguments:\n neighborStarMap {[NeighboringStar]} -- Information of neighboring stars.\n \n Raises:\n ValueError -- Not the local database.\n \"\"\"\n \n # Check the database is the local database or not\n if (self.name != self.LocalDb):\n raise ValueError(\"Can not insert data into '%s'.\" % self.name)\n\n # Insert the data \n for detector, singleNeighborStarMap in neighborStarMap.items():\n self.db.insertData(self.getFilter(), singleNeighborStarMap)\n\n def generateBSC(self, localDb):\n \"\"\"\n \n Generate the bright star catalog.\n \n Arguments:\n localDb {[database]} -- Local database to put the bright star catalog.\n \n Raises:\n ValueError -- Not remote UW database.\n TypeError -- Not ComCam type camera.\n \"\"\"\n\n # Check the database is the UW database or not\n if (self.name != self.UWdb):\n raise ValueError(\"Can not generate BSC from '%s'.\" % self.name)\n\n # Check the camera is comcam or not\n if (not isinstance(self.camera, ComCam)):\n raise TypeError(\"Camera should be ComCam type.\")\n\n # Boresight (unit: degree)\n delta = 0.2\n RaArray = np.arange(0, 360, delta)\n DecArray = np.append(np.arange(-90, 90, delta), 90)\n\n # Set the rotation angle\n cameraRotation = 0.0\n\n # Set the filter in localDb to be the same as the remote UW database\n localDb.setFilter(self.getFilter())\n\n # Go through all (RA, Dec)\n for RA in RaArray:\n for Dec in DecArray:\n # Do the query\n neighborStarMap, starMap, wavefrontSensors = self.getTargetStar((RA, Dec), cameraRotation, \n orientation=\"center\", \n offset=self.maxDistance)\n\n # Write data into the local database\n localDb.insertToBSC(neighborStarMap)\n\n def searchRaDecl(self, ra, decl):\n \"\"\"\n \n Search the star id based on ra, decl.\n \n Arguments:\n ra {[float]} -- ra in degree (0 deg - 360 deg).\n decl {[float]} -- decl in degree (-90 deg - 90 deg).\n \n Returns:\n [int] -- Star ID in database. It is noted that the id will be \"simobjid\" if the database is \n the remote UW database.\n \"\"\"\n\n starID = []\n\n # Get the star id from the database\n if (self.name == self.UWdb):\n starID = self.db.searchRaDecl(self.tableName, ra, decl)\n\n # Change the data type from decimal to int to keep the same data type as local database\n # This might be removed when the local database switchs to mssql.\n starID.append((int(starID.pop()[0]),))\n\n elif (self.name == self.LocalDb):\n starID = self.db.searchRaDecl(self.filter.getFilter(), ra, decl)\n \n return starID\n\n def updateBSC(self, listID, listOfItemToChange, listOfNewValue):\n \"\"\"\n \n Update data based on the id.\n \n Arguments:\n listID {[int]} -- ID list to change.\n listOfItemToChange {[string]} -- Item list (simobjid, ra, decl, mag, bright_star) to change.\n listOfNewValue {[valueType]} -- New value list.\n \n Raises:\n ValueError -- Not local database.\n \"\"\"\n\n # Check the database is the local database or not\n if (self.name != self.LocalDb):\n raise ValueError(\"Can not update BSC in '%s'.\" % self.name)\n\n # Update the bright star catalog\n self.db.updateData(self.filter.getFilter(), listID, listOfItemToChange, listOfNewValue)\n\n def configNbrCriteria(self, starRadiusInPixel, spacingCoefficient, maxNeighboringStar=99):\n \"\"\"\n \n Set the neighboring star criteria to decide the scientific target.\n\n Arguments:\n starRadiusInPixel {[float]} -- Diameter of star. For the defocus = 1.5 mm, the star's radius \n is 63 pixel.\n spacingCoefficient {[float]} -- Maximum distance in units of radius one donut must be \n considered as a neighbor.\n \n Keyword Arguments:\n maxNeighboringStar {[int]} -- Maximum number of neighboring stars. (default: {99})\n \"\"\"\n\n self.maxDistance = starRadiusInPixel*spacingCoefficient\n self.maxNeighboringStar = int(maxNeighboringStar)\n\n def setFilter(self, atype):\n \"\"\"\n \n Set the active filter type.\n \n Arguments:\n atype {[string]} -- Filter type.\n \"\"\"\n\n self.filter.setFilter(atype)\n\n def getFilter(self):\n \"\"\"\n \n Get the active filter type.\n \n Returns:\n [string] -- Filter type.\n \"\"\"\n\n return self.filter.getFilter()\n\n def getStddevSplit(self):\n \"\"\"\n \n Get the standard deviation in database to decide the camera crosses RA=0 or not.\n \n Returns:\n [float] -- Standard deviation.\n \"\"\"\n\n return self.db.stddevSplit\n\n def trimMargin(self, neighborStarMap, trimMarginInPixel):\n \"\"\"\n \n Trim the candidate stars if they or related neighboring stars are outside of boundary. \n \n Arguments:\n neighborStarMap{[list]} -- Information of neighboring stars and candidate stars with \n the name of sensor as a list.\n trimMarginInPixel {[float]} -- Trimed boundary in pixel. if the ccd dimension is (d1, d2), only stars \n inside (trimMarginInPixel < x1 < d1-trimMarginInPixel) and \n (trimMarginInPixel < x2 < d2-trimMarginInPixel) will be left.\n \n Raises:\n ValueError -- trimMarginInPixel is less than 0.\n ValueError -- trimMarginInPixel is bigger than the half of CCD dimension.\n \"\"\"\n\n # Check the boundary of trimMarginInPixel\n if (trimMarginInPixel<0):\n raise ValueError(\"The trimmed boudary pixel < 0.\")\n\n # Trim the stars that are in the margin.\n for detector, neighborStar in neighborStarMap.items():\n\n trimmedCandidateStarNum = 0\n\n # Detector dimension\n dim1, dim2 = self.camera.getCcdDim(detector)\n\n # Check the boundary of trimMarginInPixel\n if (trimMarginInPixel > min(dim1, dim2)/2):\n raise ValueError(\"trimMarginInPixel ('%f') >= half of CCD's dimension.\" % trimMarginInPixel)\n\n # Copy a new dictionary to avoid the iteration error for changing size of iteration\n neighborStarSimobjID = neighborStar.SimobjID.copy()\n\n # Use the candidate star as the unit to check stars are inside the boundary or not\n for candidateStar, neighboringStars in neighborStarSimobjID.items():\n\n # Get all stars (candidateStar: string + neighboringStars: list) in this item\n # Use the List[:] to get the copy of list\n allStars = neighboringStars[:]\n allStars.append(candidateStar)\n\n needToTrim = False\n # Check the coordinate for each star\n for star in allStars:\n coord1, coord2 = neighborStar.RaDeclInPixel[star]\n\n # Check the star inside the boundary or not\n if (coord1 <= trimMarginInPixel or coord1 >= dim1-trimMarginInPixel or \n coord2 <= trimMarginInPixel or coord2 >= dim2-trimMarginInPixel):\n needToTrim = True\n break\n \n # The candidate/ neighboring stars are outside of tbe boundary\n if (needToTrim):\n trimmedCandidateStarNum += 1\n\n # Add \"None\" to avoid the raised error that there is the unfound key\n neighborStar.SimobjID.pop(candidateStar, None)\n\n if (trimmedCandidateStarNum != 0):\n print(\"Trimmed candidate stars on %s: %d.\" % (detector, trimmedCandidateStarNum))\n\ndef calcPixPos(fitsFilePath, raList, decList, extLayer=0):\n \"\"\"\n \n Calculate the pixel positions based on the FITS header data. The working formula\n is provided by John.\n \n Arguments:\n fitsFilePath {[str]} -- FITS file path.\n raList {[list]} -- List of RA in degree.\n decList {[list]} -- List of Dec in degree.\n \n Keyword Arguments:\n extLayer {int} -- Extension layer in degree. (default: {0})\n \n Returns:\n [list] -- List of x position in pixel.\n [list] -- List of y position in pixel.\n \"\"\"\n\n # Get the header data\n hdr = getheader(fitsFilePath, int(extLayer))\n\n # Get the needed parameters\n crval1 = hdr[\"CRVAL1\"]\n crval2 = hdr[\"CRVAL2\"]\n cd1_1 = hdr[\"CD1_1\"]\n cd1_2 = hdr[\"CD1_2\"]\n cd2_1 = hdr[\"CD2_1\"]\n cd2_2 = hdr[\"CD2_2\"]\n crpix1 = hdr[\"CRPIX1\"]\n crpix2 = hdr[\"CRPIX2\"]\n\n # Calculate the pixel position\n xPosList = []\n yPosList = []\n for ra, dec in zip(raList, decList):\n\n # Change the direction. RA is in (-180, 180).\n if (ra > 180):\n ra = ra - 360\n\n # Calculate the pixel position based on the formula provided by John\n xPos = crpix1 + ( (ra-crval1)*cd2_2 - (dec-crval2)*cd1_2 ) / (cd2_2*cd1_1 - cd1_2*cd2_1)\n yPos = crpix2 + ( (ra-crval1)*cd2_1 - (dec-crval2)*cd1_1 ) / (cd1_2*cd2_1 - cd2_2*cd1_1)\n\n xPosList.append(xPos)\n yPosList.append(yPos)\n\n return xPosList, yPosList\n\nclass SourceSelectorTest(unittest.TestCase):\n \"\"\"\n Test the source selector. \n \"\"\"\n\n def setUp(self):\n\n # Get the path of module\n self.modulePath = getModulePath()\n\n # Camera type: \"lsst\" or \"comcam\"\n cameraType = \"comcam\"\n\n # Active filter type\n aFilterType = \"r\"\n\n # Address of local database\n dbAdress = os.path.join(self.modulePath, \"test\", \"bsc.db3\")\n\n # Remote database setting\n databaseHost = \"gateway.astro.washington.edu:51433\"\n databaseUser = \"LSST-2\"\n databasePassword = \"L$$TUser\"\n databaseName = \"LSSTCATSIM\"\n\n\n # Set the database\n self.remoteDb = SourceSelector()\n self.localDb = SourceSelector()\n\n self.remoteDb.configSelector(cameraType=cameraType, dbType=\"UWdb\", aFilter=aFilterType)\n self.localDb.configSelector(cameraType=cameraType, dbType=\"LocalDb\", aFilter=aFilterType)\n\n # Remote database infomation\n remoteDbInfo = [databaseHost, databaseUser, databasePassword, databaseName]\n\n # Connect to database\n self.remoteDb.connect(*remoteDbInfo)\n self.localDb.connect(dbAdress)\n\n def tearDown(self):\n\n # Disconnect database\n self.remoteDb.disconnect()\n self.localDb.disconnect()\n\n def testFunctions(self):\n\n # Boresight (RA, Dec) (unit: degree) (0 <= RA <= 360, -90 <= Dec <= 90)\n pointing = (20.0, 30.0)\n\n # Camera rotation\n cameraRotation = 0.0\n\n # Camera orientation for ComCam (\"center\" or \"corner\" or \"all\")\n # Camera orientation for LSSTcam (\"corner\" or \"all\")\n orientation = \"center\"\n\n # Maximum distance in units of radius one donut must be considered as a neighbor.\n spacingCoefficient = 2.5\n\n # For the defocus = 1.5 mm, the star's radius is 63 pixel.\n starRadiusInPixel = 63\n\n # Set the configuration to select the scientific target\n self.remoteDb.configNbrCriteria(starRadiusInPixel, spacingCoefficient, maxNeighboringStar=99)\n self.localDb.configNbrCriteria(starRadiusInPixel, spacingCoefficient, maxNeighboringStar=99)\n\n # Set the active filter\n # self.remoteDb.setFilter(self.aFilterType)\n # self.localDb.setFilter(self.aFilterType)\n\n # Test to get the active filter\n self.assertEqual(self.localDb.getFilter(), \"r\")\n\n # Test to get the standard deviation \n self.assertEqual(self.localDb.getStddevSplit(), 20.0)\n\n # Get the scientific target by querying the remote database\n neighborStarMap, starMap, wavefrontSensors = self.remoteDb.getTargetStar(pointing, \n cameraRotation, orientation=orientation)\n\n # Test to get at least one star\n allStars = starMap[\"R:2,2 S:1,1\"]\n self.assertTrue(len(allStars.SimobjID)>=1)\n\n # Get the scientific target by querying the local database\n neighborStarMapLocal, starMapLocal, wavefrontSensorsLocal = self.localDb.getTargetStar(pointing, \n cameraRotation, orientation=orientation)\n\n # Test the get the empty star map\n allStarsLocal = starMapLocal[\"R:2,2 S:1,1\"]\n self.assertEqual(allStarsLocal.SimobjID, [])\n\n # Insert the neighboring star map into the database\n self.localDb.insertToBSC(neighborStarMap)\n\n # Query the local database again\n neighborStarMapLocal, starMapLocal, wavefrontSensorsLocal = self.localDb.getTargetStar(pointing, \n cameraRotation, orientation=orientation)\n\n # Test to get all neighboring stars\n allNeighborStarLocal = neighborStarMapLocal[\"R:2,2 S:1,1\"]\n allNeighborStar = neighborStarMap[\"R:2,2 S:1,1\"]\n self.assertEqual(len(allNeighborStarLocal.SimobjID), len(allNeighborStar.SimobjID))\n\n # Test to trim the margin\n self.remoteDb.trimMargin(neighborStarMap, 1000)\n\n # Test to search the id of star based on (ra, decl)\n searchStarId = self.localDb.searchRaDecl(20.088157, 29.983533)\n\n # Test to update the value\n self.localDb.updateBSC([searchStarId[0][0], searchStarId[0][0]], [\"ra\", \"decl\"], [200, 200])\n newSearchStarId = self.localDb.searchRaDecl(200, 200)\n self.assertEqual(searchStarId, newSearchStarId)\n\n # Delete all data in local database\n allStarList = np.arange(1,len(allNeighborStarLocal.RaDecl)+1)\n self.localDb.db.deleteData(self.localDb.getFilter(), allStarList.tolist())\n\n def testCoorFun(self):\n fitsFilePath = os.path.join(self.modulePath, \"test\", \"eimage\", \"v99999999-fr\", \"E000\", \"R22\", \n \"eimage_99999999_R22_S11_E000.fits.gz\")\n raList = [0]\n decList = [0]\n xPosList, yPosList = calcPixPos(fitsFilePath, raList, decList)\n self.assertEqual((xPosList[0], yPosList[0]), (2000, 2036))\n\nif __name__ == \"__main__\":\n\n # Do the unit test\n unittest.main()\n","sub_path":"python/lsst/ts/wep/SourceSelector.py","file_name":"SourceSelector.py","file_ext":"py","file_size_in_byte":23772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"622723626","text":"import argparse\nimport csv\nimport glob\nimport json\nimport os\nimport string\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport numpy as np\nimport spacy\nfrom scipy import stats\nfrom tqdm import tqdm\n\nfrom fast_abs_rl.preprocess import POS_TAGS\n\nspacy_tagger = spacy.load('en_core_web_sm', disable=['ner', 'parser'])\n\n\ndef json_load_file(**kwargs):\n return json.load(open(**kwargs))\n\n\ndef tokenize_data(d):\n return [[t for t in sent.split() if t not in string.punctuation] for sent in d['article']]\n\n\ndef get_data(data_dir):\n with ThreadPoolExecutor(max_workers=int((os.cpu_count() or 4) / 4)) as executor:\n futures = []\n for split in ('train', 'val', 'test'):\n split_dir = os.path.join(data_dir, split)\n if os.path.exists(split_dir):\n for file_path in glob.iglob(os.path.join(split_dir, '*.json')):\n futures.append(executor.submit(json_load_file, file=file_path, mode='r', encoding='utf8'))\n\n for i in tqdm(range(len(futures))):\n futures[i].result()\n\n return [f.result() for f in futures]\n\n\ndef get_sentence_count(data):\n return np.asarray([len(d['article']) for d in data])\n\n\ndef get_token_per_sentence_count(data):\n return np.asarray([len(t) for d in data for t in d['tokens']])\n\n\ndef get_token_per_article_count(data):\n return np.asarray([sum(len(t) for t in d['tokens']) for d in data])\n\n\ndef get_stats(counts):\n mode = stats.mode(counts)\n return dict(mean=np.mean(counts),\n median=np.median(counts),\n min=np.min(counts),\n max=np.max(counts),\n p1=np.percentile(counts, 1),\n p5=np.percentile(counts, 5),\n p10=np.percentile(counts, 10),\n p90=np.percentile(counts, 90),\n p95=np.percentile(counts, 95),\n p99=np.percentile(counts, 99),\n std=np.std(counts),\n mode_value=mode[0][0],\n mode_count=mode[1][0])\n\n\ndef tokenize(data):\n with ThreadPoolExecutor(max_workers=int((os.cpu_count() or 4) / 4)) as executor:\n futures = [executor.submit(tokenize_data, d) for d in data]\n\n for i in tqdm(range(len(futures))):\n data[i]['tokens'] = futures[i].result()\n\n\ndef get_pos_tags(data):\n counter = Counter()\n with tqdm(total=sum(len(d['article']) for d in data)) as pbar:\n for doc in spacy_tagger.pipe((sent for d in data for sent in d['article']),\n n_threads=os.cpu_count(),\n batch_size=1024):\n for token in doc:\n counter[token.pos_] += 1\n\n pbar.update(1)\n return counter\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Analyze data')\n parser.add_argument('-d', '--data-dir', required=True)\n parser.add_argument('-o', '--output-file', default='data_analysis.csv')\n args = parser.parse_args()\n\n print('Loading data...')\n data = get_data(args.data_dir)\n\n print('Tokenizing data...')\n tokenize(data)\n\n stats_mapping = [\n ('sentences', get_sentence_count),\n ('tokens_per_article', get_token_per_article_count),\n ('tokens_per_sentence', get_token_per_sentence_count),\n ]\n\n fieldnames = [\n 'name',\n 'mean',\n 'median',\n 'min',\n 'max',\n 'p1',\n 'p5',\n 'p10',\n 'p90',\n 'p95',\n 'p99',\n 'std',\n 'mode_value',\n 'mode_count',\n ]\n\n with open(args.output_file, 'w', encoding='utf8') as out:\n csv_writer = csv.DictWriter(out, fieldnames)\n csv_writer.writeheader()\n for name, func in stats_mapping:\n print('Computing stats for {}...'.format(name))\n csv_writer.writerow({'name': name, **get_stats(func(data))})\n\n with open(os.path.splitext(os.path.normpath(args.output_file))[0] + '-pos-tags.csv', 'w', encoding='utf8') as out:\n csv_writer = csv.DictWriter(out, POS_TAGS)\n csv_writer.writeheader()\n print('Computing stats for {}...'.format('POS tags'))\n csv_writer.writerow({**{t: 0 for t in POS_TAGS}, **get_pos_tags(data)})\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"analyze_data.py","file_name":"analyze_data.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"293286641","text":"# Copyright 2011 Isotoma Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport sys\nimport stat\nimport pwd\nimport grp\nimport difflib\nimport logging\nimport string\n\ntry:\n import magic\nexcept ImportError:\n magic = None\n\nfrom jinja2 import Environment\n\nfrom yaybu import resources\nfrom yaybu.core import provider\nfrom yaybu.core import change\nfrom yaybu.core import error\n\nfrom yay import String\n\n\ndef binary_buffers(*buffers):\n\n \"\"\" Check all of the passed buffers to see if any of them are binary. If\n any of them are binary this will return True. \"\"\"\n if not magic:\n check = lambda buff: len(buff) == sum(1 for c in buff if c in string.printable)\n else:\n ms = magic.open(magic.MAGIC_MIME)\n ms.load()\n check = lambda buff: ms.buffer(buff).startswith(\"text/\")\n\n for buff in buffers:\n if buff and not check(buff):\n return True\n return False\n\nclass AttributeChanger(change.Change):\n\n \"\"\" Make the changes required to a file's attributes \"\"\"\n\n def __init__(self, context, filename, user=None, group=None, mode=None):\n self.context = context\n self.filename = filename\n self.user = user\n self.group = group\n self.mode = mode\n self.changed = False\n\n def apply(self, renderer):\n \"\"\" Apply the changes \"\"\"\n exists = False\n uid = None\n gid = None\n mode = None\n\n if os.path.exists(self.filename):\n exists = True\n st = os.stat(self.filename)\n uid = st.st_uid\n gid = st.st_gid\n mode = stat.S_IMODE(st.st_mode)\n\n if self.user is not None:\n try:\n owner = pwd.getpwnam(self.user)\n except KeyError:\n if not self.context.simulate:\n raise error.InvalidUser(\"User '%s' not found\" % self.user)\n self.context.changelog.info(\"User '%s' not found; assuming this recipe will create it\" % self.user)\n owner = None\n\n if not owner or owner.pw_uid != uid:\n self.context.shell.execute([\"/bin/chown\", self.user, self.filename])\n self.changed = True\n\n if self.group is not None:\n try:\n group = grp.getgrnam(self.group)\n except KeyError:\n if not self.context.simulate:\n raise error.InvalidGroup(\"No such group '%s'\" % self.group)\n self.context.changelog.info(\"Group '%s' not found; assuming this recipe will create it\" % self.group) #FIXME\n group = None\n\n if not group or group.gr_gid != gid:\n self.context.shell.execute([\"/bin/chgrp\", self.group, self.filename])\n self.changed = True\n\n if self.mode is not None and mode is not None:\n if mode != self.mode:\n self.context.shell.execute([\"/bin/chmod\", \"%o\" % self.mode, self.filename])\n\n # Clear the user and group bits\n # We don't need to set them as chmod will *set* this bits with an octal\n # but won't clear them without a symbolic mode\n if mode & stat.S_ISGID and not self.mode & stat.S_ISGID:\n self.context.shell.execute([\"/bin/chmod\", \"g-s\", self.filename])\n if mode & stat.S_ISUID and not self.mode & stat.S_ISUID:\n self.context.shell.execute([\"/bin/chmod\", \"u-s\", self.filename])\n\n self.changed = True\n\n\nclass AttributeChangeRenderer(change.TextRenderer):\n renderer_for = AttributeChanger\n\n\nclass FileContentChanger(change.Change):\n\n \"\"\" Apply a content change to a file in a managed way. Simulation mode is\n catered for. Additionally the minimum changes required to the contents are\n applied, and logs of the changes made are recorded. \"\"\"\n\n def __init__(self, context, filename, contents, sensitive):\n self.context = context\n self.filename = filename\n self.current = \"\"\n self.contents = contents\n self.changed = False\n self.renderer = None\n self.sensitive = sensitive\n\n def empty_file(self):\n \"\"\" Write an empty file \"\"\"\n exists = os.path.exists(self.filename)\n if not exists:\n self.context.shell.execute([\"touch\", self.filename])\n self.changed = True\n else:\n st = os.stat(self.filename)\n if st.st_size != 0:\n self.renderer.empty_file(self.filename)\n if not self.context.simulate:\n open(self.filename, \"w\").close()\n self.changed = True\n\n def overwrite_existing_file(self):\n \"\"\" Change the content of an existing file \"\"\"\n self.current = open(self.filename).read()\n if self.current != self.contents:\n self.renderer.changed_file(self.filename, self.current, self.contents, self.sensitive)\n if not self.context.simulate:\n open(self.filename, \"w\").write(self.contents)\n self.changed = True\n\n def write_new_file(self):\n \"\"\" Write contents to a new file. \"\"\"\n self.renderer.new_file(self.filename, self.contents, self.sensitive)\n if not self.context.simulate:\n open(self.filename, \"w\").write(self.contents)\n self.changed = True\n\n def write_file(self):\n \"\"\" Write to either an existing or new file \"\"\"\n exists = os.path.exists(self.filename)\n if exists:\n self.overwrite_existing_file()\n else:\n self.write_new_file()\n\n def apply(self, renderer):\n \"\"\" Apply the changes necessary to the file contents. \"\"\"\n self.renderer = renderer\n if self.contents is None:\n self.empty_file()\n else:\n self.write_file()\n\n\nclass FileChangeTextRenderer(change.TextRenderer):\n renderer_for = FileContentChanger\n\n def empty_file(self, filename):\n self.logger.notice(\"Emptied file %s\", filename)\n\n def new_file(self, filename, contents, sensitive):\n self.logger.notice(\"Writting new file '%s'\" % filename)\n if not sensitive:\n self.diff(\"\", contents)\n\n def changed_file(self, filename, previous, replacement, sensitive):\n self.logger.notice(\"Changed file %s\", filename)\n if not sensitive:\n self.diff(previous, replacement)\n\n def diff(self, previous, replacement):\n if not binary_buffers(previous, replacement):\n diff = \"\".join(difflib.unified_diff(previous.splitlines(1), replacement.splitlines(1)))\n for l in diff.splitlines():\n self.logger.info(\" %s\", l)\n else:\n self.logger.notice(\"Binary contents; not showing delta\")\n\n\nclass File(provider.Provider):\n\n \"\"\" Provides file creation using templates or static files. \"\"\"\n\n policies = (resources.file.FileApplyPolicy,)\n\n @classmethod\n def isvalid(self, *args, **kwargs):\n return super(File, self).isvalid(*args, **kwargs)\n\n def check_path(self, directory, simulate):\n frags = directory.split(\"/\")\n path = \"/\"\n for i in frags:\n path = os.path.join(path, i)\n if not os.path.exists(path): #FIXME\n if not simulate:\n raise error.PathComponentMissing(path)\n elif not os.path.isdir(path):\n raise error.PathComponentNotDirectory(path)\n\n def has_protected_strings(self):\n def iter(val):\n if isinstance(val, dict):\n for v in val.values():\n if iter(v):\n return True\n return False\n\n elif isinstance(val, list):\n for v in val:\n if iter(v):\n return True\n return False\n\n else:\n return isinstance(val, String)\n\n return iter(self.resource.template_args)\n\n def get_template_args(self):\n \"\"\" I return a copy of the template_args that contains only basic types (i.e. no protected strings) \"\"\"\n def _(val):\n if isinstance(val, dict):\n return dict((k,_(v)) for (k,v) in val.items())\n elif isinstance(val, list):\n return list(_(v) for v in val)\n elif isinstance(val, String):\n return val.unprotected\n else:\n return val\n return _(self.resource.template_args)\n\n def apply(self, context):\n name = self.resource.name\n\n self.check_path(os.path.dirname(name), context.simulate)\n\n if self.resource.template:\n # set a special line ending\n # this strips the \\n from the template line meaning no blank line,\n # if a template variable is undefined. See ./yaybu/recipe/interfaces.j2 for an example\n env = Environment(line_statement_prefix='%')\n template = env.from_string(context.get_file(self.resource.template).read())\n contents = template.render(self.get_template_args()) + \"\\n\" # yuk\n sensitive = self.has_protected_strings()\n elif self.resource.static:\n contents = context.get_file(self.resource.static).read()\n sensitive = False\n elif self.resource.encrypted:\n contents = context.get_decrypted_file(self.resource.encrypted).read()\n sensitive = True\n else:\n contents = None\n sensitive = False\n\n fc = FileContentChanger(context, self.resource.name, contents, sensitive)\n context.changelog.apply(fc)\n\n ac = AttributeChanger(context,\n self.resource.name,\n self.resource.owner,\n self.resource.group,\n self.resource.mode)\n context.changelog.apply(ac)\n\n if fc.changed or ac.changed:\n return True\n\nclass RemoveFile(provider.Provider):\n policies = (resources.file.FileRemovePolicy,)\n\n @classmethod\n def isvalid(self, *args, **kwargs):\n return super(RemoveFile, self).isvalid(*args, **kwargs)\n\n def apply(self, context):\n if os.path.exists(self.resource.name):\n if not os.path.isfile(self.resource.name):\n raise error.InvalidProvider(\"%r: %s exists and is not a file\" % (self, self.resource.name))\n context.shell.execute([\"/bin/rm\", self.resource.name])\n changed = True\n else:\n context.changelog.debug(\"File %s missing already so not removed\" % self.resource.name)\n changed = False\n return changed\n\n\nclass WatchFile(provider.Provider):\n policies = (resources.file.FileWatchedPolicy, )\n\n @classmethod\n def isvalid(self, *args, **kwargs):\n return super(WatchFile, self).isvalid(*args, **kwargs)\n\n def apply(self, context):\n \"\"\" Watched files don't have any policy applied to them \"\"\"\n return self.resource.hash() != self.resource._original_hash\n\n","sub_path":"yaybu/providers/filesystem/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":11554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494301466","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n\nScript to convert .mm files into 3 files for my solver\n\"\"\"\n\nclass File_converter:\n def __init__(self,filename,filetype):\n #filename = \"c154_3\"\n # Start by opening the file\n with open(\"data/\" + filename + \".\"+filetype,\"r\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n \n reading_precedence = False\n reading_durations = False\n reading_resources = False\n \n horizon = 0\n \n # Go through the file to find relevant information\n for line in content:\n # Find number of jobs\n if(\"jobs (incl.\" in line or \"jobs (incl.\" in line):\n startPos = line.index(\":\")\n n_jobs = eval(line[startPos + 1:])\n # Find horizon value\n if(\"horizon \" in line):\n startPos = line.index(\":\")\n horizon = eval(line[startPos + 1:])\n # Find the number of renewable resources\n if(\"- renewable\" in line):\n startPos = line.index(\":\")\n endPos = line[startPos:].index(\"R\")\n n_renewable = eval(line[startPos + 1:startPos + endPos])\n # Find the number of non-renewable resources\n if(\"- nonrenewable\" in line):\n startPos = line.index(\":\")\n endPos = line[startPos:].index(\"N\")\n n_nonrenewable = eval(line[startPos + 1:startPos + endPos])\n # Find start of the precedence table\n if(\"PRECEDENCE RELATIONS:\" in line):\n reading_precedence = True\n precedence_table = []\n continue\n # **** indicates the end of table\n if(\"****\" in line):\n reading_precedence = False\n reading_durations = False\n reading_resources = False\n # Append all of the lines into one list\n if(reading_precedence):\n precedence_table.append(line)\n # Find start of the duratios table\n if(\"REQUESTS/DURATIONS\" in line):\n reading_durations = True\n durations_table = []\n continue\n # Append al of the lines into the list\n if(reading_durations):\n durations_table.append(line)\n # If the start of Resources table\n if(\"RESOURCEAVAILABILITIES\" in line or \"RESOURCE AVAILABILITIES\" in line):\n reading_resources = True\n resources_table = []\n continue\n # Append al of the lines into the list\n if(reading_resources):\n resources_table.append(line)\n \n # Now I should have all of the tables in lists\n # Have to clean them up a bit to export as .csv files\n \n # Start with the precedence table\n export_precedence = []\n for row in precedence_table:\n export_precedence.append(\",\".join(row.split())+\"\\n\")\n \n \n # Now do durations\n export_durations = []\n # Need to add value in the first column \n durations_table2 = durations_table\n norm_len = len(durations_table[3])\n num = 1\n max_len = list(map(int, durations_table[2].split()))\n for i in range(0,len(durations_table2)):\n if(i > 2):\n x = list(map(int, durations_table[i].split()))\n #if(filename == \"J5036_5\"): \n # print(len(x),len(max_len),durations_table[i])\n #print(durations_table2[i],len(durations_table[i]),norm_len)\n if(len(x) < len(max_len)):\n durations_table2[i] = str(num) + \" \" + durations_table2[i]\n else:\n num = num + 1\n for row in durations_table2:\n export_durations.append(\",\".join(row.split())+\"\\n\")\n # Remove the 2nd line\n export_durations.pop(1)\n \n \n # Finally with Resources\n export_resources = []\n for row in resources_table:\n export_resources.append(\",\".join(row.split())+\"\\n\")\n \n # And in conclusion, write these tables to files\n with open(\"data/converted/\"+ filename + \"_precedence.csv\",\"w\") as f:\n for item in export_precedence:\n f.write(item)\n with open(\"data/converted/\"+ filename + \"_durations.csv\",\"w\") as f:\n for item in export_durations:\n f.write(item)\n with open(\"data/converted/\"+ filename + \"_resources.csv\",\"w\") as f:\n for item in export_resources:\n f.write(item)\n with(open(\"data/converted/\" + filename + \"_info.csv\",\"w\")) as f:\n f.write(str(n_jobs) + \",\" + str(horizon) + \",\" + str(n_renewable) + \",\"\n + str(n_nonrenewable) + \"\\n\")","sub_path":"code/problem_converter.py","file_name":"problem_converter.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"622412890","text":"import json\nfrom threading import Thread\nfrom .consumers import sendTLM\nimport time\nfrom raspberryPI3.RBPI3 import RBPI3\n\nUPDATE_INTERVAL = 5\n\nrbpi3 = RBPI3()\n\nclass workerTLM (Thread):\n # thread para inicilizacao do subscribe e publish da tlm envio periodico dos dados de telemetria da RaspBerry\"\"\"\n\n def __init__(self):\n Thread.__init__(self)\n self.tlm = TLMConsumer()\n\n def run(self):\n\n self.count = 1\n self.rbpi3.init()\n self.rbpi3.loop_start()\n \n while True:\n print(\"Get TLM\")\n self.rbpi3.readValues()\n sendTLM(rbpi3)\n self.count += 1\n time.sleep(UPDATE_INTERVAL)\n\n def start(self):\n Thread.start(self)","sub_path":"web/core/devices/workerRB3.py","file_name":"workerRB3.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"98040657","text":"import shelve\n\nfrom os import listdir\nfrom os.path import isfile, join\n\ninstances = {}\n\ndef get_instance(aClass, *args): \n\tif aClass not in instances: \n\t\tinstances[aClass] = aClass(*args)\n\treturn instances[aClass]\n\n\ndef singleton(aClass): \n\tdef on_call(*args):\n\t\treturn get_instance(aClass, *args) \n\treturn on_call\n\n\ndef get_file_types():\n\treturn ('py', 'txt')\n\n@singleton \nclass FileManager:\n\tdef __init__(self):\n\t\tself.shows = {}\n\n\t\tif isfile('serial.db'):\n\t\t\tserialdb = shelve.open('serial')\n\n\t\t\tfor key in sorted(serialdb):\n\t\t\t\tself.shows[key] = serialdb[key]\n\n\tdef add_show(self, file_path):\n\t\tpath_elements = file_path.split('/')\n\t\tdir_path = file_path.replace(path_elements[-1], '')\n\n\t\tserialdb = shelve.open('serial')\n\n\t\tnew_show = {}\n\t\tif not (dir_path in serialdb):\n\t\t\tonly_files = [ f for f in listdir(dir_path) \n\t\t\t\t\t\t\t if (isfile(join(dir_path, f)) and self.check_for_file_extension(f))]\n\n\t\t\tnew_show = {'current_episode' : path_elements[-1],\n\t\t\t\t\t\t\t 'path' : dir_path,\n\t\t\t\t\t\t\t 'name' : path_elements[-2],\n\t\t\t\t\t\t\t 'total_episodes' : len(only_files)}\n\t\t\tself.shows[dir_path] = new_show\n\t\t\tserialdb[dir_path] = new_show\n\n\t\tserialdb.close()\n\n\t\treturn new_show\n\n\tdef change_episode(self, file_path):\n\t\tpath_elements = file_path.split('/')\n\t\tdir_path = file_path.replace(path_elements[-1], '')\n\t\tself.shows[dir_path]['current_episode'] = path_elements[-1]\n\n\t\tserialdb = shelve.open('serial')\n\t\tserialdb[dir_path] = self.shows[dir_path]\n\t\tserialdb.close()\n\n\t\treturn path_elements[-1]\n\n\tdef remove_show(self, index):\n\t\tkey = self.get_shows()[index]['path']\n\n\t\tserialdb = shelve.open('serial')\n\t\tdel serialdb[key]\n\t\tserialdb.close()\n\n\tdef check_for_file_extension(self, file):\n\t\tfor extension in get_file_types():\n\t\t\tif file.split('.')[-1] == extension:\n\t\t\t\treturn True\n\n\t\treturn False\n\n\tdef get_shows(self):\n\t\treturn [self.shows[key] for key in sorted(self.shows)]\n\n\tdef check_next_episode(self, path):\n\t\tcurrent_show = self.shows[path]\n\t\tonly_files = [ f for f in listdir(current_show['path']) \n\t\t\t\t\t\t\t if (isfile(join(current_show['path'], f)) and self.check_for_file_extension(f))]\n\n\t\tif not (current_show['current_episode'] in only_files):\n\t\t\tonly_files.append(current_show['current_episode'])\n\n\t\tonly_files.sort(key=str.lower)\n\t\tcurrent_show['current_episode'] = only_files[only_files.index(current_show['current_episode']) + 1]\n\n\t\tserialdb = shelve.open('serial')\n\t\tserialdb[path] = current_show\n\t\tserialdb.close()","sub_path":"filemanager.py","file_name":"filemanager.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"257084810","text":"import datetime\ndef header():\n print(\"___________________________\")\n print(\" BIRTHDAY APP\")\n print(\"___________________________\")\n\ndef enter_birthday():\n global Today\n Today= datetime.date.today()\n\n year=int(input(\"what year were you born [YYYY]?\"))\n month=int(input(\"What month were you born[MM]?\"))\n day=int(input(\"What day you were born[DD]?\"))\n\n global birthday\n birthday=datetime.date(year,month,day)\n print(\"It looks like you were born on {0}\".format(birthday))\n\n\n\ndef my_calculator():\n date=datetime.date(Today.year,birthday.month,birthday.day)\n days_left=date-Today\n return days_left.days\n\ndef birthday_info():\n days_left=my_calculator()\n if(days_left<0):\n print(\"You have your birthday {0} days ago this year\".format(-days_left))\n elif(days_left>0):\n print(\"Your bithday is in {0} days \".format(days_left))\n else:\n print(\"Happy Birthday!!\")\n\n\n\ndef main():\n header()\n enter_birthday()\n birthday_info()\n\n\nmain()\n\n","sub_path":"birthday App/Birthday_app.py","file_name":"Birthday_app.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217904394","text":"import jsl\nfrom . import jslcrud\nfrom .jslcrud.storage.sqlstorage import Base\nimport sqlalchemy as sa\nimport sqlalchemy_jsonfield as sajson\nfrom .app import BaseApp\nfrom .jslcrud.storage.memorystorage import MemoryStorage\nfrom .jslcrud.storage.sqlstorage import SQLStorage\nimport json\nfrom celery.result import AsyncResult\nimport transaction\nimport time\nimport rulez\n\n\nclass CeleryTaskSchema(jsl.Document):\n task = jsl.StringField()\n task_id = jsl.StringField()\n created_ts = jsl.IntField()\n status = jsl.StringField()\n input = jsl.DictField()\n result = jsl.DictField()\n traceback = jsl.StringField()\n\n\n@BaseApp.jslcrud_identifierfields(schema=CeleryTaskSchema)\ndef task_identifierfields(schema):\n return ['task_id']\n\n\nclass CeleryTask(Base):\n __tablename__ = 'celery_tasks'\n task = sa.Column(sa.String(length=1024))\n task_id = sa.Column(sa.String(length=1024))\n created_ts = sa.Column(sa.BigInteger)\n status = sa.Column(sa.String(length=256))\n input = sa.Column(sajson.JSONField())\n result = sa.Column(sajson.JSONField())\n traceback = sa.Column(sa.Text)\n\n\nclass CeleryTaskModel(jslcrud.Model):\n schema = CeleryTaskSchema\n\n\nclass CeleryTaskCollection(jslcrud.Collection):\n schema = CeleryTaskSchema\n\n def search(self, *args, **kwargs):\n objs = super(CeleryTaskCollection, self).search(*args, **kwargs)\n if self.request.GET.get('refresh', '').lower() == 'true':\n for o in objs:\n meta = AsyncResult(o.data['task_id'])._get_task_meta()\n if meta['status'] == 'SUCCESS':\n o.data['status'] = 'SUCCESS'\n o.data['traceback'] = None\n o.data['result'] = meta['result']\n elif meta['status'] == 'FAILURE':\n o.data['status'] = 'FAILURE'\n o.data['traceback'] = meta['traceback']\n o.data['result'] = None\n return objs\n\n\nclass CeleryTaskMemoryStorage(MemoryStorage):\n model = CeleryTaskModel\n\n\nclass CeleryTaskSQLStorage(SQLStorage):\n model = CeleryTaskModel\n orm_model = CeleryTask\n\n\n@BaseApp.celery_metastore(metastore='memorystorage', schema=CeleryTaskSchema)\ndef memory_metastore(metastore, schema):\n return CeleryTaskMemoryStorage\n\n\n@BaseApp.celery_metastore(metastore='sqlstorage', schema=CeleryTaskSchema)\ndef sql_metastore(metastore, schema):\n return CeleryTaskSQLStorage\n\n\n@BaseApp.path(model=CeleryTaskCollection, path='api/v1/task')\ndef get_task_collection(app, request):\n storage = app.get_celery_metastore(request)\n return CeleryTaskCollection(request, storage)\n\n\n@BaseApp.json(model=CeleryTaskCollection, name='search')\ndef search_task(context, request):\n query = json.loads(request.GET.get('q', '{}'))\n if not query:\n query = None\n limit = int(request.GET.get('limit', 20))\n if limit > 100:\n limit = 100\n objs = context.search(query, limit=limit)\n return {'results': [obj.json() for obj in objs],\n 'total': len(objs),\n 'q': query}\n\n\n@BaseApp.path(model=CeleryTaskModel, path='api/v1/task/{identifier}')\ndef get_task(app, request, identifier):\n storage = app.get_celery_metastore(request)\n return storage.get(identifier)\n\n\ndef cleanup(appClass, age_minutes=60):\n app = appClass()\n request = app.request_class(app=app, environ={'PATH_INFO': '/'})\n transaction.begin()\n now = int(time.time() * 1000)\n try:\n collection = get_task_collection(app, request)\n oldtasks = collection.search(\n query=rulez.field['created_ts'] < (\n now - (age_minutes * 60 * 1000))\n )\n for t in oldtasks:\n t.delete()\n transaction.commit()\n except:\n transaction.abort()\n raise\n\n\ndef refresh(appClass):\n app = appClass()\n request = app.request_class(app=app, environ={'PATH_INFO': '/'})\n transaction.begin()\n now = int(time.time() * 1000)\n try:\n collection = get_task_collection(app, request)\n objs = collection.search(\n query=rulez.and_(\n rulez.field['created_ts'] > (now - (60 * 60 * 1000)),\n rulez.field['status'] == 'SUBMITTED')\n )\n for o in objs:\n meta = AsyncResult(o.data['task_id'])._get_task_meta()\n if meta['status'] == 'SUCCESS':\n o.data['status'] = 'SUCCESS'\n o.data['traceback'] = None\n o.data['result'] = meta['result']\n meta.forget()\n elif meta['status'] == 'FAILURE':\n o.data['status'] = 'FAILURE'\n o.data['traceback'] = meta['traceback']\n o.data['result'] = None\n meta.forget()\n transaction.commit()\n except:\n transaction.abort()\n raise\n","sub_path":"morpfw/tasktracker.py","file_name":"tasktracker.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"601237611","text":"import logging\nimport _thread\nimport threading\nfrom db.database import MacVod\nimport time\nimport sys\n\n\nclass MovieTracker:\n\n def __init__(self, config, threads, task_queue):\n self.__config = config\n self.__task_queue = task_queue\n self.__stop = threading.Event()\n self.__threads = threads\n self.__log_config = config['log']\n self.__mac_vod_db = MacVod(config['log'], config['dbzyzmactype'], config['database'])\n self.__movie_id_set = self.__all_movie_ids()\n self.__tv_stats=self.__all_tv_id_stat()\n self.__logger = logging.getLogger(__name__)\n self.__logger.setLevel(logging.INFO)\n fhandler = logging.FileHandler(self.__log_config['file'])\n fhandler.setLevel(logging.INFO)\n formatter = logging.Formatter(self.__log_config['pattern'])\n fhandler.setFormatter(formatter)\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n self.__logger.addHandler(console)\n self.__logger.addHandler(fhandler)\n\n def start(self):\n self.__logger.info('started')\n for tid in range(self.__threads):\n self.__logger.info('starting tacker {}!'.format(tid))\n _thread.start_new_thread(self.run, (tid,))\n\n def run(self, tid):\n while not self.__stop.is_set():\n vod_event = self.__task_queue.get()\n self.__process(tid, vod_event)\n self.__logger.info(\"movie tracker {} stopped !\".format(tid))\n\n def __process(self, tid, vod_event):\n self.__logger.info('{} process {}'.format(tid, vod_event))\n vod_id = int(vod_event.id())\n if vod_id in self.__movie_id_set:\n # update\n note = str(vod_event.note())\n stat = int(vod_event.state())\n # feedback result stat not sync with note\n if stat == 0 and note.isdigit() and int(note) > 0:\n stat = int(note)\n vod_event.vod()['state'] = vod_event.note()\n old_stat = int(self.__tv_stats.get(vod_id, sys.maxsize))\n if stat > 0 and old_stat < stat:\n self.__logger.info('update tv id {},name {}'.format(vod_id,vod_event.name()))\n self.__mac_vod_db.update_mac_vod(vod_event)\n else:\n self.__logger.info('ignore update {} {}'.format(vod_id, vod_event.name()))\n\n else:\n self.__mac_vod_db.insert_mac_vod(vod_event)\n self.__logger.info('new vod id:{},name:{}'.format(vod_id, vod_event.name()))\n self.__movie_id_set.add(int(vod_id))\n\n def __type_filter(self, vod_event):\n print('type filter')\n\n def stop(self):\n # wait vod event consume finish\n while len(self.__queue) > 0:\n time.sleep(5)\n self.__stop.set()\n self.__logger.info('event queue is empty')\n self.__mac_vod_db.close()\n\n def __all_movie_ids(self):\n columns = 'vod_id'\n id_tuples = self.__mac_vod_db.select('mac_vod', None, columns)\n id_set = set()\n for id_t in id_tuples:\n id_set.add(id_t[0])\n return id_set\n\n def __all_tv_id_stat(self):\n columns = 'vod_id,vod_state'\n condition = 'type_id_1 in(2,3,4)'\n vod_stat = self.__mac_vod_db.select('mac_vod', condition, columns)\n stat_map = {}\n for stat in vod_stat:\n stat_map[stat[0]] = stat[1]\n return stat_map\n\n\n\n\n\n\n","sub_path":"collect/parser/dbzyz/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"619376639","text":"# This file is part country_zip module for Tryton. The COPYRIGHT file at the\n# top level of this repository contains the full copyright notices and license\n# terms.\nfrom trytond.model import ModelSQL, fields\nfrom trytond.model import ValueMixin\nfrom trytond.pool import PoolMeta\nfrom trytond.modules.party.configuration import _ConfigurationValue\n\n__all__ = ['Configuration', 'ConfigurationCountry']\n\ndefault_country = fields.Many2One('country.country', 'Default Country')\n\n\nclass Configuration:\n __metaclass__ = PoolMeta\n __name__ = 'party.configuration'\n default_country = fields.MultiValue(default_country)\n\n\nclass ConfigurationCountry(_ConfigurationValue, ModelSQL, ValueMixin):\n 'Party Configuration Country'\n __name__ = 'party.configuration.default_country'\n default_country = default_country\n _configuration_value_field = 'default_country'","sub_path":"training/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76228807","text":"x , y = 3, 4\r\nprint(y)\r\n\r\n\r\nc = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}\r\n\r\n\r\n\r\ntmp = list()\r\nfor k, v in c.items() :\r\n tmp.append( (v, k) )\r\n print(tmp)\r\n\r\ndays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')\r\nprint(days[2])\r\n","sub_path":"2. Second Course Data Structure/6 week tuples/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"421406749","text":"import unittest\n\nfrom flask_monitoringdashboard.test.utils import (\n set_test_environment,\n clear_db,\n add_fake_data,\n get_test_app,\n login,\n NAME,\n test_admin_secure,\n test_get_ok,\n test_get_redirect,\n)\n\n\nclass TestSetup(unittest.TestCase):\n def setUp(self):\n set_test_environment()\n clear_db()\n add_fake_data()\n self.app = get_test_app()\n\n def test_index(self):\n \"\"\"\n Just retrieve the content and check if nothing breaks\n \"\"\"\n test_get_redirect(self, '')\n\n def test_static(self):\n \"\"\"\n Just retrieve the content and check if nothing breaks\n \"\"\"\n test_get_ok(self, 'static/css/custom.css')\n\n def test_configuration(self):\n \"\"\"\n Just retrieve the content and check if nothing breaks\n \"\"\"\n test_admin_secure(self, 'configuration')\n\n def test_rules(self):\n \"\"\"\n Just retrieve the content and check if nothing breaks\n \"\"\"\n test_admin_secure(self, 'rules')\n\n def test_monitor_rule(self):\n \"\"\"\n Test whether it is possible to monitor a rule\n \"\"\"\n data = {'name': NAME, 'value': 0}\n with self.app.test_client() as c:\n login(c)\n self.assertEqual(200, c.post('dashboard/api/set_rule', data=data).status_code)\n","sub_path":"flask_monitoringdashboard/test/views/test_setup.py","file_name":"test_setup.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"495314679","text":"from os import system as run_cmd\n\n\ndef aoc12():\n\n run_cmd(\"cls\")\n print(\"Advent of Code 2017 - Jim de Vries\")\n print(\"Day 1, Challenge 2\", \"\\n\")\n\n captcha = input(\"The captcha: \").strip()\n\n clist = list(captcha)\n cl = len(clist)\n hl = round(cl/2)\n matches = []\n index = 0\n\n for i in clist:\n if index < hl:\n ni = index + hl\n else:\n ni = index - hl\n if clist[ni] == i:\n matches.append(int(i))\n index += 1\n\n print(\"The result: \" + str(sum(matches)))\n","sub_path":"challenges/aoc12.py","file_name":"aoc12.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"245221475","text":"'''\nCreated on Mar 13, 2012\n\n@author: dreambit\n'''\nfrom abc import abstractmethod, ABCMeta\nimport time\nfrom random import random\nclass Random:\n '''\n This is an abstract class for other classes to generate random numbers\n '''\n __metaclass__ = ABCMeta\n @abstractmethod\n def random(self, count=None):\n '''\n This is an abstract method that should be overridden by the child class, which returns\n a random number generated by any law\n '''\n pass\n \n @staticmethod\n def getInitValue():\n t = time.time()\n return t - int(t)\n \nclass NaimanRandom(Random):\n def __init__(self, initValue=None):\n self.initValue = Random.getInitValue() if initValue is None else initValue \n \n def _rand_(self):\n self.initValue = round(self.initValue, 8)\n self.initValue **= 2\n self.initValue *= 100\n self.initValue -= int(self.initValue)\n while self.initValue < 0.001:\n self.initValue *= 10\n return round(self.initValue, 8)\n \n def random(self, count=None):\n if count is None:\n return self._rand_()\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(self._rand_())\n return randomList\n \n \nclass MultiplicationRandom(Random):\n def __init__(self, initValue=None):\n self.initValue = Random.getInitValue() if initValue is None else initValue\n \n \n def _rand_(self):\n last = self.initValue\n t = 5\n k = 8 * t - 3\n self.initValue = (k * last) - (int(k * last))\n while self.initValue < 0.001:\n self.initValue *= 10\n return round(self.initValue, 8)\n \n \n def random(self, count=None):\n if count is None:\n return self._rand_()\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(self._rand_())\n return randomList\n \n\nclass CreationRandom(Random):\n def __init__(self, initValue=None):\n self.initValue = Random.getInitValue() if initValue is None else initValue\n self.x1 = Random.getInitValue()\n \n def _rand_(self):\n x2 = round(self.initValue * self.x1, 8)\n while x2 < 0.001:\n x2 *= 10\n self.x1 = self.initValue\n self.initValue = float('0.' + str(x2)[2:10])\n while self.initValue < 0.01:\n self.initValue *= 10\n self.initValue = round(self.initValue, 8)\n return self.initValue\n \n \n def random(self, count=None):\n if count is None:\n return self._rand_()\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(self._rand_())\n return randomList\n \n \n\nclass DeductionRandom(Random):\n def __init__(self, initValue=None):\n self.a0 = 3141592\n self.d = 8\n self.q = 10 ** self.d\n self.pList = [3, 11, 13, 19, 21, 27, 29, 37, 53, 59, 61, 67, 69, 77, 83, 91]\n \n def _rand_(self, t):\n p = self.pList[6]\n k = 200 * t + p\n a1 = k * self.a0 % self.q\n self.a0 = a1\n return round(float('0.' + str(a1)), 8)\n \n def random(self, t=None, count=None):\n t = 0 if t is None else t \n if count is None:\n return self._rand_(t)\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(self._rand_(t))\n return randomList\n \n\n\nclass LemerRandom(Random):\n def __init__(self, initValue=None):\n self.a = 69069\n self.c = 5\n self.initValue = Random.getInitValue()\n \n def _rand_(self, t):\n self.initValue = (self.a * self.initValue + self.c) % 1\n return round(self.initValue, 8)\n \n def random(self, t=None, count=None):\n t = 0 if t is None else t \n if count is None:\n return self._rand_(t)\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(self._rand_(t))\n return randomList\n \n \nclass DefaultRandom(Random): \n def random(self, count=None): \n if count is None:\n return round(random(), 8)\n else:\n randomList = []\n for i in xrange(0, count):\n randomList.append(round(random(), 8))\n return randomList","sub_path":"Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"230113668","text":"import json\nfrom collections.abc import Container\nfrom enum import Enum\nfrom typing import Optional, Union\n\nfrom aiohttp import web\nfrom aiohttp_security import SessionIdentityPolicy\nfrom cryptography.fernet import Fernet, InvalidToken\nfrom pydantic import Json, ValidationError, parse_obj_as\n\nfrom .types import IdentityDict, Schema, UserDetails\n\n\nclass Permissions(str, Enum):\n view = \"admin.view\"\n edit = \"admin.edit\"\n add = \"admin.add\"\n delete = \"admin.delete\"\n\n\ndef has_permission(p: Union[str, Enum], permissions: Container[str]) -> bool:\n # TODO(PY311): StrEnum\n *parts, ptype = p.split(\".\") # type: ignore[union-attr]\n\n for i in range(1, len(parts)+1):\n perm = \".\".join((*parts[:i], ptype))\n if perm in permissions:\n return True\n\n wildcard = \".\".join((*parts[:i], \"*\"))\n if wildcard in permissions:\n return True\n return False\n\n\nclass TokenIdentityPolicy(SessionIdentityPolicy): # type: ignore[misc,no-any-unimported]\n def __init__(self, fernet: Fernet, schema: Schema):\n super().__init__()\n self._fernet = fernet\n config = schema[\"security\"]\n self._identity_callback = config.get(\"identity_callback\")\n self._max_age = config.get(\"max_age\")\n\n async def identify(self, request: web.Request) -> Optional[str]:\n \"\"\"Return the identity of an authorised user.\"\"\"\n # Validate JS token\n hdr = request.headers.get(\"Authorization\")\n try:\n identity_data = parse_obj_as(Json[IdentityDict], hdr)\n except ValidationError:\n return None\n\n auth = identity_data[\"auth\"].encode(\"utf-8\")\n try:\n token_identity = self._fernet.decrypt(auth, ttl=self._max_age).decode(\"utf-8\")\n except InvalidToken:\n return None\n\n # Validate cookie token\n cookie_identity = await super().identify(request)\n\n # Both identites must match.\n return token_identity if token_identity == cookie_identity else None\n\n async def remember(self, request: web.Request, response: web.Response,\n identity: str, **kwargs: object) -> None:\n \"\"\"Send auth tokens to client for authentication.\"\"\"\n # For proper security we send a token for JS to store and an HTTP only cookie:\n # https://www.redotheweb.com/2015/11/09/api-security.html\n # Send token that will be saved in local storage by the JS client.\n response.headers[\"X-Token\"] = json.dumps(await self.user_identity_dict(request, identity))\n # Send httponly cookie, which will be invisible to JS.\n await super().remember(request, response, identity, **kwargs)\n\n async def forget(self, request: web.Request, response: web.Response) -> None:\n \"\"\"Delete session cookie (JS client should choose to delete its token).\"\"\"\n await super().forget(request, response)\n\n async def user_identity_dict(self, request: web.Request, identity: str) -> IdentityDict:\n \"\"\"Create the identity information sent back to the admin client.\n\n The 'auth' key will be used for the server authentication, everything else is\n just information that the client can use. For example, 'permissions' will be\n returned by the react-admin's getPermissions() and some values like\n 'fullName' or 'avatar' will be automatically used:\n https://marmelab.com/react-admin/AuthProviderWriting.html#getidentity\n\n All details (except auth) can be specified using the identity callback.\n \"\"\"\n if self._identity_callback is None:\n user_details: UserDetails = {}\n else:\n user_details = await self._identity_callback(request, identity)\n if \"auth\" in user_details:\n raise ValueError(\"Callback should not return a dict with 'auth' key.\")\n\n auth = self._fernet.encrypt(identity.encode(\"utf-8\")).decode(\"utf-8\")\n identity_dict: IdentityDict = {\"auth\": auth, \"fullName\": \"Admin user\", \"permissions\": {}}\n # https://github.com/python/mypy/issues/6462\n identity_dict.update(user_details) # type: ignore[typeddict-item]\n # Convert to mapping so JS can test for permissions easier (JS has no set type).\n identity_dict[\"permissions\"] = dict.fromkeys(identity_dict[\"permissions\"])\n return identity_dict\n","sub_path":"aiohttp_admin/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":4355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"244161138","text":"import subprocess\nimport argparse\n\nresultList = list()\ntally = 0\nnumfiles = 1275\n\nparser = argparse.ArgumentParser(description='''Checks links for link''')\nparser.add_argument('searchterm', metavar='F', nargs=1,\n help='term to search for')\nparser.add_argument('-s', '--silent', action='store_true', help='suppress status reports')\nargs = parser.parse_args()\n\nsearchWord = args.searchterm[0]\nsilent = args.silent\n\nfor i in range(numfiles):\n filename = \"results/text/result\" + str(i) + \".html\"\n command = \"grep -li \" + searchWord + \" \" + filename\n result = subprocess.run(command, capture_output=True, text=True, errors='ignore')\n\n if(len(result.stdout)) > 0:\n resultList.append(filename)\n if(i%100 == 0):\n print(\"Searching - found in \" + str(len(resultList)) + \" pages.\", flush=True) \n\nif (len(resultList) < 10):\n print(\"term '\" + searchWord + \"' found in less than 10 pages.\")\nelse:\n \n for file in resultList:\n with open(file) as inf:\n content = inf.read()\n newname = file.replace(\"results/text/\", \"results/found/\")\n with open(newname, 'w') as of:\n of.write(content)\n","sub_path":"lectures/cs532-s19/assignments/A3/findWord.py","file_name":"findWord.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324158749","text":"# -*- coding: utf-8 -*-$\n\"\"\"Views for Survey.\"\"\"\nfrom __future__ import division\nfrom ._builtin import Page\nfrom . import models\nimport math\nfrom django.utils.translation import get_language\nfrom django.utils.translation import ugettext_lazy as _\nfrom otree.common import Currency\n\n\ndef vars_for_all_templates(self):\n \"\"\"Provide global template variables.\"\"\"\n return {\n 'lang': self.session.vars['lang'] or get_language()\n }\n\n\n# TODO: update \"Which device are you taking this study on?\" in SL\nclass Survey00(Page):\n\n form_model = models.Player\n form_fields = [\n 'which_device_did_you_take_this_study_on'\n ]\n\n\nclass Survey01(Page):\n\n form_model = models.Player\n form_fields = [\n 'overall_how_satisfied_are_you_with_life',\n 'how_much_do_you_trust_most_people_in_your_country'\n ]\n\n\nclass Survey02(Page):\n\n form_model = models.Player\n form_fields = [\n 'to_punish_someone_who_treats_others_unfairly',\n 'to_give_to_good_causes'\n ]\n\n\nclass Survey03(Page):\n\n form_model = models.Player\n form_fields = [\n 'fully_prepared_or_avoid_to_take_risks',\n 'when_someone_does_me_a_favor'\n ]\n\n\nclass Survey04(Page):\n\n form_model = models.Player\n form_fields = [\n 'people_are_looking_for_themselves_or_try_to_help_others',\n 'people_would_take_advantage_of_you_or_be_fair',\n 'receiving_government_benefits_to_which_you_are_not_entitled',\n 'cheating_on_taxes_if_you_have_a_chance'\n ]\n\n\nclass Survey05(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_much_do_you_trust_your_family',\n 'how_much_do_you_trust_people_in_your_neighborhood',\n 'how_much_do_you_trust_people_you_know_personally',\n 'how_much_do_you_trust_people_you_meet_for_the_first_time',\n 'how_much_do_you_trust_people_of_another_religion',\n 'how_much_do_you_trust_people_of_another_nationality',\n 'how_much_do_you_trust_people_who_immigrated',\n 'how_much_do_you_trust_people_who_seek_refuge',\n ]\n\n\nclass Survey06(Page):\n\n form_model = models.Player\n form_fields = [\n 'i_am_good_at_math',\n 'lost_your_wallet',\n 'did_you_vote'\n ]\n\n\nclass Survey07(Page):\n\n form_model = models.Player\n form_fields = [\n 'would_you_say_that_most_people_can_be_trusted'\n ]\n\n\nclass Survey08(Page):\n\n form_model = models.Player\n form_fields = [\n 'trust_the_government',\n 'trust_the_civil_service',\n 'trust_the_parliament',\n 'trust_the_judicial_system',\n 'trust_the_police',\n 'trust_the_media',\n 'trust_financial_institutions'\n ]\n\n\nclass Survey09(Page):\n\n form_model = models.Player\n form_fields = [\n 'public_institutions_deliver_service_in_the_best_way',\n 'public_institutions_pursue_long_term_objectives',\n 'people_in_public_institutions_are_ethical_and_not_corrupt',\n 'public_institutions_are_transparent',\n 'public_institutions_treat_all_citizens_fairly'\n ]\n\n\nclass Survey10(Page):\n\n form_model = models.Player\n form_fields = [\n 'satisfied_with_the_education_system',\n 'satisfied_with_the_health_care_system',\n 'satisfied_with_public_transport',\n 'satisfied_with_child_care_services',\n 'satisfied_with_welfare_benefits',\n 'satisfied_with_public_housing',\n 'satisfied_with_security_and_crime_prevention',\n 'satisfied_with_environmental_issues',\n 'satisfied_with_cultural_facilities'\n ]\n\nclass Survey10_5(Page):\n\n form_model = models.Player\n form_fields = [\n # 'complaint_about_quality_of_public_service_likely_resolved',\n # 'technology_speed_up_likely_to_be_adopted'\n ]\n\nclass Survey11(Page):\n\n form_model = models.Player\n form_fields = [\n # 'information_about_administrative_producedure_easy_to_find',\n 'complaint_about_quality_of_public_service_likely_resolved',\n 'decision_affecting_community_likely_to_be_consulted_upon',\n 'natural_disaster_shelter_and_clothing_availability'\n ]\n\n\nclass Survey12(Page):\n\n form_model = models.Player\n form_fields = [\n # 'start_a_business_conditions_stability',\n # 'natural_disaster_shelter_and_clothing_availability'\n ]\n\n\nclass Survey13(Page):\n\n form_model = models.Player\n form_fields = [\n # 'guilty_high_ranking_gov_employee_likely_prosecuted',\n 'accept_or_refuse_administrative_procedures_speed_up_bribe',\n 'high_ranking_gov_employee_accepts_well_paid_private_sector_job',\n 'accept_or_refuse_public_procurement_tender_allocation_bribe'\n ]\n\n\nclass Survey14(Page):\n\n form_model = models.Player\n form_fields = [\n 'social_minority_citizen_likely_to_be_treated_equally'\n ]\n\n\nclass Survey15(Page):\n\n form_model = models.Player\n form_fields = [\n 'expenditure_general_public_services_and_public_debt',\n 'expenditure_defense_and_public_order',\n 'expenditure_infrastucture_and_economic_affair',\n 'expenditure_health_and_environmental_protection',\n 'expenditure_education_and_culture',\n 'expenditure_social_protection_and_housing'\n ]\n\n\nclass Survey16(Page):\n\n form_model = models.Player\n form_fields = [\n 'resources_top_1_percent',\n 'resources_next_9_percent',\n 'resources_next_40_percent',\n 'resources_bottom_50_percent'\n ]\n\n\nclass Survey17(Page):\n\n form_model = models.Player\n form_fields = [\n # 'how_many_children_part_of_the_richest_segment',\n 'not_much_or_plenty_of_opportunity'\n ]\n\n\nclass Survey18(Page):\n\n form_model = models.Player\n form_fields = [\n 'household_expectations_for_the_12_months_to_come',\n 'likely_to_still_have_a_job_in_6_months',\n 'likely_to_find_a_job_with_similar_salary_in_6_months'\n ]\n\n\nclass Survey19(Page):\n\n form_model = models.Player\n form_fields = [\n 'government_should_encourage_or_discourage_international_trade'\n ]\n\n\nclass Survey20(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_much_info_from_tv',\n 'how_much_info_from_internet',\n 'how_much_info_from_family_friends_coworkers',\n # 'how_much_info_from_social_networks',\n # 'how_much_info_from_print_media'\n ]\n\n\nclass Survey21(Page):\n\n form_model = models.Player\n form_fields = [\n 'most_likely_threatening_privacy_hackers',\n 'most_likely_threatening_privacy_domestic_gov_agencies',\n 'most_likely_threatening_privacy_foreign_gov_agencies',\n 'most_likely_threatening_privacy_corporations'\n ]\n\n\nclass Survey22(Page):\n\n form_model = models.Player\n form_fields = [\n 'estimation_of_foreigners_in_neighborhood'\n ]\n\n\nclass Survey23(Page):\n\n form_model = models.Player\n form_fields = [\n 'statement_agreement_immigrants_are_not_integrated',\n 'statement_agreement_culture_is_undermined_by_immigrants'\n ]\n\n\nclass Survey24(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_often_do_you_get_together_with_friends',\n 'how_often_do_you_participate_in_voluntary_activities'\n ]\n\n\nclass Survey25(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_strongly_do_you_feel_connected_to_your_neighborhood'\n ]\n\n\nclass Survey26(Page):\n\n form_model = models.Player\n form_fields = [\n # 'voting_can_or_cannot_make_a_difference',\n 'people_like_me_dont_have_a_say',\n 'political_left_center_right'\n ]\n\n\nclass Survey27(Page):\n\n form_model = models.Player\n form_fields = [\n 'date_of_birth',\n 'gender'\n ]\n\n\nclass Survey28(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_many_people_in_your_household'\n ]\n\n\nclass Survey29(Page):\n\n form_model = models.Player\n form_fields = [\n 'which_country_were_you_born',\n 'what_is_your_nationality',\n 'when_did_you_arrive_in_country',\n 'were_your_parents_born_in_country'\n ]\n\n\nclass Survey30(Page):\n\n form_model = models.Player\n form_fields = [\n 'do_you_live_in_a'\n ]\n\n\nclass Survey31(Page):\n\n form_model = models.Player\n form_fields = [\n 'highest_level_of_education_you_have_completed'\n ]\n\n\nclass Survey32(Page):\n\n form_model = models.Player\n form_fields = [\n 'highest_level_of_education_your_parent_has_completed',\n ]\n\n\nclass Survey33(Page):\n\n form_model = models.Player\n form_fields = [\n 'what_best_describes_your_situation',\n 'do_you_currently_work_in_the'\n ]\n\n\nclass Survey34(Page):\n\n form_model = models.Player\n form_fields = [\n 'i_assume_that_people_have_only_the_best_intentions'\n ]\n\n\nclass Survey35(Page):\n\n form_model = models.Player\n form_fields = [\n 'individual_income_in_the_last_12_months',\n 'individual_income_confirmation'\n ]\n\n\nclass Survey36(Page):\n\n form_model = models.Player\n form_fields = [\n 'household_income_in_the_last_12_months',\n 'household_income_confirmation'\n ]\n\n def vars_for_template(self):\n \"\"\"Calculate dynamic ranges based on previous household size answer.\"\"\"\n round_to = 1000\n\n values = {\n 'sl': {\n 'A': 9000,\n 'B': 12500,\n 'C': 15000,\n 'D': 20000,\n },\n 'fr': {\n 'A': 15000,\n 'B': 20000,\n 'C': 25000,\n 'D': 32000\n },\n 'en': {\n 'A': 15000,\n 'B': 20000,\n 'C': 25000,\n 'D': 32000\n },\n 'ko': {\n 'A': 13000000,\n 'B': 20000000,\n 'C': 25000000,\n 'D': 34000000\n }\n }\n\n try:\n n = math.sqrt(int(self.player.how_many_people_in_your_household))\n except:\n n = math.sqrt(10)\n\n v = values[self.session.vars['lang']]\n\n a = round(int(v['A'] * n) / round_to) * round_to\n b = round(int(v['B'] * n) / round_to) * round_to\n c = round(int(v['C'] * n) / round_to) * round_to\n d = round(int(v['D'] * n) / round_to) * round_to\n\n return {\n 'choices': [\n _(u\"{0} - {1}\".format(Currency(0), Currency(a))),\n _(u\"{0} - {1}\".format(Currency(a + 1), Currency(b))),\n _(u\"{0} - {1}\".format(Currency(b + 1), Currency(c))),\n _(u\"{0} - {1}\".format(Currency(c + 1), Currency(d))),\n _(u\"> {0}\".format(Currency(d + 1)))\n ]\n }\n\n\nclass Survey37(Page):\n\n form_model = models.Player\n form_fields = [\n 'how_important_is_religion'\n ]\n\n\nclass Survey38(Page):\n\n form_model = models.Player\n form_fields = [\n 'open_comment'\n ]\n\n\npage_sequence = [\n Survey00,\n Survey01,\n Survey02,\n Survey03,\n # Survey04,\n Survey05,\n Survey06,\n Survey07,\n Survey08,\n Survey09,\n Survey10,\n # Survey10_5,\n Survey11,\n # Survey12,\n Survey13,\n Survey14,\n # Survey15,\n Survey16,\n Survey17,\n Survey18,\n Survey19,\n Survey20,\n # Survey21,\n Survey22,\n Survey23,\n Survey24,\n Survey25,\n Survey26,\n Survey27,\n Survey28,\n Survey29,\n Survey30,\n Survey31,\n Survey32,\n Survey33,\n # Survey34,\n Survey35,\n Survey36,\n Survey37,\n Survey38\n]\n","sub_path":"survey_i18n/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"628621436","text":"import os\nimport argparse\nimport yaml\nimport torch\nimport torch as t\nimport time\nfrom torch.utils.data import DataLoader\nfrom torch.backends import cudnn\nfrom visdom import Visdom\nimport logging\nimport cv2\nimport numpy as np\nfrom models.SSD.ssd_utils import MultiBoxLoss\nfrom data_preprocess import COCODetection, VOCDetection\nfrom utils import collect_fn, update_chart, output2maP, update_vali_chart\nfrom data_preprocess.Pascal_VOC.data_configs import VOC_TEST_IMG_SETS, VOC_CLASSES\nfrom gluoncv.utils.metrics.voc_detection import VOC07MApMetric\nfrom data_preprocess.utils import SSDAugmentation\n\n# from gluoncv.utils.metrics.coco_detection import COCODetectionMetric\n\nGPU_ACCESS = t.cuda.is_available()\nGPU_COUNTS = t.cuda.device_count()\nGPU_DEVICES = [idx for idx in range(GPU_COUNTS)]\n\nLOGGING_ITERS = 10\nSAVING_ITERS = 10000\nIMG_SIZE = 384\n\n\ndef get_args():\n # 指定dataset, 训练的iteration数(不是epoch), batch_size数, 是否用GPU(有GPU则默认用GPU)\n parser = argparse.ArgumentParser(description='Convolutional Transformer Based Single Shot MultiBox Detector '\n 'Training . Using VoC2017&2012 or COCO2014')\n parser.add_argument('--dataset', default='VOC', choices=['VOC', 'COCO'], type=str, help='dataset from VOC or COCO.')\n parser.add_argument('--network', default='CvT_SSD', choices=['CvT_SSD', 'CvT_ASSD', 'VGG_SSD', 'VGG_ASSD'],\n type=str, help='network you wanna to train.')\n\n parser.add_argument('--use-gpu', default=GPU_ACCESS, choices=[True, False], type=bool,\n help='whether use gpu to train.')\n # 如果其他显卡被占用,请在此指定使用的GPU卡序号, 默认使用机器上所有卡\n parser.add_argument('--gpu-ids', default=GPU_DEVICES, type=list, help='which gpus for training.')\n parser.add_argument('--base-network-configs-path', default=None, type=str, help='path of base-network to config, '\n 'you must give it when model-resume-path is None!')\n parser.add_argument('--base-network-resume-path', default=None, type=str, help='path of base-network to resume, '\n 'you must give it when model-resume-path is None!')\n parser.add_argument('--model-resume-path', default=None, type=str, help='path of checkpoint model file to resume '\n 'training. if not, train from scratch')\n parser.add_argument('--model-save-path', default=os.path.abspath('./weights/'), type=str,\n help='path of trained model directory')\n\n parser.add_argument('--batch-size', default=6, type=int, help='batch size for training')\n parser.add_argument('--iter-count', default=None, type=int,\n help='total training iterations count default voc:12W,coco:40w')\n parser.add_argument('--start-iter-idx', default=0, type=int, help='start training iteration index')\n parser.add_argument('--learning-rate', default=1e-3, type=float, help='initial learning rate')\n parser.add_argument('--momentum', default=0.9, type=float, help='Momentum value for optimizer')\n parser.add_argument('--weight-decay', default=5e-4, type=float, help='Weight decay for SGD')\n parser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD')\n\n parser.add_argument('--visdom', default=False, type=bool, help='whether see running log in website.')\n parser.add_argument('--logger-path', default=os.path.abspath('./run_logs/'), type=str,\n help='path of logging directory')\n\n return parser.parse_args()\n\n\ndef get_model(parser):\n # 获取模型参数配置\n model_name = parser.network\n MODEL_PATH = parser.model_resume_path\n BASE_MODEL_CONFIGS_PATH = parser.base_network_configs_path\n BASE_MODEL_FILE_PATH = parser.base_network_resume_path\n with open(BASE_MODEL_CONFIGS_PATH, 'r') as inp_:\n cvT_configs = yaml.load(inp_, Loader=yaml.FullLoader)\n cvT_model_configs = cvT_configs['MODEL']\n\n model = None\n num_classes = 21 if 'VOC' == parser.dataset else 81 # 获取物体类别送入网络\n if model_name == 'CvT_SSD':\n from models.CvT_SSD import build_ssd_from_cvt\n model = build_ssd_from_cvt(cvt_configs=cvT_model_configs,num_classes=num_classes,\n cvt_model_file_path=os.path.abspath(BASE_MODEL_FILE_PATH) if BASE_MODEL_FILE_PATH else None,\n model_path=os.path.abspath(MODEL_PATH) if MODEL_PATH else None)\n elif model_name == 'CvT_ASSD':\n from models.CvT_ASSD import build_assd_from_cvt\n model = build_assd_from_cvt(num_classes)\n elif model_name == 'VGG_SSD':\n from models.VGG_SSD import build_ssd_from_vgg\n model = build_ssd_from_vgg(mode='train', size=300, num_classes=21)\n elif model_name == 'VGG_ASSD':\n logging.error(f'I don`t build {model_name} model caused it`s no need now,if you wanna ,contact me by '\n f'phone number: 13040617148.')\n exit(-1)\n else:\n logging.error('No such model named:{} !'.format(model_name))\n exit(-1)\n return model\n\n\ndef gpu_setting(parser):\n if parser.use_gpu and GPU_ACCESS:\n cudnn.enabled = True # 允许使用非确定算法\n cudnn.benchmark = True # 让内置的 cuDNN 的 auto-tuner 自动寻找最适合当前配置的高效算法, 优化运行效率\n cudnn.deterministic = False # 使用非确定算法\n t.set_default_tensor_type('torch.cuda.FloatTensor')\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ', '.join([str(i for i in parser.gpu_ids)])\n # TODO: add torch distributed schedule if more than one gpu for training speed up. 这里可能还需优化.\n else:\n if GPU_ACCESS:\n logging.warning(\"WARNING: It looks like you have a CUDA device, but aren't using CUDA, run with --use-gpu \"\n \"argument for training speed up.\")\n t.set_default_tensor_type('torch.FloatTensor')\n\n\ndef train():\n # 训练准备\n parser = get_args()\n gpu_setting(parser)\n gpu_devices = [idx for idx, _ in enumerate(parser.gpu_ids)]\n GPU_TRAIN = parser.use_gpu and GPU_ACCESS\n PARAELLEL_FLAG = len(parser.gpu_ids) > 0 and GPU_TRAIN # 是否分布式训练\n network = get_model(parser)\n optimizer = t.optim.SGD(network.parameters(), lr=parser.learning_rate, momentum=parser.momentum,\n weight_decay=parser.weight_decay)\n num_classes = 21 if 'VOC' == parser.dataset else 81 # 获取物体类别送入网络\n iterations = 120000 if 'VOC' == parser.dataset else 400000\n lr_steps = (60000, 800000, 100000) if 'VOC' == parser.dataset else (250000, 300000, 350000)\n if parser.iter_count:\n iterations = parser.iter_count\n criterion = MultiBoxLoss(num_classes=num_classes, overlap_thresh=0.5, prior_for_matching=True, bkg_label=0,\n neg_mining=True, neg_pos=3, neg_overlap=0.5, encode_target=False,\n use_gpu=GPU_TRAIN)\n if PARAELLEL_FLAG:\n network = t.nn.DataParallel(network, device_ids=gpu_devices, output_device=gpu_devices[0])\n optimizer = t.nn.DataParallel(optimizer, device_ids=gpu_devices, output_device=gpu_devices[0])\n network.train()\n\n # 准备训练数据\n img_transform = SSDAugmentation(size=224)\n dataset = VOCDetection(img_transform=img_transform) if 'VOC' == parser.dataset else COCODetection(\n img_transform=img_transform)\n data_count = len(dataset)\n data_loader = DataLoader(dataset, batch_size=parser.batch_size, shuffle=True, collate_fn=collect_fn,\n pin_memory=True, drop_last=True, generator=t.Generator(device=t.device('cuda'))) # num_workers=2\n data_iterator = iter(data_loader)\n\n # 准备测试数据\n test_dataset = VOCDetection(image_sets=VOC_TEST_IMG_SETS, dataset_name='VOC07_test') # 测试集都用VOC2007_test\n test_data_count = len(test_dataset)\n test_data_loader = DataLoader(test_dataset, batch_size=parser.batch_size, shuffle=True, # num_workers=2,\n collate_fn=collect_fn, pin_memory=True, generator=t.Generator(device=t.device('cuda')))\n test_data_iterator = iter(test_data_loader)\n\n if parser.visdom:\n vis_ = Visdom()\n vis_title = parser.network + ' training on ' + dataset.dataset_name\n vis_legend = ['Loc Loss', 'Conf Loss', 'Total Loss']\n vis_iter_opts = {'xlabel': 'Iteration', 'ylabel': 'Loss', 'title': vis_title, 'legend': vis_legend}\n vis_epoch_opts = {'xlabel': 'Iteration', 'ylabel': 'Loss', 'title': vis_title, 'legend': vis_legend}\n # 数据从iter1 & epoch1 开始\n iter_plot, epoch_plot = vis_.line(X=[0], Y=[[0, 0, 0]], opts=vis_iter_opts), vis_.line(X=[0], Y=[[0, 0, 0]],\n opts=vis_epoch_opts)\n vis_vali_opts = {'xlabel': 'Iteration', 'ylabel': '(m)aP', 'title': vis_title,\n 'legend': VOC_CLASSES + ('maP(mean average precision)',)}\n vali_plot = vis_.line(X=[0], Y=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]],\n opts=vis_vali_opts) # 定时测试模型在VOC2007测试集上的maP指标\n # 日志文件记录 测试效果\n vali_logger = None\n if parser.logger_path:\n if os.path.isdir(parser.logger_path):\n log_name = '-'.join([parser.network, dataset.dataset_name, time.asctime().replace(' ', '_').replace(':', '_')])\n vali_logger = logging.getLogger()\n formatter = logging.Formatter('%(asctime)s - %(message)s')\n handler_ = logging.FileHandler(os.path.join(parser.logger_path, log_name), encoding='UTF-8')\n handler_.setLevel(logging.INFO)\n handler_.setFormatter(formatter)\n vali_logger.addHandler(handler_)\n console_ = logging.StreamHandler()\n console_.setLevel(logging.INFO)\n console_.setFormatter(formatter)\n vali_logger.addHandler(console_)\n else:\n logging.error('--logger-path is not a directory, can`t save logs!')\n exit(-1)\n\n # 开始训练\n epoch_loc_loss = 0\n epoch_conf_loss = 0\n iter_loc_loss = 0\n iter_conf_loss = 0\n iters_count_per_epoch = data_count // parser.batch_size # 每个epoch会遍历多少轮\n epoch_idx = (parser.start_iter_idx * parser.batch_size // data_count) + 1 # 通过 当前iteration与数据量大小计算epoch_idx\n test_metric = VOC07MApMetric(iou_thresh=0.5, class_names=VOC_CLASSES)\n epoch_start_time = time.time()\n iter_start_time = time.time()\n for iter_idx in range(parser.start_iter_idx, iterations):\n iter_idx_ = iter_idx + 1\n # 准备一个batch数据\n images, targets = next(data_iterator)\n if GPU_TRAIN:\n images = images.cuda()\n targets = [target.cuda() for target in targets]\n # 调整学习率\n if iter_idx_ in lr_steps:\n learning_rate_ = parser.learning_rate * (parser.gamma ** lr_steps.index(iter_idx_))\n for param in optimizer.param_groups:\n param['lr'] = learning_rate_\n ###########training##############\n output_ = network(images)\n output_ = (output_[0], output_[1], output_[2][0])\n loss_loc, loss_conf = criterion(output_, targets)\n epoch_loc_loss += loss_loc.item()\n epoch_conf_loss += loss_conf.item()\n iter_loc_loss += loss_loc.item()\n iter_conf_loss += loss_conf.item()\n loss_sum = loss_loc + loss_conf\n optimizer.zero_grad()\n loss_sum.backward()\n optimizer.module.step() # optimizer.step()\n ############training#############\n # when iteration goes by per-LOGGING_ITERS.\n if iter_idx_ % LOGGING_ITERS == 0:\n iter_end_time = time.time()\n iter_spend_time = iter_end_time - iter_start_time\n vali_logger.info(\n 'Iterations: [{0}]==[{1}], Epoch: [{2}], Speed: {3} pictures/sec, avg_iter_loc_loss: {4}, avg'\n '_iter_conf_loss: {5}.'.format(iter_idx_ - LOGGING_ITERS + 1, iter_idx_, epoch_idx,\n parser.batch_size\n * LOGGING_ITERS / iter_spend_time,\n iter_loc_loss / LOGGING_ITERS, iter_conf_loss / LOGGING_ITERS))\n iter_conf_loss = 0\n iter_loc_loss = 0\n\n if parser.visdom:\n update_chart(visdom=vis_, window_=iter_plot, step_idx=iter_idx_, loc_loss=loss_loc.item(),\n conf_loss=loss_conf.item())\n if iter_idx_ % iters_count_per_epoch == 0: # when in a new epoch.\n # 添加当前epoch的loss汇总到 epoch_plot 图中\n avg_epoch_loc_loss = epoch_loc_loss / iters_count_per_epoch\n avg_epoch_conf_loss = epoch_conf_loss / iters_count_per_epoch\n if parser.visdom:\n update_chart(visdom=vis_, window_=epoch_plot, step_idx=epoch_idx, loc_loss=avg_epoch_loc_loss,\n conf_loss=avg_epoch_conf_loss)\n epoch_end_time = time.time()\n epoch_spend_time = epoch_end_time - epoch_start_time\n epoch_start_time = epoch_end_time\n vali_logger.info(\n f\"*** Epoch: [{epoch_idx}], time: [{epoch_spend_time}] sec, avg_epoch_loc_loss: {avg_epoch_loc_loss}, avg_epoch_conf_loss: {avg_epoch_conf_loss}\")\n epoch_loc_loss = 0\n epoch_conf_loss = 0\n epoch_idx += 1\n if iter_idx_ % SAVING_ITERS == 0:\n # 测试当前模型在VOC2006_test上的maP.\n network.mode = 'test'\n test_metric.reset()\n for test_iter_idx in range(test_data_count // parser.batch_size): # 迭代测试集一轮即可\n images, targets = next(test_data_iterator)\n with torch.no_grad():\n output_ = network(images)\n locations_list, classes_list, scores_list = output2maP(output_)\n test_metric.update(pred_bboxes=locations_list, pred_labels=classes_list, pred_scores=scores_list,\n gt_bboxes=targets[:, :, :4], gt_labels=targets[:, :, 4], gt_difficults=None)\n aPs_maP_name, aPs_maP = test_metric.get()\n info_ = \"\\n\".join(['\\t' + k + \" == \" + str(v) for k, v in zip(aPs_maP_name, aPs_maP)])\n val_log_ = f'===[Iterations: {iter_idx_}, Validation: \\n{info_}]'\n if vali_logger:\n vali_logger.info(val_log_)\n else:\n print(val_log_)\n update_vali_chart(vis_, window_=vali_plot, step_idx=iter_idx_, maPs=aPs_maP)\n network.mode = 'train'\n # 保存模型\n if os.path.isdir(parser.model_save_path):\n torch.save(network.module.state_dict(), os.path.join(parser.model_save_path, '_'.join(\n [parser.network, dataset.dataset_name, 'iter' + str(iter_idx_)]) + '.pth'))\n else:\n vali_logger.error('--model-save-path is not a directory, can`t save model!')\n exit(-1)\n torch.save(network.module.state_dict(), os.path.join(parser.model_save_path, '_'.join(\n [parser.network, dataset.dataset_name, 'iter' + str(iterations)]) + '.pth'))\n vali_logger.info('finished !')\n\n\nif __name__ == '__main__':\n train()\n","sub_path":"run_scripts/train_multiGpus.py","file_name":"train_multiGpus.py","file_ext":"py","file_size_in_byte":15780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"338463622","text":"import os\nimport h5py\nimport numpy as np\nfrom mayavi import mlab\nimport tkinter as tk\nfrom tkinter import filedialog\n\ndef plot_c_scan_from_merged_file(merged_file_name, polarization = 'x', amp = 0):\n \"\"\"Function that reads a merged file and calls the C-Scan plotting function\n Args:\n merged_file_name (string): Name of the merged file.\n polarization (string): Identifier of the polarization to be plotted in the C-Scan. If 'x' or 'y' is received, just\n the corresponding polarization B-Scans are plotted. Other entries plot C-Scans for both polarizations.\n (Default = 'x')\n amp (float): Amplitude to be taken as maximum and minimum for the C-Scan colorbar. If zero is received, the\n function will find the range within the A-Scan amplitudes of the merged file. (Default = 0)\n \"\"\"\n # Merged file is opened into data_frame variable\n data_frame = h5py.File(merged_file_name, 'r')\n # Identifiers are set into lower case\n polarization = polarization.lower()\n # Title for the C-Scan figure\n title = data_frame.attrs['Title'] + ' C-Scan for ' + polarization + '-polarization'\n # Time-domain lower and upper limits are retrieved\n t0 = data_frame['Time'].attrs['t0']\n tf = data_frame['Time'].attrs['tf']\n qt = int(data_frame['Time'].attrs['q'])\n # x- and y-axis lower limits, upper limits and step are retrieved\n x0 = data_frame['Position'].attrs['x0']\n dx = data_frame['Position'].attrs['dx']\n xf = data_frame['Position'].attrs['xf']\n y0 = data_frame['Position'].attrs['y0']\n dy = data_frame['Position'].attrs['dy']\n yf = data_frame['Position'].attrs['yf']\n # Amount of steps over each axis is calculated. Operation rounds up the division result as needed\n qx = int(round((xf - x0) / dx + 1))\n qy = int(round((yf - y0) / dy + 1))\n\n if polarization == 'x' or polarization == 'y':\n # Creates numpy 3D array for storing C-Scan data\n c_scan_scalars = np.zeros([qx, qy, qt])\n else:\n data_frame.close()\n raise Exception(\"Can only plot the C-Scan of one polarization at a time. Please specify if x or y.\")\n\n for i in range(0, qx):\n # Indexes used to retrieve individual planes of the C-Scan are calculated\n index_0 = i * qy\n index_f = (i + 1) * qy\n\n if polarization == 'x':\n # C-Scan data is retrieved from the merged file\n c_scan_scalars[i,:,:] = data_frame['A-Scan/Re{A-Scan x-pol}'][index_0:index_f][:]\n else:\n # C-Scan data is retrieved from the merged file\n c_scan_scalars[i, :, :] = data_frame['A-Scan/Re{A-Scan y-pol}'][index_0:index_f][:]\n\n # Grid with the domain points is created. Time axis is scaled to be within the same orders of magnitude as x and y.\n x, y, z = np.mgrid[x0:xf:qx * 1j, y0:yf:qy * 1j, tf*10**8:t0:qt * 1j]\n\n # Labels for the horizontal and vertical axes are set\n x_label = 'x [m]'\n y_label = 'y [m]'\n v_label = 't [x10 ns]'\n\n # Figure is created\n mlab.figure(figure=title, size=(1100, 800))\n # Volume slice type plot is added to the figure\n if amp != 0:\n mlab.volume_slice(x, y, z, np.abs(c_scan_scalars), opacity=0.4, reset_zoom=True, vmax=amp, vmin=-amp)\n else:\n mlab.volume_slice(x, y, z, np.abs(c_scan_scalars), opacity=0.4, reset_zoom=True)\n # Options for the colorbar and axes are set\n cb1 = mlab.colorbar(orientation=\"vertical\", nb_labels=5)\n cb1.scalar_bar.unconstrained_font_size = True\n cb1.label_text_property.font_size = 10\n cb1.label_text_property.bold = False\n cb1.label_text_property.italic = False\n ax = mlab.axes(xlabel=x_label, ylabel=y_label, zlabel=v_label)\n ax.label_text_property.font_size = 1\n ax.title_text_property.font_size = 1\n # Outline for the volume slice is added to the figure\n mlab.outline()\n # Title is added to the figure\n mlab.title(title, size=0.2, height=0)\n # Contour type plot is added to the figure\n if amp != 0:\n mlab.contour3d(x, y, z, c_scan_scalars, opacity=0.4, reset_zoom=True, vmax=amp, vmin=-amp, contours=10)\n else:\n mlab.contour3d(x, y, z, c_scan_scalars, opacity=0.4, reset_zoom=True, contours=10)\n # Figure is displayed\n mlab.show()\n\n # Data frame of the .h5 file is closed\n data_frame.close()\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.withdraw()\n file = filedialog.askopenfilename(parent=root, initialdir=os.getcwd())\n root.destroy()\n # C-Scans of the merged file are plotted\n plot_c_scan_from_merged_file(file)","sub_path":"scripts procesamiento/04_plotting/c_scan_plot.py","file_name":"c_scan_plot.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"557946093","text":"class Solution(object):\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n recode = {}\n result = []\n for num1 in nums1:\n if num1 in recode:\n recode[num1] += 1\n else:\n recode[num1] = 1\n for num2 in nums2:\n if num2 in recode and recode[num2] != 0:\n result.append(num2)\n recode[num2] -= 1\n return result\n","sub_path":"题目分类/哈希表/intersection_of_two_arrays_ii_350.py","file_name":"intersection_of_two_arrays_ii_350.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"405733042","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.generics import GenericAPIView\nfrom ..permissions import IsAuthenticated\nfrom django.core.cache import cache\nfrom django.conf import settings\n\nfrom ..app_settings import (\n CreateMembershipSerializer,\n UpdateMembershipSerializer,\n DeleteMembershipSerializer,\n)\nfrom ..models import (\n User_Group_Membership\n)\nfrom ..authentication import TokenAuthentication\n\nclass MembershipView(GenericAPIView):\n\n \"\"\"\n Manages group memberships\n \"\"\"\n\n authentication_classes = (TokenAuthentication, )\n permission_classes = (IsAuthenticated,)\n allowed_methods = ('PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD')\n\n def get(self, request, *args, **kwargs):\n return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n\n def put(self, request, *args, **kwargs):\n \"\"\"\n Creates a new group membership\n\n :param request:\n :type request:\n :param args:\n :type args:\n :param kwargs:\n :type kwargs:\n :return: 201 / 400\n :rtype:\n \"\"\"\n\n serializer = CreateMembershipSerializer(data=request.data, context=self.get_serializer_context())\n\n if not serializer.is_valid():\n\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST\n )\n\n membership = User_Group_Membership.objects.create(\n user_id = serializer.validated_data['user_id'],\n group_id = serializer.validated_data['group_id'],\n creator = request.user,\n secret_key = str(serializer.validated_data['secret_key']),\n secret_key_nonce = str(serializer.validated_data['secret_key_nonce']),\n secret_key_type = str(serializer.validated_data['secret_key_type']),\n private_key = str(serializer.validated_data['private_key']),\n private_key_nonce = str(serializer.validated_data['private_key_nonce']),\n private_key_type = str(serializer.validated_data['private_key_type']),\n group_admin = serializer.validated_data['group_admin'],\n share_admin = serializer.validated_data['share_admin'],\n )\n\n if settings.CACHE_ENABLE:\n cache_key = 'psono_user_status_' + str(serializer.validated_data['user_id'])\n cache.delete(cache_key)\n\n return Response({'membership_id': membership.id}, status=status.HTTP_201_CREATED)\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Updates a group membership\n\n :param request:\n :type request:\n :param args:\n :type args:\n :param kwargs:\n :type kwargs:\n :return: 200 / 400\n :rtype:\n \"\"\"\n\n serializer = UpdateMembershipSerializer(data=request.data, context=self.get_serializer_context())\n\n if not serializer.is_valid():\n\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST\n )\n\n membership = serializer.validated_data['membership']\n membership.group_admin = serializer.validated_data['group_admin']\n membership.share_admin = serializer.validated_data['share_admin']\n membership.save()\n\n return Response(status=status.HTTP_200_OK)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n Deletes a group membership\n\n :param request:\n :param args:\n :param kwargs:\n :return: 200 / 400\n \"\"\"\n\n serializer = DeleteMembershipSerializer(data=request.data, context=self.get_serializer_context())\n\n if not serializer.is_valid():\n\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST\n )\n\n membership = serializer.validated_data.get('membership')\n\n if settings.CACHE_ENABLE:\n cache_key = 'psono_user_status_' + str(membership.user.id)\n cache.delete(cache_key)\n\n # delete it\n membership.delete()\n\n return Response(status=status.HTTP_200_OK)\n","sub_path":"psono/restapi/views/membership.py","file_name":"membership.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"9168755","text":"\"\"\"\n\nCopyright 2019-2020, Institute for Systems Biology\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n\"\"\"\n\nimport sys\nimport yaml\nimport io\nfrom git import Repo\nfrom common_etl.support import create_clean_target, generate_dataset_desc_file, install_dataset_desc\n\n'''\n----------------------------------------------------------------------------------------------\nThe configuration reader. Parses the YAML configuration into dictionaries\n'''\ndef load_config(yaml_config):\n yaml_dict = None\n config_stream = io.StringIO(yaml_config)\n try:\n yaml_dict = yaml.load(config_stream, Loader=yaml.FullLoader)\n except yaml.YAMLError as ex:\n print(ex)\n\n if yaml_dict is None:\n return None, None\n\n return yaml_dict['files_and_buckets_and_tables'], yaml_dict['steps']\n\n'''\n----------------------------------------------------------------------------------------------\nMain Control Flow\nNote that the actual steps run are configured in the YAML input!\nThis allows you to e.g. skip previously run steps.\n'''\n\ndef main(args):\n\n if len(args) != 2:\n print(\" \")\n print(\" Usage : {} \".format(args[0]))\n return\n\n print('job started')\n\n #\n # Get the YAML config loaded:\n #\n\n with open(args[1], mode='r') as yaml_file:\n params, steps = load_config(yaml_file.read())\n\n if params is None:\n print(\"Bad YAML load\")\n return\n\n #\n # Dataset descriptions are maintained in the github repo:\n #\n\n if 'pull_dataset_info_from_git' in steps:\n print('pull_dataset_info_from_git')\n try:\n create_clean_target(params['SCHEMA_REPO_LOCAL'])\n repo = Repo.clone_from(params['SCHEMA_REPO_URL'], params['SCHEMA_REPO_LOCAL'])\n repo.git.checkout(params['SCHEMA_REPO_BRANCH'])\n except Exception as ex:\n print(\"pull_dataset_info_from_git failed: {}\".format(str(ex)))\n return\n\n for mydict in params['FIX_LIST']:\n\n dataset, repo_file = next(iter(mydict.items()))\n\n if 'process_git_schemas' in steps:\n print('process_git_schemas: {}'.format(dataset))\n # Where do we dump the schema git repository?\n schema_file = \"{}/{}/{}\".format(params['SCHEMA_REPO_LOCAL'], params['RAW_SCHEMA_DIR'], repo_file)\n full_file_prefix = \"{}/{}\".format(params['PROX_DESC_PREFIX'], dataset)\n # Write out the details\n success = generate_dataset_desc_file(schema_file, full_file_prefix)\n if not success:\n print(\"process_git_schemas failed\")\n return\n\n #\n # Add description and labels to the target table:\n #\n\n if 'update_dataset_descriptions' in steps:\n print('update_dataset_descriptions: {}'.format(dataset))\n full_file_prefix = \"{}/{}\".format(params['PROX_DESC_PREFIX'], dataset)\n full_dataset_id = \"{}.{}\".format(params['TARGET_PROJECT'], dataset)\n success = install_dataset_desc(full_dataset_id, full_file_prefix)\n if not success:\n print(\"update_dataset_descriptions failed\")\n return\n\n print('job completed')\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"BQ_Table_Building/install_bq_dataset_descriptions.py","file_name":"install_bq_dataset_descriptions.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"88528907","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2016--, QIIME 2 development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport collections\nimport io\nimport os\nimport os.path\nimport shutil\nimport tempfile\nimport uuid\nimport yaml\nimport zipfile\n\nimport qiime.sdk\nimport qiime.core.util as util\n\n# Allow OrderedDict to be serialized for YAML representation\nyaml.add_representer(collections.OrderedDict, lambda dumper, data:\n dumper.represent_dict(data.items()))\n\n\nclass Archiver:\n # This class will likely defer to one of many ArchiveFormats in the future.\n # There's only one supported archive format currently.\n _VERSION = '0.2.0'\n _VERSION_FILENAME = 'VERSION'\n _README_FILENAME = 'README.md'\n _METADATA_FILENAME = 'metadata.yaml'\n DATA_DIRNAME = 'data'\n\n @classmethod\n def extract(cls, filepath, output_dir):\n with zipfile.ZipFile(filepath, mode='r') as zf:\n zf.extractall(output_dir)\n return output_dir\n\n @classmethod\n def peek(cls, filepath):\n \"\"\"\n\n Returns\n -------\n tuple\n Tuple of UUID, type, and provenance.\n\n \"\"\"\n if not zipfile.is_zipfile(filepath):\n raise zipfile.BadZipFile(\n \"%r is not a readable ZIP file, or the file does not exist\" %\n filepath)\n\n root_dir = cls._get_root_dir(filepath)\n with zipfile.ZipFile(filepath, mode='r') as zf:\n version = cls._load_version(zf, root_dir)\n if version != cls._VERSION:\n raise ValueError(\n \"Unsupported archive format version %r. \"\n \"Supported version(s): %r\" % (version, cls._VERSION))\n\n return cls._load_metadata(zf, root_dir)\n\n @classmethod\n def load(cls, filepath):\n metadata = cls.peek(filepath)\n return cls(*metadata, archive_filepath=filepath)\n\n @classmethod\n def _get_root_dir(cls, filepath):\n return os.path.splitext(os.path.basename(filepath))[0]\n\n @classmethod\n def _load_version(cls, zf, root_dir):\n version_path = os.path.join(root_dir, cls._VERSION_FILENAME)\n with zf.open(version_path) as bytes_fh:\n with io.TextIOWrapper(bytes_fh, newline=None,\n encoding='utf-8', errors='strict') as fh:\n return fh.read().rstrip('\\n')\n\n @classmethod\n def _load_metadata(cls, zf, root_dir):\n metadata_path = os.path.join(root_dir, cls._METADATA_FILENAME)\n with zf.open(metadata_path) as bytes_fh:\n with io.TextIOWrapper(bytes_fh, newline=None,\n encoding='utf-8', errors='strict') as fh:\n metadata = yaml.safe_load(fh)\n\n uuid_ = cls._parse_uuid(metadata['uuid'])\n type_ = util.parse_type(metadata['type'])\n provenance = cls._parse_provenance(metadata['provenance'])\n format = metadata['format']\n return uuid_, type_, format, provenance\n\n @classmethod\n def _parse_uuid(cls, string):\n return uuid.UUID(hex=string)\n\n # TODO implement provenance parsing for real\n @classmethod\n def _parse_provenance(cls, provenance):\n if isinstance(provenance, str):\n if provenance == 'None':\n return None\n else:\n return provenance\n else:\n return qiime.sdk.Provenance(\n execution_uuid=uuid.UUID(hex=provenance['execution-uuid']),\n # TODO this should be 'action-reference' to match QIIME 2\n # nomenclature. Not worth updating now while provenance is\n # stubbed.\n executor_reference=provenance['executor-reference'],\n artifact_uuids={k: uuid.UUID(hex=v) for k, v in\n provenance['artifact-uuids'].items()},\n parameter_references=provenance['parameter-references']\n )\n\n def __init__(self, uuid, type, format: str, provenance,\n archive_filepath=None, data_initializer=None):\n \"\"\"\n\n Parameters\n ----------\n data_initializer : callable, optional\n Callable accepting a single str argument specifying the data\n directory to write data to. Callable should not return anything,\n return values will be ignored.\n\n \"\"\"\n if archive_filepath is None and data_initializer is None:\n raise ValueError(\n \"`archive_filepath` or `data_initializer` must be provided.\")\n\n if archive_filepath is not None and data_initializer is not None:\n raise ValueError(\n \"`archive_filepath` and `data_initializer` cannot both be \"\n \"provided.\")\n\n self._uuid = uuid\n self._type = type\n self._provenance = provenance\n self._format = format\n\n self._temp_dir = tempfile.mkdtemp(prefix='qiime2-archive-temp-')\n self._data_dir = os.path.join(self._temp_dir, self.DATA_DIRNAME)\n self._pid = os.getpid()\n\n if archive_filepath is not None:\n self._extract_data(archive_filepath)\n else:\n os.mkdir(self._data_dir)\n data_initializer(self._data_dir)\n # TODO: set _temp_dir to be read-only, don't forget that windows will\n # fail on shutil.rmtree, so add an onerror callback which chmods and\n # removes again\n\n def __del__(self):\n # Destructor can be called more than once.\n if os.path.exists(self._temp_dir) and self._pid == os.getpid():\n shutil.rmtree(self._temp_dir)\n\n def _extract_data(self, archive_filepath):\n root_dir = self._get_root_dir(archive_filepath)\n prefix = os.path.join(root_dir, self.DATA_DIRNAME, '')\n\n with zipfile.ZipFile(archive_filepath, mode='r') as zf:\n for file_ in zf.namelist():\n if file_.startswith(prefix) and file_ != prefix:\n zf.extract(file_, path=self._temp_dir)\n shutil.move(os.path.join(self._temp_dir, prefix), self._temp_dir)\n os.rmdir(os.path.join(self._temp_dir, root_dir))\n\n @property\n def uuid(self):\n return self._uuid\n\n @property\n def type(self):\n return self._type\n\n @property\n def provenance(self):\n return self._provenance\n\n @property\n def format(self):\n return self._format\n\n def orphan(self, pid):\n self._pid = pid\n\n def get_data_paths(self, recursive=True):\n iterable = iter(os.walk(self._data_dir))\n if not recursive:\n iterable = [next(iterable)]\n for root, _, files in iterable:\n for fp in files:\n fullpath = os.path.join(root, fp)\n yield (os.path.relpath(fullpath, self._data_dir), fullpath)\n\n def load_data(self, loader):\n return loader(self._data_dir)\n\n def save(self, filepath):\n root_dir = self._get_root_dir(filepath)\n\n with zipfile.ZipFile(filepath, mode='w',\n compression=zipfile.ZIP_DEFLATED,\n allowZip64=True) as zf:\n self._save_version(zf, root_dir)\n self._save_readme(zf, root_dir)\n self._save_metadata(zf, root_dir)\n\n for root, dirs, files in os.walk(self._data_dir):\n for file_ in files:\n abspath = os.path.join(root, file_)\n relpath = os.path.relpath(abspath, start=self._data_dir)\n archive_path = os.path.join(\n root_dir,\n self.DATA_DIRNAME,\n relpath\n )\n zf.write(abspath, arcname=archive_path)\n\n def _save_version(self, zf, root_dir):\n version = '%s\\n' % self._VERSION\n zf.writestr(os.path.join(root_dir, self._VERSION_FILENAME),\n version.encode('utf-8'))\n\n def _save_readme(self, zf, root_dir):\n zf.writestr(os.path.join(root_dir, self._README_FILENAME),\n _README_TEXT.encode('utf-8'))\n\n def _save_metadata(self, zf, root_dir):\n metadata_bytes = yaml.dump(collections.OrderedDict([\n ('uuid', self._formatted_uuid()),\n ('type', repr(self.type)),\n ('format', self.format),\n ('provenance', self._formatted_provenance())\n ]), default_flow_style=False)\n zf.writestr(os.path.join(root_dir, self._METADATA_FILENAME),\n metadata_bytes.encode('utf-8'))\n\n def _formatted_uuid(self):\n return str(self.uuid)\n\n # TODO this is a provenance placeholder for now\n def _formatted_provenance(self):\n if self.provenance is None:\n return str(None)\n elif isinstance(self.provenance, str):\n return self.provenance\n else:\n return {\n 'execution-uuid': str(self.provenance.execution_uuid),\n # TODO this should be 'action-reference' to match QIIME 2\n # nomenclature. Not worth updating now while provenance is\n # stubbed.\n 'executor-reference': self.provenance.executor_reference,\n 'artifact-uuids': {k: str(v) for k, v in\n self.provenance.artifact_uuids.items()},\n 'parameter-references': self.provenance.parameter_references\n }\n\n\n_README_TEXT = \"\"\"# QIIME 2 archive\n\nThis archive stores the data and associated metadata of a serialized QIIME 2\nartifact or visualization.\n\n**WARNING:** This is a temporary file format used for prototyping QIIME 2. Do\nnot rely on this format for any reason as it will not be supported past the\nprototyping stage in its current form.\n\"\"\"\n","sub_path":"qiime/core/archiver.py","file_name":"archiver.py","file_ext":"py","file_size_in_byte":9986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"77481022","text":"import turtle\n\n\ndef circlefill(t,x,y,r):\n\tprint(\"two circle\")\n\tt.penup()\n\tt.goto(x,y+r)\n\tt.down()\n\tt.begin_fill()\n\tt.color(\"#00ff00\")\n\tfor i in range (1,40):\n\t\tt.forward(30)\n\t\tt.rt(9)\n\tt.end_fill()\n\t\ndef arc(t,x,y,l,tn,h):\n\t#x, y l(length) tn(turn value)\n\tt.down()\n\tt.setheading(0)\n\tt.heading()\n\tt.seth(h)\n\tfor i in range (1,10):\n\t\tt.forward(l)\n\t\tt.rt(tn)\n\t\ndef two2(t):\n\tx = 0; y = 0\n\tarc(t,x,y,40,13,270)\n\tcirclefill(t,x,y,40)\n\t\ndef main():\n\tw = turtle.Screen()\n\tw.setup(700, 700)\n\tw.clear()\n\tw.bgcolor(\"#000000\")\n\tt = turtle.Turtle()\n\ttwo2(t)\n\tw.exitonclick()\n\t\nif __name__ == '__main__':\n\tmain()\n\t\n\t\n\t\n\nif __name__ == '__main__':\n\tmain()\n\t\n'''\n#apt install python3-tk\n\t\n\n\nwn = turtle.Screen() # create a turtle\nt = turtle.Turtle()\nt.color('green') # set the color\nt.forward(50) # draw a green line of leng\nt.up() # lift up the tail\nt.forward(50) # move forward 50 without drawing\nt.right(90) # change direction to the right, left works too\nt.down() # put the tail down\nt.backward(100) # draw a green line 100 units long\nwn.exitonclick()\n'''\n","sub_path":"two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"418291684","text":"#!/usr/bin/env python3\nimport time\nimport sys\nimport os\nimport getpass\nfrom scp import SCPClient\nimport paramiko\ntry:\n import passd\nexcept:\n print(\"You do not have 'passd.py' file\")\n sys.exit()\ndronecrds='(drone coorinates when detected)'\ncameracrds='(camera number)'\nclass timer():\n def __init__(self):\n self.time=0\n self.timeline=0\n def start(self):\n self.time1=time.time()\n def stop(self):\n self.time2=time.time()\n self.timeline=round(self.time2-self.time1)\nclass DataCheck():\n def __init__(self):\n self.foo=0\n self.zp=0\n def dataq_ex(self,foo):\n self.foo=foo\n def zip_ex(self,zp):\n self.zp=zp\nclass Error(Exception):\n def __init__(self,mode):\n self.mode=mode\n Exception.__init__(self)\nclass st():\n def __init__(self,state):\n self.sta=state\n def pr(self):\n if self.sta==0:\n return('Idle/Charging')\n elif self.sta==1:\n return('Flying')\n def chgstate(self,state):\n self.sta=state\n def wasflying(self,boo):\n self.boo=boo\ndef info():\n l1='This program is a full simulator of gasoil monitoring system\\n'\n l2='It has a command prompt to accept commands\\n'\n l3='Here is the list of available commands:\\n'\n c1=\"'fly' launches the drone in air (ground usage only)\\n\"\n c2=\"'land' lands the drone and connects it and camera to the base (air usage only)\\n\"\n c3=\"'ch4' initiates emergency gas leak protocol: video that could've captured the leak is downloaded, zipped and sent to the server\\n\"\n c4=\"'download' command downloads files from camera to the computer\\n\"\n c5=\"'zip' zipps downloaded files and deletes them\\n\"\n c6=\"'send' sends zip file to the server and deletes it on the local machine\\n\"\n c7=\"'clear' is a simulation-only command to clear all files\\n\"\n c8=\"'whoami' prints logined user\\n\"\n c9=\"'logout' command is pretty clear\\n\"\n c10=\"'delete' deletes files from the camera without downloading them\\n\"\n c11=\"'ls' prints names of files in program directory\\n\"\n c11=\"'?' prints this message\\n\"\n c12=\"'exit' is the only way to exit this program\"\n print(l1+l2+l3+c1+c2+c3+c4+c5+c6+c7+c8+c9+c10+c11+c12)\ndef determ_number(file):\n #GOPR072\n file=file.replace('GOPR','')\n file=file.replace('.mp4','')\n while file.startswith('0'):\n file=file[1:]\n return file\ndef createSSHClient(server, port, user, password):\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(server, port, user, password)\n return client\ndef getfile():\n files=os.listdir()\n res=\"'\"\n for x in files:\n if '.zip' in x:\n res+=x+\"', '\"\n return(res[:len(res)-3])\ndef send(filename):\n try:\n serv=passd.server()\n port=22\n ssh = createSSHClient(serv[0], int(port), serv[1], serv[2])\n scp = SCPClient(ssh.get_transport())\n exec(\"scp.put(\"+filename+\")\")\n print('Sending successful')\n ssh.close()\n if os.system('rm *.zip')==0 and os.system('rm -rf camera/*')==0:\n print('Removing successful')\n else:\n print('Something bad happened while deleting')\n except EOFError:\n print('Sending failed')\ndef login(userlist):\n print('Authorisation required')\n while True:\n try:\n lg=input('Login: ')\n psw=getpass.getpass()\n if lg in userlist:\n if userlist[lg]==psw:\n active_user=(lg,psw)\n return active_user\n print('Wrong login/password combination')\n print()\n except KeyboardInterrupt:\n print()\n print('Login aborted')\n sys.exit()\n except EOFError:\n print()\n print('Login aborted')\n sys.exit()\n except GetPassWarning:\n print('Something really bad happened')\ndef cp(ch4=0):\n n=0\n i=0\n if ch4==1:\n CH4='CH4.'\n elif ch4==0:\n CH4=''\n dir=os.getcwd()\n source = dir+'/100GOPRO'\n target_dir = dir+'/camera'\n to=time.strftime('%Y%m%d%H%M')\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n if not os.path.exists(to):\n os.mkdir(target_dir+os.sep+CH4+to)\n print(\"Creating directory '{}''\".format(to))\n time.sleep(1)\n else:\n print(\"Directory '{}' already exists\".format(to))\n for x in os.listdir('100GOPRO'):\n if x.startswith('.'):\n os.system('rm 100GOPRO/'+x)\n files=os.listdir('100GOPRO')\n i=determ_number(files[0])\n while int(i)=10:\n zero='0'\n elif i>=100:\n zero=''\n else:\n zero='00'\n if not os.path.exists(home+'100GOPRO'):\n os.mkdir(home+'100GOPRO')\n if not os.path.exists(home+'100GOPRO/GOPR'+zero+str(i)+'.mp4'):\n os.system('touch '+home+'100GOPRO/GOPR'+zero+str(i)+'.mp4')\n ii+=1\ndef land(ch4=0):\n print('Performing landing...')\n time.sleep(5)\n print('Landed')\n dataq.dataq_ex(1)\n time.sleep(1)\n print('Connecting to the mainframe')\n time.sleep(1)\n print('Connected, ready to work')\n restart(0)\n return 0\ndef maxdate(files):\n maximum,num=0,-1\n for x in files:\n num+=1\n if x.startswith('CH4.'):\n realline=x[4:]\n if int(realline)>maximum:\n maximum=int(realline)\n maxnum=num\n res=(maximum,num)\n return(res)\ndef zip(report,check):\n qu=os.getcwd()+'/'\n if report==1:\n ch4='CH4.'\n last=1\n elif report==0:\n ch4=''\n last=0\n source=qu+'camera/'\n target_dir='archive/'\n today =time.strftime('%Y%m%d%H%M%S')\n target = ch4+today+'.zip'\n zip_command='zip'+' -r '+qu+target+' '+target_dir\n if last==1:\n for x in os.listdir(qu+'camera'):\n if x.startswith('.'):\n os.system('rm 100GOPRO/'+x)\n files=os.listdir(qu+'camera')\n maxdatum=maxdate(files)\n topath=qu+'camera/'+files[maxdatum[1]]+'/'\n elif last==0:\n topath=source+ch4\n cpc='cp'+' '+'-r '+topath+'*'+' '+target_dir\n print('(ZIP) Copy command is {}'.format(cpc))\n if not os.path.exists(qu+target_dir):\n os.mkdir(qu+target_dir)\n if os.system(cpc)==0:\n print('Succesfully copied files to zip directory')\n if report==1:\n cpc1='cp'+' '+qu+'Report'+' '+target_dir+'Report'\n if os.system(cpc1)==0:\n print('Successfully copied report')\n else:\n print('Error while copying report')\n elif report==0:\n pass\n print(\"Zip command is:\")\n print(zip_command)\n print(\"Running:\")\n if os.system(zip_command) == 0:\n print('Successfuly zipped')\n check.zip_ex(0)\n if report==1:\n rmc='rm -rf '+qu+target_dir+' '+qu+'Report'\n else:\n rmc='rm -rf '+qu+target_dir\n if os.system(rmc)==0:\n print('Deleting temp files Successful')\n else:\n print('Could not delete temp files')\n else:\n print('Zipping failed')\n else:\n print('Error while copying')\ndef CH4(state,timer1,check):\n if state.sta==0:\n print('Warning! CH4 leak detected!')\n time.sleep(2)\n print(\"I'm reporting this\")\n time.sleep(3)\n print('Downloading files from the Camera and zipping it')\n time.sleep(1)\n if dataq.foo==0:\n print('Determining camera...')\n time.sleep(3)\n print('Camera determined')\n if state.sta==1:\n date=time.strftime(\"%D %H:%M\", time.localtime(int(timer1.time1)+int(timer1.timeline)))\n else:\n date=time.strftime(\"%D %H:%M\",time.localtime(int(time.time())))\n time.sleep(2)\n print('Generating report...')\n if state.boo==1:\n coords=dronecrds\n elif state.boo==0:\n coords=cameracrds\n report(date,state,coords)\n time.sleep(3)\n print('File report created')\n print('Making a ZIP-archive...')\n cp(1)\n time.sleep(2)\n zip(1,check)\n print('Sending...')\n send(getfile())\n print('Successfully sent')\n print('Emergency situation handled. Disarming.')\n elif state.sta==1:\n timer1.stop()\n print('Warning! Arduino detected CH4 leak')\n print('Continuing the flight and then reporting after landing')\n state.wasflying(1)\n time.sleep(5)\n land(1)\n state.chgstate(0)\n CH4(state,timer1,check)\nuser=login(passd.userlist())\nstate=st(0)\ntimer1=timer()\ndataq=DataCheck()\ncommands=('fly','land','ch4','download','clear','send','whoami','logout','delete','ls','?','zip','exit')\nprint('Welcome to Gasoil Control System simulator!')\nprint('To begin, type your command below')\nwhile True:\n try:\n c=input('State: {}. >> '.format(state.pr())).replace(' ','')\n if c.isspace() or c=='':\n print('You have to input command')\n elif c.lower() not in commands:\n raise Error(-1)\n else:\n if c.lower()=='fly':\n if state.sta==1:\n raise Error(1)\n if dataq.foo==1:\n raise Error(2)\n else:\n state.chgstate(fly())\n elif c.lower()=='land':\n if state.sta==0:\n raise Error(0)\n state.chgstate(land())\n elif c.lower()=='ch4':\n if state.sta==0:\n state.wasflying(0)\n CH4(state,timer1,dataq)\n elif c.lower()=='exit':\n print('User interrupt. Simulation finished.')\n sys.exit()\n elif c.lower()=='download':\n if state.sta==1:\n raise Error(1)\n elif dataq.foo==1:\n cp()\n dataq.dataq_ex(0)\n dataq.zip_ex(1)\n else:\n raise Error(3)\n elif c.lower()=='clear':\n restart(2)\n dataq.dataq_ex(0)\n dataq.zip_ex(0)\n elif c.lower()=='delete':\n if state.sta==1:\n raise Error(1)\n if dataq.foo!=1:\n raise Error(4)\n cmd='rm '+os.getcwd()+'/100GOPRO/*'\n if os.system(cmd)==0:\n print('Files from camera deleted succesfully')\n else:\n print('Error while deleting files')\n elif c.lower()=='logout':\n print('Logging out...')\n print('Successfully logged out')\n user=login(passd.userlist())\n elif c.lower()=='whoami':\n print('Logged in as {}'.format(user[0]))\n elif c.lower()=='zip':\n if state.sta==1:\n raise Error(1)\n if int(dataq.zp)==0:\n raise Error(5)\n elif int(dataq.zp)==1:\n zip(0,dataq)\n elif c.lower()=='send':\n if state.sta==1:\n raise Error(1)\n fl=os.listdir()\n for z in fl:\n if '.zip' in z:\n break\n else:\n raise Error(6)\n print('Here comes magic')\n send(getfile())\n elif c.lower()=='ls':\n print(os.listdir())\n elif c=='?':\n info()\n else:\n print('Sorry, this feature is in development. Try again later')\n except Error as err:\n if err.mode==0:\n print(\"You can't do that while on ground\")\n elif err.mode==1:\n print(\"You can't do that while flying\")\n elif err.mode==-1:\n print(\"Wrong command. Print '?' for help\")\n elif err.mode==2:\n print('Warning: Data is not collected. Do you still want to fly? (y/n)')\n inp=input('>> ')\n if inp=='y':\n state.chgstate(fly())\n else:\n pass\n elif err.mode==3:\n print(\"You don't have any data to download\")\n elif err.mode==4:\n print(\"You don't have any data to delete\")\n elif err.mode==5:\n print(\"You don't have any data to zip\")\n elif err.mode==6:\n print(\"There is no data to send\")\n except KeyboardInterrupt:\n print()\n print(\"Do not use this to exit. Use 'Exit' command instead\")\n except EOFError:\n print()\n print(\"Nope, no way. Only 'Exit'\")\n print('Congratulations. You are now anarchist')\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":15024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"379842684","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 14 19:16:13 2018\n@author: Matthias Bischof, Jens Hambach\n\"\"\"\n\nimport anytree\nimport csv\n\n# Only supports one precedence constraint for each node\nclass CSVReader(object):\n # Reads out CSV files formatted as a matrices: one for costs, one for profits\n def __init__(self, cost_filename = 'cost.csv', profit_filename='profit.csv'):\n self.cost_filename = cost_filename\n self.profit_filename = profit_filename\n self.costs = self.open_csv(self.cost_filename)\n self.profits = self.open_csv(self.profit_filename)\n\n def open_csv(self, filename):\n i = 0\n lst = list()\n with open(filename, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=';')\n for row in csvreader:\n transf_row = [tup for tup in zip(row, range(len(row)))]\n lst.append((transf_row, i))\n i+=1\n return lst\n\n def create_tree(self):\n # Transforms the matrices into Tree nodes consisting of an index, cost, profit and the coordinates in the original csv\n i = 0\n root = TKPTreeNode(i, None, 0, 0, x=None, y=None)\n node_lst = [root]\n for cost_tup, profit_tup in zip(self.costs, self.profits):\n i += 1\n necessary_tup = [cost_tup[0].pop(), profit_tup[0].pop()]\n\t\t\t# define the precedence constraint as a tree node\n subproblem = TKPTreeNode(id=i, parent=root,\n cost=int(necessary_tup[0][0]), \n profit=int(necessary_tup[1][0]), \n x=len(cost_tup[0]), y=cost_tup[1])\n node_lst.append(subproblem)\n\t\t\t# define the other nodes in that row as children of the constraint above\n for cost_item, profit_item in zip(cost_tup[0], profit_tup[0]):\n i += 1\n node_lst.append(TKPTreeNode(id=i, parent=subproblem, cost=int(cost_item[0]), profit=int(profit_item[0]), x=cost_item[1], y=cost_tup[1]))\n return node_lst\n\n\nclass TKPTreeNode(anytree.Node):\n def __init__(self, id, parent, cost, profit, x, y):\n super().__init__(id, parent)\n self.cost = cost\n self.profit = profit\n self.set_profit_idx()\n self.set = 0\n self.set_all_cost()\n self.x = x\n self.y = y\n\n def set_profit_idx(self):\n # profit to cost ratio\n try:\n self.profit_index = self.profit / self.cost\n except ZeroDivisionError:\n self.profit_index = 0\n\n def set_all_cost(self):\n # Take the cost of the parent into the childs cost. Thus we can assure, that while \n # having two children with the same ratio, we take the one whose parent is already taken.\n try:\n self.cost = self.cost + self.parent.cost\n except:\n self.cost = 0\n\nclass Solver_dynamic(object):\n def __init__(self, tkp_root, bound):\n self.tree = tkp_root\n self.bound = bound\n self.weight = 0 \n self.items = list()\n self.solution_profit = 0\n\n def knapsack(self):\n # Puts in each iteration item with the highest ratio of profit to cost\n # into the solution set. When capacity is reached, it tries the next\n # worse item.\n while True:\n # Take all nodes that come into question\n all_nodes = [subnode for subnode in self.tree.descendants \n if subnode.set == 0 and subnode.profit > 0]\n if not all_nodes:\n # No nodes left\n break\n # Choose node with the best profit to cost ratio\n best_item = sorted(all_nodes, key=lambda x:x.profit_index)[-1]\n self.add_item(best_item)\n w = sum([node.cost for node in self.items])\n # Check that the weight does not exceed the limit\n if w > self.bound:\n # If the limit is exceeded, throw the item away\n self.delete_item(best_item)\n self.items.remove(best_item)\n else:\n # Adjust the solution weight\n self.weight = w\n self.solution_profit = sum([node.profit for node in self.items])\n return (self.weight, self.solution_profit, self.items)\n\n def add_item(self, item):\n # Adds an item to the solution\n item.set = 1\n self.items.append(item)\n # Check if the precedence constraint is satisfied\n if item.parent.set < 1:\n item.cost = item.cost - item.parent.cost\n self.items.append(item.parent)\n item.parent.set = 1\n for node in item.siblings:\n # Remove parent cost from children\n node.cost = node.cost - item.parent.cost\n node.set_profit_idx()\n\n def delete_item(self, item):\n lst = [node for node in item.siblings if node.set == 1]\n if not lst:\n item.parent.set = 0\n self.items.remove(item.parent)\n for node in item.siblings:\n # Add the weight of the constraint to each sibling of item \n # It makes profit to cost ratio worse\n node.cost = node.cost + node.parent.cost\n item.set = -1\n\nclass CSVWriter(object):\n # Writes the solution into a CSV file. Same format as the input files, \n #for each item being taken, set cell to 1, 0 otherwise\n def __init__(self, solution, tkp_root):\n self.solution_cost = solution[0]\n self.solution_profit = solution[1]\n self.node_lst = solution[2]\n self.tkp_root = tkp_root\n self.generate_matrix()\n\n def generate_matrix(self):\n # solution matrix \n self.matrix = [\n [0] +\n [0 for leaf in subproblem_node.children]\n for subproblem_node in tkp_root.children\n ]\n for n in self.node_lst:\n self.matrix[n.y][n.x] = 1\n\n def write_csv(self):\n with open('solution.csv', 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=';')\n for row in self.matrix:\n csvwriter.writerow(row)\n csvwriter.writerow(['Cost:', self.solution_cost])\n csvwriter.writerow(['Profit:', self.solution_profit])\n\nif __name__ == \"__main__\":\n\t# Define capacity value before running\n capacity_value = 50\n\n # Main\n csvread = CSVReader()\n node_lst = csvread.create_tree()\n tkp_root = node_lst[0]\n solver = Solver_dynamic(tkp_root, capacity_value)\n solution = solver.knapsack()\n print(\"Capacity value ; Used capacity value ; Profit\") \n print(capacity_value, \";\", solution[0], \";\", solution[1])\n csvwrite = CSVWriter(solution, tkp_root)\n csvwrite.write_csv()","sub_path":"tkp_dynamic.py","file_name":"tkp_dynamic.py","file_ext":"py","file_size_in_byte":6853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"376771038","text":"import json\nimport requests\nimport os.path\nimport time\nfrom random import *\n\ndef run_observer():\n try:\n while True:\n time.sleep(1)\n observer('medidas_tanques.txt')\n except KeyboardInterrupt:\n print(\"parei\")\n\ndef observer(filepath):\n if os.path.isfile(filepath):\n filename = filepath.split('.')\n file_copy = filename[0] + '_copy.txt'\n os.rename(\n filepath,\n file_copy\n )\n\n status_code = post_register_data(read_file(file_copy))\n if status_code == 200:\n delete_file(file_copy)\n\ndef delete_file(file_name):\n if os.path.isfile(file_name):\n os.remove(file_name)\n\ndef post_register_data(post_fields):\n url = 'http://169.254.150.98:3000/feeders/register_data'\n post_request = requests.post(url, json=post_fields)\n print(post_fields)\n return post_request.status_code\n\ndef read_file(file_name):\n keys = [\"network_code\",\n \"hora\",\n \"minute\",\n \"food_level\",\n \"battery_level\",\n \"error_code\",\n \"temperature\",\n \"ph\",\n \"turbidity\",\n \"conductivity\",\n \"oxigenium\"]\n json_data = {}\n array_data = []\n with open(file_name, \"r\") as file_node:\n data = file_node.readlines()\n\n for line in data:\n registers = line.split()\n\n for index, value in enumerate(registers):\n json_data[keys[index]] = value\n\n array_data.append(json_data)\n json_data = {}\n\n\n file_node.close()\n request_data = {'data':array_data}\n return request_data\n\n# ID HORA MINUTO NIVEL(0/100) BATERIA(0/100) CODE-ERROR TEMPERATURA PH TURBIDEZ CONDUTIVIDADE OXIGENIO\ndef generate_data():\n with open(\"medidas_tanques.txt\", \"w\") as outfile:\n for i in range(0, 100):\n outfile.write(str(randint(1, 3)) + ' '\n + str(randint(1, 24)) + ' '\n + str(randint(1, 60)) + ' '\n + str(randint(0, 100)) + ' '\n + str(randint(0, 100)) + ' '\n + str(randint(-1, 10)) + ' '\n + str(randint(-30, 50)) + ' '\n + str(randint(0, 14)) + ' '\n + str(randint(1, 100)) + ' '\n + str(randint(1, 100)) + ' '\n + str(randint(1, 100)) + '\\n')\n\ndef main():\n run_observer()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Projeto_crema_controle/send_post.py","file_name":"send_post.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"562299383","text":"import nibabel as nb\nimport numpy as np\nfrom pylab import cm\nfrom nipy.labs import viz\nimport pylab as plt\n\ndef plot_unwarping(mean_epi, mean_epi_uncorrected, figsize=(11.7,8.3),):\n \n fig = plt.figure(figsize=figsize)\n \n ax = plt.subplot(2,1,1)\n \n before_unwarp_data = nb.load(mean_epi_uncorrected).get_data()\n before_unwarp_affine = nb.load(mean_epi_uncorrected).get_affine()\n \n slicer = viz.plot_anat(np.asarray(before_unwarp_data), np.asarray(before_unwarp_affine), black_bg=True,\n cmap = cm.Greys_r, # @UndefinedVariable\n cut_coords = (-8,0,8),\n slicer='x',\n figure = fig,\n axes = ax,\n draw_cross = False)\n \n ax = plt.subplot(2,1,2)\n \n unwarped_data = nb.load(mean_epi).get_data()\n unwarped_affine = nb.load(mean_epi).get_affine()\n \n slicer = viz.plot_anat(np.asarray(unwarped_data), np.asarray(unwarped_affine), black_bg=True,\n cmap = cm.Greys_r, # @UndefinedVariable\n cut_coords = (-8,0,8),\n slicer='x',\n figure = fig,\n axes = ax,\n draw_cross = False)\n \n fig.suptitle('fieldmap correction', fontsize='14')\n \n return fig","sub_path":"nipy1.4/reports/unwarp.py","file_name":"unwarp.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585715334","text":"\"\"\"Contains function to plot similarity rates over the course of the seasons.\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\nimport pandas as pd\n\nfrom . import tools\n\n\ndef visualize_rates_over_time(\n rates_df: pd.DataFrame,\n league_label: str,\n min_season: int,\n max_season: int,\n rounds_list: list[int] = [1, 9, 19, 27, 37],\n tolerance: int = 1,\n) -> None:\n \"\"\"Create a line plot for the trend of similarity rates at fixed rounds\n across multiple seasons\"\"\"\n _, ax = tools.initialize_plot(1)\n\n # Adding title and subtitle\n ttl = f\"Leaderboard similarity rate with tolerance of {tolerance} over different seasons for a sample of rounds\"\n plt.suptitle(ttl, y=0.94, ha=\"center\", fontsize=18, weight=700)\n sub = tools.league_seasons_string(league_label, min_season, max_season)\n plt.title(sub, y=1, x=0.5, fontsize=14, ha=\"center\")\n\n # Customizing y axis style\n ax.set_yticks([x / 10 for x in range(1, 11)])\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))\n\n # Adding axes titles\n tools.set_y_label(ax, \"Similarity rate compared with season's final leaderboard\")\n tools.set_x_label(ax, \"Season starting year\")\n\n # Adding grid\n tools.set_grid(ax)\n\n for round_ in rounds_list:\n filt = (rates_df[\"Tolerance\"] == tolerance) & (rates_df[\"Round\"] == round_)\n season = rates_df.loc[filt, \"Season\"]\n rate = rates_df.loc[filt, \"Rate\"]\n ax.plot(season, rate, label=round_, marker=\".\", markersize=15, linewidth=1)\n\n # Adding legend\n tools.add_legend(\"Rounds\")\n\n file_name = f\"Similarity Rate over time_{league_label}_{tolerance}.png\"\n tools.save_file(file_name)\n","sub_path":"data_visualization/rates_over_time.py","file_name":"rates_over_time.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"39881178","text":"\n\nfrom xai.brain.wordbase.nouns._flourish import _FLOURISH\n\n#calss header\nclass _FLOURISHED(_FLOURISH, ):\n\tdef __init__(self,): \n\t\t_FLOURISH.__init__(self)\n\t\tself.name = \"FLOURISHED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"flourish\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_flourished.py","file_name":"_flourished.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"577285794","text":"\"\"\"\nhttp://dojopuzzles.com/problemas/exibe/numeros-romanos/\nBasic roman numbers calculator.\n\nMax number supported currently is MMMCMXCIX (3999)\n\nrun tests with:\npython -m unittest roman.py\n\n\"\"\"\nimport unittest\n\nROMAN_NUMBERS_MAP = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\nROMAN_NUMBERS_LIST_ASC = ['I', 'V', 'X', 'L', 'C', 'D', 'M']\n\nROMAN_NUMBERS = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']\nARABIC_NUMBERS = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n\n\ndef _roman_lower_than(r1, r2):\n return ROMAN_NUMBERS_LIST_ASC.index(r1) < ROMAN_NUMBERS_LIST_ASC.index(r2)\n\ndef to_roman(n):\n converted_result = ''\n n_cpy = n\n\n for i, r in enumerate(ROMAN_NUMBERS):\n r_value = ARABIC_NUMBERS[i]\n\n print('r_value=' + str(r_value))\n\n div_result = n_cpy // r_value\n\n print('div_result=' + str(div_result))\n\n if div_result > 0:\n converted_result += r * div_result\n\n print('converted_result='+converted_result)\n # Remove number from current:\n n_cpy -= (r_value * div_result)\n\n return converted_result\n\n\ndef from_roman(r):\n \"\"\"From Roman to number. Assumes the input is a roman number.\n Big numbers are not handled. Ex:\n ___\n XXV ->> 25.000\n\n \"\"\"\n #If only a single number, return from mapping\n if len(r) == 1:\n return ROMAN_NUMBERS_MAP[r]\n\n #Identify where subtractions are required\n subtract_on_index = []\n indexes_to_ignore = []\n idx = 1\n prev = r[0]\n while idx < len(r):\n c = r[idx]\n if _roman_lower_than(prev, c):\n subtract_on_index.append(idx)\n indexes_to_ignore.append(idx)\n indexes_to_ignore.append(idx-1)\n\n prev = c\n idx += 1\n\n items_to_sum_up = None\n\n #If no subtract is needed, simply sum all the numbers\n if not subtract_on_index:\n items_to_sum_up = [ROMAN_NUMBERS_MAP[itm] for itm in r]\n else:\n items_to_sum_up = [ROMAN_NUMBERS_MAP[c] for i, c in enumerate(r) if i not in indexes_to_ignore]\n\n for i in subtract_on_index:\n itm1 = ROMAN_NUMBERS_MAP[r[i]]\n itm2 = ROMAN_NUMBERS_MAP[r[i-1]]\n items_to_sum_up.append(itm1-itm2)\n\n #Sum of all numbers already converted\n return sum(items_to_sum_up)\n\n\nclass TestFromRoman(unittest.TestCase):\n#class TestFromRoman:\n\n def generic_test(self, test_scenarios):\n \"\"\" test_scenarios: tuple where the first item is the input and the 2nd is the expectation\"\"\"\n for r, expectation in test_scenarios:\n with self.subTest():\n self.assertEqual(expectation, from_roman(r))\n\n\n def test_basic_numbers(self):\n \"\"\"\n Checks the basic roman numbers\n \"\"\"\n self.generic_test([('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)])\n\n def test_numbers_requires_add(self):\n \"\"\"\n Checks cases where the basic roman numbers in sequence are summed up\n \"\"\"\n self.generic_test([('VIII', 8), ('LXII', 62), ('CLVIII', 158), ('MCXX', 1120)])\n\n\n def test_numbers_requires_subtract(self):\n \"\"\"\n Checks cases where the basic roman numbers in sequence are subtracted\n \"\"\"\n self.generic_test([('IV', 4), ('IX', 9), ('XC', 90), ('XCIX', 99)])\n\n def test_numbers(self):\n \"\"\" Generic tests with other numbers\"\"\"\n self.generic_test([('III', 3), ('XVII', 17), ('XXXVIII', 38), ('VIII', 8), ('XLV', 45),\n ('XLVI', 46), ('XLVII', 47), ('CDLXXXIX', 489), ('MMMCMXCIX',3999)])\n\n\nclass TestToRoman(unittest.TestCase):\n\n def generic_test(self, test_scenarios):\n \"\"\" test_scenarios: tuple where the first item is the input and the 2nd is the expectation\"\"\"\n for expectation, n in test_scenarios:\n with self.subTest():\n self.assertEqual(expectation, to_roman(n))\n\n def test_basic(self):\n self.assertEqual('M', to_roman(1000))\n self.assertEqual('MM', to_roman(2000))\n self.assertEqual('MMM',to_roman(3000))\n\n def test_non_multiple(self):\n self.assertEqual('VIII', to_roman(8))\n #Strugling with \"9\"\n self.assertEqual('IX', to_roman(9))\n\n def test_numbers(self):\n \"\"\" Generic tests with other numbers\"\"\"\n self.generic_test([('III', 3), ('XVII', 17), ('XXXVIII', 38), ('VIII', 8), ('XLV', 45),\n ('XLVI', 46), ('XLVII', 47), ('CDLXXXIX', 489), ('MMMCMXCIX',3999)])\n\n","sub_path":"roman.py","file_name":"roman.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"426143280","text":"#!python3\n\nimport bs4,requests,webbrowser,sys\nfrom bs4 import BeautifulSoup\n\nprint('Downloading page...')\n\nres = requests.get('https://www.xvideos.com/?k='+' '.join(sys.argv[1:]))\nres.raise_for_status()\n\nsoup = BeautifulSoup(res.text,('html.parser'))\nlinks = soup.select('p > a')\n\nprint(links[1])\n\n\nnumopen = min(len(links),4)\n\nfor i in range (numopen):\n webbrowser.open('https://www.xvideos.com'+links[i].get('href'))\n","sub_path":"WebScrapping/hubSearch.py","file_name":"hubSearch.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"266767373","text":"import tkinter as tk \r\nfrom tkinter import ttk \r\nfrom tkinter.messagebox import showinfo \r\n\r\n# Callback & functions\r\n#------------------------------------------\r\ndef clear_display_area():\r\n for widget in display_area.grid_slaves():\r\n if int(widget.grid_info()[\"row\"]) == 0:\r\n widget.grid_forget() \r\n \r\n \r\ndef display_button(active_notebook, tab_no):\r\n btn = ttk.Button(display_area, text=active_notebook +' - Tab '+ tab_no,\r\n command= lambda: showinfo(\"Tab Display\", \"Tab: \" + tab_no))\r\n btn.grid(column=0, row=0, padx=8, pady=8) \r\n\r\n\r\ndef notebook_callback(event):\r\n clear_display_area()\r\n \r\n current_notebook = str(event.widget)\r\n tab_no = str(event.widget.index(\"current\") + 1) \r\n \r\n if current_notebook.endswith('notebook'):\r\n active_notebook = 'Notebook 1'\r\n elif current_notebook.endswith('notebook2'):\r\n active_notebook = 'Notebook 2'\r\n else:\r\n active_notebook = ''\r\n \r\n display_button(active_notebook, tab_no)\r\n \r\n \r\n# GUI Creation\r\n#------------------------------------------\r\ngui = tk.Tk() \r\ngui.title(\"GUI\")\r\n\r\n\r\ntabs_frame = ttk.Frame(gui)\r\ntabs_frame.grid(row=0, column=0, sticky='W')\r\n\r\ndisplay_area = ttk.Labelframe(gui, text=' Tab Display Area ')\r\ndisplay_area.grid(row=1, column=0, sticky='WE', padx=5, pady=5)\r\n\r\ndisplay_area_label = tk.Label(display_area, text=\"\", height=2)\r\ndisplay_area_label.grid(column=0, row=0)\r\n\r\nnote1 = ttk.Notebook(tabs_frame)\r\nnote1.grid(row=0, column=0)\r\n\r\nnote2 = ttk.Notebook(tabs_frame)\r\nnote2.grid(row=1, column=0)\r\n\r\n# create and add tabs to Notebooks\r\nfor tab_no in range(5):\r\n tab1 = ttk.Frame(note1) # Create a tab for notebook 1\r\n tab2 = ttk.Frame(note2) # Create a tab for notebook 2\r\n note1.add(tab1, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 1\r\n note2.add(tab2, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 2\r\n\r\n# bind click-events to Notebooks \r\nnote1.bind(\"\", notebook_callback)\r\nnote2.bind(\"\", notebook_callback)\r\n\r\n\r\ndisplay_button('Notebook 1', '1') # mimic tab click event\r\n\r\n\r\ngui.mainloop() \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Notebooks/Notebooks_4_mimic_event.py","file_name":"Notebooks_4_mimic_event.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253679755","text":"#coding: utf-8\nimport re\nnum = []\ni = 0\nfor a in range(0,100):\n num.append(a)\n\nf = open('num.txt','w')\n#try:\n#for p in range(0,10000):\nwhile i < 100:\n f.write(str(num[i]))\n#except:\n #print('rua')\n i+=1\nf.close()\nprint('ok')\nbook= open('num.txt')\nout = book.read()\nm = re.findall('\\d+',out)\nif m:\n print(m)\n","sub_path":"3.25.py","file_name":"3.25.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"429957792","text":"# 708. Insert into a Sorted Circular Linked List\n# 2021/12/01\n# daily special\n\n# Runtime: 24 ms, faster than 99.75% of Python3 online submissions for Insert into a Sorted Circular Linked List.\n# Memory Usage: 15 MB, less than 69.07% of Python3 online submissions for Insert into a Sorted Circular Linked List.\n\n\n# dont' have a clear idea of this problem\n# write the solution based on the discussion on the official solution\n# case 1: find a node such that prev <= insert <= curr\n# case 2: insert value is either too big or too small, insert it to the tail\n# case 3: all nodes have equal values\n# case 4: single node\n\n\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\n\nclass Solution:\n def insert(self, head: 'Node', insertVal: int) -> 'Node':\n if not head:\n new_node = Node(insertVal)\n new_node.next = new_node\n return new_node\n prev, curr = head, head.next\n back = None\n while curr != head:\n if curr.val < prev.val:\n back = prev\n front = curr\n\n if prev.val <= insertVal <= curr.val:\n new_node = Node(insertVal)\n prev.next = new_node\n new_node.next = curr\n return head\n prev = curr\n curr = curr.next\n if prev.val <= insertVal <= curr.val:\n new_node = Node(insertVal)\n prev.next = new_node\n new_node.next = curr\n return head\n if back:\n new_node = Node(insertVal)\n back.next = new_node\n new_node.next = front\n return head\n new_node = Node(insertVal)\n prev.next = new_node\n new_node.next = curr\n return head\n\n\n\n","sub_path":"0708. Insert into a Sorted Circular Linked List.py","file_name":"0708. Insert into a Sorted Circular Linked List.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"256213927","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @return a ListNode\n\tdef sortList(self, head):\n\t\tif head==None or head.next==None:\n\t\t\treturn head\n\t\t[n1,n2]=[head,head]\n\t\tcount=0\n\t\twhile n1.next!=None:\n\t\t\tcount+=1\n\t\t\tn1=n1.next\n\t\t\tif count%2==0:\n\t\t\t\tn2=n2.next\n\t\tn1=n2.next\n\t\tn2.next=None\n\n\t\treturn self.merge(self.sortList(head), self.sortList(n1))\n\tdef merge(self, n1, n2):\n\t\tif n1==None:\n\t\t\treturn n2\n\t\tif n2==None:\n\t\t\treturn n1\n\n\t\tdummy=ListNode(0)\n\t\ttail=dummy\n\t\twhile n1!=None or n2!=None:\n\t\t\tif n1==None:\n\t\t\t\ttail.next=n2\n\t\t\t\tbreak\n\t\t\telif n2==None:\n\t\t\t\ttail.next=n1\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tif n1.val<=n2.val:\n\t\t\t\t\ttail.next=n1\n\t\t\t\t\ttail=n1\n\t\t\t\t\tn1=n1.next\n\t\t\t\telse:\n\t\t\t\t\ttail.next=n2\n\t\t\t\t\ttail=n2\n\t\t\t\t\tn2=n2.next\n\t\t\t\ttail.next=None\n\t\treturn dummy.next\n","sub_path":"code/SortList.py","file_name":"SortList.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"322067408","text":"total_test=int(input(\"Enter the total number of test case: \"))\r\nfor i in range(total_test):\r\n inp_string=input(\"Enter the input string: \")\r\n digit=[]\r\n for i in inp_string.split():\r\n if i.isdigit()==True:\r\n digit.append(i)\r\n max_digit=digit[0] \r\n for i in digit:\r\n if i>max_digit:\r\n max_digit=i \r\n print(max_digit)","sub_path":"max_digit_in_string.py","file_name":"max_digit_in_string.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"125240433","text":"# Votre programme 'lir'a dabord un entier représentant le nombre de montées\n# et descentes que vous avez réalisées. \n# Pour chaque montée ou descente,\n\n# il faut ensuite 'lir'e un entier représentant la variation daltitude, \n# cet entier étant strictement positif dans le cas dune montée et strictement \n# négatif dans le cas dune descente (il ny a rien à compter pour les tronçons \n# qui sont bien à plat). Votre programme devra afficher laltitude totale montée puis \n# laltitude totale descendue (ces deux nombres sont positifs).\n\n\nn = int(input())\nc1=0\nc2=0\nfor loop in range(n):\n v = int(input())\n if v> 0 :\n c1 += v\n else:\n c2 += v\nprint(c1)\nprint(abs(c2))","sub_path":"france-IOI-algorithms/Level_1/calc_denivele.py","file_name":"calc_denivele.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"129464424","text":"import stripe\nimport json\n\n\n# Get the credit card details submitted by the form\n# token = request.POST['stripeToken']\n\nstripe.api_key = 'sk_test_QCfl8BRc7BotPlqEMV0KgWHL'\n\n\nclass Stripe(object):\n\n def __init__(self, sandbox=True):\n self.sanbox = sandbox\n\n def create_customer(self, user, token):\n customer = stripe.Customer.create(\n source=token,\n description='User',\n email='email@sofadoc.com')\n print(customer)\n print('----')\n print(json.dumps(customer))\n\n def charge(self, user, amount, description, currency='eur'):\n stripe.Charge.create(\n amount=int(amount * 100),\n currency=currency,\n customer=user.id)\n","sub_path":"sofadoc/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"391576130","text":"import shlex, subprocess,sys, math, argparse, time\nfrom sympy import *\n \ndef EscribeArchivo(eq):\n f = open('plot.dat', 'w')\n arg = \"plot(\"+eq+\") \\n\"\n f.write(arg)\n f.close()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--function\", help = \"Definir funcion\")\nparser.add_argument(\"-s\", \"--starting\", help = \"Punto inicial\", type = float, default = 0.0)\nparser.add_argument(\"-p\", \"--precision\", help = \"Precision\", type = float, default = 5*10**(-6))\nargs = parser.parse_args()\n \nsym_x = Symbol('x')\n\ntry:\n fx = S(args.function)\nexcept:\n sys.exit('Error al convertir expresion.')\n \n\ntry:\n dfdx = diff(fx, Symbol('x'))\nexcept:\n sys.exit('Error al derivar.')\n \n\ne = 1\nx0 = args.starting\niterations = 0\n \nprint(\"\\n\")\nwhile ( e > args.precision ):\n # nueva estimación de raíz\n try: \n r = x0 - fx.subs({sym_x : x0})/dfdx.subs({sym_x : x0})\n except ZeroDivisionError:\n print (\"La derivada de la función en cero, se termina el ciclo.\")\n sys.exit()\n # Error Relativo\n e = abs((r - x0)/r)\n print(\"Iteracion\",iterations,\"Raiz: \",r+1,\"Error: \",e,\"\\n\")\n iterations += 1\n x0 = r\n \n \nprint ('Funcion: ',fx)\n#print(fx)\nprint ('Derivada: ',dfdx)\n#print(dfdx)\nprint (\"Raiz:\",r+1)\n#print (\"Valor de la funcion en la raiz:\",(fx.subs({sym_x : r})))\nEscribeArchivo(args.function)\nprint(\"\\nGráfica de la función introducida \")\nsys = \"gnuplot -p -e \\\"load 'plot.dat\\'\"\nd = subprocess.Popen(sys,shell=False)\n","sub_path":"Rapson.py","file_name":"Rapson.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"386653114","text":"#----------------------------------------------------------------\r\n# Introdução a Programação de Computadores - IPC\r\n# Universidade do Estado do Amazonas - UEA\r\n# Prof. Jucimar Jr\r\n#\r\n# Evandro Padilha Barroso Filho 1715310009\r\n# Gabriel Barroso da Silva Lima 1715310011\r\n# Frederico Victor Alfaia Rodrigues 1515200030\r\n# Felipe Eduardo Silva de Almeida 1715310031\r\n# Felipe Guerreiro De Mello 1315120052\r\n# Silas castro de Mendonça 1715310066\r\n#\r\n# Escreva um algoritmo em PORTUGOL que determine se dois valores inteiros e\r\n# positivos A e B são primos entre si. (dois números inteiros são ditos primos entre si,\r\n# caso não exista divisor comum aos dois números). \r\n#----------------------------------------------------------------\r\n\r\nnumber_a = float(input(\"Digite um numero: \"))\r\nnumber_b = float(input(\"Digite outro numero: \"))\r\nc = 1\r\nsummation = 0\r\nwhile c <= number_a and c <= number_b:\r\n if (number_a % c == 0) and (number_b % c == 0):\r\n summation = summation + 1\r\n c += 1\r\nif summation <= 1:\r\n print(\"São primos entre si\")\r\nelse:\r\n print(\"Não são primos entre si\")\r\n","sub_path":"lista05/lista05_lista02_questao35.py","file_name":"lista05_lista02_questao35.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"136438438","text":"# -*- coding: utf-8 -*-\n\nimport datetime\n\nfrom odoo import models, fields, api, exceptions\n\n\nclass napataPresentation(models.Model):\n _name = 'napata.presentation'\n _description = 'information presentation'\n name = fields.Char(string=\"Full name\", readonly=True)\n college_id = fields.Many2one('napata.collage', string='College',\n ondelete='cascade')\n prenent_code = fields.Char(string='prenent code')\n is_done = fields.Boolean(string=\"Can apply\")\n # get student name\n\n first_name = fields.Char(string='First Name')\n second_name = fields.Char(string='Second Name')\n third_name = fields.Char(string='Third Name')\n forth_name = fields.Char(string='Fourth Name')\n\n\n # end of name field\n nationality= fields.Many2one('res.country',\n string=\"Nationality\")\n # nationality= fields.Char(straing='Nationalities')\n idtype=fields.Selection([\n ('number', 'National number'),\n ('card', 'National card'),\n ('passport', 'Passport'),\n ('other', 'Other')\n\n ],string=\"ID Tyep\")\n id_number = fields.Char(string=\"The National Number\")\n phone_1=fields.Integer(string=\"Phone Number\")\n phone_2=fields.Integer(string=\"watsapp\")\n \n Certificate = fields.Selection([\n ('sudanese', 'Sudanese'),\n ('arabic', 'Arabic'),\n ('foreign', 'foreign'),\n ('other', 'Other')\n\n ],string=\"Certificate Tyep\")\n form = fields.Char(string=\"Form Number\")\n\n #\n # abut Us\n facebook=fields.Boolean(string=\"Face Book\")\n website=fields.Boolean(string=\"Web Site\")\n newspaper=fields.Boolean(string=\"Newspaper\")\n tv=fields.Boolean(string=\"TV\")\n radio=fields.Boolean(string=\"Radio\")\n admission_book = fields.Boolean(string=\"Admission Book\")\n\n course = fields.Selection([\n ('Scientific', 'Scientific'),\n ('literary', 'literary')],string=\"The course\")\n sit_number = fields.Integer(string=\"Sitting Number\")\n ratio=fields.Float(string=\"The ratio\")\n # form_number= fields.Char(string='Form Number',\n # required=True, copy=False, readonly=True, index=True, default=lambda self: _('New'))\n exm_year= fields.Char(string=\" exm_year\" , default=(lambda self: str(datetime.datetime.now().year-1)+\" / \"+str(datetime.datetime.now().year) ))\n\n provider=fields.Char(string=\"Applicant Name\")\n job=fields.Char(string=\"job\")\n\n\n\n\n\n\n\n\n National_card=fields.Binary(string=\"National card\")\n School_card=fields.Binary(string=\"High School Certificate\")\n phone3=fields.Integer(string=\"Phone Number\")\n parent= fields.Many2one('napata.parent',\n ondelete='cascade')\n\n\n\n main=fields.Many2one(\"napata.program\",ondelete=\"cascade\",string=\"Main Desire\")\n sub=fields.Many2many(\"napata.program\",ondelete=\"cascade\",string=\"Sub Desire\")\n preType2=fields.Char(string=\"PresntaionType\")\n\n\n fees = fields.Char(straing='Fees')\n data = fields.Char('Date current action', default=(lambda self: datetime.datetime.now().year))\n admission_ids = fields.Char(string='admission_ids')\n register = fields.Char(string='register')\n #\n pay_date = fields.Char()\n\n\n\n attendees_count = fields.Integer(\n string=\"Attendees count\", compute='_get_attendees_count', store=True)\n # Degree Holders\n submet=fields.Char(straing='Ok',default=(\"No hierarchy position.This employee has no manager or subordinate.In order to get an organigram, set a manager and save the record\"))\n signup_valid = fields.Boolean(string='Submet')\n state = fields.Selection([\n ('draft', 'Draft'),\n ('done', 'done'),\n ], string='Status', default=\"draft\", readonly=True)\n # about us desar\n @api.constrains('main', 'sub')\n def _check_instructor_not_in_attendees(self):\n for r in self:\n if r.main and r.main in r.sub:\n raise exceptions.ValidationError(\"This desire has been chosen as the main desire that cannot be chosen within the sub-desire\")\n # about us validation\n @api.constrains('facebook',\"website\",\"newspaper\",\"tv\",\"radio\",\"admission_book\")\n def _check_validation(self):\n is_valid=False\n\n if self.facebook == True:\n is_valid = True\n elif self.website == True:\n is_valid = True\n elif self.newspaper == True:\n is_valid = True\n elif self.tv == True:\n is_valid = True\n elif self.radio == True:\n is_valid = True\n elif self.admission_book == True:\n is_valid = True\n if is_valid==False:\n raise exceptions.ValidationError(\"not valid\")\n # Submet\n @api.constrains(\"signup_valid\")\n def _check_submet(self):\n if self.signup_valid == False:\n raise exceptions.ValidationError(\"not signup valid\")\n\n # code Serial auto no\n\n\n\n\n\n def action_confirm(self,vals):\n self.env['napata.register'].write({\n\n 'name': self.name,\n 'first_name': self.first_name,\n 'second_name': self.second_name,\n 'third_name': self.third_name,\n 'forth_name': self.forth_name,\n 'college_id': self.college_id.id,\n 'nationality': self.nationality.name,\n 'type_id': self.idtype,\n 'number_ids': self.id_number,\n 'phone1': self.phone,\n 'phone2': self.phone_2,\n # parint provider_name\n 'provider_name': self.provider,\n 'parent': self.parent.name,\n 'job': self.job,\n 'phone3': self.phone3,\n # fees\n 'accept_type': self.preType2,\n 'total_fees': self.fees,\n # study information\n 'cource': self.course,\n 'ratio': self.ratio,\n 'main_desires': self.main.name,\n # 'athoer_desires':self.name,\n 'siting_number': self.sit_number,\n 'form_number': self.form,\n 'pay_date': self.pay_date,\n 'admission_ids': self.admission_ids,\n\n })\n res = super(napataPresentation, self).write(vals)\n return res\n\n # @api.model\n # def create(self, vals):\n # if vals.get('form_number', _('New')) == _('New'):\n # vals['form_number'] = self.env['ir.sequence'].next_by_code('napata_register.presentation.sequence') or _('New')\n # result = super(napataPresentation, self).create(vals)\n # return result\n\n\n \n\n\n\n \n \n ","sub_path":"napata_register/models/presentation.py","file_name":"presentation.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"481110958","text":"import numpy as np\nimport queue\n\n\ndef process_configuration(configs, words, stats, u, b, t):\n try:\n while not configs.empty():\n l = configs.get(False)\n x = np.zeros(shape=(len(words), 3))\n for i in range(len(words)):\n x[i] = [u(words[i]), b(words[i - 1], words[i]), t(words[i - 2], words[i - 1], words[i])]\n total_sum = np.sum(np.matmul(x, l))\n stats.put((l, total_sum))\n\n except queue.Empty:\n _ = None # Do nothing\n","sub_path":"pythonScripts/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"20479592","text":"import logging\nimport os\n\nfrom pyramid.config import Configurator\nfrom pyramid.httpexceptions import (\n HTTPOk,\n HTTPNotFound,\n HTTPNoContent,\n HTTPCreated,\n HTTPBadRequest,\n)\nfrom cornice import Service\nfrom cornice.validators import colander_body_validator\nfrom cornice.service import get_services\nimport colander\nfrom slugify import slugify\nfrom cornice_swagger import CorniceSwagger\n\nfrom . import services\nfrom . import adapters\nfrom . import exceptions\n\nLOGGER = logging.getLogger(__name__)\n\nswagger = Service(\n name=\"Kernel API\", path=\"/__api__\", description=\"Kernel API documentation\"\n)\n\ndocuments = Service(\n name=\"documents\",\n path=\"/documents/{document_id}\",\n description=\"Get document at its latest version.\",\n)\n\nmanifest = Service(\n name=\"manifest\",\n path=\"/documents/{document_id}/manifest\",\n description=\"Get the document's manifest.\",\n)\n\nassets_list = Service(\n name=\"assets_list\",\n path=\"/documents/{document_id}/assets\",\n description=\"Get the document's assets.\",\n)\n\nassets = Service(\n name=\"assets\",\n path=\"/documents/{document_id}/assets/{asset_slug}\",\n description=\"Set the URL for an document's asset.\",\n)\n\ndiff = Service(\n name=\"diff\",\n path=\"/documents/{document_id}/diff\",\n description=\"Compare two versions of the same document.\",\n)\n\nfront = Service(\n name=\"front\",\n path=\"/documents/{document_id}/front\",\n description=\"Front-matter of the document in a normalized schema.\",\n)\n\nbundles = Service(\n name=\"bundles\",\n path=\"/bundles/{bundle_id}\",\n description=\"Get documents bundle data.\",\n)\n\nchanges = Service(\n name=\"changes\", path=\"/changes\", description=\"Get changes from all entities\"\n)\n\njournals = Service(\n name=\"journals\",\n path=\"/journals/{journal_id}\",\n description=\"Register and retrieve journals' endpoint\",\n)\n\njournal_issues = Service(\n name=\"journal_issues\",\n path=\"/journals/{journal_id}/issues\",\n description=\"Issue addition and insertion to journal.\",\n)\n\njournals_aop = Service(\n name=\"journals_aop\",\n path=\"/journals/{journal_id}/aop\",\n description=\"Manipulate ahead of print in journal\",\n)\n\n\nclass ResponseSchema(colander.MappingSchema):\n body = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass Asset(colander.MappingSchema):\n asset_id = colander.SchemaNode(colander.String())\n asset_url = colander.SchemaNode(colander.String(), validator=colander.url)\n\n\nclass Assets(colander.SequenceSchema):\n asset = Asset()\n\n\nclass RegisterDocumentSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para registro de documentos.\n \"\"\"\n\n data = colander.SchemaNode(colander.String(), validator=colander.url)\n assets = Assets()\n\n\nclass QueryDiffDocumentSchema(colander.MappingSchema):\n \"\"\"Representa os parâmetros de querystring do schema DiffDocument.\n \"\"\"\n\n from_when = colander.SchemaNode(colander.String(), missing=colander.drop)\n to_when = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass DiffDocumentSchema(colander.MappingSchema):\n \"\"\"Representa a diferença entre estados do documento\n \"\"\"\n\n data = colander.SchemaNode(colander.String(), missing=colander.drop)\n querystring = QueryDiffDocumentSchema()\n\n\nclass AssetSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para registro de ativos do documento.\n \"\"\"\n\n asset_url = colander.SchemaNode(colander.String(), validator=colander.url)\n\n\nclass JournalSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para registro de periódicos.\n \"\"\"\n\n title = colander.SchemaNode(colander.String(), missing=colander.drop)\n mission = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n title_iso = colander.SchemaNode(colander.String(), missing=colander.drop)\n short_title = colander.SchemaNode(colander.String(), missing=colander.drop)\n title_slug = colander.SchemaNode(colander.String(), missing=colander.drop)\n acronym = colander.SchemaNode(colander.String(), missing=colander.drop)\n scielo_issn = colander.SchemaNode(colander.String(), missing=colander.drop)\n print_issn = colander.SchemaNode(colander.String(), missing=colander.drop)\n electronic_issn = colander.SchemaNode(colander.String(), missing=colander.drop)\n status = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n\n @colander.instantiate(missing=colander.drop)\n class subject_areas(colander.SequenceSchema):\n name = colander.SchemaNode(colander.String())\n\n @colander.instantiate(missing=colander.drop)\n class sponsors(colander.SequenceSchema):\n sponsor = colander.SchemaNode(colander.Mapping(unknown=\"preserve\"))\n\n metrics = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n\n @colander.instantiate(missing=colander.drop)\n class subject_categories(colander.SequenceSchema):\n name = colander.SchemaNode(colander.String())\n\n @colander.instantiate(missing=colander.drop)\n class institution_responsible_for(colander.SequenceSchema):\n name = colander.SchemaNode(colander.String())\n\n online_submission_url = colander.SchemaNode(\n colander.String(), validator=colander.url, missing=colander.drop\n )\n next_journal = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n logo_url = colander.SchemaNode(\n colander.String(), validator=colander.url, missing=colander.drop\n )\n previous_journal = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n contact = colander.SchemaNode(\n colander.Mapping(unknown=\"preserve\"), missing=colander.drop\n )\n\n\nclass JournalAOPSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para a atualização de AOP em periódico\n \"\"\"\n\n aop = colander.SchemaNode(colander.String())\n\n\nclass DocumentsBundleSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para registro de Documents Bundle.\"\"\"\n\n publication_year = colander.SchemaNode(colander.Int(), missing=colander.drop)\n supplement = colander.SchemaNode(colander.String(), missing=colander.drop)\n volume = colander.SchemaNode(colander.String(), missing=colander.drop)\n number = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n @colander.instantiate(missing=colander.drop)\n class titles(colander.SequenceSchema):\n @colander.instantiate()\n class title(colander.MappingSchema):\n language = colander.SchemaNode(\n colander.String(), validator=colander.Length(2, 2)\n )\n title = colander.SchemaNode(colander.String(), validator=colander.Length(1))\n\n\nclass QueryChangeSchema(colander.MappingSchema):\n \"\"\"Representa os parâmetros de querystring do schema change.\n \"\"\"\n\n limit = colander.SchemaNode(colander.String(), missing=colander.drop)\n since = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass ChangeSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados para registro de mudança.\n \"\"\"\n\n id = colander.SchemaNode(colander.String())\n timestamp = colander.SchemaNode(colander.String())\n deleted = colander.SchemaNode(colander.Boolean())\n querystring = QueryChangeSchema()\n\n\nclass ManifestSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados do registro de Manifest\n \"\"\"\n\n data = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass QueryDocumentSchema(colander.MappingSchema):\n \"\"\"Representa os parâmetros de querystring do schema document.\n \"\"\"\n\n when = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass DocumentSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados do documento.\n \"\"\"\n\n data = colander.SchemaNode(colander.String(), missing=colander.drop)\n assets = Assets()\n querystring = QueryDocumentSchema()\n\n\nclass FrontDocumentSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados front do documento.\n \"\"\"\n\n data = colander.SchemaNode(colander.String(), missing=colander.drop)\n\n\nclass JournalIssuesSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados de atualização de fascículos de periódico.\n \"\"\"\n\n issue = colander.SchemaNode(colander.String())\n index = colander.SchemaNode(colander.Int(), missing=colander.drop)\n\n\nclass DeleteJournalIssuesSchema(colander.MappingSchema):\n \"\"\"Representa o schema de dados de deleção de fascículos de periódico.\n \"\"\"\n\n issue = colander.SchemaNode(colander.String())\n\n\n@documents.get(\n schema=DocumentSchema(),\n response_schemas={\n \"200\": DocumentSchema(description=\"Obtém o documento\"),\n \"404\": DocumentSchema(description=\"Documento não encontrado\"),\n },\n accept=\"text/xml\",\n renderer=\"xml\",\n)\ndef fetch_document_data(request):\n \"\"\"Obtém o conteúdo do documento representado em XML com todos os\n apontamentos para seus ativos digitais contextualizados de acordo com a\n versão do documento. Produzirá uma resposta com o código HTTP 404 caso o\n documento solicitado não seja conhecido pela aplicação.\n \"\"\"\n when = request.GET.get(\"when\", None)\n if when:\n version = {\"version_at\": when}\n else:\n version = {}\n try:\n return request.services[\"fetch_document_data\"](\n id=request.matchdict[\"document_id\"], **version\n )\n except (exceptions.DoesNotExist, ValueError) as exc:\n raise HTTPNotFound(exc)\n\n\n@documents.put(\n schema=RegisterDocumentSchema(),\n validators=(colander_body_validator,),\n response_schemas={\n \"201\": RegisterDocumentSchema(description=\"Documento criado com sucesso\"),\n \"204\": RegisterDocumentSchema(description=\"Documento atualizado com sucesso\"),\n },\n)\ndef put_document(request):\n \"\"\"Adiciona ou atualiza registro de documento. A atualização do documento é\n idempotente.\n\n A semântica desta view-function está definida conforme a especificação:\n https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6\n\n Em resumo, ``PUT /documents/:doc_id`` com o payload válido de acordo com o\n schema documentado, e para um ``:doc_id`` inédito, resultará no registro do\n documento e produzirá uma resposta com o código HTTP 201 Created. Qualquer\n requisição subsequente para o mesmo recurso produzirá respostas com o código\n HTTP 204 No Content.\n \"\"\"\n data_url = request.validated[\"data\"]\n assets = {\n asset[\"asset_id\"]: asset[\"asset_url\"]\n for asset in request.validated.get(\"assets\", [])\n }\n try:\n request.services[\"register_document\"](\n id=request.matchdict[\"document_id\"], data_url=data_url, assets=assets\n )\n except exceptions.AlreadyExists:\n try:\n request.services[\"register_document_version\"](\n id=request.matchdict[\"document_id\"], data_url=data_url, assets=assets\n )\n except exceptions.VersionAlreadySet as exc:\n LOGGER.info(\n 'skipping request to add version to \"%s\": %s',\n request.matchdict[\"document_id\"],\n exc,\n )\n return HTTPNoContent(\"document updated successfully\")\n else:\n return HTTPCreated(\"document created successfully\")\n\n\n@manifest.get(\n schema=ManifestSchema(),\n response_schemas={\n \"200\": ManifestSchema(description=\"Obtém o manifesto do documento\"),\n \"404\": ManifestSchema(description=\"Manifesto não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef get_manifest(request):\n \"\"\"Obtém o manifesto do documento. Produzirá uma resposta com o código\n HTTP 404 caso o documento não seja conhecido pela aplicação.\n \"\"\"\n try:\n return request.services[\"fetch_document_manifest\"](\n id=request.matchdict[\"document_id\"]\n )\n except exceptions.DoesNotExist as exc:\n raise HTTPNotFound(exc)\n\n\ndef slugify_assets_ids(assets, slug_fn=slugify):\n return [\n {\"slug\": slug_fn(asset_id), \"id\": asset_id, \"url\": asset_url}\n for asset_id, asset_url in assets.items()\n ]\n\n\n@assets_list.get(\n accept=\"application/json\",\n renderer=\"json\",\n response_schemas={\n \"200\": Assets(description=\"Lista de ativos\"),\n \"404\": Assets(description=\"Documento não encontrado\"),\n },\n)\ndef get_assets_list(request):\n \"\"\"Obtém relação dos ativos associados ao documento em determinada\n versão. Produzirá uma resposta com o código HTTP 404 caso o documento não\n seja conhecido pela aplicação.\n \"\"\"\n try:\n assets = request.services[\"fetch_assets_list\"](\n id=request.matchdict[\"document_id\"]\n )\n except exceptions.DoesNotExist as exc:\n raise HTTPNotFound(exc)\n\n assets[\"assets\"] = slugify_assets_ids(assets[\"assets\"])\n return assets\n\n\n@assets.put(\n schema=AssetSchema(),\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": AssetSchema(\n description=\"Adicionado ou atualizado o ativo digital com sucesso\"\n ),\n \"404\": AssetSchema(description=\"Ativo não encontrado\"),\n },\n)\ndef put_asset(request):\n \"\"\"Adiciona ou atualiza registro de ativo do documento. A atualização do\n ativo é idempotente.\n\n A semântica desta view-function está definida conforme a especificação:\n https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6\n \"\"\"\n assets_list = get_assets_list(request)\n assets_map = {asset[\"slug\"]: asset[\"id\"] for asset in assets_list[\"assets\"]}\n asset_slug = request.matchdict[\"asset_slug\"]\n try:\n asset_id = assets_map[asset_slug]\n except KeyError:\n raise HTTPNotFound(\n 'cannot fetch asset with slug \"%s\": asset does not exist' % asset_slug\n )\n\n asset_url = request.validated[\"asset_url\"]\n try:\n request.services[\"register_asset_version\"](\n id=request.matchdict[\"document_id\"], asset_id=asset_id, asset_url=asset_url\n )\n except exceptions.VersionAlreadySet as exc:\n LOGGER.info(\n 'skipping request to add version to \"%s/assets/%s\": %s',\n request.matchdict[\"document_id\"],\n request.matchdict[\"asset_slug\"],\n exc,\n )\n return HTTPNoContent(\"asset updated successfully\")\n\n\n@diff.get(\n schema=DiffDocumentSchema(),\n response_schemas={\n \"200\": DiffDocumentSchema(\n description=\"Retorna a diferança do documento, recebe os argumentos `from_when` e `to_when`\"\n ),\n \"400\": DiffDocumentSchema(\n description=\"Erro ao tentar processar a requisição, verifique o valor do parâmetro `from_when`\"\n ),\n \"404\": DiffDocumentSchema(description=\"Documento não encontrado\"),\n },\n renderer=\"text\",\n)\ndef diff_document_versions(request):\n \"\"\"Compara duas versões do documento. Se o argumento `to_when` não for\n fornecido, será assumido como alvo a versão mais recente.\n \"\"\"\n from_when = request.GET.get(\"from_when\", None)\n if from_when is None:\n raise HTTPBadRequest(\"cannot fetch diff: missing attribute from_when\")\n try:\n return request.services[\"diff_document_versions\"](\n id=request.matchdict[\"document_id\"],\n from_version_at=from_when,\n to_version_at=request.GET.get(\"to_when\", None),\n )\n except (exceptions.DoesNotExist, ValueError) as exc:\n raise HTTPNotFound(exc)\n\n\n@front.get(\n schema=FrontDocumentSchema(),\n response_schemas={\n \"200\": FrontDocumentSchema(\n description=\"Retorna o Front do documento (todo os dados do documento exceto o body)\"\n ),\n \"404\": FrontDocumentSchema(description=\"Front do documento não encontrado\"),\n },\n renderer=\"json\",\n)\ndef fetch_document_front(request):\n data = fetch_document_data(request)\n return request.services[\"sanitize_document_front\"](data)\n\n\n@bundles.get(\n response_schemas={\n \"200\": DocumentsBundleSchema(\n description=\"Retorna os dados do bundle solicitado\"\n ),\n \"404\": DocumentsBundleSchema(description=\"Recurso não encontrado\"),\n \"400\": DocumentsBundleSchema(\n description=\"Erro ao processar a requisição. Verifique o parâmetro `bundle_id`\"\n ),\n },\n renderer=\"json\",\n)\ndef fetch_documents_bundle(request):\n try:\n _bundle = request.services[\"fetch_documents_bundle\"](\n request.matchdict[\"bundle_id\"]\n )\n except KeyError:\n return HTTPBadRequest(\"bundle id is mandatory\")\n except exceptions.DoesNotExist as exc:\n return HTTPNotFound(str(exc))\n else:\n if _bundle.get(\"titles\"):\n _bundle[\"titles\"] = [\n {\"language\": language, \"title\": title}\n for language, title in _bundle[\"titles\"].items()\n ]\n return _bundle\n\n\n@bundles.put(\n schema=DocumentsBundleSchema(),\n response_schemas={\n \"201\": DocumentsBundleSchema(\n description=\"Documents Bundle criado com sucesso.\"\n ),\n \"204\": DocumentsBundleSchema(\n description=\"Documents Bundle atualizado com sucesso.\"\n ),\n },\n validators=(colander_body_validator,),\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef put_documents_bundle(request):\n _metadata = request.validated\n _metadata[\"titles\"] = {\n title[\"language\"]: title[\"title\"] for title in request.validated[\"titles\"] or []\n }\n try:\n request.services[\"create_documents_bundle\"](\n request.matchdict[\"bundle_id\"], metadata=_metadata\n )\n except exceptions.AlreadyExists:\n return HTTPNoContent(\"bundle updated successfully\")\n else:\n return HTTPCreated(\"bundle created successfully\")\n\n\n@bundles.patch(\n schema=DocumentsBundleSchema(),\n response_schemas={\n \"204\": DocumentsBundleSchema(\n description=\"Documents Bundle atualizado com sucesso.\"\n ),\n \"404\": DocumentsBundleSchema(description=\"Documents Bundle não encontrado.\"),\n },\n validators=(colander_body_validator,),\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef patch_documents_bundle(request):\n _metadata = request.validated\n _metadata[\"titles\"] = {\n title[\"language\"]: title[\"title\"] for title in request.validated[\"titles\"] or []\n }\n try:\n request.services[\"update_documents_bundle_metadata\"](\n request.matchdict[\"bundle_id\"], metadata=_metadata\n )\n except exceptions.DoesNotExist as exc:\n return HTTPNotFound(str(exc))\n else:\n return HTTPNoContent(\"bundle updated successfully\")\n\n\n@changes.get(\n schema=ChangeSchema(),\n response_schemas={\n \"200\": AssetSchema(description=\"Retorna a lista de mudanças\"),\n \"400\": AssetSchema(\n description=\"Erro ao processar a requisição, verifique o parâmetro `limit`\"\n ),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef fetch_changes(request):\n \"\"\"Obtém a lista de mudanças, recebe os argumentos `since` e `limit`.\n \"\"\"\n\n entity_route_map = {\n \"Document\": {\"route\": \"documents\", \"marker\": \"document_id\"},\n \"Journal\": {\"route\": \"journals\", \"marker\": \"journal_id\"},\n \"DocumentsBundle\": {\"route\": \"bundles\", \"marker\": \"bundle_id\"},\n }\n\n def _format_change(c):\n entity = entity_route_map[c[\"entity\"]]\n result = {\n \"id\": request.route_path(entity[\"route\"], **{entity[\"marker\"]: c[\"id\"]}),\n \"timestamp\": c[\"timestamp\"],\n }\n\n if \"deleted\" in c:\n result[\"deleted\"] = c[\"deleted\"]\n\n return result\n\n since = request.GET.get(\"since\", \"\")\n\n try:\n limit = int(request.GET.get(\"limit\", 500))\n except ValueError:\n raise HTTPBadRequest(\"limit must be integer\")\n\n return {\n \"since\": since,\n \"limit\": limit,\n \"results\": [\n _format_change(c)\n for c in request.services[\"fetch_changes\"](since=since, limit=limit)\n ],\n }\n\n\n@journals.put(\n schema=JournalSchema(),\n validators=(colander_body_validator,),\n response_schemas={\n \"201\": JournalSchema(description=\"Periódico criado com sucesso\"),\n \"204\": JournalSchema(\n description=\"Não foi realizada alteração para o periódico informado\"\n ),\n \"400\": JournalSchema(\n description=\"Erro ao processar a requisição, por favor verifique os dados informados\"\n ),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef put_journal(request):\n \"\"\"Registra um periódico a partir de dados submetidos e\n validados por meio do JournalSchema.\"\"\"\n\n try:\n request.services[\"create_journal\"](\n id=request.matchdict[\"journal_id\"], metadata=request.validated\n )\n except exceptions.AlreadyExists:\n return HTTPNoContent(\"journal already exists\")\n except (TypeError, ValueError) as err:\n return HTTPBadRequest(str(err))\n else:\n return HTTPCreated(\"journal created successfully\")\n\n\n@journals.get(\n schema=JournalSchema(),\n response_schemas={\n \"200\": JournalSchema(description=\"Retorna um periódico\"),\n \"404\": JournalSchema(description=\"Periódico não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef get_journal(request):\n \"\"\"Recupera um periódico por meio de seu identificador\n \"\"\"\n\n try:\n return request.services[\"fetch_journal\"](id=request.matchdict[\"journal_id\"])\n except exceptions.DoesNotExist:\n return HTTPNotFound(\n 'cannot fetch journal with id \"%s\"' % request.matchdict[\"journal_id\"]\n )\n\n\n@journals.patch(\n schema=JournalSchema,\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": JournalSchema(description=\"Periódico atualizado com sucesso\"),\n \"400\": JournalSchema(\n description=\"Erro ao tentar processar a requisição, verifique os dados submetidos\"\n ),\n \"404\": JournalSchema(description=\"Periódico não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef patch_journal(request):\n \"\"\"Atualiza um periódico a partir dos dados fornecidos e\n validados por meio do JournalSchema.\n \"\"\"\n\n try:\n request.services[\"update_journal_metadata\"](\n id=request.matchdict[\"journal_id\"], metadata=request.validated\n )\n except (TypeError, ValueError) as exc:\n return HTTPBadRequest(str(exc))\n except exceptions.DoesNotExist:\n return HTTPNotFound(\n 'cannot fetch journal with id \"%s\"' % request.matchdict[\"journal_id\"]\n )\n\n return HTTPNoContent(\"journal updated successfully\")\n\n\n@journal_issues.patch(\n schema=JournalIssuesSchema(),\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": JournalIssuesSchema(\n description=\"Fascículo adicionado ou inserido em periódico com sucesso\"\n ),\n \"404\": JournalIssuesSchema(description=\"Periódico não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef patch_journal_issues(request):\n try:\n if request.validated.get(\"index\") is not None:\n request.services[\"insert_issue_to_journal\"](\n id=request.matchdict[\"journal_id\"],\n index=request.validated[\"index\"],\n issue=request.validated[\"issue\"],\n )\n else:\n request.services[\"add_issue_to_journal\"](\n id=request.matchdict[\"journal_id\"], issue=request.validated[\"issue\"]\n )\n except exceptions.DoesNotExist as exc:\n return HTTPNotFound(str(exc))\n except exceptions.AlreadyExists as exc:\n return HTTPNoContent(\"issue added to journal successfully.\")\n else:\n return HTTPNoContent(\"issue added to journal successfully.\")\n\n\n@journals_aop.patch(\n schema=JournalAOPSchema,\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": JournalAOPSchema(\n description=\"Ahead of Print adicionado ao periódico com sucesso ao periódico\"\n ),\n \"404\": JournalAOPSchema(description=\"Periódico não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef patch_journal_aop(request):\n try:\n request.services[\"set_ahead_of_print_bundle_to_journal\"](\n id=request.matchdict[\"journal_id\"], aop=request.validated[\"aop\"]\n )\n except exceptions.DoesNotExist:\n return HTTPNotFound(\n 'cannot find journal with id \"%s\"' % request.matchdict[\"journal_id\"]\n )\n\n return HTTPNoContent(\"aop added to journal successfully\")\n\n\n@journals_aop.delete(\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": ResponseSchema(\n description=\"Ahead of Print removido do periódico com sucesso\"\n ),\n \"404\": ResponseSchema(description=\"Periódico não encontrado\"),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef delete_journal_aop(request):\n try:\n request.services[\"remove_ahead_of_print_bundle_from_journal\"](\n id=request.matchdict[\"journal_id\"]\n )\n except exceptions.DoesNotExist as exc:\n return HTTPNotFound(str(exc))\n return HTTPNoContent()\n\n\n@journal_issues.delete(\n schema=DeleteJournalIssuesSchema(),\n validators=(colander_body_validator,),\n response_schemas={\n \"204\": DeleteJournalIssuesSchema(\n description=\"Fascículo removido em periódico com sucesso\"\n ),\n \"404\": DeleteJournalIssuesSchema(\n description=\"Periódico ou fascículo não encontrado\"\n ),\n },\n accept=\"application/json\",\n renderer=\"json\",\n)\ndef delete_journal_issues(request):\n try:\n request.services[\"remove_issue_from_journal\"](\n id=request.matchdict[\"journal_id\"], issue=request.validated[\"issue\"]\n )\n except exceptions.DoesNotExist as exc:\n return HTTPNotFound(str(exc))\n else:\n return HTTPNoContent(\"issue removed from journal successfully.\")\n\n\n@swagger.get()\ndef openAPI_spec(request):\n doc = CorniceSwagger(get_services())\n doc.summary_docstrings = True\n return doc.generate(\"Kernel\", \"0.1\")\n\n\nclass XMLRenderer:\n \"\"\"Renderizador para dados do tipo ``text/xml``.\n\n Espera que o retorno da view-function seja uma string de bytes pronta para\n ser transferida para o cliente. Este renderer apenas define o content-type\n da resposta HTTP.\n \"\"\"\n\n def __init__(self, info):\n pass\n\n def __call__(self, value, system):\n request = system.get(\"request\")\n if request is not None:\n request.response.content_type = \"text/xml\"\n return value\n\n\nclass PlainTextRenderer:\n \"\"\"Renderizador para dados do tipo ``text/plain``.\n\n Espera que o retorno da view-function seja uma string de bytes pronta para\n ser transferida para o cliente. Este renderer apenas define o content-type\n da resposta HTTP.\n \"\"\"\n\n def __init__(self, info):\n pass\n\n def __call__(self, value, system):\n request = system.get(\"request\")\n if request is not None:\n request.response.content_type = \"text/plain\"\n return value\n\n\nDEFAULT_SETTINGS = [\n (\"kernel.app.mongodb.dsn\", \"KERNEL_APP_MONGODB_DSN\", str, \"mongodb://db:27017/\")\n]\n\n\ndef parse_settings(settings, defaults=DEFAULT_SETTINGS):\n \"\"\"Analisa e retorna as configurações da app com base no arquivo .ini e env.\n\n As variáveis de ambiente possuem precedência em relação aos valores\n definidos no arquivo .ini.\n\n O argumento `defaults` deve receber uma lista associativa na forma:\n\n [\n (, , , ),\n ]\n \"\"\"\n parsed = {}\n cfg = list(defaults)\n\n for name, envkey, convert, default in cfg:\n value = os.environ.get(envkey, settings.get(name, default))\n if convert is not None:\n value = convert(value)\n parsed[name] = value\n\n return parsed\n\n\ndef main(global_config, **settings):\n settings.update(parse_settings(settings))\n config = Configurator(settings=settings)\n config.include(\"cornice\")\n config.include(\"cornice_swagger\")\n config.scan()\n config.add_renderer(\"xml\", XMLRenderer)\n config.add_renderer(\"text\", PlainTextRenderer)\n\n mongo = adapters.MongoDB(settings[\"kernel.app.mongodb.dsn\"])\n Session = adapters.Session.partial(mongo)\n\n config.add_request_method(\n lambda request: services.get_handlers(Session), \"services\", reify=True\n )\n\n return config.make_wsgi_app()\n","sub_path":"documentstore/restfulapi.py","file_name":"restfulapi.py","file_ext":"py","file_size_in_byte":28832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"196210638","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Author: Sandro Lutz \n\nimport argparse\nimport requests\nimport csv\nfrom email.utils import parseaddr\n\nparser = argparse.ArgumentParser(prog='amivapi-groupmemberships-import.py',\n description='Import groupmemberships from CSV file into the AMIVAPI')\nparser.add_argument('api_domain', nargs=1, default='api.amiv.ethz.ch', help='Domain under which the AMIVAPI is accessible')\nparser.add_argument('api_token', nargs=1, default='root', help='authorization token for the AMIVAPI')\nparser.add_argument('group_id', nargs=1, default='Unknown group', help='Group ID')\nparser.add_argument('file', nargs=1, type=argparse.FileType('r'),\n default='users.csv', help='file to import from')\nargs = parser.parse_args()\n\nhost = 'https://' + ''.join(args.api_domain)\nheaders = {'Authorization': ''.join(args.api_token)}\n\nnethzList = list()\nfailedList = list()\n\ndef findUser(nethz):\n items = requests.get(host + '/users?where={\"nethz\":\"' + nethz + '\"}', headers=headers).json()['_items']\n if len(items) != 1:\n raise Exception('User with nethz ' + nethz + ' not found!')\n return items[0]\n\ndef addGroupmembership(group_id, user):\n data = {\n 'group': group_id,\n 'user': user['_id']\n }\n response = requests.post(host + '/groupmemberships', headers=headers, data=data)\n if response.status_code != 201:\n failedList.append(user['nethz'])\n\n# Read users from import file\nif (type(args.file) is list):\n reader = csv.DictReader(args.file[-1])\nelse:\n reader = csv.DictReader(args.file)\n\nunknownUsers = list()\n\nfor row in reader:\n try:\n print('------------------------------------')\n user = findUser(row['NETHZ'])\n\n print('Found user ' + user['nethz'])\n addGroupmembership(args.group_id, user)\n except Exception as e:\n print(e)\n unknownUsers.append(row)\n\nprint('----------------------------------------')\nprint('========================================')\nprint(str(len(unknownUsers)) + ' unknown Users')\nprint(str(len(failedList)) + ' failed Users')\nprint('----------------------------------------')\n","sub_path":"amivapi-groupmemberships-import.py","file_name":"amivapi-groupmemberships-import.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42419421","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n# 画像のガンマ補正 2016/08/21 masaniwa\n\nimport cv2 as cv\nimport numpy as np\nimport ProcessingTimer as pt\n\n# 画像のガンマ補正\n# @param frame 入力画像\n# @param gamma ガンマ定数\n# @return 補正画像\ndef getGammaFrame(frame, gamma):\n\tlookUpTable = np.zeros((256, 1), np.uint8)\n\t\n\tfor i in range(256):\n\t\tlookUpTable[i][0] = 255 * pow(i / 255.0, 1.0 / gamma)\n\t\t\n\treturn cv.LUT(frame, lookUpTable)\n\nif __name__ == \"__main__\":\n\tcv.namedWindow(\"InputFrame\")\n\tcv.namedWindow(\"GammaFrame\")\n\t\n\t# USBカメラ非接続でもVideoCapture.isOpened()でTrueが返ってくるので、まともにエラー処理してないです。\n\t# USBカメラ非接続でVideoCapture.read()すると落ちるので注意。\n\tcapture = cv.VideoCapture(0)\n\t\n\twhile True:\n\t\t_, inputFrame = capture.read()\n\t\t\n\t\twith pt.ProcessingTimer(\"getGammaFrame\"):\n\t\t\tgammaFrame = getGammaFrame(inputFrame, 2.0)\n\t\t\t\n\t\tcv.imshow(\"InputFrame\", inputFrame)\n\t\tcv.imshow(\"GammaFrame\", gammaFrame)\n\t\t\n\t\t# ESCキーが押されると終了\n\t\t# waitKey()で取得できるキーコードがおかしいので応急処置\n\t\tif (cv.waitKey(60) % 256) == 27:\n\t\t\tbreak\n\t\t\t\n\tcapture.release()\n\tcv.destroyAllWindows()\n","sub_path":"getGammmaFrame.py","file_name":"getGammmaFrame.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"565896336","text":"import os\nfrom array import array\n\nimport cv2\nimport pytesseract\nfrom PIL import Image\n\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract.exe'\ntessdata_dir_config = '--tessdata-dir \"C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tessdata\"'\n\ncustom_seq = '\\\\'\n\n# 图片存放路径\npic_path = '{}{}img{}cp{}'.format(os.getcwd(), os.sep, os.sep, os.sep)\nnormal_pic_path = pic_path + os.sep + \"normal\" + os.sep\nb_pic_path=pic_path + os.sep + \"b\" + os.sep\ng_pic_path=pic_path + os.sep + \"g\" + os.sep\n\n# 读取图片信息\ndef load_img_info_test_1():\n im = Image.open(pic_path + 'bc_verify_code0.jpg')\n print(im.format, im.size, im.mode, \" \")\n\n\n# 读取验证码的数字\ndef load_img_qr(i):\n img_name = 'g_verify_code_%s.jpg' % i\n im = Image.open(g_pic_path + img_name)\n # im = im.convert('RGB')\n # im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n # 拉长图像,方便识别。\n # im = im.resize((300, 80))\n vcode = pytesseract.image_to_string(im, config=tessdata_dir_config)\n vcode= vcode.replace(\" \",\"\")\n print(img_name + \" \" + vcode)\n\n\ndef load_img_qr_1(i):\n img_name = 'bc_verify_code_%s.jpg' % i\n im = Image.open(normal_pic_path + img_name)\n im = im.convert('RGB')\n im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n # 拉长图像,方便识别。\n im = im.resize((200, 80))\n a = array(im)\n for i in range(len(a)):\n for j in range(len(a[i])):\n if a[i][j][0] == 255:\n a[i][j] = [0, 0, 0]\n else:\n a[i][j] = [255, 255, 255]\n im = Image.fromarray(a)\n im.show()\n\n vcode = pytesseract.image_to_string(im, config=tessdata_dir_config)\n print(img_name + \" \" + vcode)\n\n\n# 二值化\nthreshold = 140\ntable = []\nfor i in range(256):\n if i < threshold:\n table.append(0)\n else:\n table.append(1)\n\nrep = {'O': '0',\n 'I': '1', 'L': '1',\n 'Z': '2',\n 'S': '8'\n }\n\n\ndef load_img_qr_2(i):\n name = 'verify_code_%s.jpg' % i\n # 打开图片\n im = Image.open(normal_pic_path + name)\n # 转化到灰度图\n imgry = im.convert('L')\n # 保存图像\n imgry.save(g_pic_path + 'g_' + name)\n # 二值化,采用阈值分割法,threshold为分割点\n out = imgry.point(table, '1')\n out.save(b_pic_path + 'b_' + name)\n # 识别\n text = pytesseract.image_to_string(out, config=tessdata_dir_config)\n print(text)\n # 识别对吗\n text = text.strip()\n text = text.upper()\n for r in rep:\n text = text.replace(r, rep[r])\n # out.save(text+'.jpg')\n print(text)\n return text\n\n\nif __name__ == '__main__':\n for i in range(0, 30):\n load_img_qr_2(str(i))\n for i in range(0,30):\n load_img_qr(i)\n","sub_path":"qr/bc_img_read.py","file_name":"bc_img_read.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"103467782","text":"from collections import deque\nimport random\nimport torch\n\nclass Memory(object):\n def __init__(self, size):\n self.size = size\n self.buffer = deque(maxlen=size)\n self.no_cost_buffer = deque(maxlen=size)\n self.cost_buffer = deque(maxlen=size)\n\n def push(self, state, action, reward, next_state, cost, fail):\n self.buffer.append((state, action, [reward], next_state, [cost], [fail]))\n if cost == 0:\n self.no_cost_buffer.append((state, action, [reward], next_state, [cost], [fail]))\n else:\n self.cost_buffer.append((state, action, [reward], next_state, [cost], [fail]))\n\n def get_batch(self, batch_size):\n states = []\n actions = []\n rewards = []\n next_states = []\n costs = []\n fails = []\n\n batch = random.sample(self.buffer, batch_size)\n\n for item in batch:\n state, action, reward, next_state, cost, fail = item\n states.append(state)\n actions.append(action)\n rewards.append(reward)\n next_states.append(next_state)\n costs.append(cost)\n fails.append(fail)\n return torch.FloatTensor(states), torch.FloatTensor(actions), torch.FloatTensor(rewards), torch.FloatTensor(next_states), torch.FloatTensor(costs), torch.BoolTensor(fails)\n\n def get_cost_training_batch(self, batch_size, proportion=0.5):\n states = []\n actions = []\n rewards = []\n next_states = []\n costs = []\n fails = []\n\n cost_batch_size = int(batch_size * (1 - proportion))\n cost_batch_size = min(cost_batch_size, len(self.cost_buffer))\n no_cost_batch_size = batch_size - cost_batch_size\n\n batch = random.sample(self.no_cost_buffer, no_cost_batch_size)\n for item in batch:\n state, action, reward, next_state, cost, fail = item\n states.append(state)\n actions.append(action)\n rewards.append(reward)\n next_states.append(next_state)\n costs.append(cost)\n fails.append(fail)\n\n batch = random.sample(self.cost_buffer, cost_batch_size)\n for item in batch:\n state, action, reward, next_state, cost, fail = item\n states.append(state)\n actions.append(action)\n rewards.append(reward)\n next_states.append(next_state)\n costs.append(cost)\n fails.append(fail)\n\n return torch.FloatTensor(states), torch.FloatTensor(actions), torch.FloatTensor(rewards), torch.FloatTensor(next_states), torch.FloatTensor(costs), torch.BoolTensor(fails)\n\n def __len__(self):\n return len(self.buffer)\n\n def cost_buffer_size(self):\n return len(self.cost_buffer)\n","sub_path":"lib/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"621078982","text":"#!/usr/bin/env python3\nfrom argparse import ArgumentParser\nfrom datetime import datetime, timedelta\nimport time\n\ndef time_as_hms(t):\n return datetime.now().strftime(\"%H:%M:%S\")\n\ndef linecleared_message(m):\n print('\\r' + (' ' * 40) + '\\r' + m, end='')\n\n\nparser = ArgumentParser()\nparser.add_argument('duration', help='Duration in minutes', type=float)\nparser.add_argument('-n', '--note', help='Note on the timer')\nargs = parser.parse_args()\n\nseconds = 0\nstart = datetime.now()\nend = datetime.now() + timedelta(minutes=args.duration)\nnote = (' ' + args.note + ' ') if args.note else ''\nwhile datetime.now() < end:\n delta = (end - datetime.now()).total_seconds()\n delta_min = int(delta / 60)\n delta_seconds = int(delta - (delta_min * 60))\n msg = '{}{}m{}s'.format(note.lstrip(), delta_min, delta_seconds)\n linecleared_message(msg)\n time.sleep(1)\nlinecleared_message(\"Finished {}m{}!\".format(args.duration, note.rstrip()))\nprint()\n","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"163792510","text":"from IPython import embed as shell\n\nclass Action(object):\n \"\"\"\n An action is comprised of parameters, preconditions, and effects.\n \"\"\"\n def __init__(self, params, pre, eff):\n self.params = params\n self.pre = pre\n self.eff = eff\n","sub_path":"src/core/internal_repr/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"336091981","text":"#!/usr/bin/python\n\"\"\" serverMain\n\nMain control for server-side module\n\"\"\"\n\n# imports\nimport os\nimport datetime\nimport db_connect\nimport fetch\n\n__author__ = \"Chadwick Puterbaugh\"\n__copyright__ = \"2014\"\n__credits__ = \"Chadwick Puterbaugh\"\n\n__license__ = \"GPL\"\n__version__ = \"0.0.2\"\n__maintainer__ = \"Chadwick Puterbaugh\"\n__email__ = \"chad@cwputer.com\"\n__status__ = \"Prototype\"\n\n\ndb = db_connect.get_db()\n\ndef fetch_current():\n\tfetch.fetch()\n\t\ndef fetch_history():\n\tfetch.updateHistories()\n##\n\nif __name__ == '__main__':\n\tnow = datetime.datetime.now()\n\tif now.weekday() < 5:\n\t\tfetch_current()\n\t\tif now.hour >= 17:\n\t\t\tfetch_history()\n","sub_path":"serverMain.py","file_name":"serverMain.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"125375979","text":"import random\nfrom math import log\n\ndef sequential_read(out_file_name, num_reads, offset, num_address_bits, num_data_bits):\n\t\"\"\"\n\tCreates a sequential read sequence for the Logisim Cache project beginning at offset.\n\t@out_file_name: the name of the output file\n\t@num_reads: the number of sequential reads to do\n\t@offset: how far into memory to begin the reading\n\t@num_address_bits: the number of address bits\n\t@num_data_bits: the number of data bits\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\tout_file.write('v2.0 raw\\n')\n\t\tread = 1 << (num_address_bits + num_data_bits + 1)\n\t\tdone = 1 << (num_address_bits + num_data_bits + 1 + 1)\n\t\tfor i in range(offset, offset+num_reads):\n\t\t\taddress = i << num_data_bits\n\t\t\tout_file.write('%x #read addr %d\\n' % ((read | address), i))\n\t\t\t\n\t\tout_file.write('%x #do nothing\\n' % (0)) #just a quick pause\n\t\tout_file.write('%x #complete testing and do nothing\\n' % (done))\n\t\t\t\n\ndef sequential_write(out_file_name, num_writes, offset, value_offset, \n\t\tnum_address_bits, num_data_bits, num_sets, num_ways, line_size):\n\t\"\"\"\n\tCreates a sequential write sequence for the Logisim Cache project beginnning at offset.\n\t@out_file_name: the name of the output file\n\t@num_writes: the number of sequential reads to do\n\t@offset: how far into memory to begin the reading\n\t@value_offset: what the starting data value should be \n\t@num_address_bits: the number of address bits\n\t@num_data_bits: the number of data bits\n\t@num_sets: the number of sets\n\t@num_ways: the number of lines per set\n\t@line_size: the size of each line\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\tout_file.write('v2.0 raw\\n')\n\t\tnum_line_bits = int(log(line_size,2))\n\t\tnum_set_bits = int(log(line_size,2))\n\t\tread = 1 << (num_address_bits + num_data_bits + 1)\n\t\twrite = 1 << (num_address_bits + num_data_bits)\n\t\tdone = 1 <<(num_address_bits + num_data_bits + 1 + 1)\n\t\tfor i in range(offset, offset+num_writes):\n\t\t\taddress = i << num_data_bits\n\t\t\tvalue = (value_offset + i) % (2**num_data_bits)\n\t\t\tout_file.write('%x #write value 0x%x to addr %d \\n' % ((write | address | value), value, i))\n\t\t\n\t\t#flush the cache to see if the values were updated.\n\t\tfor set in range(num_sets): #for each set\n\t\t\tselected_set = set << (num_data_bits + num_line_bits)\n\t\t\tfor way in range(0,num_ways): #for each way in the set\n\t\t\t\ttag = way << (num_data_bits + num_line_bits + num_set_bits)\n\t\t\t\tfor i in range(2): #guarentee we knock out that line to memory\n\t\t\t\t\ttag += i << (num_data_bits + num_line_bits + num_set_bits)\n\t\t\t\t\taddress = tag | selected_set\n\t\t\t\t\tout_file.write('%x #read addr %d\\n' % ((read | address), address >> num_data_bits))\n\t\t\t\t\t\n\t\t#read everything back in to see if we updated correctly\n\t\tfor i in range(offset, offset+num_writes):\n\t\t\taddress = i << num_data_bits\n\t\t\tout_file.write('%x #read addr %d\\n' % ((read | address), i))\n\t\t\t\t\t\n\t\tout_file.write('%x\\n' % (0)) #just a quick pause\n\t\tout_file.write('%x\\n' % (done)) #mark that we are completed\n\t\t\t\ndef targeted_set_read(out_file_name, num_set_reads, which_set,\n\tnum_address_bits, num_sets, line_size, num_data_bits):\n\t\"\"\"\n\tCreates a read sequence that continually accesses\n\tthe same set over and over again for the Logisim Cache project.\n\tReads are done sequentially starting from the beginning of memory\n\t@out_file_name: the name of the output file\n\t@num_set_reads: the number of reads to do\n\t@which_set: which set are we trying to keep hitting\n\t@num_address_bits: the number of address bits\n\t@num_sets: the number of sets in the cache. must be a power of 2\n\t@line_size: the number of elements per line. must be a power of 2\n\t@num_data_bits: the number of data bits\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\tout_file.write('v2.0 raw\\n')\n\t\tnum_line_bits = int(log(line_size,2))\n\t\tnum_set_bits = int(log(line_size,2))\n\t\tread = 1 << (num_address_bits + num_data_bits + 1)\n\t\tdone = 1 << (num_address_bits + num_data_bits + 1 + 1)\n\t\tthe_set = which_set << (num_data_bits + num_line_bits)\n\t\tfor i in range(num_set_reads):\n\t\t\taddress = i << (num_data_bits + num_set_bits + num_line_bits) #get the tag for the address we want to make\n\t\t\tfor j in range(line_size):\n\t\t\t\telement = j << num_data_bits\n\t\t\t\taddress |= the_set | element\n\t\t\t\tout_file.write('%x #read addr %d\\n' % ((read | address), address >> num_data_bits))\n\t\t\t#out_file.write('\\n')\n\t\tout_file.write('%x\\n' % (0)) #just a quick pause\n\t\tout_file.write('%x\\n' % (done))\n\t\t\t\n\ndef targeted_set_write(out_file_name, num_set_writes, which_set,\n\tvalue_offset, num_address_bits, num_sets, line_size, num_data_bits):\n\t\"\"\"\n\tCreates a read sequence that continually accesses\n\tthe same set over and over again for the Logisim Cache project.\n\tReads are done sequentially starting from the beginning of memory\n\t@out_file_name: the name of the output file\n\t@num_set_reads: the number of reads to do\n\t@which_set: which set are we trying to keep hitting\n\t@value_offset: the first data value to write\n\t@num_address_bits: the number of address bits\n\t@num_sets: the number of sets in the cache. must be a power of 2\n\t@line_size: the number of elements per line. must be a power of 2\n\t@num_data_bits: the number of data bits\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\tout_file.write('v2.0 raw\\n')\n\t\tnum_line_bits = int(log(line_size,2))\n\t\tnum_set_bits = int(log(line_size,2))\n\t\tread = 1 << (num_address_bits + num_data_bits + 1)\n\t\twrite = 1 << (num_address_bits + num_data_bits)\n\t\tdone = 1 << (num_address_bits + num_data_bits + 1 + 1)\n\t\tthe_set = which_set << (num_data_bits + num_line_bits)\n\t\tfor i in range(num_set_writes):\n\t\t\taddress = i << (num_data_bits + num_set_bits + num_line_bits)\n\t\t\tfor j in range(line_size):\n\t\t\t\tvalue_offset %= (2**num_data_bits)\n\t\t\t\telement = j << num_data_bits\n\t\t\t\taddress |= the_set | element\n\t\t\t\tout_file.write('%x #write value 0x%x to addr %d \\n' % \n\t\t\t\t((write | address | value_offset), value_offset, address >> num_data_bits))\n\t\t\t\tvalue_offset += 1\n\t\t\n\t\t#read in the values we just wrote out\n\t\tfor i in range(num_set_writes):\n\t\t\taddress = i << (num_data_bits + num_set_bits + num_line_bits) #get the tag for the address we want to make\n\t\t\tfor j in range(line_size):\n\t\t\t\telement = j << num_data_bits\n\t\t\t\taddress |= the_set | element\n\t\t\t\tout_file.write('%x\\n' % (read | address))\n\t\t\t#out_file.write('\\n')\n\t\tout_file.write('%x\\n' % (0)) #just a quick pause\n\t\tout_file.write('%x\\n' % (done))\n\t\t\ndef constrained_random_read_write(out_file_name, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnum_reads_and_writes, max_address, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnum_address_bits, num_data_bits):\n\t\"\"\"\n\tCreates a read sequence that randomly accesses addressses between 0 and max_address inclusive\n\t@out_file_name: the name of the output file to be created\n\t@num_reads_and_writes: the total number of reads and writes to do\n\t@max_address: the maximum address that can be generated\n\t@num_address_bits: the number of address_bits\n\t@num_data_bits: the size of each data element\n\t\"\"\"\n\t\n\twith open(out_file_name, 'w') as out_file, open('random0_sim_inputs.txt', 'w') as rand_sim_out:\n\t\tread = 1 << (num_address_bits + num_data_bits + 1)\n\t\twrite = 1 << (num_address_bits + num_data_bits)\n\t\tdone = 1 << (num_address_bits + num_data_bits + 1 + 1)\n\t\tcmds = [read,write]\n\t\t\n\t\tout_file.write('v2.0 raw\\n') #write header\n\t\tfor read_or_write in range(num_reads_and_writes):\n\t\t\tcmd = random.choice(cmds) #pick a command to do\n\t\t\taddress = random.randint(0, max_address) << num_data_bits #generate the address\n\t\t\tvalue = random.randint(0, (2**num_data_bits) - 1) #generate the value to be written if we do a write\n\t\t\tout_file.write('%x ' % (cmd | address | value)) #generate the command in the out file\n\t\t\tif cmd == read:\n\t\t\t\tout_file.write('#read addr %d' % (address >> num_data_bits))\n\t\t\t\trand_sim_out.write('r %d\\n' % (address >> num_data_bits))\n\t\t\telse:\n\t\t\t\tout_file.write('#write value 0x%x to addr %d' % (value, (address >> num_data_bits)))\n\t\t\t\trand_sim_out.write('w %d %d\\n' % ((address >> num_data_bits), value))\n\t\t\tout_file.write('\\n')\n\t\trand_sim_out.write('q\\n')\n\t\t\t\n\t\t\n\t\tout_file.write('%x #do nothing\\n' % (0)) #just a quick pause\n\t\tout_file.write('%x #complete testing and do nothing\\n' % (done))\t\n\t\t\t\n\ndef make_sequential_mem(out_file_name, num_address_bits, num_data_bits):\n\t\"\"\"\n\tCreates a memory file for the logisim cache project\n\t@out_file_name: the name of the output file\n\t@num_address_bits: the number of address bits\n\t@num_data_bits: the number of data bits\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\tout_file.write('v2.0 raw\\n')\n\t\tcount = 0\n\t\tfor i in range(2**num_address_bits):\n\t\t\tvalue = 0\n\t\t\tfor j in range(4):\n\t\t\t\tvalue |= count << (j*8)\n\t\t\t\tcount += 1\n\t\t\t\tcount %= 2**8\n\t\t\t\t\n\t\t\tout_file.write('%08x\\n' % value)\n\ndef make_random_mem(out_file_name, seed, num_address_bits, num_data_bits):\n\t\"\"\"\n\tCreates a memory file for the logisim \n\t@out_file_name: the name of the output file\n\t@seed: the seed to the random number generator\n\t@num_address_bits: the number of address bits\n\t@num_data_bits: the number of data bits\n\t\"\"\"\n\twith open(out_file_name, 'w') as out_file:\n\t\trandom.seed(seed)\n\t\tout_file.write('v2.0 raw\\n')\n\t\tfor i in range(2**num_address_bits):\n\t\t\tout_file.write('%08x\\n' % random.randint(0, 2**num_data_bits - 1))\n\ndef make_solution(out_file_name, command_file_name, mem_file_name,\n\t\t\t\t\t\t\t\t\tnum_address_bits, num_data_bits):\n\twith open(out_file_name, 'w') as out_file, open(command_file_name) as cmd_fil:\n\t\tmem = read_mem_file(mem_file_name)\n\t\tcorrect_count = 0\n\t\tread = 1 << (num_address_bits + num_data_bits + 1) #read bit\n\t\twrite = 1 << (num_address_bits + num_data_bits)\n\t\tread_set = 1 << num_data_bits #to set if we are doing a read\n\t\tdata_mask = int('1'*num_data_bits, 2)\n\t\taddr_mask = int('1'*num_address_bits, 2) << num_data_bits\n\t\tout_file.write('v2.0 raw\\n')\n\t\tout_file.write(\"#Test input file name: %s\\n\" % command_file_name)\n\t\tout_file.write(\"#Memory file name: %s\\n\" % mem_file_name)\n\t\t#out_file.write('0\\n') #first line is 0 because before first clock tick we haven't done anything\n\t\tcmd_fil.readline() #skip the header\n\t\tfor cmd in cmd_fil:\n\t\t\tcmd = cmd.split('#')[0] #keep only the part before the comments\n\t\t\tcmd = int(cmd,16)\n\t\t\taddress = (cmd & addr_mask) >> num_data_bits\n\t\t\tdata = cmd & data_mask\n\t\t\t\n\t\t\tif cmd & read: #doing a write\n\t\t\t\tout_file.write( '%x\\n' % (read_set | mem[address]))\n\t\t\t\tcorrect_count += 1\n\t\t\telif cmd & write: #doing a write\n\t\t\t\tmem[address] = data \n\t\t\t\tout_file.write('%x\\n' % mem[address])\n\t\t\telse: #doing nothing\n\t\t\t\tout_file.write('0\\n')\n\t\t\n\t\tout_file.write('#Final correct count: %d\\n' % correct_count)\n\ndef read_mem_file(mem_file_name):\n\twith open(mem_file_name) as mem_fil:\n\t\tmem = []\n\t\tmem_fil.readline() #skip the header\n\t\tfor line in mem_fil:\n\t\t\tline = line.strip() #remove \n\t\t\tfor i in range(len(line), 0, -2):\n\t\t\t\tmem.append(int(line[i-2:i],16))\n\t\treturn mem\n\t\t\t\n\t\t\n\t\ndef main():\n\t\n\t#make_sequential_mem('seq_mem.txt', 8, 32)\n\t#make_random_mem('rand_mem.txt', 1, 8, 32)\n\trandom.seed(1)\n\t\n\t#sequential_read('seq_read1.txt', 24, 0, 10, 8)\n\t#make_solution('seq_read1_seq_mem_sol.txt', 'seq_read1.txt', 'seq_mem.txt', 10, 8)\n\t\n\t#sequential_write('seq_write1.txt', 24, 0, 5, 10, 8, 2, 3, 4)\n\t#make_solution('seq_write1_seq_mem_sol.txt', 'seq_write1.txt', 'seq_mem.txt', 10, 8)\n\t\n\t\n\t#targeted_set_read('set1_targeted_read.txt', 6, 1, 10, 2, 4, 8)\n\t#make_solution('set1_targeted_read_seq_mem_sol.txt', 'set1_targeted_read.txt', 'seq_mem.txt', 10, 8)\n\t\n\t#targeted_set_write('set0_targeted_write.txt', 6, 0, 5, 10, 2, 4, 8)\n\t#make_solution('set0_targeted_write_seq_mem_sol.txt', 'set0_targeted_write.txt', 'seq_mem.txt', 10, 8)\n\t\n\tconstrained_random_read_write('random0.txt',24*4, 24*2 - 1, 10, 8)\n\t#make_solution('random0_seq_mem_sol.txt', 'random0.txt', 'seq_mem.txt', 10, 8)\n\t\n\t#constrained_random_read_write('final_test.txt',24*6, 24*3 - 1, 10, 8)\n\t#make_solution('final_test_rand_mem_sol.txt', 'final_test.txt', 'rand_mem.txt', 10, 8)\n\t\nmain()\n\n\t\t\n","sub_path":"cache_test_maker.py","file_name":"cache_test_maker.py","file_ext":"py","file_size_in_byte":11834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"429088668","text":"import scrapy\nfrom ..baseSpider import BaseSpider\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\nimport logging\nimport time\n\n\nclass WzljlSpider(BaseSpider):\n name = 'wzljl'\n source_name = '梧州零距离'\n allowed_domains = ['wz.wzljl.cn', 'www.wzljl.cn']\n spider_tags = ['梧州']\n start_urls = [\n 'http://wz.wzljl.cn/',\n 'http://www.wzljl.cn/node_440.htm',\n 'http://www.wzljl.cn/node_8654.htm',\n 'http://www.wzljl.cn/node_3780.htm'\n ]\n rules = [Rule(LinkExtractor(allow=(r'/\\?mdl=topic&do=view&id=\\d+')), callback='parse_item1', follow=False),\n Rule(LinkExtractor(allow=(r'http://www.wzljl.cn/content/\\d+-\\d+/\\d+/content_\\d+.htm')), callback='parse_item2', follow=False),\n Rule(LinkExtractor(allow=(r'https://mp.weixin.qq.com/s/\\w+')), callback='parse_item3', follow=False),\n ]\n\n def parse_item1(self, response):\n\n item = self.createItem(response)\n\n item['title'] = response.css('.content h1::text').extract_first()\n\n item['taskName'] = \"http://www.wzljl.cn/templateRes/201011/05/2730/2730/logo.jpg\"\n\n item['postBy'] = response.css('.content .wz_con span::text')[1].get()\n\n item['postOn'] = response.css('.content .wz_con em::text').re(r'\\d{4}\\-\\d{1,2}\\-\\d{1,2} \\d{2}:\\d{2}:\\d{2}')[0]\n\n item['text'] = ''.join(response.css('.wz_con_dd *::text').extract())\n\n return item\n\n def parse_item2(self, response):\n item = self.createItem(response)\n\n item['title'] = response.css('.zbt::text').extract_first()\n\n item['postBy'] = response.css('[align=right]::text').extract_first()[3:]\n\n item['postOn'] = response.css('.z03::text').extract_first().strip() + \":00\"\n\n item['text'] = ''.join(response.css('td p *::text').extract())\n\n return item\n\n def parse_item3(self, response):\n item = self.createItem(response)\n\n item['title'] = response.css('.rich_media_title::text').extract_first()\n\n item['postBy'] = response.css('section[powered-by=xiumi.us]::text')[-1]\n\n # 三种格式时间\n postOn = response.css('#publish_time::text')[0]\n postOn1 = postOn.re(r'\\d{4}\\-\\d{1,2}\\-\\d{1,2}')\n\n if not postOn1:\n postOn1 = postOn.re(r'\\d+小')\n num = 3600\n if not postOn1:\n postOn1 = postOn.re(r'\\d+ 天')[0]\n num = 3600*24\n else:\n postOn1 = postOn1[0]\n past_time = int(postOn1[:-1]) * num\n postOn1 = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(time.time())-past_time))\n else:\n postOn1 = postOn1[0]+' 00:00:00'\n\n item['text'] = ''.join(response.css('.rich_media_content *::text').extract())\n\n return item\n","sub_path":"build/lib/crawl2020/spiders/wzljl.py","file_name":"wzljl.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"531638515","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nHOST = \"localhost\"\nPORT = 4223\n#UID = \"64uer4\"\nUID = \"Mfb\"\n# master: 64uer4\n# ir: Lr8\noffset = 10.2\n\nfrom tinkerforge.ip_connection import IPConnection\n# from tinkerforge.brick_master import BrickMaster\nfrom tinkerforge.bricklet_distance_ir_v2 import BrickletDistanceIRV2\nfrom time import sleep\n\nif __name__ == \"__main__\":\n ipcon = IPConnection() # Create IP connection\n # master = BrickMaster(UID, ipcon) # Create device object\n dir = BrickletDistanceIRV2(UID, ipcon)\n\n ipcon.connect(HOST, PORT) # Connect to brickd\n # Don't use device before ipcon is connected\n\n # Get current stack voltage\n #blah = master.get_stack_current() # get_stack_voltage()\n #print(\"Info: \" + str(blah))\n distance = dir.get_distance()\n print(\"Distance: \" + str(distance/10.0) + \" cm\")\n\n while True:\n distance = dir.get_distance()\n print(\"Distance: \" + str(distance/10.0) + \" cm\")\n\n sleep(0.1)\n\n ipcon.disconnect()\n","sub_path":"prototypes/tinker/ir-distance.py","file_name":"ir-distance.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"170916400","text":"import adv_test\nfrom adv import *\n\ndef module():\n return W_Aoi\n\nclass W_Aoi(Adv):\n comment = ''\n a3 = ('sp',0.12,'fs')\n\n\n def init(this):\n if this.condition('big hitbox'):\n this.s1_addition = 4\n else:\n this.s1_addition = 1\n\n if this.condition('80 resist'):\n this.afflics.sleep.resist=80\n else:\n this.afflics.sleep.resist=100\n\n\n def s1_before(this, e):\n this.dmg_make('o_s1_hit1',1.47)\n this.afflics.sleep('s1',110,6.5)\n Teambuff('a1',0.15*this.afflics.sleep.get(),10).on()\n\n def s1_proc(this, e):\n if this.s1_addition == 4:\n this.dmg_make('o_s1_hit2',1.47)\n this.dmg_make('o_s1_hit3',1.47)\n this.dmg_make('o_s1_hit4',1.47)\n elif this.s1_addition == 1:\n pass\n\n\n\n def s2_before(this, e):\n r = this.afflics.sleep.get()\n coef = 1.40*5 * (1-r)\n return coef\n\n def s2_proc(this, e):\n r = this.afflics.sleep.get()\n coef = 1.40*5 * r\n this.dmg_make('s2',coef)\n coef = (2.80-1.40)*5 * r\n this.dmg_make('o_s2_boost',coef)\n\n\n\n\nif __name__ == '__main__':\n conf = {}\n conf['acl'] = \"\"\"\n `s1, seq=5 or fsc\n `s2, seq=5 or fsc\n `s3, seq=5 or fsc\n `fs, seq=5\n \"\"\"\n adv_test.test(module(), conf, verbose=0)\n\n","sub_path":"adv/w_aoi.py","file_name":"w_aoi.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42494874","text":"from django.forms import ModelForm,ValidationError\nfrom django.utils.translation import ugettext as _ #国际化\n\n#创建动态生成ModelForm类的函数\ndef create_model_form(request,admin_class):\n\t'''\n\t创建动态生成ModelForm类的函数\n\t:param request:\n\t:param admin_class:\n\t:return:\n\t'''\n\tdef default_clean(self):\n\t\t'''给所有form默认加一个clean验证:readonly字段验证,对整张只读表验证,clean钩子对整体验证'''\n\t\terror_list = []\n\t\tif self.instance.id: #这是一个修改的表单,如果为空就是一个添加表单,才判断字段字段值是否改变\n\t\t\tfor field in admin_class.readonly_fields:\n\t\t\t\tfield_val = getattr(self.instance,field) #从数据库中取到对应字段的值\n\n\t\t\t\tif hasattr(field_val,\"select_related\"): #多对多字段只读\n\t\t\t\t\tm2m_objs = getattr(field_val,\"select_related\")().select_related()\n\t\t\t\t\tm2m_vals = [i[0] for i in m2m_objs.values_list('id')]\n\t\t\t\t\tset_m2m_vals = set(m2m_vals)\t\t\t# print(\"cleaned data\",self.cleaned_data)\n\t\t\t\t\tset_m2m_vals_from_frontend = set([i.id for i in self.cleaned_data.get(field)])\n\t\t\t\t\tif set_m2m_vals != set_m2m_vals_from_frontend: #1 判断多对多字段是否修改\n\t\t\t\t\t\tself.add_error(field,\"readonly field\")\n\t\t\t\t\tcontinue\n\t\t\t\tfield_val_from_frontand = self.cleaned_data.get(field)\n\t\t\t\tif field_val != field_val_from_frontand: #2 判断非多对多字段是否修改\n\t\t\t\t\terror_list.append(\n\t\t\t\t\t\tValidationError(\n\t\t\t\t\t\t\t_('Field %(field)s is readonly,data should be %(val)s'),\n\t\t\t\t\t\t\tcode='invalid',\n\t\t\t\t\t\t\tparams={'field':field,'val':field_val},\n\t\t\t\t\t\t))\n\t\t\t\t#readonly_table check\n\t\t\t\t# if admin_class.readonly_table: #3 防止黑客自己写提交按钮提交整张表都是只读权限的表\n\t\tif admin_class.readonly_table: #3 防止黑客自己写提交按钮提交整张表都是只读权限的表\n\t\t\traise ValidationError(\n\t\t\t\t\t_('Table is readonly,cannot be modified ro added'),\n\t\t\t\t\tcode='invalid',\n\t\t\t\t)\n\t\tself.ValidationError = ValidationError #这样用户自己验证时就可以不必导入了\n\n\t\t#在这个cleaned方法中定义一个允许用户自己定义的方法做验证\n\t\tresponse = admin_class.default_form_validation(self) #4 clean钩子对整体验证\n\t\tif response:\n\t\t\terror_list.append(response)\n\n\t\tif error_list:\n\t\t\traise ValidationError(error_list)\n\tdef __new__(cls,*args,**kwargs):\n\t\t'''在创建form时添加样式,为每个字段预留钩子'''\n\t\tfor field_name,field_obj in cls.base_fields.items():\n\t\t\tfield_obj.widget.attrs['class'] = \"form-control\"\n\t\t\tif not hasattr(admin_class,\"is_add_form\"):\n\t\t\t\tif field_name in admin_class.readonly_fields:\n\t\t\t\t\tfield_obj.widget.attrs['disabled'] = \"disabled\"\n\n\t\t\t# clean_字段名 是字段钩子(每个字段都有对应的这个钩子)\n\t\t\tif hasattr(admin_class, \"clean_%s\" % field_name): # 用户自定义字段验证\n\t\t\t\tfield_clean_func = getattr(admin_class, \"clean_%s\" % field_name)\n\t\t\t\tsetattr(cls, \"clean_%s\" % field_name, field_clean_func)\n\t\treturn ModelForm.__new__(cls) #调用一下ModelForm的__new__方法否则不往下走\n\n\n\t'''动态生成ModelForm'''\n\tclass Meta:\n\t\tmodel = admin_class.model\n\t\tfields = \"__all__\"\n\t\texclude = admin_class.modelform_exclude_fields # 那些字段不显示\n\t\t# exclude = (\"qq\",)\n\tattrs = {'Meta':Meta}\n\t_model_form_class = type(\"DynamicModelForm\",(ModelForm,),attrs)\n\tsetattr(_model_form_class,\"__new__\",__new__)\n\tsetattr(_model_form_class,'clean',default_clean) #动态将_default_clean__函数添加到类中\n\treturn _model_form_class","sub_path":"Desktop/rewriteDjangoAdmin/kind_admin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"392683010","text":"import numpy as np\nimport params\nfrom dataset import Reader\n# import utils\nfrom create_batch import get_pair_batch_train, get_pair_batch_test, toarray, get_pair_batch_train_common, toarray_float\nimport torch\nfrom model import BiLSTM_Attention\nimport torch.nn as nn\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import precision_recall_fscore_support\nimport os\nimport logging\nimport math\nfrom matplotlib import pyplot as plt\n\n\ndef Triplenet(ratio, kkkk, data):\n # Dataset parameters\n params.batch_size = 2048\n params.lam2 = 1.0\n params.lam1 = 0\n data_path = data\n params.num_neighbor = 5\n params.anomaly_ratio = ratio\n model_name = \"TripleNet_local_2048\"\n if data_path == params.data_dir_DBPEDIA:\n data_name = \"DBpedia\"\n params.batch_size = 3600\n else:\n data_name = \"NELL\"\n\n dataset = Reader(data_path, isInjectTopK=False)\n all_triples = dataset.train_data\n labels = dataset.labels\n train_idx = list(range(len(all_triples) // 2))\n num_iterations = math.ceil(dataset.num_triples_with_anomalies / params.batch_size)\n total_num_anomalies = dataset.num_anomalies\n logging.basicConfig(level=logging.INFO)\n file_handler = logging.FileHandler(os.path.join(params.log_folder,\n model_name + \"_\" + data_name + \"_\" + str(ratio) + \"_\" + \"_log.txt\"))\n logger = logging.getLogger()\n logger.addHandler(file_handler)\n logging.info('There are %d Triples with %d anomalies in the graph.' % (len(dataset.labels), total_num_anomalies))\n\n params.total_ent = dataset.num_entity\n params.total_rel = dataset.num_relation\n\n model_saved_path = model_name + \"_\" + data_name + \"_\" + str(ratio) + \".ckpt\"\n model_saved_path = os.path.join(params.out_folder, model_saved_path)\n # model.load_state_dict(torch.load(model_saved_path))\n # Model BiLSTM_Attention\n model = BiLSTM_Attention(params.input_size_lstm, params.hidden_size_lstm, params.num_layers_lstm, params.dropout,\n params.alpha).to(params.device)\n criterion = nn.MarginRankingLoss(params.gama)\n optimizer = torch.optim.Adam(model.parameters(), lr=params.learning_rate)\n #\n for k in range(kkkk):\n for it in range(num_iterations):\n batch_h, batch_r, batch_t, batch_size = get_pair_batch_train_common(dataset, it, train_idx,\n params.batch_size,\n params.num_neighbor)\n batch_h = torch.LongTensor(batch_h).to(params.device)\n batch_t = torch.LongTensor(batch_t).to(params.device)\n batch_r = torch.LongTensor(batch_r).to(params.device)\n # input_triple, batch_size = get_pair_batch_train_common(dataset, it, train_idx,\n # params.batch_size,\n # params.num_neighbor)\n # input_triple = Variable(torch.LongTensor(input_triple).cuda())\n # batch_size = input_triples.size(0)\n out, out_att = model(batch_h, batch_r, batch_t)\n out = out.reshape(batch_size, -1, 2 * 3 * params.BiLSTM_hidden_size)\n out_att = out_att.reshape(batch_size, -1, 2 * 3 * params.BiLSTM_hidden_size)\n\n pos_h = out[:, 0, :]\n pos_z0 = out_att[:, 0, :]\n # pos_z1 = out_att[:, 1, :]\n neg_h = out[:, 1, :]\n neg_z0 = out_att[:, 1, :]\n # neg_z1 = out_att[:, 3, :]\n\n # loss function\n # positive\n pos_loss = params.lam1 * torch.norm(pos_h - pos_z0, p=2, dim=1) + \\\n params.lam2 * torch.norm(pos_h[:, 0:2 * params.BiLSTM_hidden_size] +\n pos_h[:, 2 * params.BiLSTM_hidden_size:2 * 2 * params.BiLSTM_hidden_size] -\n pos_h[:, 2 * 2 * params.BiLSTM_hidden_size:2 * 3 * params.BiLSTM_hidden_size], p=2,\n dim=1)\n # negative\n neg_loss = params.lam1 * torch.norm(neg_h - neg_z0, p=2, dim=1) + \\\n params.lam2 * torch.norm(neg_h[:, 0:2 * params.BiLSTM_hidden_size] +\n neg_h[:, 2 * params.BiLSTM_hidden_size:2 * 2 * params.BiLSTM_hidden_size] -\n neg_h[:, 2 * 2 * params.BiLSTM_hidden_size:2 * 3 * params.BiLSTM_hidden_size], p=2,\n dim=1)\n\n y = -torch.ones(batch_size).to(params.device)\n loss = criterion(pos_loss, neg_loss, y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n pos_loss_value = torch.sum(pos_loss) / (batch_size * 2.0)\n neg_loss_value = torch.sum(neg_loss) / (batch_size * 2.0)\n logging.info('There are %d Triples in this batch.' % batch_size)\n logging.info('Epoch: %d-%d, pos_loss: %f, neg_loss: %f, Loss: %f' % (\n k, it + 1, pos_loss_value.item(), neg_loss_value.item(), loss.item()))\n\n torch.save(model.state_dict(), model_saved_path)\n # # #\n # dataset = Reader(data_path, \"test\")\n model1 = BiLSTM_Attention(params.input_size_lstm, params.hidden_size_lstm, params.num_layers_lstm, params.dropout,\n params.alpha).to(params.device)\n model1.load_state_dict(torch.load(model_saved_path))\n model1.eval()\n with torch.no_grad():\n all_loss = []\n all_label = []\n start_id = 0\n\n for i in range(num_iterations):\n batch_h, batch_r, batch_t, labels, start_id, batch_size = get_pair_batch_test(dataset, params.batch_size,\n params.num_neighbor, start_id)\n # labels = labels.unsqueeze(1)\n # batch_size = input_triples.size(0)\n batch_h = torch.LongTensor(batch_h).to(params.device)\n batch_t = torch.LongTensor(batch_t).to(params.device)\n batch_r = torch.LongTensor(batch_r).to(params.device)\n labels = labels.to(params.device)\n out, out_att = model1(batch_h, batch_r, batch_t)\n\n # out_att = out_att.reshape(batch_size, 2, 2 * 3 * params.BiLSTM_hidden_size)\n out_att_view0 = out_att\n # out_att_view1 = out_att[:, 1, :]\n # [B, 600] [B, 600]\n\n loss = params.lam1 * torch.norm(out_att_view0 - out, p=2, dim=1) + \\\n params.lam2 * torch.norm(out[:, 0:2 * params.BiLSTM_hidden_size] +\n out[:, 2 * params.BiLSTM_hidden_size:2 * 2 * params.BiLSTM_hidden_size] -\n out[:, 2 * 2 * params.BiLSTM_hidden_size:2 * 3 * params.BiLSTM_hidden_size], p=2, dim=1)\n\n all_loss += loss\n all_label += labels\n\n logging.info('[Train] Evaluation on %d batch of Original graph' % i)\n\n total_num = len(all_label)\n\n # print(\"Total number of test tirples: \", total_num)\n AUC11 = roc_auc_score(toarray(all_label), toarray_float(all_loss))\n logging.info('[Train] AUC of %d triples: %f' % (total_num, AUC11))\n\n ratios = [0.001, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15]\n for i in range(len(ratios)):\n num_k = int(ratios[i] * dataset.num_original_triples)\n top_loss, top_indices = torch.topk(toarray_float(all_loss), num_k, largest=True, sorted=True)\n top_labels = toarray([all_label[top_indices[iii]] for iii in range(len(top_indices))])\n top_sum = top_labels.sum()\n recall = top_sum * 1.0 / total_num_anomalies\n precision = top_sum * 1.0 / num_k\n\n logging.info('[Train][%s][%s] Precision %f -- %f : %f' % (data_name, model_name, ratio, ratios[i], precision))\n logging.info('[Train][%s][%s] Recall %f-- %f : %f' % (data_name, model_name, ratio, ratios[i], recall))\n logging.info('[Train][%s][%s] anomalies in total: %d -- discovered:%d -- K : %d' % (\n data_name, model_name, total_num_anomalies, top_sum, num_k))\n\n if top_sum.item() < num_k and top_sum.item() != 0:\n # print(top_sum.item(), num_k)\n AUC_K = roc_auc_score(toarray(top_labels), toarray_float(top_loss))\n logging.info('[Train][%s][%s] xxxxxxxxxxxxxxxxxxxxxxx AUC %f -- %f : %f' % (\n data_name, model_name, ratio, ratios[i], AUC_K))\n\n max_top_k = total_num_anomalies * 2\n # min_top_k = total_num_anomalies // 10\n\n top_loss, top_indices = torch.topk(toarray_float(all_loss), max_top_k, largest=True, sorted=True)\n top_labels = toarray([all_label[top_indices[iii]] for iii in range(len(top_indices))])\n\n anomaly_discovered = []\n for i in range(max_top_k):\n if i == 0:\n anomaly_discovered.append(top_labels[i])\n else:\n anomaly_discovered.append(anomaly_discovered[i-1] + top_labels[i])\n\n results_interval_10 = np.array([anomaly_discovered[i * 10] for i in range(max_top_k // 10)])\n\n logging.info('[Train] final results: %s' % str(results_interval_10))\n\n top_k = np.arange(1, max_top_k + 1)\n\n assert len(top_k) == len(anomaly_discovered), 'The size of result list is wrong'\n\n precision_k = np.array(anomaly_discovered) / top_k\n recall_k = np.array(anomaly_discovered) * 1.0 / total_num_anomalies\n\n precision_interval_10 = [precision_k[i * 10] for i in range(max_top_k // 10)]\n # print(precision_interval_10)\n logging.info('[Train] final Precision: %s' % str(precision_interval_10))\n recall_interval_10 = [recall_k[i * 10] for i in range(max_top_k // 10)]\n # print(recall_interval_10)\n logging.info('[Train] final Recall: %s' % str(recall_interval_10))\n\n\n# anomaly_injected_ratios = [0.01, 0.05, 0.10, 0.001, 0.025, 0.075]\nnum_epochs = [1, 2, 3, 5]\nanomaly_injected_ratios = [0.05]\ndataset = [params.data_dir_DBPEDIA]\n\nfor num in num_epochs:\n for ratio in anomaly_injected_ratios:\n for data in dataset:\n Triplenet(ratio, num, data)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"352720837","text":"#!/usr/bin/env python2.7\nimport copy\nimport threading\nfrom collections import OrderedDict\n\nimport cv2\nimport os\nimport rospy\nfrom dynamic_reconfigure.server import Server\nfrom humanoid_league_msgs.msg import BallInImage, BallsInImage\nfrom sensor_msgs.msg import Image, RegionOfInterest\nfrom cv_bridge import CvBridge, CvBridgeError\n#from humanoid_league_image_marker.cfg import image_marker_paramsConfig\n\n\ndef draw_ball(cv_img, ball):\n \"\"\"Draws a circle on the image where the ball was seen.\"\"\"\n i = [0, 0, 0]\n i[0] = int(ball.center.x)\n i[1] = int(ball.center.y)\n i[2] = int(ball.diameter / 2.0)\n c = (255, 0, 0)\n # outer circle\n cv2.circle(cv_img, (i[0], i[1]), i[2], c, 2)\n # circle center\n cv2.circle(cv_img, (i[0], i[1]), 2, (0, 0, 255), 3)\n\n\ndef draw_ball_candidates(cv_img, candidates):\n \"\"\"Draws a list of ball candidates. The color is depending on the confidence.\"\"\"\n if len(candidates) > 0:\n for can in candidates:\n i = [0, 0, 0]\n i[0] = int(can.center.x)\n i[1] = int(can.center.y)\n i[2] = int(can.diameter / 2.0)\n\n if can.confidence >= 0.5:\n c = (0, 255, 0)\n else:\n c = (0, 0, 255)\n # print(p)\n # draw the outer circle\n cv2.circle(cv_img, (i[0], i[1]), i[2], c, 2)\n # draw the center of the circle\n cv2.circle(cv_img, (i[0], i[1]), 2, (0, 0, 255), 3)\n\n\nclass ImageMarker:\n \"\"\"This class starts a ROS node which takes images and draws recognized RoboCup Soccer objects on to it.\n Dynamic reconfigure is used to activate and deactive certain drawings.\"\"\"\n\n def __init__(self):\n # todo implement final ball, goal posts and lines\n rospy.init_node(\"humanoid_league_image_marker\")\n\n self.bridge = CvBridge()\n self.images = OrderedDict()\n self.ball_candidates = OrderedDict()\n self.balls = OrderedDict()\n\n self.img_lock = threading.Lock()\n self.can_lock = threading.Lock()\n\n self.ball_roi_active = True\n self.candidates_active = True\n self.ball_active = True\n self.goal_roi_active = True\n self.goal_posts_active = True\n self.goals_active = True\n self.obstacle_roi_active = True\n self.obstacles_active = True\n self.lines_roi_active = True\n self.line = True\n\n #self.server = Server(image_marker_paramsConfig, self.reconfigure)\n self.viz_publisher = rospy.Publisher(\"image_marker_image\", Image, queue_size=10)\n rospy.Subscriber(\"image_raw\", Image, self._image_cb, queue_size=10)\n rospy.Subscriber(\"ball_candidates\", BallsInImage, self._candidates_cb, queue_size=10)\n\n self.run()\n\n def run(self):\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n with self.img_lock:\n images = copy.deepcopy(self.images)\n\n for t in images.keys(): # imgages who are wating\n img = images.pop(t) # get image from queue\n cv_img = self.bridge.imgmsg_to_cv2(img, \"bgr8\")\n with self.can_lock:\n if t in self.ball_candidates.keys(): # Check if all data to draw is there\n print(\"test3\")\n candidates = self.ball_candidates.pop(t)\n # ball = self.balls.pop(t)\n\n if self.candidates_active:\n rospy.logwarn(\"1\")\n draw_ball_candidates(cv_img, candidates)\n # if self.ball_active:\n # draw_ball(cv_img, ball)\n\n out_msg = self.bridge.cv2_to_imgmsg(cv_img, encoding=\"bgr8\")\n self.viz_publisher.publish(out_msg)\n rate.sleep()\n\n def _image_cb(self, msg):\n with self.img_lock:\n self.images[msg.header.stamp] = msg\n\n if len(self.images) >= 10:\n self.images.popitem(last=False)\n\n def _candidates_cb(self, msg):\n with self.can_lock:\n self.ball_candidates[msg.header.stamp] = msg.candidates\n if len(self.ball_candidates) > 50:\n self.ball_candidates.popitem(last=False)\n\n def reconfigure(self, config, level):\n\n self.ball_roi_active = config[\"ball_ROI\"]\n self.candidates_active = config[\"ball_candidates\"]\n self.ball_active = config[\"ball\"]\n\n self.goal_roi_active = config[\"goal_post_ROI\"]\n self.goal_posts_active = config[\"goal_posts\"]\n self.goals_active = config[\"goals\"]\n\n self.obstacle_roi_active = config[\"obstacle_ROI\"]\n self.obstacles_active = config[\"obstacles\"]\n\n self.lines_roi_active = config[\"line_ROI\"]\n self.line = config[\"lines\"]\n return config\n\n\nif __name__ == \"__main__\":\n viz = ImageMarker()\n","sub_path":"soccer/src/humanoid_league_visualization/humanoid_league_image_marker/src/humanoid_league_image_marker/image_marker.py","file_name":"image_marker.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"264239106","text":"import argparse\nfrom data_io import DataFolder, ScanWrapper\nfrom utils import get_logger\nfrom paral import AbstractParallelRoutine\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import color, exposure\nfrom matplotlib import colors\nimport matplotlib.gridspec as gridspec\nfrom skimage.util import compare_images\nimport os\nimport pandas as pd\nfrom matplotlib.pyplot import cm\n\n\nlogger = get_logger('Plot heatmap')\n\n\nclass EvaluationDatabase:\n def __init__(self,\n body_dice_csv_folder,\n thres_body_dice,\n lung_dice_csv_folder,\n thres_lung_dice,\n jac_csv_folder,\n thres_neg_jac_ratio,\n test_prefix):\n self._body_dice_csv_folder = body_dice_csv_folder\n self._body_dice_thres = thres_body_dice\n self._lung_dice_csv_folder = lung_dice_csv_folder\n self._lung_dice_thres = thres_lung_dice\n self._jac_csv_folder = jac_csv_folder\n self._thres_neg_jac_ratio = thres_neg_jac_ratio\n self._test_data_list = {}\n self._out_dpi = 15\n # self._sub_title_font_size = 150\n # self._sub_title_font_size_double = 100\n self._sub_title_font_size = 50\n self._sub_title_font_size_double = 20\n self._test_prefix = test_prefix\n\n def read_data_list(self):\n range_search_radius, range_kp_disp, range_reg, range_sim_size = self._get_range()\n\n for idx_search_radius in range(len(range_search_radius)):\n for idx_kp_disp in range(len(range_kp_disp)):\n for idx_range_reg in range(len(range_reg)):\n for idx_range_sim_size in range(len(range_sim_size)):\n test_name = self._get_test_name(idx_search_radius,\n idx_kp_disp,\n idx_range_reg,\n idx_range_sim_size)\n complete_p = self._check_if_test_complete(test_name)\n if complete_p:\n test_data = self._read_data_of_test(test_name)\n self._test_data_list[test_name] = test_data\n logger.info(f'Read {len(self._test_data_list)} data')\n\n def save_data_list_csv(self, csv_path):\n data_list_df = pd.DataFrame.from_dict(self._test_data_list, orient='index')\n print(data_list_df)\n logger.info(f'Save csv file to {csv_path}')\n data_list_df.to_csv(csv_path)\n\n def _check_if_test_complete(self, test_name):\n csv_path = os.path.join(self._body_dice_csv_folder, test_name)\n return os.path.exists(csv_path)\n\n def get_statistics(self, val_flag):\n statics = {}\n\n data_list = [self._test_data_list[test_name][val_flag]\n for test_name in self._test_data_list]\n\n statics['min'] = np.min(data_list)\n statics['max'] = np.max(data_list)\n statics['mean'] = np.mean(data_list)\n statics['std'] = np.std(data_list)\n\n print(f'Show statistics of {val_flag}:')\n print(statics)\n return statics\n\n def _read_data_of_test(self, test_name):\n result_dict = {}\n\n body_dice_df = pd.read_csv(os.path.join(self._body_dice_csv_folder, test_name))\n body_np_list = body_dice_df['Dice'].to_numpy()\n result_dict['BodyDiceMean'] = np.mean(body_np_list)\n result_dict['BodyDiceMin'] = np.min(body_np_list)\n\n body_outlier_df = body_dice_df[body_dice_df['Dice'] < self._body_dice_thres]\n body_outlier_list = body_outlier_df['Scan'].tolist()\n result_dict['BodyDiceOutliers'] = body_outlier_list\n result_dict['NumBodyDiceOutliers'] = len(body_outlier_list)\n\n body_dice_worst_n = np.argsort(body_np_list)[0:5]\n body_dice_name_list = body_dice_df['Scan'].tolist()\n body_dice_worst_n_name_list = [body_dice_name_list[idx] for idx in body_dice_worst_n]\n result_dict['BodyDiceWorst5Scan'] = body_dice_worst_n_name_list\n\n lung_dice_df = pd.read_csv(os.path.join(self._lung_dice_csv_folder, test_name))\n lung_np_list = lung_dice_df['Dice'].to_numpy()\n result_dict['LungDiceMean'] = np.mean(lung_np_list)\n result_dict['LungDiceMin'] = np.min(lung_np_list)\n\n lung_median_idx = np.argsort(lung_np_list)[len(lung_np_list)//2]\n median_scan_name = lung_dice_df['Scan'].tolist()[lung_median_idx]\n result_dict['LungDiceMedianScan'] = median_scan_name\n\n lung_dice_worst_n = np.argsort(lung_np_list)[0:5]\n lung_dice_name_list = lung_dice_df['Scan'].tolist()\n lung_dice_worst_n_name_list = [lung_dice_name_list[idx] for idx in lung_dice_worst_n]\n result_dict['LungDiceWorst5Scan'] = lung_dice_worst_n_name_list\n\n result_dict['SumDiceMean'] = result_dict['BodyDiceMean'] + result_dict['LungDiceMean']\n\n lung_outlier_df = lung_dice_df[lung_dice_df['Dice'] < self._lung_dice_thres]\n lung_outlier_list = lung_outlier_df['Scan'].tolist()\n result_dict['LungDiceOutliers'] = lung_outlier_list\n result_dict['NumLungDiceOutliers'] = len(lung_outlier_list)\n\n jac_df = pd.read_csv(os.path.join(self._jac_csv_folder, test_name))\n jac_neg_ratio_list = jac_df['NegRatio'].to_numpy()\n result_dict['NegJacRatioMean'] = np.mean(jac_neg_ratio_list)\n\n jac_neg_ratio_outlier_df = jac_df[jac_df['NegRatio'] > self._thres_neg_jac_ratio]\n jac_neg_ratio_outlier_list = jac_neg_ratio_outlier_df['Scan'].tolist()\n result_dict['NegJacRatioOutliers'] = jac_neg_ratio_outlier_list\n result_dict['NumNegJacRatioOutliers'] = len(jac_neg_ratio_outlier_list)\n\n jac_neg_median_idx = np.argsort(jac_neg_ratio_list)[len(jac_neg_ratio_list)//2]\n median_scan_name = jac_df['Scan'].tolist()[jac_neg_median_idx]\n result_dict['JacNegMedianScan'] = median_scan_name\n\n jac_neg_worst_n = np.argsort(jac_neg_ratio_list)[-5:]\n jac_neg_name_list = jac_df['Scan'].tolist()\n jac_neg_worst_n_name_list = [jac_neg_name_list[idx] for idx in jac_neg_worst_n]\n result_dict['JacNegWorst5Scan'] = jac_neg_worst_n_name_list\n\n outlier_dice_all = result_dict['BodyDiceOutliers'] + result_dict['LungDiceOutliers']\n outlier_dice_all = set(outlier_dice_all)\n outlier_dice_all = (list(outlier_dice_all))\n result_dict['NumDiceOutliers'] = len(outlier_dice_all)\n\n outlier_all = result_dict['BodyDiceOutliers'] + result_dict['LungDiceOutliers'] + result_dict['NegJacRatioOutliers']\n outlier_all = set(outlier_all)\n outlier_all = (list(outlier_all))\n result_dict['AllOutliers'] = outlier_all\n result_dict['NumAllOutliers'] = len(outlier_all)\n\n return result_dict\n\n def plot_heat_map_grid(self, out_png, val_flag):\n num_search_radius = self._get_num_sample('search_radius')\n num_kp_disp = self._get_num_sample('kp_disp')\n num_reg = self._get_num_sample('reg')\n num_sim_size = self._get_num_sample('sim_size')\n\n fig_size_scaler = 2\n\n # fig_width = (10 * num_kp_disp + 10) * num_reg\n # fig_height = (10 * num_search_radius + 10) * num_sim_size\n\n fig_width = (fig_size_scaler * num_kp_disp + fig_size_scaler) * num_reg\n fig_height = (fig_size_scaler * num_search_radius + fig_size_scaler) * num_sim_size\n\n fig = plt.figure(figsize=(fig_width, fig_height))\n gs = gridspec.GridSpec(num_sim_size, num_reg)\n gs.update(wspace=0.2, hspace=0.2)\n\n val_statics = self.get_statistics(val_flag)\n\n for idx_sim_size in range(num_sim_size):\n sim_size = self._get_variable_range_idx('sim_size', idx_sim_size)\n for idx_reg in range(num_reg):\n # print(f'Plot idx_sim_size {idx_sim_size}, idx_reg {idx_reg}')\n reg_val = self._get_variable_range_idx('reg', idx_reg)\n data_matrix = self._get_data_matrix_search_radius_kp_disp(\n idx_sim_size,\n idx_reg,\n val_flag)\n self._plot_one_heatmap(\n idx_sim_size,\n idx_reg,\n data_matrix,\n gs,\n val_statics['min'],\n val_statics['max'],\n f'Reg. {round(reg_val, 3)}, Sim. Patch Size {sim_size}\\nX: KPs Disp, Y: Search Range.'\n )\n\n out_eps = out_png.replace('.png', '.eps')\n logger.info(f'Save png to {out_eps}')\n # plt.savefig(out_png, bbox_inches='tight', pad_inches=0, dpi=self._out_dpi)\n plt.savefig(out_eps, bbox_inches='tight', pad_inches=0, dpi=self._out_dpi)\n\n def _plot_one_heatmap(self, idx_row, idx_column, data_matrix, gs, vmin, vmax, title_str):\n range_search_radius, range_kp_disp, _, _ = self._get_range()\n\n ax = plt.subplot(gs[idx_row, idx_column])\n plt.imshow(\n data_matrix,\n cmap='hot',\n norm=colors.Normalize(vmin=vmin, vmax=vmax)\n )\n\n ax.set_yticks(np.arange(len(range_search_radius)))\n ax.set_xticks(np.arange(len(range_kp_disp)))\n\n ax.set_yticklabels(range_search_radius, {'fontsize': self._sub_title_font_size})\n ax.set_xticklabels(range_kp_disp, {'fontsize': self._sub_title_font_size})\n\n # Loop over data dimensions and create text annotations.\n for idx_search_radius in range(len(range_search_radius)):\n for idx_kp_disp in range(len(range_kp_disp)):\n ax.text(idx_kp_disp, idx_search_radius, round(data_matrix[idx_search_radius, idx_kp_disp], 5),\n ha=\"center\", va=\"center\", color=\"b\", fontdict={'fontsize': self._sub_title_font_size_double})\n # ax.text(idx_kp_disp, idx_search_radius, data_matrix[idx_search_radius, idx_kp_disp],\n # ha=\"center\", va=\"center\", color=\"b\", fontdict={'fontsize': self._sub_title_font_size})\n\n [t.set_visible(True) for t in ax.get_xticklabels()]\n [t.set_visible(True) for t in ax.get_yticklabels()]\n\n ax.set_title(title_str, fontsize=self._sub_title_font_size_double)\n\n def _get_data_matrix_search_radius_kp_disp(\n self,\n idx_sim_size,\n idx_reg,\n val_flag):\n\n num_search_radius = self._get_num_sample('search_radius')\n num_kp_disp = self._get_num_sample('kp_disp')\n\n data_matrix = np.zeros((num_search_radius, num_kp_disp)).astype(float)\n for idx_search_radius in range(num_search_radius):\n for idx_kp_disp in range(num_kp_disp):\n test_name = self._get_test_name(\n idx_search_radius,\n idx_kp_disp,\n idx_reg,\n idx_sim_size)\n if test_name in self._test_data_list:\n data_matrix[idx_search_radius][idx_kp_disp] = self._test_data_list[test_name][val_flag]\n else:\n data_matrix[idx_search_radius][idx_kp_disp] = np.nan\n\n return data_matrix\n\n def _get_num_sample(self, which_variable):\n range_search_radius, range_kp_disp, range_reg, range_sim_size = self._get_range()\n\n val_dict = {\n 'search_radius': len(range_search_radius),\n 'kp_disp': len(range_kp_disp),\n 'reg': len(range_reg),\n 'sim_size': len(range_sim_size)\n }\n\n return val_dict[which_variable]\n\n def _get_variable_range_idx(self, which_variable, idx):\n range_search_radius, range_kp_disp, range_reg, range_sim_size = self._get_range()\n\n val_dict = {\n 'search_radius': range_search_radius,\n 'kp_disp': range_kp_disp,\n 'reg': range_reg,\n 'sim_size': range_sim_size\n }\n\n return val_dict[which_variable][idx]\n\n def _get_test_name(self, idx_search_radius, idx_kp_disp, idx_reg, idx_sim_size):\n # idx_search_radius = idx_search_radius + 5\n # idx_reg = idx_reg + 2\n # idx_sim_size = idx_sim_size + 1\n return f'{self._test_prefix}_{idx_search_radius}_{idx_kp_disp}_{idx_reg}_{idx_sim_size}'\n\n @staticmethod\n def _get_range():\n # Stage 1\n # range_search_radius = np.arange(10, 31, 5, dtype=int)\n # range_kp_disp = np.arange(6, 15, 2, dtype=int)\n # range_reg = np.arange(0.4, 1.7, 0.3, dtype=float)\n # range_sim_size = np.arange(3, 10, 3, dtype=int)\n\n range_search_radius = np.arange(10, 51, 5, dtype=int)\n range_kp_disp = np.arange(6, 15, 2, dtype=int)\n range_reg = np.arange(0.4, 2.3, 0.3, dtype=float)\n range_sim_size = np.arange(3, 10, 3, dtype=int)\n\n # # Stage 2\n # range_search_radius = np.arange(4, 17, 3, dtype=int)\n # range_kp_disp = np.arange(6, 15, 2, dtype=int)\n # range_reg = np.arange(0.4, 1.7, 0.3, dtype=float)\n # range_sim_size = np.arange(3, 10, 3, dtype=int)\n\n # plot_search_radius = range_search_radius[5:9]\n # plot_kp_disp = range_kp_disp[0:4]\n # plot_reg = range_reg[2:3]\n # plot_sim_size = range_sim_size[1:2]\n\n # return plot_search_radius, plot_kp_disp, plot_reg, plot_sim_size\n return range_search_radius, range_kp_disp, range_reg, range_sim_size\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--in-archive-folder', type=str)\n parser.add_argument('--thres-lung-dice', type=float)\n parser.add_argument('--thres-body-dice', type=float)\n parser.add_argument('--thres-jac-neg-ratio', type=float)\n parser.add_argument('--out-png-folder', type=str)\n parser.add_argument('--save-csv-path', type=str)\n parser.add_argument('--test-prefix', type=str)\n args = parser.parse_args()\n\n database = EvaluationDatabase(\n os.path.join(args.in_archive_folder, 'body_dice'),\n args.thres_body_dice,\n os.path.join(args.in_archive_folder, 'lung_dice'),\n args.thres_lung_dice,\n os.path.join(args.in_archive_folder, 'jac'),\n args.thres_jac_neg_ratio,\n args.test_prefix\n )\n\n database.read_data_list()\n database.save_data_list_csv(args.save_csv_path)\n\n\n # database.get_statistics('BodyDiceMean')\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'outliers_body.png'),\n # 'NumBodyDiceOutliers'\n # )\n #\n # database.get_statistics('LungDiceMean')\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'outliers_lung.png'),\n # 'NumLungDiceOutliers'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'outliers_neg_jac.png'),\n # 'NumNegJacRatioOutliers'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'outliers_dice.png'),\n # 'NumDiceOutliers'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'outliers_all.png'),\n # 'NumAllOutliers'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'body_dice.png'),\n # 'BodyDiceMean'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'lung_dice.png'),\n # 'LungDiceMean'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'lung_dice_min.png'),\n # 'LungDiceMin'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'body_dice_min.png'),\n # 'BodyDiceMin'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'sum_dice.png'),\n # 'SumDiceMean'\n # )\n #\n # database.plot_heat_map_grid(\n # os.path.join(args.out_png_folder, 'jac_ratio_mean.png'),\n # 'NegJacRatioMean'\n # )\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/get_plot_fine_tune_grid_heatmap.py","file_name":"get_plot_fine_tune_grid_heatmap.py","file_ext":"py","file_size_in_byte":15930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"127765979","text":"import simpy\nimport random\nimport functools\nimport sys\n\nLight_Speed = 210000\n\nclass Packet(object):\n \"\"\" A very simple class that represents a packet.\n This packet will run through a queue at a switch output port.\n We use a float to represent the size of the packet in bytes so that\n we can compare to ideal M/M/1 queues.\n\n Parameters\n ----------\n time : float\n the time the packet arrives at the output queue.\n size : float\n the size of the packet in bytes\n id : int\n an identifier for the packet\n src, dst : int\n identifiers for source and destination\n flow_id : int\n small integer that can be used to identify a flow\n \"\"\"\n def __init__(self, time, size, id, src=\"a\", dst=\"z\", flow_id=0):\n # generation time\n self.time = time\n # packet size in bytes\n self.size = size\n self.id = id\n # source\n self.src = src\n # destination\n self.dst = dst\n self.flow_id = flow_id\n self.freq = -1\n\n def __repr__(self):\n return \"id: {}, src: {}, time: {}, size: {}\".\\\n format(self.id, self.src, self.time, self.size)\n\nclass PacketGenerator(object):\n \"\"\" Generates packets with given inter-arrival time distribution.\n Set the \"out\" member variable to the entity to receive the packet.\n\n Parameters\n ----------\n env : simpy.Environment\n the simulation environment\n adist : function\n a no parameter function that returns the successive inter-arrival times of the packets\n sdist : function\n a no parameter function that returns the successive sizes of the packets\n initial_delay : number\n Starts generation after an initial delay. Default = 0\n finish : number\n Stops generation at the finish time. Default is infinite\n\n\n \"\"\"\n def __init__(self, env, id, adist, sdist, initial_delay=0, finish=float(\"inf\"), flow_id=0):\n self.id = id\n self.env = env\n self.adist = adist\n self.sdist = sdist\n self.initial_delay = initial_delay\n self.finish = finish\n self.out = None\n self.packets_sent = 0\n self.action = env.process(self.run())\n self.flow_id = flow_id\n\n def run(self):\n \"\"\"The generator function used in simulations.\n \"\"\"\n yield self.env.timeout(self.initial_delay)\n while self.env.now < self.finish:\n # wait for next transmission\n yield self.env.timeout(self.adist())\n self.packets_sent += 1\n p = Packet(self.env.now, self.sdist(), self.packets_sent, src=self.id, flow_id=self.flow_id)\n\n # if(self.id[0] == 'L'): # LC\n # self.out.put(p, downstream=True)\n # elif(self.id[0] == 'O'): # ONU\n # self.out.put(p, upstream=True)\n self.out.put(p)\n\nclass SwitchPort(object):\n \"\"\" Models a switch output port with a given rate and buffer size limit in bytes.\n Set the \"out\" member variable to the entity to receive the packet.\n\n Parameters\n ----------\n env : simpy.Environment\n the simulation environment\n rate : float\n the bit rate of the port\n qlimit : integer (or None)\n a buffer size limit in bytes for the queue (does not include items in service).\n\n \"\"\"\n def __init__(self, env, rate, qlimit=None, debug=False):\n self.store = simpy.Store(env)\n self.rate = rate\n self.env = env\n self.out = None\n self.packets_rec = 0\n self.packets_drop = 0\n self.qlimit = qlimit\n self.byte_size = 0 # Current size of the queue in bytes\n self.debug = debug\n self.busy = 0 # Used to track if a packet is currently being sent\n self.action = env.process(self.run()) # starts the run() method as a SimPy process\n\n def run(self):\n while True:\n msg = (yield self.store.get())\n self.busy = 1\n self.byte_size -= msg.size\n yield self.env.timeout(msg.size*8.0/self.rate)\n if(msg.src[0] == 'L'): # LC\n self.out.put(msg, downstream=True)\n elif(msg.src[0] == 'O'): # ONU\n self.out.put(msg, upstream=True)\n self.busy = 0\n if self.debug:\n print(msg)\n\n def put(self, pkt):\n self.packets_rec += 1\n tmp = self.byte_size + pkt.size\n\n if self.qlimit is None:\n self.byte_size = tmp\n return self.store.put(pkt)\n if tmp >= self.qlimit:\n self.packets_drop += 1\n return\n else:\n self.byte_size = tmp\n return self.store.put(pkt)\n\n# Funções do SimComponents\n# https://www.grotto-networking.com/DiscreteEventPython.html\n\n###\n\nclass LineCard(object):\n def __init__(self, env, lcid, exp, out=None, distance=0):\n self.env = env\n self.lcid = lcid\n self.freq = lcid # pra simplificar, ID = frequencia\n self.delay_downstream = distance / float(Light_Speed)\n self.out = out\n\n self.downstream = simpy.Store(env)\n self.upstream = simpy.Store(env)\n\n def put(self, msg, downstream=False, upstream=False):\n print(\"%s recebeu Packet(src: %s, id: %d)\" % (self, msg.src, msg.id))\n if(downstream):\n yield self.downstream.put(msg)\n elif(upstream):\n yield self.upstream.put(msg) # packets que chegam\n\n def __repr__(self):\n return \"LineCard (id:%d)\" % self.lcid\n\nclass OLT(object):\n def __init__(self, env, lcs_qty, distance_splitter, distance_lcs, splitters):\n ### controller\n self.env = env\n self.LCS = []\n\n # create\n self.splitter = Splitter(env, 0,distance_downstream=distance_splitter, distance_upstream=distance_lcs, downstream_target=splitters, frequencies=lcs_qty) # primeiro splitter\n self.separator = Separator(env, lcs_qty)\n for i in range(lcs_qty):\n self.LCS.append(LineCard(self.env, lcid=i, exp=50, out=self.separator))\n\n # config\n self.separator.LCS = self.LCS\n self.separator.splitter = self.splitter\n self.splitter.upstream_target = self.separator\n\n self.action = env.process(self.counter())\n\n def counter(self):\n a = 0\n while True:\n print(\"\\tEnvironment time: \" + str(a))\n a += 1\n yield env.timeout(1)\n\nclass Separator(object):\n def __init__(self, env, size, LCS=None, splitter=None):\n self.env = env\n self.size = size\n self.LCS = LCS\n self.splitter = splitter\n\n def put(self, msg, downstream=False, upstream=False):\n if(downstream):\n yield self.env.process(self.splitter.put(msg, downstream=True))\n elif(upstream):\n yield self.env.process(self.LCS[msg.freq].put(msg, upstream=True)) # yield?\n\nclass Splitter(object):\n def __init__(self, env, id, distance_downstream, distance_upstream, downstream_target=None, upstream_target=None, frequencies=0):\n self.env = env\n self.id = id\n self.distance_downstream = distance_downstream\n self.distance_upstream = distance_upstream\n self.downstream_target = downstream_target\n self.upstream_target = upstream_target\n\n self.delay_upstream = distance_upstream / float(Light_Speed)\n self.delay_downstream = distance_downstream / float(Light_Speed)\n\n self.res = []\n for fr in range(frequencies):\n self.res.append(simpy.Resource(env, capacity=1))\n\n # self.splitter.put(msg, upstream=True)\n def put(self, msg, downstream=False, upstream=False, carry_delay=0):\n if(downstream):\n for target in downstream_target:\n yield self.env.timeout(self.delay_downstream)\n yield self.env.process(target.put(msg, downstream=True))\n elif(upstream):\n print(\">>> %s requested lambda %d from %s at %s\" % (self, msg.freq, str(msg.src), str(self.env.now)))\n request = self.res[msg.freq].request()\n yield request\n print(\"<<< %s accepted request from %s at %s\" % (self, str(msg.src), str(self.env.now)))\n if(type(self.upstream_target) is Splitter): # ainda não tem delay, usa o carry\n yield self.env.process(self.upstream_target.put(msg, upstream=True, carry_delay=(carry_delay + self.delay_upstream))) # carrega o delay para proximo splitter\n else: # ponto final\n yield self.env.timeout(self.delay_upstream + carry_delay)\n yield self.env.process(self.upstream_target.put(msg, upstream=True))\n yield self.res[msg.freq].release(request)\n\n def __repr__(self):\n if(type(self.upstream_target) is Splitter):\n return \"2nd Splitter (id:%d)\" % self.id\n else:\n return \"1st Splitter (id:%d)\" % self.id\n\nclass ONU(object):\n def __init__(self, env, oid, exp, splitter=None, freq=0, distance=0):\n self.env = env # environment\n self.oid = oid # onu id\n self.freq = freq\n self.splitter = splitter\n self.delay_upstream = distance / float(Light_Speed)\n\n adist = functools.partial(random.expovariate, exp) # tempo de delay para proxima transmissão\n sdist = functools.partial(random.expovariate, 0.01) # tamanho do packet (~100bytes)\n\n self.pg = PacketGenerator(self.env, \"ONU_PG_\" + str(oid), adist, sdist) # gerador de pacotes\n self.sp = SwitchPort(self.env, 10000) # bit rate of 10.000\n self.pg.out = self.sp\n self.sp.out = self\n\n self.upstream = simpy.Store(env)\n self.downstream = simpy.Store(env)\n self.action = env.process(self.run())\n\n def put(self, msg, downstream=False, upstream=False):\n if(downstream):\n self.downstream.put(msg)\n elif(upstream):\n self.upstream.put(msg)\n\n def run(self):\n while True:\n msg = yield self.upstream.get() # quando tiver, pega o packet\n msg.freq = self.freq\n print(\"Encaminhado Packet (src: %s, id: %d)... \" % (msg.src, msg.id))\n yield self.env.process(self.splitter.put(msg, upstream=True))\n # self.splitter.put(msg, upstream=True)\n\n###\n\nONU_quantity = int(sys.argv[1])\nsplitters_ratio = int(sys.argv[2])\nSIM_DURATION = int(sys.argv[3])\nRANDOM_SEED = int(sys.argv[4])\nLCS_quantity = int(sys.argv[5])\nDistance_OLT_ONU = int(sys.argv[6])\n\nif(len(sys.argv) > 7):\n Realtime_factor = float(sys.argv[7])\n print(\"\\tVariaveis:\\nONU_quantity:%d\\nsplitters_ratio:%d\\nSIM_DURATION:%d\\nRANDOM_SEED:%d\\nLCS_quantity:%d\\nDistance_OLT_ONU:%d\\nRealtime_factor:%f\" % ( ONU_quantity, splitters_ratio, SIM_DURATION, RANDOM_SEED, LCS_quantity, Distance_OLT_ONU, Realtime_factor))\n env = simpy.rt.RealtimeEnvironment(factor=Realtime_factor)\nelse:\n print(\"\\tVariaveis:\\nONU_quantity:%d\\nsplitters_ratio:%d\\nSIM_DURATION:%d\\nRANDOM_SEED:%d\\nLCS_quantity:%d\\nDistance_OLT_ONU:%d\" % ( ONU_quantity, splitters_ratio, SIM_DURATION, RANDOM_SEED, LCS_quantity, Distance_OLT_ONU))\n env = simpy.Environment()\nprint(\"\\t---------\")\nrandom.seed(RANDOM_SEED)\nsplitters_qty = int((ONU_quantity-1) / splitters_ratio) + 1\nprint(\"splitters_qty:%s\" % splitters_qty)\nonus_per_splt = int(ONU_quantity / splitters_qty) + 1\nprint(\"onus_per_splt:%s\" % onus_per_splt)\nonus_per_lc = int(onus_per_splt / LCS_quantity) # ONU qty > LCs qty\nprint(\"onus_per_lc:%s\" % onus_per_lc)\nprint(\"\\t---------\")\nprint(\"\\n\")\n\n\n# cria 2nd splitters:\nsplitters = []\noid = 0\nfreq = 0\nsplitter_ids = 1\nonus_left = splitters_qty * (onus_per_splt) - ONU_quantity\nfor i in range(splitters_qty):\n splt = Splitter(env, splitter_ids, 0, Distance_OLT_ONU, frequencies=LCS_quantity) # falta upstream target e downstream target\n splitter_ids += 1\n left = 0\n if(onus_left > 0):\n left = 1\n onus_left -= 1\n # cria onus do splitter\n onus = []\n for e in range(onus_per_splt-left):\n if(oid >= ONU_quantity):\n break\n freq += 1\n if(freq >= LCS_quantity):\n freq = 0\n onus.append(ONU(env, oid=oid, exp=77, splitter=splt, freq=freq))\n oid += 1\n\n splt.downstream_target = onus\n splitters.append(splt)\n\n#cria OLT (lcs, separator, 1st splitter)\nolt = OLT(env, LCS_quantity, Distance_OLT_ONU, 0, splitters)\n\n# atribui 2nd splitters upstream_target:\nfor splt in splitters:\n splt.upstream_target = olt.splitter\n\n# inicia simulação\nprint(\"\\n\\tStarting Simulation...\")\nenv.run(until=SIM_DURATION)\n","sub_path":"debug/sim_old_example.py","file_name":"sim_old_example.py","file_ext":"py","file_size_in_byte":12744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"244336195","text":"# Author: Shilpa Roy \n# Last updated: June 16, 2020\n\nimport itertools as it\nimport os\nimport subprocess\n\n#### USERS PUT YOUR INFO HERE ##### \n\n# Please remember to add a '/' at the very end!\npath_to_monorepo = \"/Users/shilpa-roy/checkedc/checkedc-clang/build/bin/\"\n\n\n\nprefixes = [\"arr\", \"arrstruct\", \"arrinstruct\", \"arrofstruct\", \"safefptrarg\", \"unsafefptrarg\", \"fptrsafe\", \"fptrunsafe\", \"fptrarr\", \"fptrarrstruct\", \"fptrinstruct\", \"fptrarrinstruct\", \"ptrTOptr\"] #, \"safefptrs\", \"unsafefptrs\", \"arrOFfptr\"] \naddendums = [\"\", \"proto\", \"multi\"] \n\n# casts are a whole different ballgame so leaving out for now, \n# but they can always be added in later by adding them to the cartesian product\n# casts = [\"\", \"expcastunsafe\", \"expcastsafe\", \"impcast\"]\n\nsuffixes = [\"safe\", \"callee\", \"caller\", \"both\"]\n\n# generate testnames by taking the cartesian product of the above\ntestnames = [] \nfor e in it.product(prefixes, addendums, suffixes): \n testnames.append([e[0], e[1], e[2]]) \n\n\n### FILE GENERATION ###\n\n# A typical program:\n#####################################################################\n# header (llvm-lit run command, #defines, stdlib checked protos)\n#\n# definitions (struct definitions, function prototypes)\n# CHECK annotation for definitions \n#\n# f1 (foo, bar, sus) \n# CHECK annotation for f1 \n#\n# f2 (foo, bar, sus) - (f1) \n# CHECK annotation for f2 \n#\n# f3 (foo, bar, sus) - (f1, f2)\n# CHECK annotation for f3 \n#####################################################################\n\n# header that should top every file\nheader = \"\"\"\n#include \nextern _Itype_for_any(T) void *calloc(size_t nmemb, size_t size) : itype(_Array_ptr) byte_count(nmemb * size);\nextern _Itype_for_any(T) void free(void *pointer : itype(_Array_ptr) byte_count(0));\nextern _Itype_for_any(T) void *malloc(size_t size) : itype(_Array_ptr) byte_count(size);\nextern _Itype_for_any(T) void *realloc(void *pointer : itype(_Array_ptr) byte_count(1), size_t size) : itype(_Array_ptr) byte_count(size);\nextern int printf(const char * restrict format : itype(restrict _Nt_array_ptr), ...);\nextern _Unchecked char *strcpy(char * restrict dest, const char * restrict src : itype(restrict _Nt_array_ptr));\\n\"\"\" \n\n# miscallaneous struct definitions that may or may not be used by the files above\ndefinitions = \"\"\"\nstruct general { \n int data; \n struct general *next;\n};\n\nstruct warr { \n int data1[5];\n char *name;\n};\n\nstruct fptrarr { \n int *values; \n char *name;\n int (*mapper)(int);\n};\n\nstruct fptr { \n int *value; \n int (*func)(int);\n}; \n\nstruct arrfptr { \n int args[5]; \n int (*funcs[5]) (int);\n};\n\nint add1(int x) { \n return x+1;\n} \n\nint sub1(int x) { \n return x-1; \n} \n\nint fact(int n) { \n if(n==0) { \n return 1;\n } \n return n*fact(n-1);\n} \n\nint fib(int n) { \n if(n==0) { return 0; } \n if(n==1) { return 1; } \n return fib(n-1) + fib(n-2);\n} \n\nint zerohuh(int n) { \n return !n;\n}\n\nint *mul2(int *x) { \n *x *= 2; \n return x;\n}\n\"\"\"\n\n# this function will generate a C file that contains \n# the core of the example (before the addition of checked annotations)\ndef method_gen(prefix, proto, suffix): \n return_type = arg_type = susbody = foobody = barbody = foo = bar = sus = susproto = \"\"\n\n # main processing to distinguish between the different types of test we wish to create\n if prefix==\"arr\": \n return_type = \"int *\" \n arg_type = \"int *\" \n susbody = \"\"\"\n int *z = calloc(5, sizeof(int)); \n int i, fac;\n int *p;\n for(i = 0, p = z, fac = 1; i < 5; ++i, p++, fac *= i) \n { *p = fac; }\"\"\"\n elif prefix==\"arrstruct\":\n return_type = \"int *\" \n arg_type = \"struct general *\" \n barbody = foobody = \"\"\"\n struct general *curr = y;\n int i;\n for(i = 1; i < 5; i++, curr = curr->next) { \n curr->data = i;\n curr->next = malloc(sizeof(struct general));\n curr->next->data = i+1;\n }\n \"\"\"\n susbody = \"\"\"\n int *z = calloc(5, sizeof(int)); \n struct general *p = y;\n int i;\n for(i = 0; i < 5; p = p->next, i++) { \n z[i] = p->data; \n } \n \"\"\"\n elif prefix==\"arrinstruct\":\n return_type = \"struct warr *\" \n arg_type = \"struct warr *\"\n susbody = \"\"\"\n char name[20]; \n struct warr *z = y;\n int i;\n for(i = 0; i < 5; i++) { \n z->data1[i] = i; \n }\n \"\"\"\n elif prefix==\"arrofstruct\":\n return_type = \"struct general **\"\n arg_type = \"struct general *\" \n susbody = \"\"\" \n struct general **z = calloc(5, sizeof(struct general *));\n struct general *curr = y;\n int i;\n for(i = 0; i < 5; i++) { \n z[i] = curr; \n curr = curr->next; \n } \n \"\"\" \n barbody = foobody = \"\"\"\n struct general *curr = y;\n int i;\n for(i = 1; i < 5; i++, curr = curr->next) { \n curr->data = i;\n curr->next = malloc(sizeof(struct general));\n curr->next->data = i+1;\n }\n \"\"\" \n elif prefix==\"safefptrarg\": \n sus = \"\\nint * sus(int (*x) (int), int (*y) (int)) {\\n\"\n susproto = \"\\nint * sus(int (*) (int), int (*) (int));\\n\"\n foo = \"\\nint * foo() {\\n\"\n bar = \"\\nint * bar() {\\n\"\n susbody = \"\"\" \n x = (int (*) (int)) 5;\n int *z = calloc(5, sizeof(int));\n int i;\n for(i = 0; i < 5; i++) { \n z[i] = y(i);\n }\n \"\"\"\n foobody = barbody = \"\"\" \n int (*x)(int) = add1; \n int (*y)(int) = sub1; \n int *z = sus(x, y);\n \"\"\"\n elif prefix==\"unsafefptrarg\":\n sus = \"\\nint * sus(int (*x) (int), int (*y) (int)) {\\n\"\n susproto = \"\\nint * sus(int (*) (int), int (*) (int));\\n\"\n foo = \"\\nint * foo() {\\n\"\n bar = \"\\nint * bar() {\\n\"\n susbody = \"\"\" \n x = (int (*) (int)) 5;\n int *z = calloc(5, sizeof(int));\n int i;\n for(i = 0; i < 5; i++) { \n z[i] = y(i);\n }\n \"\"\"\n foobody = barbody = \"\"\" \n int (*x)(int) = add1; \n int (*y)(int) = mul2; \n int *z = sus(x, y);\n \"\"\"\n elif prefix==\"safefptrs\": \n susproto = \"\\nint * (*sus(int (*) (int), int (*) (int))) (int *);\\n\"\n sus = \"\\nint * (*sus(int (*x) (int), int (*y) (int))) (int *) {\\n\"\n foo = \"\\nint * (*foo(void)) (int *) {\\n\"\n bar = \"\\nint * (*bar(void)) (int *) {\\n\" \n susbody = \"\"\" \n x = (int (*) (int)) 5; \n int * (*z)(int *) = mul2;\n \"\"\"\n foobody = barbody = \"\"\"\n int (*x)(int) = add1; \n int (*y)(int) = sub1; \n int *(*z)(int *) = sus(x, y);\n \"\"\"\n elif prefix==\"unsafefptrs\": \n susproto = \"\\nchar * (*sus(int (*) (int), int (*) (int))) (int *);\\n\"\n sus = \"\\nchar * (*sus(int (*x) (int), int (*y) (int))) (int *) {\\n\"\n foo = \"\\nchar * (*foo(void)) (int *) {\\n\"\n bar = \"\\nchar * (*bar(void)) (int *) {\\n\" \n susbody = \"\"\" \n x = (int (*) (int)) 5; \n char * (*z)(int *) = fib;\n \"\"\"\n foobody = barbody = \"\"\"\n int (*x)(int) = add1; \n int (*y)(int) = sub1; \n int *(*z)(int *) = sus(x, y);\n \"\"\"\n elif prefix==\"fptrsafe\":\n sus = \"\\nint * sus(struct general *x, struct general *y) {\\n\"\n susproto = \"\\nint * sus(struct general *, struct general *);\\n\"\n foo = \"\\nint * foo() {\\n\"\n bar = \"\\nint * bar() {\\n\"\n barbody = foobody = \"\"\"\n struct general *x = malloc(sizeof(struct general)); \n struct general *y = malloc(sizeof(struct general));\n struct general *curr = y;\n int i;\n for(i = 1; i < 5; i++, curr = curr->next) { \n curr->data = i;\n curr->next = malloc(sizeof(struct general));\n curr->next->data = i+1;\n }\n int * (*sus_ptr)(struct general *, struct general *) = sus; \n int *z = sus_ptr(x, y);\n \"\"\"\n susbody = \"\"\"\n x = (struct general *) 5;\n int *z = calloc(5, sizeof(int)); \n struct general *p = y;\n int i;\n for(i = 0; i < 5; p = p->next, i++) { \n z[i] = p->data; \n } \n \"\"\"\n elif prefix==\"fptrunsafe\":\n sus = \"\\nint * sus(struct general *x, struct general *y) {\\n\"\n susproto = \"\\nint * sus(struct general *, struct general *);\\n\"\n foo = \"\\nint * foo() {\\n\"\n bar = \"\\nint * bar() {\\n\"\n barbody = foobody = \"\"\"\n struct general *x = malloc(sizeof(struct general)); \n struct general *y = malloc(sizeof(struct general));\n struct general *curr = y;\n int i;\n for(i = 1; i < 5; i++, curr = curr->next) { \n curr->data = i;\n curr->next = malloc(sizeof(struct general));\n curr->next->data = i+1;\n }\n int (*sus_ptr)(struct fptr *, struct fptr *) = sus; \n int *z = (int *) sus_ptr(x, y);\n \"\"\"\n susbody = \"\"\"\n x = (struct general *) 5;\n int *z = calloc(5, sizeof(int)); \n struct general *p = y;\n int i;\n for(i = 0; i < 5; p = p->next, i++) { \n z[i] = p->data; \n } \n \"\"\"\n elif prefix==\"fptrarr\":\n sus = \"\\nint ** sus(int *x, int *y) {\\n\"\n susproto = \"\\nint ** sus(int *, int *);\\n\"\n foo = \"\\nint ** foo() {\\n\"\n bar = \"\\nint ** bar() {\\n\"\n susbody = \"\"\"\n x = (int *) 5;\n int **z = calloc(5, sizeof(int *)); \n int * (*mul2ptr) (int *) = mul2;\n int i;\n for(i = 0; i < 5; i++) { \n z[i] = mul2ptr(&y[i]);\n } \n \"\"\"\n foobody = barbody = \"\"\"\n int *x = malloc(sizeof(int)); \n int *y = calloc(5, sizeof(int)); \n int i;\n for(i = 0; i < 5; i++) { \n y[i] = i+1;\n } \n int **z = sus(x, y);\n \"\"\"\n elif prefix==\"arrOFfptr\":\n sus = \"\\nint (**sus(int *x, int *y)) (int) { \\n\"\n susproto = \"\\nint (**sus(int *x, int *y)) (int);\\n\" \n foo = \"\\nint (**foo(void)) (int) {\"\n bar = \"\\nint (**bar(void)) (int) {\"\n\n foobody = barbody = \"\"\"\n int *x = malloc(sizeof(int));\n int *y = calloc(5, sizeof(int)); \n int i;\n for(i = 0; i < 5; i++) {\n y[i] = i+1;\n } \n int (**z)(int) = sus(x, y);\n \"\"\"\n\n susbody= \"\"\" \n x = (int *) 5;\n int (**z)(int) = calloc(5, sizeof(int (*) (int))); \n z[0] = add1;\n z[1] = sub1; \n z[2] = zerohuh;\n z[3] = fib;\n z[4] = fact;\n int i;\n for(i = 0; i < 5; i++) { \n y[i] = z[i](y[i]);\n }\n \"\"\"\n elif prefix==\"fptrinstruct\":\n sus = \"\\nstruct fptr * sus(struct fptr *x, struct fptr *y) {\\n\"\n susproto = \"\\nstruct fptr * sus(struct fptr *, struct fptr *);\\n\"\n foo = \"\\nstruct fptr * foo() {\\n\"\n bar = \"\\nstruct fptr * bar() {\\n\"\n susbody = \"\"\" \n x = (struct fptr *) 5; \n struct fptr *z = malloc(sizeof(struct fptr)); \n z->value = y->value; \n z->func = fact;\n \"\"\"\n foobody = barbody = \"\"\" \n struct fptr * x = malloc(sizeof(struct fptr)); \n struct fptr *y = malloc(sizeof(struct fptr));\n struct fptr *z = sus(x, y);\n \"\"\"\n elif prefix==\"fptrarrstruct\":\n sus = \"\\nstruct fptrarr * sus(struct fptrarr *x, struct fptrarr *y) {\\n\"\n susproto = \"\\nstruct fptrarr * sus(struct fptrarr *, struct fptrarr *);\\n\"\n foo = \"\\nstruct fptrarr * foo() {\\n\"\n bar = \"\\nstruct fptrarr * bar() {\\n\"\n susbody = \"\"\" \n x = (struct fptrarr *) 5; \n char name[30]; \n struct fptrarr *z = malloc(sizeof(struct fptrarr)); \n z->values = y->values; \n z->name = strcpy(name, \"Hello World\");\n z->mapper = fact; \n int i;\n for(i = 0; i < 5; i++) { \n z->values[i] = z->mapper(z->values[i]);\n }\n \"\"\" \n foobody = barbody = \"\"\" \n char name[20]; \n struct fptrarr * x = malloc(sizeof(struct fptrarr));\n struct fptrarr *y = malloc(sizeof(struct fptrarr));\n int *yvals = calloc(5, sizeof(int)); \n int i;\n for(i = 0; i < 5; i++) {\n yvals[i] = i+1; \n } \n y->values = yvals; \n y->name = name; \n y->mapper = NULL;\n strcpy(y->name, \"Example\"); \n struct fptrarr *z = sus(x, y);\n \"\"\" \n elif prefix==\"fptrarrinstruct\":\n sus = \"\\nstruct arrfptr * sus(struct arrfptr *x, struct arrfptr *y) {\\n\"\n susproto = \"\\nstruct arrfptr * sus(struct arrfptr *, struct arrfptr *);\\n\"\n foo = \"\\nstruct arrfptr * foo() {\\n\"\n bar = \"\\nstruct arrfptr * bar() {\\n\"\n susbody = \"\"\" \n x = (struct arrfptr *) 5; \n struct arrfptr *z = malloc(sizeof(struct arrfptr)); \n int i;\n for(i = 0; i < 5; i++) { \n z->args[i] = i + 1; \n } \n z->funcs[0] = add1;\n z->funcs[1] = sub1; \n z->funcs[2] = zerohuh;\n z->funcs[3] = fib;\n z->funcs[4] = fact;\n \"\"\" \n foobody = barbody = \"\"\" \n struct arrfptr * x = malloc(sizeof(struct arrfptr));\n struct arrfptr * y = malloc(sizeof(struct arrfptr));\n \n struct arrfptr *z = sus(x, y); \n int i;\n for(i = 0; i < 5; i++) { \n z->args[i] = z->funcs[i](z->args[i]);\n }\n \"\"\"\n elif prefix==\"ptrTOptr\":\n return_type = \"char ***\"\n arg_type = \"char * * *\"\n susbody = \"\"\"\n char *ch = malloc(sizeof(char)); \n *ch = 'A'; /*Capital A*/\n char *** z = malloc(5*sizeof(char**)); \n for(int i = 0; i < 5; i++) { \n z[i] = malloc(5*sizeof(char *)); \n for(int j = 0; j < 5; j++) { \n z[i][j] = malloc(2*sizeof(char)); \n strcpy(z[i][j], ch);\n *ch = *ch + 1; \n }\n }\n \"\"\"\n\n # generate standard enders and duplications that occur in all generated tests\n\n if not \"fptr\" in prefix: \n barbody += \"{} z = sus(x, y);\".format(return_type) \n foobody += \"{} z = sus(x, y);\".format(return_type)\n data = [return_type, arg_type, arg_type]\n susproto = \"\\n{} sus({}, {});\\n\".format(*data)\n sus = \"\\n{} sus({} x, {} y) {}\\nx = ({}) 5;\".format(data[0], data[1], data[2], \"{\", arg_type)\n arg_np = \" \".join(arg_type.split(\" \")[:-1])\n foo = \"\"\"\\n{} foo() {}\n {} x = malloc(sizeof({}));\n {} y = malloc(sizeof({}));\n \"\"\".format(return_type, \"{\", arg_type, arg_np, arg_type, arg_np) \n bar = \"\"\"\\n{} bar() {}\n {} x = malloc(sizeof({}));\n {} y = malloc(sizeof({}));\n \"\"\".format(return_type, \"{\", arg_type, arg_np, arg_type, arg_np) \n \n # create unsafe use cases based on the suffix (by default, the generated code is safe)\n\n if suffix == \"both\": \n susbody += \"\\nz += 2;\"\n barbody += \"\\nz += 2;\" \n elif suffix == \"callee\": \n susbody += \"\\nz += 2;\" \n elif suffix == \"caller\": \n barbody += \"\\nz += 2;\"\n \n susbody += \"\\nreturn z; }\\n\"\n foobody += \"\\nreturn z; }\\n\" \n barbody += \"\\nreturn z; }\\n\"\n\n return [susproto, sus+susbody, foo+foobody, bar+barbody] \n\ndef process_file_smart(prefix, proto, suffix, name, cnameNOALL, cnameALL, name2, cname2NOALL, cname2ALL): \n \n # generate a descriptive comment that describes what the test will do: \n comm_general = \"/*This file tests three functions: two callers bar and foo, and a callee sus*/\\n\" \n comm_prefix = \"/*In particular, this file tests: \"\n if prefix==\"arr\": comm_prefix += \"arrays through a for loop and pointer\\narithmetic to assign into it*/\" \n if prefix==\"arrstruct\": comm_prefix += \"arrays and structs, specifically by using an array to\\ntraverse through the values of a struct*/\" \n if prefix==\"arrinstruct\": comm_prefix += \"how the tool behaves when there is an array\\nfield within a struct*/\"\n if prefix==\"arrofstruct\": comm_prefix += \"how the tool behaves when there is an array\\nof structs*/\"\n if prefix==\"safefptrarg\": comm_prefix += \"passing a function pointer as an argument to a\\nfunction safely (without unsafe casting)*/\"\n if prefix==\"unsafefptrarg\": comm_prefix += \"passing a function pointer as an argument to a\\nfunction unsafely (by casting it unsafely)*/\"\n if prefix==\"safefptrs\": comm_prefix += \"passing function pointers in as arguments and\\nreturning a function pointer safely*/\" \n if prefix==\"arrOFfptr\": comm_prefix += \"how the tool behaves when returning an array\\nof function pointers*/\"\n if prefix==\"unsafefptrs\": comm_prefix += \"passing fptrs in as arguments and returning a\\nfptr unsafely (through unsafe casting*/\"\n if prefix==\"fptrsafe\": comm_prefix += \"converting the callee into a function pointer\\nand then using that pointer for computations*/\"\n if prefix==\"fptrunsafe\": comm_prefix += \"converting the callee into a function pointer\\nunsafely via cast and using that pointer for computations*/\"\n if prefix==\"fptrarr\": comm_prefix += \"using a function pointer and an array in\\ntandem to do computations*/\"\n if prefix==\"fptrarrstruct\": comm_prefix += \"using a function pointer and an array as fields\\nof a struct that interact with each other*/\"\n if prefix==\"fptrinstruct\": comm_prefix += \"how the tool behaves when a function pointer\\nis a field of a struct*/\"\n if prefix==\"fptrarrinstruct\": comm_prefix += \"how the tool behaves when there is an array\\nof function pointers in a struct*/\"\n if prefix==\"ptrTOptr\": comm_prefix += \"having a pointer to a pointer*/\"\n comm_proto = \"\" \n if proto==\"multi\": comm_proto = \"\\n/*For robustness, this test is identical to {}.c and {}.c except in that\\nthe callee and callers are split amongst two files to see how\\nthe tool performs conversions*/\".format(prefix+\"proto\"+suffix, prefix+suffix) \n elif proto==\"proto\": comm_proto = \"\\n/*For robustness, this test is identical to {}.c except in that\\na prototype for sus is available, and is called by foo and bar,\\nwhile the definition for sus appears below them*/\".format(prefix+suffix)\n comm_suffix = \"\"\n if suffix == \"safe\": comm_suffix = \"\\n/*In this test, foo, bar, and sus will all treat their return values safely*/\"\n elif suffix == \"callee\": comm_suffix = \"\\n/*In this test, foo and bar will treat their return values safely, but sus will\\nnot, through invalid pointer arithmetic, an unsafe cast, etc*/\"\n elif suffix == \"caller\": comm_suffix = \"\\n/*In this test, foo and sus will treat their return values safely, but bar will\\nnot, through invalid pointer arithmetic, an unsafe cast, etc.*/\"\n elif suffix == \"both\": comm_suffix = \"\\n/*In this test, foo will treat its return value safely, but sus and bar will not,\\nthrough invalid pointer arithmetic, an unsafe cast, etc.*/\"\n comm_dec = \"\\n\\n/*********************************************************************************/\\n\\n\" \n\n comment = ''.join([\"\\n\", comm_dec, comm_general, comm_prefix, comm_proto, comm_suffix, comm_dec])\n \n file = open(name, \"r\") \n noallfile = open(cnameNOALL, \"r\") \n allfile = open(cnameALL, \"r\") \n\n # gather all the lines\n lines = str(file.read()).split(\"\\n\") \n noall = str(noallfile.read()).split(\"\\n\") \n yeall = str(allfile.read()).split(\"\\n\") \n\n file.close() \n noallfile.close() \n allfile.close() \n os.system(\"rm {} {}\".format(cnameNOALL, cnameALL)) \n \n # ensure all lines are the same length\n assert len(lines) == len(noall) == len(yeall), \"fix file \" + name \n\n\n if proto==\"multi\": \n file2 = open(name2, \"r\") \n noallfile2 = open(cname2NOALL, \"r\") \n allfile2 = open(cname2ALL, \"r\") \n \n # gather all the lines\n lines2 = str(file2.read()).split(\"\\n\") \n noall2 = str(noallfile2.read()).split(\"\\n\") \n yeall2 = str(allfile2.read()).split(\"\\n\")\n file2.close() \n noallfile2.close() \n allfile2.close() \n os.system(\"rm {} {}\".format(cname2NOALL, cname2ALL)) \n \n # ensure all lines are the same length\n assert len(lines2) == len(noall2) == len(yeall2), \"fix file \" + name \n\n # our keywords that indicate we should add an annotation\n keywords = \"int char struct double float\".split(\" \") \n ckeywords = \"_Ptr _Array_ptr _Nt_array_ptr _Checked _Unchecked\".split(\" \") \n\n for i in range(0, len(lines)): \n line = lines[i] \n noline = noall[i] \n yeline = yeall[i]\n if line.find(\"extern\") == -1 and ((any(substr in line for substr in keywords) and line.find(\"*\") != -1) or any(substr in noline for substr in ckeywords) or any(substr in yeline for substr in ckeywords)): \n if noline == yeline: \n lines[i] = line + \"\\n\\t//CHECK: \" + noline.lstrip()\n else: \n lines[i] = line + \"\\n\\t//CHECK_NOALL: \" + noline.lstrip() + \"\\n\\t//CHECK_ALL: \" + yeline.lstrip()\n\n if proto==\"multi\": \n for i in range(0, len(lines2)): \n line = lines2[i] \n noline = noall2[i] \n yeline = yeall2[i]\n if line.find(\"extern\") == -1 and ((any(substr in line for substr in keywords) and line.find(\"*\") != -1) or any(substr in noline for substr in ckeywords) or any(substr in yeline for substr in ckeywords)): \n if noline == yeline: \n lines2[i] = line + \"\\n\\t//CHECK: \" + noline.lstrip()\n else: \n lines2[i] = line + \"\\n\\t//CHECK_NOALL: \" + noline.lstrip() + \"\\n\\t//CHECK_ALL: \" + yeline.lstrip()\n \n run = \"// RUN: 3c -alltypes -addcr %s -- | FileCheck -match-full-lines -check-prefixes=\\\"CHECK_ALL\\\",\\\"CHECK\\\" %s\"\n run += \"\\n// RUN: 3c -addcr %s -- | FileCheck -match-full-lines -check-prefixes=\\\"CHECK_NOALL\\\",\\\"CHECK\\\" %s\"\n run += \"\\n// RUN: 3c -addcr %s -- | %clang -c -fcheckedc-extension -x c -o /dev/null -\\n\"\n run += \"\\n// RUN: 3c -alltypes -output-postfix=checked %s\" \n run += \"\\n// RUN: 3c -alltypes %S/{} -- | diff %S/{} -\".format(name + \"hecked.c\", name + \"hecked.c\") \n run += \"\\n// RUN: rm %S/{}\".format(name + \"hecked.c\")\n if proto==\"multi\": \n run = \"// RUN: 3c -base-dir=%S -addcr -alltypes -output-postfix=checkedALL %s %S/\" + name2 \n run += \"\\n// RUN: 3c -base-dir=%S -addcr -output-postfix=checkedNOALL %s %S/\" + name2 \n run += \"\\n// RUN: %clang -c %S/{} %S/{}\".format(cnameNOALL, cname2NOALL)\n run += \"\\n// RUN: FileCheck -match-full-lines -check-prefixes=\\\"CHECK_NOALL\\\",\\\"CHECK\\\" --input-file %S/{} %s\".format(cnameNOALL) \n run += \"\\n// RUN: FileCheck -match-full-lines -check-prefixes=\\\"CHECK_ALL\\\",\\\"CHECK\\\" --input-file %S/{} %s\".format(cnameALL)\n run += \"\\n// RUN: 3c -base-dir=%S -alltypes -output-postfix=checked %S/{} %s\".format(name2)\n cname = name + \"hecked.c\" \n cname2 = name2 + \"hecked.c\"\n run += \"\\n// RUN: 3c -base-dir=%S -alltypes -output-postfix=convert_again %S/{} %S/{}\".format(cname, cname2)\n cnameALLtwice1 = cname + \"onvert_again.c\" \n cnameALLtwice2 = cname2 + \"onvert_again.c\"\n run += \"\\n// RUN: diff %S/{} %S/{}\".format(cnameALLtwice1, cname)\n run += \"\\n// RUN: diff %S/{} %S/{}\".format(cnameALLtwice2, cname2)\n run += \"\\n// RUN: rm %S/{} %S/{}\".format(cnameALL, cname2ALL)\n run += \"\\n// RUN: rm %S/{} %S/{}\".format(cnameNOALL, cname2NOALL)\n run += \"\\n// RUN: rm %S/{} %S/{} %S/{} %S/{}\".format(cname, cname2, cnameALLtwice1, cnameALLtwice2)\n cnameNOALL2 = prefix + suffix + proto + \"1.checkedNOALL2.c\" \n cnameALL2 = prefix + suffix + proto + \"1.checkedALL2.c\"\n cname2NOALL2 = prefix + suffix + proto + \"2.checkedNOALL2.c\" \n cname2ALL2 = prefix + suffix + proto + \"2.checkedALL2.c\"\n cname = name + \"hecked2.c\" \n cname2 = name2 + \"hecked2.c\"\n cnameALLtwice1 = cname + \"onvert_again.c\" \n cnameALLtwice2 = cname2 + \"onvert_again.c\"\n # uncomment the following lines if we ever decide we want to generate buggy tests that don't compile\n # if bug_generated: \n # cname21 = prefix + suffix + proto + \"1_BUG.checked2.c\" \n # cname22 = prefix + suffix + proto + \"2_BUG.checked2.c\"\n run2 = \"// RUN: 3c -base-dir=%S -addcr -alltypes -output-postfix=checkedALL2 %S/{} %s\".format(name) \n run2 += \"\\n// RUN: 3c -base-dir=%S -addcr -output-postfix=checkedNOALL2 %S/{} %s\".format(name)\n run2 += \"\\n// RUN: %clang -c %S/{} %S/{}\".format(cnameNOALL2, cname2NOALL2)\n run2 += \"\\n// RUN: FileCheck -match-full-lines -check-prefixes=\\\"CHECK_NOALL\\\",\\\"CHECK\\\" --input-file %S/{} %s\".format(cname2NOALL2) \n run2 += \"\\n// RUN: FileCheck -match-full-lines -check-prefixes=\\\"CHECK_ALL\\\",\\\"CHECK\\\" --input-file %S/{} %s\".format(cname2ALL2)\n run2 += \"\\n// RUN: 3c -base-dir=%S -alltypes -output-postfix=checked2 %S/{} %s\".format(name)\n run2 += \"\\n// RUN: 3c -base-dir=%S -alltypes -output-postfix=convert_again %S/{} %S/{}\".format(cname, cname2)\n run2 += \"\\n// RUN: diff %S/{} %S/{}\".format(cnameALLtwice1, cname)\n run2 += \"\\n// RUN: diff %S/{} %S/{}\".format(cnameALLtwice2, cname2)\n run2 += \"\\n// RUN: rm %S/{} %S/{}\".format(cnameALL2, cname2ALL2)\n run2 += \"\\n// RUN: rm %S/{} %S/{}\".format(cnameNOALL2, cname2NOALL2)\n run2 += \"\\n// RUN: rm %S/{} %S/{} %S/{} %S/{}\".format(cname, cname2, cnameALLtwice1, cnameALLtwice2)\n\n file = open(name, \"w+\")\n file.write(run + comment + \"\\n\".join(lines)) \n file.close()\n\n if proto==\"multi\": \n file = open(name2, \"w+\") \n file.write(run2 + comment + \"\\n\".join(lines2)) \n file.close()\n return \n\ndef annot_gen_smart(prefix, proto, suffix):\n\n # generate the body of the file\n [susproto, sus, foo, bar] = method_gen(prefix, proto, suffix) \n\n name = prefix + proto + suffix + \".c\"\n cnameNOALL = prefix + proto + suffix + \".checkedNOALL.c\" \n cnameALL = prefix + proto + suffix + \".checkedALL.c\"\n name2 = name \n cname2NOALL = cnameNOALL \n cname2ALL = cnameALL\n\n if proto==\"multi\": \n name = prefix + suffix + proto + \"1.c\" \n name2 = prefix + suffix + proto + \"2.c\"\n cnameNOALL = prefix + suffix + proto + \"1.checkedNOALL.c\" \n cnameALL = prefix + suffix + proto + \"1.checkedALL.c\"\n cname2NOALL = prefix + suffix + proto + \"2.checkedNOALL.c\" \n cname2ALL = prefix + suffix + proto + \"2.checkedALL.c\"\n \n if proto==\"proto\": test = header + definitions + susproto + foo + bar + sus\n elif proto==\"multi\": test = header + definitions + susproto + foo + bar\n else: test = header + definitions + sus + foo + bar \n\n # write the main file \n file = open(name, \"w+\") \n file.write(test)\n file.close() \n \n # generate the second file if a multi example\n if proto==\"multi\": \n test2 = header + definitions + sus\n file = open(name2, \"w+\") \n file.write(test2)\n file.close()\n \n # run the porting tool on the file(s)\n if proto==\"multi\": \n os.system(\"{}3c -alltypes -addcr -output-postfix=checkedALL {} {}\".format(path_to_monorepo, name, name2))\n os.system(\"{}3c -addcr -output-postfix=checkedNOALL {} {}\".format(path_to_monorepo, name, name2))\n else: \n os.system(\"{}3c -alltypes -addcr -output-postfix=checkedALL {}\".format(path_to_monorepo, name))\n os.system(\"{}3c -addcr -output-postfix=checkedNOALL {}\".format(path_to_monorepo, name))\n \n # compile the files and if it doesn't compile, then let's indicate that a bug was generated for this file\n bug_generated = False\n if proto != \"multi\":\n out = subprocess.Popen(['{}clang'.format(path_to_monorepo), '-c', cnameNOALL], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) \n stdout, stderr = out.communicate()\n stdout = str(stdout) \n if \"error:\" in stdout: \n bug_generated = True\n # name = prefix + proto + suffix + \"_BUG.c\" \n else: \n out = subprocess.Popen(['{}clang'.format(path_to_monorepo), '-c', cnameNOALL, cname2NOALL], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) \n stdout, stderr = out.communicate()\n stdout = str(stdout) \n if \"error:\" in stdout: \n bug_generated = True\n # name = prefix + suffix + proto + \"1_BUG.c\"\n # name2 = prefix + suffix + proto + \"2_BUG.c\" \n\n if bug_generated: \n # uncomment the following lines if we ever want to generate buggy tests that do not compile\n # cname = prefix + suffix + proto + \"1_BUG.checked.c\"\n # cname2 = prefix + suffix + proto + \"2_BUG.checked.c\"\n os.system(\"rm {}\".format(name)) \n if proto==\"multi\": os.system(\"rm {}\".format(name2))\n return\n\n process_file_smart(prefix, proto, suffix, name, cnameNOALL, cnameALL, name2, cname2NOALL, cname2ALL) \n \n return\n\n#arr, arrinstruct, arrofstruct\nif __name__ == \"__main__\": \n os.system(\"rm *.checked*\")\n for skeleton in testnames: \n annot_gen_smart(skeleton[0], skeleton[1], skeleton[2])\n os.system(\"rm *.checked*\")\n","sub_path":"clang/test/3C/testgenerator.py","file_name":"testgenerator.py","file_ext":"py","file_size_in_byte":29203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"578208197","text":"import time\nimport random\nfrom random import randint\nimport os\nimport sys\n\ndef main():\n opening()\ndef opening():\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"It was an average day in your medieval village.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"You tend to your garden just as you do everyday.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"You look upon your village and marvel at the squalor.\\n\")\n slowType(\"You think about how lucky you are to have not been killed off by the plague.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"Or the other hundreds of illnesses that medieval medicine can't cure.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"Or how your family only went 40 days without food so far this year.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"Or how the wolves have only attacked the village twice this week.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"Or how your local tyrannical government has yet to declare an official religion \"\n \"that would effectively create justification to carry \"\n \"out the sanctioned murder of hundreds of innocent, purely for not abiding to a certain belief.\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"Everything was great\\n\")\n input()\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"When suddenly...\\n\")\n input()\n body()\ndef body():\n print(\"BAM!\")\n input()\n slowType( \"Fuckin aliens man... \\n\")\n slowType(\"They're attacking your medieval village.\\n\")\n slowType(\"You need to run away!\\n\")\n slowType(\"But first you need to decide what class you are.\\n\")\n slowType(\"1.Paladin, 2.Mage, 3.Archer, 4.Filthy Peasant\\n\")\n chooseClass = int(input())\n print (\"\")\n wrongCount = 0\n maybePeasant = randint(1,30)\n if (chooseClass > 4 or chooseClass < 0):\n os.system('cls' if os.name == 'nt' else 'clear')\n checkInput(wrongCount, chooseClass, 4)\n elif (chooseClass==1):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You are a Paladin\\n\")\n paladin()\n elif (chooseClass==2):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You are a Mage\\n\")\n mage()\n elif (chooseClass==3):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You are a Archer\\n\")\n archer()\n elif (chooseClass==4):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You chose to be a filthy peasant....\\n\")\n peasant()\n\n slowType (\"Your about to run away. \\nThe safe zone is the very next village 10 miles away \\nWhat do you take with you?\")\n\n chooseItem = int(input())\n if (chooseItem > 4):\n os.system('cls' if os.name == 'nt' else 'clear')\n checkInput(wrongCount, chooseItem, 4)\n elif (chooseItem==1):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You are a Paladin\\n\")\n paladin()\n elif (chooseItem==2):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType (\"You are a Mage\\n\")\n mage()\n elif (chooseItem==3):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"You are a Archer\\n\")\n archer()\n elif (chooseItem==4):\n os.system('cls' if os.name == 'nt' else 'clear')\n slowType(\"You chose to be a filthy peasant....\\n\")\n peasant()\n\ndef wrongExpressions(count):\n if (count == 0):\n slowType (\"That's not aan option idiot. Do it again.\")\n elif (count == 1):\n slowType (\"That's not something you can do. Do it again!\")\n elif (count == 2):\n slowType (\"Once more....that's not an option. Again\")\n elif (count == 3):\n slowType (\"Can you read? This is the fourth time you put something wrong. Again!\")\n elif (count == 4):\n slowType (\"Like, I don't understand. At this point your putting wrong answers to see these messages.\")\n elif (count >= 5 and count <= 10):\n slowType (\"Nope Again\")\n elif (count == 11):\n slowType (\"This is the last time the message will be different.\")\n else:\n slowType (\"Nope, again.\")\n\ndef checkInput(countWrong, userInput, expectedNumber ):\n while (True):\n if (userInput > expectedNumber or userInput < 0):\n wrongExpressions(countWrong)\n userInput = int(input())\n countWrong += 1\n os.system('cls' if os.name == 'nt' else 'clear')\n else:\n break\n\ndef paladin():\n strength = 70\n agility = 20\n ability = 20\n luck = 50\ndef mage():\n strength = 20\n agility = 30\n ability = 70\n luck = 50\ndef archer():\n strength = 30\n agility = 70\n ability = 30\n luck = 50\ndef peasant():\n strength = 5\n agility = 5\n ability = 5\n luck = 5\ndef slowType(str):\n for l in str:\n sys.stdout.write(l)\n sys.stdout.flush()\n time.sleep(.02)\n\nmain()","sub_path":"FleeTheVillage.py","file_name":"FleeTheVillage.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362957429","text":"import signal\n#from functools import partial\nimport time\nimport sys\nimport cv2\n\nimport argparse\nimport numpy as np\nfrom multiprocessing import Manager, Process\nimport threading\nimport socket\n\nfrom TrackerModule.tracker import LocationTracker\nfrom CameraModule.camera import CameraController\nfrom pid import PID\nfrom gui import GUI\nfrom VideoGet import VideoGet\n\n#cap = cv2.VideoCapture(0)\n\ndef core_signal_handler(sig, frame):\n sys.exit()\n\ndef pid_signal_handler(sig, frame):\n sys.exit()\n \ndef core_process(output_path, pan, tilt, pan_error, tilt_error, pid_active):\n s = socket.socket()\n s.connect(('192.168.70.4', 8802))\n print(s.recv(1024))\n signal.signal(signal.SIGINT, core_signal_handler)\n video_getter = VideoGet(remote=True).start()\n tracker = LocationTracker(remote=True, address=('', 8801))\n camera = CameraController(camera_position=[0.03,2.82,1.33], remote=True, socket=s)\n\n camera.init(refpoint_world=[0.85, 0.0, 1.35],\n use_pid = True, pid_active=pid_active, pan_error=pan_error, tilt_error=tilt_error)\n \n servo_thread = threading.Thread(target=camera.CameraRotation_Thread, args=(pan, tilt, video_getter))\n servo_thread.start()\n gui = GUI(output_path, camera, tracker, video_getter, remote=True, socket=s)\n gui.root.mainloop()\n servo_thread.join()\n #s.close()\n\ndef pid_process(output, p, i, d, error, pid_active):\n signal.signal(signal.SIGINT, pid_signal_handler)\n \n pid_control = PID(p.value, i.value, d.value)\n pid_control.initialize()\n \n while True:\n if (pid_active.value == True):\n output.value = pid_control.update(error.value)\n \nif __name__== \"__main__\":\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-o\", \"--output\", default=\"./\",\n help=\"path to output directory to store snapshots (default: current folder\")\n args = vars(ap.parse_args())\n\n # start the app\n with Manager() as manager:\n pan_error = manager.Value(\"i\", 0)\n tilt_error = manager.Value(\"i\", 0)\n pan = manager.Value(\"i\", 0)\n tilt = manager.Value(\"i\", 0)\n \n panP = manager.Value(\"f\", 0.188) #188\n panI = manager.Value(\"f\", 0.0)\n panD = manager.Value(\"f\", 0.0)\n \n tiltP = manager.Value(\"f\", 0.1558) # 1558\n tiltI = manager.Value(\"f\", 0.0)\n tiltD = manager.Value(\"f\", 0.0)\n \n pid_active = manager.Value(\"b\", False)\n \n processCore = Process(target=core_process,\n args=(args[\"output\"], pan, tilt, pan_error, tilt_error, pid_active))\n processPanPID = Process(target=pid_process,\n args=(pan, panP, panI, panD, pan_error, pid_active))\n processTiltPID = Process(target=pid_process,\n args=(tilt, tiltP, tiltI, tiltD, tilt_error, pid_active))\n \n processCore.start()\n processPanPID.start()\n processTiltPID.start()\n \n processCore.join()\n processPanPID.join()\n processTiltPID.join()\n \n \n","sub_path":"remote_client.py","file_name":"remote_client.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"286846185","text":"from sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.ensemble import RandomForestClassifier\nfrom joblib import Parallel, delayed\nfrom copy import deepcopy\nimport numpy as np\n\n\nclass FeatureSelectionMetric:\n def __init__(self, learner=None, random_state=None):\n self.learner = learner\n self.random_state = random_state\n self.value = None\n if learner is None:\n self.learner_ = RandomForestClassifier(n_estimators=100, oob_score=True, n_jobs=-1,\n random_state=self.random_state)\n else:\n self.learner_ = learner\n self.learner_.random_state = self.random_state\n \n def fit(self, x, y, candidate):\n self.learner_.fit(x[:, candidate], y)\n\n\nclass OOBFeatureSelectionMetric(FeatureSelectionMetric):\n def __init__(self, learner=None, random_state=None):\n super().__init__(learner=learner,\n random_state=random_state)\n \n def compute_value(self, x, y, candidate):\n self.value = self.learner_.oob_score_\n return self.value\n\n\nclass StabFeatureSelectionMetric(FeatureSelectionMetric):\n def __init__(self, learner=None, random_state=None):\n super().__init__(learner=learner,\n random_state=random_state)\n \n def fit(self, x, y, candidate):\n # x is a list of x_l, x_u\n x_l = x[0]\n y_l = y\n self.learner_.fit(x_l[:, candidate], y_l)\n \n def compute_value(self, x, y, candidate):\n x_u = x[1]\n max_vote_u = self.learner_.predict_proba(x_u[:, candidate]).max(axis=1)\n self.value = self.learner_.oob_score_ + max_vote_u.mean()\n return self.value\n\n\nclass CVFeatureSelectionMetric(FeatureSelectionMetric):\n def __init__(self, learner=None, n_splits=5, n_jobs=5, random_state=None):\n super().__init__(learner=learner,\n random_state=random_state)\n self.n_splits = n_splits\n self.n_jobs = n_jobs\n self.scores = None\n \n def compute_value(self, x, y, candidate):\n kf = StratifiedKFold(n_splits=self.n_splits, random_state=self.random_state, shuffle=True)\n splits = list(kf.split(x, y))\n models = list(map(lambda i: deepcopy(self.learner_), range(self.n_splits)))\n self.scores = np.array(Parallel(n_jobs=self.n_jobs)(delayed(_one_fold_fit)(\n models[i], x[:, candidate], y, splits[i][0], splits[i][1]) for i in range(self.n_splits)))\n self.value = self.scores.mean()\n return self.value\n\n\ndef _one_fold_fit(model, x, y, train_index, test_index):\n model.fit(x[train_index, :], y[train_index])\n y_pred_test = model.predict(x[test_index, :])\n return accuracy_score(y[test_index], y_pred_test)\n","sub_path":"selection_metrics.py","file_name":"selection_metrics.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"651418444","text":"\"\"\"Digital_Fingerprinting URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nimport sys,os\nfrom django.urls import path\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom dfp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('addplant/', views.insert_plant),\n path('adduser/', views.adduser),\n path('login/', views.login),\n path('plantlist/', views.plant_list),\n path('uploadfailedimg/',views.upload_failed_img),\n path('failedimgdetails',views.get_failed_img_details),\n path('adduserinfo/', views.adduserinfo),\n path('logout/', views.logout),\n path('backtrack_images/', views.backtrack_images),\n path('kpi/', views.kpi),\n \n\n]\n","sub_path":"Digital_Fingerprinting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"162519093","text":"import pandas as pd\nimport requests as req\nimport matplotlib.pyplot as plt\nimport io\n\n\ndef statsbank_format(columns):\n url = \"https://api.statbank.dk/v1/data/FOLK1A/CSV?lang=en&delimiter=Semicolon\"\n for columns in columns:\n url = url + \"&\"+columns+\"=*\"\n return url\n\n\ndef direct(columns):\n df = pd.read_csv(statsbank_format(columns), sep =';')\n return df\n\n\ndef divorced():\n '''\n What is the change in pct of divorced danes from 2008 to 2020?\n '''\n df = direct(['CIVILSTAND', 'TID'])\n \n df = df[df[\"CIVILSTAND\"].str.match('Divorced')]\n fig, ax = plt.subplots()\n ax.plot(df['TID'], df['INDHOLD'])\n ax.legend()\n plt.show()\n \n\ndef never_married():\n '''\n Which of the biggest cities has the highest percentage of 'Never Married'?\n '''\n df = direct(['OMR%C3%85DE', 'CIVILSTAND'])\n df = df[df['CIVILSTAND'].str.match('Never married')]\n df = df.sort_values(by=['INDHOLD'])[-6:-1]\n\n df.plot.bar(x='OMRÅDE', y='INDHOLD')\n plt.show()\n\n\ndef marrital_status():\n '''\n Show a bar chart of changes in marrital status in Copenhagen from 2008 till now\n '''\n df = direct(['TID','OMR%C3%85DE', 'CIVILSTAND'])\n df = df[df['OMRÅDE'].str.match('Copenhagen')]\n df = df.drop(columns=['OMRÅDE'])\n df['TID'] = df['TID'].map(lambda x: x[:4])\n \n df1 = df[df['CIVILSTAND'].str.match('Married/separated')]\n df2 = df[df['CIVILSTAND'].str.match('Never married')]\n df3 = df[df['CIVILSTAND'].str.match('Widowed')]\n df4 = df[df['CIVILSTAND'].str.match('Divorced')]\n\n df['MARSEP'] = df1['INDHOLD']\n\n df = df.drop(columns=['CIVILSTAND'])\n df = df.drop(columns=['INDHOLD'])\n df = df.dropna()\n\n df = df.drop_duplicates(subset=['TID'])\n\n df = df.reset_index()\n df1 = df1.reset_index()\n df2 = df2.reset_index()\n df3 = df3.reset_index()\n df4 = df4.reset_index()\n\n df['NEVERMARRIED'] = df2['INDHOLD']\n df['WIDOWED'] = df3['INDHOLD']\n df['DIVORCED'] = df4['INDHOLD']\n\n df.plot(x='TID', y=['MARSEP', 'NEVERMARRIED', 'WIDOWED', 'DIVORCED'], kind=\"bar\")\n plt.show()\n \ndef married_nevermarried():\n '''\n Show a bar chart of 'Married' and 'Never Married' for all ages in DK (Hint: 2 bars of different color)\n '''\n df = direct(['ALDER', 'CIVILSTAND'])\n df = df.drop(columns='TID')\n df = df[~df['ALDER'].str.match('Total')]\n df['ALDER'] = df['ALDER'].map(lambda x: x[:-6])\n\n df1 = df[df['CIVILSTAND'].str.match('Married/separated')]\n df2 = df[df['CIVILSTAND'].str.match('Never married')]\n\n df['MARRIED'] = df1['INDHOLD']\n df = df.drop(columns=['CIVILSTAND'])\n df = df.drop(columns=['INDHOLD'])\n df = df.dropna()\n\n df = df.drop_duplicates(subset=['ALDER'])\n df = df.reset_index()\n df2 = df2.reset_index()\n df['NEVER MARRIED'] = df2['INDHOLD']\n\n df.plot(x='ALDER', y=['MARRIED','NEVER MARRIED'], kind=\"bar\", width=0.5)\n plt.show()\n\n\ndef create_csv(url):\n res = req.get(url, stream=True)\n with open(\"./resources/FOLK1A.csv\", 'wb') as fileWriter:\n for line in res.iter_content():\n fileWriter.write(line)","sub_path":"week5/logic/ex01.py","file_name":"ex01.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"596131042","text":"import numpy as np\nfrom scipy.spatial.distance import pdist, squareform\nfrom params import *\n\n\ndef init(L, N, v0, R, eta):\n ''' Initialise a single run '''\n state = np.zeros( (N, 5) )\n state[:,:2] = L*np.random.random( (N, 2) ) - 0.5*L # positions x,y\n state[:,2] = 2*np.pi * np.random.random(N) # angle\n state[:,3] = v0 * np.cos(state[:,2]) # x velocity\n state[:,4] = v0 * np.sin(state[:,2]) # y velocity\n \n return state\n\n\ndef step(state, L, N, v0, R, eta, t): \n ''' Perform one step for all particles '''\n \n # Update positions\n state[:,:2] = state[:,:2] + v0*dt*state[:,3:]\n \n # Periodic boundaries\n crossedX = np.where(abs(state[:,0]) > 0.5*L)\n crossedY = np.where(abs(state[:,1]) > 0.5*L)\n state[crossedX,0] = state[crossedX,0] - np.sign(state[crossedX,0])*L\n state[crossedY,1] = state[crossedY,1] - np.sign(state[crossedY,1])*L\n \n # Initialise heading with noise\n heading = eta*np.random.random(N) - 0.5*eta\n \n # Use adjacency matrix to determine neighbours\n A = squareform(pdist(state[:,:2]))\n for i in range(N):\n adj = np.where(A[i,:] < R)[0] # indices of adjacent particles\n theta = state[adj,2] # angles of all adjacent particles\n\n # Leaders must be treated separately on account of their weight\n ldr_adj = np.where(A[i,:N_ldr] < ldr_R)[0]\n ldr_theta = state[ldr_adj,2]\n\n # Sum sin and cos of angles\n sum_sin = np.sum(np.sin(theta)) + ldr_weight*np.sum(np.sin(ldr_theta))\n sum_cos = np.sum(np.cos(theta)) + ldr_weight*np.sum(np.cos(ldr_theta))\n \n # Compute heading for this particle\n heading[i] += np.arctan2(sum_sin, sum_cos)\n \n # Update state with new headings\n state[:,2] = heading # Can add an angle here for waveyness\n \n # Some leaders may have pre-defined trajectories\n state[:N_ldr_traj,2] = ldr_traj * t\n \n # Update velocities\n state[:,3] = v0 * np.cos(state[:,2])\n state[:,4] = v0 * np.sin(state[:,2])\n \n return\n \n\ndef order_parameter(state, V_coeff):\n ''' Calculate order parameter (V) '''\n \n Vx = np.sum(state[:,3])\n Vy = np.sum(state[:,4])\n return np.sqrt(Vx*Vx + Vy*Vy) * V_coeff\n \n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"541180996","text":"#!/usr/bin/python3\n#bing_ip_mod.py\n#python3 bing_ip_mod.py -r 72.163.1.0/24 -f /tmp/bing_out.txt\n#written to use the Bing search IP modifier to get lists of hostnames behind single IP/load balancer, etc.\n#xx0hcd\n\nimport ipaddress\nimport http.client, urllib.parse, json\nimport sys, os, time\nimport getopt\n\n\nerrors = (\"\"\"\n[-]\n[-] The IP range to scan and output filename are required.\n[-]\n[+]\n[+] -r, --range \tEnter IP CIDR range.\n[+]\n[+] -f, --filename\tEnter path/filename for output file.\n[+]\n[+] i.e. python3 bing_ip_mod.py -r 72.163.1.0/24 -f /tmp/outfile.txt\n[+]\n\"\"\")\n\nif len(sys.argv) <= 1:\n print (errors)\n exit(1)\n\ndef search(argv):\n \n ip = ipaddress.ip_network(ip_range)\n\n try:\n #making sure the IP temp file is not there from a previous run, etc.\n if os.path.exists(\"/tmp/bing_hosts.txt\"):\n os.system(\"rm -r /tmp/bing_hosts.txt\")\t\t\t\n\n except (OSError,IOError):\n print (\"[-] \")\n print (\"[-] Problem deleting temp file. Check file permissions. \")\n print (\"[-] \")\n\n #put the CIDR range into a list in a temp file\n try:\n\n with open(\"/tmp/bing_hosts.txt\", \"a+\") as f:\n for i in ip.hosts():\n print(i, \"\\n\", end=\"\", file=f)\n f.close()\n time.sleep(1)\n\n except (OSError, IOError):\n print(\"[-] \")\n print(\"[-] Error opening/creating file. \")\n print(\"[-] \")\n\n #search against the temp list, output is json. Microsoft has several API's for search, this uses the basic web search.\n try:\n with open(\"/tmp/bing_hosts.txt\", \"r\") as w:\n for line in w:\n search = \"ip:\" + line\n host = \"api.cognitive.microsoft.com\"\n path = \"/bing/v7.0/search\"\n headers = {'Ocp-Apim-Subscription-Key': api_key}\n conn = http.client.HTTPSConnection(host)\n query = urllib.parse.quote(search)\n conn.request(\"GET\", path + \"?q=\" + query, headers=headers)\n response = conn.getresponse()\n result = response.read().decode(\"utf8\")\n with open(filename, \"a+\") as outfile:\n print(json.dumps(json.loads(result), indent=4), file=outfile)\n\n except (OSError, IOError):\n print(\"[-] \")\n print(\"[-] Error \")\n print(\"[-] \")\t\n\n\ndef cleanup():\n #making sure the IP temp file is removed after processing.\n try:\n if os.path.exists(\"/tmp/bing_hosts.txt\"):\n os.system(\"rm -r /tmp/bing_hosts.txt\")\t\t\t\n\n except (OSError,IOError):\n print (\"[-] \")\n print (\"[-] Problem deleting temp file. Check file permissions. \")\n print (\"[-] \")\n\n\ndef main(argv):\n\t\n global ip_range\n global filename\n global api_key\n\n #Your Microsoft Bing API key goes here.\n api_key = \"\"\n\n try:\n opts, args = getopt.getopt(argv, \"hr:f:\",[\"ip_range=\",\"filename=\"])\n\n except getopt.GetoptError:\t\t\n print (errors)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print (errors)\n sys.exit()\n elif opt in (\"-r\", \"--ip_range\"):\n ip_range = arg\n elif opt in (\"-f\", \"--filename\"):\n filename = arg\n\t\n try:\n if os.path.exists(filename):\n print (\"[+] \")\n print (\"[+] File: \" + filename + \" already exists! Please remove the old file or type in a new path/filename. \")\n print (\"[+] \")\n sys.exit()\n except (OSError, IOError):\n print (\"[-] \")\n print (\"[-] Problem writing to \", filename)\n print (\"[-] \")\n\t\n\nif __name__ == \"__main__\":\n\n while True:\n try:\n main(sys.argv[1:])\n search(sys.argv[1:])\n cleanup()\n break\n\n except IOError:\n print (errors)\n break\n\n except KeyboardInterrupt:\n print (\"\")\n print (\"[+] \")\n print (\"[+] Ctrl ^C, Aborted by user. \")\n print (\"[+] \")\n sys.exit(3)\t\n\t\n","sub_path":"bing_ip_mod.py","file_name":"bing_ip_mod.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"389096683","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nv = np.array([1, 3, 2, 4])\nx = np.array([0, 2, 4, 6])\n\nplt.figure()\nplt.plot(x, v, 'g--', label='vector')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('example title')\nplt.legend(loc='lower right')\nplt.show()\n\nprint(v.shape)\nprint(x.shape)\n","sub_path":"BigDataMooc/projects/sem2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"124462137","text":"from init_mysql_conn import sql_query\n\n\n# todo: uncomment once player perspectives is handled the same way as genres\ndef create_tables(sql_conn):\n \"\"\"\n This function creates the database tables by running a series of queries\n \"\"\"\n\n tables_creation_queries = [\n 'CREATE TABLE publishers (\\\n id int AUTO_INCREMENT PRIMARY KEY,\\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE developers (\\\n id int AUTO_INCREMENT PRIMARY KEY, \\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE age_ratings (\\\n id int AUTO_INCREMENT PRIMARY KEY,\\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE franchises (\\\n id int AUTO_INCREMENT PRIMARY KEY,\\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE game_engines (\\\n id int AUTO_INCREMENT PRIMARY KEY,\\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE player_perspectives (\\\n id int AUTO_INCREMENT PRIMARY KEY,\\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE games(\\\n id int AUTO_INCREMENT PRIMARY KEY, \\\n name varchar(250) UNIQUE, \\\n publisher_id int, \\\n age_rating_id int, \\\n franchise_id int, \\\n game_engine_id int, \\\n num_players varchar(250), \\\n release_date varchar(250), \\\n perspective_id int, \\\n FOREIGN KEY(publisher_id) REFERENCES publishers(id), \\\n FOREIGN KEY(perspective_id) REFERENCES player_perspectives(id), \\\n FOREIGN KEY(franchise_id) REFERENCES franchises(id), \\\n FOREIGN KEY(game_engine_id) REFERENCES game_engines(id), \\\n FOREIGN KEY(age_rating_id) REFERENCES age_ratings(id))',\n # developer_id int, \\\n # FOREIGN KEY(developer_id) REFERENCES developers(id), \\\n # FOREIGN KEY(game_engine_id) REFERENCES game_engines(id), \\\n # FOREIGN KEY(franchise_id) REFERENCES franchises(id), \\\n # franchise_id int, \\\n # game_engine_id int, \\\n \n\n\n 'CREATE TABLE consoles (\\\n id int AUTO_INCREMENT PRIMARY KEY, \\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE genres (\\\n id int AUTO_INCREMENT PRIMARY KEY, \\\n name varchar(250) NOT NULL, \\\n UNIQUE (name))',\n\n 'CREATE TABLE game_to_console( \\\n game_id INT NOT NULL references games(id), \\\n console_id INT NOT NULL references consoles(id), \\\n PRIMARY KEY(game_id, console_id))',\n\n # 'CREATE TABLE game_to_perspective (\\\n # game_id INT NOT NULL references games(id), \\\n # perspective_id INT NOT NULL references player_perspectives(id), \\\n # PRIMARY KEY(game_id, perspective_id))',\n\n 'CREATE TABLE game_to_genre( \\\n game_id INT NOT NULL references games(id), \\\n genre_id INT NOT NULL references genres(id), \\\n PRIMARY KEY(game_id, genre_id))',\n\n 'CREATE TABLE game_to_developer( \\\n game_id INT NOT NULL references games(id), \\\n developer_id INT NOT NULL references developers(id), \\\n console_id INT NOT NULL references consoles(id), \\\n PRIMARY KEY(game_id, developer_id, console_id))',\n\n 'CREATE TABLE main_scores( \\\n game_id int, \\\n console_id int, \\\n metascore varchar(250), \\\n userscore varchar(250), \\\n num_metascore varchar(250), \\\n num_userscore varchar(250), \\\n FOREIGN KEY(game_id) REFERENCES games(id), \\\n FOREIGN KEY(console_id) REFERENCES consoles(id))',\n\n 'CREATE TABLE user_scores( \\\n game_id int, \\\n console_id int, \\\n num_positive varchar(250), \\\n num_mixed varchar(250), \\\n num_negative varchar(250), \\\n FOREIGN KEY(game_id) REFERENCES games(id))',\n\n 'CREATE TABLE critic_scores( \\\n game_id int, \\\n console_id int, \\\n num_positive varchar(250), \\\n num_mixed varchar(250), \\\n num_negative varchar(250), \\\n FOREIGN KEY(game_id) REFERENCES games(id))'\n ]\n\n for query in tables_creation_queries:\n sql_query(sql_conn, query)\n","sub_path":"create_tables.py","file_name":"create_tables.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"338377046","text":"import redis\n\nfrom logbook import Logger\n\nfrom onitu.utils import connect_to_redis\n\n\nclass Referee(object):\n \"\"\"Referee class, receive all events and deal with them.\n\n The events are represented as Redis List 'events' that should be\n appended with RPUSH. Each item is the file id (fid) of the file\n which triggered the event.\n\n The Referee give orders to the entries via his PUB ZMQ socket,\n whose port is stored in the Redis 'referee:publisher' key.\n The Plug of each entry should subscribe to this port with a PULL\n socket and subscribe to all the events starting by their name.\n\n The notifications are sent to the publishers as multipart\n messages with three parts :\n\n - The name of the addressee (the channel)\n - The name of the entry from which the file should be transferred\n - The id of the file\n \"\"\"\n\n def __init__(self):\n super(Referee, self).__init__()\n\n self.logger = Logger(\"Referee\")\n\n self.redis = connect_to_redis()\n self.entries = self.redis.smembers('entries')\n\n self.logger.info(\"Started\")\n\n def listen(self):\n \"\"\"Listen to all the events, and handle them\n \"\"\"\n while True:\n try:\n _, event = self.redis.blpop(['events'])\n driver, fid = event.split(':')\n except redis.ConnectionError:\n exit()\n\n # delete all the newer events referring to this file\n self.redis.lrem('events', fid)\n self._handle_event(driver, fid)\n\n def _handle_event(self, driver, fid):\n \"\"\"Choose who are the entries that are concerned by the event\n and send a notification to them.\n\n For the moment all the entries are notified for each event, but\n this should change when the rules will be introduced.\n \"\"\"\n metadata = self.redis.hgetall('files:{}'.format(fid))\n owners = metadata['owners'].split(':')\n uptodate = metadata['uptodate'].split(':')\n filename = metadata['filename']\n\n self.logger.info(\"New event for '{}' from {}\", filename, driver)\n\n to_notify = []\n new_owners = []\n\n for name in self.entries:\n if name in uptodate:\n continue\n\n if name in owners:\n to_notify.append(name)\n continue\n\n to_notify.append(name)\n new_owners.append(name)\n\n if new_owners:\n value = ':'.join(owners + new_owners)\n self.redis.hset('files:{}'.format(fid), 'owners', value)\n\n for name in to_notify:\n self.logger.debug(\n \"Notifying {} about '{}'\", name, filename\n )\n self.redis.rpush(\n 'drivers:{}:events'.format(name),\n \"{}:{}\".format(uptodate[0], fid)\n )\n","sub_path":"onitu/referee/referee.py","file_name":"referee.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"56943991","text":"from numpy import *\n\n\nclass lasso:\n\n def __init__(self, Y, X):\n self.Y = Y\n self.X = X\n self.N, self.p = shape(X)\n # print(self.N)\n # print(self.p)\n self.XX = dot(X.T, X)\n self.XY = dot(X.T, Y)\n # self.beta = linalg.solve(self.XX, self.XY)\n self.beta = random.randn(self.p, 1)\n beta = self.beta\n resid = (Y - dot(X, beta))\n self.sigma2 = asscalar(dot(resid.T, resid)) / self.N\n # print(self.sigma)\n lam = 1\n self.lam2 = lam * lam * self.N\n self.E_step()\n self.M_step()\n\n def E_step(self):\n sigma = sqrt(self.sigma2)\n beta = self.beta\n lam = sqrt(self.lam2)\n self.E_1_S = abs(divide(sigma * lam, beta))\n self.E_1_S[self.E_1_S > 1E15] = 1E15\n\n # def wald_vec(self, par1, par2, n):\n # max_i = par1.size\n # result = zeros((max_i, n))\n # for i in range(0, max_i):\n # result[i, :] = random.wald(par1[i], par2, n)\n # return result\n\n # def E_step(self, n):\n # sigma = sqrt(self.sigma2)\n # beta = self.beta\n # lam = sqrt(self.lam2)\n # par1 = abs(divide(sigma * lam, beta))\n # par2 = self.lam2\n # self.E_1_S = par1\n # Tau_sample = self.wald_vec(par1, par2, n)\n # self.E_S = mean(1 / Tau_sample, 1)\n\n def M_step(self):\n # self.lam2 = self.p * 2 / self.E_S.sum()\n XX_diag = self.XX + diag(asmatrix(self.E_1_S).A1)\n self.beta = linalg.solve(XX_diag, self.XY)\n resid = (self.Y - dot(self.X, self.beta))\n par1 = asscalar(dot(resid.T, resid)) + \\\n sum(multiply(multiply(self.beta, self.beta), self.E_1_S))\n self.sigma2 = par1 / (self.p + self.N)\n\n def comp_Q(self):\n Y = self.Y\n X = self.X\n N = self.N\n p = self.p\n beta = self.beta\n sigma2 = self.sigma2\n lam = sqrt(self.lam2)\n resid = Y - dot(X, beta)\n Q = asscalar(dot(resid.T, resid)) / sigma2 + \\\n (p + N) * log(sigma2) + 2 * lam * sum(abs(beta)) / sqrt(sigma2) \\\n - 2 * p * log(lam)\n return Q\n\n def EM(self, steps):\n cur_Q = self.comp_Q()\n for i in range(0, steps):\n self.E_step()\n self.M_step()\n new_Q = self.comp_Q()\n if(abs((new_Q - cur_Q) / cur_Q) < 1E-8):\n break\n cur_Q = new_Q\n print(cur_Q, self.sigma2, self.lam2)\n # print(self.beta)\n # print(self.sigma2)\n # print(self.lam2)\n","sub_path":"lasso.py","file_name":"lasso.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"128420982","text":"from django.urls import path,re_path\n\nfrom . import views\n\nurlpatterns=[\n path(\"\",views.index,name='index'),\n re_path(r'[0-9]+[A-Z]+[0-9]*',views.student_information,name='student_information'),\n path('login',views.login,name='login'),\n path('logout',views.logout,name='logout'),\n]\n","sub_path":"infosite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"593994123","text":"from flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager\n\nfrom flaskr import create_app\nfrom flaskr.models import db\n\napp = create_app()\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command(\"db\", MigrateCommand)\n\n\n@manager.command\ndef db_drop_and_create_all():\n db.drop_all()\n db.create_all()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"backend/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"373480061","text":"import datetime\nimport os\nfrom copy import copy\n\nfrom ..constants import FIRESTORE_COLLECTIONS\nfrom ..utils import set_env_list\n\n\ndef get_collection_name(exchange, suffix=\"\"):\n if \"PYTEST_CURRENT_TEST\" in os.environ:\n suffix = f\"{suffix}-test\" if suffix else \"test\"\n collection = f\"{exchange}-{suffix}\" if suffix else exchange\n set_env_list(FIRESTORE_COLLECTIONS, collection)\n return collection\n\n\ndef firestore_data(data):\n data = copy(data)\n # Firestore doesn't like datetime.date\n if \"date\" in data:\n del data[\"date\"]\n # Timestamp\n for key in (\"timestamp\", \"listing\", \"expiry\"):\n if key in data:\n # UTC, please.\n data[key] = data[key].replace(tzinfo=datetime.timezone.utc)\n # Float\n for key in (\"open\", \"high\", \"low\", \"close\", \"price\", \"volume\", \"notional\"):\n if key in data:\n data[key] = float(data[key])\n # Int\n for key in (\"nanoseconds\", \"tickRule\", \"ticks\", \"index\"):\n if key in data:\n data[key] = int(data[key])\n return data\n","sub_path":"crypto_exchange_etl/firestore_cache/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"198853890","text":"import cv2, sys, numpy, os \nhaar_file = 'cascade.xml'\ndatasets = 'datasets'\n\n\nif __name__ == \"__main__\":\n\t\n\n\t(width, height) = (130, 100)\t \n\n\tface_cascade = cv2.CascadeClassifier(haar_file) \n\twebcam = cv2.VideoCapture(0) #1 for any other cam\n\t# cam = cv2.VideoCapture('http://192.168.43.7:8080/video')\n\tf = open(\"Log.txt\",\"a+\")\n\tf.seek(0)\n\tchk = f.read(1)\n\tif not chk:\n\t\tf.write(\"DD|MM|YYYY\\t\")\n\telse:\n\t\tf.seek(0,2) # 2 is to the eof\n\tsub_data = input(\"Enter Name : \")\t\n\tif sub_data == 'q':\n\t\texit()\n\tpath = os.path.join(datasets, sub_data) \n\tif not os.path.isdir(path): \n\t\tos.mkdir(path) \n\tcount = 0\n\twhile count >= 0: \n\t\t(_, im) = webcam.read() \n\t\tgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) \n\t\tfaces = face_cascade.detectMultiScale(gray, 1.3, 4) \n\t\tfor (x, y, w, h) in faces: \n\t\t\tcv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) \n\t\t\tface = gray[y:y + h, x:x + w] \n\t\t\tface_resize = cv2.resize(face, (width, height)) \n\t\t\tcv2.imwrite('% s/% s.png' % (path, count), face_resize) \n\t\tcount += 1\n\t\tcv2.imshow('OpenCV', im) \n\t\tif cv2.waitKey(1) & 0xFF==ord('q'):\n\t\t\tbreak\n\tf.write(sub_data+\"\\t\")\n # f.close()","sub_path":"create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"287383963","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# setup script for the extcats package.\n#\n# Author: M. Giomi (matteo.giomi@desy.de)\n\nimport os\nfrom urllib.request import urlretrieve\nfrom shutil import unpack_archive\nfrom setuptools import setup\n\nsetup(\n name='extcats',\n version='1.3',\n description='Tools to organize and query astronomical catalogs',\n author='Matteo Giomi',\n author_email='matteo.giomi@desy.de',\n packages=['extcats'],\n url = 'https://github.com/MatteoGiomi/extcats',\n download_url = 'https://github.com/MatteoGiomi/extcats/archive/1.3.tar.gz',\n install_requires=['pymongo', 'healpy', 'astropy', 'pandas', 'tqdm'],\n )\n\n# ------- download test data ------- #\n# the million quasar catalog\nmqc_testdata_dir = \"./testdata/milliquas\"\nif not os.path.isdir(mqc_testdata_dir):\n print (\"creating testdata directory: %s\"%mqc_testdata_dir)\n os.makedirs(mqc_testdata_dir)\ndest = os.path.join(mqc_testdata_dir, \"heasarc_milliquas.tdat.gz\")\nif not os.path.isfile(dest):\n print (\"downloading the million quasar catalog \\\n(MQC, https://heasarc.gsfc.nasa.gov/W3Browse/all/milliquas.html)\")\n urlretrieve(\"https://desycloud.desy.de/index.php/s/AsxkEJUJ8LrgJkd\", dest)\n\n# a few small files from Panstarrs\nps1_testdata_dir = \"./testdata/PS1DR1_test\"\nif not os.path.isdir(ps1_testdata_dir):\n print (\"creating testdata directory: %s\"%ps1_testdata_dir)\n os.makedirs(ps1_testdata_dir)\nif not os.listdir(ps1_testdata_dir):\n print (\"downloading few PS1 DR1 MeanObject table files (https://panstarrs.stsci.edu/)\")\n tmp = os.path.join(ps1_testdata_dir, \"tmp_PS1DR1_test.zip\")\n urlretrieve(\"https://desycloud.desy.de/index.php/s/3AAJ30J7YZ7dH43/download\", tmp)\n unpack_archive(tmp, \"./testdata\")\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"61692278","text":"\"\"\"\nspeakers.py\n\nSpeakers client for Mycroft.\nUSAGE:\n`python speakers.py`\n\"\"\"\n\nimport mycroft\nimport socket\nimport threading\nimport telnetlib\nimport traceback\nimport random\nimport sys\nimport subprocess\n\n# only import pyaudio if it is installed, otherwise just show a warning\ntry:\n import pyaudio\nexcept ImportError:\n print(\"WARNING: pyaudio not found, functionality is limited\")\n pyaudio = None\n\n\nclass Speakers(mycroft.App):\n\n def __init__(self):\n # initialize VLC\n if sys.platform == 'darwin':\n vlc = '/Applications/VLC.app/Contents/MacOS/VLC'\n else:\n vlc = 'vlc'\n\n # randomize which port is used (this should be enough)\n port = random.randint(2000, 60000)\n # start up vlc\n\n def start_vlc():\n subprocess.call(\n '{0} --extraint rc --rc-host=localhost:{1}'.format(\n vlc,\n port\n )\n )\n threading.Thread(target=start_vlc).start()\n self.vlc_conn = telnetlib.Telnet(\n host='localhost',\n port=port\n )\n\n @mycroft.on('APP_DEPENDENCY')\n def app_dependency(self, body):\n self.up()\n\n @mycroft.on('MSG_QUERY')\n def msg_query(self, body):\n if body['action'] == 'stream_tts':\n client_ip = body['data']['ip']\n port = body['data']['port']\n cmd = 'enqueue tcp://{0}:{1}\\nplay\\n'.format(client_ip, port)\n self.vlc_conn.write(cmd.encode('utf-8'))\n\n elif body['action'] == 'stream_video':\n cmd = 'enqueue {0}\\nplay\\n'.format(body['data'])\n self.vlc_conn.write(cmd)\n\n elif body['action'] == 'stream_spotify':\n client_ip = body['data']['ip']\n port = body['data']['port']\n audio_client = socket.create_connection((client_ip, port))\n thread = threading.Thread(target=self.play_music, args=[audio_client])\n thread.start()\n\n def play_music(self, client):\n if not pyaudio:\n print(\"WARNING: Cannot play this stream; pyaudio not installed\")\n return\n\n chunk = 2048\n p = pyaudio.PyAudio()\n stream = p.open(\n format=pyaudio.paInt16,\n channels=2,\n rate=44100,\n output=True\n )\n\n while True:\n try:\n data = client.recv(8192)\n stream.write(data)\n except ConnectionResetError:\n break\n\n stream.stop_stream()\n stream.close()\n\n p.terminate()\n\n\nif __name__ == '__main__':\n app = Speakers()\n app.start(\n 'app.json',\n 'speakers',\n host=sys.argv[1],\n port=int(sys.argv[2])\n )\n","sub_path":"speakers.py","file_name":"speakers.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"64404433","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Main Imports\n\nimport random\nimport array\nimport vrp as VRP\nimport elitism\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport _pickle as cPickle\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\nfrom tqdm import tqdm\n\n\n# ## Experiment Dictionary\n\n# In[2]:\n\n\ncombinations = [(n_vehicles, hof) for n_vehicles in np.linspace(\n 1, 620, num=32, dtype=int) for hof in [5, 10, 20, 30]]\n\nexperiment_dict = {'experiment_{}'.format(i): {\n 'num_vehicles': combinations[i][0],\n 'hof': combinations[i][1],\n} for i in range(len(combinations))}\n\n\n# ## Randomness control\n\n# In[3]:\n\n\n# set the random seed:\nRANDOM_SEED = 42\nrandom.seed(RANDOM_SEED)\n\n\n# ## Constants for TSP instance\n\n# In[4]:\n\n\nTSP_NAME = \"cost_matrix\"\nCOORDENADAS = \"demanda_bodegas\"\nDEPOT_LOCATION = 0\nPOPULATION_SIZE = 500\n\n\n# ## Genetic Algorithm Constants\n\n# In[ ]:\n\n\nP_CROSSOVER = 0.9 # probability for crossover\nP_MUTATION = 0.2 # probability for mutating an individual\nMAX_GENERATIONS = 10000\n\n\n# In[ ]:\n\n\ntoolbox = base.Toolbox()\n\n\n# ## Objective function for distance minimization\n\n# In[ ]:\n\n\ncreator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\n\n\n# ## Instance individual classes\n\n# In[ ]:\n\n\ncreator.create(\"Individual\", array.array, typecode='i', fitness=creator.FitnessMin)\n\n\n# ## Fitness function definition\n\n# In[ ]:\n\n\ndef vrpDistance(individual):\n return vrp.getMaxDistance(individual),\n\n\n# In[ ]:\n\n\ntoolbox.register(\"evaluate\", vrpDistance)\n\n\n# In[ ]:\n\n\ndef genetic_algorithm_vrp(population_size, hall_of_fame_size, max_generations, vrp_fn, best_genetic_fn,\n min_fitness_fn, mean_fitness_fn, fitness_fn, route_fn, total_veh, save=True, verbose=False, plot=False):\n '''\n @param population_size: population size for experiment\n @param hall_of_fame_size: hof size for experiment\n @param max_generations: max_gens for experiment\n @param vrp_fn: filename to save vrp object\n @param best_genetic_fn: filename to save best_genetic solution object\n @param min_fitness_fn: filename to save min fitness object\n @param mean_fitness_fn: filename to save mean fitness object\n @param fitness_fn: filename to save fitness function plot\n @param route_fn: filename to save optimal route plot\n @param total_veh: total number of vehicles for VRP\n '''\n # Create initial population (generation 0):\n population = toolbox.populationCreator(n=population_size)\n\n # Prepare the statistics object:\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"min\", np.min)\n stats.register(\"avg\", np.mean)\n\n # Define the hall-of-fame object:\n hof = tools.HallOfFame(hall_of_fame_size)\n\n # Perform the Genetic Algorithm flow with hof feature added:\n population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,\n ngen=max_generations, stats=stats, halloffame=hof, verbose=False)\n\n # Best individual stats\n best = hof.items[0]\n if verbose:\n print(\"-- Best Ever Individual = \", best)\n print(\"-- Best Ever Fitness = \", best.fitness.values[0])\n\n print(\"-- Route Breakdown = \", vrp.getRoutes(best))\n print(\"-- total distance = \", vrp.getTotalDistance(best))\n print(\"-- max distance = \", vrp.getMaxDistance(best))\n\n # Main statistics\n minFitnessValues, meanFitnessValues = logbook.select(\"min\", \"avg\")\n\n if save:\n cPickle.dump(vrp, open('Output/pkl_files/{}'.format(vrp_fn), 'wb'), -1)\n cPickle.dump(best, open('Output/{}'.format(best_genetic_fn), 'wb'), -1)\n cPickle.dump(minFitnessValues, open(\n 'Output/pkl_files/{}'.format(min_fitness_fn), 'wb'), -1)\n cPickle.dump(meanFitnessValues, open(\n 'Output/pkl_files/{}'.format(mean_fitness_fn), 'wb'), -1)\n\n if plot:\n # Plot Best Solution\n plt.figure(1)\n plt.xlabel('Latitude')\n plt.ylabel('Longitude')\n plt.title('Best Route with {} vehicles'.format(total_veh))\n vrp.plotData(best)\n plt.savefig('/Output/plots/{}'.format(route_fn))\n plt.show()\n\n # Plot solution\n plt.figure(2)\n plt.plot(minFitnessValues, color='red')\n plt.plot(meanFitnessValues, color='green')\n plt.xlabel('Generation')\n plt.ylabel('Min / Average Fitness')\n plt.title('Min and Average fitness vs. Generation')\n plt.savefig('/Output/plots/{}'.format(fitness_fn), dpi=300)\n plt.show()\n\n# In[ ]:\n\n\nfailed_experiment = dict()\n\n\nfor key in tqdm(experiment_dict.keys()):\n # try:\n vrp = VRP.VehicleRoutingProblem(\n TSP_NAME, COORDENADAS, experiment_dict[key]['num_vehicles'], DEPOT_LOCATION)\n\n # Operator for randomly shuffled indices in GA\n toolbox.register(\"randomOrder\", random.sample, range(len(vrp)), len(vrp))\n # Individual creation operator to fill up an Individual instance with shuffled indices\n toolbox.register(\"individualCreator\", tools.initIterate,\n creator.Individual, toolbox.randomOrder)\n # Population creation operator\n toolbox.register(\"populationCreator\", tools.initRepeat, list, toolbox.individualCreator)\n\n # Genetic operators\n toolbox.register(\"select\", tools.selTournament, tournsize=2)\n toolbox.register(\"mutate\", tools.mutShuffleIndexes, indpb=1.0/len(vrp))\n toolbox.register(\"mate\", tools.cxUniformPartialyMatched, indpb=2.0/len(vrp))\n\n genetic_algorithm_vrp(POPULATION_SIZE,\n experiment_dict[key]['hof'],\n MAX_GENERATIONS,\n 'vrp_solution_{}.pkl'.format(key),\n 'best_genetic_solution_{}.pkl'.format(key),\n 'min_fitness_{}.pkl'.format(key),\n 'mean_fitness_{}.pkl'.format(key),\n 'fitness_function_{}.png'.format(key),\n 'route_plot_{}.png'.format(key),\n experiment_dict[key]['num_vehicles'], save=True)\n# except:\n# print(experiment_dict[key])\n# failed_experiment[key] = experiment_dict[key]\n# print(\"Error\")\n\n\n# In[ ]:\n","sub_path":"Two-phases/Optimization/clust1_opt/Solver.py","file_name":"Solver.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"154349807","text":"#Various types of information gathering\nimport requests\nimport random\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nimport re\n\nurl = 'http://10.0.2.6/mutillidae/index.php'\n\ndef gather_header():\n try:\n r = requests.get(url)\n headers_dict = r.headers\n for key, value in headers_dict.items():\n print('[+] {} : {}'.format(key, value))\n return r\n except:\n print('[-] Error in network connection.')\n\ndef find_insecure_headers():\n headers_dict = gather_header()\n\n if headers_dict:\n headers_dict = headers_dict.headers\n else:\n return\n\n print('\\n[!] Finding vulnerablilties\\n')\n\n try:\n xssprotect = headers_dict['X-XSS-Protection']\n if xssprotect != '1; mode=block':\n print('[-] X-XSS-Protection not set properly.')\n else:\n print('[+] X-XSS-Protection set propely.')\n except:\n print('[+] Escaping')\n\n try:\n contenttype = headers_dict['X-Content-Type-Options']\n if contenttype != 'nosniff':\n print('[+] X-Content-Type-Options not set properly.')\n except:\n print('[+] Escaping')\n\n try:\n hsts = headers_dict['Strict-Transport-Security']\n except:\n print('[+] HSTS not set properly.')\n\n try:\n csp = headers_dict['Content-Security-Policy']\n print('[+] great with csp')\n except:\n print('[-] csp mising')\n\n try:\n xframe = headers_dict['x-frame-options']\n print('[+] Likely to be safe from xframe')\n except:\n print('[-] xframe Missing.')\n\ndef insecure_cookies():\n response = gather_header()\n cookies = response.cookies\n\n for cookie in cookies:\n print('[+] Name : ', cookie.name)\n print('[+] Value : ', cookie.value)\n\n if not cookie.secure:\n cookie.secure = 'True'\n else:\n cookie.secure = 'False'\n\n if 'httponly' in cookie._rest.keys():\n cookie.httponly = 'True'\n else:\n cookie.httponly = 'False'\n\n if cookie.domain_initial_dot:\n cookie.domain_initial_dot = 'True'\n else:\n cookie.domain_initial_dot = 'False'\n\n print('[+] Cookie Secure :', cookie.secure)\n print('[+] Cookie httponly :', cookie.httponly)\n print('[+] Cookies domain iniitial dot', cookie.domain_initial_dot)\n\ndef test_http_methods():\n modes_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE', 'TEST']\n\n for mode in modes_list:\n r = requests.request(mode, url)\n print('[+]', mode, r.status_code, r.reason)\n if mode == 'TRACE' and 'TRACE / HTTP/1.1' in r.text:\n print('[+] Possible cross site tracing vulnerability found.')\n\ndef jquery_check():\n #to find jquery:\"1.3.2\"\n resp = requests.get(url)\n script_tags = []\n\n soup_obj = BeautifulSoup(resp.text, 'lxml')\n for line in soup_obj.find_all('script'):\n script_tag = line.get('src')\n script_tags.append(script_tag)\n\n for script in script_tags:\n if 'jquery.min' in str(script).lower():\n js_url = urljoin(url, script)\n resp = requests.get(js_url)\n #print(resp.text)\n\njquery_check()\n","sub_path":"src/info_gathering/header_vuln.py","file_name":"header_vuln.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"150299574","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view\nfrom rest_framework.serializers import ValidationError\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework import generics, mixins, viewsets\n\nimport api.models as ApiModels\nimport api.serializers as ApiSerializers\nimport api.renderers as ApiRenderers\n\nclass CommentDetailView(mixins.ListModelMixin, viewsets.GenericViewSet):\n\t\"\"\" CDUD functionality for specific comments \"\"\"\n\trenderer_classes = (ApiRenderers.CommentJSONRenderer,)\n\tserializer_classes = ApiSerializers.CommentSerializer\n\n\tdef list(self, request, **kwargs):\n\t\t\"\"\" Return comments for specific post \"\"\"\n\t\tserializer_context = {'request': request}\n\n\t\tpostID = kwargs['id']\n\t\ttry:\n\t\t\tpost = ApiModels.Post.objects.get(id=postID)\n\t\texcept Exception:\n\t\t\traise NotFound('Post with this id does not exist')\n\n\t\tcomments = self.paginate_queryset(post.comment_set.all())\n\t\tserializer = self.serializer_classes(comments, context=serializer_context, many=True)\n\t\treturn self.get_paginated_response(serializer.data)\n\n\tdef post(self, request, **kwargs):\n\t\t\"\"\" Create comment for specific post \"\"\"\n\t\tserializer_context = {\n\t\t\t'author': request.user,\n\t\t\t'request': request\n\t\t}\n\n\t\tif not request.user.is_authenticated:\n\t\t\traise NotFound('User must be authenticated')\n\n\t\tpostID = kwargs['id']\n\t\ttry:\n\t\t\tpost = ApiModels.Post.objects.get(id=postID)\n\t\texcept Exception as e:\n\t\t\traise NotFound('Post with this id does not exist')\n\n\t\tserializer = ApiSerializers.CommentSerializer(\n\t\t\tdata={\n\t\t\t\t'post': post.id,\n\t\t\t\t'content': request.data.get('content')\n\t\t\t}, context=serializer_context\n\t\t)\n\n\t\tserializer.is_valid(raise_exception=True)\n\t\tserializer.save()\n\t\treturn Response(serializer.data, status=200)\n","sub_path":"api/Views/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"182865260","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/dsupplee/dev/apis-client-generator/src/googleapis/codegen/schema.py\n# Compiled at: 2019-01-24 16:56:47\n\"\"\"API data models - schemas and their properties.\n\nThis module handles the objects created for the \"schema\" section of an API.\n\"\"\"\n__author__ = 'aiuto@google.com (Tony Aiuto)'\nimport collections, logging\nfrom googleapis.codegen import data_types\nfrom googleapis.codegen import template_objects\nfrom googleapis.codegen.api_exception import ApiException\n_ADDITIONAL_PROPERTIES = 'additionalProperties'\n_LOGGER = logging.getLogger('codegen')\n\nclass Schema(data_types.ComplexDataType):\n \"\"\"The definition of a schema.\"\"\"\n\n def __init__(self, api, default_name, def_dict, parent=None):\n \"\"\"Construct a Schema object from a discovery dictionary.\n\n Schemas represent data models in the API.\n\n Args:\n api: (Api) the Api instance owning the Schema\n default_name: (str) the default name of the Schema. If there is an 'id'\n member in the definition, that is used for the name instead.\n def_dict: (dict) a discovery dictionary\n parent: (Schema) The containing schema. To be used to establish unique\n names for anonymous sub-schemas.\n \"\"\"\n super(Schema, self).__init__(default_name, def_dict, api, parent=parent)\n name = def_dict.get('id', default_name)\n _LOGGER.debug('Schema(%s)', name)\n template_objects.CodeObject.ValidateName(name)\n self.SetTemplateValue('wireName', name)\n class_name = api.ToClassName(name, self, element_type='schema')\n self.SetTemplateValue('className', class_name)\n self.SetTemplateValue('isSchema', True)\n self.SetTemplateValue('properties', [])\n self._module = template_objects.Module.ModuleFromDictionary(self.values) or api.model_module\n\n @classmethod\n def Create(cls, api, default_name, def_dict, wire_name, parent=None):\n \"\"\"Construct a Schema or DataType from a discovery dictionary.\n\n Schemas contain either object declarations, simple type declarations, or\n references to other Schemas. Object declarations conceptually map to real\n classes. Simple types will map to a target language built-in type.\n References should effectively be replaced by the referenced Schema.\n\n Args:\n api: (Api) the Api instance owning the Schema\n default_name: (str) the default name of the Schema. If there is an 'id'\n member in the definition, that is used for the name instead.\n def_dict: (dict) a discovery dictionary\n wire_name: The name which will identify objects of this type in data on\n the wire. The path of wire_names can trace an item back through\n discovery.\n parent: (Schema) The containing schema. To be used to establish nesting\n for anonymous sub-schemas.\n\n Returns:\n A Schema or DataType.\n\n Raises:\n ApiException: If the definition dict is not correct.\n \"\"\"\n schema_id = def_dict.get('id')\n if schema_id:\n name = schema_id\n else:\n name = default_name\n class_name = api.ToClassName(name, None, element_type='schema')\n _LOGGER.debug('Create: %s, parent=%s', name, parent.values.get('wireName', '') if parent else 'None')\n if 'type' in def_dict:\n json_type = def_dict['type']\n if json_type == 'object':\n variant = def_dict.get('variant')\n if variant:\n return cls._CreateVariantType(variant, api, name, def_dict, wire_name, parent)\n props = def_dict.get('properties')\n if props:\n return cls._CreateObjectWithProperties(props, api, name, def_dict, wire_name, parent)\n additional_props = def_dict.get(_ADDITIONAL_PROPERTIES)\n if additional_props:\n return cls._CreateMapType(additional_props, api, name, wire_name, class_name, parent)\n return cls._CreateSchemaWithoutProperties(api, name, def_dict, wire_name, parent)\n if json_type == 'array':\n return cls._CreateArrayType(api, def_dict, wire_name, class_name, schema_id, parent)\n return data_types.CreatePrimitiveDataType(def_dict, api, wire_name, parent=parent)\n referenced_schema = def_dict.get('$ref')\n if referenced_schema:\n schema = api.SchemaByName(referenced_schema)\n if schema:\n _LOGGER.debug('Schema.Create: %s => %s', default_name, schema.values.get('wireName', ''))\n return schema\n return data_types.SchemaReference(referenced_schema, api)\n else:\n raise ApiException('Cannot decode JSON Schema for: %s' % def_dict)\n return\n\n @classmethod\n def _CreateObjectWithProperties(cls, props, api, name, def_dict, wire_name, parent):\n properties = []\n schema = cls(api, name, def_dict, parent=parent)\n if wire_name:\n schema.SetTemplateValue('wireName', wire_name)\n for prop_name in sorted(props):\n prop_dict = props[prop_name]\n _LOGGER.debug(' adding prop: %s to %s', prop_name, name)\n properties.append(Property(api, schema, prop_name, prop_dict))\n if prop_name == 'etag':\n schema.SetTemplateValue('hasEtagProperty', True)\n\n schema.SetTemplateValue('properties', properties)\n names = set()\n for p in properties:\n wire_name = p.GetTemplateValue('wireName')\n no_at_sign = wire_name.replace('@', '')\n if no_at_sign in names:\n raise ApiException('Property name clash in schema %s: %s conflicts with another property' % (\n name, wire_name))\n names.add(no_at_sign)\n\n return schema\n\n @classmethod\n def _CreateVariantType(cls, variant, api, name, def_dict, wire_name, parent):\n \"\"\"Creates a variant type.\"\"\"\n variants = collections.OrderedDict()\n schema = cls(api, name, def_dict, parent=parent)\n if wire_name:\n schema.SetTemplateValue('wireName', wire_name)\n discriminant = variant['discriminant']\n for variant_entry in variant['map']:\n discriminant_value = variant_entry['type_value']\n variant_schema = api.DataTypeFromJson(variant_entry, name, parent=parent)\n variants[discriminant_value] = variant_schema\n api.SetVariantInfo(variant_entry.get('$ref'), discriminant, discriminant_value, schema)\n\n prop = Property(api, schema, discriminant, {'type': 'string'}, key_for_variants=variants)\n schema.SetTemplateValue('is_variant_base', True)\n schema.SetTemplateValue('discriminant', prop)\n schema.SetTemplateValue('properties', [prop])\n return schema\n\n @classmethod\n def _CreateMapType(cls, additional_props, api, name, wire_name, class_name, parent):\n _LOGGER.debug('Have only additionalProps for %s, dict=%s', name, additional_props)\n if additional_props.get('type') == 'array':\n name = '%sItem' % name\n subtype_name = additional_props.get('id', name + 'Element')\n _LOGGER.debug('name:%s, wire_name:%s, subtype name %s', name, wire_name, subtype_name)\n if parent and wire_name:\n base_wire_name = wire_name + 'Element'\n else:\n base_wire_name = None\n base_type = api.DataTypeFromJson(additional_props, subtype_name, parent=parent, wire_name=base_wire_name)\n map_type = data_types.MapDataType(name, base_type, parent=parent, wire_name=wire_name)\n map_type.SetTemplateValue('className', class_name)\n _LOGGER.debug(' %s is MapOf', class_name, base_type.class_name)\n return map_type\n\n @classmethod\n def _CreateSchemaWithoutProperties(cls, api, name, def_dict, wire_name, parent):\n if parent:\n try:\n pname = parent['id']\n except KeyError:\n pname = ''\n\n name_to_log = '%s.%s' % (pname, name)\n else:\n name_to_log = name\n logging.warning('object without properties %s: %s', name_to_log, def_dict)\n schema = cls(api, name, def_dict, parent=parent)\n if wire_name:\n schema.SetTemplateValue('wireName', wire_name)\n return schema\n\n @classmethod\n def _CreateArrayType(cls, api, def_dict, wire_name, class_name, schema_id, parent):\n items = def_dict.get('items')\n if not items:\n raise ApiException('array without items in: %s' % def_dict)\n tentative_class_name = class_name\n if schema_id:\n _LOGGER.debug('Top level schema %s is an array', class_name)\n tentative_class_name += 'Items'\n base_type = api.DataTypeFromJson(items, tentative_class_name, parent=parent, wire_name=wire_name)\n _LOGGER.debug(' %s is ArrayOf<%s>', class_name, base_type.class_name)\n array_type = data_types.ArrayDataType(tentative_class_name, base_type, wire_name=wire_name, parent=parent)\n if schema_id:\n array_type.SetTemplateValue('className', schema_id)\n return array_type\n\n @property\n def class_name(self):\n return self.values['className']\n\n @property\n def anonymous(self):\n return 'id' not in self.raw\n\n @property\n def properties(self):\n return self.values['properties']\n\n @property\n def isContainerWrapper(self):\n \"\"\"Is this schema just a simple wrapper around another container.\n\n A schema is just a wrapper for another datatype if it is an object that\n contains just a single container datatype and (optionally) a kind and\n etag field. This may be used by language generators to create iterators\n directly on the schema. E.g. You could have\n SeriesList ret = api.GetSomeSeriesMethod(args).Execute();\n for (series in ret) { ... }\n rather than\n for (series in ret->items) { ... }\n\n Returns:\n None or ContainerDataType\n \"\"\"\n return self._GetPropertyWhichWeWrap() is not None\n\n @property\n def containerProperty(self):\n \"\"\"If isContainerWrapper, returns the propery which holds the container.\"\"\"\n return self._GetPropertyWhichWeWrap()\n\n def _GetPropertyWhichWeWrap(self):\n \"\"\"Returns the property which is the type we are wrapping.\"\"\"\n container_property = None\n for p in self.values['properties']:\n if p.values['wireName'] == 'kind' or p.values['wireName'] == 'etag':\n continue\n if p.data_type.GetTemplateValue('isContainer'):\n if container_property:\n return\n container_property = p\n else:\n return\n\n return container_property\n\n def __str__(self):\n return '<%s Schema {%s}>' % (self.values['wireName'], self.values)\n\n\nclass Property(template_objects.CodeObject):\n \"\"\"The definition of a schema property.\n\n Example property in the discovery schema:\n \"id\": {\"type\": \"string\"}\n \"\"\"\n\n def __init__(self, api, schema, name, def_dict, key_for_variants=None):\n \"\"\"Construct a Property.\n\n A Property requires several elements in its template value dictionary which\n are set here:\n wireName: the string which labels this Property in the JSON serialization.\n dataType: the DataType of this property.\n\n Args:\n api: (Api) The Api which owns this Property\n schema: (Schema) the schema this Property is part of\n name: (string) the name for this Property\n def_dict: (dict) the JSON schema dictionary\n key_for_variants: (dict) if given, maps discriminator values to\n variant schemas.\n\n Raises:\n ApiException: If we have an array type without object definitions.\n \"\"\"\n super(Property, self).__init__(def_dict, api, wire_name=name)\n self.ValidateName(name)\n self.schema = schema\n self._key_for_variants = key_for_variants\n try:\n if self.values['wireName'] == 'items' and self.values['type'] == 'array':\n self.schema.values['isList'] = True\n except KeyError:\n pass\n\n tentative_class_name = api.NestedClassNameForProperty(name, schema)\n self._data_type = api.DataTypeFromJson(def_dict, tentative_class_name, parent=schema, wire_name=name)\n\n @property\n def code_type(self):\n if self._language_model:\n self._data_type.SetLanguageModel(self._language_model)\n return self._data_type.code_type\n\n @property\n def safe_code_type(self):\n if self._language_model:\n self._data_type.SetLanguageModel(self._language_model)\n return self._data_type.safe_code_type\n\n @property\n def primitive_data_type(self):\n if self._language_model:\n self._data_type.SetLanguageModel(self._language_model)\n return self._data_type.primitive_data_type\n\n @property\n def data_type(self):\n return self._data_type\n\n @property\n def member_name_is_json_name(self):\n return self.memberName == self.values['wireName']\n\n @property\n def is_variant_key(self):\n return self._key_for_variants\n\n @property\n def variant_map(self):\n return self._key_for_variants","sub_path":"pycfiles/google_apis_client_generator-1.7.0-py2-none-any/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":13458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"30805554","text":"import glob\nimport pandas\n\ndef calc_goals_conceded_per_game(row):\n val = 0\n if row['minutes'] > 0:\n val = row['goals_conceded'] / (row['minutes'] / 90)\n return val\n\n\ndef calc_saves_per_game(row):\n val = 0\n if row['minutes'] > 0:\n val = row['saves'] / (row['minutes'] / 90)\n return val\n\n\ndef calc_in_game_stats(row):\n if row['position'] == 'Goalkeeper':\n val = row['clean_sheets']*4 + row['saves_per_game']/3 - row['goals_conceded_per_game']/2 + row['penalties_saved']*2\n elif row['position'] == 'Defender':\n val = row['clean_sheets']*4 - row['own_goals'] - row['goals_conceded_per_game']/2\n elif row['position'] == 'Midfielder':\n val = row['goals_scored']*5 + row['assists']*3 - row['penalties_missed']\n elif row['position'] == 'Forward':\n val = row['goals_scored']*4 + row['assists']*3 - row['penalties_missed']\n return val\n\n\ndef calc_basic_stats(row):\n if row['minutes'] == 0:\n val = 0\n else:\n val = (row['total_points'] + row['bonus']) / (row['minutes'] / 90) + row['points_per_game'] + row['dreamteam_count']\n return round(val, 2)\n\n\ndef calc_popularity(row):\n val = (row['transfers_balance'] + row['transfers_balance_event'] + row['selected_by_percent'] * 50000)\n return round(val, 2)\n\n\ndef map_position(row):\n if row['element_type'] == 1:\n val = 'Goalkeeper'\n elif row['element_type'] == 2:\n val = 'Defender'\n elif row['element_type'] == 3:\n val = 'Midfielder'\n else:\n val = 'Forward'\n return val\n\n\ndef map_status(row):\n if row['status'] == 'a':\n val = 'Avaliable'\n elif row['status'] == 'd':\n val = 'Questionable'\n elif row['status'] == 'i':\n val = 'Injured'\n elif row['status'] == 's':\n val = 'Suspended'\n else:\n val = 'Unknown'\n return val\n\n\ndef map_team(row):\n if row['team_code'] == 3:\n val = 'Arsenal'\n elif row['team_code'] == 91:\n val = 'Bournemouth'\n elif row['team_code'] == 36:\n val = 'Brighton'\n elif row['team_code'] == 90:\n val = 'Burnley'\n elif row['team_code'] == 97:\n val = 'Cardiff'\n elif row['team_code'] == 8:\n val = 'Chelsea'\n elif row['team_code'] == 31:\n val = 'Crystal Palace'\n elif row['team_code'] == 11:\n val = 'Everton'\n elif row['team_code'] == 54:\n val = 'Fulham'\n elif row['team_code'] == 38:\n val = 'Huddersfield'\n elif row['team_code'] == 13:\n val = 'Leicester'\n elif row['team_code'] == 14:\n val = 'Liverpool'\n elif row['team_code'] == 43:\n val = 'Man City'\n elif row['team_code'] == 1:\n val = 'Man Utd'\n elif row['team_code'] == 4:\n val = 'Newcastle'\n elif row['team_code'] == 20:\n val = 'Southampton'\n elif row['team_code'] == 6:\n val = 'Spurs'\n elif row['team_code'] == 57:\n val = 'Watford'\n elif row['team_code'] == 21:\n val = 'West Ham'\n elif row['team_code'] == 39:\n val = 'Wolves'\n else:\n val = 'Unknown'\n return val\n\n\ndef map_code_to_str(row):\n return str(row['code'])\n\n\ndef map_id_to_str(row):\n return str(row['id'])\n\n\ndef get_player_data(base_path, player, season=\"2018-19\", range_start=1, range_end=-1):\n pl_path = base_path + \"data/\" + season + \"/players/\" + player + \"/gw.csv\"\n df = pandas.read_csv(open(pl_path, 'r'))\n x = [x * 1 for x in range(1, len(df) + 1)]\n df['gw'] = x\n if range_end == -1:\n range_end = len(df['gw'])\n\n df = df[range_start - 1:range_end]\n return df\n\n\ndef get_cumulative_data(base_path, season=\"2018-19\"):\n # all data csv path\n all_path = base_path + \"data/\" + season + \"/players_raw.csv\"\n\n # Get all players\n alldf = pandas.read_csv(all_path)\n alldf[\"code2\"] = alldf.apply(map_code_to_str, axis=1)\n alldf[\"id2\"] = alldf.apply(map_id_to_str, axis=1)\n alldf[\"lower_name\"] = alldf[\"first_name\"].str.lower() + \" \" + alldf[\"second_name\"].str.lower()\n alldf[\"full_name\"] = alldf[\"first_name\"] + \" \" + alldf[\"second_name\"]\n alldf[\"full_name_underscore\"] = alldf[\"first_name\"] + \"_\" + alldf[\"second_name\"]\n alldf[\"full_name_code\"] = alldf[\"first_name\"] + \" \" + alldf[\"second_name\"] + \"_\" + alldf[\"code2\"]\n alldf[\"full_name_id\"] = alldf[\"first_name\"] + \"_\" + alldf[\"second_name\"] + \"_\" + alldf[\"id2\"]\n alldf[\"price\"] = alldf[\"now_cost\"] / 10\n alldf[\"position\"] = alldf.apply(map_position, axis=1)\n alldf[\"avail_status\"] = alldf.apply(map_status, axis=1)\n alldf[\"team_name\"] = alldf.apply(map_team, axis=1)\n alldf['basic_stats'] = alldf.apply(calc_basic_stats, axis=1)\n alldf['quality'] = alldf['ict_index'] + alldf['form']\n\n alldf['goals_conceded_per_game'] = alldf.apply(calc_goals_conceded_per_game, axis=1)\n alldf['saves_per_game'] = alldf.apply(calc_saves_per_game, axis=1)\n alldf['in_game_stats'] = alldf.apply(calc_in_game_stats, axis=1)\n\n alldf['transfers_balance'] = alldf['transfers_in'] - alldf['transfers_out']\n alldf['transfers_balance_event'] = alldf['transfers_in_event'] - alldf['transfers_out_event']\n alldf['popularity'] = alldf.apply(calc_popularity, axis=1)\n\n return alldf\n\n\ndef get_gameweek_data(base_path, season, curr_gw):\n df1 = pandas.DataFrame()\n for f in glob.glob(base_path + 'data/'+season+'/gws/*'):\n gw = int(f[-5:-4])\n df_tmp = pandas.read_csv(f, encoding='latin_1')\n df_tmp['name'] = df_tmp['name'].str.replace('_', ' ')\n df_tmp['gw'] = gw\n df_tmp['bonus_weighted'] = df_tmp['bonus']/(curr_gw + 1 - gw)\n df_tmp['bps_weighted'] = df_tmp['bps']/(curr_gw + 1 - gw)\n df_tmp['total_points_weighted'] = df_tmp['total_points']/(curr_gw + 1 - gw)\n df_tmp['gw'] = df_tmp['gw']/(curr_gw + 1 - gw)\n df1 = df1.append(df_tmp)\n return df1\n\n\ndef get_raw_data(base_path, season):\n df1 = pandas.read_csv(base_path + 'data/' + season + '/players_raw.csv', encoding='utf8')\n df1['name'] = df1['first_name'] + ' ' + df1['second_name']\n df1[\"position\"] = df1.apply(map_position, axis=1)\n df1 = df1.sort_values(['name'], ascending=True)\n return df1\n\n\ndef calc_vpc(base_path, season, currgw):\n # cleaned data - df1\n df1 = get_raw_data(base_path, season)\n df1['value'] = df1['now_cost']/10\n df1['id_str'] = df1.apply(map_id_to_str, axis=1)\n df1['display_name'] = df1['name']\n df1['name'] = df1['name'] + ' ' + df1['id_str']\n df1 = df1[['value', 'name', 'position', 'display_name']]\n\n # data by gws for each player\n df2 = get_gameweek_data(base_path, season, currgw)\n df2 = df2[['name', 'bonus', 'bonus_weighted', 'bps', 'bps_weighted', 'total_points', 'total_points_weighted']]\n\n # df2.to_csv('in.csv', sep='\\t')\n # group by player and calculate ratio\n df2 = df2.groupby(['name']).mean()\n\n # merge\n df = pandas.merge(df1, df2, on='name', how='outer')\n df['vpc_ratio'] = df['total_points'] / df['value']\n df['vpc_ratio_weighted'] = df['total_points_weighted'] / df['value']\n\n return df\n","sub_path":"bokeh/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"203768949","text":"\nimport inspect\n\nimport datatypes\n\nfrom ..attribute import Attribute\n\n__all__ = ['dataclass']\n\n\nclass DefaultMethods:\n def __init__(cls, parameters):\n # attributes starting with an underscore are private and don't get\n # a constructor parameter, so we need to filter those out\n params = []\n private_attrs = []\n for param in parameters:\n if not param.name.startswith('_'):\n params.append(param)\n continue\n\n default_value = param.default\n if default_value is inspect.Parameter.empty:\n raise TypeError(\"private attribute {!r} must have a default value\".format(param.name))\n\n private_attrs.append(param)\n\n signature = inspect.Signature(params)\n\n def make_default_value(param):\n value_type = datatypes.python_type(param.annotation)\n if param.default is None:\n return param.default\n else:\n return value_type(param.default)\n\n def __init__(self, *args, **kwargs):\n bound_args = signature.bind(*args, **kwargs)\n\n # we don't want mutable defaults to be shared, so we'll make\n # copies of the default value for the missing arguments\n kwargs_with_defaults = {}\n for param_name, param in signature.parameters.items():\n if param_name in bound_args.arguments:\n value = bound_args.arguments[param_name]\n else:\n value = make_default_value(param)\n\n kwargs_with_defaults[param_name] = value\n\n for param in private_attrs:\n value = make_default_value(param)\n kwargs_with_defaults[param.name] = value\n\n super(cls, self).__init__()\n\n for arg_name, value in kwargs_with_defaults.items():\n setattr(self, arg_name, value)\n\n __init__.__signature__ = signature\n return __init__\n\n def __eq__(cls, parameters):\n def __eq__(self, other):\n if not isinstance(other, cls):\n return NotImplemented\n\n return vars(self) == vars(other)\n\n return __eq__\n\n def __repr__(cls, parameters):\n def __repr__(self):\n attr_names = [param.name for param in parameters]\n attr_values = [getattr(self, attr) for attr in attr_names]\n\n values = ', '.join('{}={}'.format(name, value) for name, value in zip(attr_names, attr_values))\n return '{}({})'.format(cls.__name__, values)\n\n return __repr__\n\n\n\ndef dataclass(cls=None):\n def deco(cls):\n try:\n annotations = cls.__annotations__\n except AttributeError:\n return cls\n\n parameters = []\n\n # create the attributes\n for attr_name, attr_type in annotations.items():\n default_value = getattr(cls, attr_name, inspect.Parameter.empty)\n # if issubclass(attr_type, units.Unit) and not isinstance(default_value, attr_type):\n # default_value = attr_type(default_value)\n\n parameter = inspect.Parameter(attr_name, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=default_value, annotation=attr_type)\n parameters.append(parameter)\n\n attr = Attribute.create_rw(attr_name, type=attr_type)\n setattr(cls, attr_name, attr)\n\n # create the default methods\n for name, method_factory in vars(DefaultMethods).items():\n if not callable(method_factory):\n continue\n\n if name in vars(cls):\n continue\n\n method = method_factory(cls, parameters)\n method.__qualname__ = '{}.{}'.format(cls.__qualname__, name)\n setattr(cls, name, method)\n\n return cls\n\n if cls is None:\n return deco\n else:\n return deco(cls)","sub_path":"applib/utils/dataclass.py","file_name":"dataclass.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"274906157","text":"'''\nFor example, if we wanted to resize an image and save the new image with a new name,\nwe could do it with:\n'''\nfrom PIL import Image\nim = Image(\"example.jpg\")\nnew_im = im.resize((640,480))\nnew_im.save(\"example_resized.jpg\")\n\n'''\nif we want to rotate an image, we can use code like this:\n'''\n\nfrom PIL import Image\nim = Image(\"example.jpg\")\nnew_im = im.rotate(90)\nnew_im.save(\"example_rotated.jpg\")\n\n'''\nThis method also returns a new image that we can then use to create the new rotated file. \nBecause the methods return a new object, we can even combine these operations into \njust one line that rotates, resizes, and saves:\n'''\n\nfrom PIL import Image\nim = Image(\"example.jpg\")\nim.rotate(180).resize((640,480)).save(\"flipped_and_resized.jpg\")\n\n# Note: to save a file in specific directory and JPEG format\nimg.save('/absolute/path/to/myphoto.jpg', 'JPEG')\n'''\nFor More Information Use Below\n\nhttps://pillow.readthedocs.io/en/stable/handbook/tutorial.html\n'''\n\n\n'''\nList all files in a directory using scandir()\nAn easier way to list files in a directory is to use os.scandir() or pathlib.Path():\n'''\n\nimport os\n\nbasepath = 'my_directory/'\nwith os.scandir(basepath) as entries:\n for entry in entries:\n if entry.is_file():\n print(entry.name)\n\n# The modified version looks like this: using generator expression\n\nfrom pathlib import Path\n\n# List all files in directory using pathlib\nbasepath = Path('my_directory/')\nfiles_in_basepath = (entry for entry in basepath.iterdir() if entry.is_file())\nfor item in files_in_basepath:\n print(item.name)\n\n# glob makes it easy to search for files recursively in subdirectories too:\n\nimport glob\nfor file in glob.iglob('**/*.py', recursive=True):\n print(file)\n\n# Simple Filename Pattern Matching Using fnmatch\nimport os\nimport fnmatch\n\nfor file_name in os.listdir('some_directory/'):\n if fnmatch.fnmatch(file_name, '*.txt'):\n print(file_name)\n","sub_path":"part6_week1/image_resize_sample.py","file_name":"image_resize_sample.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"478719336","text":"# -*- coding: utf-8 -*-\n#\n# This source file is part of the FabSim software toolkit,\n# which is 151distributed under the BSD 3-Clause license.\n# Please refer to LICENSE for detailed information regarding the licensing.\n#\n# This file contains FabSim definitions specific to fabFlee.\n\nfrom base.fab import *\n\n# Import V&V primitives.\nimport VVP.vvp as vvp\nimport glob\nimport csv\n\n# Add local script, blackbox and template path.\nadd_local_paths(\"FabFlee\")\n\n# import conflicts\n\n@task \ndef get_flee_location():\n \"\"\"\n Print the $flee_location env variable for the target machine.\n \"\"\"\n update_environment()\n print(env.machine_name, env.flee_location)\n\n@task \ndef sync_flee():\n \"\"\"\n Synchronize the Flee version, so that the remote machine has the latest \n version from localhost.\n \"\"\"\n update_environment()\n flee_location_local = user_config[\"localhost\"].get(\"flee_location\", user_config[\"default\"].get(\"flee_location\"))\n\n rsync_project(\n local_dir=flee_location_local + '/',\n remote_dir=env.flee_location\n ) \n\n@task\ndef extract_conflict_file(config, simulation_period, **args):\n \"\"\"\n Travels to the input_csv directory of a specific config and extracts\n a conflict progression CSV file from locations.csv.\n \"\"\"\n config_dir = \"%s/config_files/%s\" % (get_plugin_path(\"FabFlee\"), config)\n local(\"python3 %s/scripts/location2conflict.py %s \\\n %s/input_csv/locations.csv %s/input_csv/conflicts.csv\"\n % (get_plugin_path(\"FabFlee\"),\n simulation_period,\n config_dir,\n config_dir))\n\n\n@task\ndef flare_local(config, simulation_period, out_dir=\"\"):\n \"\"\"\n Run an instance of Flare on the local host.\n \"\"\"\n\n if len(out_dir) == 0:\n out_dir = \"%s_single\" % (config)\n\n flare_out_dir = \"%s/results-flare/%s\" % (\n get_plugin_path(\"FabFlee\"), out_dir)\n config_dir = \"%s/config_files/%s\" % (get_plugin_path(\"FabFlee\"), config)\n\n local(\"mkdir -p %s/input_csv\" % flare_out_dir)\n local(\"python3 %s/scripts/run_flare.py %s %s/input_csv %s/input_csv/conflicts.csv\" % (get_plugin_path(\"FabFlee\"), simulation_period, config_dir, flare_out_dir))\n\n\n@task\ndef flare_ensemble(config, simulation_period, N, out_dir):\n \"\"\"\n Run an ensemble of flare instances locally.\n config: configuration directory.\n simulation_period: simulation period in days.\n N: number of instances in ensemble.\n out_dir: base output subdirectory in flare-results.\n \"\"\"\n for i in range(0, int(N)):\n instance_out_dir = \"%s/%s\" % (out_dir, i)\n flare_local(config, simulation_period, instance_out_dir)\n\n\n@task\ndef couple_flare_to_flee(config, flare_out=\"flare-out-scratch\"):\n \"\"\"\n Converts Flare output and places it in a Flee input directory to create\n a configuration for an ensemble run.\n \"\"\"\n with_config(config)\n config_dir = env.job_config_path_local \n local(\"rm -rf %s/SWEEP\" % (config_dir))\n local(\"mkdir -p %s/SWEEP\" % (config_dir))\n local(\"cp -r %s/results-flare/%s/* %s/SWEEP/\"\n % (get_plugin_path(\"FabFlee\"), flare_out, config_dir))\n\n\n@task\ndef flee_conflict_forecast(config, simulation_period, N, **args):\n \"\"\"\n Run Flare ensemble, convert output to Flee ensemble input,\n run Flee ensemble.\n (visualize Flee output with uncertainty).\n \"\"\"\n update_environment(args)\n\n local(\"rm -rf %s/results-flare/flare-out-scratch/*\" %\n (get_plugin_path(\"FabFlee\")))\n flare_ensemble(config, simulation_period, N, \"flare-out-scratch\")\n\n couple_flare_to_flee(config, flare_out=\"flare-out-scratch\")\n\n # config_dir = \"%s/config_files/%s\" % (get_plugin_path(\"FabFlee\"), config)\n # local(\"mkdir -p %s/SWEEP\" % (config_dir))\n # local(\"cp -r %s/results-flare/flare-out-scratch/* %s/SWEEP/\"\n # % (get_plugin_path(\"FabFlee\"), config_dir))\n\n flee_ensemble(config, simulation_period, **args)\n\n\n@task\ndef flee(config, simulation_period, **args):\n \"\"\" Submit a Flee job to the remote queue.\n The job results will be stored with a name pattern as\n defined in the environment,\n e.g. car-abcd1234-localhost-4\n config :\n config directory to use for the simulation script, e.g. config=car2014\n simulation_period : length of the simulation in days.\n Keyword arguments:\n cores : number of compute cores to request\n wall_time : wall-time job limit\n memory : memory per node\n \"\"\"\n\n '''\n update_environment({\"input_directory\": \"%s/config_files/%s/input_csv\"\n % (get_plugin_path(\"FabFlee\"), config),\n \"validation_data_directory\":\n \"%s/config_files/%s/source_data\"\n % (get_plugin_path(\"FabFlee\"), config)})\n print_local_environment()\n '''\n\n update_environment(args, {\"simulation_period\": simulation_period})\n with_config(config)\n execute(put_configs, config)\n job(dict(script='flee', wall_time='0:15:0', memory='2G'), args)\n\n\n@task\ndef flee_and_plot(config, simulation_period, **args):\n \"\"\"\n Runs Flee and plots the output in a graph subdir\n \"\"\"\n update_environment(args, {\"simulation_period\": simulation_period})\n env.simulation_settings = \"simsetting.csv\"\n flee(config, simulation_period, **args)\n plot_output(\"%s\" % (env.job_name), \"graph\")\n\n\n@task\ndef pflee(config, simulation_period, **args):\n \"\"\" Submit a Pflee job to the remote queue.\n The job results will be stored with a name pattern as defined\n in the environment, e.g. car-abcd1234-localhost-4\n config :\n config directory to use for the simulation script, e.g. config=car2014\n Keyword arguments:\n cores : number of compute cores to request\n wall_time : wall-time job limit\n memory : memory per node\n \"\"\"\n '''\n update_environment({\"input_directory\": \"%s/config_files/%s/input_csv\"\n % (get_plugin_path(\"FabFlee\"), config),\n \"validation_data_directory\":\n \"%s/config_files/%s/source_data\"\n % (get_plugin_path(\"FabFlee\"), config)})\n print_local_environment()\n '''\n update_environment(args, {\"simulation_period\": simulation_period})\n with_config(config)\n execute(put_configs, config)\n job(dict(script='pflee', wall_time='0:15:0', memory='2G'), args)\n\n\n@task \ndef pflee_test(config, pmode=\"advanced\", N=\"100000\", **args):\n \"\"\"\n Run a short parallel test with a particular config.\n \"\"\"\n update_environment(args, {\"simulation_period\": 10, \"flee_parallel_mode\": pmode, \"flee_num_agents\": int(N)})\n with_config(config)\n execute(put_configs, config)\n job(dict(script='pflee_test', wall_time='0:15:0', memory='2G'), args)\n\n\n@task \ndef pflee_pmode_compare(config, cores, N=\"100000\", **args):\n \"\"\"\n Run a short parallel test with a particular config. 60 min limit per run.\n \"\"\"\n for pmode in [\"advanced\",\"classic\",\"adv-lolat\",\"cl-hilat\"]: # maps to args in test_par.py\n update_environment(args, {\"simulation_period\": 10, \"flee_parallel_mode\": pmode, \"flee_num_agents\": int(N)})\n with_config(config)\n execute(put_configs, config)\n job(dict(script='pflee_test', wall_time='1:00:0', memory='2G', cores=cores, label=pmode), args)\n\n\n@task\ndef pflee_report(results_key):\n for item in glob.glob(\"{}/*{}*/perf.log\".format(env.local_results,results_key)):\n print(item)\n with open(item) as csvfile:\n perf = csv.reader(csvfile)\n for k,e in enumerate(perf):\n if k == 1:\n print(float(e[1]))\n\n #local(\"grep main {}/{}/perf.log\".format(env.local_results,results_key))\n\n\n@task\ndef food_flee(config, simulation_period, **args):\n \"\"\" Submit a Flee job to the remote queue.\n The job results will be stored with a name pattern as defined\n in the environment, e.g. car-abcd1234-localhost-4\n config :\n config directory to use for the simulation script, e.g. config=car2014\n Keyword arguments:\n cores : number of compute cores to request\n wall_time : wall-time job limit\n memory : memory per node\n \"\"\"\n update_environment({\"input_directory\": \"%s/config_files/%s/input_csv\"\n % (get_plugin_path(\"FabFlee\"), config),\n \"validation_data_directory\":\n \"%s/config_files/%s/source_data\"\n % (get_plugin_path(\"FabFlee\"), config)})\n # print_local_environment()\n update_environment(args, {\"simulation_period\": simulation_period})\n with_config(config)\n execute(put_configs, config)\n job(dict(script='flee_food', wall_time='0:15:0', memory='2G'), args)\n\n\n@task\ndef flees(config, simulation_period, **args):\n # Save relevant arguments to a Python or numpy list.\n print(args)\n\n # Generate config directories, copying from the config provided,\n # and adding a different generated test.csv in each directory.\n # Run the flee() a number of times.\n\n\n@task\ndef flee_ensemble(config, simulation_period, script='flee', label=\"\", **args):\n \"\"\"\n Submits an ensemble of dummy jobs.\n One job is run for each file in /flee_test/SWEEP.\n \"\"\"\n update_environment(args)\n\n path_to_config = find_config_file_path(config)\n print(\"local config file path at: %s\" % path_to_config)\n sweep_dir = path_to_config + \"/SWEEP\"\n env.script = script\n env.input_name_in_config = 'flee.txt'\n env.simulation_period = simulation_period\n\n if hasattr(env, 'NoEnvScript'):\n del env['NoEnvScript']\n \n #Re-add support for labels, which are overwritten by runensemble.\n if len(label)>0:\n print(\"adding label: \",label)\n env.job_name_template += \"_{}\".format(label)\n\n if args.get(\"PilotJob\", \"False\") == \"True\":\n \n #specific workaround for Flee on Eagle.\n cmds = [\"pip install --upgrade pip\",\n \"python3 -m pip install numpy\"]\n for cmd in cmds:\n env.run_prefix_commands.append(cmd)\n\n #if len(args.get(\"AwarenessLevel\", \"\")) > 0:\n # cmd = [\"echo \\\"AwarenessLevel,{}\\\" >> simsetting.csv\".format(args.get(\"AwarenessLevel\"))]\n # print(cmd)\n # env.run_prefix_commands = env.run_prefix_commands.append(cmd)\n # print(env.run_prefix_commands)\n\n run_ensemble(config, sweep_dir, **args)\n\n\n@task\ndef pflee_ensemble(config, simulation_period, **args):\n flee_ensemble(config, simulation_period, script='pflee', **args)\n\n\n@task\ndef load_conflict(conflict_name):\n # Syntax: fab localhost load_conflict:conflict_name\n \"\"\"\n Load source data and flee csv files for a specific conflict from\n conflict data to active conflict directory.\n \"\"\"\n # copies *.csv files from $FabFlee/conflict_data/ to\n # $FabFlee/conflict_data/active_conflict.\n\n # 1. Load locations.csv, routes.csv and closures.csv files which\n # correspond to a specific conflict.\n # These CSV will be store in $FabFlee/conflict_data. Each conflict will be\n # stored in a separate folder.\n\n # 2. Move these CSVs to an \"active_conflict\" directory.\n # This is located in $FABSIM/conflict_data/active_conflict.\n local(template(\"mkdir -p %s/conflict_data/active_conflict\"\n % (get_plugin_path(\"FabFlee\"))))\n\n local(template(\"cp %s/conflict_data/%s/*.csv \\\n %s/conflict_data/active_conflict/\")\n % (get_plugin_path(\"FabFlee\"), conflict_name,\n get_plugin_path(\"FabFlee\")))\n\n local(template(\"mkdir -p %s/conflict_data/active_conflict/source_data\"\n % (get_plugin_path(\"FabFlee\"))))\n\n local(template(\"cp %s/conflict_data/%s/source_data/*.csv \\\n %s/conflict_data/active_conflict/source_data/\")\n % (get_plugin_path(\"FabFlee\"), conflict_name,\n get_plugin_path(\"FabFlee\")))\n\n local(template(\"cp %s/config_files/run.py \\\n %s/conflict_data/active_conflict\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\")))\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost load_conflict:%s\\n\" % conflict_name)\n\n\n@task\ndef clear_active_conflict(): # Syntax: fab localhost clear_active_conflict\n \"\"\" Delete all content in the active conflict directory. \"\"\"\n\n local(template(\"rm -rf %s/conflict_data/active_conflict/\"\n % (get_plugin_path(\"FabFlee\"))))\n\n\n@task\n# Syntax: fab localhost\n# change_capacities:camp_name=capacity(,camp_name2=capacity2)\ndef change_capacities(**capacities):\n \"\"\"\n Change the capacity of a set of camps in the active conflict directory.\n \"\"\"\n # Note: **capacities will be a Python dict object.\n\n capacities_string = \"\"\n for c in capacities.keys():\n capacities_string += \"%s=%s\" % (c, capacities[c])\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost change_capacities:%s\\n\"\n % capacities_string)\n\n # 1. Read in locations.csv\n # 2. for each location in the dict, find it in the csv, and modify the\n # population value accordingly.\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n\n for camp_name in capacities.keys():\n for i in range(1, len(lines)):\n if lines[i][5].strip() != \"camp\":\n continue\n if lines[i][0].strip() != camp_name:\n continue\n\n lines[i][7] = capacities[camp_name]\n\n print(lines[i])\n\n # 3. Write the updated CSV file.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n\n@task\ndef find_capacity(csv_name):\n # Syntax: fab localhost find_capacity:csv_name\n \"\"\"\n Find the highest refugee number within csv file of source data\n for neighbouring camps.\n \"\"\"\n\n import csv\n csv_file = open(\"%s/conflict_data/active_conflict/source_data/%s\"\n % (get_plugin_path(\"FabFlee\"), csv_name)).readlines()\n print(max(((i, int(l.split(',')[1])) for i, l in enumerate(\n csv_file)), key=lambda t: t[1])[1])\n\n\n@task\n# Syntax: fab localhost add_camp:camp_name,region,country(,lat,lon)\ndef add_camp(camp_name, region=\" \", country=\" \", lat=0.0, lon=0.0):\n \"\"\" Add an additional new camp to locations.csv. \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost add_camp:%s\\n\" % camp_name)\n\n # 1. Add (or make existing forwarding hub) a new camp to locations.csv\n # If new camp, add country,lat,lon,location_type(camp)\n # If existing camp, change location_type to camp\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"r\"))\n lines = [l for l in r]\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != camp_name:\n continue\n print(\"Warning: camp %s is already present in locations.csv.\"\n % (camp_name))\n return\n\n # 2. Append one line to lines, containing the details of the new camp.\n add_camp = [camp_name, region, country, lat, lon, \"camp\"]\n with open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as new_csv:\n writer = csv.writer(new_csv)\n writer.writerow(add_camp)\n print(add_camp)\n\n\n@task\ndef add_new_link(name1, name2, distance):\n \"\"\" Add a new link between locations to routes.csv. \"\"\"\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost add_new_link:%s,%s,%s\\n\"\n % (name1, name2, distance))\n\n # 1. Read routes.csv and for each location in the dict, find in the csv,\n # and change distance between two locations.\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != name1:\n continue\n if lines[i][1].strip() != name2:\n continue\n lines[i][2] = distance\n print(lines[i])\n\n # 2. Append one line to lines, containing the details of links.\n add_new_link = [name1, name2, distance]\n with open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as new_csv:\n writer = csv.writer(new_csv)\n writer.writerow(add_new_link)\n print(add_new_link)\n\n\n@task\n# Syntax: fab localhost delete_location:location_name\ndef delete_location(location_name):\n \"\"\" Delete not required camp (or location) from locations.csv. \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost delete_location:%s\\n\" % location_name)\n\n # 1. Delete camp from locations.csv containing the details of the camp.\n # 2. Write the updated CSV file.\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"r\"))\n lines = [l for l in r]\n\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n\n for i in range(0, len(lines)):\n if lines[i][0].strip() != location_name:\n writer.writerow(lines[i])\n continue\n\n print(lines[i])\n\n # 3. Check whether wanted to delete camp is present in locations.csv\n for i in range(1, len(lines)):\n if lines[i][0] == location_name:\n continue\n print(\"Warning: camp %s is deleted from locations.csv.\"\n % (location_name))\n return\n\n\n@task\n# Syntax: fab localhost change_distance:name1,name2,distance\ndef change_distance(source, destination, distance):\n \"\"\" Change distance between two locations in routes.csv. \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost change_distance:%s,%s,%s\\n\"\n % (source, destination, distance))\n\n # 1. Read routes.csv and for each location in the dict, find in the csv,\n # and change distance between two locations.\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != source:\n continue\n if lines[i][1].strip() != destination:\n continue\n lines[i][2] = distance\n print(lines[i])\n\n # 2. Write the updated closures.csv in the active_conflict directory.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n\n@task\n# Syntax: fab localhost\n# close_camp:camp_name,country(,closure_start,closure_end)\ndef close_camp(camp_name, country, closure_start=0, closure_end=-1):\n \"\"\" Close camp located within neighbouring country. \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost close_camp:%s,%s\\n\" % (camp_name, country))\n\n # 1. Change closure_start and closure_end or add a new\n # camp closure to closures.csv.\n # Format: closure type ,name1,name2,closure_start,closure_end\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/closures.csv\"\n % (get_plugin_path(\"FabFlee\")))) # Here your csv file\n lines = [l for l in r]\n camp_found = False\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != \"location\":\n continue\n if lines[i][1].strip() != camp_name:\n continue\n if lines[i][2].strip() != country:\n continue\n lines[i][3] = closure_start\n lines[i][4] = closure_end\n camp_found = True\n print(lines[i])\n\n if not camp_found:\n lines.append([\"location\", camp_name, country,\n closure_start, closure_end])\n # print(lines)\n\n # 2. Write the updated closures.csv in the active_conflict directory.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/closures.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n\n@task\n# Syntax: fab localhost\n# close_border:country1,country2(,closure_start,closure_end)\ndef close_border(country1, country2, closure_start=0, closure_end=-1):\n \"\"\"\n Close border between conflict country and camps located\n within specific neighbouring country.\n \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost close_border:%s,%s\\n\"\n % (country1, country2))\n\n # 1. Change closure_start and closure_end or add a new camp\n # closure to closures.csv.\n # Format: closure type ,name1,name2,closure_start,closure_end\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/closures.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n border_found = False\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != \"country\":\n continue\n if lines[i][1].strip() != country1:\n continue\n if lines[i][2].strip() != country2:\n continue\n lines[i][3] = closure_start\n lines[i][4] = closure_end\n border_found = True\n print(lines[i])\n\n if not border_found:\n lines.append([\"country\", country1, country2,\n closure_start, closure_end])\n\n '''\n local(template(\"cp %s/conflict_data/%s/*.csv \\\n %s/conflict_data/active_conflict/\")\n % (get_plugin_path(\"FabFlee\"), conflict_name,\n get_plugin_path(\"FabFlee\")))\n print(lines)\n '''\n\n # 2. Write the updated closures.csv in the active_conflict directory.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/closures.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n\n@task\ndef redirect(source, destination):\n # Syntax: fab localhost redirect:location_name1,location_name2\n \"\"\"\n Redirect from town or (small/other)camp to (main)camp.\n \"\"\"\n\n with open(\"%s/conflict_data/active_conflict/commands.log.txt\"\n % (get_plugin_path(\"FabFlee\")), \"a\") as myfile:\n myfile.write(\"fab localhost redirect:%s,%s\\n\" % (source, destination))\n\n # 1. Read locations.csv and for each location in the dict, find in the csv,\n # and redirect refugees from location in neighbouring country to camp.\n # 2. Change location_type of source location to forwarding_hub.\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != source:\n continue\n lines[i][5] = \"forwarding_hub\"\n\n print(lines[i])\n\n # 3. Write the updated CSV file.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/locations.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n # 4. Find the route from source to destination in routes.csv, and enable\n # forced_redirection.\n r = csv.reader(open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\"))))\n lines = [l for l in r]\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != source:\n continue\n if lines[i][1].strip() != destination:\n continue\n lines[i][3] = \"2\"\n print(lines[i])\n\n for i in range(1, len(lines)):\n if lines[i][0].strip() != destination:\n continue\n if lines[i][1].strip() != source:\n continue\n lines[i][3] = \"1\"\n print(lines[i])\n\n # 5. Write the updated CSV file.\n writer = csv.writer(open(\"%s/conflict_data/active_conflict/routes.csv\"\n % (get_plugin_path(\"FabFlee\")), \"w\"))\n writer.writerows(lines)\n\n\n@task\ndef instantiate(conflict_name):\n # Syntax: fab localhost instantiate:conflict_name\n \"\"\"\n Copy modified active conflict directory to config_files\n (i.e. flee_conflict_name) to run instance with Flee.\n \"\"\"\n\n # 1. Copy modified active_conflict directory to instantiate runs with\n # specific conflict name\n local(template(\"mkdir -p %s/config_files/%s\"\n % (get_plugin_path(\"FabFlee\"), conflict_name)))\n\n local(template(\"mkdir -p %s/config_files/%s/input_csv\"\n % (get_plugin_path(\"FabFlee\"), conflict_name)))\n\n local(template(\"cp %s/conflict_data/active_conflict/*.csv \\\n %s/config_files/%s/input_csv\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n\n local(template(\"cp %s/conflict_data/active_conflict/commands.log.txt \\\n %s/config_files/%s/\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n\n local(template(\"mkdir -p %s/config_files/%s/source_data\"\n % (get_plugin_path(\"FabFlee\"), conflict_name)))\n\n local(template(\"cp %s/conflict_data/active_conflict/source_data/*.csv \\\n %s/config_files/%s/source_data\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n\n local(template(\"cp %s/conflict_data/active_conflict/run.py \\\n %s/config_files/%s/run.py\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n\n local(template(\"cp %s/config_files/run_food.py \\\n %s/config_files/%s/run_food.py\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n # line added to copy run_food.py as well (otherwise executing\n # food_flee doesn't work...)\n\n # line added to copy simsetting.csv and make sure that\n # flee.SimulationSettings....ReadfromCSV works.\n local(template(\"cp %s/config_files/simsetting.csv \\\n %s/config_files/%s/simsetting.csv\")\n % (get_plugin_path(\"FabFlee\"), get_plugin_path(\"FabFlee\"),\n conflict_name))\n\n\n@task\n# Syntax: fab localhost\n# plot_output:flee_conflict_name_localhost_16(,graphs_dir_name)\ndef plot_output(output_dir=\"\", graphs_dir=\"\"):\n \"\"\" Plot generated output results using plot-flee-output.py. \"\"\"\n local(\"mkdir -p %s/%s/%s\" % (env.local_results, output_dir, graphs_dir))\n local(\"python3 %s/plot-flee-output.py %s/%s %s/%s/%s\"\n % (env.flee_location,\n env.local_results, output_dir,\n env.local_results, output_dir, graphs_dir))\n\n \ndef vvp_validate_results(output_dir=\"\"):\n \"\"\" Extract validation results (no dependencies on FabSim env). \"\"\"\n\n flee_location_local = user_config[\"localhost\"].get(\"flee_location\", user_config[\"default\"].get(\"flee_location\"))\n\n local(\"python3 %s/extract-validation-results.py %s > %s/validation_results.yml\"\n % (flee_location_local, output_dir, output_dir))\n\n with open(\"{}/validation_results.yml\".format(output_dir), 'r') as val_yaml:\n validation_results = yaml.load(val_yaml, Loader=yaml.SafeLoader)\n\n #TODO: make a proper validation metric using a validation schema.\n #print(validation_results[\"totals\"][\"Error (rescaled)\"])\n print(\"Validation {}: {}\".format(output_dir.split(\"/\")[-1], validation_results[\"totals\"][\"Error (rescaled)\"]))\n return validation_results[\"totals\"][\"Error (rescaled)\"]\n\n print(\"error: vvp_validate_results failed on {}\".format(output_dir))\n return -1.0\n\n@task\n# Syntax: fabsim localhost\n# validate_results:flee_conflict_name_localhost_16\ndef validate_results(output_dir):\n score = vvp_validate_results(\"{}/{}\".format(env.local_results, output_dir))\n print(\"Validation {}: {}\".format(output_dir.split[-1]), score)\n return score\n\n\ndef make_vvp_mean(np_array):\n mean_score = np.mean(np_array)\n print(\"Mean score: {}\".format(mean_score))\n return mean_score\n\n@task\ndef validate_flee_output(results_dir):\n \"\"\"\n Goes through all the output directories and calculates the validation \n scores.\n \"\"\"\n vvp.ensemble_vvp(\"{}/{}/RUNS\".format(env.local_results,results_dir), vvp_validate_results, make_vvp_mean)\n\n\n@task\ndef validate_flee(simulation_period=0, cores=4, skip_runs=False, label=\"\", AwarenessLevel=1, **args):\n \"\"\"\n Runs all the validation test and returns all scores, as well as an average.\n \"\"\"\n if len(label)>0:\n print(\"adding label: \",label)\n env.job_name_template += \"_{}\".format(label)\n\n mode=\"serial\"\n if int(cores)>1:\n mode=\"parallel\"\n\n if not skip_runs:\n if mode.lower()==\"parallel\":\n pflee_ensemble(\"validation\", simulation_period, cores=cores, **args)\n else:\n flee_ensemble(\"validation\", simulation_period, cores=1, **args)\n \n #if not run locally, wait for runs to complete\n update_environment()\n if env.host != \"localhost\":\n wait_complete(\"\")\n if skip_runs:\n env.config = \"validation\"\n\n\n fetch_results()\n\n results_dir = template(env.job_name_template)\n validate_flee_output(results_dir)\n\n\n@task\n# Syntax: fab localhost\n# plot_uq_output:flee_conflict_name_localhost_16(,graphs_dir_name)\ndef plot_uq_output(output_dir=\"\", graphs_dir=\"\"):\n \"\"\" Plot generated output results using plot-flee-output.py. \"\"\"\n local(\"mkdir -p %s/%s/%s\" % (env.local_results, output_dir, graphs_dir))\n local(\"python3 %s/plot-flee-uq-output.py %s/%s %s/%s/%s\"\n % (env.flee_location,\n env.local_results, output_dir,\n env.local_results, output_dir, graphs_dir))\n\n\n@task\n# Syntax: fab localhost compare_food:food_flee_conflict_name_localhost_16\ndef compare_food(output_dir_1=\"\"):\n \"\"\"\n Compare results of the food based simulation with the original\n flee results throughout the whole simulation.\n Syntax:\n fab localhost compare_food:food_flee_conflict_name_localhost_16\n **or any name the food directory you want to use has.\n Make sure that the non-food one exists as well.\n \"\"\"\n local(\"mkdir -p %s/%s/comparison\" % (env.results_path, output_dir_1))\n output_dir_2 = output_dir_1.partition(\"_\")[2]\n local(\"python3 %s/compare.py %s/%s %s/%s\"\n % (env.flee_location,\n env.results_path, output_dir_1,\n env.results_path, output_dir_2))\n\n@task\n\n# Syntax: fabsim localhost process_acled:country,start_date=dd-mm-yyyy,filter=[earliest,fatalities]\ndef process_acled(country,start_date,filter,admin_level):\n \"\"\"\n Process .csv files sourced from acleddata.com to a format\n Syntax:\n fabsim localhost process_acled:\n country (e.g ssudan, mali),\n start_date - \"dd-mm-yyyy (date to calculate conflict_date from),\n filter:[earliest,fatalities]\n **earliest keeps the first occurence of each admin2,\n fatalities keeps admin2 with the highest fatalities.\n admin_level: is how high the admin level you want to apply the filter to\n i.e location, admin2, admin1\n \"\"\"\n local(\"python3 %s/scripts/acled2locations.py %s %s %s %s %s\"\n %(get_plugin_path(\"FabFlee\"),\n get_plugin_path(\"FabFlee\"),\n country,\n start_date,\n filter,\n admin_level))\n\n\n@task\ndef test_variability(config, **args):\n \"\"\"\n DEPRECATED: Run a number of replicas for a specific conflict.\n \"\"\"\n print(\"This function is obsolete: please use 'fabsim flee:,replicas=,simulation_period= instead.\")\n\n\n@task\n# Syntax: fab localhost\n# test_variability_food:\n# flee_conflict_name,simulation_period=number,replicas=number\ndef test_variability_food(config, **args):\n \"\"\"\n DEPRECATED: Run a number of replicas for a specific conflict.\n \"\"\"\n print(\"This function is obsolete: please use 'fabsim food_flee:,replicas=,simulation_period= instead.\")\n\n\n@task\n# Syntax: fab localhost\n# test_sensitivity:\n# flee_conflict_name,simulation_period=number,\\\n# name=MaxMoveSpeed,values=50-100-200\ndef test_sensitivity(config, **args):\n \"\"\"\n Run simulation using different speed limits, movechances and\n awareness levels to test sensitivity.\n \"\"\"\n\n # SimSettingsCSVs directory: movechance and attractiveness\n\n import csv\n # 1. Generate simSettingsCSVs for which sensitivity analysis is conducted\n # 1a. extract parameter name\n parameter_name = args[\"name\"]\n\n # 1b. convert value range to python list\n values = args[\"values\"].split('-')\n\n # 2. Create a config directory for each simSettingsCSV (for each value in\n # the list), and place csv in it\n for v in values:\n # instantiate(\"%s_%s_%s\" % (config, args[\"name\"], v))\n local(\"cp -r %s/config_files/%s %s/config_files/%s_%s_%s\"\n % (get_plugin_path(\"FabFlee\"), config,\n get_plugin_path(\"FabFlee\"), config, args[\"name\"], v))\n\n csvfile = open('%s/config_files/%s_%s_%s/simsetting.csv'\n % (get_plugin_path(\"FabFlee\"),\n config, args[\"name\"], v), \"wb\")\n\n writer = csv.writer(csvfile)\n writer.writerow([args[\"name\"], v])\n csvfile.close()\n\n # 3. Run simulation for each config directory that is generated\n instance_config = (\"%s_%s_%s\" % (config, args[\"name\"], v))\n flee(instance_config, **args)\n\n # 4. Analyse output and report sensitivity\n\n\n# Test Functions\n# from plugins.FabFlee.test_FabFlee import *\nfrom plugins.FabFlee.run_simulation_sets import *\ntry:\n from plugins.FabFlee.flee_easyvvuq import *\n from plugins.FabFlee.run_perf_benchmarks import *\nexcept ImportError:\n pass\n","sub_path":"FabFlee.py","file_name":"FabFlee.py","file_ext":"py","file_size_in_byte":34666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369175231","text":"import FWCore.ParameterSet.Config as cms\nimport FWCore.Utilities.FileUtils as FileUtils\n\nprocess = cms.Process(\"VertexProbTrainingTreeMaker\")\n\n# geometry and global tag:\nprocess.load(\"Configuration.StandardSequences.GeometryDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, '94X_mc2017_realistic_v12')\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32( 100 )\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.source = cms.Source (\"PoolSource\",\n fileNames = cms.untracked.vstring(\n'/store/mc/RunIIFall17MiniAOD/VHToGG_M125_13TeV_amcatnloFXFX_madspin_pythia8/MINIAODSIM/94X_mc2017_realistic_v10-v1/00000/A87F7D05-0403-E811-AE12-C0BFC0E567FE.root'\n )\n)\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\"VertexProbTrainingTree.root\")\n)\n\n#Sequence builder\n#**************************************************************\nprocess.load(\"flashggDiphotonVtxPlugins/MVATraining/flashggDiphotonVertexSequence_cff\")\nprocess.flashggDiPhotons.vertexIdMVAweightfile = cms.FileInPath(\"flashggDiphotonVtxPlugins/Validation/data/TMVAClassification_BDTVtxId_SL_2017.xml\")\nprocess.flashggDiPhotons.vertexProbMVAweightfile = cms.FileInPath(\"flashggDiphotonVtxPlugins/Validation/data/TMVAClassification_BDTVtxProb_SL_2017.xml\")\n\nprocess.flashggDiPhotons.nVtxSaveInfo = cms.untracked.uint32(999)\nprocess.flashggDiPhotons.useSingleLeg = cms.bool(True)\nprocess.flashggDiPhotons.sigma1Pix = cms.double( 0.00800379 )\nprocess.flashggDiPhotons.sigma1Tib = cms.double( 0.502127 )\nprocess.flashggDiPhotons.sigma1Tob = cms.double( 5.5138 )\nprocess.flashggDiPhotons.sigma1PixFwd = cms.double( 0.0318172 )\nprocess.flashggDiPhotons.sigma1Tid = cms.double( 0.325117 )\nprocess.flashggDiPhotons.sigma1Tec = cms.double( 1.19907 )\nprocess.flashggDiPhotons.sigma2Pix = cms.double( 0.0171381 )\nprocess.flashggDiPhotons.sigma2Tib = cms.double( 0.282616 )\nprocess.flashggDiPhotons.sigma2Tob = cms.double( 3.5737 )\nprocess.flashggDiPhotons.sigma2PixFwd = cms.double( 0.0923745 )\nprocess.flashggDiPhotons.sigma2Tid = cms.double( 0.355705 )\nprocess.flashggDiPhotons.sigma2Tec = cms.double( 0.863342 )\nprocess.flashggDiPhotons.singlelegsigma1Pix = cms.double( 0.00879849 )\nprocess.flashggDiPhotons.singlelegsigma1Tib = cms.double( 1.37155 )\nprocess.flashggDiPhotons.singlelegsigma1Tob = cms.double( 2.7242 )\nprocess.flashggDiPhotons.singlelegsigma1PixFwd = cms.double( 0.0596455 )\nprocess.flashggDiPhotons.singlelegsigma1Tid = cms.double( 0.479279 )\nprocess.flashggDiPhotons.singlelegsigma1Tec = cms.double( 2.02211 )\nprocess.flashggDiPhotons.singlelegsigma2Pix = cms.double( 0.0224474 )\nprocess.flashggDiPhotons.singlelegsigma2Tib = cms.double( 0.594662 )\nprocess.flashggDiPhotons.singlelegsigma2Tob = cms.double( 0.433137 )\nprocess.flashggDiPhotons.singlelegsigma2PixFwd = cms.double( 0.137922 )\nprocess.flashggDiPhotons.singlelegsigma2Tid = cms.double( 0.421378 )\nprocess.flashggDiPhotons.singlelegsigma2Tec = cms.double( 0.977421 )\n\nprocess.commissioning = cms.EDAnalyzer('VertexProbTrainingTreeMaker',\n DiPhotonTag = cms.InputTag('flashggDiPhotons'),\n VertexTag = cms.InputTag('offlineSlimmedPrimaryVertices'),\n VertexCandidateMapTagDz = cms.InputTag('flashggVertexMapUnique'),\n BeamSpotTag = cms.InputTag('offlineBeamSpot'),\n rhoTag = cms.InputTag('fixedGridRhoFastjetAll'),\n GenParticleTag = cms.InputTag('prunedGenParticles'),\n evWeight = cms.untracked.double(1.0)\n)\n\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import DataFormat,switchOnVIDPhotonIdProducer,setupAllVIDIdsInModule,setupVIDPhotonSelection\ndataFormat = DataFormat.MiniAOD\nswitchOnVIDPhotonIdProducer(process, DataFormat.MiniAOD)\n#my_id_modules = ['RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Spring16_nonTrig_V1_cff']\nmy_id_modules = ['RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Fall17_94X_V1_cff']\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)\nprocess.flashggPhotons.effAreasConfigFile = cms.FileInPath(\"RecoEgamma/PhotonIdentification/data/Fall17/effAreaPhotons_cone03_pfPhotons_90percentBased_TrueVtx.txt\")\nprocess.flashggPhotons.egmMvaValuesMap = cms.InputTag(\"photonMVAValueMapProducer:PhotonMVAEstimatorRunIIFall17v1Values\")\n\nprocess.p = cms.Path(process.flashggDiphotonVertexSequence\n *process.egmPhotonIDSequence\n *process.commissioning\n )\n","sub_path":"MVATraining/test/VertexProbTrainingTreeMaker_cfg.py","file_name":"VertexProbTrainingTreeMaker_cfg.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"307027159","text":"# coding=utf-8\n\"\"\"\n题目:\n输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯:从1开始计数\n\"\"\"\n\n\nclass ListNode(object):\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\ndef find_kth_to_tail(head, k):\n if not head and k == 0:\n return\n fast = head\n slow = head\n for _ in range(k):\n if fast.next:\n fast = fast.next\n else:\n return\n while fast.next:\n fast = fast.next\n slow = slow.next\n return slow\n\n\nif __name__ == '__main__':\n node1 = ListNode(1)\n node1.next = ListNode(2)\n node1.next.next = ListNode(3)\n print (node1, 2)\n","sub_path":"22. 链表中倒数第k个节点.py","file_name":"22. 链表中倒数第k个节点.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"482109085","text":"from PermutationNetwork import PermutationNetwork\nfrom Ant import Ant\nfrom Utility import fitness\n\nclass Problem():\n def __init__(self, colony_size, iterations, size, alpha, beta, rho, q0, pheromone_amount, tau, default_trace):\n self.colony_size = colony_size\n self.iterations = iterations\n self.size = size\n self.alpha = alpha\n self.beta = beta\n self.rho = rho\n self.q0 = q0\n self.pheromone_amount = pheromone_amount\n self.tau = tau\n self.default_trace = default_trace\n self.colony = [Ant(size, alpha, beta, q0, pheromone_amount, tau, PermutationNetwork(size, default_trace)) for _ in range(colony_size)]\n\n def get_old_network(self):\n '''\n The old network is the sum of all personal networks of ants\n '''\n network = PermutationNetwork(self.size, 0)\n for ant in self.colony:\n for node in ant.network.nodes:\n network.add_trace(node.edge1, node.edge2, node.trace)\n return network\n\n def get_updated_network(self):\n old_network = self.get_old_network()\n network = PermutationNetwork(self.size, 0) # create a blank network\n for ant in self.colony:\n for i in range(self.size * 2 - 1):\n trace = ant.network.get_trace(ant.path[i].tolist(), ant.path[i + 1].tolist()).trace # get trace of edge\n trace /= ant.tour_length # divide it by tour length\n network.add_trace(ant.path[i].tolist(), ant.path[i + 1].tolist(), trace)\n for node in network.nodes:\n node.trace += (1 - self.rho) * old_network.get_trace(node.edge1, node.edge2).trace\n return network\n\n def get_best_path(self):\n paths = [ant.path for ant in self.colony]\n return max(paths, key=lambda path: fitness(self.size, path))\n\n def run(self):\n best_fitness = 0\n best_solution = None\n for i in range(1, self.iterations + 1):\n for ant in self.colony:\n ant.move()\n if i % (self.size * 2 - 1) == 0: # ants have completed their tours at this point\n solution = self.get_best_path()\n if fitness(self.size, solution) > best_fitness:\n best_solution = solution\n best_fitness = fitness(self.size, solution)\n if fitness(self.size, best_solution) == self.size * 2:\n break\n updated_network = self.get_updated_network()\n for ant in self.colony:\n ant.reset(updated_network)\n return best_solution, best_fitness\n\n\n \n \n\n\n","sub_path":"Artificial Intelligence/Lab5/Problem.py","file_name":"Problem.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"223512730","text":"#!/usr/bin/env python\n\nimport argparse\nimport getpass\nimport hashlib\nimport json\nimport logging\nimport random\nimport select\nimport socket \nimport struct\nimport sys\nimport time\n\n# Set default config values\nCONFIG = {\n \"stun\": [\"stun.l.google.com:19302\", \"stun1.l.google.com:19302\",\n \"stun2.l.google.com:19302\", \"stun3.l.google.com:19302\",\n \"stun4.l.google.com:19302\"],\n \"turn\": [], # Contains dicts with \"server\", \"user\", \"pass\" keys\n \"ip4\": \"172.16.0.1\",\n \"localhost\": \"127.0.0.1\",\n \"ip6_prefix\": \"fd50:0dbc:41f2:4a3c\",\n \"localhost6\": \"::1\",\n \"ip4_mask\": 24,\n \"ip6_mask\": 64,\n \"subnet_mask\": 32,\n \"svpn_port\": 5800,\n \"uid_size\": 40,\n \"sec\": True,\n \"wait_time\": 15,\n \"buf_size\": 4096,\n \"tincan_logging\": 1,\n \"controller_logging\" : \"INFO\",\n \"router_mode\": False,\n \"on-demand_connection\" : False,\n \"on-demand_inactive_timeout\" : 600\n}\n\ndef gen_ip6(uid, ip6=None):\n if ip6 is None:\n ip6 = CONFIG[\"ip6_prefix\"]\n for i in range(0, 16, 4): ip6 += \":\" + uid[i:i+4]\n return ip6\n\ndef gen_uid(ip4):\n return hashlib.sha1(ip4).hexdigest()[:CONFIG[\"uid_size\"]]\n\ndef make_call(sock, **params):\n if socket.has_ipv6: dest = (CONFIG[\"localhost6\"], CONFIG[\"svpn_port\"])\n else: dest = (CONFIG[\"localhost\"], CONFIG[\"svpn_port\"])\n return sock.sendto(json.dumps(params), dest)\n\ndef do_send_msg(sock, method, overlay_id, uid, data):\n return make_call(sock, m=method, overlay_id=overlay_id, uid=uid, data=data)\n\ndef do_set_cb_endpoint(sock, addr):\n return make_call(sock, m=\"set_cb_endpoint\", ip=addr[0], port=addr[1])\n\ndef do_register_service(sock, username, password, host):\n return make_call(sock, m=\"register_svc\", username=username,\n password=password, host=host)\n\ndef do_create_link(sock, uid, fpr, overlay_id, sec, cas, stun=None, turn=None):\n if stun is None:\n stun = random.choice(CONFIG[\"stun\"])\n if turn is None:\n if CONFIG[\"turn\"]:\n turn = random.choice(CONFIG[\"turn\"])\n else:\n turn = {\"server\": \"\", \"user\": \"\", \"pass\": \"\"}\n return make_call(sock, m=\"create_link\", uid=uid, fpr=fpr,\n overlay_id=overlay_id, stun=stun, turn=turn[\"server\"],\n turn_user=turn[\"user\"],\n turn_pass=turn[\"pass\"], sec=sec, cas=cas)\n\ndef do_trim_link(sock, uid):\n return make_call(sock, m=\"trim_link\", uid=uid)\n\ndef do_set_local_ip(sock, uid, ip4, ip6, ip4_mask, ip6_mask, subnet_mask):\n return make_call(sock, m=\"set_local_ip\", uid=uid, ip4=ip4, ip6=ip6,\n ip4_mask=ip4_mask, ip6_mask=ip6_mask,\n subnet_mask=subnet_mask)\n\ndef do_set_remote_ip(sock, uid, ip4, ip6):\n return make_call(sock, m=\"set_remote_ip\", uid=uid, ip4=ip4, ip6=ip6)\n\ndef do_get_state(sock):\n return make_call(sock, m=\"get_state\", stats=True)\n\ndef do_set_logging(sock, logging):\n return make_call(sock, m=\"set_logging\", logging=logging)\n\nclass UdpServer:\n def __init__(self, user, password, host, ip4):\n self.state = {}\n self.idle_peers = {}\n self.peers = {}\n self.conn_stat = {}\n self.user = user\n self.password = password\n self.host = host\n self.ip4 = ip4\n self.uid = gen_uid(ip4)\n if socket.has_ipv6:\n self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n else:\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.bind((\"\", 0))\n self.ctrl_conn_init()\n\n self.uid_ip_table = {}\n parts = CONFIG[\"ip4\"].split(\".\")\n ip_prefix = parts[0] + \".\" + parts[1] + \".\"\n for i in range(0, 255):\n for j in range(0, 255):\n ip = ip_prefix + str(i) + \".\" + str(j)\n uid = gen_uid(ip)\n self.uid_ip_table[uid] = ip\n\n def ctrl_conn_init(self):\n do_set_logging(self.sock, CONFIG[\"tincan_logging\"])\n do_set_cb_endpoint(self.sock, self.sock.getsockname())\n\n if not CONFIG[\"router_mode\"]:\n do_set_local_ip(self.sock, self.uid, self.ip4, gen_ip6(self.uid),\n CONFIG[\"ip4_mask\"], CONFIG[\"ip6_mask\"],\n CONFIG[\"subnet_mask\"])\n else:\n do_set_local_ip(self.sock, self.uid, CONFIG[\"router_ip\"],\n gen_ip6(self.uid), CONFIG[\"router_ip4_mask\"],\n CONFIG[\"router_ip6_mask\"], CONFIG[\"subnet_mask\"])\n\n do_register_service(self.sock, self.user, self.password, self.host)\n do_get_state(self.sock)\n\n def create_connection(self, uid, data, nid, sec, cas, ip4):\n do_create_link(self.sock, uid, data, nid, sec, cas)\n do_set_remote_ip(self.sock, uid, ip4, gen_ip6(uid))\n\n def trim_connections(self):\n for k, v in self.peers.iteritems():\n if \"fpr\" in v and v[\"status\"] == \"offline\":\n if v[\"last_time\"] > CONFIG[\"wait_time\"] * 2:\n do_send_msg(self.sock, \"send_msg\", 1, k,\n \"destroy\" + self.state[\"_uid\"])\n do_trim_link(self.sock, k)\n if CONFIG[\"on-demand_connection\"] and v[\"status\"] == \"online\": \n if v[\"last_active\"] + CONFIG[\"on-demand_inactive_timeout\"]\\\n < time.time():\n logging.debug(\"Inactive, trimming node:{0}\".format(k))\n do_send_msg(self.sock, 1, \"send_msg\", k,\n \"destroy\" + self.state[\"_uid\"])\n do_trim_link(self.sock, k)\n \n def ondemand_create_connection(self, uid, send_req):\n logging.debug(\"idle peers {0}\".format(self.idle_peers))\n peer = self.idle_peers[uid]\n fpr_len = len(self.state[\"_fpr\"])\n fpr = peer[\"data\"][:fpr_len]\n cas = peer[\"data\"][fpr_len + 1:]\n ip4 = self.uid_ip_table[peer[\"uid\"]]\n logging.debug(\"Start mutual creating connection\")\n if send_req:\n do_send_msg(self.sock, \"send_msg\", 1, uid, fpr)\n self.create_connection(peer[\"uid\"], fpr, 1, CONFIG[\"sec\"], cas, ip4)\n\n def create_connection_req(self, data):\n version_ihl = struct.unpack('!B', data[54:55])\n version = version_ihl[0] >> 4\n if version == 4:\n s_addr = socket.inet_ntoa(data[66:70])\n d_addr = socket.inet_ntoa(data[70:74])\n elif version == 6:\n s_addr = socket.inet_ntop(socket.AF_INET6, data[62:78])\n d_addr = socket.inet_ntop(socket.AF_INET6, data[78:94])\n # At present, we do not handle ipv6 multicast\n if d_addr.startswith(\"ff02\"):\n return\n\n uid = gen_uid(d_addr)\n try:\n msg = self.idle_peers[uid]\n except KeyError:\n logging.error(\"Peer {0} is not logged in\".format(d_addr))\n return\n logging.debug(\"idle_peers[uid] --- {0}\".format(msg))\n self.ondemand_create_connection(uid, send_req=True)\n\n def trigger_conn_request(self, peer):\n if \"fpr\" not in peer and peer[\"xmpp_time\"] < CONFIG[\"wait_time\"] * 8:\n self.conn_stat[peer[\"uid\"]] = \"req_sent\"\n do_send_msg(self.sock, \"con_req\", 1, peer[\"uid\"],\n self.state[\"_fpr\"]);\n\n def check_collision(self, msg_type, uid):\n if msg_type == \"con_req\" and \\\n self.conn_stat.get(uid, None) == \"req_sent\":\n if uid > self.state[\"_uid\"]:\n do_trim_link(self.sock, uid)\n self.conn_stat.pop(uid, None)\n return False\n elif msg_type == \"con_resp\":\n self.conn_stat[uid] = \"resp_recv\"\n return False\n else:\n return True\n\n def serve(self):\n socks = select.select([self.sock], [], [], CONFIG[\"wait_time\"])\n for sock in socks[0]:\n data, addr = sock.recvfrom(CONFIG[\"buf_size\"])\n if data[0] == '{':\n msg = json.loads(data)\n logging.debug(\"recv %s %s\" % (addr, data))\n msg_type = msg.get(\"type\", None)\n\n if msg_type == \"local_state\":\n self.state = msg\n elif msg_type == \"peer_state\": \n if msg[\"status\"] == \"offline\" or \"stats\" not in msg:\n self.peers[msg[\"uid\"]] = msg\n self.trigger_conn_request(msg)\n continue\n stats = msg[\"stats\"]\n total_byte = 0\n for stat in stats:\n total_byte += stat[\"sent_total_bytes\"]\n total_byte += stat[\"recv_total_bytes\"]\n msg[\"total_byte\"]=total_byte\n logging.debug(\"self.peers:{0}\".format(self.peers))\n if not msg[\"uid\"] in self.peers:\n msg[\"last_active\"]=time.time()\n elif not \"total_byte\" in self.peers[msg[\"uid\"]]:\n msg[\"last_active\"]=time.time()\n else:\n if msg[\"total_byte\"] > \\\n self.peers[msg[\"uid\"]][\"total_byte\"]:\n msg[\"last_active\"]=time.time()\n else:\n msg[\"last_active\"]=\\\n self.peers[msg[\"uid\"]][\"last_active\"]\n self.peers[msg[\"uid\"]] = msg\n\n # we ignore connection status notification for now\n elif msg_type == \"con_stat\": pass\n elif msg_type == \"con_req\": \n if CONFIG[\"on-demand_connection\"]: \n self.idle_peers[msg[\"uid\"]]=msg\n else:\n if self.check_collision(msg_type,msg[\"uid\"]): continue\n fpr_len = len(self.state[\"_fpr\"])\n fpr = msg[\"data\"][:fpr_len]\n cas = msg[\"data\"][fpr_len + 1:]\n ip4 = self.uid_ip_table[msg[\"uid\"]]\n self.create_connection(msg[\"uid\"], fpr, 1, CONFIG[\"sec\"],\n cas, ip4)\n elif msg_type == \"con_resp\":\n if self.check_collision(msg_type, msg[\"uid\"]): continue\n fpr_len = len(self.state[\"_fpr\"])\n fpr = msg[\"data\"][:fpr_len]\n cas = msg[\"data\"][fpr_len + 1:]\n ip4 = self.uid_ip_table[msg[\"uid\"]]\n self.create_connection(msg[\"uid\"], fpr, 1, CONFIG[\"sec\"],\n cas, ip4)\n\n # send message is used as \"request for start mutual connection\"\n elif msg_type == \"send_msg\": \n if CONFIG[\"on-demand_connection\"]:\n if msg[\"data\"].startswith(\"destroy\"):\n do_trim_link(self.sock, msg[\"uid\"])\n else:\n self.ondemand_create_connection(msg[\"uid\"], False)\n \n # If a packet that is destined to yet no p2p connection established\n # node, the packet as a whole is forwarded to controller\n else:\n if not CONFIG[\"on-demand_connection\"]:\n return\n if len(data) < 16:\n return\n self.create_connection_req(data)\n\ndef parse_config():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", help=\"load configuration from a file\",\n dest=\"config_file\", metavar=\"config_file\")\n args = parser.parse_args()\n\n if args.config_file:\n # Load the config file\n with open(args.config_file) as f:\n loaded_config = json.load(f)\n CONFIG.update(loaded_config)\n\n if not (\"xmpp_username\" in CONFIG and \"xmpp_host\" in CONFIG):\n raise ValueError(\"At least 'xmpp_username' and 'xmpp_host' must be \"\n \"specified in config file\")\n\n if \"xmpp_password\" not in CONFIG:\n prompt = \"\\nPassword for %s: \" % CONFIG[\"xmpp_username\"]\n CONFIG[\"xmpp_password\"] = getpass.getpass(prompt)\n\n if \"controller_logging\" in CONFIG:\n level = getattr(logging, CONFIG[\"controller_logging\"])\n logging.basicConfig(level=level)\n\ndef main():\n\n parse_config()\n count = 0\n server = UdpServer(CONFIG[\"xmpp_username\"], CONFIG[\"xmpp_password\"],\n CONFIG[\"xmpp_host\"], CONFIG[\"ip4\"])\n last_time = time.time()\n while True:\n server.serve()\n time_diff = time.time() - last_time\n if time_diff > CONFIG[\"wait_time\"]:\n count += 1\n server.trim_connections()\n do_get_state(server.sock)\n last_time = time.time()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/gvpn_controller.py","file_name":"gvpn_controller.py","file_ext":"py","file_size_in_byte":12862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"57092409","text":"import pickle\n\nfrom src.dataLoader import Document, Dataset, read_text_file, get_url_hashes, fix_missing_period\n\n\ndef get_art_abs(story_file):\n lines = read_text_file(story_file)\n\n # Lowercase everything\n lines = [line.lower() for line in lines]\n\n # Put periods on the ends of lines that are missing them (this is a problem in the dataset because many image captions don't end in periods; consequently they end up in the body of the article as run-on sentences)\n lines = [fix_missing_period(line) for line in lines]\n\n # Separate out article and abstract sentences\n article_lines = []\n highlights = []\n next_is_highlight = False\n for idx, line in enumerate(lines):\n if line == \"\":\n continue # empty line\n elif line.startswith(\"@highlight\"):\n next_is_highlight = True\n elif next_is_highlight:\n highlights.append(line)\n else:\n article_lines.append(line)\n\n # Make article into a single string\n article = ' '.join(article_lines)\n\n # Make abstract into a signle string, putting and tags around the sentences\n abstract = ' '.join([\"%s %s %s\" % ('', sent, '') for sent in highlights])\n\n return article.split(' '), abstract.split(' ')\n\n\ndef write_to_pickle(url_file, out_file, chunk_size=1000):\n url_list = read_text_file(url_file)\n url_hashes = get_url_hashes(url_list)\n url = zip(url_list, url_hashes)\n story_fnames = [\"./data/CNN_DM_stories/cnn_stories_tokenized/\" + s + \".story\"\n if u.find(\n 'cnn.com') >= 0 else \"./data/CNN_DM_stories/dm_stories_tokenized/\" + s + \".story\"\n for u, s in url]\n\n print(f\"Pickling the {url_file.split('/')[-1].split('.')[0]} data\")\n new_lines = []\n for i, filename in enumerate(story_fnames):\n if i % chunk_size == 0 and i > 0:\n pickle.dump(Dataset(new_lines), open(out_file % (i / chunk_size), \"wb\"),\n protocol=pickle.HIGHEST_PROTOCOL)\n new_lines = []\n\n try:\n art, abs = get_art_abs(filename)\n except:\n print(f\"Pickling of file {filename} did not worked.\")\n continue\n new_lines.append(Document(art, abs))\n\n if new_lines != []:\n pickle.dump(Dataset(new_lines), open(out_file % (i / chunk_size + 1), \"wb\"),\n protocol=pickle.HIGHEST_PROTOCOL)\n print(f\"Finished pickling the {url_file.split('/')[-1].split('.')[0]} data\")\n\n\ndef main():\n train_urls = \"./data/url_lists/all_train.txt\"\n val_urls = \"./data/url_lists/all_val.txt\"\n test_urls = \"./data/url_lists/all_test.txt\"\n\n write_to_pickle(test_urls, \"./data/CNN_DM_pickle_data/pickled/test_%03d.bin.p\", chunk_size=100000000)\n write_to_pickle(val_urls, \"./data/CNN_DM_pickle_data/pickled/val_%03d.bin.p\", chunk_size=100000000)\n write_to_pickle(train_urls, \"./data/CNN_DM_pickle_data/pickled/train_%03d.bin.p\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pickle_data.py","file_name":"pickle_data.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"202080724","text":"#traceback.py\r\nimport re\r\n\r\nworkfile = \"Threads.txt\"\r\n\r\nbegin = re.compile(r'\\d+:\\s+0x[0-9a-z]+\\s\\<')\r\nbegin2 = re.compile(r'0x[0-9a-z]*\\s*:\\s*')\r\n\r\n\r\ndef find_function(data, startlist, endlist):\r\n\r\n matches = []\r\n loop_data = []\r\n i = 0\r\n j = 0\r\n\r\n stripped_data = [line.strip() for line in data]\r\n\r\n for new in stripped_data:\r\n if new != '':\r\n loop_data.append(new)\r\n\r\n\r\n for datum in loop_data:\r\n if i < len(startlist):\r\n if startlist[i] in datum:\r\n if endlist[j] in datum:\r\n # Find and validate before-part.\r\n pos_a = datum.find(startlist[i])\r\n # Find and validate after part.\r\n pos_b = datum.find(endlist[j])\r\n # Return middle part.\r\n adjusted_pos_a = pos_a + len(startlist[i])\r\n matches.append(datum[adjusted_pos_a:pos_b])\r\n i += 1\r\n j += 1\r\n\r\n matches = '\\n'.join(matches)\r\n return matches\r\n\r\n\r\ndef trim (data, end):\r\n startlist = []\r\n endlist = []\r\n\r\n for line in data:\r\n if begin.search(line):\r\n startlist.append(begin.search(line).group())\r\n if end.search(line):\r\n endlist.append(end.search(line).group())\r\n\r\n elif begin2.search(line):\r\n startlist.append(begin2.search(line).group())\r\n if end.search(line):\r\n endlist.append(end.search(line).group())\r\n\r\n\r\n return startlist, endlist\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# def main():\r\n# if __name__ == '__main__':\r\n# start, end = trim()\r\n# find_function(workfile, start, end)\r\n#\r\n# main()\r\n","sub_path":"Traceback.py","file_name":"Traceback.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"185101386","text":"from __future__ import print_function, division\nfrom subprocess import check_output\nimport random, os\n\n\nclass VimWindowContext(object):\n def __init__(self, window):\n import vim\n self.vim = vim\n self._window = window\n self._old_window = vim.current.window\n self._switch_to(window)\n\n def _switch_to(self, window):\n tab = window.tabpage\n self.vim.command(':tabnext %d' % tab.number)\n self.vim.command(':%dwincmd w' % window.number)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, tb):\n self._switch_to(self._old_window)\n\n\nclass VimGdbServer(object):\n def __init__(self):\n import vim\n self.vim = vim\n vim.command(':sign define gdb_pc text=>> texthl=Search')\n self._id = None\n self._dbg_win = None\n self._dbg_tab = None\n\n def _open_dbg_win(self):\n if self._dbg_win is not None and self._dbg_win.valid:\n return self._dbg_win\n self.vim.command(':$tabnew')\n self._dbg_tab = list(self.vim.tabpages)[-1]\n self._dbg_win = self._dbg_tab.windows[0]\n return self._dbg_win\n\n def _try_command(self, *args, **kwargs):\n try:\n return self.vim.command(*args, **kwargs)\n except vim.error:\n pass\n\n def on_stop(self, file_name, line_number):\n new_id = random.randint(100, 20000)\n with VimWindowContext(self._open_dbg_win()):\n self._try_command(':edit %s' % file_name)\n self._try_command(':sign place %d line=%d name=gdb_pc file=%s' %\n (new_id, line_number, file_name))\n if self._id is not None:\n self._try_command(':sign unplace %d' % self._id)\n self._id = new_id\n self._try_command(':sign jump %d file=%s' % (self._id, file_name))\n\n\nclass VimGdbClient(object):\n def __init__(self):\n import gdb\n self.gdb = gdb\n gdb.events.stop.connect(self.on_stop)\n\n def send(self, method, *args):\n cmd = ':py3 vim_gdb_server.%s(%s)' % (method, ', '.join(repr(x) for x in args))\n check_output(['gvim', '--remote-send', cmd])\n\n def on_stop(self, event):\n frame = self.gdb.selected_frame()\n lineobj = self.gdb.find_pc_line(frame.pc())\n symtab = lineobj.symtab\n if symtab is not None:\n self.send('on_stop', symtab.fullname(), lineobj.line)\n\n\ntry:\n vim_gdb_server = VimGdbServer()\nexcept ImportError:\n pass\ntry:\n vim_gdb_client = VimGdbClient()\nexcept ImportError:\n pass\n","sub_path":"vim_gdb.py","file_name":"vim_gdb.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"365335532","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt4.QtGui import QWidget, QVBoxLayout, QTextBrowser, QPushButton, QIcon, QLineEdit, QTextCursor\nfrom PyQt4.QtCore import Qt, pyqtSignal\nimport platform\n\nclass LineEdit(QLineEdit):\n keyUpPressed = pyqtSignal()\n keyDownPressed = pyqtSignal()\n def keyPressEvent(self, event):\n super(LineEdit, self).keyPressEvent(event)\n if event.key() == Qt.Key_Up:\n self.keyUpPressed.emit()\n if event.key() == Qt.Key_Down:\n self.keyDownPressed.emit()\n def __init__(self):\n super(LineEdit, self).__init__()\n\nclass Window(QWidget):\n keyEscapePressed = pyqtSignal()\n def keyPressEvent(self, event):\n super(Window, self).keyPressEvent(event)\n if event.key() == Qt.Key_Escape:\n self.keyEscapePressed.emit()\n\n def __init__(self, parent, dialog=False):\n super(Window, self).__init__()\n self.icon = parent.windowIcon()\n self.layout\t= QVBoxLayout()\n self.textEdit1 = QTextBrowser()\n self.textEdit1.setVisible(False)\n self.layout.addWidget(self.textEdit1)\n self.textInput1 = LineEdit()\n self.textInput1.setVisible(False)\n self.layout.addWidget(self.textInput1)\n self.button1 = QPushButton()\n self.button1.setVisible(False)\n self.layout.addWidget(self.button1)\n self.button2 = QPushButton()\n self.button2.setVisible(False)\n self.layout.addWidget(self.button2)\n self.button3 = QPushButton()\n self.button3.setVisible(False)\n self.layout.addWidget(self.button3)\n self.setLayout(self.layout)\n self.setTabOrder(self.button3, self.textEdit1)\n if dialog:\n self.setWindowModality(Qt.ApplicationModal)\n if platform.system() is 'Windows':\n self.setWindowFlags(Qt.Tool)\n self.setWindowFlags(self.windowFlags() | Qt.CustomizeWindowHint)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowMinimizeButtonHint)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowSystemMenuHint)\n self.keyEscapePressed.connect(self.close)\n\n def setWindow(self, title=u'Window', icon=u''):\n self.setWindowTitle(title)\n icon = QIcon(icon)\n if icon.isNull():\n self.setWindowIcon(self.icon)\n else:\n self.setWindowIcon(icon)\n self.show()\n #self.setFixedSize(self.size())\n self.raise_()\n self.activateWindow()\n\n def setTextEdit1(self, text=u'', append=False, write=True, visible=True):\n textEdit = self.textEdit1\n if not write:\n textEdit.setReadOnly(True)\n if append:\n textEdit.moveCursor(QTextCursor.End)\n textEdit.insertPlainText(text)\n else:\n textEdit.setText(text)\n textEdit.setVisible(visible)\n return textEdit\n\n def getTextEdit1(self):\n return self.textEdit1.toPlainText()\n\n def setTextInput1(self, text=u'', append=False, write=True, action=lambda:None, history=5, visible=True):\n textInput = self.textInput1\n limit = history\n history = {'inputs':[''], 'current':-1}\n if not write:\n textInput.setReadOnly(True)\n if append:\n textInput.append(text)\n else:\n textInput.setText(text)\n def onReturnPressed():\n if textInput.text():\n history['inputs'].insert(0,textInput.text())\n if len(history['inputs']) == limit+2:\n history['inputs'][limit] = history['inputs'].pop(limit+1)\n history['current'] = -1\n action()\n textInput.clear()\n def onUpPressed():\n history['current'] += 1\n if history['current'] == len(history['inputs']):\n history['current'] = 0\n textInput.setText(history['inputs'][history['current']])\n def onDownPressed():\n history['current'] -= 1\n if history['current'] < 0:\n history['current'] = len(history['inputs']) - 1\n textInput.setText(history['inputs'][history['current']])\n textInput.returnPressed.connect(onReturnPressed)\n textInput.keyUpPressed.connect(onUpPressed)\n textInput.keyDownPressed.connect(onDownPressed)\n textInput.setVisible(visible)\n return textInput\n\n def getTextInput1(self):\n return self.textInput1.text()\n\n def setButton1(self, text=u'Button1', action=lambda:None, visible=True):\n button = self.button1\n button.setText(text)\n try:\n button.clicked.disconnect()\n except Exception:\n pass\n finally:\n button.clicked.connect(action)\n button.setAutoDefault(True)\n button.setVisible(visible)\n\n def setButton2(self, text=u'Button2', action=lambda:None, visible=True):\n button = self.button2\n button.setText(text)\n try:\n button.clicked.disconnect()\n except Exception:\n pass\n finally:\n button.clicked.connect(action)\n button.setAutoDefault(True)\n button.setVisible(visible)\n\n def setButton3(self, text=u'Button3', action=lambda:None, visible=True):\n button = self.button3\n button.setText(text)\n try:\n button.clicked.disconnect()\n except Exception:\n pass\n finally:\n button.clicked.connect(action)\n button.setAutoDefault(True)\n button.setVisible(visible)\n","sub_path":"server/windows/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"203337657","text":"# -*- coding: utf-8 -*-\n\nclass BMESBIO2Data:\n \"\"\"[将bio和bmes格式数据转换为格式化数据\n 也可以处理为对应的标注格式]\n \"\"\"\n\n def __init__(self, markType=\"BMES\"):\n \"\"\"实例化时可以选择对应的文本格式,这里支持BMES和BIO\n\n\n >>> BMESBIO2Data(\"BIO\")\n >>>\n\n \"\"\"\n self.markType = markType\n\n pass\n def autoLang(self,word):\n \"\"\"[自动检查文本语言,如果为英文则添加空格 unk 前后加入空格] \n\n Args:\n word ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n if (u'\\u0041'<= word <= u'\\u005a') or (u'\\u0061'<= word <= u'\\u007a'):\n return word+\" \"\n elif word==\"[UNK]\":\n return \" \"+word+\" \"\n else:\n return word\n \n def toData(self, markList=[]):\n \"\"\"[将标记数据转换为格式化数据]\n 返回数据为标记数据\n 返回数据集如下 (['【', '不', '良', '反', '应', '】', '⑴', '可', '见', '胃', '肠', '道', '不', '良', '反', '应', ',', '如', '恶', '心', '、', '呕', '吐', '、', '上', '腹', '疼', '痛', '、', '便', '秘', '。'], [{'type': '不良反应', 'word': ['恶', '心'], 'start': 18, 'end': 19}, {'type': '不良反应', 'word': ['呕', '吐'], 'start': 21, 'end': 22}, {'type': '不良反应', 'word': ['上', '腹', '疼', '痛'], 'start': 24, 'end': 27}, {'type': '不良反应', 'word': ['便', '秘'], 'start': 29, 'end': 30}])\n\n Args:\n markList (list, optional): [标记数据列表如“['常 O']”]. Defaults to [].\n \"\"\"\n\n pre_tag = ''\n words = []\n items = []\n text = []\n item = {\"type\": '', \"word\": [], 'start': None, 'end': None}\n # for i, line in enumerate(open(file)):\n for i, line in enumerate(markList):\n # print(line)\n if i >= 1000:\n print(\"items\", items[:10])\n break\n\n if line == \"\\n\":\n # print(text)\n # print(items)\n items = []\n text = []\n continue\n\n l = line.split(\" \")\n\n # 处理合乎规则的数据\n if len(l) == 2:\n # 自动对英文添加空格处理\n word = self.autoLang(l[0])\n \n words.append(word)\n tag = l[1].replace(\"\\n\", '')\n text.append(word)\n # print(word, \"//\", tag)\n if self.markType == \"BIO\":\n\n if tag.startswith(\"B-\"):\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n item[\"word\"].append(word)\n item[\"start\"] = i\n item[\"end\"] = i\n item[\"type\"] = tag.replace(\"B-\", '')\n # print(item)\n elif len(item[\"word\"]) > 0 and tag.startswith(\"I-\"):\n # 判断是否与前面标记数据一样类型,否则删除上面标记\n if item.get(\"type\") == tag.replace(\"I-\", ''):\n item[\"word\"].append(word)\n item[\"end\"] = i\n else:\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n\n else:\n # print(\"dd\")\n if len(item[\"word\"]) > 0:\n items.append(item)\n pre_tag = tag\n elif self.markType == \"BMES\":\n # 处理BMES格式数据\n # print(\"\")\n if tag.startswith(\"B-\"):\n # 处理开头\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n item[\"word\"].append(word)\n item[\"start\"] = i\n item[\"type\"] = tag.replace(\"B-\", '')\n\n elif len(item[\"word\"]) > 0 and tag.startswith(\"M-\"):\n # 处理中间\n\n # 判断是否与前面标记内容类型一样,否则进行重置\n if item.get(\"type\") == tag.replace(\"M-\", ''):\n item[\"word\"].append(word)\n else:\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n elif len(item[\"word\"]) > 0 and tag.startswith(\"E-\"):\n # 处理结尾\n # 判断是否与前面标记内容类型一样,否则进行重置\n if item.get(\"type\") == tag.replace(\"E-\", ''):\n item[\"word\"].append(word)\n item[\"end\"] = i\n items.append(item)\n else:\n pass\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n elif tag.startswith(\"S-\"):\n # 处理单个\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n item[\"word\"].append(word)\n item[\"type\"] = tag.replace(\"S-\", '')\n item[\"start\"] = i\n item[\"end\"] = i\n items.append(item)\n item = {\"type\": '', \"word\": [],\n 'start': None, 'end': None}\n else:\n # print(\"dd\")\n if len(item[\"word\"]) > 0 and pre_tag.startswith(\"E-\"):\n items.append(item)\n\n pre_tag = tag\n\n # print(\"items\", items[:10])\n return words, items\n\n def file2Data(self, file):\n \"\"\"[从文件获取格式化后数据]\n\n Args:\n file ([type]): [description]\n \"\"\"\n\n items = []\n item = []\n for i, line in enumerate(open(file)):\n if len(line.split(\" \")) == 2:\n item.append(line)\n pass\n elif len(item) > 0:\n items.append(item)\n item = []\n pass\n\n # print(items[:10])\n for i, line in enumerate(items):\n # print(line)\n # print(self.toData(line))\n yield self.toData(line)\n\n def data2BMES(self, words, mark):\n \"\"\"[将格式化的数据转换为BMES格式]\n\n Args: [[self.toData输出words, mark]]. Defaults to [].\n \"\"\"\n # print(words, mark)\n for m in mark:\n # mWords=m.get(\"word\")\n words[m.get(\"start\")] = \"[@\"+words[m.get(\"start\")]\n words[m.get(\"end\")] = \"\"+words[m.get(\"end\")]+\"#\"+m.get(\"type\")+\"*]\"\n # print(words)\n\n for i, w in enumerate(words):\n words[i] = words[i].replace(\"##\", \"\")\n # 此处存在问题,两个英文单词该如何处理\n return words\n","sub_path":"BMESBIO2Data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"422444496","text":"from django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\n\n\ndef send_email(email, code):\n\n subject = 'Register mail form www.izheyi.com'\n\n # text_content是用于当HTML内容无效时的替代txt文本\n text_content = '''Thanks for register www.izheyi.com,Welcome!'''\n\n html_content = '''\n

Thanks for registerwww.izheyi.com

\n

Click the link to finish the registration!

\n

This link will expire in {} days!

\n '''.format('127.0.0.1:8000', code, settings.CONFIRM_DAYS)\n\n msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"291092776","text":"from django import forms\n\nfrom .models import Reminder\n\n\nclass ReminderInlineAdminForm(forms.ModelForm):\n class Meta:\n model = Reminder\n fields = ('user', 'interval', 'object_id', 'content_type',)\n\n def clean_user(self):\n user = self.cleaned_data['user']\n if not user.email:\n raise forms.ValidationError(\n \"User doesn't have an email address, please pick a different user or add an \"\n \"email address\"\n )\n return user\n\n def validate_unique(self):\n \"\"\"\n Add this method because django doesn't validate correctly because required fields are\n excluded.\n \"\"\"\n unique_checks, date_checks = self.instance._get_unique_checks(exclude=[])\n errors = self.instance._perform_unique_checks(unique_checks)\n if errors:\n self.add_error(None, errors)\n","sub_path":"glitter/reminders/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"257090497","text":"import re\n\n#Define the input file here\nfile_in = open(\"input.ckt\", \"r\")\n\n#define the output file here\nfile_out = open(\"output4.ckt\", \"w\")\n\n#reading the input file\nnetlist = file_in.read()\nfile_in.close()\n\n#converting the netlist to line by line format\nnetlist = netlist.split(\"\\n\")\n\n#iteration for line by line\nfor line in netlist:\n\tline = line.replace(\"vdd \", \"vdda \")\n\tline = line.replace(\"vss \", \"vssa \")\n\tmatch_subckt = re.search(\"subckt\", line)\n\tmatch_gate = re.search(\"^xg\", line)\n\tmatch_inst = re.search(\"^xi\", line)\n\tmatch_gate1 = re.search(\"^x1i\", line)\n\tmatch_gate2 = re.search(\"^x2i\", line)\n\tmatch_gate3 = re.search(\"^x3i\", line)\n\tmatch_resist = re.search(\"^xr\", line)\n\tmatch_insto = re.search(\"^xo\", line)\n\tmatch_rppolywo = re.search(\"rppolywo\", line)\n\tmatch_cp1p2 = re.search(\"cp1p2\", line)\n\tmatch_cpolppw = re.search(\"cpolppw\", line)\n\n\tif \tmatch_subckt:\n\t\tnew_line = line.split(\" \")\n\t\tnew_line.insert(2, \"vssa\")\n\t\tnew_line.insert(2, \"vdda\")\n\t\tnew_line = \" \".join(new_line)\n\telif match_resist:\n\t\tnew_line = line.split(\" \")\n\t\tif len(new_line) == 4:\n\t\t\tnew_line.insert(1, \"vssa\")\n\t\t\tnew_line.insert(1, \"vdda\")\n\t\tnew_line = \" \".join(new_line)\n\telif match_gate or match_inst or match_gate1 or match_gate2 or match_gate3 or match_insto:\n\t\tnew_line = line.split(\" \")\n\t\tif not(match_rppolywo) and not(match_cp1p2) and not(match_cpolppw):\n\t\t\tnew_line.insert(1, \"vssa\")\n\t\t\tnew_line.insert(1, \"vdda\")\n\t\tnew_line = \" \".join(new_line)\n\telse:\n\t\tnew_line = line.split(\" \")\n\t\tnew_line = \" \".join(new_line)\n\n\tfile_out.write(new_line+\"\\n\")\nfile_out.close()\n","sub_path":"global_power_replacement/srch_replac_power.py","file_name":"srch_replac_power.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"436995433","text":"import os\nimport sys\nimport requests\nimport json\nimport discord\nimport spotipy\nimport spotipy.util as util\n\n\ndef read_token():\n with open(\"discord_auth.txt\", \"r\") as f:\n lines = f.readlines()\n return lines[0].strip()\n\n\ntoken = read_token()\nclient = discord.Client()\n\n\n@client.event\nasync def on_ready():\n await client.change_presence(status=discord.Status.online, activity=discord.Game('running in #music'))\n print(\"online\")\n\n# scope = 'playlist-modify-public user-read-email'\nclient_id = '' # put your client id from Spotify here\nresponse_type = 'code'\nclient_secret = '' # put your client secret from Spotify in here\nplaylist_id = '' # this is the id of your Spotify playlist\nusername = '' # spotify username\ntoken_spotify = util.prompt_for_user_token(username, scope='playlist-modify-public', # i know prompt_for_user_token is depreciated but it's the only thing that works\n client_id='',\n client_secret='',\n redirect_uri='http://localhost:8888/callback')\nsp = spotipy.Spotify(auth=token_spotify)\n\n\n@client.event\nasync def on_message(message):\n channel = 'music'\n if str(message.channel) == channel:\n if message.content.find('spotify:track:') != -1:\n print(f'message received in channel {str(message.channel)}')\n await message.channel.send('Trying to add to playlist...')\n s = str(message.content)\n tracks = s.split(',') \n for id in tracks:\n trackid = [id[14:]]\n print(trackid)\n sp.user_playlist_add_tracks(username, playlist_id=playlist_id, tracks=trackid)\n # sp.user_playlist_add_tracks(username, playlist_id=playlist_id, tracks=trackid)\n embed = discord.Embed(color=discord.Color.from_rgb(0, 240, 0), title=\"Success!\", # this embed is optional, i send it so that people on the server\n description=\"Check out the playlist at \") # know what the playlist is / can access without navigating to my\n # profile on spotify\n await message.channel.send(content=None, embed=embed)\n\nclient.run(token)\n\n\n\n","sub_path":"spotbot.py","file_name":"spotbot.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"458515912","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ylilauta/suomi24.fi nettikielitokenisoija ja virkkeistäjä\n# asahala fin-clarin 14.02.2015,\n\n# vie importilla warcciparseriin\n# kutsu funktiota tokenize, joka ottaa argumenteikseen syötemerkkjonon\n# sekä pisimmän sallitun pituuden stringille (huomaa, että cwb-encode\n# katkoo automaattisesti yli 4096 merkkiä pitkät stringit ja kadottaa\n# näiden loput. Truncate-funktiota käyttämällä skripti lisää välejä\n# n merkin välein pitkiin stringeihin, joten kaikki säilyvät.\n\nimport re\nimport html.parser\n\n\"\"\"\nsmileys = hymiöt :D :--------D ^_^ :p\nchar_map = yleiset välimerkit\nus_num = pisteillä erotetut jenkkinumerot\nurls = ne ja sähköpostit\nabbrs = kaksoispisteellä tai apostrofilla lyhennetyt ja taivutetut sanat\nabbrx = yleiset lyhenteet\ndate = päivämäärät ja järjestysluvut\nclock = kellonajat hh:mm\nacronymsN = N kirjaimen pituiset pisteellä erotetut akronyymit\n\"\"\"\n\nsmileys = r'([:;x=]-*[DEPO\\(\\)\\|codpf]+)|\\b(=?[\\^oOx-]_+[\\^oOx-]=?\\b)|[ \\b]:3'\nchar_map = r'(%s|[\\.;:,\\?!]+|[—\\(\\)\\<\\>\\{\\}]|(^|\\s)-)' % smileys\nus_num = r'(\\d+\\.)+\\d+(,\\d\\d)?|\\d+,\\d\\d'\nurls = r'(https?://|www\\.)([~/\\?\\+\\&a-z0-9_-]+?\\.?)+|'\\\n '([A-Za-z0-9]+\\.)?[A-Za-z0-9]+\\@([a-z0-9]+\\.)+[a-z]+'\nabbrs = r'[a-zA-ZÄÖÅåäö]+?[:\\'’]'\\\n '(h?[aiuoeöä]+n|[aä]|i?l[lt][aä]|i?s[st][aä]|i?lle|i?ksi)[a-z]*'\nabbrx = r' ([A-Z]|aik|kirj|alk|ark|as|ed|eKr|ekr|jKr|jkr|'\\\n 'eaa|tod|henk|ym|koht|jaa|esim|huom|jne|joht|'\\\n 'k|ks|lk|lkm|lyh|läh|miel|milj|mm|mrd|myöh|n|'\\\n 'nimim|ns|nyk|oik|os|p|ps|par|per|pj|prof|puh|'\\\n 'kok|kes|kys|ko|virh|vas|pvm|rak|s|siht|synt|t|tark|til|'\\\n 'tms|toim|huhtik||v|vas|vast|vrt|yht|yl|ym|yms|'\\\n 'yo|ao|em|ko|ml|po|so|ts|vm|etc)\\.'\nacronyms4 = r'([A-Za-z])\\.([A-Za-z])\\.([A-Za-z])\\.([A-Za-z])\\.'\nacronyms3 = r'([A-Za-z])\\.([A-Za-z])\\.([A-Za-z])\\.'\nacronyms2 = r'([A-Za-z])\\.([A-Za-z])\\.'\ndate = r'(\\d\\d?)\\.'\nclock = r'(\\d\\d?):(\\d\\d)(:\\d\\d)?'\n\ndef truncate(string, maxlen):\n \"\"\" Typistä floodaukset n (maxlen) merkkiin\"\"\"\n truncated = str()\n\n i = 0\n for c in string:\n if i == maxlen:\n truncated += '\\n'\n i = -1\n else:\n truncated += c\n i += 1\n return truncated\n\ndef split_sents(string, maxlen, sent_id):\n \n if sent_id is None:\n id_ = ''\n else:\n id_ = '_id=\"{sid}\"'.format(sid=sent_id)\n\n #korvaa unicode-lainausmerkit suomalaisiksi\n string = re.sub('[”“„\"]', ' \" ', string)\n \"\"\" Tekstin jako virkkeisiin joko kovasta välimerkistä tai hymiöstä.\n Virke saa alkaa myös pienellä alkukiraimella \"\"\"\n string = re.sub('<', ' LESSERTHAN ', string)\n string = re.sub('>', ' GREATERTHAN ', string)\n string = re.sub(\" [«»](.+?)[«»] \", r' \\1 ', string)\n string = re.sub(' \"(.+?)\" ', r' \\1 ', string)\n string = re.sub(\" ['’](.+?)['’] \", r' \\1 ', string)\n string = re.sub('\\n| +', ' ', string)\n string = re.sub('( [\\!\\?\\.]+?( %s)?( )? | %s )' % (smileys, smileys),\n r'\\1 ' %id_ , string)\n string = ' ' % id_ + string\n #purkkakorjaus, korjaa vriheellisen virkejaon \"tekstiä\", ...\n string = re.sub(' ,', ',', string)\n\n if not string.endswith((' ', '')):\n string += ' '\n\n string = re.sub('', '\"', string)\n string = re.sub('', '»', string)\n string = re.sub('', \"'\", string)\n string = re.sub('GREATERTHAN', '>', string)\n string = re.sub('LESSERTHAN', '<', string)\n string = re.sub(' +', ' ', string)\n tokens = string.split(' ')\n\n if sent_id is not None:\n tokens = [re.sub(' maxlen:\n string = truncate(string, maxlen)\n\n # muunna HTML-entiteetit ja korvaa tabit (jäsennin ei tykkää)\n string = html.parser.HTMLParser().unescape(string)\n string = re.sub('\\t', ' ', string)\n # lisää tähän poikkeuksia, mikäli haluat säilyttää html-tägejä\n # huomaa loppusuljetut tagit kuten tai
\n # saattavat aiheuttaa ongelmia cwb:n ja korpin kanssa\n string = re.sub('<.+?>', '', string)\n\n out = (re.sub(char_map, r' \\1 ', mark_specials(string)))\n # korvataan väliaikainen symboli pisteelle\n out = re.sub('QxQz', '.', remove_spaces(out))\n out = re.sub('QzQx', ':', remove_spaces(out))\n vrt = split_sents(out, maxlen, sent_id)\n return vrt[0:-1]\n","sub_path":"corp/lehdet90ff/vrt_tools.py","file_name":"vrt_tools.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"624206422","text":"import numpy\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.preprocessing import Imputer, StandardScaler, LabelBinarizer\n\n\nclass HousingPipeline(object):\n def build(self, data, category_attributes):\n number_attributes = list(data.drop(category_attributes, axis=1))\n\n num_pipeline = Pipeline([\n ('selector', DataFrameSelector(number_attributes)),\n ('imputer', Imputer(strategy='median')),\n ('attribs_adder', CombinedAttributeAdder()),\n ('std_scaler', StandardScaler())\n ])\n\n cat_pipeline = Pipeline([\n ('selector', DataFrameSelector(category_attributes)),\n ('label_binarizer', LabelBinarizer())\n ])\n\n return FeatureUnion(transformer_list=[\n ('num_pipeline', num_pipeline),\n ('cat_pipeline', cat_pipeline)\n ])\n\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n return X[self.attribute_names].values\n\n\nclass CombinedAttributeAdder(BaseEstimator, TransformerMixin):\n rooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6\n\n def __init__(self, add_bedrooms_per_room=True):\n self.add_bedrooms_per_room = add_bedrooms_per_room\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X, y=None):\n rooms_per_household = X[:, self.rooms_ix] / X[:, self.household_ix]\n population_per_household = X[:, self.population_ix] / X[:, self.household_ix]\n if self.add_bedrooms_per_room:\n bedrooms_per_room = X[:, self.bedrooms_ix] / X[:, self.rooms_ix]\n return numpy.c_[X, rooms_per_household, population_per_household, bedrooms_per_room]\n else:\n return numpy.c_[X, rooms_per_household, population_per_household]\n","sub_path":"housing/transformers.py","file_name":"transformers.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588731602","text":"#!/usr/bin/env python3\n\nimport os\nimport argparse\nfrom manager import Manager\nfrom project import Project\n\nfrom ds_utils import ArgCheck, assign_structure_recursive\nfrom struct_default_values import structure, default_values\n\n# TODO: write setup.py!\ndef get_arg_parser():\n \"\"\" Define argument parser\n\n The default values are saved as a dictionary in struct_default_values.py\n \"\"\"\n parser = argparse.ArgumentParser(description='Deep Spline Neural Network')\n\n # for test mode, need to provide --ckpt_filename\n parser.add_argument('--mode', choices=['train', 'test'], type=str,\n help=f'Train or test mode. Default: {default_values[\"mode\"]}.')\n\n # add other networks here, in the models/ directory and in Manager.build_model()\n net_choices = {'twoDnet_onehidden', 'twoDnet_onehidden', 'simplenet', 'simplestnet', \\\n 'resnet20', 'resnet32', 'resnet32_linear', 'nin', 'nin_linear'}\n parser.add_argument('--net', metavar='STR', type=str,\n help=f'Network to train. Available networks: {str(net_choices)}. Default: {default_values[\"net\"]}.')\n parser.add_argument('--model_name', metavar='STR', type=str,\n help=f'Default: {default_values[\"model_name\"]}.')\n parser.add_argument('--device', choices=['cuda:0', 'cpu'], type=str,\n help=f'Default: {default_values[\"device\"]}.')\n\n parser.add_argument('--num_epochs', metavar='INT,>0', type=ArgCheck.p_int,\n help=f'Number of epochs. Default: {default_values[\"num_epochs\"]}.')\n\n # model parameters\n activation_type_choices = {'deepBspline', 'deepRelu', 'deepBspline_explicit_linear', \\\n 'apl', 'relu', 'leaky_relu', 'prelu'}\n parser.add_argument('--activation_type', choices=activation_type_choices, type=str,\n help=f'Default: {default_values[\"activation_type\"]}.')\n\n spline_init_choices = {'relu', 'leaky_relu', 'softplus', 'even_odd', 'random', 'identity', 'zero'}\n parser.add_argument('--spline_init', choices=spline_init_choices, type=str,\n help='Initialize the b-spline coefficients according to this function. '\n f'Default: {default_values[\"spline_init\"]}.')\n parser.add_argument('--spline_size', metavar='INT>0', type=ArgCheck.p_odd_int,\n help='Number of spline coefficients. Default: {default_values[\"spline_size\"]}.')\n parser.add_argument('--spline_range', metavar='FLOAT,>0', type=ArgCheck.p_float,\n help=f'Range of spline representation. Default: {default_values[\"spline_range\"]}.')\n\n parser.add_argument('--S_apl', metavar='INT,>0', type=ArgCheck.p_int,\n help=f'Additional number of APL knots. Default: {default_values[\"S_apl\"]}.')\n\n parser.add_argument('--hidden', metavar='INT,>0', type=ArgCheck.p_int,\n help=f'Number of hidden neurons in each layer (for twoDnet). Default: {default_values[\"hidden\"]}.')\n\n # regularization\n parser.add_argument('--hyperparam_tuning', action='store_true',\n help='Tune TV/BV(2) and weight decay hyperparameters according to '\n 'a tuning constant (--lmbda).')\n parser.add_argument('--lipschitz', action='store_true',\n help='Perform lipschitz BV(2) regularization; the hyperparameter is set by --lmbda.')\n parser.add_argument('--lmbda', metavar='FLOAT,>=0', type=ArgCheck.nn_float,\n help='if --hyperparam_tuning is set, it is used tune TV/BV(2) and weight decay '\n 'hyperparameters; otherwise, it is the TV/BV(2) hyperparameter.'\n f'Default: {default_values[\"lmbda\"]}.')\n parser.add_argument('--outer_norm', metavar='INT,>0', choices=[1,2], type=ArgCheck.p_int,\n help='Outer norm for TV(2)/BV(2). Choices: {1,2}. '\n f'Default: {default_values[\"outer_norm\"]}.')\n\n parser.add_argument('--beta', metavar='FLOAT,>=0', type=ArgCheck.nn_float,\n help='Weight decay on APL parameters. '\n f'Default: {default_values[\"beta\"]}.')\n\n # optimizer\n optimizer_choices={'Adam', 'SGD'}\n parser.add_argument('--optimizer', metavar='LIST[STR]', nargs='+', type=str,\n help='Can be one or two args. In the latter case, the first arg is the main '\n 'optimizer (for network parameters) and the second arg is the aux optimizer '\n '(for deepspline parameters). Adam aux_optimizer is usually required for stability '\n f'during training, even if main optimizer is SGD. Choices: {str(optimizer_choices)}. '\n f'Default: {default_values[\"optimizer\"]}.')\n\n parser.add_argument('--lr', metavar='FLOAT,>0', type=ArgCheck.p_float,\n help=f'Learning rate for main optimizer (for network parameters). Default: {default_values[\"lr\"]}.')\n parser.add_argument('--aux_lr', metavar='FLOAT,>0', type=ArgCheck.p_float,\n help=f'Learning rate for aux optimizer (for deepspline parameters). Default: {default_values[\"aux_lr\"]}.')\n parser.add_argument('--weight_decay', metavar='FLOAT,>=0', type=ArgCheck.nn_float,\n help=f'L2 penalty on parameters. If --hyperparam_tuning is set, '\n 'then a custom weight decay is applied to the weights of the network '\n 'and --weight_decay is applied to the remaining parameters (e.g. BatchNorm). '\n 'Default: {default_values[\"weight_decay\"]}.')\n\n # multistep scheduler\n parser.add_argument('--gamma', metavar='FLOAT,[0,1]', type=ArgCheck.frac_float,\n help=f'Learning rate decay. Default: {default_values[\"gamma\"]}.')\n parser.add_argument('--milestones', metavar='LIST[INT,>0]', nargs='+', type=ArgCheck.p_int,\n help='Milestones for multi-step lr_scheduler. Set to a single value higher than num_epochs '\n 'if you do not wish to lower the learning rate during training. '\n f'Default: {default_values[\"milestones\"]}.')\n\n # logs-related\n parser.add_argument('--ckpt_filename', metavar='STR', type=str,\n help=f'Continue training (if --mode=train) or test (if --mode=test) the model saved '\n f'in this checkpoint. Default: {default_values[\"ckpt_filename\"]}.')\n\n parser.add_argument('--resume', '-r', action='store_true',\n help='Resume training from latest checkpoint. Need to provide '\n '--model_name and --log_dir where the model is saved.')\n parser.add_argument('--resume_from_best', '-best', action='store_true',\n help='Resume training from best validation accuracy checkpoint. Need to provide '\n '--model_name and --log_dir where the model is saved.')\n\n parser.add_argument('--log_dir', metavar='STR', type=str,\n help=f'Directory for saving checkpoints and tensorboard events. Default: {default_values[\"log_dir\"]}.')\n\n parser.add_argument('--log_step', metavar='INT,>0', type=ArgCheck.p_int,\n help=f'Train log step in batch_size. Default: {default_values[\"log_step\"]}.')\n parser.add_argument('--valid_log_step', metavar='INT,>0', type=ArgCheck.p_int,\n help=f'Validation step in epochs. Default: {default_values[\"valid_log_step\"]}.')\n\n parser.add_argument('--sparsify_activations', action='store_true',\n help='Sparsify activations by eliminating slopes changes below threshold.')\n parser.add_argument('--slope_diff_threshold', metavar='FLOAT,>=0', type=ArgCheck.nn_float,\n help=f'Activation slopes diff threshold. Default: {default_values[\"slope_diff_threshold\"]}.')\n\n # dataloader\n parser.add_argument('--seed', metavar='INT,>0', type=ArgCheck.nn_int,\n help=f'fix seed for reproducibility. Default: {default_values[\"seed\"]}.')\n parser.add_argument('--test_as_valid', action='store_true',\n help='Train on full training data and evaluate model on test set in validation step.')\n\n # add other datasets here and create a corresponding Dataset class in datasets.py\n dataset_choices = {'s_shape_1500', 'circle_1500', 'cifar10', 'cifar100', 'mnist'}\n parser.add_argument('--dataset_name', metavar='STR', type=str,\n help=f'dataset to train/test on. Available datasets: {str(dataset_choices)}. '\n f'Default: {default_values[\"dataset_name\"]}.')\n\n parser.add_argument('--data_dir', metavar='STR', type=str, help=f'location of the data. Default: {default_values[\"data_dir\"]}.')\n parser.add_argument('--batch_size', metavar='INT,>0', type=ArgCheck.p_int, help=f'Default: {default_values[\"batch_size\"]}.')\n\n # dataset\n parser.add_argument('--plot_imgs', action='store_true', help='Plot train/test images')\n parser.add_argument('--save_imgs', action='store_true', help='Save train/test images')\n parser.add_argument('--save_title', metavar='STR', type=str,\n help='Title for saving images. Predefined titles are used if not set.')\n\n parser.add_argument('--tensorboard', action='store_true', help='Use tensorboard logs.')\n parser.add_argument('--verbose', '-v', action='store_true', help='Print more info.')\n\n additional_info_choices = {'sparsity', 'lipschitz_bound'}\n parser.add_argument('--additional_info', metavar='LIST[STR]', nargs='+', type=str,\n help=f'Additional info to log in results json file. '\n f'Choices: {str(additional_info_choices)}. Default: {default_values[\"additional_info\"]}.')\n\n return parser\n\n\n\ndef assign_recursive(params, user_params):\n \"\"\" Assign recursive structure \"\"\"\n # assign recursive structure to both dictionaries as defined in struct_default_values.py\n user_params = assign_structure_recursive(user_params, structure)\n params = assign_structure_recursive(params, structure)\n\n return params, user_params\n\n\n\ndef verify_params(params):\n \"\"\" Verify parameters (e.g. mutual inclusivity or exclusivity) and\n assign recursive structure to parameters.\n \"\"\"\n user_params = {} # parameters input by user\n\n # Check parameters input by user and set default values\n for key, value in default_values.items():\n if key not in params or params[key] is None:\n params[key] = value # param which was not set by user\n elif params[key] is not False:\n user_params[key] = params[key] # param or action='store_true' flag input by user\n\n # check parameter dependecies\n if params['mode'] == 'test' and 'ckpt_filename' not in user_params:\n if 'log_dir' in user_params and 'model_name' in user_params:\n # test on last model checkpoint\n log_dir_model = os.path.join(params['log_dir'], params['model_name'])\n params['ckpt_filename'] = Project.get_ckpt_from_log_dir_model(log_dir_model)\n user_params['ckpt_filename'] = params['ckpt_filename']\n else:\n raise ValueError('Please provide --ckpt_filename for testing.')\n\n if params['resume_from_best']:\n params['resume'] = True # set 'resume' to True if 'resume_from_best' is True\n user_params['resume'] = True\n\n if len(params['optimizer']) > 2:\n raise ValueError('Please provide a maximum of two optimizers (main and aux).')\n\n if params['resume'] and ('log_dir' not in user_params or 'model_name' not in user_params):\n raise ValueError('Need to provide either log_dir and model_name, '\n 'if resuming training from best or latest checkpoint.')\n\n return params, user_params\n\n\n\ndef main_prog(params, isloaded_params=False):\n \"\"\" Main program\n\n Args:\n isloaded_params : True if params are loaded from ckpt\n (no need to verify) and flattened (ds_utils)\n \"\"\"\n if isloaded_params:\n assert params['mode'] != 'test', 'params need to be verified in test mode...'\n user_params = params\n else:\n params, user_params = verify_params(params)\n\n # assign recursive structure to params according to structure in struct_default_values.py\n params, user_params = assign_recursive(params, user_params)\n\n manager = Manager(params, user_params)\n\n if params['mode'] == 'train':\n print('\\n==> Training model.')\n manager.train()\n\n elif params['mode'] == 'test':\n print('\\n\\n==> Testing model.')\n manager.test()\n\n\n\nif __name__ == \"__main__\":\n\n # parse arguments\n parser = get_arg_parser()\n args = parser.parse_args()\n params = vars(args) # transform to dictionary\n\n main_prog(params)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"190893546","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport multiprocessing\nfrom util import logger\nfrom data import data_helper as hp\nfrom data import daily_data_worker as dw\n\n__data_logger = logger.set_logger('data')\n__author__ = 'Will Chen'\n\nhp.loading_calendar()\n__data_logger.info('Calendar Information loaded.')\nhp.loading_stock_list()\n__data_logger.info('All ticker info created.')\n\n\npool = multiprocessing.Pool(processes=3)\nstock_list = dw.get_stock_list()\n__data_logger.info('Ready to load prices in 3 processes')\nfor i in range(len(stock_list)):\n pool.apply_async(hp.loading_price, (stock_list[i], ))\npool.close()\npool.join()\n__data_logger.info('All price loaded into database')\n","sub_path":"data_init.py","file_name":"data_init.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"415317532","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*\n\n' a test module to run genetic algorithm '\n\nimport random\nimport json\n\n__author__ = 'Zhang Yuning'\n\npath = r'C:\\Users\\84338\\Documents\\GitHub\\LearnPython\\Genetic_Algorithm\\conditions.json'\nwith open(path) as f:\n conditions = json.load(f)\n\n\nclass Room(object):\n '''\n Init a ranctangular room\n with specific width and lenth.\n Jars which can be pick lied randomly in the room with a ratio\n '''\n\n def __init__(self, width=10, length=10):\n '''\n :param width: width of the room\n :param lenth: lenth of the room \n :type width: int\n :type length: int\n :returns: None\n ..note:: positions in the room are initialized as tuples in list \n and the positions of jars the same \n '''\n self.width = width\n self.length = length\n self.positions = [(x, y) for x in range(width) for y in range(length)]\n self.jars = random.sample(\n self.positions, (self.width * self.length) // 2)\n # def initJar(self):\n # '''\n # init jars\n # '''\n # num = (self.width * self.length) // 2\n # for i in range(num):\n # randomPosition = random.choice(self.positions)\n # while randomPosition in self.jars:\n # randomPosition = random.choice(self.positions)\n # self.jars.append(randomPosition)\n\n def isInRoom(self, position):\n '''\n :param position: a position tuple such as (x, y)\n :type position: tuple\n :returns: true if position is in room, else False\n :rtype: bool\n '''\n if position in self.positions:\n return True\n else:\n return False\n\n def pickJar(self, position):\n '''\n remove a jar from jars\n :param position: a position tuple such as (x, y)\n :type position: tuple\n :returs: None\n ..note:: pop a specific position in the list of jars\n '''\n if position in self.positions:\n self.jars.remove(position)\n else:\n raise Exception(\"Invaild Jar\")\n\n def isAllPicked(self):\n '''\n :returns: true if all jars are picked, else false\n :rtype: bool\n '''\n if len(self.jars) == 0:\n return True\n else:\n return False\n\n def getState(self, position):\n '''\n :param position: a position tuple such as (x, y)\n :type position: tuple\n :returns: the state of the position in the room, \n which can be one of 'wall' 'jar' and 'empty'\n :rtype: string\n \n here is a doctest\n :Example:\n >>> room_0 = Room(10,10)\n None\n >>> room_0.getState((9,9))\n 'empty'\n\n '''\n if position not in self.positions:\n return \"wall\"\n else:\n if position in self.jars:\n return \"jar\"\n else:\n return \"empty\"\n\n def reset(self):\n '''reset the room 1.clean the jars 2.reset the positions of jars'''\n self.jars = []\n self.jars = random.sample(\n self.positions, (self.width * self.length) // 2)\n\n\nclass Robot(object):\n '''\n init a robot with specific strategy, which could move in a room\n the robot could pick jars in the room and will get or lose score\n according to its action\n :attr direction: the action that a robot could take \n :attr status: possible status of the conditions around the robot\n :attr conditions: the combinations of the possible status around the robot\n :type direction: list of string\n :type status: list of string\n :type conditions: list\n '''\n direction = [\"up\", \"down\", \"left\", \"right\", \"stay\", \"random\", \"pick\"]\n status = [\"jar\", \"empty\", \"wall\"]\n _conditions = conditions\n\n def __init__(self, room, position=None, strategy=None):\n '''\n init a robot\n :param room: the room in which this robot is moving\n :param position: the init position of the robot\n :param strategy: the strategy of the robot on which the robot decide its action\n :type room: Room\n :type position: tuple\n :type strategy: dict\n ''' \n self.room = room\n if position is None:\n self.position = random.choice(room.positions)\n else:\n self.position = position\n if strategy is None:\n self.strategy = self.initStrategy()\n else:\n self.strategy = strategy\n self.score = 0\n\n def initStrategy(self):\n '''\n create a random strategy\n :returns: strategy\n :rtype: dict\n '''\n result = []\n for i in range(243):\n result.append(random.choice(self.direction))\n return dict(zip(Robot._conditions, result))\n\n def checkAround(self):\n '''\n check the condition around the robot\n :returns: the conditon around the robot which is a tuple of string\n :rtype: tuple\n '''\n position = self.position\n result = [\n (position[0], position[1] + 1),\n # up\n (position[0], position[1] - 1),\n # down\n (position[0] - 1, position[1]),\n # left\n (position[0] + 1, position[1]),\n # right\n position,\n # mid\n ]\n return tuple(result)\n\n def checkState(self):\n '''\n return the state around the position of robot\n :returns: the status\n :rtype: a tuple of string\n '''\n status = []\n around = self.checkAround()\n for i in range(len(around)):\n status.insert(i, self.room.getState(around[i]))\n return tuple(status)\n\n def checkStrategy(self):\n '''\n check the stategy of the robot\n and get the action according to the status\n :returns: the action\n :rtpye: string\n '''\n state = self.checkState()\n return self.strategy[str(state)]\n\n def move(self, direction):\n '''\n move robot to a specific direction\n if there is not a wall\n '''\n # this method is of functional programming style, a bit\n num = self.direction.index(direction)\n if num == 5:\n self.position = self.checkAround()[random.randint(0, 4)]\n elif num == 6:\n self.pick()\n else:\n if self.checkState()[num] != \"wall\":\n self.position = self.checkAround()[num]\n else:\n self.score -= 5\n\n def pick(self):\n '''\n pick the jar at the position of the robot\n and calculate the score\n '''\n if self.position in self.room.jars:\n self.room.pickJar(self.position)\n self.score += 10\n else:\n self.score -= 2\n\n def merge(self, other, init_position=(0, 0)):\n '''\n merge two robots and return a new robot which strategy was a mixture of its parents\n :param other: another robot\n :param init_position: the position where the offspring is born\n :type other: robot\n :type init_position: tuple\n :returns: a new robot\n :rtype: robot\n '''\n copy = self.strategy.copy()\n for key in copy:\n num = random.random()\n if num > 0.5:\n copy[key] = other.strategy[key]\n return Robot(self.room, init_position, copy)\n\n def mutate(self, mutate_odd):\n '''\n change some item of the strategy of the robot instance randomly\n :param mutate_odd: the odd of mutate\n :type mutate_odd: float \n :returns: a mixed strategy\n :rtype: dict\n '''\n copy = self.strategy.copy()\n keys = list(self.strategy.keys())\n mutatedKeys = random.sample(len(keys) * mutate_odd, keys)\n for key in mutatedKeys:\n copy[key] = random.choice(Robot.direction)\n return copy\n\n def run(self, test_amount=10, action_amount=200):\n '''\n let the robot instance constantly run specific times in the room \n refresh its score and repeat serveral times\n :param test_amount: the number of times a robot repeats running in the room\n :param action_amount: the number of times the robot runs \n :type test_amount: int\n :type action_amount: int\n :returns: the average score that a robot got in the test\n :rtype: int\n '''\n scores = []\n for i in range(test_amount):\n self.score = 0\n for j in range(action_amount):\n self.move(self.checkStrategy())\n scores.append(self.score)\n self.room.reset()\n return sum(scores) // len(scores)\n\n\nclass Population(object):\n '''\n a set or population of some robots \n which could select competitive member\n and reproduce next generation\n during which it evolves\n '''\n \n def __init__(self,\n population,\n action_amount,\n generation,\n ratio=0.1,\n pool=[],\n *,\n room=Room(10, 10),\n init_position=(0, 0)\n ):\n '''\n initailize a robot\n '''\n self.population = population\n self.room = room\n self.pool = pool\n if not self.pool:\n self.initPool()\n self.generation = generation\n self.lifetime = action_amount\n self.born_position = init_position\n self.survival_ratio = ratio\n\n def initPool(self):\n '''\n create a list of robots which represents the population of robots\n '''\n for i in range(self.population):\n self.pool.append(Robot(self.room))\n\n def run(self):\n '''\n invoke the run method of robot and test its score\n '''\n for rob in self.pool:\n rob.run()\n\n def select(self):\n '''\n select competitive robots in the population\n \n ..note:: add more code to save the data into the data base\n\n ..note:: below is the previous implmentation\n \n survivors = []\n rank = dict(zip([robot.run(self.lifetime)\n for robot in self.pool], self.pool))\n lis = list(rank.keys())\n lis.sort(reverse=True)\n print(len(rank))\n print(len(lis))\n for i in range(int(self.population * self.survival_ratio)):\n survivors.append(self.pool[i])\n '''\n def __getScore(instance):\n return instance.score\n self.pool.sort(key=__getScore, reverse=True)\n self.pool = self.pool[:int(self.population * self.survival_ratio)]\n # save pass\n\n def reproduce(self):\n '''\n reproduce the offspring of the population\n '''\n for rob in self.pool:\n rob.score = 0\n while len(self.pool) < self.population:\n parent = random.sample(self.pool, 2)\n self.pool.append(parent[0].merge(parent[1], self.born_position))\n\n def evolve(self):\n '''\n evolve the population\n '''\n for turn in range(self.generation):\n self.run()\n self.select()\n print(self.pool[0].score)\n self.reproduce()\n\n\nif __name__ == '__main__':\n import doctest\n print(__doc__)\n # doctest.testmod()\n '''\n _unit test code_\n '''\n # print(conditions,len(conditions))\n # print(Robot.initStrategy())\n room_1 = Room(10, 10)\n\n # print(room_1.jars)\n # print(room_1.isInRoom((9,9)))\n # print(len(room_1.jars))\n # print(room_1.pickJar(random.choice(room_1.jars)))\n # print(len(room_1.jars))\n # print(all([room_1.isInRoom(jar) for jar in room_1.jars]))\n # succeed!\n\n # while len(room_1.jars) != 0:\n # jar = random.choice(room_1.jars)\n # room_1.pickJar(jar)\n # print(room_1.isAllPicked())\n # succeed!\n\n # print(room_1.getState((9, 9)))\n # print(room_1.getState((0, 0)))\n # print(room_1.getState(random.choice(room_1.jars)))\n # succeed!\n\n # print(room_1.jars)\n # room_1.reset()\n # print(room_1.jars)\n # succeed!\n\n robot_1 = Robot(room_1)\n # print(robot_1.run(200))\n\n # print(dict(robot_1.strategy))\n # print(robot_1._conditions)\n # print(robot_1.direction)\n # print(robot_1.status)\n # succeed!\n # print(robot_1.checkAround())\n # print(robot_1.checkState())\n # succeed!\n # for i in range(10):\n # print(robot_1.checkStrategy())\n\n # print('initial position: {0}'.format(robot_1.position))\n # for d in robot_1.direction:\n # robot_1.move(d)\n # print(robot_1.position)\n # succeed!\n # while robot_1.room.jars:\n # robot_1.position = random.choice(robot_1.room.jars)\n # robot_1.pick()\n # print(len(robot_1.room.jars))\n # print(robot_1.getScore())\n # succeed!\n\n # robot_1.run()\n # print(robot_1.score)\n # robot_2 = Robot(room_1)\n # robot_3 = robot_1.merge(robot_2)\n # print(robot_1.strategy == robot_2.strategy)\n # print(robot_2.strategy == robot_3.strategy)\n # print(robot_3.strategy)\n print(robot_1.run())\n print(robot_1.mutate == robot_1.strategy)\n","sub_path":"init_class.py","file_name":"init_class.py","file_ext":"py","file_size_in_byte":13330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"256986688","text":"import sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, \\\n abort, render_template, flash, jsonify\n\nfrom .format_rows import *\n\napp = Flask(__name__)\napp.config.from_envvar('NAMEMAP_CONFIG_SETTINGS')\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n\"\"\"\nstatic urls\n\"\"\"\n@app.route(\"/\", methods=[\"GET\"])\ndef homepage():\n return render_template(\"home.html\")\n\n@app.route(\"/about\", methods=[\"GET\"])\ndef about():\n return render_template(\"about.html\")\n\n@app.route(\"/names\", methods=[\"GET\"])\ndef name_search():\n return render_template(\"namesearch.html\")\n\n\"\"\"\ndynamic urls\n\"\"\"\n@app.route(\"/name/,\", methods=[\"GET\"])\ndef name_page(name, gender):\n return render_template(\"name.html\", name=name, gender=gender)\n\n@app.route(\"/name/,/,\", methods=[\"GET\"])\ndef ranged_name_page(name, gender, low_year, high_year):\n return render_template(\"ranged_name.html\", name=name, gender=gender,\n low_year=low_year, high_year=high_year)\n\n@app.route(\"/multiname/\")\ndef multiname_page(names):\n return render_template(\"multiname.html\", names=names)\n\n@app.route(\"/year/\")\ndef year_page(year):\n total_query = \"\"\"SELECT count FROM years WHERE gender=? AND year=?\"\"\"\n year_query = \"\"\"SELECT name, count FROM yearnames WHERE gender=? AND year=? ORDER BY count DESC LIMIT 10\"\"\"\n\n male_total_statement = g.db.execute(total_query, (\"M\", year))\n male_total_tuple = male_total_statement.fetchone()\n male_total = male_total_tuple[0]\n\n female_total_statement = g.db.execute(total_query, (\"F\", year))\n female_total_tuple = female_total_statement.fetchone()\n female_total = female_total_tuple[0]\n\n male_statement = g.db.execute(year_query, (\"M\", year))\n male_rows = male_statement.fetchall()\n\n female_statement = g.db.execute(year_query, (\"F\", year))\n female_rows = female_statement.fetchall()\n\n return render_template(\"year.html\", year=year, male_total=male_total, female_total=female_total,\n male_names=male_rows, female_names=female_rows)\n\n@app.route(\"/compare/,/,\")\ndef compare_names(first_name, first_gender, second_name, second_gender):\n return render_template(\"compare.html\", first_name=first_name, first_gender=first_gender,\n second_name=second_name, second_gender=second_gender)\n\n\"\"\"\nAPI calls\n\"\"\"\n@app.route(\"/api/statename/,\")\ndef all_statename(name, gender):\n history_query = \"\"\"SELECT state, year, perthousand FROM statenames WHERE name=? AND gender=?\"\"\"\n statement = g.db.execute(history_query, (name, gender))\n rows = statement.fetchall()\n history = statename_history_dict(rows)\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/statename/,/,\")\ndef ranged_statename(name, gender, low_year, high_year):\n history_query = \"\"\"SELECT state, year, perthousand FROM statenames\n WHERE name=? AND gender=? AND year >= ? and year <= ?\"\"\"\n statement = g.db.execute(history_query, (name, gender, low_year, high_year))\n rows = statement.fetchall()\n history = statename_history_dict(rows)\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/yearname/,\")\ndef all_yearname(name, gender):\n history_query = \"\"\"SELECT year, count FROM yearnames WHERE name=? AND gender=?\"\"\"\n statement = g.db.execute(history_query, (name, gender))\n rows = statement.fetchall()\n history = [{\"year\": row[0], \"count\": row[1]} for row in rows]\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/yearname/,/,\")\ndef ranged_yearname(name, gender, low_year, high_year):\n history_query = \"\"\"SELECT year, count FROM yearnames\n WHERE name=? AND gender=? AND year >= ? AND year <= ?\"\"\"\n statement = g.db.execute(history_query, (name, gender, low_year, high_year))\n rows = statement.fetchall()\n history = [{\"year\": row[0], \"count\": row[1]} for row in rows]\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/multiname/states/\")\ndef multiname_statename(names):\n items = tuple(item for item in names.split(','))\n condition = \" OR \".join([\"(name=? AND gender=?)\"]*(len(items)//2))\n history_query = \"\"\"SELECT state, year, SUM(perthousand) FROM statenames WHERE %s GROUP BY state, year\"\"\" % condition\n statement = g.db.execute(history_query, items)\n rows = statement.fetchall()\n history = statename_history_dict(rows)\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/multiname/years/\")\ndef multiname_yearname(names):\n items = tuple(item for item in names.split(','))\n condition = \" OR \".join([\"(name=? AND gender=?)\"]*(len(items)//2))\n history_query = \"\"\"SELECT year, SUM(count) FROM yearnames WHERE %s GROUP BY year\"\"\" % condition\n statement = g.db.execute(history_query, items)\n rows = statement.fetchall()\n history = [{\"year\": row[0], \"count\": row[1]} for row in rows]\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/year/variety/\")\ndef year_name_variety(year):\n # total number of names per state in a given year\n variety_query = \"\"\"SELECT state, COUNT(*) FROM statenames WHERE year=? GROUP BY state\"\"\"\n # total number of babies born per state in a given year\n population_query = \"\"\"SELECT state, SUM(count) FROM stateyears WHERE year=? GROUP BY state\"\"\"\n\n statement = g.db.execute(variety_query, (year,))\n rows = statement.fetchall()\n\n pop_statement = g.db.execute(population_query, (year,))\n pop_rows = pop_statement.fetchall()\n # average number of babies per name in a given state\n history = {row[0][0]: row[1][1]/row[0][1] for row in zip(rows, pop_rows)}\n\n error = len(rows) == 0\n return jsonify(error=error, history=history)\n\n@app.route(\"/api/compare/states/,/,\")\ndef api_compare_state_names(first_name, first_gender, second_name, second_gender):\n history_query = \"\"\"SELECT state, year, perthousand FROM statenames WHERE name=? AND gender=?\"\"\"\n\n first_statement = g.db.execute(history_query, (first_name, first_gender))\n first_rows = first_statement.fetchall()\n first_dict = statename_history_dict(first_rows)\n\n second_statement = g.db.execute(history_query, (second_name, second_gender))\n second_rows = second_statement.fetchall()\n second_dict = statename_history_dict(second_rows)\n\n error = len(first_rows) == 0 and len(second_rows) == 0\n return jsonify(error=error, first=first_dict, second=second_dict)\n\n\n@app.route(\"/api/compare/years/,/,\")\ndef api_compare_year_names(first_name, first_gender, second_name, second_gender):\n history_query = \"\"\"SELECT year, count FROM yearnames WHERE name=? AND gender=?\"\"\"\n\n first_statement = g.db.execute(history_query, (first_name, first_gender))\n first_rows = first_statement.fetchall()\n first_names = [{\"year\": row[0], \"count\": row[1]} for row in first_rows]\n\n second_statement = g.db.execute(history_query, (second_name, second_gender))\n second_rows = second_statement.fetchall()\n second_names = [{\"year\": row[0], \"count\": row[1]} for row in second_rows]\n\n error = len(first_names) == 0 or len(second_names) == 0\n return jsonify(error=error, first=first_names, second=second_names)\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"namemap/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"212882983","text":"from django.test import LiveServerTestCase\nfrom django.contrib.auth import get_user_model\nfrom selenium import webdriver\nfrom .utils import create_test_data\n\n\nclass StaffTestCase(LiveServerTestCase):\n\n def setUp(self):\n\n self.browser = webdriver.Firefox()\n self.browser.implicitly_wait(2)\n\n self.admin_user = \\\n get_user_model().objects.create_superuser(\n username='bran',\n email='bran@eVantageGroup.com',\n password='august'\n )\n\n create_test_data()\n\n def tearDown(self):\n self.browser.quit()\n\n def test_staff_can_add_content(self):\n \"\"\"\n Tests that a 'staff' user can access the admin and\n add Albums, Tracks, and Solos\n \"\"\"\n # Bill would like to add a record and a number of\n # solos to JMAD. He visits the admin site\n admin_root = self.browser.get(\n self.live_server_url + '/admin/'\n )\n\n # He can tell he's in the right place because of the\n # title of the page\n self.assertEqual(self.browser.title,\n 'Log in | Django site admin')\n\n # He enters his username and password and submits the\n # form to log in\n login_form = self.browser.find_element_by_id(\n 'login-form')\n login_form.find_element_by_name('username'). \\\n send_keys('bran')\n login_form.find_element_by_name('password'). \\\n send_keys('august')\n login_form.find_element_by_css_selector(\n '.submit-row input').click()\n\n # He sees links to Albums, Tracks, and Solos\n albums_links = self.browser. \\\n find_elements_by_link_text('ALBUMS')\n inner_albums_links = self.browser. \\\n find_elements_by_link_text('Albums')\n albums_links.extend(inner_albums_links)\n self.assertEqual(\n albums_links[0].get_attribute('href'),\n self.live_server_url + '/admin/albums/'\n )\n self.assertEqual(\n albums_links[1].get_attribute('href'),\n self.live_server_url + '/admin/albums/album/'\n )\n\n self.assertEqual(\n self.browser. \\\n find_element_by_link_text('Tracks'). \\\n get_attribute('href'),\n self.live_server_url + '/admin/albums/track/'\n )\n solos_links = self.browser. \\\n find_elements_by_link_text('SOLOS')\n inner_solos_links = self.browser. \\\n find_elements_by_link_text('Solos')\n solos_links.extend(inner_solos_links)\n self.assertEqual(\n solos_links[0].get_attribute('href'),\n self.live_server_url + '/admin/solos/'\n )\n self.assertEqual(\n solos_links[1].get_attribute('href'),\n self.live_server_url + '/admin/solos/solo/'\n )\n\n # He clicks on Albums and sees all of the Albums that\n # have been added so far\n albums_links[1].click()\n self.assertEqual(\n self.browser.find_element_by_link_text(\n 'Know What I Mean?').get_attribute('href'),\n self.live_server_url + '/admin/albums/album/3/change/'\n )\n self.assertEqual(\n self.browser.find_element_by_link_text(\n 'Kind of Blue').get_attribute('href'),\n self.live_server_url + '/admin/albums/album/2/change/'\n )\n self.assertEqual(\n self.browser.find_element_by_link_text(\n 'My Favorite Things').get_attribute('href'),\n self.live_server_url + '/admin/albums/album/1/change/'\n )\n\n # Going back to the home page, he clicks the Tracks\n # link and sees the Tracks that have been added.\n # They're ordered first by Album, then by track\n # number.\n self.browser.find_element_by_css_selector(\n '#site-name a').click()\n self.browser.find_element_by_link_text('Tracks').click()\n\n track_rows = self.browser.find_elements_by_css_selector(\n '#result_list tr')\n self.assertEqual(track_rows[1].text,\n 'Kind of Blue Freddie Freeloader 2')\n self.assertEqual(track_rows[2].text,\n 'Kind of Blue Blue in Green 3')\n self.assertEqual(track_rows[3].text,\n 'Kind of Blue All Blues 4')\n self.assertEqual(track_rows[4].text,\n 'Know What I Mean? Waltz for Debby -')\n self.assertEqual(track_rows[5].text,\n 'My Favorite Things My Favorite Things -')\n\n # He adds a track to an album that already exists\n self.browser.find_element_by_link_text('ADD TRACK').click()\n\n track_form = self.browser.find_element_by_id('track_form')\n track_form.find_element_by_name('name').send_keys('So What')\n track_form.find_element_by_name('album'). \\\n find_elements_by_tag_name('option')[1].click()\n\n track_form.find_element_by_name('track_number'). \\\n send_keys('1')\n track_form.find_element_by_name('slug').send_keys('so-what')\n\n track_form.find_element_by_css_selector(\n '.submit-row input').click()\n self.assertEqual(\n self.browser.find_elements_by_css_selector(\n '#result_list tr')[1].text,\n 'Kind of Blue So What 1'\n )\n\n # He adds another track, this time on an album that is not in\n # JMAD yet\n self.browser.find_element_by_link_text('ADD TRACK').click()\n track_form = self.browser.find_element_by_id('track_form')\n track_form.find_element_by_name('name'). \\\n send_keys('My Funny Valentine')\n # After adding the basic Track info, he clicks on the plus\n # sign to add a new album.\n track_form.find_element_by_id('add_id_album').click()\n # The focus shifts to the newly opened window, where he sees\n # an Album form\n self.browser.switch_to.window(self.browser.window_handles[1])\n album_form = self.browser.find_element_by_id('album_form')\n album_form.find_element_by_name('name').send_keys('Cookin\\'')\n album_form.find_element_by_name('artist'). \\\n send_keys('Miles Davis Quintet')\n album_form.find_element_by_name('slug').send_keys('cookin')\n album_form.find_element_by_css_selector(\n '.submit-row input').click()\n\n # After adding the basic Track info, he clicks on the\n # plus sign to add a new album.\n # After creating the Album, he goes back to finish the Track\n self.browser.switch_to.window(self.browser.window_handles[0])\n track_form = self.browser.find_element_by_id('track_form')\n track_form.find_element_by_name('track_number'). \\\n send_keys('1')\n track_form.find_element_by_name('slug'). \\\n send_keys('my-funny-valentine')\n track_form.find_element_by_css_selector(\n '.submit-row input').click()\n self.assertEqual(\n self.browser.find_elements_by_css_selector(\n '#result_list tr'\n )[1].text,\n 'Cookin\\' My Funny Valentine 1'\n )\n\n # He goes back to the root of the admin site and clicks on\n # 'Solos'\n self.browser.find_element_by_css_selector(\n '#site-name a').click()\n self.browser.find_element_by_link_text('Solos').click()\n # He's sees Solos listed by Album, then Track, then start\n # time\n solo_rows = self.browser.find_elements_by_css_selector(\n '#result_list tr')\n self.assertEqual(solo_rows[1].text,\n 'All Blues Miles Davis 1:46-4:04')\n self.assertEqual(solo_rows[2].text,\n 'All Blues Cannonball Adderley 4:05-6:04')\n self.assertEqual(solo_rows[3].text.strip(),\n 'Waltz for Debby Cannonball Adderley -')\n self.assertEqual(solo_rows[4].text.strip(),\n 'My Favorite Things John Coltrane -')\n\n # He adds a Solo to a Track that already exists\n self.browser.find_element_by_link_text('ADD SOLO').click()\n solo_form = self.browser.find_element_by_id('solo_form')\n solo_form.find_element_by_name('track'). \\\n find_elements_by_tag_name('option')[7].click()\n solo_form.find_element_by_name('artist'). \\\n send_keys('McCoy Tyner')\n solo_form.find_element_by_name('instrument'). \\\n send_keys('Piano')\n solo_form.find_element_by_name('start_time'). \\\n send_keys('2:19')\n solo_form.find_element_by_name('end_time'). \\\n send_keys('7:01')\n solo_form.find_element_by_name('slug'). \\\n send_keys('mcoy-tyner')\n solo_form.find_element_by_css_selector(\n '.submit-row input').click()\n self.assertEqual(\n self.browser.find_elements_by_css_selector(\n '#result_list tr')[5].text,\n 'My Favorite Things McCoy Tyner 2:19-7:01')\n\n # He then adds a Solo for which the Track and Album\n # do not yet exist\n self.browser.find_element_by_link_text('ADD SOLO').click()\n solo_form = self.browser.find_element_by_id('solo_form')\n\n # He adds a Track from the Solo page\n solo_form.find_element_by_id('add_id_track').click()\n self.browser.switch_to.window(self.browser.window_handles[1])\n track_form = self.browser.find_element_by_id('track_form')\n track_form.find_element_by_name('name'). \\\n send_keys('In Walked Bud')\n\n # He adds an Album from the Track popup\n track_form.find_element_by_id('add_id_album').click()\n self.browser.switch_to.window(self.browser.window_handles[2])\n album_form = self.browser.find_element_by_id('album_form')\n album_form.find_element_by_name('name'). \\\n send_keys('Misterioso')\n album_form.find_element_by_name('artist'). \\\n send_keys('Thelonious Monk Quartet')\n album_form.find_element_by_name('slug'). \\\n send_keys('misterioso')\n album_form.find_element_by_css_selector(\n '.submit-row input').click()\n\n # He finishes up both parent objects, and saves the\n # Solo\n self.browser.switch_to.window(self.browser.window_handles[1])\n track_form = self.browser.find_element_by_id('track_form')\n track_form.find_element_by_name('track_number'). \\\n send_keys('4')\n track_form.find_element_by_name('slug'). \\\n send_keys('in-walked-bud')\n track_form.find_element_by_css_selector(\n '.submit-row input').click()\n\n self.browser.switch_to.window(self.browser.window_handles[0])\n solo_form = self.browser.find_element_by_id('solo_form')\n solo_form.find_element_by_name('artist'). \\\n send_keys('Johnny Griffin')\n solo_form.find_element_by_name('instrument'). \\\n send_keys('Tenor Saxophone')\n solo_form.find_element_by_name('start_time'). \\\n send_keys('0:59')\n solo_form.find_element_by_name('end_time'). \\\n send_keys('6:21')\n solo_form.find_element_by_name('slug'). \\\n send_keys('johnny-griffin')\n solo_form.find_element_by_css_selector(\n '.submit-row input').click()\n\n self.assertEqual(\n self.browser.find_elements_by_css_selector(\n '#result_list tr')[4].text,\n 'In Walked Bud Johnny Griffin 0:59-6:21'\n )\n","sub_path":"jmad/jmad/tests/test_staff_stories.py","file_name":"test_staff_stories.py","file_ext":"py","file_size_in_byte":11600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"636984217","text":"\"\"\"Xcs module for CLI.\n\n Typical usage example:\n\n xcs_command = XcsCommand()\n xcs_command.run()\n\"\"\"\nimport time\nfrom argparse import ArgumentParser, Namespace\nfrom timeit import default_timer\n\nfrom nwa.cli.base_command import BaseCommand\nfrom nwa.logger import LOGGER\n\n\nclass XcsCommand(BaseCommand):\n \"\"\"Initialise xcs command.\n\n Example:\n nwa xcs -f \n \"\"\"\n\n def __init__(self):\n super(XcsCommand, self).__init__()\n self.name = \"xcs\"\n\n def add_args(self, parser: ArgumentParser) -> None:\n parser.add_argument(\n \"-f\", \"--file\", required=True, help=\"The json file of the graph\",\n )\n\n parser.add_argument(\n \"-o\",\n \"--output\",\n required=False,\n default=time.strftime(\"%Y%m%d-%H%M%S\"),\n help=\"The filename to use as the output file\",\n )\n\n def validate_args(self, args: Namespace) -> None:\n \"\"\"Check command given argument, file.\n\n Requires a non-empty file.\n\n Raises:\n Exception: If file is not valid.\n \"\"\"\n return\n\n def execute(self, args: Namespace) -> None:\n start_time = default_timer()\n self.analyse(args.file, args.output)\n elapsed_time = default_timer() - start_time\n LOGGER.debug(f'Command \"{self.name}\" took {elapsed_time:.2f} seconds.')\n\n def analyse(self, file: str = \"\", output: str = \"\") -> None:\n \"\"\"Calls the xcs analysis with the provided graph data.\n\n Execute analysis, write output.\n\n Args:\n file: The graph file for the input of the command.\n output: The filename for the output of the command.\n \"\"\"\n raise NotImplementedError(\n f\"Method: analyse is undefined for command {self.name}\"\n )\n","sub_path":"nwa/cli/commands/xcs.py","file_name":"xcs.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362691852","text":"#!/usr/bin/python3.6\n# !-*- coding: utf-8 -*-\nfrom urllib.request import Request, URLError, HTTPError\nimport sys, os, socket, logging\nsys.path.append(os.path.dirname(__file__))\nfrom js_utils import Encryptor\nSalt = '1234qwer'\ndef initSys():\n # UTF-8\n if sys.getdefaultencoding() != 'utf-8':\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\n #System path\n sys.path.append(os.path.dirname(__file__))\n #pythonpath = os.getenv('PYTHONPATH')\n pythonpath = os.path.dirname(__file__)\n pythonpath = os.path.abspath(os.path.join(pythonpath, os.pardir))\n if pythonpath is not None:\n paths = pythonpath.split(':' if os.name=='posix' else ';')\n for path in paths:\n if not path in sys.path:\n sys.path.append(path)\n\n #socket timeout\n socket.setdefaulttimeout(30.0) \n\n pass\n\ndef httpRequest(opener, url):\n request = Request(url)\n try:\n response = opener.open(request, timeout=200)\n return response\n except URLError as e:\n print(e)\n logging.getLogger(\"app\").warn(e)\n except HTTPError as h:\n print(h)\n logging.getLogger(\"app\").warn(h)\n except socket.timeout as t:\n logging.getLogger(\"app\").warn(t)\n except:\n print (\"Unexpected error:\", sys.exc_info()[0])\n logging.getLogger(\"app\").warn('Unexpected error:', sys.exc_info()[0])\n\ndef money(string):\n import platform, locale\n if platform.system() == 'Windows':\n locale.setlocale(locale.LC_ALL, 'chs')\n else:\n locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')\n sym = locale.localeconv()['currency_symbol']\n if sym:\n string = string.replace(sym, '')\n ts = locale.localeconv()['thousands_sep']\n if ts:\n string = string.replace(ts, '') # next, replace the decimal point with a \n dd = locale.localeconv()['decimal_point']\n if dd:\n string = string.replace(dd, '.') # finally, parse the string\n return float(string) ","sub_path":"python3/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"514580392","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 26 17:49:15 2020\n\n@author: guiwe\n\"\"\"\n\n#%% Libraries Imported\n\n# Code written on Anaconda Spyder\n\n# Importing Python Libraries\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Machine Learning Libraries\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nimport eli5\nfrom eli5.sklearn import PermutationImportance\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import metrics\nfrom sklearn.externals.six import StringIO\nimport pydotplus\nfrom sklearn import tree\n\n# Geospatial Representation Libraries\n\nimport folium\n\n#%% Data Cleaning\n\n\n# Importing Pandas DataFrame from computer Library\n\ndf = pd.read_csv('Data-Collisions.csv')\n\ndf_original = df\n\n# Preparing DataFrame for Analysis\n\ncolumns = df.columns\n\ndf = df.drop(columns = ['OBJECTID','INCKEY','COLDETKEY','REPORTNO','STATUS',\n 'INTKEY','EXCEPTRSNDESC','EXCEPTRSNCODE','INCDATE',\n 'SDOTCOLNUM', 'SEGLANEKEY', 'CROSSWALKKEY'])\n\ndf['INCDTTM'] = pd.to_datetime(df['INCDTTM'], format = '%m/%d/%Y %I:%M:%S %p', errors = 'coerce')\n\ndf['TIME'] = df['INCDTTM'].dt.time\n\ndf['HOUR'] = df['INCDTTM'].dt.hour\n\ndf['DATE'] = df['INCDTTM'].dt.date\n\ndf['YEAR'] = df['INCDTTM'].dt.year\n\ndf = df.drop(columns = ['INCDTTM'])\n\n# Replace Categorical (non-numeric) with Numeric\n\ndf['UNDERINFL'] = df['UNDERINFL'].replace(to_replace = 'Y', value = 1)\ndf['UNDERINFL'] = df['UNDERINFL'].replace(to_replace = 'N', value = 0)\ndf['UNDERINFL'] = df['UNDERINFL'].replace(to_replace = '1', value = 1)\ndf['UNDERINFL'] = df['UNDERINFL'].replace(to_replace = '0', value = 0)\n\ndf['INATTENTIONIND'] = df['INATTENTIONIND'].replace(to_replace = np.nan, value = 0)\ndf['INATTENTIONIND'] = df['INATTENTIONIND'].replace(to_replace = 'Y', value = 1)\n\ndf['PEDROWNOTGRNT'] = df['PEDROWNOTGRNT'].replace(to_replace = np.nan, value = 0)\ndf['PEDROWNOTGRNT'] = df['PEDROWNOTGRNT'].replace(to_replace = 'Y', value = 1)\n\ndf['SPEEDING'] = df['SPEEDING'].replace(to_replace = np.nan, value = 0)\ndf['SPEEDING'] = df['SPEEDING'].replace(to_replace = 'Y', value = 1)\n\ndf['HITPARKEDCAR'] = df['HITPARKEDCAR'].replace(to_replace = 'N', value = 0)\ndf['HITPARKEDCAR'] = df['HITPARKEDCAR'].replace(to_replace = 'Y', value = 1)\n\n# Encoding the Categorical (non-numerical) columns to Numerical\n\nlabelencoder = LabelEncoder()\n\ndf = df.dropna() #subset = ['JUNCTIONTYPE','WEATHER','ROADCOND','LIGHTCOND','LOCATION','ADDRTYPE']\n\ndf = df.drop(df.index[(df['ROADCOND'] == 'Unknown') | (df['ROADCOND'] == 'Other')].tolist())\ndf = df.drop(df.index[(df['WEATHER'] == 'Unknown')])\ndf = df.drop(df.index[(df['LIGHTCOND'] == 'Unknown')])\ndf = df.drop(df.index[(df['JUNCTIONTYPE'] == 'Unknown')])\n\ndf['JUNCTIONTYPE'] = df['JUNCTIONTYPE'].apply(str)\ndf['COLLISIONTYPE'] = df['COLLISIONTYPE'].apply(str)\ndf['WEATHER'] = df['WEATHER'].apply(str)\ndf['ROADCOND'] = df['ROADCOND'].apply(str)\ndf['LIGHTCOND'] = df['LIGHTCOND'].apply(str)\ndf['ADDRTYPE'] = df['ADDRTYPE'].apply(str)\ndf['LOCATION'] = df['LOCATION'].apply(str)\n\ndf['JUNCTIONTYPE_CODE'] = labelencoder.fit_transform(df['JUNCTIONTYPE']).astype('int64')\ndf['COLLISIONTYPE_CODE'] = labelencoder.fit_transform(df['COLLISIONTYPE']).astype('int64')\ndf['WEATHER_CODE'] = labelencoder.fit_transform(df['WEATHER']).astype('int64')\ndf['ROADCOND_CODE'] = labelencoder.fit_transform(df['ROADCOND']).astype('int64')\ndf['LIGHT_CODE'] = labelencoder.fit_transform(df['LIGHTCOND']).astype('int64')\ndf['ADDRTYPE_CODE'] = labelencoder.fit_transform(df['ADDRTYPE']).astype('int64')\ndf['LOCATION_CODE'] = labelencoder.fit_transform(df['LOCATION']).astype('int64')\n\ndf['ST_COLCODE'] = df['ST_COLCODE'].astype('int64')\n\n# Creating a new Numeric DataFrame for analysis using Machine Learning\n\ndf2 = df\n\ndf2 = df2.drop(columns = ['LOCATION','SEVERITYDESC','COLLISIONTYPE',\n 'SDOT_COLDESC','WEATHER','ROADCOND',\n 'LIGHTCOND','ST_COLDESC','TIME','DATE',\n 'JUNCTIONTYPE','ADDRTYPE','X','Y'])\n\n# Creating Subsets of DataSet for Analysis\n\nPedestrian = df[(df['ST_COLCODE'] == 0) | # By location\n (df['ST_COLCODE'] == 1) | # Clear correlation between pedestrian right of way and intersection\n (df['ST_COLCODE'] == 2) | # Clear correlation between vehicle turning and intersection\n (df['ST_COLCODE'] == 3) | # Clear correlation between vehicle going straight and hitting pedestrian,\n (df['ST_COLCODE'] == 4) ] # this may be due to the fact that one vehicle grants right of passage and the other, unaware hits pedestrian.\n\n\ndf6 = Pedestrian.drop(columns = ['LOCATION','SEVERITYDESC','COLLISIONTYPE',\n 'SDOT_COLDESC','WEATHER','ROADCOND',\n 'LIGHTCOND','ST_COLDESC','TIME','DATE',\n 'JUNCTIONTYPE','ADDRTYPE','X','Y'])\n\nTrain = df[(df['ST_COLCODE'] == 40) | # Photo of location\n (df['ST_COLCODE'] == 41) |\n (df['ST_COLCODE'] == 42) |\n (df['ST_COLCODE'] == 43) ]\n\nBicycle = df[(df['ST_COLCODE'] == 44) | # By location\n (df['ST_COLCODE'] == 45) |\n (df['ST_COLCODE'] == 46) |\n (df['ST_COLCODE'] == 5) ]\n\ndf15 = Bicycle.drop(columns = ['LOCATION','SEVERITYDESC','COLLISIONTYPE_CODE',\n 'SDOT_COLDESC','WEATHER','ROADCOND',\n 'LIGHTCOND','ST_COLDESC','TIME','DATE',\n 'JUNCTIONTYPE','ADDRTYPE','X','Y'])\n\nObject = df[(df['ST_COLCODE'] == 50) |\n (df['ST_COLCODE'] == 51) |\n (df['ST_COLCODE'] == 52) ]\n\nAnimal = df[(df['ST_COLCODE'] == 47) |\n (df['ST_COLCODE'] == 48) |\n (df['ST_COLCODE'] == 49) ]\n\nMachinery = df[(df['ST_COLCODE'] == 60) | # By location\n (df['ST_COLCODE'] == 61) |\n (df['ST_COLCODE'] == 62) |\n (df['ST_COLCODE'] == 63) |\n (df['ST_COLCODE'] == 64) |\n (df['ST_COLCODE'] == 65) |\n (df['ST_COLCODE'] == 66) |\n (df['ST_COLCODE'] == 67) ]\n\nHazard = df[(df['ST_COLCODE'] == 54) | # low fire\n (df['ST_COLCODE'] == 55) ]\n\nDrugs = df[(df['UNDERINFL'] == 1)]\n\ndf_Drugs = Pedestrian.drop(columns = ['LOCATION','SEVERITYDESC','COLLISIONTYPE',\n 'SDOT_COLDESC','WEATHER','ROADCOND',\n 'LIGHTCOND','ST_COLDESC','TIME','DATE',\n 'JUNCTIONTYPE','ADDRTYPE','X','Y'])\n\nParking = df[(df['ST_COLCODE'] == 10) | # By locaiton & type\n (df['ST_COLCODE'] == 19) | # Clear correlation between midblock collisions\n (df['ST_COLCODE'] == 20) |\n (df['ST_COLCODE'] == 21) |\n (df['ST_COLCODE'] == 22) |\n (df['ST_COLCODE'] == 32)]\n\nOpposite_Direction = df[(df['ST_COLCODE'] == 24) | # Under influence of alcohol or drugs?\n (df['ST_COLCODE'] == 25) | # Left Turn and Intersection, Clear Correlation\n (df['ST_COLCODE'] == 26) |\n (df['ST_COLCODE'] == 27) |\n (df['ST_COLCODE'] == 28) |\n (df['ST_COLCODE'] == 29) |\n (df['ST_COLCODE'] == 30) ]\n\nSame_Direction = df[(df['ST_COLCODE'] == 71) | # Distraction?\n (df['ST_COLCODE'] == 72) |\n (df['ST_COLCODE'] == 73) |\n (df['ST_COLCODE'] == 74) |\n (df['ST_COLCODE'] == 81) |\n (df['ST_COLCODE'] == 82) |\n (df['ST_COLCODE'] == 83) |\n (df['ST_COLCODE'] == 84) ]\n\nBreaking_Parts = df[df['ST_COLCODE'] == 56]\n\nInnatention = df[df['INATTENTIONIND'] == 1] # Telephone?\n\nunknown = df['ROADCOND'].isnull().sum()\n\ncorrelation = df.corr()\n\n#%% Geospatial Plot Folium\n\n# Retrieving a sample of 600 points from the data, to plot on map\nlocation = df[['LOCATION','X','Y','SEVERITYCODE']].sample(600)\n\nseatle = folium.Map(location = [location.Y.mean(), location.X.mean()],\n zoom_start = 11.5)\n\nX_cord = location.X\n\nY_cord = location.Y\n\nseverity_code = location.SEVERITYCODE\n\nstreet_name = location.LOCATION\n\n# Creating a folium FeatureGroup\n\nfeature_group = folium.FeatureGroup('Locations')\n\nfor lat, long, loc, code in zip(Y_cord, X_cord, street_name, severity_code):\n\n if code == 1:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = loc,\n icon = folium.Icon(color = 'green', icon = 'info-sign')))\n else:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = loc,\n icon = folium.Icon(color = 'red', icon = 'info-sign')))\n\n# Saving map as an HTML\n\nseatle = seatle.add_child(feature_group)\n\nseatle = seatle.save('seatle_folium.html')\n\n#%% Speeding Correlations and Plots\n\n# Conditional probability P(Injury|Speeding)\n\nInjury_Speeding = df[(df['SEVERITYCODE.1'] == 2) & (df['SPEEDING'] == 1)] # P(Injury n Speeding)\n\nprob_1 = Injury_Speeding.shape[0]/df['SPEEDING'].sum() # P(Speeding)\n\n# Conditional probability P(Injury|Not Speeding)\n\nInjury_not_Speeding = df[(df['SEVERITYCODE.1'] == 2) & (df['SPEEDING'] == 0)] # P(Injury n Not Speeding)\n\nprob_2 = Injury_not_Speeding.shape[0]/(df.shape[0] - df['SPEEDING'].sum()) # P(Not Speeding)\n\n# Injury Prevalance by Location\n\ninjury_location = Injury_Speeding.groupby(['LOCATION'])['SPEEDING'].sum().sort_values(ascending = False).head(50) # Determining injury prevalance by location.\n\n# Plot of Speeding Categorised according to Road Condition and Light Condition\n\nbar_plot = df.groupby(['ROADCOND','LIGHTCOND']).sum()['SPEEDING'].unstack().fillna(0).plot(kind = 'bar', fontsize = 13, width = 1.0)\nplt.title('Speeding vehicle correlation with Road Condition and Lighting Condition')\nplt.xlabel('Road Condition')\nplt.ylabel('Number of Collisions (2004-2020)')\nplt.legend(loc = 10, fontsize = 'small', title = 'Light Condition')\nplt.show()\n\n# Plot of speeding prevalance against loaction (horizontal bar plot (barh))\n\ndf.groupby(['LOCATION'])['SPEEDING'].sum().sort_values(ascending = False).head(12).plot(kind = 'barh')\nplt.title('Locations with highest accounts of Speeding')\nplt.xlabel('Number of Incidents')\nplt.ylabel('Location Address')\nplt.show()\n\n# Heatmap of Speeding against Road Condition, Co-Ocurrance Matrix\n\ndf3 = df\n\ndf3['SPEEDING'] = df3['SPEEDING'].replace(0, 'No', regex = True)\ndf3['SPEEDING'] = df3['SPEEDING'].replace(1, 'Yes', regex = True)\n\ncorr_matrix_Speeding = pd.crosstab(index = df3.ROADCOND, columns = df3.SPEEDING)\n\nsns.heatmap(corr_matrix_Speeding, annot = True, cmap = 'Oranges', fmt = 'd')\nplt.title('Heatmap of Speeding against Road Condition (2004-2020)')\nplt.ylabel('Road Condition')\nplt.xlabel('Speeding')\nplt.show()\n\n#%% Accidents per time of Day Histogram\n\n# Histogram Time of Day Plot\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nfig = plt.hist(df3['HOUR'], bins = 50)\n# Plot Title and Labels\nplt.xlabel('Time of Day')\nplt.ylabel('Accidents')\nplt.title('Accidents per Time of Day')\nplt.xlim([0,23])\n# Major ticks every 6 minor ticks every 1\nmajor_ticks = np.arange(0, 25, 6)\nminor_ticks = np.arange(0, 25, 1)\nax.set_xticks(major_ticks)\nax.set_xticks(minor_ticks, minor=True)\n# And a corresponding grid\nax.grid(which='both')\n# Or if you want different settings for the grids:\nax.grid(which='minor', alpha=0.2)\nax.grid(which='major', alpha=0.5)\nplt.show()\n\n#%% Drugs and Alcohol Machine Learning\n\n\ndf_Drugs['UNDERINFL'] = df_Drugs['UNDERINFL'].replace(1, 'yes', regex = True)\ndf_Drugs['UNDERINFL'] = df_Drugs['UNDERINFL'].replace(0, 'no', regex = True)\n\ny = (df_Drugs['UNDERINFL'] == 'yes') # Converting to Binary\n\nfeature_names = [i for i in df_Drugs.columns if df_Drugs[i].dtype in [np.int64]]\n\nX = df_Drugs[feature_names]\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\nclf = RandomForestClassifier(n_estimators = 100, random_state = 0).fit(x_train, y_train)\n\nperm = PermutationImportance(clf, random_state = 1).fit(x_test, y_test)\n\nhtml_obj = eli5.show_weights(perm, feature_names = x_train.columns.tolist())\n\nwith open(\"drugs_and_alcohol_machine_learning.html\",\"wb\") as f:\n f.write(html_obj.data.encode(\"UTF-8\"))\n\n# max_depth can be established max_depth = () for the decision tree.\n\n# Calculating the RandomForestTree Error\n# Requires importing of new sklearn library\n # from sklearn.metrics import mean_absolute_error\n# pred = clf.predict(x_test)\n# error = mean_absolute_error(pred, y_test)\n\n#%% Co-Ocurrange Matrix (Heat Map) of Speeding against Alcohol\n\ndf3['UNDERINFL'] = df3['UNDERINFL'].replace(0, 'No', regex = True)\ndf3['UNDERINFL'] = df3['UNDERINFL'].replace(1, 'Yes', regex = True)\n\ncorr_matrix_Speeding = pd.crosstab(index = df3.UNDERINFL, columns = df3.SPEEDING)\n\n# Plot 1\n\nsns.heatmap(corr_matrix_Speeding, annot = True, cmap = 'YlGnBu_r', fmt = 'd')\nplt.title('Heatmap of Speeding and Alcohol/Drug Consumption (2004-2020)')\nplt.ylabel('Under Influence of Alcohol or Drugs')\nplt.xlabel('Speeding')\nplt.show()\n\n# Plot 2\n\ncorr_matrix_Speeding = pd.crosstab(index = df3.UNDERINFL, columns = df3.LIGHTCOND)\n\nsns.heatmap(corr_matrix_Speeding, annot = True, cmap = 'Blues', fmt = 'd')\nplt.title('Heatmap of Alcohol/Drug Consumption with Light Condition (2004-2020)')\nplt.ylabel('Under Influence of Alcohol or Drugs')\nplt.xlabel('Light Condition')\nplt.show()\n\n# Plot 3\n\ncorr_matrix_Speeding = pd.crosstab(index = df3.UNDERINFL, columns = df3.JUNCTIONTYPE)\n\nsns.heatmap(corr_matrix_Speeding, annot = True, cmap = 'Blues', fmt = 'd')\nplt.title('Heatmap of Alcohol/Drug Consumption with Junction Type (2004-2020)')\nplt.ylabel('Under Influence of Alcohol or Drugs')\nplt.xlabel('Junction Type')\nplt.show()\n\n\n\n#%% Accidents per time of Day Alcohol and Drugs\n\n# Recommended Police Blitz times\n\n# Histogram Time of Day Plot\nfig = plt.figure()\n\ndf20 = df3[df3['UNDERINFL'] == 'Yes']\ndf20['HOUR'] = df20['HOUR'].replace(0, 24, regex = True)\n\nax = fig.add_subplot(1, 1, 1)\nfig = plt.hist(df20['HOUR'], bins = 50)\n\n# Plot Title and Labels\nplt.xlabel('Time of Day')\nplt.ylabel('Drugs/Alcohol Accidents')\nplt.title('Drugs/Alcohol Accidents per Time of Day')\nplt.xlim([1,23])\n# Major ticks every 6 minor ticks every 1\nmajor_ticks = np.arange(0, 25, 6)\nminor_ticks = np.arange(0, 25, 1)\nax.set_xticks(major_ticks)\nax.set_xticks(minor_ticks, minor=True)\n# And a corresponding grid\nax.grid(which='both')\n# Or if you want different settings for the grids:\nax.grid(which='minor', alpha=0.2)\nax.grid(which='major', alpha=0.5)\nplt.show()\n\n#%% Alcohol and Drugs Geospatial Data\n\nalcohol_drugs = Drugs.groupby(['LOCATION','X','Y'])['VEHCOUNT'].count().sort_values(ascending=False).to_frame()\n\nalcohol_drugs = alcohol_drugs.reset_index()\n\nalcohol_drugs = alcohol_drugs[alcohol_drugs['VEHCOUNT'] > 5]\n\nalcohol_drugs['X'] = alcohol_drugs['X'].astype('float')\nalcohol_drugs['Y'] = alcohol_drugs['Y'].astype('float')\n\nX_cord = alcohol_drugs.X\n\nY_cord = alcohol_drugs.Y\n\nvehicle_count = alcohol_drugs.VEHCOUNT\n\npeople = folium.Map(location = [location.Y.mean(), location.X.mean()],\n zoom_start = 11.5)\n\n# Creating a folium FeatureGroup\n\nfeature_group = folium.FeatureGroup('people')\n\nfor lat, long, acc in zip(Y_cord, X_cord, vehicle_count):\n\n if 5 < acc < 8 :\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'green', icon = 'info-sign')))\n\n elif 8 < acc < 11:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'orange', icon = 'info-sign')))\n\n else:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'red', icon = 'info-sign')))\n\n# Saving map as an HTML\n\npeople = people.add_child(feature_group)\n\npeople = people.save('drugs_folium.html')\n\n#%% Decision Tree Alcohol and Drugs\n\ndf5 = df2\n\ndf5['UNDERINFL'] = df5['UNDERINFL'].replace(1, 'yes', regex = True)\ndf5['UNDERINFL'] = df5['UNDERINFL'].replace(0, 'no', regex = True)\n\n# Making the address type into binary data\ndf5 = df5.drop(df.index[(df['JUNCTIONTYPE'] == 2)])\n\n# Decision Tree Run Solely on Binary Data\nX = df5[['LIGHT_CODE','COLLISIONTYPE_CODE','JUNCTIONTYPE_CODE',\n 'WEATHER_CODE','ROADCOND_CODE','ADDRTYPE_CODE']].values\n\n\n# The comment box below indicates another decision tree possibility, for binary data\n# ['INATTENTIONIND','PEDROWNOTGRNT','SPEEDING','HITPARKEDCAR']\n\ny = df5['UNDERINFL']\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.3,\n random_state = 3)\n\n# Max depth established at max_depth = 4\n\ndrugTree = DecisionTreeClassifier(criterion = 'entropy', max_depth= 4).fit(x_train, y_train)\n\n# Testing the decision Tree Model with the x_test data\npredTree = drugTree.predict(x_test)\n\n# Both of the below metrics should yield the same score.\n# Validating the accuracy of the model by comparing the above prediction to the y_test (actual values)\naccuracy = metrics.accuracy_score(y_test, predTree)\n# Scoring the accuracy of the model.\nscore = drugTree.score(x_test, y_test)\n\n# Decision Tree\n\ndot_data = StringIO()\nfilename = 'drugtree.png'\nfeatureNames = ['LIGHT_CODE','COLLISIONTYPE_CODE','JUNCTIONTYPE_CODE',\n 'WEATHER_CODE','ROADCOND_CODE','ADDRTYPE_CODE']\n\ntargetNames = y.unique().tolist()\nout=tree.export_graphviz(drugTree,feature_names=featureNames,\n out_file=dot_data, class_names= np.unique(y_train),\n filled=True, special_characters=True, rotate=False)\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue())\ngraph.write_png(filename)\nimg = mpimg.imread(filename)\nplt.figure(figsize=(100, 200))\nplt.imshow(img,interpolation='nearest')\n\n#%% Pedestrian Machine Learning\n\n# Pedestrian Right of Passage\n\ndf6['PEDROWNOTGRNT'] = df6['PEDROWNOTGRNT'].replace(1, 'yes', regex = True)\ndf6['PEDROWNOTGRNT'] = df6['PEDROWNOTGRNT'].replace(0, 'no', regex = True)\n\ny = (df6['PEDROWNOTGRNT'] == 'yes') # Converting to Binary\n\nfeature_names = [i for i in df6.columns if df6[i].dtype in [np.int64]]\n\nX = df6[feature_names]\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\nclf = RandomForestClassifier(n_estimators = 100, random_state = 0).fit(x_train, y_train)\n\nperm = PermutationImportance(clf, random_state = 1).fit(x_test, y_test)\n\nhtml_obj = eli5.show_weights(perm, feature_names = x_train.columns.tolist())\n\nwith open(\"pedestrian_machine_learning.html\",\"wb\") as f:\n f.write(html_obj.data.encode(\"UTF-8\"))\n\n#%% Pedestrian Co-Ocurrance Matrix\n\n# Pedestrian Right of Passage and Collision Type\n\nPedestrian['PEDROWNOTGRNT'] = Pedestrian['PEDROWNOTGRNT'].replace(1, 'yes', regex = True)\nPedestrian['PEDROWNOTGRNT'] = Pedestrian['PEDROWNOTGRNT'].replace(0, 'no', regex = True)\n\ncorr_matrix = pd.crosstab(index = Pedestrian.ST_COLDESC, columns = Pedestrian.PEDROWNOTGRNT)\n\nsns.heatmap(corr_matrix, cmap = 'Blues', annot = True, fmt = 'd')\nplt.title('Heatmap of Pedestrian Right of Passage and Collision Type (2004-2020)')\nplt.ylabel('Collision Type')\nplt.xlabel('Pedestrian Right of Passage Granted')\nplt.show()\n\n# Pedestrian Right of Passage and Innatention\n\nPedestrian['INATTENTIONIND'] = Pedestrian['INATTENTIONIND'].replace(1, 'yes', regex = True)\nPedestrian['INATTENTIONIND'] = Pedestrian['INATTENTIONIND'].replace(0, 'no', regex = True)\n\ncorr_matrix = pd.crosstab(index = Pedestrian.INATTENTIONIND, columns = Pedestrian.PEDROWNOTGRNT)\n\nsns.heatmap(corr_matrix, cmap = 'Blues', annot = True, fmt = 'd')\nplt.title('Heatmap of Pedestrian Right of Passage and Inattentiveness Type (2004-2020)')\nplt.ylabel('Inattentiveness')\nplt.xlabel('Pedestrian Right of Passage Granted')\nplt.show()\n\n\n#%% Pedestrians Geospatial Plot\n\npedestrians = df.groupby(['LOCATION','X','Y'])['PEDCOUNT'].count().sort_values(ascending=False).to_frame()\n\npedestrians = pedestrians.reset_index()\n\npedestrians = pedestrians[pedestrians['PEDCOUNT'] > 60]\n\npedestrians['X'] = pedestrians['X'].astype('float')\npedestrians['Y'] = pedestrians['Y'].astype('float')\n\nX_cord = pedestrians.X\n\nY_cord = pedestrians.Y\n\npedstrian_count = pedestrians.PEDCOUNT\n\npeople = folium.Map(location = [location.Y.mean(), location.X.mean()],\n zoom_start = 11.5)\n\n# Creating a folium FeatureGroup\n\nfeature_group = folium.FeatureGroup('people')\n\nfor lat, long, acc in zip(Y_cord, X_cord, pedstrian_count):\n\n if 60 < acc < 100 :\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'lightgreen', icon = 'info-sign')))\n\n elif 99 < acc < 150:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'darkgreen', icon = 'info-sign')))\n\n elif 149 < acc < 200:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'orange', icon = 'info-sign')))\n\n else:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'red', icon = 'info-sign')))\n\n# Saving map as an HTML\n\npeople = people.add_child(feature_group)\n\npeople = people.save('pedestrian_folium.html')\n\nparking_spaces = df[df['LOCATION'] == 'AURORA AVE N BETWEEN N 130TH ST AND N 135TH ST']\n\nparking_spaces = parking_spaces.groupby(['ST_COLDESC'])['PEDCOUNT'].count().sort_values(ascending=False).to_frame()\n\n#should be analysed?\naccident = df[df['ST_COLDESC'] == 'From same direction - both going straight - one stopped - rear-end']\nabba = accident.PEDROWNOTGRNT.sum()\nalla = accident.PEDCOUNT.sum()\n\n\n# Innatention\ninnatentive = df.groupby(['LOCATION','X','Y'])['INATTENTIONIND'].sum().sort_values(ascending=False).to_frame()\n\n#%% Bicycle Geospatial Plot\n\nbicycle = df.groupby(['LOCATION','X','Y'])['PEDCYLCOUNT'].count().sort_values(ascending=False).to_frame()\n\nbicycle = bicycle.reset_index()\n\nbicycle['X'] = bicycle['X'].astype('float')\nbicycle['Y'] = bicycle['Y'].astype('float')\n\nbicycle = bicycle[bicycle['PEDCYLCOUNT'] > 60]\n\nX_cord = bicycle.X\n\nY_cord = bicycle.Y\n\nbicycle_count = bicycle.PEDCYLCOUNT\n\npeople = folium.Map(location = [Y_cord.mean(), X_cord.mean()],\n zoom_start = 11.5)\n\n# Creating a folium FeatureGroup\n\nfeature_group = folium.FeatureGroup('people')\n\nfor lat, long, acc in zip(Y_cord, X_cord, bicycle_count):\n\n if 60 < acc < 100 :\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'lightgreen', icon = 'info-sign')))\n\n elif 99 < acc < 150:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'darkgreen', icon = 'info-sign')))\n\n elif 149 < acc < 200:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'orange', icon = 'info-sign')))\n\n else:\n\n feature_group.add_child(folium.Marker(\n location = [lat,long], popup = acc,\n icon = folium.Icon(color = 'red', icon = 'info-sign')))\n\n# Saving map as an HTML\n\npeople = people.add_child(feature_group)\n\npeople = people.save('Bicycles.html')\n\n# Additional Analysis on Parking Spaces\n\n# parking_spaces = df[df['LOCATION'] == 'AURORA AVE N BETWEEN N 130TH ST AND N 135TH ST']\n\n# parking_spaces = parking_spaces.groupby(['ST_COLDESC'])['PEDCOUNT'].count().sort_values(ascending=False).to_frame()\n\n# #should be analysed?\n# accident = df[df['ST_COLDESC'] == 'From same direction - both going straight - one stopped - rear-end']\n# abba = accident.PEDROWNOTGRNT.sum()\n# alla = accident.PEDCOUNT.sum()\n\n\n# # Innatention\n# innatentive = df.groupby(['LOCATION','X','Y'])['INATTENTIONIND'].sum().sort_values(ascending=False).to_frame()\n\n\n#%% Heat Maps with Additional Corellations\n\n# Co-Occurance Matrix for non-numeric variables\n\ncorr_matrix = pd.crosstab(index = df.JUNCTIONTYPE, columns = df.SEVERITYDESC)\n\nsns.heatmap(corr_matrix, cmap = 'Blues', annot = True, fmt = 'd')\nplt.title('Heatmap of Severity against Junction Type (2004-2020)')\nplt.ylabel('Junction Type')\nplt.xlabel('Severity')\nplt.show()\n\nmid_block = df[(df['JUNCTIONTYPE'] == 'Mid-Block (not related to intersection)')\n & (df['SEVERITYDESC'] == 'Property Damage Only Collision')\n & (df['COLLISIONTYPE'] == 'Parked Car')]\n\nmid_parked = pd.crosstab(index = mid_block['LOCATION'], columns = df['HITPARKEDCAR']).sort_values(by = 1,ascending = False)\nmid_parked_2 = pd.crosstab(index = mid_block['SDOT_COLDESC'], columns = df['ST_COLDESC'])\n\n# Was the person on the telephone?\n\ninatention_pedest = df[df['LOCATION'] == 'N NORTHGATE WAY BETWEEN MERIDIAN AVE N AND CORLISS AVE N']\n\ncorr_matrix = pd.crosstab(index = df.PEDCOUNT, columns = df.INATTENTIONIND)\n\nsns.heatmap(corr_matrix, cmap = 'Blues', annot = True, fmt = 'd')\nplt.title('Heatmap of Pedestiran and Inattention (2004-2020)')\nplt.ylabel('Pedestrian Count')\nplt.xlabel('Inattention')\nplt.show()\n\n\n#%% Correlations Related to Tunnels\n\n# Co-Occurance Matrix for non-numeric variables\n\ncorr_matrix_2 = pd.crosstab(index = df.JUNCTIONTYPE, columns = df.SDOT_COLDESC)\n\nsns.heatmap(corr_matrix_2, cmap = sns.diverging_palette(220, 20, n=7))\n\nplt.show()\n\naddress_detailed = df.groupby(['LOCATION'])['X','Y'].mean()\n\nvehicles = df.groupby(['LOCATION'])['VEHCOUNT'].count().sort_values(ascending=False).head(20)\n\ntunnel_1 = df_original[df_original.LOCATION == 'BATTERY ST TUNNEL NB BETWEEN ALASKAN WY VI NB AND AURORA AVE N']\n\ntunnel_2 = df_original[df_original.LOCATION == 'BATTERY ST TUNNEL SB BETWEEN AURORA AVE N AND ALASKAN WY VI SB']\n\ntunnel = tunnel_1.append(tunnel_2)\n\ntunnel_type = tunnel.groupby(['ROADCOND'])['VEHCOUNT'].count()\n\nax = plt.subplot(111)\n\ntunnel_type.plot.barh()\n\nplt.show()\n\ncorr_matrix_3 = pd.crosstab(index = tunnel.SDOT_COLDESC, columns = tunnel.ROADCOND)\n\ntunnel_dry = tunnel[tunnel['ROADCOND'] == 'Dry'].groupby(['SPEEDING'])['VEHCOUNT'].count()\n\ndf5 = df\n\n#%% More Correlations, Plots, Testing, and Experimentation\n\n\ncrash_times = df5.groupby(['HOUR']).VEHCOUNT.sum()\n\ncrash_days = df5.groupby(['DATE']).VEHCOUNT.sum().sort_values(ascending = False)\n\ncurrent = df5.groupby(['DATE']).VEHCOUNT.sum().tail(200)\n\ncorr_matrix_6 = pd.crosstab(index = df5.HOUR, columns = df5.LIGHTCOND)\nsns.heatmap(corr_matrix_6, annot = True, cmap = sns.diverging_palette(220, 20, n=7), fmt = 'd')\nplt.show()\n\nlocation_streetlight = pd.crosstab(index = df5.LOCATION, columns = df5.LIGHTCOND)\n# It could be argued that there are less streats which lack street lighting, or it could be the case\n# that drivers are usually more cautious when street lighting is off, driving at a lower speed.\n\npedestrian_times = df5.groupby(['HOUR']).PEDCOUNT.sum()\n\nsns.catplot(x = 'HOUR', y = 'VEHCOUNT', data = df5, kind = 'violin')\n\nplt.show()\n\ncrash_year = df5.groupby(['YEAR']).VEHCOUNT.sum()\n\ncrash_year = crash_year.reset_index()\n\ncrash_year.plot.scatter(x = 'YEAR', y = 'VEHCOUNT')\n\nplt.show()\n\nmean = df5.groupby(['YEAR']).VEHCOUNT.sum().mean()\n\n\n# Annual Plot, does not add much to the investigation\n\ndf6 = df5[df5.YEAR != 2020]\ncrash_types = df6.groupby(['YEAR'])['VEHCOUNT','PEDCOUNT','PEDCYLCOUNT','PERSONCOUNT'].sum()\ncrash_types = crash_types.reset_index()\nfig = plt.figure()\nax = fig.add_subplot(111)\nw = 0.2\nax.bar(crash_types.YEAR - 0.4, crash_types.VEHCOUNT, width = w, align = 'center')\nax.bar(crash_types.YEAR - w, crash_types.PEDCOUNT, width = w, align = 'center')\nax.bar(crash_types.YEAR, crash_types.PEDCYLCOUNT, width = w, align = 'center')\nax.bar(crash_types.YEAR + w, crash_types.PERSONCOUNT, width = w, align = 'center')\nax.legend()\nax.autoscale()\nplt.legend()\nplt.show()\n\n\n\n\ndf2 = df.groupby(['WEATHER'])['VEHCOUNT'].max()\n\nax = plt.gca()\n\nax = df2.plot.barh()\n\nfor i, v in enumerate(df2):\n\n ax.text(v + 0, i - 0.1, str(v), color = 'blue', ha = 'left')\n\nplt.xlabel('Total Number of Vehicles involved in Collision')\n\nplt.show()\n","sub_path":"Python Scripts/Final Python Project.py","file_name":"Final Python Project.py","file_ext":"py","file_size_in_byte":28383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"243305131","text":"import os\nfrom multiprocessing import Pool, Queue, Process\n\nimport scipy\nimport utils\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom .BaseTrainer import BaseTrainer\nimport torch.nn.functional as F\n\n# from sklearn.metrics import f1_score, confusion_matrix, recall_score, jaccard_similarity_score, roc_curve, precision_recall_curve\n\nclass CNNTrainer(BaseTrainer):\n def __init__(self, arg, G, torch_device, recon_loss, val_loss, logger):\n super(CNNTrainer, self).__init__(arg, torch_device, logger)\n self.recon_loss = recon_loss\n self.val_loss=val_loss\n \n self.G = G\n self.optim = torch.optim.Adam(self.G.parameters(), lr=arg.lrG, betas=arg.beta)\n \n self.best_metric = 1.0\n\n self.sigmoid = nn.Sigmoid().to(self.torch_device)\n\n self.load()\n self.prev_epoch_loss = 0\n\n\n def save(self, epoch, filename=\"models\"):\n\n if os.path.exists(self.save_path) is False:\n os.mkdir(self.save_path)\n torch.save({\"model_type\" : self.model_type,\n \"start_epoch\" : epoch + 1,\n \"network\" : self.G.state_dict(),\n \"optimizer\" : self.optim.state_dict(),\n \"best_metric\": self.best_metric\n }, self.save_path + \"/%s.pth.tar\"%(filename))\n print(\"Model saved %d epoch\"%(epoch))\n\n\n def load(self, filename=\"models.pth.tar\"):\n if os.path.exists(self.save_path + \"/\" + filename) is True:\n print(\"Load %s File\"%(self.save_path)) \n ckpoint = torch.load(self.save_path + \"/\" + filename)\n if ckpoint[\"model_type\"] != self.model_type:\n raise ValueError(\"Ckpoint Model Type is %s\"%(ckpoint[\"model_type\"]))\n\n self.G.load_state_dict(ckpoint['network'])\n self.optim.load_state_dict(ckpoint['optimizer'])\n self.start_epoch = ckpoint['start_epoch']\n self.best_metric = ckpoint[\"best_metric\"]\n print(\"Load Model Type : %s, epoch : %d\"%(ckpoint[\"model_type\"], self.start_epoch))\n else:\n print(\"Load Failed, not exists file\")\n\n\n def train(self, train_loader, val_loader=None):\n print(\"\\nStart Train\")\n self.epoch=1500\n for epoch in range(self.start_epoch, self.epoch):\n for i, (input_, target_,_) in enumerate(train_loader):\n self.G.train()\n input_, target_= input_.to(self.torch_device), target_.to(self.torch_device)\n output_ = self.G(input_)\n recon_loss = self.recon_loss(output_, target_)\n\n #reg_loss = (torch.tensor(0).to(torch.float)).to(self.torch_device)\n #for param in self.G.parameters():\n # reg_loss +=param.norm(2)\n #factor = 0.00005\n #recon_loss += factor * reg_loss\n\n self.optim.zero_grad()\n recon_loss.backward()\n self.optim.step()\n \n if (i % 10) == 0:\n self.logger.will_write(\"[Train] epoch:%d loss:%f\"%(epoch, recon_loss))\n\n if val_loader is not None: \n self.valid(epoch, val_loader)\n else:\n self.save(epoch)\n print(\"End Train\\n\")\n\n def _test_foward(self, input_, target_):\n input_ = input_.to(self.torch_device)\n output_ = self.G(input_)\n target_ = target_\n input_ = input_\n\n return input_, output_, target_\n\n # TODO : Metric 정하기 \n def valid(self, epoch, val_loader):\n self.G.eval()\n with torch.no_grad():\n losssum=0\n count=0;\n for i, (input_, target_, _) in enumerate(val_loader):\n if (i >= val_loader.dataset.__len__()):\n break\n input_, target_= input_.to(self.torch_device), target_.to(self.torch_device)\n _, output_, target_ = self._test_foward(input_, target_)\n loss=self.val_loss(output_,target_)\n losssum=losssum+loss\n count=count+1\n\n if losssum/count < self.best_metric:\n self.best_metric = losssum/count\n self.save(epoch,\"epoch[%04d]_losssum[%f]\"%(epoch, losssum/count))\n\n self.logger.write(\"[Val] epoch:%d losssum:%f \"%(epoch, losssum/count))\n \n # TODO: Metric, save file 정하기\n def test(self, test_loader, savedir=None):\n print(\"\\nStart Test\")\n self.G.eval()\n\n if savedir==None:\n savedir='/result/test'\n else:\n savedir='/result/'+savedir\n\n if os.path.exists(self.save_path+'/result') is False:\n os.mkdir(self.save_path + '/result')\n if os.path.exists(self.save_path+savedir) is False:\n os.mkdir(self.save_path+savedir)\n\n with torch.no_grad():\n for i, (input_, target_, fname) in enumerate(test_loader):\n\n if(i>=test_loader.dataset.__len__()):\n #if (i >= 170):\n break\n\n output_ = self.G(input_)\n data={}\n coeff_mag=2000\n data['coeff_mag']=coeff_mag\n data['input']=(torch.squeeze(input_.type(torch.FloatTensor))).numpy()\n data['input']=data['input'].astype(np.uint8)\n data['output']=(torch.squeeze(output_.type(torch.FloatTensor))).numpy()\n data['output'] = (data['output']*coeff_mag).astype(np.int16)\n #data['target']=(torch.squeeze(target_.type(torch.FloatTensor))).numpy()\n scipy.io.savemat(self.save_path + savedir+\"/%s.mat\"%(fname[0][:-4]), data)\n self.logger.will_write(\"[Save] fname:%s \"%(fname[0][:-4]))\n print(\"End Test\\n\")\n","sub_path":"180907_3DcellSegmentation_regressionVer/trainers/CNNTrainer2.py","file_name":"CNNTrainer2.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"293007173","text":"import socket\n\ns = socket.socket()\n\nprint('socket created')\n\ns.bind(('localhost',9999))\n\ns.listen(3)\n\nprint('Waiting for the connection')\n\nwhile True:\n c,add = s.accept()\n name = c.recv(1024).decode()\n print('CLient connected',add,name)\n c.send(bytes(name,'utf-8'))\n c.send(bytes('You are now connected to the server'\n ' What would you like to do today'\n ' 1. Learn Python '\n '2. Order Food '\n '3. Others ','utf-8'))\n\n opt_rcvd = c.recv(1024).decode()\n if opt_rcvd == '1':\n response = 'Please refer to the Telusko Tutorial on Youtube'\n elif opt_rcvd == '2' :\n response = \"You can either use Swiggy or Zomato for the same. But you should avoid this\" \\\n \"during Corona spread. We encourage you to cook at home\"\n else:\n response = \"Sorry !! You should be studying right now\"\n\n c.send(bytes(response,'utf-8'))\n final_response = 'I hope i was helpful for you today'\n c.send(bytes(final_response,'utf-8'))\n\n c.close()","sub_path":"socketProgramming.py","file_name":"socketProgramming.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"297098134","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .forms import HelloForm\n\ndef index(request):\n params = {\n 'title':'Hello',\n 'message': 'your data:',\n 'form': HelloForm()\n }\n if (request.method == 'POST'):\n params['message'] = '名前:' + request.POST['name'] + \\\n '
メール:' + request.POST['mail'] + \\\n '
年齢:' + request.POST['age']\n params['form'] = HelloForm(request.POST)\n return render(request, 'hello/index.html', params)\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"220275143","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 4 15:46:50 2020\n\n@author: ppxsw1\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\n\nimport prot\nimport FT_1_1_module as FT\n#location = '/run/media/ppxsw1/78fe3857-1897-4617-a65e-83c9aa61be27/lambda_0/Tau_1-50/Delta_0-1500/'\n#location = '/run/media/ppxsw1/78fe3857-1897-4617-a65e-83c9aa61be27/Data_1_1/'\nlocation = '/run/media/ppxsw1/78fe3857-1897-4617-a65e-83c9aa61be27/long/'\ndef jackknife(data, block_length = 250):\n #takes a 1D array of real data (for example all the [i,j]th correlators from a single initialisation) and performs jackknife analysis on the mean\n number_of_blocks = int(data.size/block_length)\n mu = np.mean(data)\n blocked_data = np.reshape(data, (number_of_blocks, block_length))\n reduced_mu = np.zeros(number_of_blocks)\n for i in np.arange(number_of_blocks):\n reduced_mu[i] = np.mean(np.delete(blocked_data, i, axis = 0))\n error = np.sqrt((number_of_blocks - 1)*np.sum((reduced_mu - mu)**2)/number_of_blocks)\n return error\n\ndef observable(phi_data, header, p):\n #This is the observable you want to jam into the equation 26 from the below arxiv link\n #currently produces a matrix of correlators\n i_phi = np.reshape(phi_data, (prot.Nx, prot.Nrp))\n i_phi = i_phi[:, :(prot.Nt - 1)]\n init = np.reshape(header[1:(prot.Nx + 1)], (1, prot.Nx))\n i_phi = np.transpose(np.concatenate((init, np.transpose(i_phi)), axis = 0))\n phi_k = FT.ft(i_phi, p, prot.deltaX)\n phi_nk = FT.ft(i_phi, -1*p, prot.deltaX)\n phi_k = np.reshape(phi_k, (1, prot.Nt))\n phi_nk = np.reshape(phi_nk, (prot.Nt, 1))\n propogator = np.matmul(phi_nk, phi_k)\n return propogator\n\ndef calc_expectation_and_error(n_file):\n file_error = np.zeros((prot.Nx, prot.Nt), dtype = complex)\n #data location\n \n file_name = location + 'phi_' + str(n_file)\n #This is all just using pandas to load the CSV files, it's completely compatable with the outputs from the C++ code\n #It outputs it as a triplet of numpy arrays, header, aux_data, and phi_data\n data = pd.read_csv(file_name, header = None, skiprows = 1)\n header = np.array(np.array(pd.read_csv(file_name, sep='\\s+').keys())[0].split(','), dtype = float)\n data = np.array(data)\n aux_data = data[:, 2*prot.Nrt:]\n phi_data = data[:, :2*prot.Nrt]\n #This gets it from the CSV state of \"real, imag, real, imag\" to \"real + i*imag, real + i*imag\"\n temp = np.reshape(phi_data, (phi_data.shape[0], int(phi_data.shape[1]/2), 2))\n phi_data = temp[:, :, 0] + prot.j*temp[:, :, 1]\n\n #need to find the number of MC rows in the file\n number_of_iterations = phi_data.shape[0]\n #equation 26 in arxiv 1704.06404, |det J(0)| is ingored as it'll cancel between the numerator and the denominator\n phi_tilde = np.exp(aux_data[:, 2] + prot.j*aux_data[:, 3] - prot.j*aux_data[:, 1])\n denominator = np.mean(phi_tilde)\n numerator = np.zeros((number_of_iterations, prot.Nx, prot.Nt), dtype = complex)\n for q in np.arange(prot.Nx):\n p = np.sqrt(2*(1 - np.cos(q*2*np.pi/(prot.Nx*prot.deltaX))))\n for i in np.arange(number_of_iterations):\n Obs = observable(phi_data[i, :], header, p)\n #This calculates the expression fully for one initiatlisation\n F = np.diag(Obs)\n \n pi_pi = observable(np.gradient(phi_data[i, :], prot.deltaT), header, p)\n ddF = np.diag(pi_pi)\n w_squared = ddF/F\n c = np.sqrt(1 - 0.25*(prot.deltaT)**2*w_squared)\n numerator[i, q, :] = (c*np.sqrt(ddF*F) - 0.5)*phi_tilde[i]\n\n #error analysis for this file\n averaged_n = np.mean(numerator, axis = 0)/denominator\n return averaged_n\n\nn_files = 216\njackknife_block_length = 250\nexpectation_observable = np.zeros((n_files, prot.Nx, prot.Nt), dtype = complex)\nfile_error = np.zeros((n_files, prot.Nx, prot.Nt), dtype = complex)\nx_range = (np.arange(prot.Nt) + 1)*prot.deltaT\nn_threads = 2\np = Pool(n_threads)\noutput = p.map(calc_expectation_and_error, np.arange(n_files))\n\nfor i in np.arange(n_files):\n expectation_observable[i, :, :] = output[i]\nfinal_expectation = np.mean(expectation_observable, axis = 0)\nnp.save(\"expectation_observable\", expectation_observable)\n\nfor i in np.arange(prot.Nx):\n plt.figure(i)\n plt.title(r'$N_k$ $k = $' + str(i))\n plt.plot(x_range, np.real(final_expectation[i, :]).flatten(),'x')\n for j in np.arange(n_files):\n plt.plot(x_range, np.real(expectation_observable[j, 0, :]).flatten(), ',')\n plt.xlabel('t')\n plt.ylabel(r'$n(t)$')\n plt.savefig('scatter_n_'+str(i))\n \n \n","sub_path":"devsource/Correlators/data_scatterer_sans_error.py","file_name":"data_scatterer_sans_error.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91777328","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import NearestNeighbors\n\ndef find_nearest_neighbor(df_data,find_mem_from,find_mem_basedon,num_neighbors,day,window_size,sequence_by):\n day_range=day-np.flip(np.arange(window_size), 0)\n #To find the similar neigbor for training\n potential_member = df_data[find_mem_from].unique()\n dict_tmp = {k: v for v, k in enumerate(potential_member)}\n X = df_data[df_data[sequence_by].isin(day_range)].reset_index().pivot(index=find_mem_from,columns=sequence_by,values=find_mem_basedon)[day_range]\n X_index = X.index\n X = X.values\n\n nbrs = NearestNeighbors(n_neighbors=num_neighbors, algorithm='ball_tree').fit(X)\n distances, indices = nbrs.kneighbors(X)\n tmp_df = pd.DataFrame(indices)\n tmp_df = tmp_df.replace(dict_tmp)\n X = tmp_df.values \n \n return X\n\ndef get_train_data(df_data,find_mem_from,find_mem_basedon,sequence_by,window_size,num_neighbors,features_cols,target_label):\n x_train = []\n y_train = pd.DataFrame()\n for day in df_data.dayofyear.unique()[window_size-1:-1]:\n n_neighbor=find_nearest_neighbor(df_data,find_mem_from,find_mem_basedon,num_neighbors,day,window_size,sequence_by)\n# print(n_neighbor)\n day_range = day-np.flip(np.arange(window_size), 0)\n# print(day_range)\n df_tmp = df_data[df_data[sequence_by].isin(day_range)]\n\n \n for i in range(len(df_tmp[find_mem_from].unique())):\n x_tmp = df_tmp[df_tmp[find_mem_from].isin(n_neighbor[i])][features_cols] \n# print(x_tmp)\n for r in range(int(len(x_tmp)/num_neighbors)):\n for k in range(num_neighbors):\n if k ==0:\n row_num = r\n x_train.append(x_tmp.iloc[row_num].values)\n else:\n row_num +=window_size\n x_train.append(x_tmp.iloc[row_num].values)\n\n\n\n y_tmp = df_tmp[df_tmp[sequence_by].isin([day])][target_label]\n y_train = y_train.append(y_tmp,ignore_index=True)\n \n\n x_train = np.reshape(x_train,(len(df_data.dayofyear.unique()[window_size-1:-1])*window_size,window_size,num_neighbors*len(features_cols)))\n y_train = y_train.values\n \n return x_train,y_train ","sub_path":"pre_process.py","file_name":"pre_process.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"276486505","text":"import xml.etree.cElementTree as ET\nfrom xml.etree.ElementTree import tostring\nfrom util import *\n\n\ndef generaXmlViajesTransferencia():\n xmlstring = \"\"\n res = {}\n res[0] = False\n res[1] = \"\"\n\n tipo = \"IDL_VIAJES_TRANS_OR\"\n cx = creaConexion()\n\n cx[\"cur\"].execute(\"SELECT nombre FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n rows = cx[\"cur\"].fetchall()\n if len(rows) > 0:\n return True\n\n cx[\"cur\"].execute(\"INSERT INTO eg_fichprocesados (estado,hora,tipo,nombre,fecha) VALUES ('En proceso',CURRENT_TIME,'\" + tipo + \"','\" + tipo + \"',CURRENT_DATE)\")\n cx[\"conn\"].commit()\n\n try:\n prepOrd = ET.Element(\"preparation_orders\")\n int16 = ET.SubElement(prepOrd, \"int16\")\n\n cx[\"cur\"].execute(\"SELECT v.idviajemultitrans AS idviaje, v.codalmaorigen AS codalmaorigen, v.codalmadestino AS codalmadestino, v.fecha AS fecha FROM tpv_viajesmultitransstock v LEFT JOIN tpv_multitransstock m ON v.codmultitransstock = m.codmultitransstock INNER JOIN almacenesidl a ON v.codalmaorigen = a.codalmacen INNER JOIN almacenes d ON v.codalmadestino = d.codalmacen LEFT OUTER JOIN paises pa ON d.codpais = pa.codpais WHERE v.codalbarancd IS NULL AND (m.estado = 'Aceptado' OR m.estado IS NULL) AND v.fecha >= '2020-01-01' AND v.ptesincroenvio = true AND v.idviajemultitrans IN (SELECT idviajemultitrans FROM tpv_lineasmultitransstock WHERE idviajemultitrans = v.idviajemultitrans) AND v.estado = 'PTE ENVIO' AND v.codalmaorigen IN (SELECT codalmacen FROM almacenesidl) AND v.codalmadestino IN (SELECT codalmacen FROM almacenesidl) AND azkarok = false AND v.idviajemultitrans NOT IN (SELECT clave FROM idl_erroneos WHERE tipo = '\" + tipo + \"') ORDER BY v.idviajemultitrans LIMIT 1\")\n # and ag.codagenciaidl = 'DACHSER_02'selec\n\n rows = cx[\"cur\"].fetchall()\n idViaje = False\n if len(rows) > 0:\n for p in rows:\n idViaje = p[\"idviaje\"]\n\n faltaArticulos = False\n cx[\"cur\"].execute(\"SELECT l.referencia as reflinea, ia.referencia as refidl FROM tpv_lineasmultitransstock l LEFT JOIN idl_articulos ia ON l.referencia = ia.referencia WHERE l.idviajemultitrans = '\" + str(idViaje) + \"' AND ((ia.referencia IS NULL) OR (ia.referencia IS NOT NULL AND ia.ok = false)) GROUP BY l.referencia, ia.referencia\")\n rowsArt = cx[\"cur\"].fetchall()\n if len(rowsArt) > 0:\n faltaArticulos = True\n for art in rowsArt:\n print(art)\n if not art[\"refidl\"] or art[\"refidl\"] == \"\":\n cx[\"cur\"].execute(\"INSERT INTO idl_articulos (referencia,ok,idlog,fecha,hora,error) values ('\" + art[\"reflinea\"] + \"',false,NULL,CURRENT_DATE,CURRENT_TIME,'')\")\n cx[\"conn\"].commit()\n else:\n cx[\"cur\"].execute(\"UPDATE idl_articulos SET ok = false, idlog = NULL, fecha = CURRENT_DATE, hora = CURRENT_TIME, error = '' WHERE referencia = '\" + str(art[\"reflinea\"]) + \"'\")\n cx[\"conn\"].commit()\n\n print(\"registrando error para \" + str(art[\"reflinea\"]))\n registraError(tipo, idViaje, art[\"reflinea\"], cx)\n\n if faltaArticulos:\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n return True\n\n if not creaXmlEnvioViajeTransferenciaOrigen(p, int16, cx):\n print(\"No hay viajes con lineas que enviar\")\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n registraError(tipo, idViaje, \"No hay viajes con lineas que enviar\", cx)\n return False\n\n tree = ET.ElementTree(prepOrd)\n tree.write(\"./preparaciones/xmlViajesTransferencia_\" + idViaje + \".xml\")\n\n xmlstring = tostring(prepOrd, 'utf-8', method=\"xml\").decode(\"ISO8859-15\")\n #datosCX = dameDatosConexion(\"WSIDL_ENVPREP_TEST\", cx)\n datosCX = dameDatosConexion(\"WSIDL_ENVPREP\", cx)\n header = datosCX[\"header\"]\n url = datosCX[\"url\"]\n result = post_request(url, header, xmlstring)\n # result = \"GNSGNSOK\"\n print(result)\n\n status = False\n if not result:\n res[0] = False\n res[1] = result\n print(result)\n print(\"Error enviando pedido\")\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n return False\n else:\n res[0] = True\n res[1] = result\n\n root = ET.fromstring(result)\n child = root.find('int16/rub110')\n if child:\n status = child.find(\"status\").text\n\n tree = ET.ElementTree(root)\n tree.write(\"./preparaciones/resViajesTransferencia\" + idViaje + \".xml\")\n\n idlog = registraLog(\"ENV_TRANSF\", xmlstring, res, cx)\n if status:\n if status == \"OK\":\n cx[\"cur\"].execute(\"UPDATE tpv_viajesmultitransstock SET azkarok = true where idviajemultitrans = '\" + str(idViaje) + \"'\")\n cx[\"conn\"].commit()\n else:\n registraError(tipo, idViaje, \"Recepcion de respuesta \" + tipo + \" con error\", cx)\n # error = child.find(\"error_descriptions/error_description\").text\n # print(error)\n # cx[\"cur\"].execute(\"UPDATE pedidoscli SET fichero = 'ERROR: \" + str(idlog) + \"' where idpedido = \" + str(idPedido))\n else:\n print(\"No hay viajes que enviar\")\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n return True\n\n except Exception as e:\n res[0] = False\n res[1] = e\n print(e)\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n registraError(tipo, \"Exception\", e, cx)\n return False\n\n cx[\"cur\"].execute(\"DELETE FROM eg_fichprocesados WHERE tipo = '\" + tipo + \"'\")\n cx[\"conn\"].commit()\n cierraConexion(cx)\n generaXmlViajesTransferencia()\n return True\n\n\ndef creaXmlEnvioViajeTransferenciaOrigen(p, int16, cx):\n cx[\"cur\"].execute(\"SELECT barcode, cantpteenvio AS cantidad, idlinea, descripcion, numlinea FROM tpv_lineasmultitransstock WHERE cantidad > 0 AND idviajemultitrans = '\" + str(p[\"idviaje\"] + \"' AND cantpteenvio > 0\"))\n rows = cx[\"cur\"].fetchall()\n if len(rows) <= 0:\n return False\n\n sufijo = \"01\"\n\n rub110 = ET.SubElement(int16, \"rub110\")\n ET.SubElement(rub110, \"activity_code\").text = \"GNS\"\n ET.SubElement(rub110, \"physical_depot_code\").text = \"GNS\"\n ET.SubElement(rub110, \"originator_code\").text = \"EL_GANSO\"\n ET.SubElement(rub110, \"originator_reference\").text = \"V\" + p[\"idviaje\"]\n ET.SubElement(rub110, \"preparation_type_code\").text = \"010\"\n ET.SubElement(rub110, \"end_consignee_code\").text = dameAlmacenTransferencia(str(p[\"codalmadestino\"]))\n ET.SubElement(rub110, \"end_consignee_reference\").text = dameCodAlmacenTransferencia(str(p[\"codalmadestino\"]))\n ET.SubElement(rub110, \"planned_final_delivery_date_century\").text = str(p[\"fecha\"])[0:2]\n ET.SubElement(rub110, \"planned_final_delivery_date_year\").text = str(p[\"fecha\"])[2:4]\n ET.SubElement(rub110, \"planned_final_delivery_date_month\").text = str(p[\"fecha\"])[5:7]\n ET.SubElement(rub110, \"planned_final_delivery_date_day\").text = str(p[\"fecha\"])[8:10]\n\n rub111 = ET.SubElement(rub110, \"rub111\")\n ET.SubElement(rub111, \"activity_code\").text = \"GNS\"\n ET.SubElement(rub111, \"physical_depot_code\").text = \"GNS\"\n ET.SubElement(rub111, \"originator_code\").text = \"EL_GANSO\"\n ET.SubElement(rub111, \"originator_reference\").text = \"V\" + p[\"idviaje\"]\n ET.SubElement(rub111, \"preparation_order_reason_code\").text = \"TRA\"\n ET.SubElement(rub111, \"load_grouping\").text = \"TRANSFER\"\n\n \"\"\"rub11A = ET.SubElement(rub110, \"rub11A\")\n ET.SubElement(rub11A, \"activity_code\").text = \"GNS\"\n ET.SubElement(rub11A, \"physical_depot_code\").text = \"GNS\"\n ET.SubElement(rub11A, \"originator_code\").text = \"EL_GANSO\"\n ET.SubElement(rub11A, \"originator_reference\").text = \"V\" + p[\"idviaje\"] + sufijo\n ET.SubElement(rub11A, \"address_type_code\").text = \"010\"\n\n direccion = quitaIntros(str(p[\"direccion\"]))\n direccion1 = truncarDireccion(str(direccion).split(\" \"), 0, 35)\n direccion2 = truncarDireccion(str(direccion).split(\" \"), len(direccion1.split(\" \"))-1, 35)\n\n ET.SubElement(rub11A, \"name_or_company_name_in_address\").text = direccion1\n\n ET.SubElement(rub11A, \"street_and_number_and_or_po_box\").text = direccion1\n if len(direccion) > 35:\n ET.SubElement(rub11A, \"additional_addres_data_1\").text = direccion2\n\n ET.SubElement(rub11A, \"additional_address_data_2\").text = str(p[\"provincia\"])[0:35]\n ET.SubElement(rub11A, \"post_code_area_name\").text = str(p[\"ciudad\"])[0:35]\n ET.SubElement(rub11A, \"postal_code\").text = str(p[\"codpostal\"])[0:9]\n ET.SubElement(rub11A, \"iso_country_code\").text = str(p[\"codpais\"])[0:3]\n\n rub119 = ET.SubElement(rub110, \"rub119\")\n ET.SubElement(rub119, \"activity_code\").text = \"GNS\"\n ET.SubElement(rub119, \"physical_depot_code\").text = \"GNS\"\n ET.SubElement(rub119, \"originator_code\").text = \"EL_GANSO\"\n ET.SubElement(rub119, \"originator_reference\").text = \"V\" + p[\"idviaje\"] + sufijo\n ET.SubElement(rub119, \"comment_line_no\").text = \"1\"\n ET.SubElement(rub119, \"comment_group\").text = \"TRA\"\n ET.SubElement(rub119, \"comment\").text = \"UPS\"\"\"\n\n for l in rows:\n rub120 = ET.SubElement(rub110, \"rub120\")\n ET.SubElement(rub120, \"activity_code\").text = \"GNS\"\n ET.SubElement(rub120, \"physical_depot_code\").text = \"GNS\"\n ET.SubElement(rub120, \"originator_code\").text = \"EL_GANSO\"\n ET.SubElement(rub120, \"originator_reference\").text = \"V\" + p[\"idviaje\"]\n ET.SubElement(rub120, \"originator_reference_line_no\").text = str(int(l[\"numlinea\"]))\n ET.SubElement(rub120, \"item_code\").text = str(l[\"barcode\"])[0:16]\n ET.SubElement(rub120, \"item_lv_code\").text = \"11\"\n ET.SubElement(rub120, \"level_1_quantity_to_prepare\").text = str(int(l[\"cantidad\"]))\n ET.SubElement(rub120, \"owner_code_to_prepare\").text = dameCodAlmacenTransferencia(str(p[\"codalmaorigen\"]))\n ET.SubElement(rub120, \"grade_code_to_prepare\").text = \"STD\"\n\n return True\n\n\ndef dameAlmacenTransferencia(codAlmacen):\n print(\"CodAlmacen: \", codAlmacen)\n nombreAlmaDestino = \"\"\n if codAlmacen == \"IALS\":\n nombreAlmaDestino = \"ALSHAYA\"\n elif codAlmacen == \"IAND\":\n nombreAlmaDestino = \"ANDORRA\"\n elif codAlmacen == \"IAPE\":\n nombreAlmaDestino = \"APERTURAS\"\n elif codAlmacen == \"ICHI\":\n nombreAlmaDestino = \"CHILE\"\n elif codAlmacen == \"IMAY\":\n nombreAlmaDestino = \"MAYORISTA\"\n elif codAlmacen == \"IMEX\":\n nombreAlmaDestino = \"MEXICO\"\n elif codAlmacen == \"AIDL\":\n nombreAlmaDestino = \"PRINCIPAL\"\n elif codAlmacen == \"AWEB\":\n nombreAlmaDestino = \"E-COMMERCE\"\n\n return nombreAlmaDestino\n\n\ndef dameCodAlmacenTransferencia(codAlmacen):\n codAlmaDestino = \"\"\n if codAlmacen == \"IALS\":\n codAlmaDestino = \"ALS\"\n elif codAlmacen == \"IAND\":\n codAlmaDestino = \"AND\"\n elif codAlmacen == \"IAPE\":\n codAlmaDestino = \"APE\"\n elif codAlmacen == \"ICHI\":\n codAlmaDestino = \"CHI\"\n elif codAlmacen == \"IMAY\":\n codAlmaDestino = \"MAY\"\n elif codAlmacen == \"IMEX\":\n codAlmaDestino = \"MEX\"\n elif codAlmacen == \"AIDL\":\n codAlmaDestino = \"STD\"\n elif codAlmacen == \"AWEB\":\n codAlmaDestino = \"ECO\"\n\n return codAlmaDestino\n","sub_path":"peticionesidl/generaXmlViajesTransOrigen.py","file_name":"generaXmlViajesTransOrigen.py","file_ext":"py","file_size_in_byte":12343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"433424970","text":"import sys\r\ndef isPalindrome(s,i,j):\r\n if len(s)==1:\r\n return True\r\n while i Iterable[MethodInfo]:\r\n \"\"\"1 based\"\"\"\r\n in_model = False\r\n\r\n start = None\r\n name = None\r\n model = None\r\n # use start=1 to match line numbers in text editor\r\n for lineno, line in enumerate(lines, start=start_index):\r\n if line.startswith(f'class {ModelName}('):\r\n in_model = True\r\n continue\r\n\r\n if in_model:\r\n\r\n if is_class_or_module_level_statement(line):\r\n if start:\r\n yield MethodInfo(start, lineno - 1, name, model)\r\n start = None\r\n if line.startswith(' def '):\r\n start = lineno\r\n m = re.search(r'def (\\w+)\\((\\w+)', line)\r\n name = m.group(1)\r\n model = m.group(2)\r\n\r\n if is_module_level_statement(line):\r\n return\r\n\r\n\r\ndef is_class_or_module_level_statement(line):\r\n return line[:5].strip() and not line[:5].strip().startswith('#')\r\n\r\n\r\ndef is_module_level_statement(line):\r\n return line[:1].strip() and not line[:1].strip().startswith('#')\r\n\r\n\r\ndef get_method_offsets(txt, ClassName) -> List[Tuple[int, str]]:\r\n class_start, class_end = get_class_bounds(txt, ClassName)\r\n return [\r\n (m.start(), m.group(1))\r\n for m in re.finditer(r'^\\s{4}def (\\w+)\\(self\\b', txt, re.MULTILINE)\r\n if class_start < m.start() < class_end\r\n ]\r\n\r\n\r\ndef get_class_bounds(txt, ClassName):\r\n class_start = txt.index(f'\\nclass {ClassName}(')\r\n m = list(re.finditer(r'^\\w', txt[class_start:], re.MULTILINE))[1]\r\n class_end = class_start + m.start()\r\n return class_start, class_end\r\n\r\n\r\nBACKUP_FOLDER = '_REMOVE_SELF_BACKUP'\r\n\r\n\r\ndef backup(app_name):\r\n approot = Path(app_name)\r\n old_folder = Path(BACKUP_FOLDER)\r\n if not old_folder.exists():\r\n old_folder.mkdir()\r\n app_backup_dest = old_folder.joinpath(app_name)\r\n if not app_backup_dest.exists():\r\n shutil.copytree(approot, app_backup_dest)\r\n print_function(f'Your old files were saved to {BACKUP_FOLDER}/.')\r\n\r\n\r\ndef rearrange_folder(app_name):\r\n approot = Path(app_name)\r\n app_path = approot / '__init__.py'\r\n if not 'from otree.api' in app_path.read_text('utf8'):\r\n return\r\n print_function('Removing old files from', app_name)\r\n pages_path = approot / 'pages.py'\r\n models_path = approot / 'models.py'\r\n app_py_path = approot / 'app.py'\r\n if pages_path.exists():\r\n pages_path.unlink()\r\n if models_path.exists():\r\n models_path.unlink()\r\n if app_py_path.exists():\r\n app_py_path.unlink()\r\n _builtin = approot.joinpath('_builtin')\r\n if _builtin.exists():\r\n shutil.rmtree(_builtin)\r\n templates = approot.joinpath('templates', app_name)\r\n if templates.exists():\r\n copytree_py37_compat(templates, approot)\r\n shutil.rmtree(approot.joinpath('templates'))\r\n tests_noself = approot.joinpath('tests_noself.py')\r\n tests_path = approot.joinpath('tests.py')\r\n if tests_noself.exists():\r\n if tests_path.exists():\r\n tests_path.unlink()\r\n tests_noself.rename(tests_path)\r\n\r\n\r\ndef copytree_py37_compat(src, dst, symlinks=False, ignore=None):\r\n \"\"\"replacement for shutil.copytree(templates, approot, dirs_exist_ok=True)\"\"\"\r\n for item in os.listdir(src):\r\n s = os.path.join(src, item)\r\n d = os.path.join(dst, item)\r\n if os.path.isdir(s):\r\n shutil.copytree(s, d, symlinks, ignore)\r\n else:\r\n shutil.copy2(s, d)\r\n","sub_path":"otree_venv/lib/python3.8/site-packages/otree/cli/remove_self.py","file_name":"remove_self.py","file_ext":"py","file_size_in_byte":13817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"224593971","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.nn import TransformerEncoder, TransformerEncoderLayer\n\nimport spacy\nfrom collections import Counter\nfrom torchtext.vocab import Vocab # torchtext 0.9.0\n\nimport csv\nimport math\nimport pandas as pd\nfrom tqdm import tqdm\nfrom time import sleep\nimport matplotlib.pyplot as plt\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#%% manual seed\n# import numpy as np\n# import random\n# seed = 86\n# torch.manual_seed(seed)\n# torch.cuda.manual_seed(seed)\n# torch.cuda.manual_seed_all(seed)\n# np.random.seed(seed)\n# random.seed(seed)\n\n#%% Params\nPATH_TRAIN = \"news_data/train.csv\"\nPATH_TEST = \"news_data/test.csv\"\n\n# max_seq clips text tok, set max_seq to 0 for auto max text len\n# num_head has to be dividable to embed_dim (300)\n# without scheduler, lr = 1e-4 optimal, 1e-3 and higher will not train well\nMAX_SEQ = 15 # Just needs to be longer than sequence\nNUM_HID = 800 # 300*4\nNUM_HEAD = 10 #!\nNUM_LAYERS = 3 #! 2~3, over 4 will crash\nDROPOUT = 0.1 #! 0.1~0.3\n\nEPOCHS = 300\nLR = 8e-5\nBATCH_SIZE = 900\nCLIP_GRAD = 1\n\n#%% Dataset\nclass trainDataset(Dataset):\n def __init__(self, categories, label_list, titles):\n self.labels = [label_list.index(cat) for cat in categories]\n self.titles = titles\n\n def __len__(self):\n return len(self.titles)\n\n def __getitem__(self, i):\n text, text_len = self.titles[i]\n return (self.labels[i], text, text_len)\n\nclass testDataset(Dataset):\n def __init__(self, titles):\n self.titles = titles\n\n def __len__(self):\n return len(self.titles)\n\n def __getitem__(self, i):\n return self.titles[i]\n\ndef collate_train(batch):\n label_list, text_list, len_list = [], [], []\n for (label, text, text_len) in batch:\n len_list.append(text_len)\n label_list.append(label)\n text = torch.tensor(text, dtype=torch.int64)\n text_list.append(text)\n label_list = torch.tensor(label_list, dtype=torch.int64)\n text_list = torch.stack(text_list)\n return label_list.to(device), text_list.to(device), len_list\n\ndef collate_test(batch):\n text_list, len_list = [], []\n for (text, text_len) in batch:\n len_list.append(text_len)\n text = torch.tensor(text, dtype=torch.int64)\n text_list.append(text)\n text_list = torch.stack(text_list)\n return text_list.to(device), len_list\n\n#%% model\nclass PositionalEncoding(nn.Module):\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n\n\nclass TransformerNet(nn.Module):\n def __init__(self, embed_pretrain, padding_idx, max_sequence, n_hid, n_class, n_head=6, n_layers=2, dropout=0.5):\n \"\"\"\n n_tokens: vocab size\n embed_dim: size of vector for each token\n encoder: embedding matrix with size (n_tokens x embed_dim), can be imported from vocab\n\n n_class: number of classes to output\n n_head: number of attention heads for trans_encode\n n_hid: number of hidden nodes in NN part of trans_encode\n n_layers: number of trans_encoderlayer in trans_encode\n \"\"\"\n super(TransformerNet, self).__init__()\n self.encoder = nn.Embedding.from_pretrained(embed_pretrain).requires_grad_(True)\n self.embed_dim = embed_pretrain.shape[1]\n self.n_tokens = embed_pretrain.shape[0]\n self.pad_idx = padding_idx\n\n self.pos_enc = PositionalEncoding(self.embed_dim, dropout)\n\n encoder_layers = TransformerEncoderLayer(self.embed_dim, n_head, n_hid, dropout)\n self.trans_enc = TransformerEncoder(encoder_layers, n_layers)\n\n self.fc1 = nn.Sequential(\n nn.Dropout(dropout),\n nn.Tanh(),\n nn.Linear(self.embed_dim, self.embed_dim//4),\n # nn.BatchNorm1d(self.embed_dim//4),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(self.embed_dim//4, n_class),\n\n # nn.Linear(self.embed_dim, n_class),\n )\n\n def forward(self, x): # input: (batch, seq)\n # sm = self.generate_square_subsequent_mask(x.size(1)).to(device)\n km = self.get_padding_mask(x)\n\n x = torch.transpose(x, 0, 1) # (seq, batch)\n x = self.encoder(x) * math.sqrt(self.embed_dim) # (seq, batch, emb_dim)\n x = self.pos_enc(x) # (seq, batch, emb_dim)\n\n # x = self.trans_enc(x, mask=sm) # (seq, batch, emb_dim)\n x = self.trans_enc(x, src_key_padding_mask=km)\n # x = self.trans_enc(x)\n\n # pure fc\n # kmt = torch.transpose(km,0,1).unsqueeze(-1)\n # x = x*kmt\n # x = x[0]\n x = x.mean(dim=0) # (batch, emb_dim)\n x = self.fc1(x) # (batch, n_class)\n\n return x\n\n def generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def get_padding_mask(self, text):\n mask = (text != self.pad_idx).to(device) # (batch_size, word_pad_len)\n return mask\n\ndef init_weights(m):\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.zeros_(m.bias)\n\nclass CosineWarmupScheduler(optim.lr_scheduler._LRScheduler):\n def __init__(self, optimizer, warmup, max_iters):\n self.warmup = warmup\n self.max_num_iters = max_iters\n super().__init__(optimizer)\n\n def get_lr(self):\n lr_factor = self.get_lr_factor(epoch=self.last_epoch)\n return [base_lr * lr_factor for base_lr in self.base_lrs]\n\n def get_lr_factor(self, epoch):\n lr_factor = 0.5 * (1 + math.cos(math.pi * epoch / self.max_num_iters))\n if epoch <= self.warmup:\n lr_factor *= epoch * 1.0 / self.warmup\n return lr_factor\n\n#%% train\ndef train(df_train, df_test, label_list):\n\n# =============================================================================\n# text preprocess\n# =============================================================================\n print(\"Text Preprocessing...\", end=\"\")\n spacy_en = spacy.load('en_core_web_sm', disable=['parser'])\n\n def tokenizer(title, filter_ent):\n title = title.strip()\n title_doc = spacy_en(title)\n\n with title_doc.retokenize() as retokenizer:\n for ent in title_doc.ents:\n if ent.label_ in filter_ent:\n retokenizer.merge(title_doc[ent.start:ent.end], attrs={\"LOWER\": ent.label_})\n # retokenizer.merge(title_doc[ent.start:ent.end], attrs={\"LEMMA\": ent.label_})\n\n title_tok = [word.lower_ for word in title_doc if not word.is_punct]\n # title_tok = [word.lower_ for word in title_doc if not word.is_punct and not word.is_stop]\n # title_tok = [word.lower() if word not in filter_entity else word for word in title_tok]\n return title_tok\n\n filter_entity = [\"MONEY\", \"TIME\", \"PERCENT\", \"DATE\"]\n train_tok = [tokenizer(title, filter_entity) for title in df_train[\"Title\"]]\n test_tok = [tokenizer(title, filter_entity) for title in df_test[\"Title\"]]\n # specials = [\"\", \"\", \"\"]\n specials = [\"\", \"\"]\n specials.extend(filter_entity)\n\n counter = Counter()\n max_seq = MAX_SEQ\n for text_tok in train_tok:\n counter.update(text_tok)\n if MAX_SEQ == 0:\n if len(text_tok) > max_seq:\n max_seq = len(text_tok)\n\n for text_tok in test_tok:\n counter.update(text_tok)\n\n vocab = Vocab(counter, min_freq=1, vectors='glove.6B.300d', specials=specials)\n pad_idx = vocab[\"\"]\n embedding = vocab.vectors\n\n def text_pipeline(text_tok, max_seq):\n text_len = len(text_tok)\n if max_seq > text_len:\n # pad text seq with \n # text2 = [''] + text_tok + [''] * (max_seq - text_len - 1)\n text2 = text_tok + [''] * (max_seq - text_len)\n else:\n text2 = text_tok[:max_seq]\n text_len = len(text2)\n return [vocab[token] for token in text2], text_len\n\n train_list = [text_pipeline(text_tok, max_seq) for text_tok in train_tok]\n\n print(\"Done!\")\n\n# =============================================================================\n# make dataset and split to train and validation\n# =============================================================================\n data_train = trainDataset(df_train['Category'], label_list, train_list)\n\n print(\"Train data: %d, Train batches: %.1f\\n\" % \\\n (len(data_train), len(data_train)/BATCH_SIZE))\n\n trainloader = DataLoader(data_train, batch_size=BATCH_SIZE, shuffle=True, collate_fn=collate_train)\n\n # init model\n num_class = len(label_list)\n model = TransformerNet(\n embedding,\n padding_idx = pad_idx,\n max_sequence = max_seq,\n n_hid = NUM_HID,\n n_class = num_class,\n n_head = NUM_HEAD,\n n_layers = NUM_LAYERS,\n dropout = DROPOUT\n )\n model.apply(init_weights)\n model.to(device)\n\n criterion = torch.nn.CrossEntropyLoss()\n # ref: attention is all u need\n optimizer = optim.AdamW(model.parameters(), lr=LR,\n weight_decay=1e-6,\n betas=(0.9, 0.98))\n scheduler = CosineWarmupScheduler(optimizer=optimizer,\n warmup=10,\n max_iters=EPOCHS)\n\n# =============================================================================\n# train\n# =============================================================================\n print(\"Training...\")\n sleep(0.3)\n train_loss_hist, train_acc_hist = [], []\n\n t = tqdm(range(EPOCHS), ncols=200, bar_format='{l_bar}{bar:15}{r_bar}{bar:-10b}', unit='epoch')\n model.train()\n for epoch in t:\n train_loss, train_acc, train_count = 0, 0, 0\n batch_acc, batch_count = 0, 0\n for batch_id, (label, text, seq_len) in enumerate(trainloader):\n optimizer.zero_grad()\n\n out = model(text)\n loss = criterion(out, label)\n loss.backward()\n clip_grad_norm_(model.parameters(), CLIP_GRAD)\n optimizer.step()\n\n batch_acc = (out.argmax(1) == label).sum().item()\n batch_count = label.size(0)\n\n train_loss += loss.item()\n train_acc += batch_acc\n train_count += batch_count\n\n scheduler.step()\n\n train_loss = train_loss/train_count\n train_acc = train_acc/train_count*100\n\n tl_post = \"%2.5f\" % (train_loss)\n ta_post = \"%3.3f\" % (train_acc)\n t.set_postfix({\"T_Loss\": tl_post, \"T_Acc\": ta_post})\n t.update(0)\n\n train_loss_hist.append(train_loss)\n train_acc_hist.append(train_acc)\n\n # plot\n plt.figure()\n plt.plot(train_acc_hist, label=\"Train\")\n plt.title(\"Average Accuracy History\")\n plt.legend()\n plt.xlabel(\"Epochs\")\n plt.show()\n\n plt.figure()\n plt.plot(train_loss_hist, label=\"Train\")\n plt.title(\"Average Loss History\")\n plt.legend()\n plt.xlabel(\"Epochs\")\n plt.show()\n\n# =============================================================================\n# eval\n# =============================================================================\n print(\"Eval...\", end=\"\")\n # test_tok = [tokenizer(title, filter_entity) for title in df_test[\"Title\"]]\n test_list = [text_pipeline(text_tok, max_seq) for text_tok in test_tok]\n data_test = testDataset(test_list)\n testloader = DataLoader(data_test, batch_size=10, shuffle=False, collate_fn=collate_test)\n\n sleep(0.5)\n model.eval()\n ans_list = []\n with torch.no_grad():\n for batch_id, (text, seq_len) in enumerate(testloader):\n out = model(text)\n ans_list.extend(out.argmax(1).tolist())\n\n # print(len(ans_list))\n ans_labeled = [label_list[idx] for idx in ans_list]\n id_list = list(range(len(ans_list)))\n\n with open(\"output_transformer.csv\", \"w\", newline=\"\") as fp:\n fp.write(\"Id,Category\\n\")\n c_writer = csv.writer(fp)\n c_writer.writerows(zip(id_list, ans_labeled))\n\n print(\"Done!\")\n\n#%% main\nif __name__ == \"__main__\":\n df_train = pd.read_csv(PATH_TRAIN)\n df_test = pd.read_csv(PATH_TEST)\n label_list = sorted(list(set(df_train['Category'])))\n\n train(df_train, df_test, label_list)\n\n if str(device) == 'cuda':\n torch.cuda.empty_cache()\n\n","sub_path":"transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":13353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"262116710","text":"# -*- coding: utf-8 -*- \n# 爬取b站番剧信息\nimport requests\nfrom pyquery import PyQuery as pq \nimport json\nimport re\n\nclass Video(object):\n def __init__(self,name,see,intro):\n self.name = name \n self.see = see \n self.intro = intro \n def __str__(self):\n return f'''名称:{self.name}\\n播放量:{self.see}\\n简介:{self.intro}'''\n\nclass BiliCrawl(object):\n recent_url = \"https://bangumi.bilibili.com/api/timeline_v2_global\"\n detail_url = \"https://bangumi.bilibili.com/anime/{season_id}\"\n def __init__(self):\n self.dom = pq(requests.get(\"https://bangumi.bilibili.com/22/\").text)\n\n def get_recent(self,num):\n items = json.loads(requests.get(self.recent_url).text)['result']\n videos = []\n for i in items:\n name = i['title']\n # see = i['play_count']\n link = self.detail_url.format(season_id=i['season_id'])\n d = pq(requests.get(url=link).text)\n see = d('span.media-info-count-item.media-info-count-item-play > em').text()\n\n intro_js = d('body > script:first').text().lstrip('window.__INITIAL_STATE__=')\n intro_js = intro_js.rstrip('(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());')\n intro_js += '}'\n \n intro_json = json.loads(intro_js) #dict\n # print(type(intro_json))\n\n intro = intro_json['mediaInfo']['evaluate']\n intro = re.sub(r'\\t','',intro) \n #intro = d(sel).attr('content')\n videos.append(Video(name=name,see=see,intro=intro))\n if num == 0:\n for item in videos:\n print(item)\n else:\n with open('bili.txt','a',encoding='utf-8') as f:\n for item in videos[:num]:\n f.write(item.__str__()+'\\n\\n')\n print (\"结束\")\n\nif __name__ == '__main__':\n b = BiliCrawl()\n b.get_recent(6)\n\n","sub_path":"bili/bili.py","file_name":"bili.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"15487617","text":"#!usr/bin/env python\r\n#-*- coding:utf-8 _*-\r\n\"\"\"\r\n@author:47539\r\n@file: 2.py\r\n@time: 2020/6/4 23:17\r\n\"\"\"\r\n\r\n# 基本照搬课件上的示例代码\r\n\r\nimport socket\r\n\r\ndef reciever():\r\n udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n local_addr = ('127.0.0.1', 4869)\r\n # print(local_addr)\r\n udp_socket.bind(local_addr)\r\n\r\n recv_data = udp_socket.recvfrom(4048)\r\n\r\n print(recv_data)\r\n\r\n udp_socket.close()\r\n\r\nif __name__ == \"__main__\":\r\n reciever()","sub_path":"homework9/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609815957","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\ncities=['chicago','new york city','washington']\nmonths=['January', 'February', 'March', 'April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December','All']\ndays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Welcome! Let\\'s explore some US bikeshare data!')\n\n while True:\n city=str(input('What city you are interested in? Chicago, New York City or Washington? ')).lower()\n if city not in cities:\n print('Invalid city name')\n else:\n break\n\n while True:\n month=str(input('If you would like to filter by month, type out the month and if not, type out \"all\"\\n')).title()\n if month not in months:\n print('Invalid month name')\n else:\n break\n\n while True:\n day=str(input('If you would like to filter by month, type out the month and if not, type out \"all\"\\n')).title()\n if day not in days:\n print('Invalid day')\n else:\n break\n\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n \n df = pd.read_csv(CITY_DATA[city])\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n if month != 'All':\n month = months.index(month) + 1\n df = df[df['month'] == month]\n\n if day != 'All':\n df = df[df['day_of_week'] == day]\n\n return df\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month']= df['Start Time'].dt.month\n df['day_of_week']= df['Start Time'].dt.weekday_name\n \n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n \n month_mode=df['month'].mode()[0]\n print('The most common month: ' + months[month_mode-1])\n \n print('The most common day: ' + df['day_of_week'].mode()[0])\n \n df['hour'] = df['Start Time'].dt.hour\n print('The most common start hour: ' + format(df['hour'].mode()[0]))\n \n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n \n print('The most common start station: ' + df['Start Station'].mode()[0])\n \n print('The most common end station: ' + df['End Station'].mode()[0])\n \n most_common_combination = df['Start Station'].map(str) + ' to ' + df['End Station']\n print('The most popular combination: ' + most_common_combination.mode()[0])\n \n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n \n total_m, total_s = divmod(df['Trip Duration'].sum(), 60)\n total_h, total_m = divmod(total_m, 60)\n print ('Total travel time: ',total_h,' hours, ', total_m,' minutes, and ', total_s,' seconds.')\n \n mean_m, mean_s = divmod(df['Trip Duration'].mean(), 60)\n mean_h, mean_m = divmod(mean_m, 60)\n print ('Mean travel time: ',mean_h,' hours, ', mean_m,' minutes, and ', mean_s,' seconds.')\n \n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n \n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n \n print('The user can be broken down into \\n{}'.format(df['User Type'].value_counts()))\n \n if('Gender' not in df):\n print('Sorry! There is not any available gender data for this City')\n else:\n print('The genders are \\n{}'.format(df['Gender'].value_counts()))\n \n if ('Birth Year' not in df):\n print('Sorry! There is not any available gender data for this City')\n else:\n print('The Earliest birth year: {}'.format(df['Birth Year'].min()))\n print('The most recent birth year: {}'.format(df['Birth Year'].max()))\n print('The most common birth year: {}'.format(df['Birth Year'].mode()[0]))\n \n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n \ndef raw_data(df):\n\n print(df.head())\n num = 0\n while True:\n view_raw_data = input('\\nWant to view five row of raw data? Enter \"yes\" or \"no\"\\n')\n if view_raw_data.lower() != 'yes':\n return\n num = num + 5\n print(df.iloc[num:num+5])\ndef main():\n \n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n \n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n raw_data(df)\n\n \n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485274319","text":"\"\"\"\nThis module is built to keep track of all the machines connected to the server\n\"\"\"\nimport time\nimport datetime\nimport uuid\nfrom collections import deque\n\nfrom .hashmanager import *\n\n# Dictionary with the machine's UUID as the key\nmachines = {}\n\nclass Machine:\n \"\"\"\n Represents a single machine connected to the server.\n Calculates stats on the machine\n \"\"\"\n def __init__(self, instance_type):\n self.uuid = str(uuid.uuid4())\n self.workshares_complete = 0\n self.ipaddr = None\n self.lastcontacttime = None\n self.firstcontacttime = None\n self.workshares = {}\n self.hashes = 0\n self.hashrate = 0\n self.work_start = 0\n self.work_time = 0\n self.instance_type = instance_type\n\n def _calc_hashrate(self):\n \"\"\"\n Recalculate the hashrate and store it in self.hashrate\n \"\"\"\n uptime = self.uptime()\n # We haven't initialized yet\n if uptime is None:\n self.hashrate = 0\n\n now = time.time()\n # If we are currently working update the cummulative work time\n if self.work_start != 0:\n self.work_time += now - self.work_start\n self.work_start = now\n self.hashrate = self.hashes / self.work_time\n\n def complete_workshare(self, workshare_hash, start, num_hashes):\n \"\"\"\n Register completion of a workshare\n \"\"\"\n try:\n workshare = self.workshares[(workshare_hash, start)]\n except KeyError:\n return None\n\n self.workshares_complete += 1\n self.hashes += num_hashes\n self.contact()\n del self.workshares[(workshare_hash, start)]\n\n # We are no longer working, so we will update work_time and set\n # work_start to 0\n if len(self.workshares) == 0:\n self.work_time += time.time() - self.work_start\n self.work_start = 0\n self._calc_hashrate()\n\n def add_workshare(self, workshare):\n \"\"\"\n Assign a new workshare to this machine\n \"\"\"\n self.workshares[(workshare.hashstring, workshare.start)] = workshare\n # If we're not already working, then start\n if self.work_start == 0:\n self.work_start = time.time()\n\n def free_workshares(self):\n \"\"\"\n Recycle all currently active workshares on this machine\n \"\"\"\n for share in self.workshares.values():\n recycle_workshare(share)\n\n def contact(self):\n \"\"\"\"\n Register contact from this machine\n \"\"\"\n now = time.time()\n if self.firstcontacttime is None:\n self.firstcontacttime = now\n\n self.lastcontacttime = now\n\n def uptime(self):\n \"\"\"\n Calculate the time this machine has been up\n \"\"\"\n if self.firstcontacttime is None:\n return None\n return time.time() - self.firstcontacttime\n\n def lastcontact(self):\n \"\"\"\n Calculate the time since the last contact\n \"\"\"\n if self.lastcontacttime is None:\n return None\n return time.time() - self.lastcontacttime\n\n def to_dict(self):\n \"\"\"\n Return a dictionary representation of this object\n \"\"\"\n return {\n \"ip\": \"\" if self.ipaddr is None else self.ipaddr,\n \"uuid\":self.uuid,\n \"workshares\":self.workshares_complete,\n \"uptime\":_sec_to_string(self.uptime()),\n \"openshares\":len(self.workshares),\n \"hashrate\": \"%d hashes/s\" % self.hashrate,\n \"type\": instance_types[self.instance_type][0],\n \"lastcontact\": _sec_to_string(self.lastcontact())}\n\n# We have to import this here to prevent a circular dependency\nfrom .amazon import instance_types\n\n# Simple method for turning a time in seconds into a human friendly format\ndef _sec_to_string(seconds):\n if seconds is None:\n return \"Never\"\n minutes,seconds = divmod(seconds, 60)\n hours,minutes = divmod(minutes, 60)\n days,hours = divmod(hours, 24)\n returnstr = \"\"\n if days != 0:\n returnstr += \"%dd\" % days\n if hours != 0:\n returnstr += \"%dh\" % hours\n if minutes != 0:\n returnstr += \"%dm\" % minutes\n returnstr += \"%.0fs\" % seconds\n return returnstr\n","sub_path":"cloudbreaker/machines.py","file_name":"machines.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"495784125","text":"\n\nfrom xai.brain.wordbase.nouns._keel import _KEEL\n\n#calss header\nclass _KEELS(_KEEL, ):\n\tdef __init__(self,): \n\t\t_KEEL.__init__(self)\n\t\tself.name = \"KEELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"keel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_keels.py","file_name":"_keels.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"188411050","text":"from calendar import c\r\nfrom tkcalendar import Calendar\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom SendEmail import *\r\nimport time\r\nimport datetime\r\n#GUI\r\ndef CreateGUI():\r\n global frame\r\n frame = tk.Tk()\r\n frame.geometry('800x730')\r\n color = '#dcf3fa'\r\n frame.config(bg = color)\r\n global ToAddr\r\n ToAddr = Label(frame, text='Who is the receiver of this reminder?', bg= color, font='bold')\r\n ToAddr.pack()\r\n global TextField\r\n TextField = Entry(frame, bg= color, relief = 'solid')\r\n TextField.pack() \r\n global Reminder\r\n Reminder = Label(frame, text='What is the reminder?', bg= color, font='bold')\r\n Reminder.pack()\r\n global TextField1\r\n TextField1 = Entry(frame, bg= color, relief = \"solid\")\r\n TextField1.pack() \r\n global TimeDate\r\n TimeDate = Label(frame, text='When is the event/reminder?', bg= color, font='bold')\r\n TimeDate.pack()\r\n global calendar\r\n curr_year = datetime.datetime.now().year\r\n curr_month = datetime.datetime.now().month\r\n calendar = Calendar(frame, selectmode = 'day',\r\n year = curr_year, month = curr_month)\r\n calendar.pack(fill=\"both\", expand=True)\r\n global LargeMessage \r\n LargeMessage= Label(frame, text=\"Longer message:\")\r\n LargeMessage.pack()\r\n global TextField2\r\n TextField2 = Entry(frame, bg= color, width = 200, relief = \"solid\")\r\n TextField2.pack() \r\n B = Button(frame, text = \"OK\", command = Function)\r\n B.pack()\r\n frame.mainloop()\r\n\r\ndef Function():\r\n if len(TextField.get()) ==0 or len(TextField1.get()) == 0 or len(calendar.get_date()) == 0:\r\n global ErrorMessage\r\n ErrorMessage = Label(frame, text = \"Please input something in every field\")\r\n ErrorMessage.pack()\r\n else:\r\n PassedTest()\r\n\r\ndef PassedTest():\r\n date = calendar.get_date()\r\n big_mess = TextField2.get()\r\n SendEmail (TextField.get(), TextField1.get(), date, big_mess)\r\n time.sleep(2)\r\n frame.destroy()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n CreateGUI()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"392011329","text":"# -*- coding: utf-8 -*-\n\"\"\"\nОтображение состояния синхронизации по GPS или NTP.\n1. Текущее состояние синхронизации определяется двумя командами:\n ntpq -p\n ntptime\n Состояние:\n 1) Сервис ntpd не запущен\n >ntpq -p \n >ntpq: read: Connection refused\n 2) Часы синхронизированы\n ntpq -p в колонке remote адрес сервера начинается с '+' или '*' или 'o'\n в колонке reach 377\n ntptime returns code 0 (OK)\n offset - смещение относительно эталоного времени (мкс)\n 3) Синхронизируются\n a) ntpq -p в колонке remote адрес сервера начинается с ' '\n в колонке reach не 0, а в t не '-'\n b) с '+' или '*' или 'o'(PPS) \n ntptime returns code 5 (ERROR)\n в status'е UNSYNC\n 4) Нет связи с сервером\n A)\n >ntpq -p\n >Temporary failure in name resolution\n b) ntpq -p\n в колонке reach 0 в колонке t '-'\n\n\n2. Формат страницы:\nСинхронизация\n\n0. Синхронизация не используется.\n1'. Сервис ntpd не запущен.\n1\". Нет связи с сервером времени. Синхронизация невозможна.\n2. Часы синхронизированы.\nРасхождение с эталонным временем: NNNN мкс\n3. Связь установлена. Производится корректировка часов.\n\"\"\"\nimport web\nfrom config import render\nfrom utils import sync_mode\nfrom subprocess import Popen, PIPE\nfrom dotime import curPort, serverAddress\n\ntitle = 'Синхронизация'\n\ndef ntpqp():\n '''\n >ntpq -p\n >remote refid st t when poll reach delay offset jitter\n >=========================================================================\n >*ntp1.vniiftri.r .PPS. 1 u 6 16 377 11.941 0.040 0.371\n \n return , {} или '', {remote:, ...}\n '''\n err = ''\n res = {}\n par = ['ntpq', '-p']\n rcs = Popen(par, stdout = PIPE).communicate()[0].split('\\n')\n if len(rcs) < 3:\n err = rcs[0]\n else:\n res = dict(zip(rcs[0].split(), rcs[2].split()))\n return err, res\n\ndef ntptime():\n '''\n Берет из вывода команды ntptime\n код возврата ntp_gettime() и смещение ntp_adjtime()\n return code, offset\n '''\n par = ['ntptime']\n rcs = Popen(par, stdout = PIPE).communicate()[0].split('\\n')\n return rcs[0].split()[3], rcs[5].split()[1]\n\n\nclass SyncState:\n def GET(self):\n \"\"\"\n \"\"\"\n web.header('Cache-Control', 'no-store, no-cache, must-revalidate')\n web.header('Cache-Control', 'post-check=0, pre-check=0', False)\n web.header('Pragma', 'no-cache')\n \n text = []\n smode = sync_mode()\n if smode == 'manually':\n text.append(u'Синхронизация не используется.')\n else:\n if smode == 'gps':\n server = 'GPS (COM%d)' % curPort()\n else:\n server = serverAddress()\n err, pval = ntpqp()\n if err or not pval or (pval['t'] == '-' and pval['reach'] == '0'):\n text.append('Нет связи с ' + server +\n '. Синхронизация невозможна.')\n #if err:\n # text.append('Ошибка: ' + err)\n else:\n if pval['remote'][0] in ['+', '*', 'o']:\n code, offset = ntptime()\n if pval['reach'] == '377' and code == '0':\n text.append('Часы синхронизированы c ' + server + '.')\n text.append('Расхождение с эталонным временем: ' +\n offset + ' мкс')\n \n if not text:\n text.append('Связь установлена c ' + server + \n '. Производится корректировка часов.')\n return render.syncstate(text, title = title)\n","sub_path":"syncstate.py","file_name":"syncstate.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"200430472","text":"import os\nos.environ['https_proxy'] = ''\nos.environ['http_proxy'] = ''\n\nimport numpy as np\nimport pandas as pd\nimport os.path as osp\nimport pathlib\nfrom collections import deque\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom torch_geometric.data import Data, Batch, ClusterData\nfrom torch_geometric.utils.num_nodes import maybe_num_nodes\nimport torch_geometric.transforms as T\nfrom torch_geometric.datasets import Planetoid, CitationFull\nfrom torch_geometric.utils import to_networkx, from_networkx, subgraph\n\n\nimport networkx as nx\n\ndef get_connected_comp(dat):\n gg = to_networkx(dat, node_attrs=['x','y']).to_undirected()\n CGs = [gg.subgraph(c) for c in nx.connected_components(gg)]\n CG_big = sorted(CGs, key=lambda x: x.number_of_nodes(), reverse=True)[0]\n return from_networkx(CG_big)\n\ndef get_dataset(d_type, d_name, pth): \n path = osp.join(pathlib.Path().absolute(), pth , d_name)\n if d_type == 'full':\n dataset = CitationFull(path, d_name, transform=T.NormalizeFeatures())\n else:\n dataset = Planetoid(path, d_name, transform=T.NormalizeFeatures())\n \n # data = get_connected_comp(dataset[0])\n data = dataset[0]\n \n nparts = 3\n cluster_data = ClusterData(data, num_parts=nparts, recursive=False,\n save_dir=dataset.processed_dir)\n n_nodes = data.num_nodes\n b_point = cluster_data.partptr[2]\n row, col, edge_attr = cluster_data.data.adj.t().coo()\n new_edge_index = torch.stack([row, col], dim=0)\n\n adjacency = torch.full((data.num_nodes, data.num_nodes), False, dtype= torch.bool)\n adjacency[new_edge_index[0], new_edge_index[1]] = True\n\n train_data = Data(x=cluster_data.data.x[:b_point], \n edge_index=subgraph(torch.arange(b_point), new_edge_index )[0], \n y=cluster_data.data.y[:b_point])\n test_data = cluster_data[nparts-1] \n # test_data = Data(x=cluster_data.data.x[b_point:n_nodes], \n # edge_index=subgraph(torch.arange(b_point, n_nodes), new_edge_index )[0], \n # y=cluster_data.data.y[b_point:n_nodes])\n return train_data, test_data, adjacency, dataset[0]\n\ndef get_start(dat, b_size):\n inds, cnts = torch.unique(dat.edge_index, return_counts = True)\n sel = torch.argsort(cnts, descending=True)[:b_size*2]\n return inds[sel]\n\ndef tt_split_edges(dat):\n torch.manual_seed(0)\n train_test_ratio = 0.2\n\n row, col = dat.edge_index\n mask = row < col\n row, col = row[mask], col[mask]\n\n e_mask = torch.FloatTensor(row.shape[0]).uniform_() >train_test_ratio\n dat.train_test_mask = torch.cat((e_mask, e_mask))\n dat.edge_index = torch.cat( (torch.stack((row, col ), dim=1).T,\n torch.stack((col,row), dim=1).T), dim=1)\n return dat\n\ndef sample_bfs(nodes, num_hops, edge_index, num_nodes=None):\n edge_array = []\n graph_mask = []\n col, row = edge_index\n \n curr_mask = torch.full((num_nodes,), False, dtype=torch.bool)\n visited_mask = torch.full((num_nodes,), False, dtype=torch.bool)\n \n for ind, node_idx in enumerate(nodes):\n edges = []\n vmask = []\n curr_mask.fill_(False)\n visited_mask.fill_(False)\n visited_mask[node_idx] = True\n curr_mask[node_idx] = True\n for _ in range(num_hops): \n edge_mask = curr_mask[row] & ~visited_mask[col]\n curr_nodes = col[edge_mask]\n\n curr_mask.fill_(False) \n curr_mask[curr_nodes] = True \n \n vmask.append(visited_mask)\n visited_mask = visited_mask | curr_mask # add new to visited\n\n edges.append(edge_index[:,edge_mask] + num_nodes*ind) \n edge_array.append(edges)\n graph_mask.append(torch.stack(vmask))\n return edge_array, torch.stack(graph_mask)\n\ndef get_cora():\n d_name = 'Cora'\n# pth = '/home/eshikov/work/graph/graph-generation/graph_generation/data'\n pth = '/data/egor/graph_generation/graph_generation/data'\n path = osp.join(pathlib.Path().absolute(), pth , d_name)\n dataset = Planetoid(path, d_name, transform=T.NormalizeFeatures())\n gg = to_networkx(dataset[0], node_attrs=['x','y']).to_undirected()\n \n CGs = [gg.subgraph(c) for c in nx.connected_components(gg)]\n CG_big = sorted(CGs, key=lambda x: x.number_of_nodes(), reverse=True)[0]\n \n data = from_networkx(CG_big)\n r, c = data.edge_index\n adjacency = torch.full((data.num_nodes, data.num_nodes), False, dtype= torch.bool)\n adjacency[r, c] = True\n \n data.adj = adjacency\n return data, dataset[0]\n\n\ndef data_gen(data, adj, start_nodes, shuffle=True):\n n_hops = 7 \n batch_size = len(start_nodes)\n \n all_v = torch.arange(batch_size * data.num_nodes)\n\n edges_array, vm = sample_bfs(nodes=start_nodes, num_hops=n_hops, \n edge_index=data.edge_index,\n num_nodes = data.num_nodes)\n \n if shuffle:\n binds = []\n ind_q = deque(range(1, n_hops))\n for _ in range(batch_size):\n binds.append(list(ind_q))\n ind_q.rotate()\n binds = np.array(binds)\n else:\n binds = np.array([list(range(1, n_hops))]*batch_size)\n \n\n for i in range(n_hops-1):\n gr = [torch.cat(edges_array[j][:binds[j,i]], dim=1) for j in range(batch_size)]\n gr = torch.cat(gr, dim=1)\n e_1 = [edges_array[j][binds[j,i]] for j in range(batch_size)]\n e_1 = torch.cat(e_1, dim=1)\n\n v_in_graph = vm[torch.arange(batch_size), binds[:,i],:]\n v_1, _ = e_1\n v_1 = torch.unique(v_1) \n\n v_mask = ~v_in_graph.view((-1,))\n v_mask[v_1] = False\n v_0 = all_v[v_mask]\n i_0 = torch.randperm(v_0.shape[0])\n v_0 = v_0[i_0][:v_1.shape[0]]\n\n\n cc = v_1[torch.randint(len(v_1), (e_1.shape[1],))] \n v_graph = all_v[v_in_graph.view((-1,))]\n rr = v_graph[torch.randint(len(v_graph), (e_1.shape[1],))] \n e_0 = torch.stack((cc,rr))\n y_e_0 = adj[cc % data.num_nodes,rr % data.num_nodes].to(dtype=torch.float)\n\n yield torch.cat((gr, torch.flip(gr, dims=(0,))), dim=1), v_1, v_0, e_1, e_0, v_in_graph\n\ndef data_gen_edges(data, batch_size = 4, step = 8):\n istart = step\n n_edges = data.edge_index.shape[1]\n e_perm_edges = []\n for i in range(batch_size):\n e_perm_edges.append(data.edge_index[:,torch.randperm(n_edges)] + data.num_nodes *i)\n e_perm_edges = torch.stack(e_perm_edges)\n edge_index = torch.transpose(e_perm_edges, 0, 1)\n\n active_mask = torch.full((data.num_nodes * batch_size,), False, dtype=torch.bool)\n visited_mask = torch.full((data.num_nodes * batch_size,), False, dtype=torch.bool)\n nodes = torch.arange(batch_size*data.num_nodes)\n visited_mask[torch.flatten(edge_index[:,:,:istart])] = True \n\n for i in range(istart+step, n_edges, step):\n # ********* sampling edges\n graph = edge_index[:,:,:(i-step)]\n e_1 = edge_index[:,:,(i-step):i]\n\n # ********* node expansion\n active_mask.fill_(False) \n active_mask[torch.flatten(e_1)] = True \n v_exp_0_mask = visited_mask & ~active_mask # in graph but not expanding\n v_exp_1_mask = visited_mask & active_mask # in graph AND expanding\n n_e_1 = v_exp_1_mask.sum()\n v_exp_1 = nodes[v_exp_1_mask]\n v_exp_0 = nodes[v_exp_0_mask][:n_e_1]\n\n # ********* node additon\n v_add_1_mask = active_mask & ~visited_mask\n \n v_add_0_mask = ~visited_mask \n n_v_1 = v_add_1_mask.sum()\n v_left = nodes[v_add_0_mask]\n v_add_0 = v_left[torch.randperm(v_left.shape[0])][:n_v_1]\n v_add_1 = nodes[v_add_1_mask]\n # print(n_v_1, n_e_1)\n\n # ********* negative edges \n r1,c1 = e_1\n c0 = torch.zeros(size=c1.shape)\n c0[:, 0] = c1[:, -1]\n c0[:, 1:] = c1[:, :-1]\n e_0 = torch.stack( (r1,c0))\n \n yield graph.reshape((2,-1)), \\\n v_add_1_mask.view((batch_size, data.num_nodes)).sum(dim=1),\\\n torch.cat((v_exp_0,v_exp_1)),\\\n torch.cat((v_add_0,v_add_1)), \\\n torch.cat((e_0,e_1), dim=2).reshape((2,-1)).to(dtype = torch.long),\\\n visited_mask.view((batch_size, data.num_nodes))\n\n visited_mask = visited_mask | v_add_1_mask # add new to visited\n","sub_path":"src/data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":8430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"550749763","text":"from Node import Node\nfrom Router import Router\n\nclass Simulator:\n def __init__(self, fileName):\n self.open(fileName)\n self.paths = None\n\n def open(self, fileName):\n with open(fileName, 'r') as f:\n lines = f.read().split('#')[1:]\n\n in_nodes = lines[0].strip().split('\\n')[1:]\n in_routers = lines[1].strip().split('\\n')[1:]\n in_table = lines[2].strip().split('\\n')[1:]\n\n self.nodes = dict()\n self.routers = dict()\n\n for n in in_nodes:\n\n n = n.strip()\n name, mac, ip_pref, gateway = n.split(',')\n self.nodes[name] = Node(name, mac, ip_pref, gateway)\n \n for r in in_routers:\n\n r = r.strip()\n info = r.split(',')\n\n name = info[0]\n n_ports = int(info[1])\n \n self.routers[name] = Router(name, n_ports)\n\n for i in range(2,len(info),2):\n\n mac = info[i]\n ip_pref = info[i+1]\n port_num = (i-2) // 2\n\n self.routers[name].add_port(port_num, mac, ip_pref)\n\n for h in in_table:\n\n h = h.strip()\n name, next_hop, net, port = h.split(',')\n self.routers[name].add_hop(next_hop, net, port) \n\n def loadNodes(self, nodes):\n if len(nodes) >= 2:\n self.src = nodes[0]\n self.currentSrc = self.src\n self.dst = nodes[-1]\n self.btw = nodes[1:-1]\n self.paths = [self.src] + self.btw + [self.dst]\n\n def simulate(self):\n if self.paths == None:\n print(\"Invalid number of nodes to simulate\")\n self.simulatePackages()\n\n def simulatePackages(self):\n packages = [(self.paths[i], self.paths[i+1]) for i in range(len(self.paths)-1)]\n for src, dest in packages:\n self.currentSrc = src\n if (dest == self.dst):\n self.sendBackPackage(resp)\n\n def sendBackPackage(self, response):\n if response == True:\n self.currentSrc = self.paths[-1]\n self.sendPackage(self.paths[-1], self.paths[0], 8, False, True)\n else:\n self.currentSrc = response\n self.sendPackage(response, self.src, 8, True, False)\n\n \n def sendPackage(self, src, dest, ttl, timeout = False, ret = False):\n # ARP Request\n # Identify nodes and routers to broadcast and call hasIP for all of them\n if ttl == 0:\n return src\n srcIp = self.nodes[self.currentSrc].ip if self.currentSrc in self.nodes else self.routers[self.currentSrc].ports[self.routers[self.currentSrc].last_port].ip\n srcNode = self.nodes[src] if src in self.nodes else self.routers[src]\n destNode = self.nodes[dest]\n retName = self.arp_request(srcNode, destNode)\n if timeout:\n srcNode.icmp_time_exceeded(retName, srcIp, destNode.ip, ttl)\n ttl -= 1\n if retName != dest:\n return self.sendPackage(retName, dest, ttl, final, timeout, ret)\n return True\n if not ret:\n srcNode.icmp_request(retName, srcIp, destNode.ip, ttl)\n else:\n srcNode.icmp_reply(retName, srcIp, destNode.ip, ttl)\n ttl -= 1\n if retName != dest:\n return self.sendPackage(retName, dest, ttl, timeout, ret)\n return True\n \n def getNodeByIP(self, ip):\n return any([node.ip == ip for node in self.nodes.values()])\n\n def arp_request(self, srcNode, destNode):\n target = destNode.ip if srcNode.isOfGroup(destNode.group) else srcNode.gateway if type(srcNode) == Node else srcNode.router_table['0.0.0.0/0'][0]\n resp = srcNode.isInArpTable(target)\n if resp != None:\n return resp\n srcNode.arp_request(target)\n if self.getNodeByIP(target):\n for node in self.nodes:\n if srcNode.isOfGroup(self.nodes[node].group) and self.nodes[node] != srcNode:\n name = self.nodes[node].hasIP(target, srcNode)\n if name != None:\n return name\n else:\n for router in self.routers:\n name = self.routers[router].hasIP(target, srcNode)\n if name != None:\n return name\n return None","sub_path":"Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499380617","text":"import numpy as np\r\n\r\nfrom sklearn.cross_validation import ShuffleSplit\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\ndef eval_model(models, X, y):\r\n\t'''\r\n\tTakes in an array of models , fit each of the model on the training examples given\r\n\tCalculates 5-fold cross validation\r\n\t'''\r\n\tcv = ShuffleSplit(len(y), n_iter=5, test_size=0.3)\r\n\r\n\tscores = []\r\n\tfor train, test in cv:\r\n\t\tscores_combined = np.zeros(len(test))\r\n\r\n\t\tfor clf in models:\r\n\t\t\tX_train, y_train = X.iloc[train], y.iloc[train]\r\n\t\t\tX_test, y_test = X.iloc[test], y.iloc[test]\r\n\t\t\tclf.fit(X_train, y_train)\r\n\t\t\trelevance = clf.predict(X_test)\r\n\t\t\tprint(\"score: %f\" % np.sqrt(mean_squared_error(y_test, relevance)))\r\n\t\t\tscores_combined += relevance\r\n\r\n\t\tscores_combined /= len(models) * 1.\r\n\t\tscores.append(np.sqrt(mean_squared_error(y_test, scores_combined)))\r\n\t\tprint(\"combined score: %f\" % scores[-1])\r\n\r\n\treturn (np.mean(scores), np.std(scores))","sub_path":"Home-Depot/scripts/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"472075753","text":"# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import annotations\n\nimport itertools\nimport logging\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom typing import Dict, Iterable, Optional\n\nfrom pants.backend.python.dependency_inference import module_mapper, parse_python_dependencies\nfrom pants.backend.python.dependency_inference.default_unowned_dependencies import (\n DEFAULT_UNOWNED_DEPENDENCIES,\n)\nfrom pants.backend.python.dependency_inference.module_mapper import (\n PythonModuleOwners,\n PythonModuleOwnersRequest,\n ResolveName,\n)\nfrom pants.backend.python.dependency_inference.parse_python_dependencies import (\n ParsedPythonAssetPaths,\n ParsedPythonDependencies,\n ParsedPythonImports,\n ParsePythonDependenciesRequest,\n)\nfrom pants.backend.python.subsystems.setup import PythonSetup\nfrom pants.backend.python.target_types import (\n InterpreterConstraintsField,\n PythonDependenciesField,\n PythonResolveField,\n PythonSourceField,\n PythonTestSourceField,\n)\nfrom pants.backend.python.util_rules import ancestor_files, pex\nfrom pants.backend.python.util_rules.ancestor_files import AncestorFiles, AncestorFilesRequest\nfrom pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints\nfrom pants.core import target_types\nfrom pants.core.target_types import AllAssetTargets, AllAssetTargetsByPath, AllAssetTargetsRequest\nfrom pants.core.util_rules import stripped_source_files\nfrom pants.engine.addresses import Address, Addresses\nfrom pants.engine.internals.graph import Owners, OwnersRequest\nfrom pants.engine.rules import Get, MultiGet, rule, rule_helper\nfrom pants.engine.target import (\n DependenciesRequest,\n ExplicitlyProvidedDependencies,\n FieldSet,\n InferDependenciesRequest,\n InferredDependencies,\n Targets,\n)\nfrom pants.engine.unions import UnionRule\nfrom pants.option.global_options import OwnersNotFoundBehavior\nfrom pants.option.option_types import BoolOption, EnumOption, IntOption\nfrom pants.option.subsystem import Subsystem\nfrom pants.util.docutil import bin_name, doc_url\nfrom pants.util.strutil import bullet_list, softwrap\n\nlogger = logging.getLogger(__name__)\n\n\nclass UnownedDependencyError(Exception):\n \"\"\"The inferred dependency does not have any owner.\"\"\"\n\n\nclass UnownedDependencyUsage(Enum):\n \"\"\"What action to take when an inferred dependency is unowned.\"\"\"\n\n RaiseError = \"error\"\n LogWarning = \"warning\"\n DoNothing = \"ignore\"\n\n\nclass InitFilesInference(Enum):\n \"\"\"How to handle inference for __init__.py files.\"\"\"\n\n always = \"always\"\n content_only = \"content_only\"\n never = \"never\"\n\n\nclass PythonInferSubsystem(Subsystem):\n options_scope = \"python-infer\"\n help = \"Options controlling which dependencies will be inferred for Python targets.\"\n\n imports = BoolOption(\n default=True,\n help=softwrap(\n \"\"\"\n Infer a target's imported dependencies by parsing import statements from sources.\n\n To ignore a false positive, you can either put `# pants: no-infer-dep` on the line of\n the import or put `!{bad_address}` in the `dependencies` field of your target.\n \"\"\"\n ),\n )\n string_imports = BoolOption(\n default=False,\n help=softwrap(\n \"\"\"\n Infer a target's dependencies based on strings that look like dynamic\n dependencies, such as Django settings files expressing dependencies as strings.\n\n To ignore a false positive, you can either put `# pants: no-infer-dep` on the line of\n the string or put `!{bad_address}` in the `dependencies` field of your target.\n \"\"\"\n ),\n )\n string_imports_min_dots = IntOption(\n default=2,\n help=softwrap(\n \"\"\"\n If --string-imports is True, treat valid-looking strings with at least this many\n dots in them as potential dynamic dependencies. E.g., `'foo.bar.Baz'` will be\n treated as a potential dependency if this option is set to 2 but not if set to 3.\n \"\"\"\n ),\n )\n assets = BoolOption(\n default=False,\n help=softwrap(\n \"\"\"\n Infer a target's asset dependencies based on strings that look like Posix\n filepaths, such as those given to `open` or `pkgutil.get_data`.\n\n To ignore a false positive, you can either put `# pants: no-infer-dep` on the line of\n the string or put `!{bad_address}` in the `dependencies` field of your target.\n \"\"\"\n ),\n )\n assets_min_slashes = IntOption(\n default=1,\n help=softwrap(\n \"\"\"\n If --assets is True, treat valid-looking strings with at least this many forward\n slash characters as potential assets. E.g. `'data/databases/prod.db'` will be\n treated as a potential candidate if this option is set to 2 but not to 3.\n \"\"\"\n ),\n )\n init_files = EnumOption(\n help=softwrap(\n f\"\"\"\n Infer a target's dependencies on any `__init__.py` files in the packages\n it is located in (recursively upward in the directory structure).\n\n Even if this is set to `never` or `content_only`, Pants will still always include any\n ancestor `__init__.py` files in the sandbox. Only, they will not be \"proper\"\n dependencies, e.g. they will not show up in `{bin_name()} dependencies` and their own\n dependencies will not be used.\n\n By default, Pants only adds a \"proper\" dependency if there is content in the\n `__init__.py` file. This makes sure that dependencies are added when likely necessary\n to build, while also avoiding adding unnecessary dependencies. While accurate, those\n unnecessary dependencies can complicate setting metadata like the\n `interpreter_constraints` and `resolve` fields.\n \"\"\"\n ),\n default=InitFilesInference.content_only,\n )\n conftests = BoolOption(\n default=True,\n help=softwrap(\n \"\"\"\n Infer a test target's dependencies on any conftest.py files in the current\n directory and ancestor directories.\n \"\"\"\n ),\n )\n entry_points = BoolOption(\n default=True,\n help=softwrap(\n \"\"\"\n Infer dependencies on targets' entry points, e.g. `pex_binary`'s\n `entry_point` field, `python_awslambda`'s `handler` field and\n `python_distribution`'s `entry_points` field.\n \"\"\"\n ),\n )\n unowned_dependency_behavior = EnumOption(\n default=UnownedDependencyUsage.LogWarning,\n help=softwrap(\n \"\"\"\n How to handle imports that don't have an inferrable owner.\n\n Usually when an import cannot be inferred, it represents an issue like Pants not being\n properly configured, e.g. targets not set up. Often, missing dependencies will result\n in confusing runtime errors like `ModuleNotFoundError`, so this option can be helpful\n to error more eagerly.\n\n To ignore any false positives, either add `# pants: no-infer-dep` to the line of the\n import or put the import inside a `try: except ImportError:` block.\n \"\"\"\n ),\n )\n\n\n@dataclass(frozen=True)\nclass PythonImportDependenciesInferenceFieldSet(FieldSet):\n required_fields = (\n PythonSourceField,\n PythonDependenciesField,\n PythonResolveField,\n InterpreterConstraintsField,\n )\n\n source: PythonSourceField\n dependencies: PythonDependenciesField\n resolve: PythonResolveField\n interpreter_constraints: InterpreterConstraintsField\n\n\nclass InferPythonImportDependencies(InferDependenciesRequest):\n infer_from = PythonImportDependenciesInferenceFieldSet\n\n\ndef _get_inferred_asset_deps(\n address: Address,\n request_file_path: str,\n assets_by_path: AllAssetTargetsByPath,\n assets: ParsedPythonAssetPaths,\n explicitly_provided_deps: ExplicitlyProvidedDependencies,\n) -> dict[str, ImportResolveResult]:\n def _resolve_single_asset(filepath) -> ImportResolveResult:\n # NB: Resources in Python's ecosystem are loaded relative to a package, so we only try and\n # query for a resource relative to requesting module's path\n # (I.e. we assume the user is doing something like `pkgutil.get_data(__file__, \"foo/bar\")`)\n # See https://docs.python.org/3/library/pkgutil.html#pkgutil.get_data\n # and Pants' own docs on resources.\n #\n # Files in Pants are always loaded relative to the build root without any source root\n # stripping, so we use the full filepath to query for files.\n # (I.e. we assume the user is doing something like `open(\"src/python/configs/prod.json\")`)\n #\n # In either case we could also try and query based on the others' key, however this will\n # almost always lead to a false positive.\n resource_path = PurePath(request_file_path).parent / filepath\n file_path = PurePath(filepath)\n\n inferred_resource_tgts = assets_by_path.resources.get(resource_path, frozenset())\n inferred_file_tgts = assets_by_path.files.get(file_path, frozenset())\n inferred_tgts = inferred_resource_tgts | inferred_file_tgts\n\n if inferred_tgts:\n possible_addresses = tuple(tgt.address for tgt in inferred_tgts)\n if len(possible_addresses) == 1:\n return ImportResolveResult(ImportOwnerStatus.unambiguous, possible_addresses)\n\n explicitly_provided_deps.maybe_warn_of_ambiguous_dependency_inference(\n possible_addresses,\n address,\n import_reference=\"asset\",\n context=f\"The target {address} uses `{filepath}`\",\n )\n maybe_disambiguated = explicitly_provided_deps.disambiguated(possible_addresses)\n if maybe_disambiguated:\n return ImportResolveResult(ImportOwnerStatus.disambiguated, (maybe_disambiguated,))\n else:\n return ImportResolveResult(ImportOwnerStatus.ambiguous)\n else:\n return ImportResolveResult(ImportOwnerStatus.unowned)\n\n return {filepath: _resolve_single_asset(filepath) for filepath in assets}\n\n\nclass ImportOwnerStatus(Enum):\n unambiguous = \"unambiguous\"\n disambiguated = \"disambiguated\"\n ambiguous = \"ambiguous\"\n unowned = \"unowned\"\n weak_ignore = \"weak_ignore\"\n unownable = \"unownable\"\n\n\n@dataclass(frozen=True)\nclass ImportResolveResult:\n status: ImportOwnerStatus\n address: tuple[Address, ...] = ()\n\n\ndef _get_imports_info(\n address: Address,\n owners_per_import: Iterable[PythonModuleOwners],\n parsed_imports: ParsedPythonImports,\n explicitly_provided_deps: ExplicitlyProvidedDependencies,\n) -> dict[str, ImportResolveResult]:\n def _resolve_single_import(owners, import_name) -> ImportResolveResult:\n if owners.unambiguous:\n return ImportResolveResult(ImportOwnerStatus.unambiguous, owners.unambiguous)\n\n explicitly_provided_deps.maybe_warn_of_ambiguous_dependency_inference(\n owners.ambiguous,\n address,\n import_reference=\"module\",\n context=f\"The target {address} imports `{import_name}`\",\n )\n maybe_disambiguated = explicitly_provided_deps.disambiguated(owners.ambiguous)\n if maybe_disambiguated:\n return ImportResolveResult(ImportOwnerStatus.disambiguated, (maybe_disambiguated,))\n elif import_name.split(\".\")[0] in DEFAULT_UNOWNED_DEPENDENCIES:\n return ImportResolveResult(ImportOwnerStatus.unownable)\n elif parsed_imports[import_name].weak:\n return ImportResolveResult(ImportOwnerStatus.weak_ignore)\n else:\n return ImportResolveResult(ImportOwnerStatus.unowned)\n\n return {\n imp: _resolve_single_import(owners, imp)\n for owners, (imp, inf) in zip(owners_per_import, parsed_imports.items())\n }\n\n\ndef _collect_imports_info(\n resolve_result: dict[str, ImportResolveResult]\n) -> tuple[frozenset[Address], frozenset[str]]:\n \"\"\"Collect import resolution results into:\n\n - imports (direct and disambiguated)\n - unowned\n \"\"\"\n\n return frozenset(\n addr\n for dep in resolve_result.values()\n for addr in dep.address\n if (\n dep.status == ImportOwnerStatus.unambiguous\n or dep.status == ImportOwnerStatus.disambiguated\n )\n ), frozenset(\n imp for imp, dep in resolve_result.items() if dep.status == ImportOwnerStatus.unowned\n )\n\n\n@dataclass(frozen=True)\nclass UnownedImportsPossibleOwnersRequest:\n \"\"\"A request to find possible owners for several imports originating in a resolve.\"\"\"\n\n unowned_imports: frozenset[str]\n original_resolve: str\n\n\n@dataclass(frozen=True)\nclass UnownedImportPossibleOwnerRequest:\n unowned_import: str\n original_resolve: str\n\n\n@dataclass(frozen=True)\nclass UnownedImportsPossibleOwners:\n value: Dict[str, list[tuple[Address, ResolveName]]]\n\n\n@dataclass(frozen=True)\nclass UnownedImportPossibleOwners:\n value: list[tuple[Address, ResolveName]]\n\n\n@rule_helper\nasync def _find_other_owners_for_unowned_imports(\n req: UnownedImportsPossibleOwnersRequest,\n) -> UnownedImportsPossibleOwners:\n individual_possible_owners = await MultiGet(\n Get(UnownedImportPossibleOwners, UnownedImportPossibleOwnerRequest(r, req.original_resolve))\n for r in req.unowned_imports\n )\n\n return UnownedImportsPossibleOwners(\n {\n imported_module: possible_owners.value\n for imported_module, possible_owners in zip(\n req.unowned_imports, individual_possible_owners\n )\n if possible_owners.value\n }\n )\n\n\n@rule\nasync def find_other_owners_for_unowned_import(\n req: UnownedImportPossibleOwnerRequest,\n python_setup: PythonSetup,\n) -> UnownedImportPossibleOwners:\n other_owner_from_other_resolves = await Get(\n PythonModuleOwners, PythonModuleOwnersRequest(req.unowned_import, resolve=None)\n )\n\n owners = other_owner_from_other_resolves\n other_owners_as_targets = await Get(Targets, Addresses(owners.unambiguous + owners.ambiguous))\n\n other_owners = []\n\n for t in other_owners_as_targets:\n other_owner_resolve = t[PythonResolveField].normalized_value(python_setup)\n if other_owner_resolve != req.original_resolve:\n other_owners.append((t.address, other_owner_resolve))\n return UnownedImportPossibleOwners(other_owners)\n\n\n@rule_helper\nasync def _handle_unowned_imports(\n address: Address,\n unowned_dependency_behavior: UnownedDependencyUsage,\n python_setup: PythonSetup,\n unowned_imports: frozenset[str],\n parsed_imports: ParsedPythonImports,\n resolve: str,\n) -> None:\n if not unowned_imports or unowned_dependency_behavior is UnownedDependencyUsage.DoNothing:\n return\n\n other_resolves_snippet = \"\"\n if len(python_setup.resolves) > 1:\n imports_to_other_owners = (\n await _find_other_owners_for_unowned_imports(\n UnownedImportsPossibleOwnersRequest(unowned_imports, resolve),\n )\n ).value\n\n if imports_to_other_owners:\n other_resolves_lines = []\n for import_module, other_owners in sorted(imports_to_other_owners.items()):\n owners_txt = \", \".join(\n f\"'{other_resolve}' from {addr}\" for addr, other_resolve in sorted(other_owners)\n )\n other_resolves_lines.append(f\"{import_module}: {owners_txt}\")\n other_resolves_snippet = \"\\n\\n\" + softwrap(\n f\"\"\"\n These imports are not in the resolve used by the target (`{resolve}`), but they\n were present in other resolves:\n\n {bullet_list(other_resolves_lines)}\\n\\n\n \"\"\"\n )\n\n unowned_imports_with_lines = [\n f\"{module_name} (line: {parsed_imports[module_name].lineno})\"\n for module_name in sorted(unowned_imports)\n ]\n\n msg = softwrap(\n f\"\"\"\n Pants cannot infer owners for the following imports in the target {address}:\n\n {bullet_list(unowned_imports_with_lines)}{other_resolves_snippet}\n\n If you do not expect an import to be inferrable, add `# pants: no-infer-dep` to the\n import line. Otherwise, see\n {doc_url('troubleshooting#import-errors-and-missing-dependencies')} for common problems.\n \"\"\"\n )\n if unowned_dependency_behavior is UnownedDependencyUsage.LogWarning:\n logger.warning(msg)\n else:\n raise UnownedDependencyError(msg)\n\n\n@rule_helper\nasync def _exec_parse_deps(\n field_set: PythonImportDependenciesInferenceFieldSet,\n python_infer_subsystem: PythonInferSubsystem,\n python_setup: PythonSetup,\n) -> ParsedPythonDependencies:\n interpreter_constraints = InterpreterConstraints.create_from_compatibility_fields(\n [field_set.interpreter_constraints], python_setup\n )\n resp = await Get(\n ParsedPythonDependencies,\n ParsePythonDependenciesRequest(\n field_set.source,\n interpreter_constraints,\n string_imports=python_infer_subsystem.string_imports,\n string_imports_min_dots=python_infer_subsystem.string_imports_min_dots,\n assets=python_infer_subsystem.assets,\n assets_min_slashes=python_infer_subsystem.assets_min_slashes,\n ),\n )\n return resp\n\n\n@dataclass(frozen=True)\nclass ResolvedParsedPythonDependenciesRequest:\n field_set: PythonImportDependenciesInferenceFieldSet\n parsed_dependencies: ParsedPythonDependencies\n resolve: Optional[str]\n\n\n@dataclass(frozen=True)\nclass ResolvedParsedPythonDependencies:\n resolve_results: dict[str, ImportResolveResult]\n assets: dict[str, ImportResolveResult]\n explicit: ExplicitlyProvidedDependencies\n\n\n@rule\nasync def resolve_parsed_dependencies(\n request: ResolvedParsedPythonDependenciesRequest,\n python_infer_subsystem: PythonInferSubsystem,\n) -> ResolvedParsedPythonDependencies:\n \"\"\"Find the owning targets for the parsed dependencies.\"\"\"\n\n parsed_imports = request.parsed_dependencies.imports\n parsed_assets = request.parsed_dependencies.assets\n if not python_infer_subsystem.imports:\n parsed_imports = ParsedPythonImports([])\n\n explicitly_provided_deps = await Get(\n ExplicitlyProvidedDependencies, DependenciesRequest(request.field_set.dependencies)\n )\n\n if parsed_imports:\n owners_per_import = await MultiGet(\n Get(\n PythonModuleOwners,\n PythonModuleOwnersRequest(imported_module, resolve=request.resolve),\n )\n for imported_module in parsed_imports\n )\n resolve_results = _get_imports_info(\n address=request.field_set.address,\n owners_per_import=owners_per_import,\n parsed_imports=parsed_imports,\n explicitly_provided_deps=explicitly_provided_deps,\n )\n else:\n resolve_results = {}\n\n if parsed_assets:\n all_asset_targets = await Get(AllAssetTargets, AllAssetTargetsRequest())\n assets_by_path = await Get(AllAssetTargetsByPath, AllAssetTargets, all_asset_targets)\n asset_deps = _get_inferred_asset_deps(\n request.field_set.address,\n request.field_set.source.file_path,\n assets_by_path,\n parsed_assets,\n explicitly_provided_deps,\n )\n else:\n asset_deps = {}\n\n return ResolvedParsedPythonDependencies(\n resolve_results=resolve_results,\n assets=asset_deps,\n explicit=explicitly_provided_deps,\n )\n\n\n@rule(desc=\"Inferring Python dependencies by analyzing source\")\nasync def infer_python_dependencies_via_source(\n request: InferPythonImportDependencies,\n python_infer_subsystem: PythonInferSubsystem,\n python_setup: PythonSetup,\n) -> InferredDependencies:\n if not python_infer_subsystem.imports and not python_infer_subsystem.assets:\n return InferredDependencies([])\n\n parsed_dependencies = await _exec_parse_deps(\n request.field_set, python_infer_subsystem, python_setup\n )\n\n resolve = request.field_set.resolve.normalized_value(python_setup)\n\n resolved_dependencies = await Get(\n ResolvedParsedPythonDependencies,\n ResolvedParsedPythonDependenciesRequest(request.field_set, parsed_dependencies, resolve),\n )\n import_deps, unowned_imports = _collect_imports_info(resolved_dependencies.resolve_results)\n\n asset_deps, unowned_assets = _collect_imports_info(resolved_dependencies.assets)\n\n inferred_deps = import_deps | asset_deps\n\n _ = await _handle_unowned_imports(\n request.field_set.address,\n python_infer_subsystem.unowned_dependency_behavior,\n python_setup,\n unowned_imports,\n parsed_dependencies.imports,\n resolve=resolve,\n )\n\n return InferredDependencies(sorted(inferred_deps))\n\n\n@dataclass(frozen=True)\nclass InitDependenciesInferenceFieldSet(FieldSet):\n required_fields = (PythonSourceField, PythonResolveField)\n\n source: PythonSourceField\n resolve: PythonResolveField\n\n\nclass InferInitDependencies(InferDependenciesRequest):\n infer_from = InitDependenciesInferenceFieldSet\n\n\n@rule(desc=\"Inferring dependencies on `__init__.py` files\")\nasync def infer_python_init_dependencies(\n request: InferInitDependencies,\n python_infer_subsystem: PythonInferSubsystem,\n python_setup: PythonSetup,\n) -> InferredDependencies:\n if python_infer_subsystem.init_files is InitFilesInference.never:\n return InferredDependencies([])\n\n ignore_empty_files = python_infer_subsystem.init_files is InitFilesInference.content_only\n fp = request.field_set.source.file_path\n assert fp is not None\n init_files = await Get(\n AncestorFiles,\n AncestorFilesRequest(\n input_files=(fp,),\n requested=(\"__init__.py\", \"__init__.pyi\"),\n ignore_empty_files=ignore_empty_files,\n ),\n )\n owners = await MultiGet(Get(Owners, OwnersRequest((f,))) for f in init_files.snapshot.files)\n\n owner_tgts = await Get(Targets, Addresses(itertools.chain.from_iterable(owners)))\n resolve = request.field_set.resolve.normalized_value(python_setup)\n python_owners = [\n tgt.address\n for tgt in owner_tgts\n if (\n tgt.has_field(PythonSourceField)\n and tgt[PythonResolveField].normalized_value(python_setup) == resolve\n )\n ]\n return InferredDependencies(python_owners)\n\n\n@dataclass(frozen=True)\nclass ConftestDependenciesInferenceFieldSet(FieldSet):\n required_fields = (PythonTestSourceField, PythonResolveField)\n\n source: PythonTestSourceField\n resolve: PythonResolveField\n\n\nclass InferConftestDependencies(InferDependenciesRequest):\n infer_from = ConftestDependenciesInferenceFieldSet\n\n\n@rule(desc=\"Inferring dependencies on `conftest.py` files\")\nasync def infer_python_conftest_dependencies(\n request: InferConftestDependencies,\n python_infer_subsystem: PythonInferSubsystem,\n python_setup: PythonSetup,\n) -> InferredDependencies:\n if not python_infer_subsystem.conftests:\n return InferredDependencies([])\n\n fp = request.field_set.source.file_path\n assert fp is not None\n conftest_files = await Get(\n AncestorFiles,\n AncestorFilesRequest(input_files=(fp,), requested=(\"conftest.py\",)),\n )\n owners = await MultiGet(\n # NB: Because conftest.py files effectively always have content, we require an\n # owning target.\n Get(Owners, OwnersRequest((f,), OwnersNotFoundBehavior.error))\n for f in conftest_files.snapshot.files\n )\n\n owner_tgts = await Get(Targets, Addresses(itertools.chain.from_iterable(owners)))\n resolve = request.field_set.resolve.normalized_value(python_setup)\n python_owners = [\n tgt.address\n for tgt in owner_tgts\n if (\n tgt.has_field(PythonSourceField)\n and tgt[PythonResolveField].normalized_value(python_setup) == resolve\n )\n ]\n return InferredDependencies(python_owners)\n\n\n# This is a separate function to facilitate tests registering import inference.\ndef import_rules():\n return [\n resolve_parsed_dependencies,\n find_other_owners_for_unowned_import,\n infer_python_dependencies_via_source,\n *pex.rules(),\n *parse_python_dependencies.rules(),\n *module_mapper.rules(),\n *stripped_source_files.rules(),\n *target_types.rules(),\n *PythonInferSubsystem.rules(),\n *PythonSetup.rules(),\n UnionRule(InferDependenciesRequest, InferPythonImportDependencies),\n ]\n\n\ndef rules():\n return [\n *import_rules(),\n infer_python_init_dependencies,\n infer_python_conftest_dependencies,\n *ancestor_files.rules(),\n UnionRule(InferDependenciesRequest, InferInitDependencies),\n UnionRule(InferDependenciesRequest, InferConftestDependencies),\n ]\n","sub_path":"src/python/pants/backend/python/dependency_inference/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":25333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"561838665","text":"#!/usr/bin/python\n\nimport datetime\nimport re\nfrom shutil import copyfile\nfrom os import listdir\n\nblog = \"blog/\"\nmasterTemplate = \"\"\npostTemplate = \"\"\npageTemplate = \"\"\n\ndef readTemplates():\n\tglobal masterTemplate\n\tfo = open(\"mastertemplate.html\", \"r\")\n\tmasterTemplate = fo.read()\n\tfo.close()\n\t\n\tglobal postTemplate\n\tfo = open(\"posttemplate.html\", \"r\")\n\tpostTemplate = fo.read()\n\tfo.close()\n\n\tglobal pageTemplate\n\tfo = open(\"pagetemplate.html\", \"r\")\n\tpageTemplate = fo.read()\n\tfo.close()\n\ndef splitDateTitle(filename):\n\tdatetitle = filename.split(\"#\")\n\tdate = datetitle[0]\n\thtmlfilename = datetitle[1]\n\thtmlfilename = htmlfilename.replace(\"[slash]\",\" \").\\\n\t\t\t\t\t\t\t\treplace(\"[ques]\",\"\").\\\n\t\t\t\t\t\t\t\treplace(\" \",\"-\").\\\n\t\t\t\t\t\t\t\treplace(\"'\",\"\").lower()\n\treturn (date, htmlfilename)\n\t\ndef htmlFromTemplate(html):\n\tmatchObj = re.search( r'\\{\\{title=(.*?)\\}\\}', html, re.M|re.I)\n\ttitle = matchObj.group(1)\n\n\tfinalhtml = masterTemplate.replace(\"{{title}}\", title).replace(\"{{htmlcontent}}\", html)\n\treturn finalhtml\n\ndef htmlFromPostTemplate(html, htmlfilename):\n\tmatchObj = re.search( r'\\{\\{date=(.*?)\\}\\}', html, re.M|re.I)\n\tdate = matchObj.group(1)\n\tmatchObj = re.search( r'\\{\\{title=(.*?)\\}\\}', html, re.M|re.I)\n\ttitle = matchObj.group(1)\n\tmatchObj = re.search( r'\\{\\{imagesrc=(.*?)\\}\\}', html, re.M|re.I)\n\timagesrc = matchObj.group(1)\n\tmatchObj = re.search( r'\\{\\{alttext=(.*?)\\}\\}', html, re.M|re.I)\n\talttext = matchObj.group(1)\n\tdate = datetime.datetime.strptime(date, \"%Y-%m-%d-%H-%M-%S\").date().strftime(\"%d %b %Y\")\n\n\tblogurl = \"http://vineelkumarreddy.com/\"+ htmlfilename\n\n\tfinalhtml = postTemplate.replace(\"{{title}}\", title).\\\n\t\t\t\t\t\t\t replace(\"{{date}}\", date).\\\n\t\t\t\t\t\t\t replace(\"{{imagesrc}}\", imagesrc).\\\n\t\t\t\t\t\t\t replace(\"{{alttext}}\", alttext).\\\n\t\t\t\t\t\t\t replace(\"{{blogurl}}\", blogurl).\\\n\t\t\t\t\t\t\t replace(\"{{postbody}}\", html)\n\treturn finalhtml\n\ndef htmlFromPageTemplate(html, htmlfilename):\n\tfinalhtml = pageTemplate.replace(\"{{pagebody}}\", html)\n\treturn finalhtml\n\ndef populateFile(filename, html, posts_pages):\n\t(date, htmlfilename) = splitDateTitle(filename)\n\tprint(filename, \" | \" + htmlfilename)\n\n\tif posts_pages:\n\t\thtml = htmlFromPostTemplate(html, htmlfilename)\n\telse:\n\t\thtml = htmlFromPageTemplate(html, htmlfilename)\n\t\n\tfinalhtml = htmlFromTemplate(html)\n\tfo = open(blog + htmlfilename, \"w\")\n\tfo.write(finalhtml)\n\tfo.close()\n\t\ndef readFiles(path, posts_pages):\n\tfor filename in listdir(path):\n\t\tif not filename.endswith(\".swp\") : #exclude swapfiles created by Vim when editing ;)\n\t\t\tfo = open(path + filename, \"r\")\n\t\t\thtml = fo.read()\n\t\t\tfo.close()\n\t\t\tpopulateFile(filename, html, posts_pages)\n\n\ndef copyRSSFeed(path):\n\tcopyfile(path + \"rss.xml\", blog + \"rss.xml\")\t\n\n\n#start of main\nreadTemplates()\nreadFiles(\"content/posts/\", True)\nreadFiles(\"content/pages/\", False)\ncopyRSSFeed(\"content/rss/\")\n\n","sub_path":"sitegen.py","file_name":"sitegen.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"329677872","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 1 17:49:30 2017\n\n@author: DELL\nPocket PLA 跑2000的100迭代\n\"\"\"\n\n\nimport numpy as np\n\ndef openFile(fileName,dataList):\n f=open(fileName,'r')\n x=0\n for line in f:\n y=line.split()\n y=list(map(float,y))\n dataX=[]\n y.insert(0,1)\n dataX.append(y[0:5])\n dataX.append(y[5])\n dataList.append(dataX)\n x+=1\n f.close \ndef sign(t):\n if t>0:\n return 1\n else:\n return -1\ndef mui(error,data):\n tmpData=[]\n for i in range(5):\n tmpData.append(error*data[i])\n i+=1\n return tmpData \ndef add(x,y):\n temp=[]\n for i in range(5):\n temp.append(x[i]+y[i])\n i+=1\n return temp \ndef dot(w,data):\n temp=0\n speed=0.5\n #w0=-1 # +(-threshold)*x0 if x0=1, threshold=1\n for i in range(5):\n temp=temp+w[i]*data[i]*speed\n i+=1\n #temp+=w0\n return temp \n\ndef getErrorRate(w,dataList):\n n = len(dataList); \n error=0\n for i in range(0,n):\n data =dataList[i]\n fact=data[1]\n compute=sign(dot(w,data[0]))\n if fact != compute:\n error+=1\n return error/n\n\ndef pocket_pla(dataList,normalW,pocketW,Finish):\n itertion=1#修正錯誤次數\n index=0 # 計算到第幾個樣本\n while itertion')\ndef send_js(path):\n return send_from_directory('assets', path)\n\n@app.route(\"/\")\ndef hello():\n return \"LTI Bootcamp Tool Consumer, hello!\"\n\n@app.route(\"/.well-known/jwks.json\")\ndef keyset():\n return jsonify(platform.get_keyset())\n\n@app.route(\"/newtool\")\ndef newtool():\n tool = platform.new_tool()\n platform.url = request.url_root\n course_by_tool[tool.client_id] = platform.new_course()\n return jsonify({\n 'client_id': tool.client_id,\n 'deployment_id': tool.deployment_id,\n 'webkey': tool.key['webkey'],\n 'webkeyPem': tool.key['key'].exportKey().decode('utf-8')\n })\n\n@app.route(\"/tool//cisr\")\ndef content_item_launch(tool_id):\n course = course_by_tool[tool_id]\n instructor = course.roster.getInstructor()\n message = {\n \"http://imsglobal.org/lti/deep_linking_request\": {\n \"accept_media_types\": [\"application/vnd.ims.lti.v1.ltilink\"],\n \"accept_presentation_document_targets\": [ \"iframe\", \"window\"],\n \"accept_multiple\": True,\n \"auto_create\": True,\n \"data\": \"op=321&v=44\"\n }\n }\n return_url = \"/tool/{0}/cir\".format(course.id)\n return platform.get_tool(tool_id).token('LTIDeepLinkingRequest', course, instructor, message, return_url, request_url=request.url_root)\n\n@app.route(\"/tool//cir\", methods=['POST'])\ndef content_item_return(context_id):\n encoded_jwt = request.form['jws_token']\n unverified = jwt.decode(encoded_jwt, verify=False)\n tool = platform.get_tool(unverified['iss'])\n deep_linking_res = jwt.decode(encoded_jwt, \n key=tool.getPublicKey().exportKey(), \n algorithms=['RS256'],\n audience=request.url_root.rstrip('/'))\n if ('http://imsglobal.org/lti/content_items' in deep_linking_res):\n content_items = deep_linking_res['http://imsglobal.org/lti/content_items']\n platform.get_course(context_id).addResourceLinks(tool, content_items)\n return redirect('/course/'+context_id, code=302)\n\n\n@app.route(\"/tool//context//studentlaunch\")\ndef student_launch(tool_id, context_id):\n course = platform.get_course(context_id)\n rlid = request.args.get('rlid', '' )\n rlid = rlid if rlid else course.getOneGradableLinkId()\n resource_link = course.getResourceLink(rlid)\n return platform.get_tool(tool_id).token('LTIResourceLinkLaunch', \n course, \n course.roster.getOneStudent(), \n {}, \n request.url_root,\n request_url=request.url_root,\n resource_link=resource_link)\n\n\n@app.route(\"/course/\")\ndef show_course(course_id):\n return render_template('courseoutline.html', course=platform.get_course(course_id))\n\n@app.route(\"/course//gradebook\")\ndef show_gradebook(course_id):\n return render_template('gradebook.html', course=platform.get_course(course_id))\n\n@app.route(\"/auth/token\", methods=['POST'])\ndef get_access_token():\n if request.form['client_assertion_type'] != 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer':\n abort(400)\n if request.form['grant_type'] != 'client_credentials':\n abort(400)\n if not request.form.get('scope'):\n abort(400)\n assertion_jwt = request.form['client_assertion']\n client_id = jwt.decode(assertion_jwt, verify=False)['iss']\n tool = platform.get_tool(client_id)\n jwt.decode(assertion_jwt, \n tool.getPublicKey().exportKey(), \n algorithms=['RS256'],\n audience='{0}/auth/token'.format(request.url_root.rstrip('/')))\n \n access_token = new_token(client_id, request.form['scope'])\n return jsonify({\n \"access_token\" : access_token.id,\n \"token_type\" : \"Bearer\",\n \"expires_in\" : access_token.expires_in\n })\n\ndef get_and_check_lineitem(context_id, item_id, client_id):\n tool = platform.get_tool(client_id)\n course = platform.get_course(context_id)\n lineitem = course.get_lineitem(item_id)\n if not tool == lineitem.tool:\n abort(403, 'Lineitem does not belong to tool making the request')\n return lineitem\n\n@app.route(\"//lineitems//lineitem/scores\", methods=['POST'])\n@check_token('http://imsglobal.org/ags/score/publish')\ndef save_score(context_id=None, item_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n score = request.get_json()\n lineitem = get_and_check_lineitem(context_id,item_id, client_id)\n lineitem.save_score(score)\n return ''\n\n@app.route(\"//lineitems//lineitem/results\", methods=['GET'])\n@check_token('http://imsglobal.org/ags/results/get')\ndef get_results(context_id=None, item_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n lineitem = get_and_check_lineitem(context_id,item_id, client_id)\n results = list(map(lambda r: r[1].to_json(), lineitem.results.items()))\n return jsonify(results)\n\n@app.route(\"//lineitems//lineitem\", methods=['GET'])\n@check_token('http://imsglobal.org/ags/results/get')\ndef get_lineitem(context_id=None, item_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n lineitem = get_and_check_lineitem(context_id,item_id, client_id)\n return jsonify(lineitem.to_json(request.root_url.rstrip('/')))\n\n@app.route(\"//lineitems//lineitem\", methods=['PUT'])\n@check_token('http://imsglobal.org/ags/results/get')\ndef update_lineitem(context_id=None, item_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n lineitem = get_and_check_lineitem(context_id,item_id, client_id)\n lineitem.update_from_json(request.get_json())\n return jsonify(lineitem.to_json(request.root_url.rstrip('/')))\n\n@app.route(\"//lineitems//lineitem\", methods=['DELETE'])\n@check_token('http://imsglobal.org/ags/results/get')\ndef delete_lineitem(context_id=None, item_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n lineitem = get_and_check_lineitem(context_id,item_id, client_id)\n lineitem.course.remove_lineitem(item_id)\n return ''\n\n@app.route(\"//lineitems\", methods=['GET'])\n@check_token('http://imsglobal.org/ags/lineitem')\ndef get_lineitems(context_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n tool = platform.get_tool(client_id)\n course = platform.get_course(context_id)\n root_url = request.root_url.rstrip('/')\n results = list(map(lambda l: l.to_json(root_url), filter(lambda l: l.tool==tool, course.lineitems)))\n return jsonify(results)\n\n@app.route(\"//lineitems\", methods=['POST'])\n@check_token('http://imsglobal.org/ags/lineitem')\ndef add_lineitem(context_id=None, client_id=None):\n # we are not checking media type because the URL is enough of a discriminator\n tool = platform.get_tool(client_id)\n course = platform.get_course(context_id)\n lineitem = course.add_lineitem(request.get_json())\n return jsonify(lineitem.to_json(request.root_url.rstrip('/')))\n","sub_path":"server/lti_platform.py","file_name":"lti_platform.py","file_ext":"py","file_size_in_byte":7813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"637178152","text":"#!/usr/bin/env python\nimport numpy as np\nfrom argparse import ArgumentParser\nimport matplotlib.pyplot as py\np = ArgumentParser()\np.add_argument('nai')\np.add_argument('cosi')\np.add_argument('--clock_rate',type=float,default=10E6)\na = p.parse_args()\n\n#read data\nnai = np.genfromtxt(a.nai)\ncosi = np.genfromtxt(a.cosi)\n\n#analysis\ndt = np.arange(-8E-6,8E-6,1./a.clock_rate) * a.clock_rate\ncount = [np.count_nonzero(np.in1d(cosi + t,nai)) for t in dt.astype(np.int64)]\n\n#plot\npy.step(dt,count)\npy.show()\n","sub_path":"pymisc/tstamp_analyze.py","file_name":"tstamp_analyze.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"12872272","text":"from random import randint\nfrom base64 import b64encode\nfrom io import BytesIO\nimport imageio\nfrom ipyleaflet import Map, ImageOverlay\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Rectangle\n\n\ndef normalize_to_zero_one(image_data: np.ndarray) -> np.ndarray:\n max_value = image_data.max()\n if max_value == 0:\n return image_data.astype(np.float32)\n\n return image_data.astype(np.float32) / image_data.max()\n\n\ndef normalize_to_byte(image_data: np.ndarray) -> np.ndarray:\n byte_data = 255 * normalize_to_zero_one(image_data)\n\n return byte_data.astype(np.uint8)\n\n\ndef serialize_to_url(image_data: np.ndarray) -> str:\n in_memory_file = BytesIO()\n\n imageio.imwrite(in_memory_file, image_data, format='png')\n\n ascii_data = b64encode(in_memory_file.getvalue()).decode('ascii')\n\n return 'data:image/png;base64,' + ascii_data\n\n\ndef create_map(normalized_image: np.ndarray) -> Map:\n width = normalized_image.shape[0]\n height = normalized_image.shape[1]\n bounds = [(-width / 2, -height / 2), (width / 2, height / 2)]\n\n layer = ImageOverlay(url=serialize_to_url(normalized_image), bounds=bounds)\n leaflet = Map(center=[0, 0], zoom=1, interpolation='nearest')\n leaflet.clear_layers()\n leaflet.add_layer(layer)\n\n return leaflet\n\n\ndef create_image(normalized_image: np.ndarray, label: str=None):\n plt.figure(figsize=(10, 10))\n\n if label is not None:\n plt.title(label)\n\n if normalized_image.shape[2] == 1:\n plt.imshow(np.repeat(normalized_image, 3, axis=2), interpolation='none')\n else:\n plt.imshow(normalized_image, interpolation='none')\n\n\ndef show_samples_location(dataset, neighbourhood, samples_to_show_count):\n class_to_display = randint(0, len(np.unique(dataset.y)))\n train_indices = dataset.train_indices[class_to_display][0:samples_to_show_count]\n test_indices = dataset.test_indices[class_to_display][0:samples_to_show_count]\n im = dataset.x[:, :, randint(0, dataset.x.shape[-1])]\n fig, ax = plt.subplots(1)\n ax.imshow(im)\n for train in train_indices:\n x = [train.y - int(neighbourhood[0]/2), train.x - int(neighbourhood[1]/2)]\n ax.add_patch(Rectangle(x, neighbourhood[0], neighbourhood[1], color='r', fill=False))\n\n for test in test_indices:\n x = [test.y - int(neighbourhood[0]/2), test.x - int(neighbourhood[1]/2)]\n ax.add_patch(Rectangle(x, neighbourhood[0], neighbourhood[1], color='y', fill=False))\n plt.show()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"404797933","text":"#!/usr/bin/python3\nfrom random import *\nfrom math import sqrt\nimport sys\n\nsys.setrecursionlimit(100000)\nSIZE = 120\nobj_big = 30\nobj_small = 120\nobj_large = 5\nWOOD_SIZE = [101, 152, 210, 253]\nWoodSizeSmall = [24, 13, 18, 26]\nMuntainSize = [102, 124, 87]\nSEA_SIZE = [37, 64, 144, 179]\nSeaSizeSmall = [30, 68, 40, 54]\nRiverSizeSmall = [27, 19, 17, 23]\nRiverSize = [34, 49, 27, 40]\n##amount##\ngrass = '`'\nswamp = ';'\nmeadle = ':'\nsimple = '\"'\n\nsea = 'S'\nmoves = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, -1), (-1, 1), (-1, -1), (1, 1)]\ntypes = ['`', '\"', '\"', '\"', '\"', '\"', '\"', '\"', \"S\", \"T\", '~', 'S', '~', \"^\"]\n##types##\nchances = {}\nchances[\"~\"] = [0.6, 0.7, 0.3]\nchances[\"^\"] = [0.1, 0.2, 0.5]\nchances[\"T\"] = [0.9, 0.8, 0.86, 0.6]\n#chances[\"^\"] = \nchance = [ 0.3, 0.5, 0.8, 0.9, 1, 1.1, 1.2, 2.5, 1.5, 2, 1.75, 3.3]\nclass square:\n def __init__(self, typ):\n self.c = typ if typ != 0 else ''\n self.t = 'ground'\n\n if typ == 'T':\n self.t = 'tree'\n elif typ == 'S':\n self.t = \"water lake\"\n elif typ == '~':\n self.t = \"water river\"\n elif typ == 'O':\n self.t = \"ice-berg\"\n def __str__(self):\n return str(self.c)\n##colors##\ncolor = {}\ncolor[\"T\"] = '42'\ncolor['\"'] = '57;103'\ncolor[\"S\"] = '5;34;104'\ncolor[\"~\"] = '5;94;44'\ncolor[swamp] = '2;32;40'\ncolor[meadle] = '7;92'\ncolor[grass] = '1;30;102'\n##\ndef generate_sea_first(arr, i, j):\n if not (0 <= i < len(arr) and 0 <= j < len(arr[0])):\n return 0\n elif arr[i][j].c != '':\n return 0\n arr[i][j] = square(sea)\n temp = 2 * SIZE / sqrt(min(i + 1, SIZE - i) * min(j + 1, SIZE - j))\n if randint(1, SIZE) <= choice(chance) * temp:\n generate_sea_first(arr, i - 1, j)\n else:\n if random() < 0.1 and i > 0 and arr[i - 1][j].c == '':\n arr[i - 1][j] = square(simple)\n if randint(1, SIZE) <= choice(chance) * temp:\n generate_sea_first(arr, i, j - 1)\n else:\n if random() < 0.1 and j > 0 and arr[i][j - 1].c == '':\n arr[i][j - 1] = square(simple)\n if randint(1, SIZE) <= choice(chance) * temp:\n generate_sea_first(arr, i, j + 1) \n else:\n if random() < 0.1 and j < SIZE - 1 and arr[i][1 + j].c == '':\n arr[i][j + 1] = square(simple)\n if randint(1, SIZE) <= choice(chance) * temp:\n generate_sea_first(arr, i + 1, j)\n else:\n if random() < 0.1 and i < SIZE - 1 and arr[i + 1][j].c == '':\n arr[i + 1][j] = square(simple)\n\ndef generate(arr, i, j, t, am=0):\n if not(0 <= i < SIZE and 0 <= j < SIZE):\n return 0\n \n if t.t == 'tree' or t.t == 'ground':\n q = [(i, j)]\n index = 0\n if t.t == 'tree':\n if am == 0:\n size = choice(WOOD_SIZE)\n \n else:\n size = choice(WoodSizeSmall)\n else:\n size = randint(SIZE * 12, SIZE * 25)\n\n print(size)\n while index < size and index < len(q):\n i, j = q[index]\n arr[i][j] = t\n for dx, dy in moves:\n if (0 <= i + dx < SIZE and 0 <= j + dy < SIZE) and random() < 0.76 and arr[i + dx][j + dy].c == '\"':\n q.append((i + dx, j + dy))\n if index % 7 == 0:\n shuffle(q)\n index += 1\n elif t.t == 'water lake':\n\n q = [(i, j)]\n index = 0\n if am == 0:\n size = choice(SEA_SIZE)\n else:\n size = choice(SeaSizeSmall)\n print(size)\n while index < size and index < len(q):\n i, j = q[index]\n arr[i][j] = t\n for dx, dy in moves:\n if (0 <= i + dx < SIZE and 0 <= j + dy < SIZE) and random() < 0.76:\n q.append((i + dx, j + dy))\n if index % 7 == 0:\n shuffle(q)\n index += 1\n elif t.t == 'water river':\n index = 0\n q = [(i, j)]\n if am == 0:\n \n size = choice(RiverSize)\n else:\n size = choice(RiverSizeSmall)\n c_moves = moves[:]\n if i < SIZE // 2 and j < SIZE // 2:\n c_moves.extend([(0, -1), (-1, 0), (0, -1), (-1, 0)] * 5)\n elif i < SIZE // 2:\n c_moves.extend([(1, 0), (0, -1), (1, 0), (0, -1)] * 5)\n elif j < SIZE // 2:\n c_moves.extend([(-1, 0), (0, 1), (-1, 0), (0, 1)] * 5)\n else:\n c_moves.extend([(1, 0), (0, 1), (1, 0), (0, 1)]* 5)\n\n\n while index < size and index < len(q):\n i, j = q[index]\n arr[i][j] = square('~')\n dx, dy = choice(c_moves)\n \n if (0 <= i + dx < SIZE and 0 <= j + dy < SIZE):\n q.append((i + dx, j + dy))\n if (arr[q[-1][0]][q[-1][1]].t == 'water lake'):\n return 0\n\n if index % 29 == 0:\n shuffle(q)\n index += 1\nclass terra:\n def __init__(self):\n self.area = [[square(0)] * SIZE for i in range(SIZE)]\n self.t = 25\n for i in range(SIZE):\n for j in range(SIZE):\n if self.area[i][j].c == \"\" and sqrt(min(i, SIZE - i) * min(j, SIZE - j)) < SIZE / 9:\n generate_sea_first(self.area, i, j)\n for i in range(SIZE):\n for j in range(SIZE):\n if self.area[i][j].c == '':\n self.area[i][j] = square('\"')\n for i in range(obj_large):\n i, j = randint(0, SIZE - 1), randint(0, SIZE - 1)\n generate(self.area, i, j, square(choice([swamp, meadle, grass])))\n for i in range(obj_big):\n i, j = randint(10, SIZE - 10), randint(10, SIZE - 10)\n generate(self.area, i, j, square(choice(['S', '~', 'T'])))\n for i in range(obj_small):\n i, j = randint(10, SIZE - 10), randint(10, SIZE - 10)\n generate(self.area, i, j, square(choice(['S', '~', 'T'])), 1)\n def __str__(self):\n for i in range(SIZE):\n for j in range(SIZE):\n# print(str(self.area[i][j]), end='')\n print(\"\\033[\" + color[str(self.area[i][j])] + \"m\" + str(self.area[i][j]) + \"\\033[0m\", end='')\n print()\n return '\\n'\n \nworld = terra()\nprint(world)\n","sub_path":"W1/World/relief_wood_lake_river.py","file_name":"relief_wood_lake_river.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"587213674","text":"#!/usr/bin/python3\n\"\"\" app \"\"\"\nimport os\nfrom flask import Flask, Blueprint, jsonify\nfrom flask_cors import CORS\nfrom api.v1.views import app_views\nfrom models import storage\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"0.0.0.0\"}})\napp.url_map.strict_slashes = False\napp.register_blueprint(app_views)\n\n\n@app.teardown_appcontext\ndef teardown(err):\n \"\"\" method to handle \"\"\"\n storage.close()\n\n\n@app.errorhandler(404)\ndef page_not_found(err):\n \"\"\" handle for 404 errors \"\"\"\n return jsonify({\"error\": \"Not found\"}), 404\n\nif __name__ == \"__main__\":\n host = os.environ.get('HBNB_API_HOST', '0.0.0.0')\n port = os.environ.get('HBNB_API_PORT', '5000')\n app.run(host=host, port=int(port), threaded=True)\n","sub_path":"api/v1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"30577932","text":"import json\n\nimport requests\nimport storey\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\nimport mlrun\n\nhttp_adapter = HTTPAdapter(\n max_retries=Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])\n)\n\n\nclass RemoteStep(storey.SendToHttp):\n \"\"\"class for calling remote endpoints\n \"\"\"\n\n def __init__(\n self,\n url: str,\n subpath: str = None,\n method: str = None,\n headers: dict = None,\n url_expression: str = None,\n return_json: bool = True,\n **kwargs,\n ):\n \"\"\"class for calling remote endpoints\n\n sync and async graph step implementation for request/resp to remote service (class shortcut = \"$remote\")\n url can be an http(s) url (e.g. \"https://myservice/path\") or an mlrun function uri ([project/]name).\n alternatively the url_expression can be specified to build the url from the event (e.g. \"event['url']\").\n\n example pipeline::\n\n flow = function.set_topology(\"flow\", engine=\"async\")\n flow.to(name=\"step1\", handler=\"func1\")\\\n .to(RemoteStep(name=\"remote_echo\", url=\"https://myservice/path\", method=\"POST\"))\\\n .to(name=\"laststep\", handler=\"func2\").respond()\n\n\n :param url: http(s) url or function [project/]name to call\n :param subpath: path (which follows the url), use `$path` to use the event.path\n :param method: HTTP method (GET, POST, ..), default to POST\n :param headers: dictionary with http header values\n :param url_expression: an expression for getting the url from the event, e.g. \"event['url']\"\n :param return_json: indicate the returned value is json, and convert it to a py object\n \"\"\"\n if url and url_expression:\n raise mlrun.errors.MLRunInvalidArgumentError(\n \"cannot set both url and url_expression\"\n )\n self.url = url\n self.url_expression = url_expression\n self.headers = headers\n self.method = method\n self.return_json = return_json\n self.subpath = subpath or \"\"\n super().__init__(None, None, **kwargs)\n\n self._append_event_path = False\n self._endpoint = \"\"\n self._session = None\n self._url_function_handler = None\n\n def post_init(self, mode=\"sync\"):\n if self.url_expression:\n # init lambda function for calculating url from event\n self._url_function_handler = eval(\n \"lambda event: \" + self.url_expression, {}, {}\n )\n else:\n self._append_event_path = self.subpath == \"$path\"\n self._endpoint = self.context.get_remote_endpoint(self.url).strip(\"/\")\n if self.subpath and not self._append_event_path:\n self._endpoint = self._endpoint + \"/\" + self.subpath.lstrip(\"/\")\n\n async def _process_event(self, event):\n # async implementation (with storey)\n method, url, headers, body = self._generate_request(event)\n return await self._client_session.request(\n method, url, headers=headers, data=body, ssl=False\n )\n\n async def _handle_completed(self, event, response):\n response_body = await response.read()\n body = self._get_data(response_body, response.headers)\n\n if body is not None:\n new_event = self._user_fn_output_to_event(event, body)\n await self._do_downstream(new_event)\n\n def do_event(self, event):\n # sync implementation (without storey)\n if not self._session:\n self._session = requests.Session()\n self._session.mount(\"http://\", http_adapter)\n self._session.mount(\"https://\", http_adapter)\n\n method, url, headers, body = self._generate_request(event)\n try:\n resp = self._session.request(\n method, url, verify=False, headers=headers, data=body\n )\n except OSError as err:\n raise OSError(f\"error: cannot invoke url: {url}, {err}\")\n if not resp.ok:\n raise RuntimeError(f\"bad http response {resp.text}\")\n\n event.body = self._get_data(resp.content, resp.headers)\n return event\n\n def _generate_request(self, event):\n method = self.method or event.method or \"POST\"\n headers = self.headers or event.headers or {}\n\n body = None\n if method != \"GET\" and event.body is not None:\n if isinstance(event.body, (str, bytes)):\n body = event.body\n else:\n body = json.dumps(event.body)\n headers[\"Content-Type\"] = \"application/json\"\n\n if self._url_function_handler:\n url = self._url_function_handler(event.body)\n else:\n url = self._endpoint\n if self._append_event_path:\n url = url + \"/\" + event.path.lstrip(\"/\")\n return method, url, headers, body\n\n def _get_data(self, data, headers):\n if (\n self.return_json\n or headers.get(\"content-type\", \"\").lower() == \"application/json\"\n ) and isinstance(data, (str, bytes)):\n data = json.loads(data)\n return data\n\n def to_dict(self):\n args = {\n key: getattr(self, key)\n for key in [\n \"url\",\n \"subpath\",\n \"method\",\n \"headers\",\n \"return_json\",\n \"url_expression\",\n ]\n }\n return {\n \"class_name\": f\"{__name__}.{self.__class__.__name__}\",\n \"name\": self.name or self.__class__.__name__,\n \"class_args\": args,\n }\n","sub_path":"mlrun/serving/remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"496495709","text":"\"\"\"Create and control a connectivity object.\n\nThis class can be used to create and to control a connectivity object, by\nsetting node positions, connexion strength, the way of coloring connexions,\ndynamic control of transparency...\n\nThis class inherit from vispy.visuals so it can be turned into a vispy node,\nwhich make it easier to add vispy transformations.\n\"\"\"\n\nimport numpy as np\nfrom collections import Counter\n\nfrom vispy import gloo, visuals\nfrom vispy.scene.visuals import create_visual_node\n\nfrom ..utils import array2colormap, normalize, color2vb\n\n\n__all__ = ['ConnectMesh']\n\n# Vertex shader : executed code for individual vertices. The transformation\n# applied to each one of them is the camera rotation.\nvertex_shader = \"\"\"\nvarying vec4 v_color;\nvoid main()\n{\n v_color = $a_color;\n gl_Position = $transform(vec4($a_position, 1));\n}\n\"\"\"\n\n# Fragment shader : executed code to each Fragment generated by the\n# Rasterization and turn it into a set of colors and a single depth value.\n# Each single fragment is unicolor.\nfragment_shader = \"\"\"\nvarying vec4 v_color;\nvoid main() {\n gl_FragColor = v_color;\n}\n\"\"\"\n\n\nclass ConnectVisual(visuals.Visual):\n \"\"\"Create and control a connectivity object.\n\n This class can be used to create a connectivity object with several\n embeded functions for control color, connexion types...\n\n Args:\n pos: ndarray\n Position of each node. Must be a (N, 3) array.\n\n connect: ndarray\n Connection strength between each node. Must be a (N, N) array. The\n diagonal will be systematically ignored. Alternatively, the connect\n array can be turned into a masked array so that some connections\n can be ignored (or use the select parameter to do the same trick.)\n\n Kargs:\n select: ndarray, optional, (def: None)\n Select the connexions to consider or to igore. The select array\n must be a (N, N) array of boolean values. Alternatively, use a\n masked connect array in place of this parameter.\n\n colorby: string, optional, (def: 'strength')\n Define the way of coloring connexions. Use 'strength' so that the\n color materialize the strength of connexion between two nodes. Use\n 'count' so that the color materialize the number of connections per\n node.\n\n colval: dict, optional, (def: None)\n Define colors for a specifics values. For example, c_colval=\n {1.5: 'red', 2.1: 'blue'} every connexions equal to 1.5 are going\n to be red and blue for 2.1. Use np.nan: 'gray' in order to define\n the color of all connexions that are not in the dictionary\n otherwise they are going to be ignored.\n\n dynamic: tuple, optional, (def: None)\n Dynamic transparency. The dynamic parameter must be a tuple of two\n floats, each one between 0 (include) and 1 (include) and\n dynamic[0] < dynamic[1]. Connexion line transparency will be\n normalized between dynamic[0] and dynamic[1] and will be\n proportional to the connexion strength so that weakest\n connexion strength will be more transparent. This parameter is\n usefull to add some depth to the plot.\n\n cmap: string, optional, (def: 'viridis')\n The matplotlib colormap to use.\n\n clim: tuple/list, optional, (def: None)\n Limit of the colormap. The clim parameter must be a tuple / list\n of two float number each one describing respectively the (min, max)\n of the colormap. Every values under clim[0] or over clim[1] will\n peaked.\n\n vmin: float, optional, (def: None)\n Threshold from which every color will have the color defined using\n the under parameter bellow.\n\n under: tuple/string, optional, (def: None)\n Matplotlib color for values under vmin.\n\n vmax: float, optional, (def: None)\n Threshold from which every color will have the color defined using\n the over parameter bellow.\n\n over: tuple/string, optional, (def: 'darkred')\n Matplotlib color for values over vmax.\n \"\"\"\n\n def __init__(self, pos, connect, select=None, colorby='strength',\n dynamic=None, colval=None, cmap='viridis', clim=None,\n vmin=None, under=None, vmax=None, over=None):\n \"\"\"Init.\"\"\"\n # Initialize the vispy.Visual class with the vertex / fragment buffer :\n visuals.Visual.__init__(self, vertex_shader, fragment_shader)\n\n # Save variables :\n self.pos = pos\n self.connect = connect\n self.select = select\n self.colorby = colorby\n self.dynamic = dynamic\n self.colval = colval\n self._cmap = cmap\n self._vmin, self._vmax = vmin, vmax\n self._under, self._over = under, over\n self._clim = clim\n\n # Set data connexions :\n self.set_data(self.connect, self.select)\n\n # Bind data with lines :\n self._draw_mode = 'lines'\n # self.set_gl_state('translucent', depth_test=False, cull_face=False)\n\n def _prepare_transforms(self, view):\n \"\"\"This is call for the first rendering.\"\"\"\n tr = view.transforms\n view_vert = view.view_program.vert\n # view_frag = view.view_program.frag\n view_vert['transform'] = tr.get_transform()\n\n # ========================================================================\n # ========================================================================\n # CHECK INPUTS (position / data / color)\n # ========================================================================\n # ========================================================================\n def _check_position(self, pos):\n \"\"\"Check if position is a float32 type.\n\n Args:\n pos: ndarray\n Position of each node. Must be a (N, 3) array.\n \"\"\"\n if pos.shape[1] != 3:\n raise ValueError('Position must be an Nx3 matrix')\n self.pos = pos.astype(np.float32)\n\n def _check_data(self, connect, select):\n \"\"\"Check connect and select matrices.\n\n Args:\n connect: ndarray\n Connection strength between each node. Must be a (N, N) array.\n The diagonal will be systematically ignored. Alternatively, the\n connect array can be turned into a masked array so that some\n connections can be ignored (or use the select parameter to do\n the same trick.)\n\n select: ndarray, optional, (def: None)\n Select the connexions to consider or to igore. The select array\n must be a (N, N) array of boolean values. Alternatively, use a\n masked connect array in place of this parameter.\n \"\"\"\n N = self.pos.shape[0]\n # Chech array :\n if (connect.shape != (N, N)) or not isinstance(connect, np.ndarray):\n raise ValueError(\"c_connect must be an array of \"\n \"shape \" + str((N, N)))\n if select is None:\n select = np.ones_like(connect)\n if (select.shape != (N, N) or not isinstance(select, np.ndarray)):\n raise ValueError(\"c_select must be an array of \"\n \"shape \" + str((N, N)))\n # Mask c_connect :\n try:\n connect.mask\n except:\n connect = np.ma.masked_array(connect, mask=True)\n connect.mask[select.nonzero()] = False\n # Use specific color values :\n if (self.colval is not None) and isinstance(self.colval, dict):\n mask = np.ones_like(connect.mask)\n for k, v in zip(self.colval.keys(), self.colval.values()):\n mask[connect.data == k] = False\n self.colval[k] = color2vb(v)\n connect.mask = mask\n self.connect = connect\n\n def _check_color(self, colorby, cmap, dynamic):\n \"\"\"Check color parameter.\n\n Args:\n colorby: string, optional, (def: 'strength')\n Define the way of coloring connexions. Use 'strength' so that\n the color materialize the strength of connexion between two\n nodes. Use 'count' so that the color materialize the number of\n connections per node.\n\n cmap: string, optional, (def: 'viridis')\n The matplotlib colormap to use.\n\n dynamic: tuple, optional, (def: None)\n Dynamic transparency. The dynamic parameter must be a tuple of\n two floats, each one between 0 (include) and 1 (include) and\n dynamic[0] < dynamic[1]. Connexion line transparency will be\n normalized between dynamic[0] and dynamic[1] and will be\n proportional to the connexion strength so that weakest\n connexion strength will be more transparent. This parameter is\n usefull to add some depth to the plot.\n \"\"\"\n # Check colorby :\n if self.colorby not in ['count', 'strength']:\n raise ValueError(\"The colorby parameter must be 'count' or \"\n \"'strength'\")\n # Test dynamic :\n if (dynamic is not None) and not isinstance(dynamic, tuple):\n raise ValueError(\"dynamic bust be a tuple\")\n\n # ========================================================================\n # ========================================================================\n # SET FUNCTIONS (position / data / color / opacity)\n # ========================================================================\n # ========================================================================\n def set_position(self, pos):\n \"\"\"Set the position of each node.\n\n Args:\n pos: ndarray\n Position of each node. Must be a (N, 3) array.\n \"\"\"\n # Check pos :\n self._check_position(pos)\n # Set and update pos :\n self.a_position = np.zeros((2*len(self._nnz_x), 3), dtype=np.float32)\n self.a_position[self._Nindices, :] = self.pos[self._indices, :]\n self.update_position()\n\n def set_data(self, connect, select=None):\n \"\"\"Set connection strength and select non-masked connexions.\n\n Args:\n connect: ndarray\n Connection strength between each node. Must be a (N, N) array.\n The diagonal will be systematically ignored. Alternatively, the\n connect array can be turned into a masked array so that some\n connections can be ignored (or use the select parameter to do\n the same trick.)\n\n Kargs:\n select: ndarray, optional, (def: None)\n Select the connexions to consider or to igore. The select array\n must be a (N, N) array of boolean values. Alternatively, use a\n masked connect array in place of this parameter.\n \"\"\"\n # Check data :\n self._check_data(connect, select)\n # Find non-zero elements :\n self._non_zero_select()\n # Update data :\n self.set_color(colorby=self.colorby, dynamic=self.dynamic,\n cmap=self._cmap, vmin=self._vmin, vmax=self._vmax,\n under=self._under, over=self._over)\n # Update position :\n self.set_position(self.pos)\n\n def _non_zero_select(self):\n \"\"\"Find non zeros indices and connection values.\n\n This method find where there is non-masked connections.\n \"\"\"\n self._nnz_x, self._nnz_y = np.where(~self.connect.mask)\n self._indices = np.c_[self._nnz_x, self._nnz_y].flatten()\n self._Nindices = np.arange(len(self._indices))\n\n def set_color(self, colorby='strength', dynamic=False, cmap='viridis',\n clim=None, vmin=None, under=None, vmax=None, over=None):\n \"\"\"Set the connexions colors, either by strength or count.\n\n This method can be used to assign colors to the connexions, either\n coloring by connexions strength or coloring by the number of connexions\n per node.\n\n Kargs:\n colorby: string, optional, (def: 'strength')\n Define the way of coloring connexions. Use 'strength' so that\n the color materialize the strength of connexion between two\n nodes. Use 'count' so that the color materialize the number of\n connections per node.\n\n dynamic: tuple, optional, (def: None)\n Dynamic transparency. The dynamic parameter must be a tuple of\n two floats, each one between 0 (include) and 1 (include) and\n dynamic[0] < dynamic[1]. Connexion line transparency will be\n normalized between dynamic[0] and dynamic[1] and will be\n proportional to the connexion strength so that weakest\n connexion strength will be more transparent. This parameter is\n usefull to add some depth to the plot.\n\n cmap: string, optional, (def: 'viridis')\n The matplotlib colormap to use.\n\n clim: tuple/list, optional, (def: None)\n Limit of the colormap. The clim parameter must be a tuple /\n list of two float number each one describing respectively the\n (min, max) of the colormap. Every values under clim[0] or over\n clim[1] will peaked.\n\n vmin: float, optional, (def: None)\n Threshold from which every color will have the color defined\n using the under parameter bellow.\n\n under: tuple/string, optional, (def: None)\n Matplotlib color for values under vmin.\n\n vmax: float, optional, (def: None)\n Threshold from which every color will have the color defined\n using the over parameter bellow.\n\n over: tuple/string, optional, (def: 'darkred')\n Matplotlib color for values over vmax.\n \"\"\"\n # Check color elements :\n self._check_color(colorby, cmap, dynamic)\n\n # Colorby strength of connection :\n if colorby == 'strength':\n # Get non-zeros-values :\n nnz_values = self.connect.compressed()\n # Concatenate in alternance all non-zero values :\n self._all_nnz = np.c_[nnz_values, nnz_values].flatten()\n # Get looping indices :\n self._loopIndex = self._Nindices\n\n # Colorby count on each node :\n elif colorby == 'count':\n # Count the number of occurence for each node :\n node_count = Counter(np.ravel([self._nnz_x, self._nnz_y]))\n self._all_nnz = np.array([node_count[k] for k in self._indices])\n # Get looping indices :\n self._loopIndex = self._Nindices\n\n # Get (min / max) :\n self._MinMax = (self._all_nnz.min(), self._all_nnz.max())\n\n # Get associated colormap :\n if (self.colval is not None) and isinstance(self.colval, dict):\n # Build a_color and send to buffer :\n self.a_color = np.zeros((2*len(self._nnz_x), 4), dtype=np.float32)\n for k, v in zip(self.colval.keys(), self.colval.values()):\n self.a_color[self._all_nnz == k, :] = v\n else:\n colormap = array2colormap(self._all_nnz, cmap=cmap, vmin=vmin,\n vmax=vmax, under=under, over=over,\n clim=clim)\n\n # Dynamic alpha :\n if (dynamic is not False) and isinstance(dynamic, tuple):\n colormap[:, 3] = normalize(self._all_nnz, tomin=dynamic[0],\n tomax=dynamic[1])\n\n # Build a_color and send to buffer :\n self.a_color = np.zeros((2*len(self._nnz_x), 4), dtype=np.float32)\n self.a_color[self._Nindices, :] = colormap[self._loopIndex, :]\n self.update_color()\n\n def set_opacity(self, alpha=1.):\n \"\"\"Set transparency level of each connexion.\n\n Kargs:\n alpha: float, optional, (def: 1.)\n The transparency level. This parameter must be a float number\n between 0. and 1.\n \"\"\"\n N = self.a_color.shape[0]\n if isinstance(alpha, (int, float)):\n alpha_vec = np.full((N,), alpha)\n elif isinstance(alpha, np.ndarray) and (len(alpha) != N):\n raise ValueError(\"The length of alpha must be \" + str(N))\n else:\n alpha_vec = alpha.ravel()\n self.a_color[:, 3] = alpha_vec\n self.update_color()\n\n # ========================================================================\n # ========================================================================\n # UPDATE FUNCTIONS (position / color)\n # ========================================================================\n # ========================================================================\n def update_position(self):\n \"\"\"Update node positions.\"\"\"\n self.shared_program.vert['a_position'] = gloo.VertexBuffer(\n self.a_position.astype(np.float32))\n\n def update_color(self):\n \"\"\"Update connexions colors.\"\"\"\n self.shared_program.vert['a_color'] = gloo.VertexBuffer(\n self.a_color.astype(np.float32))\n\n # ========================================================================\n # ========================================================================\n # GET FUNCTIONS (position / data / color / opacity)\n # ========================================================================\n # ========================================================================\n @property\n def get_position(self):\n \"\"\"Get nodes positions.\"\"\"\n return self.shared_program.vert['a_position']\n\n @property\n def get_color(self):\n \"\"\"Get connexions colors.\"\"\"\n return self.shared_program.vert['a_color']\n\n @property\n def get_MinMax(self):\n \"\"\"Get the (min, max) connexions strength.\"\"\"\n return self._MinMax\n\nConnectMesh = create_visual_node(ConnectVisual)\n","sub_path":"visbrain/visuals/ConnectVisual.py","file_name":"ConnectVisual.py","file_ext":"py","file_size_in_byte":18363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"398771142","text":"from mcpi.minecraft import Minecraft\nmc = Minecraft.create()\npos = mc.player.getPos()\nx = pos.x\ny = pos.y\nz = pos.z\nblockType = mc.getBlock(x, y, z)\nBT = mc.getBlock(x, y + 1, z)\nUW = blockType == 9 and BT == 9\nmc.postToChat(\"The player is under water: \" + str(UW))\n","sub_path":"Better swimming.py","file_name":"Better swimming.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84688277","text":"from keras.layers import Input, Lambda, Dense, Flatten\nfrom keras.models import Model\nfrom keras.layers import GlobalAveragePooling2D\nfrom keras.applications.xception import Xception, preprocess_input\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom sklearn.metrics import confusion_matrix\nfrom keras import optimizers\nimport numpy as np\nfrom glob import glob\nimport matplotlib.pyplot as plt\n# from __future__import print_function, division\nimport keras\n\n\nimage_format = (299, 299)\ntrainingDirectory = 'Training'\nvalidationDirectory = 'Testing'\nimage_files = glob(trainingDirectory + '/*/*.jp*g')\nvalid_image_files = glob(validationDirectory + '/*/*.jp*g')\nimageNetWeights = 'imagenet'\nreluAlgorithm = 'relu'\nsoftmaxAlgorithm = 'softmax'\ncategoricalCrossentropyAlgorithm = 'categorical_crossentropy'\nadamOptimizer = 'adam'\ntrainingBatchSize = 100\ntestingBatchSize = 50\nepochNumber = 5\nepochSteps = 10\nclassificationClasses = 8\ncolorMode = 'rgb'\nvalidationAccuracy = 'val_acc'\nvalidationLoss = 'val_loss'\ntrainingAccuracy = 'acc'\ntrainingLoss = 'loss'\n\npreTrainedAlgorithm = Xception(input_shape = (299, 299, 3), weights = imageNetWeights,\n include_top = False)\n\nx = preTrainedAlgorithm.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation='relu')(x)\n\nprediction = Dense(classificationClasses, activation = softmaxAlgorithmsoft)(x)\ncustomModel = Model(inputs = preTrainedAlgorithm.input, outputs = prediction)\ncustomModel.layers[0].trainable = False\ncustomModel.summary()\n\ncallbacks_list = [\n keras.callbacks.ModelCheckpoint(\n filepath='best_model.{epoch:02d}-{val_loss:.2f}.h5',\n monitor= validationLoss, save_best_only=True),\n keras.callbacks.EarlyStopping(monitor= validationAccuracy, patience=1)\n ]\n\ncustomModel.compile(loss = categoricalCrossentropyAlgorithm,\n optimizer = adamOptimizer,\n metrics = ['accuracy'])\n\n\ntrainingDataGenerator = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2,\n horizontal_flip = True, rotation_range = 20)\n\ntestingDataGenerator = ImageDataGenerator(rescale = 1./255)\n\n# get label mapping for confusion matrix plot later\n#test_gen = trainingDataGenerator.flow_from_directory(validationDirectory, target_size=(299, 299))\n#labels = [None] * len(test_gen.class_indices)\n#for k, v in test_gen.class_indices.items():\n# labels[v] = k\n##\n## should be a strangely colored image (due to VGG weights being BGR)\n#for x, y in test_gen:\n# plt.title(labels[np.argmax(y[0])])\n# plt.imshow(x[0])\n# plt.show()\n# break\n\naugmentedTrainingData = trainingDataGenerator.flow_from_directory('Training',\n target_size = image_format,\n batch_size = trainingBatchSize,\n class_mode = 'categorical',\n color_mode= colorMode,\n shuffle=True)\n\naugmentedTestingData = testingDataGenerator.flow_from_directory('Testing',\n target_size = image_format,\n batch_size = testingBatchSize,\n class_mode = 'categorical',\n color_mode = colorMode,\n shuffle = False)\n\n#r = customModel.fit_generator(augmentedTrainingData, validation_data = augmentedTestingData,\n# epochs = epochNumber, steps_per_epoch = epochSteps,\n# validation_steps = len(augmentedTestingData))\n\n\n#def get_confusion_matrix(data_path, N, trainingBatchSize):\n# # we need to see the data in the same order\n# # for both predictions and targets\n# print(\"Generating confusion matrix\", N)\n# predictions = []\n# targets = []\n# i = 0\n# for x, y in trainingDataGenerator.flow_from_directory(data_path, \n# target_size=(299, 299), \n# shuffle=False, \n# batch_size=trainingBatchSize * 2):\n# \n# i += 1\n# if i % 50 == 0:\n# print(i)\n# p = customModel.predict(x)\n# p = np.argmax(p, axis=1)\n# y = np.argmax(y, axis=1)\n# predictions = np.concatenate((predictions, p))\n# targets = np.concatenate((targets, y))\n# if len(targets) >= N:\n# break\n# cm = confusion_matrix(targets, predictions)\n# return cm\n#\n#cm = get_confusion_matrix(trainingDirectory, len(image_files), trainingBatchSize)\n#print(cm)\n#valid_cm = get_confusion_matrix(validationDirectory, len(valid_image_files), testingBatchSize)\n#print(valid_cm)\n\n# accuracies\n#plt.plot(r.history['acc'], label='train acc')\n#plt.plot(r.history['val_acc'], label='val acc')\n#plt.legend()\n#plt.show()\n#\n## loss\n#plt.plot(r.history['loss'], label='train loss')\n#plt.plot(r.history['val_loss'], label='val loss')\n#plt.legend()\n#plt.show()\n#\n#import tensorflow as tf\n#from keras.models import load_model\n#customModel.save('KFC_new_model4.h5')\n","sub_path":"Transfer Learning with Xception/KFCTransferLearningXception3.py","file_name":"KFCTransferLearningXception3.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453815768","text":"import pytest\nimport warnings\n\nfrom tests.conftest import DATADIR, validate_host_shape\nimport pandas as pd\n\n\ndef validate_vlan_tbl(df: pd.DataFrame):\n '''Validate the VLAN table for all values'''\n\n assert (df.vlan != 0).all()\n if not (df.query('vlan != 1').interfaces.str.len() != 0).all():\n warnings.warn(f'Some VLANs not assigned to any interface')\n assert (df.state == 'active').all()\n assert (df.vlanName != '').all()\n\n\n@ pytest.mark.parsing\n@ pytest.mark.vlan\n@ pytest.mark.parametrize('table', ['vlan'])\n@ pytest.mark.parametrize('datadir', DATADIR)\ndef test_vlan_parsing(table, datadir, get_table_data):\n '''Main workhorse routine to test parsed output for VLAN table'''\n\n df = get_table_data\n\n ns_dict = {\n 'eos': 9,\n 'junos': 7,\n 'nxos': 9,\n 'ospf-ibgp': 6,\n 'mixed': 6,\n }\n\n if datadir.endswith(('vmx/parquet-out')):\n # mixed dataset has no evpn\n assert (True)\n return\n\n assert not df.empty\n\n validate_host_shape(df, ns_dict)\n validate_vlan_tbl(df)\n","sub_path":"tests/integration/test_parsing_vlan.py","file_name":"test_parsing_vlan.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"80175594","text":"'''给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。\n\n示例 1:\n\n输入: S = \"loveleetcode\", C = 'e'\n输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]\n说明:\n\n字符串 S 的长度范围为 [1, 10000]。\nC 是一个单字符,且保证是字符串 S 里的字符。\nS 和 C 中的所有字母均为小写字母。'''\n\n\nclass Solution:\n def shortestToChar(self, S, C):\n \"\"\"\n :type S: str\n :type C: str\n :rtype: List[int]\n \"\"\"\n list_out=[0 for i in range(len(S))]\n start=-1\n for i in range(len(S)):\n if S[i]!=C:\n if start+1==0:\n for j in range(i,start,-1):\n list_out[j]+=1\n else:\n list_out[i]=i-start\n elif S[i]==C:\n if start+1!=0:\n for j in range((start+i+1)//2,i):\n list_out[j]=i-j\n start=i\n return list_out\nS=\"sabasdfsadfewsssssseeeeeeeeeeeeeeeeeeeeeeeeeeeesfv\"\nC='s'\ns=Solution()\nprint(s.shortestToChar(S,C))\n","sub_path":"Questions/821. 字符的最短距离.py","file_name":"821. 字符的最短距离.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"140129572","text":"import sys\nimport os\nimport random\n\nfrom config import INPUT_DIRECTORY\nfrom config import OUTPUT_DIRECTORY\n\nfrom InputReader import InputReader\nfrom write import write\n\nfrom slide import Slide\nfrom count import get_pics_per_tags\n\nfrom graph import build_graph\nfrom graph import crawl_graph\n\nfrom score import get_current_best_score\nfrom score import slideshow_score\n\nif __name__ == '__main__':\n # Get input file from command line arg list\n input_file = sys.argv[1]\n file_path = os.path.join(INPUT_DIRECTORY, input_file)\n assert os.path.exists(file_path)\n\n # Get current best scores\n best_scores = get_current_best_score()\n initial_best_score = best_scores.get(input_file, 0)\n best_score = initial_best_score\n\n # Get objects from input file\n inputReader = InputReader(file_path)\n pics = inputReader.photos\n\n # Filter on horizontal pics\n pics = {k: v for k, v in pics.items() if v.orientation == 0}\n pics_id = list(pics.keys())\n\n print('Trying to sort %s H pics...' % len(pics_id))\n\n # Get pics per tag index\n pics_per_tag = get_pics_per_tags(pics)\n\n # Do better\n output = []\n\n print('Starting computation...')\n keep_going = True\n i = 0\n while keep_going:\n try:\n current_output = []\n\n # Build graph\n graph = build_graph(pics, pics_per_tag)\n\n path = []\n starting_node = random.choice(pics_id)\n\n # Go as far as possible\n while len(path) < len(pics_id):\n print('Crawling graph (current path=%s)...' % len(path))\n path += crawl_graph(graph, starting_node)\n\n if len(path) == len(pics_id):\n break\n else:\n path_set = set(path)\n remaining_nodes = [node_id for node_id in pics_id if node_id not in path_set]\n\n best_starting_node = None\n best_starting_node_neighbour_count = 0\n for uid in remaining_nodes:\n reachable_node_count = len(graph.get_reachable_node(uid))\n if reachable_node_count > best_starting_node_neighbour_count:\n best_starting_node = uid\n best_starting_node_neighbour_count = reachable_node_count\n\n if best_starting_node is not None:\n starting_node = best_starting_node\n else:\n break\n\n for uid in path:\n current_output.append(Slide(pics[uid]))\n\n current_score = slideshow_score(current_output)\n\n if best_score < current_score:\n print()\n print('Found a better solution (+%s)' % (current_score - best_score))\n output = current_output\n best_score = current_score\n else:\n print(\n 'Better solution not found: %s (len: %s) < %s)' % (current_score, len(current_output), best_score))\n\n except KeyboardInterrupt:\n keep_going = False\n print()\n\n # Save result to output file only if better solution found\n if initial_best_score < best_score:\n print('Better solution found! (+%s)' % (best_score - initial_best_score))\n\n output_file = os.path.splitext(input_file)[0] + '.out'\n out_path = os.path.join(OUTPUT_DIRECTORY, output_file)\n\n write(output, out_path)\n else:\n print('No better solution found :(')\n","sub_path":"graph_main.py","file_name":"graph_main.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"323079678","text":"def multiply_matrices(m1_matrix, m2_matrix):\n \"\"\"Multiplies the matrices m1_matrix and m2_matrix and returns the result matrix\"\"\"\n # Create an empty result matrix filled with 0's\n result_matrix = []\n for i in range(len(m1_matrix)):\n result_matrix.append([0] * len(m2_matrix[0]))\n\n for i in range(len(m1_matrix)):\n m_row = m1_matrix[i]\n for j in range(len(m2_matrix[0])):\n n_column = []\n for b in range(len(m2_matrix)):\n n_column.append(m2_matrix[b][j])\n\n for k in range(len(m_row)):\n result_matrix[i][j] += m_row[k] * n_column[k]\n\n return result_matrix\n\n\ndef perform_pivoting(m_matrix):\n \"\"\"Performs any necessary pivoting on m_matrix (making any changes in place)\n and returns its pivoting matrix\"\"\"\n\n m_size = len(m_matrix)\n\n # Create an identity matrix, with floating point values\n id_matrix = [[float(i == j) for i in range(m_size)] for j in range(m_size)]\n\n # Rearrange the id_matrix so that the largest absolute element of each column\n # of m_matrix is placed on the diagonal of m_matrix\n for j in range(m_size):\n max_row = j\n max_value = abs(m_matrix[j][j])\n for i in range(j, m_size):\n if abs(m_matrix[i][j]) > max_value:\n max_row = i\n max_value = m_matrix[i][j]\n\n if j != max_row:\n # Swap the affected rows\n id_matrix[j], id_matrix[max_row] = id_matrix[max_row], id_matrix[j]\n m_matrix[j], m_matrix[max_row] = m_matrix[max_row], m_matrix[j]\n\n return id_matrix\n\n\ndef perform_pa_lu_decomposition(a_matrix):\n \"\"\"Performs a PA = LU decomposition on a_matrix (a_matrix must be a square matrix)\n The function returns matrices P, L and U.\"\"\"\n\n a_size = len(a_matrix)\n\n # Create zero matrices for L and U\n l_matrix = []\n for i in range(a_size):\n l_matrix.append([0.0] * a_size)\n\n u_matrix = []\n for i in range(a_size):\n u_matrix.append([0.0] * a_size)\n\n # Create the PA matrix, which is the result of A matrix after performing any necessary pivoting\n # Initialize PA matrix using the the A matrix\n pa_matrix = a_matrix.copy()\n\n # Create the pivot matrix P\n p_matrix = perform_pivoting(pa_matrix)\n\n # Perform the PA = LU decomposition\n for j in range(a_size):\n # Set all diagonal elements of l_matrix to 1.0\n l_matrix[j][j] = 1.0\n\n for i in range(j+1):\n s1 = 0\n for k in range(i):\n s1 += u_matrix[k][j] * l_matrix[i][k]\n\n u_matrix[i][j] = pa_matrix[i][j] - s1\n\n for i in range(j, a_size):\n s2 = 0\n for k in range(j):\n s2 += u_matrix[k][j] * l_matrix[i][k]\n\n l_matrix[i][j] = (pa_matrix[i][j] - s2) / u_matrix[j][j]\n\n return p_matrix, l_matrix, u_matrix\n\n\ndef gauss(a_matrix, b_vector):\n # Perform the PA=LU decomposition of the given A matrix\n p_matrix, l_matrix, u_matrix = perform_pa_lu_decomposition(a_matrix)\n\n # Ax = b => PAx = Pb => LUx = Pb => Lc = Pb when Ux = c\n\n # Create c vector\n c_vector = [0.0] * len(l_matrix)\n\n # Convert b_vector to the format used for matrices\n b_matrix = []\n for elem in b_vector:\n b_matrix.append([float(elem)])\n\n # Calculate Pb\n pb_matrix = multiply_matrices(p_matrix, b_matrix)\n\n # Calculate c_vector by solving Lc = Pb\n for c in range(len(c_vector)):\n c_vector[c] = pb_matrix[c][0] - sum(c_vector[j] * l_matrix[c][j] for j in range(c) if c > 0)\n\n # Create x vector\n x_vector = [0.0] * len(u_matrix)\n\n # Convert c_vector to the format used for matrices\n c_matrix = []\n for elem in c_vector:\n c_matrix.append([float(elem)])\n\n # Calculate x_vector by solving Ux = c\n for x in range(len(x_vector) - 1, -1, -1):\n x_vector[x] = c_vector[x] / u_matrix[x][x] - sum(u_matrix[x][j] * x_vector[j] / u_matrix[x][x] for j in range(len(u_matrix) - 1, x, -1))\n\n return x_vector\n\n\n# Example of use\nA = [[2.0, 1.0, 5.0], [4.0, 4.0, -4.0], [1.0, 3.0, 1.0]]\nb = [5.0, 0.0, 6.0]\n\nprint(\"*** Result ***\")\nprint(\"x vector is: \", gauss(A, b))\n","sub_path":"Final for grading/Code/task-3/pa_lu_gauss.py","file_name":"pa_lu_gauss.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"21862413","text":"from math import isnan\nfrom datetime import datetime, timedelta\nfrom pybaseball import schedule_and_record\nfrom .sports_helper import SportsHelper\n\n\nclass Sports:\n \"\"\"Class which allows Marvin to retrieve sports scores.\n\n Attributes:\n helper: A SportsHelper object which assists with the\n interpretation of user commands.\n \"\"\"\n\n def __init__(self):\n self.helper = SportsHelper()\n\n def route_command(self, command, say, listen):\n \"\"\"Executes and generates a string response for a given sports\n command.\n\n Args:\n command: a string command which requests some action or\n information related to sports.\n say: A function which will say (either through text to speech\n or printing) a string in the main speaker loop\n listen: A function which will listen and record user input\n through either speech to text or through the CLI\n Returns:\n True if a command was executed (or failed while executed) and\n false if the command was invalid.\n \"\"\"\n label, args = self.helper.parse_command(command)\n # if the game was today\n if label == \"result today\":\n today = datetime.utcnow().date()\n current_year = today.year\n dataframe = schedule_and_record(\n current_year, self.helper.baseball_teams_to_abbrev[args])\n index = self.helper.dataframe_first_instance_of(\n dataframe, self.helper.date_to_dataframe_index(today))\n if index == -1:\n say(\"Could not find information about that game at this\\\ntime\")\n return True\n opp = self.helper.abbrev_to_baseball_teams[dataframe['Opp'][index]]\n runs = dataframe['R'][index]\n if not isnan(runs) or isnan(index):\n runs = int(dataframe['R'][index])\n runs_against = int(dataframe['RA'][index])\n if runs > runs_against:\n response = \"The {} beat the {} today, {} to {}\".format(\n args, opp, runs, runs_against)\n else:\n response = \"The {} lost to the {} today, {} to {}\".format(\n args, opp, runs, runs_against)\n else:\n response = \"Could not find information about that game at this\\\ntime\"\n say(response)\n # if the game was yesterday\n elif label == \"result yesterday\":\n yesterday = datetime.utcnow().date() - timedelta(1)\n current_year = yesterday.year\n dataframe = schedule_and_record(\n current_year, self.helper.baseball_teams_to_abbrev[args])\n index = self.helper.dataframe_first_instance_of(\n dataframe, self.helper.date_to_dataframe_index(yesterday))\n if index == -1 or isnan(index):\n say(\"Could not find information about that game at this\\\ntime\")\n return True\n opp = self.helper.abbrev_to_baseball_teams[dataframe['Opp'][index]]\n runs = dataframe['R'][index]\n if not isnan(runs):\n runs = int(dataframe['R'][index])\n runs_against = int(dataframe['RA'][index])\n if runs > runs_against:\n response = \"The {} beat the {} yesterday, {} to {}\".format(\n args, opp, runs, runs_against)\n else:\n response = \"The {} lost to the {} yesterday, {} to {}\".format(\n args, opp, runs, runs_against)\n else:\n response = \"Could not find information about that game at this\\\ntime\"\n say(response)\n # if the game was on a day of the week which was specified\n elif label == \"result specific\":\n day = self.helper.day_of_week_to_date(args['day'], datetime.utcnow().date())\n current_year = day.year\n dataframe = schedule_and_record(\n current_year, self.helper.baseball_teams_to_abbrev[args['team']])\n index = self.helper.dataframe_first_instance_of(\n dataframe, self.helper.date_to_dataframe_index(day))\n if index == -1 or isnan(index):\n say(\"Could not find information about that game at this\\\ntime\")\n return True\n opp = self.helper.abbrev_to_baseball_teams[dataframe['Opp'][index]]\n runs = dataframe['R'][index]\n if not isnan(runs):\n runs = int(runs)\n runs_against = int(dataframe['RA'][index])\n if runs > runs_against:\n response = \"The {} beat the {} on {}, {} to {}\".format(\n args['team'], opp, args['day'], runs, runs_against)\n else:\n response = \"The {} lost to the {} on {}, {} to {}\".format(\n args['team'], opp, args['day'], runs, runs_against)\n else:\n response = \"Could not find information about that game at this\\\ntime\"\n say(response)\n elif label == \"record\":\n current_year = datetime.utcnow().date().year\n dataframe = schedule_and_record(\n current_year, self.helper.baseball_teams_to_abbrev[args])\n record = self.helper.dataframe_last_non_nan(dataframe)\n if record == \"\":\n say(\"Could not find information about that season at this\\\ntime\")\n else:\n wins, losses = record.split(\"-\")\n response = \"The {}\\'s record this season is {} wins and {} \\\nlosses\".format(\n args, wins, losses\n )\n say(response)\n else:\n return False\n return True\n","sub_path":"modules/sports/sports.py","file_name":"sports.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"93829888","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nimport config as c\n\n\ndef send_simple_message(target_email, subject, message):\n \"\"\"send email to users\"\"\"\n return requests.post(\n \"https://api.eu.mailgun.net/v3/mg.london-man.com/messages\",\n auth=(\"api\", c.MGKEY),\n data={\n \"from\": \"Coronavirus Map \",\n \"to\": target_email,\n \"subject\": subject,\n \"text\": message,\n },\n )\n","sub_path":"core/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"149135568","text":"from zipfile import ZipFile, is_zipfile\n\nimport subprocess # nosec\nimport os\n\nfrom talentmap_api.settings import get_delineated_environment_variable\nlog_dir = get_delineated_environment_variable('DJANGO_LOG_DIRECTORY', '/var/log/talentmap/')\n\n\ndef get_log_list():\n files = []\n for file in os.listdir(log_dir):\n if file.endswith('.log'):\n files.append(file)\n\n return {\n \"data\": files\n }\n\n\ndef get_log(log_name, size=1000):\n lines = \"\"\n file_name = f\"{log_dir}{log_name}\"\n if os.path.exists(f\"{file_name}\"):\n try:\n if is_zipfile(file_name):\n with ZipFile(f\"{file_name}\") as myzip:\n for f in myzip.namelist():\n with myzip.open(f) as myfile:\n lines = myfile.read()\n else:\n lines = tail(file_name, size)\n except FileNotFoundError:\n return None\n return {\n \"data\": lines\n }\n\n\ndef tail(f, n):\n proc = subprocess.Popen(['tail', '-n', str(n), f], stdout=subprocess.PIPE) # nosec\n lines = proc.stdout.readlines()\n lines = ''.join(bytes.join(b'', lines).decode('ascii'))\n return lines\n","sub_path":"talentmap_api/log_viewer/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"198978785","text":"from mlworkflow import Operator\nfrom easydict import EasyDict as edict\n\n#from __future__ import print_function\nimport argparse\nimport os\nimport random\nimport numpy as np\nimport scipy.io as sio\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.utils.data\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\n\nfrom code.sohil.models import _netG\n\n#parser = argparse.ArgumentParser()\n#parser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\n#parser.add_argument('--ngf', type=int, default=64)\n#parser.add_argument('--samples', type=int, default=10000)\n#parser.add_argument('--imageSize', type=int, default=32, help='the height / width of the input image to network')\n#parser.add_argument('--cuda', action='store_true', help='enables cuda')\n#parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\n#parser.add_argument('--nc', type=int, default=3)\n#parser.add_argument('--classindex', type=int, default=0)\n#parser.add_argument('--netG', default='', help=\"path to netG (to load model)\")\n#parser.add_argument('--outf', default='/fs/vulcan-scratch/sohil/distGAN/checkpoints',\n# help='folder to output images and model checkpoints')\n#parser.add_argument('--manualSeed', type=int, help='manual seed')\n#parser.add_argument('--forward', help='Computes Jacobian using Forward pass', action='store_true')\n#\n#opt = parser.parse_args()\n#print(opt)\n\n# ---\n\nclass SampleGAN(Operator):\n def __init__(self, config, args):\n super(SampleGAN,self).__init__(config, args)\n opt = {\n 'samples':1000,\n 'forward':True\n }\n opt.update(args)\n self.opt = edict(opt)\n\n assert(len(self.dependencies) > 0)\n self.loader = self.dependencies[0]\n\n def run(self):\n self.log(\"Using options %s\"%str(self.opt))\n\n problem = self.loader.getSamplingGAN()\n netG = problem['netG']\n opt = problem['opt']\n\n samples = self.opt.samples # Different opt\n ngpu = opt.ngpu\n nz = opt.nz\n ngf = opt.ngf\n nc = opt.nc\n\n epsilon = 1e-5\n if self.opt.forward:\n noise = torch.FloatTensor(2*nz+1, nz, 1, 1)\n else:\n noise = torch.FloatTensor(1, nz, 1, 1)\n a = torch.FloatTensor(1,nz)\n b = torch.eye(nz) * epsilon\n\n # Perform in loader??\n if opt.cuda:\n noise = noise.cuda()\n a = a.cuda()\n b = b.cuda()\n\n gauss_const = -np.log10(np.sqrt(2*np.pi)**nz)\n log_const = np.log10(np.exp(1))\n images = np.empty([samples,nc,opt.imageSize,opt.imageSize])\n prob = np.empty([samples])\n jacob = np.empty([samples,nz])\n code = np.empty([samples,nz])\n nX = nc*opt.imageSize**2\n\n netG.eval()\n for i in range(samples):\n if i%10 == 0:\n self.log(\"Sample %d\"%i)\n\n J = np.empty([nX, nz])\n # Generate sample noise\n a.normal_(0,1)\n if self.opt.forward:\n # Generate sequence of small perturbation in input noise variable z\n noise.copy_(torch.cat((a, a+b, a-b),0).unsqueeze(2).unsqueeze(3))\n\n noisev = Variable(noise, volatile=True)\n fake = netG(noisev)\n\n I = fake.data.cpu().numpy().reshape(2*nz+1,-1)\n\n J = (I[1:nz+1,:] - I[nz+1:, :]).transpose() / (2*epsilon)\n else:\n noise.copy_(a.unsqueeze(2).unsqueeze(3))\n\n noisev = Variable(noise, requires_grad=True)\n fake = netG(noisev)\n fake = fake.view(1,-1)\n\n for k in range(nX):\n netG.zero_grad()\n fake[0,k].backward(retain_variables=True)\n J[k] = noisev.grad.data.cpu().numpy().squeeze()\n I = fake.data.cpu().numpy()\n\n images[i] = I[0,:].reshape(nc,opt.imageSize,opt.imageSize) # storing image\n R = np.linalg.qr(J, mode='r')\n Z = a.cpu().numpy()\n code[i] = Z.squeeze()\n dummy = R.diagonal().copy()\n # Note: Check how many are this small later\n dummy[np.where(np.abs(dummy) < 1e-20)] = 1\n jacob[i] = dummy\n prob[i] = -log_const * 0.5 * np.sum(Z**2) + gauss_const - np.log10(np.abs(dummy)).sum() # storing probabilities\n\n self.log(\"The minimum value of prob is {} and the maximum is {}\".format(min(prob), max(prob)))\n\n allData = {'images': images.astype(np.float32),\n 'code': code.astype(np.float32),\n 'prob': prob.astype(np.float32),\n 'jacob': jacob.astype(np.float32),\n }\n\n self.log(\"Saving sampled data\")\n self.files.save(allData,'samples',saver='mat') # Automatically appends thread number\n\n","sub_path":"code/sohil/SampleGAN.py","file_name":"SampleGAN.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"200484782","text":"#!/usr/bin/python3\n''' Pascals Triangle '''\n\n\ndef pascal_triangle(n):\n if n <= 0:\n return []\n\n my_list = [[1]]\n for count in range(1, n):\n row = [1]\n for elem in range(1, count):\n row.append(my_list[count - 1][elem - 1] + my_list[count - 1][elem])\n row.append(1)\n my_list.append(row)\n return my_list\n","sub_path":"0x0B-python-input_output/14-pascal_triangle.py","file_name":"14-pascal_triangle.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"19983485","text":"# server2.py : 계속 보낼값 입력해 보낼 수 있음.\nimport socket\nimport time\nimport select\n\nhost = 'MyIp' # Symbolic name meaning all available interfaces\nport = 5656 # Arbitrary non-privileged port\n \n\nserver_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#socket.SOCK_STREAM\nserver_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#assure reconnect\nserver_sock.bind((host, port))\nserver_sock.listen(5)#maximum number of clients\nprint(server_sock)\nsockets_list = [server_sock]#socket list... multiple clients \n\nclients = {}#socket is the key, user Data will be value \nreceiver_clients = {}#clients 중에서 receiver를 담을 딕셔너리\nsender_receiver_ID = {}#key is client scoekt and the value is receivers' ID list \nID_socket_convert = {}#ID is the key and the socket is the value \n\nprint(\"기다리는 중\")\n\ndef receive_message(client_socket):\n\ttry:\n\t\tdata = client_socket.recv(1024)#receive data\n\t\t\n\t\tif not len(data):\n\t\t\treturn False\n\n\t\tprint(\"receive Message : \" +data.decode('utf-8'))\n\t\treturn {\"data\" : data}\n\n\texcept:\n\t\treturn False\n\ndef get_receivers_from_sender(client_socket):#get user data \n\ttry:\n\t\tdata = client_socket.recv(1024)#receive data\n\t\t\n\t\tif not len(data):\n\t\t\treturn False\n\n\t\tprint(\"get_receivers_from_sender : \" +data.decode('utf-8'))\n\n\t\tinput_lists= [x.strip() for x in data.decode('utf-8').split(',')]\n\n\t\tprint(input_lists)\n\n\t\tID_socket_convert[input_lists[1]] = client_socket\n\n\t\tif input_lists[0] == 'sender':\n\t\t\tsender_receiver_ID[client_socket] = input_lists#sender라면 자기 보호자 리스트의 아이디를 넣어줌, \n\n\n\texcept:\n\t\treturn False\n\n\n\nwhile True:\n\tread_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)#read, write ,air on/ 연결한 클라이언트들의 소켓을 셀렉\n\n\tfor notified_socket in read_sockets:\n\t\tif notified_socket == server_sock: #someone just connected \n\t\t\tclient_socket, client_address = server_sock.accept()#accept connection\n\t\t\tprint(client_socket)\n\t\t\tprint(client_address)\n\n\t\t\tuser = receive_message(client_socket)#receive message\n\t\t\tif user is False:\n\t\t\t\tprint(\"USER FALSE\")\n\t\t\t\tcontinue\n\n\t\t\tprint(user['data'].decode('utf-8') + \" is connected \")\n\t\t\tuserType = user['data'].decode('utf-8')#유저가 receiver(보호자) 인지 아니면 sender(환자)인지 \n\t\t\t\n\t\t\tprint(userType)\n\n\t\t\t# if userType == 'receiver':\n\t\t\t# \tprint('pass receiver')\n\t\t\t# \treceiver_clients[client_socket] = user#receiver 라면 receiver_clients에 담아준다\n\t\t\t# \tprint(\"ACCEPTED AS receiver\")\n\n\t\t\tget_receivers_from_sender(client_socket)\n\n\t\t\tsockets_list.append(client_socket)\n\n\t\t\tclients[client_socket] = user #clients에 데이터를 담아준다\n\n\t\telse: \n\t\t\tmessage = receive_message(notified_socket)#누군가가 data를 보냈다면 \n\n\t\t\tif message is False :\n\t\t\t\tsockets_list.remove(notified_socket)\n\t\t\t\tdel clients[notified_socket]\n\t\t\t\tcontinue\n\n\t\t\tuser = clients[notified_socket] # same with message above, notified socekt is a socket that sends the data\n\n\n\t\t\t#print(f\"received message from {user['data'].decode('utf-8')} : {message['data'].decode('utf-8')}\")\n\n\t\t\t#share this message with everyBody\n\t\t\tprint(\"@@@@@@@@@@@\")\n\t\t\tprint(str(clients))\n\t\t\tprint(\"@@@@@@@@@@@\")\n\t\t\tfor client_socket in receiver_clients:#clients 중에서 receiver 에게만 메세지를 보냄 \n\t\t\t\t#print(\"for loop\")\n\t\t\t\t\n\t\t\t\tprint(\"------------------------\")\n\t\t\t\tif client_socket != notified_socket:\n\t\t\t\t\tmessage_to_send = message['data']\n\t\t\t\t\t\n\t\t\t\t\tprint(client_socket)\n\t\t\t\t\tprint(user['data'])#data that user send when they first connect\n\t\t\t\t\tprint(\"*****Message from\" + str(message_to_send) + \" AND \" + str(len(message_to_send)))\n\t\t\t\t\tclient_socket.send(message_to_send)#send message\n\n\t\t\t# for receivers in sender_receiver_ID[notified_socket]:\n\t\t\t# \tfor receiverID in receivers :\n\t\t\t# \t\tmessage_to_send = message['data']\n\t\t\t# \t\tprint(\"receivers\" )\n\t\t\t# \t\tif receiverID in ID_socket_convert:\n\t\t\t# \t\t\tID_socket_convert[receiverID].send(message_to_send)\n\n\t\t\t\t\t\n\t\t\t\n\t\t\t\t\n\n\n\tfor notified_socket in exception_sockets:\n\t\tsockets_list.remove(notified_socket)\n\t\tdel clients[notified_socket]\n\n\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"438188340","text":"import os\nimport sys\nimport datetime\n\ntry:\n\timport config\nexcept:\n\tpass\n\nif len(sys.argv) < 2:\n\tprint(' - manage API start')\n\tprint(' - manage content flush/create')\n\tprint(' - manage analytics update')\n\tprint(' - manage dashboard start')\n\tprint(' - manage sql ')\n\tprint(' - manage demo build')\n\tprint(' - manage configure')\n\tprint(' - manage test API/pricing/analytics/all/coverage')\nelif sys.argv[1] == 'API':\n\tif len(sys.argv) == 5:\n\t\tconfig.APIServer['address'] = sys.argv[3]\n\t\tconfig.APIServer['port'] = int(sys.argv[4])\n\tif sys.argv[2] == 'start':\n\t\timport core.api.main as main\n\t\tmain.start()\nelif sys.argv[1] == 'content':\n\tif sys.argv[2] == 'flush':\n\t\timport core.content.models as models\n\t\tmodels.flush()\n\telif sys.argv[2] == 'create':\n\t\timport core.content.models as models\n\t\tmodels.create()\nelif sys.argv[1] == 'analytics':\n\tif sys.argv[2] == 'update':\n\t\timport core.analytics.analytics as analytics\n\n\t\tlimit = None\n\t\tif len(sys.argv) > 4:\n\t\t\tprocessors = int(sys.argv[3])\n\t\t\tlimit = int(sys.argv[4])\n\t\t\tanalytics.Analytics().processUpdates(processors, limit)\n\t\telse:\n\t\t\tanalytics.Analytics().processUpdates()\n\t\t\t\nelif sys.argv[1] == 'dashboard':\n\tif sys.argv[2] == 'start':\n\t\timport core.dashboard.main as main\n\t\tmain.start()\nelif sys.argv[1] == 'sql':\n\tif len(sys.argv)>2:\n\t\timport core.content.models as models\n\t\tmodels.execute(sys.argv[2])\nelif sys.argv[1] == 'demo':\n\tanswer = input('Are you sure you want to setup demo? All data will be lost. [y/n]')\n\tanswer = answer.lower().strip()\n\tif answer == 'y':\n\t\timport core.demo as demo\n\t\tdemo.start()\n\telif answer == 'n':\n\t\tprint('Demo build aborted.')\n\telse:\n\t\tprint('Nevermind - incorrect answer. No demo will be built.')\nelif sys.argv[1] == 'configure':\n\timport core.configure as configure\n\tconfigure.run()\nelif sys.argv[1] == 'export':\n\tif len(sys.argv) < 4:\n\t\tprint('Missing arguments: ')\n\t\tsys.exit(0)\n\n\timport core.analytics.analytics as analytics\n\timport datetime\n\t\n\tfromDate = datetime.datetime.strptime(sys.argv[3], '%Y/%m/%d')\n\ttoDate = datetime.datetime.strptime(sys.argv[4], '%Y/%m/%d')\n\tprint('Exporting %s from %s to %s'%(sys.argv[2], fromDate, toDate))\n\n\tanalytics.Analytics().exportFile(sys.argv[2], fromDate, toDate, sys.stdout)\n\nelif sys.argv[1] == 'test':\n\tif sys.argv[2] == 'content':\n\t\timport tests.content\n\telif sys.argv[2] == 'pricing':\n\t\timport tests.pricing\n\telif sys.argv[2] == 'analytics':\n\t\timport tests.analytics\n\telif sys.argv[2] == 'terminal':\n\t\timport tests.terminal\n\telif sys.argv[2] == 'stress':\n\t\timport tests.stress\n\t\tif len(sys.argv) > 3 and sys.argv[3] == 'analyze':\n\t\t\ttests.stress.analyze()\n\t\telse:\n\t\t\ttests.stress.run()\n\telif sys.argv[2] == 'all':\n\t\timport tests.content\n\t\timport tests.pricing\n\t\timport tests.analytics\n\t\timport tests.terminal\n\telif sys.argv[2] == 'coverage':\n\t\tos.system('coverage-3.4 run manage.py test all')\n\t\tos.system('coverage-3.4 report')\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"30335860","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport numpy as np\nimport time\nimport os\nimport json\n\nimport random\nimport sqlite3\nimport math\nimport numpy\nimport scipy.stats as st\nfrom scipy.stats.stats import pearsonr\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.ticker import MaxNLocator\nfrom collections import namedtuple\n\ndef barplot(res,taggroup,tagbar):\n\n n_groups = len(taggroup)\n fig, ax = plt.subplots()\n\n index = np.arange(n_groups)\n bar_width = 0.20\n\n opacity = 0.8\n error_config = {'ecolor': '0.3'}\n\n for i in range(len(tagbar)):\n means=[]\n std=[]\n for j in range(len(taggroup)):\n means.append(res[j][i][0])\n std.append(res[j][i][1])\n rects1 = ax.bar(index, means, bar_width,\n alpha=opacity,\n yerr=std, error_kw=error_config,\n label=tagbar[i])\n index=index+ bar_width\n\n\n ax.set_ylabel('Correlation Coefficient')\n ax.set_xticks(np.arange(n_groups) + bar_width / 2)\n ax.set_xticklabels(taggroup)\n ax.legend()\n\n fig.tight_layout()\n plt.show()\n\n\ndef calc_ABAvgScore(target,score):\n\n #Average\n MOS=[0.00]*6 #8: for Antoine 6:for mine\n MOS_Count=[0]*6 #8: for Antoine 6:for mine\n for i in range(len(target)):\n MOS[int(target[i])-1]+=score[i]\n MOS_Count[int(target[i])-1]+=1\n for i in range(len(MOS)):\n MOS[i]=MOS[i]/MOS_Count[i]\n\n print(\"Mean Opinion Score of Audio-Books :\\n \"+str([\"%.3f\" % e for e in MOS]))\n\n #Confidenc_interval\n ConfInt=[0.00]*6 #8: for Antoine 6:for mine\n for i in range(len(target)):\n ConfInt[int(target[i])-1]+=(score[i]-MOS[int(target[i])-1])**2\n for i in range(len(MOS)):\n ConfInt[i]=(1.96*math.sqrt(ConfInt[i]/(MOS_Count[i]-1)))/math.sqrt(MOS_Count[i])\n\n print(\"Confidence Interval of Audio-Books Scores \\n \" + str([\"%.3f\" % e for e in ConfInt]))\n\n return MOS,ConfInt\n\ndef calc_correlationSample(SubScoreAddress,objScoreAddress,title):\n rst=[]\n SubScorelist=[]\n ObjScorelist=[]\n SubScore =json.load(open(SubScoreAddress))\n ObjScore = json.load(open(objScoreAddress))\n for i in SubScore:\n if i in ObjScore:\n # print(\"i:\"+str(i)+\", SubScore=\"+str(SubScore[i][0]/SubScore[i][1])+\", ObjScore=\"+str(ObjScore[i]))\n SubScorelist.append(SubScore[i][0]/SubScore[i][1])\n ObjScorelist.append(float(ObjScore[i][0])/ObjScore[i][1])\n plt.scatter(SubScorelist, ObjScorelist, alpha=0.5)\n plt.title(\"Subjective and Objective Evaluation of Samples\\n%s\" %title)\n plt.xlabel('Perceptual Score (0-10)')\n plt.ylabel('Objective Distance (%s)' %title)\n #plt.show()\n print(\"Samples Evaluation Correlation Coefficient: [Correlation Coefficient , p-Value]\")\n print(\"Pearson Correlation Coefficient: \"+str([\"%.3f\" % e for e in pearsonr(SubScorelist, ObjScorelist)]))\n rst.append([pearsonr(SubScorelist, ObjScorelist)[0],pearsonr(SubScorelist, ObjScorelist)[1]])\n print(\"Spearman Ranking Correlation Coefficient: \"+str([\"%.3f\" % e for e in st.spearmanr(SubScorelist, ObjScorelist)]))\n rst.append([st.spearmanr(SubScorelist, ObjScorelist)[0],st.spearmanr(SubScorelist, ObjScorelist)[1]])\n print(\"Kendall_tau Ranking Correlation Coefficient: \" + str([\"%.3f\" % e for e in st.kendalltau(SubScorelist, ObjScorelist)]))\n rst.append([st.kendalltau(SubScorelist, ObjScorelist)[0],st.kendalltau(SubScorelist, ObjScorelist)[1]])\n return rst\n\ndef calc_correlationSystem(SubScorelist,objScoreAddress):\n\n\n ObjScore = json.load(open(objScoreAddress))\n rst = []\n Scores=[]\n Target=[]\n for i in ObjScore:\n Target.append(int(i[:1]))\n Scores.append(ObjScore[i][0]/ObjScore[i][1])\n MOS, ConfInt=calc_ABAvgScore(Target, Scores)\n print(\"AudioBooks Evaluation Correlation Coefficient: [Correlation Coefficient , p-Value]\")\n print(\"Pearson Correlation Coefficient: \" + str([\"%.3f\" % e for e in pearsonr(MOS,SubScorelist)]))\n rst.append([pearsonr(MOS,SubScorelist)[0],pearsonr(MOS,SubScorelist)[1]])\n print(\"Spearman Ranking Correlation Coefficient: \" + str([\"%.3f\" % e for e in st.spearmanr(MOS,SubScorelist)]))\n rst.append([st.spearmanr(MOS,SubScorelist)[0],st.spearmanr(MOS,SubScorelist)[1]])\n print(\"Kendall_tau Ranking Correlation Coefficient: \" + str([\"%.3f\" % e for e in st.kendalltau(MOS,SubScorelist)]))\n rst.append([st.kendalltau(MOS,SubScorelist)[0],st.kendalltau(MOS,SubScorelist)[1]])\n return rst\n\ndef main():\n SubScorelist=[3.173611111111111, 3.057142857142857, 2.9722222222222223, 2.4791666666666665, 2.316546762589928, 1.410071942446043]\n res=[]\n SubScoreAddress='SubjEval/scores.json'\n objScoreAddress='ObjEval/Result/PESQscores.json'\n print(\"================= Samples ===================\")\n print(\"PESQ:\")\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"PESQ\"))\n print(\"\\nSPTKDTW: mgc\")\n objScoreAddress = 'ObjEval/Result/MGC_DTW_ScoreResult/SPTKDTWscores.json'\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"SPTKDTW-mgc\"))\n print(\"\\nIRISADTW: mgc\")\n objScoreAddress='ObjEval/Result/MGC_DTW_ScoreResult/IRISADTWscores.json'\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"IRISADTW-mgc\"))\n print(\"\\nFastDTW: mgc\")\n objScoreAddress='ObjEval/Result/MGC_DTW_ScoreResult/FastDTWscores.json'\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"FastDTW-mgc\"))\n print(\"\\nFastDTW: mfcc\")\n objScoreAddress='ObjEval/Result/MFCC_DTW_ScoreResult/FastDTWscores.json'\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"FastDTW-mfcc\"))\n print(\"\\nFastDTW: mgc Synthetic Reference\")\n objScoreAddress='ObjEval/Result/SynthRefFastDTWscores.json'\n res.append(calc_correlationSample(SubScoreAddress, objScoreAddress,\"FastDTW-mgc\"))\n barplot(res,[\"PESQ\",\"SPTKDTW-mgc\",\"IRISADTW-mgc\",\"FastDTW-mgc\",\"FastDTW-mfcc\",\"FastDTW-mgc(SynRef)\"],[\"Pearson C.C.\",\"Spearman R.C.C.\",\"Kendall_tau R.C.C.\"])\n\n\n print(\"\\n================= Systems ===================\")\n res = []\n print(\"\\nPESQ:\")\n objScoreAddress = 'ObjEval/Result/PESQscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n print(\"\\nSPTKDTW: mgc\")\n objScoreAddress = 'ObjEval/Result/MGC_DTW_ScoreResult/SPTKDTWscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n print(\"\\nIRISADTW: mgc\")\n objScoreAddress = 'ObjEval/Result/MGC_DTW_ScoreResult/IRISADTWscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n print(\"\\nFastDTW: mgc\")\n objScoreAddress = 'ObjEval/Result/MGC_DTW_ScoreResult/FastDTWscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n print(\"\\nFastDTW: mfcc\")\n objScoreAddress = 'ObjEval/Result/MFCC_DTW_ScoreResult/FastDTWscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n print(\"\\nFastDTW: mgc Synthetic Reference\")\n objScoreAddress='ObjEval/Result/SynthRefFastDTWscores.json'\n res.append(calc_correlationSystem(SubScorelist, objScoreAddress))\n barplot(res,[\"PESQ\",\"SPTKDTW-mgc\",\"IRISADTW-mgc\",\"FastDTW-mgc\",\"FastDTW-mfcc\",\"FastDTW-mgc(SynRef)\"],[\"Pearson C.C.\",\"Spearman R.C.C.\",\"Kendall_tau R.C.C.\"])\n\n\nif __name__ == '__main__':\n\n main()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Task01-Subj_Obj_Correlation/My_Test/Correlation.py","file_name":"Correlation.py","file_ext":"py","file_size_in_byte":7351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"28447825","text":"import random\n\nfrom django import template\nfrom django.conf import settings\n\nregister = template.Library()\n\n\n@register.inclusion_tag('application/usage_hint.html')\ndef get_random_hint():\n treshold = 3\n\n if not random.randint(0, treshold):\n random_hint = max(random.sample(settings.USAGE_HINTS, 2))[1]\n return {'hint': random_hint}\n","sub_path":"applications/application/templatetags/usage_hints.py","file_name":"usage_hints.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"112187149","text":"import pytest\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\nengine = create_engine('postgresql://postgres:root123@localhost/library')\nSession = sessionmaker()\n\n\n@pytest.fixture(scope='module')\ndef connection():\n connection = engine.connect()\n yield connection\n connection.close()\n\n\n@pytest.fixture(scope='function')\ndef session(connection):\n transaction = connection.begin()\n session = Session(bind=connection)\n yield session\n session.close()\n transaction.rollback()","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507256269","text":"from __future__ import division, print_function\n# coding=utf-8\nimport sys\nimport os\nimport glob\nimport re\nimport numpy as np\n\n# Keras\nfrom tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\n\n# Flask utils\nfrom flask import Flask, redirect, url_for, request, render_template\nfrom werkzeug.utils import secure_filename\n#from gevent.pywsgi import WSGIServer\n\n# Define a flask app\napp = Flask(__name__)\n\n# Model saved with Keras model.save()\nMODEL_PATH ='fresh_model_densenet121.h5'\nfresh_model = load_model(MODEL_PATH)\n\nMODEL_PATH ='withered_model_densenet121.h5'\nwithered_model = load_model(MODEL_PATH)\n\n\n\ndef fresh_model_predict(img_path, model):\n img = image.load_img(img_path, target_size=(224, 224))\n\n # Preprocessing the image\n x = image.img_to_array(img)\n # x = np.true_divide(x, 255)\n ## Scaling\n x=x/255\n x = np.expand_dims(x, axis=0)\n \n predict = model.predict(x)\n preds = np.argmax(predict, axis=1)\n #\"(\" + str((np.count_nonzero(predict == 3)/(len(predict)*len(predict[0])))*100) + \")\"\n if preds == 0:\n preds = \"Low Fresh - Below Best\"\n elif preds == 1:\n preds = \"Low Fresh - Best\"\n else:\n preds = \"Low Fresh - Poor\"\n return preds #+ \" (\" + str(predict[0][np.argmax(predict[0])]*100) + \"%)\"\n\ndef withered_model_predict(img_path, model):\n img = image.load_img(img_path, target_size=(224, 224)) #Corn_Blight (1002)\n\n # Preprocessing the image\n x = image.img_to_array(img)\n # x = np.true_divide(x, 255)\n ## Scaling\n x=x/255\n x = np.expand_dims(x, axis=0)\n \n predict = model.predict(x)\n preds = np.argmax(predict, axis=1)\n #str((np.count_nonzero(predict == 1)/(len(predict)*len(predict[0])))*100)\n if preds == 0:\n preds = \"Low Withered - Below Best\"\n elif preds == 1:\n preds = \"Low Withered - Best\"\n else:\n preds = \"Low Withered - Poor\"\n return preds #+ \" (\" + str(predict[0][np.argmax(predict[0])]*100) + \"%)\"\n\n\n\n@app.route('/', methods=['GET'])\ndef home():\n # Main page\n return render_template('home.html')\n\n@app.route('/fresh_model', methods=['GET'])\ndef fresh_index():\n # Banana Leaf Classification Page\n return render_template('fresh_index.html')\n\n@app.route('/withered_model', methods=['GET'])\ndef withered_index():\n # Plant Disease Data Page\n return render_template('withered_index.html')\n\n\n\n\n@app.route('/fresh_model/predict', methods=['GET', 'POST'])\ndef fresh_upload():\n if request.method == 'POST':\n # Get the file from post request\n f = request.files['file']\n\n # Save the file to ./uploads\n basepath = os.path.dirname(__file__)\n file_path = os.path.join(\n basepath, 'Uploads', secure_filename(f.filename))\n f.save(file_path)\n\n # Make prediction\n result = fresh_model_predict(file_path, fresh_model)\n return result\n return None\n\n@app.route('/withered_model/predict', methods=['GET', 'POST'])\ndef withered_upload():\n if request.method == 'POST':\n # Get the file from post request\n f = request.files['file']\n\n # Save the file to ./uploads\n basepath = os.path.dirname(__file__)\n file_path = os.path.join(\n basepath, 'Uploads', secure_filename(f.filename))\n f.save(file_path)\n\n # Make prediction\n result = withered_model_predict(file_path, withered_model)\n return result\n return None\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"402081255","text":"from flask import Flask, request\nfrom flask_cors import CORS\n\nimport json\nimport numpy as np\n\napp = Flask(__name__)\nCORS(app)\n\nfilename = 'data/threads-100_revV2.json'\nall_threads = None # Store all threads from the local data file\nif not all_threads:\n with open(filename, 'r') as f:\n all_threads = json.load(f)\n\nmodel_name = '' # Initially, no model is loaded\n\n# model endpoint\n@app.route(\"/model\")\ndef model():\n # Modelling\n data = request.args.get('data', '')\n labelled_threads = json.loads(data) # This is a list of dictionary { threadId, classId }\n labelled_all_threads = build_dummy_model(labelled_threads) # To be replaced by proper active learning modelling\n\n # Getting recommendations\n recommend = request.args.get('rec', '') == 'true'\n recommended_samples = [] # Return empty list if no recommendation required\n if recommend:\n recommended_samples = get_dummy_recommended_samples() # To be replaced by proper active learning modelling\n\n # Prepare returning object (note that there are some `tolist()` to make object JSON serialisable)\n return_object = {\n 'classLookup': labelled_all_threads,\n 'samples': recommended_samples\n }\n\n return json.dumps(return_object)\n\ndef build_dummy_model(labelled_threads):\n \"Return random labels for the entire dataset as a dictionary { threadId: classId }.\"\n classes = get_available_classes(labelled_threads)\n labels = np.random.choice(classes, size=len(all_threads), replace=True).tolist()\n labelled_all_threads = { t['threadId']: labels[i] for i, t in enumerate(all_threads) }\n return labelled_all_threads\n\ndef get_available_classes(labelled_threads):\n \"Return a list of classes appeared in the threads.\"\n return list(set(t['classId'] for t in labelled_threads))\n\ndef get_dummy_recommended_samples():\n \"Randomly return 50 thread IDs.\"\n all_thread_ids = [t['threadId'] for t in all_threads]\n return np.random.permutation(all_thread_ids)[:50].tolist()\n\n# save endpoint\n@app.route(\"/save\")\ndef save():\n model_name = request.args.get('name', '') # Use this to save the model\n print(model_name)\n return ''\n\n# load endpoint\n@app.route(\"/load\")\ndef load():\n model_name = request.args.get('name', '') # Use this to load the model\n print(model_name)\n return ''","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"436925487","text":"from logging import StreamHandler, basicConfig, DEBUG, WARNING, getLogger, Formatter\n\nmpl_logger = getLogger('matplotlib')\nmpl_logger.setLevel(WARNING)\n\ndef setup_logger(log_file):\n format_str = '%(asctime)s@%(name)s %(levelname)s # %(message)s'\n basicConfig(filename=log_file, level=DEBUG, format=format_str)\n stream_handler = StreamHandler()\n stream_handler.setFormatter(Formatter(format_str))\n getLogger().addHandler(stream_handler)\n\nif __name__ == '__main__':\n setup_logger(\"Neural_ODE/test/logs/test.log\")\n logger = getLogger(\"test\")\n logger.info(\"OK\")","sub_path":"src/lib/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"14594079","text":"\"\"\"\n# This library is in charge of the play flow. It will call the cards library to help with everything card related.\n\n\"\"\"\n\nimport cards\nimport sys\n\n\ndef play():\n # First, we ask the player how much does he want to bet.\n bet = cards.place_bet()\n double_down = False\n\n # Check if he introduced a valid value.\n if bet is None:\n print(\"Program ending\")\n\n # If he did, we proceed with the game\n else:\n # Deal the first 2 cards to dealer and player.\n player_hand = cards.deal_first_hand()\n print(\"Player's hand:\", player_hand)\n dealer_hand = cards.deal_first_hand()\n print(\"Dealer's hand:\", dealer_hand[0])\n\n # Check if any of them have a 21 with the first 2 cards.\n if cards.natural_blackjack(player_hand):\n print(\"Player wins with a natural blackjack!\", player_hand)\n\n elif cards.natural_blackjack(dealer_hand):\n print(\"Dealer wins with a natural blackjack!\", dealer_hand)\n\n # Check if the first 2 player's cards sum 9, 10, 11.\n else:\n if cards.check_double_down(player_hand):\n response = input(\"Would you like to double down? (Y/N):\")\n\n if response == 'Y':\n bet += bet\n double_down = True\n print(\"Your bet has doubled, now you're playing with: %d\" % bet)\n\n elif response == 'N':\n print(\"Your bet stays the same\")\n\n else:\n print(\"Invalid input, please introduce 'Y' or 'N' next time.\")\n sys.exit()\n\n # Set response to Y to enter the loop\n response = 'Y'\n while response == 'Y':\n # Check if player wants another card and if he can actually get one.\n response = input(\"Would you like another card? (Y/N): \")\n\n if response == 'Y' and cards.check_score(player_hand) <= 21:\n cards.hit(player_hand)\n print(\"Player's hand:\", player_hand)\n if double_down:\n break\n if cards.check_score(player_hand) > 21:\n print(\"You bust with %d points. Dealer wins\" % cards.check_score(player_hand))\n sys.exit(\"Game over\")\n if cards.check_score(player_hand) == 21:\n break\n\n elif response != 'Y' and response != 'N':\n print(\"Invalid input, please introduce 'Y' or 'N' next time.\")\n\n # After player is done with his hand, dealer plays.\n cards.dealer_play(dealer_hand)\n print(\"Player's hand: \", player_hand)\n\n # Both are done with their hands. Check scores and display result.\n cards.compare_hands(player_hand, dealer_hand, bet)\n","sub_path":"Refactor/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"185374079","text":"#!/usr/bin/env python\n# coding:utf-8\n\nimport sys\n\nN = int(input())\nNG = [0, 0, 0]\nNG[0] = int(input())\nNG[1] = int(input())\nNG[2] = int(input())\n\nif N in NG:\n print('NO')\n sys.exit()\n\ncount = 0\nwhile N>0:\n if N-3 not in NG:\n N -= 3\n count += 1\n elif N-2 not in NG:\n N -= 2\n count += 1\n elif N-1 not in NG:\n N -= 1\n count += 1\n else:\n print('NO')\n break\nelse:\n if count<=100:\n print('YES')\n else:\n print('NO')\n\n\n# バグ?取りきれずにダメだったコード\n# import sys\n# def cost(distance):\n# c1 = distance // 3\n# c2 = (distance - (c1 * 3)) // 2\n# c3 = (distance - (c1 * 3) - (c2 * 2))\n# # print(c1+c2+c3)\n# return(c1 + c2 + c3)\n#\n# N = int(input())\n# NG = [0, 0, 0]\n# NG[0] = int(input())\n# NG[1] = int(input())\n# NG[2] = int(input())\n# NG.sort(reverse=True)\n#\n#\n# if N in NG:\n# print('NO')\n# sys.exit()\n#\n# if N == 1:\n# print('YES')\n# sys.exit()\n#\n# if NG[0] == NG[1] + 1 == NG[2] + 2:\n# print('NO')\n# sys.exit()\n#\n# while True:\n# if N < NG[0]:\n# NG.pop(0)\n# else:\n# break\n#\n# num = 0\n# for i in range(len(NG)):\n# num += cost(N - NG[i] + 1)\n# N = NG[i] - 1\n# num += cost(NG[-1]-1)\n# NG.insert(0, N)\n# NG.append(0)\n# count = 0\n# if i in range(len(NG)-1):\n# if NG[i] == NG[i+1] + 1:\n# count += 1\n# num += len(NG) - 1 - count\n# print(num)\n# if num > 100:\n# print('NO')\n# else:\n# print('YES')\n","sub_path":"atcoder/ABC/011/abc11c.py","file_name":"abc11c.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"317534917","text":"#解法一 排序\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n d = {}\n for i in nums:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = list(d.values())\n l.sort(reverse=True)\n result = []\n for i in range(0, k):\n for key in d:\n if d[key] == l[i]:\n result.append(key)\n a = list(set(result))\n return a\n\n#解法二:堆\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n d = collections.Counter(nums)\n result = []\n heap = []\n for num, freq in d.items() :\n # 如果堆满了(k个元素)\n if len(heap) == k :\n # 弹出最小频率的元组\n if heap[0][0] < freq:\n heapq.heapreplace(heap, (freq, num))\n else : \n heapq.heappush(heap, (freq, num))\n while heap :\n result.append(heapq.heappop(heap)[1])\n \n return result\n","sub_path":"Week_02/topKFrequent.py","file_name":"topKFrequent.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"534691280","text":"#!/usr/bin/env python3\n\nfrom time import sleep\nfrom sqlalchemy.exc import IntegrityError\n\nfrom database import Database\nfrom webdriver import create_webdriver\n\ndb = Database()\n\nWEB_DRIVER = create_webdriver()\nsleep(2)\n\n# Busco los jugadores\nfor team in db.teams.select().execute().fetchall():\n WEB_DRIVER.get(team.url)\n sleep(5)\n\n players = []\n for p in WEB_DRIVER.find_elements_by_class_name('fi-p'):\n\n try:\n pos = p.find_element_by_class_name('fi-p__info--role').text\n except:\n continue\n\n if pos == \"COACH\":\n continue\n\n url = p.find_element_by_class_name('fi-p--link').get_attribute('href')\n player = {\n 'id': int(url.split('/')[-2]),\n 'team_id': team.id,\n 'num': int(p.find_element_by_class_name('fi-p__num').text),\n 'name': p.find_element_by_class_name('fi-p__nShorter').text,\n 'pos': pos,\n 'url': url,\n }\n\n try:\n db.players.insert(player).execute()\n players.append(player)\n print(player)\n except IntegrityError:\n continue\n\nWEB_DRIVER.close()\n","sub_path":"create_players.py","file_name":"create_players.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"566691553","text":"from rest_framework import serializers\nfrom . import models\nfrom allauth.socialaccount.models import SocialToken\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Profile\n fields = (\n 'user'\n )\n \nclass TokenSerializer(serializers.ModelSerializer):\n class Meta:\n model = SocialToken\n fields = (\n 'account',\n 'token',\n )\n\nclass JobSerializer(serializers.ModelSerializer):\n created_date = serializers.DateTimeField(format=\"%Y-%m-%d\", required=False, read_only=True)\n class Meta:\n ordering = ['-id']\n model = models.Job\n fields = (\n 'id',\n 'job_company',\n 'job_title',\n 'job_body',\n 'job_url',\n 'job_source',\n 'job_location',\n 'favorite',\n 'created_date',\n 'expiration_date'\n )\n\nclass CompanySerializer(serializers.ModelSerializer):\n companies = serializers.IntegerField()\n class Meta:\n model = models.Job\n fields = (\n 'id',\n 'companies',\n 'job_company',\n )\n","sub_path":"app/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"589739560","text":"# Implementar la funcion actualizar_persona, que actualiza un registro de una persona basado en su id.\n# Devuelve un booleano en base a si encontro el registro y lo actualizo o no.\n\nimport datetime\n\nfrom Practico_03A.ejercicio_04 import buscar_persona\nfrom Practico_03A.ejercicio_02 import agregar_persona\nfrom Practico_03A.ejercicio_01 import reset_tabla, engine, Persona\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import update\n\nDBSession = sessionmaker()\nDBSession.bind = engine\nsession = DBSession()\n\n\ndef actualizar_persona(id_persona, nombre, nacimiento, dni, altura):\n encontrado=buscar_persona(id_persona)\n if encontrado is False:\n return False\n else:\n stmt = update(Persona)\\\n .where(Persona.idPersona == id_persona)\\\n .values(nombre=nombre,fechaNacimiento=nacimiento,dni=dni,altura=altura)\n session.execute(stmt)\n session.commit()\n\n\n@reset_tabla\ndef pruebas():\n id_juan = agregar_persona('juan perez', datetime.datetime(1988, 5, 15), 32165498, 180)\n actualizar_persona(id_juan, 'juan carlos perez', datetime.datetime(1988, 4, 16), 32165497, 181)\n assert buscar_persona(id_juan) == (1, 'juan carlos perez', datetime.datetime(1988, 4, 16).strftime(\"%Y-%m-%d %H:%M:%S\"), 32165497, 181)\n assert actualizar_persona(123, 'nadie', datetime.datetime(1988, 4, 16), 12312312, 181) is False\n\nif __name__ == '__main__':\n pruebas()\n","sub_path":"Practico_03A/ejercicio_05.py","file_name":"ejercicio_05.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"116669456","text":"from rest_framework import generics\nfrom rest_framework.authentication import TokenAuthentication\nfrom django.contrib.auth.models import User\nfrom .serializer import Loginserializer,InventorySerializer,ModelApprovalSerializer\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom inventory.models import Inventory,ModelApproval\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import Permission\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.parsers import JSONParser\n\n# Create your views here.\n\"\"\"method to check user\"\"\"\ndef check_user(request,action,view):\n groups = request.user.groups.all().values_list('name', flat=True)\n user_perm= request.user.user_permissions.all().values_list('name', flat=True)\n keyword= action+\" \"+view\n user_perm=list(filter(lambda x: keyword in x, user_perm))\n if any([i == 'Store Manager' for i in groups]):\n return True\n elif user_perm:\n return True\n else:\n return False\n\n\n\"\"\"class for login api\"\"\"\nclass Login(APIView):\n def post(self, request, format=None):\n serializer = Loginserializer(data=request.data)\n if serializer.is_valid():\n email = serializer.data['email']\n password = serializer.data['password']\n output=dict()\n if User.objects.filter(email=email).exists():\n user = User.objects.get(email=email)\n if user.check_password(password) and user.is_active:\n token=Token.objects.get_or_create(user=user)\n output['status']=status.HTTP_200_OK\n output['usermsg']=\"Login successful\"\n output['redirect']=serializer.data['redirect_url']\n output['token']=token[0].key\n return Response(output,status=status.HTTP_200_OK)\n else:\n output['status'] = status.HTTP_203_NON_AUTHORITATIVE_INFORMATION\n output['usermsg'] = \"email/password is incorrect\"\n return Response(output, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)\n else:\n return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)\n\n\"\"\"class for inventory GET/POST\"\"\"\nclass InventoryList(generics.ListCreateAPIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'inventory_list.html'\n queryset = Inventory.objects.all()\n serializer_class = InventorySerializer\n parser_classes = (JSONParser,)\n def list(self, request):\n queryset = self.get_queryset()\n # getting diffrent check based on diffrent user\n store_manager_check = False\n add_perm_check=check_user(request,\"add\",\"inventory\") #checking add permission\n change_perm_check=check_user(request,\"change\",\"inventory\") #checking change permission\n delete_perm_check=check_user(request,\"delete\",\"inventory\") #checking delete permission\n groups = request.user.groups.all().values_list('name', flat=True)\n if any([i == 'Store Manager' for i in groups]):\n store_manager_check = True\n return Response({'inventory': queryset,\"store_manager_check\":store_manager_check,\"add_perm_check\":add_perm_check,\"change_perm_check\":change_perm_check,\"delete_perm_check\":delete_perm_check})\n\n def create(self, request, *args, **kwargs):\n if check_user(request,\"add\",\"inventory\"):\n try:\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n output = {\"msg\": \"Inventory Added Successfully\"}\n output.update(serializer.data)\n return Response(output, status=status.HTTP_201_CREATED,template_name=None)\n except:\n error_msj=serializer.errors.keys()[0]+\" \"+serializer.errors[serializer.errors.keys()[0]]\n output = {\"msg\": error_msj}\n output.update(serializer.data)\n return Response(output)\n else:\n output = {\"msg\": \"You are not authorize to add Inventory\"}\n return Response(output)\n\n\n\"\"\"class for inventory PUT/DELETE\"\"\"\nclass InventoryDetail(generics.RetrieveUpdateDestroyAPIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n queryset = Inventory.objects.all()\n serializer_class = InventorySerializer\n def list(self, request):\n queryset = self.get_queryset()\n return Response({'inventory': queryset},template_name='inventory_list.html')\n def update(self, request, *args, **kwargs):\n if check_user(request,\"change\",\"inventory\"):\n partial = kwargs.pop('partial', False)\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n\n if getattr(instance, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n instance._prefetched_objects_cache = {}\n output={\"msg\":str(instance.productName)+\" is updated\"}\n output.update(serializer.data)\n return Response(output)\n else:\n output = {\"msg\":\"You are not authorize to update Inventory\"}\n return Response(output)\n\n def destroy(self, request, *args, **kwargs):\n if check_user(request,\"delete\",\"inventory\"):\n instance = self.get_object()\n self.perform_destroy(instance)\n output = {\"msg\": \"Inventory deleted\"}\n return Response(output)\n else:\n output = {\"msg\": \"You are not authorize to delete Inventory\"}\n return Response(output)\n\n\"\"\"Model Approval Class\"\"\"\nclass ApprovModel(generics.ListCreateAPIView,generics.RetrieveUpdateDestroyAPIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n queryset = ModelApproval.objects.all()\n serializer_class = ModelApprovalSerializer\n def list(self, request):\n queryset = self.get_queryset()\n innerHtml=\"\"\n for approveRequest in queryset:\n if approveRequest.requestedBy != request.user:\n if not approveRequest.approve:\n button=\"\"\n else:\n button=\"\"\n\n innerHtml+=\"\"+approveRequest.requestedBy.email+\"\"+approveRequest.action+\"\"+button+\"\"\n #output.append([approveRequest.requestedBy.email,approveRequest.action,approveRequest.approve])\n\n html=\"\" +innerHtml+ \"
emailactionPermission
\"\n return Response(html)\n\n def post(self, request, format=None):\n serializer = ModelApprovalSerializer(data=request.data)\n if serializer.is_valid():\n action=serializer.data['action']\n admin_name=serializer.data['admin_name']\n if ContentType.objects.filter(model=admin_name).exists():\n content_id=ContentType.objects.get(model=admin_name)\n else:\n return Response(\"This model doesn't exist\")\n action = action + \"_\" + admin_name\n\n if check_user(request,action,admin_name):\n return Response(\"You already have this permission\")\n\n if not ModelApproval.objects.filter(requestedBy=request.user,action=action,content_type=content_id,approve=0).exists():\n ModelApproval(requestedBy=request.user,action=action,content_type=content_id).save()\n return Response(\"Approval request has been sent\")\n else:\n return Response(\"You already sent this request\")\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def put(self, request, pk, format=None):\n modlobj=ModelApproval.objects.get(id=pk)\n permisnObj=Permission.objects.get(codename=modlobj.action)\n modlobj.requestedBy.user_permissions.add(permisnObj)\n modlobj.approveBy=request.user.email\n modlobj.approve=1\n modlobj.save()\n return Response(\"Request Approved\")\n\n\n\n\n\n\n","sub_path":"cointribe/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508347781","text":"def errorCheck(varName, type, question):\r\n x=0\r\n while x == 0:\r\n try:\r\n varName=type(varName)\r\n #tries to convert the variable into an integer/float\r\n x=1\r\n #stops the loop\r\n except ValueError:\r\n varName = input(question)\r\n #if it is unable to convert the users input it asks the question again\r\n return varName\r\n\r\n","sub_path":"ErrorCheck.py","file_name":"ErrorCheck.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"184060143","text":"def no_dups(s):\n # Your code here\n if s == \"\":\n return s\n\n words = s.split(' ')\n store = {}\n i = 1\n for word in words:\n if store.get(word) is None:\n store[word] = i\n i += 1\n\n store_items = list(store.items())\n store_items.sort(key=lambda x: x[1])\n\n s = [\"\"] * len(store_items)\n\n for i, item in enumerate(store_items):\n s[i] = item[0]\n\n return ' '.join(s)\n\n\nif __name__ == \"__main__\":\n print(no_dups(\"\"))\n print(no_dups(\"hello\"))\n print(no_dups(\"hello hello\"))\n print(no_dups(\"cats dogs fish cats dogs\"))\n print(no_dups(\"spam spam spam eggs spam sausage spam spam and spam\"))\n","sub_path":"applications/no_dups/no_dups.py","file_name":"no_dups.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"328982817","text":"import serial\nfrom time import sleep\nfrom read_ports import serial_ports\nser=serial.Serial(serial_ports()[0],9600)\n\nwhile True :\n try:\n # print(\"contacting server\")\n r = requests.get('http://0.0.0.0:5000/getinstructions')\n # print('request is: {}', int(r.text))\n if(int(r.text) == 11):\n user_input=str.encode('1')\n elif(int(r.text) == 12):\n user_input=str.encode('2')\n except:\n print(\"WTF\")\n ser.write(user_input) # Convert the decimal number to ASCII then send it to the Arduino\n sleep(0.1)","sub_path":"remotePi/arduino_scripts/test_comms.py","file_name":"test_comms.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"229822935","text":"import sys\n\ndef star_pattern1(n):\n for i in range(1, n+1):\n print(\"* \"*i)\n\ndef star_pattern2(n):\n k = 2*n - 2\n for i in range(0, n):\n for j in range(0, k):\n print(end=\" \")\n k = k - 2\n for j in range(0, i+1):\n print(\"* \", end=\"\")\n print(\"\\r\")\n\ndef star_pattern3(n):\n for i in range(0, n):\n for j in range(n, i, -1):\n print(\"* \", end=\"\")\n print()\n\ndef pyramid_pattern1(n):\n k = 0\n for i in range(1, n+1):\n for space in range(1, (n-i)+1):\n print(end=\" \")\n while k != (2*i-1):\n print(\"* \", end=\"\")\n k = k + 1\n k = 0\n print()\n\ndef pyramid_pattern2(n):\n k = 1\n for i in range(0, n):\n for j in range(0, k):\n print(\"* \", end=\"\")\n k = k + 2\n print()\n\ndef pyramid_pattern3(n):\n k, tim = 36, 1\n for i in range(0, n):\n for j in range(0, k):\n print(end=\" \")\n k = k - 4\n for j in range(0, tim):\n print(\"* \", end=\"\")\n tim = tim + 2\n print()\n\ndef number_pattern1(n):\n k = 1\n for i in range(0, n):\n for j in range(0, i+1):\n print(k, end=\" \")\n k = k + 1\n print()\n\ndef number_pattern2(n):\n num = 1\n for i in range(0, n):\n num = 1\n for j in range(0, i+1):\n print(num, end=\" \")\n num = num + 1\n print()\n\ndef number_pattern3(n):\n num = 1\n for i in range(0, n):\n for j in range(n, i, -1):\n print(num, end=\" \")\n num = num + 1\n print()\n num = 1\n\ndef number_pattern4(n):\n num, incr = 1, 1\n for i in range(0, n):\n for j in range(0, incr):\n print(num, end=\" \")\n num = num + 1\n print()\n incr = incr + 2\n\ndef number_pattern5(n):\n num, count, decr = 1, 0, 8\n for i in range(0, n):\n for k in range(0, decr):\n print(end=\" \")\n for j in range(0, i):\n count = count + 1\n num = count\n temp = num\n for j in range(0, i):\n print(num, end=\" \")\n num = num - 1\n print()\n num = temp\n decr = decr - 2\n\ndef alphabet_pattern1(n):\n val = 65\n for i in range(0, n):\n for j in range(0, i+1):\n ch = chr(val)\n print(ch, end=\" \")\n val = val + 1\n print()\n\ndef alphabet_pattern2(n):\n val = 65\n for i in range(0, n):\n for j in range(0, i+1):\n ch = chr(val)\n print(ch, end=\" \")\n val = val + 1\n print()\n\ndef alphabet_pattern3(n):\n incr, val = 1, 65\n for i in range(0, n):\n for j in range(0, incr):\n ch = chr(val)\n print(ch, end=\" \")\n val = val + 1\n incr = incr + 2\n print()\n\ndef alphabet_pattern4(n):\n decr = 8\n count = 64\n val = 65\n for i in range(0, 5):\n for k in range(0, decr):\n print(end=\" \")\n for j in range(0, i+1):\n count = count + 1\n val = count\n temp = val\n for j in range(0, i+1):\n ch = chr(val)\n print(ch, end=\" \")\n val = val - 1\n val = temp\n decr = decr - 2\n print()\n\ndef star_patterns():\n print(\"\\n Star Patterns \\n 1. Star Pattern 1 \\t 2. Star Pattern 2 \\t 3. Star Pattern 3 \\t 0. Exit\")\n choice = int(input(\"\\n Enter your choice (Exit = 0) : \"))\n getvalue = int(input(\"\\n How many element : \"))\n if choice==1:\n star_pattern1(getvalue)\n elif choice==2:\n star_pattern2(getvalue)\n elif choice==3:\n star_pattern3(getvalue)\n elif choice==0:\n print(\"\\n Exiting..\")\n sys.exit()\n\ndef alphabet_patterns():\n print(\"\\n Alphabet Patterns \\n 1. Alphabet Pattern 1 \\t 2. Alphabet Pattern 2 \\t 3. Alphabet Pattern 3 \\t 4. Aphabet Pattern 4 \\t 0. Exit\")\n choice = int(input(\"\\n Enter your choice (Exit = 0) : \"))\n getvalue = int(input(\"\\n How many element : \"))\n if choice==1:\n alphabet_pattern1(getvalue)\n elif choice==2:\n alphabet_pattern2(getvalue)\n elif choice==3:\n alphabet_pattern3(getvalue)\n elif choice==4:\n alphabet_pattern4(getvalue)\n elif choice==0:\n print(\"\\n Exiting..\")\n sys.exit()\n\ndef pyramid_patterns():\n print(\"\\n Pyramid Patterns \\n 1. Pyramid Pattern 1 \\t 2. Pyramid Pattern 2 \\t 3. Pyramid Pattern 3 \\t 0. Exit\")\n choice = int(input(\"\\n Enter your choice (Exit = 0) : \"))\n getvalue = int(input(\"\\n How many element : \"))\n if choice==1:\n pyramid_pattern1(getvalue)\n elif choice==2:\n pyramid_pattern2(getvalue)\n elif choice==3:\n pyramid_pattern3(getvalue)\n elif choice==0:\n print(\"\\n Exiting..\")\n sys.exit()\n\ndef number_patterns():\n print(\"\\n Number Patterns \\n 1. Number Pattern 1 \\t 2. Number Pattern 2 \\t 3. Number Pattern 3 \\t 4. Number Pattern 4 \\t 5. Number Pattern 5 \\t 0. Exit\")\n choice = int(input(\"\\n Enter your choice (Exit = 0) : \"))\n getvalue = int(input(\"\\n How many element : \"))\n if choice==1:\n number_pattern1(getvalue)\n elif choice==2:\n number_pattern2(getvalue)\n elif choice==3:\n number_pattern3(getvalue)\n elif choice==4:\n number_pattern4(getvalue)\n elif choice==5:\n number_pattern5(getvalue)\n elif choice==0:\n print(\"\\n Exiting..\")\n sys.exit()\n\n\nfor i in range(0,6):\n print(\"\\n Patterns \\n 1. Star Patterns \\t 2. Number patterns \\t 3. Alphabet Patterns \\t 4. Pyramid Patterns \\t 0. Exit\")\n main_choice = int(input(\"\\n Enter your Main choice (Exit = 0) : \"))\n if main_choice==1:\n star_patterns()\n elif main_choice==2:\n number_patterns()\n elif main_choice==3:\n alphabet_patterns()\n elif main_choice==4:\n pyramid_patterns()\n elif main_choice==0:\n print(\"\\n Exiting..\")\n sys.exit()\n","sub_path":"Begineers/Patterns.py","file_name":"Patterns.py","file_ext":"py","file_size_in_byte":5926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508740410","text":"from __future__ import print_function\nimport os, sys, shutil, yaml\n\nclass BestModelSaver():\n def __init__(self, save_dir):\n self.save_dir = save_dir\n self.best_dir = os.path.join(self.save_dir, \"best\")\n\n def remove_and_initialise_best_dir(self):\n if os.path.exists(self.best_dir):\n shutil.rmtree(self.best_dir)\n os.makedirs(self.best_dir)\n # save checkpoint file\n checkpoint = os.path.join(self.best_dir, \"checkpoint\")\n if not os.path.exists(checkpoint):\n with open(checkpoint, 'w') as f:\n f.write(\"model_checkpoint_path: \\\"model.ckpt\\\"\\n\")\n # copy config and chars/vocab file\n for file in [\"config.pkl\", 'chars_vocab.pkl']:\n shutil.copyfile(os.path.join(self.save_dir, file),\n os.path.join(self.best_dir, file))\n\n def keep_best(self, model_path, train_loss, step, total_steps):\n score_filepath = os.path.join(self.best_dir, \"model_info.yaml\")\n try:\n with open(score_filepath) as f:\n d = yaml.load(f)\n best_score_so_far = d['training_loss']\n except IOError:\n best_score_so_far = sys.float_info.max\n if train_loss >= best_score_so_far:\n return\n # now copy files\n shutil.copyfile(model_path, os.path.join(self.best_dir, \"model.ckpt\"))\n shutil.copyfile(model_path+\".meta\", os.path.join(self.best_dir, \"model.ckpt.meta\"))\n # save model info\n d = {'training_loss': float(train_loss), 'current_step': step, 'total_steps': total_steps}\n with open(score_filepath, 'w') as f:\n yaml.dump(d, f, default_flow_style=False)\n print(\"model also saved to the 'best' folder\")","sub_path":"train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"452276075","text":"import random\nimport math\nfrom .vector import Vector3D\n\nMAP_SCALE = 1\n\n\nclass Mobile(object):\n\n def __init__(self):\n self.position = Vector3D()\n self.destination = Vector3D()\n self.velocity = Vector3D()\n self.heading = Vector3D()\n self.view_radius = 50.0\n self.angle = 1.0\n self.min_x = self.min_z = self.max_x = self.max_z = 0\n\n def set_size(self, max_x, max_z):\n self.min_x = MAP_SCALE\n self.min_z = MAP_SCALE\n self.max_x = (max_x * MAP_SCALE) - MAP_SCALE\n self.max_z = (max_z * MAP_SCALE) - MAP_SCALE\n\n def calculate_position(self, dt):\n position = Vector3D()\n position.x = self.position.x + (self.velocity.x * dt)\n position.y = self.position.y + (self.velocity.y * dt) # + (0.5f * t2)\n position.z = self.position.z + (self.velocity.z * dt)\n return position\n\n def calculate_new_orientation(self, destination):\n dx = float(destination.x - self.position.x)\n dy = float(destination.y - self.position.y)\n dz = float(destination.z - self.position.z)\n f2_norma = math.sqrt((dx * dx + dy * dy + dz * dz))\n\n if f2_norma > 0:\n self.velocity.x = float(dx / f2_norma)\n self.velocity.y = float(dy / f2_norma)\n self.velocity.z = float(dz / f2_norma)\n else:\n self.velocity.x = 0.0\n self.velocity.y = 0.0\n self.velocity.z = 0.0\n\n if self.velocity.length() > 0.0001:\n self.heading.x = self.velocity.x\n self.heading.y = self.velocity.y\n self.heading.z = self.velocity.z\n\n self.velocity.x *= 2\n self.velocity.y *= 2\n self.velocity.z *= 2\n\n def calculate_new_destination(self, radius_x, radius_y):\n x = self.position.x + ((random.random() * (radius_x * 2)) - radius_x)\n z = self.position.z + ((random.random() * (radius_y * 2)) - radius_y)\n\n x = min(x, self.min_x)\n x = max(x, self.max_x)\n z = min(z, self.min_z)\n z = max(z, self.max_z)\n\n return Vector3D(x=x, y=0.0, z=z)\n\n def get_destination(self):\n return self.destination\n\n def set_destination(self, destination):\n self.destination = destination\n\n def get_position(self):\n return self.position\n\n def get_angle(self):\n return self.angle\n\n def get_view_radius(self):\n return self.view_radius\n\n def get_heading(self):\n return self.heading\n\n def get_velocity(self):\n return self.velocity\n","sub_path":"pygomas/mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"255976335","text":"#!/usr/bin/env python3\nfrom modules.intcode import IntcodeMachine\nfrom threading import Thread\n\ninputfile = \"input.txt\"\nresults = []\n\nwith open(inputfile) as f:\n line = f.readlines()[0].strip()\n\ncodes = [ int(c) for c in line.split(',') ]\n\nim = IntcodeMachine(codes)\ninQ = im.inputQueue\noutQ = im.outputQueue\n#myInput= [ int(c) for c in input('The input digits separated by comma\\n').split(',') ]\n#im.setInput(myInput)\n\ndef getSymbol(block: int) -> str:\n if block == 0:\n return \".\"\n if block == 1:\n return \"W\"\n if block == 2:\n return \"B\"\n if block == 3:\n return \"H\"\n if block == 4:\n return \"O\"\n\n return \"?\"\n\nt = Thread(target=im.run)\ngameBoard = {}\nt.start()\n\nwhile t.is_alive():\n # inQ.put(1)\n x = outQ.get()\n y = outQ.get()\n block = outQ.get()\n gameBoard[(x,y)] = block\n\nt.join()\nwidth = max( [ point[0] for point in gameBoard.keys() ] )\nheight = max( [ point[1] for point in gameBoard ] )\n\nfor y in range(height):\n line=\"\"\n for x in range(width):\n line+=getSymbol(gameBoard[(x,y)])\n\n print(line)\n\nprint(len( [ block for block in gameBoard.values() if block == 2] ))\nprint(len(gameBoard))\n","sub_path":"day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"471076062","text":"# Summing series using Recursion\n# by Yiyang 09/02/18\n\n# the series:\n# m(n) = sigma(1/i), i = 1 to n\n\ncalcValues = {1:1.0} # use a dict to store the calculated values in the series to reduce repeated work, default value m(1)\n\ndef sum_series1(num):\n \n if num in calcValues:\n return calcValues[num]\n else:\n calcValues[num] = sum_series1(num-1) + 1.0 / num\n return calcValues[num]\n\n# main\nnum = int(input(\"Enter the number n for series m(n): \"))\nprint(\"m({0}) = {1:.5f}\".format(num, sum_series1(num)))\n","sub_path":"Practical 4/q1_sum_series1.py","file_name":"q1_sum_series1.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"388923323","text":"#!/usr/bin/python3\n\n# Copyright © 2012-2015 Graham Sellers\n\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice (including the next\n# paragraph) shall be included in all copies or substantial portions of the\n# Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\nimport sys\n\nimport time\n\nfullscreen = True\n\ntry:\n from OpenGL.GLUT import *\n from OpenGL.GL import *\n from OpenGL.GLU import *\n from OpenGL.raw.GL.ARB.vertex_array_object import glGenVertexArrays, \\\n glBindVertexArray\n\nexcept:\n print ('''\n ERROR: PyOpenGL not installed properly.\n ''')\n sys.exit()\n\n\nfrom math import cos, sin\n\n\nvs_source = '''\n#version 410 core \n\nvoid main(void) \n{ \n const vec4 vertices[] = vec4[](vec4( 0.25, -0.25, 0.5, 1.0), \n vec4(-0.25, -0.25, 0.5, 1.0), \n vec4( 0.25, 0.25, 0.5, 1.0)); \n\n gl_Position = vertices[gl_VertexID]; \n} \n'''\n\n\ntcs_source = '''\n#version 410 core \n\nlayout (vertices = 3) out; \n\nvoid main(void) \n{ \n if (gl_InvocationID == 0) \n { \n gl_TessLevelInner[0] = 5.0; \n gl_TessLevelOuter[0] = 5.0; \n gl_TessLevelOuter[1] = 5.0; \n gl_TessLevelOuter[2] = 5.0; \n } \n gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; \n} \n'''\n\n\ntes_source = '''\n#version 410 core \n\nlayout (triangles, equal_spacing, cw) in; \n\nvoid main(void) \n{ \n gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) + \n (gl_TessCoord.y * gl_in[1].gl_Position) + \n (gl_TessCoord.z * gl_in[2].gl_Position); \n} \n'''\n\n\nfs_source = '''\n#version 410 core \n\nout vec4 color; \n\nvoid main(void) \n{ \n color = vec4(0.0, 0.8, 1.0, 1.0); \n} \n'''\n\n\ndef compile_program():\n\n program = glCreateProgram()\n\n vs = glCreateShader(GL_VERTEX_SHADER);\n glShaderSource(vs, vs_source);\n glCompileShader(vs);\n\n tcs = glCreateShader(GL_TESS_CONTROL_SHADER);\n glShaderSource(tcs, tcs_source);\n glCompileShader(tcs);\n\n tes = glCreateShader(GL_TESS_EVALUATION_SHADER);\n glShaderSource(tes, tes_source);\n glCompileShader(tes);\n\n fs = glCreateShader(GL_FRAGMENT_SHADER);\n glShaderSource(fs, fs_source);\n glCompileShader(fs);\n\n glAttachShader(program, vs);\n glAttachShader(program, tcs);\n glAttachShader(program, tes);\n glAttachShader(program, fs);\n\n glLinkProgram(program);\n \n vao = GLuint(0)\n glGenVertexArrays(1, vao);\n glBindVertexArray(vao);\n\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\n return program\n\n\n\n\n\nclass Scene:\n\n def __init__(self):\n pass\n \n def display(self):\n\n green = [ 0.0, 0.25, 0.0, 1.0 ]\n glClearBufferfv(GL_COLOR, 0, green)\n\n glUseProgram(compile_program())\n glDrawArrays(GL_PATCHES, 0, 3)\n \n glutSwapBuffers()\n\n def reshape(self, width, height):\n pass\n\n def keyboard(self, key, x, y ):\n global fullscreen\n \n print ('key:' , key)\n if key == b'\\x1b': # ESC\n sys.exit()\n \n elif key == b'f' or key == b'F': #fullscreen toggle\n \n if (fullscreen == True):\n glutReshapeWindow(512, 512)\n glutPositionWindow(int((1360/2)-(512/2)), int((768/2)-(512/2)))\n fullscreen = False\n else:\n glutFullScreen()\n fullscreen = True\n \n print('done')\n\n def init(self):\n pass\n\nif __name__ == '__main__':\n start = time.time()\n\n glutInit()\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)\n \n w1 = glutCreateWindow('Listing 3.7 and Listing 3.8')\n glutInitWindowPosition(int((1360/2)-(512/2)), int((768/2)-(512/2)))\n\n fullscreen = False\n #glutFullScreen()\n \n scene = Scene()\n glutReshapeFunc(scene.reshape)\n glutDisplayFunc(scene.display)\n glutKeyboardFunc(scene.keyboard)\n\n glutIdleFunc(scene.display)\n\n scene.init()\n \n glutMainLoop()\n\n","sub_path":"chapt03/listing37.py","file_name":"listing37.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585330926","text":"# Make a dictionary containing three major rivers and the country each river runs through.\n# One key-value pair might be 'nile': 'egypt'.\n\nrivers = {\n\t'nile': 'egypt',\n\t'mississippi': 'the united states',\n\t'ganges': 'india'\n\t}\n\n# Use a loop to print a sentence about each river, such as The Nile runs through Egypt\n\nfor river, country in rivers.items():\n\tprint(f\"The {river.title()} runs through {country.title()}.\")\n\n# Use a loop to print the name of each river included in the dictionary.\n\nprint(\"\\nThe following are the rivers mentioned:\")\nfor river in rivers.keys():\n\tprint(river.title())\n\n# Use a loop to print the name of each country included in the dictionary.\n\nprint(\"\\nThe following are the countries mentioned:\")\nfor country in rivers.values():\n\tprint(country.title())","sub_path":"chp6/rivers.py","file_name":"rivers.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76985678","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 12 18:00:23 2019\r\n\r\n@author: 74293\r\n\"\"\"\r\n\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn import svm\r\nfrom sklearn.metrics import classification_report\r\n\r\nimport pickle\r\n\r\ndef svm_train_model(X_train, Y_train):\r\n '''\r\n print(\"Fitting the classifier to the training set\")\r\n #t0 = time()\r\n param_grid = {'C': [1,10, 100, 500, 1e3, 5e3, 1e4, 5e4, 1e5],\r\n 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }\r\n clf = GridSearchCV(svm.SVC(kernel='rbf', class_weight='balanced'), param_grid)\r\n clf = clf.fit(pca.X_train, pca.Y_train)\r\n #print(\"done in %0.3fs\" % (time() - t0))\r\n print(\"Best estimator found by grid search:\")\r\n #本例中最好的参数为c = 500, cache_size = 200, gamma = 0.01, degree = 3, kernel = 'rbf', tol = 0.001\r\n print(clf.best_estimator_)\r\n print(clf.best_estimator_.n_support_)\r\n '''\r\n svc = svm.SVC(kernel = 'rbf',C=500, gamma = 0.01).fit(X_train, Y_train)\r\n s=pickle.dumps(svc)\r\n f=open('svm.txt','wb')\r\n f.write(s)\r\n f.close()\r\n return svc\r\n\r\ndef svm_predict_model(X_text, svc):\r\n \r\n # label_pr = svc.predict(pca.X_train)\r\n label_pr2 = svc.predict(pca.X_test)\r\n #最后的正确率为89%\r\n print(classification_report(Y_test, label_pr2))\r\n\r\n","sub_path":"code/score/Svm.py","file_name":"Svm.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"26757713","text":"#!/usr/bin/python3\n#-*- coding: UTF-8 -*-\n\nimport numpy as np\nfrom numpy import pi\n\nclass Spline:\n def __init__(self):\n pass\n\n def fit(self, knots, values, d0, dn):\n \"\"\"Fit spline to given values known in knots.\n\n Keyword arguments:\n knots -- knots\n values -- given values\n d0 -- derivative in knots[0]\n dn -- derivative in knots[n]\n \"\"\"\n self.knots = np.array(knots)\n self.n = len(knots)\n self.values = np.array(values)\n h = knots[1] - knots[0]\n # form the known-values vector Y\n Y = np.zeros((self.n))\n Y[0] = d0\n Y[1 : self.n - 1] = [3.0 / h * (self.values[i + 2] - self.values[i]) for i in range(self.n - 2)]\n Y[self.n - 1] = dn\n # compute the derivatives vector D with Tridiagonal Matrix Algorithm\n D = self.__solve(Y)\n # compute the coefficients in matrix form\n s = np.array([\n [1.0, 0, 0, 0],\n [0, 1.0, 0, 0],\n [-3.0 / (h ** 2), -2.0 / h, 3.0 / (h ** 2), -1.0 / h],\n [2.0 / (h ** 3), 1.0 / (h ** 2), -2.0 / (h ** 3), 1.0 / (h ** 2)]\n ])\n p = np.transpose([[self.values[i], D[i], self.values[i + 1], D[i + 1]] for i in range(self.n - 1)])\n self.A = np.transpose(s.dot(p))\n return self\n\n def value(self, knot):\n \"\"\"Compute value in given knot.\n\n Keyword arguments:\n knot -- given knot, must be in interval [x[0], ..., x[n]]\n \"\"\"\n if self.A is None:\n return None\n if (knot < self.knots[0]) or (knot > self.knots[self.n - 1]):\n return None\n\n i = [j for j in range(len(self.knots)-1) if (knot >= self.knots[j] and knot <= self.knots[j + 1])][0]\n x_i = np.array([\n 1,\n (knot - self.knots[i]),\n (knot - self.knots[i]) ** 2,\n (knot - self.knots[i]) ** 3,\n ])\n return x_i.dot(self.A[i])\n\n def __solve(self, d):\n n = len(d) # eq number\n x = np.zeros((n, )) # result\n alpha = np.zeros((n, ))\n beta = np.zeros((n, ))\n alpha[1] = 0\n beta[1] = d[0]\n # implicit: a = 1, b = 4, c = 1\n for i in range(2, n):\n alpha[i] = -1 / (alpha[i - 1] + 4)\n beta[i] = (d[i - 1] - beta[i - 1]) / (alpha[i - 1] + 4)\n # explicit eval of last component\n x[-1] = d[-1]\n for i in reversed(range(0, n - 1)):\n x[i] = alpha[i + 1] * x[i + 1] + beta[i + 1]\n\n return x\n\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n from TDMAsolver import TDMAsolver\n\n knots = np.arange(0.0, 8 * pi + 0.1, pi / 4)\n values = knots * np.sin(knots) + np.log(knots + 1)\n d = np.divide(1, (knots + 1)) + np.sin(knots) + knots * np.cos(knots)\n x = np.arange(0.0, 8 * pi, 0.05)\n spl = Spline().fit(knots, values, d[0], d[-1])\n f = [spl.value(e) for e in x]\n\n true_values = x * np.sin(x) + np.log(x + 1)\n SSE = np.sum([(f[i] - true_values[i]) ** 2 for i in range(len(x))])\n\n line1, = plt.plot(knots, values, 'ro', label=\"Заданные значения\")\n line2, = plt.plot(x, f, label=\"Интерполяция\")\n legend1 = plt.legend(handles=[line1], loc=1)\n ax = plt.gca().add_artist(legend1)\n plt.legend(handles=[line2], loc=4)\n\n plt.grid(True)\n plt.xlabel(\"Сумма квадратов отклонений SSE=%.5f\" % SSE)\n plt.show()\n","sub_path":"interp/spline.py","file_name":"spline.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"118912795","text":"def show_magicians(arrs):\n while arrs:\n tempName = arrs.pop()\n print(\"Hello! \" + tempName.title())\n\ndef make_great(arrs): #解法2:arrs.pop()到新数组, 顺带加上 The Great, 此时 arrs 已空, 将新数组 pop 回去(套路啊...)\n changedArr = []\n for arr in arrs: # JS 用惯了就喜欢用个 for 循环\n arr = \"The Great \" +arr\n changedArr.append(arr)\n return changedArr\n\narrs = [\"micheal\", \"jared\", \"wayne\"]\nshow_magicians(make_great(arrs))\nshow_magicians(arrs)\n","sub_path":"函数练习2.py","file_name":"函数练习2.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"641035343","text":"import urwid\n\nfrom pib.menuconfig.buttonbox import ButtonBox\nfrom pib.menuconfig.motif import MotifLineBox\nfrom pib.menuconfig.subtreewalker import SubtreeWalker\n\n# This file implements a dialog box in the style of Linux's menuconfig\nclass MenuconfigDialog(urwid.WidgetWrap):\n def __init__(self, root_menu_item, hint=None):\n self._menu_history = []\n self._root_menu_item = root_menu_item\n\n # Provide a hint at the top of the screen (as in Linux's menuconfig)\n if hint == None:\n # XXX\n hint = u'Arrow keys navigate the menu. Press to perform the selected action. Press to enter submenus --->.\\nLegend: <+> some builds selected <*> all builds selected'\n # hint = u'';\n self._hint = urwid.Text(hint)\n\n # Dynamic buttons for controlling the menu (as in Linux's menuconfig)\n self._button_box = ButtonBox()\n\n # Make a dummy menu widget\n self._menu = urwid.SolidFill('X')\n # Add decoration around the menu\n self._menu = MotifLineBox(self._menu, inset=True)\n self._menu = urwid.Padding(self._menu, left=1, right=1)\n\n # Build the self._menu \"view\" from the given root_menu_item \"model\"\n self._enter_menu(root_menu_item)\n\n # Place the menu on top and the button box on bottom\n self._main_widget = urwid.Frame(\n self._menu,\n header=self._hint,\n footer=self._button_box,\n focus_part='body'\n )\n\n urwid.WidgetWrap.__init__(self, self._main_widget)\n\n def _enter_menu(self, root_menu_item):\n keys = root_menu_item.get_child_keys()\n if len(keys) <= 0:\n return # Can't enter an empty menu\n self._menu_history.append(root_menu_item)\n self._set_menu(root_menu_item)\n\n def _back_menu(self, foo=None): # Eat the button argument\n if len(self._menu_history) <= 1:\n # Don't pop the root menu item\n return\n self._menu_history.pop()\n prev_menu = self._menu_history[-1]\n self._set_menu(prev_menu)\n\n def _set_menu(self, root_menu_item):\n keys = root_menu_item.get_child_keys()\n first_item = root_menu_item.get_child_node(keys[0])\n self._menu_tree = urwid.TreeListBox(SubtreeWalker(first_item))\n self._menu.original_widget.set_original_widget(self._menu_tree)\n # Now that we're in a different menu, we will have new buttons\n self._update_buttons()\n self._invalidate()\n\n def _update_buttons(self):\n current_focus = self._menu_tree.get_focus()\n focus_actions = current_focus[0].get_actions()\n menu_actions = []\n if len(self._menu_history) > 1:\n menu_actions.append(('Back', self._back_menu))\n self._button_box.set_actions(\n focus_actions +\n menu_actions\n )\n # Select the first button by default\n if len(self._button_box.buttons) > 0:\n self._button_box.buttons[0].pseudo_focus = True\n \n\n def keypress(self, size, key):\n if key in ('left', 'right'):\n return self._button_box.keypress(size, key)\n elif key in ('up', 'down', 'page up', 'page down'):\n initial_focus = self._menu_tree.get_focus()\n result = self._menu.keypress(size, key)\n current_focus = self._menu_tree.get_focus()\n if initial_focus[0] is not current_focus[0]:\n self._update_buttons()\n return result\n elif key in (' '):\n # Send space keys to the action in focus in the button box\n return self._button_box.keypress(size, key)\n elif key in ('enter'):\n current_focus = self._menu_tree.get_focus()\n node = current_focus[0].get_node()\n if node.is_submenu():\n self._enter_menu(node)\n return None\n return key\n return key\n\n def _menu_item_clicked(self, item):\n # TODO: Maybe make a note that this menu item is in focus?\n pass\n","sub_path":"pib-tui/pib/menuconfig/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"174798909","text":"import requests\n\nbase_url = \"https://ru.wikipedia.org/w/api.php?action=opensearch&search=\"\nrequest_params = \"&limit=3&origin=*&format=json\"\n\n\ndef proceedSearch(q):\n response = requests.get(base_url + q + request_params, timeout=(20, 20))\n print(response.json())\n if response.status_code == 200:\n return response.json()[3]\n else:\n return None\n","sub_path":"wiki_test.py","file_name":"wiki_test.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"554684844","text":"import time\n\ndef is_sorted(items):\n for i in range(len(items) - 1):\n if items[i] >= items[i + 1]:\n return False\n return True\n\ndef bubble_sort(items):\n while is_sorted(items) == False:\n for i in range(len(items) - 1):\n if items[i] >= items[i + 1]:\n items[i], items[i + 1] = items[i + 1], items[i]\n return items\n\nstart_time = time.time()\nprint(bubble_sort([9,4,17,2]))\nprint(\"%.10f seconds\" % (time.time() - start_time))\n\ndef bubble_sort_recursive(items):\n for i in range(len(items) - 1):\n if items[i] >= items[i + 1]:\n items[i], items[i + 1] = items[i + 1], items[i]\n return bubble_sort_recursive(items)\n return items\n\nstart_time_recursive = time.time()\nprint(bubble_sort_recursive([9,4,17,2]))\nprint(\"%.10f seconds\" % (time.time() - start_time_recursive))\n","sub_path":"SortingAlgorithm/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"195615495","text":"import discord\r\nimport asyncio\r\nfrom discord.ext import commands\r\n\r\nclass Mycog:\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command()\r\n async def test(self):\r\n await self.bot.say(\"Bot is up and running!\")\r\n\r\n @commands.command()\r\n async def punch(self, user : discord.Member):\r\n await self.bot.say(\"ONE PUNCH! And \" + user.mention + \" is out! ლ(ಠ益ಠლ)\")\r\n\r\n @asyncio.coroutine\r\n def welcome(user):\r\n m = config['welcome_message'].format(\r\n name = user.name,\r\n mention_name = user.mention,\r\n id = user.id,\r\n )\r\n if public_channel is not None:\r\n yield from bot.send_message(public_channel, m)\r\n\r\n @asyncio.coroutine\r\n def help_message(user):\r\n m = config['help_message'].format(\r\n name = user.name,\r\n mention_name = user.mention,\r\n id = user.id,\r\n )\r\n yield from bot.send_message(user, m)\r\n\r\n @bot.listen\r\n @asyncio.coroutine\r\n def on_member_join(member):\r\n server = member.server\r\n if server.id != config['server']:\r\n return\r\n\r\n # debug!\r\n print('{} [id = {}] joined the server'.format(member.name, member.id))\r\n\r\n yield from help_message(member)\r\n yield from welcome(member)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Mycog(bot))\r\n","sub_path":"cog1/cog1.py","file_name":"cog1.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"654437923","text":"# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (nested_scopes, generators, division, absolute_import, with_statement,\n print_function, unicode_literals)\n\nimport os\nimport unittest\nfrom tempfile import mkdtemp\n\nfrom twitter.common.dirutil import safe_mkdir, safe_open, safe_rmtree\n\nfrom pants.base.address import Address\nfrom pants.base.build_root import BuildRoot\nfrom pants.base.target import Target\nfrom pants.targets.sources import SourceRoot\n\n\nclass BaseBuildRootTest(unittest.TestCase):\n \"\"\"A baseclass useful for tests requiring a temporary buildroot.\"\"\"\n\n build_root = None\n\n @classmethod\n def build_path(cls, relpath):\n \"\"\"Returns the canonical BUILD file path for the given relative build path.\"\"\"\n if os.path.basename(relpath).startswith('BUILD'):\n return relpath\n else:\n return os.path.join(relpath, 'BUILD')\n\n @classmethod\n def create_dir(cls, relpath):\n \"\"\"Creates a directory under the buildroot.\n\n relpath: The relative path to the directory from the build root.\n \"\"\"\n safe_mkdir(os.path.join(cls.build_root, relpath))\n\n @classmethod\n def create_file(cls, relpath, contents='', mode='w'):\n \"\"\"Writes to a file under the buildroot.\n\n relpath: The relative path to the file from the build root.\n contents: A string containing the contents of the file - '' by default..\n mode: The mode to write to the file in - over-write by default.\n \"\"\"\n with safe_open(os.path.join(cls.build_root, relpath), mode=mode) as fp:\n fp.write(contents)\n\n @classmethod\n def create_target(cls, relpath, target):\n \"\"\"Adds the given target specification to the BUILD file at relpath.\n\n relpath: The relative path to the BUILD file from the build root.\n target: A string containing the target definition as it would appear in a BUILD file.\n \"\"\"\n cls.create_file(cls.build_path(relpath), target, mode='a')\n\n @classmethod\n def setUpClass(cls):\n cls.build_root = mkdtemp(suffix='_BUILD_ROOT')\n BuildRoot().path = cls.build_root\n cls.create_file('pants.ini')\n Target._clear_all_addresses()\n\n @classmethod\n def tearDownClass(cls):\n BuildRoot().reset()\n SourceRoot.reset()\n safe_rmtree(cls.build_root)\n\n @classmethod\n def target(cls, address):\n \"\"\"Resolves the given target address to a Target object.\n\n address: The BUILD target address to resolve.\n\n Returns the corresponding Target or else None if the address does not point to a defined Target.\n \"\"\"\n return Target.get(Address.parse(cls.build_root, address, is_relative=False))\n","sub_path":"tests/python/pants_test/base_build_root_test.py","file_name":"base_build_root_test.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"477494770","text":"import sys\nimport types\nimport os\nimport collections\n\nfrom . import io\nfrom . import cursor\nfrom . import bases\nfrom . import tools\nfrom . import helpers\n\n\n__all__ = ('update', 'respond', 'edit', 'select')\n\n\n_io = io.IO(sys.stdin, sys.stdout)\n\n\n_cursor = cursor.Cursor(_io)\n\n\n_assets = types.SimpleNamespace(\n caption = tools.Caption(\n tools.Display(\n _io,\n _cursor\n )\n ),\n machine = None,\n shows = [],\n fall = 0,\n signal = None,\n gentle = False,\n)\n\n\ndef _finish(gentle):\n\n _assets.signal()\n\n _assets.gentle = gentle\n\n\ndef finish(gentle):\n\n \"\"\"\n Stop listening for keypresses.\n \"\"\"\n\n _finish(gentle)\n\n\ndef _update(value):\n\n _assets.machine.clear()\n\n _assets.caption.update(value)\n\n _assets.machine.draw()\n _assets.machine.focus()\n\n\ndef update(value):\n\n \"\"\"\n Update hint.\n \"\"\"\n\n with _cursor.hidden:\n _update(value)\n\n\ndef _respond(shows, full, color, draw, delimit):\n\n _assets.machine.clear()\n\n if shows is None:\n shows = _assets.shows.copy()\n\n _assets.shows.clear()\n\n if color:\n paint = lambda value: helpers.paint(value, color)\n shows = map(paint, shows)\n\n show = delimit.join(shows)\n\n if not full:\n show = _assets.fall * os.linesep + show\n\n _assets.caption.finish(show, full = full)\n\n if not full:\n _io.send(os.linesep)\n\n\ndef respond(shows = None,\n full = False,\n color = None,\n draw = True,\n delimit = ', '):\n\n \"\"\"\n Reset state and show results.\n\n :param list[str] show:\n What to show instead.\n :param bool full:\n Whether to also erase prompt.\n :param str color:\n Used to paint results.\n :param bool draw:\n Whether to show results.\n :param str delimit:\n Used to join results together.\n \"\"\"\n\n with _cursor.hidden:\n _respond(shows, full, color, draw, delimit)\n\n\ndef _execute(machine, check):\n\n _assets.machine = machine\n\n translator = bases.Translator(_io, callback = _assets.machine.invoke)\n\n source = bases.Source(_io, callback = translator.invoke)\n\n _assets.signal = source.done\n\n while True:\n source.stream()\n result = _assets.machine.get()\n if _assets.gentle and check and not check(result):\n _io.ring()\n continue\n break\n\n shows = machine.view(result)\n _assets.shows.extend(shows)\n\n return result\n\n\ndef _measure():\n\n (my, mx) = _cursor.measure()\n\n my -= 1\n mx -= 1\n\n _assets.caption.locate(mx)\n\n return (my, mx)\n\n\nclass Abort(Exception):\n\n __slots__ = ()\n\n\ndef _callback(function):\n\n def callback(name, *args):\n if function:\n result = _assets.machine.get()\n try:\n function(name, result, *args)\n except Abort:\n _io.ring()\n return\n if name == 'submit':\n _finish(True)\n\n return callback\n\n\ndef _line_edit_single(my, mx, limit, funnel, callback):\n\n editor = tools.LineEditor(\n _io,\n _cursor,\n mx,\n limit,\n funnel,\n callback = callback\n )\n\n return editor\n\n\ndef _line_edit_multi(my, mx, trail, limit, funnel, callback):\n\n def finchk():\n init = len(editor.subs)\n subs = editor.subs[-trail:]\n result = len(subs) == trail and not any(sub.buffer for sub in subs)\n if result:\n extra = init == trail\n editor.delete(True, trail - extra)\n return result\n\n editor = tools.MultiLineEditor(\n _io,\n _cursor,\n finchk,\n my,\n mx,\n limit,\n funnel,\n callback = callback\n )\n\n return editor\n\n\ndef edit(prompt = None,\n *,\n hint = None,\n limit = None,\n funnel = None,\n trail = 2,\n check = None,\n callback = None,\n multi = False):\n\n \"\"\"\n Await and return input from user.\n\n :param str prompt:\n Persistent prompt shown before input.\n :param str hint:\n Temporary grayed-out prompt shown after prompt.\n :param int limit:\n Max allowed size of internal rune buffer.\n :param func funnel:\n Used with ``(rune)`` and must return some rune.\n :param int trail:\n Only with ``multi``. Amount of empty lines required to submit.\n :param func check:\n Used with ``(result)`` for validation and must return :class:`bool`.\n :param func callback:\n Used with ``(name, *args)`` for listening to keypress events.\n :param bool multi:\n Whether to accept line breaks.\n\n Event names are followed by current result, and then arguments.\n \"\"\"\n\n (my, mx) = _measure()\n\n callback = _callback(callback)\n\n if multi:\n machine = _line_edit_multi(my, mx, trail, limit, funnel, callback)\n fall = 1\n else:\n machine = _line_edit_single(my, mx, limit, funnel, callback)\n fall = 0\n\n _assets.fall = fall\n\n _assets.caption.create(prompt or '', hint or '', fall = multi)\n\n value = _execute(machine, check)\n\n return value\n\n\ndef _select_single(my, mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n callback):\n\n select = tools.Select(\n _io,\n _cursor,\n my,\n mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n callback = callback\n )\n\n return select\n\n\ndef _select_multi(my, mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n unpin,\n pin,\n indexes,\n callback):\n\n select = tools.MultiSelect(\n unpin,\n pin,\n indexes,\n _io,\n _cursor,\n my,\n mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n callback = callback\n )\n\n return select\n\n\ndef _select_filter(pairs, argument):\n\n argument = argument.lower()\n\n counter = collections.Counter(argument)\n\n for (index, option) in pairs:\n option = option.lower()\n for (rune, rcount) in counter.items():\n ccount = option.count(rune)\n if 0 < ccount >= rcount:\n continue\n break\n else:\n yield (index, option)\n\n\ndef select(options,\n prompt = None,\n *,\n hint = None,\n prefix = '> ',\n color = None,\n indent = None,\n funnel = None,\n filter = None,\n limit = 6,\n index = 0,\n unpin = '[ ] ',\n pin = '[X] ',\n indexes = (),\n check = None,\n callback = None,\n multi = False):\n\n \"\"\"\n Draw a menu of options. Traverse using **↑** and **↓** keys. Type to filter.\n Enter to submit. Return index(es) of option(s).\n\n This should not be used directly for most purposes.\n\n :param str prompt:\n Persistent prompt shown before input.\n :param str hint:\n Temporary grayed-out prompt shown after prompt.\n :param str prefix:\n Indicator for unpinned item.\n :param str color:\n ANSI color sequence to paint unpinned item.\n :param func funnel:\n Used with current ``(option)`` and must return some :class:`str`.\n :param int limit:\n Max amount of options displayed at any point.\n :param int index:\n Where to place the cursor upon initial draw.\n :param str unpin:\n Indicator for un-selected items (multi only).\n :param str pin:\n Indicator for selected items (multi only).\n :param list[int] indexes:\n Indexes options to pre-select (multi only).\n :param func check:\n Used with ``(result)`` for validation and must return :class:`bool`.\n :param func callback:\n Used with ``(name, *args)`` for listening to keypress events.\n :param bool multi:\n Whether to allow multiple selections using **←** and **→** keys.\n\n Event names are followed by current result, and then arguments.\n \"\"\"\n\n (my, mx) = _measure()\n\n if color:\n def paint(index, option):\n return helpers.paint(option, color)\n funnel = helpers.combine_functions(funnel, paint, index = 1)\n\n if not limit:\n limit = len(options)\n my = min(my, limit)\n\n pushers = [len(prefix)]\n if indent:\n pushers.append(indent)\n cover = max(pushers)\n if multi:\n cover += max(map(len, (unpin, pin)))\n\n mx -= cover\n\n callback = _callback(callback)\n\n if not filter:\n filter = _select_filter\n\n if multi:\n machine = _select_multi(\n my, mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n unpin,\n pin,\n indexes,\n callback\n )\n else:\n machine = _select_single(\n my, mx,\n options,\n prefix,\n indent,\n funnel,\n filter,\n index,\n callback\n )\n\n _assets.fall = 0\n\n _assets.caption.create(prompt or '', hint or '', fall = 1)\n\n machine.draw()\n machine.focus()\n\n with _cursor.hidden:\n value = _execute(machine, check)\n\n return value\n","sub_path":"survey/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":9517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"440796692","text":"import torch.nn as nn\nimport numpy as np\nimport torch\n\n# class TokenEmbedding(nn.Embedding):\n# def __init__(self, vocab_size, embed_size=512):\n# super().__init__(vocab_size, embed_size, padding_idx=0)\nclass TokenEmbedding(nn.Module):\n def __init__(self, vocab_size, embed_size=512):\n super().__init__()\n #path='/home/sriharshkamma/final/BERT-pytorch/fv.npy'\n path='/home/sriharshkamma/final/BERT-pytorch/bert_pytorch/fasttext_vectors.npy'\n embedding_array=np.load(path)\n self.embedding_dim=embed_size\n self.embedding=nn.Embedding(vocab_size, embed_size, padding_idx=0)\n self.embedding.weight.data.copy_(torch.from_numpy(embedding_array))\n self.embedding.weight.requires_grad=False\n def forward(self,x):\n return self.embedding(x)\n \n","sub_path":"bert_pytorch/model/embedding/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"639410390","text":"import sys\nsys.stdin = open('input.txt')\n\n\n# 구현은 했으나 아직 인덱스 에러를 해결하지 못했음\n# 디버깅 돌려보면서 찾는 중입니다.\n\ndef is_palindrome(i, j, k, board):\n len_board_h = len(board)//2\n\n if len(board) % 2:\n start = board[:len_board_h] # 구간의 처음 ~ 중간까지의 범위\n end = board[:len_board_h:-1] # 중간 ~ 구간의 끝 까지의 범위 (비교할 수 있도록 반대로 슬라이싱하였다.)\n # [구간의 끝 : 중간 : -1]\n # 회문의 길이가 홀수일 떄\n else:\n start = board[:len_board_h] # 구간의 처음 ~ 중간 글자 이전\n end = board[:len_board_h-1:-1] # 중간글자 다음부터 ~ 구간의 끝\n\n # 비교한 두 범위가 같다면 정답을 반환한다.\n if start == end:\n return board\n\n return []\n\n\nfor idx in range(1, 11):\n n = int(input())\n board = [list(input()) for _ in range(100)]\n board_r = list(map(list, zip(*board)))\n\n answer = 1\n for i in range(100):\n for j in range(98):\n for k in range(j+2, 101):\n\n # 가로\n garo = is_palindrome(i, j, k, board[i][j:k])\n if len(garo) > answer:\n answer = len(garo)\n\n\n # 세로\n sero = is_palindrome(i, j, k, board_r[i][j:k])\n if len(sero) > answer:\n answer = len(sero)\n\n\n print('#{} {}'.format(idx, answer))","sub_path":"SWEA/1216_회문2/1216_회문2.py","file_name":"1216_회문2.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"333063431","text":"import sys\nimport math\nimport numpy as np\nfrom PyEngine3D.Utilities import Float4\n\nEPSILON = sys.float_info.epsilon\nGRAVITY = 20.0\nBOUND_BOX_OFFSET = 0.1\n\nCHECK_COLLIDE_HEIGHT_MAP_LEVEL = 3\n\nHIT_RENDER_TIME = 0.2\nHIT_RENDER_COLOR = Float4(10.0, 10.0, 2.0, 1.0)\n\n# Player\nACCELERATION = 2.0\nFORWARD_MOVE_SPEED = 15.0\nAIM_ANGLE_THRESHOLD = 0.08\n\nSIDE_ACCELERATION = 8.0\nSIDE_MOVE_SPEED = 15.0\n\nVERTICAL_ACCELERATION = 8.0\nVERTICAL_MOVE_SPEED = 15.0\n\nROTATION_PITCH_LIMIT = math.pi * 0.3\nROTATION_ROLL_LIMIT = math.pi * 0.25\nROTATION_SPEED = 2.0\nROTATION_ROLL_SPEED = 1.0\n\nTOP_POSITION_LIMIT = 50.0\nBOTTOM_POSITION_LIMIT = -50.0\nDAMPING_HEIGHT = 5.0\nDAMPING_RATIO = min(1.0, max(0.0, DAMPING_HEIGHT / (TOP_POSITION_LIMIT - BOTTOM_POSITION_LIMIT)))\n\n# Camera\nROTATION_DELAY_SPEED = 2.0\nROTATION_DELAY_LIMIT = 0.25\nCAMERA_OFFSET_HORIZONTAL = 8.0\nCAMERA_OFFSET_VERTICAL = 8.0\nCAMERA_OFFSET_SPEED = 5.0\nCAMERA_OFFSET_Y = 4.0\n\n# UI\nAIM_DISTANCE = 100000.0\nZOOM_SPEED = 5.0\n\n# Resources\nSOUND_EXPLOSION = 'explode_02'\nSOUND_FIRE = 'assaultrifle1'\nSOUND_BULLET_HITS = ['Bullet_Metal_01', 'Bullet_Metal_02', 'Bullet_Metal_03']\nSOUND_BGM = 'game_load'\nSOUND_BEEP_WANING = 'beep_warning'\n\nTEXTURE_ALERT = 'alert'\n","sub_path":"Scripts/GameClient/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"458215234","text":"# Represents a TCP segment\n# Author: James Patton\n\n\nclass TcpSegment():\n def __init__(self, stream):\n \"\"\"\n Initialized with a byte stream, NOT a string!\n \"\"\"\n self._parse_header(stream)\n self._build_header_dict()\n\n def _parse_header(self, stream):\n \"\"\"\n Parses the received bytestream into header fields\n \"\"\"\n # The first 16 bytes are source port\n self.source_port = self.concat_bytes(stream[0:2])\n \n # The second 16 bytes are dest port\n self.dest_port = self.concat_bytes(stream[2:4])\n\n # The entire 32 byte word is the sequence number\n self.seq_number = self.concat_bytes(stream[4:8])\n\n # The next word is the acknowledgement number\n self.ack_number = self.concat_bytes(stream[8:12])\n\n # first 4 bits of Byte 12 is the data offset\n mask = 0b11110000\n self.data_offset = (stream[12] & mask) >> 4\n\n if self.data_offset not in range(5, 16):\n raise ValueError('Data Offset out of bounds: %s' % stream[12])\n\n # first three bits of last four of Byte 12 is reserved\n mask = 0b00001110\n self.reserved = (stream[12] & mask) >> 1\n\n if self.reserved != 0:\n error = 'Reserved must be zero, instead is %s' % self.reserved\n raise ValueError(error)\n\n # last bit is the ns flag\n mask = 0b00000001\n self.ns = stream[12] & mask\n\n # byte 13 is remaining control flags\n self.cwr = (stream[13] & 0b10000000) >> 7\n self.ece = (stream[13] & 0b01000000) >> 6\n self.urg = (stream[13] & 0b00100000) >> 5\n self.ack = (stream[13] & 0b00010000) >> 4\n self.psh = (stream[13] & 0b00001000) >> 3\n self.rst = (stream[13] & 0b00000100) >> 2\n self.syn = (stream[13] & 0b00000010) >> 1\n self.fin = stream[13] & 0b00000001\n\n # bytes 14 & 15 are the window size\n self.win_size = self.concat_bytes(stream[14:16])\n\n # bytes 16 & 17 are the checksum\n self.checksum = self.concat_bytes(stream[16:18])\n\n # bytes 18 & 19 are the urg_pointer\n self.urg_pointer = self.concat_bytes(stream[18:20])\n\n # Remaining bytes are the TCP data\n self.data = stream[self.data_offset:]\n\n def _build_header_dict(self):\n self.header = {}\n self.header['protocol'] = 'TCP'\n self.header['source_port'] = self.source_port\n self.header['dest_port'] = self.dest_port\n self.header['seq_number'] = self.seq_number\n self.header['ack_number'] = self.ack_number\n self.header['data_offset'] = self.data_offset\n self.header['reserved'] = self.reserved\n self.header['ns'] = self.ns\n self.header['cwr'] = self.cwr\n self.header['ece'] = self.ece\n self.header['urg'] = self.urg\n self.header['ack'] = self.ack\n self.header['psh'] = self.psh\n self.header['rst'] = self.rst\n self.header['syn'] = self.syn\n self.header['fin'] = self.fin\n self.header['win_size'] = self.win_size\n self.header['checksum'] = self.checksum\n self.header['urg_pointer'] = self.urg_pointer\n\n def concat_bytes(self, seq):\n \"\"\"\n concatenates a byte list into a single 32 bit word\n (if byte list is length 4 or less\n \"\"\"\n accum = 0\n length = len(seq)\n for i in range(length):\n accum |= seq[i] << 8 * (length - 1 - i)\n\n return accum\n","sub_path":"protocol/tcp_segment.py","file_name":"tcp_segment.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533691038","text":"\"\"\"\nCopyright 2019 Anqi Fu, Junzi Zhang\n\nThis file is part of A2DR.\n\nA2DR is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nA2DR is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with A2DR. If not, see .\n\"\"\"\n\nimport numpy as np\nimport scipy as sp\nimport numpy.linalg as LA\nimport copy\nimport time\nimport scipy.sparse.linalg\nimport matplotlib\nmatplotlib.use('TKAgg')\nimport matplotlib.pyplot as plt\n\nfrom cvxpy import *\nfrom scipy import sparse\nfrom scipy.optimize import nnls\nfrom sklearn.datasets import make_sparse_spd_matrix\n\nfrom a2dr import a2dr\nfrom a2dr.proximal import *\nfrom a2dr.tests.base_test import BaseTest\n\nclass TestPaper(BaseTest):\n \"\"\"Unit tests for A2DR paper experiments.\"\"\"\n\n def setUp(self):\n np.random.seed(1)\n self.eps_rel = 1e-8 # specify these in all examples?\n self.eps_abs = 1e-6\n self.MAX_ITER = 1000\n\n def test_coupled_qp(self):\n # Problem data.\n K = 4 # number of blocks\n p = 10 # number of coupling constraints\n nk = 30 # variable dimension of each subproblem QP\n mk = 50 # constrain dimension of each subproblem QP\n A_list = [np.random.randn(p, nk) for k in range(K)]\n F_list = [np.random.randn(mk, nk) for k in range(K)]\n q_list = [np.random.randn(nk) for k in range(K)]\n x_list = [np.random.randn(nk) for k in range(K)]\n g_list = [F_list[k].dot(x_list[k])+0.1 for k in range(K)]\n A = np.hstack(A_list)\n x = np.hstack(x_list)\n b = A.dot(x)\n P_list = [np.random.randn(nk,nk) for k in range(K)]\n Q_list = [P_list[k].T.dot(P_list[k]) for k in range(K)]\n \n # Convert problem to standard form.\n def tmp(k, Q_list, q_list, F_list, g_list):\n return lambda v, t: prox_qp(v, t, Q_list[k], q_list[k], F_list[k], g_list[k])\n # Use \"map\" method to avoid implicit overriding, which would make all the proximal operators the same\n prox_list = list(map(lambda k: tmp(k,Q_list,q_list,F_list,g_list), range(K)))\n \n # Solve with DRS.\n drs_result = a2dr(prox_list, A_list, b, anderson=False, precond=True, max_iter=self.MAX_ITER)\n print('DRS finished.')\n \n # Solve with A2DR.\n a2dr_result = a2dr(prox_list, A_list, b, anderson=True, precond=True, max_iter=self.MAX_ITER)\n print('A2DR finished.')\n self.compare_total(drs_result, a2dr_result)\n \n # Check solution correctness.\n a2dr_x = a2dr_result['x_vals']\n a2dr_obj = np.sum([a2dr_x[k].dot(Q_list[k]).dot(a2dr_x[k]) \n + q_list[k].dot(a2dr_x[k]) for k in range(K)])\n a2dr_constr_vio = [np.linalg.norm(np.maximum(F_list[k].dot(a2dr_x[k])-g_list[k],0))**2 \n for k in range(K)]\n a2dr_constr_vio += [np.linalg.norm(A.dot(np.hstack(a2dr_x))-b)**2]\n a2dr_constr_vio_val = np.sqrt(np.sum(a2dr_constr_vio))\n print('objective value of A2DR = {}'.format(a2dr_obj))\n print('constraint violation of A2DR = {}'.format(a2dr_constr_vio_val))\n\nif __name__ == '__main__':\n tests = TestPaper()\n tests.setUp()\n tests.test_coupled_qp()\n\n","sub_path":"examples/paper_examples/coupled_qp.py","file_name":"coupled_qp.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"592691484","text":"import tkinter\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nfrom tkinter import font\r\nimport tkinter.filedialog as fd\r\nimport WolverineFunctions\r\nimport FieldFunctions\r\nimport SensorrunGenerator\r\nimport pandas\r\nimport os\r\nimport multiprocessing\r\nimport base64\r\n\r\ndef donothing():\r\n print(\"nothing happened\")\r\n\r\ndef AskForFilepath():\r\n# ask the user for a file input path to create folders in\r\n print(\"Select a folder containing run data\")\r\n print()\r\n\r\n listbox1.delete(0, END)\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\"%H:%M:%S\") + \" Gathering path information\")\r\n listbox1.insert(END, \"- make sure to close any files that will be opened by this program\")\r\n\r\n filepath = fd.askdirectory()\r\n\r\n print(filepath)\r\n\r\n pb[\"value\"] = 0\r\n entrybox.delete(0, END)\r\n entrybox.insert(0, filepath)\r\n\r\n CheckForFilepath()\r\n\r\n return filepath\r\n\r\ndef CheckForFilepath():\r\n \"\"\"If there is nothing in the entrybox, this greys out the process run button\"\"\"\r\n if entrybox.get() == '':\r\n processbutton.state(['disabled'])\r\n else:\r\n processbutton.state(['!disabled'])\r\n\r\ndef CheckforDupes():\r\n \"\"\"Checks for dupe runs in the database. if the run is in the database, the whole upload is canceled\"\"\"\r\n print(\"Checking for dupes\")\r\n\r\n filepath = entrybox.get()\r\n\r\n # this checks to see if the Generate sensorrun box is checked. If it is, it will generate a new sensorrun before\r\n # it has the chance to check for dupes\r\n if SRBool.get() == 1:\r\n if os.path.exists(filepath + '/Sensorrun.txt'):\r\n result = messagebox.askyesno(\"warning\", \"Sensorrun.txt aleady exists. \\nWould you like to overwrite it?\")\r\n\r\n if result == True:\r\n SRGenerator.generate(entrybox)\r\n listbox1.insert(END, \"- Sensorrun.txt Created\")\r\n SRBoolButton.invoke()\r\n else:\r\n return False\r\n\r\n else:\r\n SRGenerator.generate(entrybox)\r\n listbox1.insert(END, \"- Sensorrun.txt Created\")\r\n SRBoolButton.invoke()\r\n\r\n\r\n #this gets the sensorrundataframe using the getsensorrun function from wolverine. the entrybox.get is the filepath\r\n #this is the current sensorrun file\r\n if os.path.isdir(filepath):\r\n try:\r\n sensorrun_df = WolverineFunctions.GetSensorrun(entrybox.get())\r\n except:\r\n listbox1.insert(END, \"No Sensorrun.txt detected\")\r\n listbox1.update()\r\n else:\r\n return\r\n\r\n #the try/except block is here just in case there are no sensorruns in the database .\r\n #if there arent, the Check for dupes exits and everything proceeds without it\r\n #this is the list of sensorruns in the database\r\n try:\r\n sensorrun_db = pandas.read_sql_table(table_name=\"sensorrun\", con=WolverineFunctions.EstablishConnection(), schema=\"wolverine\", columns=['runname'])\r\n except:\r\n return\r\n\r\n #turning the column headers into a list because the first line is read in as headers\r\n sensorrun_df_columns = list(sensorrun_df)\r\n\r\n #grabbing the runnumber from the list of headers\r\n currentrunid = str(sensorrun_df_columns[1])\r\n print(f\"Current Run = {currentrunid}\")\r\n\r\n #creating a list of runnumbers from the database\r\n runs = sensorrun_db['runname'].tolist()\r\n print(runs)\r\n\r\n\r\n\r\n #Checking if the current run number is in the list of runs\r\n if currentrunid in runs:\r\n print(\"THERE'S A DUPE\")\r\n return True\r\n else:\r\n print(\"no dupes\")\r\n listbox1.insert(END, f\"- Preparing to process {currentrunid}\")\r\n listbox1.update()\r\n return False\r\n\r\ndef ProcessRunParent():\r\n if CheckforDupes() == True:\r\n listbox1.insert(END, \"\")\r\n listbox1.insert(END, \"- Duplicate Sensorrun.txt detected. Check to see if the run name is the same\")\r\n listbox1.update()\r\n return\r\n elif CheckforDupes() == False:\r\n processrun()\r\n\r\ndef processrun(newyaw=0):\r\n # Asking the user where the raw files are located. This path will also be where the CSV output\r\n # files are generated.\r\n filepath = entrybox.get()\r\n # starttime = 0 # Time the loading process begins\r\n # endtime = 0 # Time the loading process ended. Will be used with start time to show total time process took.\r\n\r\n if not os.path.isdir(filepath):\r\n # The user clicked the \"Cancel\" button while being prompted to select the raw file(s) location.\r\n listbox1.delete(0, END)\r\n listbox1.insert(END, \"invalid filepath\")\r\n else:\r\n\r\n # Making sure the raw data files exist. They must all exist in order for the process to begin.\r\n if CheckForFiles(filepath):\r\n\r\n # Display the start time of the process\r\n starttime = WolverineFunctions.time.time()\r\n\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\"%H:%M:%S\") + \" Checking for duplicate runs\")\r\n pb[\"value\"] = 1\r\n\r\n # If another shapefile is added, add it here\r\n shapefiles = ['alison35plots', 'f119_rbtn']\r\n sensorrun_df = WolverineFunctions.GetSensorrun(filepath)\r\n\r\n current_shapefile = sensorrun_df.iloc[16][1].lower()\r\n current_shapefile = current_shapefile[1:]\r\n\r\n if current_shapefile in shapefiles:\r\n # creating folders\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\"%H:%M:%S\") + \" Start Time\")\r\n listbox1.update()\r\n print(filepath)\r\n WolverineFunctions.CreateFolders(filepath)\r\n # updating the progressbar\r\n pb[\"value\"] = 10\r\n\r\n # reading and uploading sensorrun to the database\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Uploading Sensorrun to database\")\r\n listbox1.update()\r\n vRunID = WolverineFunctions.ReadSensorrun(filepath, newyaw)\r\n pb[\"value\"] = 20\r\n\r\n # reading campbell scientific loger (TOA5_11790.Wolverine.dat)\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Converting lat and long to UTM coordinates for Campbell Scientific logger\")\r\n listbox1.update()\r\n campbellscientific_csv = WolverineFunctions.ReadCampbellScientificCSV(filepath, vRunID, newyaw, snapyaw=ToggleSnappingBool.get())\r\n pb[\"value\"] = 30\r\n\r\n # uploading all the separate tables created in the last step to the db\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Uploading all tables from Campbell Scientific logger to the database\")\r\n listbox1.update()\r\n WolverineFunctions.UploadAllTables(campbellscientific_csv, filepath + '\\processed')\r\n pb[\"value\"] = 60\r\n\r\n # reading the geoscout logger (MAP0001) and uploading ccsensor1/2/3/4 to the db\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Reading and uploading Geoscout Logger\")\r\n listbox1.update()\r\n WolverineFunctions.ReadGeoLoggerCSV(filepath, vRunID, campbellscientific_csv)\r\n\r\n # reading back gsalldata with the thermalcouple and stmakepoint added on\r\n gsalldata_df = pandas.read_sql_query(f\"select * from {current_shapefile}.gsalldata\")\r\n gsalldata_df.to_csv(filepath + '\\processed' + '\\gsalldata.csv', encoding='utf-8')\r\n\r\n pb[\"value\"] = 70\r\n\r\n # reading campbell scientific loger (TOA5_50076.WolverineEx.dat)\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Reading and uploading the second campbell scientific file\")\r\n listbox1.update()\r\n WolverineFunctions.ReadCampbellScientific2(filepath, vRunID)\r\n pb[\"value\"] = 80\r\n\r\n # refreshing the tree after everything is uploaded to the database\r\n RefreshTree()\r\n\r\n # if the Generate Clipped checkbox is clipped, this will generate all of the clipped CSV files for\r\n # each of the individual plots, as well as clipped CSVs for each table\r\n if ClippedBool.get() == 1:\r\n\r\n clipped_dir = filepath + \"\\clipped\"\r\n if os.path.isdir(clipped_dir):\r\n print(\"clipped folder found at: \" + clipped_dir)\r\n else:\r\n os.makedirs(clipped_dir)\r\n print(\"clipped folder created at: \" + clipped_dir)\r\n print()\r\n\r\n # select the right shapefile def\r\n\r\n connection = WolverineFunctions.EstablishConnection()\r\n\r\n print(\"Shapefile: \" + sensorrun_df.iloc[16][1])\r\n\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Creating clipped CSVs (This takes a while)\")\r\n listbox1.update()\r\n FieldFunctions.CreateCSVs(current_shapefile, vRunID, connection, filepath)\r\n\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\r\n \"%H:%M:%S\") + \" Creating individual plot CSVs (This takes even longer)\")\r\n listbox1.update()\r\n FieldFunctions.create_clipped_plots(current_shapefile, vRunID, connection, filepath)\r\n\r\n\r\n #subtracting the start time from the current time to get total elapsed time and printing it\r\n elapsed_time = WolverineFunctions.time.time() - starttime\r\n elapsed_time = WolverineFunctions.time.strftime(\"%H:%M:%S\", WolverineFunctions.time.gmtime(elapsed_time))\r\n\r\n pb[\"value\"] = 100\r\n listbox1.insert(END, \"- \" + WolverineFunctions.time.strftime(\"%H:%M:%S\") + \" Completed :)\")\r\n listbox1.insert(END, \" \")\r\n listbox1.insert(END, \"- Time elapsed: {}\".format(elapsed_time))\r\n listbox1.update()\r\n print(\"Finished\" + elapsed_time + WolverineFunctions.time.strftime(\"%H:%M:%S\"))\r\n else:\r\n listbox1.insert(END, \"Incorrect Shapefile Provided\")\r\n print(\"Incorrect Shapefile Provided\")\r\n\r\n\r\n RefreshTree()\r\n\r\ndef GetSensorrunForTree():\r\n try:\r\n runs_df = pandas.read_sql_table(table_name=\"sensorrun\",\r\n con=WolverineFunctions.EstablishConnection(),\r\n schema=\"wolverine\",\r\n columns=['sensorrunid', 'runname', 'platform_name',\r\n 'sensorrun_datetime', 'fieldid', 'offset_modification'])\r\n except:\r\n dataset = {'sensorrunid':['Empty!'],\r\n 'runname':['error'],\r\n 'platform_name':['retrieving'],\r\n 'sensorrun_datetime':['runs'],\r\n 'fieldid':['from'],\r\n 'offset_modification':['database']}\r\n runs_df = pandas.DataFrame(data=dataset)\r\n\r\n return runs_df\r\n\r\ndef RefreshTree():\r\n #getting the sensorrun table from the database\r\n # this try except block is there just in case there are no runs in the database\r\n runs_df = GetSensorrunForTree()\r\n\r\n # setting dropdowns before they are filtered as no not get rid of all of the values\r\n # creating valuelists for each dropdownbox, then extending them with each of the unique values from the sensorrun\r\n # dataframe\r\n indexvalues = ['all']\r\n indexvalues.extend(runs_df['runname'].unique().tolist())\r\n namevalues = ['all']\r\n namevalues.extend(runs_df['platform_name'].unique().tolist())\r\n datevalues = ['all']\r\n # the .unique() function really messes up the datetime, and it is unnecessary because each time will be unique anyway\r\n datevalues.extend(runs_df['sensorrun_datetime'].tolist())\r\n fieldvalues = ['all']\r\n fieldvalues.extend(runs_df['fieldid'].unique().tolist())\r\n\r\n # setting the dropdown values to each of the valuelists\r\n dropdown1['values'] = (indexvalues)\r\n dropdown2['values'] = (namevalues)\r\n dropdown3['values'] = (datevalues)\r\n dropdown4['values'] = (fieldvalues)\r\n\r\n #checking for the content of each combobox. if it is all, we dont want to filter it, so we do nothing and move on to the next one\r\n #if it isnt all, then it must be one of the values in the dropdownbox, and the dataframe is filtered based on what was\r\n #chosen in the dropdown\r\n if dropdown1.get() == 'all':\r\n pass\r\n else:\r\n runs_df = runs_df.where(runs_df['runname'] == dropdown1.get())\r\n\r\n if dropdown2.get() == 'all':\r\n pass\r\n else:\r\n runs_df = runs_df.where(runs_df['platform_name'] == dropdown2.get())\r\n\r\n if dropdown3.get() == 'all':\r\n pass\r\n else:\r\n runs_df = runs_df.where(runs_df['sensorrun_datetime'] == dropdown3.get())\r\n\r\n if dropdown4.get() == 'all':\r\n pass\r\n else:\r\n #dropdown4.get needs to be casted to an int or else it will give an invalid type comparison error\r\n runs_df = runs_df.where(runs_df['fieldid'] == int(dropdown4.get()))\r\n\r\n #dropping lines with NAN so that they don't show up in the treeview\r\n runs_df = runs_df.dropna(how='any')\r\n\r\n #clearing the treeview before insertion of new values\r\n for i in treeview.get_children():\r\n treeview.delete(i)\r\n\r\n #iterating through the dataframe and inserting each row into the treeview\r\n #each loop through inserts one row\r\n for i in range(0, len(runs_df)):\r\n treeview.insert('', '0', str(i), text=runs_df.iloc[i]['sensorrunid'])\r\n treeview.set(str(i), 'runname', runs_df.iloc[i]['runname'])\r\n treeview.set(str(i), 'platformname', runs_df.iloc[i]['platform_name'])\r\n treeview.set(str(i), 'datetime', runs_df.iloc[i]['sensorrun_datetime'])\r\n treeview.set(str(i), 'field', runs_df.iloc[i]['fieldid'])\r\n treeview.set(str(i), 'yawmod', runs_df.iloc[i]['offset_modification'])\r\n\r\n\r\n\r\n treeview.update()\r\n\r\ndef select_item(a): # added self and a (event)\r\n try:\r\n item = treeview.selection()[0] # which row did you click on\r\n print('{}: {} selected sensorrunid: {}'.format(treeview.item(item)['values'][1],treeview.item(item)['values'][0], treeview.item(item)['text'][:])) # prints the first value of the values (the id value)\r\n currentselection['text'] = '{}: {}'.format(treeview.item(item)['values'][1],treeview.item(item)['values'][0])\r\n yawframe.pack(side=RIGHT, anchor=N)\r\n except IndexError:\r\n print(\"Not a row\")\r\n\r\ndef CheckForFiles(filepath):\r\n if os.path.isfile(filepath + '/Sensorrun.txt') == True \\\r\n and os.path.isfile(filepath + '/MAP0001.csv') == True \\\r\n and os.path.isfile(filepath + '/TOA5_11790.Wolverine.dat') == True \\\r\n and os.path.isfile(filepath + '/TOA5_50076.WolverineEx.dat'):\r\n return True\r\n else:\r\n # one of the raw files did not exist in the selected folder. The user is informed and they\r\n # must start over again by clicking on the Load Data button themselves.\r\n listbox1.delete(0, END)\r\n listbox1.insert(END, \"Selected folder does not contain necessary files.\")\r\n if os.path.isfile(filepath + '/Sensorrun.txt') == False:\r\n listbox1.insert(END, \"- Sensorrun.txt missing\")\r\n\r\n if os.path.isfile(filepath + '/MAP0001.csv') == False:\r\n listbox1.insert(END, \"- MAP0001.csv missing\")\r\n\r\n if os.path.isfile(filepath + '/TOA5_11790.Wolverine.dat') == False:\r\n listbox1.insert(END, \"- TOA5_11790.Wolverine.dat\")\r\n\r\n if os.path.isfile(filepath + '/TOA5_50076.WolverineEx.dat') == False:\r\n listbox1.insert(END, \"- TOA5_50076.WolverineEx.dat missing\")\r\n return False\r\n\r\ndef yawupdate():\r\n # this gets the filepath from the entrybox to update\r\n filepath = entrybox.get()\r\n\r\n if CheckForFiles(filepath) and CheckforDupes():\r\n item = treeview.selection()[0]\r\n sensorrun_txt = WolverineFunctions.GetSensorrun(filepath)\r\n if sensorrun_txt.columns.values[1] == treeview.item(item)['values'][0]:\r\n\r\n conn = WolverineFunctions.EstablishConnection()\r\n newyaw = yawentrybox.get()\r\n item = treeview.selection()[0]\r\n runnumber = treeview.item(item)['text'][:]\r\n print(f\"sensorrunid: {runnumber}\")\r\n\r\n thisrun = pandas.read_sql_query(f\"select * from wolverine.sensorrun where sensorrunid = {runnumber}\",\r\n con=conn)\r\n\r\n #checking if the listbox is empty\r\n if newyaw == '':\r\n listbox1.insert(END, \"\")\r\n listbox1.insert(END, \"- No input\")\r\n return\r\n else:\r\n listbox1.insert(END, \"\")\r\n\r\n # trying to convert the entry to a float. if the entry is invalid, it says so in the listbox\r\n # try:\r\n newyaw = float(newyaw)\r\n\r\n listbox1.insert(END, f\"- Updating yaw for {runnumber} by {newyaw} degrees\")\r\n listbox1.update()\r\n\r\n conn.execute(f\"DELETE FROM wolverine.sensorrun WHERE sensorrunid = {runnumber}\")\r\n\r\n # the main process run function is called again, but this time it has a yaw to add to the other ones\r\n processrun(newyaw)\r\n\r\n listbox1.insert(END, f\"- Updated yaw for Run {treeview.item(item)['values'][0]} by {newyaw} degrees\")\r\n listbox1.update()\r\n # except ValueError:\r\n # print(\"input was not a valid number\")\r\n # listbox1.insert(END, \"- input was not a valid number\")\r\n # listbox1.update()\r\n else:\r\n listbox1.insert(END, \"- files did not match the database\")\r\n\r\ndef toggleSRGenerator():\r\n if SRBool.get() == 1:\r\n listbox1.forget()\r\n scrolly.forget()\r\n GeneratorFrame.pack(side=LEFT, fill=BOTH, expand=True)\r\n SRBoolButton['bg'] = '#73d290'\r\n # listbox1['width'] = int(listbox1['width'] / 2)\r\n if os.path.isfile(entrybox.get() + \"/Sensorrun.txt\"):\r\n SRGenerator.ImportSensorrun(entrybox.get() + \"/Sensorrun.txt\")\r\n else:\r\n listbox1.pack(side=LEFT, fill=BOTH, expand=True)\r\n scrolly.pack(side=LEFT, fill=Y)\r\n GeneratorFrame.forget()\r\n SRBoolButton['bg'] = '#ada79d'\r\n # listbox1['width'] = listbox1['width'] * 2\r\n\r\ndef toggleClipped():\r\n if ClippedBool.get() == 1:\r\n ClippedBoolButton['bg'] = '#73d290'\r\n else:\r\n ClippedBoolButton['bg'] = '#ada79d'\r\n\r\ndef toggleSnapping():\r\n if ToggleSnappingBool.get() == 1:\r\n ToggleSnappingBoolButton['bg'] = '#73d290'\r\n else:\r\n ToggleSnappingBoolButton['bg'] = '#ada79d'\r\n\r\ndef Show_Sensorrunid():\r\n treeview['show'] = 'tree'\r\n\r\ndef Show_Headings():\r\n treeview['show'] = 'headings'\r\n\r\n# def ToggleOptions():\r\n# if optionsbool.get() == 0:\r\n# optionsbool.set(1)\r\n# optionsframe.forget()\r\n# elif optionsbool.get() == 1:\r\n# optionsbool.set(0)\r\n# optionsframe.pack(side=LEFT, fill=Y)\r\n\r\ndef bigfont():\r\n if default_font['size'] != 13:\r\n default_font.configure(size=13)\r\n else:\r\n default_font.configure(size=9)\r\n\r\ndef DarkTheme():\r\n root.style = ttk.Style()\r\n\r\n listbox1['background'] = \"#23272A\"\r\n listbox1['foreground'] = \"white\"\r\n treeandscrollbarframe['background'] = \"#66615a\"\r\n yawframe['background'] = \"#66615a\"\r\n yawlabel['background'] = \"#66615a\"\r\n yawlabel['foreground'] = \"white\"\r\n currentselection['background'] = \"#66615a\"\r\n currentselection['foreground'] = \"white\"\r\n bottomframe['background'] = '#66615a'\r\n optionsframe['bg'] = '#66615a'\r\n topframe['background'] = '#7a756e'\r\n\r\n SRGenerator.row_version.the_label['background'] = \"#23272A\"\r\n SRGenerator.row_version.the_label['foreground'] = \"white\"\r\n SRGenerator.row_version.row['background'] = \"#23272A\"\r\n SRGenerator.run_name.the_label['background'] = \"#23272A\"\r\n SRGenerator.run_name.the_label['foreground'] = \"white\"\r\n SRGenerator.run_name.row['background'] = \"#23272A\"\r\n SRGenerator.shape_file.the_label['background'] = \"#23272A\"\r\n SRGenerator.shape_file.the_label['foreground'] = \"white\"\r\n SRGenerator.shape_file.row['background'] = \"#23272A\"\r\n SRGenerator.unexpected_condition.the_label['background'] = \"#23272A\"\r\n SRGenerator.unexpected_condition.the_label['foreground'] = \"white\"\r\n SRGenerator.unexpected_condition.row['background'] = \"#23272A\"\r\n SRGenerator.sensor_condition.the_label['background'] = \"#23272A\"\r\n SRGenerator.sensor_condition.the_label['foreground'] = \"white\"\r\n SRGenerator.sensor_condition.row['background'] = \"#23272A\"\r\n SRGenerator.platform_condition.the_label['background'] = \"#23272A\"\r\n SRGenerator.platform_condition.the_label['foreground'] = \"white\"\r\n SRGenerator.platform_condition.row['background'] = \"#23272A\"\r\n SRGenerator.field_condition.the_label['background'] = \"#23272A\"\r\n SRGenerator.field_condition.the_label['foreground'] = \"white\"\r\n SRGenerator.field_condition.row['background'] = \"#23272A\"\r\n SRGenerator.weather_condition.the_label['background'] = \"#23272A\"\r\n SRGenerator.weather_condition.the_label['foreground'] = \"white\"\r\n SRGenerator.weather_condition.row['background'] = \"#23272A\"\r\n SRGenerator.field_direction.the_label['background'] = \"#23272A\"\r\n SRGenerator.field_direction.the_label['foreground'] = \"white\"\r\n SRGenerator.field_direction.row['background'] = \"#23272A\"\r\n SRGenerator.vehicle_id.the_label['background'] = \"#23272A\"\r\n SRGenerator.vehicle_id.the_label['foreground'] = \"white\"\r\n SRGenerator.vehicle_id.row['background'] = \"#23272A\"\r\n SRGenerator.operator_id.the_label['background'] = \"#23272A\"\r\n SRGenerator.operator_id.the_label['foreground'] = \"white\"\r\n SRGenerator.operator_id.row['background'] = \"#23272A\"\r\n SRGenerator.platform_name.the_label['background'] = \"#23272A\"\r\n SRGenerator.platform_name.the_label['foreground'] = \"white\"\r\n SRGenerator.platform_name.row['background'] = \"#23272A\"\r\n SRGenerator.field_crop_treatment_id.the_label['background'] = \"#23272A\"\r\n SRGenerator.field_crop_treatment_id.the_label['foreground'] = \"white\"\r\n SRGenerator.field_crop_treatment_id.row['background'] = \"#23272A\"\r\n SRGenerator.imu_value.the_label['background'] = \"#23272A\"\r\n SRGenerator.imu_value.the_label['foreground'] = \"white\"\r\n SRGenerator.imu_value.row['background'] = \"#23272A\"\r\n SRGenerator.cc_to_bed_height.the_label['background'] = \"#23272A\"\r\n SRGenerator.cc_to_bed_height.the_label['foreground'] = \"white\"\r\n SRGenerator.cc_to_bed_height.row['background'] = \"#23272A\"\r\n SRGenerator.date_time.the_label['background'] = \"#23272A\"\r\n SRGenerator.date_time.the_label['foreground'] = \"white\"\r\n SRGenerator.date_time.row['background'] = \"#23272A\"\r\n SRGenerator.field_number.the_label['background'] = \"#23272A\"\r\n SRGenerator.field_number.the_label['foreground'] = \"white\"\r\n SRGenerator.field_number.row['background'] = \"#23272A\"\r\n SRGenerator.crop_id.the_label['background'] = \"#23272A\"\r\n SRGenerator.crop_id.the_label['foreground'] = \"white\"\r\n\r\n SRGenerator.row_version.the_input['background'] = '#575c63'\r\n SRGenerator.row_version.the_input['foreground'] = \"white\"\r\n SRGenerator.run_name.the_input['background'] = '#575c63'\r\n SRGenerator.run_name.the_input['foreground'] = \"white\"\r\n SRGenerator.unexpected_condition.the_input['background'] = '#575c63'\r\n SRGenerator.unexpected_condition.the_input['foreground'] = \"white\"\r\n SRGenerator.sensor_condition.the_input['background'] = '#575c63'\r\n SRGenerator.sensor_condition.the_input['foreground'] = \"white\"\r\n SRGenerator.platform_condition.the_input['background'] = '#575c63'\r\n SRGenerator.platform_condition.the_input['foreground'] = \"white\"\r\n SRGenerator.field_condition.the_input['background'] = '#575c63'\r\n SRGenerator.field_condition.the_input['foreground'] = \"white\"\r\n SRGenerator.weather_condition.the_input['background'] = '#575c63'\r\n SRGenerator.weather_condition.the_input['foreground'] = \"white\"\r\n SRGenerator.field_direction.the_input['background'] = '#575c63'\r\n SRGenerator.field_direction.the_input['foreground'] = \"white\"\r\n SRGenerator.vehicle_id.the_input['background'] = '#575c63'\r\n SRGenerator.vehicle_id.the_input['foreground'] = \"white\"\r\n SRGenerator.operator_id.the_input['background'] = '#575c63'\r\n SRGenerator.operator_id.the_input['foreground'] = \"white\"\r\n SRGenerator.platform_name.the_input['background'] = '#575c63'\r\n SRGenerator.platform_name.the_input['foreground'] = \"white\"\r\n SRGenerator.field_crop_treatment_id.the_input['background'] = '#575c63'\r\n SRGenerator.field_crop_treatment_id.the_input['foreground'] = \"white\"\r\n SRGenerator.imu_value.the_input['background'] = '#575c63'\r\n SRGenerator.imu_value.the_input['foreground'] = \"white\"\r\n SRGenerator.cc_to_bed_height.the_input['background'] = '#575c63'\r\n SRGenerator.cc_to_bed_height.the_input['foreground'] = \"white\"\r\n SRGenerator.date_time.the_input['background'] = '#575c63'\r\n SRGenerator.date_time.the_input['foreground'] = \"white\"\r\n SRGenerator.field_number.the_input['background'] = '#575c63'\r\n SRGenerator.field_number.the_input['foreground'] = \"white\"\r\n SRGenerator.crop_id.the_input['background'] = '#575c63'\r\n SRGenerator.crop_id.the_input['foreground'] = \"white\"\r\n SRGenerator.crop_id.row['background'] = \"#23272A\"\r\n SRGenerator.mainframe['background'] = \"#23272A\"\r\n GeneratorFrame['background'] = \"#23272A\"\r\n\r\n root.style.theme_use(\"clam\")\r\n root.style.configure('TButton', background='SystemButtonFace')\r\n\r\n root.style.configure(\"Treeview\", background=\"#23272A\", fieldbackground=\"#23272A\", foreground=\"white\")\r\n\r\ndef LightTheme():\r\n root.style = ttk.Style()\r\n\r\n listbox1['background'] = \"white\"\r\n listbox1['foreground'] = \"black\"\r\n treeandscrollbarframe['background'] = \"SystemButtonFace\"\r\n yawframe['background'] = \"SystemButtonFace\"\r\n yawlabel['background'] = \"SystemButtonFace\"\r\n yawlabel['foreground'] = \"black\"\r\n currentselection['background'] = \"SystemButtonFace\"\r\n currentselection['foreground'] = \"black\"\r\n bottomframe['background'] = '#999389'\r\n optionsframe['bg'] = '#999389'\r\n topframe['background'] = '#bfbbb5'\r\n\r\n\r\n SRGenerator.row_version.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.row_version.the_label['foreground'] = \"black\"\r\n SRGenerator.row_version.the_input['background'] = \"white\"\r\n SRGenerator.row_version.the_input['foreground'] = \"black\"\r\n SRGenerator.row_version.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.run_name.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.run_name.the_label['foreground'] = \"black\"\r\n SRGenerator.run_name.the_input['background'] = \"white\"\r\n SRGenerator.run_name.the_input['foreground'] = \"black\"\r\n SRGenerator.run_name.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.shape_file.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.shape_file.the_label['foreground'] = \"black\"\r\n SRGenerator.shape_file.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.unexpected_condition.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.unexpected_condition.the_label['foreground'] = \"black\"\r\n SRGenerator.unexpected_condition.the_input['background'] = \"white\"\r\n SRGenerator.unexpected_condition.the_input['foreground'] = \"black\"\r\n SRGenerator.unexpected_condition.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.sensor_condition.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.sensor_condition.the_label['foreground'] = \"black\"\r\n SRGenerator.sensor_condition.the_input['background'] = \"white\"\r\n SRGenerator.sensor_condition.the_input['foreground'] = \"black\"\r\n SRGenerator.sensor_condition.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.platform_condition.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.platform_condition.the_label['foreground'] = \"black\"\r\n SRGenerator.platform_condition.the_input['background'] = \"white\"\r\n SRGenerator.platform_condition.the_input['foreground'] = \"black\"\r\n SRGenerator.platform_condition.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_condition.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_condition.the_label['foreground'] = \"black\"\r\n SRGenerator.field_condition.the_input['background'] = \"white\"\r\n SRGenerator.field_condition.the_input['foreground'] = \"black\"\r\n SRGenerator.field_condition.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.weather_condition.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.weather_condition.the_label['foreground'] = \"black\"\r\n SRGenerator.weather_condition.the_input['background'] = \"white\"\r\n SRGenerator.weather_condition.the_input['foreground'] = \"black\"\r\n SRGenerator.weather_condition.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_direction.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_direction.the_label['foreground'] = \"black\"\r\n SRGenerator.field_direction.the_input['background'] = \"white\"\r\n SRGenerator.field_direction.the_input['foreground'] = \"black\"\r\n SRGenerator.field_direction.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.vehicle_id.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.vehicle_id.the_label['foreground'] = \"black\"\r\n SRGenerator.vehicle_id.the_input['background'] = \"white\"\r\n SRGenerator.vehicle_id.the_input['foreground'] = \"black\"\r\n SRGenerator.vehicle_id.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.operator_id.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.operator_id.the_label['foreground'] = \"black\"\r\n SRGenerator.operator_id.the_input['background'] = \"white\"\r\n SRGenerator.operator_id.the_input['foreground'] = \"black\"\r\n SRGenerator.operator_id.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.platform_name.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.platform_name.the_label['foreground'] = \"black\"\r\n SRGenerator.platform_name.the_input['background'] = \"white\"\r\n SRGenerator.platform_name.the_input['foreground'] = \"black\"\r\n SRGenerator.platform_name.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_crop_treatment_id.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_crop_treatment_id.the_label['foreground'] = \"black\"\r\n SRGenerator.field_crop_treatment_id.the_input['background'] = \"white\"\r\n SRGenerator.field_crop_treatment_id.the_input['foreground'] = \"black\"\r\n SRGenerator.field_crop_treatment_id.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.imu_value.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.imu_value.the_label['foreground'] = \"black\"\r\n SRGenerator.imu_value.the_input['background'] = \"white\"\r\n SRGenerator.imu_value.the_input['foreground'] = \"black\"\r\n SRGenerator.imu_value.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.cc_to_bed_height.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.cc_to_bed_height.the_label['foreground'] = \"black\"\r\n SRGenerator.cc_to_bed_height.the_input['background'] = \"white\"\r\n SRGenerator.cc_to_bed_height.the_input['foreground'] = \"black\"\r\n SRGenerator.cc_to_bed_height.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.date_time.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.date_time.the_label['foreground'] = \"black\"\r\n SRGenerator.date_time.the_input['background'] = \"white\"\r\n SRGenerator.date_time.the_input['foreground'] = \"black\"\r\n SRGenerator.date_time.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_number.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.field_number.the_label['foreground'] = \"black\"\r\n SRGenerator.field_number.the_input['background'] = \"white\"\r\n SRGenerator.field_number.the_input['foreground'] = \"black\"\r\n SRGenerator.field_number.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.crop_id.the_label['background'] = \"SystemButtonFace\"\r\n SRGenerator.crop_id.the_label['foreground'] = \"black\"\r\n SRGenerator.crop_id.the_input['background'] = \"white\"\r\n SRGenerator.crop_id.the_input['foreground'] = \"black\"\r\n SRGenerator.crop_id.row['background'] = \"SystemButtonFace\"\r\n SRGenerator.mainframe['background'] = \"SystemButtonFace\"\r\n GeneratorFrame['background'] = \"SystemButtonFace\"\r\n\r\n root.style.theme_use(\"vista\")\r\n root.style.configure('TButton', background='#999389')\r\n root.style.configure(\"Treeview\", background=\"white\", fieldbackground=\"white\", foreground=\"black\")\r\n\r\nif __name__ == \"__main__\":\r\n multiprocessing.freeze_support()\r\n runs_df = GetSensorrunForTree()\r\n\r\n root = Tk()\r\n root.title('HTP Cart Application: Wolverine 2018')\r\n try:\r\n icon = PhotoImage(file='wolverineicon.png')\r\n root.tk.call('wm', 'iconphoto', root._w, icon)\r\n except:\r\n pass\r\n root.configure(background='#bfbbb5')\r\n\r\n toptopframe = Frame(root)\r\n toptopframe.configure(background='#bfbbb5')\r\n toptopframe.pack(side=TOP, fill=BOTH, expand=True)\r\n\r\n topframe = Frame(toptopframe)\r\n topframe.configure(background='#bfbbb5')\r\n topframe.pack(side=RIGHT, fill=BOTH, expand=True)\r\n\r\n # LISTBOX AND SCROLLBAR\r\n listboxandscrollbarframe = Frame(topframe)\r\n listboxandscrollbarframe.configure(background='#bfbbb5')\r\n listbox1 = Listbox(listboxandscrollbarframe, width=80)\r\n listbox1.pack(side=LEFT, fill=BOTH, expand=True)\r\n\r\n listbox1.insert(END, \" Welcome to the Wolverine Cart application!\")\r\n listbox1.insert(END, \"\")\r\n listbox1.insert(END, \" You can view and edit previous runs on the right and you can upload runs into the\")\r\n listbox1.insert(END, \" database using the selection below\")\r\n listbox1.insert(END, \"\")\r\n listbox1.insert(END, \" If you don't have a Sensorrun.txt already created, you can check the box on the \")\r\n listbox1.insert(END, \" left side of the screen to fill one out\")\r\n\r\n scrolly = Scrollbar(listboxandscrollbarframe, orient=VERTICAL)\r\n listbox1['yscrollcommand'] = scrolly.set\r\n scrolly['command'] = listbox1.yview\r\n scrolly.pack(side=LEFT, fill=Y)\r\n listboxandscrollbarframe.pack(expand=True, side=LEFT,padx=10,pady=10,fill=BOTH)\r\n\r\n # TREEVIEW\r\n treeandscrollbarframe = Frame(topframe)\r\n treeandfilterframe = Frame(treeandscrollbarframe)\r\n treeview = ttk.Treeview(treeandfilterframe, height=23)\r\n columns = ('runname', 'platformname', 'datetime', 'field', 'yawmod')\r\n treeview.config(columns = columns)\r\n treeview.heading('runname', text='Run Name')\r\n treeview.heading('platformname', text='Platform Name')\r\n treeview.heading('datetime', text='Date and Time of run')\r\n treeview.heading('field', text='Field Number')\r\n treeview.heading('yawmod', text='Offset Modification')\r\n treeview.column('#0', width=50, anchor='center')\r\n treeview.column('runname', width=150 ,anchor='center')\r\n treeview.column('platformname', width=100, anchor='center')\r\n treeview.column('datetime', anchor='center')\r\n treeview.column('field', width=100, anchor='center')\r\n treeview.column('yawmod', width=115,anchor='center')\r\n treeview.bind('', select_item)\r\n treeview['show'] = 'headings' #gets rid of the empty first column\r\n\r\n scrolly2 = Scrollbar(treeandscrollbarframe, orient=VERTICAL, command=treeview.yview)\r\n treeview['yscrollcommand'] = scrolly2.set\r\n scrolly2.pack(side=RIGHT, fill=Y)\r\n\r\n dropdownframe = Frame(treeandfilterframe)\r\n # dropdownframe.pack(side=TOP, anchor=W)\r\n\r\n # creating each of the dropdowns so that they are all only able to be read in the dropdownframe\r\n dropdown1 = ttk.Combobox(dropdownframe, state='readonly')\r\n dropdown2 = ttk.Combobox(dropdownframe, state='readonly')\r\n dropdown3 = ttk.Combobox(dropdownframe, state='readonly')\r\n dropdown4 = ttk.Combobox(dropdownframe, state='readonly')\r\n\r\n #setting the default values of the dropdownbox to 'all'\r\n dropdown1.set('all')\r\n dropdown2.set('all')\r\n dropdown3.set('all')\r\n dropdown4.set('all')\r\n\r\n # creating valuelists for each dropdownbox, then extending them with each of the unique values from the sensorrun\r\n # dataframe\r\n indexvalues = ['all']\r\n indexvalues.extend(runs_df['runname'].unique().tolist())\r\n namevalues = ['all']\r\n namevalues.extend(runs_df['platform_name'].unique().tolist())\r\n datevalues = ['all']\r\n datevalues.extend(runs_df['sensorrun_datetime'].tolist())\r\n fieldvalues = ['all']\r\n fieldvalues.extend(runs_df['fieldid'].unique().tolist())\r\n\r\n # setting the dropdown values to each of the valuelists\r\n dropdown1['values'] = (indexvalues)\r\n dropdown2['values'] = (namevalues)\r\n dropdown3['values'] = (datevalues)\r\n dropdown4['values'] = (fieldvalues)\r\n\r\n dropdown1.pack(side=LEFT)\r\n dropdown2.pack(side=LEFT)\r\n dropdown3.pack(side=LEFT)\r\n dropdown4.pack(side=LEFT)\r\n\r\n treeview.pack(side=LEFT, fill=BOTH, expand=True)\r\n treeandfilterframe.pack(side=LEFT, fill=BOTH, expand=True)\r\n treeandscrollbarframe.pack(side=RIGHT,padx=10,pady=10,fill=BOTH, expand=True)\r\n RefreshTree()\r\n\r\n # YAW EDITOR POPOUT\r\n yawframe = Frame(treeandscrollbarframe)\r\n yawlabel = Label(yawframe, text='Edit Yaw')\r\n currentselection = Label(yawframe, text='none') #this is 'none' because as soon as you click on something in the treeview, it gets updated\r\n yawentrybox = ttk.Entry(yawframe)\r\n\r\n yaweditbutton = ttk.Button(yawframe, text=\"Update Yaw\", command=yawupdate)\r\n yawbackbutton = ttk.Button(yawframe, text='Back', command=lambda: yawframe.forget())\r\n\r\n yawlabel.pack()\r\n currentselection.pack(padx=3)\r\n yawentrybox.pack(padx=5, pady=5)\r\n yaweditbutton.pack()\r\n yawbackbutton.pack()\r\n\r\n # ENTRY BOX AND BUTTONS\r\n bottomframe = Frame(root)\r\n bottomframe.configure(background='#999389')\r\n bottomframe.pack(fill=BOTH, side=BOTTOM)\r\n\r\n pb = ttk.Progressbar(bottomframe, orient=HORIZONTAL, length=200, mode='determinate')\r\n pb[\"maximum\"] = 100\r\n pb.pack(side=LEFT, padx=5,pady=5)\r\n\r\n getfilepathbutton = ttk.Button(bottomframe, text=\"Select Run\", command=AskForFilepath)\r\n getfilepathbutton.pack(side=LEFT, anchor=E, padx=5,pady=5)\r\n\r\n entrybox = ttk.Entry(bottomframe, width=70)\r\n entrybox.pack(side=LEFT, padx=5,pady=5)\r\n\r\n GeneratorFrame = Frame(listboxandscrollbarframe)\r\n SRGenerator = SensorrunGenerator.SensorInputWindow(GeneratorFrame)\r\n\r\n refreshtree = ttk.Button(bottomframe, text=\"Refresh Tree\", command=RefreshTree)\r\n refreshtree.pack(side=RIGHT, padx=5,pady=5)\r\n\r\n processbutton = ttk.Button(bottomframe, text=\"Process Run\", command=ProcessRunParent)\r\n processbutton.pack(side=LEFT, padx=5,pady=5)\r\n\r\n optionsframe = Frame(toptopframe)\r\n optionsframe['bg'] = '#999389'\r\n optionsframe.pack(side=LEFT, fill=Y)\r\n\r\n SRBool = IntVar()\r\n SRBoolButton = Checkbutton(optionsframe, text=\"Generate Sensorrun\", variable=SRBool, command=toggleSRGenerator,\r\n bg='#ada79d')\r\n SRBoolButton.pack(anchor=W, padx=5, pady=5)\r\n\r\n ClippedBool = IntVar()\r\n ClippedBoolButton = Checkbutton(optionsframe, text=\"Generate Clipped\", variable=ClippedBool, command=toggleClipped,\r\n bg='#ada79d')\r\n ClippedBoolButton.pack(anchor=W, padx=5, pady=5)\r\n\r\n ToggleSnappingBool = IntVar()\r\n ToggleSnappingBoolButton = Checkbutton(optionsframe, text=\"Snap Yaw\", variable=ToggleSnappingBool,\r\n command=toggleSnapping, bg='#ada79d')\r\n ToggleSnappingBoolButton.pack(anchor=W, padx=5, pady=5)\r\n\r\n CheckForFilepath()\r\n\r\n\r\n # MENU SYSTEM\r\n menu = Menu(root)\r\n root.config(menu=menu)\r\n\r\n # optionsmenu = Menu(menu, tearoff=False)\r\n # menu.add_cascade(label='Options', menu=optionsmenu)\r\n # optionsbool = IntVar()\r\n # optionsbool.set(1)\r\n # optionsmenu.add_command(label='Show Run Options', command=ToggleOptions)\r\n\r\n viewmenu = Menu(menu, tearoff=False)\r\n menu.add_cascade(label='View', menu=viewmenu)\r\n viewmenu.add_command(label='Light Theme', command=LightTheme)\r\n viewmenu.add_command(label='Dark Theme', command=DarkTheme)\r\n viewmenu.add_command(label='Yaw Modification', command=lambda: yawframe.pack(side=RIGHT, anchor=N))\r\n viewmenu.add_command(label='Show Sensorrunid', command=Show_Sensorrunid)\r\n viewmenu.add_command(label='Show Headers', command=Show_Headings)\r\n viewmenu.add_command(label=\"BIG FONT\", command=bigfont)\r\n\r\n default_font = font.nametofont(\"TkDefaultFont\")\r\n default_font.configure(size=9)\r\n\r\n # bigfont()\r\n # DarkTheme()\r\n LightTheme()\r\n\r\n root.mainloop()\r\n","sub_path":"Wolverine.py","file_name":"Wolverine.py","file_ext":"py","file_size_in_byte":41322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369322695","text":"# hello.py\n# says 'Hello, git!'\n# also does fizzBuzz\n# someting ;\n\ndef fizzBuzzIterative(start, end):\n for i in range(start, end):\n fizzBuzzPrint(i)\n\ndef fizzBuzzPrint(n):\n mod3 = not n % 3\n mod5 = not n % 5\n if (not mod3 and not mod5):\n print(n)\n elif (mod3 and mod5):\n print(\"Fizz Buzz\")\n elif (mod3):\n print(\"Fizz \")\n elif (mod5):\n print(\"Buzz \")\n\nprint(\"'Hello, git!'\")\n\nn = int(input(\"FizzBuzz final number? \"))\n\nfizzBuzzIterative(1, n + 1)\n\nprint(\"FizzBuzz Completed\")\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"523405585","text":"# -*- coding: utf-8 -*-\n\"\"\"Nexus 3 CLI\n\nUsage:\n nexus3 --help, -h\n nexus3 login\n nexus3 (list|ls) \n nexus3 (upload|up) \n nexus3 repo create hosted maven \n [--blob=] [--version=]\n [--layout=] [--strict-content]\n [--write=]\n nexus3 repo create hosted (npm|pypi|raw|rubygems) \n [--blob=] [--write=] [--strict-content]\n nexus3 repo create hosted yum \n [--blob=] [--write=]\n [--depth=] [--strict-content]\n nexus3 repo create proxy maven \n [--blob=] [--version=]\n [--layout=] [--strict-content]\n nexus3 repo create proxy (npm|pypi|raw|rubygems|yum)\n \n [--blob=] [--strict-content]\n nexus3 repo list\n nexus3 repo rm \n nexus3 script create \n nexus3 script list\n nexus3 script (rm|run) \n\nOptions:\n -h --help This screen\n --blob= Use this blob with new repository [default: default]\n --depth= Depth (0-5) where repodata folder(s) exist [default: 0]\n --write= Accepted: allow, allow_once, deny [default: allow_once]\n --layout= Accepted: strict, permissive [default: strict]\n --version= Accepted: release, snapshot, mixed [default: release]\n --strict-content Enable strict content type validation\n\nCommands:\n login Test login and save credentials to ~/.nexus-cli\n list List all files within a path in the repository\n repo create Create a repository using the format and options provided\n repo list List all repositories available on the server\n repo rm Not implemented; please use Nexus Web UI to remove \n script create Create or update a script using the file\n script list List all scripts available on the server\n script rm Remove existing \n script run Run the existing \n\"\"\"\nimport getpass\nimport inflect\nimport json\nimport sys\nimport types\n\nfrom builtins import str # unfuck Python 2's unicode\nfrom docopt import docopt\n\nfrom nexuscli import nexus_repository\nfrom nexuscli.exception import NexusClientConfigurationNotFound\nfrom nexuscli.nexus_client import NexusClient\nfrom nexuscli.nexus_script import script_method_object\n\nPLURAL = inflect.engine().plural\n\n\ndef _input(prompt, default=None):\n \"\"\"\n :return: raw_input for Python 2.x and input for Python 3.x\n :rtype: function\n \"\"\"\n if sys.version_info < (3, 0):\n real_input = raw_input # noqa - Python2\n else:\n real_input = input\n\n value = real_input('{prompt} ({default}):'.format(**locals()))\n if value:\n return value\n\n return default\n\n\ndef do_login():\n nexus_url = _input('Nexus OSS URL', NexusClient.DEFAULT_URL)\n nexus_user = _input('Nexus admin username', NexusClient.DEFAULT_USER)\n nexus_pass = getpass.getpass(\n prompt='Nexus admin password ({}):'.format(\n NexusClient.DEFAULT_PASS))\n if not nexus_pass:\n nexus_pass = NexusClient.DEFAULT_PASS\n\n client = NexusClient(url=nexus_url, user=nexus_user, password=nexus_pass)\n client.write_config()\n\n sys.stderr.write('\\nConfiguration saved to {}\\n'.format(\n NexusClient.CONFIG_PATH))\n\n\ndef get_client():\n client = NexusClient()\n try:\n client.read_config()\n return client\n except NexusClientConfigurationNotFound:\n sys.stderr.write(\n 'Configuration not found; please run nexus-cli.py login\\n')\n sys.exit(1)\n\n\ndef cmd_script_do_list(nexus_client):\n json_response = nexus_client.script_list()\n\n sys.stderr.write('Name (type)\\n')\n for script in json_response:\n sys.stdout.write('{script[name]} ({script[type]})\\n'.format(\n script=script))\n\n\ndef cmd_script_do_create(nexus_client, script_path):\n script_content = json.load(open(script_path), strict=False)\n nexus_client.script_create(script_content)\n\n\ndef cmd_script(args):\n nexus_client = get_client()\n\n if args.get('list'):\n cmd_script_do_list(nexus_client)\n elif args.get('rm'):\n nexus_client.script_delete(args.get(''))\n elif args.get('run'):\n nexus_client.script_run(args.get(''))\n elif args.get('create'):\n cmd_script_do_create(nexus_client, args.get(''))\n else:\n raise NotImplementedError\n\n\ndef cmd_repo_do_list(nexus_client):\n json_response = nexus_client.repo_list()\n\n output_format = '{0:40} {1:7} {2:7} {3}\\n'\n sys.stderr.write(output_format.format('Name', 'Format', 'Type', 'URL'))\n sys.stderr.write(output_format.format('----', '------', '----', '---'))\n for repo in json_response:\n sys.stdout.write(output_format.format(\n repo['name'], repo['format'], repo['type'], repo['url']))\n\n\ndef nexus_policy(policy_name, user_option):\n if user_option == '__imports':\n return nexus_repository.POLICY_IMPORTS[policy_name]\n\n policy = nexus_repository.POLICIES[policy_name].get(user_option)\n if policy is None:\n raise AttributeError('Valid options for --{} are: {}'.format(\n policy_name, list(nexus_repository.POLICIES[policy_name])))\n return policy\n\n\ndef args_to_repo_params_hosted_maven(args):\n # Repository createMavenHosted(final String name,\n # final String blobStoreName,\n # final boolean strictContentTypeValidation,\n # final VersionPolicy versionPolicy,\n # final WritePolicy writePolicy,\n # final LayoutPolicy layoutPolicy);\n repo_params = args_to_repo_params_hosted(args)\n repo_params.update({\n 'versionPolicy': nexus_policy('version', args['--version']),\n 'layoutPolicy': nexus_policy('layout', args['--layout']),\n '__imports': [\n item for policy_name in ['version', 'write', 'layout']\n for item in nexus_policy(policy_name, '__imports')],\n })\n\n return repo_params\n\n\ndef args_to_repo_params_proxy_maven(args):\n # createMavenProxy(\n # String name,\n # String remoteUrl,\n # String blobStoreName,\n # boolean strictContentTypeValidation,\n # org.sonatype.nexus.repository.maven.VersionPolicy versionPolicy,\n # org.sonatype.nexus.repository.maven.LayoutPolicy layoutPolicy)\n\n # the unused 'write' import doesn't hurt and the extra writePolicy param\n # will be ignored as the format string for the statement doesn't use it\n repo_params = args_to_repo_params_hosted_maven(args)\n repo_params.update(args_to_repo_params_proxy(args))\n\n return repo_params\n\n\ndef args_to_repo_params_hosted_yum(args):\n # createYumHosted(\n # String name,\n # String blobStoreName,\n # boolean strictContentTypeValidation,\n # org.sonatype.nexus.repository.storage.WritePolicy writePolicy,\n # int depth)\n repo_params = args_to_repo_params_hosted(args)\n repo_params.update({'depth': args['--depth']})\n\n return repo_params\n\n\ndef args_to_repo_params_proxy_yum(args):\n # createYumProxy(\n # String name,\n # String remoteUrl,\n # String blobStoreName,\n # boolean strictContentTypeValidation)\n return args_to_repo_params_proxy(args)\n\n\ndef args_to_repo_params(args):\n # Parameters common to createFormatHosted and createFormatProxy\n # create(Npm|PyPi|Raw|Rubygems)Hosted(\n # String name,\n # String blobStoreName,\n # boolean strictContentTypeValidation,\n # org.sonatype.nexus.repository.storage.WritePolicy writePolicy)\n repo_params = {\n 'name': args[''],\n 'blobStoreName': args['--blob'],\n 'strictContentTypeValidation': str(args['--strict-content']).lower(),\n }\n\n return repo_params\n\n\ndef args_to_repo_params_hosted(args):\n # create(Npm|PyPi|Raw|Rubygems)Hosted(\n # String name,\n # String blobStoreName,\n # boolean strictContentTypeValidation,\n # org.sonatype.nexus.repository.storage.WritePolicy writePolicy)\n method_name = 'repository.create{}Hosted'.format(args_to_repo_format(args))\n repo_params = args_to_repo_params(args)\n repo_params.update({\n 'writePolicy': nexus_policy('write', args['--write']),\n '__method': method_name,\n '__imports': nexus_policy('write', '__imports'),\n })\n\n return repo_params\n\n\ndef args_to_repo_params_proxy(args):\n # create(Npm|PyPi|Raw|Rubygems)Proxy(\n # String name,\n # String remoteUrl,\n # String blobStoreName,\n # boolean strictContentTypeValidation)\n method_name = 'repository.create{}Proxy'.format(args_to_repo_format(args))\n repo_params = args_to_repo_params(args)\n repo_params.update({\n 'remoteUrl': args[''],\n '__method': method_name,\n })\n\n return repo_params\n\n\ndef cmd_repo_do_create(\n nexus_client, repo_params, repo_type='hosted', repo_format=None):\n script_method = script_method_object(repo_type, repo_format)\n script_content, script_name = script_method(repo_params)\n\n nexus_client.script_create(script_content)\n nexus_client.script_run(script_name)\n nexus_client.script_delete(script_name)\n sys.stderr.write('Created repository: {}\\n'.format(repo_params['name']))\n\n\ndef args_to_repo_format(args):\n accepted_formats = ['maven', 'npm', 'pypi', 'raw', 'rubygems', 'yum']\n # docopt guarantees only one is True\n for format_name in accepted_formats:\n if args.get(format_name) is True:\n if format_name == 'pypi':\n return 'PyPi' # bloody bastards 🤬\n return format_name.title()\n # Just in case:\n raise AttributeError(\n 'User arguments did not match a recognised format: {}'.format(\n accepted_formats))\n\n\ndef args_to_repo_type(args):\n accepted_types = ['hosted', 'proxy']\n # docopt guarantees only one is True\n for type_name in accepted_types:\n if args.get(type_name) is True:\n return type_name\n # Just in case:\n raise AttributeError(\n 'User arguments did not match a recognised type: {}'.format(\n accepted_types))\n\n\ndef cmd_repo_create(nexus_client, args):\n repo_type = args_to_repo_type(args)\n repo_format = args_to_repo_format(args).lower()\n\n # these special snowflakes have their own groovy method signatures\n snowflake_repo_formats = ['maven', 'yum']\n if repo_format in snowflake_repo_formats:\n # ie: args_to_repo_params_maven, args_to_repo_params_yum\n method_name = 'args_to_repo_params_{repo_type}_{repo_format}'.format(\n **locals())\n args_to_repo_params_method = globals()[method_name]\n else:\n method_name = 'args_to_repo_params_{repo_type}'.format(**locals())\n args_to_repo_params_method = globals()[method_name]\n repo_format = None\n\n repo_params = args_to_repo_params_method(args)\n cmd_repo_do_create(nexus_client, repo_params,\n repo_type=repo_type, repo_format=repo_format)\n\n\ndef cmd_repo(args):\n nexus_client = get_client()\n\n if args.get('list'):\n cmd_repo_do_list(nexus_client)\n elif args.get('create'):\n cmd_repo_create(nexus_client, args)\n else:\n raise NotImplementedError\n\n\ndef cmd_list(args):\n \"\"\"\n Performs the `rekt ar search` command using the configured artefact\n repository service.\n \"\"\"\n nexus_client = get_client()\n repository_path = args['']\n artefact_list = nexus_client.list(repository_path)\n\n # FIXME: is types.GeneratorType still used?\n if isinstance(artefact_list, (list, types.GeneratorType)):\n for artefact in iter(artefact_list):\n sys.stdout.write('{}\\n'.format(artefact))\n return 0\n else:\n return 1\n\n\ndef _cmd_up_down_errors(count, action):\n \"\"\"Print and exit with error if upload/download didn't succeed\"\"\"\n if count == 0:\n # FIXME: inflex the action verb to past participle\n sys.stderr.write('WARNING: no files were {}\\'ed.'.format(action))\n sys.exit(1)\n\n if count == -1:\n sys.stderr.write('ERROR during {} operation.'.format(action))\n sys.exit(2)\n\n\ndef cmd_upload(args):\n \"\"\"\n Performs the `rekt ar upload` command using the configured artefact\n repository service.\n \"\"\"\n nexus_client = get_client()\n source = args['']\n destination = args['']\n\n sys.stderr.write(\n 'Uploading {source} to {destination}\\n'.format(**locals()))\n\n upload_count = nexus_client.upload(source, destination)\n\n _cmd_up_down_errors(upload_count, 'upload')\n\n file = PLURAL('file', upload_count)\n sys.stderr.write(\n 'Uploaded {upload_count} {file} to {destination}\\n'.format(**locals()))\n return 0\n\n\ndef main(argv=None):\n arguments = docopt(__doc__, argv=argv)\n if arguments.get('login'):\n do_login()\n NexusClient()\n elif arguments.get('script'):\n cmd_script(arguments)\n elif arguments.get('repo'):\n cmd_repo(arguments)\n elif arguments.get('list') or arguments.get('ls'):\n cmd_list(arguments)\n elif arguments.get('upload') or arguments.get('up'):\n cmd_upload(arguments)\n else:\n raise NotImplementedError\n","sub_path":"src/nexuscli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"556386307","text":"# 91. Minimum Adjustment Cost\n# Description\n# Notes\n# Testcase\n# Judge\n# Discuss\n# Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.\n#\n# If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|\n#\n# Notice\n# You can assume each number in the array is a positive integer and not greater than 100.\n#\n# Have you met this question in a real interview?\n# Example\n# Given [1,4,2,3] and target = 1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal.\n#\n# Return 2.\n#\n# Tags\n# Dynamic Programming Backpack LintCode Copyright\nimport sys\n\n\n# wrong, list index out of range\nclass Solution:\n \"\"\"\n @param: A: An integer array\n @param: target: An integer\n @return: An integer\n \"\"\"\n\n def MinAdjustmentCost(self, A, target):\n # write your code here\n\n \"from start to end, adjust each integer. when adjust A[i], we can adjust A[i-1] + target to A[i-1] - target. so total 2*target + 1 choice, the cost we spend is A[i] - A[i-1] - target to A[i] - A[i-1] + target\"\n\n \"think it this way, every time we try to adjust A[i-1] to in range target of A[i], we bring up or down of A[i-1] and this will also affect all previous element. so it is multiplied by i-1\"\n\n \"dynamic programming, the matrix size is len(A) + 1 * (2 * target + 1)\"\n\n \" do we need to remmeber current value after adjustment??\"\n\n if A is None or len(A) == 0 or target <= 0:\n return 0\n\n mat = []\n\n n = len(A)\n\n \"initialization\"\n for i in range(0, n + 1):\n mat.append([0])\n for j in range(0, n + 1):\n mat[i].append(0)\n\n \"consider i, j. The last element is A[i], adjustment to A[i-1] is A[i] + j, cost is A[i-1] - (A[i] + j)\"\n\n \" or we consider i, j, current array length is i, current last adjust position is j. No!\"\n\n for i in range(1, n + 1):\n\n for j in range(1, i + 1):\n \"this step, adjust cost is (j)*abs(abs(A[j] - A[j+1]) - target)\"\n \"we need to calculate cost carefully\"\n\n \"A[j] to A[j+1} +/- target, minimum cost of A[j] move to this range\"\n\n mat[i][j] = mat[i][j - 1] + j * (min(A[j] - (A[j + 1] + target), A[j] - (A[j + 1] - target)))\n\n \" in this way, we fixed last element A[i] actually. we may need to move whole array back to balance a little bit\"\n\n \"we need to find minimum cost, it is minimum of last row\"\n\n minx = mat[-1][-1]\n\n for i in range(1, n + 1):\n minx = min(minx, mat[-1][i])\n\n return minx\n\n\nassert Solution().MinAdjustmentCost([1, 4, 2, 3], 1) == 2\n\n\n# /*\n# * SOLUTION 4:\n# * DP\n# * */\n# /**\n# * @param A: An integer array.\n# * @param target: An integer.\n# */\n\nclass Solution2:\n def MinAdjustmentCost(self,A, target):\n # // write your code here\n if (A == None or len(A) == 0):\n return 0\n\n # // D[i][v]: 把index = i的值修改为v,所需要的最小花费\n D = [ ]\n\n for i in range(0,len(A)):\n D.append([0])\n for j in range(0,100):\n D[i].append(0)\n\n size = len(A)\n\n for i in range(0, size):\n for j in range(1, 101):\n D[i][j] = sys.maxsize\n if (i == 0):\n # // The first element.\n D[i][j] = abs(j - A[i])\n else:\n for k in range(1, 101):\n # // 不符合条件\n if (abs(j - k) > target):\n pass\n\n dif = abs(j - A[i]) + D[i - 1][k]\n D[i][j] = min(D[i][j], dif)\n\n ret = sys.maxsize\n for i in range(1, 101):\n ret = min(ret, D[size - 1][i])\n\n return ret\n\nassert Solution2().MinAdjustmentCost([1, 4, 2, 3], 1) == 2\n\n# TODO need to understand and fix","sub_path":"Algorithm/Python/DynamicProgramming/Backpack/MinimumAdjustmentCost.py","file_name":"MinimumAdjustmentCost.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"620012262","text":"import logging\nimport random\nimport time\nimport sys\nimport traceback\nimport asyncio\nimport collections\n\nimport discord\nimport aiohttp\n\nimport uvloop\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nfrom discord.ext import commands\n\nimport joseconfig as config\nfrom ext.common import SayException\n\nlogging.basicConfig(level=logging.INFO, \\\n format='[%(levelname)7s] [%(name)s] %(message)s')\n\nlog = logging.getLogger(__name__)\n\n\nextensions = [\n 'config', 'admin', 'exec', 'pipupdates',\n 'coins', 'coins+',\n 'basic',\n 'gambling',\n 'speak',\n 'math',\n 'datamosh',\n 'memes',\n 'extra',\n 'stars',\n 'stats',\n 'mod', 'botcollection',\n 'channel_logging',\n 'playing',\n]\n\n\nCHECK_FAILURE_PHRASES = [\n 'br?',\n 'u died [real] [Not ClickBait]',\n 'rEEEEEEEEEEEEE',\n 'not enough permissions lul',\n]\n\n\nBAD_ARG_MESSAGES = [\n 'dude give me the right thing',\n 'u can\\'t give me this and think i can do something',\n 'succ my rod',\n 'i\\'m not a god, fix your args',\n]\n\n\nclass JoseContext(commands.Context):\n async def ok(self):\n try:\n await self.message.add_reaction('👌')\n except discord.Forbidden:\n await self.message.channel.send('ok')\n\n async def not_ok(self):\n try:\n await self.message.add_reaction('❌')\n except discord.Forbidden:\n await self.message.channel.send('not ok')\n\n async def success(self, flag):\n if flag:\n await self.ok()\n else:\n await self.not_ok()\n\n\nclass JoseBot(commands.Bot):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.init_time = time.time()\n self.config = config\n self.session = aiohttp.ClientSession()\n self.simple_exc = [SayException]\n\n # reeeeee dont query mongo every message god damn it\n self.block_cache = {}\n\n async def on_ready(self):\n log.info(f'Logged in! {self.user!s}')\n\n async def is_blocked(self, user_id: int):\n \"\"\"Returns If a user is blocked to use José. Uses cache\"\"\"\n if user_id in self.block_cache:\n return self.block_cache[user_id]\n\n blocked = await self.block_coll.find_one({'user_id': user_id})\n is_blocked = bool(blocked)\n self.block_cache[user_id] = is_blocked\n \n return is_blocked\n\n async def is_blocked_guild(self, guild_id: int):\n \"\"\"Returns if a guild is blocked to use José. Uses cache\"\"\"\n if guild_id in self.block_cache:\n return self.block_cache[guild_id]\n\n blocked = await self.block_coll.find_one({'guild_id': guild_id})\n is_blocked = bool(blocked)\n self.block_cache[guild_id] = is_blocked\n \n return is_blocked\n\n async def on_command(self, ctx):\n # thanks dogbot ur a good\n author = ctx.message.author\n checks = [c.__qualname__.split('.')[0] for c in ctx.command.checks]\n location = '[DM]' if isinstance(ctx.channel, discord.DMChannel) else '[Guild]'\n log.info('%s [cmd] %s(%d) \"%s\" checks=%s', location, author, author.id, ctx.message.content,\n ','.join(checks) or '(none)')\n\n async def on_command_error(self, ctx, error):\n message = ctx.message\n\n if isinstance(error, commands.errors.CommandInvokeError):\n orig = error.original\n if isinstance(orig, SayException):\n await ctx.send(orig.args[0])\n return\n\n tb = ''.join(traceback.format_exception(\n type(error.original), error.original,\n error.original.__traceback__\n ))\n\n if isinstance(orig, tuple(self.simple_exc)):\n log.error(f'Errored at {message.content!r} from {message.author!s}\\n{error.original!r}')\n else:\n log.error(f'Errored at {message.content!r} from {message.author!s}\\n{tb}')\n\n if isinstance(orig, self.cogs['Coins'].TransferError):\n await ctx.send(f'JoséCoin error: `{error.original!r}`')\n return\n\n await ctx.send(f'fucking 🅱enis, u 🅱roke the bot ```py\\n{tb}\\n```')\n elif isinstance(error, commands.errors.BadArgument):\n await ctx.send(f'bad arg — {random.choice(BAD_ARG_MESSAGES)}')\n elif isinstance(error, commands.errors.CheckFailure):\n await ctx.send(f'check fail — {random.choice(CHECK_FAILURE_PHRASES)}')\n\n async def on_message(self, message):\n author_id = message.author.id\n\n if await self.is_blocked(author_id):\n return\n\n try:\n guild_id = message.guild.id\n\n if await self.is_blocked_guild(guild_id):\n return\n except AttributeError:\n # in a DM\n pass\n\n ctx = await self.get_context(message, cls=JoseContext)\n await self.invoke(ctx)\n\n\njose = JoseBot(command_prefix='j.', description='i\\'m a meme', pm_help=None)\n\nif __name__ == '__main__':\n for extension in extensions:\n try:\n t_start = time.monotonic()\n jose.load_extension(f'ext.{extension}')\n t_end = time.monotonic()\n delta = round((t_end - t_start) * 1000, 2)\n log.info(f\"[load] {extension} took {delta}ms\")\n except Exception as err:\n log.error(f'Failed to load {extension}', exc_info=True)\n sys.exit(1)\n\n jose.run(config.token)\n","sub_path":"jose.py","file_name":"jose.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"353734794","text":"from api.search import Api\nfrom simulator.models import *\nfrom datetime import datetime\n\n\n'''\nAdds the stock corrosponding to a given code to a user's watchlist,\nprovided the stock code is valid.\n\nparameters\n code : string\n user : User model\nreturns\n messages : {string : string}\n'''\ndef add(code, user):\n # Get current stock info from Finnhub API\n code = code.upper()\n api = Api()\n messages = {}\n try:\n stockinfo = api.search(code)\n except Exception as e:\n messages['error'] = str(e)\n return messages\n\n price = stockinfo['c']\n timestamp = stockinfo['t']\n\n # cache stock info if this is the first time app has encountered stock\n stocks = Stock.objects.filter(code=code)\n if(stocks.count() != 1):\n Stock.objects.create(name=stockinfo[\"name\"], code=code)\n \n stock_to_add_in_wl = Stock.objects.get(code=code)\n wl = WatchListItem.objects.filter(user_id=user, stock=stock_to_add_in_wl)\n if(wl.count() != 0):\n messages['error'] = \"Stock {} is already in your watchlist\".format(code)\n return messages\n \n WatchListItem.objects.create(user_id=user, stock=stock_to_add_in_wl, timestamp=datetime.utcnow().timestamp())\n messages['success'] = \"Stock {} added to your watchlist\".format(code)\n\n return messages\n\n\n'''\nReturns a list of dictionaries containing information about all stocks in a given\nuser's watchlist.\n\nparameters\n user : User model\n messages : {string : string}\nreturns\n wlist : [ {string : any} ]\n messages : {string : string}\n'''\ndef list_watchlist(user, messages):\n api = Api()\n result = WatchListItem.objects.filter(user_id=user)\n\n wlist = []\n \n for row in result:\n wlist_entry = {}\n code = row.stock.code\n wlist_entry['code'] = code\n wlist_entry['name'] = row.stock.name\n wlist_entry['date'] = row.date\n wlist_entry['timestamp'] = row.timestamp\n \n # Get current stock info from Finnhub API\n try:\n stockinfo = api.search(code)\n wlist_entry['current'] = stockinfo['c']\n wlist_entry['change'] = stockinfo['change']\n except Exception as e:\n wlist_entry['current'] = \"N/A\"\n wlist_entry['change'] = \"N/A\"\n messages['error'] = str(e)\n\n \n wlist.append(wlist_entry)\n\n # Get all alerts related to stock\n stock = Stock.objects.get(code=code)\n alerts_to_show = WatchListAlert.objects.filter(user_id=user, stock=stock, triggered=True, shown=False)\n print(len(alerts_to_show))\n for alert in alerts_to_show:\n messages[f'alert at {alert.dateTriggered} for {alert.stock.code}'] = f\"Stock {alert.stock.name} hit {alert.watchprice} at {alert.dateTriggered}\"\n alert.shown=True\n alert.save()\n \n # Column for watch prices not triggered yet\n alerts_not_triggered_yet = WatchListAlert.objects.filter(user_id=user, stock=stock, triggered=False)\n wlist_entry['alerts'] = []\n for alert in alerts_not_triggered_yet:\n wlist_entry['alerts'].append(alert)\n \n return wlist, messages\n\n\n'''\nRemoves the watchlist entry of a given stock code from a users watchlist, \nas well as all untriggered alerts for that watchlist entry.\n\nparameters\n code : string\n user : User model\nreturns\n messages : {string : string}\n'''\ndef remove(code, user):\n code = code.upper()\n messages = {}\n\n stock_to_remove_from_wl = Stock.objects.get(code=code)\n wl = WatchListItem.objects.get(user_id=user, stock=stock_to_remove_from_wl)\n\n untriggered_alerts = WatchListAlert.objects.filter(user_id=user, stock=stock_to_remove_from_wl, triggered=False)\n for alert in untriggered_alerts:\n alert.delete()\n\n wl.delete()\n\n messages['removed_from_wl'] = \"Stock {} and untriggered alerts have been removed from your watchlist\".format(code)\n return messages\n","sub_path":"modules/watchlist.py","file_name":"watchlist.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"115041738","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport xml.etree.ElementTree as ET # Creating an XML file\nfrom xml.dom import minidom # Formatting the XML file\nimport sys,os\nfrom shapely.geometry import Polygon\nfrom shapely.ops import cascaded_union,polygonize\n\n\ndef takeInputs(csvfile,grid_size):\n\tdata = pd.read_csv(csvfile)\n\tfname = []\n\ttruths = []\n\tfor i in range(len(data)):\n\t\tfname.append(data['filename'][i][-28:])\n\t\tcondition = 'TruePositive'\n\t\tif(condition in data):\n\t\t\tif(data['TruePositive'][i]==1):\n\t\t\t\ttruths.append(2)\n\t\t\telif(data['TrueNegative'][i]==1):\n\t\t\t\ttruths.append(3)\n\t\t\telif(data['FalsePositive'][i]==1):\n\t\t\t\ttruths.append(4)\n\t\t\telif(data['FalseNegative'][i]==1):\n\t\t\t\ttruths.append(5)\n\t\t\telif(data['prediction'][i]==0):\n\t\t\t\ttruths.append(0)\n\t\t\telif(data['prediction'][i]==1):\n\t\t\t\ttruths.append(1)\n\t\telse:\n\t\t\tif(data['prediction'][i]==0):\n\t\t\t\ttruths.append(0)\n\t\t\telif(data['prediction'][i]==1):\n\t\t\t\ttruths.append(1)\n\tvalues = []\n\tfor f in fname:\n\t\tx = \"\"\n\t\ty = \"\"\n\t\ta = \"\"\n\t\tb = \"\"\n\t\tfor i in range(len(f)-2):\n\t\t\tif(f[i]+f[i-1]==\"x-\"):\n\t\t\t\tk =i+1\n\t\t\t\tfor i in range(k,len(f)):\n\t\t\t\t\tif(f[i]=='-'):\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tx+=f[i]\n\t\t\tif(f[i]+f[i-1]==\"y-\"):\n\t\t\t\tk=i+1\n\t\t\t\tfor i in range(k,len(f)):\n\t\t\t\t\tif(f[i]=='-'):\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\ty+=f[i]\n\t\tif(x!=\"\" and y!=\"\"):\n\t\t\tx = int(x) # Row value\n\t\t\ty = int(y) # Coloumn value\n\t\t\tvalues.append([a,b,x,y]) \n\tfinal = []\n\tj=0\t\n\tfor i in range(len(values)):\n\t\ttemp = []\n\t\tgrid_size = 256\n\t\tactual_x = values[i][2]+grid_size\n\t\tactual_y = values[i][3]\n\t\ttemp.append([actual_x,actual_y])\n\t\ttemp.append([actual_x-grid_size,actual_y])\n\t\ttemp.append([actual_x-grid_size,actual_y+grid_size])\n\t\ttemp.append([actual_x,actual_y+grid_size]) \n\t\ttemp.append(truths[i])\n\t\tfinal.append(temp)\n\treturn final\n\ndef makeAnnotation(final, dest, num):\n\t\"\"\"\n\t\tCreating annotations for the XML file\n\t\tArgs:\n\t\t\tA 2-D array containing the list of tiles to be written into an XML file\n\t\t\tThe file path for the XML file\n\t\t\tDenotes the different number of annotations required based of an input i.e\n\t\t\t\t3 - txt\n\t\t\t\t4 - CSV\n\t\tReturns:\n\t\t\tvoid\n\t\t\tThis method creates an XML file and writes the required annotations from the inputs\n\t\"\"\"\n\n\troot = ET.Element(\"Annotations\")\n\troot.set(\"MicronsPerPixel\",\"0.500000\")\n\n\tfor j in range(num):\n\t\ta1 = ET.Element(\"Annotation\")\n\t\ta1.set(\"Id\", str(j+1))\n\t\ta1.set(\"Name\",\"\")\n\t\ta1.set(\"ReadOnly\",\"0\")\n\t\ta1.set(\"NameReadOnly\",\"0\")\n\t\ta1.set(\"LineColorReadOnly\",\"0\")\n\t\ta1.set(\"Incremental\",\"0\")\n\t\ta1.set(\"Type\",\"6\")\n\t\t\t \n\t\tif(j==0):\n\t\t\ta1.set(\"LineColor\",\"65280\") #green colour\n\t\telif(j==1):\n\t\t\ta1.set(\"LineColor\",\"255\") #red colour\n\t\telif(j==2):\n\t\t\ta1.set(\"LineColor\",\"16744448\") #True Positive\n\t\telif(j==3):\n\t\t\ta1.set(\"LineColor\",\"16776960\") #True Negative\n\t\telif(j==4):\n\t\t\ta1.set(\"LineColor\",\"65535\") #yellow #False Possitive\n\t\telif(j==5):\n\t\t\ta1.set(\"LineColor\",\"4194368\") #black #False -ve\n\n\t\ta1.set(\"Visible\",\"1\")\n\t\ta1.set(\"Selected\",\"1\")\n\t\ta1.set(\"MarkupImagePath\",\"\")\n\t\ta1.set(\"MacroName\",\"\")\n\t\troot.append(a1)\n\n\t\tb1 = ET.SubElement(a1,\"Attributes\")\n\t\tb2 = ET.SubElement(b1,\"Attribute\",{\"Name\":\"Description\",\"Id\":\"0\",\"Value\":\"\",})\n\n\t\tr1 = ET.SubElement(a1,\"Regions\")\n\t\tr2 = ET.SubElement(r1,\"RegionAttributeHeaders\")\n\t\tr3 = ET.SubElement(r2,\"AttributeHeader\",{\"Id\":\"9999\",\"Name\":\"Region\",\"ColumnWidth\":\"-1\",})\n\t\tr3 = ET.SubElement(r2,\"AttributeHeader\",{\"Id\":\"9997\",\"Name\":\"Length\",\"ColumnWidth\":\"-1\",})\n\t\tr3 = ET.SubElement(r2,\"AttributeHeader\",{\"Id\":\"9996\",\"Name\":\"Area\",\"ColumnWidth\":\"-1\",})\n\t\tr3 = ET.SubElement(r2,\"AttributeHeader\",{\"Id\":\"9998\",\"Name\":\"Text\",\"ColumnWidth\":\"-1\",})\n\t\tr3 = ET.SubElement(r2,\"AttributeHeader\",{\"Id\":\"1\",\"Name\":\"Description\",\"ColumnWidth\":\"-1\",})\n\t\t\n\t\t# Making the regions to be marked\n\t\tfor i in range(len(final)):\n\t\t\tif(final[i][4]==j):\n\t\t\t\tx1 = abs(final[i][0][0]-final[i][1][0])\n\t\t\t\tx2 = abs(final[i][0][1]-final[i][3][1])\n\t\t\t\tr = ET.SubElement(r1,\"Region\",{\"Id\":str(i+1),\n\t\t\t\t\t\t\t\t\t\t\t\t\"Type\":\"1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"Zoom\":\"1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"Selected\":\"1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"ImageLocation\":\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"ImageFocus\":\"-1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"Length\":str(float(2*(x1+x2))),\n\t\t\t\t\t\t\t\t\t\t\t\t\"Area\":str(float(x1*x2)),\n\t\t\t\t\t\t\t\t\t\t\t\t\"LengthMicrons\":str(float(x1+x2)),\n\t\t\t\t\t\t\t\t\t\t\t\t\"AreaMicrons\":str(float((x1*x2)/4)),\n\t\t\t\t\t\t\t\t\t\t\t\t\"Text\":\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"NegativeROA\":\"0\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"InputRegionId\":\"0\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"Analyze\":\"0\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"DisplayId\":str(i+1),})\n\t\t\t\tatt = ET.SubElement(r,\"Attributes\")\n\t\t\t\tver = ET.SubElement(r,\"Vertices\") \n\t\t\t\tv1 = ET.SubElement(ver,\"Vertex\",{\"X\":str(final[i][0][0]),\"Y\":str(final[i][0][1]),\"Z\":\"0\",})\n\t\t\t\tv2 = ET.SubElement(ver,\"Vertex\",{\"X\":str(final[i][1][0]),\"Y\":str(final[i][1][1]),\"Z\":\"0\",})\n\t\t\t\tv3 = ET.SubElement(ver,\"Vertex\",{\"X\":str(final[i][2][0]),\"Y\":str(final[i][2][1]),\"Z\":\"0\",})\n\t\t\t\tv4 = ET.SubElement(ver,\"Vertex\",{\"X\":str(final[i][3][0]),\"Y\":str(final[i][3][1]),\"Z\":\"0\",})\n\n\ttree = ET.ElementTree(root)\n\n\twith open(dest, \"wb\") as files:\n\t\ttree.write(files)\n\tprint(\"XML file created successfully!\")\n\n\ndef formatXML(filename):\n\t\"\"\"\n\t\tUsed to format an XML file to make it more readable\n\t\tArgs:\n\t\t\tThe XML file\n\t\tReturns:\n\t\t\tvoid\n\t\t\tThis method formats the XML file after the file has been created\n\t\"\"\"\n\n\twith open(filename) as xmldata:\n\t\txml = minidom.parseString(xmldata.read())\n\t\txml_pretty = xml.toprettyxml()\n\t\tf = open(filename,\"w\")\n\t\tf.write(xml_pretty)\n\tprint(\"XML formatted Successfully\")\n\ndef makeXML(filename,grid_size):\n\t\"\"\"\n\t\tMain function that generates the XML file for the sample 003\n\t\n\t\tArgs:\n\t\t\tThe input file from which the values are read\n\t\t\tThe length of the grid\n\t\n\t\tReturns:\n\t\t\tvoid\n\t\t\tThis method calls the appropriate methods to read the values and creates an XML file accordingly\n\t\t\n\t\tNote: For a CSV file it creates an XML file for the existing dataset\n\t\"\"\"\n\tf = takeInputs(filename,grid_size)\n\t#print(f)\n\tfname = filename[:len(filename)-4]\n\tmakeAnnotation(f,fname + \".xml\", 6)\n\tformatXML(fname + \".xml\")\n\t\nif __name__ == \"__main__\":\n\ttilesize = 256\n\t#xmlpath = \"I:\\\\Qupath-WSI\\\\TimestampsFolder\\\\2021-03-14_14-48-51\\\\Sample003_optimized_geoaugmented_CART_roc_auc_jyothidataset_resultsof_prediction_gt_latest_version.csv\"\n\t#makeXML(xmlpath,tilesize)\n","sub_path":"main/Visualize/createXML.py","file_name":"createXML.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"254085519","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass List:\n def __init__(self):\n self.first = None\n self.last = None\n\n def add(self, data):\n new_element = Node(data)\n if not self.first:\n self.first = self.last = new_element\n else:\n self.last.next = new_element\n self.last = self.last.next\n return new_element\n\n def show(self, current=None):\n if not self.first:\n print('empty')\n else:\n if not current:\n current = self.first\n print(current.data)\n if current.next:\n self.show(current.next)\n\n def remove_digit(self, digit, current=None):\n if not self.first:\n return\n if not current:\n current = self.first\n if current.data == digit:\n self.first = self.first.next\n self.remove_digit(digit)\n else:\n self.remove_digit(digit, current)\n elif current.next:\n self.remove_digit(digit, current.next)\n if current.next.data == digit:\n current.next = current.next.next\n\nl = List()\nl.add(2)\nl.add(2)\nl.add(6)\nl.add(4)\nl.add(2)\nl.add(2)\nl.remove_digit(2)\nl.show()\n","sub_path":"linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"510052517","text":"#!/usr/bin/python3\n\nimport os\nimport sys\nimport json\nimport collections\nimport subprocess\nimport argparse\n\nproc = subprocess.Popen(['gcc', '-dumpmachine'], stdout=subprocess.PIPE)\nnative = proc.stdout.read().decode().strip()\n\nproc = subprocess.Popen(['git', 'describe', '--dirty'], stdout=subprocess.PIPE)\nversion = proc.stdout.read().decode().strip()\n\nwith open('configs.json') as config_file:\n\tconfigs = json.load(config_file, object_pairs_hook=collections.OrderedDict)\n\nprint(native)\n\nenv = dict(os.environ)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--targets', required=False)\nparser.add_argument('--hosts', required=False)\n\nargs, unknown = parser.parse_known_args()\n\ntarget_list = []\nhost_list = []\n\nif args.targets != None:\n\tfor target in args.targets.split(','):\n\t\ttarget_list.append(target)\n\nif args.hosts != None:\n\tfor host in args.hosts.split(','):\n\t\thost_list.append(host)\n\ndef get_config_var(name, target, host):\n\tvar = None\n\tif name in target:\n\t\tvar = target[name]\n\tif name in target[\"hosts\"][host]:\n\t\tvar = target[\"hosts\"][host][name]\n\n\treturn var\n\t\n\ndef build_host(target_name, target_config, host_name, host_config):\n\tbinutils_config = get_config_var(\"binutils_config\", target, h)\n\tgcc_config = get_config_var(\"gcc_config\", target, h)\n\tgcc_bootstrap_config = get_config_var(\"gcc_bootstrap_config\", target, h)\n\n\tenv['TARGET'] = target_name\n\tenv['HOST'] = host_name\n\tenv['BUILD'] = host_name\n\t\t\t\n\tif binutils_config != None:\n\t\tenv['BINUTILS_CONFIG'] = binutils_config\n\tif gcc_config != None:\n\t\tenv['GCC_CONFIG'] = gcc_config\n\tif gcc_bootstrap_config != None:\n\t\tenv['GCC_BOOTSTRAP_CONFIG'] = gcc_bootstrap_config\n\n\tprint(\"Building a %s toolchain for %s.\" % (target_name, host_name))\n\t\n\tp = subprocess.Popen(['make -j16'], env=env, shell=True)\n\tp.wait()\n\nfor k, target in configs[\"targets\"].items():\n\tif len(target_list) > 0 and k not in target_list:\n\t\tprint(\"skipping %s\" % k)\n\t\tcontinue\t\n\n\tif \"hosts\" in target:\n\t\tfor h, host in target[\"hosts\"].items():\n\t\t\tif len(host_list) > 0 and h not in host_list:\n\t\t\t\tcontinue\n\t\t\tbuild_host(k, target, h, host)\n\t\t\t\n\nsys.exit(1)\n\nfor k, host in hosts.items():\n for target in host[\"targets\"]:\n env['TARGET'] = k\n env['HOST'] = h\n print(\"Building a %s toolchain for %s.\" % (target, k))\n logfile = \"output/%s/%s/%s/build.log\" % (version, target, k)\n with open(logfile, 'w') as f:\n p = subprocess.Popen(['make'], env=env, stdout=subprocess.PIPE)\n i = 0\n for line in iter(p.stdout.readline, ''):\n #sys.stdout.write(line.decode())\n sys.stdout.write(\"Logged: %d lines to %s\\r\" % (i, logfile))\n i = i + 1\n f.write(line.decode())\n f.flush()\n\n p.wait()\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"415671983","text":"import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nimport numpy as np\nfrom scipy.linalg import schur, logm, expm\n\n\n\ndef Pauli(n):\n if n==0:\n return np.eye(2)\n elif n==1:\n return np.array([[0,1],[1,0]])\n elif n==2:\n return np.array([[0,-1j],[1j,0]])\n elif n==3:\n return np.array([[1,0],[0,-1]])\n else:\n raise ValueError('Input must be integer from 0 to 3.')\n\n# returns sigma_a^p*sigma_b^q, with a,b = 1,2,3, p,q being position\ndef Kron2body(N_atom,a,b,p,q):\n y=1\n for i in range(N_atom):\n if i==p:\n y=np.kron(y,Pauli(a))\n elif i==q:\n y=np.kron(y,Pauli(b))\n else:\n y=np.kron(y,np.eye(2))\n return y\n\ndef Hamiltonian(N_atom,bc,cplist,model):\n H=np.zeros((2**N_atom,2**N_atom))\n for pp in range(len(cplist)):\n for p in range(N_atom):\n if bc=='p':\n q=(p+pp+1)%N_atom\n elif bc=='o':\n q=p+pp+1\n if q>=N_atom:\n continue\n H=H+cplist[pp]*(model[0]*Kron2body(N_atom,1,0,p,q)\n +model[1]*Kron2body(N_atom,2,0,p,q)\n +model[2]*Kron2body(N_atom,3,0,p,q))\n if np.max(np.abs(np.imag(H)))<1e-10: #why?\n H=np.real(H)\n return H\n\n\n\n\n\nclass PpEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.maxTime=None\n self.nSpin=None\n self.target=None\n self.action_space=spaces.Discrete(6) # delay, x, y, -x, -y, terminate\n self.observation_space=None\n self.state={\"pp\": 0, \"n\": 0}\n self.pulses = {\"pp\": [], \"n\": 0}\n self.U0=None\n self.pw=None # pulse width\n self.H0=None # original Hamiltonian\n self.Htarget=None\n\n self.unitary=None\n self.frame=np.eye(2) # Toggling frame unitary\n\n def setParam(self, maxTime, nSpin,pw):\n self.maxTime=maxTime\n self.observation_space= spaces.Dict({\"pp\": spaces.Discrete(5**maxTime), \"n\": spaces.Discrete(maxTime)})\n self.nSpin=nSpin\n self.unitary=np.eye(2**nSpin) # Unitary operator\n self.pw=pw\n\n def setTarget(self,target, false_frame=0):\n if self.nSpin!=None:\n sh=target.shape\n if sh[0]!=2**self.nSpin or sh[1]!=2**self.nSpin:\n raise ValueError('target must be a 2^nSpin-by-2^nSpin matrix.')\n else:\n raise ValueError('setParam before setTarget')\n self.target=target\n self.false_frame = false_frame\n \n \n def setTargetH(self,target):\n if self.nSpin!=None:\n sh=target.shape\n if sh[0]!=2**self.nSpin or sh[1]!=2**self.nSpin:\n raise ValueError('target must be a 2^nSpin-by-2^nSpin matrix.')\n else:\n raise ValueError('setParam before setTarget')\n self.Htarget=target\n \n \n \n\n def Pauli(self, n):\n if n==0:\n return np.eye(2)\n elif n==1:\n return np.array([[0,1],[1,0]])\n elif n==2:\n return np.array([[0,-1j],[1j,0]])\n elif n==3:\n return np.array([[1,0],[0,-1]])\n else:\n raise ValueError('Input must be integer from 0 to 3.')\n\n def setU0(self,U0):\n if self.nSpin!=None:\n sh=U0.shape\n if sh[0]!=2**self.nSpin or sh[1]!=2**self.nSpin:\n raise ValueError('U0 must be a 2^nSpin-by-2^nSpin matrix.')\n else:\n raise ValueError('setParam before setU0')\n self.U0=U0\n \n def setH0(self,H0):\n if self.nSpin!=None:\n sh=H0.shape\n if sh[0]!=2**self.nSpin or sh[1]!=2**self.nSpin:\n raise ValueError('H0 must be a 2^nSpin-by-2^nSpin matrix.')\n else:\n raise ValueError('setParam before setH0')\n self.H0=H0\n\n# get Tr(self.unitary*self.target')\n def getFidelity(self):\n D, V=schur(self.unitary)\n dd=np.diag(np.exp(np.log(np.diag(D))/self.state['n'])) \n U=np.dot(np.dot(V,dd),np.transpose(np.conjugate(V))) # unitary operator in unit time\n return np.abs(np.sum(U*np.transpose(np.conjugate(self.target)))/2**self.nSpin)\n \n\n# get u_frame^{\\kron^nSpin}\n def u_frame_nSpin(self, u_frame):\n temp=1\n for p in range(self.nSpin):\n temp=np.kron(temp,u_frame)\n return temp\n\n def H_pulse_nSpin(self, index):\n n=index\n if n==0:\n temp=np.eye(2**self.nSpin)\n elif n==1:\n temp=Hamiltonian(self.nSpin,'p',[1],[1,0,0])\n elif n==2:\n temp=Hamiltonian(self.nSpin,'p',[1],[0,1,0])\n elif n==3:\n temp=Hamiltonian(self.nSpin,'p',[1],[-1,0,0])\n elif n==4:\n temp=Hamiltonian(self.nSpin,'p',[1],[0,-1,0])\n return temp\n \n def step(self, action):\n # update self.pulses\n self.pulses['pp'].append(action)\n self.pulses['n'] += 1\n \n if action==5:\n if np.max(np.abs(self.frame-np.eye(2)))<1e-10:\n \n reward=-np.log(1-self.getFidelity())\n# reward=reward_fake\n# if reward<24:\n# reward=self.false_frame\n # reward = 0 if reward<11 else reward\n else:\n reward=self.false_frame\n \n return self.state, reward, True, {\"frame\":self.frame}\n \n pp=self.state[\"pp\"]+action*5**self.state[\"n\"]\n self.state[\"pp\"]=pp\n self.state[\"n\"]=self.state[\"n\"]+1\n\n pw=self.pw\n field=self.H_pulse_nSpin(action)\n tauu=1-pw\n phi=np.pi/2\n unitary_n=np.dot(expm(-1j*self.H0*tauu),expm(-1j*(self.H0*pw-phi/2*field)))\n self.unitary=np.dot(unitary_n,self.unitary)\n \n \n if action==0:\n u_pulse=np.eye(2)\n elif action>0 and action<3:\n u_pulse=1/np.sqrt(2)*(np.eye(2)-1j*self.Pauli(action))\n elif action<5:\n u_pulse=1/np.sqrt(2)*(np.eye(2)+1j*self.Pauli(action-2))\n else:\n raise ValueError('Action must be integer from 0 to 5.')\n self.frame=np.dot(self.frame,u_pulse)\n\n \n \n \n \n\n return self.state, -0.00, False, {\"frame\":self.frame}\n \n def reset(self):\n self.state={\"pp\": 0, \"n\": 0}\n self.pulses={\"pp\": [], \"n\": 0}\n # self.U0=None\n if self.nSpin==None:\n self.unitary=None # Unitary operator\n else:\n self.unitary=np.eye(2**self.nSpin)\n self.frame=np.eye(2)\n return self.state, {\"frame\":self.frame}\n \n def render(self, mode='human', close=False):\n pass\n","sub_path":"xyhuang/Beat_RS/gym_pp/envs/pp_env.py","file_name":"pp_env.py","file_ext":"py","file_size_in_byte":6267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"443188173","text":"import random\nimport networkx as nx\nimport numpy as np\nimport numba\nimport timeout_decorator\nimport copy\nfrom timeit import default_timer\n\nprint(numba.config.NUMBA_NUM_THREADS)\nprint(numba.config.NUMBA_DEFAULT_NUM_THREADS)\n\n##******** Read graph data ********##\n\n## Number of nodes (100/1,000/10,000/100,000/1,000,000)\nnodes = [100, 1000, 10000, 100000, 1000000]\nprint('Nodes: ', nodes)\n## Total degree\ndegree = [3, 4, 5]\nprint('Degree: ', degree)\n\nfor i in nodes:\n for j in degree: \n locals()['data_n' + str(i) + '_d' + str(j)] = []\n with open('graph_n' + str(i) + '_d' + str(j) + '.txt', 'r') as f:\n lines = f.read().splitlines()\n for line in lines:\n l = line.split()\n item = [int(l[0]), int(l[1]), float(l[2])]\n locals()['data_n' + str(i) + '_d' + str(j)].append(item)\n\n print(locals()['data_n' + str(i) + '_d' + str(j)][0])\n\n\n\n##******** Implementation 1: list ********##\n##**** Construct distance matrix ****##\n\n@timeout_decorator.timeout(10800)\ndef distance_matrix_list(graph, n):\n ## calculate distance matrix\n INF = float('inf')\n dist_mtx = [[INF] * n for i in range(n)]\n for g in graph:\n i = g[0] - 1\n j = g[1] - 1\n d = g[2]\n dist_mtx[i][j] = d\n dist_mtx[j][i] = d\n\n ## set diagonal to 0\n for i in range(n):\n dist_mtx[i][i] = 0.0\n \n return dist_mtx\n\n\n\n##**** Calculate Hedetniemi Matrix Sum ****##\n\n@timeout_decorator.timeout(10800)\ndef hede_distance_list(matrix, n):\n INF = float('inf')\n mtx_a_t = [[INF] * n for i in range(n)]\n mtx_a_t_1 = copy.deepcopy(matrix)\n\n for p in range(n):\n for i in range(n):\n a = mtx_a_t_1[i] \n for j in range(n):\n b = [row[j] for row in matrix] \n mtx_a_t[i][j] = min([a[k] + b[k] for k in range(n)])\n \n if mtx_a_t == mtx_a_t_1:\n break\n else:\n mtx_a_t_1 = copy.deepcopy(mtx_a_t) \n \n return mtx_a_t\n\n\n\n##******** Implementation 2: numpy ********##\n##**** Construct distance matrix ****##\n\n@timeout_decorator.timeout(10800)\ndef distance_matrix_np(graph, n):\n ## calculate distance matrix\n dist_mtx = np.full((n,n), np.inf)\n for g in graph:\n i = int(g[0]) - 1\n j = int(g[1]) - 1\n d = g[2]\n dist_mtx[i,j] = d\n dist_mtx[j,i] = d\n\n ## set diagonal to 0\n np.fill_diagonal(dist_mtx, 0)\n \n return dist_mtx\n\n\n\n##**** Calculate Hedetniemi Matrix Sum ****##\n\n@timeout_decorator.timeout(10800)\ndef hede_distance_np(matrix, n):\n mtx_a_t = np.full((n,n), np.inf)\n mtx_a_t_1 = matrix.copy()\n \n for p in range(n):\n for i in range(n):\n a = mtx_a_t_1[i]\n for j in range(n):\n b = matrix[:,j]\n mtx_a_t[i,j] = np.amin([a[k] + b[k] for k in range(n)])\n \n if np.array_equal(mtx_a_t, mtx_a_t_1):\n break\n else:\n mtx_a_t_1 = mtx_a_t.copy() \n \n return mtx_a_t\n\n\n\n##******** Implementation 3: numba (njit) ********##\n##**** Construct distance matrix ****##\n\n@timeout_decorator.timeout(10800)\n@numba.njit\ndef distance_matrix_nb(graph, n):\n ## calculate distance matrix\n dist_mtx = np.full((n,n), np.inf)\n for g in numba.prange(graph.shape[0]):\n i = int(graph[g,0]) - 1\n j = int(graph[g,1]) - 1\n d = graph[g,2]\n dist_mtx[i,j] = d\n dist_mtx[j,i] = d\n\n ## set diagonal to 0\n np.fill_diagonal(dist_mtx, 0)\n \n return dist_mtx\n\n\n\n##**** Calculate Hedetniemi Matrix Sum ****##\n\n@timeout_decorator.timeout(10800)\n@numba.njit\ndef hede_distance_nb(matrix, n):\n mtx_a_t = np.full((n,n), np.inf)\n mtx_a_t_1 = matrix.copy() \n \n for p in numba.prange(n):\n for i in numba.prange(n):\n a = mtx_a_t_1[i]\n for j in numba.prange(n):\n b = matrix[:,j]\n mtx_a_t[i,j] = np.amin(np.array([a[k] + b[k] for k in range(n)]))\n \n if np.array_equal(mtx_a_t, mtx_a_t_1):\n break\n else:\n mtx_a_t_1 = mtx_a_t.copy() \n \n return mtx_a_t\n\n\n\n##******** Main ********##\n\nwith open('hedet_results.csv', 'w') as fw:\n fw.write('nodes,degree,list_t1,list_t2,np_t1,np_t2,nb_t1,nb_t2\\n')\n fw.flush()\n \n for i in nodes:\n for j in degree:\n data = locals()['data_n' + str(i) + '_d' + str(j)]\n \n ## List t1\n try:\n start = default_timer()\n dist_mtx_list = distance_matrix_list(data, i)\n stop = default_timer()\n list_t1 = stop - start\n except:\n list_t1 = float('inf')\n \n ## List t2\n try:\n start = default_timer()\n mtx_a_t_list = hede_distance_list(dist_mtx_list, i)\n stop = default_timer()\n list_t2 = stop - start\n ## print shortest path matrix\n with open('hede_dist_list' + '_n' + str(i) + '_d' + str(j) + '.txt', 'w') as f:\n f.write('\\n'.join(['\\t'.join([str(round(cell,2)) for cell in row]) for row in mtx_a_t_list]))\n except:\n list_t2 = float('inf')\n \n ## Numpy t1\n try:\n start = default_timer()\n dist_mtx_np = distance_matrix_np(np.array(data), i)\n stop = default_timer()\n np_t1 = stop - start\n except:\n np_t1 = float('inf')\n \n ## Numpy t2\n try:\n start = default_timer()\n mtx_a_t_np = hede_distance_np(dist_mtx_np, i)\n stop = default_timer()\n np_t2 = stop - start\n ## print shortest path matrix\n with open('hede_dist_np' + '_n' + str(i) + '_d' + str(j) + '.txt', 'w') as f:\n f.write('\\n'.join(['\\t'.join([str(round(cell,2)) for cell in row]) for row in mtx_a_t_np.tolist()])) \n except:\n np_t2 = float('inf')\n \n ## Numba (njit) t1\n try:\n start = default_timer()\n dist_mtx_nb = distance_matrix_nb(np.array(data), i)\n stop = default_timer()\n nb_t1 = stop - start\n except:\n nb_t1 = float('inf')\n \n ## Numba (njit) t2\n try:\n start = default_timer()\n mtx_a_t_nb = hede_distance_nb(dist_mtx_nb, i)\n stop = default_timer()\n nb_t2 = stop - start\n ## print shortest path matrix\n with open('hede_dist_nb' + '_n' + str(i) + '_d' + str(j) + '.txt', 'w') as f:\n f.write('\\n'.join(['\\t'.join([str(round(cell,2)) for cell in row]) for row in mtx_a_t_nb.tolist()])) \n except:\n nb_t2 = float('inf')\n \n fw.write(str(i) + ',' + str(j) + ',' + str(list_t1) + ',' + str(list_t2) + ','\n + str(np_t1) + ',' + str(np_t2) + ',' + str(nb_t1) + ',' + str(nb_t2) + '\\n')\n\n fw.flush()\nfw.close()\n","sub_path":"scripts/hedetniemi/hedetniemi_distance.py","file_name":"hedetniemi_distance.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"305336487","text":"#!/usr/bin/python\n\nimport sys\nimport numpy as np\nimport netCDF4 as nc\nfrom numpy import arange, dtype\n\n#*******************************************************************************\ndef main(args):\n\n \"\"\"USE\n {0} mask.nc input.nc output.nc\n\nDESCRIPTION\n Computes pressure from density and e3t (that changes with SSH).\n\n\"\"\"\n if len(args)<4 or args[1]=='-h' or args[1]=='--help':\n print( main.func_doc.format(args[0]) )\n return 0\n\n# ===============================================================================\n# mask file\n# ===============================================================================\n\n fichiermask=args[1]\n\n mask_file=nc.Dataset(fichiermask)\n depth=mask_file.variables['gdept_1d'][:]\n tmask=mask_file.variables['tmask'][0,:,:,:]\n mask_file.close()\n\n#===============================================================================\n# input\n#===============================================================================\n\n fichierjulien=args[2]\n lefichier = nc.Dataset(fichierjulien)\n\n e3tv=lefichier.variables['e3t']\n ji=e3tv.shape[3]\n jj=e3tv.shape[2]\n jk=e3tv.shape[1]\n jl=e3tv.shape[0]\n\n e3wv=lefichier.variables['e3w']\n rhopv=lefichier.variables['rhop']\n itv=lefichier.variables['time_counter']\n\n lon=lefichier.variables['nav_lon_grid_T'][:]\n lat=lefichier.variables['nav_lat_grid_T'][:]\n\n#===============================================================================\n# output\n#===============================================================================\n\n p_file=args[3]\n print('Creating '+p_file)\n\n # this will overwrite the file\n ncfile = nc.Dataset(p_file,'w', format='NETCDF3_CLASSIC')\n setattr(ncfile,'history',' '.join(args))\n ncfile.createDimension('x',ji)\n ncfile.createDimension('y',jj)\n ncfile.createDimension('dept',jk)\n ncfile.createDimension('time') # unlimited\n\n data = ncfile.createVariable('lont',dtype('float64').char,('y','x'))\n data[:] = lon\n setattr(data, 'units',\"degrees_north\")\n setattr(data, 'standard_name',\"longitude_at_T_location\")\n\n data = ncfile.createVariable('latt',dtype('float64').char,('y','x'))\n data[:] = lat\n setattr(data, 'units',\"degrees_east\")\n setattr(data, 'standard_name',\"latitude_at_T_location\")\n\n data = ncfile.createVariable('dept',dtype('float64').char,('dept'))\n data[:] = depth\n setattr(data, 'units',\"m\")\n setattr(data, 'positive',\"down\")\n setattr(data, 'standard_name',\"depth_at_T_location\")\n setattr(data, 'axis',\"Z\")\n\n otv = ncfile.createVariable('time',dtype('float64').char,('time'))\n setattr(otv, 'units',itv.units)\n setattr(otv, 'standard_name',\"time\")\n setattr(otv, 'axis',\"T\")\n\n pv = ncfile.createVariable('Pbc',dtype('float32').char,('time','dept','y','x'))\n setattr(pv, 'standard_name',\"Amplitude Of Pressure Total\")\n setattr(pv, 'units',\"m-1.kg.s-2\")\n setattr(pv, 'coordinates', \"time dept latt lont\")\n\n#===============================================================================\n# process\n#===============================================================================\n\n print( 'Dimensions: jl={} jk={} jj={} ji={}'.format(jl,jk,jj,ji) )\n\n p_bc=np.zeros(shape=(jk,jj,ji))\n\n grav=9.81\n\n for l in range(0,jl):\n\n time=itv[l]\n print( 'Time frame {}/{}'.format(l,jl) )\n\n e3t=e3tv[l, 0, :, :]\n e3w=e3wv[l, :, :, :]\n rhop=rhopv[l, :, :, :]\n\n for k in range(0,jk):\n if k==0:\n p0=0.5*grav*e3t*rhop[k,:,:]\n else:\n p0+=0.5*grav*e3w[k,:,:]*(rhop[k,:,:]+rhop[k-1,:,:])\n\n p0*=tmask[k,:,:]\n p_bc[k,:,:]=p0\n\n p_bc[tmask==0]=nc.default_fillvals['f4']\n pv[l,:,:,:] = p_bc\n otv[l] = time\n\n#===============================================================================\n# clean-up\n#===============================================================================\n\n lefichier.close()\n ncfile.close()\n\n\n#*******************************************************************************\nif __name__ == '__main__':\n #file:///usr/share/doc/packages/python/html/python-2.7-docs-html/library/sys.html#sys.exit\n sys.exit(main(sys.argv))\n","sub_path":"examples/calcul_pressure-lagrangien.py","file_name":"calcul_pressure-lagrangien.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"18961031","text":"import filecmp\nimport argparse\nimport os.path\nfrom dirsync import sync\n\nclass Sync():\n Host_Dir = ''\n Dest_Dir = ''\n\n def __init__(self, Args):\n self.Host_Dir = Args.hostdir\n self.Dest_Dir = Args.destdir\n\n def Require_Syncing(self, Host, Dest):\n dirs_cmp = filecmp.dircmp(Host, Dest)\n if len(dirs_cmp.left_only) > 0 or len(dirs_cmp.right_only) > 0 or len(dirs_cmp.funny_files) > 0:\n return True\n (_, mismatch, errors) = filecmp.cmpfiles(Host\n , Dest\n , dirs_cmp.common_files\n , shallow = False)\n if len(mismatch) > 0 or len(errors) > 0:\n return True\n for common_dir in dirs_cmp.common_dirs:\n new_dir1 = os.path.join(Host, common_dir)\n new_dir2 = os.path.join(Dest, common_dir)\n if not self.Require_Syncing(new_dir1, new_dir2):\n return False\n return False\n \n def Sync_Files(self): \n try:\n (sync(self.Host_Dir, self.Dest_Dir, 'sync') \n if self.Require_Syncing(self.Host_Dir, self.Dest_Dir) \n else print('No action required\\n'))\n except FileNotFoundError as e:\n print(e)\n \nif __name__ == '__main__':\n P = argparse.ArgumentParser(description='File Sync v0.1')\n P.add_argument('-syncall', help=' Syncs all files in given host directory', required=True, action='store_true')\n P.add_argument('-hostdir', help=' Path to host directory', required=True)\n P.add_argument('-destdir', help=' Path to destination directory', required=True)\n\n Sync_Object = Sync(P.parse_args())\n Sync_Object.Sync_Files()","sub_path":"Sync_Work_Files.py","file_name":"Sync_Work_Files.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"172031905","text":"def id_sequence_extractor(input_path):\n print(\"---> Reading {} raw file...\".format(input_path))\n data = {}\n with open(input_path, \"r\") as f:\n for line in f:\n line = line.rstrip()\n if line.startswith(\">\"):\n uniprot_id = line.split(\"|\")[1]\n data.setdefault(uniprot_id, \"\")\n else:\n data[uniprot_id] += line\n return data\n","sub_path":"predictor/core/uniprot_extractor.py","file_name":"uniprot_extractor.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"210513939","text":"import logging\nfrom config import get_cfg\nfrom db.sql import SQLConnection\nfrom tools import redisdb\nfrom models.institucion import Provincia, Institucion\n\n\nclass Provincias():\n\n # presupone la variable de entorno JUS_CONF\n #config_class = get_cfg()\n # asi es como esta en flask, pero se definira\n # dentro del __init__\n\n def __init__(self, env=\"JUS_CONF\", redis=None, sql=None):\n self.conf = get_cfg(env=env)\n self.redis = redis\n self.sql = sql\n\n if self.redis:\n self.rdb = self.setup_redis()\n if self.sql:\n self.sql = self.setup_sql()\n\n def logger(self):\n logger = logging.getLogger(__name__)\n self.conf.setup_log()\n return logger\n\n def setup_sql(self):\n self.sql = SQLConnection(self.conf.get_sql)\n\n return self.sql\n\n def close_sql(self):\n self.sql.close_session()\n del(self.sql)\n\n def setup_redis(self):\n self.rdb = redisdb.RDB(self.conf.redis['host'])\n return self.rdb\n\n @property\n def get_workdir(self):\n return self.conf.get_workdir\n\n @property\n def institucion(self):\n return Institucion\n\n @property\n def provincia(self):\n return Provincia\n\n def search_files(self, provincia=None, institucion=None):\n results = []\n if provincia:\n for row in self.sql.session.query(Institucion)\\\n .join(Institucion.provincia)\\\n .filter(Provincia.desc == provincia)\\\n .all():\n result = {'inst': row.name,\n 'folder': row.folder,\n 'tipo': row.tipo,\n 'r_key': row.r_key,\n 'prov': row.provincia.desc}\n results.append(result)\n\n\n\n\n\n\n\n\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"639920158","text":"from socket import *\nfrom multiprocessing import Process\nimport re\nimport sys\nwsgi_dir=\"./wsgipython\"\nHTML_ROOT_DIR=\"./html\"\n\nclass HTTPServer(object):\n\t\n\tdef __init__(self):\n\t\tself.ser_socket=socket(AF_INET,SOCK_STREAM)\n\t\tself.ser_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)\n\tdef start(self):\n\t\tself.ser_socket.listen(128)\n\n\t\twhile True:\n\t\t\tclient_socket,client_adress=self.ser_socket.accept()\n\t\t\tprint(\"[%s,%s]\"%(client_adress))\n\t\t\thandle_process=Process(target=self.handle_client,args=(client_socket,))\n\t\t\thandle_process.start()\n\t\t\tclient_socket.close()\n\tdef start_response(self,status,headers):\n\t\t#server_headers={(\"server\",\"my sever\")}\n\t \t#server_headers+headers\n\t \tresponse_headers=\"HTTP/1.1 \"+status+\"\\r\\n\"\n\t \tfor header in headers:\n\t \t\tresponse_headers+=\"%s: %s\\r\\n\" % header\n\t \tself.response_headers=response_headers\n\tdef handle_client(self,client_socket):\n\t\trequest_data=client_socket.recv(1024)\n\t\t#print(\"request_data:\",request_data)\n\t\t'''responst_start=\"HTTP/1.1 200 OK\\r\\n\"\n\t\tresponst_heders=\"Server:My sever\\r\\n\"\n\t\tresponst_body=\"hello incast\"\n\t\tresponse=responst_start+responst_heders+\"\\r\\n\"+responst_body\n\t\tprint(\"response data:\",response)\n\t\tclient_socket.send(bytes(response,\"utf-8\"))\n\t\tprint(\"success\")\n\t\tclient_socket.close()'''\n\t\trequest_lines=request_data.splitlines()\n\t\t#for line in request_lines:\n\t\t\t#print(line)\n\t\trequest_start_line=request_lines[0] #markkkkkkkkkkkkkk\n\t\t'''print(\"***********\")\n\t\tprint(request_start_line)\n\t\tprint(\"***********\")'''\n\t\tfile_name=re.match(r\"\\w+ +(/[^ ]*) \",request_start_line.decode(\"utf-8\")).group(1)\n\t\tb=\".py\"\n\t\t'''print(\"***********\")\n\t\tprint(file_name)\n\t\tprint(\"***********\")'''\n\t\t#print(b)\n\t\t#print(file_name)\n\t\tif str(file_name).endswith(b):\n\t\t\tm=__import__(file_name[1:-3])\n\t\t\tenv={}\n\t\t\tresponse_body=m.application(env,self.start_response)\n\t\t\tresponse=self.response_headers+\"\\r\\n\"+response_body\n\n\n\n\t\telse:\n\t\t#if \"/\"==file_name:\n\t\t\t#file_name=\"/index.html\"\n\t\t\tfile_name=\"index.html\"\n\t\t\ttry:\n\t\t\t\tfile=open(file_name,\"rb\")\n\t\t\texcept IOError:\n\t\t\t\tresponst_start=\"HTTP/1.1 404 Not Found\\r\\n\"\n\t\t\t\tresponst_heders=\"Server:My sever\\r\\n\"\n\t\t\t\tresponst_body=\"the file is not found!\"\n\t\t\telse:\n\t\t\t\tfile_data=file.read()\n\t\t\t\tfile.close()\n\t\t\t\tresponst_start=\"HTTP/1.1 200 OK\\r\\n\"\n\t\t\t\tresponst_heders=\"Server:My sever\\r\\n\"\n\t\t\t\tresponst_body=file_data.decode(\"utf-8\")\n\t\t#response=responst_start+responst_heders+\"\\r\\n\"+responst_body\n\t\tclient_socket.send(bytes(response,\"utf-8\"))\n\t\tclient_socket.close()\n\tdef bind(self,port):\n\t\tself.ser_socket.bind((\"\",port))\ndef main():\n\tsys.path.insert(1,wsgi_dir)\n\thttp_sever=HTTPServer()\n\thttp_sever.bind(7788)\n\thttp_sever.start()\n\n\t\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"web1/02-static-web.py","file_name":"02-static-web.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"543946593","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nweather.py London Seattle \"New York\"\nWeather for London:\n 59┬░F\n Mostly Cloudy\n Wind: SE at 9 mph\n Humidity: 67%\nWeather for Seattle, WA:\n 48┬░F\n Overcast\n Wind: S at 10 mph\n Humidity: 74%\nWeather for New York, NY:\n 62┬░F\n Clear\n Wind: NE at 5 mph\n Humidity: 50%\n\"\"\"\nimport sys\nfrom argparse import ArgumentParser\nimport requests\nfrom xml.dom import minidom\n\nAPI_URL = \"http://www.google.com/ig/api?\"\n\ndef main():\n arguments = ArgumentParser(prog=\"weather\")\n arguments.add_argument(\"--unit\", choices=\"CF\", dest=\"unit\", default=\"F\", help=\"Which unit to display the temperatures in\")\n arguments.add_argument(\"location\", nargs=\"+\")\n args = arguments.parse_args(sys.argv[1:])\n\n for location in args.location:\n payload = {'weather':location}\n xml = requests.get(API_URL,params=payload)\n doc = minidom.parseString(xml.text)\n\n forecast_information = doc.documentElement.getElementsByTagName(\"forecast_information\")[0]\n city = forecast_information.getElementsByTagName(\"city\")[0].getAttribute(\"data\")\n\n current_conditions = doc.documentElement.getElementsByTagName(\"current_conditions\")[0]\n temp = current_conditions.getElementsByTagName(\"temp_f\" if args.unit == \"F\" else \"temp_c\")[0].getAttribute(\"data\")\n condition = current_conditions.getElementsByTagName(\"condition\")[0].getAttribute(\"data\")\n wind_condition = current_conditions.getElementsByTagName(\"wind_condition\")[0].getAttribute(\"data\")\n humidity = current_conditions.getElementsByTagName(\"humidity\")[0].getAttribute(\"data\")\n\n indent = \" \"\n print(\"Weather for {0}:\".format(city))\n print(indent + \"{0}°{1}\".format(temp, args.unit))\n print(indent + condition)\n print(indent + wind_condition)\n print(indent + humidity)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"81313274","text":"#!/usr/local/bin/python3\nimport xlrd as exc\nimport csv\nimport argparse\nimport str_token_gen as s\nimport reverse_token_gen as r\nfrom abbv import abbvtool\nimport collections\nimport flattenlist as fl\ndef parse_args():\n\tparser=argparse.ArgumentParser( description ='supply file that need to be parsed')\n\tparser.add_argument('--filename',required=True)\n\tparser.add_argument('--outputname',required=True)\n\treturn parser.parse_args()\n\n\ndef csvconvert(filename,outputname):\n\tworkbook = exc.open_workbook(filename)\n\tintial_li=[]\n\tfieldnames = ['sheetname', 'parentObject', 'label','tag','value','context','acronym','pre','post']\n\tfor i in workbook.sheet_names():\n\t\tprocessing_sheet=i\n\t\tworksheet = workbook.sheet_by_name(processing_sheet)\n\t\tfor j in range(2, worksheet.nrows):\n\t\t\tacronym=abbvtool(worksheet.cell_value(j,3))\n\t\t\ttxt_val = worksheet.cell_value(j,4)\n\t\t\tlabel = worksheet.cell_value(j,3)\n\t\t\tprefix=''\n\t\t\tsuffix=''\n\t\t\ttry:\n\t\t\t\tif label.upper() in txt_val.upper():\n\t\t\t\t\tprefix = txt_val.upper().split(label.upper())[0]\n\t\t\t\t\tsuffix = txt_val.upper().split(label.upper())[1]\n\t\t\t\telif acronym.upper() in txt_val.upper():\n\t\t\t\t\tprefix = txt_val.upper().split(acronym.upper())[0]\n\t\t\t\t\tsuffix = txt_val.upper().split(acronym.upper())[1]\n\t\t\t\telse:\n\t\t\t\t\tprefix='NA'\n\t\t\t\t\tsuffix='NA'\n\t\t\texcept:\n\t\t\t\tpass \n\t\t\tintial_li.append([i]+worksheet.row_values(j)+[acronym]+[prefix]+[suffix]) \n\twith open(outputname, \"w\",encoding='utf-8') as f:\n\t\twriter = csv.writer(f,delimiter='~',quotechar ='\"',quoting=csv.QUOTE_NONNUMERIC)\n\t\twriter.writerow(fieldnames)\n\t\twriter.writerows(intial_li)\n\tpre_post_output=[]\n\tfor l in intial_li:\n\t\tif 'DATA' in l[3].upper() and 'NA' not in l:\n\t\t\treversed(r.reverse_lemma(l[-2]))\n\t\t\t#print( [l[5]]+r.reverse_lemma(l[-2])+['target'] +s.lemma(l[-1]))\n\t\t\tpre_post_ls=r.reverse_lemma(l[-2]) +s.lemma(l[-1])\n\t\t\tpre_post_output=pre_post_ls +pre_post_output\n\t\t\n\tcounter=collections.Counter(pre_post_output)\n\tprint(counter.most_common(1000))\n\treturn intial_li\n\n\ndef main():\n\targs = parse_args()\n\tcsvconvert(args.filename,args.outputname)\n\n\nif __name__ == \"__main__\":\n\tmain()\t\n","sub_path":"token_gen.py","file_name":"token_gen.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508663557","text":"#!/usr/bin/python3\nimport sys, math\n\nsBox = {\n\t0: 14,\n\t1: 4, \n\t2: 13,\n\t3: 1,\n\t4: 2,\n\t5: 15,\n\t6: 11, \n\t7: 8,\n\t8: 3,\n\t9: 10,\n\t10: 6,\n\t11: 12, \n\t12: 5,\n\t13: 9,\n\t14: 0,\n\t15: 7\n}\n\nsBoxInverse = {\n\t14: 0,\n\t4: 1, \n\t13: 2,\n\t1: 3,\n\t2: 4,\n\t15: 5,\n\t11: 6, \n\t8: 7,\n\t3: 8,\n\t10: 9,\n\t6: 10,\n\t12: 11, \n\t5: 12,\n\t9: 13,\n\t0: 14,\n\t7: 15\n}\n\ndef xor(a, b):\n\tresult = \"\"\n\tfor i in range(0, len(a)):\n\t\tbitA = int(a[i])\n\t\tbitB = int(b[i])\n\n\t\tif (bitA == 1 and bitB == 1) or (bitA == 0 and bitB == 0):\n\t\t\tresult+=str(0)\n\t\telse:\n\t\t\tresult+=str(1)\n\n\treturn result\n\ndef ComputeV(ciphertext, key, partial):\n\tif partial:\n\t\tkLeft = key[0:4]\n\t\tcLeft = ciphertext[4:8]\n\n\t\tkRight = key[4:8]\n\t\tcRight = ciphertext[12:16]\n\n\t\treturn xor(kLeft, cLeft), xor(kRight, cRight)\n\telse:\n\t\tk1 = key[0:4]\n\t\tc1 = ciphertext[0:4]\n\n\t\tk2 = key[4:8]\n\t\tc2 = ciphertext[4:8]\n\n\t\tk3 = key[8:12]\n\t\tc3 = ciphertext[8:12]\n\n\t\tk4 = key[12:16]\n\t\tc4 = ciphertext[12:16]\n\n\t\treturn xor(k1, c1), xor(k2, c2), xor(k3, c3), xor(k4, c4)\n\ndef ComputeUPartial(vLeft, vRight):\n\tleft = sBoxInverse[int(vLeft, 2)]\n\tright = sBoxInverse[int(vRight, 2)]\n\n\treturn '{:04b}'.format(left), '{:04b}'.format(right)\n\ndef ComputeUFull(v1, v2, v3, v4):\n\tu1 = sBoxInverse[int(v1, 2)]\n\tu2 = sBoxInverse[int(v2, 2)]\n\tu3 = sBoxInverse[int(v3, 2)]\n\tu4 = sBoxInverse[int(v4, 2)]\n\n\treturn '{:04b}'.format(u1), '{:04b}'.format(u2), '{:04b}'.format(u3), '{:04b}'.format(u4)\n\n#Determines the bias across all plaintext/ciphertext pairs\ndef linear(plaintexts, ciphertexts, key):\n\tzeroes = 0\n\tones = 0\n\n\tfor i in range(0, len(ciphertexts)):\n\t\tvLeft, vRight = ComputeV(ciphertexts[i], key, True)\n\t\tuLeft, uRight = ComputeUPartial(vLeft, vRight)\n\n\t\t#Bits for the linear approximation: \n\t\t#U6, U8, U14, U16, P5, P7, P8\n\t\tbits = [uLeft[1], uLeft[3], uRight[1], uRight[3], \n\t\t\t\tplaintexts[i][4], plaintexts[i][6], plaintexts[i][7]]\n\n\t\tresult = xor(bits[0], bits[1])\n\t\tfor j in range(2, len(bits)):\n\t\t\tresult = xor(result, bits[j])\n\n\t\tif result == \"1\":\n\t\t\tones += 1\n\t\telse:\n\t\t\tzeroes += 1\n\n\tdiff = ones-(len(ciphertexts)/2)\n\tbias = diff/len(ciphertexts)\n\treturn abs(bias)\n\n#Determines the bias across all plaintext/ciphertext pairs for full key K\n#This almost the same as the other function, but we care about different bits\n#Fix it if there is time\ndef linearFull(plaintexts, ciphertexts, key):\n\tzeroes = 0\n\tones = 0\n\n\tfor i in range(0, len(ciphertexts)):\n\t\tv1, v2, v3, v4 = ComputeV(ciphertexts[i], key, False)\n\t\tu1, u2, u3, u4 = ComputeUFull(v1, v2, v3, v4)\n\n\t\t# \t#Bits for the linear approximation: \n\t\t# \t#U42, U46, U410, U414, P1, P4, P9, P12\n\t\tbits = [u1[1], u2[1], u3[1], u4[1], \n\t\t \t\tplaintexts[i][0], plaintexts[i][3], plaintexts[i][8], plaintexts[i][11]]\n\n\t\tresult = xor(bits[0], bits[1])\n\t\tfor j in range(2, len(bits)):\n\t\t\tresult = xor(result, bits[j])\n\n\t\tif result == \"1\":\n\t\t\tones += 1\n\t\telse:\n\t\t\tzeroes += 1\n\n\tdiff = ones-(len(ciphertexts)/2)\n\tbias = diff/len(ciphertexts)\n\treturn abs(bias)\n\ndef main():\n\tmode = sys.argv[1]\n\n\tplaintexts = [line.strip() for line in open(\"plaintexts.txt\", 'r')]\n\tciphertexts = [line.strip() for line in open(\"ciphertext06.txt\", 'r')]\n\t\n\tif mode == \"--q2a\":\n\t\tk5partial = \"01110110\"\n\t\tbias = linear(plaintexts, ciphertexts, k5partial)\n\t\tprint(\"Bias for key: \" + k5partial + \", is: \" + str(bias))\n\telif mode == \"--q2b\":\n\t\tprint(\"Computing the bias for all possible partial keys...\")\n\t\tresults = dict()\n\n\t\tfor i in range(0, 16):\n\t\t\tfor j in range(0, 16):\n\t\t\t\tkey = '{:04b}'.format(i) + '{:04b}'.format(j)\n\t\t\t\tbias = linear(plaintexts, ciphertexts, key)\n\t\t\t\tresults[key] = bias\n\n\t\tresults = sorted(results.items(), key=lambda x: x[1], reverse=True)\n\t\tprint(results)\n\telif mode == \"--q2d\":\n\t\tprint(\"Computing the bias for all K5 using partial key: .... 0011 .... 1000\")\n\t\tresults = dict()\n\n\t\tfor i in range(0, 16):\n\t\t\tfor j in range(0, 16):\n\t\t\t\tkey = '{:04b}'.format(i) + \"0011\" + '{:04b}'.format(j) + \"1000\"\n\t\t\t\tbias = linearFull(plaintexts, ciphertexts, key)\n\t\t\t\tresults[key] = bias\n\n\t\tresults = sorted(results.items(), key=lambda x: x[1], reverse=True)\n\t\tprint(results)\t\nmain()\n","sub_path":"A2/Linear/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"107053047","text":"#!/usr/bin/env python\n\"\"\"\nGPIO Class\nCreated: 2017 May 24\nAuthor: James Quen\n\nDescription:\nImplementation of the GPIO class object\n\"\"\"\n\nimport wiringpi\n\nfrom subprocess import call, PIPE, Popen\nfrom configuration import ateConfig\n\n# To setup wiringpi pin states\nWIRING_PI_INPUT = 0\nWIRING_PI_OUTPUT = 1\nWIRING_PI_ALT0 = 4\n\nWIRING_PI_PULL_DOWN = 1\nWIRING_PI_PULL_UP = 2\n\nclass GPIO():\n def __init__(self, pin, inferConfiguration=False):\n '''\n Initializes GPIO as defined in the pi3Pins dictionary.\n :param pin: Dicitonary containing pin information\n :param inferConfiguration: If true, rather than initializing the state and mode of the gpio\n to the parameters present in pin, it will load the current state.\n '''\n\n self.__BCM = pin['BCM']\n self.__mode = pin['mode']\n self.__name = pin['name']\n self.__physical = pin['physical']\n self.__value = pin['value']\n self.__wPi = pin['wPi']\n self.__type = pin['type']\n\n # sets wiringpi to use BCM pin numbering\n wiringpi.wiringPiSetupGpio()\n\n # Configure pin to initial mode.\n if inferConfiguration:\n # Fetch pin mode from hardware\n self.refreshMode()\n else:\n self.configureAs(self.__mode)\n\n # Set pin to initial value if it is an output or pull state if it is an input.\n if inferConfiguration:\n # read current state regardless of mode\n self.read()\n # leave pull-down and pull-up as they are\n else:\n if self.__mode == 'out':\n self.set(self.__value)\n elif self.__mode == 'in':\n if self.__value == '1':\n self.pullUp()\n elif self.__value == '0':\n self.pullDown()\n\n def configureAs(self, mode):\n '''\n This function configures the GPIO as an input, output, or alt0.\n :param mode: String input of the desired mode.\n :return: none\n '''\n ateConfig.log.logger.debug(\"Configuring %s as %s.\" % (self.__name, mode))\n # self.__mode = mode\n\n # if mode == 'in':\n # wiringpi.pinMode(int(self.__BCM), WIRING_PI_INPUT)\n #\n # elif mode == 'out':\n # wiringpi.pinMode(int(self.__BCM), WIRING_PI_OUTPUT)\n #\n # elif mode == 'alt0':\n # wiringpi.pinMode(int(self.__BCM), WIRING_PI_ALT0)\n\n if mode == 'in' or mode == 'out' or mode == 'alt0':\n # print(\"Configuring %s as %s.\" % (self.__usage, mode))\n call([\"gpio\", \"-g\", \"mode\", self.__BCM, mode])\n ateConfig.log.logger.debug(\"Configured %s as %s.\" % (self.__name, mode))\n # Save the mode it is in.\n self.__mode = mode\n\n\n else:\n self.__mode = None\n ateConfig.log.logger.error(\"Error: Invalid pin mode! Mode can only be in, out, or alt0.\")\n\n def configureAsInput(self):\n '''\n This function configures the GPIO as an input.\n :return: \n '''\n\n self.configureAs('in')\n\n def configureAsOutput(self):\n '''\n This function configures the GPIO as an output.\n :return: \n '''\n\n self.configureAs('out')\n\n def configureAsAlt0(self):\n '''\n This function configures the GPIO as its first alternate function.\n :return: \n '''\n\n self.configureAs('alt0')\n\n def set(self, state):\n '''\n This function sets the GPIO high or low if it is configured as an output.\n :param state: String input for the desired state.\n :return: none\n '''\n\n ateConfig.log.logger.debug(\"Setting %s to %s.\" % (self.__name, state))\n\n if self.__mode == 'out' and (state == '1' or state == '0'):\n wiringpi.digitalWrite(int(self.__BCM), int(state))\n #call([\"gpio\", \"-g\", \"write\", self.__BCM, state])\n\n ateConfig.log.logger.debug(\"%s set to %s.\" % (self.__name, state))\n\n self.__value = state\n else:\n ateConfig.log.logger.error(\"Error: Invalid pin state! State can only be 1 or 0.\")\n\n def pull(self, state):\n '''\n This function sets GPIO with a pull up or pull down if it is configured as an input.\n :param state: String input for pull state. Can only be 'up' or 'down'.\n :return: none\n '''\n ateConfig.log.logger.debug(\"Enabling pull %s on %s.\" % (state, self.__name))\n\n # if self.__mode == 'in':\n # if state == 'up':\n # wiringpi.pullUpDnControl(int(self.__BCM), WIRING_PI_PULL_UP)\n #\n # elif state == 'down':\n # wiringpi.pullUpDnControl(int(self.__BCM), WIRING_PI_PULL_DOWN)\n if self.__mode == 'in' and (state == 'up' or state == 'down'):\n\n call([\"gpio\", \"-g\", \"mode\", self.__BCM, state])\n\n ateConfig.log.logger.debug(\"Enabled pull %s on %s.\" % (state, self.__name))\n else:\n ateConfig.log.logger.error(\"Error: Invalid pull state! State can only be up or down.\")\n\n def pullUp(self):\n '''\n This function enables the pull up of the GPIO.\n :return: \n '''\n\n self.pull('up')\n\n def pullDown(self):\n '''\n This function enables the pull up of the GPIO.\n :return: \n '''\n\n self.pull('down')\n\n def read(self):\n '''\n This function gets the state of the GPIO.\n :return: string value of GPIO state.\n '''\n\n # cmd = Popen([\"gpio\", \"-g\", \"read\", self.__BCM], stdout=PIPE)\n #\n # # Get the data. The communicate function returns (output, returnCode).\n # data = cmd.communicate()[0]\n #\n # # Convert byte format to string.\n # self.__value = str(int(data.decode('utf-8'), 16))\n #\n # # Close the PIPE.\n # cmd.stdout.close()\n\n self.__value = str(wiringpi.digitalRead(int(self.__BCM)))\n\n ateConfig.log.logger.debug(\"%s is %s\" % (self.__name, self.__value))\n\n return self.__value\n\n def getInfo(self):\n '''\n This function returns all information pertaining to this GPIO.\n :return: Dictionary of information of this GPIO.\n '''\n\n # If the mode is an input, read the value in case it has been changed externally.\n if self.__mode == 'in':\n self.read()\n\n info = {'BCM': self.__BCM,\n 'mode': self.__mode,\n 'name': self.__name,\n 'physical': self.__physical,\n 'value': self.__value,\n 'wPi': self.__wPi,\n }\n\n ateConfig.log.logger.debug(\"Info on %s: %s\" % (self.__name, info))\n\n return info\n\n def getInfoForMonitor(self):\n '''\n This function is a modified version of getInfo, that reads regardless of whether the pin is in or out, and\n returns additional information needed for the gpioMonitor.\n :return: Dictionary of information for this GPIO.\n '''\n\n #read regardless of state\n self.read()\n #refresh the mode in case it has been changed externally\n self.refreshMode()\n\n #build the dictionary of info\n info = {'mode': self.__mode,\n 'name': self.__name,\n 'value': self.__value,\n }\n\n return info\n\n def refreshMode(self):\n '''\n This function updates the mode of the pin, in case it has been changed by another program\n '''\n\n #Get alt bits\n alt = wiringpi.getAlt(int(self.__BCM))\n\n #Set the mode\n if alt == WIRING_PI_INPUT:\n self.__mode = 'in'\n elif alt == WIRING_PI_OUTPUT:\n self.__mode = 'out'\n elif alt == WIRING_PI_ALT0:\n self.__mode = 'alt0'\n\n","sub_path":"utilities/gpio.py","file_name":"gpio.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"258968385","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#UNAM-CERT\n# Santiago Mancera Arturo Samuel\n# Sarmiento Campos José\n# Valle Juarez Pedro Ángel\n\nimport os\nimport DAO\n\n# Conexion a la base de datos y extraccion de información\nconexion = DAO.Conexion()\nconn = conexion.conectar()\nlista1,lista2,lista3,lista4,lista5 = conexion.ip_dominio(conn)\nconn.close()\n\n# Función Principal se creo para llamar sin argumentos\ndef maincsv():\n writecsv(lista1,lista2,lista3,lista4,lista5)\n\ndef writecsv(Dominios,ips,tipo_contenido,cms,puertos):\n # Función que escribe una lista separada por comas basada en dos listas \n rango = len(Dominios)\n arch = open('datos.csv',\"w\")\n for x in range(0,rango):\n arch.write(Dominios[x]+\",\")\n arch.write(ips[x]+\",\")\n arch.write(tipo_contenido[x]+\",\")\n arch.write(cms[x]+\",\")\n arch.write(str(puertos[x])+\"\\n\")\n arch.close()\n\ndef genlista(Ruta):\n arch = open(Ruta,\"r\")\n vulne = arch.read()\n lista = vulne.split(\",\")\n return lista \n \n# writecsv([\"www.fff.xxx\",\"www.fgr.zzz\",\"www.tyu.ppp\"],[\"192.168.1.32\",\"192.168.1.33\",\"192.168.1.34\"])\n","sub_path":"isc.py","file_name":"isc.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"14762105","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass UserExtensionPolicy(Model):\n \"\"\"UserExtensionPolicy.\n\n :param display_name: User display name that this policy refers to\n :type display_name: str\n :param permissions: The extension policy applied to the user\n :type permissions: :class:`ExtensionPolicy `\n :param user_id: User id that this policy refers to\n :type user_id: str\n \"\"\"\n\n _attribute_map = {\n 'display_name': {'key': 'displayName', 'type': 'str'},\n 'permissions': {'key': 'permissions', 'type': 'ExtensionPolicy'},\n 'user_id': {'key': 'userId', 'type': 'str'}\n }\n\n def __init__(self, display_name=None, permissions=None, user_id=None):\n super(UserExtensionPolicy, self).__init__()\n self.display_name = display_name\n self.permissions = permissions\n self.user_id = user_id\n","sub_path":"vsts/vsts/extension_management/v4_1/models/user_extension_policy.py","file_name":"user_extension_policy.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"336738265","text":"import base64\nimport io\nimport json\nimport os\nimport sys\nimport urllib\n\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn import model_selection, preprocessing, metrics, naive_bayes, tree\n\nfrom read_image import ReadImage\n\n\nclass Classifier:\n def __init__(self, data=None):\n self.__labels = []\n self.__data = data\n self.__h5_data = os.path.dirname(__file__) + '/output/data.h5'\n self.__h5_labels = os.path.dirname(__file__) + '/output/labels.h5'\n\n def prepare(self):\n features, classes = [], []\n\n for image in self.__data:\n features.append(image[0:6])\n classes.append(image[6])\n\n self.__labels = np.unique(classes)\n preprocessed = preprocessing.LabelEncoder()\n output = preprocessed.fit_transform(classes)\n\n scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))\n rescaled_features = scaler.fit_transform(features)\n\n final_features = np.array(rescaled_features)\n final_labels = np.array(output)\n\n h5f_data = h5py.File(self.__h5_data, 'w')\n h5f_data.create_dataset('dataset_1', data=final_features)\n\n h5f_label = h5py.File(self.__h5_labels, 'w')\n h5f_label.create_dataset('dataset_1', data=final_labels)\n\n h5f_data.close()\n h5f_label.close()\n\n def NaiveBayes(self):\n self.prepare()\n\n final_features, final_labels = self.load_dataset()\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(\n np.array(final_features), np.array(final_labels)\n )\n\n model = naive_bayes.GaussianNB()\n model.fit(X_train, y_train)\n\n if sys.platform.startswith('linux'):\n self.confusion_matrix2(model, X_train, y_train)\n else:\n self.confusion_matrix(model, X_test, y_test)\n\n def DecisionTree(self):\n self.prepare()\n\n final_features, final_labels = self.load_dataset()\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(\n np.array(final_features), np.array(final_labels)\n )\n\n model = tree.DecisionTreeClassifier()\n model.fit(X_train, y_train)\n\n if sys.platform.startswith('linux'):\n self.confusion_matrix2(model, X_train, y_train)\n else:\n self.confusion_matrix(model, X_test, y_test)\n\n # Tree\n print(tree.plot_tree(model))\n # https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\n\n def confusion_matrix(self, model, x_test, y_test):\n title = \"Matriz de confusão\"\n\n disp = metrics.plot_confusion_matrix(\n model, x_test, y_test, cmap=plt.cm.Greys)\n\n disp.ax_.set_title(title)\n\n my_path = os.getcwd()\n filename = 'MatrizDeConfusao.png'\n file_path = my_path + '/public/' + filename\n\n fig = plt.gcf()\n buf = io.BytesIO()\n fig.savefig(buf, format='png')\n buf.seek(0)\n string = base64.b64encode(buf.read())\n\n confusion_matrix = {}\n\n confusion_matrix['uri'] = 'data:image/png;base64,' + \\\n urllib.parse.quote(string)\n\n print(json.dumps(confusion_matrix))\n\n def confusion_matrix2(self, model, x_train, y_train):\n # TODO: VERIFICAR PARAMETROS\n y_pred = model.predict(x_train)\n cf_matrix = metrics.confusion_matrix(y_train, y_pred)\n\n sns.heatmap(cf_matrix, annot=True)\n\n my_path = os.getcwd()\n filename = 'MatrizDeConfusao.png'\n file_path = my_path + '/public/' + filename\n\n fig = plt.gcf()\n buf = io.BytesIO()\n fig.savefig(buf, format='png')\n buf.seek(0)\n string = base64.b64encode(buf.read())\n\n confusion_matrix = {}\n\n confusion_matrix['uri'] = 'data:image/png;base64,' + \\\n urllib.parse.quote(string)\n\n print(json.dumps(confusion_matrix))\n\n def load_dataset(self):\n h5f_data = h5py.File(self.__h5_data, 'r')\n h5f_label = h5py.File(self.__h5_labels, 'r')\n\n final_features_string = h5f_data['dataset_1']\n final_labels_string = h5f_label['dataset_1']\n\n final_features = np.array(final_features_string)\n final_labels = np.array(final_labels_string)\n\n h5f_data.close()\n h5f_label.close()\n\n return final_features, final_labels\n\n @staticmethod\n def predict(model, img, X_train, X_test, y_train, y_test):\n features_from_img = ReadImage().read(img=img)\n\n if model == 'naive-bayes':\n model = naive_bayes.GaussianNB()\n elif model == 'decision-tree':\n model = tree.DecisionTreeClassifier()\n\n model.fit(X_train, y_train)\n\n scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))\n rescaled_feature = scaler.fit_transform(\n np.array(features_from_img[0:6]).reshape(-1, 1))\n\n predict = model.predict(X_test)\n prediction = model.predict(rescaled_feature.reshape(1, -1))[0]\n\n accuracy = metrics.accuracy_score(\n y_test, predict) * 100\n\n return prediction, features_from_img, accuracy\n\n def classify(self, img, model):\n final_features, final_labels = self.load_dataset()\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(\n final_features, final_labels, test_size=0.35, train_size=0.65\n )\n\n prediction, featuresFromImg, accuracy = self.predict(model,\n img, X_train, X_test, y_train, y_test)\n\n label = 'Milhouse'\n if prediction:\n label = 'Apu'\n\n print(json.dumps({\n 'features': {\n 'Milhouse Blue Hair': featuresFromImg[0],\n 'Milhouse Pink Shirt': featuresFromImg[1],\n 'Milhouse Red Shorts ': featuresFromImg[2],\n 'Apu Brown Skin': featuresFromImg[3],\n 'Apu Green Jacket': featuresFromImg[4],\n 'Apu Yellow Pants': featuresFromImg[5]\n },\n 'prediction': {\n 'accuracy': accuracy,\n 'label': label\n }\n }))\n","sub_path":"python/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":6291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"148183755","text":"# rover.py\n# Program to calculate the amount of time for a photo to reach\n# Earth from Mars\n\ndef main():\n speedLight = 186000\n distance = 34000000\n\n time = distance / speedLight\n print(\"The amount of time it takes a photo to travel from Mars to Earth is\", time, \"seconds\")\nmain()\n","sub_path":"rover.py","file_name":"rover.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497986946","text":"# -*- coding: utf-8 -*-\n#\nfrom __future__ import print_function\n\nfrom .__about__ import __version__, __author__, __author_email__, __website__\n\nfrom . import cli\nfrom .tools import (\n create_dict,\n decode,\n pybtex_to_dict,\n pybtex_to_bibtex_string,\n write,\n update,\n translate_month,\n)\nfrom .crossref import Crossref\nfrom .dblp import Dblp\nfrom .sync import sync\nfrom .journal_abbrev import journal_abbrev\nfrom .adapt_doi_urls import adapt_doi_urls\n\n__all__ = [\n \"__version__\",\n \"__author__\",\n \"__author_email__\",\n \"__website__\",\n \"cli\",\n \"create_dict\",\n \"decode\",\n \"pybtex_to_dict\",\n \"pybtex_to_bibtex_string\",\n \"write\",\n \"update\",\n \"translate_month\",\n \"Crossref\",\n \"Dblp\",\n \"sync\",\n \"journal_abbrev\",\n \"adapt_doi_urls\",\n]\n\ntry:\n import pipdate\nexcept ImportError:\n pass\nelse:\n if pipdate.needs_checking(__name__):\n print(pipdate.check(__name__, __version__), end=\"\")\n","sub_path":"betterbib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"263398048","text":"import opengraph\nfrom flask import Flask, request, jsonify\nimport urlcanon\n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n\nurl_db = {}\n\n\ndef get_canonized_url(url):\n return urlcanon.parse_url(url)\n\n\ndef scrape_page(og_obg):\n return {}\n\n\ndef get_url_record_by_url(db, url):\n for k, v in db.items():\n if v[\"url\"] == url:\n return [k, v]\n return None\n\n\ndef get_ogp_info(msg_id=None, url=None):\n if msg_id == None or url == None:\n return None\n rec = {}\n rec['url'] = url\n data = {}\n og = OpenGraph(\n url, [\"og:title\", \"article:published_time\", \"og:price:amount\"])\n\n # print(og.metadata)\n # print(og.metadata['title'])\n\n rec['og_obg'] = og\n # rec['valid'] = og.is_valid()\n return rec\n\n\nclass MyWebService:\n @app.route('/stories', methods=['GET'])\n def get_stories(msg_id=None):\n if msg_id == None:\n return ('no URL')\n elif msg_id in url_db:\n url_record = url_db[msg_id]\n return ('found')\n else:\n return ('No url %s ' % url)\n\n @app.route('/stories', methods=['POST'])\n def set_stories():\n url = request.args.get('url')\n print('url %s' % url)\n if url == None:\n return \"error\"\n else:\n c_url = get_canonized_url(url)\n exist_rec = get_url_record_by_url(url_db, c_url)\n if exist_rec:\n print(\"exist?\")\n return exist_rec[0]\n else:\n if len(url_db) == 0:\n print(\"no db\")\n msg_id = 1\n else:\n msg_id = max([int(_) for _ in url_db.keys()]) + 1\n print(msg_id)\n mdi = get_ogp_info(msg_id, c_url)\n url_db[msg_id] = mdi\n\n return mdi\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"653280946","text":"x = int(input(\"Enter what are you looking for?? \"))\r\n\r\narr = [5,8,4,9,2]\r\nk = 1\r\nfor i in arr:\r\n\r\n\r\n if i == x:\r\n print(str(i) + \" is in the list and it's position is \" +str(k) + \" in the list.\")\r\n break\r\n k += 1\r\n\r\n\r\nelse:\r\n print(str(x) +\" does not in the list.\")\r\n\r\n\r\nprint(\" \")\r\n# 2nd way by make a function.\r\n\r\nn = int(input(\"Enter any number: \"))\r\nx = \"\"\r\ndef search(n, list):\r\n for i in range(len(list)):\r\n if list[i] == n:\r\n globals()['x']=i\r\n return True\r\n\r\nlist = [1,2,3,4,5,6]\r\n\r\nif search(n, list):\r\n print(\"found at \", x+1)\r\n\r\nelse:\r\n print(\"Not found\")\r\n\r\n","sub_path":"72_linear_search_using_python.py","file_name":"72_linear_search_using_python.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"633232049","text":"# $ python3 exercise_I.py -small_mol SM.csv -cyclic_pep CP.csv\n\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Lasso\nfrom sklearn.ensemble import RandomForestRegressor as RFR\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom exercise_A import Draw_mol\nfrom exercise_C import RDKit_2D_descriptors, get_2D_desc\nfrom exercise_D import calc_lnka\n\nimport optuna\n\ndef objective(trial):\n \"\"\"\n search hyper parameter based on RMSE value (5-fold CV)\n \"\"\"\n\n # number of trees\n n_estimators = trial.suggest_int('n_estimators', 100, 1000)\n # min samples for dividing node\n min_samples_split = trial.suggest_int('min_samples_split', 2, 20)\n # min samples for making leaf\n min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 10)\n # num of features (if overfitting, recommend to decrease)\n max_features = trial.suggest_loguniform('max_features', 0.5, 1.)\n # max of node (if overfitting, recommend to decrease)\n max_leaf_nodes = trial.suggest_int('max_leaf_nodes', 100, 1000)\n # cost-complexity-pruning (if overfitting, recommend to increase)\n ccp_alpha = trial.suggest_loguniform('ccp_alpha', 1e-6, 1e-1)\n\n reg = RFR(n_estimators=n_estimators,\n \t min_samples_split=min_samples_split,\n \t min_samples_leaf=min_samples_leaf,\n \t max_features=max_features,\n \t max_leaf_nodes=max_leaf_nodes,\n \t oob_score=True,\n \t ccp_alpha=ccp_alpha,\n n_jobs=-1,\n random_state=0)\n \n rmse_list = cross_val_score(reg, X_sm, y_sm, scoring='neg_root_mean_squared_error', cv=5, n_jobs=-1)\n # convert neg_rmse value to positive \n return - np.array(rmse_list).mean()\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"construct regression model from Small molecule data\")\n parser.add_argument(\"-small_mol\", help=\"path to small molecule csv data\")\n parser.add_argument(\"-cyclic_pep\", help=\"path to cyclic peptide drug csv data\")\n args = parser.parse_args()\n if args.small_mol is None:\n print(parser.print_help())\n exit(1)\n if args.cyclic_pep is None:\n print(parser.print_help())\n exit(1)\n\n ##### exercise E step #####\n\n ##### 1. data preparation #####\n # read SM.csv\n df = pd.read_csv(args.small_mol)\n # make explanatory variable\n smiles = df['SMILES'].values\n # apply compute_2D_desc to each molecule\n X_sm = np.array([RDKit_2D_descriptors(mol).compute_2D_desc() for mol in smiles])\n # make response variable\n # apply calc_lnka to each PPB\n y_sm = df['PPB (fb)'].apply(calc_lnka).values\n # Standardization of explanatory variables\n sc = StandardScaler()\n X_sm = sc.fit_transform(X_sm)\n\n ##### 2. search hyper parameters using optuna #####\n study = optuna.create_study()\n study.optimize(objective, n_trials=100)\n # output result of searching hyper parameters\n print('Random Forest Regressor : Best Parameters')\n for key, value in study.best_params.items():\n \tprint(f'{key} = {value},')\n print('==================================================')\n\n ##### 3. output best parameters' result #####\n reg = RFR(**study.best_params)\n # 5-fold cross validation \n kf = KFold(n_splits=5, shuffle=True, random_state=0)\n # store each RMSE value and R value\n RMSE = []\n R = []\n for tr_index, val_index in kf.split(X_sm, y_sm):\n \t# split train data and validation data\n \tX_tr, X_val = X_sm[tr_index], X_sm[val_index]\n \ty_tr, y_val = y_sm[tr_index], y_sm[val_index]\n \treg.fit(X_tr, y_tr)\n \t# validate regressor\n \ty_pr = reg.predict(X_val)\n \t# root-MSE\n \tRMSE.append(np.sqrt(mean_squared_error(y_val, y_pr)))\n \t# not diagonal element of variance-covariance matrix\n \tR.append(np.corrcoef(y_val, y_pr)[0,1])\n print('RMSE (ln(K_a))')\n print(RMSE)\n print('R (ln(K_a))')\n print(R)\n\n # ====== * ===== * ===== * ===== #\n\n ##### exercise F step #####\n \n ##### 4. prepare cyclic peptide drug data #####\n\n # read CP.csv\n # the same variable for saving memory\n df = pd.read_csv(args.cyclic_pep)\n # make explanatory variable\n smiles = df['SMILES'].values\n # apply compute_2D_desc to each molecule\n X_cp = np.array([RDKit_2D_descriptors(mol).compute_2D_desc() for mol in smiles])\n # make response variable\n # apply calc_lnka to each PPB\n y_cp = df['PPB(fb)'].apply(calc_lnka).values\n # apply StandardScaler\n X_cp = sc.transform(X_cp)\n\n # train with small molecule data\n reg = RFR(**study.best_params)\n reg.fit(X_sm, y_sm)\n # prediction Cyclic peptide drug\n y_pred = reg.predict(X_cp)\n # calculate performance and output\n rmse = np.sqrt(mean_squared_error(y_cp, y_pred))\n r = np.corrcoef(y_cp, y_pred)[0,1]\n # check important descriptors\n # store 2D descriptors list\n desc_list = get_2D_desc()\n weight_list = reg.feature_importances_\n for desc, weight in zip(desc_list, weight_list):\n # if importances is larger than 0.02, then output descriptors and weight\n if abs(weight) > 0.02:\n print(f'[2D description name] : {desc}')\n print(f'[importances] : {weight}')\n print(\"===================================================\")\n print('RMSE (ln(K_a))')\n print(rmse)\n print('R (ln(K_a))')\n print(r)\n","sub_path":"exercise_I.py","file_name":"exercise_I.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"434437430","text":"class Solution(object):\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # import math\n # f = math.factorial(n)\n # def isPossible(x):\n # res = f % (10 ** x)\n # print(f\"{f} % {10 ** x} == 0 is {res == 0}\")\n # return res == 0\n\n # l = 0\n # r = n\n # while r - l > 1:\n # mid = (l + r) // 2\n # print(f\"({l} + {r}) // 2 = {mid}\")\n # if isPossible(mid):\n # l = mid\n # else:\n # r = mid\n # return l\n print(int(n))\n return 0 if n == 0 else n // 5 + self.trailingZeroes(n // 5)\n\ns = Solution()\nres = s.trailingZeroes(8836)\nprint(res)","sub_path":"lc/python3/172-factorial-trailing-zeroes.py","file_name":"172-factorial-trailing-zeroes.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"436476641","text":"import numpy as np\nimport math as m\nimport sys\nimport fnmatch\nfrom scipy import *\nimport pandas as pd\nimport re\nimport lmfit\nimport matplotlib.pyplot as plt\nfrom lmfit.models import GaussianModel\nfrom lmfit.models import SkewedGaussianModel\nfrom lmfit.models import VoigtModel\nfrom lmfit.models import QuadraticModel\nfrom lmfit.models import ExponentialGaussianModel\nfrom sklearn.cluster import MeanShift\n\ndef Calculator(xs, xserr, ys, yserr, cluster_of_interest):\n\n radius = np.sqrt(np.square(xs[cluster_of_interest]+1.94)+np.square(ys[cluster_of_interest]-3.77))\n radius = round(radius, 3)\n radius_uncertainty = np.sqrt(np.square(xserr[cluster_of_interest])+np.square(yserr[cluster_of_interest]))\n radius_uncertainty = round(radius_uncertainty, 3)\n\n angle = m.atan2(3.77-ys[cluster_of_interest],-1.94-xs[cluster_of_interest])\n angle_uncertainty = 1/(np.square(3.77-ys[cluster_of_interest])+np.square(-1.94-xs[cluster_of_interest]))*np.sqrt(np.square(-1.94-xs[cluster_of_interest])*np.square(0.05)+np.square(xs[cluster_of_interest]+1.94)*np.square(yserr[cluster_of_interest])+np.square(ys[cluster_of_interest]-3.77)*np.square(0.05)+np.square(3.77-ys[cluster_of_interest])*np.square(xserr[cluster_of_interest]))\n angle = round(angle, 3)\n angle_uncertainty = round(angle_uncertainty, 3)\n #print(rxs)\n\n return radius, radius_uncertainty, angle, angle_uncertainty\n\ndef Frequency(rxs, rxserr, rys, ryserr, rindex, mxs, mxserr, mys, myserr, mindex):\n\n frequency_guess = 781283.9864\n time = 345009\n\n rot_time = 1000000/frequency_guess\n N = int(round(time/rot_time))\n radius = np.sqrt(np.square(mxs[mindex]+1.94)+np.square(mys[mindex]-3.77))\n \n theta = m.atan2(3.77-mys[mindex],-1.94-mxs[mindex])-m.atan2(3.77-rys[rindex],-1.94-rxs[rindex])\n theta_uncertainty = 1/(np.square(3.77-mys[mindex])+np.square(-1.94-mxs[mindex]))*np.sqrt(np.square(-1.94-mxs[mindex])*np.square(0.05)+np.square(mxs[mindex]+1.94)*np.square(myserr[mindex])+np.square(mys[mindex]-3.77)*np.square(0.05)+np.square(3.77-mys[mindex])*np.square(mxserr[mindex]))\n if theta<0:\n theta = theta+2*pi\n N = N-1\n frequency = (theta+2*pi*N)/(2*pi*time*0.000001)\n frequency_uncertainty = np.sqrt(np.square(rys[rindex]*rxserr[rindex])+np.square(rxs[rindex]*ryserr[rindex])+np.square(rxs[rindex]*ryserr[rindex])+np.square(rys[rindex]*rxserr[rindex]))/(2*pi*radius*radius*time*0.000001)\n\n theta = round(theta, 3)\n theta_uncertainty = round(theta_uncertainty, 3)\n frequency = round(frequency, 4)\n frequency_uncertainty = round(frequency_uncertainty, 4)\n return N, theta, theta_uncertainty, frequency, frequency_uncertainty\n\ndef poswithtof(name, tlow, thigh, *args):\n\n data = pd.read_csv(name, sep = '\\t', names = ['chan', 'count', 'time', 'trig'], comment = '#')\n\n source = \"\".join(array(array(data.chan.values,int),str))\n pattern = \"12347\"\n c = source.count(pattern)\n res = [m.start() for m in re.finditer(pattern,source)]\n\n df = [data.iloc[i:i+5] for i in res]\n\n h = pd.concat(df,keys=res).reset_index()\n h.columns = [\"num1\",\"num2\",\"chan\",\"count\",\"time\",\"trig\"]\n\n df = pd.DataFrame([])\n\n df[\"x1\"] = h.set_index(\"num1\").query(\"chan==1\").time\n df[\"x2\"] = h.set_index(\"num1\").query(\"chan==2\").time\n df[\"y1\"] = h.set_index(\"num1\").query(\"chan==3\").time\n df[\"y2\"] = h.set_index(\"num1\").query(\"chan==4\").time\n df[\"tof\"] = h.set_index(\"num1\").query(\"chan==7\").time\n df[\"trig\"] = h.set_index(\"num1\").query(\"chan==7\").trig\n df['sumx'] = df['x1'] + df['x2']\n df['sumy'] = df['y1'] + df['y2']\n\n df = df.query('%f -1:\n xkeep.append(X[i][0])\n ykeep.append(X[i][1])\n return xs, xserr, ys, yserr, ips, xkeep, ykeep, X, n_clusters_, labels, cluster_center\n\ndef gaussmodel(xmin,xmax,data,numbin, *args):#clr):\n if len(args) == 0:\n clr = new_blue\n if len(args) == 1:\n clr = args[0]\n #xbins = plt.hist(data, bins = numbin, range = (xmin,xmax), alpha = 0.6, color = clr, histtype = 'stepfilled')\n xbins = plt.hist(data, bins = 6, range = (xmin,xmax), alpha = 0.6, color = clr, histtype = 'stepfilled')\n xcenter = (xbins[1][:-1] + xbins[1][1:])/2.0\n mod = GaussianModel()\n pars = mod.guess(xbins[0], x = xcenter)\n fit = mod.fit(xbins[0], x = xcenter, params = pars, method = 'leastsq')\n #print fit.fit_report()\n xfit = arange(xmin,xmax, 0.01)\n #plt.plot(xfit, fit.eval(x=xfit), 'k-')\n return fit.params['center'].value, fit.params['center'].stderr\n","sub_path":"Ugly First Pass Code/Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"262546600","text":"import types\nfrom abc import abstractmethod\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom uuid import uuid4\nfrom warnings import warn\n\nimport h5py\nimport numpy as np\nimport pandas as pd\n\nfrom .data_utils import DataIO, append_data, extend_data\nfrom .utils import (docval, get_docval, call_docval_func, getargs, ExtenderMeta, get_data_shape, fmt_docval_args,\n popargs, LabelledDict)\n\n\ndef _set_exp(cls):\n \"\"\"Set a class as being experimental\"\"\"\n cls._experimental = True\n\n\ndef _exp_warn_msg(cls):\n \"\"\"Generate a warning message experimental features\"\"\"\n pfx = cls\n if isinstance(cls, type):\n pfx = cls.__name__\n msg = ('%s is experimental -- it may be removed in the future and '\n 'is not guaranteed to maintain backward compatibility') % pfx\n return msg\n\n\nclass AbstractContainer(metaclass=ExtenderMeta):\n # The name of the class attribute that subclasses use to autogenerate properties\n # This parameterization is supplied in case users would like to configure\n # the class attribute name to something domain-specific\n\n _experimental = False\n\n _fieldsname = '__fields__'\n\n _data_type_attr = 'data_type'\n\n # Subclasses use this class attribute to add properties to autogenerate\n # Autogenerated properties will store values in self.__field_values\n __fields__ = tuple()\n\n # This field is automatically set by __gather_fields before initialization.\n # It holds all the values in __fields__ for this class and its parent classes.\n __fieldsconf = tuple()\n\n _pconf_allowed_keys = {'name', 'doc', 'settable'}\n\n # Override the _setter factor function, so directives that apply to\n # Container do not get used on Data\n @classmethod\n def _setter(cls, field):\n \"\"\"\n Make a setter function for creating a :py:func:`property`\n \"\"\"\n name = field['name']\n\n if not field.get('settable', True):\n return None\n\n def setter(self, val):\n if val is None:\n return\n if name in self.fields:\n msg = \"can't set attribute '%s' -- already set\" % name\n raise AttributeError(msg)\n self.fields[name] = val\n\n return setter\n\n @classmethod\n def _getter(cls, field):\n \"\"\"\n Make a getter function for creating a :py:func:`property`\n \"\"\"\n doc = field.get('doc')\n name = field['name']\n\n def getter(self):\n return self.fields.get(name)\n\n setattr(getter, '__doc__', doc)\n return getter\n\n @staticmethod\n def _check_field_spec(field):\n \"\"\"\n A helper function for __gather_fields to make sure we are always working\n with a dict specification and that the specification contains the correct keys\n \"\"\"\n tmp = field\n if isinstance(tmp, dict):\n if 'name' not in tmp:\n raise ValueError(\"must specify 'name' if using dict in __fields__\")\n else:\n tmp = {'name': tmp}\n return tmp\n\n @classmethod\n def _check_field_spec_keys(cls, field_conf):\n for k in field_conf:\n if k not in cls._pconf_allowed_keys:\n msg = (\"Unrecognized key '%s' in %s config '%s' on %s\"\n % (k, cls._fieldsname, field_conf['name'], cls.__name__))\n raise ValueError(msg)\n\n @classmethod\n def _get_fields(cls):\n return getattr(cls, cls._fieldsname)\n\n @classmethod\n def _set_fields(cls, value):\n return setattr(cls, cls._fieldsname, value)\n\n @classmethod\n def get_fields_conf(cls):\n return cls.__fieldsconf\n\n @ExtenderMeta.pre_init\n def __gather_fields(cls, name, bases, classdict):\n '''\n This classmethod will be called during class declaration in the metaclass to automatically\n create setters and getters for fields that need to be exported\n '''\n fields = cls._get_fields()\n if not isinstance(fields, tuple):\n msg = \"'%s' must be of type tuple\" % cls._fieldsname\n raise TypeError(msg)\n\n # check field specs and create map from field name to field conf dictionary\n fields_dict = OrderedDict()\n for f in fields:\n pconf = cls._check_field_spec(f)\n cls._check_field_spec_keys(pconf)\n fields_dict[pconf['name']] = pconf\n all_fields_conf = list(fields_dict.values())\n\n # check whether this class overrides __fields__\n if len(bases):\n # find highest base class that is an AbstractContainer (parent is higher than children)\n base_cls = None\n for base_cls in reversed(bases):\n if issubclass(base_cls, AbstractContainer):\n break\n\n base_fields = base_cls._get_fields() # tuple of field names from base class\n if base_fields is not fields:\n # check whether new fields spec already exists in base class\n fields_to_remove_from_base = list()\n for field_name in fields_dict:\n if field_name in base_fields:\n fields_to_remove_from_base.append(field_name)\n # prepend field specs from base class to fields list of this class\n # but only field specs that are not redefined in this class\n base_fields_conf = base_cls.get_fields_conf() # tuple of fields configurations from base class\n base_fields_conf_to_add = list()\n for pconf in base_fields_conf:\n if pconf['name'] not in fields_to_remove_from_base:\n base_fields_conf_to_add.append(pconf)\n all_fields_conf[0:0] = base_fields_conf_to_add\n\n # create getter and setter if attribute does not already exist\n # if 'doc' not specified in __fields__, use doc from docval of __init__\n docs = {dv['name']: dv['doc'] for dv in get_docval(cls.__init__)}\n for field_conf in all_fields_conf:\n pname = field_conf['name']\n field_conf.setdefault('doc', docs.get(pname))\n if not hasattr(cls, pname):\n setattr(cls, pname, property(cls._getter(field_conf), cls._setter(field_conf)))\n\n cls._set_fields(tuple(field_conf['name'] for field_conf in all_fields_conf))\n cls.__fieldsconf = tuple(all_fields_conf)\n\n def __new__(cls, *args, **kwargs):\n inst = super().__new__(cls)\n if cls._experimental:\n warn(_exp_warn_msg(cls))\n inst.__container_source = kwargs.pop('container_source', None)\n inst.__parent = None\n inst.__children = list()\n inst.__modified = True\n inst.__object_id = kwargs.pop('object_id', str(uuid4()))\n inst.parent = kwargs.pop('parent', None)\n return inst\n\n @docval({'name': 'name', 'type': str, 'doc': 'the name of this container'})\n def __init__(self, **kwargs):\n name = getargs('name', kwargs)\n if '/' in name:\n raise ValueError(\"name '\" + name + \"' cannot contain '/'\")\n self.__name = name\n self.__field_values = dict()\n\n @property\n def name(self):\n '''\n The name of this Container\n '''\n return self.__name\n\n @docval({'name': 'data_type', 'type': str, 'doc': 'the data_type to search for', 'default': None})\n def get_ancestor(self, **kwargs):\n \"\"\"\n Traverse parent hierarchy and return first instance of the specified data_type\n \"\"\"\n data_type = getargs('data_type', kwargs)\n if data_type is None:\n return self.parent\n p = self.parent\n while p is not None:\n if getattr(p, p._data_type_attr) == data_type:\n return p\n p = p.parent\n return None\n\n @property\n def fields(self):\n return self.__field_values\n\n @property\n def object_id(self):\n if self.__object_id is None:\n self.__object_id = str(uuid4())\n return self.__object_id\n\n @docval({'name': 'recurse', 'type': bool,\n 'doc': \"whether or not to change the object ID of this container's children\", 'default': True})\n def generate_new_id(self, **kwargs):\n \"\"\"Changes the object ID of this Container and all of its children to a new UUID string.\"\"\"\n recurse = getargs('recurse', kwargs)\n self.__object_id = str(uuid4())\n self.set_modified()\n if recurse:\n for c in self.children:\n c.generate_new_id(**kwargs)\n\n @property\n def modified(self):\n return self.__modified\n\n @docval({'name': 'modified', 'type': bool,\n 'doc': 'whether or not this Container has been modified', 'default': True})\n def set_modified(self, **kwargs):\n modified = getargs('modified', kwargs)\n self.__modified = modified\n if modified and isinstance(self.parent, Container):\n self.parent.set_modified()\n\n @property\n def children(self):\n return tuple(self.__children)\n\n @docval({'name': 'child', 'type': 'Container',\n 'doc': 'the child Container for this Container', 'default': None})\n def add_child(self, **kwargs):\n warn(DeprecationWarning('add_child is deprecated. Set the parent attribute instead.'))\n child = getargs('child', kwargs)\n if child is not None:\n # if child.parent is a Container, then the mismatch between child.parent and parent\n # is used to make a soft/external link from the parent to a child elsewhere\n # if child.parent is not a Container, it is either None or a Proxy and should be set to self\n if not isinstance(child.parent, AbstractContainer):\n # actually add the child to the parent in parent setter\n child.parent = self\n else:\n warn('Cannot add None as child to a container %s' % self.name)\n\n @classmethod\n def type_hierarchy(cls):\n return cls.__mro__\n\n @property\n def container_source(self):\n '''\n The source of this Container\n '''\n return self.__container_source\n\n @container_source.setter\n def container_source(self, source):\n if self.__container_source is not None:\n raise Exception('cannot reassign container_source')\n self.__container_source = source\n\n @property\n def parent(self):\n '''\n The parent Container of this Container\n '''\n # do it this way because __parent may not exist yet (not set in constructor)\n return getattr(self, '_AbstractContainer__parent', None)\n\n @parent.setter\n def parent(self, parent_container):\n if self.parent is parent_container:\n return\n\n if self.parent is not None:\n if isinstance(self.parent, AbstractContainer):\n raise ValueError(('Cannot reassign parent to Container: %s. '\n 'Parent is already: %s.' % (repr(self), repr(self.parent))))\n else:\n if parent_container is None:\n raise ValueError(\"Got None for parent of '%s' - cannot overwrite Proxy with NoneType\" % repr(self))\n # NOTE this assumes isinstance(parent_container, Proxy) but we get a circular import\n # if we try to do that\n if self.parent.matches(parent_container):\n self.__parent = parent_container\n parent_container.__children.append(self)\n parent_container.set_modified()\n else:\n self.__parent.add_candidate(parent_container)\n else:\n self.__parent = parent_container\n if isinstance(parent_container, Container):\n parent_container.__children.append(self)\n parent_container.set_modified()\n\n def _remove_child(self, child):\n \"\"\"Remove a child Container. Intended for use in subclasses that allow dynamic addition of child Containers.\"\"\"\n if not isinstance(child, AbstractContainer):\n raise ValueError('Cannot remove non-AbstractContainer object from children.')\n if child not in self.children:\n raise ValueError(\"%s '%s' is not a child of %s '%s'.\" % (child.__class__.__name__, child.name,\n self.__class__.__name__, self.name))\n child.__parent = None\n self.__children.remove(child)\n child.set_modified()\n self.set_modified()\n\n\nclass Container(AbstractContainer):\n \"\"\"A container that can contain other containers and has special functionality for printing.\"\"\"\n\n _pconf_allowed_keys = {'name', 'child', 'required_name', 'doc', 'settable'}\n\n @classmethod\n def _setter(cls, field):\n \"\"\"Returns a list of setter functions for the given field to be added to the class during class declaration.\"\"\"\n super_setter = AbstractContainer._setter(field)\n ret = [super_setter]\n # create setter with check for required name\n if field.get('required_name', None) is not None:\n name = field['required_name']\n idx1 = len(ret) - 1\n\n def container_setter(self, val):\n if val is not None:\n if not isinstance(val, AbstractContainer):\n msg = (\"Field '%s' on %s has a required name and must be a subclass of AbstractContainer.\"\n % (field['name'], self.__class__.__name__))\n raise ValueError(msg)\n if val.name != name:\n msg = (\"Field '%s' on %s must be named '%s'.\"\n % (field['name'], self.__class__.__name__, name))\n raise ValueError(msg)\n ret[idx1](self, val)\n\n ret.append(container_setter)\n\n # create setter that accepts a value or tuple, list, or dict or values and sets the value's parent to self\n if field.get('child', False):\n idx2 = len(ret) - 1\n\n def container_setter(self, val):\n ret[idx2](self, val)\n if val is not None:\n if isinstance(val, (tuple, list)):\n pass\n elif isinstance(val, dict):\n val = val.values()\n else:\n val = [val]\n for v in val:\n if not isinstance(v.parent, Container):\n v.parent = self\n # else, the ObjectMapper will create a link from self (parent) to v (child with existing\n # parent)\n\n ret.append(container_setter)\n return ret[-1]\n\n def __repr__(self):\n cls = self.__class__\n template = \"%s %s.%s at 0x%d\" % (self.name, cls.__module__, cls.__name__, id(self))\n if len(self.fields):\n template += \"\\nFields:\\n\"\n for k in sorted(self.fields): # sorted to enable tests\n v = self.fields[k]\n # if isinstance(v, DataIO) or not hasattr(v, '__len__') or len(v) > 0:\n if hasattr(v, '__len__'):\n if isinstance(v, (np.ndarray, list, tuple)):\n if len(v) > 0:\n template += \" {}: {}\\n\".format(k, self.__smart_str(v, 1))\n elif v:\n template += \" {}: {}\\n\".format(k, self.__smart_str(v, 1))\n else:\n template += \" {}: {}\\n\".format(k, v)\n return template\n\n @staticmethod\n def __smart_str(v, num_indent):\n \"\"\"\n Print compact string representation of data.\n\n If v is a list, try to print it using numpy. This will condense the string\n representation of datasets with many elements. If that doesn't work, just print the list.\n\n If v is a dictionary, print the name and type of each element\n\n If v is a set, print it sorted\n\n If v is a neurodata_type, print the name of type\n\n Otherwise, use the built-in str()\n Parameters\n ----------\n v\n\n Returns\n -------\n str\n\n \"\"\"\n\n if isinstance(v, list) or isinstance(v, tuple):\n if len(v) and isinstance(v[0], AbstractContainer):\n return Container.__smart_str_list(v, num_indent, '(')\n try:\n return str(np.asarray(v))\n except ValueError:\n return Container.__smart_str_list(v, num_indent, '(')\n elif isinstance(v, dict):\n return Container.__smart_str_dict(v, num_indent)\n elif isinstance(v, set):\n return Container.__smart_str_list(sorted(list(v)), num_indent, '{')\n elif isinstance(v, AbstractContainer):\n return \"{} {}\".format(getattr(v, 'name'), type(v))\n else:\n return str(v)\n\n @staticmethod\n def __smart_str_list(str_list, num_indent, left_br):\n if left_br == '(':\n right_br = ')'\n if left_br == '{':\n right_br = '}'\n if len(str_list) == 0:\n return left_br + ' ' + right_br\n indent = num_indent * 2 * ' '\n indent_in = (num_indent + 1) * 2 * ' '\n out = left_br\n for v in str_list[:-1]:\n out += '\\n' + indent_in + Container.__smart_str(v, num_indent + 1) + ','\n if str_list:\n out += '\\n' + indent_in + Container.__smart_str(str_list[-1], num_indent + 1)\n out += '\\n' + indent + right_br\n return out\n\n @staticmethod\n def __smart_str_dict(d, num_indent):\n left_br = '{'\n right_br = '}'\n if len(d) == 0:\n return left_br + ' ' + right_br\n indent = num_indent * 2 * ' '\n indent_in = (num_indent + 1) * 2 * ' '\n out = left_br\n keys = sorted(list(d.keys()))\n for k in keys[:-1]:\n out += '\\n' + indent_in + Container.__smart_str(k, num_indent + 1) + ' ' + str(type(d[k])) + ','\n if keys:\n out += '\\n' + indent_in + Container.__smart_str(keys[-1], num_indent + 1) + ' ' + str(type(d[keys[-1]]))\n out += '\\n' + indent + right_br\n return out\n\n\nclass Data(AbstractContainer):\n \"\"\"\n A class for representing dataset containers\n \"\"\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'the name of this container'},\n {'name': 'data', 'type': ('scalar_data', 'array_data', 'data'), 'doc': 'the source of the data'})\n def __init__(self, **kwargs):\n call_docval_func(super().__init__, kwargs)\n self.__data = getargs('data', kwargs)\n\n @property\n def data(self):\n return self.__data\n\n @property\n def shape(self):\n \"\"\"\n Get the shape of the data represented by this container\n :return: Shape tuple\n :rtype: tuple of ints\n \"\"\"\n return get_data_shape(self.__data)\n\n @docval({'name': 'dataio', 'type': DataIO, 'doc': 'the DataIO to apply to the data held by this Data'})\n def set_dataio(self, **kwargs):\n \"\"\"\n Apply DataIO object to the data held by this Data object\n \"\"\"\n dataio = getargs('dataio', kwargs)\n dataio.data = self.__data\n self.__data = dataio\n\n @docval({'name': 'func', 'type': types.FunctionType, 'doc': 'a function to transform *data*'})\n def transform(self, **kwargs):\n \"\"\"\n Transform data from the current underlying state.\n\n This function can be used to permanently load data from disk, or convert to a different\n representation, such as a torch.Tensor\n \"\"\"\n func = getargs('func', kwargs)\n self.__data = func(self.__data)\n return self\n\n def __bool__(self):\n if self.data is not None:\n if isinstance(self.data, (np.ndarray, tuple, list)):\n return len(self.data) != 0\n if self.data:\n return True\n return False\n\n def __len__(self):\n return len(self.__data)\n\n def __getitem__(self, args):\n return self.get(args)\n\n def get(self, args):\n if isinstance(self.data, (tuple, list)) and isinstance(args, (tuple, list, np.ndarray)):\n return [self.data[i] for i in args]\n if isinstance(self.data, h5py.Dataset) and isinstance(args, np.ndarray):\n # This is needed for h5py 2.9 compatability\n args = args.tolist()\n return self.data[args]\n\n def append(self, arg):\n self.__data = append_data(self.__data, arg)\n\n def extend(self, arg):\n self.__data = extend_data(self.__data, arg)\n\n\nclass DataRegion(Data):\n\n @property\n @abstractmethod\n def data(self):\n '''\n The target data that this region applies to\n '''\n pass\n\n @property\n @abstractmethod\n def region(self):\n '''\n The region that indexes into data e.g. slice or list of indices\n '''\n pass\n\n\ndef _not_parent(arg):\n return arg['name'] != 'parent'\n\n\nclass MultiContainerInterface(Container):\n \"\"\"Class that dynamically defines methods to support a Container holding multiple Containers of the same type.\n\n To use, extend this class and create a dictionary as a class attribute with any of the following keys:\n * 'attr' to name the attribute that stores the Container instances\n * 'type' to provide the Container object type (type or list/tuple of types, type can be a docval macro)\n * 'add' to name the method for adding Container instances\n * 'get' to name the method for getting Container instances\n * 'create' to name the method for creating Container instances (only if a single type is specified)\n\n If the attribute does not exist in the class, it will be generated. If it does exist, it should behave like a dict.\n\n The keys 'attr', 'type', and 'add' are required.\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n if cls is MultiContainerInterface:\n raise TypeError(\"Can't instantiate class MultiContainerInterface.\")\n if not hasattr(cls, '__clsconf__'):\n raise TypeError(\"MultiContainerInterface subclass %s is missing __clsconf__ attribute. Please check that \"\n \"the class is properly defined.\" % cls.__name__)\n return super().__new__(cls, *args, **kwargs)\n\n @staticmethod\n def __add_article(noun):\n if isinstance(noun, tuple):\n noun = noun[0]\n if isinstance(noun, type):\n noun = noun.__name__\n if noun[0] in ('aeiouAEIOU'):\n return 'an %s' % noun\n return 'a %s' % noun\n\n @staticmethod\n def __join(argtype):\n \"\"\"Return a grammatical string representation of a list or tuple of classes or text.\n\n Examples:\n cls.__join(Container) returns \"Container\"\n cls.__join((Container, )) returns \"Container\"\n cls.__join((Container, Data)) returns \"Container or Data\"\n cls.__join((Container, Data, Subcontainer)) returns \"Container, Data, or Subcontainer\"\n \"\"\"\n\n def tostr(x):\n return x.__name__ if isinstance(x, type) else x\n\n if isinstance(argtype, (list, tuple)):\n args_str = [tostr(x) for x in argtype]\n if len(args_str) == 1:\n return args_str[0]\n if len(args_str) == 2:\n return \" or \".join(tostr(x) for x in args_str)\n else:\n return \", \".join(tostr(x) for x in args_str[:-1]) + ', or ' + args_str[-1]\n else:\n return tostr(argtype)\n\n @classmethod\n def __make_get(cls, func_name, attr_name, container_type):\n doc = \"Get %s from this %s\" % (cls.__add_article(container_type), cls.__name__)\n\n @docval({'name': 'name', 'type': str, 'doc': 'the name of the %s' % cls.__join(container_type),\n 'default': None},\n rtype=container_type, returns='the %s with the given name' % cls.__join(container_type),\n func_name=func_name, doc=doc)\n def _func(self, **kwargs):\n name = getargs('name', kwargs)\n d = getattr(self, attr_name)\n ret = None\n if name is None:\n if len(d) > 1:\n msg = (\"More than one element in %s of %s '%s' -- must specify a name.\"\n % (attr_name, cls.__name__, self.name))\n raise ValueError(msg)\n elif len(d) == 0:\n msg = \"%s of %s '%s' is empty.\" % (attr_name, cls.__name__, self.name)\n raise ValueError(msg)\n else: # only one item in dict\n for v in d.values():\n ret = v\n else:\n ret = d.get(name)\n if ret is None:\n msg = \"'%s' not found in %s of %s '%s'.\" % (name, attr_name, cls.__name__, self.name)\n raise KeyError(msg)\n return ret\n\n return _func\n\n @classmethod\n def __make_getitem(cls, attr_name, container_type):\n doc = \"Get %s from this %s\" % (cls.__add_article(container_type), cls.__name__)\n\n @docval({'name': 'name', 'type': str, 'doc': 'the name of the %s' % cls.__join(container_type),\n 'default': None},\n rtype=container_type, returns='the %s with the given name' % cls.__join(container_type),\n func_name='__getitem__', doc=doc)\n def _func(self, **kwargs):\n # NOTE this is the same code as the getter but with different error messages\n name = getargs('name', kwargs)\n d = getattr(self, attr_name)\n ret = None\n if name is None:\n if len(d) > 1:\n msg = (\"More than one %s in %s '%s' -- must specify a name.\"\n % (cls.__join(container_type), cls.__name__, self.name))\n raise ValueError(msg)\n elif len(d) == 0:\n msg = \"%s '%s' is empty.\" % (cls.__name__, self.name)\n raise ValueError(msg)\n else: # only one item in dict\n for v in d.values():\n ret = v\n else:\n ret = d.get(name)\n if ret is None:\n msg = \"'%s' not found in %s '%s'.\" % (name, cls.__name__, self.name)\n raise KeyError(msg)\n return ret\n\n return _func\n\n @classmethod\n def __make_add(cls, func_name, attr_name, container_type):\n doc = \"Add %s to this %s\" % (cls.__add_article(container_type), cls.__name__)\n\n @docval({'name': attr_name, 'type': (list, tuple, dict, container_type),\n 'doc': 'the %s to add' % cls.__join(container_type)},\n func_name=func_name, doc=doc)\n def _func(self, **kwargs):\n container = getargs(attr_name, kwargs)\n if isinstance(container, container_type):\n containers = [container]\n elif isinstance(container, dict):\n containers = container.values()\n else:\n containers = container\n d = getattr(self, attr_name)\n for tmp in containers:\n if not isinstance(tmp.parent, Container):\n tmp.parent = self\n # else, the ObjectMapper will create a link from self (parent) to tmp (child with existing parent)\n if tmp.name in d:\n msg = \"'%s' already exists in %s '%s'\" % (tmp.name, cls.__name__, self.name)\n raise ValueError(msg)\n d[tmp.name] = tmp\n return container\n\n return _func\n\n @classmethod\n def __make_create(cls, func_name, add_name, container_type):\n doc = \"Create %s and add it to this %s\" % (cls.__add_article(container_type), cls.__name__)\n\n @docval(*filter(_not_parent, get_docval(container_type.__init__)), func_name=func_name, doc=doc,\n returns=\"the %s object that was created\" % cls.__join(container_type), rtype=container_type)\n def _func(self, **kwargs):\n cargs, ckwargs = fmt_docval_args(container_type.__init__, kwargs)\n ret = container_type(*cargs, **ckwargs)\n getattr(self, add_name)(ret)\n return ret\n\n return _func\n\n @classmethod\n def __make_constructor(cls, clsconf):\n args = list()\n for conf in clsconf:\n attr_name = conf['attr']\n container_type = conf['type']\n args.append({'name': attr_name, 'type': (list, tuple, dict, container_type),\n 'doc': '%s to store in this interface' % cls.__join(container_type), 'default': dict()})\n\n args.append({'name': 'name', 'type': str, 'doc': 'the name of this container', 'default': cls.__name__})\n\n @docval(*args, func_name='__init__')\n def _func(self, **kwargs):\n call_docval_func(super(cls, self).__init__, kwargs)\n for conf in clsconf:\n attr_name = conf['attr']\n add_name = conf['add']\n container = popargs(attr_name, kwargs)\n add = getattr(self, add_name)\n add(container)\n\n return _func\n\n @classmethod\n def __make_getter(cls, attr):\n \"\"\"Make a getter function for creating a :py:func:`property`\"\"\"\n\n def _func(self):\n # initialize the field to an empty labeled dict if it has not yet been\n # do this here to avoid creating default __init__ which may or may not be overridden in\n # custom classes and dynamically generated classes\n if attr not in self.fields:\n def _remove_child(child):\n if child.parent is self:\n self._remove_child(child)\n self.fields[attr] = LabelledDict(attr, remove_callable=_remove_child)\n\n return self.fields.get(attr)\n\n return _func\n\n @classmethod\n def __make_setter(cls, add_name):\n \"\"\"Make a setter function for creating a :py:func:`property`\"\"\"\n\n @docval({'name': 'val', 'type': (list, tuple, dict), 'doc': 'the sub items to add', 'default': None})\n def _func(self, **kwargs):\n val = getargs('val', kwargs)\n if val is None:\n return\n getattr(self, add_name)(val)\n\n return _func\n\n @ExtenderMeta.pre_init\n def __build_class(cls, name, bases, classdict):\n \"\"\"Verify __clsconf__ and create methods based on __clsconf__.\n This method is called prior to __new__ and __init__ during class declaration in the metaclass.\n \"\"\"\n if not hasattr(cls, '__clsconf__'):\n return\n\n multi = False\n if isinstance(cls.__clsconf__, dict):\n clsconf = [cls.__clsconf__]\n elif isinstance(cls.__clsconf__, list):\n multi = True\n clsconf = cls.__clsconf__\n else:\n raise TypeError(\"'__clsconf__' for MultiContainerInterface subclass %s must be a dict or a list of \"\n \"dicts.\" % cls.__name__)\n\n for conf_index, conf_dict in enumerate(clsconf):\n cls.__build_conf_methods(conf_dict, conf_index, multi)\n\n # make __getitem__ (square bracket access) only if one conf type is defined\n if len(clsconf) == 1:\n attr = clsconf[0].get('attr')\n container_type = clsconf[0].get('type')\n setattr(cls, '__getitem__', cls.__make_getitem(attr, container_type))\n\n # create the constructor, only if it has not been overridden\n # i.e. it is the same method as the parent class constructor\n if '__init__' not in cls.__dict__:\n setattr(cls, '__init__', cls.__make_constructor(clsconf))\n\n @classmethod\n def __build_conf_methods(cls, conf_dict, conf_index, multi):\n # get add method name\n add = conf_dict.get('add')\n if add is None:\n msg = \"MultiContainerInterface subclass %s is missing 'add' key in __clsconf__\" % cls.__name__\n if multi:\n msg += \" at index %d\" % conf_index\n raise ValueError(msg)\n\n # get container attribute name\n attr = conf_dict.get('attr')\n if attr is None:\n msg = \"MultiContainerInterface subclass %s is missing 'attr' key in __clsconf__\" % cls.__name__\n if multi:\n msg += \" at index %d\" % conf_index\n raise ValueError(msg)\n\n # get container type\n container_type = conf_dict.get('type')\n if container_type is None:\n msg = \"MultiContainerInterface subclass %s is missing 'type' key in __clsconf__\" % cls.__name__\n if multi:\n msg += \" at index %d\" % conf_index\n raise ValueError(msg)\n\n # create property with the name given in 'attr' only if the attribute is not already defined\n if not hasattr(cls, attr):\n getter = cls.__make_getter(attr)\n setter = cls.__make_setter(add)\n doc = \"a dictionary containing the %s in this %s\" % (cls.__join(container_type), cls.__name__)\n setattr(cls, attr, property(getter, setter, None, doc))\n\n # create the add method\n setattr(cls, add, cls.__make_add(add, attr, container_type))\n\n # create the create method, only if a single container type is specified\n create = conf_dict.get('create')\n if create is not None:\n if isinstance(container_type, type):\n setattr(cls, create, cls.__make_create(create, add, container_type))\n else:\n msg = (\"Cannot specify 'create' key in __clsconf__ for MultiContainerInterface subclass %s \"\n \"when 'type' key is not a single type\") % cls.__name__\n if multi:\n msg += \" at index %d\" % conf_index\n raise ValueError(msg)\n\n # create the get method\n get = conf_dict.get('get')\n if get is not None:\n setattr(cls, get, cls.__make_get(get, attr, container_type))\n\n\nclass Row(object, metaclass=ExtenderMeta):\n \"\"\"\n A class for representing rows from a Table.\n\n The Table class can be indicated with the __table__. Doing so\n will set constructor arguments for the Row class and ensure that\n Row.idx is set appropriately when a Row is added to the Table. It will\n also add functionality to the Table class for getting Row objects.\n\n Note, the Row class is not needed for working with Table objects. This\n is merely convenience functionality for working with Tables.\n \"\"\"\n\n __table__ = None\n\n @property\n def idx(self):\n \"\"\"The index of this row in its respective Table\"\"\"\n return self.__idx\n\n @idx.setter\n def idx(self, val):\n if self.__idx is None:\n self.__idx = val\n else:\n raise ValueError(\"cannot reset the ID of a row object\")\n\n @property\n def table(self):\n \"\"\"The Table this Row comes from\"\"\"\n return self.__table\n\n @table.setter\n def table(self, val):\n if val is not None:\n self.__table = val\n if self.idx is None:\n self.idx = self.__table.add_row(**self.todict())\n\n @ExtenderMeta.pre_init\n def __build_row_class(cls, name, bases, classdict):\n table_cls = getattr(cls, '__table__', None)\n if table_cls is not None:\n columns = getattr(table_cls, '__columns__')\n if cls.__init__ == bases[-1].__init__: # check if __init__ is overridden\n columns = deepcopy(columns)\n func_args = list()\n for col in columns:\n func_args.append(col)\n func_args.append({'name': 'table', 'type': Table, 'default': None,\n 'help': 'the table this row is from'})\n func_args.append({'name': 'idx', 'type': int, 'default': None,\n 'help': 'the index for this row'})\n\n @docval(*func_args)\n def __init__(self, **kwargs):\n super(cls, self).__init__()\n table, idx = popargs('table', 'idx', kwargs)\n self.__keys = list()\n self.__idx = None\n self.__table = None\n for k, v in kwargs.items():\n self.__keys.append(k)\n setattr(self, k, v)\n self.idx = idx\n self.table = table\n\n setattr(cls, '__init__', __init__)\n\n def todict(self):\n return {k: getattr(self, k) for k in self.__keys}\n\n setattr(cls, 'todict', todict)\n\n # set this so Table.row gets set when a Table is instantiated\n table_cls.__rowclass__ = cls\n else:\n if bases != (object,):\n raise ValueError('__table__ must be set if sub-classing Row')\n\n def __eq__(self, other):\n return self.idx == other.idx and self.table is other.table\n\n\nclass RowGetter:\n \"\"\"\n A simple class for providing __getitem__ functionality that returns\n Row objects to a Table.\n \"\"\"\n\n def __init__(self, table):\n self.table = table\n self.cache = dict()\n\n def __getitem__(self, idx):\n ret = self.cache.get(idx)\n if ret is None:\n row = self.table[idx]\n ret = self.table.__rowclass__(*row, table=self.table, idx=idx)\n self.cache[idx] = ret\n return ret\n\n\nclass Table(Data):\n r'''\n Subclasses should specify the class attribute \\_\\_columns\\_\\_.\n\n This should be a list of dictionaries with the following keys:\n\n - ``name`` the column name\n - ``type`` the type of data in this column\n - ``doc`` a brief description of what gets stored in this column\n\n For reference, this list of dictionaries will be used with docval to autogenerate\n the ``add_row`` method for adding data to this table.\n\n If \\_\\_columns\\_\\_ is not specified, no custom ``add_row`` method will be added.\n\n The class attribute __defaultname__ can also be set to specify a default name\n for the table class. If \\_\\_defaultname\\_\\_ is not specified, then ``name`` will\n need to be specified when the class is instantiated.\n\n A Table class can be paired with a Row class for conveniently working with rows of\n a Table. This pairing must be indicated in the Row class implementation. See Row\n for more details.\n '''\n\n # This class attribute is used to indicate which Row class should be used when\n # adding RowGetter functionality to the Table.\n __rowclass__ = None\n\n @ExtenderMeta.pre_init\n def __build_table_class(cls, name, bases, classdict):\n if hasattr(cls, '__columns__'):\n columns = getattr(cls, '__columns__')\n\n idx = dict()\n for i, col in enumerate(columns):\n idx[col['name']] = i\n setattr(cls, '__colidx__', idx)\n\n if cls.__init__ == bases[-1].__init__: # check if __init__ is overridden\n name = {'name': 'name', 'type': str, 'doc': 'the name of this table'}\n defname = getattr(cls, '__defaultname__', None)\n if defname is not None:\n name['default'] = defname\n\n @docval(name,\n {'name': 'data', 'type': ('array_data', 'data'), 'doc': 'the data in this table',\n 'default': list()})\n def __init__(self, **kwargs):\n name, data = getargs('name', 'data', kwargs)\n colnames = [i['name'] for i in columns]\n super(cls, self).__init__(colnames, name, data)\n\n setattr(cls, '__init__', __init__)\n\n if cls.add_row == bases[-1].add_row: # check if add_row is overridden\n\n @docval(*columns)\n def add_row(self, **kwargs):\n return super(cls, self).add_row(kwargs)\n\n setattr(cls, 'add_row', add_row)\n\n @docval({'name': 'columns', 'type': (list, tuple), 'doc': 'a list of the columns in this table'},\n {'name': 'name', 'type': str, 'doc': 'the name of this container'},\n {'name': 'data', 'type': ('array_data', 'data'), 'doc': 'the source of the data', 'default': list()})\n def __init__(self, **kwargs):\n self.__columns = tuple(popargs('columns', kwargs))\n self.__col_index = {name: idx for idx, name in enumerate(self.__columns)}\n if getattr(self, '__rowclass__') is not None:\n self.row = RowGetter(self)\n call_docval_func(super(Table, self).__init__, kwargs)\n\n @property\n def columns(self):\n return self.__columns\n\n @docval({'name': 'values', 'type': dict, 'doc': 'the values for each column'})\n def add_row(self, **kwargs):\n values = getargs('values', kwargs)\n if not isinstance(self.data, list):\n msg = 'Cannot append row to %s' % type(self.data)\n raise ValueError(msg)\n ret = len(self.data)\n row = [values[col] for col in self.columns]\n row = [v.idx if isinstance(v, Row) else v for v in row]\n self.data.append(tuple(row))\n return ret\n\n def which(self, **kwargs):\n '''\n Query a table\n '''\n if len(kwargs) != 1:\n raise ValueError(\"only one column can be queried\")\n colname, value = kwargs.popitem()\n idx = self.__colidx__.get(colname)\n if idx is None:\n msg = \"no '%s' column in %s\" % (colname, self.__class__.__name__)\n raise KeyError(msg)\n ret = list()\n for i in range(len(self.data)):\n row = self.data[i]\n row_val = row[idx]\n if row_val == value:\n ret.append(i)\n return ret\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, args):\n idx = args\n col = None\n if isinstance(args, tuple):\n idx = args[1]\n if isinstance(args[0], str):\n col = self.__col_index.get(args[0])\n elif isinstance(args[0], int):\n col = args[0]\n else:\n raise KeyError('first argument must be a column name or index')\n return self.data[idx][col]\n elif isinstance(args, str):\n col = self.__col_index.get(args)\n if col is None:\n raise KeyError(args)\n return [row[col] for row in self.data]\n else:\n return self.data[idx]\n\n def to_dataframe(self):\n '''Produce a pandas DataFrame containing this table's data.\n '''\n\n data = {colname: self[colname] for ii, colname in enumerate(self.columns)}\n return pd.DataFrame(data)\n\n @classmethod\n @docval(\n {'name': 'df', 'type': pd.DataFrame, 'doc': 'input data'},\n {'name': 'name', 'type': str, 'doc': 'the name of this container', 'default': None},\n {\n 'name': 'extra_ok',\n 'type': bool,\n 'doc': 'accept (and ignore) unexpected columns on the input dataframe',\n 'default': False\n },\n )\n def from_dataframe(cls, **kwargs):\n '''Construct an instance of Table (or a subclass) from a pandas DataFrame. The columns of the dataframe\n should match the columns defined on the Table subclass.\n '''\n\n df, name, extra_ok = getargs('df', 'name', 'extra_ok', kwargs)\n\n cls_cols = list([col['name'] for col in getattr(cls, '__columns__')])\n df_cols = list(df.columns)\n\n missing_columns = set(cls_cols) - set(df_cols)\n extra_columns = set(df_cols) - set(cls_cols)\n\n if extra_columns:\n raise ValueError(\n 'unrecognized column(s) {} for table class {} (columns {})'.format(\n extra_columns, cls.__name__, cls_cols\n )\n )\n\n use_index = False\n if len(missing_columns) == 1 and list(missing_columns)[0] == df.index.name:\n use_index = True\n\n elif missing_columns:\n raise ValueError(\n 'missing column(s) {} for table class {} (columns {}, provided {})'.format(\n missing_columns, cls.__name__, cls_cols, df_cols\n )\n )\n\n data = []\n for index, row in df.iterrows():\n if use_index:\n data.append([\n row[colname] if colname != df.index.name else index\n for colname in cls_cols\n ])\n else:\n data.append(tuple([row[colname] for colname in cls_cols]))\n\n if name is None:\n return cls(data=data)\n return cls(name=name, data=data)\n","sub_path":"src/hdmf/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":44973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"240166856","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport math\n\nfrom wx.lib.plot import *\nimport wx\nimport numpy\n\nfrom gui.md_3d_canvas import Md3DCanvas\nfrom libpy.modan_dbclass import MdDatasetView\nfrom libpy.mdstatistics import MdPrincipalComponent2\nfrom libpy.mdstatistics import MdCanonicalVariate\nfrom libpy.mdstatistics import MdManova\nfrom libpy.modan_exception import MdException\nuse_mplot = False\n\nCONST = {}\nCONST['DIALOG_SIZE'] = wx.Size(1024, 768)\nCONST['IDX_BOOKSTEIN'] = 0\nCONST['IDX_SBR'] = 1\nCONST['IDX_GLS'] = 2\nCONST['IDX_RFTRA'] = 3\n\nCONTROL_ID = {}\nCONTROL_ID['ID_CHK_AUTO_ROTATE'] = 2021\nCONTROL_ID['ID_CHK_SHOW_INDEX'] = 2022\nCONTROL_ID['ID_CHK_SHOW_WIREFRAME'] = 2023\nCONTROL_ID['ID_CHK_SHOW_MEANSHAPE'] = 2024\nCONTROL_ID['ID_EIGENVALUE_LISTCTRL'] = 2025\nCONTROL_ID['ID_LOADING_LISTCTRL'] = 2026\nCONTROL_ID['ID_RAWDATA_LISTCTRL'] = 2027\nCONTROL_ID['ID_SUPERIMPOSED_LISTCTRL'] = 2028\nCONTROL_ID['ID_FINALCOORDINATES_LISTCTRL'] = 2029\n\nCONTROL_ID['ID_RADIO_SUPERIMPOSITION'] = 2031\nCONTROL_ID['ID_OBJECT_LISTCTRL'] = 2032\nCONTROL_ID['ID_ANALYZE_BUTTON'] = 2033\n\nCONTROL_ID['ID_XAXIS_COMBO'] = 2041\nCONTROL_ID['ID_YAXIS_COMBO'] = 2042\nCONTROL_ID['ID_ZAXIS_COMBO'] = 2043\n\n\n\n# if( half_len == len_arr ):\n\nclass MdPlotter(wx.Window):\n def __init__(self, parent, id):\n wx.Window.__init__(self, parent, id)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.SetBackgroundColour('#aaaaaa')\n self.SetSize((400, 400))\n self.buffer = wx.BitmapFromImage(wx.EmptyImage(400, 400))\n self.x_margin = 20\n self.y_margin = 20\n self.scale = -1\n self.axis_1 = 0\n self.axis_2 = 1\n\n def AdjustScale(self):\n self.width = self.GetSize().width\n self.height = self.GetSize().height\n max_x = -99999\n max_y = -99999\n\n for mdobject in self.dataset.object_list:\n x, y = mdobject.coords[self.axis_1], mdobject.coords[self.axis_2]\n #print x,y\n max_x = max(math.fabs(x), max_x)\n max_y = max(math.fabs(y), max_y)\n\n #print \"max\", max_x, max_y\n self.max_x = max_x\n self.max_y = max_y\n\n available_x = self.width - self.x_margin * 2\n available_y = self.height - self.y_margin * 2\n #print \"avail wxh\", w, h\n scale_x = ( available_x ) / ( max_x * 2 )\n scale_y = ( available_y ) / ( max_y * 2 )\n\n #print \"scale\", scale_x, scale_y\n self.scale = min(scale_x, scale_y)\n #print \"final scale\", self.scale\n\n x_scale = self.max_x\n x_order = 0\n while x_scale < 1:\n x_scale *= 10\n x_order -= 1\n while x_scale > 10:\n x_scale /= 10\n x_order += 1\n\n #print x_scale, x_order\n\n upper_x = math.ceil(x_scale)\n if x_scale < 3:\n step = 0.5\n temp_x = 0\n else:\n step = 1\n temp_x = 0\n scales = []\n while temp_x <= upper_x:\n scales.append(temp_x * ( 10 ** (x_order) ))\n scales.append(temp_x * -1 * ( 10 ** (x_order) ))\n temp_x += step\n\n self.x_scales = scales\n\n #print \"x scales\", self.x_scales\n\n y_scale = self.max_y\n y_order = 0\n while y_scale < 1:\n y_scale *= 10\n y_order -= 1\n while y_scale > 10:\n y_scale /= 10\n y_order += 1\n\n #print y_scale, y_order\n\n upper_y = math.ceil(y_scale)\n if y_scale < 3:\n step = 0.5\n temp_y = 0\n else:\n step = 1\n temp_y = 0\n scales = []\n while temp_y <= upper_y:\n scales.append(temp_y * ( 10 ** (y_order) ))\n scales.append(temp_y * -1 * ( 10 ** (y_order) ))\n temp_y += step\n\n self.y_scales = scales\n\n #print \"y scales\", self.y_scales\n\n\n def GraphXYtoScreenXY(self, x, y):\n new_x = int(math.floor(float(x) * self.scale + 0.5)) + math.floor(self.width / 2 + 0.5)\n new_y = int(math.floor(float(-1.0 * y) * self.scale + 0.5)) + math.floor(self.height / 2 + 0.5)\n return new_x, new_y\n\n def ScreenXYtoGraphXY(self, x, y):\n new_x = float(x) / self.scale\n new_y = float(y) / self.scale\n return new_x, new_y\n\n def DrawToBuffer(self):\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\n dc.SetBackground(wx.GREY_BRUSH)\n dc.Clear()\n\n ''' Draw Axes '''\n dc.SetPen(wx.Pen(\"black\", 1))\n y = int(self.height - self.y_margin)\n\n dc.DrawLine(self.x_margin, y, self.width, y)\n for x in self.x_scales:\n scr_x, temp_y = self.GraphXYtoScreenXY(x, 0)\n if scr_x > 0 and scr_x < self.width:\n dc.DrawLine(scr_x, y, scr_x, y - int(self.y_margin / 2))\n dc.DrawText(str(x), scr_x - 5, y)\n\n x = self.x_margin\n dc.DrawLine(x, 0, x, self.height - self.y_margin)\n for y in self.y_scales:\n temp_x, scr_y = self.GraphXYtoScreenXY(0, y)\n if scr_y > 0 and scr_y < self.height:\n dc.DrawLine(x, scr_y, x + int(self.x_margin / 2), scr_y)\n dc.DrawText(str(y), 0, scr_y - 3)\n\n ''' plot data '''\n dc.SetPen(wx.Pen(\"red\", 1))\n i = 1\n for object in self.dataset.object_list:\n x, y = self.GraphXYtoScreenXY(object.coords[self.axis_1], object.coords[self.axis_2])\n #print x,y\n dc.DrawCircle(x, y, 3)\n dc.DrawText(object.objname, x, y)\n i += 1\n return\n\n def OnPaint(self, event):\n dc = wx.BufferedPaintDC(self, self.buffer)\n\n def SetDataset(self, dataset):\n self.dataset = dataset\n self.AdjustScale()\n self.DrawToBuffer()\n self.Refresh()\n\n def SetAxes(self, axis1, axis2):\n self.axis_1 = axis1\n self.axis_2 = axis2\n\n\nclass ModanDatasetViewer(wx.Dialog):\n def __init__(self, parent, id=-1):\n wx.Dialog.__init__(self, parent, id, \"Analysis\", size=CONST['DIALOG_SIZE'])\n\n panel = wx.Panel(self, -1)\n\n self.dataset = None\n self.show_index = False\n self.auto_rotate = False\n self.show_wireframe = True\n self.show_meanshape = True\n self.superimposition_method = CONST['IDX_GLS']\n self.xaxis_pc_idx = 1\n self.yaxis_pc_idx = 2\n #self.superimposition = ID_RD_PROCRUSTES\n self.selected_object_list = []\n\n self.ThreeDViewer = Md3DCanvas(panel)\n self.ThreeDViewer.SetMinSize((400, 400))\n self.ResultViewer = wx.Notebook(panel)\n self.eigenvalue_listctrl = wx.ListCtrl(self.ResultViewer, CONTROL_ID['ID_EIGENVALUE_LISTCTRL'], style=wx.LC_REPORT)\n self.eigenvalue_listctrl.InsertColumn(0, 'PC', width=40)\n self.eigenvalue_listctrl.InsertColumn(1, 'Eigen Val.', width=100)\n self.eigenvalue_listctrl.InsertColumn(2, 'Perct.', width=100)\n self.loading_listctrl = wx.ListCtrl(self.ResultViewer, CONTROL_ID['ID_LOADING_LISTCTRL'], style=wx.LC_REPORT)\n self.loading_listctrl_initialized = False\n self.coordinates_listctrl = wx.ListCtrl(self.ResultViewer, CONTROL_ID['ID_FINALCOORDINATES_LISTCTRL'], style=wx.LC_REPORT)\n self.coordinates_listctrl_initialized = False\n #self.rawdata_listctrl = wx.ListCtrl( self.ResultViewer, ID_RAWDATA_LISTCTRL, style=wx.LC_REPORT)\n #self.rawdata_listctrl_initialized = False\n self.superimposed_listctrl = wx.ListCtrl(self.ResultViewer, CONTROL_ID['ID_SUPERIMPOSED_LISTCTRL'], style=wx.LC_REPORT)\n self.superimposed_listctrl_initialized = False\n\n self.PCAViewer = PlotCanvas(self.ResultViewer)\n self.PCAViewer.SetPointLabelFunc(self.DrawPointLabel)\n #self.PCAViewer = MdPlotter(panel,-1)\n self.PCAViewer.SetMinSize((400, 400))\n self.PCAViewer.SetEnablePointLabel(True)\n # Create mouse event for showing cursor coords in status bar\n self.PCAViewer.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n # Show closest point when enabled\n self.PCAViewer.canvas.Bind(wx.EVT_MOTION, self.OnMotion)\n\n self.ResultViewer.AddPage(self.PCAViewer, \"Plot\")\n self.ResultViewer.AddPage(self.eigenvalue_listctrl, \"Eigen value\")\n self.ResultViewer.AddPage(self.loading_listctrl, \"Loading\")\n #self.ResultViewer.AddPage( self.rawdata_listctrl, \"Raw data\" )\n self.ResultViewer.AddPage(self.superimposed_listctrl, \"Superimposed\")\n self.ResultViewer.AddPage(self.coordinates_listctrl, \"Coordinates\")\n\n if use_mplot:\n pass\n #self.MplotViewer = wxmpl.PlotPanel( self.ResultViewer, -1 )\n #self.MplotViewer.SetMinSize((400, 400))\n #self.Bind( wxmpl.EVT_POINT, self.OnPoint , self.MplotViewer )\n #wxmpl.EVT_POINT(self, self.MplotViewer.GetId(), self.OnPoint)\n #self.ResultViewer.AddPage(self.MplotViewer, \"Mplot\")\n #self.MplotViewer.mpl_connect('pick_event', self.OnPick)\n self.ResultViewer.SetMinSize((400, 400))\n\n self.baseline_point_list = []\n self.edge_list = []\n self.landmark_list = []\n\n self.pc_list = []\n for i in range(15):\n self.pc_list.append('PC' + str(i + 1))\n\n self.xAxisLabel = wx.StaticText(panel, -1, 'X Axis', style=wx.ALIGN_RIGHT)\n self.xAxisCombo = wx.ComboBox(panel, CONTROL_ID['ID_XAXIS_COMBO'], \"PC1\", (15, 30), wx.DefaultSize, self.pc_list,\n wx.CB_DROPDOWN)\n self.yAxisLabel = wx.StaticText(panel, -1, 'Y Axis', style=wx.ALIGN_RIGHT)\n self.yAxisCombo = wx.ComboBox(panel, CONTROL_ID['ID_YAXIS_COMBO'], \"PC2\", (15, 30), wx.DefaultSize, self.pc_list,\n wx.CB_DROPDOWN)\n\n self.Bind(wx.EVT_COMBOBOX, self.OnXAxis, id=CONTROL_ID['ID_XAXIS_COMBO'])\n self.Bind(wx.EVT_COMBOBOX, self.OnYAxis, id=CONTROL_ID['ID_YAXIS_COMBO'])\n #self.zAxisLabel = wx.StaticText( panel, -1, 'Z Axis', style=wx.ALIGN_RIGHT )\n #self.zAxisCombo = wx.ComboBox( panel, ID_ZAXIS_COMBO, \"PC3\", (15,30),wx.DefaultSize, self.pc_list, wx.CB_DROPDOWN )\n axesSizer = wx.BoxSizer()\n axesSizer.Add(self.xAxisLabel, wx.EXPAND)\n axesSizer.Add(self.xAxisCombo, wx.EXPAND)\n axesSizer.Add(self.yAxisLabel, wx.EXPAND)\n axesSizer.Add(self.yAxisCombo, wx.EXPAND)\n #axesSizer.Add( self.zAxisLabel, wx.EXPAND )\n #axesSizer.Add( self.zAxisCombo, wx.EXPAND )\n\n self.chkAutoRotate = wx.CheckBox(panel, CONTROL_ID['ID_CHK_AUTO_ROTATE'], \"Auto Rotate\")\n self.chkShowIndex = wx.CheckBox(panel, CONTROL_ID['ID_CHK_SHOW_INDEX'], \"Show Index\")\n self.chkShowWireframe = wx.CheckBox(panel, CONTROL_ID['ID_CHK_SHOW_WIREFRAME'], \"Show Wireframe\")\n self.chkShowMeanshape = wx.CheckBox(panel, CONTROL_ID['ID_CHK_SHOW_MEANSHAPE'], \"Show Mean Shape\")\n self.Bind(wx.EVT_CHECKBOX, self.ToggleAutoRotate, id=CONTROL_ID['ID_CHK_AUTO_ROTATE'])\n self.Bind(wx.EVT_CHECKBOX, self.ToggleShowIndex, id=CONTROL_ID['ID_CHK_SHOW_INDEX'])\n self.Bind(wx.EVT_CHECKBOX, self.ToggleShowWireframe, id=CONTROL_ID['ID_CHK_SHOW_WIREFRAME'])\n self.Bind(wx.EVT_CHECKBOX, self.ToggleShowMeanshape, id=CONTROL_ID['ID_CHK_SHOW_MEANSHAPE'])\n self.chkAutoRotate.SetValue(self.auto_rotate)\n self.chkShowWireframe.SetValue(self.show_wireframe)\n self.chkShowIndex.SetValue(self.show_index)\n self.chkShowMeanshape.SetValue(self.show_meanshape)\n\n self.checkboxSizer = wx.BoxSizer(wx.VERTICAL)\n self.checkboxSizer.Add(self.chkAutoRotate, wx.EXPAND)\n self.checkboxSizer.Add(self.chkShowIndex, wx.EXPAND)\n self.checkboxSizer.Add(self.chkShowWireframe, wx.EXPAND)\n self.checkboxSizer.Add(self.chkShowMeanshape, wx.EXPAND)\n\n self.testButton = wx.Button(panel, CONTROL_ID['ID_ANALYZE_BUTTON'], 'Analyze')\n self.cvaButton= wx.Button(panel, -1, 'CVA')\n self.copyButton = wx.Button(panel, -1, 'Copy')\n self.Bind(wx.EVT_BUTTON, self.OnAnalyze, id=CONTROL_ID['ID_ANALYZE_BUTTON'])\n self.Bind(wx.EVT_BUTTON, self.OnCVA, self.cvaButton)\n self.Bind(wx.EVT_BUTTON, self.OnCopy, self.copyButton)\n\n radioList = [\"Bookstein\", \"SBR\", \"Procrustes (GLS)\", \"Resistant fit\"]\n self.rdSuperimposition = wx.RadioBox(panel, CONTROL_ID['ID_RADIO_SUPERIMPOSITION'], \"Superimposition Method\",\n choices=radioList, style=wx.RA_VERTICAL)\n self.Bind(wx.EVT_RADIOBOX, self.OnSuperimposition, id=CONTROL_ID['ID_RADIO_SUPERIMPOSITION'])\n self.rdSuperimposition.SetSelection(2)\n\n\n\n\n #self.rdGroupInfo = wx.RadioBox( panel, wx.NewId(), \"Group information\", choices=[\"No group information\" for i in range( 10 )], style=wx.RA_VERTICAL )\n\n\n self.groupLabel = []\n self.groupLabelSizer = wx.BoxSizer(wx.VERTICAL)\n for i in range(10):\n self.groupLabel.append(wx.StaticText(panel, -1, ''))\n self.groupLabelSizer.Add(self.groupLabel[i], wx.EXPAND)\n\n il = wx.ImageList(16, 16, True)\n il_max = il.Add(wx.Bitmap(\"icon/visible_16.png\", wx.BITMAP_TYPE_PNG))\n il_max = il.Add(wx.Bitmap(\"icon/invisible_16.png\", wx.BITMAP_TYPE_PNG))\n self.object_listctrl = wx.ListCtrl(panel, CONTROL_ID['ID_OBJECT_LISTCTRL'], style=wx.LC_REPORT)\n self.object_listctrl.InsertColumn(0, '', width=20)\n self.object_listctrl.InsertColumn(1, 'Name', width=80)\n self.object_listctrl.AssignImageList(il, wx.IMAGE_LIST_SMALL)\n #self.object_listctrl.InsertColumn(1,'X', width=landmarkCoordWidth)\n #self.object_listctrl.InsertColumn(2,'Y', width=landmarkCoordWidth)\n #self.object_listctrl.InsertColumn(3,'Z', width=landmarkCoordWidth)\n self.object_listctrl.SetMinSize((100, 400))\n self.object_listctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnObjectSelected, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n self.object_listctrl.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnObjectSelected, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n self.object_listctrl.Bind(wx.EVT_LEFT_DCLICK, self.OnObjectDoubleClick, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n #self.object_listctrl.Bind(wx.EVT_LEFT_DOWN, self.OnObjectClick, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n #self.object_listctrl.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n #self.object_listctrl.Bind(wx.EVT_RIGHT_UP, self.OnRightUp, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n self.object_listctrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick, id=CONTROL_ID['ID_OBJECT_LISTCTRL'])\n\n\n self.canvasOptionSizer = wx.GridBagSizer(hgap=5, vgap=5)\n self.canvasOptionSizer.Add(self.ThreeDViewer, pos=(0, 0), span=(1, 2), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.ResultViewer, pos=(0, 3), span=(1, 2), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.checkboxSizer, pos=(1, 0), flag=wx.EXPAND)\n #self.canvasOptionSizer.Add( self.chkAutoRotate, pos=(1,0), flag=wx.EXPAND )\n #self.canvasOptionSizer.Add( self.chkShowIndex, pos=(2,0), flag=wx.EXPAND )\n #self.canvasOptionSizer.Add( self.chkShowWireframe, pos=(3,0), flag=wx.EXPAND )\n #self.canvasOptionSizer.Add( self.chkShowMeanshape, pos=(4,0), flag=wx.EXPAND )\n self.canvasOptionSizer.Add(self.rdSuperimposition, pos=(1, 1), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.object_listctrl, pos=(0, 2), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.testButton, pos=(2, 0), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.cvaButton, pos=(2, 1), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.copyButton, pos=(2, 2), flag=wx.EXPAND)\n #self.canvasOptionSizer.Add( self.rdGroupInfo, pos=(1,2), span=(4,1),flag=wx.EXPAND)\n self.canvasOptionSizer.Add(self.groupLabelSizer, pos=(1, 3), flag=wx.EXPAND)\n self.canvasOptionSizer.Add(axesSizer, pos=(1, 4), flag=wx.EXPAND)\n\n self.pca_done = False\n self.show_legend = False\n panel.SetSizer(self.canvasOptionSizer)\n panel.Fit()\n self.panel = panel\n\n def DrawPointLabel(self, dc, mDataDict):\n \"\"\"This is the fuction that defines how the pointLabels are plotted\n dc - DC that will be passed\n mDataDict - Dictionary of data that you want to use for the pointLabel\n\n As an example I have decided I want a box at the curve point\n with some text information about the curve plotted below.\n Any wxDC method can be used.\n \"\"\"\n # ----------\n dc.SetPen(wx.Pen(wx.BLACK))\n dc.SetBrush(wx.Brush(wx.BLACK, wx.SOLID))\n\n sx, sy = mDataDict[\"scaledXY\"] #scaled x,y of closest point\n dc.DrawRectangle(sx - 5, sy - 5, 10, 10) #10by10 square centered on point\n px, py = mDataDict[\"pointXY\"]\n cNum = mDataDict[\"curveNum\"]\n pntIn = mDataDict[\"pIndex\"]\n legend = mDataDict[\"legend\"]\n #make a string to display\n #s = \"Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i\" %(cNum, legend, px, py, pntIn)\n s = legend\n dc.DrawText(s, sx, sy + 1)\n # -----------\n\n def OnMouseLeftDown(self, event):\n s = \"Left Mouse Down at Point: (%.4f, %.4f)\" % self.PCAViewer._getXY(event)\n #print s\n #self.SetStatusText(s)\n event.Skip() #allows plotCanvas OnMouseLeftDown to be called\n\n def OnMotion(self, event):\n #show closest point (when enbled)\n if self.PCAViewer.GetEnablePointLabel() == True:\n #make up dict with info for the pointLabel\n #I've decided to mark the closest point on the closest curve\n dlst = self.PCAViewer.GetClosestPoint(self.PCAViewer._getXY(event), pointScaled=True)\n if dlst != []: #returns [] if none\n curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst\n #make up dictionary to pass to my user function (see DrawPointLabel)\n mDataDict = {\"curveNum\": curveNum, \"legend\": legend, \"pIndex\": pIndex,\n \"pointXY\": pointXY, \"scaledXY\": scaledXY}\n #pass dict to update the pointLabel\n self.PCAViewer.UpdatePointLabel(mDataDict)\n event.Skip() #go to next handler\n\n\n def OnSuperimposition(self, event):\n radioSelected = event.GetEventObject()\n method = radioSelected.GetSelection()\n if method == self.superimposition_method:\n return\n\n wx.BeginBusyCursor()\n baseline = self.ThreeDViewer.dataset.baseline_point_list\n\n self.superimposition_method = method\n if method == CONST['IDX_BOOKSTEIN']:\n #print \"bookstein\"\n if len(baseline) == 0:\n wx.MessageBox(\"Baseline not defined!\")\n wx.EndBusyCursor()\n return\n for mo in self.ThreeDViewer.dataset.object_list:\n mo.bookstein_registration(baseline)\n #mo.move_to_center()\n self.ThreeDViewer.dataset.reference_shape = self.ThreeDViewer.dataset.get_average_shape()\n elif method == CONST['IDX_SBR']:\n #print \"sbr\"\n if len(baseline) == 0:\n wx.MessageBox(\"Baseline not defined!\")\n wx.EndBusyCursor()\n return\n for mo in self.ThreeDViewer.dataset.object_list:\n mo.sliding_baseline_registration(baseline)\n #mo.move_to_center()\n self.ThreeDViewer.dataset.reference_shape = self.ThreeDViewer.dataset.get_average_shape()\n elif method == CONST['IDX_GLS']:\n #print \"procrustes\"\n self.ThreeDViewer.dataset.procrustes_superimposition()\n self.ThreeDViewer.dataset.reference_shape = self.ThreeDViewer.dataset.get_average_shape()\n elif method == CONST['IDX_RFTRA']:\n #print \"resistant fit\"\n self.ThreeDViewer.dataset.resistant_fit_superimposition()\n self.ThreeDViewer.dataset.reference_shape = self.ThreeDViewer.dataset.get_average_shape()\n self.ThreeDViewer.SetSuperimpositionMethod(method)\n #self.SetDataset( self.ThreeDViewer.dataset )\n self.SetObject(self.ThreeDViewer.dataset.reference_shape)\n self.ThreeDViewer.ResetParameters()\n self.ThreeDViewer.Refresh(False)\n\n if True:\n self.PerformPCA()\n self.VisualizePCAResult()\n wx.EndBusyCursor()\n\n #self.superimposition =\n #print radioSelected.GetSelection()\n\n def PerformCVA(self):\n\n self.cva = MdCanonicalVariate()\n datamatrix = []\n category_list = []\n for obj in self.dataset.object_list:\n datum = []\n for lm in obj.landmark_list:\n datum.extend(lm.coords)\n datamatrix.append(datum)\n for p in obj.property_list:\n if p.propertyname_id == self.selected_propertyname_id:\n category_list.append(p.property)\n self.cva.SetData(datamatrix)\n self.cva.SetCategory(category_list)\n self.cva.Analyze()\n self.loading_listctrl_initialized = False\n self.coordinates_listctrl_initialized = False\n\n number_of_axes = min(self.cva.nObservation, self.cva.nVariable)\n self.xAxisCombo.Clear()\n self.yAxisCombo.Clear()\n for i in range(number_of_axes):\n self.xAxisCombo.Append(\"CV\" + str(i + 1))\n self.yAxisCombo.Append(\"CV\" + str(i + 1))\n self.xAxisCombo.SetSelection(0)\n self.yAxisCombo.SetSelection(1)\n\n self.cva_done = True\n\n\n def PerformPCA(self):\n\n self.pca = MdPrincipalComponent2()\n datamatrix = []\n for obj in self.dataset.object_list:\n datum = []\n for lm in obj.landmark_list:\n datum.extend( lm.coords )\n datamatrix.append(datum)\n\n self.pca.SetData(datamatrix)\n self.pca.Analyze()\n self.loading_listctrl_initialized = False\n self.coordinates_listctrl_initialized = False\n\n number_of_axes = min(self.pca.nObservation, self.pca.nVariable)\n self.xAxisCombo.Clear()\n self.yAxisCombo.Clear()\n for i in range(number_of_axes):\n self.xAxisCombo.Append(\"PC\" + str(i + 1))\n self.yAxisCombo.Append(\"PC\" + str(i + 1))\n\n self.xAxisCombo.SetSelection(0)\n self.yAxisCombo.SetSelection(1)\n\n self.pca_done = True\n\n def VisualizePCAResult(self):\n #print self.pca.raw_eigen_values\n if not self.pca_done:\n return\n\n self.eigenvalue_listctrl.DeleteAllItems()\n for i in range(len(self.pca.raw_eigen_values)):\n #print mo.objname\n self.eigenvalue_listctrl.Append((\n 'PC' + str(i + 1), math.floor(self.pca.raw_eigen_values[i] * 100000 + 0.5) / 100000,\n math.floor(self.pca.eigen_value_percentages[i] * 10000 + 0.5) / 100 ))\n\n ''' loading '''\n if not self.loading_listctrl_initialized:\n self.loading_listctrl.DeleteAllItems()\n self.loading_listctrl.DeleteAllColumns()\n for i in range(len(self.pca.raw_eigen_values)):\n self.loading_listctrl.InsertColumn(i, 'Var' + str(i + 1), width=60)\n self.loading_listctrl.InsertColumn(0, 'PC', width=50)\n self.loading_listctrl_initialized = True\n #print self.pca.loading\n for i in range(self.pca.nVariable):\n list = []\n #list[:] = self.pca.loading[i]\n for j in range(self.pca.nVariable):\n val = self.pca.loading[i, j]\n #print val,\n val = math.floor(val * 1000 + 0.5) / 1000\n #print val\n list.append(val)\n list.insert(0, \"PC\" + str(i + 1))\n self.loading_listctrl.Append(list)\n\n ''' superimposed coordinates '''\n if not self.superimposed_listctrl_initialized:\n self.superimposed_listctrl.DeleteAllItems()\n self.superimposed_listctrl.DeleteAllColumns()\n for i in range(self.pca.nVariable):\n self.superimposed_listctrl.InsertColumn(i, 'Var' + str(i + 1), width=60)\n self.superimposed_listctrl.InsertColumn(0, 'ObjName', width=80)\n self.superimposed_listctrl_initialized = True\n\n i = 0\n for obj in self.dataset.object_list:\n list = []\n for j in range(self.pca.nVariable):\n val = self.pca.data[i][j]\n val = math.floor(val * 1000 + 0.5) / 1000\n list.append(val)\n list.insert(0, obj.objname)\n self.superimposed_listctrl.Append(list)\n i += 1\n\n ''' final coordinates '''\n if not self.coordinates_listctrl_initialized:\n self.coordinates_listctrl.DeleteAllItems()\n self.coordinates_listctrl.DeleteAllColumns()\n for i in range(len(self.pca.raw_eigen_values)):\n self.coordinates_listctrl.InsertColumn(i, 'PC' + str(i + 1), width=60)\n self.coordinates_listctrl.InsertColumn(0, 'ObjName', width=80)\n self.coordinates_listctrl_initialized = True\n\n ''' coordinates '''\n i = 0\n for obj in self.dataset.object_list:\n list = []\n for j in range(self.pca.nVariable):\n val = self.pca.rotated_matrix[i, j]\n val = math.floor(val * 1000 + 0.5) / 1000\n list.append(val)\n list.insert(0, obj.objname)\n self.coordinates_listctrl.Append(list)\n i += 1\n\n m = []\n i = 0\n for obj in self.dataset.object_list:\n key = \"\"\n for p in obj.property_list:\n if p.propertyname_id == self.selected_propertyname_id:\n key = p.property\n x = self.pca.rotated_matrix[i, self.xaxis_pc_idx - 1]\n y = self.pca.rotated_matrix[i, self.yaxis_pc_idx - 1]\n str_x = str(math.floor(x * 1000 + 0.5) / 1000)\n str_y = str(math.floor(y * 1000 + 0.5) / 1000)\n #print x, y\n i += 1\n m.append(PolyMarker([( x, y )], legend=obj.objname + \" (\" + key + \") (\" + str_x + \",\" + str_y + \")\",\n colour=self.group_colors[key], marker=self.group_symbols[key]))\n #print m\n #self.PCAViewer.SetEnableLegend(True)\n self.PCAViewer.Draw(PlotGraphics(m, \"\", \"PC\" + str(self.xaxis_pc_idx), \"PC\" + str(self.yaxis_pc_idx)))\n self.PCAViewer.Refresh()\n\n def VisualizeCVAResult(self):\n #print self.pca.raw_eigen_values\n if not self.cva_done:\n return\n\n self.eigenvalue_listctrl.DeleteAllItems()\n for i in range(len(self.cva.raw_eigen_values)):\n #print mo.objname\n self.eigenvalue_listctrl.Append((\n 'CV' + str(i + 1), math.floor(self.cva.raw_eigen_values[i] * 100000 + 0.5) / 100000,\n math.floor(self.cva.eigen_value_percentages[i] * 10000 + 0.5) / 100 ))\n\n if not self.loading_listctrl_initialized:\n self.loading_listctrl.DeleteAllItems()\n self.loading_listctrl.DeleteAllColumns()\n for i in range(len(self.pca.raw_eigen_values)):\n self.loading_listctrl.InsertColumn(i, 'Var' + str(i + 1), width=60)\n self.loading_listctrl.InsertColumn(0, 'CV', width=50)\n self.loading_listctrl_initialized = True\n\n #print self.pca.loading\n for i in range(self.cva.nVariable):\n list = []\n #list[:] = self.pca.loading[i]\n for j in range(self.cva.nVariable):\n val = self.cva.loading[i, j]\n #print val,\n val = math.floor(val * 1000 + 0.5) / 1000\n #print val\n list.append(val)\n list.insert(0, \"CV\" + str(i + 1))\n self.loading_listctrl.Append(list)\n #print self.cva.loading\n #print self.cva.rotated_matrix\n\n if not self.coordinates_listctrl_initialized:\n self.coordinates_listctrl.DeleteAllItems()\n self.coordinates_listctrl.DeleteAllColumns()\n for i in range(len(self.cva.raw_eigen_values)):\n self.coordinates_listctrl.InsertColumn(i, 'CV' + str(i + 1), width=60)\n self.coordinates_listctrl.InsertColumn(0, 'ObjName', width=80)\n self.coordinates_listctrl_initialized = True\n\n ''' coordinates '''\n i = 0\n for obj in self.dataset.object_list:\n list = []\n for j in range(self.cva.nVariable):\n val = self.cva.rotated_matrix[i, j]\n val = math.floor(val * 1000 + 0.5) / 1000\n list.append(val)\n list.insert(0, obj.objname)\n self.coordinates_listctrl.Append(list)\n i += 1\n\n m = []\n i = 0\n for obj in self.dataset.object_list:\n for p in obj.property_list:\n if p.propertyname_id == self.selected_propertyname_id:\n key = p.property\n x = self.cva.rotated_matrix[i, self.xaxis_pc_idx - 1]\n y = self.cva.rotated_matrix[i, self.yaxis_pc_idx - 1]\n str_x = str(math.floor(x * 1000 + 0.5) / 1000)\n str_y = str(math.floor(y * 1000 + 0.5) / 1000)\n #print x, y\n i += 1\n m.append(PolyMarker([( x, y )], legend=obj.objname + \" (\" + key + \") (\" + str(x) + \",\" + str(y) + \")\",\n colour=self.group_colors[key], marker=self.group_symbols[key]))\n #print m\n #self.PCAViewer.SetEnableLegend(True)\n self.PCAViewer.Draw(PlotGraphics(m, \"\", \"CV\" + str(self.xaxis_pc_idx), \"CV\" + str(self.yaxis_pc_idx)))\n self.PCAViewer.Refresh()\n\n\n def OnCopy(self, event):\n\n #print \"copy\"\n selected_tab = self.ResultViewer.GetSelection()\n ret_str = \"\"\n if selected_tab == 0:\n context = wx.ClientDC(self.PCAViewer)\n memory = wx.MemoryDC()\n x, y = self.PCAViewer.GetClientSizeTuple()\n bitmap = wx.EmptyBitmap(x, y, -1)\n memory.SelectObject(bitmap)\n memory.Blit(0, 0, x, y, context, 0, 0)\n memory.SelectObject(wx.NullBitmap)\n #bitmap.SaveFile( \"test.bmp\", wxBITMAP_TYPE_BMP )\n #img = self.PCAViewer.CopyImage()\n wx.TheClipboard.Open()\n success = wx.TheClipboard.SetData(wx.BitmapDataObject(bitmap))\n wx.TheClipboard.Close()\n #self.PCAViewer.SaveFile()\n elif selected_tab == 1:\n for i in range(len(self.pca.raw_eigen_values)):\n val = math.floor(self.pca.raw_eigen_values[i] * 100000 + 0.5) / 100000\n if val == 0.0: break\n ret_str += 'PC' + str(i + 1) + \"\\t\" + str(val) + \"\\t\" + str(\n math.floor(self.pca.eigen_value_percentages[i] * 10000 + 0.5) / 100) + \"%\" + \"\\n\"\n wx.TheClipboard.Open()\n success = wx.TheClipboard.SetData(wx.TextDataObject(ret_str))\n wx.TheClipboard.Close()\n #print ret_str\n\n elif selected_tab == 2:\n # pca result\n for i in range(len(self.pca.loading[..., 0])):\n list = []\n #list[:] = self.pca.loading[i]\n for val in self.pca.loading[i]:\n #print val,\n #val = math.floor( val * 1000 + 0.5 ) / 1000\n #print val\n list.append(val)\n list.insert(0, \"PC\" + str(i + 1))\n ret_str += \"\\t\".join([str(x) for x in list]) + \"\\n\"\n wx.TheClipboard.Open()\n success = wx.TheClipboard.SetData(wx.TextDataObject(ret_str))\n wx.TheClipboard.Close()\n #print ret_str\n elif selected_tab == 3:\n ''' coordinates '''\n i = 0\n for obj in self.dataset.object_list:\n list = []\n for j in range(self.pca.nVariable):\n val = self.pca.rotated_matrix[i, j]\n #val = math.floor( val * 1000 + 0.5 ) / 1000\n list.append(val)\n list.insert(0, obj.objname)\n ret_str += \"\\t\".join([str(x) for x in list]) + \"\\n\"\n #self.coordinates_listctrl.Append( list )\n i += 1\n wx.TheClipboard.Open()\n success = wx.TheClipboard.SetData(wx.TextDataObject(ret_str))\n wx.TheClipboard.Close()\n\n\n def OnCVA(self, event):\n self.PerformCVA()\n self.VisualizeCVAResult()\n\n def OnTest2(self, event):\n print( \"anova\")\n self.manova = MdManova()\n self.manova.AddDataset(self.dataset)\n print( \"a\")\n self.manova.Analyze()\n\n '''\n\n if not use_mplot:\n return\n if not self.show_legend:\n fig = self.MplotViewer.get_figure()\n axes = fig.gca()\n keys = []\n for key in self.group_symbols.keys():\n if key != '': keys.append(key)\n axes.legend(keys,\n 'upper center', shadow=True, numpoints=1)\n self.MplotViewer.draw()\n #self.MplotViewer.Show()\n self.show_legend = True\n else:\n fig = self.MplotViewer.get_figure()\n axes = fig.gca()\n axes.legend_ = None\n self.MplotViewer.draw()\n #self.MplotViewer.Show()\n self.show_legend = False\n '''\n return\n\n def OnPoint(self, event):\n #print \"on point\"\n #print event\n #print event.axes\n #print event.x, event.y\n #print event.xdata, event.ydata\n if not use_mplot:\n return\n i = 0\n min_dist = 99999\n min_idx = -1\n for object in self.pca.new_dataset.object_list:\n dist = math.sqrt(( object.coords[self.xaxis_pc_idx - 1] - event.xdata ) ** 2 + (\n object.coords[self.yaxis_pc_idx - 1] - event.ydata ) ** 2)\n #print i, object.objname, dist, min_dist, min_idx\n if dist < min_dist:\n min_dist = dist\n min_idx = i\n #print \"min:\", dist, min_dist, min_idx\n i += 1\n #if min_dist <\n #print self.pca.new_dataset.objects[min_idx].objname\n self.OnAnalyze(None)\n fig = self.MplotViewer.get_figure()\n #fig.clear()\n a = fig.gca()\n x = self.pca.new_dataset.object_list[min_idx].coords[self.xaxis_pc_idx - 1]\n y = self.pca.new_dataset.object_list[min_idx].coords[self.yaxis_pc_idx - 1]\n a.annotate(self.pca.new_dataset.object_list[min_idx].objname, xy=(x, y), xycoords='data',\n xytext=(-30, -30), textcoords='offset points',\n arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3,rad=.2\")\n )\n self.MplotViewer.draw()\n #min_dist = min( min_dist, dist )\n\n #event.axes.pick(event)\n #print event\n #event.axes.pick(event)\n\n def OnAnalyze(self, event):\n #self.PerformPCA()\n #self.VisualizePCAResult()\n\n marker_list_x = {}\n marker_list_y = {}\n marker_list_name = {}\n marker_list_symbol = {}\n symbol_list = ['bo', 'r>', 'ro', 'b>', 'r+', 'rs', 'bs']\n i = 0\n for object in self.pca.new_dataset.object_list:\n key = object.group_list[self.selected_group_idx]\n if not marker_list_x.has_key(key):\n marker_list_x[key] = []\n marker_list_y[key] = []\n marker_list_name[key] = []\n marker_list_symbol[key] = symbol_list[i]\n i += 1\n marker_list_x[key].append(object.coords[self.xaxis_pc_idx - 1])\n marker_list_y[key].append(object.coords[self.yaxis_pc_idx - 1])\n marker_list_name[key].append(object.objname)\n\n #return\n\n if not use_mplot:\n return\n\n fig = self.MplotViewer.get_figure()\n fig.clear()\n a = fig.gca()\n for key in marker_list_x.keys():\n #a.scatter( marker_list_x[key], marker_list_y[key], s=20, c = marker_list_symbol[key][0], marker = marker_list_symbol[key][1] )#, marker_list_symbol[key] )\n a.plot(marker_list_x[key], marker_list_y[key], marker_list_symbol[key], label=marker_list_name[key],\n markeredgewidth=0) #self.OnPick )\n self.MplotViewer.draw()\n #self.MplotViewer.Show()\n\n def ToggleShowWireframe(self, event):\n self.show_wireframe = self.chkShowWireframe.GetValue()\n if ( self.show_wireframe ):\n self.ThreeDViewer.ShowWireframe()\n else:\n self.ThreeDViewer.HideWireframe()\n\n def ToggleShowIndex(self, event):\n self.show_index = self.chkShowIndex.GetValue()\n if ( self.show_index ):\n self.ThreeDViewer.ShowIndex()\n else:\n self.ThreeDViewer.HideIndex()\n\n def ToggleAutoRotate(self, event):\n self.auto_rotate = self.chkAutoRotate.GetValue()\n if ( self.auto_rotate):\n self.ThreeDViewer.BeginAutoRotate()\n else:\n self.ThreeDViewer.EndAutoRotate()\n\n def ToggleShowMeanshape(self, event):\n self.show_meanshape = self.chkShowMeanshape.GetValue()\n if ( self.show_meanshape):\n self.ThreeDViewer.ShowMeanshape()\n else:\n self.ThreeDViewer.HideMeanshape()\n\n def SetObject(self, mo):\n #print \"opengltestwin setobject\"\n self.ThreeDViewer.SetSingleObject(mo)\n if self.auto_rotate:\n self.ThreeDViewer.BeginAutoRotate(50)\n #self.auto_rotate = True\n\n def SetDataset(self, ds):\n wx.BeginBusyCursor()\n self.dataset = MdDatasetView(ds)\n try:\n self.dataset.procrustes_superimposition()\n except( MdException, e):\n wx.MessageBox(str(e))\n wx.EndBusyCursor()\n return\n self.dataset.reference_shape.dataset_id = ds.id\n self.SetObject(self.dataset.reference_shape)\n self.object_listctrl.DeleteAllItems()\n self.edge_list = self.dataset.edge_list\n i = 0\n\n if len(self.dataset.baseline_point_list) == self.dataset.dimension:\n #print \"baseline\", ds.baseline\n self.rdSuperimposition.EnableItem(0, True)\n self.rdSuperimposition.EnableItem(1, True)\n self.rdSuperimposition.EnableItem(3, False)\n else:\n self.rdSuperimposition.EnableItem(0, False)\n self.rdSuperimposition.EnableItem(1, False)\n self.rdSuperimposition.EnableItem(3, False)\n\n for mo in self.dataset.object_list:\n #print mo.objname\n #mo.find()\n mo.visible = True\n mo.selected = False\n self.object_listctrl.Append(( \"\", mo.objname, ))\n self.object_listctrl.SetItemImage(i, 0, 0)\n i += 1\n self.ThreeDViewer.SetDataset(self.dataset)\n #print self.dataset.wireframe, self.dataset.edge_list\n self.baseline_point_list = self.dataset.baseline_point_list\n self.edge_list = self.dataset.edge_list\n\n self.PerformPCA()\n\n i = 0\n if len(self.dataset.propertyname_list) > 0:\n self.rdGroupInfo = wx.RadioBox(self.panel, wx.NewId(), \"Group information\",\n choices=[p.propertyname for p in self.dataset.propertyname_list], style=wx.RA_VERTICAL)\n else:\n self.rdGroupInfo = wx.RadioBox(self.panel, wx.NewId(), \"Group information\", choices=[\"All\"],\n style=wx.RA_VERTICAL)\n self.Bind(wx.EVT_RADIOBOX, self.OnChangeGroupInfo, self.rdGroupInfo)\n #self.canvasOptionSizer.Add( )\n self.canvasOptionSizer.Add(self.rdGroupInfo, pos=(1, 2), flag=wx.EXPAND)\n self.rdGroupInfo.SetSelection(0)\n self.OnChangeGroupInfo(None)\n #while i < 9:\n # i+= 1\n # self.rdGroupInfo.SetItemLabel( i, \"\" )\n # self.rdGroupInfo.ShowItem( i, False )\n self.panel.Layout()\n self.panel.Fit()\n wx.EndBusyCursor()\n #self.rdGroupInfo.Set\n #self.rdSuperimposition.SetSelection( 2 )\n\n def OnChangeGroupInfo(self, event):\n wx.BeginBusyCursor()\n groupname = self.rdGroupInfo.GetStringSelection()\n #\"groupname: \", groupname\n found = False\n idx = -1\n\n for i in range(len(self.dataset.propertyname_list)):\n if groupname == self.dataset.propertyname_list[i].propertyname:\n idx = i\n propertyname_id = self.dataset.propertyname_list[i].id\n found = True\n self.selected_propertyname_id = propertyname_id\n\n self.group_symbols = {}\n self.group_colors = {}\n if found:\n for object in self.dataset.object_list:\n #\"onchange group_list\", object.objname, object.group_list\n for p in object.property_list:\n if p.propertyname_id == propertyname_id:\n groupinfo = p.property\n if not self.group_symbols.has_key(groupinfo):\n self.group_symbols[groupinfo] = 0\n self.group_symbols[groupinfo] += 1\n symbol_list = ['circle', 'square', 'triangle', 'triangle_down', 'cross', 'plus']\n color_list = ['blue', 'green', 'yellow', 'red', 'grey'] #, 'black' ]\n\n i = 0\n for key in self.group_symbols.keys():\n self.group_colors[key] = color_list[i % len(color_list)]\n self.group_symbols[key] = symbol_list[i % len(symbol_list)]\n self.groupLabel[i].SetLabel(\n key + \":\" + color_list[i % len(color_list)] + \" \" + symbol_list[i % len(symbol_list)])\n #print i, key\n i += 1\n for i in range(i, 10):\n self.groupLabel[i].SetLabel(\"\")\n #print key, group_symbols[key]\n self.group_colors[''] = 'blue'\n self.group_symbols[''] = 'circle'\n\n self.VisualizePCAResult()\n wx.EndBusyCursor()\n return\n\n #self.SetSize((400,400))\n\n def OnObjectSelected(self, event):\n selected_idx_list = self.GetSelectedItemIndex(self.object_listctrl)\n self.ThreeDViewer.SelectObject(selected_idx_list)\n self.ThreeDViewer.Refresh(False)\n\n def OnLeftUp(self, event):\n #print \"leftup\"\n selected_idx_list = self.GetSelectedItemIndex(self.object_listctrl)\n self.ThreeDViewer.SelectObject(selected_idx_list)\n self.ThreeDViewer.Refresh(False)\n\n def GetSelectedItemIndex(self, listctrl):\n #pass\n rv = []\n selected_idx = listctrl.GetFirstSelected()\n if ( selected_idx < 0 ):\n return rv\n else:\n #rv.append( listctrl.GetItemText(selected_idx) )\n rv.append(selected_idx)\n\n while (1):\n selected_idx = listctrl.GetNextSelected(selected_idx)\n if ( selected_idx < 0 ):\n break\n rv.append(selected_idx)\n #rv.append( listctrl.GetItemText(selected_idx) )\n\n return rv\n\n def OnObjectClick(self, event):\n selected_idx = self.object_listctrl.GetFocusedItem()\n if self.ThreeDViewer.dataset.object_list[selected_idx].visible:\n #print \"visible -> invisible\"\n self.object_listctrl.SetItemImage(selected_idx, 1, 1)\n else:\n #print \"invisible -> visible\"\n self.object_listctrl.SetItemImage(selected_idx, 0, 0)\n self.ThreeDViewer.ToggleObjectVisibility(selected_idx)\n self.ThreeDViewer.Refresh(False)\n\n def OnObjectDoubleClick(self, event):\n selected_idx = self.object_listctrl.GetFocusedItem()\n if self.ThreeDViewer.dataset.object_list[selected_idx].visible:\n #print \"visible -> invisible\"\n self.object_listctrl.SetItemImage(selected_idx, 1, 1)\n else:\n #print \"invisible -> visible\"\n self.object_listctrl.SetItemImage(selected_idx, 0, 0)\n self.ThreeDViewer.ToggleObjectVisibility(selected_idx)\n self.ThreeDViewer.Refresh(False)\n\n def OnRightDown(self,event):\n event_point = event.GetPoint()\n #print event_point\n\n m = wx.Menu()\n i = m.Append(wx.NewId(), '&Hide this')\n self.Bind(wx.EVT_MENU, self.OnHideThis, i)\n i = m.Append(wx.NewId(), 'Hide &Others')\n self.Bind(wx.EVT_MENU, self.OnHideOthers, i)\n self.PopupMenu(m, event_point)\n\n def OnRightUp(self,event):\n event_point = event.GetPoint()\n #print event_point\n\n def OnRightClick(self,event):\n\n itemid = self.object_listctrl.GetFirstSelected()\n #print \"first selected item: \", itemid\n if ( itemid < 0 ):\n return\n object_idx_list = []\n while ( itemid >= 0 ):\n object_idx_list.append(itemid)\n itemid = self.object_listctrl.GetNextSelected(itemid)\n self.selected_object_list = object_idx_list\n\n\n selected_idx = self.object_listctrl.GetFocusedItem()\n self.selected_object_list = [selected_idx]\n\n m = wx.Menu()\n if self.ThreeDViewer.dataset.object_list[selected_idx].visible:\n i = m.Append(wx.NewId(), '&Hide this')\n self.Bind(wx.EVT_MENU, self.OnHideThis, i)\n else:\n i = m.Append(wx.NewId(), '&Show this')\n self.Bind(wx.EVT_MENU, self.OnShowThis, i)\n i = m.Append(wx.NewId(), 'Hide &Others')\n self.Bind(wx.EVT_MENU, self.OnHideOthers, i)\n i = m.Append(wx.NewId(), 'S&how others')\n self.Bind(wx.EVT_MENU, self.OnShowOthers, i)\n\n event_point = event.GetPoint()\n pos = self.object_listctrl.GetPosition()\n (x1, y1 )= pos\n (x2, y2 ) = event_point\n menu_point = ( x1+x2, y1+y2 )\n #print pos\n #print \"right click\", menu_point\n\n self.PopupMenu(m, menu_point)\n\n def OnShowThis(self,event):\n for i in range(len(self.ThreeDViewer.dataset.object_list)):\n if i in self.selected_object_list and not self.ThreeDViewer.dataset.object_list[i].visible:\n self.object_listctrl.SetItemImage(i, 0, 0)\n self.ThreeDViewer.ToggleObjectVisibility(i)\n self.ThreeDViewer.Refresh(False)\n\n def OnHideThis(self,event):\n for i in range(len(self.ThreeDViewer.dataset.object_list)):\n if i in self.selected_object_list and self.ThreeDViewer.dataset.object_list[i].visible:\n self.object_listctrl.SetItemImage(i, 1, 1)\n self.ThreeDViewer.ToggleObjectVisibility(i)\n self.ThreeDViewer.Refresh(False)\n\n def OnHideOthers(self,event):\n for i in range(len(self.ThreeDViewer.dataset.object_list)):\n if i not in self.selected_object_list and self.ThreeDViewer.dataset.object_list[i].visible:\n self.object_listctrl.SetItemImage(i, 1, 1)\n self.ThreeDViewer.ToggleObjectVisibility(i)\n self.ThreeDViewer.Refresh(False)\n #print self.selected_object_list\n #print \"hide others\"\n\n def OnShowOthers(self,event):\n for i in range(len(self.ThreeDViewer.dataset.object_list)):\n if i not in self.selected_object_list and not self.ThreeDViewer.dataset.object_list[i].visible:\n self.object_listctrl.SetItemImage(i, 0, 0)\n self.ThreeDViewer.ToggleObjectVisibility(i)\n self.ThreeDViewer.Refresh(False)\n #print self.selected_object_list\n #print \"hide others\"\n\n def OnXAxis(self, event):\n x = self.xAxisCombo.GetValue()\n xaxis = x.replace(\"PC\", \"\")\n self.xaxis_pc_idx = int(xaxis)\n self.VisualizePCAResult()\n\n def OnYAxis(self, event):\n y = self.yAxisCombo.GetValue()\n yaxis = y.replace(\"PC\", \"\")\n self.yaxis_pc_idx = int(yaxis)\n self.VisualizePCAResult()\n","sub_path":"gui/dialog_datasetviewer.py","file_name":"dialog_datasetviewer.py","file_ext":"py","file_size_in_byte":48357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"596865533","text":"from django import template\nfrom django.template.defaultfilters import stringfilter\nfrom announcements.models import Comment\n\nregister = template.Library()\n\n\n@register.filter(name='confirmed_comment_filter')\ndef confirmed_comment_filter(ann_object):\n return Comment.objects.filter(com_ann=ann_object, com_confirmed=True)\n\n\n@register.filter(name='unconfirmed_comment_filter')\ndef unconfirmed_comment_filter(ann_object):\n return Comment.objects.filter(com_ann=ann_object, com_confirmed=False)\n\n\n@register.filter(name='censor')\n@stringfilter\ndef censor(value):\n forbidden_words = [\"плохое слово 1\", \"плохое слово 2\", \"плохое слово 3\"]\n f_words = [word for word in forbidden_words if word in value]\n if f_words:\n new_value = value\n for f_word in f_words:\n new_value = new_value.replace(f_word, f_word[0] + '*' * (len(f_word)-2) + f_word[-1])\n return new_value\n else:\n return value\n","sub_path":"announcements/templatetags/custom_filters_and_tags.py","file_name":"custom_filters_and_tags.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"549927143","text":"\n#ImportModules\nimport ShareYourSystem as SYS\n\n#Definition a MakerClass\n@SYS.ClasserClass()\nclass MakerClass(SYS.SetterClass):\n\n\tdef default_init(self,\n\t\t\t_MakingIntsList={\n\t\t\t\t\t\t\t'DefaultValueType':property,\n\t\t\t\t\t\t\t'PropertyInitVariable':None,\n\t\t\t\t\t\t\t'PropertyDocStr':'I am doing the thing here'\n\t\t\t\t\t\t\t},\n\t\t\t_MadeSumInt=0\t\n\t\t):\n\t\tpass\n\n\t#Definition a binding function\n\tdef propertize_setMakingIntsList(self,_SettingValueVariable):\n\n\t\t#debug\n\t\tself.debug('MakingIntsList is setted !')\n\n\t\t#set the value of the \"hidden\" property variable\n\t\tself._MakingIntsList=_SettingValueVariable\n\n\t\t#Bind with MadeInt setting\n\t\tself.MadeSumInt=sum(self._MakingIntsList)\n\n#define and set\nMyMaker=MakerClass(\n\t)\n\n#print(MakerClass.)\n\n#print\nprint('MyMaker before set is ')\nSYS._print(MyMaker)\n\n#set\nMyMaker.__setitem__(\n\t\t'MakingIntsList',\n\t\t[3,4]\n\t)\n\n#print\nprint('MyMaker is ')\nSYS._print(MyMaker)\n\n","sub_path":"Pythonlogy/build/lib/ShareYourSystem/Standards/Itemizers/Setter/19_ExampleDoc.py","file_name":"19_ExampleDoc.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"11593686","text":"import nltk, logging, random, sys, operator, string, re, numpy, pandas, csv, coloredlogs\nfrom qa_engine.base import QABase\nfrom qa_engine.score_answers import main as score_answers\nimport questionTypes as qt\nimport helper as h\nfrom collections import defaultdict\n\ncoloredlogs.install(level=logging.DEBUG, fmt='%(lineno)d - %(funcName)s - %(levelname)s - %(message)s')\n\nDATA_DIR = \"./wordnet\"\nwn = nltk.corpus.wordnet\n# logging.basicConfig(level=logging.DEBUG, format='%(lineno)d - %(funcName)s - %(levelname)s - %(message)s')\n# logging.basicConfig(level=logging.DEBUG, format='%(lineno)d - %(message)s')\n# ps = nltk.stem.PorterStemmer()\nsno = nltk.stem.SnowballStemmer('english')\n# lemma = nltk.wordnet.WordNetLemmatizer()\nstopwords = set(nltk.corpus.stopwords.words(\"english\"))\n\nfile = open(\"hw8-process.txt\", \"w\")\nfile.write(\"Process:\\n\")\nfile.close()\n\ndef write(string):\n file = open(\"hw8-process.txt\", \"a\")\n string = string.replace(\"\\n\", \"\\n\\t\")\n try:\n file.write(\"%s\\n\" %string)\n except:\n file.write(\"%s\\n\" %string.encode('utf-8'))\n file.close()\n\ndef get_sentences(text):\n \"\"\" tokenizes and pos tags the text\"\"\"\n # logging.debug(text)\n sentences = nltk.sent_tokenize(text)\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\n sentences = [nltk.pos_tag(sent) for sent in sentences]\n # logging.debug(sentences)\n return sentences\n\ndef get_bow(tagged_tokens, yes_stem):\n \"\"\"normalizes, removes stop words, punctuation, and stems the words\"\"\"\n\n intermediate = [t[0].lower() for t in tagged_tokens if t[0].lower() not in stopwords]\n intermediate = [t for t in intermediate if t not in list(string.punctuation)]\n if yes_stem:\n return set([sno.stem(t) for t in intermediate])\n else:\n return set(intermediate)\n\ndef find_phrase(tagged_tokens, qbow):\n for i in range(len(tagged_tokens) - 1, 0, -1):\n word = (tagged_tokens[i])[0]\n if word in qbow:\n return tagged_tokens[i+1:]\n\ndef baseline(qbow, sentences):\n # qtokens: is a list of pos tagged question tokens with SW removed\n # sentences: is a list of pos tagged story sentences\n # stopwords is a set of stopwords\n # Collect all the candidate answers\n answers = []\n # logging.debug(sentences)\n for i in range(len(sentences)):\n sent = sentences[i]\n # A list of all the word tokens in the sentence\n sbow = get_bow(sent, True)\n # logging.debug(sbow)\n # logging.debug(qbow)\n # Count the # of overlapping words between the Q and the A\n # & is the set intersection operator\n overlap = len(qbow & sbow)\n # logging.debug(overlap)\n answers.append((overlap, sent, i))\n\n # Sort the results by the first element of the tuple (i.e., the count)\n # Sort answers from smallest to largest by default, so reverse it\n # logging.debug(answers)\n answers = sorted(answers, key=operator.itemgetter(0), reverse=True)\n # logging.debug(answers)\n # Return the best answer\n best_answer = (answers[0])[1]\n final_overlap = (answers[0])[0]\n sentence_index = (answers[0])[2]\n return best_answer, final_overlap, sentence_index\n\ndef untokenize(words):\n text = ' '.join(words)\n step1 = text.replace(\"`` \", '\"').replace(\" ''\", '\"').replace('. . .', '...')\n step2 = step1.replace(\" ( \", \" (\").replace(\" ) \", \") \")\n step3 = re.sub(r' ([.,:;?!%]+)([ \\'\"`])', r\"\\1\\2\", step2)\n step4 = re.sub(r' ([.,:;?!%]+)$', r\"\\1\", step3)\n step5 = step4.replace(\" '\", \"'\").replace(\" n't\", \"n't\").replace(\n \"can not\", \"cannot\")\n step6 = step5.replace(\" ` \", \" '\")\n return step6.strip()\n\ndef base_line(question_text, story_text):\n # question_text = question[\"text\"]\n\n qbow = get_bow(get_sentences(question_text)[0], True)\n sentences = get_sentences(story_text)\n answer, overlap, sentence_index = baseline(qbow, sentences)\n # logging.debug('qbow: %s', qbow)\n # logging.debug('sentences: %s', sentences[sentence_index])\n # logging.debug('answer: %s', answer)\n # print(\"question: %s\" %question_text)\n # print(\"answer:\", \" \".join(t[0] for t in answer))\n words = list(zip(*answer))\n # logging.debug(untokenize(words[0]))\n # logging.debug(\"overlap: %s\" %overlap)\n answer_sent = untokenize(words[0])\n return (answer_sent, overlap, sentence_index)\n\ndef get_sent_at_index(text, index, offset):\n # logging.debug(\"Looking for sentance at index \\'%s\\' from: \\n%s\" % (str(index), text))\n sentences = nltk.tokenize.sent_tokenize(text)\n if offset == 1:\n sent_at_index = sentences[index] + sentences[index + offset]\n else:\n sent_at_index = sentences[index + offset] + sentences[index]\n\n # logging.debug(\"sentence at index %s is \\'%s\\'\" % (index, sent_at_index))\n return sent_at_index\n\ndef get_sent(question, story, question_text, story_or_sch, other_has_run, run):\n # question: the question object we are given\n # story: the story object we are given\n # question_text: should be either and empty string or the qestion with synsets replced\n # story_or_sch: needs to be either story or sch to indicate which story to look in\n # other_has_run: means sch has been run already and now run this on story or vise versa\n # run: is to return this this time no matter if its running sch or story. Used to\n # make the function return and not get stuck into and infinite loop\n\n if question_text == \"\":\n question_text = question[\"text\"]\n if story_or_sch == \"story\":\n story_text = story[\"text\"]\n other_text = \"sch\"\n elif story_or_sch == \"sch\":\n story_text = story[\"sch\"]\n other_text = \"story\"\n else:\n logging.error(\"%s isnt either \\'story\\' or \\'sch\\'. Yell at Devin.\" % story_or_sch)\n exit()\n parse = story_or_sch + \"_par\"\n dep = story_or_sch + \"_dep\"\n # logging.debug(\"question type: \\'%s\\'\" %question[\"type\"])\n # logging.debug(\"question: \\'%s\\'\" %question[\"text\"])\n # logging.debug(\"story: \\'%s\\'\" %story[\"text\"])\n\n if not pandas.isnull(story_text):\n # logging.debug(pandas.isnull(story_text))\n answer_sent, overlap, sentence_index = base_line(question_text, story_text)\n offset = 0\n if \"before\" in question_text:\n # logging.debug(\"\\'%s\\' contains before --------------------------------------------------------------------\" % question_text)\n # logging.debug(\"sentence \\'%s\\' at index \\'%s\\'\" % (answer_sent, str(sentence_index + offset)))\n offset = -1\n answer_sent = get_sent_at_index(story_text, sentence_index + offset, 1)\n # sentence_index += 1\n if \"after\" in question_text:\n # logging.debug(\"\\'%s\\' contains before --------------------------------------------------------------------\" % question_text)\n # logging.debug(\"sentence \\'%s\\' at index \\'%s\\'\" % (answer_sent, str(sentence_index + offset)))\n offset = 1\n answer_sent = get_sent_at_index(story_text, sentence_index + offset, -1)\n # sentence_index -= 1\n else:\n overlap = 0\n if overlap == 0 and run == 1:\n logging.debug(\"your getting stuck in an infinite loop\")\n # logging.debug(answer_sent)\n if offset == 1:\n return answer_sent,\\\n [story[parse][sentence_index], story[parse][sentence_index + offset]],\\\n [story[dep][sentence_index], story[dep][sentence_index + offset]]\n elif offset == -1:\n return answer_sent,\\\n [story[parse][sentence_index + offset], story[parse][sentence_index]],\\\n [story[dep][sentence_index + offset], story[dep][sentence_index]]\n elif offset == 0:\n return answer_sent,\\\n [story[parse][sentence_index]],\\\n [story[dep][sentence_index]]\n else:\n logging.error(\"Error offset doesnt equal 1, 0, or -1\")\n exit()\n elif overlap == 0 and other_has_run == 1:\n return get_sent(question, story, question_text, other_text, 1, 1)\n elif overlap == 0:\n #logging.debug(\"Overlap was 0. Trying with Story now.\")\n return get_sent(question, story, question_text, other_text, 1, 0)\n else:\n #logging.debug(\"final overlap: %s\" %overlap)\n # logging.debug(answer_sent)\n if offset == 1:\n return answer_sent,\\\n [story[parse][sentence_index], story[parse][sentence_index + offset]],\\\n [story[dep][sentence_index], story[dep][sentence_index + offset]]\n elif offset == -1:\n return answer_sent,\\\n [story[parse][sentence_index + offset], story[parse][sentence_index]],\\\n [story[dep][sentence_index + offset], story[dep][sentence_index]]\n elif offset == 0:\n return answer_sent,\\\n [story[parse][sentence_index]],\\\n [story[dep][sentence_index]]\n else:\n logging.error(\"Error offset doesnt equal 1, 0, or -1\")\n exit()\n\ndef get_characters(story):\n #likely overfit to our dataset. Unlikely to perfectly expand outside of the fables...\n story_text = story[\"text\"]\n qt.bprint(story_text)\n\n\n sentences = get_sentences(story_text)\n qt.bprint(\"%s\"%sentences)\n\n if story[\"sid\"].startswith(\"fables\"):\n candidates = []\n\n for sent in sentences:\n for wordNum in range(len(sent)):\n if sent[wordNum][0].lower() == \"the\": candidates.append((sent[wordNum+1][0].lower(), sent[wordNum+1][1]))\n if sent[wordNum][0].isupper() and wordNum != 0: candidates.append((sent[wordNum][0].lower(), sent[wordNum][1]))\n\n story_text = story[\"sch\"]\n\n sentences = get_sentences(story_text)\n\n for sent in sentences:\n for wordNum in range(len(sent)):\n if sent[wordNum][0].lower() == \"the\": candidates.append((sent[wordNum+1][0].lower(), sent[wordNum+1][1]))\n if sent[wordNum][0].isupper() and wordNum != 0: candidates.append((sent[wordNum][0].lower(), sent[wordNum][1]))\n\n partsOfSpeach = {}\n counts = {}\n maxValue = 0\n for word in candidates:\n if word[0] in partsOfSpeach:\n partsOfSpeach[word[0]].add(word[1])\n counts[word[0]] += 1\n else:\n partsOfSpeach[word[0]] = { word[1] }\n counts[word[0]] = 1\n\n maxValue = max(counts[word[0]], maxValue)\n\n finalists = []\n for candidate in partsOfSpeach:\n if \"NNP\" in partsOfSpeach[candidate] and counts[candidate] >= .55*maxValue : finalists.append(candidate)\n\n\n return \"a \"+\" and a \".join(list(set(finalists)))\n else:\n trees = nltk.ParentedTree.convert(story[\"story_par\"])\n trees += nltk.ParentedTree.convert(story[\"sch_par\"])\n\n candidates = []\n\n for tree in trees:\n #qt.bprint(\"%s\" %tree)\n candidates+= h.get_all_decendents_with_label(tree, \"NP\")\n\n \n #qt.bprint(\"candidates: %s\" %candidates)\n disqualified = [\"i\", \"he\", \"she\", \"him\", \"her\", \"it\", \"they\", \"them\"]\n \n counts = {}\n maxValue = 0\n for word in candidates:\n if not(word.lower() in disqualified) and word.lower() in counts:\n counts[word.lower()] += 1\n else:\n counts[word.lower()] = 1\n\n maxValue = max(counts[word.lower()], maxValue)\n\n #qt.bprint(\"count: %s\" %counts)\n \n\n finalists = []\n for candidate in counts:\n if counts[candidate] >= .55*maxValue : finalists.append(candidate)\n\n #qt.bprint(\"finalists: %s\" %finalists)\n\n return \" and \".join(list(set(finalists)))\n\ndef load_wordnet_ids(filename):\n file = open(filename, 'r')\n if \"noun\" in filename: type = \"noun\"\n else: type = \"verb\"\n csvreader = csv.DictReader(file, delimiter=\",\", quotechar='\"')\n word_ids = defaultdict()\n for line in csvreader:\n word_ids[line['synset_id']] = {'synset_offset': line['synset_offset'], 'story_'+type: line['story_'+type], 'stories': line['stories']}\n return word_ids\n\ndef get_synset_sentence(question, story):\n # logging.debug(\"question type: \\'%s\\'\" % question[\"type\"])\n # logging.debug(\"question: \\'%s\\'\" % question[\"text\"])\n # logging.debug(\"story id: %s\" % story[\"sid\"])\n # logging.debug(\"story: \\'%s\\'\" %story[\"text\"])\n question_text_synset = \"\"\n noun_ids = load_wordnet_ids(\"{}/{}\".format(DATA_DIR, \"Wordnet_nouns.csv\"))\n verb_ids = load_wordnet_ids(\"{}/{}\".format(DATA_DIR, \"Wordnet_verbs.csv\"))\n story_text = story[\"text\"]\n question_text = question[\"text\"]\n # logging.debug(\"question text: \\'%s\\'\" % question_text)\n question_sent = get_sentences(question_text)\n # logging.debug(\"question sentence: \\'%s\\'\" % question_sent)\n question_bow = get_bow(question_sent[0], False)\n # logging.debug(\"question bag of words: \\'%s\\'\" % question_bow)\n synset_dict = {}\n for token in question_bow:\n # logging.debug([synset.name() for synset in wn.synsets(token)])\n synset_dict[token] = [synset.name() for synset in wn.synsets(token)]\n # logging.debug(synset_dict)\n for word in synset_dict:\n # logging.debug(\"\\'%s\\' : \\'%s\\'\" % (word, synset_dict[word]))\n for each in synset_dict[word]:\n # logging.debug(each)\n for synset_id, tuple in noun_ids.items():\n if each == synset_id and word != tuple['story_noun'] and story[\"sid\"] in tuple[\"stories\"]:\n logging.debug(\"\\'%s\\' == \\'%s\\' and \\'%s\\' != \\'%s\\'\" % (each, synset_id, word, tuple['story_noun']))\n logging.debug(\"question text before: \\'%s\\'\" % question_text)\n logging.debug(\"%s is in both nouns_id and the synsets of the question\" % each)\n question_text = question_text.replace(word, tuple['story_noun'])\n logging.debug(\"question text after: \\'%s\\'\" % question_text)\n # exit()\n for synset_id, tuple in verb_ids.items():\n if each == synset_id and word != tuple['story_verb'] and story[\"sid\"] in tuple[\"stories\"]:\n logging.debug(\"\\'%s\\' == \\'%s\\' and \\'%s\\' != \\'%s\\'\" % (each, synset_id, word, tuple['story_verb']))\n logging.debug(\"question text before: \\'%s\\'\" % question_text)\n logging.debug(\"%s is in both verbs_id and the synsets of the question\" % each)\n question_text = question_text.replace(word, tuple['story_verb'])\n logging.debug(\"question text after: \\'%s\\'\" % question_text)\n # exit()\n return question_text\n \ndef combine_trees(listOTrees):\n if len(listOTrees) == 1:\n return listOTrees[0]\n else:\n tree1 = ' '.join(str(listOTrees[0]).split())\n tree2 = ' '.join(str(listOTrees[1]).split())\n combinedTree = \"(S %s %s)\" %(tree1, tree2)\n\n #qt.bprint(\"%s\" %combinedTree)\n\n combinedTree = nltk.Tree.fromstring(combinedTree)\n\n #qt.bprint(\"%s\" %combinedTree)\n\n return combinedTree\n\ndef get_answer(question, story):\n \"\"\"\n :param question: dict\n :param story: dict\n :return: str\n\n question is a dictionary with keys:\n dep -- A list of dependency graphs for the question sentence.\n par -- A list of constituency parses for the question sentence.\n text -- The raw text of story.\n sid -- The story id.\n difficulty -- easy, medium, or hard\n type -- whether you need to use the 'sch' or 'story' versions\n of the .\n id -- The id of the question.\n\n\n story is a dictionary with keys:\n story_dep -- list of dependency graphs for each sentence of\n the story version.\n sch_dep -- list of dependency graphs for each sentence of\n the sch version.\n sch_par -- list of constituency parses for each sentence of\n the sch version.\n story_par -- list of constituency parses for each sentence of\n the story version.\n sch -- the raw text for the sch version.\n text -- the raw text for the story version.\n sid -- the story id\n\n\n \"\"\"\n logging.info(\"\\t\\t\\t\\t\\tNEXT Question\")\n # logging.info(\"qid: \\'%s\\'\" %question[\"qid\"])\n\n # print(get_synset_sentence(question, story))\n # return\n\n if question[\"text\"].lower() == \"who is the story about?\":\n return get_characters(story)\n\n lookIn = question[\"type\"].lower()\n difficulty = question[\"difficulty\"].lower()\n if difficulty == \"easy\" or difficulty == \"medium\":\n # return\n logging.info(\"%s - %s\" % (difficulty, question[\"text\"]))\n if \"sch\" in lookIn and \"story\" in lookIn:\n sentence, stree, dep_parse = get_sent(question, story, \"\",\"story\", 0, 0)\n elif \"sch\" in lookIn:\n sentence, stree, dep_parse = get_sent(question, story, \"\",\"sch\", 0, 0)\n elif \"story\" in lookIn:\n sentence, stree, dep_parse = get_sent(question, story, \"\", \"story\", 0, 0)\n else:\n logging.error(\"Question type '%s' does not contain either: \\'Sch\\' or \\'Story\\'\" %lookIn)\n logging.warning(\"Trying on story now. it may or may not crash\")\n sentence, stree, dep_parse = get_sent(question, story, \"\", \"story\", 0, 0)\n else:\n logging.info(\"%s - %s\" % (difficulty, question[\"text\"]))\n if \"sch\" in lookIn and \"story\" in lookIn:\n question_sentence = get_synset_sentence(question, story)\n sentence, stree, dep_parse = get_sent(question, story, question_sentence,\"story\", 0, 0)\n elif \"sch\" in lookIn:\n question_sentence = get_synset_sentence(question, story)\n sentence, stree, dep_parse = get_sent(question, story, question_sentence,\"sch\", 0, 0)\n elif \"story\" in lookIn:\n question_sentence = get_synset_sentence(question, story)\n sentence, stree, dep_parse = get_sent(question, story, question_sentence, \"story\", 0, 0)\n else:\n logging.error(\"Question type '%s' does not contain either: \\'Sch\\' or \\'Story\\'\" %lookIn)\n logging.warning(\"Trying on story now. it may or may not crash\")\n question_sentence = get_synset_sentence(question, story)\n sentence, stree, dep_parse = get_sent(question, story, question_sentence, \"story\", 0, 0)\n # logging.debug(sentence)\n # logging.debug(stree)\n qtree = nltk.ParentedTree.convert(question[\"par\"])\n stree = nltk.ParentedTree.convert( combine_trees(stree) )\n pos_question = h.get_pos(question[\"text\"])\n pos_sent = h.get_pos(sentence)\n #lemma_sent = qt.pair_with_lemmatized(sentence, dep_parse)\n\n questionType = qt.get_question_type(question[\"text\"])\n\n if questionType == qt.Curious or qt.Curious == \"any\":\n # print(\"\\n#-----------------------------------------------------------------------------------#\\n\")\n # logging.debug(question[\"qid\"])\n # logging.debug(\"Question: \"+ question[\"text\"])\n # logging.debug(\"\\tPOS Question: \"+ pos_question )\n # logging.debug(\"\\tQuestion Tree: %s\" %qtree)\n # # logging.debug(question[\"type\"])\n # logging.debug(\"\\tSentence: \"+ sentence)\n # logging.debug(\"\\tPOS Sent: \"+ pos_sent)\n # logging.debug(\"\\tSent Tree: %s\" %stree)\n\n\n write(\"\\n#-----------------------------------------------------------------------------------#\\n\")\n write(question[\"qid\"])\n write(\"Question: \"+ question[\"text\"])\n write(\"\\tPOS Question: \"+ pos_question )\n write(\"\\tQuestion Tree: %s\" %qtree)\n write(\"\\tQuestion Type: %s\" %question[\"type\"])\n write(\"\\tKind of question: %s\"%questionType)\n write(\"\\tQuestion Difficulty: %s\"%question[\"difficulty\"])\n write(\"\\tSentence: \"+ sentence)\n write(\"\\tPOS Sent: \"+ pos_sent)\n write(\"\\tSent Tree: %s\" %stree)\n #logging.debug(dep_parse)\n #logging.debug(type(dep_parse))\n #write(\"\\tSent Lemmatized: %s\" %lemma_sent)\n\n\n\n\n # logging.debug)(\"\\t\"+questionType)\n if( questionType == \"where\" ):\n potentialAnswer = qt.where_par(question, stree, dep_parse)\n \n if potentialAnswer != str:\n potentialAnswer = qt.where_pos(sentence)\n\n\n elif( questionType == \"when\" ):\n\n potentialAnswer = qt.when_par(question, stree)\n\n if potentialAnswer == None:\n potentialAnswer = qt.when_min(sentence)\n\n elif( questionType == \"why\" ):\n potentialAnswer = qt.why_par(question, stree)\n\n if potentialAnswer == None:\n potentialAnswer = qt.why_min(question, sentence)\n\n if potentialAnswer == None:\n potentialAnswer = qt.why_default(question, sentence)\n\n elif( questionType == \"who\" ):\n potentialAnswer = qt.who_par(question, stree, dep_parse)\n\n if potentialAnswer == None:\n potentialAnswer = qt.who_pos(question, sentence)\n\n if potentialAnswer == None or potentialAnswer == sentence:\n potentialAnswer = get_characters(story).replace(\"and\", \"\")\n\n elif( questionType == \"what\" ):\n potentialAnswer = qt.what_par(question, stree, dep_parse)\n\n if potentialAnswer == None:\n potentialAnswer = qt.what_pos(question, sentence)\n\n elif( questionType == \"did\" or questionType == \"had\"):\n potentialAnswer = qt.did_default(sentence) #\"yes no\"\n\n else:\n potentialAnswer = sentence#defaultAnswer(question[\"type\"], story)\n\n if questionType == qt.Curious or qt.Curious == \"any\":\n logging.debug(\"\\tFinal answer: %s\" % str(potentialAnswer))\n write(\"\\tFinal answer: %s\" % str(potentialAnswer))\n\n answer = potentialAnswer\n\n\n return answer\n\n\n#############################################################\n### Dont change the code below here\n##########################break###################################\n\nclass QAEngine(QABase):\n @staticmethod\n def answer_question(question, story):\n answer = get_answer(question, story)\n return answer\n\n\ndef run_qa():\n QA = QAEngine()\n QA.run()\n QA.save_answers()\n\ndef main():\n #run_specific(\"mc500.train.18.25\")\n run_qa()\n # You can uncomment this next line to evaluate your\n # answers, or you can run score_answers.py\n score_answers()\n\ndef run_specific(qid):\n QA = QAEngine()\n question = QA.get_question(qid)\n story = QA.get_story(question[\"sid\"])\n QA.answer_question(question, story)\n\nif __name__ == \"__main__\":\n\n main()\n","sub_path":"assignment8/qa.py","file_name":"qa.py","file_ext":"py","file_size_in_byte":22680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"155670419","text":"from channels.generic.websockets import JsonWebsocketConsumer\nfrom channels.binding.websockets import WebsocketBinding\nfrom django.db.models import Sum\nfrom .models import Article, Bounty, Claim\n\n\nclass CurationBinding(WebsocketBinding):\n model = Bounty\n stream = \"curating\"\n fields = \"id\", \"title\", \"description\", \"url\", \"total\"\n\n @classmethod\n def group_names(cls, instance):\n return cls.stream,\n\n def serialize_data(self, instance):\n article = instance.article\n return {\n 'id': article.pk,\n 'title': article.title,\n 'description': article.description,\n 'url': article.url,\n 'total': article.bounties.aggregate(total=Sum('amount'))['total'],\n }\n\n def has_permission(self, user, action, pk):\n return True # user.is_authenticated\n\n\nclass CurationConsumer(JsonWebsocketConsumer):\n groups = (\n CurationBinding.stream,\n )\n\n def connect(self, message, multiplexer=None, **kwargs):\n multiplexer.send({\n 'action': 'list',\n 'model': 'claim.bounty',\n 'data': [{\n 'id': article.pk,\n 'title': article.title,\n 'description': article.description,\n 'url': article.url,\n 'total': article.bounties.aggregate(total=Sum('amount'))['total'],\n } for article in Article.objects.filter(phase=Article.BIDDING).all()]\n })\n","sub_path":"trive/apps/claim/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"574018722","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 18 14:30:47 2018\n\n@author: GLOtastic\n\n\"\"\"\nfrom imu import IMU\nfrom pid import PID\nfrom ptu_newmark import PTU\nfrom ss import SS\n\nimport time\nimport random\nimport scipy.io as sio\nimport argparse\nfrom datetime import datetime\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport cv2\nimport ephem\nimport os\nfrom glob import glob\n\n\nclass SS_tracking:\n '''\n PID tracking of the sun using a FLIR Pan Tilt Unit and feedback from sun sensors\n \n Inputs:\n ss: list of sun sensor serial connection objects \n ptu: pan-tilt unit serial connection object\n ss_read: list of sun sensors to capture data from (ie ss_read=[1,2] will only read \n 2 sun sensors with instrument ids of 1 and 2)\n ss_track: list of sun sensors to use for tracking (ie ss_track=[1,2] will only track \n with 2 sun sensors with instrument ids of 1 and 2)\n ss_eshim_x: list of x-axis \"electronic shims (offset in degrees in sun \n sensor x-axis)\" for all sun sensors corresponding to the\n sun sensors listed in in ss_track\n ss_eshim_y: list of y-axis \"electronic shims (offset in degrees in sun \n sensor y-axis)\" for all sun sensors corresponding to the\n sun sensors listed in in ss_track\n pid_x: PID class object for tracking in pan-axis\n pid_y: PID class object for tracking with tilt-axis\n ptu_cmd_delay: number of seconds to pause between a pan-axis and tilt-axis PTU command\n track mode (int):\n 1: PID Position Control\n 2: PID Absolute Velocity Control\n 3: PID Velocity Derivative Control\n 4: No tracking - Read Sun Sensor Data Only\n 5: Ephemeris Tracking: Stationary platform\n 6: Ephemeris Tracking: Moving platform (need GPS sensor)\n hz: sampling frequency (in hz)\n track_time: number of seconds to track and record data\n save_dir: directory to save tracking data to\n show_display: (boolean) set display on/off\n screen_res: screen resolution (default = (1280,800))\n '''\n def __init__(self,\n ss,\n ptu_x,\n ptu_y,\n imu,\n ss_read=[1,2,3],\n ss_track=[1,2,3],\n ss_eshim_x=[0.0,0.0,0.0],\n ss_eshim_y=[0.0,0.0,0.0],\n filter_kern=[0.5,0.5],\n pid_x=None,\n pid_y=None,\n ptu_cmd_delay=0.025,\n track_mode=3,\n hz=20,\n track_time=120,\n save_dir = 'C:/git_repos/GLO/Tutorials/tracking/',\n track_x=True,\n track_y=True,\n screen_res=(1280,800)\n ):\n \n #Initialize parameters\n self.ss = ss\n self.ptu_x = ptu_x\n self.ptu_y = ptu_y\n self.imu=imu\n self.ss_read = ss_read\n self.ss_track = ss_track\n self.ss_eshim_x = ss_eshim_x\n self.ss_eshim_y = ss_eshim_y\n self.filter_kern = filter_kern\n self.pid_x = pid_x\n self.pid_y = pid_y\n self.ptu_cmd_delay=ptu_cmd_delay\n self.track_mode=track_mode\n self.hz=hz\n self.delay = 1.0/hz\n self.track_time=track_time\n self.save_dir = save_dir\n self.track_x = track_x\n self.track_y = track_y\n self.screen_res = screen_res\n \n #PtU initial paramaters\n try:\n self.ptu_x.cmd('@01STOP\\r') #Make sure PTU starts out stopped\n except:\n print('Could not Stop PTU pan axis, CHECK THE CABLES!!!')\n try:\n self.ptu_y.cmd('@01STOP\\r') #Make sure PTU starts out stopped\n except:\n print('Could not Stop PTU tilt axis, CHECK THE CABLES!!!')\n self.ptu_cmd_x = 0.0\n self.ptu_cmd_y = 0.0\n self.ptu_dir_x = 0\n self.ptu_dir_y = 0\n self.ptu_dir_x_new = 0\n self.ptu_dir_y_new = 0\n self.ptu_vel_lo = 15 #Set minimum velocity of PTU to 15 steps/sec\n self.ptu_vel_hi = 80000 #Set maximum velocity of ptu to 80000 steps/sec\n self.ptu_sat = False #gets set to True if PTU is saturated (0>ptu_vel<15 or ptu_vel>80000)\n self.pid_integrate = True #Set to False to ignore integral PID gain \n self.imu_filt_x = 0.0\n \n self.pid_x_dt = np.nan\n self.pid_y_dt = np.nan\n \n #Initialize PTU speed to 0\n self.spd_last_x = 0.0\n self.spd_last_y = 0.0\n \n self.t1=999\n self.t2=999\n self.t3=999\n self.t4=999\n self.t5=999\n self.t6=999\n self.t7=999\n self.t8=999\n self.t9=999\n self.t10=999\n self.t11=999\n \n #Initialized dataframe to store data \n self.data = pd.DataFrame(columns=['ss_mean_x',\n 'ss_mean_y',\n 'ss_filt_x',\n 'ss_filt_y',\n 'ss1_x_raw',\n 'ss1_y_raw',\n 'ss2_x_raw',\n 'ss2_y_raw',\n 'ss3_x_raw',\n 'ss3_y_raw',\n 'ptu_cmd_x',\n 'ptu_cmd_y',\n 'ptu_pos_x',\n 'ptu_pos_y',\n 'ptu_dir_x',\n 'ptu_dir_y',\n 'imu_accel_x',\n 'imu_accel_y',\n 'imu_accel_z',\n 'imu_ang_x',\n 'imu_ang_y',\n 'imu_ang_z',\n 'imu_mag_x',\n 'imu_mag_y',\n 'imu_mag_z',\n 'imu_ypr_x',\n 'imu_ypr_y',\n 'imu_ypr_z', \n 'imu_filt_x',\n 'elapsed',\n 't0',\n 't1',\n 't2',\n 't3',\n 't4',\n 't5',\n 't6',\n 't7',\n 't8',\n 't9',\n 't10',\n 't11',\n 'pid_out_x',\n 'pid_out_y',\n 'pid_x_dt',\n 'pid_y_dt'\n ])\n \n# def setup_ptu(self):\n# '''\n# Set PTU to the appropriate control mode\n# Not currently used, need to change this logic from FLIR to Newmark logic\n# '''\n# try:\n# #Position mode\n# if self.track_mode == 1:\n# self.ptu_x.cmd('ci ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('i ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('ps1000 ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('ts1000 ')\n# #Velocity Mode\n# if (self.track_mode == 2) | (self.track_mode == 3):\n# self.ptu_x.cmd('cv ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('i ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('ps0 ')\n# time.sleep(0.1)\n# self.ptu_x.cmd('ts0 ')\n# except:\n# sys.exit('Failed to set PTU control mode')\n \n def save_data(self):\n '''\n Check to see if directory for todays date exists, if not then create one\n and then save all data to a .csv file\n ''' \n file_time=time.strftime(\"%Y%m%d_%H%M%S\")\n dir_date = time.strftime(\"%Y%m%d\")+'/'\n if not os.path.exists(self.save_dir+dir_date):\n os.makedirs(self.save_dir+dir_date) \n #find all csv files in today's folder \n file_list = glob(self.save_dir+dir_date+ '/*.csv')\n run_number=0\n #loop through list \n if(len(file_list)!=0): #only check list if is not empty, if empty leave run number as zero\n for i in range(len(file_list)):\n run = file_list[i].split('RUN')[-1].split('.')[0]\n if int(run) >= run_number: \n run_number = int(run)+1 #make the run number one larger than the largest\n \n #Save data to file \n f_name=self.save_dir+dir_date+'ss_track_'+file_time+'_RUN'+str(run_number)+'.csv'\n print('saving tracking data to',f_name)\n self.data.to_csv(f_name,index_label='time')\n \n #Reopen data file and append header with various tracking run parameters\n df = pd.read_csv(f_name, header=None, index_col=None)\n n_cols=len(df.columns)\n print('df columns = ',len(df.columns))\n header=[]\n for j in range(n_cols):\n header.append('')\n #insert desired values into header[] in format set out below \n header[0]=self.pid_x.Kp\n header[1]=self.pid_y.Kp\n header[2]=self.pid_x.Ki\n header[3]=self.pid_y.Ki\n header[4]=self.pid_x.Kd\n header[5]=self.pid_y.Kd\n header[6]=self.hz\n header[7]=run_number\n header[8]=self.track_mode\n header[9]=self.track_time\n header[10]=self.ss_eshim_x\n header[11]=self.ss_eshim_y\n header[12]=self.filter_kern\n header[13] = self.track_x\n header[14] = self.track_y\n df.columns = header\n df.to_csv(f_name, index=False) #add line 1 of header\n \n df = pd.read_csv(f_name, header=None, index_col=None)\n n_cols=len(df.columns)\n header=[]\n for j in range(n_cols):\n header.append('')\n #add whatever strings to header \n header[0]='kpx'\n header[1]='kpy'\n header[2]='kix'\n header[3]='kiy'\n header[4]='kdx'\n header[5]='kdy'\n header[6]='hz'\n header[7]='run'\n header[8]='track_mode'\n header[9]='track_time'\n header[10]='eshim_x'\n header[11]='eshim_y'\n header[12] = 'filter_kern'\n header[13] = 'track_x'\n header[14] = 'track_y'\n df.columns = header\n df.to_csv(f_name, index=False) #add line 2 of header\n \n #Save data as matlab .mat file for simulation\n try:\n print('Saving .mat file to ',cwd+'/run'+str(run_number)+'.mat')\n sio.savemat(self.save_dir+dir_date+'ss_track_'+file_time+'_RUN'+str(run_number)+'.mat',\n {'elapsed':self.data['elapsed'].values,\n 'imu_filt_x':self.data['imu_filt_x'].values,\n 'imu_ang_x':self.data['imu_ang_x'].values,\n 'imu_ang_y':self.data['imu_ang_y'].values,\n 'imu_ang_z':self.data['imu_ang_z'].values,\n 'ss_filt_x':self.data['ss_filt_x'].values,\n 'ss_filt_y':self.data['ss_filt_y'].values,\n 'ss_mean_x':self.data['ss_mean_x'].values,\n 'ss_mean_y':self.data['ss_mean_y'].values,\n 'ptu_cmd_x':self.data['ptu_cmd_x'].values,\n 'ptu_cmd_y':self.data['ptu_cmd_y'].values,\n 'ptu_pos_x':self.data['ptu_pos_x'].values,\n 'ptu_pos_y':self.data['ptu_pos_y'].values,\n 'ptu_dir_x':self.data['ptu_dir_x'].values,\n 'ptu_dir_y':self.data['ptu_dir_y'].values,\n 'kpx':self.pid_x.Kp,\n 'kpy':self.pid_y.Kp,\n 'kix':self.pid_x.Ki,\n 'kiy':self.pid_y.Ki,\n 'kdx':self.pid_x.Kd,\n 'kdy':self.pid_y.Kd,\n 'hz':self.hz,\n 'track_mode':self.track_mode,\n 'track_time':self.track_time,\n 'ss_eshim_x':self.ss_eshim_x,\n 'ss_eshim_y':self.ss_eshim_y}) \n except:\n print('Could not save .mat file')\n \n def ptu_stop(self,axis='x'):\n '''\n Stop PTU and set ptu_dir to 0\n Specify axis = 'x' or 'y' corresponding to 'pan' or 'tilt' axis\n '''\n if axis == 'x':\n ptu_response = self.ptu_x.cmd('@01STOP\\r',delay=self.ptu_cmd_delay)\n if ptu_response == 'OK':\n self.ptu_dir_x_new=0\n else:\n self.ptu_dir_x_new = self.ptu_dir_x\n if axis == 'y':\n ptu_response = self.ptu_y.cmd('@01STOP\\r',delay=self.ptu_cmd_delay)\n if ptu_response == 'OK':\n self.ptu_dir_y_new=0\n else:\n self.ptu_dir_y_new = self.ptu_dir_y\n \n def ptu_set_speed(self,ptu_speed,axis='x'):\n '''\n Send absolute value of desired speed command to ptu \n Specify axis = 'x' or 'y' corresponding to 'pan' or 'tilt' axis\n '''\n if axis == 'x':\n self.t10 = time.time()\n command = '@01SSPD'+str(int(np.abs(ptu_speed)))+'\\r'\n self.ptu_x.cmd(command) #send x-axis ptu velocity command (absolute value of ptu_cmd\n #self.ptu_x.cmd('@01SSPD40000\\r')\n self.t11 = time.time()\n if axis == 'y':\n command = '@01SSPD'+str(int(np.abs(ptu_speed)))+'\\r'\n self.ptu_y.cmd(command) #send y-axis ptu velocity command (absolute value of ptu_cmd\n \n def ptu_jog_pos(self,axis='x'):\n '''\n Jog PTU in positive direction, set ptu_dir=1\n Specify axis = 'x' or 'y' corresponding to 'pan' or 'tilt' axis\n '''\n if axis == 'x':\n ptu_response = self.ptu_x.cmd('@01J+\\r') #jog ptu in positive direction\n if ptu_response == 'OK':\n print(self.cnt,'OK')\n self.ptu_dir_x_new=1\n else:\n self.ptu_dir_x_new = self.ptu_dir_x\n if axis == 'y':\n ptu_response = self.ptu_y.cmd('@01J+\\r') #jog ptu in positive direction\n if ptu_response == 'OK':\n self.ptu_dir_y_new=1\n else:\n self.ptu_dir_y_new = self.ptu_dir_y\n \n def ptu_jog_neg(self,axis='x'):\n '''\n Jog PTU in positive direction, set ptu_dir=-1\n Specify axis = 'x' or 'y' corresponding to 'pan' or 'tilt' axis\n '''\n if axis == 'x':\n ptu_response = self.ptu_x.cmd('@01J-\\r') #jog ptu in negative direction\n if ptu_response == 'OK':\n self.ptu_dir_x_new=-1\n else:\n self.ptu_dir_x_new = self.ptu_dir_x\n if axis == 'y':\n ptu_response = self.ptu_y.cmd('@01J-\\r') #jog ptu in negative direction\n if ptu_response == 'OK':\n self.ptu_dir_y_new=-1\n else:\n self.ptu_dir_y_new = self.ptu_dir_y\n \n def ptu_max_speed(self,axis='x'):\n '''\n set PTU to max allowable speed (80000)\n Specify axis = 'x' or 'y' corresponding to 'pan' or 'tilt' axis\n '''\n if axis == 'x':\n self.ptu_x.cmd('@01SSPD80000\\r')\n if axis == 'y':\n self.ptu_y.cmd('@01SSPD80000\\r')\n\n# def sine_wave(self,mode=1):\n# '''\n# mode 1: slow speed test\n# mode 2: fast speed test\n# '''\n# dt = time.time()-self.t_start\n# amp = 4.0\n# period = 3.0\n# offset = amp*np.sin(dt*2*np.pi/period)\n# return offset\n \n \n def run(self):\n '''\n Start tracking loop\n '''\n #Initialize PTU\n #self.setup_ptu()\n \n #Reference time for elapsed tracking time\n self.t_start = time.time() \n self.cnt = 0\n \n while True: #Main tracking loop that cycles at set sampling frequency\n #Time reference to ensure tracking operates at approximately set sampling frequency\n self.t0 = time.time()\n \n######################### Read Fine Sun Sensors ###############################\n ang_x = np.zeros(3,dtype=float) \n ang_y = np.zeros(3,dtype=float)\n ang_x.fill(np.nan)\n ang_y.fill(np.nan)\n\n #Collect Sun Sensor data\n for i in ss_read: #Loop through all sun sensors in ss_read\n self.ss[i-1].read_data_all() #Read all data from sun sensor using SS class, correct for python 0-indexing \n if i in self.ss_track: #Only include x and y SS offsets if included in ss_track\n ang_x[i-1] = self.ss[i-1].ang_x_raw + self.ss_eshim_x[i-1]\n ang_y[i-1] = self.ss[i-1].ang_y_raw + self.ss_eshim_y[i-1]\n \n #Uncomment the next three lines to test a sine wave \n# offset = self.sine_wave()\n# ang_x[i-1] = self.ss[i-1].ang_x_raw + offset\n# ang_y[i-1] = self.ss[i-1].ang_y_raw + offset\n print(ang_x,round(self.imu_filt_x*180/np.pi,4))\n######################## Take Mean of Fine Sun Sensors ######################## \n# #Take arithmetic mean of all sun sensors listed in ss_track\n self.ss_mean_x = np.nanmean(ang_x)\n self.ss_mean_y = np.nanmean(ang_y)\n \n# #Take geometric mean of all sun sensors listed in ss_track\n# num_x = np.count_nonzero(~np.isnan(ang_x)) #count number of non-nan elements in ang_x\n# num_y = np.count_nonzero(~np.isnan(ang_y)) #count number of non-nan elements in ang_y\n# self.ss_mean_x = np.nanprod(ang_x)**(1./num_x) #geometric mean\n# self.ss_mean_y = np.nanprod(ang_y)**(1./num_y) #geometric mean\n \n #Read current PTU position - need to implement, see genie_track_newmark.py\n \n #Read current IMU values (IMU filters values internally)\n try:\n self.imu_ang_r = self.imu.grab_ang_r()\n self.imu_filt_x = self.imu_ang_r.z\n except:\n print('Could not grab IMU data, cnt=',self.cnt)\n self.imu_filt_x = np.nan\n \n######################### Filter SS data ###################################### \n #Use filter kernel to filter ss_mean_x and ss_mean_y\n #initialize sun sensor filtered x/y by muliplying the current \n #ss_mean_x and ss_mean_y by the last index in the filter kernel\n self.ss_filt_x = self.filter_kern[-1]*self.ss_mean_x\n self.ss_filt_y = self.filter_kern[-1]*self.ss_mean_y\n \n #Now cycle through the rest of filter weights in filter_kern \n if len(self.filter_kern) > 1: #if filter window size = 1, then do no filtering\n if self.cnt > len(self.filter_kern): #wait until enough samples are available to filter \n #loop through the rest of the filter kernel and multiply the \n #weights by the appropriate indices of the past ss_mean_x and ss_mean_y values\n for i in np.arange(-1,-len(self.filter_kern),-1):\n self.ss_filt_x += self.filter_kern[i-1]*self.data['ss_mean_x'][i]\n self.ss_filt_y += self.filter_kern[i-1]*self.data['ss_mean_y'][i]\n else:\n #Just use raw ss data (mean values) until enough samples have been collected (# of elements of filter_kern)\n self.ss_filt_x = self.ss_mean_x\n self.ss_filt_y = self.ss_mean_y\n \n self.t1 = time.time()\n######################## PID Controller #######################################\n #Use ss_filt_x and ss_filt_y as input to PID controller to generate PID output\n try:\n if (self.ss_filt_x > -5) & (self.ss_filt_x < 5):\n self.pid_out_x,self.pid_y_dt = self.pid_x.GenOut(self.ss_filt_x,self.cnt) #generate x-axis control output in \"degrees\"\n print(self.cnt,self.pid_out_x)\n #Track mode 3: use differential velocity control (last speed + pid output)\n if self.track_mode == 2:\n self.ptu_cmd_x = self.pid_out_x*self.pid_x.deg2pos\n if self.track_mode == 3:\n self.ptu_cmd_x = self.spd_last_x + self.pid_out_x*self.pid_x.deg2pos #convert to PTU positions\n self.spd_last_x = self.ptu_cmd_x\n #Track mode 4: use PID output - imu_ang_z as PTU command\n if self.track_mode == 4:\n if self.imu_filt_x != np.nan:\n self.ptu_cmd_x = self.pid_out_x*self.pid_x.deg2pos - self.imu_filt_x #convert to PTU positions\n else:\n self.ptu_cmd_x = self.pid_out_x*self.pid_x.deg2pos #ignore IMU data if nan\n \n else:\n print('Sun sensor x-axis outside FOV, cnt=',self.cnt)\n self.pid_out_x = np.nan\n self.ptu_cmd_x = np.nan\n \n if (self.ss_filt_y > -5) & (self.ss_filt_y < 5):\n self.pid_out_y,self.pid_x_dt = self.pid_y.GenOut(self.ss_filt_y,self.cnt) #generate y-axis control output in \"degrees\"\n if self.track_mode == 2:\n self.ptu_cmd_y = self.pid_out_y*self.pid_y.deg2pos\n if self.track_mode == 3:\n self.ptu_cmd_y = self.spd_last_y + self.pid_out_y*self.pid_y.deg2pos #convert to PTU positions\n self.spd_last_y = self.ptu_cmd_y\n if self.track_mode == 4:\n self.ptu_cmd_y = self.pid_out_y*self.pid_y.deg2pos #ignore IMU data if nan\n else:\n print('Sun sensor y-axis outside FOV, cnt=',self.cnt)\n self.pid_out_y = np.nan\n self.ptu_cmd_y = np.nan \n \n except:\n print('PID output generation failed, cnt=',self.cnt)\n self.pid_out_x = np.nan\n self.ptu_cmd_x = np.nan\n self.pid_out_y = np.nan\n self.ptu_cmd_y = np.nan\n \n self.t2 = time.time()\n##################### PTU Logic ###############################################\n #Implement 'switch direction' logic for newmark PTU x-axis\n if self.track_x:\n self.t6 = time.time()\n if (self.ptu_dir_x < 0):\n \tif (-self.ptu_vel_hi < self.ptu_cmd_x < -self.ptu_vel_lo):\n \t\tself.ptu_set_speed(self.ptu_cmd_x,axis='x')\n \tif self.ptu_cmd_x < -self.ptu_vel_hi:\n \t\tself.ptu_max_speed(axis='x')\n \tif (-self.ptu_vel_lo < self.ptu_cmd_x < self.ptu_vel_lo):\n \t\tself.ptu_stop(axis='x')\n \tif (self.ptu_cmd_x >= self.ptu_vel_lo):\n \t\tself.ptu_stop(axis='x')\n \t\tself.ptu_set_speed(self.ptu_cmd_x,axis='x')\n \t\tself.ptu_jog_pos(axis='x')\n \n self.t7 = time.time()\n if self.ptu_dir_x > 0:\n \tif self.ptu_cmd_x <= -self.ptu_vel_lo:\n \t\tself.ptu_stop(axis='x')\n \t\tself.ptu_set_speed(-self.ptu_cmd_x,axis='x')\n \t\tself.ptu_jog_neg(axis='x')\n \tif (-self.ptu_vel_lo < self.ptu_cmd_x < self.ptu_vel_lo):\n \t\tself.ptu_stop(axis='x')\n \tif (self.ptu_vel_lo <= self.ptu_cmd_x <= self.ptu_vel_hi):\n \t\tself.ptu_set_speed(self.ptu_cmd_x,axis='x')\n \tif self.ptu_cmd_x > self.ptu_vel_hi:\n \t\tself.ptu_max_speed(axis='x')\n self.t8 = time.time() \t\n if self.ptu_dir_x == 0:\n \tif (-self.ptu_vel_hi <= self.ptu_cmd_x <= -self.ptu_vel_lo):\n \t\tself.ptu_set_speed(-self.ptu_cmd_x,axis='x')\n \t\tself.ptu_jog_neg(axis='x')\n \tif (self.ptu_vel_hi >= self.ptu_cmd_x >= self.ptu_vel_lo):\n \t\tself.ptu_set_speed(self.ptu_cmd_x,axis='x')\n \t\tself.ptu_jog_pos(axis='x')\n \tif (self.ptu_cmd_x < -self.ptu_vel_hi):\n \t\tself.ptu_max_speed(axis='x')\n \t\tself.ptu_jog_neg(axis='x')\n \tif (self.ptu_cmd_x > self.ptu_vel_hi):\n \t\tself.ptu_max_speed(axis='x')\n \t\tself.ptu_jog_pos(axis='x')\n self.t9 = time.time()\n self.ptu_dir_x = self.ptu_dir_x_new\n \n #Implement 'switch direction' logic for newmark PTU y-axis \n if self.track_y:\n if self.ptu_dir_y < 0:\n \tif (-self.ptu_vel_hi < self.ptu_cmd_y < -self.ptu_vel_lo):\n \t\tself.ptu_set_speed(self.ptu_cmd_y,axis='y')\n \tif self.ptu_cmd_y < -self.ptu_vel_hi:\n \t\tself.ptu_max_speed(axis='y')\n \tif (-self.ptu_vel_lo < self.ptu_cmd_y < self.ptu_vel_lo):\n \t\tself.ptu_stop(axis='y')\n \tif self.ptu_cmd_y >= self.ptu_vel_lo:\n \t\tself.ptu_stop(axis='y')\n \t\tself.ptu_set_speed(self.ptu_cmd_y,axis='y')\n \t\tself.ptu_jog_pos(axis='y')\n \n if self.ptu_dir_y > 0:\n \tif self.ptu_cmd_y <= -self.ptu_vel_lo:\n \t\tself.ptu_stop(axis='y')\n \t\tself.ptu_set_speed(-self.ptu_cmd_y,axis='y')\n \t\tself.ptu_jog_neg(axis='y')\n \tif (-self.ptu_vel_lo < self.ptu_cmd_y < self.ptu_vel_lo):\n \t\tself.ptu_stop(axis='y')\n \tif (self.ptu_vel_lo <= self.ptu_cmd_y <= self.ptu_vel_hi):\n \t\tself.ptu_set_speed(self.ptu_cmd_y,axis='y')\n \tif self.ptu_cmd_y > self.ptu_vel_hi:\n \t\tself.ptu_max_speed(axis='y')\n \t\n if self.ptu_dir_y == 0:\n \tif (-self.ptu_vel_hi <= self.ptu_cmd_y <= -self.ptu_vel_lo):\n \t\tself.ptu_set_speed(-self.ptu_cmd_y,axis='y')\n \t\tself.ptu_jog_neg(axis='y')\n \tif (self.ptu_vel_hi >= self.ptu_cmd_y >= self.ptu_vel_lo):\n \t\tself.ptu_set_speed(self.ptu_cmd_y,axis='y')\n \t\tself.ptu_jog_pos(axis='y')\n \tif (self.ptu_cmd_y < -self.ptu_vel_hi):\n \t\tself.ptu_max_speed(axis='y')\n \t\tself.ptu_jog_neg(axis='y')\n \tif (self.ptu_cmd_y > self.ptu_vel_hi):\n \t\tself.ptu_max_speed(axis='y')\n \t\tself.ptu_jog_pos(axis='y')\n \n self.ptu_dir_y = self.ptu_dir_y_new\n \n self.t3 = time.time()\n#################### PID Anti-Windup Logic #################################### \n #Implement PID anti-windup logic - turn off integral gain if PTU is saturated\n #Determine if PTU is saturated\n if np.abs(self.ptu_cmd_x) > self.ptu_vel_hi:\n \tself.ptu_sat = True\n if np.abs(self.ptu_cmd_x) < self.ptu_vel_lo:\n \tself.ptu_sat = True\n \t\n #If PTU is saturated, and offset is in same direction as PTU command, then disable PID integral gain \n if self.ptu_sat:\n \tif (self.ss_filt_x * self.ptu_cmd_x) > 0:\n self.pid_integrate = False\n \n #Use PID integral gain if PTU is not saturated\n if ~self.ptu_sat:\n self.pid_integrate = True\n \n self.t4 = time.time()\n############################# Store Data ###################################### \n #Record time elapsed from start of tracking loop to store in dataframe\n self.elapsed = time.time() - self.t_start\n self.d_time = datetime.now()\n if self.cnt > 1:\n self.dt = self.elapsed - self.data['elapsed'][self.cnt-1]\n \n# try:\n #Grab extra data from IMU\n self.imu_accel=self.imu.grab_accel()\n self.imu_ypr=self.imu.grab_ypr()\n self.imu_mag=self.imu.grab_mag()\n \n if self.cnt < 1:\n self.t5=1.0\n #Create a list of all data to nicely add a row of data to the dataframe\n data_add = [self.ss_mean_x,\n self.ss_mean_y,\n self.ss_filt_x,\n self.ss_filt_y,\n ang_x[0],\n ang_y[0],\n ang_x[1],\n ang_y[1],\n ang_x[2],\n ang_y[2],\n self.ptu_cmd_x,\n self.ptu_cmd_y,\n np.nan, #self.ptu_pos_x NEED to add\n np.nan, #self.ptu_pos_y NEED to add\n self.ptu_dir_x,\n self.ptu_dir_y,\n self.imu_accel.x,\n self.imu_accel.y,\n self.imu_accel.z,\n self.imu_ang_r.x,\n self.imu_ang_r.y,\n self.imu_ang_r.z,\n self.imu_mag.x,\n self.imu_mag.y,\n self.imu_mag.z,\n self.imu_ypr.x,\n self.imu_ypr.y,\n self.imu_ypr.z, \n self.imu_filt_x,\n self.elapsed,\n self.t0,\n self.t1,\n self.t2,\n self.t3,\n self.t4,\n self.t5,\n self.t6,\n self.t7,\n self.t8,\n self.t9,\n self.t10,\n self.t11,\n self.pid_out_x,\n self.pid_out_y,\n self.pid_x_dt,\n self.pid_y_dt\n ]\n# except:\n# #print('Could not grab IMU data accel, ypr, and mag, cnt=',self.cnt)\n# data_add = [np.nan,\n# np.nan,\n# ang_x[0],\n# ang_y[0],\n# ang_x[1],\n# ang_y[1],\n# ang_x[2],\n# ang_y[2],\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan,\n# np.nan, \n# self.imu_filt_x,\n# self.elapsed,\n# ]\n\n \n #add row of data to dataframe\n self.data.loc[self.d_time] = data_add\n \n #increment tracking loop counter\n self.cnt+=1\n \n #Maintain desired tracking loop frequency\n t_diff = time.time() - self.t0\n if self.delay - t_diff > 0:\n time.sleep(self.delay - t_diff)\n print('sleeping for ',self.delay - t_diff)\n self.t5 = time.time()\n #Check to see if specified tracking time has expired\n if (time.time() - self.t_start) > self.track_time:\n #Stop PTU from moving after tracking completes\n try:\n self.ptu_stop(self,axis='x')\n self.ptu_stop(self,axis='y')\n except:\n print('Could not send PTU zero speed command, watch your toes!')\n print('Tracking complete, thanks for playing!')\n return\n\n \nif __name__ == '__main__':\n cwd = os.getcwd() \n parser = argparse.ArgumentParser(description='Sun sensor tracking code\\n'+\n 'I will add description later, I promise...')\n \n###### Operational parameters ###########\n parser.add_argument('-tx','--track_x',\n default=True,\n type=bool,\n help='Tracking in x-axis')\n\n parser.add_argument('-ty','--track_y',\n default=False,\n type=bool,\n help='Tracking in y-axis')\n \n parser.add_argument('-tm','--track_mode', # 3 = differential velocity mode (no IMU)\n default=3, # 4 = IMU compensation\n type=int,\n help='Tracking mode')\n \n parser.add_argument('-fk','--filter_kern',\n default=[0.5,0.5],\n type=list,\n help='Filter mode')\n \n parser.add_argument('-fw','--filter_win',\n default=5,\n type=int,\n help='Filter window size') \n \n parser.add_argument('-pm','--ptu_offset_mode',\n default=0,\n type=int,\n help='PTU offset mode')\n\n parser.add_argument('-d','--display',\n default='False',\n type=str,\n help='show display')\n \n parser.add_argument('-t','--track_time',\n default=5,\n type=float,\n help='Total time to track (seconds)')\n \n parser.add_argument('-hz','--hz',\n default=20,\n type=float,\n help='Tracking frequency (hz)')\n \n parser.add_argument('-s','--save_dir',\n default=cwd+'/testing/',\n type=str,\n help='Directory to save data to')\n \n parser.add_argument('-r','--read_dir',\n default=cwd+'/Data.txt',\n type=str,\n help='File to read camera position from')\n \n# parser.add_argument('-h','--help',\n# default=False,\n# type=bool,\n# help='Display help')\n\n###### PID parameters ###############\n parser.add_argument('-kpx','--kpx',\n default=.04,\n type=float,\n help='Proportional gain x-axis')\n \n parser.add_argument('-kpy','--kpy',\n default=-0.04,\n type=float,\n help='Proportional gain y-axis')\n \n parser.add_argument('-kdx','--kdx',\n default=0.2,\n type=float,\n help='Derivative gain x-axis')\n \n parser.add_argument('-kdy','--kdy',\n default=-0.2,\n type=float,\n help='Derivative gain y-axis')\n \n parser.add_argument('-kix','--kix',\n default=0.0,\n type=float,\n help='Integral gain x-axis')\n \n parser.add_argument('-kiy','--kiy',\n default=0.0,\n type=float,\n help='Integral gain y-axis')\n\n \n######## Sun sensor parameters #################\n \n parser.add_argument('-ss1_r','--ss1_read',\n default=True,\n type=bool,\n help='Read data from SS1 (True/False)')\n \n parser.add_argument('-ss2_r','--ss2_read',\n default=False,\n type=bool,\n help='Read data from SS2 (True/False)')\n \n parser.add_argument('-ss3_r','--ss3_read',\n default=False,\n type=bool,\n help='Read data from SS3 (True/False)')\n \n parser.add_argument('-ss1','--ss1_track',\n default=True,\n type=bool,\n help='Track with SS1 (True/False)')\n \n parser.add_argument('-ss2','--ss2_track',\n default=False,\n type=bool,\n help='Track with SS2 (True/False)')\n \n parser.add_argument('-ss3','--ss3_track',\n default=False,\n type=bool,\n help='Track with SS3 (True/False)')\n\n# ss_eshim_x = [-1.763, -1.547, -1.578] #Specify electronic shims (x-dir) for sun sensors\n# ss_eshim_y = [-2.290, -2.377, -2.215] #Specify electronic shims (y-dir) for sun sensors \n parser.add_argument('-ss1_ex','--ss1_eshim_x',\n default=0.0,\n type=float,\n help='SS1 electronic shim x-axis')\n \n parser.add_argument('-ss2_ex','--ss2_eshim_x',\n default=-0.0,\n type=float,\n help='SS2 electronic shim x-axis')\n \n parser.add_argument('-ss3_ex','--ss3_eshim_x',\n default=0.0,\n type=float,\n help='SS3 electronic shim x-axis')\n \n parser.add_argument('-ss1_ey','--ss1_eshim_y',\n default=0.0,\n type=float,\n help='SS1 electronic shim y-axis')\n \n parser.add_argument('-ss2_ey','--ss2_eshim_y',\n default=0.0,\n type=float,\n help='SS2 electronic shim y-axis')\n \n parser.add_argument('-ss3_ey','--ss3_eshim_y',\n default=0.0,\n type=float,\n help='SS3 electronic shim y-axis')\n \n parser.add_argument('-ss1_c','--ss1_com_port',\n default='COM6',\n type=str,\n help='SS1 comm port')\n \n parser.add_argument('-ss2_c','--ss2_com_port',\n default='COM4',\n type=str,\n help='SS2 com port')\n \n parser.add_argument('-ss3_c','--ss3_com_port',\n default='COM8',\n type=str,\n help='SS3 com port')\n \n parser.add_argument('-ss1_b','--ss1_baud_rate',\n default=115200,\n type=int,\n help='SS1 baud_rate')\n \n parser.add_argument('-ss2_b','--ss2_baud_rate',\n default=115200,\n type=int,\n help='SS2 baud_rate')\n \n parser.add_argument('-ss3_b','--ss3_baud_rate',\n default=115200,\n type=int,\n help='SS3 baud_rate')\n \n parser.add_argument('-ss1_i','--ss1_inst_id',\n default=1,\n type=int,\n help='SS1 instrument id')\n \n parser.add_argument('-ss2_i','--ss2_inst_id',\n default=2,\n type=int,\n help='SS2 instrument id')\n \n parser.add_argument('-ss3_i','--ss3_inst_id',\n default=3,\n type=int,\n help='SS3 instrument id')\n \n###### IMU parameters ###########\n parser.add_argument('-imu_c','--imu_com_port',\n default='COM7',\n type=str,\n help='IMU comm port') \n \n parser.add_argument('-imu_b','--imu_baud_rate',\n default=115200,\n type=int,\n help='IMU baud_rate')\n \n \n###### PTU parameters ###########\n parser.add_argument('-ptu_xc','--ptu_x_com_port',\n default='COM9',\n type=str,\n help='IMU comm port') \n \n parser.add_argument('-ptu_xb','--ptu_x_baud_rate',\n default=115200,\n type=int,\n help='IMU baud_rate')\n \n parser.add_argument('-ptu_yc','--ptu_y_com_port',\n default='COM11',\n type=str,\n help='IMU comm port') \n \n parser.add_argument('-ptu_yb','--ptu_y_baud_rate',\n default=115200,\n type=int,\n help='IMU baud_rate')\n \n parser.add_argument('-ptu_d','--ptu_cmd_delay',\n default=0.00,\n type=float,\n help='PTU command delay')\n \n parser.add_argument('-ptu_s','--ptu_step_size',\n default=500,\n type=int,\n help='PTU step size (default=500)')\n\n# parser.add_argument('-ptu_m','--ptu_set_micro',\n# default=False,\n# type=bool,\n# help='set PTU to microstep (eighth)')\n \n parser.add_argument('-ptu_lat','--ptu_lat',\n default='37.205144',\n type=str,\n help='PTU latitude')\n\n parser.add_argument('-ptu_lon','--ptu_lon',\n default='-80.417560',\n type=str,\n help='PTU longitude')\n \n parser.add_argument('-ptu_alt','--ptu_alt',\n default=634,\n type=int,\n help='PTU altitude')\n \n parser.add_argument('-ptu_utc','--ptu_utc_off',\n default=4,\n type=int,\n help='PTU UTC offset')\n\n \n params=parser.parse_args() \n \n# if params.help:\n# print('Tracking Mode (use -tm= ):\\n'+\n# '1: PTU position-command mode: Simple PID control of ss offset\\n'+\n# '2: PTU velocity-command mode: -imu velocity + PID control of ss position\\n'+\n# '3: PTU velocity-command mode: -imu velocity - derivative of ss_offset + PID control of ss position\\n'+\n# '4: No tracking - Read Sun Sensor Data Only\\n'+\n# '5: Ephemeris Tracking: Stationary platform\\n'+\n# '6: Ephemeris Tracking: Moving platform (need GPS sensor)')\n# \n# print('Sun Sensor/IMU Filtering Mode (use -fm= ):\\n'+\n# '1: Raw data: Use mean of raw data from all tracking sun sensors\\n'+\n# '2: Rolling Mean: Apply rolling mean to last n samples (n=filter window size)\\n'+\n# '3: Butterworth: Apply butterworth filter to last n samples (n=filter window size)\\n')\n# \n# print('Filter window size (use -fw=)\\n'+\n# 'ie, -fw=4 will use a filter window size of 4')\n# sys.exit()\n \n #Define Modes \n track_mode = params.track_mode #default: 4 = no tracking\n ptu_offset_mode = params.ptu_offset_mode #default: 0 no PTU offset prior to tracking\n \n #Initiate PID control loop\n #pan-axis (x-axis) PID gains\n pid_x= PID(step_size=params.ptu_step_size) #'eighth' #pid_x will control azimuth ptu motor (assuming orientation of ss is correct)\n pid_x.SetKp(params.kpx) #0.44\n pid_x.SetKi(params.kix) #0.05*0\n pid_x.SetKd(params.kdx) #0.3\n \n #tilt-axis (y-axis) PID gains\n pid_y= PID(step_size=params.ptu_step_size) #pid_y will control azimuth ptu motor (assuming orientation of ss is correct)\n pid_y.SetKp(params.kpy) #-0.44\n pid_y.SetKi(params.kiy) #0.01*0\n pid_y.SetKd(params.kdy) #-0.3\n \n print('Pan axis (x-axis) PID gains kpx=',params.kpx,'kix=',params.kix,'kdx=',params.kdx)\n print('Tilt axis (t-axis) PID gains kpy=',params.kpy,'kiy=',params.kiy,'kdy=',params.kdy)\n\n #not used currently\n #Obtain ephemeris data\n# ep = ephem.Observer()\n\n #Establish communication with sun sensor/s - store in a list\n ss=[SS(inst_id=params.ss1_inst_id,com_port=params.ss1_com_port,baudrate=params.ss1_baud_rate),\n SS(inst_id=params.ss2_inst_id,com_port=params.ss2_com_port,baudrate=params.ss2_baud_rate),\n SS(inst_id=params.ss3_inst_id,com_port=params.ss3_com_port,baudrate=params.ss3_baud_rate)]\n \n #List of sun sensors to read data from\n ss_read = []\n if params.ss1_read:\n ss_read.append(1)\n if params.ss2_read:\n ss_read.append(2)\n if params.ss3_read:\n ss_read.append(3)\n \n #List of sun sensors to use for tracking (also need to check if data is being read from sensor)\n ss_track = []\n if params.ss1_read:\n if params.ss1_track:\n ss_track.append(1)\n if params.ss2_read:\n if params.ss2_track:\n ss_track.append(2)\n if params.ss3_read:\n if params.ss3_track:\n ss_track.append(3)\n \n\n print('eshims_x',[params.ss1_eshim_x,\n params.ss2_eshim_x,\n params.ss3_eshim_x])\n print('eshims_y',[params.ss1_eshim_y,\n params.ss2_eshim_y,\n params.ss3_eshim_y])\n \n #Establish communication with IMU\n imu=IMU(com_port=params.imu_com_port,baudrate=params.imu_baud_rate)\n \n #Establish communication with PTU\n try:\n if params.track_x:\n ptu_x = PTU(com_port=params.ptu_x_com_port,\n baudrate=params.ptu_x_baud_rate,\n cmd_delay=params.ptu_cmd_delay)\n else:\n ptu_x = None\n except:\n print('COULD NOT TALK TO PTU pan axis!!!')\n ptu_x=None\n try:\n if params.track_y:\n ptu_y = PTU(com_port=params.ptu_y_com_port,\n baudrate=params.ptu_y_baud_rate,\n cmd_delay=params.ptu_cmd_delay)\n else:\n ptu_y = None\n except:\n print('COULD NOT TALK TO PTU tilt axis!!!')\n ptu_y=None\n\n #Set ptu=None if not using tracking to ensure PTU is not moved after initial offset\n if track_mode == 4:\n ptu_x.ptu.close()\n ptu_y.ptu.close()\n ptu_x=None\n ptu_y=None\n print('Not tracking, so disconnecting from the PTU for safe measure')\n\n #Initiate PTU tracking\n ss_tracking = SS_tracking(ss,\n ptu_x,\n ptu_y,\n imu,\n ss_read=ss_read,\n ss_track=ss_track,\n ss_eshim_x=[params.ss1_eshim_x,\n params.ss2_eshim_x,\n params.ss3_eshim_x], \n ss_eshim_y=[params.ss1_eshim_y,\n params.ss2_eshim_y,\n params.ss3_eshim_y],\n filter_kern=params.filter_kern,\n pid_x=pid_x,\n pid_y=pid_y,\n ptu_cmd_delay=params.ptu_cmd_delay,\n track_mode=track_mode,\n hz=params.hz,\n track_time=params.track_time,\n save_dir=params.save_dir,\n track_x=params.track_x,\n track_y=params.track_y,\n )\n \n print('Tracking with sun sensors',ss_track,'for',params.track_time,'seconds')\n \n #Begin PTU tracking\n ss_tracking.run()\n \n #Save data\n ss_tracking.save_data()\n \n #Grab data in dataframe\n df = ss_tracking.data\n \n df['ss_time'] = df['t1']-df['t0']\n df['pid_time'] = df['t2']-df['t1']\n df['ptu_time'] = df['t3']-df['t2']\n df['aw_time'] = df['t4']-df['t3']\n df['data_time'] = df['t5']-df['t4']\n df['move_neg'] = df['t7']-df['t6']\n df['move_pos'] = df['t8']-df['t7']\n df['stopeed'] = df['t9']-df['t8']\n df['setspeed'] = df['t11']-df['t10']\n \n #Close IMU connection\n try:\n imu.imu.disconnect()\n except:\n print('Could not disconnect from IMU')\n \n #Close PTU connections\n try:\n ptu_x.cmd('@01STOP\\r')\n ptu_x.ptu.close()\n except:\n print('Could not disconnect from PTU Pan Axis')\n try:\n ptu_y.cmd('@01STOP\\r')\n ptu_y.ptu.close()\n except:\n print('Could not disconnect from PTU Tilt Axis')\n \n #Close sun sensor connections\n for i in range(len(ss)):\n try:\n ss[i].ss.serial.close() \n except:\n print('could not close sun sensor',i)\n\n ##################################### Plot Data ########################### \n try:\n #Plot y_angle raw vs. filtered \n x=df['elapsed']\n y1=df['imu_ang_z']*180./np.pi\n y2=df['imu_filt_x']*180./np.pi\n# y3=df['ss2_x_raw']\n y4=df['ss1_x_raw']\n# y5=df['ss2_x_raw']\n y6=df['ptu_cmd_x']\n y7=df['pid_out_x']\n\n #y12=df['imu_filt_y']*180./np.pi\n# y3=df['ss2_x_raw']\n y14=df['ss1_y_raw']\n# y5=df['ss2_x_raw']\n y16=df['ptu_cmd_y']\n \n plt.figure(figsize=(10,10))\n plt.plot(y4,y14,'o')\n win_size=1.0\n plt.xlim((-win_size,win_size))\n plt.ylim((-win_size,win_size))\n plt.hlines(0.1,-0.1,0.1,color='red')\n plt.vlines(0.1,-0.1,0.1,color='red')\n plt.hlines(-0.1,-0.1,0.1,color='red')\n plt.vlines(-0.1,-0.1,0.1,color='red')\n plt.grid()\n \n plt.figure()\n plt.hist(df['ss1_x_raw'],bins=200)\n \n plt.figure()\n plt.plot(x,y1,'o-',label='imu_ang_z')\n plt.xlabel('Time Elapsed (seconds)')\n plt.ylabel('Degrees')\n plt.title('X-Axis sensor data at '+str(params.hz)+'hz\\n kp='+str(params.kpx)+' ki='+str(params.kix)+' kd='+str(params.kdx))\n plt.legend()\n \n plt.figure()\n # plt.plot(x,y2,'o-',label='imu_filt_x')\n plt.plot(x,y4,'o-',label='ss2_ss_filt_x')\n # plt.plot(x,y4,'o-',label='filtered ss')\n plt.plot(x,y6/ss_tracking.pid_x.deg2pos,'o-',label='ptu_cmd_x')\n plt.plot(x,y7*10,'o',label='pid_out_x')\n plt.xlabel('Time Elapsed (seconds)')\n plt.ylabel('Degrees')\n #plt.ylim((-3,3))\n #plt.title('Y-Axis sensor data at '+str(hz)+'hz\\n kp='+str(params.kpy)+' ki='+str(params.kiy)+' kd='+str(params.kdy))\n plt.legend()\n \n plt.figure()\n plt.title('X-Axis sensor data at '+str(params.hz)+'hz\\n kp='+str(params.kpx)+' ki='+str(params.kix)+' kd='+str(params.kdx))\n plt.plot(x,y4,'o-',label='ss2_ang_x_raw')\n plt.plot(x,y6,'o-',label='ptu cmd x')\n plt.legend()\n plt.figure()\n # plt.plot(x,y2,'o-',label='imu_filt_x')\n plt.plot(x,y4,'o-',label='ss2_ss_filt_x')\n plt.plot(x,y1,'o-',label='imu_ang_z')\n # plt.plot(x,y4,'o-',label='filtered ss')\n plt.plot(x,y6/ss_tracking.pid_x.deg2pos,'o-',label='ptu_cmd_x')\n #plt.plot(x,y7*10,'o',label='pid_out_x')\n plt.xlabel('Time Elapsed (seconds)')\n plt.ylabel('Degrees')\n plt.hlines(0.1,x[0],x[-1],color='red')\n plt.hlines(-0.1,x[0],x[-1],color='red')\n #plt.ylim((-3,3))\n #plt.title('Y-Axis sensor data at '+str(hz)+'hz\\n kp='+str(params.kpy)+' ki='+str(params.kiy)+' kd='+str(params.kdy))\n plt.legend()\n except:\n print('Failed to plot data')\n\n\n## Add to help display \n# if manual_config == True:\n# ptu_micro = int(input('Set PTU to microstep mode?:\\n'+\n# '0: No\\n'+\n# '1: Yes\\n'+\n# '>>> '))\n#\n# \n# else:\n# filter_mode = default_filter_mode\n# \n# ptu_offset_mode = int(input('Select PTU offset mode:\\n'+\n# '0: No Pointing Offset\\n'+\n# '1: Point PTU at Sun\\n'+\n# '2: Point PTU at Moon\\n'+\n# '>>> ')) ","sub_path":"ss_track_newmark.py","file_name":"ss_track_newmark.py","file_ext":"py","file_size_in_byte":54096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"47596498","text":"\"\"\"\nASGI App using dataclasses module for request/response objects\n\"\"\"\n\n__version__ = '0.6.0a5'\n\nfrom apidaora.content import ContentType\nfrom apidaora.core.response import (\n HTMLResponse,\n JSONResponse,\n PlainResponse,\n Response,\n)\nfrom apidaora.method import MethodType\nfrom apidaora.openapi.app import operations_app as appdaora\nfrom apidaora.openapi.app import spec_app as appdaora_spec\nfrom apidaora.openapi.parameters import header_param\nfrom apidaora.openapi.path_decorator.base import path\nfrom apidaora.openapi.request import JSONRequestBody\n\n\n__all__ = [\n ContentType.__name__,\n MethodType.__name__,\n path.__name__,\n appdaora.__name__,\n appdaora_spec.__name__,\n HTMLResponse.__name__,\n JSONResponse.__name__,\n PlainResponse.__name__,\n Response.__name__,\n header_param.__name__,\n JSONRequestBody.__name__,\n]\n","sub_path":"apidaora/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"607412241","text":"# ------------------------------------------------------------------------------\n# Copyright (c) 2018 David Lechner \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# -----------------------------------------------------------------------------\n\n\"\"\"\nAn assortment of classes modeling specific features of the EV3 brick.\n\"\"\"\n\nfrom .core import *\n\n\nOUTPUT_A = 'pistorms:BAM1'\nOUTPUT_B = 'pistorms:BAM2'\nOUTPUT_C = 'pistorms:BBM1'\nOUTPUT_D = 'pistorms:BBM2'\n\nINPUT_1 = 'pistorms:BAS1'\nINPUT_2 = 'pistorms:BAS2'\nINPUT_3 = 'pistorms:BBS1'\nINPUT_4 = 'pistorms:BBS2'\n\n\nclass Leds(object):\n \"\"\"\n The PiStorms LEDs.\n \"\"\"\n\n red_left = Led(name_pattern='pistorms:BB:red:brick-status')\n red_right = Led(name_pattern='pistorms:BA:red:brick-status')\n green_left = Led(name_pattern='pistorms:BB:green:brick-status')\n green_right = Led(name_pattern='pistorms:BA:green:brick-status')\n blue_left = Led(name_pattern='pistorms:BB:blue:brick-status')\n blue_right = Led(name_pattern='pistorms:BA:blue:brick-status')\n\n LEFT = (red_left, green_left, blue_left)\n RIGHT = (red_right, green_right, blue_right)\n\n BLACK = (0, 0, 0)\n RED = (1, 0, 0)\n GREEN = (0, 1, 0)\n BLUE = (0, 0, 1)\n YELLOW = (1, 1, 0)\n CYAN = (0, 1, 1)\n MAGENTA = (1, 0, 1)\n\n @staticmethod\n def set_color(group, color, pct=1):\n \"\"\"\n Sets brightness of leds in the given group to the values specified in\n color tuple. When percentage is specified, brightness of each led is\n reduced proportionally.\n\n Example::\n\n Leds.set_color(LEFT, MAGENTA)\n \"\"\"\n for l, v in zip(group, color):\n l.brightness_pct = v * pct\n\n @staticmethod\n def set(group, **kwargs):\n \"\"\"\n Set attributes for each led in group.\n\n Example::\n\n Leds.set(LEFT, brightness_pct=0.5, trigger='timer')\n \"\"\"\n for led in group:\n for k in kwargs:\n setattr(led, k, kwargs[k])\n\n @staticmethod\n def all_off():\n \"\"\"\n Turn all leds off\n \"\"\"\n Leds.red_left.brightness = 0\n Leds.red_right.brightness = 0\n Leds.green_left.brightness = 0\n Leds.green_right.brightness = 0\n Leds.blue_left.brightness = 0\n Leds.blue_right.brightness = 0\n\n\nclass Button(ButtonEVIO):\n \"\"\"\n PiStorms Buttons\n \"\"\"\n\n @staticmethod\n def on_go(state):\n \"\"\"\n This handler is called by `process()` whenever state of 'enter' button\n has changed since last `process()` call. `state` parameter is the new\n state of the button.\n \"\"\"\n pass\n\n _buttons = {\n 'go': {\n 'name': '/dev/input/by-path/platform-3f804000.i2c-event',\n 'value': 103,\n },\n }\n\n @property\n def go(self):\n \"\"\"\n Check if 'go' button is pressed.\n \"\"\"\n return 'go' in self.buttons_pressed\n","sub_path":"F_flask/Part4_数据库/venv/Lib/site-packages/ev3dev/pistorms.py","file_name":"pistorms.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"230896497","text":"import moviepy.editor as mpy\n\n# 读取词云视频\nmy_clip = mpy.VideoFileClip('result.mp4')\n# 截取背景音乐\naudio_background = mpy.AudioFileClip('song.mp4').subclip(17, 42)\naudio_background.write_audiofile('vmt.mp3')\n# 视频中插入音频\nfinal_clip = my_clip.set_audio(audio_background)\n# 保存为最终的视频 动听的音乐!漂亮小姐姐词云跳舞视频!\nfinal_clip.write_videofile('final_video.mp4')\n","sub_path":"210207ciyun/06get_voice.py","file_name":"06get_voice.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232176293","text":"data = [int(n) for n in open('day08.txt').readline()]\ndata_size = len(data)\nwidth = 25\nheight = 6\nlayer_size = width * height\nlayers_count = data_size / layer_size\nlayers = [data[x:x+layer_size] for x in range(0, data_size, layer_size)]\n\nmin_zero_count = layers[0].count(0)\nmin_zero_layer = layers[0]\n\nfor layer in layers:\n zero_count = layer.count(0)\n if zero_count < min_zero_count:\n min_zero_count = zero_count\n min_zero_layer = layer\n\nprint(\"1=\", min_zero_layer.count(1) * min_zero_layer.count(2))\n\n\nrender = []\nfor idx in range(0, layer_size):\n for layer in layers:\n if layer[idx] == 2:\n continue\n elif layer[idx] == 1:\n render.append(\"*\")\n break\n else:\n render.append(\" \")\n break\n\nprint(len(render))\n\npicture = [render[x:x+width] for x in range(0, layer_size, width)]\npicture = [\"\".join(x) for x in picture]\n\nprint(\"\\n\".join(picture))\n","sub_path":"day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"148432599","text":"from pages import views\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nhandler404 = 'pages.views.notfound'\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'signschool.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^pages/', include('pages.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.landing, name = \"landing\"),\n url(r'^ourstory/$', views.Ourstory, name='Our Story'),\n url(r'^welcome/$', views.register_user, name='welcome'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^modules/$', views.modules, name='modules'),\n url(r'^hello/$', views.hello, name='hello'),\n url(r'^landing/$', views.home, name='home'),\n url(r'^BingSiteAuth.xml/$', views.Bing, name='Bing'),\n url(r'^sitemap.xml/$', views.Sitemap, name='Sitemap'),\n url(r'^robots.txt/$', views.robots, name='Robots'),\n url(r'^mobilelanding/$', views.mobilelanding, name='mobilelanding'),\n url(r'^mobilehello/$', views.mobilehello, name='mobilehello'),\n url(r'^threequickquestions$', views.landing_request, name='landing_request'),\n url(r'^thankyou/$', views.survey_submit, name='survey_submit'),\n url(r'^thanks/$', views.thankyou, name='thankyou'),\n url(r'^mobilethankyou/$', views.mobilethankyou, name='mobilethankyou'),\n url(r'^uhoh/$', views.uhoh, name='uhoh'),\n url(r'^legal/$', views.legal, name='legal'),\n url(r'^signin/$', views.pleasesignin, name='pleasesignin'),\n url(r'^auth_user/$', views.auth_user, name='auth_user'),\n url(r'^auth_user_demo/$', views.auth_user_demo, name='auth_user_demo'),\n url(r'^invalid/$', views.invalid_login, name='invalid_login'),\n url(r'^demo/$', views.demo, name='demo'),\n url(r'^demo1/$', views.demo1, name='demo1'),\n url(r'^demo2/$', views.demo2, name='demo2'),\n url(r'^demo3/$', views.demo3, name='demo3'),\n url(r'^demo4/$', views.demo4, name='demo4'),\n url(r'^demo5/$', views.demo5, name='demo5'),\n url(r'^demo6/$', views.demo6, name='demo6'),\n url(r'^demo7/$', views.demo7, name='demo7'),\n url(r'^demo8/$', views.demo8, name='demo8'),\n url(r'^demothanks/$', views.demothanks, name='demothanks'),\n url(r'^P5ex/$', views.P5ex, name='P5ex'),\n url(r'^P6ex/$', views.P6ex, name='P6ex'),\n url(r'^P7ex/$', views.P7ex, name='P7ex'),\n url(r'^P8ex/$', views.P8ex, name='P8ex'),\n url(r'^ClassmatesL1/$', views.ClassmatesL1, name='ClassmatesL1'),\n url(r'^ClassmatesP1/$', views.ClassmatesP1, name='ClassmatesP1'),\n url(r'^ClassmatesP2/$', views.ClassmatesP2, name='ClassmatesP2'),\n url(r'^ClassmatesP3/$', views.ClassmatesP3, name='ClassmatesP3'),\n url(r'^ClassmatesP4/$', views.ClassmatesP4, name='ClassmatesP4'),\n url(r'^ClassmatesP5/$', views.ClassmatesP5, name='ClassmatesP5'),\n url(r'^ClassmatesP6/$', views.ClassmatesP6, name='ClassmatesP6'),\n url(r'^ClassmatesP7/$', views.ClassmatesP7, name='ClassmatesP7'),\n url(r'^ClassmatesP8/$', views.ClassmatesP8, name='ClassmatesP8'),\n url(r'^ClassmatesP9/$', views.ClassmatesP9, name='ClassmatesP9'),\n url(r'^ClassmatesP10/$', views.ClassmatesP10, name='ClassmatesP10'),\n url(r'^ClassmatesQ1/$', views.ClassmatesQ1, name='ClassmatesQ1'),\n # url(r'^awesome/$', views.awesome, name='awesome'),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns(\n 'django.views.static',\n (r'media/(?P.*)',\n 'serve',\n {'document_root': settings.MEDIA_ROOT}), )\n\nurlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', \n \t{'document_root': settings.STATIC_ROOT}),\n )\n\nurlpatterns += staticfiles_urlpatterns()","sub_path":"signschool/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"41803515","text":"from libSRHD import SRHDRiemannSolver\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\n\n\n\n\ndef get_ps(rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma, T, xs, x0=0.5):\n print(rhoL, uxL, utL, pL, rhoR, uxR, utR, pR)\n solver = SRHDRiemannSolver(rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma, x0, verbose=False)\n qs = np.array([solver(x, T) for x in xs])\n return qs[:, 3]\n\ndef sod_problem2(N=100):\n gamma = 5./3\n rhoL = 1\n pL = 1\n uxL = 0.\n pR = 0.1\n rhoR = 0.125\n uxR = 0.5\n utL = None\n utR = 0\n variab = np.linspace(0.5, 0.999, N)\n return rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma, variab\n\n\ndef sod_problem(N=100):\n gamma = 5./3\n rhoL = 1\n pL = 1\n uxL = 0.5\n pR = 0.1\n rhoR = 0.125\n uxR = 0\n utL = 0\n utR = None\n variab = np.linspace(0, 0.9, N)\n return rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma, variab\n\n\nif __name__ == '__main__':\n\n xs = np.linspace(0, 1, 100)\n T = 0.4\n\n rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma, variab = sod_problem2(50)\n args = [rhoL, uxL, utL, pL, rhoR, uxR, utR, pR, gamma]\n var_idx = [idx for idx, v in enumerate(args) if v is None][0]\n\n def set_arg(v):\n args[var_idx] = v\n return True\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ps = [get_ps(*args, T, xs, x0=0.5) for v in variab if set_arg(v)]\n xs, variab = np.meshgrid(xs, variab)\n surf = ax.plot_surface(xs, variab, ps, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n ax.set_xlabel('x')\n ax.set_ylabel('variable')\n ax.set_zlabel('p')\n\n col_labels = ['L', 'R']\n row_labels = ['rho', 'ux', 'ut', 'p']\n table_vals = [[rhoL, rhoR], [uxL, uxR], [utL, utR], [pL, pR]]\n\n plt.table(cellText=table_vals,\n colWidths=[0.1] * 3,\n rowLabels=row_labels,\n colLabels=col_labels,\n loc='lower left')\n\n fig.colorbar(surf, shrink=0.5, aspect=5)\n\n plt.show()\n\n\n","sub_path":"TEST_varUt.py","file_name":"TEST_varUt.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"513536780","text":"#! /usr/bin/env python\n\nimport rospy\nimport actionlib\nimport random\n\nfrom my_nav_robot.msg import NavigateAction, NavigateFeedback, NavigateResult\n\ndef sign(x):\n if x >= 0:\n return 1\n else:\n return -1\n\nclass NavigateServer:\n def __init__(self, nodeName):\n self.server = actionlib.SimpleActionServer(\"my_nav_robot\",\n NavigateAction,\n execute_cb=self.execute,\n auto_start=False)\n self.nodeName = nodeName\n self.server.start()\n self.curPos = [0, 0] # current position\n self.maxStep = 3\n self.feedback = NavigateFeedback()\n self.result = NavigateResult()\n\n def execute(self, goal):\n r = rospy.Rate(5)\n rospy.loginfo(\"Navigate server is executing\")\n success = True\n\n # Go incrementally\n while self.curPos[0] != goal.x or self.curPos[1] != goal.y:\n if self.server.is_preempt_requested():\n rospy.loginfo(\"%s: Preempted\" % self.nodeName)\n success = False\n break\n xdiff = goal.x - self.curPos[0]\n self.curPos[0] += sign(xdiff) * min(random.randint(0, self.maxStep), abs(xdiff))\n ydiff = goal.y - self.curPos[1]\n self.curPos[1] += sign(ydiff) * min(random.randint(0, self.maxStep), abs(ydiff))\n\n self.feedback.x = self.curPos[0]\n self.feedback.y = self.curPos[1]\n self.feedback.status = \"Robot is moving. Now at: (%.2f, %.2f)\" % (self.curPos[0], self.curPos[1])\n self.server.publish_feedback(self.feedback)\n r.sleep()\n \n if success:\n self.result.reached = True\n rospy.loginfo(\"%s: Succeeded\" % self.nodeName)\n else:\n self.result.reached = False\n self.server.set_succeeded(self.result)\n\nif __name__ == '__main__':\n rospy.init_node('navigate_server')\n server = NavigateServer(rospy.get_name())\n rospy.spin()\n","sub_path":"scripts/navigate_server.py","file_name":"navigate_server.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"593524288","text":"import argparse\nimport pandas as pd\n\nparser = argparse.ArgumentParser(description='''Reads in a list of variables and\n builds a .csv from them - requires pandas''')\n# parser.add_argument('datafile', help='Datasheet')\nparser.add_argument('varfile', help='Variable file list')\nparser.add_argument('outfile', help='Output file')\nparser.add_argument('--nomissing', action='store_true', help='Removes rows with NA')\n\nargs = parser.parse_args()\n\nwith open(args.varfile) as f:\n variables = f.read().strip().split()\n\n# endswith()\n\ndf = pd.read_csv('../RUNDMC_data/rundmc_data.csv', na_values='Null')\ndf_subset = df[variables]\n\nif args.nomissing:\n df_subset = df_subset.dropna(axis=0)\n \ndf_subset.to_csv(args.outfile, index=False, header=True)\n","sub_path":"scripts/build_df.py","file_name":"build_df.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"38261774","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('authorities', '0008_auto_20160124_1443'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AuthorityServiceDetails',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),\n ('LAid', models.IntegerField(blank=True, null=True)),\n ('LGIL', models.IntegerField(blank=True, null=True)),\n ('URL', models.URLField(blank=True)),\n ('last_updated', models.DateTimeField(blank=True)),\n ('LGSL', models.ForeignKey(to='authorities.AuthorityServiceCategory')),\n ],\n ),\n migrations.AlterField(\n model_name='authority',\n name='ons_id',\n field=models.CharField(max_length=100, blank=True, unique=True),\n ),\n migrations.AddField(\n model_name='authorityservicedetails',\n name='SNAC',\n field=models.ForeignKey(to_field='ons_id', to='authorities.Authority'),\n ),\n ]\n","sub_path":"democracy_club/apps/authorities/migrations/0009_auto_20160124_1524.py","file_name":"0009_auto_20160124_1524.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"204463276","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef linear_regression(x, y):\n Sxx = np.sum(x * x) - np.sum(x)*np.sum(x) / len(x)\n Sxy = np.sum(x * y) - np.sum(x)*np.sum(y) / len(x)\n\n b = Sxy / Sxx\n a = np.mean(y) - b*np.mean(x)\n\n return a, b\n\ndef make_line(x, a, b):\n y = a + b*x\n return y\n\n\n# Generating correlated data\nmean : float = 0.0\nstd : float = 1.0\npoints : int = 100\n\nx = np.random.normal(mean, std, points)\ny = x + np.random.normal(mean, std, points)\n\na, b = linear_regression(x, y)\n\nreg_x = np.linspace(mean-3*std, mean+3*std, 100)\nreg_y = make_line(reg_x, a, b)\n\nequation = 'y = {} + x * {}'.format(\"%.2f\" % a, \"%.2f\" % b)\n\nplt.plot(reg_x, reg_y, '-b', label=equation)\nplt.scatter(x, y, c='orange')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(loc='upper left')\nplt.show()\n","sub_path":"curves/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"117547341","text":"#-*- coding: utf-8 -*-\n#\n#@PraktLib.py:\talle möglichen Funktionen und Beispiele, die bei Versuchsauswertungen hilfreich sein könnten\n#@author: Olexiy Fedorets\n#@date: Mon 18.09.2017\n\n# @TODO: fitData(method=\"manual,leastsq,ODR,curvefit,...\"), readLabFile ohne String,\n#\t\t residuen, abweichung mit fehler, chiq berechnen\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.fftpack\nimport scipy.odr\nimport io\nimport random\nimport scipy.optimize as spopt\n# import sys\n# sys.path.append(\"../../PraktikumPyLib/\")\n\nfef\n\ndef readLabFile(file):\n\t'''\n\tCASSY LAB Datei einlesen (Version fuer python3).\n\n\tMessdaten werden anhand von Tabulatoren identifiziert.\n\n\tGibt ein numpy-Array zurueck.\n\n\t'''\n\tf = open(file)\n\tdataSectionStarted = False\n\tdataSectionEnded = False\n\tdata = ''\n\tfor line in f:\n\t\tif '\\t' in line and not dataSectionEnded:\n\t\t\tdata += line\n\t\t\tdataSectionStarted = True\n\t\tif not '\\t' in line and dataSectionStarted:\n\t\t\tdataSectionEnded = True\n\tf.close()\n\tdnew = data.encode('utf-8',errors='ignore')\n\treturn np.genfromtxt(io.BytesIO(dnew), unpack=True, dtype=float)\n\ndef weightedMean(x, ex):\n\t# return np.average(x,weights=ex,returned=True) \t# this should be equivalent\n\tmean = np.sum(x/ex**2)/np.sum(1./ex**2)\n\tsigma = np.sqrt(1./np.sum(1./ex**2))\n\treturn mean, sigma\n\ndef minToDeg(value):\n\treturn value/60.\n\ndef degToSr(value):\n\treturn value*(2.*np.pi/360.)\n\ndef srToDeg(value):\n\treturn value*(360./(2.*np.pi))\n\ndef chiq(f,ydata,yerrors=1.,ndf=1.):\n\tchiq = np.sum(np.power((ydata-f)/yerrors,2))\n\treturn chiq, chiq/ndf\n\ndef deviation(expval,expval_err,trueval,trueval_err):\n\treturn np.abs(trueval-expval)/np.sqrt(expval_err**2+trueval_err**2)\n\n# @TODO\n# This is made for Python3 ONLY !!\ndef printAsLatexTable(data,colTitles,rowTitles=\"\",mathMode=True,decimals=2):\n\t# safety first :\n\tif len(colTitles) != data.shape[1]:\n\t\tprint(\"Dimensions of data and colTitles don't match!\")\n\t\treturn -1\n\tif 0 != len(rowTitles) and len(rowTitles) != data.shape[0]-1:\t\t\t\t\t# -1 because we don't put anything in upper left corner of the table\n\t\tprint(\"Dimensions of data and rowTitles don't match!\")\n\t\treturn -2\n\n\t# we need the r-strings here to escape format placeholders like {} or \\\n\tprint(\"\\n\")\n\tprint(r\"\\begin{table}[H]\")\n\tprint(r\"\\renewcommand{\\arraystretch}{1.5}\")\n\tprint(r\"\\centering\")\n\tprint(r\"\t\\begin{tabular}{|%s|}\" % \"|\".join(\"c\" for _ in colTitles))\n\tprint(r\"\t\\hline\")\n\tprint(r\"\t&\" if 0!=len(rowTitles) else \"\t\",\n\t\t\t\" & \".join(str(colTitle) for colTitle in colTitles),\n\t\t\tr\"\\\\\")\n\tprint(r\"\t\\hline\")\n\n\t# use of %g should be considered here, as we dont know how data will exactly look like\n\tif 0 != len(rowTitles):\n\t\tfor row,rowTitle in enumerate(rowTitles):\n\t\t\tprint(\"\t%s\" % str(rowTitle),\n\t\t\t\t\t\" & \".join(\"${:.{prec}f}$\".format(data[row,col], prec=decimals) if mathMode else \"%s\" % data[row,col] for col in range(data.shape[1]) ),\n\t\t\t\t\tr\"\\\\\")\n\t\t\tprint(\"\t\\hline\")\n\telse:\n\t\tfor row in range(data.shape[0]):\n\t\t\tprint(\"\t\",\n\t\t\t\t\t\" & \".join(\"${:.{prec}f}$\".format(data[row,col], prec=decimals) if mathMode else \"%s\" % data[row,col] for col in range(data.shape[1]) ),\n\t\t\t\t\tr\"\\\\\")\n\t\t\tprint(\"\t\\hline\")\n\n\tprint(r\"\t\\end{tabular}\")\n\tprint(r\"\\caption{ }\")\n\tprint(r\"\\label{table: }\")\n\tprint(r\"\\end{table}\")\n\tprint(\"\\n\")\n\treturn 0\n\ndef randomColors(num):\n\tcolors = []\n\tfor i in range(num):\n\t\tcolors.append(\"#%06X\" % random.randint(0,0xFFFFFF))\n\treturn colors\n\ndef separator(length):\n\tprint(\"=\"*length)\n\ndef linreg_manual(x,y,ey):\n\t'''\n\n\tLineare Regression.\n\n\tParameters\n\t----------\n\tx : array_like\n\t\tx-Werte der Datenpunkte\n\ty : array_like\n\t\ty-Werte der Datenpunkte\n\tey : array_like\n\t\tFehler auf die y-Werte der Datenpunkte\n\n\tDiese Funktion benoetigt als Argumente drei Listen:\n\tx-Werte, y-Werte sowie eine mit den Fehlern der y-Werte.\n\tSie fittet eine Gerade an die Werte und gibt die\n\tSteigung a und y-Achsenverschiebung b mit Fehlern\n\tsowie das chi^2 und die Korrelation von a und b\n\tals Liste aus in der Reihenfolge\n\t[a, ea, b, eb, chiq, cov].\n\t'''\n\n\ts = np.sum(1./ey**2)\n\tsx = np.sum(x/ey**2)\n\tsy = np.sum(y/ey**2)\n\tsxx = np.sum(x**2/ey**2)\n\tsxy = np.sum(x*y/ey**2)\n\tdelta = s*sxx-sx*sx\n\tb = (sxx*sy-sx*sxy)/delta\n\ta = (s*sxy-sx*sy)/delta\n\teb = np.sqrt(sxx/delta)\n\tea = np.sqrt(s/delta)\n\tcov = -sx/delta\n\tcorr = cov/(ea*eb)\n\tchiq = np.sum(((y-(a*x+b))/ey)**2)\n\n\treturn(a,ea,b,eb,chiq,corr)\n\ndef plotFit(x,xerr,y,yerr,title=\"test\",xlabel=\"\",ylabel=\"\",res_ylabel=r\"$y - (a \\cdot x + b)$\",capsize=3,fontsize=20,show=True,method='leastsq'):\n\t# print(len(x),len(xerr),len(y),len(yerr),y.shape)\n\tline = lambda p,x: p[0]*x+p[1]\n\n\n\tif method=='leastsq':\n\t\tp0 = [0,0]\t# start values\n\t\tchifunc = lambda p,x,xerr,y,yerr: (y-line(p,x))/np.sqrt(yerr**2+p[0]*xerr**2)\t# p[0] = d/dx line()\n\t\tfitparam,cov,_,_,_ = spopt.leastsq(chifunc,p0,args=(x,xerr,y,yerr),full_output=True)\n\t\t# print(fitparam,cov)\n\t\tchiq = np.sum(chifunc(fitparam,x,xerr,y,yerr)**2) / (len(y)-len(fitparam))\n\t\tfitparam_err = np.sqrt(np.diag(cov)*chiq)\t\t\t\t\t\t\t\t\t# leastsq returns the 'fractional covariance matrix'\n\t\t# print(chiq,fitparam_err)\n\n\tif method=='ODR':\n\t\ta_ini,ea_ini,b_ini,eb_ini,chiq_ini,corr_ini = linreg_manual(x,y,yerr)\n\n\n\t\tdef f(B, x):\n\t\t\treturn B[0]*x + B[1]\n\n\t\tmodel = scipy.odr.Model(f)\n\t\tdata = scipy.odr.RealData(x, y, sx=xerr, sy=yerr)\n\t\todr = scipy.odr.ODR(data, model, beta0=[a_ini, b_ini])\n\t\toutput = odr.run()\n\t\tndof = len(x)-2\n\t\tchiq = output.res_var*ndof\n\t\tcorr = output.cov_beta[0,1]/np.sqrt(output.cov_beta[0,0]*output.cov_beta[1,1])\n\n\t\tfitparam = [output.beta[0],output.beta[1]]\n\t\tfitparam_err = [output.sd_beta[0],output.sd_beta[1]]\n\n\tif show:\n\t\tfig,ax = plt.subplots(2,1,figsize=(15,10))\n\t\tresidue = y-line(fitparam,x)\n\t\tax[0].plot(x,line(fitparam,x),'r-',\n\t\t\t\t\tlabel=\"Fit: $a = %.3f \\pm %.3f$, \\n $b = %.3f \\pm %.3f$\"\n\t\t\t\t\t\t\t% (fitparam[0],fitparam_err[0],fitparam[1],fitparam_err[1]))\n\t\tax[0].errorbar(x,y,xerr=xerr,yerr=yerr,fmt='.',color='b',capsize=capsize-1)\n\t\tax[0].set_title(title,fontsize=fontsize)\n\t\tax[0].set_xlabel(xlabel,fontsize=fontsize)\n\t\tax[0].set_ylabel(ylabel,fontsize=fontsize)\n\t\tax[0].legend(loc='lower right',fontsize=fontsize)\n\t\tax[0].grid(True)\n\t\tax[1].errorbar(x,residue,yerr=np.sqrt(yerr**2+fitparam[0]*xerr**2),fmt='x',color='b',capsize=capsize,\n\t\t\t\t\tlabel=r\"$\\frac{\\chi^2}{ndf} = %.3f$\" % np.around(chiq,3))\n\t\tax[1].axhline(0,color='r')\n\t\tax[1].set_title(\"Residuenverteilung\",fontsize=fontsize)\n\t\tax[1].set_xlabel(xlabel,fontsize=fontsize)\n\t\tax[1].set_ylabel(res_ylabel,fontsize=fontsize)\n\t\tax[1].legend(loc='upper right',fontsize=fontsize)\n\t\tax[1].grid(True)\n\t\tfig.tight_layout()\n\t\tfig.savefig(\"Plots/\"+title+\".pdf\",format='pdf',dpi=256)\n\n\treturn fitparam,fitparam_err,chiq\n\n####################################################################################\n\n\n\n\ndef lineare_regression_xy(x,y,ex,ey):\n\t'''\n\n\tLineare Regression mit Fehlern in x und y.\n\n\tParameters\n\t----------\n\tx : array_like\n\t\tx-Werte der Datenpunkte\n\ty : array_like\n\t\ty-Werte der Datenpunkte\n\tex : array_like\n\t\tFehler auf die x-Werte der Datenpunkte\n\tey : array_like\n\t\tFehler auf die y-Werte der Datenpunkte\n\n\tDiese Funktion benoetigt als Argumente vier Listen:\n\tx-Werte, y-Werte sowie jeweils eine mit den Fehlern der x-\n\tund y-Werte.\n\tSie fittet eine Gerade an die Werte und gibt die\n\tSteigung a und y-Achsenverschiebung b mit Fehlern\n\tsowie das chi^2 und die Korrelation von a und b\n\tals Liste aus in der Reihenfolge\n\t[a, ea, b, eb, chiq, cov].\n\n\tDie Funktion verwendet den ODR-Algorithmus von scipy.\n\t'''\n\ta_ini,ea_ini,b_ini,eb_ini,chiq_ini,corr_ini = lineare_regression(x,y,ey)\n\n\tdef f(B, x):\n\t\treturn B[0]*x + B[1]\n\n\tmodel = scipy.odr.Model(f)\n\tdata = scipy.odr.RealData(x, y, sx=ex, sy=ey)\n\todr = scipy.odr.ODR(data, model, beta0=[a_ini, b_ini])\n\toutput = odr.run()\n\tndof = len(x)-2\n\tchiq = output.res_var*ndof\n\tcorr = output.cov_beta[0,1]/np.sqrt(output.cov_beta[0,0]*output.cov_beta[1,1])\n\n\treturn output.beta[0],output.sd_beta[0],output.beta[1],output.sd_beta[1],chiq,corr\n\n\ndef fourier(t,y):\n\t'''\n\n\tFourier-Transformation.\n\n\tParameters\n\t----------\n\tt : array_like\n\t\tZeitwerte der Datenpunkte\n\ty : array_like\n\t\ty-Werte der Datenpunkte\n\n\tGibt das Fourierspektrum in Form zweier Listen (freq,amp)\n\tzurueck, die die Fourieramplituden als Funktion der zugehoerigen\n\tFrequenzen enthalten.\n\t'''\n\tdt = (t[-1]-t[0])/(len(t)-1)\n\tfmax = 0.5/dt\n\tstep = fmax/len(t)\n\tfreq=np.arange(0.,fmax,2.*step)\n\tamp = np.zeros(len(freq))\n\ti=0\n\tfor f in freq:\n\t\tomega=2.*np.pi*f\n\t\tsc = sum(y*np.cos(omega*t))/len(t)\n\t\tss = sum(y*np.sin(omega*t))/len(t)\n\t\tamp[i] = np.sqrt(sc**2+ss**2)\n\t\ti+=1\n\treturn (freq,amp)\n\n\ndef fourier_fft(t,y):\n\t'''\n\n\tSchnelle Fourier-Transformation.\n\n\tParameters\n\t----------\n\tt : array_like\n\t\tZeitwerte der Datenpunkte\n\ty : array_like\n\t\ty-Werte der Datenpunkte\n\n\tGibt das Fourierspektrum in Form zweier Listen (freq,amp)\n\tzurueck, die die Fourieramplituden als Funktion der zugehoerigen\n\tFrequenzen enthalten.\n\t'''\n\tdt = (t[-1]-t[0])/(len(t)-1)\n\t# print(dt,t.size)\n\tamp = abs(scipy.fftpack.fft(y))\n\tfreq = scipy.fftpack.fftfreq(len(t),dt)\n\t# amp = np.fft.fft(y)\n\t# freq = np.fft.fftfreq(len(t))\n\treturn (freq,amp)\n\n\ndef exp_einhuellende(t,y,ey,Sens=0.1):\n\t'''\n\tExponentielle Einhuellende.\n\n\tParameters\n\t----------\n\tt : array_like\n\t\tZeitwerte der Datenpunkte\n\ty : array_like\n\t\ty-Werte der Datenpunkte\n\tey : array_like\n\t\tFehler auf die y-Werte der Datenpunkte\n\tSens : float, optional\n\t\tSensitivitaet, Wert zwischen 0 und 1\n\n\tDie Funktion gibt auf der Basis der drei Argumente (Listen\n\tmit t- bzw. dazugehoerigen y-Werten plus y-Fehler) der Kurve die\n\tParameter A0 und delta samt Fehlern der Einhuellenden von der Form\n\tA=A0*exp(-delta*t) (Abfallende Exponentialfunktion) als Liste\n\t[A0, sigmaA0, delta, sigmaDelta] aus.\n\tOptional kann eine Sensibilitaet angegeben werden, die bestimmt,\n\tbis zu welchem Prozentsatz des hoechsten Peaks der Kurve\n\tnoch Peaks fuer die Berechnung beruecksichtigt werden (default=10%).\n\t'''\n\tif not 0.y[1]:\n\t\tPeaks.append(y[0])\n\t\tPeakZeiten.append(t[0])\n\t\tPeakFehler.append(ey[0])\n\tfor i in range(1,len(t)-1):\n\t\tif y[i] >= y[i+1] and \\\n\t\t y[i] >= y[i-1] and \\\n\t\t ( len(Peaks)==0 or y[i] != Peaks[-1] ): #handle case \"plateau on top of peak\"\n\t\t Peaks.append(y[i])\n\t\t PeakZeiten.append(t[i])\n\t\t PeakFehler.append(ey[i])\n\n\t# Loesche alle Elemente die unter der Sensibilitaetsschwelle liegen\n\tSchwelle=max(Peaks)*Sens\n\tfor i in range(0,len(Peaks)):\n\t\tif Peaks[i] > Schwelle:\n\t\t\tGutePeaks.append(Peaks[i])\n\t\t\tGutePeakZeiten.append(PeakZeiten[i])\n\t\t\tGutePeakFehler.append(PeakFehler[i])\n\n\t# Transformiere das Problem in ein lineares\n\tPeaksLogarithmiert = log(np.array(GutePeaks))\n\tFortgepflanzteFehler = np.array(GutePeakFehler) / np.array(GutePeaks)\n\tLR = lineare_regression(np.array(GutePeakZeiten),PeaksLogarithmiert,FortgepflanzteFehler)\n\n\tA0=exp(LR[2])\n\tsigmaA0=LR[3]*exp(LR[2])\n\tdelta=-LR[0]\n\tsigmaDelta=LR[1]\n\treturn(A0,sigmaA0,delta,sigmaDelta)\n\ndef untermenge_daten(x,y,x0,x1):\n\t'''\n\tExtrahiere kleinere Datensaetze aus (x,y), so dass x0 <= x <= x1\n\t'''\n\txn=[]\n\tyn=[]\n\tfor i,v in enumerate(x):\n\t\tif x0<=v<=x1:\n\t\t\txn.append(x[i])\n\t\t\tyn.append(y[i])\n\n\treturn (np.array(xn),np.array(yn))\n\ndef peak(x,y,x0,x1):\n\t'''\n\tApproximiere ein lokales Maximum in den Daten (x,y) zwischen x0 und x1.\n\t'''\n\tN = len(x)\n\tymin = max(y)\n\tymax = min(y)\n\ti1 = 0\n\ti2 = N-1\n\tfor i in range(N):\n\t\tif x[i]>=x0:\n\t\t\ti1=i\n\t\t\tbreak\n\tfor i in range(N):\n\t\tif x[i]>=x1:\n\t\t\ti2=i+1\n\t\t\tbreak\n\tfor i in range(i1,i2):\n\t\tif y[i]>ymax:\n\t\t\tymax=y[i]\n\t\tif y[i]ymax*val:\n\t\t\ti0=i\n\t\t\tbreak\n\tfor i in range(i0+1,N):\n\t\tif y[i]>> from detect_peaks import detect_peaks\n\t>>> x = np.random.randn(100)\n\t>>> x[60:81] = np.nan\n\t>>> # detect all peaks and plot data\n\t>>> ind = detect_peaks(x, show=True)\n\t>>> print(ind)\n\n\t>>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5\n\t>>> # set minimum peak height = 0 and minimum peak distance = 20\n\t>>> detect_peaks(x, mph=0, mpd=20, show=True)\n\n\t>>> x = [0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0]\n\t>>> # set minimum peak distance = 2\n\t>>> detect_peaks(x, mpd=2, show=True)\n\n\t>>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5\n\t>>> # detection of valleys instead of peaks\n\t>>> detect_peaks(x, mph=0, mpd=20, valley=True, show=True)\n\n\t>>> x = [0, 1, 1, 0, 1, 1, 0]\n\t>>> # detect both edges\n\t>>> detect_peaks(x, edge='both', show=True)\n\n\t>>> x = [-2, 1, -2, 2, 1, 1, 3, 0]\n\t>>> # set threshold = 2\n\t>>> detect_peaks(x, threshold = 2, show=True)\n\t\"\"\"\n\n\tx = np.atleast_1d(x).astype('float64')\n\tif x.size < 3:\n\t\treturn np.array([], dtype=int)\n\tif valley:\n\t\tx = -x\n\t# find indices of all peaks\n\tdx = x[1:] - x[:-1]\n\t# handle NaN's\n\tindnan = np.where(np.isnan(x))[0]\n\tif indnan.size:\n\t\tx[indnan] = np.inf\n\t\tdx[np.where(np.isnan(dx))[0]] = np.inf\n\tine, ire, ife = np.array([[], [], []], dtype=int)\n\tif not edge:\n\t\tine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0]\n\telse:\n\t\tif edge.lower() in ['rising', 'both']:\n\t\t\tire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0]\n\t\tif edge.lower() in ['falling', 'both']:\n\t\t\tife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0]\n\tind = np.unique(np.hstack((ine, ire, ife)))\n\t# handle NaN's\n\tif ind.size and indnan.size:\n\t\t# NaN's and values close to NaN's cannot be peaks\n\t\tind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)]\n\t# first and last values of x cannot be peaks\n\tif ind.size and ind[0] == 0:\n\t\tind = ind[1:]\n\tif ind.size and ind[-1] == x.size-1:\n\t\tind = ind[:-1]\n\t# remove peaks < minimum peak height\n\tif ind.size and mph is not None:\n\t\tind = ind[x[ind] >= mph]\n\t# remove peaks - neighbors < threshold\n\tif ind.size and threshold > 0:\n\t\tdx = np.min(np.vstack([x[ind]-x[ind-1], x[ind]-x[ind+1]]), axis=0)\n\t\tind = np.delete(ind, np.where(dx < threshold)[0])\n\t# detect small peaks closer than minimum peak distance\n\tif ind.size and mpd > 1:\n\t\tind = ind[np.argsort(x[ind])][::-1] # sort ind by peak height\n\t\tidel = np.zeros(ind.size, dtype=bool)\n\t\tfor i in range(ind.size):\n\t\t\tif not idel[i]:\n\t\t\t\t# keep peaks with the same height if kpsh is True\n\t\t\t\tidel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \\\n\t\t\t\t\t& (x[ind[i]] > x[ind] if kpsh else True)\n\t\t\t\tidel[i] = 0 # Keep current peak\n\t\t# remove the small peaks and sort back the indices by their occurrence\n\t\tind = np.sort(ind[~idel])\n\n\tif show:\n\t\tif indnan.size:\n\t\t\tx[indnan] = np.nan\n\t\tif valley:\n\t\t\tx = -x\n\t\t_plot(x, mph, mpd, threshold, edge, valley, ax, ind)\n\n\treturn ind\n\n\n\n\n\n\n #\n #\n # import numpy as np\n # from numpy import sqrt,sin,cos,log,exp\n # import scipy\n # import scipy.fftpack\n # import scipy.odr\n #\n # import numpy as np\n # import matplotlib.pyplot as plt\n # from pylab import *\n #\n # def sigmagew(liste):\n # k=0\n # for i in range(len(liste)):\n # k+=1/liste[i]**2\n # sigma= sqrt(1/k)\n # return sigma\n #\n # def meangew(y,sigma):\n # k=0\n # for i in range(len(sigma)):\n # k+=y[i]/sigma[i]**2\n # mean=k*(sigmagew(sigma)**2)\n # return mean\n #\n # def fourier_fft(t,y):\n # '''\n #\n # Schnelle Fourier-Transformation.\n #\n # Parameters\n # ----------\n # t : array_like\n # Zeitwerte der Datenpunkte\n # y : array_like\n # y-Werte der Datenpunkte\n #\n # Gibt das Fourierspektrum in Form zweier Listen (freq,amp)\n # zurueck, die die Fourieramplituden als Funktion der zugehoerigen\n # Frequenzen enthalten.\n # '''\n # dt = (t[-1]-t[0])/(len(t)-1)\n # amp = abs(scipy.fftpack.fft(y))\n # freq = scipy.fftpack.fftfreq(len(t),dt)\n # return (freq,amp)\n #\n # def fourier(t,y):\n # '''\n #\n # Fourier-Transformation.\n #\n # Parameters\n # ----------\n # t : array_like\n # Zeitwerte der Datenpunkte\n # y : array_like\n # y-Werte der Datenpunkte\n #\n # Gibt das Fourierspektrum in Form zweier Listen (freq,amp)\n # zurueck, die die Fourieramplituden als Funktion der zugehoerigen\n # Frequenzen enthalten.\n # '''\n #\n # dt = (t[-1]-t[0])/(len(t)-1)\n # fmax = 0.5/dt\n # step = fmax/len(t)\n # freq=np.arange(0.,fmax,2.*step)\n # amp = np.zeros(len(freq))\n # i=0\n # for f in freq:\n # omega=2.*np.pi*f\n # sc =0\n # ss =0\n #\n # for j in range(len(t)):\n # sc += (y[j]*cos(omega*t[j]))/len(t)\n # ss += (y[j]*sin(omega*t[j]))/len(t)\n #\n #\n #\n # amp[i] = sqrt(sc**2+ss**2)\n # i+=1\n # return (freq,amp)\n #\n #\n # def peaks(y, Sens):\n # Peaks=[]\n # GutePeaks=[]\n # Indexes=[]\n # GuteIndexes=[]\n #\n #\n # for i in range(2,len(y)-3):\n # if abs(y[i]) >= abs(y[i+1]) and \\\n # abs(y[i]) >= abs(y[i-1]) and \\\n # abs(y[i]) >= abs(y[i+2]) and \\\n # abs(y[i]) >= abs(y[i-2]) and \\\n # abs(y[i]) >= abs(y[i+3]) and \\\n # abs(y[i]) >= abs(y[i-3]) and \\\n # ( len(Peaks)==0 or y[i] != Peaks[-1] ): #handle case \"plateau on top of peak\"\n # Peaks.append(y[i])\n # Indexes.append(i)\n #\n #\n # # Loesche alle Elemente die unter der Sensibilitaetsschwelle liegen\n # Schwelle=max(Peaks)*Sens\n # for i in range(0,len(Peaks)):\n # if abs(Peaks[i]) > abs(Schwelle):\n # GutePeaks.append(Peaks[i])\n # GuteIndexes.append(i)\n #\n # ind=[]\n # for i in range(len(GuteIndexes)):\n # ind.append(Indexes[GuteIndexes[i]])\n #\n # return ind\n #\n # def differenz(x):\n # diff = []\n # for i in range(len(x)-1):\n # d = abs(x[i+1]-x[i])\n # diff.append(d)\n # return diff\n #\n # def skiplines (text, n): # n (Anzahl an Zeilen zu skippen)\n # for i in range(n):\n # text.readline()\n #\n # def spalten (text, n): # n (Welche Spalte soll generiert werden)\n # spalte = []\n # for i in range(800):\n # bumper = text.readline()\n # zeile = bumper.split('\\t') # gespaltene Zeile\n # spalte.append(zeile [n-1])\n # return spalte\n #\n\n\n\n\n\n\n\n\n\n\n\t# annotate:\n\t# ax[0][0].annotate(\"Guete: Q = U_0/U_cross = %.2f\" % (Ucross/U0), xy=(0.65,0.5), xycoords='axes fraction')\n\t# plt.xticks(list(plt.xticks()[0]) + extraticks)\n\t# lines = plt.plot(x,y)\n\t# ax = lines[0].axes\n\t# ax.set_xticks(list(ax.get_xticks()) + extraticks)\n\n\t# plt.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95,wspace=0.1) # just to make better use of space\n\t# plt.get_current_fig_manager().window.showMaximized()\n\n\n\t# QsG1,sigmaQsG1 = map(list,zip(*resultsG1))\t\t\t\t\t\t\t\t\t\t\t# so macht man aus einer liste von tuplen zwei listen von jeweils allen tuple[0] und tuple[1]\n # QsG2,sigmaQsG2 = map(list,zip(*resultsG2))\n# >>> pairs.sort(key=lambda pair: pair[1])\n# >>> pairs.sort(key=lambda pair: pair[1])\n","sub_path":"GP1/PraktLib.py","file_name":"PraktLib.py","file_ext":"py","file_size_in_byte":25672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453128780","text":"from django.http import HttpResponse\nfrom caja.serializers import MovimientoCajaImprimirSerializer as MovimientosSerializer\nfrom typing import List, Optional\nfrom datetime import datetime\nfrom decimal import Decimal\n\nfrom common.imprimir import setUpStyles, MARGINS, pdf_tabla, paragraph, GRIS_OSCURO\n\nfrom reportlab.lib.pagesizes import A4, landscape\nfrom reportlab.platypus.doctemplate import SimpleDocTemplate\nfrom reportlab.platypus import Table, Paragraph, TableStyle\nfrom reportlab.lib.units import mm\nfrom reportlab.lib import colors\n\nLARGOS_CABECERA = [100*mm, 75*mm, 103*mm]\nLARGOS_PIE = [249*mm, 24*mm]\n\n#Columnas contiene en cada entrada (nombre_columna, tamaño, key)\nCOLUMNAS = (('Hora', 14*mm, 'hora'), ('Usuario', 17*mm, 'usuario'),\n ('Tipo de mov.', 27*mm, 'tipo'), ('Paciente', 33*mm, 'paciente'),\n ('Obra Social', 33*mm, 'obra_social'), ('Médico', 33*mm, 'medico'),\n ('Práctica', 23*mm, 'practica'), ('Detalle', 49*mm, 'concepto'),\n ('Monto', 21*mm, 'monto'), ('Monto ac.', 23*mm, 'monto_acumulado'))\n\nstyles = setUpStyles()\n\ndef generar_pdf_caja(\n response: HttpResponse, movimientos: MovimientosSerializer,\n fecha: Optional[datetime], monto_acumulado: Decimal, total: Decimal\n) -> HttpResponse:\n pdf = SimpleDocTemplate(\n response,\n pagesize=landscape(A4),\n title='Movimientos de caja {0}'.format(fecha),\n topMargin=MARGINS['top'],\n bottomMargin=MARGINS['bottom'],\n )\n\n elements = pdf_encabezado(fecha, monto_acumulado)\n largos_columnas = [columna[1] for columna in COLUMNAS]\n elements += pdf_tabla(movimientos, largos_columnas, pdf_tabla_encabezado, pdf_tabla_body)\n elements += pdf_pie(total)\n\n pdf.build(elements)\n return response\n\n\ndef pdf_encabezado(fecha: Optional[datetime], monto_acumulado: int) -> List[Table]:\n fecha_str = fecha.strftime('%A, %d de %B de %Y') if fecha else ''\n return [Table([[\n paragraph('INFORME DE MOVIMIENTOS DE CAJA', 'Heading3'),\n paragraph(fecha_str, 'Center'),\n paragraph(f'Monto acumulado hasta la fecha: {monto_acumulado}', 'Right')\n ]],\n colWidths=LARGOS_CABECERA,\n )]\n\ndef pdf_tabla_encabezado() -> List[List[Paragraph]]:\n return [[paragraph(columna[0]) for columna in COLUMNAS]]\n\n\ndef pdf_tabla_body(movimientos: MovimientosSerializer) -> List[List[Paragraph]]:\n return [\n [paragraph(movimiento[key[2]]) for key in COLUMNAS]\n for movimiento in movimientos\n ]\n\ndef pdf_pie(total: Decimal):\n return [Table([[paragraph('Total:'), paragraph(f'${total}')]],\n colWidths=LARGOS_PIE,\n style=TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(GRIS_OSCURO))])\n )]\n","sub_path":"caja/imprimir.py","file_name":"imprimir.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"650682026","text":"#simsim2.py\n\nimport random\nimport time\n\nf = open(\"D:\\Code\\project\\simsim2\\sim.txt\", 'r')\nlines = f.readlines()\n\nwhile 1:\n mal = input(\"나 >> \")\n if mal == \"그만\": break \n time.sleep(0.3)\n if mal == \"강성훈\":\n print(\"심심이 >> 잘생김\\n\")\n continue\n print(\"심심이 >>\", random.choice(lines))","sub_path":"sim_t1.py","file_name":"sim_t1.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"238989588","text":"from typing import List\nfrom db.repository.userrole import get_role\nimport re\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\n\nfrom db.schemas.groupdevice import GroupCreate, GroupUpdate, ShowGroup\nfrom db.repository.groupdevice import create_group, delete_group, devices_present_in_group, list_groups, retrived_group, update_group\nfrom db.session import get_db\nfrom db.models.user import Users\nfrom apis.version1.route_login import get_current_user_from_token\nfrom db.repository.association import delete_association, delete_association_by_group\nfrom core.config import settings\n\nrouter = APIRouter()\n\n\n@router.post(\"/group\", response_model=ShowGroup)\ndef create_new_group(group: GroupCreate, db: Session = Depends(get_db), current_user: Users = Depends(get_current_user_from_token)):\n owner_id = current_user.user_id\n userrole = get_role(user_id=owner_id, db=db)\n if userrole.role_id == settings.ADMIN or userrole.role_id == settings.MANAGER:\n group = create_group(group=group, db=db, owner_id=owner_id)\n return group\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail=\"You have not privilages to create device\")\n\n\n@router.get(\"/{group_id}\", response_model=ShowGroup)\ndef retrived_group_by_name(group_id: int, db: Session = Depends(get_db)):\n group = retrived_group(group_id=group_id, db=db)\n if not group:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Group with {group_id} not found\")\n return group\n\n\n\n@router.put(\"/{group_id}\")\ndef update_group_by_name(group_id: int, group: GroupUpdate, db: Session = Depends(get_db), current_user: Users = Depends(get_current_user_from_token)):\n owner_id = current_user.user_id\n groups = retrived_group(group_id=group_id, db=db)\n if groups is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Device with id {group_id} not found\")\n if groups.group_owner_id == current_user.user_id:\n message = update_group(group_id=group_id, db=db, group=group, owner_id=owner_id)\n if not message:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Device with id {group_id} not found\")\n return \"Successfully Updated\"\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail=\"You have not privilages to update this device\") \n\n\n\n@router.delete(\"/{group_id}\")\ndef delete_device_by_name(group_id: int, db: Session = Depends(get_db), current_user: Users = Depends(get_current_user_from_token)):\n owner_id = current_user.user_id\n groups = retrived_group(group_id=group_id, db=db)\n if not groups:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Group with name {group_id} not found\")\n if groups.group_owner_id == current_user.user_id:\n delete_association_by_group(group_id=group_id,db=db,owner_id=owner_id)\n delete_group(group_id=group_id,owner_id=owner_id,db=db)\n return \"Successfully Deleted\"\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"You are not permitted\")\n\n\n@router.get(\"/{group_id}/devices\")\ndef retrived_device_from_group(group_id: int,db: Session = Depends(get_db)):\n device = devices_present_in_group(group_id=group_id, db=db)\n if device is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Device not found\")\n return device\n\n\n\n# @router.get(\"/groups\", response_model=List[ShowGroup])\n# def list_of_all_groups(db: Session = Depends(get_db)):\n# groups = list_groups(db=db)\n# return groups\n\n\n","sub_path":"backend/apis/version1/route_group.py","file_name":"route_group.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"172811629","text":"\"\"\"\n Copyright 2020 Kartik Sharma, Saurabh Saxena\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n ==============================================================================\n\n\"\"\"\n\n\"\"\" Flask App Main Views \"\"\"\nimport base64\nfrom flask.views import View\nfrom flask import (\n render_template,\n request,\n jsonify,\n Flask,\n)\n\nfrom core import builder\nfrom . import topics\n\napp = Flask(__name__, template_folder=\"././templates\")\nSUGGESTIONS = topics.SUGGESTIONS\n\n\nclass HomePageView(View):\n \"\"\"Recarxiv Homepage View Handler\"\"\"\n\n methods = [\"GET\"]\n\n def dispatch_request(self):\n return render_template(\"homepage/homepage.html\")\n\n\nclass FetchUserSuggestionHandler(View):\n \"\"\"User Suggestions Input\"\"\"\n\n methods = [\"GET\"]\n\n def dispatch_request(self):\n return render_template(\"app/FetchSuggestionPage.html\", suggestions=SUGGESTIONS)\n\n\nclass UserSuggestedTopicHandler(View):\n \"\"\"Fetch user suggested topics and return success\"\"\"\n\n methods = [\"POST\"]\n\n def dispatch_request(self):\n fetch_topics = request.form.get(\"selected\")\n selected = fetch_topics.split(\",\")\n url_string = \"\"\n for names in selected:\n url_string += names + \"-\"\n encoded_strign = base64.b64encode(bytes(url_string, \"utf-8\"))\n return jsonify(\n {\"message\": \"success\", \"url\": str(encoded_strign.decode(\"UTF-8\", \"ignore\"))}\n )\n\n\nclass RecommendedArxiv(View):\n \"\"\"Recommend Papers based on selected topics\"\"\"\n\n methods = [\"GET\"]\n\n def dispatch_request(self, arxiv_base64):\n selected_topics = (\n base64.b64decode(arxiv_base64).decode(\"UTF-8\", \"ignore\").split(\"-\")[:-1]\n )\n user_profile = []\n for index in selected_topics:\n user_profile.append(SUGGESTIONS[index])\n clustertopic = builder.ClusterTopic()\n payload = clustertopic(user_profile)\n return render_template(\"app/RecommendArxiv.html\", payload=payload)\n","sub_path":"views/main_views.py","file_name":"main_views.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"478500254","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\BitBucket\\djmicrosip_apps\\djmicrosip_facturacion\\djmicrosip_facturacion\\urls.py\n# Compiled at: 2017-09-21 14:27:03\nfrom django.conf.urls import patterns, url\nfrom . import views\nurlpatterns = patterns('', (\n '^$', views.index), (\n '^facturar/(?P\\\\d+)/$', views.facturar), (\n '^factura_ticket/$', views.FacturaTicket), (\n '^mostrar_factura/$', views.mostrar_factura))","sub_path":"pycfiles/djmicrosip_facturacion-0.0.1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"385210343","text":"__author__ = 'amir'\n\n\nNUM_PHASES=0\nTREE=0\n\nlst=[\"TREE\",\"ROLLOUT\",\"NUM_PHASES\"]\nEnum1={}\nfor x,ind in enumerate(lst):\n Enum1[ind]=x\n\nlst=[\"CONSISTENT\",\"INCONSISTENT\",\"RESAMPLED\",\"OUT_OF_PARTICLES\"]\nEnum2={}\nfor x,ind in enumerate(lst):\n Enum2[ind]=x\n\nclass STATUS(object):\n def __init__(self):\n self.Phase=Enum1[\"TREE\"]\n self.Particles=Enum2[\"CONSISTENT\"]\n","sub_path":"sfl/Planner/pomcp_old/pomcp/STATUS.py","file_name":"STATUS.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"378223735","text":"from nn.learning_algorithm import LearningAlgorithm\nfrom nn import NeuralNetwork as NN, sigmoid, MultilayerPerceptron, online, minibatch, batch, relu\nfrom nn import ErrorCalculator\nfrom nn.activation_functions import identity, tanh, tanh_classification\nfrom nn.utilities import encode_categorical, plot\nfrom nn.utilities import read_monk\nimport numpy as np\nfrom nn import validation, split_dataset\n\n\nif __name__ == '__main__':\n train_data, test_data = read_monk(3)\n train_set, validation_set = split_dataset(train_data, 2/3, to_shuffle=True, seed=0)\n\n seed = 78\n epochs_limit = 466\n eta = 0.1\n alpha = 0.5\n alambd = 0.001\n validation_error = ErrorCalculator.MSE\n\n nn = NN(\n seed=seed,\n epochs_limit=epochs_limit,\n learning_algorithm=batch,\n n_init=1,\n error_calculator=ErrorCalculator.MSE,\n architecture=MultilayerPerceptron(\n size_hidden_layers=(2, 2),\n eta=eta,\n alpha=alpha,\n alambd=alambd,\n activation=tanh_classification,\n activation_hidden=relu,\n ),\n )\n\n nn.fit(train_set)\n\n nn.error_calculator = ErrorCalculator.MSE\n print('mse', nn.compute_error(train_set), nn.compute_error(validation_set), nn.compute_error(test_data))\n\n nn.error_calculator = ErrorCalculator.MEE\n print('mee', nn.compute_error(train_set), nn.compute_error(validation_set), nn.compute_error(test_data))\n\n nn.error_calculator = ErrorCalculator.ACC\n print('acc', nn.compute_error(train_set), nn.compute_error(validation_set), nn.compute_error(test_data))\n\n # MSE\n nn.error_calculator = ErrorCalculator.MSE\n training_curve = nn.compute_learning_curve(train_set)\n validation_curve = nn.compute_learning_curve(validation_set)\n testing_curve = nn.compute_learning_curve(test_data)\n\n print('mse_last_curve', training_curve[-1], validation_curve[-1], testing_curve[-1])\n plot(training_curve, validation=validation_curve, testing=testing_curve)\n\n # ACC\n nn.error_calculator = ErrorCalculator.ACC\n training_curve = nn.compute_learning_curve(train_set)\n validation_curve = nn.compute_learning_curve(validation_set)\n testing_curve = nn.compute_learning_curve(test_data)\n\n print('acc_last_curve', training_curve[-1], validation_curve[-1], testing_curve[-1])\n plot(training_curve, validation=validation_curve, testing=testing_curve)\n","sub_path":"nn/playground/monk/monk3_plot.py","file_name":"monk3_plot.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"260722619","text":"# Saebom Kwon, saebom, 38120092, SI507 Waiver\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'http://www.michigandaily.com'\ng = requests.get(url)\n\nsoup = BeautifulSoup(g.content, 'html.parser')\n\ndef get_link(item):\n link_list = []\n li = soup.select(\"ol > li > a\")\n for link in li:\n link_list.append(link.get('href'))\n return link_list\n\nlink_list = get_link(soup.find_all('ol'))\n\ndef article_info(item):\n toon_url = 'http://www.michigandaily.com' + item\n g = requests.get(toon_url)\n soup = BeautifulSoup(g.content, 'html.parser')\n title = soup.find('title')\n title = title.text.replace(\" | The Michigan Daily\", \"\")\n try:\n author = soup.select('.byline > .link > a')[0].text\n except:\n author = None\n return title, author\n\nmost_read_list = []\n\nfor link in link_list:\n most_read_data = (article_info(link))\n most_read_list.append(most_read_data)\n\nprint(\"Michigan Daily -- MOST READ\")\nfor title, author in most_read_list:\n print(title, \"\\n by\", author)\n","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"429219476","text":"import numpy as np\nimport os\nimport pandas as pd\nimport matplotlib\nimport numpy as np\n\n# matplotlib.use('TkAgg')\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\nimport matplotlib.pyplot as plt\nimport csv\nimport os\n\nfrom cnns.nnlib.utils.general_utils import get_log_time\n\nprint(matplotlib.get_backend())\n\ndelimiter = ';'\nclasses_nr = 10\n\nylabel_size = 25\nfont = {'size': 30}\nmatplotlib.rc('font', **font)\nlw = 4\nfontsize = 25\nlegend_size = fontsize\ntitle_size = fontsize\nfont = {'size': fontsize}\nmatplotlib.rc('font', **font)\n\nlegend_position = 'right'\nframeon = False\nbbox_to_anchor = (0.0, -0.1)\n\n# plt.interactive(True)\n# http://ksrowell.com/blog-visualizing-data/2012/02/02/optimal-colors-for-graphs/\nMY_BLUE = (57, 106, 177)\nMY_ORANGE = (218, 124, 48)\nMY_GREEN = (62, 150, 81)\nMY_RED = (204, 37, 41)\nMY_BLACK = (83, 81, 84)\nMY_GOLD = (148, 139, 61)\nMY_VIOLET = (107, 76, 154)\nMY_BROWN = (146, 36, 40)\nMY_OWN = (25, 150, 10)\n\n\ndef get_color(COLOR_TUPLE_255):\n return [x / 255 for x in COLOR_TUPLE_255]\n\n\nline_width = 4\ncolors = [get_color(color) for color in\n [MY_RED, MY_BLUE, MY_RED, MY_GREEN, MY_BLACK, MY_GOLD,\n MY_VIOLET, MY_OWN, MY_BROWN, MY_GREEN]]\nmarkers = [\"o\", \"+\", \"^\", \"v\", \"D\", \"^\", \"+\", 'o', 'v', '+']\nlinestyles = [\"-\", \"--\", \":\", \"--\", \"-\", \"--\", \"-\", \"--\", ':', ':']\n\n\ndef check_image_indexes(data, step):\n image_indexes = get_column(data, col_nr=13, col_name='image_index',\n dtype=np.int)\n i = 1\n j = 0\n for val in image_indexes:\n if i != val:\n print(f\"{i} has to be equal {val}\")\n i += 1\n if i == step:\n print('j: ', j)\n i = 0\n i += 1\n\n\nstats = {\n 'avg': np.nanmean,\n # 'median': np.median,\n # 'std': np.std,\n # 'min': np.min,\n # 'max': np.max,\n}\n\n\ndef get_stats(vals):\n results = {}\n for key, op in stats.items():\n results[key] = op(vals)\n return results\n\n\ndef get_column(data, col_nr, col_name, dtype=np.float):\n # col_name_from_col_nr = data_all[col_nr - 1][0]\n # print('col name: ', col_name_from_col_nr)\n assert col_name == col_name\n vals = np.asarray(\n data.iloc[:, col_nr],\n dtype=dtype)\n return vals\n\n\ndef get_col_nr(data, col_name):\n W = data.shape[1]\n for i in range(W):\n data_col_name = data.iloc[0, i]\n # print('data_col_name: ', data_col_name)\n if data_col_name == col_name:\n return i\n return None\n\n\ndef get_col_val(data, col_name, dtype=np.float):\n col_nr = get_col_nr(data, col_name)\n if col_nr is None:\n raise Exception(f'Column with name: {col_name} not found.')\n col_nr_values = col_nr + 1\n return get_column(data=data, col_nr=col_nr_values,\n col_name=col_name, dtype=dtype)\n\n\ndef get_col_vals(data, col_names, dtype=np.float):\n col_vals = []\n for col_name in col_names:\n col_val = get_col_val(data=data, col_name=col_name, dtype=dtype)\n col_vals.append(col_val)\n return col_vals\n\n\ndef plot_graph(recovered_org_grad, recovered_2nd_grad,\n not_recovered_org_grad, not_recovered_2nd_grad):\n i = 0\n plt.scatter(recovered_org_grad, recovered_2nd_grad,\n label='recovered',\n lw=line_width,\n color=colors[i % len(colors)],\n linestyle=linestyles[i % len(linestyles)],\n # linestyle='None',\n marker=markers[i % len(markers)])\n i += 1\n plt.scatter(not_recovered_org_grad, not_recovered_2nd_grad,\n label='not recovered',\n lw=line_width,\n color=colors[i % len(colors)],\n linestyle=linestyles[i % len(linestyles)],\n # linestyle='None',\n marker=markers[i % len(markers)])\n\n # plt.title('Scatter plot pythonspot.com')\n plt.xlabel('org grad')\n plt.ylabel('2nd highest org grad')\n plt.legend()\n plt.show()\n\n\ndef plot_results(results):\n fig = plt.figure(figsize=(16, 7))\n plt.subplot(2, 1, 1)\n plt.title(\"Carlini-Wagner $L_2$ attack (confidence=1000)\", fontsize=title_size)\n\n x = results[:, 0]\n y_1 = results[:, 1] * 100\n\n plt.plot(x, y_1,\n # label='train on SVD representation (3 channels, V*D*U is p by p)',\n label=f\"% lowest gradient = highest confidence\",\n lw=lw,\n linestyle=\":\",\n marker='',\n color=get_color(MY_BLUE)\n )\n\n # condition number\n y_2 = results[:, 2] * 100\n\n plt.plot(x, y_2,\n # label='train on SVD representation (3 channels, V*D*U is p by p)',\n label=\"% adversarial examples found\",\n lw=lw,\n linestyle='-',\n marker='o',\n color=get_color(MY_RED)\n )\n\n # % confidence value\n y_3 = results[:, 3] * 100\n\n plt.plot(x, y_3,\n # label='train on SVD representation (3 channels, V*D*U is p by p)',\n label=\"avg adv confidence\",\n lw=lw,\n linestyle='-',\n marker='^',\n color=get_color(MY_GREEN)\n )\n\n # plt.xlabel(\"C&W $L_2$ attack strength\")\n plt.ylabel(\"Normalized %\", fontsize=ylabel_size)\n plt.xscale('log', basex=10)\n plt.ylim(0, 100)\n minx = 0.0001\n maxx = 10\n plt.xlim(minx, maxx)\n # plt.xticks(np.arange(min(x), max(x) + 5000, 5000))\n # plt.xlim(0, 23000)\n # plt.grid()\n plt.legend(loc='lower right',\n frameon=frameon,\n prop={'size': legend_size},\n # bbox_to_anchor=bbox_to_anchor,\n ncol=1,\n )\n\n # plot the adversarial distance\n plt.subplot(2, 1, 2)\n y_3 = results[:, -1]\n plt.plot(x, y_3,\n # label='train on SVD representation (3 channels, V*D*U is p by p)',\n label=\"Adversarial $L_2$ distance\",\n lw=lw,\n linestyle='-',\n marker='^',\n color=get_color(MY_BLACK)\n )\n\n plt.xlabel(\"C&W $L_2$ attack strength\")\n plt.ylabel(\"$L_2$ distance\", fontsize=ylabel_size)\n plt.xscale('log', basex=10)\n # plt.ylim(0, 100)\n # plt.xticks(np.arange(min(x), max(x) + 5000, 5000))\n plt.xlim(minx, maxx)\n # plt.grid()\n plt.legend(loc='lower right',\n frameon=frameon,\n prop={'size': legend_size},\n # bbox_to_anchor=bbox_to_anchor,\n ncol=1,\n )\n\n fig.tight_layout()\n # plt.show()\n format = \"pdf\" # \"png\" or \"pdf\"\n dir_path = os.path.dirname(os.path.realpath(__file__))\n file_name = dir_path + \"/\" + \"carlini_wagner_attack_strength_confidence_norm_gradient_\"\n file_name += \"_\" + get_log_time() + \".\" + format\n fig.savefig(file_name,\n bbox_inches='tight',\n transparent=False)\n plt.close()\n\n\ndef get_file_stats(file_name, results, class_type='adv'):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n data_path = os.path.join(dir_path, file_name)\n start_from_line = None\n max_cols = 157\n data_all = pd.read_csv(\n data_path, header=start_from_line, sep=delimiter,\n error_bad_lines=False, names=list(range(0, max_cols)))\n # print('shape of data all: ', data_all.shape)\n # print(data_all.head(5))\n attack_strength_name = 'adv_attack_strength'\n\n attack_strengths = get_col_val(data=data_all,\n col_name=attack_strength_name,\n dtype=np.float)\n\n unique_strenghts = np.unique(attack_strengths)\n\n attack_strength_col = get_col_nr(data=data_all,\n col_name=attack_strength_name)\n attack_strength_col_vals = attack_strength_col + 1\n\n for attack_strength in unique_strenghts:\n data = data_all[\n data_all.iloc[:, attack_strength_col_vals] == attack_strength]\n\n H, W = data.shape\n correctly_classified = H\n # print('correctly_classified: ', correctly_classified)\n\n adv_class_name_col = 4\n data = data[data.iloc[:, adv_class_name_col] == 'adv_class']\n H, W = data.shape\n adv_found = H\n\n col_names = []\n for class_nr in range(classes_nr):\n col_names += ['l2_norm_' + class_type + '_class_' + str(class_nr)]\n norm_vals = get_col_vals(data=data, col_names=col_names)\n\n target_classes = get_col_val(data=data,\n col_name=class_type + '_class',\n dtype=np.int)\n\n recovered = get_col_val(data=data,\n col_name='is_gauss_recovered',\n dtype=np.bool)\n # print('total recovered: ', np.nansum(recovered))\n\n dist_adv_org = get_col_val(data=data,\n col_name='z_l2_dist_adv_org_image',\n dtype=np.float)\n # print('averge l2 dist adv org: ', np.nanmean(dist_adv_org))\n\n adv_confidence = get_col_val(data=data,\n col_name='adv_confidence',\n dtype=np.float)\n avg_adv_confidence = np.nanmean(adv_confidence)\n\n\n class_type = 'org' if class_type == 'original' else 'adv'\n col_names = []\n for class_nr in range(classes_nr):\n col_names += [class_type + '_confidence_class_' + str(class_nr)]\n conf_vals = get_col_vals(data=data, col_names=col_names)\n\n recovered_org_grad = []\n recovered_2nd_grad = []\n\n not_recovered_org_grad = []\n not_recovered_2nd_grad = []\n\n count_lowest = 0\n count_highest = 0\n for row_nr in range(adv_found):\n class_nr = target_classes[row_nr]\n confs = []\n for conf_val in conf_vals:\n confs.append(conf_val[row_nr])\n max_conf = np.argmax(confs)\n assert max_conf == class_nr\n norms = []\n for norm_val in norm_vals:\n norms.append(norm_val[row_nr])\n min_class = np.argmin(norms)\n if min_class == class_nr:\n count_lowest += 1\n max_class = np.argmax(norms)\n if max_class == class_nr:\n count_highest += 1\n\n # norms = (norms - np.average(norms)) / np.std(norms)\n\n norm_org = norms[class_nr]\n norms[class_nr] = np.max(norms)\n norm_2nd = np.min(norms)\n\n if recovered[row_nr]:\n recovered_org_grad.append(norm_org)\n recovered_2nd_grad.append(norm_2nd)\n else:\n not_recovered_org_grad.append(norm_org)\n not_recovered_2nd_grad.append(norm_2nd)\n\n values = [\n attack_strength,\n count_lowest / adv_found,\n adv_found / correctly_classified,\n avg_adv_confidence,\n correctly_classified,\n count_lowest,\n count_highest,\n adv_found,\n np.sum(recovered),\n np.mean(dist_adv_org)]\n results.append(values)\n values_str = delimiter.join([str(x) for x in values])\n print(values_str)\n\n\ndef compute():\n # file_name = 'gradients_confidence_org_adv.csv'\n # file_name = '2019-11-15-04-12-26-863148_cifar10_grad_stats.csv'\n # class_type = 'original'\n class_type = 'adv'\n header = [\n 'adv strength',\n 'agreement lowest gradient and max confidence',\n '% of adv (out of correctly classified)',\n 'avg prediction confidence',\n 'correctly classified',\n 'norm lowest for ' + class_type,\n 'norm highest for ' + class_type,\n 'adv found',\n 'recovered number',\n 'dist adv org']\n header_str = delimiter.join(header)\n print(header_str)\n results = []\n files = [\n \"2019-12-13-12-53-46-542496_cifar10_grad_stats.csv\", # skr\n \"2019-12-13-12-56-32-374438_cifar10_grad_stats.csv\", # skr\n \"2019-12-13-18-58-51-053128_cifar10_grad_stats.csv\",\n \"2019-12-13-19-01-31-196764_cifar10_grad_stats.csv\",\n \"2019-12-13-19-16-31-829369_cifar10_grad_stats.csv\",\n \"2019-12-13-19-19-19-825889_cifar10_grad_stats.csv\",\n ]\n for file_name in files:\n get_file_stats(file_name,\n class_type=class_type,\n results=results)\n results = sorted(results, key=lambda val: val[0])\n\n print('Sorted results: ')\n for result in results:\n for val in result:\n print(str(val) + delimiter, end=\"\")\n print()\n plot_results(np.array(results))\n\n\nif __name__ == \"__main__\":\n compute()\n","sub_path":"cnns/graphs/gradient_gauss_cw_classes/analyze_gradients_confidence_adv_full_test.py","file_name":"analyze_gradients_confidence_adv_full_test.py","file_ext":"py","file_size_in_byte":12706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"278739381","text":"import pandas as pd\nfrom firebase import firebase\n\n#Lee el archivo excel base xplorandom.xlsx y lo asigna a un DataFrame\nxplorandom=pd.ExcelFile('D:\\Mi nuevo camino/bd_xplorandom/estructura_info.xlsx') #Tener cuidado con las formas\\literal, ya que pueden generar error para Python\ndf=pd.read_excel(xplorandom,'xplorandom',usecols=['Id', 'Pais', 'Departamento', 'Ciudad',\n 'Razon', 'Direccion', 'TelefonoFijo', 'Celular', 'Whatsapp', 'email', 'facebook', 'instagram',\n 'twitter', 'tiktok', 'SectorCadena', 'Plan', 'CantidadPersonas', 'DetallePlan', 'Precio','Dia',\n 'HoraInicio', 'HoraFin', 'Edad'], dtype={\"Celular\":str}) #(variable de la ruta, Nombrn(\"https://events-e3ea4-default-rtdb.firebaseio.com/\",None) #Conecta con la base de datos en Firebase\n#precio=df.loc[df['Precio']<=5000]\n#print(precio)\n\n#Evalúa la condición de planes meores o iguales a $5.000\nmenor_cinco_lucas=df.loc[lambda df:df['Precio']<=5000,:]\nprint(menor_cinco_lucas)\n\n#Evalúa la condición de planes meores o iguales a $10.000\nmenor_diez_lucas=df.loc[lambda df:df['Precio']<=10000,:]\nprint(menor_diez_lucas)\n\n#Evalúa la condición de planes meores o iguales a $20.000\nmenor_veinte_lucas=df.loc[lambda df:df['Precio']<=20000,:]\nprint(menor_veinte_lucas)\n\n#Evalúa la condición de planes meores o iguales a $50.000\nmenor_cincuenta_lucas=df.loc[lambda df:df['Precio']<=50000,:]\nprint(menor_cincuenta_lucas)\n\n#Evalúa la condición de planes meores o iguales a $100.000\nmenor_cien_lucas=df.loc[lambda df:df['Precio']<=100000,:]\nprint(menor_cien_lucas)\n\n#Evalúa la condición de planes meores o iguales a $200.000\nmenor_doscientas_lucas=df.loc[lambda df:df['Precio']<=200000,:]\nprint(menor_doscientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $300.000\nmenor_trescientas_lucas=df.loc[lambda df:df['Precio']<=300000,:]\nprint(menor_trescientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $400.000\nmenor_cuatrocientas_lucas=df.loc[lambda df:df['Precio']<=400000,:]\nprint(menor_cuatrocientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $500.000\nmenor_quinientas_lucas=df.loc[lambda df:df['Precio']<=500000,:]\nprint(menor_quinientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $600.000\nmenor_seiscientas_lucas=df.loc[lambda df:df['Precio']<=600000,:]\nprint(menor_seiscientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $700.000\nmenor_setecientas_lucas=df.loc[lambda df:df['Precio']<=700000,:]\nprint(menor_setecientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $800.000\nmenor_ochocientas_lucas=df.loc[lambda df:df['Precio']<=800000,:]\nprint(menor_ochocientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $900.000\nmenor_novecientas_lucas=df.loc[lambda df:df['Precio']<=900000,:]\nprint(menor_novecientas_lucas)\n\n#Evalúa la condición de planes meores o iguales a $1.000.000\nmenor_unmillon_lucas=df.loc[lambda df:df['Precio']<=1000000,:]\nprint(menor_unmillon_lucas)\n\n#precio=df['Precio']\n#print(precio)\n\n#Establece la conexión con la bases de datos en Firebase\nfirebase=firebase.FirebaseApplication(\"https://xplorandom-default-rtdb.firebaseio.com/\",None)\n\n#Asigna a la varable data el DataFrame y lo convierte a JSON\ndata5=menor_cinco_lucas.to_json(orient='records')\ndata10=menor_diez_lucas.to_json(orient='records')\ndata20=menor_veinte_lucas.to_json(orient='records')\ndata50=menor_cincuenta_lucas.to_json(orient='records')\ndata100=menor_cien_lucas.to_json(orient='records')\ndata200=menor_doscientas_lucas.to_json(orient='records')\ndata300=menor_trescientas_lucas.to_json(orient='records')\ndata400=menor_cuatrocientas_lucas.to_json(orient='records')\ndata500=menor_doscientas_lucas.to_json(orient='records')\ndata600=menor_seiscientas_lucas.to_json(orient='records')\ndata700=menor_setecientas_lucas.to_json(orient='records')\ndata800=menor_ochocientas_lucas.to_json(orient='records')\ndata900=menor_novecientas_lucas.to_json(orient='records')\ndata1000=menor_unmillon_lucas.to_json(orient='records')\n\n#Envía a la base de datos Firebase el objeto girardot con el archivo JSON de la tabla asignada al DataFrame\nresult5=firebase.post('/girardot5',data5)#Envia el JSON a la base de datos en Firebase\nresult10=firebase.post('/girardot10',data10)\nresult20=firebase.post('/girardot20',data20)\nresult50=firebase.post('girardot50',data50)\nresult100=firebase.post('/girardot100',data100)\nresult200=firebase.post('/girardot200',data200)\nresult300=firebase.post('/girardot300',data300)\nresult400=firebase.post('/girardot400',data400)\nresult500=firebase.post('(girardot500',data500)\nresult600=firebase.post('/girardot600',data600)\nresult700=firebase.post('/girardot700',data700)\nresult800=firebase.post('/girardot800',data800)\nresult900=firebase.post('/girardot900',data900)\nresult1000=firebase.post('/girardot1000',data1000)\n\n\nprint(result5) #Muestra el registro \nprint(result10)\nprint(result20)\nprint(result50)\nprint(result100)\nprint(result200)\nprint(result300)\nprint(result400)\nprint(result500)\nprint(result600)\nprint(result700)\nprint(result800)\nprint(result900)\nprint(result1000)\n\n\n\n\"\"\"\"\nimport openpyxl\nexcel_document=openpyxl.load_workbook('D:\\Mi nuevo camino/bd_xplorandom/estructura_info.xlsx')\nprint (type(excel_document)) #Resultado: \nprint(excel_document.get_sheet_names()) #Resultado: ['xplorandom']\n\n#Accediendo a las celdas en el libro\ndato=excel_document.get_sheet_by_name('xplorandom')\nprint(dato['R4'].value)\n\"\"\"\n\"\"\"\nimport sys\nfrom openpyxl import workbook\nfrom xlrd import open_workbook\narchivo=open_workbook('D:\\Mi nuevo camino/bd_xplorandom/estructura_info.xlsx')\nprint(\"Número de hojas: \",workbook.nsheets)\n\"\"\"","sub_path":"project_xplorandom/code_xplorandom.py","file_name":"code_xplorandom.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"175026846","text":"# Itertools Exercise:\n# Use itertools to group the list of breweries from 'https://api.openbrewerydb.org/breweries'\n# according to its brewery type.\n\n\nfrom itertools import groupby\nimport requests\n\nr = requests.get(\"https://api.openbrewerydb.org/breweries\")\n\nfor i, j in groupby(\n sorted(r.json(), key=lambda k: k[\"brewery_type\"]), lambda data: data[\"brewery_type\"]\n):\n print(i.title(), \":\", \", \".join([berry[\"name\"] for berry in list(j)]))\n","sub_path":"Modules/itertools_module/dev_exercise/haze_breweries.py","file_name":"haze_breweries.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"370409704","text":"from django.conf import settings\nfrom django.contrib.auth import login\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.http import HttpRequest\nfrom django.utils.importlib import import_module\n\nfrom celery import Celery\nfrom djblets.siteconfig.models import SiteConfiguration\nfrom reviewboard.extensions.base import Extension\n\nfrom reviewbotext.handlers import SignalHandlers\nfrom reviewbotext.models import ReviewBotTool\nfrom reviewbotext.resources import review_bot_review_resource, \\\n review_bot_tool_resource\n\nclass ReviewBotExtension(Extension):\n \"\"\"An extension for communicating with Review Bot\"\"\"\n is_configurable = True\n has_admin_site = True\n default_settings = {\n 'ship_it': False,\n 'comment_unmodified': False,\n 'open_issues': False,\n 'BROKER_URL': '',\n 'user': None,\n 'max_comments': 30,\n }\n resources = [\n review_bot_review_resource,\n review_bot_tool_resource,\n ]\n\n def __init__(self, *args, **kwargs):\n super(ReviewBotExtension, self).__init__(*args, **kwargs)\n self.settings.load()\n self.celery = Celery('reviewbot.tasks')\n self.signal_handlers = SignalHandlers(self)\n\n def shutdown(self):\n self.signal_handlers.disconnect()\n super(ReviewBotExtension, self).shutdown()\n\n def notify(self, request_payload):\n \"\"\"Add the request to the queue.\"\"\"\n self.celery.conf.BROKER_URL = self.settings['BROKER_URL']\n\n review_settings = {\n 'max_comments': self.settings['max_comments'],\n }\n payload = {\n 'request': request_payload,\n 'review_settings': review_settings,\n 'session': self._login_user(self.settings['user']),\n 'url': self._rb_url(),\n }\n #if reviewbot user is not required\n if not self.settings['rb_reviewer']:\n review = True\n #if reviewbot user is required and reviewbot reviewer is present\n elif request_payload['reviewbot_user']:\n review = True\n else:\n review = False\n\n tools = ReviewBotTool.objects.filter(enabled=True,\n run_automatically=True)\n if review:\n for tool in tools:\n review_settings['ship_it'] = tool.ship_it\n review_settings['comment_unmodified'] = tool.comment_unmodified\n review_settings['open_issues'] = tool.open_issues\n payload['review_settings'] = review_settings\n try:\n self.celery.send_task(\n \"reviewbot.tasks.ProcessReviewRequest\",\n [payload, tool.tool_settings],\n queue='%s.%s' % (tool.entry_point, tool.version))\n except:\n raise\n\n def _login_user(self, user_id):\n \"\"\"\n Login as specified user, does not depend on auth backend (hopefully).\n\n This is based on Client.login() with a small hack that does not\n require the call to authenticate().\n\n Will return the session id of the login.\n \"\"\"\n user = User.objects.get(id=user_id)\n user.backend = \"%s.%s\" % (\"django.contrib.auth.backends\",\n \"ModelBackend\")\n engine = import_module(settings.SESSION_ENGINE)\n\n # Create a fake request to store login details.\n request = HttpRequest()\n request.session = engine.SessionStore()\n login(request, user)\n request.session.save()\n return request.session.session_key\n\n def send_refresh_tools(self):\n \"\"\"Request workers to update tool list.\"\"\"\n self.celery.conf.BROKER_URL = self.settings['BROKER_URL']\n payload = {\n 'session': self._login_user(self.settings['user']),\n 'url': self._rb_url(),\n }\n self.celery.control.broadcast('update_tools_list', payload=payload)\n\n def _rb_url(self):\n \"\"\"Returns a valid reviewbot url including http protocol.\"\"\"\n protocol = SiteConfiguration.objects.get_current().get(\n \"site_domain_method\")\n domain = Site.objects.get_current().domain\n return '%s://%s%s' % (protocol, domain, settings.SITE_ROOT)\n","sub_path":"extension/reviewbotext/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"390725737","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.views import View\nfrom .forms import UserSignup, UserLogin, ConcertForm, UserUpdate\nfrom .models import Concert, AttendConcert, FollowedUser\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom datetime import datetime, timedelta, timezone\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMessage\n\ndef home(request):\n return render(request, 'home.html')\n\ndef test(request):\n return render(request, 'test.html')\n\nclass Signup(View):\n form_class = UserSignup\n template_name = 'signup.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.set_password(user.password)\n user.save()\n messages.success(request, \"You have successfully signed up.\")\n login(request, user)\n return redirect(\"home\")\n messages.warning(request, form.errors)\n return redirect(\"signup\")\n\nclass Login(View):\n form_class = UserLogin\n template_name = 'login.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n\n auth_user = authenticate(username=username, password=password)\n if auth_user is not None:\n login(request, auth_user)\n messages.success(request, \"Welcome Back!\")\n return redirect('concert-dashboard')\n messages.warning(request, \"Wrong email/password combination. Please try again.\")\n return redirect(\"login\")\n messages.warning(request, form.errors)\n return redirect(\"login\")\n\n\nclass Logout(View):\n def get(self, request, *args, **kwargs):\n logout(request)\n messages.success(request, \"You have successfully logged out.\")\n return redirect(\"login\")\n\ndef concert_list(request):\n present= datetime.now()\n concerts = Concert.objects.filter(start_date__gte=present)\n users=User.objects.all()\n query = request.GET.get('q')\n if query:\n concerts = concerts.filter(\n Q(organizer__username__icontains=query)|\n Q(name__icontains=query)|\n Q(description__icontains=query)|\n Q(concert_of__icontains=query)\n ).distinct()\n\n follow_list = []\n if request.user.is_authenticated:\n follow_list = request.user.follower.all().values_list('following', flat=True)\n context = {\n \"concerts\": concerts,\n \"follow_list\":follow_list,\n \"users\":users,\n }\n return render(request, 'list.html', context)\n\n\n\ndef profiles(request):\n users=User.objects.all()\n contect = {\n \"users\":users,\n }\n\n\ndef concert_dashboard(request):\n present=datetime.now()\n\n concerts = Concert.objects.filter(organizer=request.user)\n attending = AttendConcert.objects.filter(user=request.user).filter(Q(concert__start_date__gte=present))\n attended = AttendConcert.objects.filter(user=request.user).filter(Q(concert__start_date__lt=present))\n follow_list = request.user.following.all().values_list('follower', flat=True)\n users = User.objects.filter(id__in=follow_list)\n query = request.GET.get('q')\n if query:\n concerts = concerts.filter(\n Q(organizer__username__icontains=query)|\n Q(name__icontains=query)|\n Q(description__icontains=query)|\n Q(concert_of__icontains=query)\n ).distinct()\n attending = attending.filter(\n Q(concert__organizer__username__icontains=query)|\n Q(concert__name__icontains=query)|\n Q(concert__description__icontains=query)|\n Q(concert__concert_of__icontains=query)\n ).distinct()\n attended = attended.filter(\n Q(concert__organizer__username__icontains=query)|\n Q(concert__name__icontains=query)|\n Q(concert__description__icontains=query)|\n Q(concert__concert_of__icontains=query)\n ).distinct()\n\n\n context = {\n \"concerts\": concerts,\n \"attending\": attending,\n \"attended\": attended,\n \"users\" : users,\n }\n return render(request, 'dashboard.html', context)\n\ndef concert_detail(request, concert_id):\n concerts = Concert.objects.get(id=concert_id)\n booked= AttendConcert.objects.filter(concert=concerts)\n if request.method == \"POST\":\n quantity=request.POST.get(\"quantity\")\n AttendConcert.objects.create(quantity=quantity, user=request.user, concert=concerts)\n concerts.capacity = int(concerts.capacity) - int(quantity)\n concerts.save()\n email = EmailMessage('Successfully Booked', 'You have succesffully booked for %s' %(concerts.name), to=[request.user.email])\n email.send()\n return redirect('concert-dashboard')\n\n context = {\n \"concert\": concerts,\n \"booked\":booked,\n }\n return render(request, 'concertdetail.html', context)\n\ndef concert_create(request):\n invitation=FollowedUser.objects.filter(following=request.user)\n if request.user.is_anonymous:\n return redirect('signin')\n form = ConcertForm()\n if request.method == \"POST\":\n form = ConcertForm(request.POST)\n if form.is_valid():\n concert = form.save(commit=False)\n concert.organizer = request.user\n concert.save()\n email = EmailMessage('New Concert', 'Dont miss %s book quickly' %(concert.name), to=[user.follower.email for user in invitation])\n email.send()\n return redirect('concert-dashboard')\n context = {\n \"form\":form,\n }\n return render(request, 'concertcreate.html', context)\n\ndef concert_update(request, concert_id):\n concert_obj = Concert.objects.get(id=concert_id)\n if not (request.user.is_staff or request.user == concert_obj.organizer):\n return redirect('no-access')\n form = ConcertForm(instance=concert_obj)\n if request.method == \"POST\":\n form = ConcertForm(request.POST, request.FILES, instance=concert_obj)\n if form.is_valid():\n form.save()\n return redirect('concert-dashboard')\n context = {\n \"concert_obj\": concert_obj,\n \"form\":form,\n }\n return render(request, 'concertupdate.html', context)\n\ndef profile_update(request, profile_id):\n profile = User.objects.get(id=profile_id)\n form = UserUpdate(instance=profile)\n if request.method == \"POST\":\n form = UserUpdate(request.POST, instance=profile)\n if form.is_valid():\n user = form.save(commit=False)\n user.set_password(user.password)\n user.save()\n messages.success(request, \"You have successfully Updated profile.\")\n return redirect('concert-dashboard')\n context = {\n \"profile\": profile,\n \"form\":form,\n }\n return render(request, 'profileupdate.html', context)\n\ndef unbook(request, attend_id):\n booking_obj = AttendConcert.objects.get(user=request.user, id=attend_id)\n present=datetime.now()\n timeofevent=datetime.combine(booking_obj.concert.start_date, booking_obj.concert.start_time)\n if (timeofevent - timedelta(hours=3)) >= present:\n concert= Concert.objects.get(id=booking_obj.concert.id)\n concert.capacity=int(concert.capacity)+int(booking_obj.quantity)\n concert.save()\n booking_obj.delete()\n else:\n messages.success(request, \"It's too late to unbook\")\n return redirect('concert-dashboard')\n\ndef user_follow(request, user_id):\n user_obj = User.objects.get(id=user_id)\n if request.user.is_anonymous:\n return redirect('login')\n \n followed, created = FollowedUser.objects.get_or_create(follower=request.user, following=user_obj)\n if created:\n action=\"follow\"\n else:\n followed.delete()\n action=\"unfollow\"\n\n response = {\n \"action\": action,\n }\n return JsonResponse(response, safe=False)\n\ndef followed_users(request):\n if request.user.is_anonymous:\n return redirect('login')\n follow_list = request.user.follower.all().values_list('following', flat=True)\n users = User.objects.filter(id__in=follow_list)\n query = request.GET.get('q')\n if query:\n users = users.filter(\n Q(username__icontains=query)|\n Q(id__icontains=query)\n ).distinct()\n\n context = {\n \"users\": users,\n }\n return render(request, 'followed_users.html', context)\n\ndef organizer_detail(request, organizer_id):\n present=datetime.now()\n organizer = User.objects.get(id=organizer_id)\n concerts = Concert.objects.filter(organizer=organizer).filter(Q(start_date__gte=present))\n counter=concerts.count()\n context = {\n \"organizer\": organizer,\n \"concerts\":concerts,\n \"counter\":counter,\n }\n return render(request, 'organizerdetail.html', context)\n\n","sub_path":"events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"413215758","text":"import io\r\nimport imageio\r\n\r\nclass VideoStream:\r\n\tdef __init__(self, filename):\r\n\t\tself.filename = filename\r\n\t\ttry:\r\n\t\t\tself.reader = imageio.get_reader(filename, 'ffmpeg')\r\n\t\texcept:\r\n\t\t\traise IOError\r\n\t\tself.frameCnt = 0\r\n\t\tself.frameNum = 0\r\n\t\r\n\tdef countFrame(self):\r\n\t\treader = imageio.get_reader(self.filename, 'ffmpeg')\r\n\t\tself.frameCnt = 0\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\treader.get_next_data()\r\n\t\t\t\tself.frameCnt += 1\r\n\t\t\texcept:\r\n\t\t\t\tbreak\r\n\t\r\n\tdef setFrameCnt(self, cnt):\r\n\t\tself.frameCnt = cnt\r\n\t\t\r\n\tdef nextFrame(self):\r\n\t\t\"\"\"Get next frame.\"\"\"\r\n\t\ttry:\r\n\t\t\tbuffer = io.BytesIO()\r\n\t\t\tdata = self.reader.get_next_data()\r\n\t\t\timageio.imwrite(buffer, data, format='JPEG')\r\n\t\t\tself.frameNum += 1\r\n\t\t\treturn buffer.getvalue()\r\n\t\texcept:\r\n\t\t\treturn bytes(0)\r\n\t\r\n\tdef getFrame(self, index):\r\n\t\ttry:\r\n\t\t\tbuffer = io.BytesIO()\r\n\t\t\tdata = self.reader.get_data(index)\r\n\t\t\timageio.imwrite(buffer, data, format='JPEG')\r\n\t\t\tself.frameNum = index\r\n\t\t\treturn buffer.getvalue()\r\n\t\texcept:\r\n\t\t\treturn bytes(0)\r\n\t\t\r\n\tdef frameNbr(self):\r\n\t\t\"\"\"Get frame number.\"\"\"\r\n\t\treturn self.frameNum\r\n\r\n\r\n# class VideoStream:\r\n# \tdef __init__(self, filename):\r\n# \t\tself.filename = filename\r\n# \t\ttry:\r\n# \t\t\tself.file = open(filename, 'rb')\r\n# \t\texcept:\r\n# \t\t\traise IOError\r\n# \t\tself.frameNum = 0\r\n\t\t\r\n# \tdef nextFrame(self):\r\n# \t\t\"\"\"Get next frame.\"\"\"\r\n# \t\tdata = self.file.read(5) # Get the framelength from the first 5 bits\r\n# \t\tif data: \r\n# \t\t\tframelength = int(data)\r\n\t\t\t\t\t\t\t\r\n# \t\t\t# Read the current frame\r\n# \t\t\tdata = self.file.read(framelength)\r\n# \t\t\tself.frameNum += 1\r\n# \t\treturn data\r\n\t\t\r\n# \tdef frameNbr(self):\r\n# \t\t\"\"\"Get frame number.\"\"\"\r\n# \t\treturn self.frameNum\r\n","sub_path":"VideoStream.py","file_name":"VideoStream.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"568835710","text":"import folium\nimport os\nimport json\n\n# Create map object\nm = folium.Map(location=[42.3601, -71.0589], zoom_start=12)\n\n# Global tooltip\ntooltip = 'Click For More Info'\n\n# Create custom marker icon\nlogoIcon = folium.features.CustomIcon('logo.png', icon_size=(50, 50))\n\n# Vega data\nvis = os.path.join('data', 'vis.json')\n\n# Geojson Data\noverlay = os.path.join('data', 'overlay.json')\n\n# Create markers\nfolium.Marker([42.363600, -71.099500],\n popup='Location One',\n tooltip=tooltip).add_to(m),\nfolium.Marker([42.333600, -71.109500],\n popup='Location Two',\n tooltip=tooltip,\n icon=folium.Icon(icon='cloud')).add_to(m),\nfolium.Marker([42.377120, -71.062400],\n popup='Location Three',\n tooltip=tooltip,\n icon=folium.Icon(color='purple')).add_to(m),\nfolium.Marker([42.374150, -71.122410],\n popup='Location Four',\n tooltip=tooltip,\n icon=folium.Icon(color='green', icon='leaf')).add_to(m),\nfolium.Marker([42.375140, -71.032450],\n popup='Location Five',\n tooltip=tooltip,\n icon=logoIcon).add_to(m),\nfolium.Marker([42.315140, -71.072450],\n popup=folium.Popup(max_width=450).add_child(folium.Vega(json.load(open(vis)), width=450, height=250))).add_to(m)\n\n# Circle marker\nfolium.CircleMarker(\n location=[42.466470, -70.942110],\n radius=50,\n popup='My Birthplace',\n color='#428bca',\n fill=True,\n fill_color='#428bca'\n).add_to(m)\n\n# Geojson overlay\nfolium.GeoJson(overlay, name='cambridge').add_to(m)\n\n# Generate map\nm.save('map.html')\n\n\n\n\n# ------------------------------------------------------------------------------------------------\n# so let's write a custom temporary-HTML renderer\n# pretty much copy-paste of this answer: https://stackoverflow.com/a/38945907/3494126\nimport subprocess\nimport webbrowser\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\n\nPORT = 7000\nHOST = '127.0.0.1'\nSERVER_ADDRESS = '{host}:{port}'.format(host=HOST, port=PORT)\nFULL_SERVER_ADDRESS = 'http://' + SERVER_ADDRESS\n\n\ndef TemproraryHttpServer(page_content_type, raw_data):\n \"\"\"\n A simpe, temprorary http web server on the pure Python 3.\n It has features for processing pages with a XML or HTML content.\n \"\"\"\n\n class HTTPServerRequestHandler(BaseHTTPRequestHandler):\n \"\"\"\n An handler of request for the server, hosting XML-pages.\n \"\"\"\n\n def do_GET(self):\n \"\"\"Handle GET requests\"\"\"\n\n # response from page\n self.send_response(200)\n\n # set up headers for pages\n content_type = 'text/{0}'.format(page_content_type)\n self.send_header('Content-type', content_type)\n self.end_headers()\n\n # writing data on a page\n self.wfile.write(bytes(raw_data, encoding='utf'))\n\n return\n\n if page_content_type not in ['html', 'xml']:\n raise ValueError('This server can serve only HTML or XML pages.')\n\n page_content_type = page_content_type\n\n # kill a process, hosted on a localhost:PORT\n subprocess.call(['fuser', '-k', '{0}/tcp'.format(PORT)])\n\n # Started creating a temprorary http server.\n httpd = HTTPServer((HOST, PORT), HTTPServerRequestHandler)\n\n # run a temprorary http server\n httpd.serve_forever()\n\n\ndef run_html_server(html_data=None):\n\n if html_data is None:\n html_data = \"\"\"\n \n \n \n Page Title\n \n \n

This is a Heading

\n

This is a paragraph.

\n \n \n \"\"\"\n\n # open in a browser URL and see a result\n webbrowser.open(FULL_SERVER_ADDRESS)\n\n # run server\n TemproraryHttpServer('html', html_data)\n\n# ------------------------------------------------------------------------------------------------\n\n\n# now let's save the visualization into the temp file and render it\nfrom tempfile import NamedTemporaryFile\ntmp = NamedTemporaryFile()\nfolium_map.save(tmp.name)\nwith open(tmp.name) as f:\n folium_map_html = f.read()\n\nrun_html_server(folium_map_html)","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"38521317","text":"#!/bin/python3\n\nimport os\n\n\ndef page_count(number_of_pages, page_number):\n \"\"\" Returns the minimum number of pages a student\n must turn to open a book to the desired page \"\"\"\n\n if page_number % 2 == 0: # Even page number\n open_at_page = (page_number, page_number + 1)\n else: # Odd page number\n open_at_page = (page_number - 1, page_number)\n\n start_count = 0 # Count from front cover\n end_count = number_of_pages # Count from back cover\n\n # Loop until one of the counts matches the page number\n while start_count not in open_at_page and end_count not in open_at_page:\n start_count += 2 # Two pages per page turn\n end_count -= 2\n\n # Returns the number of pages turned for the count in open_page\n if start_count in open_at_page:\n return int(start_count / 2)\n elif end_count in open_at_page:\n return int((number_of_pages - end_count) / 2)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n number = int(input()) # Number of pages\n page = int(input()) # Page number\n\n result = page_count(number, page)\n\n fptr.write(str(result) + '\\n')\n fptr.close()\n","sub_path":"problem_solving/algorithms/implementation/drawing_book.py","file_name":"drawing_book.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"401438431","text":"import unittest\nfrom pprint import pprint\n\nfrom google.protobuf.descriptor_pb2 import FileDescriptorProto\nfrom google.protobuf.descriptor_pb2 import FieldDescriptorProto\n\nfrom bonsai.common.message_builder import reconstitute_from_bytes\n\n\ndef _serialize_type_from_description(name, fields):\n fdp = FileDescriptorProto()\n fdp.name = '{}.proto'.format(name)\n mt = fdp.message_type.add()\n mt.name = name\n\n for idx, field in enumerate(fields):\n f = mt.field.add()\n f.name = field[0]\n f.number = idx + 1\n f.type = field[1]\n f.label = FieldDescriptorProto.LABEL_OPTIONAL\n if f.type == FieldDescriptorProto.TYPE_MESSAGE:\n f.type_name = field[2]\n\n data = mt.SerializeToString()\n return data\n\n\nclass MessageReconstitute(unittest.TestCase):\n\n def test_reconstitute_single_schema(self):\n \"\"\"\n Tests the reconstitution of a schema with 1 primitive field\n \"\"\"\n data = _serialize_type_from_description(\n 'test_single_schema', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n test_class = reconstitute_from_bytes(data)\n test = test_class()\n test.a = 42\n self.assertEqual(42, test.a)\n\n def test_reconstitute_composite_schema_with_luminance(self):\n \"\"\"\n Tests the reconstitution of a schema with 1 structure field\n \"\"\"\n data = _serialize_type_from_description(\n 'test_composite_schema', [('a',\n FieldDescriptorProto.TYPE_MESSAGE,\n 'bonsai.inkling_types.proto.Luminance')]\n )\n test_class = reconstitute_from_bytes(data)\n test = test_class()\n test.a.width = 42\n self.assertEqual(42, test.a.width)\n\n def test_reconstitute_two_schemas_same_name_different_fields(self):\n \"\"\"\n Tests that reconstituting two schemas with the same name but\n different fields result in two classes.\n \"\"\"\n data1 = _serialize_type_from_description(\n 'same_name_1', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n data2 = _serialize_type_from_description(\n 'same_name_1', [('a', FieldDescriptorProto.TYPE_STRING)]\n )\n self.assertNotEqual(data1, data2)\n test_class_1 = reconstitute_from_bytes(data1)\n test_class_2 = reconstitute_from_bytes(data2)\n self.assertNotEqual(test_class_1, test_class_2)\n\n def test_reconstitute_two_schemas_same_name_same_fields(self):\n \"\"\"\n Tests that reconsitituting two schemas with the same name and same\n fields results in the same class.\n \"\"\"\n data = _serialize_type_from_description(\n 'same_name_2', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n test_class_1 = reconstitute_from_bytes(data)\n test_class_2 = reconstitute_from_bytes(data)\n self.assertEqual(test_class_1, test_class_2)\n\n def test_reconstitute_two_schemas_different_names_same_fields(self):\n \"\"\"\n Tests that reconstituting two schemas with different names and the same\n fields results in different classes.\n \"\"\"\n data1 = _serialize_type_from_description(\n 'test_5_1', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n data2 = _serialize_type_from_description(\n 'test_5_2', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n self.assertNotEqual(data1, data2)\n test_class_1 = reconstitute_from_bytes(data1)\n test_class_2 = reconstitute_from_bytes(data2)\n self.assertNotEqual(test_class_1, test_class_2)\n\n def test_reconstitute_two_schemas_different_names_different_fields(self):\n \"\"\"\n Tests that reconstituting two schemas with different names and\n different fields results in different classes.\n \"\"\"\n data1 = _serialize_type_from_description(\n 'test_6_1', [('a', FieldDescriptorProto.TYPE_UINT32)]\n )\n data2 = _serialize_type_from_description(\n 'test_6_2', [('a', FieldDescriptorProto.TYPE_STRING)]\n )\n self.assertNotEqual(data1, data2)\n test_class_1 = reconstitute_from_bytes(data1)\n test_class_2 = reconstitute_from_bytes(data2)\n self.assertNotEqual(test_class_1, test_class_2)\n\n\n# PyCharm uses the below lines to allow running unit tests with its own\n# unit testing engine. The lines below are added by the PyCharm Python\n# unit tests template.\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"bonsai/common/test_message_builder.py","file_name":"test_message_builder.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"215122817","text":"import matplotlib.pyplot as plt\nimport re\nimport sys\nimport numpy as np\n\n# Output of ts_parse application to be fed to this script which will\n# result in e.g.\n# ./out/bin/PC/ts_parse player3_config.cfg /home2/sb_media/Bloomberg_locals/EA002096_with_PETP.ts 482 481 o.aac o.h264 >EA002096_withpetp.txt\n#\n\nf = open(sys.argv[1])\n\npids = []\n\n\nfor s in sys.argv[2:]:\n pids.append(int(s))\n\npid_data = {int(p) : {'x' : [], 'y' : []} for p in pids}\nprint(pid_data)\n\nv = []\na = []\n\nfor l in f:\n w = l.split(',')\n l_pid = int(w[0])\n if l_pid in pids:\n pid_data[l_pid]['x'].append(int(w[4]))\n pid_data[l_pid]['y'].append(int(w[2]))\n#plt.plot(x,y, label='video pts', x1, y1, label='audio pts')\n\npts = {}\npts_diff = {}\nmax_diff = 0\nmin_diff = 100000000000000000000000\nfor p in pids:\n pts[p] = np.array(pid_data[p]['y'])\n pts[p].sort()\n pts_diff[p] = pts[p][1:pts[p].size] - pts[p][0:pts[p].size-1]\n if max(pts_diff[p]) > max_diff:\n max_diff = max(pts_diff[p])\n if min(pts_diff[p]) < min_diff:\n min_diff = min(pts_diff[p])\n print(pts_diff[p])\n\n\n\nplt.ylim([(min_diff - 100),(max_diff +200)])\nlab = []\nfor pid in pids:\n print(pid)\n #s = plt.plot(np.array(pid_data[pid]['y'][1:])/1000., pts_diff[pid], label='%d pts' % pid)\n s = plt.plot(pts[pid][1:]/1000., pts_diff[pid], label='%d pts' % pid)\n lab.append(s)\n\nplt.grid(True)\nplt.xlabel('Pts val')\nplt.ylabel('PTS Diff')\nplt.legend()\nplt.show()\n","sub_path":"python/plot_pid_pts_diff.py","file_name":"plot_pid_pts_diff.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"618963397","text":"# -*- coding: utf-8 -*-\nimport os.path as op\nfrom aiida import orm\nfrom aiida.engine import run\nfrom aiida_common_workflows.workflows.relax.generator import RelaxType\n\n#Next three lines must be modified.\n\n#from aiida_common_workflows.workflows.relax. #... import MyInpGen\n#InpGen = #MyInpGen\n#calc_engines = #my cal eng schema\n#{\n# 'relax': {\n# 'code': '@localhost',\n# 'options': {\n# 'resources': {\n# 'num_machines': 2\n# },\n# 'max_walltime': 86400,\n# }\n# },\n# 'maybe another step?': {\n# 'code': '@localhost',\n# 'options': {\n# 'resources': {\n# 'num_machines': 2\n# },\n# 'max_walltime': 3600,\n# 'queue': 'debug',\n# 'account': 'ABC'\n# }\n# }\n#}\n\n#Don't touch the rest\n\nrelaxation_type = RelaxType.ATOMS\nprotocol = 'moderate'\n\ndef rescale(structure, scale):\n \"\"\"\n Calcfunction to rescale a structure by a scaling factor.\n Uses ase.\n :param structure: An AiiDA structure to rescale\n :param scale: The scale factor\n :return: The rescaled structure\n \"\"\"\n\n the_ase = structure.get_ase()\n new_ase = the_ase.copy()\n new_ase.set_cell(the_ase.get_cell() * float(scale), scale_atoms=True)\n new_structure = orm.StructureData(ase=new_ase)\n\n return new_structure\n\ndef structure_init():\n \"\"\"\n Workfunction to create structure of a given element taking it from a reference\n list of scructures and a reference volume.\n :param element: The element to create the structure with.\n :return: The structure and the kpoint mesh (from file, releted to the structure!).\n \"\"\"\n import pymatgen as mg\n\n structure_file = op.realpath(op.join(op.dirname(__file__), 'data/Si.cif'))\n\n in_structure = mg.Structure.from_file(structure_file, primitive=False)\n\n newreduced = in_structure.copy()\n newreduced.scale_lattice(float(20.4530) * in_structure.num_sites)\n structure = orm.StructureData(pymatgen_structure=newreduced)\n\n return structure\n\nstructure = structure_init()\n\nfor scale in [0.94,0.96,0.98,1,1.02,1.04,1.06]:\n scaled = rescale(structure, scale)\n builder = InpGen.get_builder(scaled, calc_engines, protocol, relaxation_type, threshold_forces=0.001)\n future = run(builder)\n print('Launching {0} at volume rescaled of {1}'.format(future.pk, scale))\n","sub_path":"aiida_common_workflows/workflows/relax/examples/eos_silicon.py","file_name":"eos_silicon.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"1028967","text":"#! /usr/bin/env python3\n\nimport sys\nimport math\nimport h5py\n\nstart_pos = []\nend_pos = []\n\nwith h5py.File(sys.argv[1], 'r') as f:\n pos_x = f['pos_x_final']\n pos_y = f['pos_y_final']\n pos_z = f['pos_z_final']\n \n start_pos = [list(entry) for entry in zip(pos_x[...], pos_y[...], pos_z[...])]\n\nwith h5py.File(sys.argv[2], 'r') as f2:\n pos_x = f2['pos_x_final']\n pos_y = f2['pos_y_final']\n pos_z = f2['pos_z_final']\n \n end_pos = [list(entry) for entry in zip(pos_x[...], pos_y[...], pos_z[...])]\n\nif not len(start_pos) == len(end_pos):\n print (\"*ERROR* Start and final clouds have different number of points!\")\n exit(-1)\n\nmin_dist = sys.float_info.max\nmax_dist = -sys.float_info.max\nfor i in range(0,len(start_pos)):\n delta_pos = []\n for j in range(0,3):\n delta_pos.append(start_pos[i][j] - end_pos[i][j])\n \n dist = 0.0\n for j in range(0,3):\n dist = dist + delta_pos[j] * delta_pos[j]\n \n dist = math.sqrt(dist)\n if min_dist > dist:\n min_dist = dist\n \n if max_dist < dist:\n max_dist = dist\n\nprint(\"Maximum distance: \" + str(max_dist))\nprint(\"Minimum distance: \" + str(min_dist))\n\nif abs(max_dist - min_dist) > 0.01:\n print(\"Distance difference: \" + str(abs(max_dist - min_dist)) + \" > 0.01 - ERROR\")\n print(\"*ERROR* Points have NOT move uniformly!\")\nelse:\n print(\"Distance difference: \" + str(abs(max_dist - min_dist)) + \" < 0.01 - OK\")\n\nmin_dot = sys.float_info.max\nmax_dot = -sys.float_info.max\n\nfor i in range(0,len(start_pos)):\n start_vec = start_pos[i]\n end_vec = end_pos[i]\n \n vec_len = math.sqrt(start_vec[0] * start_vec[0] + \n start_vec[1] * start_vec[1] + \n start_vec[2] * start_vec[2])\n start_vec[0] = start_vec[0] / vec_len\n start_vec[1] = start_vec[1] / vec_len\n start_vec[2] = start_vec[2] / vec_len\n \n vec_len = math.sqrt(end_vec[0] * end_vec[0] + \n end_vec[1] * end_vec[1] + \n end_vec[2] * end_vec[2])\n end_vec[0] = end_vec[0] / vec_len\n end_vec[1] = end_vec[1] / vec_len\n end_vec[2] = end_vec[2] / vec_len\n \n dot = start_vec[0] * end_vec[0] + start_vec[1] * end_vec[1] + start_vec[2] * end_vec[2]\n \n if min_dot > dot:\n min_dot = dot\n \n if max_dot < dot:\n max_dot = dot\n\nprint(\"\")\nprint(\"Maximum angle: \" + str(math.degrees(math.acos(max(-1.0, min_dot)))) + \" deg\")\nprint(\"Minimum angle: \" + str(math.degrees(math.acos(min(1.0, max_dot)))) + \" deg\")\n\nif math.degrees(math.acos(max(-1.0, min_dot))) > 1.0:\n print(\"*ERROR* Points haven NOT move uniformly towards center of mass!\")\n print(\"Maximum angle is more than 1* (should be as close to 0 as possible).\")\nelse:\n print(\"OK\")\n","sub_path":"pcg/proj2/tests/test-data/test_nbody.py","file_name":"test_nbody.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"59554985","text":"from yahoo_fin import stock_info as si\nfrom collections import deque\nfrom stockstats import StockDataFrame\nfrom sklearn import preprocessing, utils\nfrom sklearn.model_selection import train_test_split\n\nimport numpy as np\nimport pandas as pd\nimport random\n\ndef interpolate_missing_values(df, feature_columns):\n for column in feature_columns:\n df[column] = df[column].replace([np.inf, -np.inf, 0], np.nan)\n df[column] = df[column].interpolate()\n return df\n\ndef relativize_df(df, feature_columns):\n new_cols = [\"date\"] + feature_columns\n result = pd.DataFrame(columns=new_cols)\n result[\"date\"] = df.values[1:,0]\n for column in feature_columns:\n col_data = df[column]\n col_data_shifted = col_data.shift(1)\n col_data_relativized = col_data / col_data_shifted\n result[column] = col_data_relativized.values[1:]\n \n return result\n\n\ndef load_data(csv_files, relativize=False, n_steps=50, shuffle=True, lookup_step=1,\n test_size_in_days=40, feature_columns=['adjclose', 'volume', 'open', 'high', 'low'],\n stat_columns=['macd'], target=\"adjclose\"):\n\n last_date = \"\"\n last_date_file = \"\"\n results = {}\n for file in csv_files:\n df = pd.read_csv(file)\n # if relativize:\n # df = relativize_df(df, feature_columns)\n\n df = interpolate_missing_values(df, feature_columns)\n\n current_last_date = df.values[-1][0]\n if last_date == \"\":\n last_date = current_last_date\n last_date_file = file\n elif last_date != current_last_date:\n raise ValueError(\"Expecting same last date on data: \",\n file, \" last date is \", current_last_date , \" where \",\n last_date_file, \" date is \", last_date)\n \n results[file] = load_data_single(\n df, n_steps, shuffle, lookup_step, test_size_in_days, feature_columns, stat_columns, target)\n\n if len(csv_files) == 1:\n return results[csv_files[0]]\n \n result = {}\n for file in csv_files:\n for key in [\"X_train\", \"X_test\", \"y_train\", \"y_test\"]:\n if key in result:\n result[key] = np.append(result[key], results[file][key], axis=0)\n else:\n result[key] = results[file][key]\n\n\n train_samples = len(result[\"X_train\"])\n test_samples = len(result[\"X_test\"])\n \n test_percent = test_samples*100.0 / float(test_samples + train_samples)\n\n print(f\"Train samples: {train_samples}. Test samples: {test_samples}. TestPercent: {test_percent:.2f}\")\n print(\"Train shape: \", result[\"X_train\"].shape)\n \n return result\n \ndef get_buy_hold_sell_targets(df, target, lookup_step):\n data = df[target]\n # df['target'] = data\n maxs = data.rolling(lookup_step+1).max().shift(-lookup_step)\n mins = data.rolling(lookup_step+1).min().shift(-lookup_step)\n\n data.drop(data.tail(lookup_step).index, inplace=True)\n maxs.drop(maxs.tail(lookup_step).index, inplace=True)\n mins.drop(mins.tail(lookup_step).index, inplace=True)\n\n maxdiff = maxs/data\n mindiff = mins/data\n # means = data.rolling(lookup_step).mean().shift(-lookup_step)\n \n factor = 0.20\n buy = maxdiff > (1+factor)\n sell = mindiff < (1-factor)\n hold = ~ (buy | sell) \n\n targets = np.array([buy.astype(int), hold.astype(int), sell.astype(int)]).transpose()\n print(f\"Targets: \",targets.sum(axis=0))\n return targets\n\n\ndef load_data_single(df, n_steps=50, shuffle=True, lookup_step=1,\n test_size_in_days=40, feature_columns=['adjclose', 'volume', 'open', 'high', 'low'],\n stat_columns=['macd'], target=\"adjclose\", scale_sequences=True):\n \"\"\"\n Loads data from dir, as well as scaling, shuffling, normalizing and splitting.\n Params:\n ticker (str/pd.DataFrame): the ticker you want to load, examples include AAPL, TESL, etc.\n n_steps (int): the historical sequence length (i.e window size) used to predict, default is 50\n scale (bool): whether to scale prices from 0 to 1, default is True\n shuffle (bool): whether to shuffle the training data, default is True\n lookup_step (int): the future lookup step to predict, default is 1 (e.g next day)\n test_size (float): ratio for test data, default is 0.2 (20% testing data)\n feature_columns (list): the list of features to use to feed into the model, default is everything grabbed from yahoo_fin\n \"\"\"\n\n feature_columns = np.concatenate((feature_columns, stat_columns), axis=None)\n\n sdf = StockDataFrame.retype(df.copy())\n\n for stat in stat_columns:\n df[stat] = sdf[stat]\n\n # this will contain all the elements we want to return from this function\n result = {}\n # we will also return the original dataframe itself\n result['df'] = df.copy()\n\n # make sure that the passed feature_columns exist in the dataframe\n for col in feature_columns:\n assert col in df.columns\n\n column_scaler = {}\n # scale the data (prices) from 0 to 1\n for column in feature_columns:\n scaler = preprocessing.MinMaxScaler()\n df[column] = scaler.fit_transform(\n np.expand_dims(df[column].values, axis=1))\n column_scaler[column] = scaler\n\n # print(column_scaler)\n # add the MinMaxScaler instances to the result returned\n result[\"column_scaler\"] = column_scaler\n\n # add the target column (label) by shifting by `lookup_step`\n # future = df[target].shift(-lookup_step)\n # future.drop(future.tail(lookup_step).index, inplace=True)\n\n targets = get_buy_hold_sell_targets(df, target, lookup_step)\n\n # last `lookup_step` columns contains NaN in future column\n # get them before droping NaNs\n # last_sequence = np.array(df[feature_columns].tail(lookup_step))\n # get last_sequence for prediction\n last_sequence = np.array(df[feature_columns].tail(n_steps))\n\n # # drop NaNs\n # df.dropna(inplace=True)\n\n sequence_data = []\n sequences = deque(maxlen=n_steps)\n\n for entry, target in zip(df[feature_columns].values, targets):\n sequences.append(entry)\n if len(sequences) == n_steps:\n sequence_data.append([np.array(sequences), target])\n\n\n if scale_sequences:\n scaler = preprocessing.MinMaxScaler()\n scaler.fit(last_sequence.flatten().reshape(-1, 1))\n last_sequence = scaler.transform(last_sequence)\n result['last_sequence_scaler'] = scaler\n\n # add to result\n result['last_sequence'] = last_sequence\n\n # construct the X's and y's\n X, y, scalers = [], [], []\n for seq, target in sequence_data:\n if scale_sequences:\n scaler = preprocessing.MinMaxScaler()\n scaler.fit(seq.flatten().reshape(-1, 1))\n seq = scaler.transform(seq)\n # target = scaler.transform(target.reshape(-1, 1))[0][0]\n scalers.append(scaler)\n\n X.append(seq)\n y.append(target)\n\n # convert to numpy arrays\n X = np.array(X)\n y = np.array(y)\n\n # reshape X to fit the neural network\n\n # X = X.reshape((X.shape[0], X.shape[2], X.shape[1]))\n\n samples = len(y)\n test_size = test_size_in_days / float(samples)\n print(f\"test_size: {test_size:.2f}\")\n\n ### Split the dataset \n ## This method isn't right. Mixes values from the same time periods\n # result[\"X_train\"], result[\"X_test\"], result[\"y_train\"], result[\"y_test\"] = train_test_split(\n # X, y, test_size=test_size, shuffle=shuffle)\n\n ## Splits train and test data and then shuffle\n result[\"X_train\"], result[\"X_test\"], result[\"y_train\"], result[\"y_test\"], result[\"scalers_train\"], result[\"scalers_test\"] = train_test_split(\n X, y, scalers, test_size=test_size, shuffle=False)\n\n if shuffle:\n result[\"X_train\"], result[\"y_train\"] = utils.shuffle(\n result[\"X_train\"], result[\"y_train\"])\n\n return result\n","sub_path":"machine-learning/stock-prediction/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":7896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469861415","text":"#!/bin/env/python\n# -*- coding: utf-8 -*-\n\n# Run on Raspberry Pi in order to log measured values from arduino connected via USB.\n\nimport serial\nimport datetime\nimport time\n\narduino_serial = serial.Serial('/dev/ttyACM0', 9600)\n\nstartup_datetime_str = datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")\n\nwith open(startup_datetime_str + \"_measurement\", \"w\") as f:\n\n while 1:\n\n # get measurements from arduino\n measurement_str = arduino_serial.readline()\n\n # get datetime for measurement\n measurement_datetime_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S \")\n\n # append current line to file\n f.write(measurement_datetime_str + measurement_str)\n","sub_path":"moisture-measurement/moisture-measurement.py","file_name":"moisture-measurement.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"519704382","text":"import math\nimport Tkinter as tk\nimport time\nfrom random import random, randint, shuffle\nimport numpy as np\n\n\n\ndef _create_circle(self, x, y, r, **kwargs):\n return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)\ntk.Canvas.create_circle = _create_circle\n\ndef generatePoints():\n h, k = 7, 5\n r = 5\n\n x1 = math.sqrt(r) + h\n x2 = -1 * math.sqrt(r) + h\n y1 = math.sqrt(r) + k\n y2 = -1 * math.sqrt(r) + k\n\n r = math.sqrt(r)\n x = r * math.cos(math.pi/4)\n y = r * math.sin(math.pi/4)\n xu = h - x\n xv = h + x\n yu = k - y\n yv = k + y\n points = [(x1, k), (xv, yu), (h, y2), (xu, yu), \\\n (x2, k), (xu, yv), (h, y1), (xv, yv)]\n shuffle(points)\n return points\n\ndef generatePopulation(num_of_pop):\n return [generatePoints() for x in range(num_of_pop)]\n\nclass GA: \n def __init__(self, settings):\n self.selection_rate = settings[0]\n self.mutation_rate = settings[1]\n\n def visualize(self, points):\n master = tk.Tk()\n w = tk.Canvas(master, width=280, height=200)\n w.pack()\n circle_r = 5\n # w.create_circle(h * 20, k * 20, circle_r)\n for i in range(8):\n w.create_circle(points[i][0] * 20, points[i][1] * 20, circle_r)\n\n fitness = self.fitness(points)\n w.delete('fit')\n canvas_id = w.create_text(20, 20, anchor='nw', tags='fit')\n w.itemconfig(canvas_id, text='Fitness: ' + str(round(fitness, 4)))\n for i in range(len(points) - 1):\n w.create_line(points[i][0] * 20, points[i][1] * 20, points[i + 1][0] * 20, points[i + 1][1] * 20)\n w.update()\n time.sleep(1)\n w.mainloop()\n\n def fitness(self, points):\n length = len(points)\n total_d = 0\n for i in range(length - 1):\n d = math.sqrt((points[i][0] - points[i + 1][0]) ** 2 + (points[i][1] - points[i+1][1]) ** 2)\n total_d = total_d + d\n return total_d\n\n def crossover(self, male, female):\n for i in range(3):\n temp1 = male[i]\n temp2 = female[i]\n male[i] = female[i]\n female[i] = temp1\n for x in range(len(male)):\n if male[i] == male[x] and i != x:\n male[x] = temp1\n for x in range(len(female)):\n if female[i] == female[x] and i != x:\n female[x] = temp2\n return [male, female]\n\n def averageFitness(self, pop):\n fitnesses = [self.fitness(x) for x in pop]\n worst_individual = np.amax(fitnesses)\n fitnesses = [abs(x - worst_individual) for x in fitnesses]\n return np.sum(fitnesses) / float(len(pop))\n\n def evolve(self, pop):\n rated_points = [self.fitness(x) for x in pop]\n worst_individual = np.amax(rated_points) \n rated_points = [(abs(self.fitness(x) - worst_individual), x) for x in pop]\n rated_points = sorted(rated_points)\n rated_points = [x[1] for x in rated_points]\n\n # Select Fit group and random people for new generation\n length_fp = int((1 - .1) * len(rated_points))\n new_gen = rated_points[length_fp:]\n for point in rated_points[:length_fp]:\n if self.selection_rate > random():\n new_gen.append(point)\n\n # mutate some of the individuals\n for individual in new_gen:\n index1 = randint(0, len(individual) - 1)\n index2 = randint(0, len(individual) - 1)\n if self.mutation_rate > random():\n if index1 != index2:\n temp = individual[index1]\n individual[index1] = individual[index2]\n individual[index2] = temp\n\n # Fill up the rest of the pop\n desired_length = len(rated_points) - len(new_gen)\n children = []\n while len(children) < desired_length:\n male = randint(0, len(new_gen) - 1)\n female = randint(0, len(new_gen) - 1)\n if male != female:\n male = new_gen[male]\n female = new_gen[female]\n [child1, child2] = self.crossover(male, female)\n children.append(child1)\n children.append(child2)\n \n new_gen.extend(children) \n return new_gen\n\ndef main():\n\n selection_rate = 0.05\n mutation_rate = 0.001\n points = generatePoints()\n ga = GA((selection_rate, mutation_rate))\n # ga.visualize(points)\n pop = generatePopulation(100)\n rated_pop = []\n for i in range(200):\n rated_pop.append((ga.averageFitness(pop), pop))\n pop = ga.evolve(pop)\n\n pop = rated_pop[-1][1]\n pop = sorted(pop)\n individual_sample = pop[0]\n \n # ga.visualize(individual_sample)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"Visualize.py","file_name":"Visualize.py","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"6394368","text":"#This Simulation Created by Vijay Kag \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nimport math as mt\r\nfrom physical_objects import circle,sline,springcoil\r\nclass Spring_1D:\r\n def __init__(self,mass=1,stiffness=1,damping=0.03,gravity=2,time=200,dt=0.1,natural_length=4,yinitial=-2,velocity=0,frame_interval=15,figsize=(10,8),repeat=True):\r\n self.m=mass\r\n self.k=stiffness\r\n self.damp=damping\r\n self.gravity=gravity\r\n self.yi=yinitial\r\n self.vyi=velocity\r\n self.l0=natural_length\r\n self.tf=time\r\n self.dt=dt\r\n self.y=[]\r\n self.vy=[]\r\n self.t=[]\r\n self.nt=int(self.tf/self.dt)\r\n self.frame_interval=frame_interval\r\n self.figsize=figsize\r\n self.count=0\r\n self.ani=None\r\n self.repeat=repeat\r\n def f(self,y,vy):\r\n return (-self.k*(self.l0+y)-self.gravity-self.damp*vy)/self.m\r\n def __solve_system(self):\r\n self.t.append(0)\r\n self.y.append(self.yi)\r\n self.vy.append(self.vyi)\r\n for i in range(self.nt):\r\n t1=self.f(self.y[i],self.vy[i])\r\n self.t.append((i+1)*self.dt)\r\n self.y.append(self.y[i]+self.dt*self.vy[i]+self.dt**2/2*t1)\r\n self.vy.append(self.vy[i]+self.dt*self.f(self.y[i]+self.dt/2*self.vy[i],self.vy[i]+self.dt/2*t1))\r\n def show_particle(self):\r\n if self.count==0:\r\n self.__solve_system()\r\n self.count=self.count+1\r\n fig = plt.figure(figsize=self.figsize) \r\n ax = plt.axes(xlim=(-4,4), ylim=(min(self.y)-3,1)) \r\n pline1,=ax.plot([], [], lw=2,c='b') \r\n cline1,=ax.plot([], [], lw=2,c='r')\r\n plt.hlines(0,-2,2)\r\n def animate(i):\r\n cx1,cy1=circle(0,self.y[i],0.2)\r\n tn1,tn2=springcoil(0,0,0,self.y[i],10,0.1,70)\r\n if self.y[i]**2 None:\n cls.url = Conf.TEST_URL.value\n cls.http = HttpRequests(cls.url)\n cls.mysql = Mysql_connet('device')\n cls.mysql.insert_device()\n\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.mysql.delete_device()\n cls.mysql.close()\n @doc_parameter(Conf.TEST_URL.value,uri)\n def test_add_task_success(self):\n '''查询锁申请授权息成功用例:{}{}'''\n payload = {\n \"lockName\": \"string\",\n \"name\": \"string\",\n \"pageNum\": 0,\n \"pageSize\": 0,\n \"startNum\": 0,\n \"status\": 0,\n \"total\": 0,\n \"userName\": \"string\"\n }\n payload = json.dumps(payload)\n headers = {'Content-Type': 'application/json'}\n response = Test_Add_Task.http.post(\n uri, data=payload, headers=headers)\n logging_test.log_test()\n logging_test.logging.info(Conf.TEST_URL.value + uri + '-接口返回:' + response.text)\n self.assertEqual(200, response.status_code, '返回非200')\n self.assertEqual(str(0), str(response.json()['code']), '查询锁申请授权息失败')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_case/web_test_case/cellar_well_key_auhorize_controller/test_pageQuery.py","file_name":"test_pageQuery.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"146435854","text":"\"\"\"\nmavDynamics \n - this file implements the dynamic equations of motion for MAV\n - use unit quaternion for the attitude state\n \nmavsim_python\n - Beard & McLain, PUP, 2012\n - Update history: \n 2/24/2020 - RWB\n\"\"\"\nimport sys\n\nsys.path.append(\"..\")\nimport numpy as np\n\n# load message types\nfrom message_types.msg_state import MsgState\nfrom message_types.msg_sensors import MsgSensors\nfrom message_types.msg_delta import MsgDelta\n\nimport parameters.aerosonde_parameters as MAV\nimport parameters.sensor_parameters as SENSOR\nfrom tools.rotations import Quaternion2Rotation, Quaternion2Euler, Euler2Rotation\n\n\nclass MavDynamics:\n def __init__(self, Ts):\n self._ts_simulation = Ts\n # set initial states based on parameter file\n # _state is the 13x1 internal state of the aircraft that is being propagated:\n # _state = [pn, pe, pd, u, v, w, e0, e1, e2, e3, p, q, r]\n # We will also need a variety of other elements that are functions of the _state and the wind.\n # self.true_state is a 19x1 vector that is estimated and used by the autopilot to control the aircraft:\n # true_state = [pn, pe, h, Va, alpha, beta, phi, theta, chi, p, q, r, Vg, wn, we, psi, gyro_bx, gyro_by, gyro_bz]\n self._state = np.array(\n [\n [MAV.north0], # (0)\n [MAV.east0], # (1)\n [MAV.down0], # (2)\n [MAV.u0], # (3)\n [MAV.v0], # (4)\n [MAV.w0], # (5)\n [MAV.e0], # (6)\n [MAV.e1], # (7)\n [MAV.e2], # (8)\n [MAV.e3], # (9)\n [MAV.p0], # (10)\n [MAV.q0], # (11)\n [MAV.r0],\n ]\n ) # (12)\n # store wind data for fast recall since it is used at various points in simulation\n self._wind = np.array([[0.0], [0.0], [0.0]]) # wind in NED frame in meters/sec\n # store forces to avoid recalculation in the sensors function\n self._forces = np.array([[0.0], [0.0], [0.0]])\n self._Va = MAV.u0\n self._alpha = 0\n self._beta = 0\n # initialize true_state message\n self.true_state = MsgState()\n # initialize the sensors message\n self._sensors = MsgSensors()\n # random walk parameters for GPS\n self._gps_nu_n = 0.0\n self._gps_nu_e = 0.0\n self._gps_nu_h = 0.0\n # timer so that gps only updates every ts_gps seconds\n self._t_gps = 999.0 # large value ensures gps updates at initial time.\n # update velocity data and forces and moments\n self._update_velocity_data()\n self._forces_moments(delta=MsgDelta())\n\n ###################################\n # public functions\n def update(self, delta, wind):\n \"\"\"\n Integrate the differential equations defining dynamics, update sensors\n delta = (delta_a, delta_e, delta_r, delta_t) are the control inputs\n wind is the wind vector in inertial coordinates\n Ts is the time step between function calls.\n \"\"\"\n # get forces and moments acting on rigid bod\n forces_moments = self._forces_moments(delta)\n\n # Integrate ODE using Runge-Kutta RK4 algorithm\n time_step = self._ts_simulation\n k1 = self._derivatives(self._state, forces_moments)\n k2 = self._derivatives(self._state + time_step / 2.0 * k1, forces_moments)\n k3 = self._derivatives(self._state + time_step / 2.0 * k2, forces_moments)\n k4 = self._derivatives(self._state + time_step * k3, forces_moments)\n self._state += time_step / 6 * (k1 + 2 * k2 + 2 * k3 + k4)\n\n # normalize the quaternion\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n normE = np.sqrt(e0 ** 2 + e1 ** 2 + e2 ** 2 + e3 ** 2)\n self._state[6][0] = self._state.item(6) / normE\n self._state[7][0] = self._state.item(7) / normE\n self._state[8][0] = self._state.item(8) / normE\n self._state[9][0] = self._state.item(9) / normE\n\n # update the airspeed, angle of attack, and side slip angles using new state\n self._update_velocity_data(wind)\n # update the message class for the true state\n self._update_true_state()\n\n def sensors(self):\n \"Return value of sensors on MAV: gyros, accels, absolute_pressure, dynamic_pressure, GPS\"\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n\n # euler angles\n phi, theta, psi = Quaternion2Euler(np.array([e0, e1, e2, e3]))\n R = Quaternion2Rotation(np.array([e0, e1, e2, e3]))\n\n # position kinematics using quaternion to avoid singularity\n u = self._state.item(3)\n v = self._state.item(4)\n w = self._state.item(5)\n pdot = R @ np.array([[u], [v], [w]])\n\n # simulate rate gyros(units are rad / sec)\n self._sensors.gyro_x = self._state[10, 0] + np.random.normal(\n SENSOR.gyro_x_bias, SENSOR.gyro_sigma\n )\n self._sensors.gyro_y = self._state[11, 0] + np.random.normal(\n SENSOR.gyro_y_bias, SENSOR.gyro_sigma\n )\n self._sensors.gyro_z = self._state[12, 0] + np.random.normal(\n SENSOR.gyro_z_bias, SENSOR.gyro_sigma\n )\n\n # simulate accelerometers(units of g)\n self._sensors.accel_x = (\n self._forces.item(0) / MAV.mass\n + MAV.gravity * np.sin(theta)\n + np.random.normal(0, SENSOR.accel_sigma)\n )\n self._sensors.accel_y = (\n self._forces.item(1) / MAV.mass\n - MAV.gravity * np.cos(theta) * np.sin(phi)\n + np.random.normal(0, SENSOR.accel_sigma)\n )\n self._sensors.accel_z = (\n self._forces.item(2) / MAV.mass\n - MAV.gravity * np.cos(theta) * np.cos(phi)\n + np.random.normal(0, SENSOR.accel_sigma)\n )\n # simulate magnetometers\n # magnetic field in provo has magnetic declination of 12.5 degrees\n # and magnetic inclination of 66 degrees\n iota = np.radians(66)\n delta = np.radians(12.5)\n R_mag = Euler2Rotation(0, -iota, delta).T\n # magnetic field in inertial frame: unit vector\n mag_inertial = R_mag @ np.array([[1, 0, 0]]).T\n R = R.T # body to inertial\n # magnetic field in body frame: unit vector\n mag_body = R @ mag_inertial\n self._sensors.mag_x = mag_body.item(0) + np.random.normal(\n SENSOR.mag_beta, SENSOR.mag_sigma\n )\n self._sensors.mag_y = mag_body.item(1) + np.random.normal(\n SENSOR.mag_beta, SENSOR.mag_sigma\n )\n self._sensors.mag_z = mag_body.item(2) + np.random.normal(\n SENSOR.mag_beta, SENSOR.mag_sigma\n )\n # simulate pressure sensors\n self._sensors.abs_pressure = MAV.rho * MAV.gravity * -self._state.item(\n 2\n ) + np.random.normal(0, SENSOR.abs_pres_sigma)\n self._sensors.diff_pressure = MAV.rho * self._Va**2 / 2 + np.random.normal(\n 0, SENSOR.diff_pres_sigma\n )\n # simulate GPS sensor\n if self._t_gps >= SENSOR.ts_gps:\n self._gps_nu_n = np.exp(\n -SENSOR.gps_k * SENSOR.ts_gps\n ) * self._gps_nu_n + np.random.normal(0, SENSOR.gps_n_sigma)\n self._gps_nu_e = np.exp(\n -SENSOR.gps_k * SENSOR.ts_gps\n ) * self._gps_nu_e + np.random.normal(0, SENSOR.gps_e_sigma)\n self._gps_nu_h = np.exp(\n -SENSOR.gps_k * SENSOR.ts_gps\n ) * self._gps_nu_h + np.random.normal(0, SENSOR.gps_h_sigma)\n self._sensors.gps_n = self._state.item(0) + self._gps_nu_n\n self._sensors.gps_e = self._state.item(1) + self._gps_nu_e\n self._sensors.gps_h = self._state.item(2) + self._gps_nu_h\n self._sensors.gps_Vg = np.sqrt(\n (self._Va * np.cos(psi) + self._wind.item(0)) ** 2 + (self._Va * np.sin(psi) + self._wind.item(1)) ** 2\n ) + np.random.normal(0, SENSOR.gps_Vg_sigma)\n self._sensors.gps_course = np.arctan2(\n self._Va * np.sin(psi) + self._wind.item(1), self._Va * np.cos(psi) + self._wind.item(0)\n ) + np.random.normal(0, SENSOR.gps_course_sigma)\n self._t_gps = 0.0\n else:\n self._t_gps += self._ts_simulation\n return self._sensors\n\n def external_set_state(self, new_state):\n self._state = new_state\n\n ###################################\n # private functions\n def _derivatives(self, state, forces_moments):\n \"\"\"\n for the dynamics xdot = f(x, u), returns f(x, u)\n \"\"\"\n # extract the states\n # north = state.item(0)\n # east = state.item(1)\n # altitude = state.item(2)\n # print(state)\n u = state.item(3)\n v = state.item(4)\n w = state.item(5)\n e0 = state.item(6)\n e1 = state.item(7)\n e2 = state.item(8)\n e3 = state.item(9)\n p = state.item(10)\n q = state.item(11)\n r = state.item(12)\n # extract forces/moments\n fx = forces_moments.item(0)\n fy = forces_moments.item(1)\n fz = forces_moments.item(2)\n l = forces_moments.item(3)\n m = forces_moments.item(4)\n n = forces_moments.item(5)\n\n # euler angles\n phi, theta, psi = Quaternion2Euler(np.array([e0, e1, e2, e3]))\n R = Quaternion2Rotation(np.array([e0, e1, e2, e3]))\n\n # position kinematics using quaternion to avoid singularity\n pdot = R @ np.array([[u], [v], [w]])\n\n pn_dot = pdot[0, 0]\n pe_dot = pdot[1, 0]\n pd_dot = pdot[2, 0]\n\n # position dynamics\n u_dot = (r * v - q * w) + fx / MAV.mass\n v_dot = (p * w - r * u) + fy / MAV.mass\n w_dot = (q * u - p * v) + fz / MAV.mass\n\n # rotational kinematics\n e0_dot = 0.5 * (-p * e1 - q * e2 - r * e3)\n e1_dot = 0.5 * (p * e0 + r * e2 - q * e3)\n e2_dot = 0.5 * (q * e0 - r * e1 + p * e3)\n e3_dot = 0.5 * (r * e0 + q * e1 - p * e2)\n\n # gammas\n gamma1 = MAV.gamma1\n gamma2 = MAV.gamma2\n gamma3 = MAV.gamma3\n gamma4 = MAV.gamma4\n gamma5 = MAV.gamma5\n gamma6 = MAV.gamma6\n gamma7 = MAV.gamma7\n gamma8 = MAV.gamma8\n\n # rotatonal dynamics\n p_dot = gamma1 * p * q - gamma2 * q * r + gamma3 * l + gamma4 * n\n q_dot = gamma5 * p * r - gamma6 * (p ** 2 - r ** 2) + m / MAV.Jy\n r_dot = gamma7 * p * q - gamma1 * q * r + gamma4 * l + gamma8 * n\n\n # collect the derivative of the states\n x_dot = np.array(\n [\n [\n pn_dot,\n pe_dot,\n pd_dot,\n u_dot,\n v_dot,\n w_dot,\n e0_dot,\n e1_dot,\n e2_dot,\n e3_dot,\n p_dot,\n q_dot,\n r_dot,\n ]\n ]\n ).T\n return x_dot\n\n def _update_velocity_data(self, wind=np.zeros((6, 1))):\n steady_state = wind[0:3]\n gust = wind[3:6]\n # convert wind vector from world to body frame and add gust\n wind_body_frame = Quaternion2Rotation(self._state[6:10])\n self._wind = wind_body_frame @ steady_state + gust # wind in the world frame\n # velocity vector relative to the airmass\n ur = self._state[3, 0] - self._wind[0, 0]\n vr = self._state[4, 0] - self._wind[1, 0]\n wr = self._state[5, 0] - self._wind[2, 0]\n # compute airspeed\n self._Va = np.sqrt(ur ** 2 + vr ** 2 + wr ** 2)\n # compute angle of attack\n if ur == 0:\n print(\"ur is zero!!\")\n self._alpha = 0\n else:\n self._alpha = np.arctan2(wr, ur)\n # compute sideslip angle\n if self._Va == 0:\n print(\"Va is zero!!\")\n self._beta = 0\n else:\n self._beta = np.arcsin(vr / self._Va)\n\n def _forces_moments(self, delta):\n \"\"\"\n return the forces on the UAV based on the state, wind, and control surfaces\n :param delta: np.matrix(delta_a, delta_e, delta_r, delta_t)\n :return: Forces and Moments on the UAV np.matrix(Fx, Fy, Fz, Ml, Mn, Mm)\n \"\"\"\n delta_a = delta.aileron\n delta_e = delta.elevator\n delta_r = delta.rudder\n delta_t = delta.throttle\n\n phi, theta, psi = Quaternion2Euler(self._state[6:10, 0])\n p = self._state.item(10)\n q = self._state.item(11)\n r = self._state.item(12)\n\n # compute gravitational forces, using quaternion\n ex = self._state.item(7)\n ey = self._state.item(8)\n ez = self._state.item(9)\n e0 = self._state.item(6)\n\n # gravity force expressed in body frame, try quaternion2rotation\n f_g = (\n MAV.mass\n * MAV.gravity\n * np.array(\n [\n [2 * (ex * ez - ey * e0)],\n [2 * (ey * ez + ex * e0)],\n [ez ** 2 + e0 ** 2 - ex ** 2 - ey ** 2],\n ]\n )\n )\n\n # compute Lift (eq. 4.9) and Drag (eq 4.11) coefficients, sigma (eq 4.10)\n # using nonlinear blended model for CL(alpha) and CD(alpha)\n sigma = (\n 1\n + np.exp(-MAV.M * (self._alpha - MAV.alpha0))\n + np.exp(MAV.M * (self._alpha + MAV.alpha0))\n ) / (\n (1 + np.exp(-MAV.M * (self._alpha - MAV.alpha0)))\n * (1 + np.exp(MAV.M * (self._alpha + MAV.alpha0)))\n )\n CL = (1 - sigma) * (MAV.C_L_0 + MAV.C_L_alpha * self._alpha) + sigma * (\n 2 * np.sign(self._alpha) * np.sin(self._alpha) ** 2 * np.cos(self._alpha)\n )\n CD = MAV.C_D_p + (MAV.C_L_0 + MAV.C_L_alpha * self._alpha) ** 2 / (\n np.pi * MAV.e * MAV.AR\n )\n # compute Lift(eq 4.6) and Drag (eq 4.7) Forces\n temp = 0.5 * MAV.rho * self._Va ** 2 * MAV.S_wing\n F_lift = temp * (\n CL + MAV.C_L_q * MAV.c * q / (2 * self._Va) + MAV.C_L_delta_e * delta_e\n )\n F_drag = temp * (\n CD + MAV.C_D_q * MAV.c * q / (2 * self._Va) + MAV.C_D_delta_e * delta_e\n )\n\n # compute propeller thrust and torque\n thrust_prop, torque_prop = self._motor_thrust_torque(self._Va, delta_t)\n # print(\"Thrust: \", thrust_prop)\n\n # compute longitudinal forces in body frame (4.24)\n sa = np.sin(self._alpha)\n ca = np.cos(self._alpha)\n\n # #LONG WAY\n # C_X = -CD * ca + CL * sa\n # C_X_q = -MAV.C_D_q * ca + MAV.C_L_q * sa\n # C_X_delta_e = -MAV.C_D_delta_e * ca + MAV.C_L_delta_e * sa\n # C_Z = -CD * sa - CL * ca\n # C_Z_q = -MAV.C_D_q * sa - MAV.C_L_q * ca\n # C_Z_delta_e = -MAV.C_D_delta_e * sa - MAV.C_L_delta_e * ca\n\n # fx = (\n # f_g[0, 0]\n # + thrust_prop\n # + temp * (C_X + C_X_q * MAV.c * q / (2 * self._Va))\n # + temp * (C_X_delta_e * delta_e)\n # )\n # fz = (\n # f_g[2, 0]\n # + temp * (C_Z + C_Z_q * MAV.c * q / (2 * self._Va))\n # + temp * (C_Z_delta_e * delta_e)\n # )\n\n # SHORT WAY\n fx = f_g[0, 0] - F_drag * ca + F_lift * sa + thrust_prop\n fz = f_g[2, 0] - F_drag * sa - F_lift * ca\n\n # compute lateral forces in body frame (4.24)\n fy = (\n f_g[1, 0]\n + temp\n * (\n MAV.C_Y_0\n + MAV.C_Y_beta * self._beta\n + MAV.C_Y_p * MAV.b * p / (2 * self._Va)\n + MAV.C_Y_r * MAV.b * r / (2 * self._Va)\n )\n + temp * (MAV.C_Y_delta_a * delta_a + MAV.C_Y_delta_r * delta_r)\n )\n\n # compute logitudinal torque in body frame, My = m (4.26)\n My = temp * (\n MAV.c\n * (\n MAV.C_m_0\n + MAV.C_m_alpha * self._alpha\n + MAV.C_m_q * MAV.c * q / (2 * self._Va)\n )\n ) + temp * (MAV.c * (MAV.C_m_delta_e * delta_e))\n # compute lateral torques in body frame Mx = l, Mz = n\n Mx = (\n temp\n * (\n MAV.b\n * (\n MAV.C_ell_0\n + MAV.C_ell_beta * self._beta\n + MAV.C_ell_p * MAV.b * p / (2 * self._Va)\n + MAV.C_ell_r * MAV.b * r / (2 * self._Va)\n )\n )\n + temp\n * (MAV.b * (MAV.C_ell_delta_a * delta_a + MAV.C_ell_delta_r * delta_r))\n + torque_prop\n )\n Mz = temp * (\n MAV.b\n * (\n MAV.C_n_0\n + MAV.C_n_beta * self._beta\n + MAV.C_n_p * MAV.b * p / (2 * self._Va)\n + MAV.C_n_r * MAV.b * r / (2 * self._Va)\n )\n ) + temp * (MAV.b * (MAV.C_n_delta_a * delta_a + MAV.C_n_delta_r * delta_r))\n\n self._forces[0] = fx\n self._forces[1] = fy\n self._forces[2] = fz\n forces_moments = np.array([[fx, fy, fz, Mx, My, Mz]]).T\n # print(\"forces\\n\", forces_moments)\n # return np.array([[0, 0, 0, 0.0, 0.0, 0.0]]).T\n return forces_moments\n\n def _motor_thrust_torque(self, Va, delta_t):\n # compute thrust and torque due to propeller (See addendum by McLain)\n # map delta_t throttle command(0 to 1) into motor input voltage (eq 4.22)\n V_in = MAV.V_max * delta_t\n\n # Angular speed of propeller (eq 4.21)\n a = MAV.rho * MAV.D_prop ** 5 * MAV.C_Q0 / (2 * np.pi) ** 2\n b = (\n MAV.rho * MAV.D_prop ** 4 * MAV.C_Q1 * Va / (2 * np.pi)\n + MAV.KQ ** 2 / MAV.R_motor\n )\n c = (\n MAV.rho * MAV.D_prop ** 3 * MAV.C_Q2 * Va ** 2\n - MAV.KQ * V_in / MAV.R_motor\n + MAV.KQ * MAV.i0\n )\n Omega_p = (-b + np.sqrt(b ** 2 - 4 * a * c)) / (2 * a)\n\n # calculate advance ratio J\n J = (2 * np.pi * Va) / (Omega_p * MAV.D_prop)\n\n # calculate nondimensional coefficients\n C_T = MAV.C_T2 * J ** 2 + MAV.C_T1 * J + MAV.C_T0\n C_Q = MAV.C_Q2 * J ** 2 + MAV.C_Q1 * J + MAV.C_Q0\n\n # thrust (eq 4.17) and torque (eq 4.18) due to propeller\n thrust_prop = C_T * MAV.rho * MAV.D_prop ** 4 * Omega_p ** 2 / (4 * np.pi ** 2)\n torque_prop = C_Q * MAV.rho * MAV.D_prop ** 5 * Omega_p ** 2 / (4 * np.pi ** 2)\n return thrust_prop, torque_prop\n\n def _update_true_state(self):\n # update the class structure for the true state:\n # [pn, pe, h, Va, alpha, beta, phi, theta, chi, p, q, r, Vg, wn, we, psi, gyro_bx, gyro_by, gyro_bz]\n phi, theta, psi = Quaternion2Euler(self._state[6:10])\n pdot = Quaternion2Rotation(self._state[6:10]) @ self._state[3:6]\n self.true_state.north = self._state.item(0)\n self.true_state.east = self._state.item(1)\n self.true_state.altitude = -self._state.item(2)\n self.true_state.Va = self._Va\n self.true_state.alpha = self._alpha\n self.true_state.beta = self._beta\n self.true_state.phi = phi\n self.true_state.theta = theta\n self.true_state.psi = psi\n self.true_state.Vg = np.linalg.norm(pdot)\n self.true_state.gamma = np.arcsin(pdot.item(2) / self.true_state.Vg)\n self.true_state.chi = np.arctan2(pdot.item(1), pdot.item(0))\n self.true_state.p = self._state.item(10)\n self.true_state.q = self._state.item(11)\n self.true_state.r = self._state.item(12)\n self.true_state.wn = self._wind.item(0)\n self.true_state.we = self._wind.item(1)\n","sub_path":"chap7/mav_dynamics.py","file_name":"mav_dynamics.py","file_ext":"py","file_size_in_byte":19904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"214230888","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#Импортируем библиотеку Math\nimport math\n#Импортируем один из пакетов Matplotlib\nimport pylab\nimport random\n#Импортируем пакет со вспомогательными функциями\nfrom matplotlib import mlab\nmass=[] # массив для значений на выходе антенны \nxlist = mlab.frange (1, 500, 1)# набор итераций от 1 до 500-й\nw1=complex(1 ,0)# начальное значение 1-го весового коэффициента\nw2=complex(1 ,0)# начальное значение 2-го весового коэффициента\nd_lambda=0.5\nfor k in range(1,501):# 500 итераций\n # х1 - комплексное значение первой случайной помехи\n x1=complex(random.normalvariate(0, 10) ,random.normalvariate(0, 10))\n # х2 - комплексное значение второй случайной помехи\n x2=complex(random.normalvariate(0, 10) ,random.normalvariate(0, 10))\n # 1-я помехах с угла 30 градусов, 2-я с угла 45 градусов\n # x2elem - значения суммы помех во втором антенном элементе\n fi=2*math.pi*d_lambda*math.sin(math.pi/180.0*30) \n x2elem=x1*complex(math.cos(fi) ,math.sin(fi))\n fi=2*math.pi*d_lambda*math.sin(math.pi/180.0*45) \n x2elem=x2elem+x2*complex(math.cos(fi) ,math.sin(fi))\n # x2elem - значения суммы помех в третьем антенном элементе\n fi=2*2*math.pi*d_lambda*math.sin(math.pi/180.0*30) \n x3elem=x1*complex(math.cos(fi) ,math.sin(fi))\n fi=2*2*math.pi*d_lambda*math.sin(math.pi/180.0*45) \n x3elem=x3elem+x2*complex(math.cos(fi) ,math.sin(fi))\n # x1elem - значения суммы помех во 1-м антенном элементе\n x1elem=x1+x2\n # e - значение на выходе АР\n e=x1elem+w1*x2elem+w2*x3elem\n # e_osh - значение ошибки\n e_osh=-e\n w1=w1+2*0.0003*e_osh*x2elem.conjugate()\n w2=w2+2*0.0003*e_osh*x3elem.conjugate()\n mass.append(abs(e))\npylab.plot (xlist, mass)\n#Покажем окно с нарисованным графиком\npylab.show() ","sub_path":"Sublim/py/python/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"54173719","text":"import unittest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass SearchResultsPageTest(unittest.TestCase):\n @classmethod # only run on the class instead of method\n def setUpClass(inst):\n # create a Firefox session\n inst.driver = webdriver.Firefox()\n inst.driver.implicitly_wait(30)\n inst.driver.maximize_window()\n inst.driver.get(\"https://www.bankofireland.com/search/\")\n inst.driver.title\n\n def test_jsbarsearch(self):\n self.searchfield = self.driver.find_element_by_class_name(\"js-search-bar\")\n self.searchfield.click()\n self.field = self.driver.find_element_by_id(\"s\")\n self.field.clear()\n self.field.send_keys(\"loans\")\n self.field.send_keys(Keys.ENTER)\n time.sleep(5)\n expected = \"https://www.bankofireland.com/search/?q=loans\"\n actual = self.driver.current_url\n self.assertEqual(expected,actual,\"Urls do not match\")\n\n @classmethod\n def tearDownClass(inst):\n # close the browser window\n inst.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"PycharmProjects/deleteme/Search_Results_Page.py","file_name":"Search_Results_Page.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"27542774","text":"import threading\nimport os \nimport time\n\nimport grpc\n\nimport proto.chat_pb2 as chat\nimport proto.chat_pb2_grpc as rpc\n\naddress = 'localhost'\nport = 11912\n\n\nclass Client:\n\n def __init__(self, u: str):\n # the frame to put ui components on\n self.username = u\n # create a gRPC channel + stub\n channel = grpc.insecure_channel(address + ':' + str(port))\n self.conn = rpc.ChatServerStub(channel)\n # create new listening thread for when new message streams come in\n threading.Thread(target=self.__ListenForMessages, daemon=True).start()\n\n def __ListenForMessages(self):\n \"\"\"\n This method will be ran in a separate thread as the main/ui thread, because the for-in call is blocking\n when waiting for new messages\n \"\"\"\n for note in self.conn.ChatStream(chat.Empty()):\n print(\"R[{}] {}\".format(note.name, note.message))\n\n def SendMessage(self, message):\n if message is not '':\n n = chat.Note()\n n.name = self.username\n n.message = message\n print(\"S[{}] {}\".format(n.name, n.message))\n self.conn.SendNote(n)\n\nif __name__ == '__main__':\n username = None\n while username is None:\n username = input(\"Enter your name: \") \n c = Client(username)\n while True:\n line = input(\"> \")\n if line == \"exit\":\n os.exit()\n c.SendMessage(line)\n time.sleep(0.02)\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"424552369","text":"# -*- coding: utf-8 -*-\n# Version: 1.4\n# See github page to report issues or contribute:\n# https://github.com/hssm/anki-addons\n\nfrom PyQt4 import QtGui\n\nfrom aqt import *\nfrom aqt.browser import DataModel\nfrom aqt.forms.browser import Ui_Dialog\nfrom anki.hooks import wrap\nfrom anki.find import Finder\n\nCONF_KEY_CHECKED = 'strip_ar_diac_checked'\n\n# Note: the current algorithm strips secondary code points regardless of the\n# preceding code point. This is likely to be sufficient for this add-on.\nignorables = [\n# Always ignore\nu'\\u0600', u'\\u0601', u'\\u0602', u'\\u0603', u'\\u0604', u'\\u0606', u'\\u0607',\nu'\\u0608', u'\\u0609', u'\\u060A', u'\\u060C', u'\\u060D', u'\\u060E', u'\\u060F',\nu'\\u0610', u'\\u0611', u'\\u0612', u'\\u0613', u'\\u0614', u'\\u0615', u'\\u0616',\nu'\\u0617', u'\\u0618', u'\\u0619', u'\\u061A', u'\\u061B', u'\\u061E', u'\\u061F',\nu'\\u0640', u'\\u066A', u'\\u066B', u'\\u066C', u'\\u066D', u'\\u06D4', u'\\u06D6',\nu'\\u06D7', u'\\u06D8', u'\\u06D9', u'\\u06DA', u'\\u06DB', u'\\u06DC', u'\\u06DD',\nu'\\u06DE', u'\\u06DF', u'\\u06E0', u'\\u06E1', u'\\u06E2', u'\\u06E3', u'\\u06E4',\nu'\\u06E7', u'\\u06E8', u'\\u06E9', u'\\u06EA', u'\\u06EB', u'\\u06EC', u'\\u06ED',\n\n# Secondary\nu'\\u064B', u'\\uFE71', u'\\uFE70', u'\\u08F0', u'\\u08E7', u'\\u064C', u'\\uFE72',\nu'\\uFC5E', u'\\u08F1', u'\\u08E8', u'\\u064D', u'\\uFE74', u'\\uFC5F', u'\\u08F2',\nu'\\u08E9', u'\\u064E', u'\\uFE77', u'\\uFE76', u'\\uFCF2', u'\\uFC60', u'\\u08E4',\nu'\\u08F4', u'\\u08F5', u'\\u064F', u'\\uFE79', u'\\uFE78', u'\\uFCF3', u'\\uFC61',\nu'\\u08E5', u'\\u08FE', u'\\u0650', u'\\uFE7B', u'\\uFE7A', u'\\uFCF4', u'\\uFC62',\nu'\\u08E6', u'\\u08F6', u'\\u0651', u'\\uFE7D', u'\\uFE7C', u'\\uFC63', u'\\u0652',\nu'\\uFE7F', u'\\uFE7E', u'\\u0653', u'\\u0654', u'\\u0655', u'\\u065F', u'\\u0656',\nu'\\u0657', u'\\u0658', u'\\u0659', u'\\u065A', u'\\u065B', u'\\u065C', u'\\u065D',\nu'\\u065E', u'\\u08F7', u'\\u08F8', u'\\u08FD', u'\\u08FB', u'\\u08FC', u'\\u08F9',\nu'\\u08FA', u'\\u0670']\n\n\ntranslationTable = dict.fromkeys(map(ord, ignorables), None)\n\ndef stripArabic(txt):\n \"\"\"Return txt excluding ignorable Arabic diacritics.\"\"\"\n return txt.translate(translationTable)\n\n\ndef mySearch(self, txt, reset=True):\n \"\"\"Overriding browser.py -> DataModel.Search. Do a search using custom\n methods if the Arabic diacritics checkbox is checked.\"\"\"\n\n if reset:\n self.beginReset()\n \n # NOTE: Only override the finder function on the click of the browser's\n # \"search\" button since this function is used elsewhere. We restore\n # it to the original one after we do our search.\n origFindText = Finder._findText\n if self.browser.form.arToggleButton.isChecked():\n Finder._findText = myFindText\n txt = unicode(txt)\n txt = stripArabic(txt)\n\n self.cards = []\n self.cards = self.col.findCards(txt, order=True)\n\n # Put back original function after search\n Finder._findText = origFindText\n \n if reset:\n self.endReset()\n \n\ndef myFindText(self, val, args):\n \"\"\"Build a custom SQL query to invoke a function to strip Arabic\n diacritics from the search space.\"\"\"\n \n val = val.replace(\"*\", \"%\")\n args.append(\"%\"+val+\"%\")\n args.append(\"%\"+val+\"%\")\n\n # NOTE: the \"?\" is assumed to be stripped already.\n return \"(n.sfld like ? escape '\\\\' or \"\\\n \"stripArabic(n.flds) like ? escape '\\\\')\"\n\n \ndef mySetupUi(self, mw):\n \"\"\"Add new items to the browser UI to allow toggling the add-on.\"\"\"\n \n # Surely there's a better place for this ! \n # Create a new SQL function that we can use in our queries.\n mw.col.db._db.create_function(\"stripArabic\", 1, stripArabic)\n\n # Our UI stuff\n self.arToggleButton = QtGui.QCheckBox(self.widget)\n self.arToggleLabel = QtGui.QLabel(\"Strip Arabic\\n Diacritics\")\n \n # Initial checked state is what we had saved previously\n self.arToggleButton.setCheckState(mw.col.conf.get(CONF_KEY_CHECKED, 0))\n\n # Save state on toggle\n mw.connect(self.arToggleButton, SIGNAL(\"stateChanged(int)\"), onChecked)\n \n # Add our items to the right of the search box. We do this by moving\n # every widget out of the gridlayout and into a new list. We simply\n # add our stuff in the new list in the right place before moving them\n # back to gridlayout.\n n_items = self.gridLayout.count()\n items= []\n for i in range(0, n_items):\n item = self.gridLayout.itemAt(i).widget()\n items.append(item)\n if item == self.searchEdit:\n items.append(self.arToggleButton)\n items.append(self.arToggleLabel)\n \n for i, item in enumerate(items):\n self.gridLayout.addWidget(item, 0, i, 1, 1)\n \n \ndef onChecked(state):\n \"\"\"Save the checked state in Anki's configuration.\"\"\"\n mw.col.conf[CONF_KEY_CHECKED] = state\n\nUi_Dialog.setupUi= wrap(Ui_Dialog.setupUi, mySetupUi)\nDataModel.search = mySearch","sub_path":"strip_arabic_diacritics.py","file_name":"strip_arabic_diacritics.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"307241508","text":"import vtk\n\n# Create the reader and read a data file. \nsr = vtk.vtkSTLReader()\nsr.SetFileName(r\"C:\\Users\\lee\\Desktop\\untitled.stl\")\nsr.Update()\n\nstlMapper = vtk.vtkPolyDataMapper()\nstlMapper.SetInputConnection(sr.GetOutputPort())\n\nstlActor = vtk.vtkLODActor()\nstlActor.SetMapper(stlMapper)\n\n#stlActor.SetPosition(-50, 0, 0)\n\np = [0, 0, 0]\npolydata = sr.GetOutput()\nptsNum=polydata.GetNumberOfPoints()\ncellNum=polydata.GetNumberOfCells()\nprint(\"GetNumberOfPieces %s\"%polydata.GetNumberOfPieces())\nprint(\"GetNumberOfStrips %s\"%polydata.GetNumberOfStrips())\nprint(\"GetNumberOfCells %s\"%cellNum)\nprint(\"GetNumberOfPoints %s\"%ptsNum)\nfor i in range(ptsNum):\n polydata.GetPoint(i, p)\n # print(p)\n\npts=[]\nfor j in range(cellNum):\n c=polydata.GetCell(j)\n pts_cell=[c.GetPointId(0),c.GetPointId(1),c.GetPointId(2)]\n pts.extend(pts_cell)\n\n# Create the Renderer, RenderWindow, and RenderWindowInteractor\nren = vtk.vtkRenderer()\n\nrenWin = vtk.vtkRenderWindow()\nrenWin.AddRenderer(ren)\niren = vtk.vtkRenderWindowInteractor()\niren.SetRenderWindow(renWin)\n\n# Add the actors to the render; set the background and size\nren.AddActor(stlActor)\nren.SetBackground(0.1, 0.1, 0.1)\nrenWin.SetSize(500, 500)\n\n# create coordinate axes in the render window\naxes = vtk.vtkAxesActor() \naxes.SetTotalLength(2, 2, 2) # Set the total length of the axes in 3 dimensions\n# Set the type of the shaft to a cylinder:0, line:1, or user defined geometry. \naxes.SetShaftType(0) \naxes.SetCylinderRadius(0.02) \naxes.SetAxisLabels(0) \nren.AddActor(axes)\n \nstyle = vtk.vtkInteractorStyleTrackballCamera()\nstyle.SetDefaultRenderer(ren)\niren.SetInteractorStyle(style)\niren.Initialize()\n\nrenWin.SetWindowName(\"STL Import\")\nrenWin.Render()\niren.Start()","sub_path":"RL/my-grab/vtkSTL.py","file_name":"vtkSTL.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"136358791","text":"from covs.kernel import *\r\n\r\nclass FGP(nn.Module):\r\n def __init__(self, n_dim, ls=None):\r\n super(FGP, self).__init__()\r\n self.device = get_cuda_device()\r\n self.n_dim = n_dim\r\n self.cov = CovFunction(self.n_dim, ls=ls).to(self.device)\r\n self.mean = MeanFunction().to(self.device)\r\n self.lik = LikFunction().to(self.device)\r\n\r\n def NLL(self, X, Y):\r\n Yc = Y.float() - self.mean.mean.float()\r\n Kxx = self.cov(X)\r\n torch.diagonal(Kxx).fill_(torch.exp(2.0 * self.cov.sn) + torch.exp(2.0 * self.lik.noise))\r\n L = torch.cholesky(Kxx, upper=False)\r\n Linv = torch.mm(torch.inverse(L), Yc)\r\n res = 0.5 * torch.sum(torch.log(L.diag())) + 0.5 * torch.mm(Linv.t(), Linv)\r\n return res\r\n\r\n def predict(self, Xt, X, Y, var=False):\r\n with torch.no_grad():\r\n Yc = Y.float() - self.mean.mean.float()\r\n Ktx = self.cov(Xt, X)\r\n Kxx = self.cov(X)\r\n Q_inv = torch.inverse(Kxx + torch.exp(2.0 * self.lik.noise) * torch.eye(X.shape[0]).to(self.device)).float()\r\n Yt = torch.mm(Ktx, torch.mm(Q_inv, Yc)) + self.mean.mean.float()\r\n if var is False:\r\n return Yt\r\n Ktt = self.cov(Xt)\r\n Vt = Ktt - torch.mm(Ktx, torch.mm(Q_inv, Ktx.t()))\r\n return Yt, Vt\r\n\r\n def forward(self, Xt, X, Y, grad=False, var=False):\r\n if grad is False:\r\n return self.predict(Xt, X, Y, var=var)\r\n Yc = Y.float() - self.mean.mean.float()\r\n Ktx = self.cov(Xt, X)\r\n Kxx = self.cov(X)\r\n Q_inv = torch.inverse(Kxx + torch.exp(2.0 * self.lik.noise) * torch.eye(X.shape[0]).to(self.device)).float()\r\n Yt = torch.mm(Ktx, torch.mm(Q_inv, Yc)) + self.mean.mean.float()\r\n if var is False:\r\n return Yt\r\n Ktt = self.cov(Xt)\r\n Vt = Ktt - torch.mm(Ktx, torch.mm(Q_inv, Ktx.t()))\r\n return Yt, Vt\r\n\r\n","sub_path":"gps/fgp.py","file_name":"fgp.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"131125823","text":"\"\"\" Conditional DCGAN for MNIST images generations.\n Author: Moustafa Alzantot (malzantot@ucla.edu)\n All rights reserved.\n\"\"\"\n\nfrom __future__ import print_function\n#%matplotlib inline\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\nfrom data_loader import get_loader\n\n# SAMPLE_SIZE = 80\nNUM_LABELS = 8\n\nclass Generator(nn.Module):\n def __init__(self, nz, ngf, nc):\n super(Generator, self).__init__()\n # TODO: Fix this with GPU and cuda \n self.ngpu = 0 \n self.main = nn.Sequential(\n # input is Z, going into a convolution\n # nn.ConvTranspose2d( nz, ngf , 4, 1, 0, bias=False),\n nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (nc) x 64 x 64\n )\n\n def forward(self, input):\n return self.main(input)\n\nclass Discriminator(nn.Module):\n def __init__(self, ndf, nc):\n super(Discriminator, self).__init__()\n # TODO: Fix this with GPU and cuda \n self.ngpu = 0 \n self.main = nn.Sequential(\n # input is (nc) x 64 x 64\n nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf) x 32 x 32\n nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*2) x 16 x 16\n nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*4) x 8 x 8\n nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 8),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*8) x 4 x 4\n nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, input):\n return self.main(input)\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\n\ndef train_generator(netG, netD, num_epochs, dataloader, device, batch_size, nz):\n\n # Initialize BCELoss function\n criterion = nn.BCELoss()\n\n # Create batch of latent vectors that we will use to visualize\n # the progression of the generator\n fixed_noise = torch.randn(64, args.nz, 1, 1, device=device)\n\n # Establish convention for real and fake labels during training\n real_label = 1\n fake_label = 0\n\n # Setup Adam optimizers for both G and D\n optimizerD = optim.Adam(netD.parameters(), lr=args.lr, betas=(args.beta1, 0.999))\n optimizerG = optim.Adam(netG.parameters(), lr=args.lr, betas=(args.beta1, 0.999))\n # Training Loop\n # Lists to keep track of progress\n img_list = []\n G_losses = []\n D_losses = []\n iters = 0\n print(\"Starting Training Loop...\")\n # For each epoch\n for epoch in range(num_epochs):\n # For each batch in the dataloader\n for i, data in enumerate(dataloader, 0):\n \n ############################\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n ###########################\n ## Train with all-real batch\n netD.zero_grad()\n # Format batch\n real_cpu = data[0].to(device)\n batch_size = real_cpu.size(0)\n # print(real_cpu.size())\n # print(\"batch size\" + str(b_size))\n label = torch.full((batch_size,), real_label, device=device)\n # Forward pass real batch through D\n # print(label.size())\n output = netD(real_cpu).view(-1)\n # Calculate loss on all-real batch\n # reshape to batch size \n # output = output.reshape((batch_size, int(output.size()[0]/batch_size)))\n # print(output.size())\n errD_real = criterion(output, label)\n # Calculate gradients for D in backward pass\n errD_real.backward()\n D_x = output.mean().item()\n\n ## Train with all-fake batch\n # Generate batch of latent vectors\n noise = torch.randn(batch_size, nz, 1, 1, device=device)\n # Generate fake image batch with G\n fake = netG(noise)\n label.fill_(fake_label)\n # Classify all fake batch with D\n output = netD(fake.detach()).view(-1)\n # Calculate D's loss on the all-fake batch\n errD_fake = criterion(output, label)\n # Calculate the gradients for this batch\n errD_fake.backward()\n D_G_z1 = output.mean().item()\n # Add the gradients from the all-real and all-fake batches\n errD = errD_real + errD_fake\n # Update D\n optimizerD.step()\n\n ############################\n # (2) Update G network: maximize log(D(G(z)))\n ###########################\n netG.zero_grad()\n label.fill_(real_label) # fake labels are real for generator cost\n # Since we just updated D, perform another forward pass of all-fake batch through D\n output = netD(fake).view(-1)\n # Calculate G's loss based on this output\n errG = criterion(output, label)\n # Calculate gradients for G\n errG.backward()\n D_G_z2 = output.mean().item()\n # Update G\n optimizerG.step()\n \n # Output training stats\n if i % 50 == 0:\n print('[%d/%d][%d/%d]\\tLoss_D: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'\n % (epoch, num_epochs, i, len(dataloader),\n errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n \n # Save Losses for plotting later\n G_losses.append(errG.item())\n D_losses.append(errD.item())\n \n # Check how the generator is doing by saving G's output on fixed_noise\n if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):\n with torch.no_grad():\n fake = netG(fixed_noise).detach().cpu()\n img_list.append(vutils.make_grid(fake, padding=2, normalize=True))\n \n iters += 1\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Conditional DCGAN')\n parser.add_argument('--batch_size', type=int, default=64,\n help='Batch size (default=64)')\n parser.add_argument('--lr', type=float, default=0.01,\n help='Learning rate (default=0.01)')\n parser.add_argument('--epochs', type=int, default=10,\n help='Number of training epochs.')\n parser.add_argument('--nz', type=int, default=100,\n help='Number of dimensions for input noise.')\n parser.add_argument('--beta1', type = float, default = 0.5, \n help=\"Beta1 hyperparam for Adam optimizers.\")\n parser.add_argument('--cuda', action='store_true',\n help='Enable cuda')\n parser.add_argument('--save_every', type=int, default=1,\n help='After how many epochs to save the model.')\n parser.add_argument('--print_every', type=int, default=50,\n help='After how many epochs to print loss and save output samples.')\n parser.add_argument('--save_dir', type=str, default='models',\n help='Path to save the trained models.')\n parser.add_argument('--image_size',type=int, default=64)\n parser.add_argument('--crop_size',type=int, default=64)\n parser.add_argument('--num_workers', type=int, default=1)\n parser.add_argument('--samples_dir', type=str, default='samples',\n help='Path to save the output samples.')\n parser.add_argument('--emotion_dir', type=str, default='/Users/evazhang/Downloads/entropy-gan-master/data/Emotion', help='emotion data directory.')\n parser.add_argument('--image_dir', type=str, default='/Users/evazhang/Downloads/entropy-gan-master/data/data/ck_align', help='image data directory')\n parser.add_argument('--cls', type=int, default=7)\n parser.add_argument('--kfold', type=int, default=10)\n parser.add_argument('--ithfold', type=int, default=0)\n parser.add_argument('--mode', type=str, default='train', help='train|valid')\n parser.add_argument('--nc', type=int, default = 3, help = 'nchannels, default rgb = 3')\n parser.add_argument('--ndf', type = int, default = 64, help = 'size of feature map in discriminator')\n parser.add_argument('--ngf', type = int, default = 64, help = 'size of feature map in generator')\n\n args = parser.parse_args()\n \n if not os.path.exists(args.save_dir):\n os.mkdir(args.save_dir)\n\n if not os.path.exists(args.samples_dir):\n os.mkdir(args.samples_dir)\n\n if os.path.exists(args.emotion_dir):\n print(os.path.isdir(args.emotion_dir + '/S010'))\n\n device = torch.device(\"cuda:0\" if (torch.cuda.is_available() and ngpu > 0) else \"cpu\")\n\n # initialize train loaders for ck+ data \n train_loader, valid_loader, _ = get_loader(args)\n\n # initialize models \n netD = Discriminator(args.ndf, args.nc)\n netD.apply(weights_init)\n netG = Generator(args.nz, args.ngf, args.nc)\n netG.apply(weights_init)\n train_generator(netG, netD, args.epochs, train_loader, device, args.batch_size, args.nz)\n\n\n\n\n\n","sub_path":"dcgan_new.py","file_name":"dcgan_new.py","file_ext":"py","file_size_in_byte":10668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"518183706","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 13 10:24:56 2020\n\n@author: arslan\n\"\"\"\n\nfrom pyit2fls import IT2Mamdani, IT2FS_Gaussian_UncertStd, IT2FS_plot, \\\n product_t_norm, max_s_norm, crisp\nfrom numpy import linspace, random, sin, cos, array\n\ndomainX1 = linspace(-1., 1., 101)\ndomainX2 = linspace(-1., 1., 101)\ndomainY1 = linspace(-0.5, 1.5, 101)\ndomainY2 = linspace(-0.5, 1.5, 101)\n\nX1Small = IT2FS_Gaussian_UncertStd(domainX1, [-1., 0.2, 0.1, 1.])\nX1Medium = IT2FS_Gaussian_UncertStd(domainX1, [0., 0.2, 0.1, 1.])\nX1Large = IT2FS_Gaussian_UncertStd(domainX1, [1., 0.2, 0.1, 1.])\n# IT2FS_plot(X1Small, X1Medium, X1Large)\n\nX2Small = IT2FS_Gaussian_UncertStd(domainX2, [-1., 0.2, 0.1, 1.])\nX2Medium = IT2FS_Gaussian_UncertStd(domainX2, [0., 0.2, 0.1, 1.])\nX2Large = IT2FS_Gaussian_UncertStd(domainX2, [1., 0.2, 0.1, 1.])\n# IT2FS_plot(X2Small, X2Medium, X2Large)\n\nY1Small = IT2FS_Gaussian_UncertStd(domainY1, [-0.5, 0.2, 0.1, 1.])\nY1Medium = IT2FS_Gaussian_UncertStd(domainY1, [0.5, 0.2, 0.1, 1.])\nY1Large = IT2FS_Gaussian_UncertStd(domainY1, [1.5, 0.2, 0.1, 1.])\n# IT2FS_plot(Y1Small, Y1Medium, Y1Large)\n\nY2Small = IT2FS_Gaussian_UncertStd(domainY2, [-0.5, 0.2, 0.1, 1.])\nY2Medium = IT2FS_Gaussian_UncertStd(domainY2, [0.5, 0.2, 0.1, 1.])\nY2Large = IT2FS_Gaussian_UncertStd(domainY2, [1., 0.2, 0.1, 1.])\n# IT2FS_plot(Y2Small, Y2Medium, Y2Large)\n\nmyIT2FLS = IT2Mamdani(product_t_norm, max_s_norm, method=\"CoSet\")\nmyIT2FLS.add_input_variable(\"x1\")\nmyIT2FLS.add_input_variable(\"x2\")\nmyIT2FLS.add_output_variable(\"y1\")\nmyIT2FLS.add_output_variable(\"y2\")\n\nnX1 = 3\nX1Sets = [X1Small, X1Medium, X1Large]\nnX2 = 3\nX2Sets = [X2Small, X2Medium, X2Large]\nnY1 = 3\nY1Sets = [Y1Small, Y1Medium, Y1Large]\nnY2 = 3\nY2Sets = [Y2Small, Y2Medium, Y2Large]\n\ndef generateRuleBase():\n Rules = []\n for i in range(9):\n rule = [i // nX1, i % nX2, \n random.randint(nY1), random.randint(nY2)]\n Rules.append(rule)\n return Rules\n\n\ntt = 2 * (random.rand(20) - 0.5)\nData = array([sin(tt), \n cos(tt), \n sin(tt) + cos(tt), \n cos(tt) - sin(tt)])\n\ndef error(R, D):\n # R: Rules\n # D: Data\n err = 0.\n myIT2FLS.rules = []\n for rule in R:\n myIT2FLS.add_rule([(\"x1\", X1Sets[rule[0]]), (\"x2\", X2Sets[rule[1]])], \n [(\"y1\", Y1Sets[rule[2]]), (\"y2\", Y2Sets[rule[3]])])\n for i in range(D.shape[1]):\n tr = myIT2FLS.evaluate({\"x1\":D[0, i], \"x2\":D[1, i]})\n err += (crisp(tr[\"y1\"]) - D[2, i]) ** 2 + (crisp(tr[\"y2\"]) - D[3, i]) ** 2\n return err\n \nif __name__ == \"__main__\":\n myRules = [[0, 0, 0, 1], \n [0, 1, 0, 2], \n [0, 2, 1, 2], \n [1, 0, 0, 0], \n [1, 1, 1, 1], \n [1, 2, 2, 2], \n [2, 0, 1, 0], \n [2, 1, 2, 0], \n [2, 2, 2, 1]]\n minErr = float(\"inf\")\n minRules = []\n for i in range(100):\n rule = generateRuleBase()\n err = error(rule, Data)\n if err < minErr:\n minErr = err\n minRules = rule\n print(str(i) + \".\", err)\n \n print(\"Best generated rule base:\")\n print(minRules)\n print(\"Minimum error:\", minErr)\n \n print(\"Rule base defined by expert:\")\n print(myRules)\n print(\"Error:\", error(myRules, Data))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"examples/ex_11_0.7.0.py","file_name":"ex_11_0.7.0.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"87427102","text":"# Copyright 2021, Google LLC.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"AIST++ train/val/test set split setting.\"\"\"\nimport re\n\nMUSIC_ID_TESTVAL = '(mBR0|mPO1|mLO2|mMH3|mLH4|mHO5|mWA0|mKR2|mJS3|mJB5)'\nMOTION_GEN_ID_TESTVAL = '.*_sBM_.*_(mBR|mPO|mLO|mMH|mLH|mHO|mWA|mKR|mJS|mJB).*_(ch01|ch02)'\nMOTION_GEN_ID_TESTVAL_PAIRED = '.*_sBM_.*_(mBR0|mPO1|mLO2|mMH3|mLH4|mHO5|mWA0|mKR2|mJS3|mJB5)_(ch01|ch02)'\nMOTION_GEN_ID_TESTVAL_UNPAIRED = '.*_sBM_.*_(mBR5|mPO5|mLO5|mMH0|mLH0|mHO0|mWA5|mKR5|mJS0|mJB0)_(ch01|ch02)'\n\nMOTION_PRED_ID_VAL = '.*_ch01'\nMOTION_PRED_ID_TEST = '.*_ch02'\n\n\ndef get_testval_music_id(video_name):\n \"\"\"Get the test / val music name for a specific video name.\"\"\"\n music_id = video_name.split('_')[-2]\n if 'mBR' in music_id:\n return 'mBR0'\n elif 'mPO' in music_id:\n return 'mPO1'\n elif 'mLO' in music_id:\n return 'mLO2'\n elif 'mMH' in music_id:\n return 'mMH3'\n elif 'mLH' in music_id:\n return 'mLH4'\n elif 'mHO' in music_id:\n return 'mHO5'\n elif 'mWA' in music_id:\n return 'mWA0'\n elif 'mKR' in music_id:\n return 'mKR2'\n elif 'mJS' in music_id:\n return 'mJS3'\n elif 'mJB' in music_id:\n return 'mJB5'\n else:\n assert False, video_name\n\n\ndef get_split(video_names, task, subset, **kwargs):\n \"\"\"Get the subset split of AIST++ dataset.\"\"\"\n assert task in ['generation', 'prediction']\n assert subset in ['train', 'val', 'test', 'all']\n\n split = {\n 'video_names': [],\n 'music_names': [],\n 'is_paired':\n kwargs['is_paired'] if 'is_paired' in kwargs else None,\n }\n\n if task == 'prediction' and subset == 'val':\n split['video_names'] = [\n video_name for video_name in video_names\n if re.match(MOTION_PRED_ID_VAL, video_name)\n ]\n\n elif task == 'prediction' and subset == 'test':\n split['video_names'] = [\n video_name for video_name in video_names\n if re.match(MOTION_PRED_ID_TEST, video_name)\n ]\n\n elif task == 'prediction' and subset == 'train':\n split['video_names'] = [\n video_name for video_name in video_names\n if (not re.match(MOTION_PRED_ID_VAL, video_name) and\n not re.match(MOTION_PRED_ID_TEST, video_name))]\n\n elif task == 'generation' and (subset == 'val' or subset == 'test'):\n assert split['is_paired'] in [True, False]\n if split['is_paired']:\n split['video_names'] = [\n video_name for video_name in video_names\n if re.match(MOTION_GEN_ID_TESTVAL_PAIRED, video_name)\n ]\n split['music_names'] = [\n video_name.split('_')[-2] for video_name in split['video_names']\n ]\n else:\n split['video_names'] = [\n video_name for video_name in video_names\n if re.match(MOTION_GEN_ID_TESTVAL_UNPAIRED, video_name)\n ]\n split['music_names'] = [\n get_testval_music_id(video_name)\n for video_name in split['video_names']\n ]\n\n elif task == 'generation' and subset == 'train':\n split['video_names'] = [\n video_name for video_name in video_names\n if (not re.match(MOTION_GEN_ID_TESTVAL, video_name) and\n not re.match(MUSIC_ID_TESTVAL, video_name.split('_')[-2]))]\n split['music_names'] = [\n video_name.split('_')[-2] for video_name in split['video_names']\n ]\n\n else:\n raise NotImplementedError\n\n return split\n","sub_path":"tools/aist_preprocess/split_setting.py","file_name":"split_setting.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76302409","text":"#!/usr/bin/env python3\n\nimport rospy\nimport os\nimport tty\nimport sys\nimport termios\nimport _thread\nfrom enum import Enum\nfrom haruto_msgs.msg import Reply\nfrom haruto_msgs.msg import PWM\n\nclass TunerMode(Enum):\n IDLE = 1\n FORWARD = 2\n REVERSE = 3\n FORWARD_WRITE = 4\n REVERSE_WRITE = 5\n\nclass HarutoEncoderTuner(object):\n \"\"\" \n Class for tuning encoder ticks. (The robot is run for 1m in forward and reverse direction to measure ticks elapsed by encoder)\n \"\"\"\n def __init__(self):\n self.pwm_publisher = rospy.Publisher('/diff_pwm', PWM, queue_size=10)\n\n self.tick = {'front_left_tick': 0, 'back_left_tick': 0, 'front_right_tick': 0, 'back_right_tick': 0}\n self.mode = TunerMode.IDLE\n\n rospy.init_node('encoder_tuner', anonymous=True)\n rospy.loginfo('Intialising haruto encoder tuner node')\n\n def process_key_events(self):\n \"\"\"\n Method to listen for keyboard events to start measuring \n Key s for starting encoder measurements in forward mode \n key r for starting encoder measurements in reverse mode\n key b for stopping encoder measurements \n \"\"\"\n orig_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin)\n x = -1\n while x == chr(115) or x == chr(114) or x == chr(98) or x == -1: \n x = sys.stdin.read(1)[0]\n if x == chr(115):\n self.mode = TunerMode.FORWARD\n pwm = PWM()\n pwm.front_left_pwm = 100\n pwm.back_left_pwm = 100\n pwm.front_right_pwm = 100\n pwm.back_right_pwm = 100\n pwm.left_state = 1\n pwm.right_state = 1\n self.pwm_publisher.publish(pwm)\n rospy.loginfo('starting to record in forward mode')\n elif x == chr(114):\n self.mode = TunerMode.REVERSE\n pwm = PWM()\n pwm.front_left_pwm = 100\n pwm.back_left_pwm = 100\n pwm.front_right_pwm = 100\n pwm.back_right_pwm = 100\n pwm.left_state = 2\n pwm.right_state = 2\n self.pwm_publisher.publish(pwm)\n rospy.loginfo('starting to record in reverse mode')\n elif x == chr(98):\n if self.mode == TunerMode.FORWARD:\n self.mode = TunerMode.FORWARD_WRITE\n rospy.loginfo('stopping record in forward mode')\n elif self.mode == TunerMode.REVERSE:\n self.mode = TunerMode.REVERSE_WRITE \n rospy.loginfo('stopping record in reverse mode')\n pwm = PWM()\n pwm.front_left_pwm = 0\n pwm.back_left_pwm = 0\n pwm.front_right_pwm = 0\n pwm.back_right_pwm = 0\n pwm.left_state = 3\n pwm.right_state = 3\n self.pwm_publisher.publish(pwm)\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) \n\n \n def process_encoder_tuner(self, data: Reply):\n \"\"\"\n Callback method to get feedback of ticks from encoders \n\n :params data: Reply\n \"\"\"\n if self.mode == TunerMode.FORWARD or self.mode == TunerMode.REVERSE:\n self.tick['front_left_tick'] = abs(data.tick.front_left_tick)\n self.tick['front_right_tick'] = abs(data.tick.front_right_tick)\n self.tick['back_left_tick'] = abs(data.tick.back_left_tick)\n self.tick['back_right_tick'] = abs(data.tick.back_right_tick)\n\n elif self.mode == TunerMode.FORWARD_WRITE:\n file = open('/home/santosh/Projects/forward.txt', 'w')\n file.write(str(self.tick['front_left_tick']) + ' ' + str(self.tick['back_left_tick']) + ' ' + str(self.tick['front_right_tick']) + ' ' + str(self.tick['back_right_tick']))\n file.close()\n\n rospy.loginfo('writing to forward file')\n self.mode = TunerMode.IDLE\n\n elif self.mode == TunerMode.REVERSE_WRITE:\n file = open('/home/santosh/Projects/reverse.txt', 'w')\n file.write(str(self.tick['front_left_tick']) + ' ' + str(self.tick['back_left_tick']) + ' ' + str(self.tick['front_right_tick']) + ' ' + str(self.tick['back_right_tick']))\n file.close()\n\n rospy.loginfo('writing to reverse file')\n self.mode = TunerMode.IDLE\n \n def start_listening(self):\n \"\"\"\n Method to start listening (node startup) \n \"\"\"\n rospy.Subscriber('/diff_feedback', Reply, self.process_encoder_tuner)\n _thread.start_new_thread(self.process_key_events, ())\n rospy.spin()\n\nif __name__ == '__main__':\n haruto_encoder_tuner = HarutoEncoderTuner()\n haruto_encoder_tuner.start_listening()","sub_path":"scripts/encoder_tuner.py","file_name":"encoder_tuner.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"502130409","text":"# CTI-110 \r\n# P3HW1 - Software Sales\r\n# Jessica Thompson\r\n# 02/23/2018\r\n#\r\n\r\nnumberofpackages = int(input(\"Enter the number of packages purchased: \"))\r\n\r\npackageprice = 99\r\n\r\ndef main():\r\n if numberofpackages < 10:\r\n discount = 0\r\n elif numberofpackages < 20:\r\n discount = .10\r\n elif numberofpackages < 50:\r\n discount = .20\r\n elif numberofpackages < 100:\r\n discount = .30\r\n elif numberofpackages >= 100:\r\n discount = .40\r\n\r\n subtotal = numberofpackages * packageprice\r\n discountamount = discount * subtotal\r\n total = subtotal - discountamount\r\n\r\n print(\"Amount of discount: $\", format(discountamount, \",.2f\"))\r\n print(\"Total: $\", format(total, \",.2f\"))\r\n\r\nmain()\r\n","sub_path":"P3HW2_SoftwareSales_ThompsonJessica.py","file_name":"P3HW2_SoftwareSales_ThompsonJessica.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"548021321","text":"import os\nimport GCcount\nimport sys\nsys.path.append('/usr/local/lib/python2.7/site-packages/')\nimport RNA\nfwrite = open(\"performance_test_results.csv\", \"a\")\nfread = open(\"performance_test_sequences.txt\", \"r\")\nseq = fread.readline()\nfwrite.write(\"Sequence,SecondaryStructure,Length,Runtime,GCcontent,GCdistance,StructureDistance\\n\")\nwhile len(seq) != 0:\n\tseq = seq.replace(\"\\n\", \"\")\n\tif (seq[0] == \"#\"):\n\t\tseq = fread.readline()\n\t\tcontinue\n\tfwrite.write(seq + \",\")\n\tgc = GCcount.GCcount(seq)\n\tseq = RNA.fold(seq)[0]\n\tfwrite.write(seq + \",\")\n\tfwrite.write(str(len(seq)) + \",\")\n\tfwrite.flush()\n\tos.system(\"python2 MCTS-RNA.py -s \\\"\" + seq + \"\\\" -GC \" + str(gc) + \" -d 0.02 -pk 0\")\n\tseq = fread.readline()\n\nfread.close()\nfwrite.close()","sub_path":"performance_tests.py","file_name":"performance_tests.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"304330696","text":"from sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport pandas, numpy, string\nfrom keras.preprocessing import text, sequence\nfrom keras import layers, models, optimizers\n\ndata = open('data/corpus').read()\nlabels, texts = [], []\nfor i, line in enumerate(data.split(\"\\n\")):\n content = line.split()\n labels.append(content[0])\n texts.append(content[1])\n\n\n#创建一个dataframe,列名为text和label\ntrainDF = pandas.DataFrame()\ntrainDF['text'] = texts\ntrainDF['label'] = labels\n#将数据集分为训练集和验证集\ntrain_x, valid_x, train_y, valid_y = model_selection.train_test_split(trainDF['text'], trainDF['label'])\n#加载预先训练好的词嵌入向量\nembeddings_index = {}\n#下载网址:https://fasttext.cc/docs/en/english-vectors.html\nfor i, line in enumerate(open('data/wiki-news-300d-1M.vec')):\n values = line.split()\n embeddings_index[values[0]] = numpy.asarray(values[1:], dtype='float32')\n\n\n #创建一个分词器\n token = text.Tokenizer()\n token.fit_on_texts(trainDF['text'])\n word_index = token.word_index\n\n\n #将文本转换为分词序列,并填充它们保证得到相同长度的向量\n train_seq_x = sequence.pad_sequences(token.texts_to_sequences(train_x), maxlen=70)\n valid_seq_x = sequence.pad_sequences(token.texts_to_sequences(valid_x), maxlen=70)\n\n\n #创建分词嵌入映射\n embedding_matrix = numpy.zeros((len(word_index) + 1, 300))\n for word, i in word_index.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\ndef train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):\n\n # fit the training dataset on the classifier\n classifier.fit(feature_vector_train, label)\n\n # predict the labels on validation dataset\n predictions = classifier.predict(feature_vector_valid)\n\n if is_neural_net:\n\n predictions = predictions.argmax(axis=-1)\n\n else:\n\n return metrics.accuracy_score(predictions, valid_y)\n# label编码为目标变量\nencoder = preprocessing.LabelEncoder()\ntrain_y = encoder.fit_transform(train_y)\nvalid_y = encoder.fit_transform(valid_y)\nprint(train_y)\n\ndef create_rnn_lstm():\n # Add an Input Layer\n input_layer = layers.Input((70, ))\n\n # Add the word embedding Layer\n embedding_layer = layers.Embedding(len(word_index) + 1, 300, weights=[embedding_matrix], trainable=False)(input_layer)\n embedding_layer = layers.SpatialDropout1D(0.3)(embedding_layer)\n\n # Add the LSTM Layer\n lstm_layer = layers.LSTM(100)(embedding_layer)\n\n # Add the output Layers\n output_layer1 = layers.Dense(50, activation=\"relu\")(lstm_layer)\n output_layer1 = layers.Dropout(0.25)(output_layer1)\n output_layer2 = layers.Dense(1, activation=\"sigmoid\")(output_layer1)\n\n # Compile the model\n model = models.Model(inputs=input_layer, outputs=output_layer2)\n model.compile(optimizer=optimizers.Adam(), loss='binary_crossentropy')\n return model\n\nclassifier = create_rnn_lstm()\naccuracy = train_model(classifier, train_seq_x, train_y, valid_seq_x, is_neural_net=True)\nprint (\"RNN-LSTM, Word Embeddings\", accuracy)","sub_path":"words_handle_rnn_LSTM.py","file_name":"words_handle_rnn_LSTM.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"50332505","text":"from urllib import request\nimport json\n# 在这里填写文件下载路径,\nfilefull = \"E:\\\\test\\\\1\\\\\"\nheader = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (\" +\n \"KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n}\nsource = \"https://www.bilibili.com/index/index-icon.json\"\nreq = request.Request(url=source, headers=header)\ndata = request.urlopen(req).read().decode()\ndata = json.loads(data)\ndata = data[\"fix\"]\ntry:\n with open(\"topright.txt\") as tmp:\n got = json.load(tmp)\nexcept FileNotFoundError:\n print(\"first time to run\")\n got = {}\nnum = 0\nfilefull += \"{}.gif\"\nfor i in data:\n if i[\"id\"] in got.keys():\n continue\n req = request.Request(headers=header, url=\"http:\" + i[\"icon\"])\n print(i[\"title\"])\n with open(filefull.format(i[\"title\"] + i[\"id\"]), \"wb\") as tmp:\n tmp.write(request.urlopen(req).read())\n got[i[\"id\"]] = i[\"title\"]\nwith open(\"topright.txt\", \"w\") as tmp:\n json.dump(got, tmp)\nprint(\"finished\")\n","sub_path":"topright2.py","file_name":"topright2.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"546670107","text":"from copy import deepcopy\n\nimport torch\n\nfrom models.base_model import ARFlow\nfrom utils.flow_utils import evaluate_flow\n\n\nclass SintelRawFlow(ARFlow):\n\n def __init__(self, cfg):\n super().__init__(cfg)\n\n def training_step(self, batch, batch_idx):\n # read data to device\n img1, img2 = batch['img1'], batch['img2']\n img_pair = torch.cat([img1, img2], 1)\n # compute output\n res_dict = self.model(img_pair, with_bk=True)\n flows_12, flows_21 = res_dict['flows_fw'], res_dict['flows_bw']\n flows = [torch.cat([flo12, flo21], 1) for flo12, flo21 in\n zip(flows_12, flows_21)]\n loss, l_ph, l_sm, flow_mean = self.loss_func(flows, img_pair)\n scaled_loss = 1024. * loss\n log_dict = {\n 'loss': loss.item(),\n 'l_ph': l_ph.item(),\n 'l_sm': l_sm.item(),\n 'flow_mean': flow_mean.item(),\n }\n return {\n 'loss': scaled_loss,\n 'log': log_dict,\n }\n\n def on_after_backward(self):\n for param in [p for p in self.model.parameters() if p.requires_grad]:\n param.grad.data.mul_(1. / 1024)\n\n def validation_step(self, batch, batch_idx, dataset_idx):\n img1, img2 = batch['img1'], batch['img2']\n img_pair = torch.cat([img1, img2], 1)\n gt_flows = batch['target']['flow'].cpu().numpy().transpose([0, 2, 3, 1])\n\n # compute output\n flows = self.model(img_pair)['flows_fw']\n pred_flows = flows[0].detach().cpu().numpy().transpose([0, 2, 3, 1])\n es = evaluate_flow(gt_flows, pred_flows)\n epe = torch.tensor(es).mean()\n return {'val_epe': epe}\n\n def validation_epoch_end(self, outputs):\n log_dict = {}\n for dataset_idx, out in enumerate(outputs):\n epe = torch.stack([output['val_epe'] for output in out]).mean()\n log_dict.update({f'val_epe_{dataset_idx}': epe})\n return {\n 'val_loss': log_dict['val_epe_0'],\n 'log': log_dict\n }\n","sub_path":"models/sintel_raw.py","file_name":"sintel_raw.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345075935","text":"import requests\nimport time\nimport json\nimport base64,re,os\n#1.登陆教务网\nclass random_num():#获取验证码\n\tdef tryagain(self,name):\n\t\teval(\"self.\"+name + '()')\n\tdef __init__(self):\n\t# client_id 为官网获取的AK, client_secret 为官网获取的SK\n\t\ttry:\n\t\t\tself.session = requests.session()\n\t\t\tself.session.get(\"http://jwc.swjtu.edu.cn/service/login.html\")\n\t\t\thost = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Wd8p7GGkRpb6KXB4Qu5fByvj&client_secret=tQAxfDVDoW9OzreQY2VsR17TP9pTaDUy'\n\t\t\tresponse = requests.get(host)\n\t\t\tif response:\n\t\t\t\tself.access_token = response.json()['access_token']\n\t\texcept:\n\t\t\tself.tryagain('init')\n\tdef get_str(self):\n\t\tr = self.session.get(\"http://jwc.swjtu.edu.cn/vatuu/GetRandomNumberToJPEG?test=\"+str(int(time.time())))\n\t\timg = base64.b64encode(r.content)\n\t\tparams = {\"image\":img}\n\t\trequest_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n\t\trequest_url = request_url + \"?access_token=\" + self.access_token\n\t\theaders = {'content-type': 'application/x-www-form-urlencoded'}\n\t\tresponse = requests.post(request_url, data=params, headers=headers)\n\t\tif response:\n\t\t\t#print(response.json())\n\t\t\ttry:\n\t\t\t\tresult = response.json()['words_result'][0]\n\t\t\t\t#print('1',result)\n\t\t\t\tself.result = result['words'].strip()\n\t\t\t\tif len(self.result) != 4:\n\t\t\t\t\t#print(self.result)\n\t\t\t\t\traise Exception(\"Invalid\")\n\t\t\texcept:\n\t\t\t\tself.tryagain('get_str')\n\n\nclass login():#柔和验证码获取\n\tdef tryagain(self,name):\n\t\tprint('重试'+name)\n\t\teval(\"self.\"+name + '()')\n\tdef get_str(self):\n\t\tr = self.session.get(\"http://jwc.swjtu.edu.cn/vatuu/GetRandomNumberToJPEG?test=\"+str(int(time.time())))\n\t\timg = base64.b64encode(r.content)\n\t\tparams = {\"image\":img}\n\t\trequest_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic\"#accurate_basic\"\n\t\trequest_url = request_url + \"?access_token=\" + self.access_token\n\t\theaders = {'content-type': 'application/x-www-form-urlencoded'}\n\t\tresponse = requests.post(request_url, data=params, headers=headers)\n\t\tif response:\n\t\t\t#print(response.json())\n\t\t\ttry:\n\t\t\t\tresult = response.json()['words_result'][0]\n\t\t\t\t#print('1',result)\n\t\t\t\tself.yzm = result['words'].strip()\n\t\t\t\tif len(self.yzm) != 4:\n\t\t\t\t\t#print(self.yzm)\n\t\t\t\t\traise Exception(\"Invalid\")\n\t\t\texcept:\n\t\t\t\t#print(response.text)\n\t\t\t\tself.tryagain('get_str')\n\t\t\t\treturn\n\tdef __init__(self,username=\"\",password=\"\"):\n\t\t#获取用户信息\n\t\tif(username and password):\n\t\t\tself.username = username\n\t\t\tself.password = password\n\t\telse:\n\t\t\tprint('输入错误,无用户名')\n\t\t\texit()\n\t\tprint(\"正在获取验证码......\")\n\t\ttry:\n\t\t\tself.session = requests.session()\n\t\t\tself.session.get(\"http://jwc.swjtu.edu.cn/service/login.html\")\n\t\t\thost = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Wd8p7GGkRpb6KXB4Qu5fByvj&client_secret=tQAxfDVDoW9OzreQY2VsR17TP9pTaDUy'\n\t\t\tresponse = requests.get(host)\n\t\t\tif response:\n\t\t\t\tself.access_token = response.json()['access_token']\n\t\texcept Exception:\n\t\t\tself.tryagain('__init__')\n\n\t\tself.get_str()#获取验证码\n\t\tprint('验证码解析成功:',self.yzm)\n\t\t#模拟登陆\n\t\t#第一步POST发送\n\t\tsendmsg = {\n\t\t 'username' : self.username,\n\t\t 'password' : self.password,\n\t\t 'url' : 'http://jwc.swjtu.edu.cn/vatuu/UserExitAction&returnUrl',\n\t\t 'area' : '',\n\t\t 'ranstring' : self.yzm,\n\t\t }\n\t\tlogin_header = {\n\t\t 'Referer' : 'http://jwc.swjtu.edu.cn/service/login.html',\n\t\t 'Origin' : 'http://jwc.swjtu.edu.cn',\n\t\t 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',\n\t\t 'DNT' : '1',\n\t\t 'Accept' : 'application/json, text/javascript, */*; q=0.01',\n\t\t 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t 'X-Requested-With' : 'XMLHttpRequest',\n\t\t}\n\t\tr = self.session.post(\"http://jwc.swjtu.edu.cn/vatuu/UserLoginAction\", data=sendmsg ,headers=login_header)\n\t\tloginMsg = json.loads(r.text)['loginMsg']\n\t\t#print(loginMsg)\n\t\tif '不正确' in loginMsg:\n\t\t\tself.__init__(self.username,self.password)\n\t\t\treturn\n\n\t\t#第二步确认登陆\n\t\tsendmsg = {\n\t\t 'url' : 'http://jwc.swjtu.edu.cn/vatuu/UserExitAction&returnUrl',\n\t\t 'returnUrl' : '',\n\t\t 'loginMsg' : loginMsg\n\t\t}\n\t\tlogin_header = {\n\t\t 'Referer' : 'http://jwc.swjtu.edu.cn/vatuu/StudentScoreInfoAction?setAction=studentMarkUseProgram',\n\t\t 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',\n\t\t 'DNT' : '1',\n\t\t 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n\t\t 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t 'Upgrade-Insecure-Requests' : '1',\n\t\t 'Accept-Encoding' : 'deflate',\n\t\t 'Accept-Language' : 'zh-CN,zh;q=0.9'\n\t\t}\n\t\tr = self.session.post(\"http://jwc.swjtu.edu.cn/vatuu/UserLoadingAction\", data=sendmsg ,headers=login_header)\n\t\tprint('登陆成功')\n\t\t#已经成功登陆","sub_path":"swjtu_jw_login.py","file_name":"swjtu_jw_login.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"467066952","text":"from presidio.builders.model.aggr_model_operator_builder import AggrModelOperatorBuilder\nfrom presidio.builders.model.raw_model_operator_builder import RawModelOperatorBuilder\nfrom presidio.builders.presidio_dag_builder import PresidioDagBuilder\nfrom presidio.operators.model.smart_model_accumulate_operator import SmartModelAccumulateOperator\nfrom presidio.utils.services.fixed_duration_strategy import FIX_DURATION_STRATEGY_DAILY\n\n\nclass SmartModelAccumulateOperatorBuilder(PresidioDagBuilder):\n \"\"\"\n The \"SmartModelAccumulateOperatorBuilder\" responsible for accumulating the smart events.\n returns smart_model_accumulate_operator according of the given smart_conf_name\n \"\"\"\n\n accumulate_interval_conf_key = \"components.ade.models.smart_records.accumulate_interval_in_days\"\n accumulate_interval_default_value = 1\n\n @staticmethod\n def get_accumulate_interval(config_reader):\n return config_reader.read_daily_timedelta(\n SmartModelAccumulateOperatorBuilder.accumulate_interval_conf_key,\n SmartModelAccumulateOperatorBuilder.accumulate_interval_default_value)\n\n @staticmethod\n def get_min_gap_from_dag_start_date_to_start_accumulating(conf_reader):\n raw_model_min_gap_from_dag_start_date_to_start_modeling = RawModelOperatorBuilder.get_min_gap_from_dag_start_date_to_start_raw_modeling(\n conf_reader)\n aggr_model_min_gap_from_dag_start_date_to_start_modeling = AggrModelOperatorBuilder.get_min_gap_from_dag_start_date_to_start_aggr_modeling(\n conf_reader)\n return max(raw_model_min_gap_from_dag_start_date_to_start_modeling,\n aggr_model_min_gap_from_dag_start_date_to_start_modeling)\n\n def build(self, dag):\n \"\"\"\n Build smart_model_accumulate_operator.\n\n :param dag: The smart_model DAG to populate\n :type dag: airflow.models.DAG\n :return: smart_model_accumulate_operator\n :rtype: presidio.operators.fixed_duration_jar_operator.FixedDurationJarOperator\n \"\"\"\n\n smart_model_accumulate_operator = SmartModelAccumulateOperator(\n fixed_duration_strategy=FIX_DURATION_STRATEGY_DAILY,\n command=PresidioDagBuilder.presidio_command,\n smart_events_conf=dag.default_args.get(\"smart_conf_name\"),\n dag=dag\n )\n\n return smart_model_accumulate_operator\n","sub_path":"presidio-core/presidio-workflows/presidio/builders/smart_model/smart_model_accumulate_operator_builder.py","file_name":"smart_model_accumulate_operator_builder.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"532545413","text":"'''\nCreated on 5. nov. 2014\n\n@author: luka.skrinjar\n'''\nfrom pprint import pprint\n\n\nclass Test_object(object):\n def __init__(self, a):\n self.a = a\n \n self.b = [self.a, 1, 2, 3]\n\n def update_a(self, a_new):\n self.a = a_new\n \n\nobj = Test_object(a = 99)\n\npprint(vars(obj))\nobj.update_a(a_new = 101)\npprint(vars(obj))\n","sub_path":"src/V46/sandbox/object_attrib_update.py","file_name":"object_attrib_update.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"520219168","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLeast cost transmission line path tests\n\"\"\"\nfrom click.testing import CliRunner\nimport json\nimport numpy as np\nimport os\nimport pytest\nimport tempfile\nimport traceback\n\nfrom rex.utilities.loggers import LOGGERS\n\nfrom reV.handlers.exclusions import ExclusionLayers\n\nfrom reVX import TESTDATADIR\nfrom reVX.cli import main as cli\nfrom reVX.least_cost_xmission.cost_creator_cli import main\nfrom reVX.least_cost_xmission.cost_creator import XmissionCostCreator, \\\n XmissionConfig\nfrom reVX.least_cost_xmission.config import TEST_DEFAULT_MULTS\n\nBASELINE_H5 = os.path.join(TESTDATADIR, 'xmission', 'xmission_layers.h5')\nEXCL_H5 = os.path.join(TESTDATADIR, 'ri_exclusions', 'ri_exclusions.h5')\nISO_REGIONS_F = os.path.join(TESTDATADIR, 'xmission', 'ri_regions.tif')\nXC = XmissionConfig()\n\n\ndef build_test_costs():\n \"\"\"\n Build test costs\n \"\"\"\n extra_layers = {'layers':\n {'transmission_barrier':\n os.path.join(TESTDATADIR, 'xmission',\n 'ri_trans_barriers.tif')}}\n XmissionCostCreator.run(BASELINE_H5, ISO_REGIONS_F, excl_h5=EXCL_H5,\n slope_layer='ri_srtm_slope', nlcd_layer='ri_nlcd',\n tiff_dir=None, default_mults=TEST_DEFAULT_MULTS,\n extra_layers=extra_layers)\n\n\n@pytest.fixture(scope=\"module\")\ndef runner():\n \"\"\"\n cli runner\n \"\"\"\n return CliRunner()\n\n\ndef test_land_use_multiplier():\n \"\"\" Test land use multiplier creation \"\"\"\n lu_mults = {'forest': 1.63, 'wetland': 1.5}\n arr = np.array([[[0, 95, 90], [42, 41, 15]]])\n xcc = XmissionCostCreator(BASELINE_H5, ISO_REGIONS_F)\n out = xcc._compute_land_use_mult(arr, lu_mults,\n land_use_classes=XC['land_use_classes'])\n expected = np.array([[[1.0, 1.5, 1.5], [1.63, 1.63, 1.0]]],\n dtype=np.float32)\n assert np.array_equal(out, expected)\n\n\ndef test_slope_multiplier():\n \"\"\" Test slope multiplier creation \"\"\"\n arr = np.array([[[0, 1, 10], [20, 1, 6]]])\n config = {'hill_mult': 1.2, 'mtn_mult': 1.5,\n 'hill_slope': 2, 'mtn_slope': 8}\n xcc = XmissionCostCreator(EXCL_H5, ISO_REGIONS_F)\n out = xcc._compute_slope_mult(arr, config)\n expected = np.array([[[1.0, 1.0, 1.5], [1.5, 1.0, 1.2]]],\n dtype=np.float32)\n assert np.array_equal(out, expected)\n\n\ndef test_full_costs_workflow():\n \"\"\"\n Test full cost calculator workflow for RI against known costs\n \"\"\"\n xcc = XmissionCostCreator(BASELINE_H5, ISO_REGIONS_F,\n iso_lookup=XC['iso_lookup'])\n\n mults_arr = xcc.compute_multipliers(\n XC['iso_multipliers'], excl_h5=EXCL_H5, slope_layer='ri_srtm_slope',\n nlcd_layer='ri_nlcd', land_use_classes=XC['land_use_classes'],\n default_mults=TEST_DEFAULT_MULTS)\n\n for _, capacity in XC['power_classes'].items():\n with ExclusionLayers(BASELINE_H5) as el:\n known_costs = el['tie_line_costs_{}MW'.format(capacity)]\n\n blc_arr = xcc.compute_base_line_costs(capacity,\n XC['base_line_costs'])\n costs_arr = blc_arr * mults_arr\n assert np.isclose(known_costs, costs_arr).all()\n\n\ndef test_cli(runner):\n \"\"\"\n Test CostCreator CLI\n \"\"\"\n\n with tempfile.TemporaryDirectory() as td:\n layers = {'layers':\n {'ri_srtm_slope': os.path.join(TESTDATADIR, 'ri_exclusions',\n 'ri_srtm_slope.tif'),\n 'ri_nlcd': os.path.join(TESTDATADIR, 'ri_exclusions',\n 'ri_nlcd.tif')}}\n layers_path = os.path.join(td, 'layers.json')\n with open(layers_path, 'w') as f:\n json.dump(layers, f)\n\n excl_h5 = os.path.join(td, \"test.h5\")\n result = runner.invoke(cli, ['exclusions',\n '-h5', excl_h5,\n 'layers-to-h5',\n '-l', layers_path])\n msg = ('Failed with error {}'\n .format(traceback.print_exception(*result.exc_info)))\n assert result.exit_code == 0, msg\n\n mults_path = os.path.join(td, 'default_mults.json')\n with open(mults_path, 'w') as f:\n json.dump(TEST_DEFAULT_MULTS, f)\n\n extra_layers = {'layers':\n {'transmission_barrier':\n os.path.join(TESTDATADIR, 'xmission',\n 'ri_trans_barriers.tif')}}\n config = {\n \"log_directory\": td,\n \"execution_control\": {\n \"option\": \"local\",\n },\n \"h5_fpath\": excl_h5,\n \"iso_regions\": ISO_REGIONS_F,\n \"slope_layer\": 'ri_srtm_slope',\n \"nlcd_layer\": 'ri_nlcd',\n \"default_mults\": mults_path,\n \"extra_layers\": extra_layers\n }\n config_path = os.path.join(td, 'config.json')\n with open(config_path, 'w') as f:\n json.dump(config, f)\n\n result = runner.invoke(main, ['from-config',\n '-c', config_path])\n msg = ('Failed with error {}'\n .format(traceback.print_exception(*result.exc_info)))\n assert result.exit_code == 0, msg\n\n with ExclusionLayers(BASELINE_H5) as f_truth:\n with ExclusionLayers(excl_h5) as f_test:\n for layer in f_truth.layers:\n test = f_test[layer]\n truth = f_truth[layer]\n\n assert np.allclose(truth, test)\n\n LOGGERS.clear()\n\n\ndef execute_pytest(capture='all', flags='-rapP'):\n \"\"\"Execute module as pytest with detailed summary report.\n\n Parameters\n ----------\n capture : str\n Log or stdout/stderr capture option. ex: log (only logger),\n all (includes stdout/stderr)\n flags : str\n Which tests to show logs and results for.\n \"\"\"\n\n fname = os.path.basename(__file__)\n pytest.main(['-q', '--show-capture={}'.format(capture), fname, flags])\n\n\nif __name__ == '__main__':\n execute_pytest()\n","sub_path":"tests/test_xmission_cost_creator.py","file_name":"test_xmission_cost_creator.py","file_ext":"py","file_size_in_byte":6203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"99370165","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nplt.rcParams[\"figure.figsize\"] = [12, 12]\n\n\ndef create_grid(data, drone_altitude, safety_distance):\n \"\"\"\n Returns a grid representation of a 2D configuration space \n based on given obstacle data, drone altitude and safety distance\n arguments.\n \"\"\"\n\n # minimum and maximum north coordinates\n north_min = np.floor(np.amin(data[:, 0] - data[:, 3]))\n north_max = np.ceil(np.amax(data[:, 0] + data[:, 3]))\n\n # minimum and maximum east coordinates\n east_min = np.floor(np.amin(data[:, 1] - data[:, 4]))\n east_max = np.ceil(np.amax(data[:, 1] + data[:, 4]))\n\n # given the minimum and maximum coordinates we can \n # calculate the size of the grid\n north_size = int(np.ceil((north_max - north_min)))\n east_size = int(np.ceil((east_max - east_min)))\n \n grid = np.zeros((north_size, east_size))\n for i in range(data.shape[0]):\n north, east, alt, d_north, d_east, d_alt = data[i, :]\n if alt + d_alt + safety_distance > drone_altitude:\n obstacle = [\n int(north - d_north - safety_distance - north_min),\n int(north + d_north + safety_distance - north_min),\n int(east - d_east - safety_distance - east_min),\n int(east + d_east + safety_distance - east_min)\n ]\n grid[obstacle[0]:obstacle[1], obstacle[2]:obstacle[3]] = 1 \n\n return grid\n\n\nif __name__ == '__main__':\n\n filename = 'colliders.csv'\n data = np.loadtxt(filename, delimiter=',', dtype=\"Float64\", skiprows=2)\n print(data)\n\n # static drone altitude (metres)\n drone_altitude = 6\n # minimum distance required to stay away from an obstacle (metres)\n safe_distance = 3\n\n grid = create_grid(data, drone_altitude, safe_distance)\n plt.imshow(grid, origin=\"lower\")\n plt.xlabel('EAST')\n plt.ylabel('NORTH')\n plt.show()\n","sub_path":"planning/drone/configurable_space.py","file_name":"configurable_space.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"206434739","text":"import sys\nimport os\nimport shlex\nfrom time import time\nfrom subprocess import Popen, call\n\nfrom py3status.formatter import Formatter\n\n\nPY3_CACHE_FOREVER = -1\nPY3_LOG_ERROR = 'error'\nPY3_LOG_INFO = 'info'\nPY3_LOG_WARNING = 'warning'\n\n\nclass Py3:\n \"\"\"\n Helper object that gets injected as self.py3 into Py3status\n modules that have not got that attribute set already.\n\n This allows functionality like:\n User notifications\n Forcing module to update (even other modules)\n Triggering events for modules\n\n Py3 is also used for testing in which case it does not get a module when\n being created. All methods should work in this situation.\n \"\"\"\n\n CACHE_FOREVER = PY3_CACHE_FOREVER\n\n LOG_ERROR = PY3_LOG_ERROR\n LOG_INFO = PY3_LOG_INFO\n LOG_WARNING = PY3_LOG_WARNING\n\n # All Py3 Instances can share a formatter\n _formatter = Formatter()\n\n def __init__(self, module=None, i3s_config=None, py3status=None):\n self._audio = None\n self._colors = {}\n self._i3s_config = i3s_config or {}\n self._module = module\n self._is_python_2 = sys.version_info < (3, 0)\n\n if py3status:\n self._py3status_module = py3status\n\n # we are running through the whole stack.\n # If testing then module is None.\n if module:\n self._output_modules = module._py3_wrapper.output_modules\n if not i3s_config:\n config = self._module.i3status_thread.config['general']\n self._i3s_config = config\n self._py3status_module = module.module_class\n\n def __getattr__(self, name):\n \"\"\"\n Py3 can provide COLOR constants\n eg COLOR_GOOD, COLOR_BAD, COLOR_DEGRADED\n but also any constant COLOR_XXX we find this color in the config\n if it exists\n \"\"\"\n if not name.startswith('COLOR_'):\n raise AttributeError\n name = name.lower()\n if name not in self._colors:\n if self._module:\n color_fn = self._module._py3_wrapper.get_config_attribute\n color = color_fn(self._module.module_full_name, name)\n else:\n color = self._i3s_config.get(name)\n self._colors[name] = color\n return self._colors[name]\n\n def _get_module_info(self, module_name):\n \"\"\"\n THIS IS PRIVATE AND UNSUPPORTED.\n Get info for named module. Info comes back as a dict containing.\n\n 'module': the instance of the module,\n 'position': list of places in i3bar, usually only one item\n 'type': module type py3status/i3status\n \"\"\"\n if self._module:\n return self._output_modules.get(module_name)\n\n def i3s_config(self):\n \"\"\"\n returns the i3s_config dict.\n \"\"\"\n return self._i3s_config\n\n def is_python_2(self):\n \"\"\"\n True if the version of python being used is 2.x\n Can be helpful for fixing python 2 compatability issues\n \"\"\"\n return self._is_python_2\n\n def is_my_event(self, event):\n \"\"\"\n Checks if an event triggered belongs to the module recieving it. This\n is mainly for containers who will also recieve events from any children\n they have.\n\n Returns True if the event name and instance match that of the module\n checking.\n \"\"\"\n if not self._module:\n return False\n\n return (\n event.get('name') == self._module.module_name and\n event.get('instance') == self._module.module_inst\n )\n\n def log(self, message, level=LOG_INFO):\n \"\"\"\n Log the message.\n The level must be one of LOG_ERROR, LOG_INFO or LOG_WARNING\n \"\"\"\n assert level in [\n self.LOG_ERROR, self.LOG_INFO, self.LOG_WARNING\n ], 'level must be LOG_ERROR, LOG_INFO or LOG_WARNING'\n\n if self._module:\n message = 'Module `{}`: {}'.format(\n self._module.module_full_name, message)\n self._module._py3_wrapper.log(message, level)\n\n def update(self, module_name=None):\n \"\"\"\n Update a module. If module_name is supplied the module of that\n name is updated. Otherwise the module calling is updated.\n \"\"\"\n if not module_name and self._module:\n return self._module.force_update()\n else:\n module_info = self._get_module_info(module_name)\n if module_info:\n module_info['module'].force_update()\n\n def get_output(self, module_name):\n \"\"\"\n Return the output of the named module. This will be a list.\n \"\"\"\n output = []\n module_info = self._get_module_info(module_name)\n if module_info:\n output = module_info['module'].get_latest()\n return output\n\n def trigger_event(self, module_name, event):\n \"\"\"\n Trigger an event on a named module.\n \"\"\"\n if module_name and self._module:\n self._module._py3_wrapper.events_thread.process_event(\n module_name, event)\n\n def prevent_refresh(self):\n \"\"\"\n Calling this function during the on_click() method of a module will\n request that the module is not refreshed after the event. By default\n the module is updated after the on_click event has been processed.\n \"\"\"\n if self._module:\n self._module.prevent_refresh = True\n\n def notify_user(self, msg, level='info', rate_limit=5):\n \"\"\"\n Send a notification to the user.\n level must be 'info', 'error' or 'warning'.\n rate_limit is the time period in seconds during which this message\n should not be repeated.\n \"\"\"\n if self._module:\n # force unicode for python2 str\n if self._is_python_2 and isinstance(msg, str):\n msg = msg.decode('utf-8')\n module_name = self._module.module_full_name\n self._module._py3_wrapper.notify_user(\n msg, level=level, rate_limit=rate_limit, module_name=module_name)\n\n def register_function(self, function_name, function):\n \"\"\"\n Register a function for the module.\n\n The following functions can be registered\n\n > __content_function()__\n >\n > Called to discover what modules a container is displaying. This is\n > used to determine when updates need passing on to the container and\n > also when modules can be put to sleep.\n >\n > the function must return a set of module names that are being\n > displayed.\n >\n > Note: This function should only be used by containers.\n >\n > __urgent_function(module_names)__\n >\n > This function will be called when one of the contents of a container\n > has changed from a non-urgent to an urgent state. It is used by the\n > group module to switch to displaying the urgent module.\n >\n > `module_names` is a list of modules that have become urgent\n >\n > Note: This function should only be used by containers.\n \"\"\"\n if self._module:\n my_info = self._get_module_info(self._module.module_full_name)\n my_info[function_name] = function\n\n def time_in(self, seconds=None, sync_to=None, offset=0):\n \"\"\"\n Returns the time a given number of seconds into the future. Helpful\n for creating the `cached_until` value for the module output.\n\n Note: form version 3.1 modules no longer need to explicitly set a\n `cached_until` in their response unless they wish to directly control\n it.\n\n seconds specifies the number of seconds that should occure before the\n update is required.\n\n sync_to causes the update to be syncronised to a time period. 1 would\n cause the update on the second, 60 to the nearest minute. By defalt we\n syncronise to the nearest second. 0 will disable this feature.\n\n offset is used to alter the base time used. A timer that started at a\n certain time could set that as the offset and any syncronisation would\n then be relative to that time.\n \"\"\"\n\n if seconds is None:\n # If we have a sync_to then seconds can be 0\n if sync_to and sync_to > 0:\n seconds = 0\n else:\n try:\n # use py3status modules cache_timeout\n seconds = self._py3status_module.cache_timeout\n except AttributeError:\n # use default cache_timeout\n seconds = self._module.config['cache_timeout']\n\n # Unless explicitly set we sync to the nearest second\n # Unless the requested update is in less than a second\n if sync_to is None:\n if seconds and seconds < 1:\n sync_to = 0\n else:\n sync_to = 1\n\n requested = time() + seconds - offset\n\n # if sync_to then we find the sync time for the requested time\n if sync_to:\n requested = (requested + sync_to) - (requested % sync_to)\n\n return requested + offset\n\n def safe_format(self, format_string, param_dict=None):\n \"\"\"\n Parser for advanced formating.\n\n Unknown placeholders will be shown in the output eg `{foo}`\n\n Square brackets `[]` can be used. The content of them will be removed\n from the output if there is no valid placeholder contained within.\n They can also be nested.\n\n A pipe (vertical bar) `|` can be used to divide sections the first\n valid section only will be shown in the output.\n\n A backslash `\\` can be used to escape a character eg `\\[` will show `[`\n in the output. Note: `\\?` is reserved for future use and is removed.\n\n `{}` will be converted, or removed if it is None or empty.\n Formating can also be applied to the placeholder eg\n `{number:03.2f}`.\n\n example format_string:\n \"[[{artist} - ]{title}]|{file}\"\n This will show `artist - title` if artist is present,\n `title` if title but no artist,\n and `file` if file is present but not artist or title.\n\n param_dict is a dictionary of palceholders that will be substituted.\n If a placeholder is not in the dictionary then if the py3status module\n has an attribute with the same name then it will be used.\n \"\"\"\n try:\n return self._formatter.format(\n format_string,\n self._py3status_module,\n param_dict\n )\n except Exception:\n return 'invalid format'\n\n def build_composite(self, format_string, param_dict=None, composites=None):\n \"\"\"\n Build a composite output using a format string.\n\n Takes a format_string and treats it the same way as `safe_format` but\n also takes a composites dict where each key/value is the name of the\n placeholder and either an output eg `{'full_text': 'something'}` or a\n list of outputs.\n \"\"\"\n try:\n return self._formatter.format(\n format_string,\n self._py3status_module,\n param_dict,\n composites,\n )\n except Exception:\n return [{'full_text': 'invalid format'}]\n\n def check_commands(self, cmd_list):\n \"\"\"\n Checks to see if commands in list are available using `which`.\n Returns the first available command.\n \"\"\"\n devnull = open(os.devnull, 'w')\n for cmd in cmd_list:\n c = shlex.split('which {}'.format(cmd))\n if call(c, stdout=devnull, stderr=devnull) == 0:\n return cmd\n\n def play_sound(self, sound_file):\n \"\"\"\n Plays sound_file if possible.\n \"\"\"\n self.stop_sound()\n cmd = self.check_commands(['paplay', 'play'])\n if cmd:\n sound_file = os.path.expanduser(sound_file)\n c = shlex.split('{} {}'.format(cmd, sound_file))\n self._audio = Popen(c)\n\n def stop_sound(self):\n \"\"\"\n Stops any currently playing sounds for this module.\n \"\"\"\n if self._audio:\n self._audio.kill()\n self._audio = None\n","sub_path":"py3status/py3.py","file_name":"py3.py","file_ext":"py","file_size_in_byte":12376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"140466904","text":"\n\n#calss header\nclass _BOURGEOISIE():\n\tdef __init__(self,): \n\t\tself.name = \"BOURGEOISIE\"\n\t\tself.definitions = [u'(in Marxism) the part of society, including employers and people who run large companies, that has most of the money and takes advantage of ordinary workers: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_bourgeoisie.py","file_name":"_bourgeoisie.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217523124","text":"# Copyright 2019 Catalyst IT Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\nimport falcon\n\nfrom oslo_log import log as logging\n\nfrom zaqar.common import decorators\nfrom zaqar.i18n import _\nfrom zaqar.transport import acl\nfrom zaqar.transport import validation\nfrom zaqar.transport.wsgi import errors as wsgi_errors\nfrom zaqar.transport.wsgi import utils as wsgi_utils\n\nLOG = logging.getLogger(__name__)\n\n\nclass Resource(object):\n\n __slots__ = ('_driver', '_conf',\n '_message_ctrl', '_subscription_ctrl', '_validate')\n\n def __init__(self, driver):\n self._driver = driver\n self._conf = driver._conf\n self._message_ctrl = driver._storage.message_controller\n self._subscription_ctrl = driver._storage.subscription_controller\n self._validate = driver._validate\n\n @decorators.TransportLog(\"Topics item\")\n @acl.enforce(\"topics:purge\")\n def on_post(self, req, resp, project_id, topic_name):\n try:\n if req.content_length:\n document = wsgi_utils.deserialize(req.stream,\n req.content_length)\n self._validate.queue_purging(document)\n else:\n document = {'resource_types': ['messages', 'subscriptions']}\n except validation.ValidationFailed as ex:\n LOG.debug(ex)\n raise wsgi_errors.HTTPBadRequestAPI(str(ex))\n\n try:\n if \"messages\" in document['resource_types']:\n pop_limit = 100\n LOG.debug(\"Purge all messages under topic %s\", topic_name)\n messages = self._message_ctrl.pop(topic_name, pop_limit,\n project=project_id)\n while messages:\n messages = self._message_ctrl.pop(topic_name, pop_limit,\n project=project_id)\n\n if \"subscriptions\" in document['resource_types']:\n LOG.debug(\"Purge all subscriptions under topic %s\", topic_name)\n results = self._subscription_ctrl.list(topic_name,\n project=project_id)\n subscriptions = list(next(results))\n for sub in subscriptions:\n self._subscription_ctrl.delete(topic_name,\n sub['id'],\n project=project_id)\n except ValueError as err:\n raise wsgi_errors.HTTPBadRequestAPI(str(err))\n except Exception:\n description = _(u'Topic could not be purged.')\n LOG.exception(description)\n raise wsgi_errors.HTTPServiceUnavailable(description)\n\n resp.status = falcon.HTTP_204\n","sub_path":"zaqar/transport/wsgi/v2_0/topic_purge.py","file_name":"topic_purge.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"603428916","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def __str__(self):\n return \"TN={}({}, {})\".format(self.val, self.left or \"_\", self.right or \"_\")\n\nclass Solution:\n def buildTree(self, preorder: list, inorder: list) -> TreeNode:\n if not preorder: return None\n return self.dfs(preorder, inorder, 0, 0, len(preorder))[0]\n\n def dfs(self, preorder: list, inorder: list, root: int, ileft: int, iright: int) -> (TreeNode, int):\n if not ileft < iright: return None, 0\n value = preorder[root]\n node = TreeNode(value)\n\n try:\n mid = inorder.index(value, ileft, iright)\n\n left, left_size = self.dfs(preorder, inorder, root + 1, ileft, mid)\n node.left = left\n right, right_size = self.dfs(preorder, inorder, root + left_size + 1, mid+1, iright)\n node.right = right\n return node, left_size + right_size + 1\n except:\n return None, 0\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.buildTree([3],[3]))\n print(sol.buildTree([3,9,20,15,7],[9,3,15,20,7]))\n print(sol.buildTree([1,2,3],[2,3,1]))","sub_path":"0105.py","file_name":"0105.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"140538926","text":"from flask import Flask, g, jsonify, session\nfrom os import listdir\nimport requests\nimport sqlite3\n\nport = 0\n\napp = Flask(__name__)\n\n@app.route('/find///', methods=['post'])\n@app.route('/count//', methods=['post'])\ndef count(query, nextport):\n print('counting ' + query + ' in worker')\n conn = sqlite3.connect('Wordlist.db')\n c = conn.cursor()\n c.execute(\"\"\"SELECT quantity FROM wordlist WHERE term = ?\"\"\", (query,))\n indb = c.fetchall()\n # Als de zoekterm niet in de database voor komt zoeken we door de files heen\n if len(indb) is 0:\n print('query not counted before')\n i = 0\n quantity = 0\n txtfiles = ''\n for file in listdir('files'):\n if file.endswith(\".txt\"):\n with open('files/' + file) as f:\n contents = f.read()\n if query.lower() in contents.lower():\n txtfiles = txtfiles + file + '#'\n quantity = quantity + 1\n i = i + 1\n c.execute(\"\"\"INSERT INTO wordlist(term, quantity, cdocs) VALUES (?,?,?)\"\"\", (query, quantity, txtfiles))\n conn.commit()\n conn.close()\n print('The port of the next machine is: ' + str(nextport))\n global port\n port = nextport\n return 'Done'\n\n\n@app.route('/reduce-count//', methods = ['get'])\ndef reducecount(query,totalcount):\n print('iterating through reduce-count')\n conn = sqlite3.connect('Wordlist.db')\n c = conn.cursor()\n c.execute(\"\"\"SELECT quantity FROM wordlist WHERE term = ?\"\"\", (query,))\n quantity = c.fetchone()[0]\n totalcount = totalcount + quantity\n print('The current total amount is ' + str(totalcount))\n global port\n url = 'http://127.0.0.1:' + str(port) + '/reduce-count/' + str(query)\n response = requests.get(url)\n return 'NEXT'\n\n\n@app.route('/reduce-count/')\ndef reducecount2(query):\n print('initialising reduce-count')\n conn = sqlite3.connect('Wordlist.db')\n c = conn.cursor()\n c.execute(\"\"\"SELECT quantity FROM wordlist WHERE term = ?\"\"\", (query,))\n quantity = c.fetchone()[0]\n totalcount = quantity\n print('The current total amount is ' + str(totalcount))\n global port\n url = 'http://127.0.0.1:' + str(port) + '/reduce-count/' + str(query) + '/' + str(totalcount)\n # response = requests.get(url)\n # if port == 5000:\n # return totalcount\n # else\n # return 'PLACEHOLDER'\n\n\nif __name__ == '__main__':\n app.run(host=\"127.0.0.1\", port=\"5001\")","sub_path":"docker/dockerserver.py","file_name":"dockerserver.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"136599260","text":"class Solution(object):\n def intersection(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n set1 = set(nums1)\n inter = set()\n for e in nums2:\n if e in set1:\n inter.add(e)\n return list(inter)\n","sub_path":"IntersectOfArrays.py","file_name":"IntersectOfArrays.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533762382","text":"# https://leetcode.com/problems/remove-duplicate-letters/\n\nimport collections\n\ns = \"cbacdcbc\"\ncounter, seen, stack = collections.Counter(s), set(), collections.deque()\n\nfor char in s:\n counter[char] -= 1\n if char in seen: continue\n \n while stack and char < stack[-1] and counter[stack[-1]] > 0:\n seen.remove(stack.pop())\n stack.append(char)\n seen.add(char)\n\nprint(''.join(stack))\n \n ","sub_path":"interview/4. Stack, Queue/failed/remove-duplicate-letters.py","file_name":"remove-duplicate-letters.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"121192219","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright © 2013 eNovance\n#\n# Author: Julien Danjou \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Publish a counter using an UDP mechanism\n\"\"\"\n\nfrom ceilometer import publisher\nfrom ceilometer.openstack.common import log\nfrom ceilometer.openstack.common.gettextutils import _\nfrom oslo.config import cfg\nimport msgpack\nimport socket\n\nLOG = log.getLogger(__name__)\n\nUDP_PUBLISH_GROUP = cfg.OptGroup(name='publisher_udp',\n title='Options for UDP publisher')\n\nUDP_PUBLISH_OPTS = [\n cfg.StrOpt('host',\n default=\"localhost\",\n help='The host target to publish metering records to.',\n ),\n cfg.IntOpt('port',\n default=4952,\n help='The port to send UDP meters to.',\n ),\n]\n\n\ndef register_opts(config):\n \"\"\"Register the options for publishing UDP messages.\n \"\"\"\n config.register_group(UDP_PUBLISH_GROUP)\n config.register_opts(UDP_PUBLISH_OPTS,\n group=UDP_PUBLISH_GROUP)\n\n\nregister_opts(cfg.CONF)\n\n\nclass UDPPublisher(publisher.PublisherBase):\n\n def __init__(self):\n self.socket = socket.socket(socket.AF_INET,\n socket.SOCK_DGRAM)\n\n def publish_counters(self, context, counters, source):\n \"\"\"Send a metering message for publishing\n\n :param context: Execution context from the service or RPC call\n :param counter: Counter from pipeline after transformation\n :param source: counter source\n \"\"\"\n\n for counter in counters:\n msg = counter._asdict()\n msg['source'] = source\n LOG.debug(_(\"Publishing counter %s over UDP to %s:%d\"),\n msg,\n cfg.CONF.publisher_udp.host,\n cfg.CONF.publisher_udp.port)\n try:\n self.socket.sendto(msgpack.dumps(msg),\n (cfg.CONF.publisher_udp.host,\n cfg.CONF.publisher_udp.port))\n except Exception as e:\n LOG.warn(_(\"Unable to send counter over UDP\"))\n LOG.exception(e)\n","sub_path":"ceilometer/publisher/udp.py","file_name":"udp.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"207607152","text":"from base.base_model import BaseModel\nimport tensorflow as tf\nimport numpy as np\n\n\nclass Attn_Fuse_Model(BaseModel):\n def __init__(self, data_loader, config):\n super(Attn_Fuse_Model, self).__init__(config)\n # Get the data_loader to make the joint of the inputs in the graph\n self.data_loader = data_loader\n\n # define some important variables\n self.x_base = None # input from 6 base recommender: (172,6)\n self.x_hour = None # input from one-hot hour vector: (24,1)\n self.y = None # output of label: one-hot channel vector: (172,1)\n self.is_training = None\n self.out_argmax = None\n self.loss = None\n self.acc = None\n self.optimizer = None\n self.train_step = None\n\n self.build_model()\n self.init_saver()\n\n def build_model(self):\n \n \"\"\"\n Helper Variables\n \"\"\"\n self.global_step_tensor = tf.Variable(0, trainable=False, name='global_step')\n self.global_step_inc = self.global_step_tensor.assign(self.global_step_tensor + 1)\n self.global_epoch_tensor = tf.Variable(0, trainable=False, name='global_epoch')\n self.global_epoch_inc = self.global_epoch_tensor.assign(self.global_epoch_tensor + 1)\n \n \"\"\"\n Inputs to the network\n \"\"\"\n with tf.variable_scope('inputs'):\n self.x_base, self.x_hour, self.y = self.data_loader.get_input()\n self.is_training = tf.placeholder(tf.bool, name='Training_flag')\n tf.add_to_collection('inputs', self.x_base)\n tf.add_to_collection('inputs', self.x_hour)\n tf.add_to_collection('inputs', self.y)\n tf.add_to_collection('inputs', self.is_training)\n\n \"\"\"\n Network Architecture\n \"\"\"\n with tf.variable_scope('network'):\n\n self.x_hour = tf.to_float(self.x_hour)\n with tf.variable_scope('attn_mech'):\n fc1 = tf.contrib.layers.fully_connected(self.x_hour,\n 256,\n activation_fn=tf.nn.tanh,\n normalizer_fn=None,\n normalizer_params=None,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n weights_regularizer=None,\n biases_initializer=tf.contrib.layers.xavier_initializer(),\n biases_regularizer=None,\n trainable=True,\n scope=\"fc1\")\n\n fc1 = tf.contrib.layers.batch_norm(fc1)\n\n fc2 = tf.contrib.layers.fully_connected(fc1,\n 256,\n activation_fn=tf.nn.tanh,\n normalizer_fn=None,\n normalizer_params=None,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n weights_regularizer=None,\n biases_initializer=tf.contrib.layers.xavier_initializer(),\n biases_regularizer=None,\n trainable=True,\n scope=\"fc2\")\n\n fc2 = tf.contrib.layers.batch_norm(fc2)\n\n fc3 = tf.contrib.layers.fully_connected(fc2,\n 256,\n activation_fn=tf.nn.tanh,\n normalizer_fn=None,\n normalizer_params=None,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n weights_regularizer=None,\n biases_initializer=tf.contrib.layers.xavier_initializer(),\n biases_regularizer=None,\n trainable=True,\n scope=\"fc3\")\n\n fc3 = tf.contrib.layers.batch_norm(fc3)\n\n conv_kernel = tf.contrib.layers.fully_connected(fc3,\n int(self.x_base.shape[1]),\n activation_fn=tf.nn.sigmoid,\n normalizer_fn=None,\n normalizer_params=None,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n weights_regularizer=None,\n biases_initializer=tf.contrib.layers.xavier_initializer(),\n biases_regularizer=None,\n trainable=True,\n scope=\"conv_kernel\")\n\n\n with tf.variable_scope('attn_fuse'):\n conv_kernel = tf.reshape(conv_kernel, [tf.shape(conv_kernel)[0], 1, -1], name=\"conv_kernel_reshape\")\n prod = tf.matmul(conv_kernel, self.x_base, name=\"prod\") # [?,1,6]*[?,6,172] --> [?,1,172]\n self.out = tf.squeeze(prod, name=\"out\")\n # self.out = tf.nn.softmax(prod, name=\"out\") #-->[?,172]\n\n # x_base_reshape = tf.reshape(self.x_base, [tf.shape(self.x_base)[0], tf.shape(self.x_base)[1], tf.shape(self.x_base)[2], 1]) # reshape base --> [?,6,172,1]\n # conv_kernel_reshape = tf.reshape(conv_kernel, [tf.shape(conv_kernel)[0], tf.shape(conv_kernel)[1], 1, 1]) # reshape kernel --> [?,6,1,1]\n # conv = tf.nn.conv2d(x_base_reshape, conv_kernel_reshape, [1, 6, 1, 1], \"SAME\", name = \"Conv\")\n # self.out = tf.squeeze(conv) #-->[?,172]\n # self.out = tf.contrib.layers.softmax(self.out)\n\n tf.add_to_collection('out', self.out)\n\n\n \"\"\"\n Some operators for the training process\n \"\"\"\n with tf.variable_scope('out_argmax'):\n self.out_argmax = tf.argmax(self.out, axis=1, output_type=tf.int64, name='out_argmax') # --> [?,]\n\n with tf.variable_scope('loss-acc'):\n y_ind = tf.argmax(self.y, axis=1) # --> [?,]\n self.loss = tf.losses.softmax_cross_entropy(onehot_labels=self.y, logits=self.out, scope=\"loss\")\n self.acc = tf.reduce_mean(tf.cast(tf.equal(y_ind, self.out_argmax), tf.float32),name=\"acc\")\n self.acc2 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,2), tf.float32),name=\"acc2\")\n self.acc3 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,3), tf.float32),name=\"acc3\")\n self.acc4 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,4), tf.float32),name=\"acc4\")\n self.acc5 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,5), tf.float32),name=\"acc5\")\n self.acc6 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,6), tf.float32),name=\"acc6\")\n self.acc7 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,7), tf.float32),name=\"acc7\")\n self.acc8 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,8), tf.float32),name=\"acc8\")\n self.acc9 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,9), tf.float32),name=\"acc9\")\n self.acc10 = tf.reduce_mean(tf.cast(tf.nn.in_top_k(self.out,y_ind,10), tf.float32),name=\"acc10\")\n\n with tf.variable_scope('train_step'):\n starter_learning_rate = self.config.learning_rate\n self.learning_rate = tf.train.exponential_decay(starter_learning_rate, self.global_step_tensor,\n 100000, 0.96, staircase=True)\n self.optimizer = tf.train.AdamOptimizer(learning_rate)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.train_step = self.optimizer.minimize(self.loss, global_step=self.global_step_tensor)\n\n tf.add_to_collection('train', self.train_step)\n tf.add_to_collection('train', self.loss)\n tf.add_to_collection('train', self.acc)\n tf.add_to_collection('train', self.acc2)\n tf.add_to_collection('train', self.acc3)\n tf.add_to_collection('train', self.acc4)\n tf.add_to_collection('train', self.acc5)\n tf.add_to_collection('train', self.acc6)\n tf.add_to_collection('train', self.acc7)\n tf.add_to_collection('train', self.acc8)\n tf.add_to_collection('train', self.acc9)\n tf.add_to_collection('train', self.acc10)\n\n print(\"total num of weights: \", np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))\n\n\n def init_saver(self):\n \"\"\"\n initialize the tensorflow saver that will be used in saving the checkpoints.\n :return:\n \"\"\"\n self.saver = tf.train.Saver(max_to_keep=self.config.max_to_keep, save_relative_paths=True)\n","sub_path":"models/attn_fuse_model.py","file_name":"attn_fuse_model.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"400954812","text":"import unittest\nimport os\n\nfrom programy.utils.geo.geonames import GeoNamesApi\nfrom programy.utils.license.keys import LicenseKeys\n\n#############################################################################\n#\n\nclass GeoNamesTests(unittest.TestCase):\n\n def test_geonames_no_license_keys(self):\n license_keys = LicenseKeys()\n with self.assertRaises(Exception):\n geonames = GeoNamesApi(license_keys)\n\n def test_geonames_no_account_name(self):\n license_keys = LicenseKeys()\n license_keys.add_key('GEO_NAMES_COUNTRY', \"DummyValue\")\n with self.assertRaises(Exception):\n geonames = GeoNamesApi(license_keys)\n\n def test_geonames_no_country(self):\n license_keys = LicenseKeys()\n license_keys.add_key('GEO_NAMES_ACCOUNTNAME', \"DummyValue\")\n with self.assertRaises(Exception):\n geonames = GeoNamesApi(license_keys)\n\n def test_geonames_with_license_keys(self):\n license_keys = LicenseKeys()\n license_keys.add_key('GEO_NAMES_COUNTRY', \"DummyValue\")\n license_keys.add_key('GEO_NAMES_ACCOUNTNAME', \"DummyValue\")\n geonames = GeoNamesApi(license_keys)\n\n def test_geonames(self):\n\n license_keys = LicenseKeys()\n license_keys.load_license_key_file(os.path.dirname(__file__)+ os.sep + \"test.keys\")\n\n geonames = GeoNamesApi(license_keys)\n self.assertIsNotNone(geonames)\n\n GeoNamesApi.get_latlong_for_postcode_response_file = os.path.dirname(__file__)+ os.sep + \"geonames_latlong.json\"\n\n latlng = geonames.get_latlong_for_postcode('KY39UR')\n self.assertIsNotNone(latlng)\n self.assertEquals(latlng.latitude, 56.07206267570594)\n self.assertEquals(latlng.longitude, -3.175233048730664)\n","sub_path":"test/programytest/utils/geo/test_geonames.py","file_name":"test_geonames.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"48033782","text":"# Autor: Mariana Mejía Béjar, A01374862\n# Calcular el área y perímetro de un trapecio isósceles\n\n\ndef calcularArea(a, b, h) :\n # Calcula a través de su respectiva fórmula, el área del trapecio isósceles\n area = (a+b)/2*h\n return area\n\ndef calcularPerimetro(a, b, h) :\n # Calcula a través de su respectiva fórmula, el perímetro del trapecio isósceles\n perimetro = ((((a-b)/2)**2 + h**2)**0.5)*2 + a + b \n return perimetro\n \ndef main ():\n # Define el programa principal\n baseMayor = int(input(\"Escribe la longitud de la base mayor: \"))\n baseMenor = int(input(\"Escribe la longitud de la base menor: \"))\n altura = int(input(\"Escribe la altura: \"))\n \n Area = calcularArea(baseMayor, baseMenor, altura)\n Perimetro = calcularPerimetro(baseMayor, baseMenor, altura)\n \n print(\"Área: %.2f\" % Area)\n print(\"Perímetro: %.2f\" % Perimetro)\n\n \n# Llamar al programa principal\nmain ()\n\n\n","sub_path":"Mision_03/Trapecio.py","file_name":"Trapecio.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"496568693","text":"from chart3 import Chart3\nimport load_data as ld\nimport date_time_util as dtutil\nimport time\nimport multiprocessing as mlp\nfrom multiprocessing import Process\n\nDATA_FILE = \"GBPUSD15.csv\"\n\n\ndef get_ohlc():\n ohlcs = ld.load_cvs(DATA_FILE)\n prices = [[\n dtutil.date_time_str_2_float(olhc[0]+' '+olhc[1]),\n float(olhc[2]),\n float(olhc[3]),\n float(olhc[4]),\n float(olhc[5])\n ] for olhc in ohlcs]\n return prices\n\n# chart = None\n\n# def animate():\n# global chart\n# chart.animate()\n\n\nif __name__ == \"__main__\":\n chart = Chart3(data=get_ohlc())\n queue = mlp.Queue()\n p = Process(target=chart.animate, args=(queue,))\n p.start()\n step = 0\n while True:\n queue.put({\"step\":step, \"acct\":0, \"positions\":[]})\n step += 1\n time.sleep(0.5)","sub_path":"stock_experiment/chart3_test.py","file_name":"chart3_test.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"642219512","text":"\"\"\"\nrequests_tracker.models\n=======================\n\"\"\"\nfrom django.db import models, transaction\nfrom django.utils.timezone import now\n\nfrom requests_tracker import http_methods\nfrom requests_tracker import states\nfrom requests_tracker.exceptions import (\n ConcurrencyTransitionError, StateTransitionError\n)\nfrom requests_tracker.filtering import categories\nfrom requests_tracker.filtering import columns\n\n\nclass HttpMessage(models.Model):\n\n content = models.TextField(blank=True)\n\n def __unicode__(self):\n return unicode(self.content)\n\n\nclass Record(models.Model):\n\n # tracking record info\n uid = models.UUIDField(unique=True)\n identity = models.CharField(\n max_length=64,\n blank=True,\n default=''\n )\n state = models.CharField(\n max_length=16,\n choices=zip(states.ALL_STATES, states.ALL_STATES),\n default=states.CREATED\n )\n remark = models.CharField(\n max_length=255,\n blank=True,\n default=''\n )\n\n # request info\n method = models.CharField(\n max_length=8,\n choices=zip(http_methods.ALL_METHODS, http_methods.ALL_METHODS),\n default=http_methods.GET\n )\n url = models.URLField(max_length=255)\n request_message = models.ForeignKey(\n HttpMessage,\n null=True,\n blank=True,\n related_name='record_set_for_request_message',\n )\n\n # response info\n status_code = models.PositiveSmallIntegerField(default=0)\n response_message = models.ForeignKey(\n HttpMessage,\n null=True,\n blank=True,\n related_name='record_set_for_response_message',\n )\n\n # important datetimes\n date_created = models.DateTimeField(default=now)\n duration = models.DurationField(blank=True, null=True)\n\n def __unicode__(self):\n return unicode(u\"[#%s] %s %s\" % (self.pk, self.method, self.url))\n\n @transaction.atomic\n def transit(self, to_state, **kwargs):\n if states.can_transit(self.state, to_state):\n kwargs.update({'state': to_state})\n\n rows = Record.objects.filter(pk=self.pk, state=self.state) \\\n .update(**kwargs)\n\n if rows:\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n else:\n msg = \"transit from %r to %r conflicted.\" \\\n % (self.state, to_state)\n raise ConcurrencyTransitionError(msg)\n else:\n msg = \"can not transit from %r to %r\" % (self.state, to_state)\n raise StateTransitionError(msg)\n\n @transaction.atomic\n def update(self, **kwargs):\n Record.objects.filter(pk=self.pk).update(**kwargs)\n\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n\n\nclass AbstractFilter(models.Model):\n\n name = models.CharField(max_length=64, unique=True)\n is_active = models.BooleanField(default=False)\n\n # filter rules\n column = models.PositiveSmallIntegerField(\n choices=columns.COLUMN_CHOICES,\n )\n category = models.PositiveSmallIntegerField(\n choices=categories.CATEGORY_CHOICES,\n default=categories.EQUAL,\n )\n rule = models.CharField(max_length=1024)\n\n # important dates\n date_created = models.DateTimeField(default=now)\n last_modified = models.DateTimeField(auto_now=True, blank=True)\n\n class Meta:\n abstract = True\n\n def __unicode__(self):\n return unicode(u\"[#%s] %s\" % (self.pk, self.name))\n\n\nclass Filter(AbstractFilter):\n pass\n\n\nclass Exclude(AbstractFilter):\n pass\n","sub_path":"requests_tracker/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"547571012","text":"import numpy as np\nimport psi4\nfrom HFSCF import Diag, OrthoS, OrthoF, Fock, ElEnergy, Unitary, Hermitian, EHF, SSquared\nimport time\nimport matplotlib.pyplot as plt\n\npsi4.core.set_output_file('output.dat', True)\npsi4.set_memory(int(5e8))\nnp_memory = 2\n\npsi4.set_options({'basis': 'cc-pvdz'})\n\nmol = psi4.geometry(\"\"\"\nO 0.000000000000 -0.143225816552 0.000000000000\nH 1.638036840407 1.136548822547 -0.000000000000\nH -1.638036840407 1.136548822547 -0.000000000000\nunits bohr\n\"\"\")\nmol.update_geometry()\n\nnre = mol.nuclear_repulsion_energy()\nwave = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option('basis'))\nmints = psi4.core.MintsHelper(wave.basisset())\n\nocc_a = wave.nalpha()\nocc_b = wave.nbeta()\n\nS = np.asarray(mints.ao_overlap())\nT = np.asarray(mints.ao_kinetic())\nV = np.asarray(mints.ao_potential())\nERI = np.asarray(mints.ao_eri())\nHcore = T + V\n\nSval, Svec = Diag(S)\nSmin = OrthoS(Sval, Svec)\n\nFa = Fb = OrthoF(Hcore, Smin)\nFa_val, Fa_vec = Fb_val, Fb_vec = Diag(Fa)\nCa = Cb = Smin @ Fa_vec\n\nDa = np.einsum('ik,jk->ij',Ca[:, :occ_a], Ca[:, :occ_a])\nDb = np.einsum('ik,jk->ij',Cb[:, :occ_b], Cb[:, :occ_b])\n\nEza_el = np.einsum('ij,ij->', Da, 2*Hcore)\nEzb_el = np.einsum('ij,ij->', Db, 2*Hcore)\n\nehf = 0\nDE = -Eza_el\nval = 1e-12\niteration = 0\nenergieshf = []\niterations =[]\ntotal_time = time.time()\n\nwhile DE > val:\n DE = 0\n iteration += 1\n iterations.append(iteration)\n # nieuwe fockmatrix maken\n Fa = Fock(Da, Db, Hcore, ERI)\n Fb = Fock(Db, Da, Hcore, ERI)\n # gemiddelde energie berekenen met zelfde density matrix als fock\n E_el = EHF(Hcore, Da, Fa, Db, Fb)\n # fock matrix orthogonaliseren en diagonaliseren\n Fa_acc = OrthoF(Fa, Smin)\n Fb_acc = OrthoF(Fb, Smin)\n Fa_acc_val, Fa_acc_vec = Diag(Fa_acc)\n Fb_acc_val, Fb_acc_vec = Diag(Fb_acc)\n Ca = Smin @ Fa_acc_vec\n Cb = Smin @ Fb_acc_vec\n # nieuwe density matrix opstellen\n Da = np.einsum('ik,jk->ij', Ca[:, :occ_a], Ca[:, :occ_a])\n Db = np.einsum('ik,jk->ij', Cb[:, :occ_b], Cb[:, :occ_b])\n energieshf.append(E_el)\n DE = abs(ehf - E_el)\n ehf = E_el\nS2, Sz = SSquared(Da, Db, Ca, occ_b, occ_a)\nprint('SCF energy (Hartree): {}\\t = {}\\t = {}\\nLoop time: {}s'.format(energieshf[-1] + nre, S2, Sz, time.time() - total_time))\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"522008851","text":"import json\nfrom google.cloud.aiplatform import CustomJob, Model\nfrom google.cloud import storage\nimport dvc.api\nimport yaml\nimport uuid\nimport os.path\nfrom sacred import Experiment\nfrom edge.sacred import get_mongo_observer\nfrom edge.config import EdgeConfig\nfrom edge.state import EdgeState\n\n_config = EdgeConfig.load_default()\nstate = EdgeState.load(_config)\n\nex = Experiment(\"fashion-mnist-model-training\")\nex.observers.append(get_mongo_observer(_config))\n\n\n@ex.config\ndef config():\n print(\"Preparing job to run on Vertex AI\")\n params = yaml.safe_load(open(\"params.yaml\"))[\"train\"]\n\n # Get dataset links\n train_uri = dvc.api.get_url(\"data/fashion-mnist/train.pickle\")\n test_uri = dvc.api.get_url(\"data/fashion-mnist/test.pickle\")\n\n # Define output bucket\n vertex_dir = os.path.join(state.storage_bucket_state.bucket_path, _config.storage_bucket.vertex_jobs_directory)\n output_dir = os.path.join(vertex_dir, str(uuid.uuid4()))\n\n model_gs_link = os.path.join(output_dir, \"model.joblib\")\n metrics_gs_link = os.path.join(output_dir, \"metrics.json\")\n\n image_tag = os.environ.get(\"IMAGE_TAG\")\n if image_tag is None:\n image_tag = \"latest\"\n\n\n@ex.automain\ndef main(\n _run,\n params,\n train_uri: str,\n test_uri: str,\n vertex_dir: str,\n output_dir: str,\n metrics_gs_link: str,\n image_tag: str,\n):\n print(\"Running the job\")\n # Run job\n CustomJob.from_local_script(\n display_name=\"Fashion MNIST Naive Bayes\",\n script_path=\"train.py\",\n container_uri=\"europe-docker.pkg.dev/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest\",\n requirements=[\n \"scikit-learn==0.23.1\",\n \"google-cloud-storage==1.38.0\",\n \"dill==0.3.4\",\n \"scipy==1.6.3\",\n ],\n args=[\n \"--model-dir\", output_dir,\n \"--model-metrics-path\", metrics_gs_link,\n \"--n-neigbours\", str(params[\"n_neighbours\"]),\n train_uri,\n test_uri\n ],\n replica_count=1,\n project=_config.google_cloud_project.project_id,\n location=_config.google_cloud_project.region,\n staging_bucket=vertex_dir\n ).run()\n\n # Get results back\n print(\"Fetching the results\") # TODO see options for linking from gs, instead of downloading locally\n\n client = storage.Client()\n metrics = json.loads(storage.Blob.from_string(metrics_gs_link, client).download_as_bytes())\n\n for metric in metrics:\n _run.log_scalar(metric, metrics[metric])\n\n # Create model on Vertex\n print(\"Creating model\")\n serving_container_image_uri = f\"gcr.io/{_config.google_cloud_project.project_id}/{_config.vertex.prediction_server_image}:{image_tag}\"\n model = Model.upload(\n display_name=_config.vertex.model_name,\n project=_config.google_cloud_project.project_id,\n location=_config.google_cloud_project.region,\n serving_container_image_uri=serving_container_image_uri,\n serving_container_predict_route=\"/infer\",\n serving_container_health_route=\"/health\",\n serving_container_ports=[8000],\n artifact_uri=output_dir,\n )\n\n with open(\"vertex_model.json\", \"w\") as f:\n json.dump({\n \"model_name\": model.resource_name,\n }, f)\n","sub_path":"models/fashion/train-vertex.py","file_name":"train-vertex.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"358026047","text":"#!/bin/env python3\nfrom sys import argv, stdin\nfrom os.path import isfile\n(_, src, out, srcdir, objdir, bindir) = argv\n\ndef filename(dep):\n return dep[len(srcdir)+1:-2]\n\nodeps = {}\n\nfor line in stdin:\n line = line.strip()\n (head, deps) = line.split(':', 1)\n deps = deps.split(' ')\n objdeps = [dep for dep in deps if isfile(\"%s/%s.c\" % (srcdir, filename(dep)))]\n odeps[filename(objdeps[0])] = set(objdeps)\n\nseen = set()\n\nwhile odeps[src] - seen:\n dep = next(iter(odeps[src] - seen))\n seen.add(dep)\n odeps[src] |= odeps[filename(dep)]\n\nprint(\"%s: %s\" % (out, \" \".join(odeps[src])))\nprint(\"%s/%s: %s\" % (bindir, src, \" \".join(set(\"%s/%s.o\" % (objdir, filename(o)) for o in odeps[src]))))\n\n","sub_path":"bin/make_bin_deps.py","file_name":"make_bin_deps.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"29848504","text":"\"\"\"\nNote:\n Please change class_text_to_int function to reflect the labels\n used in label_map.pbtxt file.\n\n\"\"\"\nimport os\nimport io\nimport pdb\nimport argparse\nimport pandas as pd\nimport tensorflow as tf\nimport sys\nfrom PIL import Image\nfrom object_detection.utils import dataset_util\nfrom collections import namedtuple, OrderedDict\n\n\ndef split(df, group):\n data = namedtuple(\"data\", [\"filename\", \"object\"])\n gb = df.groupby(group)\n return [\n data(filename, gb.get_group(x))\n for filename, x in zip(gb.groups.keys(), gb.groups)\n ]\n\n\ndef class_text_to_int(row_label):\n if row_label == \"hand\": # 'keyboard'\n return 1\n # comment upper if statement and uncomment these statements for multiple labelling\n # if row_label == FLAGS.label0:\n # return 1 # as in pbtxt file\n # elif row_label == FLAGS.label1:\n # return 2 # as in pbtxt file\n else:\n None\n\n\ndef get_image_path(data_dir, img_name):\n \"\"\"\n Find path of image. Thanks to Carlos for unique naming convention.\n This logic is only possible because of that.\n \"\"\"\n files = []\n # r=root, d=directories, f = files\n for r, d, f in os.walk(data_dir):\n for file in f:\n if img_name in file:\n files.append(os.path.join(r, file))\n\n if len(files) > 1:\n print(\"More than one image with same name is found\")\n print(files)\n sys.exit()\n\n return os.path.dirname(files[0])\n\n\ndef create_tf_example(group, data_dir):\n path = get_image_path(data_dir, group.filename)\n with tf.gfile.GFile(os.path.join(path, \"{}\".format(group.filename)), \"rb\") as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n width, height = image.size\n\n filename = group.filename.encode(\"utf8\")\n image_format = b\"png\"\n # check if the image format is matching with your images.\n xmins = []\n xmaxs = []\n ymins = []\n ymaxs = []\n classes_text = []\n classes = []\n\n for index, row in group.object.iterrows():\n xmins.append(row[\"xmin\"] / width)\n xmaxs.append(row[\"xmax\"] / width)\n ymins.append(row[\"ymin\"] / height)\n ymaxs.append(row[\"ymax\"] / height)\n try:\n classes_text.append(row[\"class\"].encode(\"utf8\"))\n except:\n pdb.set_trace()\n\n classes.append(class_text_to_int(row[\"class\"]))\n\n tf_example = tf.train.Example(\n features=tf.train.Features(\n feature={\n \"image/height\": dataset_util.int64_feature(height),\n \"image/width\": dataset_util.int64_feature(width),\n \"image/filename\": dataset_util.bytes_feature(filename),\n \"image/source_id\": dataset_util.bytes_feature(filename),\n \"image/encoded\": dataset_util.bytes_feature(encoded_jpg),\n \"image/format\": dataset_util.bytes_feature(image_format),\n \"image/object/bbox/xmin\": dataset_util.float_list_feature(xmins),\n \"image/object/bbox/xmax\": dataset_util.float_list_feature(xmaxs),\n \"image/object/bbox/ymin\": dataset_util.float_list_feature(ymins),\n \"image/object/bbox/ymax\": dataset_util.float_list_feature(ymaxs),\n \"image/object/class/text\": dataset_util.bytes_list_feature(\n classes_text\n ),\n \"image/object/class/label\": dataset_util.int64_list_feature(classes),\n }\n )\n )\n return tf_example\n\n\ndef parse_arguments():\n \"\"\"\n Parse arguments\n \"\"\"\n\n parser = argparse.ArgumentParser(description=\"Creates tfrecord from csv files\")\n parser.add_argument(\n \"--csv\", metavar=\"c\", nargs=\"+\", required=True, help=\"full paths to csv files\"\n )\n parser.add_argument(\n \"--labels\", metavar=\"l\", nargs=\"+\", required=True, help=\"Lable of objects\"\n )\n parser.add_argument(\n \"--output\",\n metavar=\"o\",\n type=str,\n required=True,\n help=\"full path to output file\",\n )\n parser.add_argument(\n \"--images\",\n metavar=\"ip\",\n nargs=\"+\",\n required=False,\n help=\"Root directory whre the images can be found\",\n )\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n\n writer = tf.python_io.TFRecordWriter(args.output)\n\n # Looping through all th csv files\n for idx, ccsv in enumerate(args.csv):\n print(\"Creating tfrecord for \", ccsv)\n data_dir = args.images[idx]\n ccsv_df = pd.read_csv(ccsv)\n grouped = split(ccsv_df, \"filename\")\n for group in grouped:\n tf_example = create_tf_example(group, data_dir)\n writer.write(tf_example.SerializeToString())\n\n writer.close()\n print(\"Successfully created tfrecord file at \", args.output)\n","sub_path":"HandDetection in Videos(Custom Dataset) using Single Shot Detector(TensorFlow)/generate_tfrecord/generate_tfrecord.py","file_name":"generate_tfrecord.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"572176092","text":"from pandas.core.frame import DataFrame\nfrom pandas.io import html\nimport requests\nimport lxml.html as lh\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, timedelta\nfrom datetime import date\nimport time\n\ndef YJDownloadStockData(symbol, startdate:datetime):\n\n\n\n url = 'https://finance.yahoo.co.jp/quote/' + symbol + '.T/history?from='+startdate.strftime('%Y%m%d')+'&to='+ datetime.now().strftime('%Y%m%d') + '&timeFrame=d&page=' #+ '1'\n \n # n_days = (datetime.today() - startdate).days\n\n n_days = np.busday_count( startdate.date(), datetime.today().date() )- 200\n\n #'https://finance.yahoo.co.jp/quote/8411.T/history?from=20210101&to=20210913&timeFrame=d&page=1'\n #url = '/home/carlo/Downloads/8411.html'\n\n columns = ['date', 'adjclose']\n\n wholepage_stock_data = pd.DataFrame()\n \n\n \n for p in range(1,50): \n #with open(url+str(i),'r') as f:\n #doc = lh.fromstring(f.read())\n time.sleep(1)\n try:\n page = requests.get(url+str(p))\n except:\n pass\n doc = lh.fromstring(page.content)\n stock_data = pd.DataFrame()\n tr_elements = doc.xpath('//tr')\n\n col = []\n i = 0\n\n for t in tr_elements[0]:\n i+=1\n name = t.text_content()\n print (name)\n\n\n\n for j in range(1, len(tr_elements)):\n T = tr_elements[j]\n index = 0\n stockticker = []\n error = False\n for t in T.iterchildren(): \n print(index)\n data = t.text_content()\n# print(data)\n if (index == 0):\n if(data==''):\n error = True\n pass\n datastring = str(data)\n datastring = datastring.replace(\"年\", \"/\")\n datastring = datastring.replace(\"月\", \"/\")\n datastring = datastring.replace(\"日\", \"\")\n stockticker.append(datastring)\n \n if (index == 6):\n stockticker.append(data)\n index+=1\n \n stock_data = stock_data.append(dict(zip(columns, stockticker)), ignore_index=True)\n stock_data = stock_data.dropna()\n print(stock_data.head())\n wholepage_stock_data = wholepage_stock_data.append(stock_data)\n\n wholepage_stock_data = wholepage_stock_data.dropna()\n wholepage_stock_data.set_index('date')\n # print(wholepage_stock_data)\n return wholepage_stock_data\n\n\ndef ReadStocksFromFile():\n stocks = pd.DataFrame()\n return stocks\n\n\ndef FormatStocksCSVs():\n i = 0\n stock_prices = pd.DataFrame()\n stock_symbols = pd.DataFrame()\n stock_symbols = pd.read_csv('https://raw.githubusercontent.com/cartasuzuki/phynance/master/datasets/nikkei_high_dividend_yield_50_weight_en.csv', usecols=['Code'])\n for symbol in stock_symbols['Code']:\n myprices = pd.DataFrame()\n myprices = pd.read_csv(str(symbol)+\".csv\")\n myprices.set_index('date')\n if(i==0):\n stock_prices[['date']] = myprices[['date']]\n stock_prices.set_index('date')\n i = 1\n stock_prices[[str(symbol)]] = myprices[['adjclose']]\n\n stock_prices.to_csv('nikkei50.csv')\n\n\ndef DownloadAllStocksCSVs():\n fromdate = datetime(2017,1,1)\n stockdata = pd.DataFrame()\n stock_symbols = pd.read_csv('https://raw.githubusercontent.com/cartasuzuki/phynance/master/datasets/nikkei_high_dividend_yield_50_weight_en.csv', usecols=['Code'])\n for symbol in stock_symbols['Code']:\n stockdata = YJDownloadStockData(str(symbol), fromdate)\n stockdata.to_csv(str(symbol)+'.csv')\n print( str(symbol) +'.csv saved')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"YJDownloadNikkei50Prices.py","file_name":"YJDownloadNikkei50Prices.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"69616377","text":"from numpy import genfromtxt\nimport numpy as np\nfrom sklearn import datasets, linear_model\n\n# data.csv里的变量分别是 英里数 次数 车型 时间(Y)\ndata_path = r\"F:\\WebProjects\\blog\\linear-regression\\data.csv\"\ndilivery_data = genfromtxt(data_path, delimiter=',')\n\n# print(\"data\")\n# print(dilivery_data)\n\n# 前面的':'表示所有行 后面的':-1'表示所有列但不包括-1(最后一列)\nX = dilivery_data[:, :-1]\n# 前面的':'表示所有行 后面的'-1'表示最后一列\nY = dilivery_data[:, -1]\n\nregr = linear_model.LinearRegression()\n# fit 对数据进行建模\nregr.fit(X, Y)\n\n# b1, b2, b3 ... bn\nprint(\"coefficients: {}\".format(regr.coef_))\n\n# 截距 b0\nprint(\"intercept: {}\".format(regr.intercept_))\n\nxPred = np.array([[102, 6]])\nyPred = regr.predict(xPred)\n\nprint(\"predicted y: {}\".format(yPred))\n","sub_path":"linear-regression/code-multi-regression.py","file_name":"code-multi-regression.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"90875833","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats\n\ndef gen_2d_data():\n \"\"\"Genarate 2D data by mixture of two 2D gaussians\"\"\"\n # first gaussian samples\n mean0 = [8,8]\n cov0 = [[1, 0], [0, 3]]\n points0= np.random.multivariate_normal(mean0, cov0, 600)\n\n mean1 = [1,1]\n cov1 = [[2, 0], [0, 1]] \n points1= np.random.multivariate_normal(mean1, cov1, 400)\n points = np.concatenate((points0, points1), axis = 0)\n np.random.shuffle(points)\n return points\n\ndef k_means(points):\n \"\"\"Apply Expectation-Maximization algorithm\"\"\"\n mu0 = [-1,-1]\n mu1 = [1,1]\n while True:\n print(mu0)\n print(mu1)\n new_mu0 = [0,0]\n new_mu1 = [0,0]\n num_0 = 0\n num_1 = 0\n for pt in points:\n d0 = np.linalg.norm(pt - mu0)\n d1 = np.linalg.norm(pt - mu1)\n if d0 <= d1:\n num_0 = num_0 + 1\n new_mu0 = new_mu0 + pt\n else:\n num_1 = num_1 + 1\n new_mu1 = new_mu1 + pt\n new_mu0 = new_mu0 / num_0\n new_mu1 = new_mu1 / num_1\n d0 = np.linalg.norm(new_mu0 - mu0)\n d1 = np.linalg.norm(new_mu1 - mu1)\n if d0 < 0.00001 and d1 < 0.00001:\n break\n else:\n mu0 = new_mu0\n mu1 = new_mu1\n return new_mu0, new_mu1\n \n \nif __name__ == '__main__':\n points = gen_2d_data()\n plt.scatter(points[:,0], points[:,1], s=10, facecolors='none')\n plt.show()\n mu0, mu1 = k_means(points)","sub_path":"k-means/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"309617142","text":"from itertools import chain\nimport calendar\nimport random\nimport logging\nlogger = logging.getLogger(__name__)\nfrom datetime import datetime, timedelta, date\nfrom django.db import models, transaction, IntegrityError\nfrom django.db.models import F, Count, Prefetch\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse, reverse_lazy\nfrom django.utils.safestring import mark_safe\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom . utils import sortPieData\nfrom . calendar import Calendar\nfrom . models import StorageItem, Recipe, Ingredient, Meal\nfrom . forms import StorageItemForm, RecipeForm, IngredientForm, MealForm\nfrom django.views.generic import (TemplateView, ListView, DetailView,\n CreateView, UpdateView, DeleteView)\n\n\n############################################################################\n# Home Page\n\nclass HomeView(TemplateView):\n template_name = 'appFood/home.html'\n\n###########################################################################\n# Storage Items\n\nclass StorageItemListView(ListView):\n model = StorageItem\n\ndef getShoppingList(request):\n low_items_List_queryset = StorageItem.objects.filter(quant_onHand__lt=1)\n need_list_queryset = Ingredient.objects.exclude(ingredient_name__in=list(StorageItem.objects.all()))\n shoppingList = list(chain(low_items_List_queryset, need_list_queryset))\n\n return render(request, 'appFood/shopping_list.html', {'shoppingList': shoppingList})\n\nclass StorageItemDetailView(DetailView):\n model = StorageItem\n\nclass CreateStorageItemView(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/storageitem_detail.html'\n\n form_class = StorageItemForm\n model = StorageItem\n\nclass UpdateStorageItemView(LoginRequiredMixin, UpdateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/storageitem_detail.html'\n\n form_class = StorageItemForm\n model = StorageItem\n\nclass DeleteStorageItemView(LoginRequiredMixin, DeleteView):\n model = StorageItem\n success_url = reverse_lazy('storageitem_list')\n\n##########################################################################\n# Recipes\n\nclass RecipeListView(ListView):\n model = Recipe\n\nclass RecipeDetailView(DetailView):\n model = Recipe\n\nclass CreateRecipeView(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/recipe_detail.html'\n\n form_class = RecipeForm\n model = Recipe\n\nclass UpdateRecipeView(LoginRequiredMixin, UpdateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/recipe_detail.html'\n\n form_class = RecipeForm\n model = Recipe\n\ndef decreaseStorage(request, pk):\n try:\n recipe = get_object_or_404(Recipe, pk=pk)\n ingredients = Ingredient.objects.select_related().filter(recipe = recipe)\n StorageItem.objects.filter(item_name__in=list(ingredients)).update(quant_onHand=F('quant_onHand')-1)\n StorageItem.objects.filter(item_name__in=list(ingredients)).update(item_count=F('item_count')+1)\n except IntegrityError:\n HttpResponse(\"Error, not enough items in storage.\")\n\n return render(request, 'appFood/recipe_detail.html', {'recipe': recipe})\n\n\nclass DeleteRecipeView(LoginRequiredMixin, DeleteView):\n model = Recipe\n success_url = reverse_lazy('recipe_list')\n\n###########################################################################\n# Ingredients\n\nclass IngredientListView(ListView):\n model = Ingredient\n\nclass IngredientDetailView(DetailView):\n model = Ingredient\n\nclass CreateIngredientView(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/ingredient_detail.html'\n\n form_class = IngredientForm\n model = Ingredient\n\nclass UpdateIngredientView(LoginRequiredMixin, UpdateView):\n login_url = '/login/'\n redirect_field_name = 'appFood/ingredient_detail.html'\n\n form_class = IngredientForm\n model = Ingredient\n\nclass DeleteIngredientView(LoginRequiredMixin, DeleteView):\n model = Ingredient\n success_url = reverse_lazy('recipe_list')\n\n##########################################################################\n#Calendar and Meals\n\nclass CalendarView(ListView):\n\tmodel = Meal\n\ttemplate_name = 'appFood/calendar.html'\n\tsuccess_url = reverse_lazy(\"calendar\")\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super().get_context_data(**kwargs)\n\t\td = get_date(self.request.GET.get('month', None))\n\t\tcal = Calendar(d.year, d.month)\n\t\thtml_cal = cal.formatmonth(withyear=True)\n\t\tcontext['calendar'] = mark_safe(html_cal)\n\t\tcontext['prev_month'] = prev_month(d)\n\t\tcontext['next_month'] = next_month(d)\n\t\treturn context\n\ndef get_date(month):\n if month:\n year, month = (int(x) for x in month.split('-'))\n return date(year, month, day = 1)\n return date.today()\n\ndef prev_month(d):\n first = d.replace(day = 1)\n prev_month = first - timedelta(days = 1)\n month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)\n return month\n\ndef next_month(d):\n days_in_month = calendar.monthrange(d.year, d.month)[1]\n last = d.replace(day = days_in_month)\n next_month = last + timedelta(days = 1)\n month = 'month=' + str(next_month.year) + '-' + str(next_month.month)\n return month\n\ndef meal(request, meal_id = None):\n instance = Meal()\n if meal_id:\n instance = get_object_or_404(Meal, pk=meal_id)\n else:\n instance = Meal()\n\n form = MealForm(request.POST or None, instance = instance)\n if request.POST and form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('calendar'))\n return render(request, 'appFood/meal.html', {'form': form})\n\n#############################################################################\n# Reports\n\nclass ReportView(TemplateView):\n template_name = 'appFood/reports.html'\n\n# Most used storage items\ndef topTenItems(request):\n return render(request, 'appFood/topTenStorage.html')\n\ndef topItemsChart(request):\n labels = []\n data = []\n topItems = StorageItem.objects.values('item_name', 'item_count').order_by('-item_count')[:10]\n for item in topItems:\n labels.append(item['item_name'])\n data.append(item['item_count'])\n\n return JsonResponse(data={'labels':labels, 'data':data,})\n\n# Ingredients that overlap with other recipes the most\ndef mostCommonIngredients(request):\n return render(request, 'appFood/topTenIngred.html')\n\ndef topIngredsChart(request):\n labels = []\n data = []\n ingredients = Ingredient.objects.values('ingredient_name').annotate(count=Count('recipe')).filter(count__gte=2).order_by('-count')[:10]\n for ingred in ingredients:\n labels.append(ingred['ingredient_name'])\n data.append(ingred['count'])\n\n return JsonResponse(data={'labels':labels, 'data':data,})\n\n# Gets all recipes by category\ndef recipeByCategory(request):\n labels = ['American', 'Italian', 'Mexican', 'Asian', 'Dessert', 'Other']\n data = []\n pieData = list(Recipe.objects.values('category_name').order_by('category_name').annotate(count=Count('category_name')))\n data = sortPieData(pieData)\n\n return render(request, 'appFood/recipeByCategory.html', {'labels': labels, 'data': data})\n\n# Recipe recommendations\ndef recommendRecipes(request):\n recipes = list(Recipe.objects.all())\n randomeRecipes = random.sample(recipes, 3)\n meals = Meal.objects.all()\n toprecipes = Recipe.objects.prefetch_related('recipes').annotate(count=Count('recipes')).filter(count__gte=1).order_by('-count')[:2]\n bottomrecipes = Recipe.objects.prefetch_related('recipes').annotate(count=Count('recipes')).filter(count__gte=1).order_by('count')[:2]\n recmdRcpList = list(chain(randomeRecipes, toprecipes, bottomrecipes))\n\n return render(request, 'appFood/recommendedRecipes.html', {'recmdRcpList': recmdRcpList})\n","sub_path":"appFood/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"197002727","text":"import argparse\r\nimport os\r\nimport sys\r\n\r\nimport tarfile\r\nfrom six.moves import cPickle as pickle\r\nimport tensorflow as tf\r\n\r\nHEIGHT = 32\r\nWIDTH = 32\r\nDEPTH = 3\r\n\r\ndef normalize(image):\r\n \"\"\"Convert `image` from [0, 255] -> [0, 1] floats.\"\"\"\r\n image = tf.cast(image, tf.float32) * (1. / 255)\r\n return image \r\n \r\ndef crop_pad(image):\r\n image = tf.image.resize_image_with_crop_or_pad(image, 40, 40)\r\n image = tf.random_crop(image, [32, 32, 3])\r\n return image\r\n\r\ndef horizontal_flip(image):\r\n image = tf.image.random_flip_left_right(image)\r\n return image\r\n\r\ndef replace_slice(input_: tf.Tensor, replacement, begin) -> tf.Tensor:\r\n inp_shape = tf.shape(input_)\r\n size = tf.shape(replacement)\r\n padding = tf.stack([begin, inp_shape - (begin + size)], axis=1)\r\n replacement_pad = tf.pad(replacement, padding)\r\n mask = tf.pad(tf.ones_like(replacement, dtype=tf.bool), padding)\r\n return tf.where(mask, replacement_pad, input_)\r\ndef cutout(x: tf.Tensor, h: int=8, w: int=8, c: int = 3) -> tf.Tensor:\r\n shape = tf.shape(x)\r\n x0 = tf.random.uniform([], 0, shape[0] + 1 - h, dtype=tf.int32)\r\n y0 = tf.random.uniform([], 0, shape[1] + 1 - w, dtype=tf.int32)\r\n \r\n x = replace_slice(x, tf.random.uniform([h, w, c], dtype = tf.float32), [x0, y0, 0])\r\n# x = replace_slice(x, tf.zeros([h, w, c], dtype = tf.float32), [x0, y0, 0])\r\n return x \r\n\r\ndef parser(serialized_example):\r\n \"\"\"Parses a single tf.Example into image and label tensors.\"\"\"\r\n # Dimensions of the images in the CIFAR-10 dataset.\r\n features = tf.parse_single_example(\r\n serialized_example,\r\n features={\r\n 'image': tf.FixedLenFeature([], tf.string),\r\n 'label': tf.FixedLenFeature([], tf.int64),\r\n })\r\n image = tf.decode_raw(features['image'], tf.uint8)\r\n image.set_shape([DEPTH * HEIGHT * WIDTH])\r\n image = normalize(image)\r\n\r\n # Reshape from [depth * height * width] to [depth, height, width].\r\n image = tf.cast(\r\n tf.transpose(tf.reshape(image, [DEPTH, HEIGHT, WIDTH]), [1, 2, 0]),\r\n tf.float32)\r\n label = tf.cast(features['label'], tf.int32)\r\n label = tf.one_hot(label, 10)\r\n\r\n # Custom preprocessing.\r\n\r\n image = crop_pad(image)\r\n image = horizontal_flip(image)\r\n image = cutout(image)\r\n\r\n return image, label \r\n \r\ndef parser_test(serialized_example):\r\n \"\"\"Parses a single tf.Example into image and label tensors.\"\"\"\r\n # Dimensions of the images in the CIFAR-10 dataset.\r\n # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the\r\n # input format.\r\n features = tf.parse_single_example(\r\n serialized_example,\r\n features={\r\n 'image': tf.FixedLenFeature([], tf.string),\r\n 'label': tf.FixedLenFeature([], tf.int64),\r\n })\r\n image = tf.decode_raw(features['image'], tf.uint8)\r\n image.set_shape([DEPTH * HEIGHT * WIDTH])\r\n image = normalize(image)\r\n\r\n image = tf.cast(\r\n tf.transpose(tf.reshape(image, [DEPTH, HEIGHT, WIDTH]), [1, 2, 0]),\r\n tf.float32)\r\n label = tf.cast(features['label'], tf.int32)\r\n label = tf.one_hot(label, 10)\r\n\r\n return image, label \r\n\r\ndef create_Test_dataset(filename_test,batch_size=128):\r\n\tdataset_test = tf.data.TFRecordDataset(filename_test).repeat(1)\r\n\r\n\tdataset_test = dataset_test.map(parser_test, num_parallel_calls=batch_size)\r\n\tdataset_test = dataset_test.shuffle(buffer_size=10000) \r\n\r\n\tdataset_test = dataset_test.batch(batch_size)\r\n\t\r\n\treturn dataset_test\r\n\t\r\ndef create_Train_dataset(filename_train,batch_size=128):\r\n\tdataset_train = tf.data.TFRecordDataset(filename_train)\r\n\tdataset_train = dataset_train.apply(tf.data.experimental.shuffle_and_repeat(50000,1))\r\n\tdataset_train = dataset_train.apply(tf.data.experimental.map_and_batch(parser,batch_size, num_parallel_calls=batch_size))\r\n\tdataset_train = dataset_train.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\r\n\treturn dataset_train\t\r\n\r\n\r\ndef load_data(path):\r\n\tdataset = tf.data.TFRecordDataset(path)\r\n\tdef parser(record):\r\n\t\tfeatures = tf.parse_single_example(\r\n\t\trecord,\r\n\t\tfeatures={\r\n\t\t 'image': tf.FixedLenFeature([], tf.string),\r\n\t\t 'label': tf.FixedLenFeature([], tf.int64),\r\n\t\t})\r\n\t\timage = tf.decode_raw(features['image'], tf.uint8)\r\n\t\timage.set_shape([DEPTH * HEIGHT * WIDTH])\r\n\r\n\t\timage = tf.cast(\r\n\t\ttf.transpose(tf.reshape(image, [DEPTH, HEIGHT, WIDTH]), [1, 2, 0]),\r\n\t\ttf.float32)\r\n\t\tlabel = tf.cast(features['label'], tf.int32)\r\n\t\treturn image, label \r\n\r\n\tdataset = dataset.map(parser)\r\n\tdataset = dataset.batch(50000)\r\n\tdataset = dataset.repeat(1)\r\n\titerator = dataset.make_one_shot_iterator()\r\n\treturn iterator.get_next()\r\n\r\ndef convert_to_numpy(filepath):\r\n\timg_data,img_lbl = load_data(filepath)\r\n\timg_data = img_data.numpy().astype(int)\r\n\timg_lbl = img_lbl.numpy().astype(int)\r\n\treturn img_data, img_lbl\r\n\t\r\nif __name__ == '__main__':\r\n create_Train_dataset()\r\n create_Test_dataset()\r\n","sub_path":"TF_Records/process_tfrecords.py","file_name":"process_tfrecords.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"549017706","text":"import tests\n\n\nclass TestPython(tests.AgileTest):\n config_file = 'tests/configs/python.json'\n\n async def test_simple(self):\n executor = await self.executor(tasks=[\"variables\"])\n await executor.run()\n self.assertEqual(executor.context['random'], 50)\n","sub_path":"tests/test_vars.py","file_name":"test_vars.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"22573202","text":"from bs4 import BeautifulSoup as bs\nimport requests \nimport pandas as pd\nurl=\"https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars\"\npage=requests.get(url)\nsoup=bs(page.text,\"html.parser\")\nstartable=soup.find(\"table\")\ntemplist=[]\ntablerows=startable.find_all('tr')\nfor tr in tablerows:\n td=tr.find_all('td')\n row=[i.text.rstrip() for i in td]\n templist.append(row)\nstarnames=[]\ndistance=[]\nmass=[]\nradius=[]\nlum=[]\nfor i in range(1,len(templist)):\n starnames.append(templist[i][1])\n distance.append(templist[i][3])\n mass.append(templist[i][5])\n radius.append(templist[i][6])\n lum.append(templist[i][7])\ndf2=pd.DataFrame(list(zip(starnames,distance,mass,radius,lum)),columns=['star_name','Distance','Mass','Radius',\"Luminosity\"])\nprint(df2)\ndf2.to_csv('bright_star.csv')","sub_path":"projectwebscraping.py","file_name":"projectwebscraping.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573137239","text":"\"\"\"Play Conway's Game of Life in a curses window.\"\"\"\n\nimport argparse\nimport curses\nimport curses.ascii\nimport itertools\n\nfrom .life import Life, Geometry, GEOMETRIES\n\n# Dead cells are marked by the space character: ' '\n_CH_DEAD = \" \"\n\n# Living cells are marked by the character '@'\n_CH_ALIVE = \"@\"\n\n# Program name\n_PROGRAM = \"python -m life\"\n\n# Program description\n_DESCRIPTION = \"Conway's Game of Life on compact surfaces.\"\n\n# Command line argument parsing\nparser = argparse.ArgumentParser(prog=_PROGRAM, description=_DESCRIPTION)\n\nparser.add_argument(\"--geometry\", type=str, choices=GEOMETRIES,\n default=Geometry.TORUS, help=\"specify the board geometry\")\nparser.add_argument(\"--prob\", type=float, default=0.25,\n help=\"probability of a cell starting out alive\")\nparser.add_argument(\"--seed\", type=int, default=None,\n help=\"pseudo-random number generator seed\")\nparser.add_argument(\"--delay\", type=int, default=60,\n help=\"number of milliseconds to pause between states\")\nparser.add_argument(\"--draw\", action=\"store_true\", help=\"draw the initial board before playing\")\n\n\ndef draw_cell(screen, life, row, col):\n \"\"\"Draw a cell on the life board.\"\"\"\n cell_marker = _CH_ALIVE if life.state[row, col] else _CH_DEAD\n try:\n screen.addch(row, col, cell_marker)\n except curses.error:\n pass\n\n\ndef draw_board(screen, life):\n \"\"\"Draw the entire game of life board.\"\"\"\n for row, col in itertools.product(range(life.n_rows), range(life.n_cols)):\n draw_cell(screen, life, row, col)\n\n\ndef move_cursor_up(life, row, col):\n \"\"\"Move the cursor up if possible.\"\"\"\n if row > 0:\n row -= 1\n else:\n if life.geometry in (Geometry.TORUS, Geometry.KLEIN_BOTTLE):\n row = life.n_rows - 1\n elif life.geometry == Geometry.PROJECTIVE_PLANE:\n row = life.n_rows - 1\n col = life.n_cols - col - 1\n else:\n curses.flash()\n\n return row, col\n\n\ndef move_cursor_down(life, row, col):\n \"\"\"Move the cursor down if possible.\"\"\"\n if row < life.n_rows - 1:\n row += 1\n else:\n if life.geometry in (Geometry.TORUS, Geometry.KLEIN_BOTTLE):\n row = 0\n elif life.geometry == Geometry.PROJECTIVE_PLANE:\n row = 0\n col = life.n_cols - col - 1\n else:\n curses.flash()\n\n return row, col\n\n\ndef move_cursor_left(life, row, col):\n \"\"\"Move the cursor left if possible.\"\"\"\n if col > 0:\n col -= 1\n else:\n if life.geometry in (Geometry.CYLINDER, Geometry.TORUS):\n col = life.n_cols - 1\n elif life.geometry in (Geometry.MOBIUS_STRIP, Geometry.KLEIN_BOTTLE,\n Geometry.PROJECTIVE_PLANE):\n col = life.n_cols - 1\n row = life.n_rows - row - 1\n else:\n curses.flash()\n\n return row, col\n\n\ndef move_cursor_right(life, row, col):\n \"\"\"Move the cursor right if possible.\"\"\"\n if col < life.n_cols - 1:\n col += 1\n else:\n if life.geometry in (Geometry.CYLINDER, Geometry.TORUS):\n col = 0\n elif life.geometry in (Geometry.MOBIUS_STRIP, Geometry.KLEIN_BOTTLE,\n Geometry.PROJECTIVE_PLANE):\n col = 0\n row = life.n_rows - row - 1\n else:\n curses.flash()\n\n return row, col\n\n\ndef main(stdscr, *, geometry, prob, seed, delay, draw):\n \"\"\"Game of Life driver function.\n\n Parameters\n ----------\n stdscr : curses.window\n The main curses window.\n\n geometry : str\n The Game of Life board geometry.\n\n prob : float\n Probability of a cell starting out alive.\n\n seed : int, array-like, or None\n Seed for the pseudo-random number generator.\n\n delay : int\n Number of milliseconds to pause between consecutive board states.\n\n draw : bool\n Whether to manually draw the initial board (if True) or randomly generate an initial board\n (if False).\n \"\"\"\n # Clear the screen\n stdscr.clear()\n\n # Get the full dimensions of the screen\n n_rows, n_cols = stdscr.getmaxyx()\n\n # Create a Game of Life instance to be played\n life = Life(n_rows, n_cols, geometry=geometry, prob=prob, seed=seed)\n\n # Initialize the board\n if draw:\n # Make the cursor extra visible and put it in the center of the board.\n curses.curs_set(2)\n cursor_row = life.n_rows // 2 + 1\n cursor_col = life.n_cols // 2\n stdscr.move(cursor_row, cursor_col)\n\n while True:\n # Wait for input from the user.\n c = stdscr.getch()\n\n if curses.ascii.isblank(c):\n # Stop drawing when is pressed\n break\n elif curses.ascii.isspace(c):\n # If the user pressed , toggle the cell under the cursor\n life.toggle_cell(cursor_row, cursor_col)\n draw_cell(stdscr, life, cursor_row, cursor_col)\n elif c == curses.KEY_UP:\n # Move the cursor up if possible\n cursor_row, cursor_col = move_cursor_up(life, cursor_row, cursor_col)\n elif c == curses.KEY_DOWN:\n # Move the cursor down if possible\n cursor_row, cursor_col = move_cursor_down(life, cursor_row, cursor_col)\n elif c == curses.KEY_LEFT:\n # Move the cursor left if possible\n cursor_row, cursor_col = move_cursor_left(life, cursor_row, cursor_col)\n elif c == curses.KEY_RIGHT:\n # Move the cursor right if possible\n cursor_row, cursor_col = move_cursor_right(life, cursor_row, cursor_col)\n elif curses.ascii.isalpha(c) and chr(c) in \"rR\":\n # If the user presses the 'R' key, randomize the board\n life.randomize()\n draw_board(stdscr, life)\n elif curses.ascii.isalpha(c) and chr(c) in \"qQ\":\n # If the user presses the 'Q' key, exit\n return\n elif c == curses.KEY_RESIZE:\n # If the user resizes the window, exit\n return\n else:\n # TODO: add more functionality (e.g., help menu)\n pass\n\n # Move the cursor to a potentially new location\n stdscr.move(cursor_row, cursor_col)\n else:\n # Bypass drawing the board manually\n life.randomize()\n\n # Hide the cursor\n curses.curs_set(0)\n\n # Don't wait for the user to enter anything\n stdscr.timeout(0)\n\n while True:\n try:\n draw_board(stdscr, life)\n curses.delay_output(delay)\n life.evolve()\n c = stdscr.getch()\n if c != -1:\n break\n except KeyboardInterrupt:\n break\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n curses.wrapper(main, geometry=args.geometry, prob=args.prob, seed=args.seed,\n delay=args.delay, draw=args.draw)\n","sub_path":"life/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"577889537","text":"import random\nimport aiohttp\n\nimport discord\nfrom discord.ext import commands\nfrom help.help import help, handle_error, help_category\n\n\nclass Xkcd(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @help(\n brief=\"Ruft einen xkcd Comic ab\",\n syntax=\"!xkcd \",\n parameters={\n \"number\": \"*(optional)* Entweder die Nummer eines spezifischen xkcd Comics, oder `latest`, für den aktuellsten\",\n },\n )\n @commands.command(name=\"xkcd\")\n async def cmd_xkcd(self, ctx, number=None):\n\n async with aiohttp.ClientSession() as session:\n\n # Daten vom aktuellsten Comic holen, um max zu bestimmen\n async with session.get('http://xkcd.com/info.0.json') as request:\n data = await request.json()\n max = data['num']\n\n # Nummer übernehmen wenn vorhanden und zwischen 1 und max, sonst random Nummer wählen\n if number == 'latest':\n n = max\n else:\n try:\n n = number if (number and 0 < int(number) <= max) else str(random.randint(1, max))\n except ValueError:\n n = str(random.randint(1, max))\n\n # Daten zum Bild holen\n async with session.get(f'http://xkcd.com/{n}/info.0.json') as request:\n n_data = await request.json()\n\n img = n_data['img']\n num = n_data['num']\n title = n_data['title']\n text = n_data['alt']\n\n # Comic embedden\n e = discord.Embed()\n e.set_image(url=img)\n e.url = img\n e.title = f'xkcd #{num}'\n e.add_field(name=title, value=text)\n e.set_footer(text='https://xkcd.com', icon_url='https://xkcd.com/s/0b7742.png')\n\n await ctx.send(embed=e)\n","sub_path":"xkcd.py","file_name":"xkcd.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"364013559","text":"import pygame, glob\n\nanimationDirections = ['UP', 'BACKLEFT', 'LEFT', 'FRONTLEFT', 'FRONT', 'FRONTRIGHT', 'RIGHT', 'BACKRIGHT']\n\n#do not touch!!! (ask me why)\nclass GameSprite(object):\n\n def __init__(self, path, positions):\n self.frameDict = {}\n \n for pos in positions:\n for dir in animationDirections:\n self.frameDict.update({pos+'_'+dir:self.getImages(path, pos+'_'+dir)})\n \n def getImages(self, path, subPath):\n surfaces = []\n \n for f in glob.glob(path+subPath+\"/*.png\"):\n # print f\n surfaces.append(pygame.image.load(f))\n surfaces[-1].convert_alpha()\n \n temp = list(surfaces)\n \n if len(temp):\n temp.pop()\n temp.reverse()\n temp.pop()\n \n return surfaces+temp\n \n def getFrames(self, position, direction):\n return self.frameDict[position+'_'+animationDirections[direction]]","sub_path":"animations.py","file_name":"animations.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"638047495","text":"import pytest\n\nfrom flake8_aaa.block import Block\nfrom flake8_aaa.exceptions import EmptyBlock\nfrom flake8_aaa.types import LineType\n\n\ndef test_none():\n \"\"\"\n Block must have nodes\n \"\"\"\n block = Block([], LineType.act)\n\n with pytest.raises(EmptyBlock):\n block.get_span(13)\n\n\n@pytest.mark.parametrize(\n 'code_str', [\n '''\n# Check first token and last token line numbers of the first and last lines\n# (which span multiple lines). The whole test body is passed into the block.\n\ndef test(): # Line 5\n x = (\n 1,\n 2,\n )\n\n result = x + (3, 4)\n\n assert result == (\n 1,\n 2,\n 3,\n 4,\n ) # Line 18\n'''\n ]\n)\ndef test(first_node_with_tokens):\n block = Block(first_node_with_tokens.body, LineType._assert)\n\n result = block.get_span(5)\n\n assert result == (1, 13)\n","sub_path":"tests/block/test_get_span.py","file_name":"test_get_span.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508948767","text":"\"\"\"Math functions for calculator.\"\"\"\n\n\ndef add(input_list):\n \"\"\"Return the sum of the two input integers.\"\"\"\n sum_num = 0\n for number in input_list:\n sum_num = sum_num + number\n return sum_num\n\ndef subtract(input_list):\n \"\"\"Return the second number subtracted from the first.\"\"\"\n\n difference = input_list[0]\n for number in input_list[1:]:\n difference = difference - number\n return difference\n\ndef multiply(input_list):\n \"\"\"Multiply the two inputs together.\"\"\"\n product = input_list[0]\n for number in input_list[1:]:\n product = product * number\n return product\n\ndef divide(input_list):\n \"\"\"Divide the first input by the second, returning a floating point.\"\"\"\n quotient = input_list[0]\n for number in input_list[1:]:\n quotient = quotient / number\n return quotient\n\ndef square(input_list):\n \"\"\"Return the square of the input.\"\"\"\n square_list = []\n for number in input_list:\n square_list.append(number ** 2)\n return square_list\n\ndef cube(input_list):\n \"\"\"Return the cube of the input.\"\"\"\n cube_list = []\n for number in input_list:\n cube_list.append(number ** 3)\n return cube_list\n\ndef power(input_list):\n \"\"\"Raise num1 to the power of num2 and return the value.\"\"\"\n total = input_list[0]\n for number in input_list[1:]:\n total = total ** number\n return total\n\n# def mod(input_list):\n# \"\"\"Return the remainder of num1 / num2.\"\"\"\n# return int(num1)% int(num2)\n\n\n# num1 = 10\n# num2 = 3\n# num3 = 2\n# print add(num1, num2)\n# print subtract(num1, num2)\n# print multiply(num1, num2)\n# print divide(num1, num2)\n# print square(num1)\n# print cube(num1)\n# print power(num1, num2)\n# print mod(num1, num2)\n# print add_mult(num1, num2, num3)\n# print add_cubes(num1, num2)\n","sub_path":"arithmetic.py","file_name":"arithmetic.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"560921217","text":"import secrets\nfrom django.db import models\nfrom django.contrib.auth import get_user_model\nfrom graphql import GraphQLError\nimport graphene\nfrom graphene_django import DjangoObjectType\nfrom graphene_file_upload.scalars import Upload\nfrom user.graphql.types import UserType\nfrom system.graphql.mutation import create_system_image\nfrom .types import InviteType\nfrom ..models import Invite\n\n\nclass CreateInvite(graphene.Mutation):\n created_invitation = graphene.Field(InviteType)\n\n class Arguments:\n first_name = graphene.String(required=True)\n last_name = graphene.String(required=True)\n email = graphene.String(required=False)\n phone = graphene.String(required=False)\n note = graphene.String(required=False)\n avatar_image = Upload(required=False)\n\n def mutate(self, info, first_name, last_name, email, phone, note):\n sponsor = info.context.user\n users = get_user_model().objects.all()\n for user in users:\n if user.email == email:\n raise GraphQLError('This email already has an account')\n elif user.phone_number == phone:\n raise GraphQLError(\n 'This phone number is already attached to an account')\n else:\n pass\n\n else:\n avatar = None\n\n invite = Invite.objects.create(\n token=secrets.token_urlsafe(20),\n first_name=first_name,\n last_name=last_name,\n email=email,\n phone_number=phone,\n note=note,\n avatar=avatar,\n sponsor=sponsor.id,\n )\n invite.save()\n sponsor_invites = sponsor.invites.add(invite)\n return CreateInvite(created_invitation=invite)\n\n\nclass CreateInviteMutation(graphene.ObjectType):\n create_invite = CreateInvite.Field()\n\n\nclass ClaimInvite(graphene.Mutation):\n invite = graphene.Field(InviteType)\n\n class Arguments:\n invite_token = graphene.String()\n\n def mutate(self, info, invite_token):\n try:\n invite = Invite.objects.get(token=invite_token)\n if invite.is_expired():\n invite.delete()\n raise graphene.GraphQLError('Your Invite has expired')\n except invite.DoesNotExist:\n raise graphene.GraphQLError('This is not a valid Invite code')\n return ClaimInvite(invite=invite)\n\n\nclass ClaimInviteMutation(graphene.ObjectType):\n claim_invite = ClaimInvite.Field()\n\n\nclass UpdateInvite(graphene.Mutation):\n invite = graphene.Field(InviteType)\n\n class Arguments:\n invite_id = graphene.String()\n first_name = graphene.String()\n last_name = graphene.String()\n email = graphene.String()\n phone_number = graphene.String()\n avatar_image = Upload(required=False)\n\n def mutate(self, info, invite_id, first_name, last_name, email, phone_number, avatar_image):\n try:\n invite = Invite.objects.get(id=invite_id)\n except invite.DoesNotExist:\n raise graphene.GraphQLError('Looks like this invite is invalid')\n if first_name:\n invite.first_name = first_name\n if last_name:\n invite.last_name = last_name\n if email:\n invite.email = email\n if phone_number:\n invite.phone_number = phone_number\n if avatar_image:\n image = create_system_image(info, avatar_image, post_id=None)\n invite.avatar = image\n invite.save()\n return UpdateInvite(invite=invite)\n\n\nclass UpdateInviteMutation(graphene.ObjectType):\n update_invite = UpdateInvite.Field()\n\n\nclass DeleteInvite(graphene.Mutation):\n is_deleted = graphene.Boolean()\n\n class Arguments:\n invite_id = graphene.ID()\n\n def mutate(self, info, invite_id):\n invite = Invite.objects.filter(id=invite_id)\n invite.delete()\n return DeleteInvite(is_deleted=True)\n\n\nclass DeleteInviteMutation(graphene.ObjectType):\n delete_invite = DeleteInvite.Field()\n\n\nclass CreateUserFromInvite(graphene.Mutation):\n user = graphene.Field(UserType)\n\n class Arguments:\n invite_id = graphene.String()\n username = graphene.String()\n password = graphene.String()\n\n def mutate(self, info, invite_id, username, password):\n try:\n invite = Invite.objects.get(id=invite_id)\n new_user = get_user_model()(\n username=username,\n email=invite.email,\n phone_number=invite.phone_number,\n first_name=invite.first_name,\n last_name=invite.last_name,\n sponsor=invite.sponsor\n )\n new_user.set_password(password)\n new_user.save()\n profile = new_user.profile\n profile.profile_avatar = invite.avatar\n profile.save()\n invite.delete()\n except invite.DoesNotExist:\n raise graphene.GraphQLError(\n 'The invite you are trying to access is invalid')\n\n return CreateUserFromInvite(user=new_user)\n\n\nclass CreateUserFromInviteMutation(graphene.ObjectType):\n create_user_from_invite = CreateUserFromInvite.Field()\n","sub_path":"invites/graphql/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"561360562","text":"\"\"\"OpenAPI core contrib flask views module\"\"\"\nfrom flask.views import MethodView\n\nfrom openapi_core.contrib.flask.decorators import FlaskOpenAPIViewDecorator\nfrom openapi_core.contrib.flask.handlers import FlaskOpenAPIErrorsHandler\nfrom openapi_core.validation.request.validators import RequestValidator\nfrom openapi_core.validation.response.validators import ResponseValidator\n\n\nclass FlaskOpenAPIView(MethodView):\n \"\"\"Brings OpenAPI specification validation and unmarshalling for views.\"\"\"\n\n openapi_errors_handler = FlaskOpenAPIErrorsHandler\n\n def __init__(self, spec):\n super().__init__()\n self.request_validator = RequestValidator(spec)\n self.response_validator = ResponseValidator(spec)\n\n def dispatch_request(self, *args, **kwargs):\n decorator = FlaskOpenAPIViewDecorator(\n request_validator=self.request_validator,\n response_validator=self.response_validator,\n openapi_errors_handler=self.openapi_errors_handler,\n )\n return decorator(super().dispatch_request)(*args, **kwargs)\n","sub_path":"openapi_core/contrib/flask/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"455109786","text":"# !/usr/bin/python\n\n#F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)\n# 树形递归\ndef fib(n):\n if n == 2 or n ==1 :\n return 1\n else:\n return fib(n-1) + fib(n-2)\nprint(fib(11))\n\n#//尾递归就是操作的最后一步是调用自身的递归\n#递归非常耗费内存,因为需要同时保存成千上百个调用记录,很容易发生\"栈溢出\"错误(stack overflow)\n# 。但对于尾递归来说,由于只存在一个调用记录,所以永远不会发生\"栈溢出\"错误。\ndef fibs(n, a = 0, b = 1):\n if n == 0:\n return a\n if n == 1:\n return b\n print(\"n =%d and nub = %d tatal = %d\" %(n,a,b))\n return fibs(n-1,b,a+b);\n\n#print(fibs(9))\n\n#迭代循环\n#迭代是将输出做为输入,再次进行处理。比如将摄像头对着显示器;比如镜子对着镜子\ndef fib_iteration(n):\n if n == 1 or n == 2:\n return 1\n\n result = prev_reslut = 1\n next_result = 0\n i = 2\n while( i < n ):\n i += 1\n next_result = prev_reslut \n prev_reslut = result\n result = prev_reslut + next_result\n return result\n\nprint(fib_iteration(106)) \n\n# 阶乘\ndef factorial(n):\n if n == 0 :\n return 1\n else:\n print(\" %d * factorial(%d -1) \" % (n,n ))\n return n * factorial(n -1) #// 最后一步不是调用自身,因此不是尾递归\n#最多需要保存n个调用记录,复杂度 O(n)\ndef tail_factorial(n,tail=1):\n if n == 0:\n return tail\n return tail_factorial(n -1 ,tail * n ) \n#如果改写成尾递归,只保留一个调用记录,复杂度 O(1) \n\n\n ","sub_path":"python_100_exercise/6_fibonacci.py","file_name":"6_fibonacci.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"385954197","text":"import numpy as np\nimport sys\nimport time\nfrom sklearn.preprocessing import scale\n\nfrom cluster.selfrepresentation import ElasticNetSubspaceClustering, SparseSubspaceClusteringOMP\nfrom gen_union_of_subspaces import gen_union_of_subspaces\nfrom metrics.cluster.accuracy import clustering_accuracy\nfrom sklearn import cluster\n\n# =================================================\n# 载入独立子空间数据集 并三维可视化\n# =================================================\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom gen_union_of_subspaces import gen_union_of_subspaces\n\nambient_dim = 9\nsubspace_dim = 6\nnum_subspaces = 5\nnum_points_per_subspace = 50\n\nX, y_true = gen_union_of_subspaces(ambient_dim, subspace_dim, num_subspaces, num_points_per_subspace, 0.00)\ny_true = y_true.reshape(250)\nX = scale(X)\nfig = plt.figure()\nax1 = Axes3D(fig)\nax1.scatter3D(X[:,1],X[:,2],X[:,3], c=y_true) #绘制散点图\nax1.legend\n# plt.savefig(\"unsp1.png\",bbox_inches='tight')\nplt.show()\n\n# ================================================================================\n# 定义二维带标签可视化函数\n# ================================================================================\nimport matplotlib.pyplot as plt\nimport matplotlib.patheffects as PathEffects\n# We import seaborn to make nice plots.\nimport seaborn as sns\nsns.set_style('darkgrid')\nsns.set_palette('muted')\nsns.set_context(\"notebook\", font_scale=1.5,\n rc={\"lines.linewidth\": 2.5})\n\ndef scatter(x, colors, title = None, label = True):\n # We choose a color palette with seaborn.\n palette = np.array(sns.color_palette(\"hls\", 5))\n\n # We create a scatter plot.\n f = plt.figure(figsize=(8,8))\n\n ax = plt.subplot(aspect='equal')\n sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40,\n c=palette[colors.astype(np.int)])\n plt.xlim(-25, 25)\n plt.ylim(-25, 25)\n ax.axis('off')\n ax.axis('tight')\n\n # We add the labels for each digit.\n txts = []\n if label == True:\n for i in range(5):\n # Position of each label.\n xtext, ytext = np.median(x[colors == i, :], axis=0)\n txt = ax.text(xtext, ytext, str(i), fontsize=24)\n txt.set_path_effects([\n PathEffects.Stroke(linewidth=5, foreground=\"w\"),\n PathEffects.Normal()])\n txts.append(txt)\n if title != None:\n tit = plt.title(title)\n else: tit = None\n return f, ax, sc, txts, tit\n\n\n# ========================================================================\n# t-SNE + k-means 聚类效果\n# =========================================================================\nfrom sklearn.manifold import TSNE\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import adjusted_rand_score as ari\nRS = 1\nt_3 = time.time()\ntsne_proj = TSNE(random_state=RS, perplexity= 15).fit_transform(X)\nprint(tsne_proj.shape)\nt_4 = time.time()\nax1 = scatter(tsne_proj, y_true, \"t-SNE visualization of raw data\")\n# plt.savefig('unsp2.png',bbox_inches='tight')\nplt.show()\n\n\ncalinski = []\n# k-means 测试选取最佳聚类数\n\nfor i in range(1,10):\n y_pred = KMeans(n_clusters=i, random_state=9).fit_predict(tsne_proj)\n score = ari(y_true, y_pred)\n calinski.append(score)\n\nfig = plt.figure()\nax =fig.add_subplot(1,1,1)\nax.plot(range(1, 10), calinski)\nax.set_xlabel('n_cluster')\nax.set_ylabel('CHS')\nplt.show() #观察选取最佳聚类数\n# plt.savefig('wtrend.png', bbox_inches = 'tight')\n\nt_1 = time.time()\ntsne_pred = KMeans(n_clusters=5, random_state=9).fit_predict(tsne_proj) #k-means 结果\nt_2 = time.time()\ntsne_t = t_2-t_1 +t_4-t_3 #计算运行时间\n\nax2 = scatter(tsne_proj, tsne_pred, \"clustering result of t-SNE\") #可视化聚类结果\nplt.show()\n# plt.savefig('sne_mn.png')\n# =================================================================================\n# PCA+ kmeans 和直接 k-means 聚类效果与可视化\n# =================================================================================\nfrom sklearn.decomposition import PCA\nfrom sklearn import metrics\nchs = metrics.calinski_harabasz_score\n\npca = PCA(n_components=6)\npca.fit(X)\nprint(pca.explained_variance_ratio_)\npca = PCA(n_components=0.95)\npca.fit(X)\nprint(pca.n_components_)\n\nratiorange = np.arange(0.5, 1, 0.01)\nncomp = []\nfor r in ratiorange:\n pca = PCA(n_components=r)\n pca.fit(X)\n k = pca.n_components_\n ncluster = ncomp.append(k)\n\nfig = plt.figure()\nax =fig.add_subplot(1,1,1)\nax.plot(ncomp, ratiorange)\nax.set_xlabel('n_components')\nax.set_ylabel('variance ratio')\nplt.show() #观察选取最佳维数\n# plt.savefig('upca.png', bbox_inches='tight')\n\n\npca = PCA(n_components=7).fit(X)\nt1 = time.time()\npca_pred = KMeans(init=pca.components_, n_clusters=7, n_init=1).fit(X)\npca_pred = pca_pred.labels_\nt2 = time.time()\nkm_pred = KMeans(init='random', n_clusters=5, n_init=10).fit(X)\nkm_pred = km_pred.labels_\n#这里调用传统KMeans算法\nt3 = time.time()\npca_t = t2-t1\nkm_t = t3-t2\n\n# pca_proj2 = PCA(n_components=2).transform(X)\n# pca_pred2 = KMeans(n_clusters=10, random_state=9).fit_predict(pca_proj2)\n\nreduced_data = PCA(n_components=5).fit_transform(X)\nkmeans = KMeans(init='k-means++', n_clusters=5, n_init=5)\nkmeans.fit(reduced_data)\npca_pred2 = kmeans.labels_\n# scatter(reduced_data, pca_pred2, \"clustering result of PCA\")\n# plt.show()\n# plt.savefig('pca_mn.png')\n\n# ================================================================================\n# 谱聚类\n# ================================================================================\n\nfrom sklearn import metrics\nfrom sklearn.cluster import SpectralClustering\nchs = metrics.calinski_harabasz_score\nfrom sklearn.metrics import adjusted_rand_score as ari\n\n\nneig = np.arange(5, 50, 5)\nychs = []\n\nt1 = time.time()\nsc_pred = SpectralClustering(n_clusters=7,affinity='nearest_neighbors',n_neighbors=6).fit_predict(X)\nt2 = time.time()\nsc_t = t2 - t1\n# ===================================================================\n# 在MATLAB中使用SSC-ADMM求解并将结果载入pycharm\n# =====================================================================\nfrom scipy import io\nfrom numpy import mat\nX_mat = mat(X)\ny_mat = mat(y_true)\nio.savemat(\"unsp.mat\",{\"data\": X_mat, \"target\": y_mat})\n\nssc = io.loadmat('SSC2.mat')\nssc_1 = ssc['ssc']\nssc_pred = ssc_1.reshape(250)\nssc_t = 0\n\n# =================================================================================\n# 最优聚类结果评判与对比\n# ==================================================================================\nfrom sklearn.metrics import adjusted_rand_score as ari\nfrom sklearn import metrics\n\nchs = metrics.calinski_harabasz_score\n\n\n# y_pred =(\n# ('PCA', pca_pred)\n# ('KMeans', km_pred)\n# #('Spectral Clustering',sc_pred)\n# #('t-SNE', tsne_pred)\n# )\n# for name, label_pred in y_pred:\n# ARI = adjusted_rand_score(y_true,label_pred)\n# CHI = metrics.calinski_harabasz_score(X,label_pred)\n#\n# print('算法: {}. ARI: {}. CHI: {}'.format(name, ARI, CHI))\nkm_chs = chs(X, km_pred)\ntsne_chs = chs(X, tsne_pred)\npca_chs = chs(X, pca_pred)\nsc_chs = chs(X, sc_pred)\nssc_chs = chs(X, ssc_pred)\n\npca_ari = ari(y_true, pca_pred)\nkm_ari = ari(y_true, km_pred)\ntsne_ari = ari(y_true, tsne_pred)\nsc_ari = ari(y_true, sc_pred)\nssc_ari = ari(y_true, ssc_pred)\n\nprint('PCA: CHS: {}. ARI: {}. 运行时间: {}'.format(pca_chs, pca_ari, pca_t))\nprint('t-SNE: CHS: {}. ARI: {}. 运行时间: {}'.format(tsne_chs, tsne_ari, tsne_t))\nprint('k-means: CHS: {}. ARI: {}. 运行时间: {}'.format(km_chs, km_ari, km_t))\nprint('谱聚类: CHS: {}. ARI: {}. 运行时间: {}'.format(sc_chs, sc_ari, sc_t))\nprint('SSC-ADMM: CHS: {}. ARI: {}. 运行时间: {}'.format(ssc_chs, ssc_ari, ssc_t))\n\n","sub_path":"test_indepsubspace.py","file_name":"test_indepsubspace.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"460914149","text":"# coding:utf-8\n\nimport pandas as pd\nimport numpy as np\nimport urllib.request\nimport json\nimport re\nimport time\nimport lxml\nimport pymysql\nimport math\n\n\nfrom lxml.html import tostring\nfrom base_func import getDist, getFileNameList, is_line_cross\nfrom bridge import Bridge\nfrom emergency import Emergency\nfrom traffic import Traffic\nfrom weather import Weather\nfrom port import Port\n\n\n####################################################\n\n# xpath爬取网页数据,中文解码\ndef _callback(matches):\n id = matches.group(1)\n try:\n return chr(int(id))\n except:\n return id\n\n\ndef decode_unicode_references(data):\n return re.sub(\"&#(\\d+)(;|(?=\\s))\", _callback, str(data))\n\n\ndef coordinates_kml(file_path):\n \"\"\"\n 从kml文件中获取经纬度数据\n :param file_path: kml文件所在路径,类型:string\n :return: 经纬坐标,用“;”分割,类型:list\n \"\"\"\n # 打开kml文件\n kml_file = open(file_path, \"r\")\n\n # 将kml中的文件转换成string后,将经纬度坐标信息转换成list\n kml_string = kml_file.read()\n coordinates_string = kml_string.split(\"\")[1]\\\n .split(\"\")[0]\\\n .replace(\"\\t\", \"\") \\\n .replace(\"\\n\", \"\")\n coordinates_list = coordinates_string.split(\" \")\n out_put_coordinates_list = []\n for coordinate in coordinates_list:\n if coordinate:\n tmp_coordinate = coordinate.split(\",\")\n out_put_coordinates_list.append([tmp_coordinate[0], tmp_coordinate[1]])\n return out_put_coordinates_list\n\n\ndef point_poly(pointLon, pointLat, polygon):\n \"\"\"\n 判断点是否在多边形内\n :param pointLon: 该点的经度,类型:float\n :param pointLat: 该点的唯独,类型:float\n :param polygon: 多边形的经纬度坐标列表,类型:list\n :return: t/f\n \"\"\"\n polygon = np.array(polygon)\n polygon = np.array([[float(x) for x in line] for line in polygon])\n cor = len(polygon)\n i = 0\n j = cor - 1\n inside = False\n while (i < cor):\n if ((((polygon[i, 1] < pointLat) & (polygon[j, 1] >= pointLat))\n | ((polygon[j, 1] < pointLat) & (polygon[i, 1] >= pointLat)))\n & ((polygon[i, 0] <= pointLon) | (polygon[j, 0] <= pointLon))):\n a = (polygon[i, 0] +\n (pointLat - polygon[i, 1]) / (polygon[j, 1] - polygon[i, 1]) *\n (polygon[j, 0] - polygon[i, 0]))\n\n if (a < pointLon):\n inside = not inside\n j = i\n i = i + 1\n return inside\n\n\ndef get_paint_data(ys_ais_df):\n \"\"\"\n 获取作图数据\n :param ys_ais_df: 洋山AIS数据,类型data frame\n :return: mmsi船舶的mmsi号,类型data frame\n \"\"\"\n print(\"all mmsi length is %d\" % len(list(set(ys_ais_df[\"unique_ID\"]))))\n gdf = ys_ais_df.groupby(\"unique_ID\")\n\n mmsiList = []\n for key, group in gdf:\n if (len(group) > 500) & (len(group) < 1000):\n # print(key)\n mmsiList.append(key)\n mmsiDF = pd.DataFrame(mmsiList)\n print(\"paint mmsi length is %d \" % len(mmsiDF))\n mmsiDF.columns = [\"mmsi\"]\n return mmsiDF\n\n\ndef move_time_axis(ys_ais_data, max_time=14400):\n \"\"\"\n 移动时间轴\n :param ys_ais_data: 警戒区内的AIS数据,类型data frame\n :param max_time: 若移动时间轴后,时间仍然过大,则设置最大时间再次移动时间轴,类型:int\n :return: 移动过时间轴后的警戒区内AIS数据,类型list\n \"\"\"\n ys_ais_data = ys_ais_data.sort_values(by=[\"unique_ID\", \"acquisition_time\"])\n ys_ais_data = np.array(ys_ais_data)\n moved_list = []\n index = 0\n group = 0\n while index < len(ys_ais_data):\n if index == 0:\n str_time = ys_ais_data[index][1]\n else:\n if ys_ais_data[index][0] != ys_ais_data[index - 1][0]:\n group = group_num\n group += 1\n str_time = ys_ais_data[index][1]\n new_time = int(ys_ais_data[index][1] - str_time)\n now_count = new_time // max_time\n new_time = new_time % max_time\n group_num = group + now_count\n moved_list.append([group_num, new_time,\n ys_ais_data[index][2], ys_ais_data[index][3]])\n index += 1\n return moved_list\n\n\ndef diff_enter_out_stage(ys_ais, area_poly, group_num):\n \"\"\"\n 利用主巷道的多边形范围,判���船舶进出多边形的航段\n :param ys_ais: 洋山的AIS数据,类型:data frame\n :param area_poly: 主航道多边形经纬度数据,类型:list\n :param group_num: 船舶分组序号,类型:int\n :return: 将unique_ID变为group来区分,进出多边形的航段,类型:data frame\n \"\"\"\n # 将ais数据data frame转换为矩阵\n ys_ais = np.array(ys_ais)\n\n # 初始化在多边形内的航段索引\n inside_stage_index = []\n tmp_index = []\n\n # 将ais数据中的数据转换为数值类型\n ais = [[float(x) for x in inner] for inner in ys_ais]\n\n # 对时间轴进行排序\n ais.sort(key=lambda y: y[1])\n\n # 特殊判断:判断第一条数据是否在多边形内\n pre_point_bool = point_poly(ais[0][2], ais[0][3], area_poly)\n\n # 判断:若ais数据条数大于或等于2条时,才进行找航段操作\n if len(ais) > 1:\n # 从第一条数据开始循环判断,直到倒数第二条\n for i in range(0, len(ais) - 1):\n # 判断当前ais数据与下条ais数据是否在多边形内\n i_point_bool = pre_point_bool\n ip1_point_bool = point_poly(ais[i + 1][2], ais[i + 1][3], area_poly)\n\n # 判断:若有一条在多边形内,则记录当前行所在的索引\n if i_point_bool | ip1_point_bool:\n tmp_index.append(i)\n\n # 判断:若当前已经循环到倒数第三条\n if i == (len(ais) - 2):\n # 判断:是否存在在多边形内的航段\n if len(tmp_index) != 0:\n # 将最后一条数据进行输出,并清空暂存航段\n tmp_index.append(i + 1)\n inside_stage_index.append(tmp_index)\n tmp_index = []\n else:\n if len(tmp_index) != 0:\n tmp_index.append(i)\n inside_stage_index.append(tmp_index)\n tmp_index = []\n pre_point_bool = ip1_point_bool\n\n elif len(ais) == 2:\n if pre_point_bool:\n tmp_index.append(0)\n tmp_index.append(1)\n inside_stage_index.append(tmp_index)\n\n out_put_list = []\n for index, x in enumerate(inside_stage_index):\n str_time = ys_ais[x[0]][1]\n for inside_index in x:\n out_put_list.append([group_num, ys_ais[inside_index][1] - str_time,\n ys_ais[inside_index][2], ys_ais[inside_index][3]])\n group_num += 1\n return out_put_list, group_num\n\n\ndef enter_circle_ais(ys_ais, pre_time=5400, aft_time=5400):\n \"\"\"\n 找出进入过警戒范围的ais数据,并追溯其进入前与离开后1.5小时的ais数据\n :param ys_ais: 洋山水域范围内的ais数据,类型:data frame\n :param pre_time: 进入前追溯的时间,单位:秒,类型:int\n :param aft_time: 离开后追溯的时间,单位:秒,类型:int\n :return: 进入过警戒范围的ais数据,并追溯其进入前与离开后1.5小时的ais数据,类型:data frame\n \"\"\"\n entered_circle_ais_array = []\n # 对ys_ais进行分组\n ys_ais_gdf = ys_ais.groupby('unique_ID')\n\n # 若存在进入过警戒区,则追溯其进入前与离开后1.5小时的ais数据\n for key, value in ys_ais_gdf:\n print(\"mmsi = %d\" % key)\n group_ais_array = np.array(value)\n # 对单船ais数据按时间维度进行排序\n # group_ais_array = group_ais_array[group_ais_array[:, 1].argsort()]\n\n # 循环每行,找到在警戒范围内的数据点,并追溯\n group_ais_index = 0\n while group_ais_index < len(value):\n # 计算当前ais数据点与警戒范围中心的距离,单位:km\n dst_center = getDist(lon1=group_ais_array[group_ais_index, 2], lat1=group_ais_array[group_ais_index, 3],\n lon2=122.1913, lat2=30.5658)\n\n # 判断是否在警戒范围内\n if dst_center < 1.852*2.0: # 若在境界范围内,记录进入时间\n # 记录进入时间\n enter_time = int(group_ais_array[group_ais_index, 1])\n else: # 若不在境界范围内,循环下条\n group_ais_index += 1\n continue\n\n # 找出进入警戒范围前、后1.5小时的ais数据索引,下次循环的索引\n entered_circle_ais_one_stage = group_ais_array[(group_ais_array[:, 1] <= enter_time + aft_time) &\n (group_ais_array[:, 1] >= enter_time - pre_time)]\n entered_circle_ais_array.extend(entered_circle_ais_one_stage)\n max_time_one_stage = np.max(entered_circle_ais_one_stage[:, 1])\n group_ais_index = np.max(np.where(group_ais_array[:, 1] == max_time_one_stage)) + 1\n return entered_circle_ais_array\n\n\ndef inside_poly_ais(ys_ais, area_poly, group_num):\n \"\"\"\n 找出在多边形内的AIS数据\n :param ys_ais: 洋山的AIS数据,类型:data frame\n :param area_poly: 主航道多边形经纬度数据,类型:list\n :param group_num: 船舶分组序号,类型:int\n :return: 返回在多边形内的AIS数据,类型:data frame\n \"\"\"\n ys_ais = np.array(ys_ais)\n out_list = []\n\n index = 0\n ais_len = len(ys_ais)\n if ais_len > 1:\n while index < ais_len:\n if point_poly(ys_ais[index][2], ys_ais[index][3], area_poly):\n out_list.append([group_num, ys_ais[index][1], ys_ais[index][2],\n ys_ais[index][3]])\n else:\n str_time = 0\n group_num += 1\n index += 1\n return out_list, group_num\n\n\ndef get_ais_inside_circle(ys_ais, center, radius=1.852 * 20):\n \"\"\"\n 找到在警戒区内,进入过警戒范围圆形的AIS数据\n :param ys_ais: 洋山的AIS数据,类型:data frame\n :param center: 圆形警戒范围的圆心坐标,类型:list\n :param radius: 圆形警戒范围的半径,单位,海里。类型:float\n :return: 在警戒范围内的出现过的船舶MMSI,类型:list\n \"\"\"\n ys_ais = np.array(ys_ais)\n\n out_mmsi = []\n for line in ys_ais:\n dst = getDist(line[2], line[3], center[0], center[1])\n if dst < radius:\n out_mmsi.append(line[0])\n return list(set(out_mmsi))\n\n\ndef sub_main_channel(main_channel_ais, enter_poly_df):\n \"\"\"\n 分辨出主航道内的不同航段\n :param main_channel_ais: 主航道内的AIS数据,类型:data frame\n :param enter_poly_df: 航段入口多边形数据,类型:data frame\n :return: 在main_channel_ais的基础上增加一个字段,用于区分主航道内航段,类型:data frame\n \"\"\"\n main_channel_ais_gdf = main_channel_ais.groupby(\"unique_ID\")\n enter_poly_gdf = enter_poly_df.groupby(\"poly_id\")\n sub_channel_ais_list = []\n for key, value in main_channel_ais_gdf:\n value_length = len(value)\n print(key)\n inside_poly_str = \"\"\n inside_poly_id = None\n for index in range(value_length):\n for poly_id, poly in enter_poly_gdf:\n if point_poly(float(value.iloc[index, 2]), float(value.iloc[index, 3]),\n poly):\n # inside_poly_str = inside_poly_str + str(poly_id) + \";\"\n inside_poly_id = poly_id\n break\n sub_channel_ais_list.append([value.iloc[index, 0], value.iloc[index, 1],\n value.iloc[index, 2], value.iloc[index, 3], inside_poly_id])\n return sub_channel_ais_list\n\n\ndef sub_main_channel_poly_filter(warning_area_ais, enter_num, out_num, poly_df):\n \"\"\"\n 在警戒范围内的AIS数据,根据北上,南下,东西,西东航向来区分\n :param warning_area_ais: 警戒范围内的AIS数据\n :param enter_num: 入口编号,类型:int\n :param out_num: 出口编号,类型:int\n :param poly_df: 入口(出口)多边形坐标数据,类型:data frame\n :return: \n \"\"\"\n warning_area_ais_gdf = warning_area_ais.groupby(\"unique_ID\")\n enter_poly_df = poly_df[poly_df[\"poly_id\"] == enter_num]\n out_poly_df = poly_df[poly_df[\"poly_id\"] == out_num]\n other_poly_df = poly_df[(poly_df[\"poly_id\"] != enter_num) & (poly_df[\"poly_id\"] != out_num)]\n\n sub_channel_mmsi = []\n for key, value in warning_area_ais_gdf:\n value_array = np.array(value)\n value_length = len(value)\n mid_idx = value_length // 2\n print(key)\n # 初始化对入口、出口的判断参数,是否进如果其他出入口参数\n enter_bool = False\n out_bool = False\n other_bool = False\n\n if value_length >= 3:\n # 获取其余出入口的编号\n other_poly_id_list = list(set(other_poly_df[\"poly_id\"]))\n\n # 找到入口\n for enter_idx in range(mid_idx):\n # 判断是否进入过入口\n if point_poly(value_array[enter_idx, 2], value_array[enter_idx, 3], enter_poly_df):\n enter_bool = True\n else:\n pass\n\n # 判断是否进如果除出口外的多边形\n for other_poly_id in other_poly_id_list:\n each_other_poly_df = other_poly_df[other_poly_df[\"poly_id\"] == other_poly_id]\n if point_poly(value_array[enter_idx, 2], value_array[enter_idx, 3], each_other_poly_df):\n other_bool = True\n break\n\n # 找到出口\n for out_idx in range(mid_idx, value_length):\n # 判断是否进入过出口多边形\n if point_poly(value_array[out_idx, 2], value_array[out_idx, 3], out_poly_df):\n out_bool = True\n else:\n pass\n\n # 判断是否进入过除入口、出口外其他的多边形\n if not other_bool:\n for other_poly_id in other_poly_id_list:\n each_other_poly_df = other_poly_df[other_poly_df[\"poly_id\"] == other_poly_id]\n if point_poly(value_array[out_idx, 2], value_array[out_idx, 3], each_other_poly_df):\n other_bool = True\n break\n\n # 若满足出口与入口都是指定的编号,则记录mmsi编号\n if (enter_bool & out_bool) & (not other_bool):\n sub_channel_mmsi.append(key)\n\n # 根据获取到的mmsi编号抽取AIS数据\n sub_channel_ais = warning_area_ais[warning_area_ais[\"unique_ID\"].isin(sub_channel_mmsi)]\n return sub_channel_ais\n\n\ndef multiple_poly_list(kml_list):\n \"\"\"\n 从多个kml文件中整合多边形坐标数据\n :param kml_list: kml文件路径列表,类型:list\n :return: 多个多边形坐标数据,类型:data frame\n \"\"\"\n # 获取多个多边形经纬度数据,整合到data frame中\n poly_list = []\n for kml in kml_list:\n coordinates_list = coordinates_kml(kml)\n for line in coordinates_list:\n line.append(int(kml[-5]))\n poly_list.append(line)\n poly_df = pd.DataFrame(poly_list)\n poly_df.columns = [\"longitude\", \"latitude\", \"poly_id\"]\n return poly_df\n\n\ndef sum_ship_warning_area(ys_ais, center, radius=1.852*1, interval=10*60):\n \"\"\"\n 统计洋山警戒范围每10分钟内的船舶数量\n :param ys_ais: 洋山水域范围内的AIS数据,类型:data frame\n :param center: 警戒范围圆心,类型:list\n :param radius: 警戒范围半径,单位:公里,类型:float\n :param interval: 统计间隔时间,单位:秒,类型:int\n :return: 每隔10分钟,警戒范围内的船舶数量,类型:data frame\n \"\"\"\n # 获取数据集中最小的AIS数据时间\n min_time = min(ys_ais[\"acquisition_time\"])\n\n # 对所有AIS数据中的时间字段,减去最小时间\n ys_ais[\"acquisition_time\"] = ys_ais[\"acquisition_time\"] - min_time\n\n # 根据间隔时间进行分段\n ys_ais[\"partition\"] = ys_ais[\"acquisition_time\"] // interval\n\n # 计算每一段中,在警戒范围内的AIS数据条数\n partition_list = list(set(ys_ais[\"partition\"]))\n partition_ship_list = []\n for partition in partition_list:\n print(\"now_partition is %d, all_partition is %d\" % (partition, max(partition_list)))\n sub_partition_array = np.array(ys_ais[ys_ais[\"partition\"] == partition])\n ship_list = []\n for line in sub_partition_array:\n dst = getDist(line[2], line[3], center[0], center[1])\n if dst < radius:\n ship_list.append(line[0])\n ship_count = len(set(ship_list))\n partition_ship_list.append([partition, ship_count])\n\n # 输出结果\n partition_df = pd.DataFrame(partition_ship_list)\n partition_df.columns = [\"partition\", \"count\"]\n return partition_df\n\n\ndef fit_sub_channel(sub_channel_ais, interval_time=10*60):\n \"\"\"\n 拟合子航道曲线\n :param sub_channel_ais: 子航道的AIS数据,类型:data frame\n :param interval_time: 间隔时间(默认10分钟),单位:秒,类型:int\n :return: 由n个点组成的点组成的三维分段直线,类型:data frame\n \"\"\"\n # 根据间隔时间,获取子航道每条数据所处第几段\n sub_channel_ais[\"partition\"] = sub_channel_ais[\"acquisition_time\"] // interval_time\n\n # 获取分段列表\n partition_list = list(set(sub_channel_ais[\"partition\"]))\n fit_points_list = []\n\n for partition in partition_list:\n partition_ais = sub_channel_ais[sub_channel_ais[\"partition\"] == partition]\n mean_lon = np.mean(partition_ais[\"longitude\"])\n mean_lat = np.mean(partition_ais[\"latitude\"])\n mean_time = np.mean(partition_ais[\"acquisition_time\"])\n fit_points_list.append([mean_lon, mean_lat, mean_time])\n\n # 返回拟合函数的点\n fit_points_df = pd.DataFrame(fit_points_list)\n fit_points_df.columns = [\"longitude\", \"latitude\", \"acquisition_time\"]\n return fit_points_df\n\n\ndef fit_sub_channel_opt(sub_channel_ais, interval_time=1*60):\n \"\"\"\n 拟合子航道曲线\n :param sub_channel_ais: 子航道的AIS数据,类型:data frame\n :param interval_time: 间隔时间(默认10分钟),单位:秒,类型:int\n :return: 由n个点组成的点组成的三维分段直线,类型:data frame\n \"\"\"\n # 根据间隔时间,获取子航道每条数据所处第几段\n sub_channel_ais[\"partition\"] = sub_channel_ais[\"acquisition_time\"] // interval_time\n\n # 获取分段列表\n partition_list = list(set(sub_channel_ais[\"partition\"]))\n fit_points_list = []\n\n for partition in partition_list:\n partition_ais = sub_channel_ais[sub_channel_ais[\"partition\"].isin(range(partition-2, partition+3))]\n mean_lon = np.mean(partition_ais[\"longitude\"])\n mean_lat = np.mean(partition_ais[\"latitude\"])\n mean_time = np.mean(partition_ais[\"acquisition_time\"])\n fit_points_list.append([mean_lon, mean_lat, mean_time])\n\n # 返回拟合函数的点\n fit_points_df = pd.DataFrame(fit_points_list)\n fit_points_df.columns = [\"longitude\", \"latitude\", \"acquisition_time\"]\n return fit_points_df\n\n\ndef filter_moor_ship(sub_channel_ais, interval_lon=0.5):\n \"\"\"\n 过滤子航道内停泊的船舶ais数据\n :param sub_channel_ais: 子航道内的ais数据,类型:data frame\n :param interval_lon: 最大最小经纬度之差,类型:float\n :return: 无停泊船舶的子航道ais数据,类型:data frame\n \"\"\"\n # 初始化需要过滤的mmsi列表\n filter_mmsi_list = []\n\n # 对子航道ais数据按mmsi进行分组\n ship_gdf = sub_channel_ais.groupby('unique_ID')\n\n # 判断每条船的最大最小经纬度之差\n for key, value in ship_gdf:\n max_lon = np.max(value['longitude'])\n min_lon = np.min(value['longitude'])\n if max_lon - min_lon < interval_lon:\n filter_mmsi_list.append(key)\n else:\n pass\n return filter_mmsi_list\n\n\ndef filter_low_speed_ship(sub_channel_ais):\n \"\"\"\n 在航道拟合时,删去噪声数据\n :param sub_channel_ais: 子航道内的ais数据,类型:data frame\n :return: 删去噪声后的数据\n \"\"\"\n speed_list = []\n sub_channel_ais_gdf = sub_channel_ais.groupby('unique_ID')\n for mmsi, value in sub_channel_ais_gdf:\n print(mmsi)\n tmp_speed_list = []\n value_array = np.array(value)\n value_array = value_array[value_array[:, 1].argsort()]\n for index in range(len(value_array) - 1):\n dst = getDist(lon1=value_array[index, 2], lat1=value_array[index, 3],\n lon2=value_array[index+1, 2], lat2=value_array[index+1, 3], )\n deta_time = value_array[index+1, 1] - value_array[index, 1]\n if deta_time == 0:\n deta_time += 1\n avg_speed = dst / deta_time\n tmp_speed_list.append(avg_speed)\n speed_list.append([mmsi, np.mean(tmp_speed_list)])\n return speed_list\n\n\ndef filter_point_before_circle(fit_line_df):\n \"\"\"\n 从拟合曲线中找到离开圆之前的轨迹点\n :param fit_line_df: 拟合曲线数据,类型:data frame\n :return: 离开圆之前的拟合曲线\n \"\"\"\n # 找到每条曲线中,离开圆之前的点\n filtered_point_df = pd.DataFrame()\n inside_circel_bool_list = []\n for key, value in fit_line_df.groupby('channel_id'):\n inside_circle_bool = False\n value = np.array(value)\n for index, line in enumerate(value):\n dst_center = getDist(lon1=line[0], lat1=line[1], lon2=122.1913, lat2=30.5658)\n if dst_center < 1.852*2:\n inside_circle_bool = True\n else:\n if inside_circle_bool:\n filtered_point_df = filtered_point_df.append(pd.DataFrame(value[:index, :]))\n # filtered_point_df.insert(4, 'inside_circle', inside_circel_bool_list)\n break\n inside_circel_bool_list.append(inside_circle_bool)\n filtered_point_df.insert(4, 'inside_circle', inside_circel_bool_list)\n # filtered_point_df['inside_circle'] = inside_circel_bool_list\n return filtered_point_df\n\n\ndef predict_circle_ship_number(ys_ais, fit_line_df, str_time=1464739031, end_time=1465920000):\n \"\"\"\n 获取某10分钟时限内的ais数据,结合拟合后的曲线,预测1小时后船舶在警戒范围内的船舶数量\n :param ys_ais: 洋山水域内的ais数据,类型:data frame\n :param fit_line_df: 拟合曲线数据,类型:data frame\n :param str_time: ais数据开始时间,类型:int\n :param end_time: ais数据结束时间,类型:int\n :return: 1小时后圆内的船舶条数,类型:int\n \"\"\"\n # 初始化预测结果\n predict_res = []\n\n # 将拟合曲线数据转换为矩阵\n fit_line_array = np.array(fit_line_df)\n enter_out_array = fit_line_array[fit_line_array[:, 4] == True]\n\n # 获取某10分钟时限的ais数据\n predict_str_time = np.random.random_integers(str_time, end_time-600)\n ys_ais = ys_ais[(ys_ais['acquisition_time'] >= predict_str_time) &\n (ys_ais['acquisition_time'] <= predict_str_time + 600)]\n print(\"10分钟内,ais数据有%s\" % len(ys_ais))\n print(\"开始时间为 %s\" % predict_str_time)\n\n # 找到船舶最新一条的轨迹点,与拟合曲线中的点的位置关系\n for mmsi, value in ys_ais.groupby('unique_ID'):\n # print(\"mmsi = %d\" % mmsi)\n newest_point = value.iloc[-1, :]\n min_dst = 99999999\n min_dst_channel = False\n\n # 用最���的ais数据点与拟合曲线数据中每个点进行对比,找到该点属于哪条航道\n for row in fit_line_array:\n point_line_dst = getDist(lon1=newest_point['longitude'], lat1=newest_point['latitude'],\n lon2=row[0], lat2=row[1])\n if point_line_dst < min_dst:\n min_dst = point_line_dst\n min_dst_channel = row[3]\n now_time = row[2]\n enter_time = enter_out_array[enter_out_array[:, 3] == min_dst_channel][0, 2] - now_time\n out_time = enter_out_array[enter_out_array[:, 3] == min_dst_channel][-1, 2] - now_time\n\n\n if (min_dst < 1.2) & (enter_time > 0) & (out_time > 0):\n predict_res.append([mmsi, enter_time // 600, out_time // 600])\n else:\n pass\n return predict_res, predict_str_time\n\n\ndef real_ship_circle(ys_ais, predict_str_time, interval_time=30*60):\n \"\"\"\n 检验预测结果\n :param ys_ais: 洋山水域内ais数据,类型:data frame\n :param predict_str_time: 预测开始时间,类型:int\n :param interval_time: 预测开始时间追溯时间,类型:int\n :return: 真实圆内的船舶数量,类型:int\n \"\"\"\n ys_ais = np.array(ys_ais[(ys_ais['acquisition_time'] >= predict_str_time + interval_time) &\n (ys_ais['acquisition_time'] <= predict_str_time + interval_time + 600)])\n mmsi_list = []\n for row in ys_ais:\n dst_center = getDist(lon1=row[2], lat1=row[3], lon2=122.1913, lat2=30.5658)\n if dst_center < 1.852 * 2:\n mmsi_list.append(row[0])\n return len(set(mmsi_list)), set(mmsi_list)\n\n\ndef north_port_get():\n \"\"\"\n 获取北部港区风力、能见度数据\n :return: 返回日期,时间,风力,能见度数据,类型:data frame\n \"\"\"\n from bs4 import BeautifulSoup\n\n now_timestamp = int(time.time() * 1000)\n url = r'http://115.231.126.81/Forecast/PopupContent?stationNum=58472&interval=24&_=%s' % now_timestamp\n headers = {'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '\n r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',\n 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',\n 'Connection': 'keep-alive'}\n req = urllib.request.Request(url, headers=headers)\n page_source_json = urllib.request.urlopen(req).read().decode('utf-8')\n page_source = json.loads(page_source_json)['html']\n bs_page = BeautifulSoup(page_source, 'html.parser').decode('utf-8')\n root_page = lxml.etree.HTML(bs_page)\n\n # 初始化日期,时间,风力,能见度列表\n all_date_list = []\n all_clock_list = []\n all_wind_list = []\n all_njd_list = []\n\n # xpath获取时间数据\n time_xpath = '//*[@style=\"min-width:60px;\"]'\n root_time_list = root_page.xpath(time_xpath)\n for time_element in root_time_list:\n time_str = decode_unicode_references(tostring(time_element)).split(r'\\n ')[1]\\\n .split(r'\\n ')[0]\n time_date = int(time_str.split('日')[0])\n time_clock = int(time_str.split('日')[1].split('时')[0])\n all_date_list.append(time_date)\n all_clock_list.append(time_clock)\n\n # xpath获取风力数据\n wind_xpath = '//table/tbody/tr'\n root_wind_list = root_page.xpath(wind_xpath)\n wind_str = decode_unicode_references(tostring(root_wind_list[0]))\n wind_pattern = re.compile(u''\n u'(.*?)', re.S)\n wind_elements_list = re.findall(wind_pattern, wind_str)\n for wind_element in wind_elements_list:\n wind_level = (wind_element.split(r'\\n ')[1]).split(r'\\n ')[0]\n all_wind_list.append(int(wind_level))\n\n # xpath获取能见度数据\n njd_xpath = '//table/tbody/tr'\n root_njd_list = root_page.xpath(njd_xpath)\n njd_str = decode_unicode_references(tostring(root_njd_list[4]))\n njd_pattern = re.compile(r'(.*?)', re.S)\n njd_elements_list = re.findall(njd_pattern, njd_str)\n for njd_element in njd_elements_list:\n njd_dst = (njd_element.split(r'\\n ')[1]).split(r'\\n ')[0]\n all_njd_list.append(int(njd_dst))\n weather_predick_df = pd.DataFrame(columns=['date', 'clock', 'wind', 'njd'])\n weather_predick_df['date'] = all_date_list\n weather_predick_df['clock'] = all_clock_list\n weather_predick_df['wind'] = all_wind_list\n weather_predick_df['njd'] = all_njd_list\n now_time_index = weather_predick_df[(weather_predick_df['date'] == int(time.strftime('%d'))) &\n (weather_predick_df['clock'] == int(time.strftime('%H')))].index.tolist()\n if len(now_time_index) > 0:\n weather_predick_df = weather_predick_df.iloc[now_time_index:, :]\n else:\n weather_predick_df = weather_predick_df.iloc[-1, :]\n\n return np.max(weather_predick_df['wind']), np.min(weather_predick_df['njd'])\n\n\ndef bridge_cross_poly(ys_ais):\n \"\"\"\n 找到东海大桥通航孔多边形\n :param ys_ais: 洋山水域ais数据,类型:data frame\n :return: 返回通过东海大桥的ais数据点,类型:data frame\n \"\"\"\n bridge_line_1 = [[121.9101275192141, 30.85886907127729], [121.9743845226048, 30.74938456976765]]\n bridge_line_2 = [[121.9740364308981, 30.74907407855846], [121.9754932694055, 30.70342865962283]]\n bridge_line_3 = [[121.9758474404916, 30.70342475630693], [122.0105453839071, 30.65993827754983]]\n ys_ais_gdf = ys_ais.groupby('unique_ID')\n\n crossing_points = []\n for mmsi, value in ys_ais_gdf:\n print('mmsi = %s' % mmsi)\n value_array = np.array(value)\n value_array = value_array[value_array[:, 1].argsort()]\n\n # 从第一条开始循环一条船的ais数据\n index = 0\n if len(value_array) > 1:\n while index < (len(value_array) - 1):\n if is_line_cross(str1=[value_array[index, 2], value_array[index, 3]],\n end1=[value_array[index + 1, 2], value_array[index + 1, 3]],\n str2=bridge_line_3[0], end2=bridge_line_3[1]):\n crossing_points.append([value_array[index, 2], value_array[index, 3]])\n crossing_points.append([value_array[index + 1, 2], value_array[index + 1, 3]])\n index += 1\n return crossing_points\n\n\ndef get_bridge_poly():\n \"\"\"\n 获取bridge_data中,通航孔的多边形数据\n :return: 多边形数据的矩阵,类型np.array\n \"\"\"\n # 获取通航孔多边形坐标\n bridge_poly_list = []\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic')\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM bridge_data\")\n for row in cur.fetchall():\n poly_id = row[0]\n poly_coordinate_string = row[-1]\n print(poly_coordinate_string)\n poly_coordinate_list = []\n for coordinate in poly_coordinate_string.split(';'):\n if coordinate:\n lon_ = float(coordinate.split('*')[0])\n lat_ = float(coordinate.split('*')[1])\n poly_coordinate_list.append([lon_, lat_])\n bridge_poly_list.append([poly_id, poly_coordinate_list])\n cur.close()\n conn.close()\n return bridge_poly_list\n\n\ndef merge_ship_static(file_path):\n \"\"\"\n 合并船舶信息表\n :param file_path: 表格所在路径,类型:string\n :return: 船舶信息合并后的数据,类型:data frame\n \"\"\"\n file_name_list = getFileNameList(file_path)\n ship_static_df_list = []\n for file_name in file_name_list:\n print(file_name)\n ship_static_df = pd.read_excel(file_path + file_name)\n ship_static_df_list.append(ship_static_df)\n print(\"mergeing....\")\n all_ship_df = pd.concat(ship_static_df_list)\n return all_ship_df\n\n\ndef if_string(test_string):\n is_string = False\n for x in test_string:\n if (x.isdigit()) | (x == '.'):\n is_string = True\n else:\n is_string = False\n break\n if not is_string:\n return '0'\n else:\n return test_string\n\n\ndef ship_static_mysql():\n \"\"\"\n 船舶静态数据入库\n :return:\n \"\"\"\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n # 读取船舶静态数据\n ship_static_df = pd.read_csv('/home/qiu/Documents/ys_ais/all_ship_static_ys_opt.csv').fillna(0)\n ship_static_array = np.array(ship_static_df)\n print(ship_static_df.columns)\n\n # 循环导入船舶静态数据\n ssd_id = 4\n error_count = 0\n for line in ship_static_array:\n try:\n mmsi = if_string(str(line[10]))\n imo = if_string(str(line[8]))\n tonnage = if_string(str(line[20]))\n dwt = if_string(str(line[22]))\n monitor_rate = if_string(str(line[23]))\n length = if_string(str(line[17]))\n width = if_string(str(line[18]))\n insert_sql = \"\"\"\n INSERT INTO ship_static_data VALUES ('%d', '%d', '%d', '%s', '%s', '%s', null, '%s', '%s', '%s',\n '%s', '%f', '%f', '%f', '%f', '%f', null, null)\n \"\"\" % (ssd_id, int(float(mmsi)), int(float(imo)), line[1], line[2], line[7], line[11], line[13], line[3],\n line[4], float(tonnage), float(dwt), float(monitor_rate), float(length),\n float(width))\n ssd_id += 1\n print(ssd_id)\n cur.execute(insert_sql)\n except Exception as e:\n error_count += 1\n print(e)\n\n print(\"error count is %d\" % error_count)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef ship_static_opt(file_path):\n \"\"\"\n 找到有mmsi数据的船舶基本信息\n :param file_path:\n :return:\n \"\"\"\n file_ = open(file_path)\n ship_static_list = []\n for line in file_:\n if \"主机功率\" not in line:\n line_list = line.split(\"\\n\")[0].split(\",\")\n out_line_list = []\n for ele in line_list:\n tmp_ele = ele.replace(\" \", \"\").replace(\",\", \"\")\n out_line_list.append(tmp_ele)\n ship_static_list.append(out_line_list)\n ship_static_df = pd.DataFrame(ship_static_list)\n return ship_static_df\n\n\ndef emergency_ship_mysql():\n \"\"\"\n 应急船舶数据导入数据库\n :return:\n \"\"\"\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n emergency_ship_array = np.array(pd.read_csv('/home/qiu/Documents/ys_ais/船舶数据清单/'\n '上海海事局辖区社会应急力量配置情况统计 (辖区汇总表)-20171020.csv'))\n print(emergency_ship_array)\n count = 20\n for line in emergency_ship_array:\n insert_sql = \"\"\"\n INSERT INTO emergency_ship VALUE('%s', '%s', null, null, null, null, '%s', '%s', '%s', null, null, \n '%s', '%s', null, null, '%s', '%s', '%s', '%s', '%s', '%s', \n '%s', '%s', '%s', '%s', '%s', null, '%s', '%s', '%s', '%s', \n null, '%s', '%s', '%s', '%s', '%s', '%s')\n \"\"\" % (count, line[6], int(line[27]), line[26], line[5],\n line[7], line[8],\n line[1], line[3], line[10], line[11], line[12], line[13], line[14], line[15],\n line[16], line[17], line[18], line[20], line[21], line[22], line[23],\n str(line[25]), str(line[28]), str(line[29]), str(line[30]), str(line[31]), str(line[32]))\n count += 1\n cur.execute(insert_sql)\n conn.commit()\n cur.close()\n conn.commit()\n\n\ndef ais_static_mysql():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n # 创建ais_static表\n create_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS ship_static_data_eway(\n ssde_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ,\n mmsi INT,\n create_time DATETIME ,\n shiptype VARCHAR(100) ,\n IMO VARCHAR(100) ,\n callsign VARCHAR(100) ,\n ship_length FLOAT ,\n ship_width FLOAT ,\n pos_type VARCHAR(100) ,\n eta VARCHAR(100) ,\n draught FLOAT ,\n destination VARCHAR(100)\n )\n \"\"\"\n cur.execute(create_sql)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef tb_warning_pop_mysql():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n # 创建ais_static表\n create_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS tb_warning_pop(\n twp_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ,\n create_time DATETIME,\n wind_warning_text VARCHAR(100),\n njd_warning_text VARCHAR(100),\n ship_port_warning_text VARCHAR(100),\n bridge_warning_text VARCHAR(100),\n traffic_warning_text VARCHAR(100), \n extend TEXT\n )\n \"\"\"\n cur.execute(create_sql)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef breth_data_mysql():\n breth_df = pd.read_excel('/home/qiu/Documents/ys_ais/码头表.xlsx')\n breth_df = breth_df[~breth_df[u'序号'].isnull()]\n breth_df = breth_df.fillna(0)\n breth_array = np.array(breth_df)\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n bd_id = 5\n for line in breth_array:\n breth_name = line[1]\n breth_length = int(line[2])\n if ('-' in str(line[3])) & ('万' in str(line[3])):\n max_dwt = float(line[3].split('万')[0].split('-')[1])\n min_dwt = float(line[3].split('万')[0].split('-')[0])\n elif ('-' in str(line[3])) & (not '万' in str(line[3])):\n max_dwt = float(line[3].split('-')[1])\n min_dwt = float(line[3].split('-')[0])\n else:\n max_dwt = float(line[3])\n min_dwt = float(line[3])\n breth_type = line[5]\n font_depth = float(line[6])\n roundabout_area = line[7]\n roundabout_depth = line[8]\n remarks = line[9]\n\n insert_sql = \"\"\"\n INSERT INTO breth_data VALUES ('%d', '%s', '%d', '%f', '%f', '%s', '%f', '%s', '%s', '%s')\n \"\"\" % (bd_id, breth_name, breth_length, min_dwt, max_dwt, breth_type, font_depth,\n roundabout_area, roundabout_depth, remarks)\n cur.execute(insert_sql)\n bd_id += 1\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef ship_static_eway_mysql():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n ship_static_df = pd.read_csv('/home/qiu/Documents/unique_static_2016.csv')\n ship_static_array = np.array(ship_static_df)\n error_count = 0\n for line in ship_static_array:\n try:\n insert_sql = \"\"\"\n INSERT INTO ship_static_data_eway(mmsi, create_time, shiptype, IMO, callsign, ship_length, ship_width,\n pos_type, eta, draught, destination, ship_english_name) \n VALUE('%d', NULL , '%s', '%s', '%s', '%f', '%f', '%s', '%s', '%f', NULL , '%s')\n \"\"\" % (int(line[7]), line[9], line[5], line[1], line[6], float(line[12]),\n 0.0, line[4], float(line[3]), line[8])\n # print(insert_sql)\n cur.execute(insert_sql)\n except Exception as e:\n print(e)\n error_count += 1\n print(\"error count is %d\" % error_count)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef tb_ship_data_mysql():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n ship_static_df = pd.read_csv('/home/qiu/Documents/unique_static_2016.csv')\n print(ship_static_df.head())\n input(\"-----------\")\n ship_static_array = np.array(ship_static_df)\n error_count = 0\n for line in ship_static_array:\n try:\n insert_sql = \"\"\"\n INSERT INTO tb_ship_data(mmsi, imo, ship_callsign, ship_english_name,\n shiptype, width, length, eta, draught, destination)\n VALUE('%d', NULL , '%s', '%s', '%s', '%f', '%f', '%s', '%s', '%f', NULL , '%s')\n \"\"\" % (int(line[7]), line[9], line[5], line[1], line[6], float(line[12]),\n 0.0, line[4], float(line[3]), line[8])\n # print(insert_sql)\n cur.execute(insert_sql)\n except Exception as e:\n print(e)\n error_count += 1\n print(\"error count is %d\" % error_count)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef get_ship_static_mysql():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n select_sql = \"\"\"\n SELECT * FROM ship_static_data\n \"\"\"\n cur.execute(select_sql)\n ship_static_eway_df = pd.DataFrame(list(cur.fetchall()))\n ship_static_eway_df.columns = ['ssd_id', 'mmsi', 'imo', 'ship_chinese_name', 'ship_english_name', 'ship_callsign',\n 'sea_or_river', 'flag', 'sail_area', 'ship_port', 'ship_type', 'tonnage', 'dwt',\n 'monitor_rate', 'length', 'width', 'wind_resistance_level', 'height_above_water']\n print(ship_static_eway_df.head())\n\n\ndef drop_same_emergency_ship():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n select_sql = \"\"\"\n SELECT * FROM emergency_ship\n \"\"\"\n cur.execute(select_sql)\n\n emergency_ship_df = pd.DataFrame(list(cur.fetchall()))\n emergency_ship_df = emergency_ship_df.drop_duplicates()\n emergency_ship_array = np.array(emergency_ship_df)\n\n inserted_mmsi_list = []\n count = 800\n for line in emergency_ship_array:\n insert_sql = \"\"\"\n INSERT INTO emergency_ship VALUES ('%s', '%s', null, null, null, null, '%s', '%s', '%s', null, null, \n '%s', '%s', null, null, '%s', '%s', '%s', '%s', '%s', '%s', \n '%s', '%s', '%s', '%s', '%s', null, '%s', '%s', '%s', '%s', \n null, '%s', '%s', '%s', '%s', '%s', '%s')\n \"\"\" % (count, line[1], line[6], line[7], line[8],\n line[11],line[12], line[15], line[16], line[17], line[18], line[19], line[20],\n line[21],line[22], line[23], line[24], line[25], line[27], line[28], line[29], line[30],\n line[32], line[33], line[34], line[35], line[36], line[37])\n count += 1\n if not line[1] in inserted_mmsi_list:\n cur.execute(insert_sql)\n inserted_mmsi_list.append(line[1])\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef add_standard_ship_name():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n select_sql = \"\"\"\n SELECT * FROM ship_static_data_eway\n \"\"\"\n cur.execute(select_sql)\n for line in cur.fetchall():\n # print(line)\n # input(\"----------\")\n if line[11]:\n standard_ship_english_name = line[11].replace(' ', '')\n update_sql = \"\"\"\n UPDATE ship_static_data_eway SET standard_ship_english_name='%s' WHERE mmsi='%d'\n \"\"\" % (standard_ship_english_name, line[0])\n print(line[0])\n cur.execute(update_sql)\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef add_mysql_tel():\n # 链接数据库\n conn = pymysql.connect(host='192.168.1.63', port=3306, user='root', passwd='traffic170910@0!7!@#3@1',\n db='dbtraffic', charset='utf8')\n cur = conn.cursor()\n\n tel_file = open('/home/qiu/Desktop/tel_list_预案组.txt', 'r')\n count = 100\n create_time = time.strftime('%Y-%m-%d %H:%M:%S')\n for line in tel_file:\n tel_list = line.split('\\n')[0].split(',')\n print(tel_list)\n for tel in tel_list:\n insert_sql = \"\"\"\n INSERT INTO t_manager(ID, LOGIN_NAME, LOGIN_PASSWORD, CREATE_DATE, UPDATE_DATE, \n tel, ext_person, manager_id, IS_DELETE) VALUE ('%s', '%s','%s', '%s', '%s', '%s', '%s', '%d', '%d')\n \"\"\" % (count, tel, tel,create_time, create_time, tel, 3, count, 0)\n cur.execute(insert_sql)\n count += 1\n conn.commit()\n cur.close()\n conn.close()\n tel_file.close()\n\n\ndef coor_cog(lon1, lat1, lon2, lat2):\n \"\"\"\n 根据AIS数据两点,得到cog\n :param lon1:\n :param lat1:\n :param lon2:\n :param lat2:\n :return:\n \"\"\"\n import math\n deta_lon = lon2 - lon1\n deta_lat = lat2 - lat1\n if (deta_lon > 0.) & (deta_lat < 0.):\n return 90 - (math.atan(abs(deta_lat/deta_lon)) * (180. / math.pi))\n elif (deta_lon > 0.) & (deta_lat > 0.):\n return 90 + (math.atan(abs(deta_lat/deta_lon)) * (180. / math.pi))\n elif (deta_lon < 0.) & (deta_lat > 0.):\n return 270 - (math.atan(abs(deta_lat/deta_lon)) * (180. / math.pi))\n elif (deta_lon < 0.) & (deta_lat < 0.):\n return 270 + (math.atan(abs(deta_lat/deta_lon)) * (180. / math.pi))\n\n\ndef get_cog_fit_line():\n \"\"\"\n 获取拟合曲线每个点的cog\n :return: 对拟合曲线数据添加一列cog字段,类型:dataframe\n \"\"\"\n fit_line_file_list = ['/home/qiu/Documents/ys_ais/交通预警优化数据/opt_east_west_fit_line.csv',\n '/home/qiu/Documents/ys_ais/交通预警优化数据/opt_north_up_fit_line.csv',\n '/home/qiu/Documents/ys_ais/交通预警优化数据/opt_south_down_fit_line.csv',\n '/home/qiu/Documents/ys_ais/交通预警优化数据/opt_west_east_fit_line.csv']\n fit_line_df_list = []\n for fit_line_file in fit_line_file_list:\n fit_line_df = pd.read_csv(fit_line_file)\n cog_list = []\n for index in range(len(fit_line_df) - 1):\n cog_float = fit_line_cog(lon1=fit_line_df.iloc[index, 0], lat1=fit_line_df.iloc[index, 1],\n lon2=fit_line_df.iloc[index+1, 0], lat2=fit_line_df.iloc[index+1, 1])\n cog_list.append(cog_float)\n cog_list.append(0.)\n fit_line_df['cog'] = cog_list\n fit_line_df_list.append(fit_line_df)\n fit_line_sum_df = pd.concat(fit_line_df_list, ignore_index=True)\n # /home/qiu/Documents/ys_ais/交通预警优化数据/opt_west_east_fit_line.csv\n fit_line_sum_df.to_csv('/home/qiu/Documents/ys_ais/交通预警优化数据/opt_all_fit_line.csv', index=None)\n print(fit_line_sum_df)\n\n\nif __name__ == \"__main__\":\n # # --------------------------------------------------------------------------\n # # 获取洋山水域内AIS数据\n # data = pd.read_csv(\"/home/qiu/Documents/ys_ais/pre_201606_ys.csv\", header=None)\n # data.columns = [\"unique_ID\", \"acquisition_time\", \"target_type\", \"data_supplier\", \"data_source\",\n # \"status\", \"longitude\", \"latitude\", \"area_ID\", \"speed\", \"conversion\", \"cog\",\n # \"true_head\", \"power\", \"ext\", \"extend\"]\n # data = data.loc[:, [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]]\n # data = data.sort_values(by=[\"unique_ID\", \"acquisition_time\"])\n # data[\"longitude\"] = data[\"longitude\"] / 1000000.\n # data[\"latitude\"] = data[\"latitude\"] / 1000000.\n\n # # 获取某10分钟时限的ais数据\n # str_time = 1464739031\n # end_time = 1465920000\n # predict_str_time = np.random.random_integers(str_time, end_time - 600)\n # ys_ais = data[(data['acquisition_time'] >= predict_str_time) &\n # (data['acquisition_time'] <= predict_str_time + 600)]\n # ys_ais.to_csv('/home/qiu/Documents/ys_ais/pre_201606_ys_10mins.csv', index=None)\n\n # ------------------------------------------------------------------------\n # 找到在警戒区内出现过的船舶ais,并追溯前后1.5小时\n # entered_circle_ais_df = pd.DataFrame(enter_circle_ais(ys_ais=data), columns=[\"unique_ID\", \"acquisition_time\",\n # \"longitude\", \"latitude\"])\n # print(entered_circle_ais_df.head())\n # print(len(entered_circle_ais_df))\n # entered_circle_ais_df.to_csv(\"/home/qiu/Documents/ys_ais/entered_circle_ais.csv\", index=None)\n\n # # -------------------------------------------------------------------------\n # # 获取境界范围多边形数据,并用进出多边形来对ais数据进行分组\n # kml_path = \"/home/qiu/Documents/ys_ais/新警戒区观测区.kml\"\n # coordinates_list = coordinates_kml(kml_path)\n # coordinates_list = [[float(x) for x in line] for line in coordinates_list]\n #\n # gdf = data.groupby(\"unique_ID\")\n # str_group_num = 0\n # out_list = []\n # for mmsi, value in gdf:\n # print(mmsi)\n # out_put_list, group_num = inside_poly_ais(ys_ais=value, area_poly=coordinates_list,\n # group_num=str_group_num)\n # if len(out_put_list) > 0:\n # out_list.extend(out_put_list)\n # out_df = pd.DataFrame(out_list)\n # out_df.columns = [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]\n # out_df = out_df.sort_values(by=[\"unique_ID\", \"acquisition_time\"])\n # out_df.to_csv(\"/home/qiu/Documents/ys_ais/new_inside_poly_ais.csv\", index=None)\n\n # # --------------------------------------------------------------\n # # 对分组后的数据,平移时间轴\n # out_df = pd.read_csv(\"/home/qiu/Documents/ys_ais/new_inside_poly_ais.csv\")\n # print(len(set(out_df[\"unique_ID\"])))\n # inside_circle_mmsi = get_ais_inside_circle(out_df, [122.1913, 30.5658])\n # print(inside_circle_mmsi)\n # out_df = out_df[out_df[\"unique_ID\"].isin(inside_circle_mmsi)]\n # moved_out_df = pd.DataFrame(move_time_axis(out_df))\n # moved_out_df.columns = [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]\n # print(len(moved_out_df))\n # moved_out_df = pd.DataFrame(move_time_axis(moved_out_df))\n # moved_out_df.columns = [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]\n # print(len(moved_out_df))\n # moved_out_df.to_csv(\"/home/qiu/Documents/ys_ais/new_moved_time_ais.csv\", index=None)\n\n # # ----------------------------------------------------------------\n # # 区分进入主航道是的入口编号\n # kml_path_list = [\"/home/qiu/Documents/ys_ais/警戒区进口1.kml\",\n # \"/home/qiu/Documents/ys_ais/新警戒区入口2.kml\",\n # \"/home/qiu/Documents/ys_ais/新警戒区入口3.kml\",\n # \"/home/qiu/Documents/ys_ais/新警戒区入口4.kml\",\n # \"/home/qiu/Documents/ys_ais/新警戒区入口5.kml\",\n # \"/home/qiu/Documents/ys_ais/新警戒区入口6.kml\"]\n # poly_df = multiple_poly_list(kml_path_list)\n # main_channel_ais = pd.read_csv(\"/home/qiu/Documents/ys_ais/new_moved_time_ais.csv\")\n # # test_df = poly_df[poly_df[\"poly_id\"] == 1]\n # sub_channel_ais = sub_main_channel_poly_filter(main_channel_ais, 3, 5, poly_df)\n # # tmp_df = sub_channel_ais[(sub_channel_ais[\"latitude\"] > 30.62) |\n # # (sub_channel_ais[\"latitude\"] == 30.535891) |\n # # (sub_channel_ais[\"acquisition_time\"] >= 5000)]\n # # filter_mmsi_list = list(set(tmp_df[\"unique_ID\"]))\n # # sub_channel_ais = sub_channel_ais[~sub_channel_ais[\"unique_ID\"].isin(filter_mmsi_list)]\n # # sub_channel_ais = pd.DataFrame(sub_channel_ais)\n # # sub_channel_ais.columns = [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\", \"poly_id\"]\n # # sub_channel_ais = sub_channel_ais[~sub_channel_ais[\"poly_id\"].isnull()]\n # sub_channel_ais.to_csv(\"/home/qiu/Documents/ys_ais/new_sub_channel_ais_north_up.csv\", index=None)\n # # print(sub_channel_ais)\n\n # # ------------------------------------------------\n # # 子航道拟合\n # # 122156281, 30551332, 7101\n # sub_channel_ais = pd.read_csv(\"/home/qiu/Documents/ys_ais/new_sub_channel_ais_west_east.csv\")\n # # print(sub_channel_ais[(sub_channel_ais['longitude'] == 122.216003) | (sub_channel_ais['acquisition_time'] == 1585)])\n # # input(\"---------1-------------\")\n # print(sub_channel_ais.head())\n # mmsi_speed_list = filter_low_speed_ship(sub_channel_ais)\n # mmsi_speed_df = pd.DataFrame(mmsi_speed_list, columns=['unique_ID', 'avg_speed'])\n # # filter_mmsi.extend(filter_moor_ship(sub_channel_ais))\n # print(mmsi_speed_df)\n # print(np.mean(mmsi_speed_df['avg_speed']))\n # filter_mmsi = list(mmsi_speed_df[mmsi_speed_df['avg_speed'] > 0.177485]['unique_ID'])\n # filter_mmsi.extend([622, 1004])\n # input(\"------------------------\")\n # # keep_mmsi = sub_channel_ais[(sub_channel_ais['longitude'] > 122.4) &\n # # (sub_channel_ais['acquisition_time'] > 5000)]['unique_ID']\n # # print(list(set(keep_mmsi)))\n # sub_channel_ais_filtered = sub_channel_ais[~sub_channel_ais[\"unique_ID\"].isin(list(set(filter_mmsi)))]\n # sub_channel_ais_filtered.to_csv(\"/home/qiu/Documents/ys_ais/new_west_east_paint_data.csv\", index=None)\n # fit_channel_df = fit_sub_channel_opt(sub_channel_ais_filtered)\n # fit_channel_df.to_csv(\"/home/qiu/Documents/ys_ais/交通预警优化数据/opt_west_east_fit_line.csv\", index=None)\n # print(fit_channel_df)\n\n # # ----------------------------------------------------------------\n # # 计算警戒范围内可能出现的最大船舶数量\n # data = pd.read_csv(\"/home/qiu/Documents/ys_ais/pre_201606_ys.csv\", header=None)\n # data.columns = [\"unique_ID\", \"acquisition_time\", \"target_type\", \"data_supplier\", \"data_source\",\n # \"status\", \"longitude\", \"latitude\", \"area_ID\", \"speed\", \"conversion\", \"cog\",\n # \"true_head\", \"power\", \"ext\", \"extend\"]\n # data = data.loc[:, [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]]\n # print(data.head())\n # data[\"longitude\"] = data[\"longitude\"] / 1000000.\n # data[\"latitude\"] = data[\"latitude\"] / 1000000.\n # partition_count_df = sum_ship_warning_area(data, [122.1913, 30.5658], 1.852*2.0)\n # partition_count_df.to_csv(\"/home/qiu/Documents/ys_ais/partition_count.csv\", index=None)\n # print(partition_count_df)\n # print(partition_count_df.describe())\n # print(set(partition_count_df[\"count\"]))\n\n # # ------------------------------------------------------------------\n # # 找到拟合曲线中,离开圆之前的点\n # fit_line_east_west_df = pd.read_csv('/home/qiu/Documents/ys_ais/east_west_fit_line.csv')\n # fit_line_north_up_df = pd.read_csv('/home/qiu/Documents/ys_ais/new_north_up_fit_line.csv')\n # fit_line_south_down_df = pd.read_csv('/home/qiu/Documents/ys_ais/new_south_down_fit_line.csv')\n # fit_line_west_east_df = pd.read_csv('/home/qiu/Documents/ys_ais/new_west_east_fit_line.csv')\n # fit_line_df = pd.concat([fit_line_east_west_df, fit_line_north_up_df,\n # fit_line_south_down_df, fit_line_west_east_df], ignore_index=True)\n # print(fit_line_df.head())\n # input(\"--------------------\")\n fit_line_df = pd.read_csv('/home/qiu/Documents/ys_ais/交通预警优化数据/opt_all_fit_line.csv')\n filtered_fit_line_df = filter_point_before_circle(fit_line_df=fit_line_df)\n filtered_fit_line_df.columns = ['longitude', 'latitude', 'acquisition_time', 'channel_id', 'inside_circle', 'cog']\n filtered_fit_line_df.to_csv(\"/home/qiu/Documents/ys_ais/交通预警优化数据/filtered_fit_line.csv\", index=None)\n print(filtered_fit_line_df)\n\n # # 检验模型\n # predict_res, predict_str_time = predict_circle_ship_number(ys_ais=data, fit_line_df=filtered_fit_line_df)\n # predict_res_df = pd.DataFrame(predict_res, columns=['mmsi', 'enter_time', 'out_time'])\n # print(predict_res_df)\n # # res = predict_res[((predict_res['enter_time'] >= 6.) & (predict_res['enter_time'] <= 7.)) |\n # # ((predict_res['out_time'] >= 6.) & (predict_res['out_time'] <= 7.))]\n # # print(len(res))\n # real_number, mmsi_list = real_ship_circle(ys_ais=data, predict_str_time=predict_str_time)\n # print(real_number, mmsi_list)\n # print(predict_str_time)\n\n # # -------------------------------------------------------------------\n # # 测试网页数据get\n # max_wind, min_njd = north_port_get()\n # print(max_wind, min_njd)\n\n # # -------------------------------------------------------------------\n # # 获取通过东海大桥的点\n # crossing_points = bridge_cross_poly(data)\n # crossing_points_df = pd.DataFrame(crossing_points)\n # crossing_points_df.columns = ['longitude', 'latitude']\n # crossing_points_df.to_csv('/home/qiu/Documents/ys_ais/crossing_bridge_points_3.csv', index=None)\n\n # ----------------------------------------------------------------------\n # 东海大桥通航孔坐标列表转字符串\n # kml_path_list = [\"/home/qiu/Documents/ys_ais/通航孔1.kml\",\n # \"/home/qiu/Documents/ys_ais/通航孔2.kml\",\n # \"/home/qiu/Documents/ys_ais/通航孔3.kml\",\n # \"/home/qiu/Documents/ys_ais/通航孔4.kml\",\n # \"/home/qiu/Documents/ys_ais/通航孔5.kml\"]\n # bridge_ploy = multiple_poly_list(kml_path_list)\n # print(bridge_ploy)\n # for poly_id, value in bridge_ploy.groupby('poly_id'):\n # print(poly_id)\n # value_array = np.array(value)\n # coordinate_string = \"\"\n # for row in value_array:\n # coordinate_string = coordinate_string + \\\n # str(round(float(row[0]), 4)) + \"*\" + str(round(float(row[1]), 4)) + \";\"\n # print(coordinate_string)\n\n # ----------------------------------------------------\n # 获取最新10分钟内,东海大桥的通航情况\n # bridge = Bridge()\n # ys_ais_10mins = pd.read_csv('/home/qiu/Documents/ys_ais/pre_201606_ys.csv', header=None)\n # print(ys_ais_10mins)\n # bridge_cross_df = bridge.bridge_main(ys_ais=ys_ais_10mins)\n\n # # ------------------------------------------------------\n # # 应急决策\n # emergency = Emergency()\n # emergency.emergency_main(ys_ais_10mins=data)\n\n # # --------------------------------------------------------\n # # 交通预警\n # ys_ais_10mins = pd.read_csv('/home/qiu/Documents/ys_ais/pre_201606_ys_10mins.csv')\n # traffic = Traffic()\n # predict_res_df = pd.DataFrame(traffic.traffic_main(ys_ais=ys_ais_10mins))\n\n # # -------------------------------------------------------\n # # 天气报告\n # weather = Weather()\n # weather.report_mysql()\n\n # # --------------------------------------------------------\n # # 靠离泊\n # port = Port()\n # port.port_main()\n\n # --------------------------------------------------------\n # 合并从洋山获取到的船舶静态数据\n # file_path = \"/home/qiu/Documents/ys_ais/船舶数据清单/FULL/\"\n # all_ship_static_df = merge_ship_static(file_path)\n # all_ship_static_df_length = len(all_ship_static_df)\n # all_ship_static_array = np.array(all_ship_static_df)\n # for index in range(all_ship_static_df_length):\n # print(index)\n # columns_length = len(all_ship_static_array[index, :])\n # for column in range(columns_length):\n # if ',' in str(all_ship_static_array[index, column]):\n # all_ship_static_array[index, column] = str(all_ship_static_array[index, column]).replace(',', '')\\\n # .replace(' ', '')\n # all_ship_static_opt_df = pd.DataFrame(all_ship_static_array)\n # all_ship_static_opt_df.to_csv('/home/qiu/Documents/ys_ais/all_ship_static_ys.csv', index=None)\n # print(all_ship_static_df.head())\n #-------------------------------------------------------------\n # file_path = \"/home/qiu/Documents/ys_ais/all_ship_static_ys.csv\"\n # header = pd.read_excel('/home/qiu/Documents/ys_ais/船舶数据清单/FULL/hsData_0.xls').columns\n # df = ship_static_opt(file_path)\n # df.columns = header\n # df.to_csv('/home/qiu/Documents/ys_ais/all_ship_static_ys_opt.csv', index=None)\n # print(df.head())\n\n # get_ship_static_mysql()\n\n # from email.mime.text import MIMEText\n #\n # msg = MIMEText('hello,send by python...', 'plain', 'utf-8')\n #\n # # 发送邮箱地址\n # from_addr = 'qiujiayu0212@163.com'\n #\n # # 邮箱授权码,非登陆密码\n # password = 'yingming0403'\n #\n # # 收件箱地址\n # to_addr = 'sohu.321@qq.com'\n #\n # # smtp服务器\n # smtp_server = 'smtp.163.com'\n # # 发送邮箱地址\n # msg['From'] = from_addr\n # # 收件箱地址\n # msg['To'] = to_addr\n # # 主题\n # msg['Subject'] = 'the frist mail'\n # import smtplib\n #\n # server = smtplib.SMTP(smtp_server, 25)\n #\n # server.set_debuglevel(1)\n #\n # print(from_addr)\n # print(password)\n # server.login(from_addr, password)\n #\n # a = server.sendmail(from_addr, [to_addr], msg.as_string())\n # print(a)\n #\n # server.quit()\n\n # get_cog_fit_line()\n","sub_path":"ys_2017/ys_test.py","file_name":"ys_test.py","file_ext":"py","file_size_in_byte":63289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362947659","text":"\"\"\"\nName: eLCS_ConfigPars.py\nAuthors: Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA\nContact: ryan.j.urbanowicz@darmouth.edu\nCreated: November 1, 2013\nDescription: Manages the configuration file, by loading it, parsing it and passing values to the 'Constants' module.\n \n---------------------------------------------------------------------------------------------------------------------------------------------------------\neLCS: Educational Learning Classifier System - A basic LCS coded for educational purposes. This LCS algorithm uses supervised learning, and thus is most \nsimilar to \"UCS\", an LCS algorithm published by Ester Bernado-Mansilla and Josep Garrell-Guiu (2003) which in turn is based heavily on \"XCS\", an LCS \nalgorithm published by Stewart Wilson (1995). \n\nCopyright (C) 2013 Ryan Urbanowicz \nThis program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the \nFree Software Foundation; either version 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLILITY \nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, \nInc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n---------------------------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\n# Import Required Modules----------\nfrom eLCS.Constants import cons\n\n\n# ---------------------------------\n\nclass ConfigParser(object):\n \"\"\"This class docstring shows how to use sphinx and rst syntax\n\n The first line is brief explanation, which may be completed with\n a longer one. For instance to discuss about its methods. The only\n method here is :func:`function1`'s. The main idea is to document\n the class and methods's arguments with\n\n - **parameters**, **types**, **return** and **return types**::\n\n :param arg1: description\n :param arg2: description\n :type arg1: type description\n :type arg1: type description\n :return: return description\n :rtype: the return type description\n\n - and to provide sections such as **Example** using the double commas syntax::\n\n :Example:\n\n followed by a blank line !\n\n which appears as follow:\n\n :Example:\n\n followed by a blank line\n\n - Finally special sections such as **See Also**, **Warnings**, **Notes**\n use the sphinx syntax (*paragraph directives*)::\n\n .. seealso:: blabla\n .. warnings also:: blabla\n .. note:: blabla\n .. todo:: blabla\n\n .. note::\n There are many other Info fields but they may be redundant:\n * param, parameter, arg, argument, key, keyword: Description of a\n parameter.\n * type: Type of a parameter.\n * raises, raise, except, exception: That (and when) a specific\n exception is raised.\n * var, ivar, cvar: Description of a variable.\n * returns, return: Description of the return value.\n * rtype: Return type.\n\n .. note::\n There are many other directives such as versionadded, versionchanged,\n rubric, centered, ... See the sphinx documentation for more details.\n\n Here below is the results of the :func:`function1` docstring.\n\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n\n :param filename:\n \"\"\"\n self.commentChar = '#'\n self.paramChar = '='\n self.parameters = self.parseConfig(filename) # Parse the configuration file and get all parameters.\n cons.setConstants(self.parameters) # Store run parameters in the 'Constants' module.\n\n def parseConfig(self, filename):\n \"\"\" Parses the configuration file. \"\"\"\n parameters = {}\n try:\n f = open(filename)\n except Exception as inst:\n print(type(inst))\n print(inst.args)\n print(inst)\n print('cannot open', filename)\n raise\n else:\n for line in f:\n # Remove text after comment character.\n if self.commentChar in line:\n line, comment = line.split(self.commentChar,\n 1) # Split on comment character, keep only the text before the character\n\n # Find lines with parameters (param=something)\n if self.paramChar in line:\n parameter, value = line.split(self.paramChar, 1) # Split on parameter character\n parameter = parameter.strip() # Strip spaces\n value = value.strip()\n parameters[parameter] = value # Store parameters in a dictionary\n\n f.close()\n\n return parameters\n","sub_path":"eLCS/ConfigParser.py","file_name":"ConfigParser.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"174343196","text":"if __name__ == '__main__':\n \"Uploads current folder as repository to GitHub.\"\n from os import system, path\n\n root = 'https://github.com/ychnlgy/'\n\n # init repository if not already #\n if not path.exists('.git'):\n system('git init')\n branch = root+raw_input('Branch: ')+'.git'\n system('git remote add origin %s' % branch)\n\n # pull #\n system('git pull origin master')\n\n # prepare files for upload #\n system('git add .')\n comment = raw_input('Description of commit: ')\n system('git commit -m \"%s\"' % comment)\n\n # push commits to master forcefully #\n system('git push origin master')\n\n # If push not successful, you can still force it. #\n force = raw_input('Force? ')\n if force == 'yes': system('git push origin master --force')\n","sub_path":"git_it.py","file_name":"git_it.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507519834","text":"import unittest\n\nimport copy\nfrom compyl.lexer import Lexer, LexerError\n\nFAIL = False\n\n\ndef get_token_stream(lexer, buffer):\n lexer.read(buffer)\n tk_list = []\n\n tk = lexer.lex()\n\n while tk:\n tk_list.append(tk)\n tk = lexer.lex()\n\n return tk_list\n\n\ndef get_token_stream_types(lexer, buffer):\n return [tk.type for tk in get_token_stream(lexer, buffer)]\n\n\ndef get_token_stream_values(lexer, buffer):\n return [tk.value for tk in get_token_stream(lexer, buffer)]\n\n\ndef test_regexp_on_buffer(regexp, buffer):\n rules = [(regexp, 'placeholder')]\n lexer = Lexer(rules=rules)\n lexer.build()\n\n return get_token_stream_values(lexer, buffer)\n\n\nclass LexerTestBasic(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n rules = [\n (r'[a-z]+', 'WORD'),\n (r'unreachable', 'UNREACHABLE'),\n (r'[0-9]+', 'NUMBER'),\n (r' ', None),\n ]\n\n cls.lexer = Lexer(rules=rules, line_rule='\\n')\n cls.lexer.build()\n\n cls.lexer_copy = copy.deepcopy(cls.lexer)\n\n def tearDown(self):\n self.__class__.lexer = copy.deepcopy(self.lexer_copy)\n\n def test_token_stream(self):\n buffer = \"11 words written here\\n\" + \\\n \"unreachable should be a word\\n\"\n\n token_types = get_token_stream_types(self.lexer, buffer)\n expected_types = ['NUMBER'] + ['WORD'] * 8\n\n self.assertEqual(token_types, expected_types)\n\n def test_token_empty_stream(self):\n buffer = \"\"\n\n token_types = get_token_stream_types(self.lexer, buffer)\n expected_types = []\n\n self.assertEqual(token_types, expected_types)\n\n def test_syntax_error(self):\n buffer = \"words then some forbidden token ?\"\n self.assertRaises(LexerError, get_token_stream, self.lexer, buffer)\n\n\nclass LexerTestSpecialActions(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n def letter_counter(t):\n t.params['letters'] += 1\n\n def digit_counter(t):\n t.params['digits'] += 1\n\n rules = [\n (r'[a-z]', letter_counter, 'trigger_on_contain'),\n (r'[0-9]', digit_counter, 'trigger_on_contain'),\n (r'[a-zA-Z0-9]+', 'TOKEN'),\n (r'[a-zA-Z0-9]+END', 'TOKEN', 'non_greedy'),\n (r' ', None)\n ]\n\n cls.lexer = Lexer(rules=rules, line_rule='\\n', params={'letters': 0, 'digits': 0})\n cls.lexer.build()\n\n cls.lexer_copy = copy.deepcopy(cls.lexer)\n\n def tearDown(self):\n self.__class__.lexer = copy.deepcopy(self.lexer_copy)\n\n def test_trigger_on_contain(self):\n buffer = 'foo bar 1 test 567'\n get_token_stream(self.lexer, buffer)\n\n self.assertEqual(self.lexer.params['letters'], 10)\n self.assertEqual(self.lexer.params['digits'], 4)\n\n def test_non_greedy(self):\n buffer = 'fooENDbar'\n token_types = get_token_stream_types(self.lexer, buffer)\n expected = ['TOKEN', 'TOKEN']\n\n self.assertEqual(token_types, expected)\n\n def test_sample(self):\n buffer = ' foo bar\\n' + 'bar foo '\n token_types = get_token_stream_types(self.lexer, buffer)\n expected = ['TOKEN'] * 4\n\n self.assertEqual(token_types, expected)\n\n\nclass LexerTestController(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n def skip_next(t):\n t.increment_pos()\n\n def increment_line(t):\n t.increment_line()\n\n rules = [\n (r'[a-zA-Z]', 'LETTER'),\n (r'\\n', None),\n (r'\\n', increment_line, 'trigger_on_contain'),\n (r'[a-zA-Z]', skip_next, 'trigger_on_contain')\n ]\n\n cls.lexer = Lexer(rules=rules)\n cls.lexer.build()\n\n cls.lexer_copy = copy.deepcopy(cls.lexer)\n\n def tearDown(self):\n self.__class__.lexer = copy.deepcopy(self.lexer_copy)\n\n def test_increment_pos(self):\n buffer = 'A1V3K6'\n\n token_types = get_token_stream_types(self.lexer, buffer)\n expected = ['LETTER'] * 3\n\n self.assertEqual(token_types, expected)\n\n def test_increment_line(self):\n buffer = '\\n\\n'\n\n self.assertEqual(self.lexer.lineno, 1)\n\n token_types = get_token_stream(self.lexer, buffer)\n expected = []\n\n self.assertEqual(token_types, expected)\n self.assertEqual(self.lexer.lineno, 3)\n\n\nclass LexerTestLineRule(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n rules = [\n (r'\\w+', 'WORD'),\n (r' |\\t', None)\n ]\n\n cls.lexer = Lexer(rules=rules, line_rule='\\n')\n cls.lexer.build()\n\n cls.lexer_copy = copy.deepcopy(cls.lexer)\n\n def tearDown(self):\n self.__class__.lexer = copy.deepcopy(self.lexer_copy)\n\n def test_line_rule(self):\n buffer = \"\"\"some code\n some more code\n \"\"\"\n\n self.lexer.read(buffer)\n\n t = self.lexer.lex()\n self.lexer.lex()\n self.assertEqual(self.lexer.lineno, 1)\n self.lexer.lex()\n self.assertEqual(self.lexer.lineno, 2)\n\n get_token_stream(self.lexer, '')\n\n self.assertEqual(self.lexer.lineno, 3)\n\n\nclass LexerTestRegexp(unittest.TestCase):\n def test_match_dot(self):\n rules = [\n (r'.', 'DOT')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n lexer.read('a\\n')\n\n tk = lexer.lex()\n self.assertEqual(tk.value, 'a')\n self.assertRaises(LexerError, lexer.lex)\n\n def test_match_any(self):\n rules = [\n (r'_', 'ANY')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, '&F=\\n')\n self.assertEqual(token_values, ['&', 'F', '=', '\\n'])\n\n def test_match_kleene(self):\n # The x before the MANY_A rule is needed as regexp must have minimal length over 0\n rules = [\n (r'xa*', 'MANY_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'xxaaa')\n self.assertEqual(token_values, ['x', 'xaaa'])\n\n def test_match_plus(self):\n rules = [\n (r'a+', 'MANY_A'),\n (r'xa+', 'X_WITH_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'aaa')\n self.assertEqual(token_values, ['aaa'])\n\n lexer.read('x')\n self.assertRaises(LexerError, lexer.lex)\n\n def test_match_optional(self):\n rules = [\n (r'xa?', 'X_MAYBE_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'xxa')\n self.assertEqual(token_values, ['x', 'xa'])\n\n def test_match_amount(self):\n rules = [\n (r'a{3}', 'THREE_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n lexer.read('aaaaa')\n tk = lexer.lex()\n self.assertEqual(tk.value, 'aaa')\n self.assertRaises(LexerError, lexer.lex)\n\n def test_match_min_max_amount(self):\n rules = [\n (r'a{2, 3}x', 'THREE_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n lexer.read('aaaxaaxax')\n tk = lexer.lex()\n self.assertEqual(tk.value, 'aaax')\n tk = lexer.lex()\n self.assertEqual(tk.value, 'aax')\n self.assertRaises(LexerError, lexer.lex)\n\n def test_match_or(self):\n rules = [\n (r'A|B', 'A_OR_B')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'AB')\n self.assertEqual(token_values, ['A', 'B'])\n\n def test_match_set(self):\n rules = [\n (r'[abc]', 'ABC')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'abc')\n self.assertEqual(token_values, ['a', 'b', 'c'])\n self.assertRaises(LexerError, get_token_stream, lexer, 'd')\n\n def test_match_set_inverse(self):\n rules = [\n (r'[^a]', 'NOT_A')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, 'bcd')\n self.assertEqual(token_values, ['b', 'c', 'd'])\n self.assertRaises(LexerError, get_token_stream, lexer, 'a')\n\n def test_match_escape(self):\n rules = [\n (r'\\*', 'STAR')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n token_values = get_token_stream_values(lexer, '*')\n self.assertEqual(token_values, ['*'])\n\n def test_match_escape_space(self):\n rules = [\n (r'\\s', 'SPACE')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = ' \\t\\n\\r\\f\\v'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n\n def test_match_escape_non_space(self):\n rules = [\n (r'\\S', 'NOT_SPACE')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = 'abc'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n for c in ' \\t\\n\\r\\f\\v':\n lexer.pos = 0\n lexer.buffer = ''\n self.assertRaises(LexerError, get_token_stream, lexer, c)\n\n def test_match_escape_alphanum(self):\n rules = [\n (r'\\w', 'ALPHNUM')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n\n def test_match_escape_non_alphanum(self):\n rules = [\n (r'\\W', 'NOT_ALPHANUM')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = '.:+!@#:'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890':\n lexer.pos = 0\n lexer.buffer = ''\n self.assertRaises(LexerError, get_token_stream, lexer, c)\n\n def test_match_escape_num(self):\n rules = [\n (r'\\d', 'NUM')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = '123456789'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n\n def test_match_escape_non_num(self):\n rules = [\n (r'\\D', 'NOT_NUM')\n ]\n\n lexer = Lexer(rules=rules)\n lexer.build()\n\n buffer = '.:+!@#:ABCabcxyzXYZ'\n token_values = get_token_stream_values(lexer, buffer)\n self.assertEqual(token_values, list(buffer))\n for c in '123456789':\n lexer.pos = 0\n lexer.buffer = ''\n self.assertRaises(LexerError, get_token_stream, lexer, c)\n\n\nclass LexerTestRegexpPriority(unittest.TestCase):\n\n def test_priority(self):\n \"\"\"\n Challenge the RegExp module on various corner case of regexp operation priority\n \"\"\"\n\n expected_rule_buffer_outputs = [\n (r'abc|def', 'abc', ['abc']),\n (r'abc|def', 'def', ['def']),\n (r'abc|def', 'abdef', FAIL),\n (r'ab(c|d)ef', 'abcef', ['abcef']),\n (r'ab(c|d)ef', 'abc', FAIL),\n (r'ab(c|d)ef', 'def', FAIL),\n (r'a|b+', 'a', ['a']),\n (r'a|b+', 'b', ['b']),\n (r'a|b+', 'bb', ['bb']),\n (r'a|b+', 'bbb', ['bbb']),\n (r'a|b+', 'aa', ['a', 'a']),\n (r'a+|b+', 'aaa', ['aaa']),\n (r'a+|b+', 'bb', ['bb']),\n (r'a+|b+', 'aabb', ['aa', 'bb']),\n (r'(a|b)+', 'a', ['a']),\n (r'(a|b)+', 'b', ['b']),\n (r'(a|b)+', 'aba', ['aba']),\n (r'ab{1,3}', 'ab', ['ab']),\n (r'ab{1,3}', 'abb', ['abb']),\n (r'ab{1,3}', 'abbb', ['abbb']),\n (r'ab{1,3}', 'abbbb', FAIL),\n (r'(a|b){1,2}', 'ab', ['ab']),\n (r'(a|b){1,2}', 'ba', ['ba']),\n (r'(a|b){1,2}', 'b', ['b']),\n (r'(a|b){1,2}', 'aaa', ['aa', 'a']),\n (r'a{2}+', 'aa', ['aa']),\n (r'a{2}+', 'aaaa', ['aaaa']),\n (r'a+{2}', 'aa', ['aa']),\n (r'a+{2}', 'aaa', ['aaa']),\n (r'a+{2}', 'a', FAIL),\n (r'(a*b)+', 'bbabaab', ['bbabaab']),\n (r'[a-z][A-Z]+', 'xXX', ['xXX']),\n (r'[a-z][A-Z]+', 'xXxXX', ['xX', 'xXX']),\n (r'([a-z][A-Z])+', 'xXxX', ['xXxX']),\n (r'([a-z][A-Z])+', 'xXX', FAIL),\n (r'([a-z][A-Z])+', 'XxX', FAIL),\n (r'a([bc]d)*', 'abd', ['abd']),\n (r'a([bc]d)*', 'a', ['a']),\n (r'a([bc]d)*', 'abdcdbd', ['abdcdbd']),\n (r'a([bc]d)*', 'abdacdbd', ['abd', 'acdbd']),\n (r'a([bc]d)*', 'add', FAIL),\n (r'a([bc]d)*', 'abc', FAIL),\n (r'a|b|c', 'a', ['a']),\n (r'a|b|c', 'b', ['b']),\n (r'a|b|c', 'c', ['c']),\n (r'a|b|c', 'ac', ['a', 'c']),\n (r'(a|b)|c', 'a', ['a']),\n (r'(a|b)|c', 'b', ['b']),\n (r'(a|b)|c', 'c', ['c']),\n (r'(a|b)|c', 'ac', ['a', 'c']),\n (r'xa?|bc', 'x', ['x']),\n (r'xa?|bc', 'xa', ['xa']),\n (r'xa?|bc', 'bc', ['bc']),\n (r'xa?|bc', 'xbc', ['x', 'bc']),\n (r'[^\\W]\\++(j|l?)?', 'a+', ['a+']),\n (r'[^\\W]\\++(j|l?)?', 'b++j', ['b++j']),\n (r'[^\\W]\\++(j|l?)?', 'c+++l', ['c+++l']),\n (r'[^\\W]\\++(j|l?)?', 'a+a+', ['a+', 'a+']),\n (r'[^\\W]\\++(j|l?)?', 'a+ja+', ['a+j', 'a+']),\n (r'[^\\W]\\++(j|l?)?', '$+j', FAIL),\n (r'[^\\W]\\++(j|l?)?', 'w+jl', FAIL),\n ]\n\n for rules, buffer, expected in expected_rule_buffer_outputs:\n if expected is not FAIL:\n self.assertEqual(\n test_regexp_on_buffer(rules, buffer),\n expected\n )\n else:\n self.assertRaises(\n LexerError,\n test_regexp_on_buffer, rules, buffer\n )\n\n\n\nclass LexerTestTerminalAction(unittest.TestCase):\n def test_single_terminal_action(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_matches(t):\n t.params['count'] += 1\n\n lexer = Lexer(rules=rules, line_rule='\\s', terminal_actions=[count_all_matches], params={'count': 0})\n lexer.build()\n\n get_token_stream(lexer, 'word word word')\n self.assertEqual(lexer.params['count'], 5)\n\n def test_two_terminal_action(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_matches(t):\n t.params['count'] += 1\n\n def count_all_matches_again(t):\n t.params['count'] += 1\n\n lexer = Lexer(\n rules=rules,\n line_rule='\\s',\n terminal_actions=[count_all_matches, count_all_matches_again],\n params={'count': 0}\n )\n lexer.build()\n\n get_token_stream(lexer, 'word word word')\n self.assertEqual(lexer.params['count'], 10)\n\n def test_terminal_action_always(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_matches(t):\n t.params['count'] += 1\n\n lexer = Lexer(\n rules=rules,\n line_rule='\\s',\n terminal_actions=[(count_all_matches, 'always')],\n params={'count': 0}\n )\n lexer.build()\n\n get_token_stream(lexer, 'word word word')\n self.assertEqual(lexer.params['count'], 5)\n\n def test_terminal_action_on_ignored(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_ignored(t):\n t.params['count'] += 1\n\n lexer = Lexer(\n rules=rules,\n line_rule='\\s',\n terminal_actions=[(count_all_ignored, 'only_ignored')],\n params={'count': 0}\n )\n lexer.build()\n\n get_token_stream(lexer, 'word word word')\n self.assertEqual(lexer.params['count'], 2)\n\n def test_terminal_action_on_tokens(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_tokens(t):\n t.params['count'] += 1\n\n lexer = Lexer(\n rules=rules,\n line_rule='\\s',\n terminal_actions=[(count_all_tokens, 'only_tokens')],\n params={'count': 0}\n )\n lexer.build()\n\n get_token_stream(lexer, 'word word word')\n self.assertEqual(lexer.params['count'], 3)\n\n def test_action_when_choices(self):\n rules = [\n (r'\\w+', 'WORD'),\n ]\n\n def count_all_tokens(t):\n pass\n\n self.assertRaises(LexerError, Lexer,\n rules=rules,\n terminal_actions=[(count_all_tokens, 'only_foo')]\n )\n\n\nclass LexerTestBuild(unittest.TestCase):\n\n def test_regexp_minimum_length(self):\n rules = [\n (r'a*', 'A')\n ]\n\n lexer = Lexer(rules=rules)\n\n self.assertRaises(LexerError, lexer.build)\n\n def test_special_action_choices(self):\n rules = [\n (r'a', 'A', 'foo')\n ]\n\n lexer = Lexer(rules=rules)\n\n self.assertRaises(LexerError, lexer.build)\n\n\nclass LexerTestSave(LexerTestBasic):\n \"\"\"\n Rerun the tests from LexerTestBasic but by saving and loading the created lexer before tests\n \"\"\"\n lexer_filename = \"test_lexer_save.p\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.lexer.save(cls.lexer_filename)\n\n def tearDown(self):\n self.__class__.lexer = Lexer.load(self.lexer_filename)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"tests/test_lexer.py","file_name":"test_lexer.py","file_ext":"py","file_size_in_byte":17982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345791272","text":"# x''+b*x'+A*x^3=B*cos(omega*t)\n#A=1 omega=1 (B,b)=(7,6) \n# t=0 x=3 x'=0\n\nimport numpy as np\nimport math as m\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport multiprocessing\nimport time\nfrom numba import jit\ndef df2(x,z,t,):\n a=B*m.cos(t)-x*x*x-b*z\n return a\nkk=[[7,6],[7,0.6],[10,0.05],[7,0.01]]\np=0\nwhile p<4:\n B=kk[p][0]\n b=kk[p][1]\n n=100000\n i=0\n h=25*m.pi/n\n r=np.array([3,0])\n xx=[]\n yy=[]\n while i<=n:\n k1=np.array([r[1],df2(r[0],r[1],i*h)])\n #print(df2(r[0],r[1],i*h))\n r2=r+0.5*k1*h\n k2=np.array([r2[1],df2(r2[0],r2[1],i*h+0.5*h)])\n r3=r+0.5*k2*h\n k3=np.array([r3[1],df2(r3[0],r3[1],i*h+0.5*h)])\n r4=r+k3*h\n k4=np.array([r4[1],df2(r4[0],r4[1],i*h+h)])\n rplus=r+(1/6)*(k1+2*k2+2*k3+k4)*h\n r=rplus\n xx.append(r[0])\n yy.append(i*h)\n i=i+1\n plt.figure(figsize=(10,10))\n plt.plot(yy,xx)\n a1='b_time'\n a2=str(kk[p][0])\n aa='_'\n a3=str(kk[p][1])\n a4='.png'\n plotPath= a1+a2+aa+a3+a4\n plt.savefig(plotPath)\n p=p+1\nplt.show()\n","sub_path":"Computational physics/HW13/HW13/project2/b_time.py","file_name":"b_time.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"278261858","text":"#import brian_no_units\n#from brian import *\nimport sys\nfrom pylab import *\nfrom time import time\n\n \n# [float(sys.argv[idx+i]) for i in xrange(nConns)]\nidx=1\nn = int(sys.argv[idx])\nidx=idx+ 1\nfileName_t = sys.argv[idx]\nidx=idx+ 1\nfileName_v = sys.argv[idx]\nidx=idx+ 1\n\nfileName_t2 = sys.argv[idx]\nidx=idx+ 1\nfileName_v2 = sys.argv[idx]\nidx=idx+ 1\n\nfileName_t3 = sys.argv[idx]\nidx=idx+ 1\nfileName_v3 = sys.argv[idx]\nidx=idx+ 1\n\nfileName_t4 = sys.argv[idx]\nidx=idx+ 1\nfileName_v4 = sys.argv[idx]\nidx=idx+ 1\n\nfileName_t5 = sys.argv[idx]\nidx=idx+ 1\nfileName_v5 = sys.argv[idx]\nidx=idx+ 1\n\nopFile = sys.argv[idx]\nidx=idx+1\n\ndoShow=int(sys.argv[idx]) #0=savefig, 1=show plot\n#t = [0,1,2,3,4,5,6,7,8,9]\n#v = [-60, -55, -50, -55, -40, -30, 0, 20, -55, -60]\n\nwith open(fileName_t) as f:\n tStr = f.read().splitlines()\n t = [float(tChar) for tChar in tStr]\nwith open(fileName_v) as f:\n vStr = f.read().splitlines()\n v = [float(vChar) for vChar in vStr]\n \nwith open(fileName_t2) as f:\n tStr2 = f.read().splitlines()\n t2 = [float(tChar) for tChar in tStr2]\nwith open(fileName_v2) as f:\n vStr2 = f.read().splitlines()\n v2 = [float(vChar) for vChar in vStr2]\n \nwith open(fileName_t3) as f:\n tStr3 = f.read().splitlines()\n t3 = [float(tChar) for tChar in tStr3]\nwith open(fileName_v3) as f:\n vStr3 = f.read().splitlines()\n v3 = [float(vChar) for vChar in vStr3]\n \nwith open(fileName_t4) as f:\n tStr4 = f.read().splitlines()\n t4 = [float(tChar) for tChar in tStr4]\nwith open(fileName_v4) as f:\n vStr4 = f.read().splitlines()\n v4 = [float(vChar) for vChar in vStr4]\n \nwith open(fileName_t5) as f:\n tStr5 = f.read().splitlines()\n t5 = [float(tChar) for tChar in tStr5]\nwith open(fileName_v5) as f:\n vStr5 = f.read().splitlines()\n v5 = [float(vChar) for vChar in vStr5]\n_title = ' '\n\nconstraint_string = ['A','B','C','D','E','F']\ncomp_title=[' ',' ']\n\nrcParams.update({'font.size': 12})\n\nfig = figure()\nfig.set_size_inches(5, 15, forward=True)\nbigsubplot = fig.add_subplot(1,1,1, axisbg='none') \n\nbigsubplot.set_xlabel('Time (ms)', labelpad=10)\nbigsubplot.set_ylabel('V (mV)', labelpad=20)\nbigsubplot.get_xaxis().set_ticklabels([])\nbigsubplot.get_yaxis().set_ticklabels([])\n# Turn off axis lines and ticks of the big subplot\nbigsubplot.spines['top'].set_color('none')\nbigsubplot.spines['bottom'].set_color('none')\nbigsubplot.spines['left'].set_color('none')\nbigsubplot.spines['right'].set_color('none')\nbigsubplot.tick_params(top='off', bottom='off', left='off', right='off')\n \nfig.add_subplot(5,1,1)\nplot(t, v, lw=1, color=[0.6,0,0])\nfig.add_subplot(5,1,2)\nplot(t2, v2, lw=1, color=[0.6,0,0])\nfig.add_subplot(5,1,3)\nplot(t3, v3, lw=1, color=[0.6,0,0])\nfig.add_subplot(5,1,4)\nplot(t4, v4, lw=1, color=[0.6,0,0])\nfig.add_subplot(5,1,5)\nplot(t5, v5, lw=1, color=[0.6,0,0])\n\nsubplots_adjust(left=.2)\nsubplots_adjust(hspace=.2)\n #axis('off')\n# plot(VM.times / ms, VM[i] / mV)\ndoShow=0\nif(doShow==0):\n savefig(\"output/\"+opFile+\".png\", dpi=100)\nif(doShow==1):\n #savefig(\"output/\"+opFile+\".svg\", dpi=300)\n show()","sub_path":"PythonScripts/_1cFromJava5V.py","file_name":"_1cFromJava5V.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"602002453","text":"import shutil\nimport os\nimport json\nimport time\nimport subprocess\nfrom pathlib import Path\n\n# const\nMOD_NAME = \"MomoTweak\"\nMOD_DIRECTORY = \"\\\\Mod\"\nINFO = \"\\\\info.json\"\nFACTORIO = \"factorio.exe\"\n\n# factorio don't load this zip file.\nIS_ZIP = False\nFactorioPath = [\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\common\\\\Factorio\\\\bin\\\\x64\\\\factorio.exe\",\n \"G:\\\\SteamLibrary\\\\steamapps\\\\common\\\\Factorio\\\\bin\\\\x64\\\\factorio.exe\", \n \"C:\\\\Program Files (x86)\\\\Steam\\\\factorio.exe\"]\n \n# variable\nFactorioModsPath = \"\"\nGitPath = \"\"\n\ndef Init():\n path = os.path.realpath(__file__)\n global GitPath\n GitPath = os.path.dirname(path)\n global FactorioModsPath\n FactorioModsPath = str(Path(GitPath).parent)\n print(\"Init\")\n print(\"Factorio Mod Path = \" + FactorioModsPath)\n print(\"GitPath = \" + GitPath)\n\ndef ZipDirectory(version):\n directory = GitPath + MOD_DIRECTORY\n print(\"Start export Directory :\" + directory)\n if (IS_ZIP):\n shutil.make_archive(MOD_NAME + \"_\" + version, 'zip', directory)\n return MOD_NAME + \"_\" + version + \".zip\"\n else:\n target_dir = FactorioModsPath + \"\\\\\" + MOD_NAME + \"_\" + version\n if os.path.isdir(target_dir) :\n shutil.rmtree(target_dir)\n shutil.copytree(directory, target_dir)\n return MOD_NAME + \"_\" + version\n return \"\"\n \ndef GetVersion():\n json_data = open(GitPath + MOD_DIRECTORY + INFO).read()\n info = json.loads(json_data)\n version = info[\"version\"]\n print (\"Read \" + INFO + \" get version = \" + version)\n return version\n\ndef MoveZipOut(zip_name):\n fileFrom = GitPath + '\\\\' + zip_name\n fileTo = FactorioModsPath + '\\\\' + zip_name\n print(\"Move \" + zip_name)\n print(\"From : \" + fileFrom)\n print(\"To : \" + fileTo)\n if os.path.isfile(fileTo) :\n os.remove(fileTo)\n print (\"file Exist \" + zip_name + \" Removed\")\n os.rename(fileFrom, fileTo)\n\ndef FindFactorio():\n task = os.popen('tasklist /nh /fi \"IMAGENAME eq \"' + FACTORIO).read()\n return FACTORIO in task\n\ndef RunFactorio():\n for factorio in FactorioPath :\n if os.path.isfile(factorio) :\n os.startfile(factorio)\n print(\"Run Factorio\")\n return\n print(\"No Factorio in path.\")\n\n# ==============================================================================\n\n# == Program ===================================================================\n\nInit()\nzipName = ZipDirectory(GetVersion())\nif IS_ZIP:\n MoveZipOut(zipName)\nprint(\"Export Completed\")\ntime.sleep(.500)\nif not (FindFactorio()):\n RunFactorio()\n\ntime.sleep(5.000)\n\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51240503","text":"while True:\n\tprint(\"Enter 'x' for exit.\")\n\tprint(\"Enter starting and ending number: \")\n\tstart = input()\n\tend = input()\n\tif start == 'x':\n\t\tbreak\n\telse:\n\t\tlower_number = int(start)\n\t\tupper_number = int(end)\n\t\tprint(\"\\nPrime Numbers between the given range:\")\n\t\tfor num in range(lower_number, upper_number+1):\n\t\t\tif num>1:\n\t\t\t\tfor i in range(2, num):\n\t\t\t\t\tif(num%i)==0:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(num)\n","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"557103667","text":"from openspending import model\nfrom ... import DatabaseTestCase, helpers as h\n\ndef mock_dimension():\n return {\n 'key': 'bar',\n 'label': 'some_dimension',\n 'type': 'classifier'\n }\n\nclass TestDimension(DatabaseTestCase):\n\n def test_dimension_create_raise_if_type_none(self):\n d = mock_dimension()\n\n del d['type']\n h.assert_raises(ValueError,\n model.dimension.create,\n dataset_name='foo',\n **d)\n\n def test_dimension_raise_if_type_value(self):\n d = mock_dimension()\n\n d['type'] = 'value'\n h.assert_raises(ValueError,\n model.dimension.create,\n dataset_name='foo',\n **d)","sub_path":"openspending/test/unit/model/test_dimension.py","file_name":"test_dimension.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"614161670","text":"\"\"\"\nImplementation of: Dissimilarity Mixture Autoencoder (DMAE) for Deep Clustering.\n\n**This package contains tf.keras.initializers that can be used to initialize DMAE.**\n\nAuthor: Juan Sebastián Lara Ramírez \n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom DMAE import Dissimilarities\nfrom sklearn.cluster import KMeans\n\nclass InitPlusPlus(tf.keras.initializers.Initializer):\n \"\"\"\n A tf.keras initializer similar to the K-Means++ initialization (Arthur, David, and Sergei Vassilvitskii. k-means++: The advantages of careful seeding. Stanford, 2006.) that allows dissimilarities.\n \n Arguments:\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n dissimilarity: function, default: DMAE.Dissimilarities.euclidean\n A tensorflow function that computes a paiwise dissimilarity function between a batch\n of points and the cluster's parameters (means and covariances).\n iters: int, default: 100\n Number of interations to run the K-means++ initialization.\n \"\"\"\n \n def __init__(self, X, n_clusters, dissimilarity=Dissimilarities.euclidean, iters=100):\n self.__X = X\n self.__n_clusters = n_clusters\n self.__dissimilarity = dissimilarity\n self.__iters = iters\n \n def __call__(self, shape, dtype):\n idx = np.arange(self.__X.shape[0])\n np.random.shuffle(idx)\n selected = idx[:self.__n_clusters]\n init_vals = self.__X[idx[:self.__n_clusters]]\n\n for i in range(self.__iters):\n clus_sim = self.__dissimilarity(init_vals, init_vals).numpy()\n np.fill_diagonal(clus_sim, np.inf)\n\n candidate = self.__X[np.random.randint(self.__X.shape[0])].reshape(1, -1)\n candidate_sims = self.__dissimilarity(candidate, init_vals).numpy().flatten()\n closest_sim = candidate_sims.min()\n closest = candidate_sims.argmin()\n if closest_sim>clus_sim.min():\n replace_candidates_idx = np.array(np.unravel_index(clus_sim.argmin(), clus_sim.shape))\n replace_candidates = init_vals[replace_candidates_idx, :]\n\n closest_sim = self.__dissimilarity(candidate, replace_candidates).numpy().flatten()\n replace = np.argmin(closest_sim)\n init_vals[replace_candidates_idx[replace]] = candidate\n else:\n candidate_sims[candidate_sims.argmin()] = np.inf\n second_closest = candidate_sims.argmin()\n if candidate_sims[second_closest] > clus_sim[closest].min():\n init_vals[closest] = candidate\n return tf.cast(init_vals, dtype)\n\nclass InitKMeans(tf.keras.initializers.Initializer):\n \"\"\"\n A tf.keras initializer to assign the clusters from a sklearn's KMeans model to DMAE.\n \n Arguments:\n kmeans_model: sklearn.cluster.KMeans\n Pretrained KMeans model to initialize DMAE.\n \"\"\"\n \n def __init__(self, kmeans_model):\n self.__kmeans = kmeans_model\n \n def __call__(self, shape, dtype):\n return tf.cast(self.__kmeans.cluster_centers_, dtype)\n \nclass InitIdentityCov(tf.keras.initializers.Initializer):\n \"\"\"\n A tf.keras initializer to assign identity matrices to covariances in DMAE.\n \n Arguments:\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n \"\"\"\n \n def __init__(self, X, n_clusters):\n self.__X = X\n self.__n_clusters = n_clusters\n \n def __call__(self, shape, dtype):\n return tf.eye(self.__X.shape[1], batch_shape=[self.__n_clusters])\n \nclass InitKMeansCov(tf.keras.initializers.Initializer):\n \"\"\"\n A tf.keras initializer to compute covariance matrices from K-means assignments to initialize DMAE.\n \n Arguments:\n kmeans_model: sklearn.cluster.KMeans\n Pretrained KMeans model to initialize DMAE.\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n \"\"\"\n def __init__(self, kmeans_model, X, n_clusters):\n self.__kmeans_model = kmeans_model\n self.__X = X\n self.__n_clusters = n_clusters\n \n def __call__(self, shape, dtype):\n res = []\n preds = self.__kmeans_model.predict(self.__X)\n for i in range(self.__n_clusters):\n clus_points = self.__X[preds==i]\n res.append(np.expand_dims(np.linalg.cholesky(np.linalg.inv(np.cov(clus_points.T))), axis=0))\n return tf.cast(np.concatenate(res, axis=0), dtype)\n \nclass initializers():\n def __init__(self):\n self.InitPlusPlus = InitPlusPlus\n self.InitKMeans = InitKMeans\n self.InitIdentityCov = InitIdentityCov\n self.InitKMeansCov = InitKMeansCov","sub_path":"DMAE/Initializers.py","file_name":"Initializers.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"154594493","text":"#!/usr/bin/env python\n\n\"\"\"\nThis script takes enhancerLifted.db as input, and finds unique regions labeled as enhancers.\nThe output will be several .db database files, one for each species represented in the original\ndataset.\n\"\"\"\n\nf_in = open(\"enhancerLifted.db.sorted\")\n\ns_p = \"\"\nc_p = \"\"\n\nfor line in f_in:\n\tfields = line.strip().split(\"\\t\")\n\ts = fields[3].lower()\n\tc = fields[0]\n\tstart = int(fields[1])\n\tend = int(fields[2])\n\tcontext = eval(fields[4])\n\tvalidation = fields[5]\n\tbuild = fields[6]\n\ttargets = eval(fields[7])\n\tdoi = fields[8]\n\taccession = fields[9]\n\n\tif s == s_p:\n\t\tif c == c_p:\n\t\t\tif start <= (reg_end + 200):\n\t\t\t\tif end > reg_end:\n\t\t\t\t\treg_end = end\n\t\t\t\t\treg_con = reg_con + context\n\t\t\t\t\treg_val = reg_val + \", \" + validation\n\t\t\t\t\treg_tar = reg_tar + targets\n\t\t\t\t\tdoi = reg_doi + \", \" + doi\n\t\t\t\t\treg_acc = reg_acc + \", \" + accession\n\t\t\telse:\n\t\t\t\tnl = c_p + \"\\t\" + str(reg_start) + \"\\t\" + str(reg_end) + \"\\t\" + s_p + \"\\t\" + str(reg_con) + \"\\t\" + \\\n\t\t\t\t\treg_val + \"\\t\" + reg_bld + \"\\t\" + str(reg_tar) + \"\\t\" + reg_doi + \"\\t\" + reg_acc + '\\n'\n\t\t\t\tg.write(nl)\n\t\t\t\treg_start = start\n\t\t\t\treg_end = end\n\t\t\t\treg_con = context\n\t\t\t\treg_val = validation\n\t\t\t\treg_bld = build\n\t\t\t\treg_tar = targets\n\t\t\t\treg_doi = doi\n\t\t\t\treg_acc = accession\n\t\telse:\n\t\t\tnl = c_p + \"\\t\" + str(reg_start) + \"\\t\" + str(reg_end) + \"\\t\" + s_p + \"\\t\" + str(reg_con) + \"\\t\" + \\\n\t\t\t\treg_val + \"\\t\" + reg_bld + \"\\t\" + str(reg_tar) + \"\\t\" + reg_doi + \"\\t\" + reg_acc + '\\n'\n\t\t\tg.write(nl)\n\t\t\tc_p = c\n\t\t\treg_start = start\n\t\t\treg_end = end\n\t\t\treg_con = context\n\t\t\treg_val = validation\n\t\t\treg_bld = build\n\t\t\treg_tar = targets\n\t\t\treg_doi = doi\n\t\t\treg_acc = accession\n\telse:\n\t\tif s_p != \"\":\n\t\t\tnl = c_p + \"\\t\" + str(reg_start) + \"\\t\" + str(reg_end) + \"\\t\" + s_p + \"\\t\" + str(reg_con) + \"\\t\" + \\\n\t\t\t\treg_val + \"\\t\" + reg_bld + \"\\t\" + str(reg_tar) + \"\\t\" + reg_doi + \"\\t\" + reg_acc + '\\n'\n\t\t\tg.write(nl)\n\t\t\tg.close()\n\t\tg = open( s + \"_nonRed.db\", \"wb\" )\n\t\ts_p = s\n\t\tc_p = c\n\t\treg_start = start\n\t\treg_end = end\n\t\treg_con = context\n\t\treg_val = validation\n\t\treg_bld = build\n\t\treg_tar = targets\n\t\treg_doi = doi\n\t\treg_acc = accession\n\nnl = c_p + \"\\t\" + str(reg_start) + \"\\t\" + str(reg_end) + \"\\t\" + s_p + \"\\t\" + str(reg_con) + \"\\t\" + \\\n\treg_val + \"\\t\" + reg_bld + \"\\t\" + str(reg_tar) + \"\\t\" + reg_doi + \"\\t\" + reg_acc + '\\n'\ng.write(nl)\ng.close()\n\n## ** Check to see if the final line is being duplicated.","sub_path":"Aim_3_Enh_Pred/Aim_3_1/enhancer_db/bin/db_unique.py","file_name":"db_unique.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"170693152","text":"matriz = list()\nlinha = list()\nsPares = s3c = m2l = 0\n\nfor i in range(0, 3):\n for j in range(0, 3):\n linha.append(int(input(f'Digite o elemento ({i},{j}) = ')))\n matriz.append(linha[:])\n linha.clear()\nprint('=~' * 15)\nfor i in range(0, 3):\n print(f' [{matriz[i][0]}:^3] [{matriz[i][1]}:^3] [{matriz[i][2]}:^3] ')\nprint('=~' * 15)\nfor linha in matriz:\n for num in linha:\n if num % 2 == 0:\n sPares += num\nprint(f'A soma dos valores pares é {sPares}')\n\nfor i in range(0, 3):\n s3c += matriz[i][2]\n\nprint(f'A soma dos valores da terceira coluna é {s3c}')\n\nfor i in range(0, 3):\n if i == 0:\n m2l = matriz[1][0]\n elif m2l < matriz[1][i]:\n m2l = matriz[1][i]\n\nprint(f'E o maior da segunda linha é {m2l}')\n","sub_path":"Exercícios - Mundo 3/Ex087.py","file_name":"Ex087.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"536704664","text":"class Solution(object):\n def findCircleNum(self, K): \n circles = 0\n visited = set()\n for person in range(len(K)):\n if person not in visited:\n circles += 1\n self.dfs(person, K, visited)\n \n return circles\n \n \n def dfs(self, node, K, visited):\n for person, is_friend in enumerate(K[node]):\n if is_friend and person not in visited:\n visited.add(person)\n self.dfs(person, K, visited)\n \"\"\"\n :type M: List[List[int]]\n :rtype: int\n \"\"\"\n","sub_path":"Week_One/Friends_Circle.py","file_name":"Friends_Circle.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"86799813","text":"\n\nwith open('package.log', 'rb') as file:\n\tdata = file.read()\n\tprint('file size = {}'.format(len(data)))\n\nidx0 = data.index(b'\\xff\\xd8\\xff')\nidx1 = data.index(b'\\xff\\xd9')\n\nif idx1 < idx0:\n\tprint(\"Limpiando imagen. idx = {}, {}\".format(idx0, idx1))\n\tdata = data[idx0:]\n\nidx = 0\nwhile True:\n\ttry:\n\t\tidxb = data.index(b'\\xff\\xd8\\xff')\n\t\tprint(\"Image {}: idxb = {}\".format(idx, idxb))\n\texcept:\t\n\t\tprint(\"End of buffer: 0\")\n\t\tbreak\n\n\ttry:\n\t\tidxe = data.index(b'\\xff\\xd9')\n\t\tprint(\"Image {}: idxe = {}\".format(idx, idxe))\n\texcept:\t\n\t\tprint(\"End of buffer: 1\")\n\t\tbreak\n\n\twith open('prueba_video.avi', 'ab') as file:\n\t\tfile.write(data[idxb:idxe+2])\n\tdata = data[idxe+2:]\n\tidx = idx + 1","sub_path":"WirelessIPCamera/Wireless_Camera_Server/sock/Codigos de respaldo/video1.py","file_name":"video1.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585461196","text":"import tensorflow as tf\n\ninput = tf.constant([[[[1], [2], [3]],\n [[4], [5], [6]],\n [[7], [8], [9]]]],\n dtype=tf.float32)\n\n# input = tf.constant([[[[-0.8113182 ], [ 1.4845988 ], [ 0.06532937]],\n# [[-2.4427042 ], [ 0.0992484 ], [ 0.5912243 ]],\n# [[ 0.59282297], [-2.1229296 ], [-0.72289723]]]],\n# dtype=tf.float32)\n\nprint(\"input.shape\")\nwith tf.Session() as se:\n se.run(tf.global_variables_initializer())\n print(se.run(input))\n\nprint( \"filter.shape\")\nfilter = tf.Variable(tf.random_normal([3,3,1, 1], stddev = 1, seed = 1))\n# filter = tf.Variable(tf.ones([1, 1, 1, 2]));\nwith tf.Session() as se:\n se.run(tf.global_variables_initializer());\n print(se.run(filter));\n\nprint(\"tf.conv2d\")\nop = tf.nn.conv2d(input, filter, strides = [1, 1, 1, 1], padding = 'VALID')\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n result = sess.run(op)\n print(result)\n","sub_path":"csdnexamples/conv2dtest1.py","file_name":"conv2dtest1.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"191302686","text":"\nimport os\nimport csv\nimport math\n\nchanges = []\nammount = []\nsustrahend = []\nminuend = []\npair = []\n\nprint(\"\"\"\n-----------------------------------------------------------------------------------------\n Financial Analysis\n-----------------------------------------------------------------------------------------\n\"\"\")\n\nfile_csv = os.path.join(\"..\",\"Resources\", \"budget_data.csv\")\n\n# OPENING THE DOOR\nwith open(file_csv, \"r\") as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=\",\")\n header=next(csv_reader)\n csv_reader= list(csv_reader)\n# Getting the number of lines no header = number of months\n num_months = len(csv_reader)\n print(f\"Total months: {num_months}\")\n# Go for the total ammount\n for obs in csv_reader:\n ammount.append(obs[1])\n total_ammount = [float(obs1) for obs1 in ammount]\n total_ammount1 = sum(total_ammount)\n print(f\"Total: {total_ammount1}\")\n# Get averange of the changes\n# SUSTRAHEND\n for row in ammount:\n sustrahend.append(row)\n if row == \"671099\":\n sustrahend.remove(row)\n total_sustrahend = [float(row) for row in sustrahend]\n\n# MINUEND\n for x in ammount:\n minuend.append(x)\n if x == \"867884\":\n minuend.remove(x)\n\n total_minuend = [float(x) for x in minuend]\n\n#making a zip object, looking for a tuple\n\n zip_object = zip(total_sustrahend, total_minuend)\n\n for total_sustrahend, total_minuend in zip_object:\n changes.append(total_minuend-total_sustrahend) \n \n total_changes = sum(changes)\n average_changes = total_changes/len(changes)\n\n print(f\"Average change: ${average_changes}\")\n\n# Going for greatest increase and decrease using the index of the list changes\n maximu = math.trunc(max(changes))\n minimu = math.trunc(min(changes))\n \n index_max = changes.index(maximu)\n index_min = changes.index(minimu)\n\n worst_change = changes[int(index_min)]\n worst_month = csv_reader[int(index_min)+1]\n\n best_change = changes[int(index_max)]\n best_month = csv_reader[int(index_max)+1]\n\n print(f\"Greatest Increase in Profits: {best_month[0]} (${math.trunc(best_change)})\")\n print(f\"Greatest Decrease in Profits: {worst_month[0]} (${math.trunc(worst_change)})\")\n\n\n# Export into a text file with the results\nbudget_final = os.path.join(\"..\",\"Resources\",\"budget_data_final.txt\")\n\nwith open(budget_final, \"w\") as file_final:\n\n file_final.write(\"Financial Analysis\\n\")\n file_final.write(\"-----------------------------------------------\\n\")\n file_final.write(f\"Total months: {num_months}\\n\")\n file_final.write(f\"Total: ${total_ammount1}\\n\")\n file_final.write(f\"Average Change: ${average_changes}\\n\")\n file_final.write(f\"Greatest Increase in Profits: {best_month[0]} (${math.trunc(best_change)})\\n\")\n file_final.write(f\"Greatest Decrease in Losses: {worst_month[0]} (${math.trunc(worst_change)})\\n\")\n\n\nprint(\"\"\"\n-----------------------------------------------------------------------------------------\n We've finished!\n-----------------------------------------------------------------------------------------\n\"\"\")\n\n\n\n","sub_path":"PyBank/Resources/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"105292258","text":"\"\"\"\nbirthday.py\nAuthor: jaEimele24\nCredit: Tutorials\nAssignment: Birthday-quiz\n\nYour program will ask the user the following questions, in this order:\n\n1. Their name.\n2. The name of the month they were born in (e.g. \"September\").\n3. The year they were born in (e.g. \"1962\").\n4. The day they were born on (e.g. \"11\").\n\nIf the user's birthday fell on October 31, then respond with:\n\n You were born on Halloween!\n\nIf the user's birthday fell on today's date, then respond with:\n\n Happy birthday!\n\nOtherwise respond with a statement like this:\n\n Peter, you are a winter baby of the nineties.\n\nExample Session\n\n Hello, what is your name? Eric\n Hi Eric, what was the name of the month you were born in? September\n And what year were you born in, Eric? 1972\n And the day? 11\n Eric, you are a fall baby of the stone age.\n\"\"\"\nfrom datetime import datetime\nfrom calendar import month_name\ntodaymonth = datetime.today().month\ntodaydate = datetime.today().day\nName=input('Hello, what is your name? ')\nBirthMonth=input('Hi {0}, what was the name of the month you were born in? '.format(Name))\nBirthyear=int(input('And what year were you born in, {0}? '.format(Name)))\nBirthDay=int(input('And the day? '))\nBearthseason=1\nBirthage=2\nk=0\nif BirthMonth == \"October\" and BirthDay == 31:\n print('You were born on Halloween!')\n k=1\nmonth = month_name[todaymonth]\nif BirthDay==todaydate and BirthMonth==month:\n print('Happy birthday!')\n k=1\nif BirthMonth == \"December\" or BirthMonth == \"January\" or BirthMonth == \"February\":\n Birthseason = \"winter\"\nif BirthMonth == \"March\" or BirthMonth == \"April\" or BirthMonth == \"May\":\n Birthseason=\"spring\"\nif BirthMonth == \"June\" or BirthMonth == \"July\" or BirthMonth == \"August\":\n Birthseason = \"summer\"\nif BirthMonth == \"September\" or BirthMonth == \"October\" or BirthMonth == \"November\":\n Birthseason = \"fall\"\nif Birthyear < 1980:\n Birthage=\"Stone Age\"\nif Birthyear >= 1980 and Birthyear < 1990:\n Birthage=\"eighties\"\nif Birthyear >= 1990 and Birthyear < 2000:\n Birthage=\"nineties\"\nif Birthyear >= 2000:\n Birthage=\"two thousands\"\nrandomplatitudes=\"you are a\"\nmorepointlesswords=\"baby of the\"\ndumbpunctuation=\",\"\nname=Name,\nif k==0:\n print('{0}, {1} {2} {3} {4}.'.format(Name,randomplatitudes,Birthseason,morepointlesswords,Birthage))\n\n\n\n","sub_path":"birthday.py","file_name":"birthday.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"471227854","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[2]:\n\n\nfrom lxml import html\nimport requests\nimport urllib\nimport re as regex\n\n\n# In[3]:\n\n\n# load data from AEA_NDA excel sheet - pre 2004\ndrug_list_pre_2004 = pd.read_csv('../raw_data/drug_list_pre_2004.csv')\n\n# convert nda_num to 6 digit format\ndrug_list_pre_2004['nda_num'] = drug_list_pre_2004['nda_num'].astype(str) \ndrug_list_pre_2004['nda_num'] = drug_list_pre_2004.nda_num.str.zfill(6) \n\n# convert nda_num column to a list\nnda_num_list_pre_2004 = drug_list_pre_2004['nda_num'].to_list()\n\n# sort the list\nnda_num_list_pre_2004.sort()\n\n# create a random sample of 100 nda_num for testing purposes\nnda_num_list_pre_2004_random100 = np.random.choice(nda_num_list_pre_2004, 100, replace = False)\n\nnda_num_list_pre_2004.head()\n\n\n# In[ ]:\n\n\n# load data from AEA_NDA excel sheet - post 2004\ndrug_list_post_2004 = pd.read_csv('../raw_data/drug_list_post_2004.csv')\n\n# convert nda_num to 6 digit format\ndrug_list_post_2004['nda_num'] = drug_list_post_2004['nda_num'].astype(int) \ndrug_list_post_2004['nda_num'] = drug_list_post_2004['nda_num'].astype(str) \ndrug_list_post_2004['nda_num'] = drug_list_post_2004.nda_num.str.zfill(6) \n\n# convert nda_num column to a list\nnda_num_list_post_2004 = drug_list_post_2004['nda_num'].to_list()\n\n# sort the list\nnda_num_list_post_2004.sort()\n\nnda_num_list_post_2004.head()\n\n\n# In[ ]:\n\n\n# loop over all nda_num\nfor nda_num in nda_num_list_pre_2004:\n \n number_of_files_saved = 0\n print('Searching approval letters for ', nda_num)\n\n # get html content of the drug web page\n page = requests.get('https://www.accessdata.fda.gov/scripts/cder/daf/index.cfm?event=overview.process&ApplNo=' + nda_num)\n tree = html.fromstring(page.content)\n\n # iterate through all links in the page content\n for elem in tree.iterlinks():\n \n # get the 2nd element of the link tuple\n link_to_letter = elem[2]\n \n # check if the link is a pdf\n # split link into a list by \".\" and get the last elem, which is the file extension\n fileExtension = link_to_letter.split(\".\")[-1] \n if fileExtension == \"pdf\":\n \n # use regex to check if its approval letter and not a supplement letter\n if((bool(regex.search('.*(appletter).*', link_to_letter))) \n and (not bool(regex.search('.*(((s|S|slr|SLR|se|SE|sel|SEL|scp|SCP|scm|SCM|scf|SCF|scr|SCR|spd|SPD)[0-9]+)|(/(slc|SLC)/)).*', link_to_letter))) \n and (not bool(regex.search('.*([0-9]{30,}).*', link_to_letter)))):\n \n print('Checking .. ', link_to_letter)\n \n # use regex to extract year from link url\n year = regex.match('.*/(([0-9][0-9][0-9][0-9])|([0-9][0-9])|(pre96))/.*', link_to_letter).groups()[0]\n \n # replace spaces with %20 in url\n link_to_letter = link_to_letter.replace(\" \", \"%20\")\n \n print('Downloading ... ', link_to_letter)\n urllib.request.urlretrieve(link_to_letter, './../results/approval_letters/' + year + '/' + nda_num + '-' + str(number_of_files_saved) + '.pdf')\n \n number_of_files_saved = number_of_files_saved + 1\n\n print('Search complete.')\n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"dowloading_drug_letters.py","file_name":"dowloading_drug_letters.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"612107401","text":"class PhoneBookList(object):\n \"\"\"docstring for PhoneBookList\"\"\"\n def __init__(self):\n super(PhoneBookList, self).__init__()\n self.book = []\n\n def add_contact(self, username, phone_number):\n self.book.append((username, phone_number))\n\n def search(self, username):\n count = 0\n\n for u, p in self.book:\n count += 1\n if u == username:\n result = {\n 'count': count,\n 'phone_number': p\n }\n return result\n result = {\n 'count': count,\n 'phone_number': None\n }\n\n return result\n\n\nclass PhoneBookDict(object):\n \"\"\"docstring for PhoneBookDict\"\"\"\n def __init__(self):\n super(PhoneBookDict, self).__init__()\n self.book = {}\n\n def add_contact(self, username, phone_number):\n self.book[username] = phone_number\n\n def search(self, username):\n result = {\n 'count': 1,\n 'phone_number': self.book.get(username, None)}\n return result\n","sub_path":"29-01-2016/data_structure.py","file_name":"data_structure.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"375721689","text":"# import libraries\nimport re\nimport sys\nimport functions\nimport unidecode\nimport requests\nfrom bs4 import BeautifulSoup\n\n# specify the url\nurl = 'https://www.hplovecraft.com/writings/texts/fiction/mm.aspx'\n\n# setting our translation conditions\ntranslation = {ord('—'): ' ', ord('′'): None, ord(\"”\"): \".\", ord(\"“\"): None}\n\n# query the website and return the html to the variable 'response'\nresponse = requests.get(url)\n\n# checking if we get a response from the website before continue\nif response.ok:\n\n # parse the html using beautiful soup and store in variable 'soup'\n soup = BeautifulSoup(response.text,features=\"html.parser\")\n\n # select the part we need in the html, here the division with the book content\n book = soup.find('div', attrs={\"align\": \"justify\"})\n\n # get the text without tags\n book = book.getText()\n # using the translation to replace wrong characters selected before\n book = book.translate(translation)\n book = unidecode.unidecode(book)\n\n # first split to get the chapters\n chapters = book.split(\".\\r\\n\\r\\n\")\n\n # using the chapters to get paragraphs\n paragraphs = [ele.split(\".\\n\") for ele in chapters]\n\n # launching the main loop to ask until the answer is correct with our conditions\n while __name__ == \"__main__\":\n choice = input(\"Consulter le nombre de lettres (1) ou le nombre de mots (2) ? \\n\")\n if choice == '1':\n functions.letters_counter(chapters, paragraphs)\n exit(0)\n if choice == '2':\n functions.words_counter(chapters, paragraphs)\n exit(0)\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"239089892","text":"from threading import Thread\nimport time\nimport random\n\nthread_end_time = []\n\ndef print_times():\n # thread_counter = 0\n while True:\n if len(thread_end_time) > 0:\n _time = thread_end_time.pop(0)\n if(_time == \"exit\"):\n break\n print(*_time, sep=\"->\")\n # thread_counter += 1\n # if thread_counter >= 10:\n # break\n \n\ndef func(thread_name, start_time):\n start_time = time.time()\n time.sleep(random.randint(3, 8))\n thread_end_time.append((thread_name,\"%.2fs\" %(time.time()-start_time)))\n\nthreads = []\nfor i in range(10):\n thread = Thread(target=func, args=(f'Thread {i+1}', time.time()))\n threads.append(thread)\n\ntime.sleep(2)\n\nfor thread in threads:\n thread.start()\n # thread.join()\n\nprinter = Thread(target=print_times)\n\nprinter.start()\n\nfor thread in threads:\n thread.join()\n\nthread_end_time.append(\"exit\")\n\n# print(*thread_end_time, sep=\"\\n\")\n\n\n\n","sub_path":"PY-DEV/Session 14/threadcounter.py","file_name":"threadcounter.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"366251679","text":"import album\nimport song\n\n\nclass RainwaveArtist(object):\n '''A :class:`RainwaveArtist` object represents one artist.\n\n .. note::\n\n You should not instantiate an object of this class directly, but rather\n obtain one from :attr:`RainwaveChannel.artists` or\n :attr:`RainwaveSong.artists`.\n '''\n\n def __init__(self, channel, raw_info):\n self._channel = channel\n self._raw_info = raw_info\n\n def __repr__(self):\n return ''.format(self)\n\n def __str__(self):\n return self.name.encode(u'utf-8')\n\n @property\n def id(self):\n '''The ID of the artist.'''\n return self._raw_info[u'artist_id']\n\n @property\n def name(self):\n '''The name of the artist.'''\n return self._raw_info[u'artist_name']\n\n @property\n def numsongs(self):\n '''The number of songs attributed to the artist.'''\n if u'artist_numsongs' not in self._raw_info:\n more_info = self._channel._get_artist_raw_info(self.id)\n self._raw_info = dict(self._raw_info.items() + more_info.items())\n return self._raw_info[u'artist_numsongs']\n\n @property\n def songs(self):\n '''A list of :class:`RainwaveSong` objects attributed to the artist.'''\n if u'songs' not in self._raw_info:\n more_info = self._channel._get_artist_raw_info(self.id)\n self._raw_info = dict(self._raw_info.items() + more_info.items())\n if not hasattr(self, u'_songs'):\n self._songs = []\n for raw_song in self._raw_info[u'songs']:\n album_id = raw_song[u'album_id']\n new_raw_album = self._channel._get_album_raw_info(album_id)\n new_album = album.RainwaveAlbum(self._channel, new_raw_album)\n new_song = song.RainwaveSong(new_album, raw_song)\n self._songs.append(new_song)\n return self._songs\n","sub_path":"gutter/artist.py","file_name":"artist.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"353967725","text":"from pravac import Pravac\nfrom tocka import Tocka\nimport numpy as np\nfrom matplotlib import dates\n\nclass TrendBaseFibExtension:\n def __init__(self, ohcl):\n self.ohcl = ohcl\n self.A = Tocka('A', 'y')\n self.B = Tocka('B', 'b')\n self.C = Tocka('C', 'g')\n self.pornadjiABC()\n self.tocke = [self.A, self.B, self.C]\n self.spojiABC()\n def trend(self):\n self.spojiABC()\n self.X = Tocka('', '')\n self.D = Tocka('D', 'r')\n self.udaljenostCD()\n self.postaviLinije()\n def spojiABC(self):\n for i in range(0, len(self.tocke)-1):\n p = Pravac(self.tocke[i], self.tocke[i+1], '', \"b\")\n p.postaviPravac()\n def udaljenostCD(self):\n self.D.date = self.C.date\n self.X.date = self.B.date\n self.X.price = self.C.price\n self.X.price += self.B.price - self.A.price\n self.D.price = self.X.price\n def pornadjiABC(self):\n self.pronadjiAB()\n self.pornadjiRetraceC()\n def pronadjiAB(self):\n self.findedA = False\n self.findedB = False\n date = 0\n high = 2\n low = 3\n self.A.price = self.ohcl[0][low]\n self.A.date = self.ohcl[0][date]\n \n for i, row in enumerate(self.ohcl[1:], start=1):\n if not self.findedB:\n if row[low] <= self.A.price:\n self.A.price = row[low]\n self.A.date = row[date]\n self.A.index = i\n self.findedA = True\n granica = self.ohcl[self.A.index][high] + self.ohcl[self.A.index][high]*0.01\n self.B.price = self.ohcl[i][high]\n self.B.date = self.ohcl[i][date]\n self.B.index = self.A.index\n elif self.findedA == True:\n lowCandels = 0\n for i, row in enumerate(self.ohcl[self.B.index+1:], start=self.B.index+1):\n if (row[high] > self.B.price):\n lowCandels = 0\n if (row[high] >= granica):\n self.B.price = row[high]\n self.B.date = row[date]\n self.B.index = i\n self.findedB = True\n else:\n lowCandels += 1\n if lowCandels == 3:\n break\n else:\n break\n def pornadjiRetraceC(self):\n date = 0\n high = 2\n low = 3\n priceA = self.A.price\n priceB = self.B.price\n indexB = self.B.index\n udaljenosAB = dates.num2date(self.B.date) - dates.num2date(self.A.date)\n self.C.price = priceB\n for i, row in enumerate(self.ohcl[indexB:], start=indexB):\n if row[low] < self.C.price:\n #uvjet da je cijena između A i B\n if row[low] >= priceA or row[high] <= priceB:\n #jedan od uvjeta da tocka C bude udaljena od B kao i tocka A do B \n if (dates.num2date(row[date]) - dates.num2date(self.ohcl[indexB][date])) <= udaljenosAB:\n #razlika u dvije minimalne vrijednosti manja od 5%\n if ((self.C.price-self.C.price*0.0005) >= row[low]) or (self.C.price <= row[low]):\n self.C.price = row[low]\n self.C.date = row[date]\n self.C.index = i\n #print('A:{0:.10f},B:{1:.10f},a:{2:.10f},C:{3:.10f}'.format(self.A.price, self.B.price, dates.num2date(self.B.date), self.C.price)) \n #a = np.add(self.price*0.00045,self.price)\n #print(dates.num2date(self.B.date).strftime(\"%Y-%m-%d %H:%M\"))\n #print(dates.num2date(row[date]))\n #print(udaljenosAB)\n def postaviTockeABC(self):\n self.A.postaviTocku()\n self.B.postaviTocku()\n self.C.postaviTocku()\n def postavi0(self):\n self.D.postaviTocku()\n self.X.date = self.B.date\n self.X.price = self.C.price\n g = Pravac(self.X, self.C, '0', \"#486982\")\n g.postaviHorizontalnuLiniju(self.C.price)\n def postavi25(self):\n udaljeosCD = np.subtract(self.D.price, self.C.price) \n self.X.price = np.sum([self.C.price, udaljeosCD*0.25])\n g = Pravac(self.X, self.C, '25', \"g\")\n g.postaviHorizontalnuLiniju(self.X.price)\n def postavi50(self):\n udaljeosCD = np.subtract(self.D.price, self.C.price) \n self.X.price = np.sum([self.C.price, udaljeosCD*0.5])\n g = Pravac(self.X, self.C, '50', \"r\")\n g.postaviHorizontalnuLiniju(self.X.price)\n def postavi75(self):\n udaljeosCD = np.subtract(self.D.price, self.C.price) \n self.X.price = np.sum([self.C.price, udaljeosCD*0.75])\n g = Pravac(self.X, self.C, '75', \"#0099FF\")\n g.postaviHorizontalnuLiniju(self.X.price)\n def postavi100(self):\n g = Pravac(self.X, self.D, '100', \"b\")\n g.postaviHorizontalnuLiniju(self.D.price)\n def postaviLinije(self):\n self.postavi0()\n self.postavi25()\n self.postavi50()\n self.postavi75()\n self.postavi100()","sub_path":"trendBaseFibExtension.py","file_name":"trendBaseFibExtension.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"443935681","text":"import sys\nimport math\n\n\n#CONSTANT DECLARATION\nPRISONER = 'Prisoner'\nCITIZEN = 'Citizen'\n\nX = 0\nY = 1\n\n#FUNCTION USED TO FIND DISTANCE BETWEEN 2 POINTS\ndef distance(point1, point2):\n return math.sqrt((point1[X] - point2[X]) ** 2 + (point1[Y] - point2[Y]) ** 2)\n\n#FUNCTION USED TO CHECK WETHER A POINT IS BETWEEN 2 OTHERS\ndef is_between(point, a, b):\n rel_tol = 1e-09\n abs_tol = 0.0\n\n dist_1 = distance(a, point) + distance(point, b)\n dist_2 = distance(a, b)\n\n #ABS AND MAX TO COMPARE FLOATS\n return abs(dist_1 - dist_2) <= max(rel_tol * max(abs(dist_1), abs(dist_2)), abs_tol)\n\n#CHECK WETHER THE POINT IS IN THE BORDER OF THE POLYGON OR NOT\ndef point_on_border(point, poly):\n n = len(poly)\n for i in range(n):\n p1 = poly[i]\n p2 = poly[-n+i+1]\n if is_between(point, p1, p2):\n return True\n return False\n\n#FUNCTION USE IN is_in_polygon FUNCTION\ndef angle_2d(x1, y1, x2, y2):\n theta1 = math.atan2(y1, x1)\n theta2 = math.atan2(y2, x2)\n dtheta = theta2 - theta1\n\n two_pi = math.pi + math.pi\n while dtheta > math.pi:\n dtheta -= two_pi\n while dtheta < -math.pi:\n dtheta += two_pi\n \n return dtheta\n\n#CHECK WETHER POINT IS INSIDE POLYGON, WHERE POLYGON IS A LIST OR TUPLE OF POINTS\ndef is_in_polygon(polygon, point):\n \n angle = 0\n n = polygon.__len__()\n p1 = [0, 0]\n p2 = [0, 0]\n\n for i in range(0, n):\n p1[X] = polygon[i][X] - point[X]\n p1[Y] = polygon[i][Y] - point[Y]\n p2[X] = polygon[(i + 1) % n][X] - point[X]\n p2[Y] = polygon[(i + 1) % n][Y] - point[Y]\n \n angle += angle_2d(p1[X], p1[Y], p2[X], p2[Y])\n \n if abs(angle) < math.pi:\n return False\n else:\n return True\n\n#MAIN FUNCTION THAT PARSES THE PEOPLE.TXT AND PRINTS THE RESULTS, TAKES FILEPATH AS ARGUMENT\ndef challenge(filePath):\n \n #LIST CONTAINING PARSED COORDINATES\n coords = []\n\n try:\n txt = open(filePath, 'r')\n lines = txt.readlines()\n\n #TXT PARSING\n for line in lines:\n coor = line.strip().split(',')\n \n item = []\n \n for i in range(0, coor.__len__() - 1):\n item.append(tuple(coor[i].strip().split(' ')))\n \n item.append(tuple(coor[coor.__len__() - 1].strip().split('|')[X].strip().split(' ')))\n item.append(tuple(coor[coor.__len__() - 1].strip().split('|')[Y].strip().split(' ')))\n coords.append(item)\n\n coords = list(map(lambda arr: list(map(lambda inner_arr: tuple(map(float, inner_arr)), arr)), coords))\n\n #REALEASE RESOURCES\n finally:\n if txt:\n txt.close()\n\n #FIND MAX VALUES AND MIN VALUES FIRST\n for inner_arr in coords:\n\n minX = inner_arr[0][X]\n maxX = inner_arr[0][X]\n minY = inner_arr[0][Y]\n maxY = inner_arr[0][Y]\n\n person = inner_arr[inner_arr.__len__() - 1]\n polygon = inner_arr[0:inner_arr.__len__() - 1]#NON INCLUSIVE AS WELL\n\n #START FROM 1 SINCE 0 IS BEEN TAKEN AS THE BASE ABOVE\n for i in range(1, inner_arr.__len__() - 1):#NON INCLUSIVE\n point = inner_arr[i]\n minX = min(minX, point[X])\n maxX = max(maxX, point[X])\n minY = min(minY, point[Y])\n maxY = max(maxY, point[Y])\n \n #DISCARD IF IT IS OUT OF BOUNDS\n if person[X] < minX or person[X] > maxX or person[Y] < minY or person[Y] > maxY:\n pass\n \n else:\n\n #ELSE CHECK WETHER IT IS IN POLYGON OR NOT\n if is_in_polygon(polygon, person):\n print(PRISONER)\n\n #IF THE FUNCTION RETURNS FALSE IT CAN STILL BE INSIDE BUT ON THE POLYGON EDGES,\n #SO WE MAKE SURE BY RUNNING THE point_on_border FUNCTION\n else:\n #NOW WE ARE SURE IT IS A PRISONER\n if point_on_border(person, polygon):\n print(PRISONER)\n #NOW WE ARE SURE IT IS A CITIZEN\n else:\n print(CITIZEN)\n\n\nchallenge(sys.argv[1])\n","sub_path":"challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"430327053","text":"import random\ndef input_num(message):\n\twhile True:\n\t\ttry:\n\t\t\tn = int(input(message))\n\t\t\treturn n\n\t\texcept ValueError:\n\t\t\tprint(\"Mutqagreq tiv!\")\ndef rand_str_arr(n = 5):\n\tarr = []\n\tfor i in range(n):\n\t\tarr.append(chr(random.randint(0,25) + 97))\n\treturn arr\nwhile True:\n\tn = input_num(\"Mutqagreq zuyg erkarutyuny (0 - elq): \")\n\tif n is 0:\n\t\tprint(\"Hajoxutyun!\")\n\t\tbreak\n\tarr = rand_str_arr(n)\n\tprint(\"Array = \", arr)\n\tc = 0\n\tfor i in range(n):\n\t\tif ord(arr[i]) < ord('k'):\n\t\t\tc += 1\n\tprint(\"Qanaky =\", c)","sub_path":"Homeworks 0 OLD/Xndragirq/275.py","file_name":"275.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"412083842","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param: root: the root of binary tree\n @param: target: An integer\n @return: all valid paths\n \"\"\"\n def binaryTreePathSum(self, root, target):\n def dfs(root, val, val_list):\n if not root.left and not root.right:\n if val == target:\n return ans.append(val_list)\n if root.left:\n dfs(root.left, val + root.left.val, val_list + [root.left.val])\n if root.right:\n dfs(root.right, val + root.right.val, val_list + [root.right.val])\n \n ans = []\n if not root:\n return ans\n dfs(root, root.val, [root.val])\n return ans","sub_path":"376. Binary Tree Path Sum.py","file_name":"376. Binary Tree Path Sum.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"336659723","text":"#02. keras_load_data.py\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n#keras는 tensorflow에 포함된 개념\n# 폴더에서 이미지 데이터넷을\n# 배치 사이즈 - 680개 다 학습시키면 시간이 너무 오래걸림, 여러개의 덩어리로 분리시켜서 학습(ex 32개짜리 덩어리로 랜덤으로 분류하여 학습)\n\ntrain_dataset = tf.keras.preprocessing.image_dataset_from_directory(\n 'D:/문서/GitHub/Face-Mask-Detector/Mask-Training/data/',\n validation_split=0.2, # 검증 데이터 비율\n subset='training',\n seed=123, # seed값을 고정시키니까 계속실행해도 같은 이미지가 나옴 999로 하면 랜덤으로 나옴, 현재시간을 넣으면 매번 바뀜\n image_size=(224,224),\n batch_size=16\n\n)\n\nvalid_dataset = tf.keras.preprocessing.image_dataset_from_directory(\n 'D:/문서/GitHub/Face-Mask-Detector/Mask-Training/data/',\n validation_split=0.2,\n subset='validation',\n seed=123,\n image_size=(224,224),\n batch_size=16\n\n)\n\n#print(train_dataset.class_names)\n\n#print(train_dataset)\nplt.figure(0)\nplt.title('train_dataset')\nfor images, labels in train_dataset.take(1): # 이 속에는 16개 이미지\n for i in range(9):\n plt.subplot(3, 3, i+1)\n plt.imshow(images[i].numpy().astype('uint8')) # 정수 픽셀값으로 변환해서 출력\n plt.title(train_dataset.class_names[labels[i]])\n plt.axis('off') # 축을 꺼버림(좌표값 없앰)\n\nplt.show()\n\nplt.figure(1)#0번과 구별\nplt.title('valid_dataset')\nfor images, labels in valid_dataset.take(1):\n for i in range(16):\n plt.subplot(4,4,i+1)\n plt.imshow(images[i].numpy().astype('uint8')) # 8바이트짜리 unsigned int\n plt.title(valid_dataset.class_names[labels[i]])\n plt.axis('off')\n\nplt.show()","sub_path":"lab_ai/02. keras_load_data.py","file_name":"02. keras_load_data.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"480312211","text":"# This is an example PAT configuration showing the usage of PAT on minbias data\n\n# Starting with a skeleton process which gets imported with the following line\nfrom PhysicsTools.PatAlgos.patTemplate_cfg import *\n\nfrom PhysicsTools.PatAlgos.tools.coreTools import *\n\n## global tag for data\nprocess.GlobalTag.globaltag = cms.string('GR09_R_34X_V4::All')\n\n#switch off new tau features introduced in 33X to restore 31X defaults\n# new feaures: - shrinkingConeTaus instead of fixedCone ones\n# - TaNC discriminants attached for shrinkingConeTaus\n# - default preselection on cleaningLayer1\nfrom PhysicsTools.PatAlgos.tools.tauTools import *\nswitchTo31Xdefaults(process)\n\n\n# turn off MC matching for the process\nremoveMCMatching(process, ['All'])\n\n# get the 2360 GeV jet corrections\nfrom PhysicsTools.PatAlgos.tools.jetTools import *\nswitchJECSet( process, \"2360GeV\")\n\n\n# Add PF jets\naddJetCollection(process,cms.InputTag('ak5PFJets'),\n 'AK5', 'PF',\n doJTA = False,\n doBTagging = False,\n jetCorrLabel = ('AK5','PF'),\n doType1MET = False,\n doL1Cleaning = False, \n doL1Counters = False,\n genJetCollection=cms.InputTag(\"ak5GenJets\"),\n doJetID = False,\n jetIdLabel = \"ak5\"\n )\n\n\n# require physics declared\nprocess.physDecl = cms.EDFilter(\"PhysDecl\",\n applyfilter = cms.untracked.bool(True)\n)\n\n# require scraping filter\nprocess.scrapingVeto = cms.EDFilter(\"FilterOutScraping\",\n applyfilter = cms.untracked.bool(True),\n debugOn = cms.untracked.bool(False),\n numtrack = cms.untracked.uint32(10),\n thresh = cms.untracked.double(0.2)\n )\n\n\n# configure HLT\nprocess.load('L1TriggerConfig.L1GtConfigProducers.L1GtTriggerMaskTechTrigConfig_cff')\nprocess.load('HLTrigger/HLTfilters/hltLevel1GTSeed_cfi')\nprocess.hltLevel1GTSeed.L1TechTriggerSeeding = cms.bool(True)\nprocess.hltLevel1GTSeed.L1SeedsLogicalExpression = cms.string('0 AND ((40 OR 41) AND NOT (36 OR 37 OR 38 OR 39))')\n\n\nprocess.load('Analysis.AnalysisFilters.PVFilter_cff')\n\n\n# remove the tag infos\nprocess.patJets.addTagInfos = False\nprocess.selectedPatJets.cut = cms.string('pt > 10 & abs(eta) < 3.0')\nprocess.patJetsAK5PF.addTagInfos = False\nprocess.selectedPatJetsAK5PF.cut = cms.string('pt > 8 & abs(eta) < 3.0')\n\n# Add the files for runs 123575 and 123596\nreadFiles = cms.untracked.vstring()\nsecFiles = cms.untracked.vstring()\n\nreadFiles.extend( [\n'/store/data/BeamCommissioning09/MinimumBias/RECO/18thFebPreProd_351p1-v3/0000/BEF77CC5-C71D-DF11-A707-00237DA15C7C.root'\n ] );\nprocess.source.fileNames = readFiles\n\n# let it run\nprocess.p = cms.Path(\n process.hltLevel1GTSeed*\n process.scrapingVeto*\n process.physDecl*\n process.pvFilter*\n process.patDefaultSequence\n )\n\n# rename output file\nprocess.out.fileName = cms.untracked.string('reco_2360GeV_firstdata_351patch1_18feb_rereco_pat.root')\n\n# reduce verbosity\nprocess.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000)\n\n# process all the events\nprocess.maxEvents.input = 5000\nprocess.options.wantSummary = True\n\nprocess.out.outputCommands = cms.untracked.vstring([\n #'drop *_genParticles_*_*',\n #'keep *_genEvt_*_*',\n 'keep *_offlinePrimaryVertices_*_*',\n 'keep *_towerMaker_*_*',\n 'keep recoPFCandidates_particleFlow_*_*',\n 'keep *_offlineBeamSpot_*_*',\n 'keep *_generalTracks_*_*',\n \"keep *_selectedPatJets*_*_*\"\n ]\n )\n","sub_path":"JetAnalysis/test/patLayer1_fromRECO_2360GeV_firstdata_18feb_rereco_cfg.py","file_name":"patLayer1_fromRECO_2360GeV_firstdata_18feb_rereco_cfg.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"413544929","text":"from datetime import datetime\nimport itertools\nimport pandas as pd\n\ncount_ = itertools.count()\ncount_bid = itertools.count()\ncount_ask = itertools.count()\n\ncount_trades = itertools.count()\n\n\nclass Order:\n \"\"\"\n This class represents the order\n \"\"\"\n\n def __init__(self, agent, quantity, price):\n \"\"\"\n Init\n @param self:\n @param agent:\n @return:\n \"\"\"\n now = datetime.now()\n self.agent = agent\n self.quantity = quantity\n self.state = \"NC\"\n self.date = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n self.price = price\n self.index = next(count_)\n self.id = 0\n\n def to_dict(self):\n \"\"\"\n to dict\n @param self:\n @return:\n \"\"\"\n # raise NotImplementedError\n return {\"agent\": int(self.agent), \"quantity\": self.quantity, \"price\": self.price, \"id\": self.id}\n\n def to_list(self):\n return list(self.to_dict().values())\n # def __init__(self, row):\n # self.__init__(self,row[\"agent\"], row[\"amount\"])\n\n\nclass AskOrder(Order):\n\n def __init__(self, agent, quantity, price):\n Order.__init__(self, agent, quantity, price)\n self.id = next(count_ask)\n\n\nclass BidOrder(Order):\n\n def __init__(self, agent, quantity, price):\n Order.__init__(self, agent, quantity, price)\n self.id = next(count_bid)\n\n\nclass NoOrder(Order):\n\n def __init__(self, agent):\n Order.__init__(self, agent, 0, 0)\n\n\nclass Trade:\n def __init__(self, buyer, seller, quantity, price, step, episode):\n self.date = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n self.buyer = buyer\n self.seller = seller\n self.quantity = quantity\n self.price = price\n self.total_price = self.price * self.quantity\n self.id = next(count_trades)\n self.step = step\n self.episode = episode\n\n def to_dict(self):\n return {\"buyer\": self.buyer, \"seller\": self.seller, \"quantity\": self.quantity,\n \"price\": self.price, \"id\": self.id, \"step\": self.step, \"episode\": self.episode}\n\n def to_list(self):\n return list(self.to_dict())\n","sub_path":"tradingsimulation/book/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"122744143","text":"colored = {}\ncolored['X'] = ['X', '', 'red', 0, 'gray', 1, [\"blinked\"]]\ncolored['M'] = ['M', '', 'red', 0, 'gray', 0, [\"blinked\"]]\ncolored['@'] = ['@', '', \"purpur\", 0, 'black', 0, [\"hard\"]]\nclass obj:\n def __init__(self, sym, world):\n self.c = sym\n self.x = 0\n self.y = 0\n self.world = world\n\n#All types should be possible on default\n def move(self, dx=0, dy=0, Possible={'ground', 'tree', 'sea water', 'water lake', 'water river', 'ice-berg', 'mountain'}):\n if isinstance(dx, tuple):\n dx, dy = dx\n if (0 <= self.x + dx < self.world.size) and (0 <= self.y + dy < self.world.size) and (self.world.area[self.x + dx][self.y + dy].t in Possible) and self.world.area[self.x + dx][self.y + dy].obj == None:\n self.world.area[self.x][self.y].obj = None\n self.x += dx\n self.y += dy\n print(Possible, self.world.area[self.x][self.y].t, self.world.area[self.x][self.y].t in Possible, sep = '\\n')\n self.world.area[self.x][self.y].obj = self\n return True\n return False\n def go_to(self, x, y):\n self.x = x\n self.y = y\n def __str__(self):\n return self.c\n #def turn(self, world):\n \n # return\n def color_args(self):\n return colored[self.c]\n\ndef Help():\n print(\"\"\"\\n\n If you want to make a new type of object, \n you should go into the file W1/World/objects.py and write: \n colored[''] = ['', '', '', 0, \n '', 0, []] \\n \n if you want to make new object in new programm, write \n a = obj(, )\n if you want to move, you should use \"move\"\\n\n if you want to print all, you should ask me\n \"\"\")\n\n\n#Help()\n","sub_path":"W2/helpers/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"458214142","text":"class japoneses:\n\n\tdef __init__(self, marca, modelo, ano, transmision, status = False):\n\t\tself.marca = marca\n\t\tself.modelo = modelo\n\t\tself.ano = ano\n\t\tself.transmision = transmision\n\t\tself.status = status\n\n\tdef verdatos(self):\n\t\tprint(\"Marca: \"+self.marca)\n\t\tprint(\"Modelo: \"+self.modelo)\n\t\tprint(\"ano: \"+self.ano)\n\t\tprint(\"transmision: \"+self.transmision)\n\n\tdef status_venta(self):\n\t\treturn self.status\n\n\tdef verificar_status(self):\n\t\tif self.status_venta():\n\t\t\tprint(\"Status: Disponible\")\n\t\telse:\n\t\t\tprint(\"Status: Vendido\")\n\n\njdm = japoneses(\"mitsubishi\", \"eclipse\",\"99\",\"sincronico\",True)\n\njdm.verdatos()\njdm.verificar_status()\n","sub_path":"clases/carritos.py","file_name":"carritos.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"473466347","text":"from __future__ import unicode_literals, division, absolute_import\nfrom datetime import datetime\nimport logging\nimport re\nimport sys\n\nfrom path import Path\n\nfrom flexget import plugin\nfrom flexget.config_schema import one_or_more\nfrom flexget.event import event\nfrom flexget.entry import Entry\n\nlog = logging.getLogger('find')\n\n\nclass InputFind(object):\n \"\"\"\n Uses local path content as an input, recurses through directories and creates entries for files that match mask.\n\n You can specify either the mask key, in shell file matching format, (see python fnmatch module,) or regexp key.\n\n Example::\n\n find:\n path: /storage/movies/\n mask: *.avi\n\n Example::\n\n find:\n path:\n - /storage/movies/\n - /storage/tv/\n regexp: .*\\.(avi|mkv)$\n \"\"\"\n\n schema = {\n 'type': 'object',\n 'properties': {\n 'path': one_or_more({'type': 'string', 'format': 'path'}),\n 'mask': {'type': 'string'},\n 'regexp': {'type': 'string', 'format': 'regex'},\n 'recursive': {'type': 'boolean'}\n },\n 'required': ['path'],\n 'additionalProperties': False\n }\n\n def prepare_config(self, config):\n from fnmatch import translate\n # If only a single path is passed turn it into a 1 element list\n if isinstance(config['path'], basestring):\n config['path'] = [config['path']]\n config.setdefault('recursive', False)\n # If mask was specified, turn it in to a regexp\n if config.get('mask'):\n config['regexp'] = translate(config['mask'])\n # If no mask or regexp specified, accept all files\n if not config.get('regexp'):\n config['regexp'] = '.'\n\n def on_task_input(self, task, config):\n self.prepare_config(config)\n entries = []\n match = re.compile(config['regexp'], re.IGNORECASE).match\n for folder in config['path']:\n folder = Path(folder).expanduser()\n log.debug('scanning %s' % folder)\n if config['recursive']:\n files = folder.walk(errors='ignore')\n else:\n files = folder.listdir()\n for item in files:\n e = Entry()\n try:\n # TODO: config for listing files/dirs/both\n if item.isdir():\n continue\n except UnicodeError as e:\n log.warning('Filename `%s` in `%s` is not decodable by declared filesystem encoding `%s`. '\n 'Either your environment does not declare the correct encoding, or this filename '\n 'is incorrectly encoded.' %\n (item.name, item.dirname(), sys.getfilesystemencoding()))\n continue\n\n e['title'] = item.namebase\n # If mask fails continue\n if not match(item.name):\n continue\n try:\n e['timestamp'] = datetime.fromtimestamp(item.getmtime())\n except ValueError as e:\n log.debug('Error setting timestamp for %s: %s' % (item, e))\n e['location'] = item\n # Windows paths need an extra / prepended to them for url\n if not item.startswith('/'):\n item = '/' + item\n e['url'] = 'file://%s' % item\n entries.append(e)\n return entries\n\n\n@event('plugin.register')\ndef register_plugin():\n plugin.register(InputFind, 'find', api_ver=2)\n","sub_path":"flexget/plugins/input/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"403809259","text":"import RPi.GPIO as gpio\nimport time\n'''\nA controller for the lock mechanism through GPIO\nMakes it east to assert individual locks for a brief period of time\n'''\n#gpio.setwarnings(False)\n\ngpio.setmode(gpio.BCM)\n\n# A relation between locks and GPIO pins in the form LOCK:GPIO_PIN\npins = {1:2, 2:4, 3:17, 4:22, 5:10, 6:11, 7:5, 8:13}\n\n# Initialize each pin to output\nfor pin in list(pins.keys()):\n gpio.setup(pins[pin], gpio.OUT)\n\n# Helper methods to assert individual pins\ndef assert1(pin):\n gpio.output(pins[pin], gpio.HIGH)\n\ndef assert0(pin):\n gpio.output(pins[pin], gpio.LOW)\n\n# Sets all working pins to 0\ndef lockAll():\n for pin in list(pins.keys()):\n assert0(pin)\n\n# unlocks a given lock for 4 seconds\ndef unlock(lock):\n assert1(lock)\n time.sleep(4)\n lockAll()\n\n# power-cycles all locks on startup\nfor pin in list(pins.keys()):\n assert1(pin)\nlockAll()\n","sub_path":"LockController.py","file_name":"LockController.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"215801206","text":"#\n# OS_2_v0.py\n#\n# Copyright © 2010-2014, 2016 Monotype Imaging Inc. All Rights Reserved.\n#\n\n\"\"\"\nSupport for original Version 0 OS/2 tables, as defined by Microsoft. Note this\ndiffers from Apple's definition of Version 0; see OS_2_v0_mac.py for that\nformat.\n\"\"\"\n\n# Other imports\nfrom fontio3.fontdata import simplemeta\nfrom fontio3 import utilities\n\nfrom fontio3.OS_2 import (\n familyclass_v0,\n OS_2_v0_mac,\n panose,\n panose_fam2_v0,\n selection_v0,\n typeflags_v0,\n vendors_v0)\n\n# -----------------------------------------------------------------------------\n\n#\n# Private constants\n#\n\n_weightClassNames = (\n \"Thin\",\n \"Ultra-light\",\n \"Light\",\n \"Regular\",\n \"Medium\",\n \"Demi-bold\",\n \"Bold\",\n \"Ultra-bold\",\n \"Heavy\")\n\n_widthClassNames = (\n \"Ultra-condensed\",\n \"Extra-condensed\",\n \"Condensed\",\n \"Semi-condensed\",\n \"Normal\",\n \"Semi-expanded\",\n \"Expanded\",\n \"Extra-expanded\",\n \"Ultra-expanded\")\n\n_xAvgCharWidthFactors = {\n ord('a'): 64,\n ord('b'): 14,\n ord('c'): 27,\n ord('d'): 35,\n ord('e'): 100,\n ord('f'): 20,\n ord('g'): 14,\n ord('h'): 42,\n ord('i'): 63,\n ord('j'): 3,\n ord('k'): 6,\n ord('l'): 35,\n ord('m'): 20,\n ord('n'): 56,\n ord('o'): 56,\n ord('p'): 17,\n ord('q'): 4,\n ord('r'): 49,\n ord('s'): 56,\n ord('t'): 71,\n ord('u'): 31,\n ord('v'): 10,\n ord('w'): 18,\n ord('x'): 3,\n ord('y'): 18,\n ord('z'): 2,\n ord(' '): 166}\n\n# -----------------------------------------------------------------------------\n\n#\n# Private functions\n#\n\ndef _pprint_usWeightClass(p, value, label, **kwArgs):\n \"\"\"\n >>> p = pp.PP()\n >>> _pprint_usWeightClass(p, 300, \"Weight class\")\n Weight class: Light (value 300)\n \n >>> _pprint_usWeightClass(p, 350, \"Weight class\")\n Weight class: Between Light and Regular (value 350)\n \n >>> _pprint_usWeightClass(p, 30, \"Weight class\")\n Weight class: Thinner than 'Thin' (value 30)\n \n >>> _pprint_usWeightClass(p, 3000, \"Weight class\")\n Weight class: Heavier than 'Heavy' (value 3000)\n \"\"\"\n \n if value < 100:\n s = \"Thinner than 'Thin' (value %d)\" % (value,)\n elif value > 900:\n s = \"Heavier than 'Heavy' (value %d)\" % (value,)\n else:\n n = (value - 100) // 100\n \n if value % 100:\n t = (_weightClassNames[n], _weightClassNames[n+1], value)\n s = \"Between %s and %s (value %d)\" % t\n \n else:\n s = \"%s (value %d)\" % (_weightClassNames[n], value)\n \n p.simple(s, label=label)\n\ndef _pprint_usWidthClass(p, value, label, **kwArgs):\n \"\"\"\n >>> p = pp.PP()\n >>> _pprint_usWidthClass(p, 7, \"Width class\")\n Width class: Expanded\n \n >>> _pprint_usWidthClass(p, 11, \"Width class\")\n Traceback (most recent call last):\n ...\n ValueError: Unknown width class value: 11\n \"\"\"\n \n if value not in frozenset(range(1, 10)):\n raise ValueError(\"Unknown width class value: %s\" % (value,))\n \n p.simple(_widthClassNames[value - 1], label=label)\n\ndef _recalc_fsSelection(oldValue, **kwArgs):\n newValue = oldValue.__copy__()\n e = kwArgs['editor']\n \n if e is None:\n raise NoEditor()\n \n if not e.reallyHas(b'head'):\n raise NoHead()\n \n headFlags = e.head.macStyle\n \n # sync bold and italic\n newValue.bold = headFlags.bold\n newValue.italic = headFlags.italic\n \n # do regular check\n if oldValue.regular:\n newValue.bold = newValue.italic = False\n \n return newValue != oldValue, newValue\n\ndef _recalc_usFirstCharIndex(oldValue, **kwArgs):\n e = kwArgs['editor']\n \n if e is None:\n raise NoEditor()\n \n if not e.reallyHas(b'cmap'):\n raise NoCmap()\n \n m = e.cmap.getUnicodeMap()\n \n if not m:\n m = e.cmap.getSymbolMap() or [0]\n \n newValue = min(0xFFFF, min(m))\n return newValue != oldValue, newValue\n\ndef _recalc_usLastCharIndex(oldValue, **kwArgs):\n e = kwArgs['editor']\n \n if e is None:\n raise NoEditor()\n \n if not e.reallyHas(b'cmap'):\n raise NoCmap()\n \n m = e.cmap.getUnicodeMap()\n \n if not m:\n m = e.cmap.getSymbolMap() or [0]\n \n newValue = min(0xFFFF, max(m))\n return newValue != oldValue, newValue\n\ndef _recalc_xAvgCharWidth(oldValue, **kwArgs):\n editor = kwArgs['editor']\n \n if editor is None:\n raise NoEditor()\n \n if not editor.reallyHas(b'hmtx'):\n raise NoHmtx()\n \n if not editor.reallyHas(b'cmap'):\n raise NoCmap()\n \n mtx = editor.hmtx\n uMap = editor.cmap.getUnicodeMap()\n cumulWeight = 0\n weighted = []\n \n for uniScalar, weight in _xAvgCharWidthFactors.items():\n if uniScalar in uMap:\n cumulWeight += weight\n weighted.append(mtx[uMap[uniScalar]].advance * weight)\n \n if cumulWeight:\n s = sum(weighted)\n newValue = int(s / cumulWeight)\n newValueRound = int(round(s / cumulWeight))\n \n else:\n s = sum(obj.advance for obj in mtx.values())\n newValue = int(s / len(mtx))\n newValueRound = int(round(s / len(mtx)))\n \n if kwArgs.get('forApple', False):\n newValue = newValueRound\n \n elif (newValue != newValueRound) and ('logger' in kwArgs):\n kwArgs['logger'].warning((\n 'V0606',\n (newValue, newValueRound),\n \"The recalculated xAvgCharWidth value (%d) is one less than the \"\n \"rounded value (%d). The smaller value will be used for \"\n \"compatibility with Windows, but consider using a newer version \"\n \"of the OS/2 table.\"))\n \n return newValue != oldValue, newValue\n\ndef _validate(obj, **kwArgs):\n logger = kwArgs['logger']\n \n if obj.fsSelection.bold and (obj.usWeightClass < 500):\n logger.warning((\n 'W2103',\n (obj.fsSelection.bold, obj.usWeightClass),\n \"The fsSelection.bold bit (%s) is inconsistent \"\n \"with the usWeightClass %d\"))\n \n panoseEnumInvs = obj.panoseArray.getEnumInverseMaps()\n \n if 'weight' in panoseEnumInvs:\n panoseAsWeightClass = (\n panoseEnumInvs['weight'][obj.panoseArray.weight] * 89 + 100)\n \n pwdifference = abs(obj.usWeightClass - panoseAsWeightClass)\n \n if pwdifference >= 200:\n logger.warning((\n 'W2116',\n (obj.usWeightClass, obj.panoseArray.weight),\n \"The usWeightClass %d is inconsistent \"\n \"with the PANOSE weight %s\"))\n\n if not obj.fsSelection.italic:\n if obj.ySuperscriptXOffset != 0:\n logger.warning((\n 'V0340',\n (),\n \"The ySuperscriptXOffset is non-zero, but the font is not \"\n \"styled as italic.\"))\n \n if obj.ySubscriptXOffset != 0:\n logger.warning((\n 'V0340',\n (),\n \"The ySubscriptXOffset is non-zero, but the font is not \"\n \"styled as italic.\"))\n \n return True\n\ndef _validate_sFamilyClass(value, **kwArgs):\n logger = kwArgs['logger']\n \n try:\n inRange = 0 <= value < 0x10000\n except:\n inRange = False\n \n if not inRange:\n logger.error((\n 'G0009',\n (),\n \"The sFamilyClass value is non-numeric or out of range.\"))\n \n return False\n \n hi, lo = divmod(value, 256)\n r = True\n \n if hi in {6, 11, 13, 14}:\n logger.error((\n 'E2119',\n (hi,),\n \"The sFamilyClass class ID %d is reserved.\"))\n \n r = False\n \n elif hi > 14:\n logger.error((\n 'E2120',\n (hi,),\n \"The sFamilyClass class ID %d is undefined.\"))\n \n r = False\n \n if value not in familyclass_v0.labels:\n logger.error((\n 'E2121',\n (lo, hi),\n \"The sFamilyClass subclass %d is not defined for class %d\"))\n \n r = False\n \n return r\n\ndef _validate_usFirstCharIndex(value, **kwArgs):\n logger = kwArgs['logger']\n editor = kwArgs['editor']\n \n if (editor is None) or (not editor.reallyHas(b'cmap')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate usFirstCharIndex because the Editor and/or \"\n \"Cmap are missing or empty.\"))\n \n return False\n \n uMap = editor.cmap.getUnicodeMap()\n \n if not uMap:\n uMap = editor.cmap.getSymbolMap() or [0]\n \n actualMin = min(0xFFFF, min(uMap))\n \n if value != actualMin:\n logger.error((\n 'E2130',\n (actualMin, value),\n \"The usFirstCharIndex should be 0x%04X, but is 0x%04X\"))\n \n return False\n \n return True\n\ndef _validate_usLastCharIndex(value, **kwArgs):\n logger = kwArgs['logger']\n editor = kwArgs['editor']\n \n if editor is None or (not editor.reallyHas(b'cmap')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate usLastCharIndex because the Editor and/or \"\n \"Cmap are missing or empty.\"))\n \n return False\n \n uMap = editor.cmap.getUnicodeMap()\n \n if not uMap:\n uMap = editor.cmap.getSymbolMap() or [0]\n \n actualMax = min(0xFFFF, max(uMap))\n \n if value != actualMax:\n logger.error((\n 'E2131',\n (actualMax, value),\n \"The usLastCharIndex should be 0x%04X, but is 0x%04X\"))\n \n return False\n \n return True\n\ndef _validate_usWeightClass(value, **kwArgs):\n logger = kwArgs['logger']\n q, r = divmod(value, 100)\n\n # 20160408: re-vamp to address VALIDATE-211\n\n if r == 0 and 1 <= q <= 9: # simple multiple of 100 in range 100-999\n logger.info((\n 'V1055',\n (value,),\n \"The usWeightClass value %d is valid\"))\n\n elif r == 50 and 2 <= q <= 9: # multiple of 50 in range 250-999\n logger.warning((\n 'V1056',\n (value,),\n \"The usWeightClass value %d is valid, but is \"\n \"not a multiple of 100\"))\n\n else:\n logger.error((\n 'E2133',\n (value,),\n \"The usWeightClass value %d is not valid\"))\n \n return False\n \n return True\n\ndef _validate_usWidthClass(value, **kwArgs):\n logger = kwArgs['logger']\n \n if (value < 1) or (value > 9):\n logger.error((\n 'E2134',\n (value,),\n \"The usWidthClass value %d is not valid\"))\n \n return False\n \n return True\n\ndef _validate_usWinAscent(value, **kwArgs):\n logger = kwArgs['logger']\n headTbl = kwArgs['editor'].head\n \n if value == 0:\n logger.error((\n 'V0821',\n (),\n \"The usWinAscent value is zero.\"))\n \n return False\n\n if headTbl.yMax > value:\n logger.warning((\n 'V0918',\n (headTbl.yMax, value),\n \"The font-wide head.yMax %d exceeds the usWinAscent %d. Clipping may occur.\"))\n \n return True\n\ndef _validate_usWinDescent(value, **kwArgs):\n logger = kwArgs['logger']\n headTbl = kwArgs['editor'].head\n \n if value == 0:\n logger.error((\n 'V0821',\n (),\n \"The usWinDescent value is zero.\"))\n \n return False\n\n if abs(headTbl.yMin) > value:\n logger.warning((\n 'V0919',\n (headTbl.yMin, value),\n \"The font-wide head.yMin %d exceeds the usWinDescent %d. Clipping may occur.\"))\n \n return True\n\ndef _validate_xAvgCharWidth(value, **kwArgs):\n logger = kwArgs['logger']\n \n try:\n changed, correctValue = _recalc_xAvgCharWidth(value, **kwArgs)\n except ValueError:\n changed = None\n \n if changed is None:\n logger.warning((\n 'W2104',\n (),\n \"Could not validate xAvgCharWidth because table(s) are missing\"))\n \n elif changed:\n logger.error((\n 'E2135',\n (correctValue, value),\n \"The xAvgCharWidth should be %d, but is %d\"))\n \n return False\n \n return True\n\ndef _validate_yStrikeoutPosition(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= e.head.unitsPerEm:\n logger.warning((\n 'W2107',\n (value,),\n \"The yStrikeoutPosition value of %d is unlikely. I guess.\"))\n \n return True\n\ndef _validate_yStrikeoutSize(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= (e.head.unitsPerEm // 4):\n logger.warning((\n 'W2108',\n (value,),\n \"The yStrikeoutSize value of %d seems iffy.\"))\n \n return True\n\ndef _validate_ySubscriptXOffset(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if abs(value) >= e.head.unitsPerEm:\n logger.warning((\n 'V0341',\n (value,),\n \"The ySubscriptXOffset value of %d is unlikely.\"))\n \n else:\n logger.info((\n 'V0339',\n (value,),\n \"The ySubscriptXOffset value is %d\"))\n\n return True\n\ndef _validate_ySubscriptXSize(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= e.head.unitsPerEm:\n logger.warning((\n 'W2109',\n (value,),\n \"The ySubscriptXSize value of %d is, like, totally wack.\"))\n \n return True\n\ndef _validate_ySubscriptYOffset(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if abs(value) >= e.head.unitsPerEm:\n logger.warning((\n 'V0341',\n (value,),\n \"The ySubscriptYOffset value of %d is unlikely.\"))\n \n else:\n logger.info((\n 'V0339',\n (value,),\n \"The ySubscriptYOffset value is %d\"))\n\n return True\n\ndef _validate_ySubscriptYSize(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= e.head.unitsPerEm:\n logger.warning((\n 'W2111',\n (value,),\n \"The ySubscriptYSize value of %d has bad karma.\"))\n \n return True\n\ndef _validate_ySuperscriptXOffset(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if abs(value) >= e.head.unitsPerEm:\n logger.warning((\n 'V0341',\n (value,),\n \"The ySuperscriptXOffset value of %d is unlikely.\"))\n \n else:\n logger.info((\n 'V0339',\n (value,),\n \"The ySuperscriptXOffset value is %d\"))\n\n return True\n\ndef _validate_ySuperscriptXSize(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= e.head.unitsPerEm:\n logger.warning((\n 'W2112',\n (value,),\n \"The ySuperscriptXSize value of %d is, like, totally wack.\"))\n \n return True\n\ndef _validate_ySuperscriptYOffset(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if abs(value) >= e.head.unitsPerEm:\n logger.warning((\n 'V0341',\n (value,),\n \"The ySuperscriptYOffset value of %d is unlikely.\"))\n \n else:\n logger.info((\n 'V0339',\n (value,),\n \"The ySuperscriptYOffset value is %d\"))\n\n return True\n\ndef _validate_ySuperscriptYSize(value, **kwArgs):\n logger = kwArgs['logger']\n e = kwArgs['editor']\n \n if e is None or (not e.reallyHas(b'head')):\n logger.error((\n 'V0553',\n (),\n \"Unable to validate yStrikeoutPosition, because the Editor and/or \"\n \"Head table are missing or empty.\"))\n \n return False\n \n if value < 0 or value >= e.head.unitsPerEm:\n logger.warning((\n 'W2114',\n (value,),\n \"The ySuperscriptYSize value of %d has bad karma.\"))\n \n return True\n\n# -----------------------------------------------------------------------------\n\n#\n# Exceptions\n#\n\nif 0:\n def __________________(): pass\n\nclass NoCmap(ValueError): pass\nclass NoEditor(ValueError): pass\nclass NoHead(ValueError): pass\nclass NoHmtx(ValueError): pass\n\n# -----------------------------------------------------------------------------\n\n#\n# Classes\n#\n\nif 0:\n def __________________(): pass\n\nclass OS_2(object, metaclass=simplemeta.FontDataMetaclass):\n \"\"\"\n Objects representing OS/2 tables, version 0 (as defined by Microsoft).\n \n >>> _testingValues[1].pprint()\n OS/2 Version: 0 (Windows)\n Average weighted escapement: 600\n Weight class: Demi-bold (value 600)\n Width class: Extra-expanded\n Type Flags:\n Embedding Level: Preview & Print Embedding\n Subscript horizontal font size: 0\n Subscript vertical font size: 0\n Subscript x-offset: 0\n Subscript y-offset: 0\n Superscript horizontal font size: 0\n Superscript vertical font size: 0\n Superscript x-offset: 0\n Superscript y-offset: 0\n Strikeout size: 0\n Strikeout position: 0\n IBM font family class and subclass: No Classification\n PANOSE specification:\n Family Type: Latin Text\n Serif Type: Flared\n Weight: Any\n Proportion: Expanded\n Contrast: Any\n Stroke Variation: Any\n Arm Style: Any\n Letterform: Any\n Midline: Any\n x-Height: Any\n Font vendor: Monotype\n Selection Flags:\n Strikeout\n Minimum Unicode: 32\n Maximum Unicode: 32\n Typographic ascender: 1400\n Typographic descender: -800\n Typographic line gap: 0\n Windows ascender: 0\n Windows descender: 0\n \"\"\"\n \n #\n # Class definition variables\n #\n \n objSpec = dict(\n obj_validatefunc_partial = _validate)\n \n attrSpec = dict(\n version = dict(\n attr_initfunc = (lambda: 0),\n attr_label = \"OS/2 Version\",\n attr_pprintfunc = (lambda p,n,label,**k: p.simple(\"0 (Windows)\", label))),\n \n xAvgCharWidth = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Average weighted escapement\",\n attr_recalculatefunc = _recalc_xAvgCharWidth,\n attr_representsx = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_xAvgCharWidth),\n \n usWeightClass = dict(\n attr_initfunc = (lambda: 400),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Weight class\",\n attr_pprintfunc = _pprint_usWeightClass,\n attr_validatefunc = _validate_usWeightClass),\n \n usWidthClass = dict(\n attr_initfunc = (lambda: 5),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Width class\",\n attr_pprintfunc = _pprint_usWidthClass,\n attr_validatefunc = _validate_usWidthClass),\n \n fsType = dict(\n attr_followsprotocol = True,\n attr_initfunc = typeflags_v0.TypeFlags,\n attr_label = \"Type Flags\"),\n \n ySubscriptXSize = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Subscript horizontal font size\",\n attr_scaledirect = True,\n attr_validatefunc = _validate_ySubscriptXSize),\n \n ySubscriptYSize = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Subscript vertical font size\",\n attr_scaledirect = True,\n attr_validatefunc = _validate_ySubscriptYSize),\n \n ySubscriptXOffset = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Subscript x-offset\",\n attr_representsx = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_ySubscriptXOffset),\n \n ySubscriptYOffset = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Subscript y-offset\",\n attr_representsy = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_ySubscriptYOffset),\n \n ySuperscriptXSize = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Superscript horizontal font size\",\n attr_scaledirect = True,\n attr_validatefunc = _validate_ySuperscriptXSize),\n \n ySuperscriptYSize = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Superscript vertical font size\",\n attr_scaledirect = True,\n attr_validatefunc = _validate_ySuperscriptYSize),\n \n ySuperscriptXOffset = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Superscript x-offset\",\n attr_representsx = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_ySuperscriptXOffset),\n \n ySuperscriptYOffset = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Superscript y-offset\",\n attr_representsy = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_ySuperscriptYOffset),\n \n yStrikeoutSize = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Strikeout size\",\n attr_scaledirect = True,\n attr_representsy = True,\n attr_validatefunc_partial = _validate_yStrikeoutSize),\n \n yStrikeoutPosition = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Strikeout position\",\n attr_representsy = True,\n attr_scaledirect = True,\n attr_validatefunc_partial = _validate_yStrikeoutPosition),\n \n sFamilyClass = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"IBM font family class and subclass\",\n attr_pprintfunc = (lambda p,n,label,**k: p.simple(familyclass_v0.labels[n], label=label)),\n attr_validatefunc = _validate_sFamilyClass),\n \n panoseArray = dict(\n attr_followsprotocol = True,\n attr_initfunc = panose_fam2_v0.Panose_fam2,\n attr_label = \"PANOSE specification\"),\n \n achVendID = dict(\n attr_initfunc = (lambda: b'MONO'),\n attr_label = \"Font vendor\",\n attr_pprintfunc = (lambda p,n,label,**k: p.simple(vendors_v0.labels[n], label=label))),\n \n fsSelection = dict(\n attr_followsprotocol = True,\n attr_initfunc = selection_v0.Selection,\n attr_label = \"Selection Flags\",\n attr_recalculatefunc = _recalc_fsSelection),\n \n usFirstCharIndex = dict(\n attr_initfunc = (lambda: 0x0020),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Minimum Unicode\",\n attr_recalculatefunc = _recalc_usFirstCharIndex,\n attr_validatefunc = _validate_usFirstCharIndex),\n \n usLastCharIndex = dict(\n attr_initfunc = (lambda: 0x0020),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Maximum Unicode\",\n attr_recalculatefunc = _recalc_usLastCharIndex,\n attr_validatefunc = _validate_usLastCharIndex),\n \n sTypoAscender = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Typographic ascender\",\n attr_scaledirect = True,\n attr_representsy = True),\n \n sTypoDescender = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Typographic descender\",\n attr_scaledirect = True,\n attr_representsy = True),\n \n sTypoLineGap = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeShort,\n attr_label = \"Typographic line gap\",\n attr_scaledirect = True,\n attr_representsy = True),\n \n usWinAscent = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Windows ascender\",\n attr_scaledirect = True,\n attr_representsy = True,\n attr_validatefunc = _validate_usWinAscent),\n \n usWinDescent = dict(\n attr_initfunc = (lambda: 0),\n attr_inputcheckfunc = utilities.inRangeUshort,\n attr_label = \"Windows descender\",\n attr_scaledirect = True,\n attr_representsy = True,\n attr_validatefunc = _validate_usWinDescent))\n \n attrSorted = (\n 'version', 'xAvgCharWidth', 'usWeightClass', 'usWidthClass', 'fsType',\n 'ySubscriptXSize', 'ySubscriptYSize', 'ySubscriptXOffset',\n 'ySubscriptYOffset', 'ySuperscriptXSize', 'ySuperscriptYSize',\n 'ySuperscriptXOffset', 'ySuperscriptYOffset', 'yStrikeoutSize',\n 'yStrikeoutPosition', 'sFamilyClass', 'panoseArray', 'achVendID',\n 'fsSelection', 'usFirstCharIndex', 'usLastCharIndex', 'sTypoAscender',\n 'sTypoDescender', 'sTypoLineGap', 'usWinAscent', 'usWinDescent')\n \n #\n # Class methods\n #\n \n @classmethod\n def fromvalidatedwalker(cls, w, **kwArgs):\n \"\"\"\n Like fromwalker(), this method returns a new OS_2. However, it also\n does extensive validation via the logging module (the client should\n have done a logging.basicConfig call prior to calling this method,\n unless a logger is passed in via the 'logger' keyword argument).\n \"\"\"\n \n logger = kwArgs.get('logger', None)\n assert logger is not None # we're only called via factory\n \n logger.debug((\n 'V0001',\n (w.length(),),\n \"Walker has %d remaining bytes.\"))\n \n if w.length() < 78:\n logger.error(('E2127', (), \"Insufficient bytes\"))\n return None\n \n ver = w.unpack(\"H\")\n \n if ver != 0:\n logger.error(('V0002', (), \"Expected version 0\"))\n return None\n \n v = [ver]\n okToReturn = True\n v.extend(w.unpack(\"H2h\"))\n obj = typeflags_v0.TypeFlags.fromvalidatedwalker(w, **kwArgs)\n \n if obj is None:\n okToReturn = False\n \n v.append(obj)\n v.extend(w.unpack(\"10hH\"))\n obj = panose.Panose_validated(w, os2panver=0, **kwArgs)\n \n if obj is None:\n okToReturn = False\n \n v.append(obj)\n v.append(w.unpack(\"16x4s\"))\n obj = selection_v0.Selection.fromvalidatedwalker(w, **kwArgs)\n \n if obj is None:\n okToReturn = False\n \n v.append(obj)\n v.extend(w.unpack(\"2H3h2H\"))\n return (cls(*v) if okToReturn else None)\n \n @classmethod\n def fromversion0mac(cls, v0MacObj, **kwArgs):\n \"\"\"\n Returns a new OS_2 object from the specified version 0 (Mac) object.\n \"\"\"\n \n # no recalculation is needed for this conversion\n return cls(\n xAvgCharWidth = v0MacObj.xAvgCharWidth,\n usWeightClass = v0MacObj.usWeightClass,\n usWidthClass = v0MacObj.usWidthClass,\n fsType = v0MacObj.fsType,\n ySubscriptXSize = v0MacObj.ySubscriptXSize,\n ySubscriptYSize = v0MacObj.ySubscriptYSize,\n ySubscriptXOffset = v0MacObj.ySubscriptXOffset,\n ySubscriptYOffset = v0MacObj.ySubscriptYOffset,\n ySuperscriptXSize = v0MacObj.ySuperscriptXSize,\n ySuperscriptYSize = v0MacObj.ySuperscriptYSize,\n ySuperscriptXOffset = v0MacObj.ySuperscriptXOffset,\n ySuperscriptYOffset = v0MacObj.ySuperscriptYOffset,\n yStrikeoutSize = v0MacObj.yStrikeoutSize,\n yStrikeoutPosition = v0MacObj.yStrikeoutPosition,\n sFamilyClass = v0MacObj.sFamilyClass,\n panoseArray = v0MacObj.panoseArray,\n achVendID = v0MacObj.achVendID,\n fsSelection = v0MacObj.fsSelection,\n usFirstCharIndex = v0MacObj.usFirstCharIndex,\n usLastCharIndex = v0MacObj.usLastCharIndex)\n \n @classmethod\n def fromwalker(cls, w, **kwArgs):\n \"\"\"\n Returns a new OS_2 object from the specified walker.\n \n >>> _testingValues[0] == OS_2.frombytes(_testingValues[0].binaryString())\n True\n \n >>> _testingValues[1] == OS_2.frombytes(_testingValues[1].binaryString())\n True\n \"\"\"\n \n ver = w.unpack(\"H\")\n assert ver == 0 # caller must be using the right class\n v = [ver]\n v.extend(w.unpack(\"H2h\"))\n v.append(typeflags_v0.TypeFlags.fromwalker(w, **kwArgs))\n v.extend(w.unpack(\"10hH\"))\n v.append(panose.Panose(w, os2panver=0, **kwArgs))\n # 4 longs of zeroes ignored for unicode ranges, not used in v1\n w.skip(16)\n v.append(w.unpack(\"4s\"))\n v.append(selection_v0.Selection.fromwalker(w, **kwArgs))\n v.extend(w.unpack(\"2H3h2H\"))\n return cls(*v)\n \n #\n # Public methods\n #\n \n def asVersion0Mac(self, **kwArgs):\n \"\"\"\n Returns a Version 0 (Mac) OS_2 object from self.\n \"\"\"\n \n return OS_2_v0_mac.OS_2(\n xAvgCharWidth = self.xAvgCharWidth,\n usWeightClass = self.usWeightClass,\n usWidthClass = self.usWidthClass,\n fsType = self.fsType,\n ySubscriptXSize = self.ySubscriptXSize,\n ySubscriptYSize = self.ySubscriptYSize,\n ySubscriptXOffset = self.ySubscriptXOffset,\n ySubscriptYOffset = self.ySubscriptYOffset,\n ySuperscriptXSize = self.ySuperscriptXSize,\n ySuperscriptYSize = self.ySuperscriptYSize,\n ySuperscriptXOffset = self.ySuperscriptXOffset,\n ySuperscriptYOffset = self.ySuperscriptYOffset,\n yStrikeoutSize = self.yStrikeoutSize,\n yStrikeoutPosition = self.yStrikeoutPosition,\n sFamilyClass = self.sFamilyClass,\n panoseArray = self.panoseArray,\n achVendID = self.achVendID,\n fsSelection = self.fsSelection,\n usFirstCharIndex = self.usFirstCharIndex,\n usLastCharIndex = self.usLastCharIndex)\n \n def buildBinary(self, w, **kwArgs):\n \"\"\"\n Adds the binary data for the OS_2 object to the specified LinkedWriter.\n \n >>> utilities.hexdump(_testingValues[0].binaryString())\n 0 | 0000 0000 0190 0005 0000 0000 0000 0000 |................|\n 10 | 0000 0000 0000 0000 0000 0000 0000 0000 |................|\n 20 | 0200 0000 0000 0000 0000 0000 0000 0000 |................|\n 30 | 0000 0000 0000 0000 0000 4D4F 4E4F 0000 |..........MONO..|\n 40 | 0020 0020 0000 0000 0000 0000 0000 |. . .......... |\n \n >>> utilities.hexdump(_testingValues[1].binaryString())\n 0 | 0000 0258 0258 0008 0004 0000 0000 0000 |...X.X..........|\n 10 | 0000 0000 0000 0000 0000 0000 0000 0000 |................|\n 20 | 020E 0005 0000 0000 0000 0000 0000 0000 |................|\n 30 | 0000 0000 0000 0000 0000 4D4F 4E4F 0010 |..........MONO..|\n 40 | 0020 0020 0578 FCE0 0000 0000 0000 |. . .x........ |\n \"\"\"\n \n w.add(\"Hh2H\",\n self.version, self.xAvgCharWidth, self.usWeightClass,\n self.usWidthClass)\n \n self.fsType.buildBinary(w, **kwArgs)\n \n w.add(\"10hH\",\n self.ySubscriptXSize, self.ySubscriptYSize, self.ySubscriptXOffset,\n self.ySubscriptYOffset, self.ySuperscriptXSize,\n self.ySuperscriptYSize, self.ySuperscriptXOffset,\n self.ySuperscriptYOffset, self.yStrikeoutSize,\n self.yStrikeoutPosition, self.sFamilyClass)\n \n self.panoseArray.buildBinary(w, **kwArgs)\n w.add(\"16x4s\", self.achVendID)\n self.fsSelection.buildBinary(w, **kwArgs)\n \n w.add(\"2H3h2H\",\n self.usFirstCharIndex, self.usLastCharIndex, self.sTypoAscender,\n self.sTypoDescender, self.sTypoLineGap, self.usWinAscent,\n self.usWinDescent)\n\n# -----------------------------------------------------------------------------\n\n#\n# Test code\n#\n\nif 0:\n def __________________(): pass\n\nif __debug__:\n from fontio3 import utilities\n from fontio3.utilities import pp\n \n _testingValues = (\n OS_2(),\n \n OS_2(\n xAvgCharWidth = 600,\n usWeightClass = 600,\n usWidthClass = 8,\n fsType = typeflags_v0.TypeFlags.fromnumber(4),\n panoseArray = panose_fam2_v0.Panose_fam2(serif=\"Flared\", proportion=\"Expanded\"),\n fsSelection = selection_v0.Selection(strikeout=True),\n sTypoAscender = 1400,\n sTypoDescender = -800))\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n if __debug__:\n _test()\n","sub_path":"fontio3/build/lib.linux-x86_64-3.6/fontio3/OS_2/OS_2_v0.py","file_name":"OS_2_v0.py","file_ext":"py","file_size_in_byte":35920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"227089449","text":"\nMAX = 10005\nV = None\nE = None\n\nterm = \"ALLIZZWELL\"\n\ndr = [0, 0, 1, -1, 1, 1, -1, -1]\ndc = [1, -1, 0, 0, 1, -1, 1, -1]\n\n\ndef check_valid(x, y):\n if x>=0 and x=0 and y 0 do not matter\n level = 0\n valley_count = 0\n tracking_dict = {'U': 0, 'D': 0}\n for c in path:\n if c == 'D':\n level -= 1\n tracking_dict['D'] += 1\n elif c == 'U':\n level += 1\n if(tracking_dict['D'] > 0 and level == 0):\n tracking_dict['D'] = 0\n valley_count += 1\n\n return valley_count\n \n\nif __name__ == '__main__':\n steps = 8\n path = 'UDDDUDUU'\n # path = 'DDUUUUDD'\n print(countingValleys(steps, path))\n","sub_path":"HackerRank/Interview Preparation Kit/Warm Up Challenges/CountingValleys.py","file_name":"CountingValleys.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"268047069","text":"\"\"\"\nModul IP Finder\n\nEine Erklärung was heir passiert\n\nEin Aufrufbeispiel\n\nVerweise\n\"\"\"\nimport typing\nimport re\n\n\n\nclass IpFinder:\n '''\n Klassendokumentation\n '''\n PATTERN_IP = r\"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\"\n\n def __init__(self, file_path: str, pattern_ip: str=None) -> None:\n \"\"\" Docstring \"\"\"\n self.file_path = file_path\n self.log_data: str = \"\"\n self.adresses: list = []\n self.pattern_ip = pattern_ip if pattern_ip else self.PATTERN_IP\n\n def read_log(self, file_path: str=\"\") -> object:\n '''\n Funktionsname:\n '''\n if file_path:\n self.file_path = file_path\n with open(self.file_path, \"r\") as file_descriptor:\n self.log_data = file_descriptor.read()\n return self\n\n def find_ip_adresses(self, pattern_ip: str=\"\") -> object:\n '''\n Funktionsname:\n '''\n if not pattern_ip:\n pattern_ip = self.pattern_ip\n matches = re.finditer(pattern_ip, self.log_data, re.MULTILINE)\n self.adresses = [match.group() for match in matches]\n return self\n\n\n def get_ip_adresses(self) -> list:\n '''\n Funktionsname:\n '''\n return self.adresses\n\nif __name__ == \"__main__\":\n FILE_PATH = \"/home/coder/Workspace/kurse_python_cleancoding/Materialien/Sample.log\"\n\n print(IpFinder(FILE_PATH).\n read_log().\n find_ip_adresses().\n get_ip_adresses())\n ","sub_path":"Teilnehmer/tn04/Tag2/reader_4.py","file_name":"reader_4.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"602782051","text":"# 가상의 센서 4개 운영 \n# 값은 센서마다 범위를 주고, 랜덤하게\n# \n# 온도 센서 5초 간격으로 측정값 발행(iot/user1/temp)\n# 습도 센서 7초 간격으로 측정값 발행(iot/user1/humi)\n# 조도 센서 10초 간격으로 측정값 발행(iot/user1/illu)\n# 미세먼지 센서 12초 간격으로 측정값 발행(iot/user1/dust)\n\nfrom threading import Thread\nimport time\nimport random\nimport paho.mqtt.client as mqtt\n\nHOST = \"localhost\"\nclass Sensor(Thread):\n def __init__(self, interval, range, topic):\n super().__init__()\n self.interval = interval # 전송 간격\n self.range = range # 값의 범위 튜플\n self.topic = topic # 튜플\n self.client = mqtt.Client()\n\n def run(self):\n self.client.connect(HOST)\n while True:\n time.sleep(self.interval)\n value = random.uniform(*self.range)\n # 토픽 발행\n print(self.topic, value)\n self.client.publish(self.topic, value)\n self.client.loop(2)\n\nif __name__ == \"__main__\":\n temp_sensor = Sensor(5, (3, 10), 'iot/user1/temp')\n temp_sensor.start()\n\n","sub_path":"sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"365763841","text":"# -*- coding: utf-8 -*-\n\nname = \"twaddress\"\n\n\nfrom twaddress import algo\nfrom slugify import slugify\nimport re\n\n\ndef _to_eng(cut_result, for_post=False):\n code, city, road, village, address = cut_result\n\n if for_post:\n result = [road, village, '\\n%s %s' % (city, code), '\\nTaiwan (R.O.C.)']\n else:\n result = [road, village, '%s %s' % (city, code), 'Taiwan (R.O.C.)']\n if address['巷']:\n result.insert(0, 'Ln. ' + address['巷'])\n if address['弄']:\n result.insert(0, 'Aly. ' + address['弄'])\n if address['號']:\n result.insert(0, 'No.' + address['號'])\n if address['樓']:\n result.insert(0, address['樓'])\n if address['室']:\n result.insert(0, address['室'])\n\n result_str = ', '.join(filter(lambda x: x, result))\n # replace remaining chinese chars\n pattern = '[\\u4E00-\\u9FA5]+'\n match = re.findall(pattern, result_str)\n for m in match:\n result_str = result_str.replace(m, slugify(m,separator=' ', lowercase=False) + ' ')\n return result_str\n \n\n\ndef get(address, for_post=False):\n return _to_eng(cut(address), for_post=for_post)\n\n\ndef cut(address):\n return algo.mms_cut(address)\n","sub_path":"twaddress/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"260247153","text":"import numpy as np\nimport os\nimport tensorflow as tf\nimport time\n\nimport model.inference as inference\nimport utils.config as config_utils\nimport utils.gpu as gpu\nimport preprocessing\n\n\nfrom utils.face_class import FaceClass\nfrom model import loss_box, loss_class\nfrom utils.model_type import ModelType\nfrom preprocessing.picture import Picture\nfrom utils.sample_type import SampleType\n\n\ndef extract_samples(output_path, pics, sample_type):\n\n if not len(pics):\n return\n\n counter = 0\n\n tf.print(\n f'=> Starting Extraction ({ModelType.RNET}): {sample_type} samples'\n )\n\n progbar = tf.keras.utils.Progbar(\n len(pics), width=50, verbose=1, interval=0.05, stateful_metrics=None,\n unit_name='step'\n )\n progbar.update(0)\n\n for t_pic in pics:\n pic = t_pic.get_as_picture()\n if not pic:\n continue\n\n if len(pic.box):\n pic_stage1 = inference.stage1(pnet_model,\n pic,\n preconfig.stage1.pyramid_levels,\n preconfig.stage1.iou_threshold,\n preconfig.stage1.min_score,\n preconfig.stage1.min_face_size)\n\n pos = neg = part = 0\n for sbox in pic_stage1.box:\n [spic, iou] = pic.extract(sbox, (24, 24))\n\n if iou < 0.3 and neg < 3 * (pos + 1):\n neg += 1\n preprocessing.save_img(\n spic, output_path, ModelType.RNET, sample_type, FaceClass.NEGATIVE, f'{counter:04}')\n elif iou >= 0.4 and iou <= 0.65 and part < pos + 1:\n part += 1\n preprocessing.save_img(\n spic, output_path, ModelType.RNET, sample_type, FaceClass.PART_FACE, f'{counter:04}')\n elif iou > 0.65:\n pos += 1\n preprocessing.save_img(\n spic, output_path, ModelType.RNET, sample_type, FaceClass.POSITIVE, f'{counter:04}')\n else:\n continue\n counter += 1\n progbar.add(1)\n\n\nstart_time = time.time()\nconfig = config_utils.get_config()\npreconfig = config.preprocessing\ngpu.configure(preconfig.force_cpu, config.gpu_mem_limit)\n\nOUTPUT_PATH = config.sample_path\npics = preprocessing.get_picture(preconfig)\n\npnet_model = tf.keras.models.load_model(\n os.path.join(config.model_path, ModelType.PNET),\n custom_objects={'loss_class': loss_class, 'loss_box': loss_box})\n\nnp.random.shuffle(pics)\ntrain_len = len(pics) * preconfig.percentage.training // 100\nval_len = len(pics) * preconfig.percentage.validation // 100\ntrain_pics = pics[0:train_len]\nval_pics = pics[train_len:train_len + val_len]\ntest_pics = pics[train_len + val_len:]\n\nextract_samples(OUTPUT_PATH, train_pics, SampleType.TRAIN)\nextract_samples(OUTPUT_PATH, val_pics, SampleType.VALIDATION)\nextract_samples(OUTPUT_PATH, test_pics, SampleType.TEST)\n\nprint(f'\\nElapsed Time: {(time.time() - start_time):.2f} (s)')\n","sub_path":"src/preprocess_rnet.py","file_name":"preprocess_rnet.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"600128843","text":"import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,\n n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Bayesian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n \"\"\"\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n best_model = None\n best_score = float(\"inf\")\n n_features = self.X.shape[1]\n\n for n_components in range(self.min_n_components, self.max_n_components + 1):\n try:\n model = self.base_model(n_components)\n model.fit(self.X, self.lengths)\n logL = model.score(self.X, self.lengths)\n N = self.X.shape[0] # Number of data points\n\n # p = total number of parameters in the model:\n # n_components * (n_components - 1) --> transition probabilities between states (the last row can be calculated\n # because the total probability must sum 1.0, that's the reason of the -1 term)\n # n_components - 1 --> initial probabilities\n # n_components * n_features * 2 --> means and variances for each feature\n p = (n_components ** 2) + (n_components * n_features * 2) - 1\n\n bic = -2. * logL + p * np.log(N)\n\n if bic < best_score:\n # Keep the model with the lowest score\n best_model = model\n best_score = bic\n except Exception as ex:\n # Nothing to do. Just the model could not be trained with this number of components\n # print(\"Exception ocurred for word {} and {} components: {}\".format(self.this_word, n_components, ex))\n pass\n\n return best_model\n\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n https://pdfs.semanticscholar.org/ed3d/7c4a5f607201f3848d4c02dd9ba17c791fc2.pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n best_model = None\n best_score = float(\"-inf\")\n M = len(self.hwords) # Total number of categories (words)\n for num_components in range(self.min_n_components, self.max_n_components + 1):\n try:\n model = self.base_model(num_components)\n model.fit(self.X, self.lengths)\n # Likehood term\n logP = model.score(self.X, self.lengths)\n # Anti-likehood terms\n sum_ = 0.0\n for word in (word for word in self.hwords if word != self.this_word):\n X, lengths = self.hwords[word]\n sum_ += model.score(X, lengths)\n sum_ /= (M - 1)\n\n dic = logP - sum_\n\n if dic > best_score:\n best_model = model\n best_score = dic\n except Exception as ex:\n # Nothing to do. Just the model could not be trained with this number of components\n #print(\"Exception ocurred for word {} and {} components: {}\".format(self.this_word, num_components, ex))\n pass\n\n return best_model\n\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n # Number of sequences for the current word\n num_sequences = len(self.lengths)\n\n # Number of folds by default used by KFold (it could be parametrized in the class)\n # By default we will use the same number splits than sequences for this word, but we will limit it\n K = min(num_sequences, 20)\n\n if K == 0:\n # No data points\n return None\n best_global_score = float(\"-inf\")\n best_global_model = None\n\n if K == 1:\n # Cross validation cannot be applied. Just return a trained model with the single sequence available\n for num_components in range(self.min_n_components, self.max_n_components + 1):\n try:\n model = self.base_model(num_components)\n model.fit(self.X, self.lengths)\n score = model.score(self.X, self.lengths)\n if score > best_global_score:\n # Keep the model that worked best for this number of components\n best_global_model = model\n best_global_score = score\n except Exception as ex:\n # Nothing to do. Just the model could not be trained with this number of components\n # print(\"Exception occurred for word {} and {} components: {}\".format(self.this_word, num_components,\n # ex))\n pass\n return best_global_model\n\n # Apply cross validation\n kf = KFold(n_splits=K, random_state=self.random_state, shuffle=True)\n # print(\"Total sequences for word {}: {}. Number of splits: {}\".format(self.this_word, num_sequences, K))\n\n for num_components in range(self.min_n_components, self.max_n_components + 1):\n try:\n score = 0.0\n nfolds = 0\n best_model = None\n best_score = float(\"-inf\")\n # print (\"Testing {} components...\".format(num_components))\n for train_index, test_index in kf.split(self.sequences):\n # Select indexes to make this training\n # print (\"Word: {}\".format(self.this_word))\n # print (\"train_index: \", train_index)\n # print (\"test_index: \", test_index)\n model = self.base_model(num_components)\n\n # Get the sequences based on the train index\n # Unfortunately we have to iterate because self.sequences is a list of lists with variable size\n seqs = []\n lengths = []\n for ix in train_index:\n for seq in self.sequences[ix]:\n seqs.append(np.array(seq))\n lengths.append(self.lengths[ix])\n x = np.array(seqs)\n # Train with train set\n model.fit(x, lengths)\n\n # Test with test set\n seqs = []\n lengths = []\n for ix in test_index:\n for seq in self.sequences[ix]:\n seqs.append(np.array(seq))\n lengths.append(self.lengths[ix])\n x = np.array(seqs)\n likehood = model.score(x, lengths)\n\n # Keep the best model for this number of components so far\n if likehood > best_score:\n best_model = model\n best_score = likehood\n\n # Add the score (the final result will be the average)\n score += likehood\n nfolds += 1\n # The final components score will be the average score for all the folds\n score /= nfolds\n if score > best_global_score:\n # Keep the model that worked best for this number of components\n best_global_model = best_model\n best_global_score = score\n except Exception as ex:\n # Nothing to do. Just the model could not be trained with this number of components\n #print(\"Exception occurred for word {} and {} components: {}\".format(self.this_word, num_components, ex))\n pass\n\n return best_global_model","sub_path":"my_model_selectors.py","file_name":"my_model_selectors.py","file_ext":"py","file_size_in_byte":10638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"55959847","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 21 17:43:26 2018\n\n@author: Nanda Christanto\n\"\"\"\n\n\"\"\"bilangan prima antara 1-101\"\"\" \ndef prime(x) :\n prim = True \n if x >= 2 : \n for i in range (2,x) :\n if x % i == 0 : \n prim = False \n else : \n prim = False\n return prim\n\nfor i in range(1,101) :\n if prime(i) :\n print (i)\n ","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"302189863","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nFAILED_STATUS = 2\n\n\ndef parse_ansible_copy_result(node, tool, tracer):\n result = tracer.result\n config = tool.get_config()\n if \"sha1sum\" in config:\n local_checksum = config[\"sha1sum\"]\n else:\n local_checksum = None\n\n if \"ansible_result\" in result and result[\"ansible_result\"]:\n remote_checksum = result[\"ansible_result\"][\"checksum\"]\n if local_checksum != remote_checksum:\n tracer.switch(FAILED_STATUS, msg=\"checksum不一致,文件可能损坏\")\n\n\nhooks = {\n \"上传文件\": {\n \"拷贝文件\": parse_ansible_copy_result\n }\n}\n","sub_path":"library/python/autotools/autotools/lib/internal/upload_files/HOOKS.py","file_name":"HOOKS.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"119709733","text":"height = int(input(\"What's your height in cm? \"))\nage = int(input(\"What's your age?\"))\nbill = 0\nif(height >= 120):\n if(age <12):\n bill=5\n print(\"The child ticlet is $5\")\n elif(age <= 18):\n bill = 7\n print(\"The adult ticket is $7\")\n elif(age > 18 and age < 45 ):\n bill = 9\n print(\"The younster ticket is $9\")\n else:\n bill = 0\n print(\"The senior ticket is $0\")\n want_photo = input(\"You need to take the photo? Y or N.\\n \")\n if(want_photo == 'Y'):\n bill = bill + 3\n print(\"Your bill amount is: \", bill)\nelse:\n print(\"Sorry, You can't ride the roller coaster\")\n\n\n","sub_path":"day3.5.py","file_name":"day3.5.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"355630371","text":"import re\n\ndef word_count(message):\n # Returns a count of the number of each word in a message.\n # My first thought is that a hash would work, though it might not be\n # as efficient as other methods. It would, however, be very readable.\n\n count = {}\n\n for word in message.split():\n word = word.lower(); # Convert to lower case\n word = re.sub(r'\\W+', '', word); # Get rid of non-alphabetical characters\n if(word != ''): # We might be left with a null word\n if (word in count):\n count[word] = count[word] + 1;\n else:\n count[word] = 1;\n\n return count\n","sub_path":"all_data/exercism_data/python/word-count/5df217a80cc0491d8b86caee1e701669.py","file_name":"5df217a80cc0491d8b86caee1e701669.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"336243029","text":"# -*- coding: utf-8 -*-\n\nimport ujson\n\nimport pytest\n\nCORRECT_GET_BLOCK_1000_RESPONSE = {\n \"id\": 1,\n \"result\": {\n \"previous\":\n \"000003e7c4fd3221cf407efcf7c1730e2ca54b05\",\n \"timestamp\":\n \"2016-03-24T16:55:30\",\n \"witness\":\n \"initminer\",\n \"transaction_merkle_root\":\n \"0000000000000000000000000000000000000000\",\n \"extensions\": [],\n \"witness_signature\":\n \"207f15578cac20ac0e8af1ebb8f463106b8849577e21cca9fc60da146d1d95df88072dedc6ffb7f7f44a9185bbf9bf8139a5b4285c9f423843720296a44d428856\",\n \"transactions\": [],\n \"block_id\":\n \"000003e8b922f4906a45af8e99d86b3511acd7a5\",\n \"signing_key\":\n \"STM8GC13uCZbP44HzMLV6zPZGwVQ8Nt4Kji8PapsPiNq1BK153XTX\",\n \"transaction_ids\": []\n }\n}\n\n@pytest.mark.timeout(5)\n@pytest.mark.parametrize(\n 'request',\n [\n # single jsonrpc steemd request\n dict(id=1, jsonrpc='2.0', method='get_block', params=[1000]),\n\n # batch jsronrpc steemd request\n [\n dict(id=2, jsonrpc='2.0', method='get_block', params=[1000]),\n dict(id=3, jsonrpc='2.0', method='get_block', params=[1000])\n ],\n\n # single jsonrpc old-style steemd requests\n dict(\n id=1,\n jsonrpc='2.0',\n method='call',\n params=['database_api', 'get_block', [1000]]),\n\n # batch jsonrpc old-style steemd request\n [\n dict(\n id=4,\n jsonrpc='2.0',\n method='call',\n params=['database_api', 'get_block', [1000]]),\n dict(\n id=5,\n jsonrpc='2.0',\n method='call',\n params=['database_api', 'get_block', [1000]]),\n ],\n\n # batch jsonrpc mixed-style steemd request\n [\n dict(id=6, jsonrpc='2.0', method='get_block', params=[1000]),\n dict(\n id=7,\n jsonrpc='2.0',\n method='call',\n params=['database_api', 'get_block', [1000]]),\n ]\n ])\ndef test_jsonrpc_request(app, request):\n _, response = app.test_client.post(\n '/', json=request, server_kwargs=dict(workers=1))\n assert response.status == 200\n assert response.headers['Content-Type'] == 'application/json'\n json_response = ujson.loads(response.body.decode())\n if isinstance(request, list):\n assert isinstance(json_response, list)\n for i, resp in enumerate(json_response):\n assert isinstance(resp, dict)\n assert request[i]['id'] == resp['id']\n assert 'error' not in resp\n if isinstance(request, dict):\n assert request['id'] == json_response['id']\n assert isinstance(json_response, dict)\n assert 'error' not in json_response\n\n@pytest.mark.timeout(5)\ndef test_batch_jsonrpc_requests(app, random_jrpc_batch):\n _, response = app.test_client.post(\n '/', json=random_jrpc_batch, server_kwargs=dict(workers=1))\n assert response.status == 200\n assert response.headers['Content-Type'] == 'application/json'\n json_response = ujson.loads(response.body.decode())\n assert isinstance(json_response, list)\n assert len(json_response) == len(random_jrpc_batch)\n for i, item in enumerate(json_response):\n assert item['id'] == random_jrpc_batch[i]['id']\n assert 'result' in item\n assert 'error' not in item\n\n\ndef test_all_steemd_calls(app, all_steemd_jrpc_calls):\n _, response = app.test_client.post(\n '/', json=all_steemd_jrpc_calls, server_kwargs=dict(workers=1))\n assert response.status == 200\n assert response.headers['Content-Type'] == 'application/json'\n json_response = ujson.loads(response.body.decode())\n assert 'id' in json_response\n assert 'result' in json_response\n assert 'error' not in json_response\n","sub_path":"tests/test_jsonrpc_routes.py","file_name":"test_jsonrpc_routes.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"282168965","text":"import control as ctrl\nfrom control import matlab\n# aca deberia hacer una funcion que recibe polos\n# que tiene un algoritmo definido\n# y que devuelve el array de numerador y denominador para poder ponerlo en una funcion lti\n\n\ndef gather1stand2ndOrder(poles):\n newPoles=[]\n for i in range(len(poles)):\n if poles[i].imag>=0:\n newPoles.append(poles[i])\n return newPoles\n\ndef LP_FreqTransform2ndOrd(sk,wp): #esta funcion necesita un solo conjugado!!\n num=[1]\n den=[1/wp**2,-2*sk.real/wp, abs(sk)**2]\n return num, den\n\ndef LP_FreqTransform2ndOrd(sk,wp):\n num = [wp]\n den = [1,-sk*wp]\n return num,den\n\npoles=[(-0.3826834323650897+0.9238795325112867j), (-0.9238795325112867+0.3826834323650899j), (-0.9238795325112868-0.38268343236508967j), (-0.38268343236509034-0.9238795325112865j)]\n# wp/(s-sk*wp)\nwp=100\nx= ctrl.TransferFunction([1], [1])\npoles=gather1stand2ndOrder(poles)\n\nfor i in range(len(poles)):\n if poles[i].imag>0:\n num,den =LP_FreqTransform2ndOrd(poles[i],wp)\n elif poles[i].imag==0:\n num,den =LP_FreqTransform2ndOrd(poles[i],wp)\n x*=ctrl.TransferFunction(num,den)\nprint(x)\nnum,den=matlab.tfdata(x)\n\nprint(num[0][0]) # se accede asi\nprint(den[0][0])\n# print(den[0][0])\n","sub_path":"TP4/proyecto_oficial/controltf_testbench.py","file_name":"controltf_testbench.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"206196397","text":"class Solution:\n def solve(self, intervals):\n result = []\n intervals.sort(key=lambda interval: interval[0])\n\n start, end = intervals[0]\n for interval in intervals:\n # can't be merged, append the length directly and reassign the bounds\n if interval[0] > end:\n result.append(end - start + 1)\n start, end = interval\n # can be merged, compare the upper bound before merging\n else:\n end = max(end, interval[1])\n result.append(end - start + 1)\n\n return max(result)\n","sub_path":"solutions/0333_Longest-Interval/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"286251176","text":"import pandas as pd\nimport numpy as np\n\ndef standardize_column_names(data):\n \n print(\"Standardizing Column Names...\")\n \n # Replace space and '_' in column names and convert them to lowercase \n data.columns = [i.replace(' ', '_').lower() for i in data.columns]\n \n return data\n\ndef drop_features(data, columns_to_drop):\n \n print(\"Dropping Columns...\")\n \n # Drop all the list of columns specified by the user\n data = data.drop(columns_to_drop, axis=1, errors='ignore')\n \n return data\n\ndef drop_duplicate_rows(data):\n \n print(\"Removing Duplicates...\")\n \n # Drop all the duplicate rows\n data = data.drop_duplicates()\n \n return data\n\ndef replace_value(data, columns, value_to_replace, new_value):\n \n print(\"Replacing values...\")\n \n # If columns not specified by the user, replace value in all columns \n if columns==[]:\n data = data.replace(value_to_replace, new_value)\n else:\n for column in columns:\n data[column] = data[column].replace(value_to_replace, new_value)\n \n return data\n\ndef fill_na_rows(data):\n \n print(\"Filling Missing Values...\")\n \n # Retrieve the list of columns having nulls and interpolate for each column\n na_columns = data.columns[data.isna().any()].tolist()\n for column in na_columns:\n data[column] = data[column].interpolate(method='pad', limit_direction='forward')\n \n return data\n\ndef drop_na_rows(data):\n \n print(\"Dropping Missing Values...\")\n \n # Drop all nulls\n data = data.dropna() \n \n return data\n\ndef reduce_feature_cardinality(data, category_column, new_value, threshold):\n \n print(\"Reducing Column Cardinality...\")\n \n # If user doesn't input new value to replace with\n if pd.isnull(new_value):\n new_value = \"other\"\n \n # Find relative frequency of column to compare with threshold\n relative_pct = data[category_column].value_counts(dropna=False, normalize=True).round(2)\n \n values_to_retain = []\n # If threshold not provided by user, retain only top 5 values else extract values to retain\n if threshold == 0:\n values_to_retain = relative_pct[:5].index.to_list()\n else:\n cum_relative_pct = 0\n for idx in relative_pct.index:\n cum_relative_pct += relative_pct[idx]\n if cum_relative_pct < threshold:\n values_to_retain.append(idx)\n if cum_relative_pct == threshold:\n values_to_retain.append(idx)\n break\n \n # Replace all values in DataFrame other than values marked to be retained\n data_out = data.copy()\n data_out.loc[~data[category_column].isin(values_to_retain), category_column] = new_value\n \n return data_out\n\ndef convert_features_dtype_to_datetime(data, datetime_columns):\n \n print(\"Converting dtypes to datetime...\")\n \n # Convert columns to datetime\n data_out = data.copy()\n data_out.loc[:, datetime_columns] = data[datetime_columns].apply(pd.to_datetime, infer_datetime_format=True, errors='ignore')\n \n return data_out\n\ndef convert_features_dtype_to_category(data, category_columns):\n \n print(\"Converting dtypes to category...\")\n \n # Convert columns to category type\n data_out = data.copy()\n data_out.loc[:, category_columns] = data[category_columns].apply(pd.Categorical)\n \n return data_out\n\ndef convert_features_dtype_to_numeric(data, numeric_columns):\n \n print(\"Converting dtypes to numeric...\")\n \n # Convert columns to numeric\n data_out = data.copy()\n data_out.loc[:, numeric_columns] = data[numeric_columns].apply(pd.to_numeric, errors='ignore')\n \n return data_out\n\ndef remove_outliers_in_numerical_feature(data, num_columns):\n \n print(\"Removing outliers...\")\n \n # If user doesn't provide the column name(s), then infer the type\n if num_columns==[]:\n num_columns = data.select_dtypes(include=np.number).columns\n \n # Remove outliers for specified columns\n for column in num_columns:\n q1 = data[column].quantile(0.25)\n q3 = data[column].quantile(0.75)\n iqr = q3-q1\n fence_low = q1-1.5*iqr\n fence_high = q3+1.5*iqr\n data = data.loc[(data[column] > fence_low) & (data[column] < fence_high)]\n \n return data\n\n#================================================================================================================================\n\ndef clean(data, method=\"default\", columns=[], dtype=\"numeric\", to_replace=\"\", value=np.nan, threshold=0):\n \n try:\n \n # Default method\n if method==\"default\":\n data = standardize_column_names(data)\n data = drop_duplicate_rows(data)\n data = drop_na_rows(data) \n return data\n \n if method==\"standardize\":\n data = standardize_column_names(data)\n return data\n \n if method==\"dropcols\":\n data = drop_features(data, columns)\n return data\n\n if method==\"duplicates\":\n data = drop_duplicate_rows(data)\n return data\n\n if method==\"replaceval\":\n data = replace_value(data, columns, to_replace, value)\n return data\n\n if method==\"fillmissing\": \n data = fill_na_rows(data)\n return data\n \n if method==\"dropmissing\":\n data = drop_na_rows(data)\n return data\n \n if method==\"cardinality\":\n data = reduce_feature_cardinality(data, columns, value, threshold)\n return data\n\n if method==\"dtypes\":\n if dtype==\"datetime\":\n data = convert_features_dtype_to_datetime(data, columns)\n if dtype==\"category\":\n data = convert_features_dtype_to_category(data, columns)\n if dtype==\"numeric\":\n data = convert_features_dtype_to_numeric(data, columns)\n return data\n \n if method==\"outliers\":\n data = remove_outliers_in_numerical_feature(data, columns)\n return data\n \n except Exception as e:\n print(e)\n return data","sub_path":"quickda/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":6204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"41412428","text":"#Python wrapper / library for Einstein Analytics API\nimport sys\nimport browser_cookie3\nimport requests\nimport json\nimport time\nimport datetime\nfrom dateutil import tz\nimport pandas as pd\nimport numpy as np\nimport re\nfrom pandas import json_normalize\nfrom decimal import Decimal\nimport base64\nimport csv\nimport unicodecsv\nfrom unidecode import unidecode\nimport math\n\n\nclass salesforceEinsteinAnalytics(object):\n\tdef __init__(self, env_url, browser):\n\t\tself.env_url = env_url\n\t\ttry:\n\t\t if browser == 'chrome':\n\t\t cj = browser_cookie3.chrome(domain_name=env_url[8:]) #remove first 8 characters since browser cookie does not expect \"https://\"\n\t\t my_cookies = requests.utils.dict_from_cookiejar(cj)\n\t\t self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}\n\t\t elif browser == 'firefox':\n\t\t cj = browser_cookie3.firefox(domain_name=env_url[8:])\n\t\t my_cookies = requests.utils.dict_from_cookiejar(cj)\n\t\t self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}\n\t\t else:\n\t\t print('Please select a valid browser (chrome or firefox)')\n\t\t sys.exit(1)\n\t\texcept:\n\t\t print('ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox).')\n\t\t sys.exit(1)\n\n\n\t#set timezone for displayed operation start time\n\tdef get_local_time(self, add_sec=None, timeFORfile=False):\n\t curr_time = datetime.datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal())\n\t if add_sec is not None:\n\t return (curr_time + datetime.timedelta(seconds=add_sec)).strftime(\"%I:%M:%S %p\")\n\t elif timeFORfile == True:\n\t return curr_time.strftime(\"%m_%d_%Y__%I%p\")\n\t else:\n\t return curr_time.strftime(\"%I:%M:%S %p\")\t\n\n\n\tdef get_dataset_id(self, dataset_name, search_type='API Name', verbose=False):\n\t\tparams = {'pageSize': 50, 'sort': 'Mru', 'hasCurrentOnly': 'true', 'q': dataset_name}\n\t\tdataset_json = requests.get(self.env_url+'/services/data/v48.0/wave/datasets', headers=self.header, params=params) \n\t\tdataset_df = json_normalize(json.loads(dataset_json.text)['datasets'])\n\n\t\t#check if the user wants to seach by API name or label name\n\t\tif search_type == 'UI Label':\n\t\t\tdataset_df = dataset_df[dataset_df['label'] == dataset_name]\n\t\telse:\n\t\t\tdataset_df = dataset_df[dataset_df['name'] == dataset_name]\n\n\t\t#show user how many matches that they got. Might want to use exact API name if getting multiple matches for label search.\n\t\tif verbose == True:\n\t\t\tprint('Found '+str(dataset_df.shape[0])+' matching datasets.')\n\n\t\t#if dataframe is empty then return not found message or return the dataset ID\n\t\tif dataset_df.empty == True:\n\t\t\tprint('Dataset not found. Please check name or API name in Einstein Analytics.')\n\t\t\tsys.exit(1)\n\t\telse:\n\t\t\tdsnm = dataset_df['name'].tolist()[0]\n\t\t\tdsid = dataset_df['id'].tolist()[0]\n\t\t\t\n\t\t\t#get dataset version ID\n\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/datasets/'+dsid, headers=self.header)\n\t\t\tdsvid = json.loads(r.text)['currentVersionId']\n\t\t\t\n\t\t\treturn dsnm, dsid, dsvid \n\n\n\tdef run_saql_query(self, saql, save_path=None, verbose=False):\n\t\t'''\n\t\t\tThis function takes a saql query as an argument and returns a dataframe or saves to csv\n\t\t\tThe query can be in JSON form or can be in the UI SAQL form\n\t\t\tload statements must have the appropreate spaces: =_load_\\\"datasetname\\\";\n\t\t'''\n\t\t\n\t\tif verbose == True:\n\t\t\tstart = time.time()\n\t\t\tprint('Checking SAQL and Finding Dataset IDs...')\n\t\t\tprint('Process started at: '+str(self.get_local_time()))\n\t\t\n\t\tsaql = saql.replace('\\\"','\\\\\"') #convert UI saql query to JSON format\n\t\t\n\t\t#create a dictionary with all datasets used in the query\n\t\tload_stmt_old = re.findall(r\"(= load )(.*?)(;)\", saql)\n\t\tload_stmt_new = load_stmt_old.copy()\n\t\tfor ls in range(0,len(load_stmt_new)):\n\t\t\tload_stmt_old[ls] = ''.join(load_stmt_old[ls])\n\n\t\t\tdsnm, dsid, dsvid = self.get_dataset_id(dataset_name=load_stmt_new[ls][1].replace('\\\\\"',''), verbose=verbose)\n\t\t\tload_stmt_new[ls] = ''.join(load_stmt_new[ls])\n\t\t\tload_stmt_new[ls] = load_stmt_new[ls].replace(dsnm, dsid+'/'+dsvid)\n\n\t\t#update saql with dataset ID and version ID\n\t\tfor i in range(0,len(load_stmt_new)):\n\t\t\tsaql = saql.replace(load_stmt_old[i], load_stmt_new[i])\n\t\tsaql = saql.replace('\\\\\"','\\\"')\n\n\t\tif verbose == True:\n\t\t\tprint('Running SAQL Query...')\n\n\t\t#run query and return dataframe or save as csv\n\t\tpayload = {\"query\":saql}\n\t\tr = requests.post(self.env_url+'/services/data/v48.0/wave/query', headers=self.header, data=json.dumps(payload) )\n\t\tdf = json_normalize(json.loads(r.text)['results']['records'])\n\t\t\n\t\t\n\t\tif save_path is not None:\n\t\t\tif verbose == True:\n\t\t\t\tprint('Saving result to CSV...')\n\t\t\t\n\t\t\tdf.to_csv(save_path, index=False)\n\t\t\t\n\t\t\tif verbose == True:\n\t\t\t\tend = time.time()\n\t\t\t\tprint('Dataframe saved to CSV...')\n\t\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\t\t\treturn df\n\n\t\telse:\n\t\t\tif verbose == True:\n\t\t\t\tend = time.time()\n\t\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\t\t\treturn df\n\n\n\tdef restore_previous_dashboard_version(self, dashboard_id, version_num=None, save_json_path=None):\n\t\t'''\n\t\t\tversion number goes backwards 0 = current version 20 is max oldest version.\n\t\t\tTypically best practice to run the function and view the history first before supplying a version number.\n\t\t'''\n\t\t#get broken dashboard version history\n\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/dashboards/'+dashboard_id+'/histories', headers=self.header)\n\t\thistory_df = json_normalize(json.loads(r.text)['histories'])\n\t\t\t\n\t\tif save_json_path is not None and version_num is not None:\n\t\t\tpreview_link = history_df['previewUrl'].tolist()[version_num]\n\t\t\tr_restore = requests.get(self.env_url+preview_link, headers=self.header)\n\t\t\twith open(save_json_path, 'w', encoding='utf-8') as f:\n\t\t\t\tjson.dump(r_restore.json(), f, ensure_ascii=False, indent=4)\n\t\t\n\t\telif version_num is not None:\n\t\t\tpayload = { \"historyId\": history_df['id'].tolist()[version_num] }\n\t\t\tfix = requests.put(self.env_url+history_df['revertUrl'].tolist()[version_num], headers=self.header, data=json.dumps(payload))\n\t\t\n\t\telse:\n\t\t\treturn history_df\n\t\t\n\n\n\tdef get_app_user_list(self, app_id=None, save_path=None, verbose=False, max_request_attempts=3):\n\t\t\n\t\tif verbose == True:\n\t\t\tstart = time.time()\n\t\t\tprogress_counter = 0\n\t\t\tprint('Getting app user list and access details...')\n\t\t\tprint('Process started at: '+str(self.get_local_time()))\n\n\t\tif app_id is None:\n\t\t\t'''ALERT: CURRENTLY GETTING AN ERROR FOR ALL APP REQUEST\n\t\t\t\tERROR = OpenSSL.SSL.SysCallError: (-1, 'Unexpected EOF')\n\t\t\t\tProposed Solution is to add a try/except block to handle the error\n\t\t\t'''\n\t\t\tattempts = 0\n\t\t\twhile attempts < max_request_attempts:\n\t\t\t\ttry:\n\t\t\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders', headers=self.header)\n\t\t\t\t\tresponse = json.loads(r.text)\n\t\t\t\t\ttotal_size = response['totalSize']\n\t\t\t\t\tnext_page = response['nextPageUrl']\n\n\t\t\t\t\tapp_user_df = pd.DataFrame()\n\t\t\t\t\tbreak\n\t\t\t\texcept:\n\t\t\t\t\tattempts += 1\n\t\t\t\t\tif verbose == True:\n\t\t\t\t\t\tprint(\"Unexpected error:\", sys.exc_info()[0])\n\t\t\t\t\t\tprint(\"Trying again...\")\n\n\t\t\tfor app in response['folders']:\n\t\t\t\tattempts = 0\n\t\t\t\twhile attempts < max_request_attempts:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app[\"id\"], headers=self.header)\n\t\t\t\t\t\tusers = json.loads(r.text)['shares']\n\t\t\t\t\t\tfor u in users: \n\t\t\t\t\t\t\tapp_user_df = app_user_df.append(\t{\t\"AppId\": app['id'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AppName\": app['name'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserId\": u['sharedWithId'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserName\": u['sharedWithLabel'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AccessType\": u['accessType'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserType\": u['shareType']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}, ignore_index=True)\n\t\t\t\t\t\tbreak\n\t\t\t\t\texcept:\n\t\t\t\t\t\tattempts += 1\n\t\t\t\t\t\tif verbose == True:\n\t\t\t\t\t\t\tprint(\"Unexpected error:\", sys.exc_info()[0])\n\t\t\t\t\t\t\tprint(\"Trying again...\")\n\n\t\t\t#continue to pull data from next page\n\t\t\tattempts = 0 # reset attempts for additional pages\n\t\t\twhile next_page is not None:\n\t\t\t\tif verbose == True:\n\t\t\t\t\tprogress_counter += 25\n\t\t\t\t\tprint('Progress: '+str(round(progress_counter/total_size*100,1))+'%')\n\n\t\t\t\twhile attempts < max_request_attempts:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tnp = requests.get(self.env_url+next_page, headers=self.header)\n\t\t\t\t\t\tresponse = json.loads(np.text)\n\t\t\t\t\t\tnext_page = response['nextPageUrl']\n\t\t\t\t\t\tbreak\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tnext_page = None\n\t\t\t\t\t\tprint(sys.exc_info()[0])\n\t\t\t\t\t\tbreak\n\t\t\t\t\texcept:\n\t\t\t\t\t\tattempts += 1\n\t\t\t\t\t\tif verbose == True:\n\t\t\t\t\t\t\tprint(\"Unexpected error:\", sys.exc_info()[0])\n\t\t\t\t\t\t\tprint(\"Trying again...\")\n\n\n\t\t\t\twhile attempts < max_request_attempts:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tfor app in response['folders']:\n\t\t\t\t\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app[\"id\"], headers=self.header)\n\t\t\t\t\t\t\tusers = json.loads(r.text)['shares']\n\t\t\t\t\t\t\tfor u in users: \n\t\t\t\t\t\t\t\tapp_user_df = app_user_df.append(\t{\t\"AppId\": app['id'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AppName\": app['name'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserId\": u['sharedWithId'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserName\": u['sharedWithLabel'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AccessType\": u['accessType'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserType\": u['shareType']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}, ignore_index=True)\n\t\t\t\t\t\tbreak\n\t\t\t\t\texcept:\n\t\t\t\t\t\tattempts += 1\n\t\t\t\t\t\tif verbose == True:\n\t\t\t\t\t\t\tprint(\"Unexpected error:\", sys.exc_info()[0])\n\t\t\t\t\t\t\tprint(\"Trying again...\")\n\n\n\t\telif app_id is not None:\n\t\t\tif type(app_id) is list or type(app_id) is tuple:\n\t\t\t\tfor app in app_id:\n\t\t\t\t\tapp_user_df = pd.DataFrame()\n\t\t\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app, headers=self.header)\n\t\t\t\t\tresponse = json.loads(r.text)\n\t\t\t\t\tfor u in response['shares']: \n\t\t\t\t\t\tapp_user_df = app_user_df.append(\t{\t\"AppId\": app, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AppName\": response['name'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserId\": u['sharedWithId'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserName\": u['sharedWithLabel'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AccessType\": u['accessType'], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"UserType\": u['shareType']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}, ignore_index=True)\n\t\t\telse:\n\t\t\t\tprint('Please input a list or tuple of app Ids')\n\t\t\t\tsys.exit(1)\n\n\t\t\n\t\t\n\t\tif save_path is not None:\n\t\t\tif verbose == True:\n\t\t\t\tprint('Saving result to CSV...')\n\n\t\t\tapp_user_df.to_csv(save_path, index=False)\n\t\t\t\n\t\t\tif verbose == True:\n\t\t\t\tend = time.time()\n\t\t\t\tprint('Dataframe saved to CSV...')\n\t\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\n\t\t\treturn app_user_df\n\t\t\t\n\t\telse: \n\t\t\tif verbose == True:\n\t\t\t\tend = time.time()\n\t\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\t\t\treturn app_user_df\n\n\n\tdef update_app_access(self, user_dict, app_id, update_type, verbose=False):\n\t\t'''\n\t\t\tupdate types include: addNewUsers, fullReplaceAccess, removeUsers, updateUsers\n\t\t'''\n\t\tif verbose == True:\n\t\t\tstart = time.time()\n\t\t\tprint('Updating App Access...')\n\t\t\tprint('Process started at: '+str(self.get_local_time()))\n\t\t\n\t\tif update_type == 'fullReplaceAccess':\n\t\t\tshares = user_dict\n\n\t\telif update_type == 'addNewUsers':\n\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app_id, headers=self.header)\n\t\t\tresponse = json.loads(r.text)\n\t\t\tshares = response['shares']\n\t\t\t\n\t\t\t#remove fields in the JSON that we don't want\n\t\t\tfor s in shares:\n\t\t\t\ttry:\n\t\t\t\t\tdel s['sharedWithLabel']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\tdel s['imageUrl']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\n\t\t\tshares = shares + user_dict\n\n\t\telif update_type == 'removeUsers':\n\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app_id, headers=self.header)\n\t\t\tresponse = json.loads(r.text)\n\t\t\tshares = response['shares']\n\t\t\t\n\t\t\tto_remove = []\n\t\t\tfor u in user_dict:\n\t\t\t\tto_remove.append(u['sharedWithId'])\n\n\t\t\tfor s in shares:\n\t\t\t\tif s['sharedWithId'] in to_remove:\n\t\t\t\t\tshares.remove(s)\n\n\t\t\t#remove fields in the JSON that we don't want\n\t\t\tfor s in shares:\n\t\t\t\ttry:\n\t\t\t\t\tdel s['sharedWithLabel']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\tdel s['imageUrl']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\telif update_type == 'updateUsers':\n\t\t\tr = requests.get(self.env_url+'/services/data/v48.0/wave/folders/'+app_id, headers=self.header)\n\t\t\tresponse = json.loads(r.text)\n\t\t\tshares = response['shares']\n\t\t\t\n\t\t\tto_update = []\n\t\t\tfor u in user_dict:\n\t\t\t\tto_update.append(u['sharedWithId'])\n\n\t\t\tfor s in range(0,len(shares)):\n\t\t\t\tif shares[s]['sharedWithId'] in to_update:\n\t\t\t\t\tshares[s] = next(item for item in user_dict if item[\"sharedWithId\"] == shares[s]['sharedWithId'])\n\n\t\t\t#remove fields in the JSON that we don't want\n\t\t\tfor s in shares:\n\t\t\t\ttry:\n\t\t\t\t\tdel s['sharedWithLabel']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\tdel s['imageUrl']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\telse:\n\t\t\tshares = None\n\t\t\tprint('Please choose a user update operation. Options are: addNewUsers, fullReplaceAccess, removeUsers, updateUsers')\n\t\t\tsys.exit(1)\n\t\t\n\t\tif shares is not None:\n\t\t\tpayload = {\"shares\": shares}\n\t\t\tr = requests.patch(self.env_url+'/services/data/v48.0/wave/folders/'+app_id, headers=self.header, data=json.dumps(payload))\n\n\n\t\tif verbose == True:\n\t\t\tend = time.time()\n\t\t\tprint('User Access Updated')\n\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\n\n\tdef update_dashboard_access(self, update_df, update_type, verbose=True):\n\t\t'''\n\t\t\tFunction to make it easier to update access using dashboard names vs finding all apps needed.\n\t\t\tupdate dataframe should have the following columns: Dashboard Id, Access Type, and User Id\n\t\t'''\n\t\tpass\n\n\tdef remove_non_ascii(self, df, columns=None):\n\t\tif columns == None:\n\t\t\tcolumns = df.columns\n\t\telse:\n\t\t\tcolumns = columns\n\n\t\tfor c in columns:\n\t\t\tif df[c].dtype == \"O\":\n\t\t\t\tdf[c] = df[c].apply(lambda x: unidecode(x).replace(\"?\",\"\"))\n\n\n\tdef create_xmd(self, df, dataset_label, useNumericDefaults=True, default_measure_val=\"0.0\", default_measure_fmt=\"0.0#\", charset=\"UTF-8\", deliminator=\",\", lineterminator=\"\\r\\n\"):\n\t\tdataset_label = dataset_label\n\t\tdataset_api_name = dataset_label.replace(\" \",\"_\")\n\n\t\tfields = []\n\t\tfor c in df.columns:\n\t\t\tif df[c].dtype == \"datetime64[ns]\":\n\t\t\t\tname = c.replace(\" \",\"_\")\n\t\t\t\tname = name.replace(\"__\",\"_\")\n\t\t\t\tdate = {\n\t\t\t\t\t\"fullyQualifiedName\": name,\n\t\t\t\t\t\"name\": name,\n\t\t\t\t\t\"type\": \"Date\",\n\t\t\t\t\t\"label\": c,\n\t\t\t\t\t\"format\": \"yyyy-MM-dd HH:mm:ss\"\n\t\t\t\t}\n\t\t\t\tfields.append(date)\n\t\t\telif np.issubdtype(df[c].dtype, np.number):\n\t\t\t\tif useNumericDefaults == True:\n\t\t\t\t\tprecision = 18\n\t\t\t\t\tscale = 2\n\t\t\t\telif useNumericDefaults == False:\n\t\t\t\t\tprecision = df[c].astype('str').apply(lambda x: len(x.replace('.', ''))).max()\n\t\t\t\t\tscale = -df[c].astype('str').apply(lambda x: Decimal(x).as_tuple().exponent).min()\n\t\t\t\tname = c.replace(\" \",\"_\")\n\t\t\t\tname = name.replace(\"__\",\"_\")\n\t\t\t\tmeasure = {\n\t\t\t\t\t\"fullyQualifiedName\": name,\n\t\t\t\t\t\"name\": name,\n\t\t\t\t\t\"type\": \"Numeric\",\n\t\t\t\t\t\"label\": c,\n\t\t\t\t\t\"precision\": precision,\n\t\t\t\t\t\"defaultValue\": default_measure_val,\n\t\t\t\t\t\"scale\": scale,\n\t\t\t\t\t\"format\": default_measure_fmt,\n\t\t\t\t\t\"decimalSeparator\": \".\"\n\t\t\t\t}\n\t\t\t\tfields.append(measure)\n\t\t\telse:\n\t\t\t\tname = c.replace(\" \",\"_\")\n\t\t\t\tname = name.replace(\"__\",\"_\")\n\t\t\t\tdimension = {\n\t\t\t\t\t\"fullyQualifiedName\": name,\n\t\t\t\t\t\"name\": name,\n\t\t\t\t\t\"type\": \"Text\",\n\t\t\t\t\t\"label\": c\n\t\t\t\t}\n\t\t\t\tfields.append(dimension)\n\n\t\txmd = {\n\t\t\t\"fileFormat\": {\n\t\t\t\t\t\t\t\"charsetName\": charset,\n\t\t\t\t\t\t\t\"fieldsDelimitedBy\": deliminator,\n\t\t\t\t\t\t\t\"linesTerminatedBy\": lineterminator\n\t\t\t\t\t\t},\n\t\t\t\"objects\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"connector\": \"CSV\",\n\t\t\t\t\t\t\t\"fullyQualifiedName\": dataset_api_name,\n\t\t\t\t\t\t\t\"label\": dataset_label,\n\t\t\t\t\t\t\t\"name\": dataset_api_name,\n\t\t\t\t\t\t\t\"fields\": fields\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t} \n\t\treturn str(xmd).replace(\"'\",'\"')\n\n\n\n\tdef load_df_to_EA(self, df, dataset_api_name, xmd=None, encoding='UTF-8', operation='Overwrite', useNumericDefaults=True, default_measure_val=\"0.0\", \n\t\tdefault_measure_fmt=\"0.0#\", charset=\"UTF-8\", deliminator=\",\", lineterminator=\"\\r\\n\", removeNONascii=True, ascii_columns=None, fillna=True, dataset_label=None, verbose=False):\n\t\t'''\n\t\t\tfield names will show up exactly as the column names in the supplied dataframe\n\t\t'''\n\n\t\tif verbose == True:\n\t\t\tstart = time.time()\n\t\t\tprint('Loading Data to Einstein Analytics...')\n\t\t\tprint('Process started at: '+str(self.get_local_time()))\n\n\t\tdataset_api_name = dataset_api_name.replace(\" \",\"_\")\n\n\t\tif fillna == True:\n\t\t\tfor c in df.columns:\n\t\t\t\tif df[c].dtype == \"O\":\n\t\t\t\t\tdf[c].fillna('NONE', inplace=True)\n\t\t\t\telif np.issubdtype(df[c].dtype, np.number):\n\t\t\t\t\tdf[c].fillna(0, inplace=True)\n\t\t\t\telif df[c].dtype == \"datetime64[ns]\":\n\t\t\t\t\tdf[c].fillna(pd.to_datetime('1900-01-01 00:00:00'), inplace=True)\n\n\n\t\tif ascii_columns is not None:\n\t\t\tself.remove_non_ascii(df, columns=ascii_columns)\n\t\telif removeNONascii == True:\n\t\t\tself.remove_non_ascii(df)\n\n\t\t\n\t\t# Upload Config Steps\n\t\tif xmd is not None:\n\t\t\txmd64 = base64.urlsafe_b64encode(json.dumps(xmd).encode(encoding)).decode()\n\t\telse:\n\t\t\txmd64 = base64.urlsafe_b64encode(self.create_xmd(df, dataset_api_name, useNumericDefaults=useNumericDefaults, default_measure_val=default_measure_val, \n\t\t\t\tdefault_measure_fmt=default_measure_fmt, charset=charset, deliminator=deliminator, lineterminator=lineterminator).encode(encoding)).decode()\n\n\n\t\tupload_config = {\n\t\t\t\t\t\t'Format' : 'CSV',\n\t\t\t\t\t\t'EdgemartAlias' : dataset_api_name,\n\t\t\t\t\t\t'Operation' : operation,\n\t\t\t\t\t\t'Action' : 'None',\n\t\t\t\t\t\t'MetadataJson': xmd64\n\t\t\t\t\t}\n\n\n\t\tr1 = requests.post(self.env_url+'/services/data/v48.0/sobjects/InsightsExternalData', headers=self.header, data=json.dumps(upload_config))\n\t\ttry:\n\t\t\tjson.loads(r1.text)['success'] == True\n\t\texcept: \n\t\t\tprint('ERROR: Upload Config Failed')\n\t\t\tprint(r1.text)\n\t\t\tsys.exit(1)\n\t\tif verbose == True:\n\t\t\tprint('Upload Configuration Complete...')\n\t\t\tprint('Chunking and Uploading Data Parts...')\n\n\t\t\n\t\tMAX_FILE_SIZE = 10 * 1000 * 1000 - 49\n\t\tdf_memory = sys.getsizeof(df)\n\t\trows_in_part = math.ceil(df.shape[0] / math.ceil(df_memory / MAX_FILE_SIZE))\n\n\t\tpartnum = 0\n\t\trange_start = 0\n\t\tmax_data_part = rows_in_part\n\t\tfor chunk in range(0, math.ceil(df_memory / MAX_FILE_SIZE)):\n\t\t\tdf_part = df.iloc[range_start:max_data_part,:]\n\t\t\tif chunk == 0:\n\t\t\t\tdata_part64 = base64.b64encode(df_part.to_csv(index=False, quotechar='\"', quoting=csv.QUOTE_MINIMAL).encode('UTF-8')).decode()\n\t\t\telse:\n\t\t\t\tdata_part64 = base64.b64encode(df_part.to_csv(index=False, header=False, quotechar='\"',quoting=csv.QUOTE_MINIMAL).encode('UTF-8')).decode()\n\t\t\t\n\t\t\trange_start += rows_in_part\n\t\t\tmax_data_part += rows_in_part\n\t\t\tpartnum += 1\n\t\t\tif verbose == True:\n\t\t\t\tprint('\\rChunk '+str(chunk+1)+' of '+str(math.ceil(df_memory / MAX_FILE_SIZE))+' completed', end='', flush=True)\n\n\t\t\tpayload = {\n\t\t\t\t\"InsightsExternalDataId\" : json.loads(r1.text)['id'],\n\t\t\t\t\"PartNumber\" : str(partnum),\n\t\t\t\t\"DataFile\" : data_part64\n\t\t\t}\n\n\t\t\tr2 = requests.post(self.env_url+'/services/data/v48.0/sobjects/InsightsExternalDataPart', headers=self.header, data=json.dumps(payload))\n\t\ttry:\n\t\t\tjson.loads(r2.text)['success'] == True\n\t\texcept: \n\t\t\tprint('\\nERROR: Datapart Upload Failed')\n\t\t\tprint(r2.text)\n\t\t\tsys.exit(1)\n\t\tif verbose == True:\n\t\t\tprint('\\nDatapart Upload Complete...')\n\n\n\t\tpayload = {\n\t\t\t\t\t\"Action\" : \"Process\"\n\t\t\t\t}\n\n\t\tr3 = requests.patch(self.env_url+'/services/data/v48.0/sobjects/InsightsExternalData/'+json.loads(r1.text)['id'], headers=self.header, data=json.dumps(payload))\n\t\tif verbose == True:\n\t\t\tend = time.time()\n\t\t\tprint('Data Upload Process Started. Check Progress in Data Monitor.')\n\t\t\tprint('Job ID: '+str(json.loads(r1.text)['id']))\n\t\t\tprint('Completed in '+str(round(end-start,3))+'sec')\n\n\nif __name__ == '__main__':\t\n\tpass\n","sub_path":"SalesforceEinsteinAnalytics/SFDC_EA.py","file_name":"SFDC_EA.py","file_ext":"py","file_size_in_byte":19370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"351489072","text":"\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(az=dict(default=None, required=False), cidr=dict(default=None, required=True), state=dict(default='present', choices=['present', 'absent']), tags=dict(default={\n \n }, required=False, type='dict', aliases=['resource_tags']), vpc_id=dict(default=None, required=True)))\n module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)\n if (not HAS_BOTO):\n module.fail_json(msg='boto is required for this module')\n (region, ec2_url, aws_connect_params) = get_aws_connection_info(module)\n if region:\n try:\n connection = connect_to_aws(boto.vpc, region, **aws_connect_params)\n except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:\n module.fail_json(msg=str(e))\n else:\n module.fail_json(msg='region must be specified')\n vpc_id = module.params.get('vpc_id')\n tags = module.params.get('tags')\n cidr = module.params.get('cidr')\n az = module.params.get('az')\n state = module.params.get('state')\n try:\n if (state == 'present'):\n result = ensure_subnet_present(connection, vpc_id, cidr, az, tags, check_mode=module.check_mode)\n elif (state == 'absent'):\n result = ensure_subnet_absent(connection, vpc_id, cidr, check_mode=module.check_mode)\n except AnsibleVPCSubnetException as e:\n module.fail_json(msg=str(e))\n module.exit_json(**result)\n","sub_path":"Data Set/bug-fixing-1/274016101f9e4f34847a53c10c2857f838bb4bc7-
-fix.py","file_name":"274016101f9e4f34847a53c10c2857f838bb4bc7-
-fix.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"337920268","text":"import cv2 \nimport numpy as np\nimport base64\nfrom PIL import Image\nfrom io import BytesIO\nfrom app import imgMods\nfrom flask import make_response, jsonify\n\ndef process_request(req):\n ####### BGR RGB HACKY FIX --- NEEDS PROPPER FIX ####\n blueness_val = float(req['redness'])\n redness_val = float(req['blueness'])\n greenness_val = float(req['greenness'])\n brightness_val = float(req['brightness'])\n saturation_val = float(req['saturation'])\n blur_sharp_val = float(req['blur_sharp'])\n rotation_val = int(req['rotation'])\n image_base64_str = req['img']\n # Base64 str to nparr so can perform opencv operations:\n img = imgMods.b64_to_nparr(image_base64_str)\n \n mod_img = imgMods.bgr_intensity(img, blueness_val, greenness_val, redness_val)\n mod_img = imgMods.brightness_saturation_mod(mod_img, brightness_val, saturation_val)\n mod_img = imgMods.blur_sharp_mod(mod_img, blur_sharp_val)\n mod_img = np.rot90(mod_img, -rotation_val)\n\n mod_img_b64 = imgMods.np_img_to_b64(mod_img)\n del mod_img # for gc\n return make_response(jsonify(mod_img_b64), 200)\n\ndef upload_img_to_base64(img):\n '''Decode img from bytes to np.array. Then convert to base64str'''\n nparr = np.fromstring(img, np.uint8)\n img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n #bgr to rgb:\n img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)\n\n #convert np array to pil img, then pil img to base64\n pil_img = Image.fromarray(img_np)\n output_buffer = BytesIO()\n pil_img.save(output_buffer, format='JPEG')\n byte_data = output_buffer.getvalue()\n base_img = str(base64.b64encode(byte_data))\n return base_img[2:-1]\n\ndef b64_to_nparr(base64str):\n return np.array(Image.open(BytesIO(base64.b64decode(base64str))).convert('RGB'))\n\ndef arr_to_uint8_225_max(arr):\n arr[arr>255] = 255\n return arr.astype('uint8')\n\ndef bgr_intensity(img, blueness_val, greenness_val, redness_val):\n b, g, r = cv2.split(img)\n b = np.rint(b * blueness_val).astype('uint16')\n g = np.rint(g * greenness_val).astype('uint16')\n r = np.rint(r * redness_val).astype('uint16')\n b = arr_to_uint8_225_max(b)\n g = arr_to_uint8_225_max(g)\n r = arr_to_uint8_225_max(r)\n return cv2.merge((b,g,r))\n\ndef np_img_to_b64(img_np):\n pil_img = Image.fromarray(img_np)\n output_buffer = BytesIO()\n pil_img.save(output_buffer, format='JPEG')\n byte_data = output_buffer.getvalue()\n base_img = str(base64.b64encode(byte_data))\n return base_img[2:-1]\n\ndef brightness_saturation_mod(img, brightness_val, saturation_val):\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n h, s, v = cv2.split(hsv)\n s = np.rint(s * saturation_val).astype('uint16')\n v = np.rint(v * brightness_val).astype('uint16')\n s = arr_to_uint8_225_max(s)\n v = arr_to_uint8_225_max(v)\n hsv_mod = cv2.merge((h,s,v))\n return cv2.cvtColor(hsv_mod, cv2.COLOR_HSV2BGR) \n\ndef unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=0.0, threshold=0):\n \"\"\"Return a sharpened version of the image, using an unsharp mask.\n Full disclosure, this is stolen from:\n https://stackoverflow.com/questions/4993082/how-can-i-sharpen-an-image-in-opencv\"\"\"\n blurred = cv2.GaussianBlur(image, kernel_size, sigma)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))\n sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))\n sharpened = sharpened.round().astype(np.uint8)\n if threshold > 0:\n low_contrast_mask = np.absolute(image - blurred) < threshold\n np.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\ndef blur_sharp_mod(mod_img, blur_sharp_val):\n if blur_sharp_val > 0:\n mod_img = imgMods.unsharp_mask(mod_img, amount=blur_sharp_val)\n if blur_sharp_val < 0:\n for i in range(round(abs(blur_sharp_val))):\n kernel = (5,5)\n mod_img = cv2.GaussianBlur(mod_img, kernel, 0)\n return mod_img\n\n","sub_path":"app/app/imgMods.py","file_name":"imgMods.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"252937222","text":"import logging\nfrom time import sleep\n\nimport allure\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nfrom HomeWork.Selenium_Hw_19.Selenium_Hw_19_6_27.Selenium_HomeWork_19_6_27.basepage import BasePage\n\n\nclass CreateDepartmentPage(BasePage):\n _COMPANYNAME = (By.ID, 'party_name')\n _DEPARTMENTINPUTNAME = (By.XPATH, \"//*[text()='部门名称']/..//input[1]\")\n _DEPARTMENTSELECT = (By.XPATH, \"//*[text()='选择所属部门']\")\n _DEPARTMENTNAME = (By.XPATH, \"//*[@class='jstree-anchor']\")\n _COMMITBTN = (By.XPATH, \"//*[text()='确定']\")\n _CONTACT = (By.ID, 'menu_contacts')\n\n def create_department(self, departmentinputname):\n from HomeWork.Selenium_Hw_19.Selenium_Hw_19_6_27.Selenium_HomeWork_19_6_27.contact_page import ContactPage\n sleep(2)\n with allure.step('获取公司名'):\n logging.info('获取公司名')\n company_name = self.find(*self._COMPANYNAME).text\n with allure.step('输入部门名称'):\n logging.info('输入部门名称')\n self.find(*self._DEPARTMENTINPUTNAME).send_keys(departmentinputname)\n with allure.step('选择所属部门'):\n logging.info('选择所属部门')\n self.find_and_click(*self._DEPARTMENTSELECT)\n eles = self.finds(*self._DEPARTMENTNAME)\n print(eles)\n for value in eles:\n if value.text == company_name:\n value.click()\n with allure.step('点击确定'):\n logging.info('点击确定')\n self.find_and_click(*self._COMMITBTN)\n self.find_and_click(*self._CONTACT)\n return ContactPage(self.driver)","sub_path":"HomeWork/Selenium_Hw_19/Selenium_Hw_19_6_27/Selenium_HomeWork_19_6_27/create_department_page.py","file_name":"create_department_page.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"417345676","text":"import json\nimport re\n\n\nclass Grammar:\n def __init__(self):\n # set of nonterminals\n self.nonterminals = set()\n # set of terminals\n self.terminals = set()\n # set of Productions\n self.productions = set()\n # initial symbol\n self.initial_symbol = None\n # epsilon symbol\n self.epsilon = \"@\"\n\n def construct_from_fa(self, finite_automaton):\n # set initial symbol\n self.initial_symbol = \"S\"\n # set terminals\n [self.terminals.add(symbol) for symbol in finite_automaton.input_symbols]\n # map states to nonterminals\n finite_automaton.states.remove(finite_automaton.initial_state)\n state_nonterminal_map = {finite_automaton.initial_state: self.initial_symbol}\n for state in finite_automaton.states:\n state_nonterminal_map[state] = chr(ord('A') + len(state_nonterminal_map.keys()) - 1)\n\n # translate productions\n productions = []\n for (state1, input_symbol), state2 in finite_automaton.transition_function.items():\n nonterminal = state_nonterminal_map[state1]\n production = [p for p in productions if p.nonterminals == nonterminal]\n if not production:\n production = Production(nonterminal, [])\n else:\n production = production[0]\n for s in state2:\n production.results.append(str(input_symbol) + str(state_nonterminal_map[s]))\n # handle final states in rhs productions\n if s in finite_automaton.final_states:\n production.results.append(str(input_symbol))\n productions.append(production)\n [self.productions.add(p) for p in productions]\n\n # add nonterminals\n [self.nonterminals.add(n) for n in state_nonterminal_map.values()]\n\n def is_right_linear(self) -> bool:\n \"\"\"\n G = (N, 𝚺, P, S) is a right linear grammar if\n ∀p∊P: A->aB, A->b, where A,B ∊ N and a,b ∊ 𝚺\n • A is a single symbol (corresponding to a state) and is a non-terminal symbol\n • a corresponds to a lexical item found in the set of terminals\n • B is a single non-terminal symbol\n :return: True if right linear, False otherwise\n \"\"\"\n for production in self.productions:\n nonterminals_string = \"\".join(self.nonterminals)\n terminals_string = \"\".join(self.terminals) + self.epsilon\n # check left hand side\n if not re.match(\"^[\" + nonterminals_string + \"]$\", production.nonterminals):\n return False\n # check right hand side\n for result in production.results:\n if not re.match(\"^[\" + terminals_string + \"]+\" \"[\" + nonterminals_string + \"]?$\", result):\n return False\n return True\n\n def is_regular(self) -> bool:\n \"\"\"\n A Grammar G = (N, 𝚺, P, S) is regular if\n • G is right linear grammar\n • A→ ∉ P, with the exception that S → eps ∊ P,\n in which case S does not appear in the rhs (right hand side) of any other production\n :return: True if regular, False otherwise\n \"\"\"\n # check if is right linear grammar\n if not self.is_right_linear():\n return False\n # check epsilon productions\n for production in self.productions:\n if self.epsilon in production.results:\n if self.initial_symbol != production.nonterminals or self._is_in_rhs(production.nonterminals):\n return False\n\n return True\n\n def _is_in_rhs(self, nonterminal):\n \"\"\"\n Check if given nonterminal appears in any rhs of any production of the grammar\n :param nonterminal: String\n :return: True if found, False otherwise\n \"\"\"\n for production in self.productions:\n for result in production.results:\n if nonterminal in result:\n return True\n return False\n\n def read_file(self, filename) -> None:\n with open(filename) as json_data:\n data = json.load(json_data)\n self.nonterminals = set(data[\"nonterminals\"])\n self.terminals = set(data[\"terminals\"])\n for nonterminal in self.nonterminals:\n results = data[\"productions\"][nonterminal].split(\"|\")\n production = Production(nonterminal, results)\n self.productions.add(production)\n self.initial_symbol = data[\"initial_symbol\"]\n\n def __str__(self) -> str:\n result = \"Nonterminals: \"\n result += str(self.nonterminals)\n result += \"\\nTerminals: \"\n result += str(self.terminals)\n result += \"\\nProductions: \"\n for production in self.productions:\n result += str(production)\n result += \",\\n\"\n if len(self.productions) > 0:\n result = result[:-2]\n result += \"\\nInitial symbol: \"\n result += str(self.initial_symbol)\n return result\n\n\nclass Production:\n def __init__(self, nonterminals, results):\n # string with one or more nonterminals\n self.nonterminals = nonterminals\n # list of | delimited productions\n self.results = results\n\n def __eq__(self, o: object) -> bool:\n if isinstance(o, Production):\n return o.nonterminals == self.nonterminals\n return False\n\n def __hash__(self) -> int:\n return hash(self.nonterminals)\n\n def __str__(self) -> str:\n to_str = \"\" + str(self.nonterminals) + \" -> \"\n for elem in self.results:\n to_str += elem\n to_str += \" | \"\n return to_str[:-2]\n","sub_path":"LFTC/Scanner/domain/Grammar.py","file_name":"Grammar.py","file_ext":"py","file_size_in_byte":5758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"277322007","text":"from flask import Flask, request, jsonify, abort\n\napp = Flask(__name__)\n\n@app.errorhandler(404)\ndef not_found(error=None):\n message = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n resp = jsonify(message)\n resp.status_code = 404\n\n return resp\n\n@app.errorhandler(500)\ndef internal_error(error=None):\n message = {\n 'status': 500,\n 'message': 'ERROR in app: ' + request.url,\n }\n resp = jsonify(message)\n resp.status_code = 500\n\n return resp\n\n@app.route('/users/', methods = ['GET'])\ndef api_users(userid):\n users = {'1':'john', '2':'steve', '3':'bill'}\n if userid in users:\n return jsonify({userid:users[userid]})\n else:\n return not_found()\n\nif __name__=='__main__':\n app.run(debug=False, port=5000)\n \n ###END\n\n#curl -X GET http://127.0.0.1:5000/echo","sub_path":"programacion/python/Flask_microframework/API_REST/clusterproject/webminer/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"28466879","text":"#URLify, Write a method to replace all strings with '%20'. You may\n#assume that the string has sufficient space at the end to hold\n#the additional characters, and that you are given the true length\n\ndef URLify(text, length):\n urlString = ''\n for i in range(0, length):\n #test if space\n if (ord(text[i]) == 32):\n urlString += '%20'\n else:\n urlString += text[i]\n return urlString\n\ntext = \"Mr John Smith \"\nlength = 13\nurl = URLify(text, length)\nprint(url)\n","sub_path":"CrackingTheCodingInterview/1ArrayAndStrings/1.3URLify.py","file_name":"1.3URLify.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"346111229","text":"from collections import Counter\n\n\n# T=n,S=1\ndef main(s, k):\n res, n = 0, len(s)\n freq, left = Counter(), 0\n for right in range(n):\n freq[s[right]] += 1\n while len(freq) > k:\n freq[s[left]] -= 1\n if not freq[s[left]]:\n del freq[s[left]]\n left += 1\n if len(freq) == k:\n res = max(res, right - left + 1)\n return res\n\n\nfor s, k in [\n ('aaaaa', 3),\n ('aabacbebebe', 3),\n ('aabacbebebe', 3),\n ('ddacbbaccdedacebb', 3),\n ('loveleetcode', 4),\n ('aaabc', 2),\n ('eceba', 2),\n ('aa', 1),\n]:\n print(main(s, k))\n","sub_path":"hashmap/leetcode/sliding-window/longest-substring/longest-substring-with-k-distinct-characters.py","file_name":"longest-substring-with-k-distinct-characters.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"}

Examining the Scriptures Daily