diff --git "a/4943.jsonl" "b/4943.jsonl" new file mode 100644--- /dev/null +++ "b/4943.jsonl" @@ -0,0 +1,236 @@ +{"seq_id":"16877934519","text":"import sys\nfrom itertools import chain\n\nfrom deadtrees.constants import HOME_HTML, MODEL_CHECKPOINT_PATH, PACKAGE_DIR\nfrom deadtrees.version import __version__\nfrom setuptools import find_packages, setup\n\nif not MODEL_CHECKPOINT_PATH.exists():\n # develop will be in argv if we do e.g. `pip install -e .`\n if \"develop\" not in sys.argv:\n # logger.error(\"can't build a non-development package with no model\")\n # raise FileNotFoundError(MODEL_CHECKPOINT_PATH)\n pass\n\n# extra package dependencies\nEXTRAS = {\n \"train\": [\"wandb\", \"seaborn\"],\n \"preprocess\": [\n \"gdal\",\n \"pygeos\",\n \"bottleneck\",\n \"dask\",\n \"rioxarray>=0.4\",\n \"xarray\",\n ],\n}\nEXTRAS[\"all\"] = [i for i in chain.from_iterable(EXTRAS.values())]\n\n\nsetup(\n name=\"deadtrees\",\n version=__version__,\n packages=find_packages(),\n install_requires=[\n \"albumentations\",\n \"dvc[s3]\",\n \"python-dotenv\",\n \"hydra-core>=1.1.0\",\n \"hydra-colorlog>=1.1.0\",\n \"pydantic\",\n \"torch>=1.10.0\",\n \"torchvision>=0.12.0\",\n \"pytorch-lightning>=1.5\",\n \"rich\",\n \"tqdm\",\n \"webdataset==0.1.62\",\n \"segmentation_models_pytorch>=0.2.1\",\n \"efficientnet-pytorch>=0.7.1\",\n ],\n # install in editable mode: pip install -e \".[train,preprocess]\" or\n # pip install -e \".[all]\"\n extras_require=EXTRAS,\n entry_points={\n \"demo\": [\n \"deadtrees=deadtrees.__main__:main\",\n ],\n },\n package_data={\n \"deadtrees\": [\n # str(MODEL_CHECKPOINT_PATH.relative_to(PACKAGE_DIR) / \"*.torch\"),\n # str(HOME_HTML.relative_to(PACKAGE_DIR)),\n ]\n },\n)\n","repo_name":"cwerner/deadtrees","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"4725985955","text":"import os\nimport glob\n\n# Lấy đường dẫn thư mục hiện tại\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\n# Duyệt qua tất cả các thư mục con trong thư mục hiện tại\nfor dir_name in os.listdir(current_dir):\n sub_dir = os.path.join(current_dir, dir_name)\n \n # Kiểm tra nếu là thư mục\n if os.path.isdir(sub_dir):\n # Tìm tất cả các tệp ảnh trong thư mục (chỉ tìm kiểu .png và .jpg)\n images = glob.glob(sub_dir + \"/*.png\") + glob.glob(sub_dir + \"/*.jpg\")\n \n # Nếu số lượng ảnh nhỏ hơn 2\n if len(images) < 2:\n # Đổi tên thư mục, thêm chuỗi \"XxX \" vào cuối\n new_dir_name = sub_dir + \"XxX \"\n os.rename(sub_dir, new_dir_name)\n","repo_name":"hannaZyunHND/auto-read-pp-to-image","sub_path":"check-file.py","file_name":"check-file.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14400143242","text":"\nfrom setuptools import setup, find_packages\n\nMAJOR = \"0\"\nMINOR = \"1\"\nPATCH = \"2\"\n\n_VERSION_TAG = \"{MAJOR}.{MINOR}.{PATCH}\".format(MAJOR=MAJOR, MINOR=MINOR, PATCH=PATCH)\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\ndef get_version():\n # import subprocess\n # commit_hash = str(subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE).stdout)[2:-3]\n return '{VERSION_TAG}'.format(VERSION_TAG=_VERSION_TAG)\n\n\nsetup(\n name=\"edf2parquet\",\n version=get_version(),\n author=\"Narayan Schütz\",\n author_email=\"narayan.schuetz@gmail.com\",\n description=\"A Python based utility package to convert EDF/EDF+ files to Apache Parquet file format.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/NarayanSchuetz/edf2parquet\",\n packages=find_packages(),\n install_requires=[\n 'pytest',\n 'numpy',\n 'pandas>=2.0.0',\n 'pyarrow',\n 'pyedflib>=0.1.32',\n ],\n setup_requires=[\n 'pytest-runner',\n ],\n tests_require=[\n 'pytest-runner',\n 'pytest',\n 'pytest-mock',\n 'requests'\n ],\n zip_safe=False,\n python_requires='>=3.8'\n)\n","repo_name":"NarayanSchuetz/edf2parquet","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70736752359","text":"\"\"\"\n[MEDIUM]\nThis problem was asked by Microsoft\n\nGiven a dictionary of words and a string made up of those words (no spaces),\nreturn the original sentence in a list. If there is more than one possible\nreconstruction, return any of them. If there is no possible reconstruction,\nthen return null.\n\nFor example, given the set of words 'quick', 'brown', 'the', 'fox', and the\nstring \"thequickbrownfox\", you should return ['the', 'quick', 'brown', 'fox'].\n\nGiven the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the\nstring \"bedbathandbeyond\", return either ['bed', 'bath', 'and', 'beyond] or\n['bedbath', 'and', 'beyond'].\n\"\"\"\nfrom typing import List\n\n\n# Problem with this is python's recursion depth limit (max 990), so for inputs\n# bigger than 990, it will fail.\n# Recursion level limit can be overridden by\n# import sys\n# sys.setrecursionlimit(new_limit)\n# Which is not recommended :)\ndef reconstruct_sentence(words: List[str], sentence: str) -> List[str] or None:\n reconstruct = []\n reconstruct_sentence_helper(words, sentence, reconstruct)\n if ''.join(reconstruct) == sentence:\n return reconstruct\n\n\ndef reconstruct_sentence_helper(words: List[str], sentence: str,\n reconstruct: []) -> List[str] or None:\n for i, word in enumerate(words):\n if sentence.startswith(word):\n reconstruct.append(word)\n reconstruct_sentence_helper(words, sentence[len(word):],\n reconstruct)\n break\n\n\n# LeetCode solutions:\n# https://leetcode.com/problems/word-break/discuss/43788/4-lines-in-Python\ndef word_break(words: List[str], sentence: str) -> bool:\n ok = [True]\n for i in range(1, len(sentence) + 1):\n outcomes = []\n for j in range(i):\n ok_segment = ok[j]\n sentence_segment = sentence[j:i]\n outcomes.append(ok_segment and sentence_segment in words)\n ok += any(outcomes),\n return ok[-1]\n\n\ndef word_break_2(words: List[str], sentence: str) -> bool:\n ok = [True]\n max_len = max(map(len, words + ['']))\n words = set(words)\n for i in range(1, len(sentence) + 1):\n outcomes = []\n for j in range(max(0, i - max_len), i):\n outcomes.append(ok[j] and sentence[j:i] in words)\n ok += any(outcomes),\n return ok[-1]\n\n\ndef test(actual_result: List[str] or None, expected_result: List[str] or None):\n error_message = f'{actual_result} != {expected_result}'\n try:\n if isinstance(expected_result, list) and isinstance(expected_result[0],\n list):\n error_message = f'{actual_result} not in {expected_result}'\n assert actual_result in expected_result\n else:\n assert actual_result == expected_result\n except AssertionError:\n raise Exception(error_message)\n\n\nif __name__ == '__main__':\n # Tests that the sentence can be constructed\n words = ['quick', 'brown', 'the', 'fox']\n sentence = 'thequickbrownfox'\n test(reconstruct_sentence(words, sentence),\n ['the', 'quick', 'brown', 'fox'])\n\n # Tests that the sentence can be constructed with extra words\n words = ['bed', 'bath', 'bedbath', 'and', 'beyond']\n sentence = 'bedbathandbeyond'\n test(reconstruct_sentence(words, sentence),\n [['bed', 'bath', 'and', 'beyond'], ['bedbath', 'and', 'beyond']])\n\n # Tests that the sentence can not be constructed\n words = ['quick', 'brown', 'the', 'fox']\n sentence = 'shouldreturnnone'\n test(reconstruct_sentence(words, sentence), None)\n\n # Tests that the sentence can not be constructed when part of the\n # sentence is not in the words\n words = ['should', 'return']\n sentence = 'shouldreturnnone'\n test(reconstruct_sentence(words, sentence), None)\n\n assert not word_break(words, sentence)\n assert not word_break_2(words, sentence)\n words = ['quick', 'brown', 'the', 'fox']\n sentence = 'thequickbrownfox'\n assert word_break(words, sentence)\n assert word_break_2(words, sentence)\n\n from timeit import timeit\n\n print(\"SHORT INPUT\")\n # 0.04855309998674784 s\n print(timeit(lambda: reconstruct_sentence(words, sentence), number=10000))\n # 0.3338475000055041 s\n print(timeit(lambda: word_break(words, sentence), number=10000))\n # 0.1519888000038918 s\n print(timeit(lambda: word_break_2(words, sentence), number=10000))\n\n from random import choice\n from string import ascii_lowercase\n\n sentence = ''.join(choice(ascii_lowercase) for i in range(990))\n words = [char for char in sentence]\n print(\"LONG INPUT\")\n # 2.8604491999867605 s\n print(timeit(lambda: reconstruct_sentence(words, sentence), number=1000))\n # 3829.796891799997 s\n print(timeit(lambda: word_break(words, sentence), number=1000))\n # 0.6658393000107026 s\n print(timeit(lambda: word_break_2(words, sentence), number=1000))\n","repo_name":"jpayan/excercises","sub_path":"daily/817_reconstruct_sentence.py","file_name":"817_reconstruct_sentence.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"34445044084","text":"import hashlib\n# import uuid\nfrom ..models import *\nimport random\nimport string\n\ndef sendrandomnumber():\n return random.randrange(50)\n\ndef randomString(stringLength):\n\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ndef generateqr():\n number = sendrandomnumber()\n mot = randomString(number)\n m = hashlib.sha224('{}'.format(mot).encode()).hexdigest()\n\n try:\n new_qr_code = Qrcode.objects.filter(jours=date.today(),status=True)[:1].get()\n new_qr_code.titre_slug= m\n new_qr_code.save()\n except:\n pass\n return m\n\n \n \n\n\n\n\n\n\n\n","repo_name":"WiiNTERNITY/qrCodePython","sub_path":"nanpresance/nanapp/autotast/generateqrcode.py","file_name":"generateqrcode.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18218323860","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 ('catalogue', '0006_auto_20151231_1404'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='product',\n name='visits',\n field=models.PositiveIntegerField(default=0, verbose_name='Number of visit', help_text='Number of times this product has been visited'),\n ),\n ]\n","repo_name":"massawho/dancart-cms","sub_path":"apps/catalogue/migrations/0007_product_visits.py","file_name":"0007_product_visits.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"74748282601","text":"#!/usr/bin/env python\n# license removed for brevity\nimport rospy\nfrom geometry_msgs.msg import TwistStamped\nfrom random import random\nfrom random import seed\n\ndef talker():\n pub = rospy.Publisher(\"vicon/vicon/anafi_1\", TwistStamped, queue_size=10)\n rospy.init_node('anafi_1', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n i = .05\n while not rospy.is_shutdown():\n data = TwistStamped()\n data.twist.linear.x = i\n data.twist.linear.y = i\n data.twist.linear.z = i\n rospy.loginfo(data)\n pub.publish(data)\n rate.sleep()\n\n i+= .025\n\nif __name__ == '__main__':\n seed(1)\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"tkschuler/anafi-swarm","sub_path":"vicontalker.py","file_name":"vicontalker.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13929576234","text":"'''\n在 Subsets 迭代版本的基础上思考。在迭代重复元素的时候会生成重复的结果,那么在迭代重复元素时要特殊处理一下。\n就拿[1,2,2]来说,在迭代完1之后结果集为[[], [1]],迭代第一个2后,[[], [1], [2], [1,2]],接下来就要迭代重复的元素2了,\n此时如果遍历在迭代第一个2之前就存在的结果集元素([[], [1]])时,就会产生重复,\n我们只能在上一轮迭代产生的新的结果中继续添加。\n所以要一个额外的变量来表示在结果集中的哪个位置开始遍历。\n'''\nclass Solution(object):\n def subsetsWithDup(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = [[]]\n nums.sort()\n temp_size = 0\n for i in range(len(nums)):\n start = temp_size if i >= 1 and nums[i] == nums[i - 1] else 0\n temp_size = len(result)\n for j in range(start, temp_size):\n result.append(result[j] + [nums[i]])\n return result\n","repo_name":"hanlaoshi/leetcode-DailyProblem","sub_path":"090. Subsets II/090. Subsets II.py","file_name":"090. Subsets II.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"zh","doc_type":"code","stars":30,"dataset":"github-code","pt":"18"} +{"seq_id":"20703682110","text":"class MyHashMap:\n\n def __init__(self):\n self.x=[[]] *2957\n self.size=2957\n\n def put(self, key: int, value: int) -> None:\n j=self.hash(key)\n for i in self.x[j]:\n if key==i[0]:\n i[1]=value \n return\n self.x[j].append([key,value])\n \n\n def get(self, key: int) -> int:\n j=self.hash(key)\n for i in self.x[j]:\n if key==i[0]:\n return i[1]\n return -1\n \n\n def remove(self, key: int) -> None:\n k=self.hash(key)\n for j,i in enumerate(self.x[k]):\n if key==i[0]:\n self.x[k].pop(j) \n return\n return\n \n def hash(self,key)->int:\n return key%2957\n \n \n\n\n# Your MyHashMap object will be instantiated and called as such:\n# obj = MyHashMap()\n# obj.put(key,value)\n# param_2 = obj.get(key)\n# obj.remove(key)\n","repo_name":"beimnet777/A2SV","sub_path":"Design HashMap.py","file_name":"Design HashMap.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"12024986222","text":"\"\"\"\nNeed to use xlrd and xlwt to read and write Microsoft Excel Files\nAnd xlutils for some utils\n\n\n\"\"\"\n\nimport xlrd, xlwt\nimport xlutils \nimport csv\n\n#opens the workbook\nprint(\"Opening Workbook\")\nwb = xlrd.open_workbook(\"ag_hr_1998.xls\")\n\n#opens the worksheet: can do this by index or name \nprint(\"Opening Worksheets\")\nicahr = wb.sheet_by_name('ICA HR') # might need to escape space\nawhr = wb.sheet_by_name('AW HR')\netawhr = wb.sheet_by_name('ETAW HR')\n\n#data cell's values are accessible by sheet.cell(row,column).value\\\n#should print out the first year in both (1998)\n#print(icahr.cell(1,0).value) \n#print(etawhr.cell(1,0).value) \n#print(icahr.cell(1,5).value)\n#for NC in range (5,24):\n#\tprint(icahr.cell(1,NC).value)\n\nICA_row = [] #make a list for ica table\nAW_row = []\nETAW_row = []\n\nfor row in range (1,11):\n\tfor col in range (5,25):\t\t\t\t#create list for row for ICA\n\t\t#print(icahr.cell(row,col).value), #this prevents columns from printing new lines\n\t\t#print(\" \"),\n\t\tICA_row.append(icahr.cell(row,col).value)\n\t#print(\"\") #this prints a new line to seperate the rows\n\tfor col in range (3,23):\n\t\tAW_row.append(awhr.cell(row,col).value)\n\tfor col in range (3,23):\n\t\tETAW_row.append(etawhr.cell(row,col).value)\n\tprint(ICA_row)\n\tprint(AW_row)\n\tprint(ETAW_row)\n\tICA_row[:] = []\n\tAW_row[:] = []\n\tETAW_row[:] = []\n\tprint(\"\")\n\t\n#we can now iterate through the list and make each row a list \n\n\n#then we make a dot product between the two lists\n\n\n\n\n\n\"\"\"\nReferences: \nhttp://www.sitepoint.com/using-python-parse-spreadsheet-data/ \nhttp://stackoverflow.com/questions/4093989/dot-product-in-python\n\n\"\"\"","repo_name":"ucd-cws/CropEconScript","sub_path":"cropecon.py","file_name":"cropecon.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24931415229","text":"from django.core.management.base import BaseCommand, CommandError\nfrom principal.models import Usuario,Pelicula,Puntuacion,Categoria,CategoriaPelicula,Ocupacion,Puntuacion\nimport shelve\n\nclass Command(BaseCommand):\n \n help = 'Persistent dictionaries from DB'\n \n def handle(self, *args, **options):\n dbDict = {\"Usuarios\": Usuario.objects.all()}\n usuarios = {}\n for usuario in Usuario.objects.all():\n puntuaciones = {}\n for puntuacion in Puntuacion.objects.filter(idUsuario = usuario.idUsuario):\n# print(puntuacion.idPelicula)\n puntuaciones[Pelicula.objects.get(idPelicula = puntuacion.idPelicula.idPelicula).idPelicula] = puntuacion.puntuacion\n usuarios[usuario.idUsuario] = puntuaciones\n\n s = shelve.open('dicts.db')\n try:\n s['usuariosPuntuaciones'] = usuarios\n finally:\n s.close()\n\n# s = shelve.open('test_shelf.db')\n# try:\n# existing = s['key1']\n# finally:\n# s.close()\n# \n# print(existing)","repo_name":"que-si-que-yo-acabo-este-ano/AII","sub_path":"Django_Form/principal/management/commands/createDictionary.py","file_name":"createDictionary.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38707779559","text":"\"\"\"\nЗадание 4.\nРеализуйте скрипт \"Кэширование веб-страниц\"\n\nФункция должна принимать url-адрес и проверять\nесть ли в кэше соответствующая страница или нет\nесть ли в кэше соответствующая страница или нет\n\nПример кэша: {'url-адрес': 'хеш url-а'; 'url-адрес': 'хеш url-а'; ...}\n\nЕсли страница в кэше есть, просто вернуть значение хеша, например, 'хеш url-а'\nЕсли страницы в кэше нет, то вычислить хеш и записать в кэш\n\nПодсказка: задачу решите обязательно с применением 'соленого' хеширования\nи одного из алгоритмов, например, sha512\nМожете усложнить задачу, реализовав ее через ООП\n\"\"\"\nfrom hashlib import md5\n\ncache = {'https://gb.ru/': 'a783210eb908ec6d9ae5522cc933138998defd6ee70dfb1dea416cecdf391f58',\n 'https://www.python.org/': '6bd7e4a1b937bdf1c5f65d1312a4ee9f98defd6ee70dfb1dea416cecdf391f58',\n 'https://github.com/': '008ec4453ff31513f43893cba7aa31c898defd6ee70dfb1dea416cecdf391f58'}\n\nsalt = md5(b'site').hexdigest()\n\n\ndef add_url(url):\n if url in cache:\n print(cache[url])\n else:\n hashh = md5(url.encode('UTF-8')).hexdigest() + salt\n cache[url] = hashh\n print('Записаны новые данные')\n print(f'URL: {url}\\nHash: {hashh}')\n\n\nif __name__ == '__main__':\n add_url(input('Введите URL: '))\n","repo_name":"pmtkachev/GB_algorithms_2022","sub_path":"Урок 3. Практическое задание/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21564581813","text":"from flask import request\nfrom flask_restful import Resource\nfrom prometheus_flask_exporter import RESTfulPrometheusMetrics\n\nfrom lib.models import db\nfrom lib.models.key_value_pair import KeyValuePair\n\n\nmetrics = RESTfulPrometheusMetrics.for_app_factory()\n\n\nclass GetKeyValuePair(Resource):\n def get(self, key):\n row = (KeyValuePair.query.filter(KeyValuePair.key == key).first())\n if row:\n value = row.value\n return {\"value\": value}\n else:\n return {\"message\": \"Key value pair does not exist\"}\n\n\nclass SetKeyValuePair(Resource):\n def post(self):\n key = request.form['key']\n value = request.form['value']\n row = (KeyValuePair.query.filter(KeyValuePair.key == key).first())\n if row:\n row.value = value\n else:\n row = KeyValuePair(key=key, value=value)\n db.db_session.add(row)\n db.db_session.commit()\n return {key: value}\n\n\nclass SearchKeyValuePair(Resource):\n def get(self):\n prefix = request.args.get('prefix')\n suffix = request.args.get('suffix')\n if prefix:\n rows = KeyValuePair.query.filter(KeyValuePair.key.startswith(prefix)).all()\n elif suffix:\n rows = KeyValuePair.query.filter(KeyValuePair.key.endswith(suffix)).all()\n list_of_keys = [row.key for row in rows]\n return {'keys': list_of_keys}\n\n","repo_name":"sushantkumr/KeyValueStore","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"6817127561","text":"from django.urls import path\nfrom . import views\nfrom .views import (\n ToDoCreateView,\n ToDoListView,\n ToDoDeleteView\n)\n\n\nurlpatterns = [\n path('', ToDoListView.as_view(), name='website-home'),\n path('about/', views.about, name='website-about'),\n path('todo/create/', ToDoCreateView.as_view(), name='todo-create'),\n path('todo/delete/', ToDoDeleteView.as_view(), name='todo-delete')\n]\n","repo_name":"marcinlukanus/DjangoToDo","sub_path":"djangoToDoProject/website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20094477985","text":"import traceback\nfrom datetime import datetime\n\nimport typer\nfrom rich import print as rprint\nfrom rich.console import Console\nfrom rich.table import Table\n\nfrom track.app_constants import DATE_FORMAT\n\n\ndef get_conn_string(db_path: str):\n \"\"\"Generate a connection string for the database\"\"\"\n return \"sqlite:///\" + db_path\n\n\ndef parse_date(date: str):\n \"\"\"Parse the given string to a date object\"\"\"\n try:\n return datetime.strptime(date, DATE_FORMAT).date()\n except ValueError:\n rprint(\n \"[red]Date is invalid or was not specified in the expected format[/red][yellow] YYYY-MM-DD.[/yellow]\"\n )\n raise typer.Exit(1)\n except Exception:\n rprint(\n f\"[red]Something went wrong while parsing the date: {date}[/red]: {traceback.print_exc()}\" # traceback.print_exc will print the stack trace of the last exception occurred.\n )\n raise typer.Exit(1)\n\n\ndef validate_dates(start_date, end_date):\n \"\"\"Validate the start and the end date.\"\"\"\n if end_date < start_date:\n typer.secho(\n f\"Start date {start_date} is greater than the end date {end_date}.\",\n fg=typer.colors.BRIGHT_RED,\n )\n raise typer.Exit(1)\n return True\n\n\ndef print_applications(applications):\n \"\"\"Use rich to print applications in table format\"\"\"\n\n console = Console()\n\n table = Table(title=\"Job Applications\", style=\"yellow\")\n table.add_column(\"ID\", style=\"cyan\")\n table.add_column(\"Company\", style=\"magenta\")\n table.add_column(\"Position\")\n table.add_column(\"Status\")\n table.add_column(\"Applied at\")\n table.add_column(\"Updated at\")\n\n for application in applications:\n table.add_row(\n str(application.id), # int can't be rendered in rich\n application.company,\n application.position,\n application.status,\n str(application.applied_at), # date can't be rendered in rich\n str(application.updated_at),\n )\n\n console.print(table)\n","repo_name":"itsadityagupta/track-job-applications","sub_path":"track/app_functions.py","file_name":"app_functions.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"6936619956","text":"# Imports ---------------\n\nfrom guizero import App, Text\n\n\n# Functions -------------\n\ndef flash_text():\n if title.visible:\n title.hide()\n else:\n title.show()\n\n\n# App -------------------\n\napp = App(\"its all gone wrong\", bg=\"dark green\")\n\ntitle = Text(app, text=\"Hard to read\", size=\"14\", font=\"Comic Sans\", color=\"green\")\n\napp.repeat(1000, flash_text)\n\napp.display()\n","repo_name":"themagpimag/createguis","sub_path":"Chapter 5 World's Worst GUI/worst2.py","file_name":"worst2.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"18"} +{"seq_id":"40226795661","text":"# encoding: utf-8\n# test_chunker.py\n\nimport pandas as pd\nfrom pandas import Series\n\n\nchunker = pd.read_csv('ch06/ex6.csv', chunksize=1000)\n\ntot = Series([])\n\nfor piece in chunker:\n\ttot = tot.add(piece['key'].value_counts(), fill_value=0)\n\ntot = tot.order(ascending=False)\n","repo_name":"lee-seul/development_practice","sub_path":"ipython/ipy/test_chunker.py","file_name":"test_chunker.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9981293765","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\n\r\nclass HuffNode:\r\n def __init__(self, char, freq):\r\n self.char = char\r\n self.freq = freq\r\n self.left = None\r\n self.right = None\r\n \r\n def is_leaf(self):\r\n return not(self.left or self.right)\r\n \r\ndef create_frequencies(data):\r\n '''\r\n Function to create frequencies for character data\r\n '''\r\n frequency_dict = {}\r\n for char in data:\r\n if char not in frequency_dict.keys():\r\n frequency_dict[char] = 1\r\n else:\r\n frequency_dict[char] += 1\r\n frequencies = []\r\n for char, freq in frequency_dict.items():\r\n frequencies.append(HuffNode(char, freq))\r\n \r\n return frequencies\r\n\r\ndef sort_frequencies(frequencies):\r\n sorted_freq = sorted(frequencies, key=lambda x: x.freq, reverse=True)\r\n return sorted_freq\r\n\r\ndef build_huff_tree(text):\r\n frequencies = create_frequencies(text)\r\n frequencies = sort_frequencies(frequencies)\r\n \r\n while len(frequencies) > 1:\r\n left = frequencies.pop()\r\n right = frequencies.pop()\r\n \r\n freq_sum = left.freq + right.freq\r\n \r\n parent = HuffNode(None, freq_sum)\r\n parent.left = left\r\n parent.right = right\r\n \r\n frequencies.append(parent)\r\n \r\n frequencies = sort_frequencies(frequencies)\r\n \r\n return frequencies[0]\r\n\r\ndef trim_huff_tree(tree, huff_code):\r\n huff_dict = {}\r\n if not tree:\r\n return huff_dict\r\n if tree.is_leaf():\r\n huff_dict[tree.char] = huff_code\r\n huff_dict.update(trim_huff_tree(tree.left, huff_code + '0'))\r\n huff_dict.update(trim_huff_tree(tree.right, huff_code + '1'))\r\n return huff_dict\r\n\r\ndef decode_next(data, index, tree):\r\n assert(tree)\r\n assert(len(data) > 0)\r\n if tree.is_leaf():\r\n return tree.char, index\r\n if data[index] == '0':\r\n return decode_next(data, index + 1, tree.left)\r\n else:\r\n return decode_next(data, index + 1, tree.right)\r\n \r\n\r\ndef huffman_encoding(text):\r\n assert len(text) > 0, \"text should not be empty\"\r\n huff_tree = build_huff_tree( text )\r\n huff_map = trim_huff_tree( huff_tree, '' )\r\n data = ''\r\n for char in text:\r\n data += huff_map[char]\r\n return data, huff_tree\r\n\r\n\r\n\r\ndef huffman_decoding(data, tree):\r\n assert data, 'Encoding is not available'\r\n assert(tree)\r\n text, next_index = decode_next( data, 0, tree )\r\n while next_index < len(data):\r\n next_char, next_index = decode_next( data, next_index, tree )\r\n text += next_char\r\n return text\r\n\r\ndef test_encoding(text):\r\n print (\"Original Text:\\t\\t {}\".format( text ))\r\n print (\"Size:\\t\\t\\t {}\".format( sys.getsizeof(text) ))\r\n \r\n encoded_data, tree = huffman_encoding(text)\r\n print (\"Huffman Encoding:\\t {}\".format(encoded_data))\r\n print (\"Size:\\t\\t\\t {}\".format( sys.getsizeof( int(encoded_data, base=2) ) )) if encoded_data else 0\r\n \r\n \r\n decoded_data = huffman_decoding(encoded_data, tree)\r\n print (\"Decoded Text:\\t\\t {}\".format(decoded_data))\r\n print (\"Size:\\t\\t\\t {}\".format( sys.getsizeof(decoded_data) ))\r\n \r\n return decoded_data == text\r\n\r\n\r\n#Test Cases\r\n\r\nprint( test_encoding(\"The bird is the word\") )\r\n#Original Text: The bird is the word\r\n#Size: 69\r\n#Huffman Encoding: 1110100100010111000110101101100111111110111100010001011001110000101101\r\n#Size: 36\r\n#Decoded Text: The bird is the word\r\n#Size: 69\r\n#True\r\n\r\nprint( test_encoding(\"Adam\") )\r\n#Original Text: Adam\r\n#Size: 53\r\n#Huffman Encoding: 01001110\r\n#Size: 28\r\n#Decoded Text: Adam\r\n#Size: 53\r\n#True\r\n\r\nprint( test_encoding(\"The quick brown fox jumps over the lazy dog.\") )\r\n#Original Text: The quick brown fox jumps over the lazy dog\r\n#Size: 93\r\n#Huffman Encoding: 100101000101011110011110111100110000010000011100011101100010001001101111011000010111111101110101110100101000010111110010101010101011011111010110001010111110100110111110110110001111110000001110011110010\r\n#Size: 52\r\n#Decoded Text: The quick brown fox jumps over the lazy dog\r\n#Size: 93\r\n#True\r\n\r\nprint( test_encoding(\"ABBBBABBABABBBAABABABAABABA\") )\r\n#Original Text: ABBBBABBABABBBAABABABAABABA\r\n#Size: 76\r\n#Huffman Encoding: 011110110101110010101001010\r\n#Size: 28\r\n#Decoded Text: ABBBBABBABABBBAABABABAABABA\r\n#Size: 76\r\n#True\r\n\r\nprint( test_encoding(\"ABA\"))\r\n#Original Text: ABA\r\n#Size: 52\r\n#Huffman Encoding: 101\r\n#Size: 28\r\n#Decoded Text: ABA\r\n#Size: 52\r\n#True\r\n\r\n#print( test_encoding(\"AAA\"))\r\n#The string contains same characters which means the entropy in the data is zero and hence, it defeats the purpose of encoding.\r\n#AssertionError: Encoding is not available. \r\n\r\n#print( test_encoding(\"\") )\r\n# AssertionError text should not be empty","repo_name":"akarr24/Udacity-Data-Strucutres-and-Algorithms-","sub_path":"Project 2/problem_3.py","file_name":"problem_3.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29093342957","text":"import subprocess\nfrom bs4 import BeautifulSoup as Soup\nimport os\nimport pandas as pd\nfrom navigome_independent_tests import bonferroni_cutoff\nfrom sys import argv\n\nworkdir = str(argv[1])\n\nf_reference = workdir + \"/input/gwas_reference_toadd\"\nf_reference_complete = workdir + \"/input/gwas_reference\"\ncutoff = bonferroni_cutoff(workdir + '/input/correlation_matrix')\ncsvfile = pd.read_csv(f_reference, keep_default_na=False)\ncodes = csvfile['code']\n\noutdir = workdir + '/output/correlations'\nif not os.path.exists(outdir):\n os.makedirs(outdir)\n\n# new headers and nav bars for html files\nnewheader = '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n\nnavbar1 = ('')\nnavbar = navbar1\n\nadddiv = (\n '
' +\n '

Filter genetic correlations by selecting different options (significance, direction, category). ' +\n 'The number of independent traits was estimated by ' +\n 'computing the number of principal components accounting for 99.5% ' +\n 'of variance explained in the trait/trait genetic correlation matrix, ' +\n 'and used to estimate the Bonferroni significance threshold.' +\n '

' +\n '
')\n\nfor i in codes:\n # merge reference data and correlations\n cmd = [\n 'python',\n workdir +\n '/scripts/' +\n 'navigome_vis4_corr.py',\n workdir +\n '/input/correlation_data/' +\n str(i) +\n '.correlations',\n str(i),\n \" %.2e\" %\n (cutoff),\n f_reference_complete,\n workdir +\n '/output/correlations/' +\n str(i) +\n '.correlations']\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n (output, err) = process.communicate()\n p_status = process.wait()\n print(str(i))\n with open(workdir + '/output/correlations/' + str(i) + '.correlations' + '.html', 'r') as f:\n head = newheader + '' + \\\n \"Genetic correlations: \" + str(i) + ''\n html = f.read()\n soup = Soup(html, features=\"html.parser\")\n soup.head.contents = Soup(head,\n features=\"html.parser\")\n # soup.body.insert_before(Soup(navbar,features=\"html.parser\"))\n soup.div.insert_after(Soup(adddiv, features=\"html.parser\"))\n soup = str(soup).replace(\n 'embedOpt = {\"mode\": \"vega-lite\"};',\n 'embedOpt = {\"mode\": \"vega-lite\", \"loader\": vega.loader({target: \\'_blank\\'})};')\n with open(workdir + '/output/correlations/' + str(i) + '.correlations' + '.html', 'w') as fout:\n fout.write(str(soup))\n","repo_name":"hagax8/navigome","sub_path":"scripts/runcorrelations_processes.py","file_name":"runcorrelations_processes.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41610701225","text":"import requests\n\nparams = (\n ('client_id', '5fe01282e94241328a84e7c5cc169164'),\n ('redirect_uri', 'http://example.com/callback'),\n ('scope', 'user-read-private user-read-email'),\n ('response_type', 'token'),\n)\n\nresponse = requests.get('https://accounts.spotify.com/authorize', params=params)\nprint(response.text)","repo_name":"GabrielElkadiki/cuHacking2019","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19421151980","text":"from classes.sensor import Sensor\nimport os.path\nimport time\nimport numpy as np\nlogging_port = 30303\nnode1=Sensor(\"localhost\", 9029,\"sensor_dust_cows_room\", \"localhost\", 9002, \"device_2\", logging_port)\nnode2 = Sensor(\"localhost\", 9030,\"sensor_dust_field1\", \"localhost\", 9003, \"device_3\", logging_port)\nnode3 = Sensor(\"localhost\", 9031,\"sensor_dust_main_gate\", \"localhost\", 9001, \"device_1\", logging_port)\nnode4 = Sensor(\"localhost\", 9032,\"sensor_dust_construction_area\", \"localhost\", 9005, \"device_5\", logging_port)\nnode5 = Sensor(\"localhost\", 9033,\"sensor_dust_vineyard\", \"localhost\", 9004, \"device_4\", logging_port)\n\ntry:\n # the metrics are in micrograms/m^3\n node1_item = np.random.uniform(0,30)\n node2_item = np.random.uniform(0,15)\n node3_item = np.random.uniform(0,60)\n node4_item = np.random.uniform(0,100)\n node5_item = np.random.uniform(0,25)\n information1=node1.publish(\"farm1/dust/cows_room\", node1_item)\n information2 = node2.publish(\"farm1/dust/field1\", node2_item)\n information3 = node3.publish(\"farm1/dust/main_gate\", node3_item)\n information4 = node4.publish(\"farm1/dust/construction_area\", node4_item)\n information5 = node5.publish(\"farm1/dust/vineyard\", node5_item)\nexcept KeyboardInterrupt:\n print(\"Sensor finished publishing data\")\n\n\n","repo_name":"raosp123/Scalable-NDN","sub_path":"dust_sensor_simulation.py","file_name":"dust_sensor_simulation.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11726576622","text":"\nimport torch\nimport torch.nn as nn\n\nimport torchvision.transforms as transforms\n\nimport custom_models \nimport load_cifar10 \n\n# Loading the data\n#------------------------------------------------------------------------------\n\nuse_gpu = True\nPICKLED_FILES_PATH = \"./Data/cifar-10-batches-py\" \n\nX_train, y_train, X_test, y_test = load_cifar10.convert_pkl_to_numpy(PICKLED_FILES_PATH)\n\n# some transforms have to be applied as Alexnet cannot accept images less than 224x224\ntransform = transforms.Compose([\n transforms.ToPILImage(mode=\"RGB\"), # input has to be converted to PIL image otherwise Resize won't work\n transforms.Resize((224, 224)),\n transforms.ToTensor()\n ])\n\ntrain_dataset = load_cifar10.CIFAR10Dataset(X_train, y_train, use_gpu=False, transform=transform) # in order for thransforms to work output tensors should not be on gpu\n\n# Training the model\n#------------------------------------------------------------------------------\n\nclass AlexNet(nn.Module):\n ''' from pytorch github - https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py '''\n \n def __init__(self, num_classes=1000):\n super(AlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n )\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 6 * 6, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), 256 * 6 * 6)\n x = self.classifier(x)\n return x\n\nalexnet = AlexNet(num_classes=10)\n\nmodel = custom_models.CustomModel(alexnet, use_gpu)\n\n# setting hyperparameters\nbatch_size = 200\nlearning_rate = 0.0001\nnum_epochs = 1\nloss = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.module.parameters(), lr=learning_rate)\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\nmodel.train(dataset=train_dataset, \n batch_size=batch_size,\n loss=loss, \n optimizer=optimizer, \n num_epochs=num_epochs,\n val_batchsize=30)\n\ntorch.save(model.module.state_dict(), \"alexnet_model.params\")\n\n# Evaluation of the model\n#------------------------------------------------------------------------------\n\nX_for_evaluation = X_test[1000:2000,:]\ny_for_evaluation = y_test[1000:2000]\ntest_dataset = load_cifar10.CIFAR10Dataset(X_for_evaluation, y_for_evaluation, use_gpu=False, transform=transform)\nacc, cf = custom_models.predict_many_images(model, dataset=test_dataset)\nprint(\"Acc: {}, \\n\\nConfusion Matrix: \\n {}\".format(acc, cf))\n\n","repo_name":"cecP/cifar10-pytorch","sub_path":"train_alexnet_model.py","file_name":"train_alexnet_model.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15202048551","text":"# 0 means refuse the money (10 €)\r\n# 1 means accept the money (10 €)\r\n\r\n# 0 0 both get 5 €\r\n# 0 1 the second one gets all 10 €\r\n# 1 0 the first one gets all 10 €\r\n# 1 1 both get 1 €\r\n\r\nimport random # to use randint\r\n\r\n# The answer is random\r\n# 1/2 chance of refusing, 1/2 of accepting\r\nclass RandomChoice:\r\n def answer(self, lastOpponentAnswer):\r\n return random.randint(0,1)\r\n\r\n# Attempts to cooperate with the second player\r\n# As long as the second player also refuses, refuse\r\n# If the 2nd player betrays, refuse random amount of turns\r\n# Then attempt to cooperate again\r\nclass Cooperative:\r\n #__betray = False\r\n #__attemptToCooperate = False\r\n\r\n def __init__(self):\r\n self.__betray = False\r\n self.__attemptToCooperate = False\r\n\r\n def answer(self, lastOpponentAnswer):\r\n if lastOpponentAnswer == -1:\r\n return 0\r\n if self.__attemptToCooperate == True:\r\n self.__attemptToCooperate = False\r\n return 0\r\n if lastOpponentAnswer == 1:\r\n self.__betray = True\r\n if self.__betray == True:\r\n if lastOpponentAnswer == 0: # if opponent refused in the last turn\r\n if random.randint(0,1) == 1: # 1/2 chance of forgiving\r\n self.__betray = False\r\n self.__attemptToCooperate = True\r\n return 0\r\n else:\r\n return 1\r\n else:\r\n if random.randint(0,4) == 4: # 1/5 chance of forgiving\r\n self.__betray = False\r\n self.__attemptToCooperate = True\r\n return 0\r\n else:\r\n return 1\r\n\r\n return 0\r\n\r\n# Enables a human to play via keyboard input\r\nclass RealPlayer:\r\n def answer(self, lastOpponentAnswer):\r\n print (\"Opponent's last answer: \", lastOpponentAnswer)\r\n while True:\r\n ans = int(input(\"Your answer: \"))\r\n if ans == 0 or ans == 1:\r\n return ans;\r\n\r\n# Always accepts the money\r\nclass AlwaysAccept:\r\n def answer(self, lastOpponentAnswer):\r\n return 1\r\n\r\n# Always refuses the money\r\nclass AlwaysRefuse:\r\n def answer(self, lastOpponentAnswer):\r\n return 0\r\n \r\n# Repeat opponent's last choice\r\n# First turn is random\r\nclass TitForTat:\r\n def answer(self, lastOpponentAnswer):\r\n if lastOpponentAnswer == -1:\r\n return random.randint(0,1)\r\n return lastOpponentAnswer\r\n\r\nclass Adaptive:\r\n #testTitForTatCounter = 0\r\n #currentTurn = 0\r\n #myStrategy = [0, 0, 1, 1, 1]\r\n #opponentStrategy = []\r\n\r\n def __init__(self):\r\n self.testTitForTatCounter = 0\r\n self.currentTurn = 0\r\n self.myStrategy = [0, 0, 1, 1, 1]\r\n self.opponentStrategy = [] \r\n \r\n def answer(self, lastOpponentAnswer):\r\n if self.currentTurn > 0:\r\n self.opponentStrategy.append(lastOpponentAnswer)\r\n if self.currentTurn == 5:\r\n self.analyseData()\r\n if self.currentTurn >= 5:\r\n self.chooseNextMove()\r\n ans = self.myStrategy[self.currentTurn]\r\n self.currentTurn+=1\r\n #if self.currentTurn == 10:\r\n #print(self.testTitForTatCounter, end = '\\n')\r\n \r\n return ans\r\n\r\n def analyseData(self):\r\n # always refuse\r\n if self.opponentStrategy.count(0) == self.opponentStrategy.__len__():\r\n self.alwaysRefuse = True\r\n return\r\n\r\n # always accept\r\n if self.opponentStrategy.count(1) == self.opponentStrategy.__len__():\r\n self.alwaysAccept = True\r\n return\r\n\r\n # tit for tat\r\n titForTatMatches = 0\r\n for i in range(1, 5):\r\n if self.myStrategy[i-1] == self.opponentStrategy[i]:\r\n titForTatMatches += 1\r\n if titForTatMatches == 4: # it probably is tit for tat\r\n self.titForTat = True\r\n return\r\n #print(\"tit for tat matches\" + str(titForTatMatches), end='\\n')\r\n\r\n if self.opponentStrategy[0] == 0 and self.opponentStrategy[1] == 0: # probably wants to cooperate\r\n if self.opponentStrategy[2] == 1: # it punishes me for not cooperating\r\n for i in range(2, self.opponentStrategy.__len__()):\r\n if self.opponentStrategy[i] == 0: # it gives me another chance\r\n self.forgiveLength = i - 2;\r\n if i == 3:\r\n if self.opponentStrategy[4] == 0: # it gives me at least 2 chances\r\n self.pavlovSuperForgiving = True\r\n return\r\n else: # it gave me one chance\r\n self.pavlovForgiving = True\r\n return\r\n else: # it punished me too late\r\n self.unknown = True\r\n return\r\n\r\n # if it is not anything anything from above\r\n self.unknown = True\r\n\r\n # always cooperate\r\n def __titForTat(self):\r\n # check if the strategy is still the same\r\n if self.myStrategy[self.currentTurn-2] != self.opponentStrategy[self.currentTurn-1]:\r\n del self.titForTat\r\n self.unknown = True\r\n self.__unknown()\r\n return False\r\n\r\n self.testTitForTatCounter+=1\r\n self.myStrategy.append(0)\r\n return True\r\n\r\n # always defect\r\n def __alwaysRefuse(self):\r\n if self.opponentStrategy[-1] != 0:\r\n del self.alwaysRefuse\r\n self.unknown = True\r\n self.__unknown()\r\n return False\r\n\r\n self.myStrategy.append(1)\r\n return True\r\n\r\n # always defect\r\n def __alwaysAccept(self):\r\n if self.opponentStrategy[-1] != 1:\r\n del self.alwaysAccept\r\n self.unknown = True\r\n self.__unknown()\r\n return False\r\n\r\n self.myStrategy.append(1)\r\n return True\r\n\r\n # use tit for tat\r\n def __unknown(self):\r\n # check if it isn't aproximating a truly random algorithm\r\n if self.currentTurn > 10:\r\n randomnessRatio = self.opponentStrategy.count(1) / self.opponentStrategy.__len__()\r\n if randomnessRatio >= 0.4 and randomnessRatio <= 0.6:\r\n del self.unknown\r\n self.random = True\r\n self.__random()\r\n return False\r\n \r\n self.myStrategy.append(self.opponentStrategy[-1])\r\n return True\r\n\r\n # always defect\r\n def __random(self):\r\n # check if it still seems to be random\r\n randomnessRatio = self.opponentStrategy.count(1) / self.opponentStrategy.__len__()\r\n if not (randomnessRatio >= 0.4 and randomnessRatio <= 0.6):\r\n del self.random\r\n self.unknown = True\r\n self.__unknown()\r\n return False\r\n\r\n self.myStrategy.append(1)\r\n return True\r\n\r\n # attempt to cooperate\r\n def __pavlovForgiving(self):\r\n if self.opponentStrategy[-1] == 1: #I must have betrayed or it's a different algorithm\r\n # check if it is a different algorithm\r\n if self.myStrategy[self.currentTurn-2] == 0 and self.opponentStrategy[self.currentTurn-2] == 0 and self.myStrategy[self.currentTurn-1] == 0:\r\n # it defects me when I don't\r\n self.unknown = True;\r\n\r\n opponentLastCooperationIndex = 0\r\n myLastCooperationIndex = 0\r\n for i in range(self.opponentStrategy.__len__()-1, -1, -1): # find the last turn opponent tried to cooperate\r\n if self.opponentStrategy[i] == 0:\r\n opponentLastCooperationIndex = i\r\n break\r\n for i in range(self.myStrategy[self.currentTurn-1], -1, -1): # find the last turn I tried to cooperate\r\n if self.myStrategy[i] == 0:\r\n myLastCooperationIndex = i\r\n break\r\n # if the last time I tried to cooperate was the last turn find how long is the row\r\n if myLastCooperationIndex == self.currentTurn-1:\r\n row = 0\r\n for i in range(self.myStrategy[self.currentTurn-1], opponentLastCooperationIndex, -1):\r\n if self.myStrategy[i] == 0:\r\n row += 1\r\n else:\r\n break\r\n if row > 5: # if it hasn't forgiven me in 5 turns, give up, it isn't forgiving\r\n del self.pavlovForgiving\r\n self.pavlovUnforgiving = True\r\n self.__pavlovUnforgiving()\r\n return False\r\n else: # try to make it forgive and cooperate\r\n self.myStrategy.append(0)\r\n return True\r\n else: # it cooperates\r\n if hasattr(self, 'pavlovSuperForgiving'):\r\n del self.pavlovForgiving\r\n self.__pavlovSuperForgiving()\r\n return False\r\n\r\n self.myStrategy.append(0) # also cooperate\r\n return True\r\n\r\n def __pavlovUnforgiving(self):\r\n # anyway check if it has forgiven\r\n if self.opponentStrategy[-1] == 0:\r\n del self.pavlovUnforgiving\r\n self.pavlovForgiving = True\r\n self.__pavlovForgiving(self)\r\n return False\r\n\r\n # otherwise always defect\r\n self.myStrategy.append(1)\r\n return True\r\n\r\n def __pavlovSuperForgiving(self):\r\n if hasattr(self, 'forgiveCount') == False and self.opponentStrategy[-1] == 0:\r\n self.myStrategy.append(1)\r\n return True\r\n if hasattr(self, 'forgiveCount') == True and self.opponentStrategy[-1] == 0:\r\n del self.pavlovSuperForgiving\r\n self.pavlovForgiving = True\r\n return False\r\n if hasattr(self, 'forgiveCount') == False:\r\n # count how many times it has forgiven me\r\n self.forgiveCount = 0\r\n for i in range(self.currentTurn-2, -1, -1):\r\n if self.myStrategy[i] == 1 and self.opponentStrategy[i+1] == 0:\r\n self.forgiveCount += 1\r\n else:\r\n break\r\n # try to make it cooperate again\r\n self.pavlovForgiving = True\r\n self.__pavlovForgiving()\r\n return False\r\n else:\r\n if self.forgiveCount > 0:\r\n self.myStrategy.append(1)\r\n self.forgiveCount -= 1\r\n else:\r\n self.myStrategy.append(0)\r\n return True\r\n\r\n def chooseNextMove(self):\r\n if hasattr(self, 'titForTat'):\r\n self.__titForTat()\r\n elif hasattr(self, 'alwaysRefuse'):\r\n self.__alwaysRefuse()\r\n elif hasattr(self, 'alwaysAccept'):\r\n self.__alwaysAccept()\r\n elif hasattr(self, 'unknown'):\r\n self.__unknown()\r\n elif hasattr(self, 'random'):\r\n self.__random()\r\n elif hasattr(self, 'pavlovForgiving'):\r\n self.__pavlovForgiving()\r\n elif hasattr(self, 'pavlovUnforgiving'):\r\n self.__pavlovUnforgiving()\r\n elif hasattr(self, 'pavlovSuperForgiving'):\r\n self.__pavlovSuperForgiving()\r\n else:\r\n print (\"error: no pattern chosen\", end=\"\\n\") # should not happen\r\n\r\n\r\n\r\n\r\n### HERE END THE STRATEGIES ###\r\n","repo_name":"SlowerPhoton/IB111","sub_path":"Projects/Prisoner's Dilemma/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":11488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10065496147","text":"import argparse\nimport functools\nimport os\nimport sys\n\nfrom werkzeug.debug import DebuggedApplication\nfrom werkzeug.serving import run_simple\n\nfrom satosa.proxy_server import make_app\nfrom satosa.satosa_config import SATOSAConfig\n\nconfig_file = os.environ.get(\"SATOSA_CONFIG\", \"proxy_conf.yaml\")\nsatosa_config = SATOSAConfig(config_file)\napp = make_app(satosa_config)\n\n\ndef main():\n global app\n\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('port', type=int)\n parser.add_argument('--keyfile', type=str)\n parser.add_argument('--certfile', type=str)\n parser.add_argument('--host', type=str)\n parser.add_argument('-d', action='store_true', dest=\"debug\",\n help=\"enable debug mode.\")\n args = parser.parse_args()\n\n if (args.keyfile and not args.certfile) or (args.certfile and not args.keyfile):\n print(\"Both keyfile and certfile must be specified for HTTPS.\")\n sys.exit()\n\n if args.debug:\n app.app = functools.partial(app.app, debug=True)\n app = DebuggedApplication(app)\n\n if (args.keyfile and args.certfile):\n ssl_context = (args.certfile, args.keyfile)\n else:\n ssl_context = None\n\n if args.host:\n run_simple(args.host, args.port, app, ssl_context=ssl_context)\n else:\n run_simple('localhost', args.port, app, ssl_context=ssl_context)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MESH-Research/SATOSA","sub_path":"src/satosa/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"23797483395","text":"import copy\nimport cupy as cp\nimport csv\nimport os\nimport random\nfrom typing import List\n\nclass ParallelSearch:\n def __init__(self,\n kmer_size = 32):\n self.blocks = {}\n self.base_mapping = {'N': 0, 'A': 1, 'C': 2, 'G': 3, 'T': 4}\n self.kmer_size = kmer_size\n self.results = {}\n self.record_results = False\n\n def seq_to_numeric(self, seq):\n return [self.base_mapping.get(s, 0) for s in seq]\n\n def buildBlock(self,\n block_name: str,\n genome_file: str):\n \n def reverseComplement(sequence):\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\n return ''.join(complement[base] for base in reversed(sequence))\n \n if self.record_results:\n return\n # Extract genome from file\n f = open(genome_file, 'r')\n genome = [\"\".join(fragment.split('\\n')[1:]) for fragment in f.read().split('>')[1:]]\n genome = genome + [reverseComplement(fragment) for fragment in genome]\n f.close()\n\n # Extract kmers from genome\n kmers_in_genome = []\n for fragment in genome:\n kmers_in_fragment_num = len(fragment) - self.kmer_size + 1\n for kmer_idx in range(kmers_in_fragment_num):\n kmers_in_genome.append(fragment[kmer_idx: kmer_idx + self.kmer_size])\n\n self._buildBlock(block_name=block_name,\n sequences=kmers_in_genome)\n\n def search(self,\n patterns,\n threshold = 0,\n time = 0,\n discharge_rate = 0,\n true_genome = 'Nan'):\n \n self._perturbateBlocks(\n time=time,\n discharge_rate=discharge_rate\n )\n\n # Build results\n results = None\n if (threshold, time, discharge_rate) in self.results:\n results = self.results[(threshold, time, discharge_rate)]\n else:\n results = {\n \"threshold\": threshold,\n \"time\": time,\n \"discharge rate\": discharge_rate\n }\n for block_name in self.blocks:\n results.update({\n block_name + \"-tp\": 0,\n block_name + \"-fp\": 0,\n block_name + \"-fn\": 0,\n block_name + \"-tn\": 0\n })\n self.results[(threshold, time, discharge_rate)] = results\n for pattern in patterns:\n if len(pattern) != self.kmer_size:\n continue\n ########### Search Pattern ###########\n pattern_array = cp.array(self.seq_to_numeric(pattern), dtype='int32')\n matching_blocks = []\n\n for block_name, block in self.blocks.items():\n def baseNeq(b1, b2):\n return not (b1 == b2 or b1 == 0 or b2 == 0)\n \n patternNeq = cp.vectorize(baseNeq)\n distances = cp.sum(patternNeq(block, pattern_array), axis=1)\n if cp.any(distances <= threshold):\n matching_blocks.append(block_name)\n ######################################\n\n ########### Update Results ###########\n for matching_block in matching_blocks:\n if true_genome in matching_block:\n self.results[(threshold, time, discharge_rate)][matching_block + \"-tp\"] += 1\n else:\n self.results[(threshold, time, discharge_rate)][matching_block + \"-fp\"] += 1\n if not true_genome in matching_blocks and not true_genome == \"Nan\":\n self.results[(threshold, time, discharge_rate)][true_genome + \"-fn\"] += 1\n\n for block_name in self.blocks:\n if block_name != true_genome and not block_name in matching_blocks:\n self.results[(threshold, time, discharge_rate)][block_name + \"-tn\"] += 1\n ######################################\n self._resetBlocks()\n \n def recordResults(self,\n results_file: str):\n os.makedirs(\"/\".join(results_file.split(\"/\")[:-1]), exist_ok=True)\n self.record_results = True\n self.results_file = results_file\n self.results_headers = [\"threshold\", \"time\", \"discharge rate\"]\n for block_name in self.blocks:\n self.results_headers.append(block_name + \"-tp\")\n self.results_headers.append(block_name + \"-fp\")\n self.results_headers.append(block_name + \"-fn\")\n self.results_headers.append(block_name + \"-tn\")\n self.results = {}\n\n\n def stopRecording(self):\n with open(self.results_file, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(self.results_headers)\n for result in self.results.values():\n writer.writerow([result[header] for header in self.results_headers])\n self.record_results = False\n self.results = {}\n\n def _buildBlock(self, block_name, sequences):\n seq_matrix = cp.array([self.seq_to_numeric(s) for s in sequences], dtype='int32')\n self.blocks[block_name] = seq_matrix\n\n def _perturbateBlocks(self, \n time,\n discharge_rate,\n mu = 100,\n sigma = 16.6,\n ):\n self.orig_blocks = copy.deepcopy(self.blocks)\n if discharge_rate > 0:\n self._readBaseFlips(discharge_rate)\n if time > 0:\n self._timeBaseFlips(time,\n mu=mu,\n sigma=sigma)\n \n def _resetBlocks(self):\n self.blocks = copy.deepcopy(self.orig_blocks)\n\n def _readBaseFlips(\n self,\n discharge_rate):\n for block_name, block in self.blocks.items():\n self.blocks[block_name] = cp.where(\n cp.random.rand(block.shape[0], block.shape[1]) < discharge_rate,\n self.base_mapping[\"N\"],\n block\n )\n\n def _timeBaseFlips(\n self,\n time,\n mu,\n sigma):\n for block_name, block in self.blocks.items():\n timingOfFlips = cp.random.normal(mu, sigma, block.shape)\n print(time)\n print(timingOfFlips)\n print(cp.where(timingOfFlips < time, self.base_mapping[\"N\"], block))\n self.blocks[block_name] = cp.where(timingOfFlips < time, self.base_mapping[\"N\"], block)\n","repo_name":"zuherJahshan/dash-cam","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":6528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30523675232","text":"from bisect import bisect_left\n\n\nh, w, r, c = map(int, input().split())\nn = int(input())\n\nhight = {}\nwidth = {}\nhi = set()\nwi = set()\nfor _ in range(n):\n x, y = map(int, input().split())\n hight.setdefault(y, [])\n width.setdefault(x, [])\n hight[y].append(x)\n width[x].append(y)\n hi.add(y)\n wi.add(x)\n\nfor v in hight:\n hight[v].sort()\nfor v in width:\n width[v].sort()\n\nq = int(input())\nx, y = r, c\nfor _ in range(q):\n d, l = input().split()\n l = int(l)\n\n if d == 'U':\n if y not in hi:\n x -= l\n else:\n idx = bisect_left(hight[y], x) - 1\n if idx == -1:\n x -= l\n else:\n x = max(x-l, hight[y][idx] + 1)\n elif d == 'D':\n if y not in hi:\n x += l\n else:\n idx = bisect_left(hight[y], x)\n if idx == len(hight[y]):\n x += l\n else:\n x = min(x+l, hight[y][idx]-1)\n elif d == 'L':\n if x not in wi:\n y -= l\n else:\n idx = bisect_left(width[x], y) - 1\n if idx == -1:\n y -= l\n else:\n y = max(y-l, width[x][idx]+1)\n elif d == 'R':\n if x not in wi:\n y += l\n else:\n idx = bisect_left(width[x], y)\n if idx == len(width[x]):\n y += l\n else:\n y = min(y+l, width[x][idx]-1)\n x = max(1, min(x, h))\n y = max(1, min(y, w))\n print(x, y)","repo_name":"chikati3/Atcoder","sub_path":"abc273/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41565296617","text":"# pastebin_api.py\n\nimport requests\n\ndef create_paste(title, body, duration, publicly_listed):\n \"\"\"\n Creates a new PasteBin paste and returns the url.\n\n Parameters\n ----------\n title : str\n The title of the paste.\n body : str\n The body of the paste.\n duration : int\n The expiration duration of the paste.\n Should be one of the following:\n - 1 : 10 minutes\n - 2 : 1 hour\n - 4 : 1 day\n - 5 : 1 week\n - 6 : 2 weeks\n - 7 : 1 month\n publicly_listed : bool\n Whether the paste should be publicly listed or not.\n\n Returns\n -------\n str or None\n The URL of the newly created paste, or None\n if the creation failed.\n \"\"\"\n data = {\n 'title': title,\n 'body': body,\n 'expire': duration,\n 'public': publicly_listed\n }\n url = 'https://pastebin.com/api/api_post.php'\n r = requests.post(url, data=data)\n if r.status_code == 200:\n return r.text\n else:\n print('Response code: {}'.format(r.status_code))\n return None\n","repo_name":"tanvirannvy/COMP593-Lab-5","sub_path":"pastebin_api.py","file_name":"pastebin_api.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"75234037159","text":"import sys\ninput = sys.stdin.readline\n###########################################\ndx = [0, -1, 0, 1]\ndy = [-1, 0, 1, 0]\n###########################################\ndef first_masic():\n global n, arr, fish, arr_n, arr_m\n # 최초 호출시 첫번째 마법으로 만들어진 행렬을 만드는 부분\n if n is None:\n n = 1\n while True:\n if n ** 2 >= N:\n break\n n += 1\n\n if N != n ** 2:\n n -= 1\n if N - n ** 2 == n:\n arr = [[None for _ in range(n)] for _ in range(n + 1)]\n arr_n = n + 1\n arr_m = n\n elif N - n**2 - n > 0:\n arr = [[None for _ in range(N - n**2)] for _ in range(n+1)]\n arr_n = n+1\n arr_m = N - n**2\n\n elif N - n**2 - n < 0:\n arr = [[None for _ in range(n + N - n ** 2)] for _ in range(n)]\n arr_n = n\n arr_m = N - n ** 2 + n\n\n\n else:\n arr = [[None for _ in range(n)] for _ in range(n)]\n arr_n = n\n arr_m = n\n\n i = N\n x = arr_n - 1\n y = arr_m\n dir = 0\n\n if n ** 2 != N:\n x = arr_n - 1\n y = arr_m\n\n for i in range(N-1, -1, -1):\n x += dx[dir]\n y += dy[dir]\n\n arr[x][y] = i\n\n nx = x + dx[dir]\n ny = y + dy[dir]\n\n if nx < 0 or nx >= arr_n or ny < 0 or ny >= arr_m:\n dir = (dir + 1) % 4\n break\n\n for j in range(i-1, -1, -1):\n x += dx[dir]\n y += dy[dir]\n\n arr[x][y] = j\n\n nx = x + dx[dir]\n ny = y + dy[dir]\n\n if N != n ** 2:\n if nx < 0 or nx >= arr_n - 1 or ny < 0 or ny >= n or arr[nx][ny] is not None:\n dir = (dir + 1) % 4\n else:\n if nx < 0 or nx >= n or ny < 0 or ny >= n or arr[nx][ny] is not None:\n dir = (dir + 1) % 4\n\n###########################################\n new_arr = fish.copy()\n\n if N != n ** 2:\n for i in range(arr_n):\n for j in range(arr_m):\n if arr[i][j] is None:\n continue\n for dir in range(4):\n nx = i + dx[dir]\n ny = j + dy[dir]\n\n if nx < 0 or nx >= arr_n or ny < 0 or ny >= arr_m or arr[nx][ny] is None:\n continue\n\n if fish[arr[i][j]] - fish[arr[nx][ny]] >= 5:\n new_arr[arr[i][j]] -= (fish[arr[i][j]] - fish[arr[nx][ny]]) // 5\n new_arr[arr[nx][ny]] += (fish[arr[i][j]] - fish[arr[nx][ny]]) // 5\n\n else:\n for j in range(n):\n for i in range(n):\n for dir in range(4):\n nx = i + dx[dir]\n ny = j + dy[dir]\n\n if nx < 0 or nx >= n or ny < 0 or ny >= n:\n continue\n\n if fish[arr[i][j]] - fish[arr[nx][ny]] >= 5:\n new_arr[arr[i][j]] -= (fish[arr[i][j]] - fish[arr[nx][ny]]) // 5\n new_arr[arr[nx][ny]] += (fish[arr[i][j]] - fish[arr[nx][ny]]) // 5\n\n return_arr = []\n if N != n ** 2:\n for j in range(arr_m):\n for i in range(arr_n - 1, -1, -1):\n if arr[i][j] is None:\n continue\n\n return_arr.append(new_arr[arr[i][j]])\n else:\n for j in range(n):\n for i in range(n-1, -1, -1):\n return_arr.append(new_arr[arr[i][j]])\n\n return return_arr\n\n\n###########################################\ndef second_masic():\n global arr_2\n if arr_2 is None:\n arr_2 = [[0 for _ in range(N // 4)] for _ in range(4)]\n\n nN = 0\n for i in range(N//4-1, -1, -1):\n arr_2[2][i] = nN\n nN += 1\n for i in range(N//4):\n arr_2[1][i] = nN\n nN += 1\n for i in range(N//4-1, -1, -1):\n arr_2[0][i] = nN\n nN += 1\n for i in range(N//4):\n arr_2[3][i] = nN\n nN += 1\n\n new_arr = fish.copy()\n\n for i in range(4):\n for j in range(N//4):\n for dir in range(4):\n nx = i + dx[dir]\n ny = j + dy[dir]\n\n if nx < 0 or nx >= 4 or ny < 0 or ny >= N//4:\n continue\n\n if fish[arr_2[i][j]] - fish[arr_2[nx][ny]] >= 5:\n new_arr[arr_2[i][j]] -= (fish[arr_2[i][j]] - fish[arr_2[nx][ny]]) // 5\n new_arr[arr_2[nx][ny]] += (fish[arr_2[i][j]] - fish[arr_2[nx][ny]]) // 5\n\n return_arr = []\n for j in range(N//4):\n for i in range(3, -1, -1):\n return_arr.append(new_arr[arr_2[i][j]])\n\n return return_arr\n\n\n###########################################\nN, K = map(int, input().split())\n\nn = None\narr = None\narr_n = 0\narr_m = 0\n\narr_2 = None\nfish = list(map(int, input().split()))\n\ncount = 0\nwhile True:\n min_fish = 10001\n max_fish = 0\n\n min_fish_list = []\n for i in range(N):\n if fish[i] < min_fish:\n min_fish = fish[i]\n min_fish_list = [i]\n\n elif fish[i] == min_fish:\n min_fish_list.append(i)\n\n max_fish = max(max_fish, fish[i])\n\n if max_fish - min_fish <= K:\n break\n\n for i in min_fish_list:\n fish[i] += 1\n\n fish = first_masic()\n fish = second_masic()\n count += 1\n\nprint(count)\n###########################################\n# K = 0\n# fish = [5, 2, 3, 14, 9, 2, 11, 8]\n# for N in range(4, 100, 4):\n# n = None\n# arr = None\n# first_masic()\n# print(N)\n# for j in arr:\n# print(j)\n#\n# print(\"#########################################\")","repo_name":"Sunghyun1320/algorithm","sub_path":"python/BOJ/just_study/23291.py","file_name":"23291.py","file_ext":"py","file_size_in_byte":5841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16339358860","text":"# -*- encoding: utf-8 -*-\n'''\n@project : LeetCode\n@File : isRectangleOverlap.py\n@Contact : 9824373@qq.com\n@Desc :\n 矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。\n\n 如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。\n\n 给出两个矩形,判断它们是否重叠并返回结果。\n\n 示例 1:\n\n 输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]\n 输出:true\n 示例 2:\n\n 输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]\n 输出:false\n\n\n 提示:\n\n 两个矩形 rec1 和 rec2 都以含有四个整数的列表的形式给出。\n 矩形中的所有坐标都处于 -10^9 和 10^9 之间。\n x 轴默认指向右,y 轴默认指向上。\n 你可以仅考虑矩形是正放的情况��\n\n@Modify Time @Author @Version @Desciption\n------------ ------- -------- -----------\n2020-03-18 zhan 1.0 None\n'''\nfrom typing import List\n\nclass Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n if (rec1[0] <= rec2[0] < rec1[2] and rec2[1] < rec1[3] and rec2[3] >= rec1[1]) or \\\n (rec2[0] <= rec1[0] < rec2[2] and rec1[1] < rec2[3] and rec1[3] >= rec2[1]):\n return True\n\n return False\n #\n # if (rec1[0] <= rec2[0] < rec1[2] and rec1[1] <= rec2[1] < rec1[3]) or \\\n # (rec1[0] < rec2[2] <= rec1[2] and rec1[1] < rec2[3] <= rec1[3]):\n # return True\n # # else: return False\n # if (rec2[0] <= rec1[0] < rec2[2] and rec2[1] <= rec1[1] < rec2[3]) or \\\n # (rec2[0] < rec1[2] <= rec2[2] and rec2[1] < rec1[3] <= rec2[3]):\n # return True\n #\n # if ((rec1[0] <= rec2[0] < rec1[2] and rec2[1] <= rec1[1]) and (rec1[0] <= rec2[2] <= rec1[2] and rec2[3] >= rec1[3])) or \\\n # ((rec2[0] <= rec1[0] < rec2[2] and rec1[1] <= rec2[1]) and (\n # rec2[0] <= rec1[2] <= rec2[2] and rec1[3] >= rec2[3])):\n # return True\n # return False\n\nif __name__ == '__main__':\n rec1 = [0, 0, 2, 2]\n rec2 = [1, 1, 3, 3]\n\n # rec1 = [0, 0, 1, 1]\n # rec2 = [1, 0, 2, 1]\n\n # rec1 = [-7, -3, 10, 5]\n # rec2 = [-6, -5, 5, 10]\n rec1 = [1, 13, 16, 20]\n rec2 = [2, 12, 11, 18]\n\n ans = Solution().isRectangleOverlap(rec1,rec2)\n print(ans)\n\n\n\n\n\n","repo_name":"passionzhan/LeetCode","sub_path":"isRectangleOverlap.py","file_name":"isRectangleOverlap.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5884469593","text":"from Bio.Seq import Seq\nimport os\nimport sys\nimport unittest\nfrom io import StringIO\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src'))\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'tests'))\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\nfrom functions_test import *\nfrom Biogrinder import Biogrinder\nfrom SimulatedRead import SimulatedRead\n\nclass Test_27_Stdin(unittest.TestCase):\n def setUp(self):\n # Simulating the __DATA__ section in Perl\n data = \"\"\">seq1 this is the first sequence\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n>seq2\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\n>seq3\ngggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg\ngggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg\n>seq4\ntttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt\n>seq5 last sequence, last comment\naaaaaaaaaattttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttgggggggggg\"\"\"\n \n self.stdin_backup = sys.stdin\n sys.stdin = StringIO(data)\n\n def tearDown(self):\n sys.stdin = self.stdin_backup\n\n def test_input_from_stdin(self):\n\n factory = Biogrinder('-rf', '-',\n '-rd', '48',\n '-tr', '100',\n '-id', '0')\n factory.next_lib()\n nof_reads = 0\n while True:\n read = factory.next_read()\n if not read:\n break\n nof_reads += 1\n self.ok_read(read, None, nof_reads)\n self.assertEqual(nof_reads, 100)\n\n def ok_read(self, read, req_strand, nof_reads):\n self.assertIsInstance(read, SimulatedRead)\n source = read.reference_id\n strand = read.strand\n req_strand = strand if req_strand is None else req_strand\n self.assertEqual(strand, req_strand)\n\n letters = {'seq1': 'A', 'seq2': 'C', 'seq3': 'G', 'seq4': 'T', 'seq5': 'ATG'}[source]\n if req_strand == -1:\n letters = str(Seq(letters).reverse_complement())\n\n self.assertRegex(str(read.seq), f\"[{letters}]+\")\n self.assertEqual(read.id, str(nof_reads))\n \nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"philcharron-cfia/biogrinder","sub_path":"tests/test_27_stdin.py","file_name":"test_27_stdin.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20694786284","text":"import numpy as np\nimport os,sys,time,random,argparse,subprocess\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport metadata,util\n\n##########################################################################\n##########################################################################\n##########################################################################\n#test machine configuration\nbrokers=['node2']\nsubscriber_test_machines=['node17','node25','node26']\npublisher_test_machines=['node%d'%(i) for i in range(3,42,1)]\nfor m in subscriber_test_machines:\n publisher_test_machines.remove(m)\n\n#maximum number of publishers \nmaximum_publishers=reduce(lambda x,y:x+y,\\\n [metadata.pub_per_hw_type[metadata.get_hw_type(host)] for host in publisher_test_machines])\n\n#maximum number of subscribers\nmaximum_subscribers=reduce(lambda x,y:x+y,\\\n [metadata.sub_per_hw_type[metadata.get_hw_type(host)] for host in subscriber_test_machines])\n\n#maximum publication rate supported for a given per-topic processing interval\nmax_supported_rates={\n 5:192,\n 10:94,\n 15:65,\n 20:45,\n 25:36,\n 30:30,\n 35:26,\n 40:23,\n 45:20,\n 50:16,\n}\n##########################################################################\n##########################################################################\n##########################################################################\n#Test parameters\npayload=4000\nper_publisher_publication_rate=1\nsubscribers_per_topic=1\nliveliness=120\nrates=5\nprocessing_intervals=[10,20,30,40] #milliseconds\nrange_of_rates={ #msg/sec\n 10:[int(v) for v in np.linspace(1,max_supported_rates[10],rates)],\n 20:[int(v) for v in np.linspace(1,max_supported_rates[20],rates)],\n 30:[int(v) for v in np.linspace(1,max_supported_rates[30],rates)],\n 40:[int(v) for v in np.linspace(1,max_supported_rates[40],rates)],\n}\n##########################################################################\n##########################################################################\n##########################################################################\ndef pattern(foreground_processing_interval,foreground_rate,topics):\n p='f:%d:%d,'%(foreground_processing_interval,foreground_rate)\n for i in range(topics):\n #randomly select a processing interval and rate for the topic\n interval= processing_intervals[random.randint(0,len(processing_intervals)-1)]\n rate= range_of_rates[interval][random.randint(0,len(range_of_rates[interval])-1)]\n p=p+'t%d:%d:%d,'%(i+1,interval,rate)\n return p.rstrip(',')\n\ndef check_correctness(pattern):\n total_publishers=reduce(lambda x,y:x+y,[int(t.split(':')[2]) for t in pattern.split(',')])\n if total_publishers <= maximum_publishers:\n return True\n else:\n return False\n\ndef combinations(foreground_processing_interval,foreground_rate,topics,count):\n res=set()\n while(len(res) < count):\n p= pattern(foreground_processing_interval,foreground_rate,topics)\n if(check_correctness(p)):\n res.add(p)\n return res\n\ndef create_configuration(iteration):\n config=[]\n for t in iteration.split(','):\n topic,processing_interval,rate=t.split(':') \n num_publishers=int(rate)/per_publisher_publication_rate\n #pub_distribution=topic:#pub:rate:sample_count:payload:interval\n pub_distribution='%s:%d:%d:%d:%d:%s'%(topic,\n num_publishers,\n per_publisher_publication_rate,\n liveliness,\n payload,\n processing_interval)\n #sub_distribution=topic:#sub:sample_count:interval\n sub_distribution='%s:%d:%d:%s'%(topic,\n subscribers_per_topic,\n liveliness*num_publishers,\n processing_interval)\n #topic_configuration= name,processing_interval,rate,pub_distribution,sub_distribution,#pub,#sub,#endpoints,payload,interval*rate\n topic_config='%s,%s,%s,%s,%s,%d,%d,%d,%d,%f'%(topic,\n processing_interval,\n rate,\n pub_distribution,\n sub_distribution,\n num_publishers,\n subscribers_per_topic,\n num_publishers+subscribers_per_topic,\n payload,\n (int(processing_interval)*int(rate))/1000.0)\n \n config.append(topic_config)\n return config\n \ndef place(endpoint_type,endpoint_distribution):\n placement={}\n if(endpoint_type=='sub'):\n hosts=list(subscriber_test_machines)\n host_capacity_map={h:metadata.get_host_subscriber_capacity(h)\\\n for h in subscriber_test_machines}\n elif(endpoint_type=='pub'):\n hosts=list(publisher_test_machines)\n host_capacity_map={h:metadata.get_host_publisher_capacity(h)\\\n for h in publisher_test_machines}\n else:\n print('endpoint_type:%s is invalid'%(endpoint_type))\n return\n\n for mapping in endpoint_distribution:\n if(endpoint_type=='sub'):\n #sub_distribution=topic:#sub:sample_count:interval\n topic,num_sub,sample_count,processing_interval=mapping.split(':')\n count=int(num_sub)\n if(endpoint_type=='pub'):\n #pub_distribution=topic:#pub:rate:sample_count:payload:interval\n topic,num_pub,rate,sample_count,payload,processing_interval=mapping.split(':')\n count=int(num_pub)\n \n while(count!=0):\n host=hosts[0]\n capacity=host_capacity_map[host]\n if(count<=capacity):\n if(endpoint_type=='sub'):\n if host in placement:\n placement[host].append('%s:%d:%s:%s'%(topic,count,\n sample_count,processing_interval))\n else:\n placement[host]=['%s:%d:%s:%s'%(topic,count,\n sample_count,processing_interval)]\n if(endpoint_type=='pub'):\n if host in placement:\n placement[host].append('%s:%d:%s:%s:%s:%s'%(topic,count,\n rate,sample_count,payload,processing_interval))\n else:\n placement[host]=['%s:%d:%s:%s:%s:%s'%(topic,count,\n rate,sample_count,payload,processing_interval)]\n\n host_capacity_map[host]=host_capacity_map[host]-count\n if(host_capacity_map[host]==0):\n hosts.pop(0)\n count=0\n else:\n if(endpoint_type=='sub'):\n if host in placement:\n placement[host].append('%s:%d:%s:%s'%(topic,capacity,\n sample_count,processing_interval))\n else:\n placement[host]=['%s:%d:%s:%s'%(topic,capacity,\n sample_count,processing_interval)]\n if(endpoint_type=='pub'):\n if host in placement:\n placement[host].append('%s:%d:%s:%s:%s:%s'%(topic,capacity,\n rate,sample_count,payload,processing_interval))\n else:\n placement[host]=['%s:%d:%s:%s:%s:%s'%(topic,capacity,\n rate,sample_count,payload,processing_interval)]\n host_capacity_map[host]=0\n hosts.pop(0)\n count=count-capacity\n return placement\n\ndef model_features(config):\n res={}\n for tdesc in config:\n parts= tdesc.split(',')\n topic_name=parts[0]\n processing_interval=parts[1]\n publication_rate=parts[2]\n background_rate_x_processing_interval=0\n for tdesc in config:\n other_topic_name=tdesc.split(',')[0]\n if not other_topic_name==topic_name:\n background_rate_x_processing_interval+= float(tdesc.split(',')[-1])\n \n res[topic_name]='%s,%s,%f'%(processing_interval,publication_rate,background_rate_x_processing_interval)\n return res\n \ndef model_output(log_dir,run_id):\n toGb=.000008\n res={}\n with open('%s/%s/summary/summary_util.csv'%(log_dir,run_id),'r') as f:\n #skip header:hostname,avg_cpu(%),avg_iowait(%),avg_mem(gb),avg_nw(kB/sec)\n next(f)\n hostname,cpu,iowait,mem,nw= next(f).split(',')\n res['cpu']=float(cpu)\n res['mem']=float(mem)\n res['nw']=float(nw)*toGb\n\n res['90th']={}\n res['avg']={}\n with open('%s/%s/summary/summary_topic.csv'%(log_dir,run_id),'r') as f:\n #skip header:\n next(f)\n for line in f:\n parts=line.split(',')\n res['90th'][parts[0]]=float(parts[9])\n res['avg'][parts[0]]=float(parts[2])\n return res\n\ndef experiment(log_dir,run_id,config,subscriber_placement,publisher_placement):\n #clean-up before running any test\n print(\"\\n\\nCleaning logs directory\")\n util.clean_logs(','.join(subscriber_placement.keys()+publisher_placement.keys()+brokers))\n\n #restart edge-broker\n print(\"\\n\\nRestarting EdgeBroker\")\n print(len(brokers))\n util.start_eb(','.join(brokers)) \n\n #start the experiment and wait for it to finish\n print('\\n\\n\\nStarting test endpoints')\n print(\"Subscribers:{}\".format(subscriber_placement))\n print(\"Publishers:{}\".format(publisher_placement))\n load=util.Coordinate(\"test\",run_id,subscriber_placement,\\\n publisher_placement)\n\n #start monitoring processes\n util.start_monitors(run_id,\"test\",0,','.join(brokers))\n #start test endpoints\n load.start()\n #wait for test to finish\n load.wait()\n #kill all endpoints\n load.kill()\n #close zk connection\n load.stop()\n\n #collect logs\n print(\"\\n\\nCollecting Logs\")\n client_and_broker_machines=[]\n map(lambda x: client_and_broker_machines.append(x),brokers) \n map(lambda x: client_and_broker_machines.append(x),subscriber_placement.keys()) \n map(lambda x: client_and_broker_machines.append(x),publisher_placement.keys()) \n util.collect_logs(run_id,log_dir,','.join(client_and_broker_machines))\n\n #write test configuration\n print(\"\\n\\nSaving test configuration\")\n with open('%s/%s/config'%(log_dir,run_id),'w') as f:\n #topic_configuration= name,processing_interval,rate,pub_distribution,sub_distribution,#pub,#sub,#endpoints,payload,interval*rate\n f.write('topic_name,processing_interval,aggregate_rate,publisher_distribution,subscriber_distribution,number_of_publishers,number_of_subscribers,total_endpoints,payload,interval*rate\\n')\n for topic_description in config:\n f.write(topic_description+'\\n') \n\n #summarize results\n print(\"\\n\\nSummarizing results\")\n subprocess.check_call(['python','src/plots/summarize/summarize.py',\\\n '-log_dir',log_dir,'-sub_dirs',str(run_id)])\n\n #copy model features \n print(\"\\n\\nCopying model features\")\n y=model_output(log_dir,run_id)\n features=model_features(config)\n with open('%s/%s/features'%(log_dir,run_id),'w') as f:\n f.write('#background_topics,foreground_processing_interval,foreground_rate,background_rate_x_processing_interval,\\\n foreground_avg_latency,foreground_90th_percentile_latency,broker_cpu,broker_mem,broker_nw\\n')\n for topic,features in features.items():\n if (topic=='f'):\n f.write('%d,%s,%f,%f,%f,%f,%f\\n'%(len(config)-1,features,y['avg'][topic],y['90th'][topic],y['cpu'],y['mem'],y['nw']))\n\n\ndef run(config,log_dir,run_id):\n #get subscriber configurations for all topics in this test config\n subscribers=['%s'%(tdesc.split(',')[4]) for tdesc in config]\n #get publisher configurations for all topics in this test config\n publishers=['%s'%(tdesc.split(',')[3]) for tdesc in config]\n\n #get placement for all subscribers in this test\n subscriber_placement=place('sub',subscribers)\n #get placement for all publishers in this test\n publisher_placement=place('pub',publishers)\n \n #run experiment\n experiment(log_dir,run_id,config,subscriber_placement,publisher_placement)\n \n \nif __name__ == \"__main__\":\n parser= argparse.ArgumentParser(description='script for collecting performance data for a given foreground rate, foreground processing interval and number of colocated topics')\n parser.add_argument('-log_dir',required=True)\n parser.add_argument('-foreground_processing_interval',type=int,required=True)\n parser.add_argument('-foreground_rate',type=int,required=True)\n parser.add_argument('-topics',type=int,required=True)\n parser.add_argument('-combinations',type=int,required=True)\n args=parser.parse_args()\n\n #create test combinations for given number of colocated topics and number of test combinations\n res=combinations(args.foreground_processing_interval,args.foreground_rate,args.topics,args.combinations)\n for idx,test_iteration in enumerate(res):\n #get test configuration\n config=create_configuration(test_iteration)\n #execute test\n run(config,args.log_dir,idx+1)\n","repo_name":"doc-vu/edgent","sub_path":"scripts/experiment/src/tests/rate_processing_interval_combinations_2.py","file_name":"rate_processing_interval_combinations_2.py","file_ext":"py","file_size_in_byte":11946,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"19576332701","text":"from scipy.optimize import minimize\nimport re\nfrom qxelarator import qxelarator\nfrom functools import reduce\nimport numpy as np\n\nclass VQE(object):\n \n def __init__(self):\n self.minimizer = minimize\n self.minimizer_kwargs = {'method':'Nelder-Mead', 'options':{'maxiter':200, 'ftol':1.0e-8, 'xtol':1.0e-8, 'disp':True}}\n \n def vqe_run(self, ansatz, h, steps, x0, aid, cfs):\n \n \"\"\"\n args:\n ansatz: variational functional closure in cQASM\n h: hamiltonian\n x0: initial parameters for generating the function of the functional\n return:\n x: set of ansats parameters\n fun: scalar value of the objective function\n \"\"\"\n t_name = \"test_output/\"+ansatz+\".qasm\"\n p_name = \"test_output/\"+ansatz+\"_try\"+\".qasm\"\n \n def objective_func(x):\n add_param(x) # If parameterised program construct not available, define new program here \n return expectation(h)\n \n def add_param(x):\n template = open(t_name,\"r\")\n prog = open(p_name,\"w\")\n param_ctr = 0\n s = 0\n param_max = len(cfs)\n for line in template:\n if re.search('\\*',line):\n if aid[param_ctr] == 0: # beta replacer\n theta = x[s]\n else: # gamma replacer\n theta = x[s+steps]\n line_new = re.sub('\\*',str(theta*cfs[param_ctr]), line)\n param_ctr += 1\n if param_ctr == param_max:\n param_ctr = 0\n s += 1\n prog.write(line_new)\n else:\n prog.write(line)\n template.close()\n prog.close() \n \n def expectation(h):\n # We will not use the wavefunction (display command) as is not possible in a real QC\n # E = = real(dot(transjugate(wf),dot(H,wf))) \n \n # WATSON: correct this for n-qubits\n qx = qxelarator.QX()\n qx.set(p_name)\n shots = 1000\n p0 = 0\n for i in range(shots):\n qx.execute()\n c0 = qx.get_measurement_outcome(0)\n if c0 == False:\n p0 = p0+1\n E = (p0/shots)**2 - ((shots-p0)/shots)**2\n return E\n \n args = [objective_func, x0]\n return self.minimizer(*args, **self.minimizer_kwargs)\n\n\nclass QAOA(object): \n def get_angles(self, qubits, steps, betas, gammas, ham, ang_id, coeffs):\n # Finds optimal angles with the quantum variational eigensolver method.\n t_name = \"test_output/graph.qasm\"\n tv_name = \"test_output/qaoa.qasm\"\n p_name = \"test_output/qaoa_try.qasm\"\n\n def make_qaoa():\n cfs = []\n # Make VQE ansatz template from QAOA ansatz\n prog = open(tv_name,\"w\")\n prog.write(\"qubits \"+str(qubits)+\"\\n\")\n # Reference state preparation\n for i in range(0,qubits):\n prog.write(\"h q\"+str(i)+\"\\n\")\n # Repeat ansatz for specified steps\n for i in range(0,steps):\n template = open(t_name,\"r\")\n for line in template:\n prog.write(line)\n template.close()\n cfs = np.hstack((cfs,coeffs))\n prog.close()\n return cfs\n \n full_coeffs = make_qaoa()\n #H_cost = []\n angles = np.hstack((betas, gammas)) # A concatenated list of angles [betas]+[gammas]\n \n v = VQE()\n result = v.vqe_run(\"qaoa\", ham, steps, angles, ang_id, coeffs) # VQE for PauliTerm Hamiltonian and coefficients \n return result\n \n def probabilities(ang):\n # Computes the probability of each state given a particular set of angles.\n prog = \"test_output/qaoa_try.qasm\"\n probs = []\n # RUN AND MEASURE ALL n QUBITS, TO DETERINE PROBABILITY OF ALL 2^n STATES\n return probs\n \n \n #def get_string():\n # Compute the most probable string.\n \n###################################################################################################################\n\nimport networkx as nx\n\ndef graph_to_pqasm(g):\n # Specific for Max-Cut Hamiltonian\n # PauliTerm to Gates concept from rigetti/pyquil/pyquil/paulis.py\n coeffs = [] # Weights for the angle parameter for each gate\n angle_id = []\n sZ = np.array([[1,0],[0,-1]])\n sX = np.array([[0,1],[1,0]])\n I = np.eye(2) \n H_cost = np.kron(I,np.kron(I,I))\n H_cost = np.dot(np.kron(I,np.kron(I,sZ)),H_cost)\n H_cost = np.dot(np.kron(I,np.kron(sZ,I)),H_cost)\n H_cost = np.dot(np.kron(I,np.kron(I,sX)),H_cost)\n H_cost = np.dot(np.kron(I,np.kron(sZ,I)),H_cost)\n H_cost = np.dot(np.kron(sZ,np.kron(I,I)),H_cost)\n H_cost = np.dot(np.kron(I,np.kron(sX,I)),H_cost)\n #print(H_cost)\n t_name = \"test_output/graph.qasm\"\n ansatz = open(t_name,\"w\") \n for i,j in g.edges():\n # 0.5*Z_i*Z_j\n ansatz.write(\"cnot q\"+str(i)+\",q\"+str(j)+\"\\n\")\n ansatz.write(\"rz q\"+str(i)+\",*\\n\")\n coeffs.append(2*0.5)\n angle_id.append(0) # beta\n ansatz.write(\"cnot q\"+str(i)+\",q\"+str(j)+\"\\n\")\n # -0.5*I_0\n ansatz.write(\"x q\"+str(0)+\"\\n\")\n ansatz.write(\"rz q\"+str(0)+\",*\\n\")\n coeffs.append(-1*0.5)\n angle_id.append(0) # beta\n ansatz.write(\"x q\"+str(0)+\"\\n\")\n ansatz.write(\"rz q\"+str(0)+\",*\\n\")\n coeffs.append(-1*0.5)\n angle_id.append(0) # beta\n for i in g.nodes():\n # -X_i\n ansatz.write(\"h q\"+str(i)+\"\\n\")\n ansatz.write(\"rz q\"+str(i)+\",*\\n\")\n coeffs.append(2*-1)\n angle_id.append(1) # gamma\n ansatz.write(\"h q\"+str(i)+\"\\n\")\n ansatz.close()\n return H_cost, coeffs, angle_id\n \n###################################################################################################################\n\n# Barbell graph\ng = nx.Graph()\ng.add_edge(0,1)\ng.add_edge(1,2)\nhc, coeffs, aid = graph_to_pqasm(g)\n\nsteps = 2\nqb = len(g.nodes()) # Number of qubits\nb = np.random.uniform(0, np.pi, steps) # Initial beta angle parameters of cost Hamiltonian\ng = np.random.uniform(0, 2*np.pi, steps) # Initial gamma angle parameters of driving/mixing Hamiltonian\n\n#print(qb,steps,b,g,hc,aid,coeffs)\n\nqaoa_obj = QAOA()\n\nr = qaoa_obj.get_angles(qb,steps,b,g,hc,aid,coeffs)\nprint(r.status, r.fun, r.x)\n'''\nOptimization terminated successfully.\n Current function value: 1.000000\n Iterations: 25\n Function evaluations: 149\n(array([2.32105514, 2.0138622 ]), array([2.20695693, 1.86485137]))\n'''\n\n# The last qaoa_try will have the optimal angles\nprobs = qaoa_obj.probabilities()\n#print(probs)","repo_name":"prince-ph0en1x/QWorld","sub_path":"archives/qaoa_0p1.py","file_name":"qaoa_0p1.py","file_ext":"py","file_size_in_byte":6917,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"73811684200","text":"import logging\nimport time\nfrom base64 import b64encode\nfrom operator import attrgetter\nfrom typing import Dict, Iterable, List, Optional, Union\n\nfrom boto3.resources.base import ServiceResource\nfrom boto.ec2.instance import Instance as Boto2Instance\nfrom boto.ec2.spotinstancerequest import SpotInstanceRequest\nfrom botocore.client import BaseClient\n\nfrom toil.lib.aws.session import establish_boto3_session\nfrom toil.lib.aws.utils import flatten_tags\nfrom toil.lib.exceptions import panic\nfrom toil.lib.retry import (ErrorCondition,\n get_error_code,\n get_error_message,\n old_retry,\n retry)\n\na_short_time = 5\na_long_time = 60 * 60\nlogger = logging.getLogger(__name__)\n\n\nclass UserError(RuntimeError):\n def __init__(self, message=None, cause=None):\n if (message is None) == (cause is None):\n raise RuntimeError(\"Must pass either message or cause.\")\n super().__init__(\n message if cause is None else cause.message)\n\n\ndef not_found(e):\n try:\n return get_error_code(e).endswith('.NotFound')\n except ValueError:\n # Not the right kind of error\n return False\n\ndef inconsistencies_detected(e):\n if get_error_code(e) == 'InvalidGroup.NotFound':\n return True\n m = get_error_message(e).lower()\n matches = ('invalid iam instance profile' in m) or ('no associated iam roles' in m)\n return matches\n\n# We also define these error categories for the new retry decorator\nINCONSISTENCY_ERRORS = [ErrorCondition(boto_error_codes=['InvalidGroup.NotFound']),\n ErrorCondition(error_message_must_include='Invalid IAM Instance Profile'),\n ErrorCondition(error_message_must_include='no associated IAM Roles')]\n\n\ndef retry_ec2(t=a_short_time, retry_for=10 * a_short_time, retry_while=not_found):\n return old_retry(delays=(t, t, t * 2, t * 4),\n timeout=retry_for,\n predicate=retry_while)\n\n\nclass UnexpectedResourceState(Exception):\n def __init__(self, resource, to_state, state):\n super().__init__(\n \"Expected state of %s to be '%s' but got '%s'\" %\n (resource, to_state, state))\n \ndef wait_transition(resource, from_states, to_state,\n state_getter=attrgetter('state')):\n \"\"\"\n Wait until the specified EC2 resource (instance, image, volume, ...) transitions from any\n of the given 'from' states to the specified 'to' state. If the instance is found in a state\n other that the to state or any of the from states, an exception will be thrown.\n\n :param resource: the resource to monitor\n :param from_states:\n a set of states that the resource is expected to be in before the transition occurs\n :param to_state: the state of the resource when this method returns\n \"\"\"\n state = state_getter(resource)\n while state in from_states:\n time.sleep(a_short_time)\n for attempt in retry_ec2():\n with attempt:\n resource.update(validate=True)\n state = state_getter(resource)\n if state != to_state:\n raise UnexpectedResourceState(resource, to_state, state)\n\n\ndef wait_instances_running(ec2, instances: Iterable[Boto2Instance]) -> Iterable[Boto2Instance]:\n \"\"\"\n Wait until no instance in the given iterable is 'pending'. Yield every instance that\n entered the running state as soon as it does.\n\n :param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests\n :param Iterable[Boto2Instance] instances: the instances to wait on\n :rtype: Iterable[Boto2Instance]\n \"\"\"\n running_ids = set()\n other_ids = set()\n while True:\n pending_ids = set()\n for i in instances:\n if i.state == 'pending':\n pending_ids.add(i.id)\n elif i.state == 'running':\n if i.id in running_ids:\n raise RuntimeError(\"An instance was already added to the list of running instance IDs. Maybe there is a duplicate.\")\n running_ids.add(i.id)\n yield i\n else:\n if i.id in other_ids:\n raise RuntimeError(\"An instance was already added to the list of other instances. Maybe there is a duplicate.\")\n other_ids.add(i.id)\n yield i\n logger.info('%i instance(s) pending, %i running, %i other.',\n *list(map(len, (pending_ids, running_ids, other_ids))))\n if not pending_ids:\n break\n seconds = max(a_short_time, min(len(pending_ids), 10 * a_short_time))\n logger.info('Sleeping for %is', seconds)\n time.sleep(seconds)\n for attempt in retry_ec2():\n with attempt:\n instances = ec2.get_only_instances(list(pending_ids))\n\n\ndef wait_spot_requests_active(ec2, requests: Iterable[SpotInstanceRequest], timeout: float = None, tentative: bool = False) -> Iterable[List[SpotInstanceRequest]]:\n \"\"\"\n Wait until no spot request in the given iterator is in the 'open' state or, optionally,\n a timeout occurs. Yield spot requests as soon as they leave the 'open' state.\n\n :param requests: The requests to wait on.\n\n :param timeout: Maximum time in seconds to spend waiting or None to wait forever. If a\n timeout occurs, the remaining open requests will be cancelled.\n\n :param tentative: if True, give up on a spot request at the earliest indication of it\n not being fulfilled immediately\n\n \"\"\"\n\n if timeout is not None:\n timeout = time.time() + timeout\n active_ids = set()\n other_ids = set()\n open_ids = None\n\n def cancel():\n logger.warning('Cancelling remaining %i spot requests.', len(open_ids))\n ec2.cancel_spot_instance_requests(list(open_ids))\n\n def spot_request_not_found(e):\n return get_error_code(e) == 'InvalidSpotInstanceRequestID.NotFound'\n\n try:\n while True:\n open_ids, eval_ids, fulfill_ids = set(), set(), set()\n batch = []\n for r in requests:\n if r.state == 'open':\n open_ids.add(r.id)\n if r.status.code == 'pending-evaluation':\n eval_ids.add(r.id)\n elif r.status.code == 'pending-fulfillment':\n fulfill_ids.add(r.id)\n else:\n logger.info(\n 'Request %s entered status %s indicating that it will not be '\n 'fulfilled anytime soon.', r.id, r.status.code)\n elif r.state == 'active':\n if r.id in active_ids:\n raise RuntimeError(\"A request was already added to the list of active requests. Maybe there are duplicate requests.\")\n active_ids.add(r.id)\n batch.append(r)\n else:\n if r.id in other_ids:\n raise RuntimeError(\"A request was already added to the list of other IDs. Maybe there are duplicate requests.\")\n other_ids.add(r.id)\n batch.append(r)\n if batch:\n yield batch\n logger.info('%i spot requests(s) are open (%i of which are pending evaluation and %i '\n 'are pending fulfillment), %i are active and %i are in another state.',\n *list(map(len, (open_ids, eval_ids, fulfill_ids, active_ids, other_ids))))\n if not open_ids or tentative and not eval_ids and not fulfill_ids:\n break\n sleep_time = 2 * a_short_time\n if timeout is not None and time.time() + sleep_time >= timeout:\n logger.warning('Timed out waiting for spot requests.')\n break\n logger.info('Sleeping for %is', sleep_time)\n time.sleep(sleep_time)\n for attempt in retry_ec2(retry_while=spot_request_not_found):\n with attempt:\n requests = ec2.get_all_spot_instance_requests(\n list(open_ids))\n except BaseException:\n if open_ids:\n with panic(logger):\n cancel()\n raise\n else:\n if open_ids:\n cancel()\n\n\ndef create_spot_instances(ec2, price, image_id, spec, num_instances=1, timeout=None, tentative=False, tags=None) -> Iterable[List[Boto2Instance]]:\n \"\"\"\n Create instances on the spot market.\n \"\"\"\n def spotRequestNotFound(e):\n return getattr(e, 'error_code', None) == \"InvalidSpotInstanceRequestID.NotFound\"\n\n for attempt in retry_ec2(retry_for=a_long_time,\n retry_while=inconsistencies_detected):\n with attempt:\n requests = ec2.request_spot_instances(\n price, image_id, count=num_instances, **spec)\n\n if tags is not None:\n for requestID in (request.id for request in requests):\n for attempt in retry_ec2(retry_while=spotRequestNotFound):\n with attempt:\n ec2.create_tags([requestID], tags)\n\n num_active, num_other = 0, 0\n # noinspection PyUnboundLocalVariable,PyTypeChecker\n # request_spot_instances's type annotation is wrong\n for batch in wait_spot_requests_active(ec2,\n requests,\n timeout=timeout,\n tentative=tentative):\n instance_ids = []\n for request in batch:\n if request.state == 'active':\n instance_ids.append(request.instance_id)\n num_active += 1\n else:\n logger.info(\n 'Request %s in unexpected state %s.',\n request.id,\n request.state)\n num_other += 1\n if instance_ids:\n # This next line is the reason we batch. It's so we can get multiple instances in\n # a single request.\n yield ec2.get_only_instances(instance_ids)\n if not num_active:\n message = 'None of the spot requests entered the active state'\n if tentative:\n logger.warning(message + '.')\n else:\n raise RuntimeError(message)\n if num_other:\n logger.warning('%i request(s) entered a state other than active.', num_other)\n\n\ndef create_ondemand_instances(ec2, image_id, spec, num_instances=1) -> List[Boto2Instance]:\n \"\"\"\n Requests the RunInstances EC2 API call but accounts for the race between recently created\n instance profiles, IAM roles and an instance creation that refers to them.\n\n :rtype: List[Boto2Instance]\n \"\"\"\n instance_type = spec['instance_type']\n logger.info('Creating %s instance(s) ... ', instance_type)\n for attempt in retry_ec2(retry_for=a_long_time,\n retry_while=inconsistencies_detected):\n with attempt:\n return ec2.run_instances(image_id,\n min_count=num_instances,\n max_count=num_instances,\n **spec).instances\n\n\ndef prune(bushy: dict) -> dict:\n \"\"\"\n Prune entries in the given dict with false-y values.\n Boto3 may not like None and instead wants no key.\n \"\"\"\n pruned = dict()\n for key in bushy:\n if bushy[key]:\n pruned[key] = bushy[key]\n return pruned\n\n\n# We need a module-level client to get the dynamically-generated error types to\n# catch, and to wait on IAM items.\niam_client = establish_boto3_session().client('iam')\n\n# exception is generated by a factory so we weirdly need a client instance to reference it\n@retry(errors=[iam_client.exceptions.NoSuchEntityException],\n intervals=[1, 1, 2, 4, 8, 16, 32, 64])\ndef wait_until_instance_profile_arn_exists(instance_profile_arn: str):\n # TODO: We have no guarantee that the ARN contains the name.\n instance_profile_name = instance_profile_arn.split(':instance-profile/')[-1]\n logger.debug(\"Checking for instance profile %s...\", instance_profile_name)\n iam_client.get_instance_profile(InstanceProfileName=instance_profile_name)\n logger.debug(\"Instance profile found\")\n\n\n@retry(intervals=[5, 5, 10, 20, 20, 20, 20], errors=INCONSISTENCY_ERRORS)\ndef create_instances(ec2_resource: ServiceResource,\n image_id: str,\n key_name: str,\n instance_type: str,\n num_instances: int = 1,\n security_group_ids: Optional[List] = None,\n user_data: Optional[Union[str, bytes]] = None,\n block_device_map: Optional[List[Dict]] = None,\n instance_profile_arn: Optional[str] = None,\n placement_az: Optional[str] = None,\n subnet_id: str = None,\n tags: Optional[Dict[str, str]] = None) -> List[dict]:\n \"\"\"\n Replaces create_ondemand_instances. Uses boto3 and returns a list of Boto3 instance dicts.\n\n See \"create_instances\" (returns a list of ec2.Instance objects):\n https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances\n Not to be confused with \"run_instances\" (same input args; returns a dictionary):\n https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.run_instances\n\n Tags, if given, are applied to the instances, and all volumes.\n \"\"\"\n logger.info('Creating %s instance(s) ... ', instance_type)\n\n if isinstance(user_data, str):\n user_data = user_data.encode('utf-8')\n\n request = {'ImageId': image_id,\n 'MinCount': num_instances,\n 'MaxCount': num_instances,\n 'KeyName': key_name,\n 'SecurityGroupIds': security_group_ids,\n 'InstanceType': instance_type,\n 'UserData': user_data,\n 'BlockDeviceMappings': block_device_map,\n 'SubnetId': subnet_id}\n\n if instance_profile_arn:\n # We could just retry when we get an error because the ARN doesn't\n # exist, but we might as well wait for it.\n wait_until_instance_profile_arn_exists(instance_profile_arn)\n\n # Add it to the request\n request['IamInstanceProfile'] = {'Arn': instance_profile_arn}\n\n if placement_az:\n request['Placement'] = {'AvailabilityZone': placement_az}\n\n if tags:\n # Tag everything when we make it.\n flat_tags = flatten_tags(tags)\n request['TagSpecifications'] = [{'ResourceType': 'instance', 'Tags': flat_tags},\n {'ResourceType': 'volume', 'Tags': flat_tags}]\n\n return ec2_resource.create_instances(**prune(request))\n\n@retry(intervals=[5, 5, 10, 20, 20, 20, 20], errors=INCONSISTENCY_ERRORS)\ndef create_launch_template(ec2_client: BaseClient,\n template_name: str,\n image_id: str,\n key_name: str,\n instance_type: str,\n security_group_ids: Optional[List] = None,\n user_data: Optional[Union[str, bytes]] = None,\n block_device_map: Optional[List[Dict]] = None,\n instance_profile_arn: Optional[str] = None,\n placement_az: Optional[str] = None,\n subnet_id: Optional[str] = None,\n tags: Optional[Dict[str, str]] = None) -> str:\n \"\"\"\n Creates a launch template with the given name for launching instances with the given parameters.\n\n We only ever use the default version of any launch template.\n\n Internally calls https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html?highlight=create_launch_template#EC2.Client.create_launch_template\n\n :param tags: Tags, if given, are applied to the template itself, all instances, and all volumes.\n :param user_data: non-base64-encoded user data to pass to the instances.\n\n\n :return: the ID of the launch template.\n\n\n \"\"\"\n logger.info('Creating launch template for %s instances ... ', instance_type)\n\n if isinstance(user_data, str):\n # Make sure we have bytes\n user_data = user_data.encode('utf-8')\n\n # Then base64 and decode back to str.\n user_data = b64encode(user_data).decode('utf-8')\n\n template = {'ImageId': image_id,\n 'KeyName': key_name,\n 'SecurityGroupIds': security_group_ids,\n 'InstanceType': instance_type,\n 'UserData': user_data,\n 'BlockDeviceMappings': block_device_map,\n 'SubnetId': subnet_id}\n\n if instance_profile_arn:\n # We could just retry when we get an error because the ARN doesn't\n # exist, but we might as well wait for it.\n wait_until_instance_profile_arn_exists(instance_profile_arn)\n\n # Add it to the request\n template['IamInstanceProfile'] = {'Arn': instance_profile_arn}\n\n if placement_az:\n template['Placement'] = {'AvailabilityZone': placement_az}\n\n if tags:\n # Tag everything when we make it.\n flat_tags = flatten_tags(tags)\n template['TagSpecifications'] = [{'ResourceType': 'instance', 'Tags': flat_tags},\n {'ResourceType': 'volume', 'Tags': flat_tags}]\n\n request = {'LaunchTemplateData': prune(template),\n 'LaunchTemplateName': template_name}\n\n if tags:\n request['TagSpecifications'] = [{'ResourceType': 'launch-template', 'Tags': flat_tags}]\n\n return ec2_client.create_launch_template(**request)['LaunchTemplate']['LaunchTemplateId']\n\n\n@retry(intervals=[5, 5, 10, 20, 20, 20, 20], errors=INCONSISTENCY_ERRORS)\ndef create_auto_scaling_group(autoscaling_client: BaseClient,\n asg_name: str,\n launch_template_ids: Dict[str, str],\n vpc_subnets: List[str],\n min_size: int,\n max_size: int,\n instance_types: Optional[List[str]] = None,\n spot_bid: Optional[float] = None,\n spot_cheapest: bool = False,\n tags: Optional[Dict[str, str]] = None) -> None:\n\n \"\"\"\n Create a new Auto Scaling Group with the given name (which is also its\n unique identifier).\n\n :param autoscaling_client: Boto3 client for autoscaling.\n :param asg_name: Unique name for the autoscaling group.\n :param launch_template_ids: ID of the launch template to make instances\n from, for each instance type.\n :param vpc_subnets: One or more subnet IDs to place instances in the group\n into. Determine the availability zone(s) instances will launch into.\n :param min_size: Minimum number of instances to have in the group at all\n times.\n :param max_size: Maximum number of instances to allow in the group at any\n time.\n :param instance_types: Use a pool over the given instance types, instead of\n the type given in the launch template. For on-demand groups, this is\n a prioritized list. For spot groups, we let AWS balance according to\n spot_strategy. Must be 20 types or shorter.\n :param spot_bid: If set, the ASG will be a spot market ASG. Bid is in\n dollars per instance hour. All instance types in the group are bid on\n equivalently.\n :param spot_cheapest: If true, use the cheapest spot instances available out\n of instance_types, instead of the spot instances that minimize\n eviction probability.\n :param tags: Tags to apply to the ASG only. Tags for the instances should\n be added to the launch template instead.\n\n\n The default version of the launch template is used.\n \"\"\"\n\n if instance_types is None:\n instance_types = []\n\n if instance_types is not None and len(instance_types) > 20:\n raise RuntimeError(f\"Too many instance types ({len(instance_types)}) in group; AWS supports only 20.\")\n\n if len(vpc_subnets) == 0:\n raise RuntimeError(\"No VPC subnets specified to launch into; not clear where to put instances\")\n\n def get_launch_template_spec(instance_type):\n \"\"\"\n Get a LaunchTemplateSpecification for the given instance type.\n \"\"\"\n return {'LaunchTemplateId': launch_template_ids[instance_type], 'Version': '$Default'}\n\n # We always write the ASG with a MixedInstancesPolicy even when we have only one type.\n # And we use a separate launch template for every instance type, and apply it as an override.\n # Overrides is the only way to get multiple instance types into one ASG; see:\n # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.create_auto_scaling_group\n # We need to use a launch template per instance type so that different\n # instance types with specified EBS storage size overrides will get their\n # storage.\n mip = {'LaunchTemplate': {'LaunchTemplateSpecification': get_launch_template_spec(next(iter(instance_types))),\n 'Overrides': [{'InstanceType': t, 'LaunchTemplateSpecification': get_launch_template_spec(t)} for t in instance_types]}}\n\n if spot_bid is not None:\n # Ask for spot instances by saying everything above base capacity of 0 should be spot.\n mip['InstancesDistribution'] = {'OnDemandPercentageAboveBaseCapacity': 0,\n 'SpotAllocationStrategy': 'capacity-optimized' if not spot_cheapest else 'lowest-price',\n 'SpotMaxPrice': str(spot_bid)}\n\n asg = {'AutoScalingGroupName': asg_name,\n 'MixedInstancesPolicy': prune(mip),\n 'MinSize': min_size,\n 'MaxSize': max_size,\n 'VPCZoneIdentifier': ','.join(vpc_subnets)}\n\n if tags:\n # Tag the ASG itself.\n asg['Tags'] = flatten_tags(tags)\n\n logger.debug(\"Creating Autoscaling Group across subnets: %s\", vpc_subnets)\n\n # Don't prune the ASG because MinSize and MaxSize are required and may be 0.\n autoscaling_client.create_auto_scaling_group(**asg)\n","repo_name":"DataBiosphere/toil","sub_path":"src/toil/lib/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":22519,"program_lang":"python","lang":"en","doc_type":"code","stars":856,"dataset":"github-code","pt":"18"} +{"seq_id":"73040095082","text":"\"\"\"This module installs some napari-specific types in magicgui, if present.\n\nmagicgui is a package that allows users to create GUIs from python functions\nhttps://magicgui.readthedocs.io/en/latest/\n\nIt offers a function ``register_type`` that allows developers to specify how\ntheir custom classes or types should be converted into GUIs. Then, when the\nend-user annotates one of their function arguments with a type hint using one\nof those custom classes, magicgui will know what to do with it.\n\n\"\"\"\nimport weakref\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type\n\nfrom .. import layers, types\nfrom ..utils.misc import ensure_list_of_layer_data_tuple\nfrom ..viewer import Viewer\n\ntry:\n from magicgui import register_type\nexcept ImportError:\n\n def register_type(*args, **kwargs):\n pass\n\n\nif TYPE_CHECKING:\n from magicgui.widgets._bases import CategoricalWidget\n\n\ndef register_types_with_magicgui():\n \"\"\"Register napari types with magicgui.\n\n Parameter Annotations -> Widgets:\n napari.layers.Layer, will be rendered as a ComboBox.\n if a parameter is annotated as a subclass Layer type, then the\n combobox options will be limited to that layer type.\n napari.Viewer, will be rendered as a ComboBox, with the current viewer\n as the only choice.\n\n Return Annotations -> Widgets:\n napari.layers.Layer will add a new layer to the Viewer.\n if a return is annotated as a subclass of Layer, then the\n corresponding layer type will be added. As of 0.4.3, the user\n must return an actual layer instance\n see `add_layer_to_viewer` for detail\n napari.types.Data will add a new layer to the Viewer.\n using a bare data array (e.g. numpy array) as a return value.\n napari.types.LayerDataTuple will add a new layer to the Viewer.\n and expects the user to return a single layer data tuple\n List[napari.types.LayerDataTuple] will add multiple new layer to the\n Viewer. And expects the user to return a list of layer data tuples.\n\n \"\"\"\n register_type(\n layers.Layer, choices=get_layers, return_callback=add_layer_to_viewer\n )\n register_type(Viewer, bind=find_viewer_ancestor)\n register_type(\n types.LayerDataTuple,\n return_callback=add_layer_data_tuples_to_viewer,\n )\n register_type(\n List[types.LayerDataTuple],\n return_callback=add_layer_data_tuples_to_viewer,\n )\n for layer_name in layers.NAMES:\n data_type = getattr(types, f'{layer_name.title()}Data')\n register_type(\n data_type,\n choices=get_layers_data,\n return_callback=add_layer_data_to_viewer,\n )\n\n\ndef add_layer_data_to_viewer(gui, result, return_type):\n \"\"\"Show a magicgui result in the viewer.\n\n This function will be called when a magicgui-decorated function has a\n return annotation of one of the `napari.types.Data` ... and\n will add the data in ``result`` to the current viewer as the corresponding\n layer type.\n\n Parameters\n ----------\n gui : MagicGui or QWidget\n The instantiated MagicGui widget. May or may not be docked in a\n dock widget.\n result : Any\n The result of the function call. For this function, this should be\n *just* the data part of the corresponding layer type.\n return_type : type\n The return annotation that was used in the decorated function.\n\n Examples\n --------\n This allows the user to do this, and add the result as a viewer Image.\n\n >>> @magicgui\n ... def make_layer() -> napari.types.ImageData:\n ... return np.random.rand(256, 256)\n\n \"\"\"\n\n if result is None:\n return\n\n viewer = find_viewer_ancestor(gui)\n if not viewer:\n return\n\n try:\n viewer.layers[gui.result_name].data = result\n except KeyError:\n layer_type = return_type.__name__.replace(\"Data\", \"\").lower()\n adder = getattr(viewer, f'add_{layer_type}')\n adder(data=result, name=gui.result_name)\n\n\ndef add_layer_data_tuples_to_viewer(gui, result, return_type):\n \"\"\"Show a magicgui result in the viewer.\n\n This function will be called when a magicgui-decorated function has a\n return annotation of one of the `napari.types.Data` ... and\n will add the data in ``result`` to the current viewer as the corresponding\n layer type.\n\n Parameters\n ----------\n gui : MagicGui or QWidget\n The instantiated MagicGui widget. May or may not be docked in a\n dock widget.\n result : Any\n The result of the function call. For this function, this should be\n *just* the data part of the corresponding layer type.\n return_type : type\n The return annotation that was used in the decorated function.\n\n Examples\n --------\n This allows the user to do this, and add the result to the viewer\n\n >>> @magicgui\n ... def make_layer() -> napari.types.LayerDataTuple:\n ... return (np.ones((10,10)), {'name': 'hi'})\n\n >>> @magicgui\n ... def make_layer() -> List[napari.types.LayerDataTuple]:\n ... return [(np.ones((10,10)), {'name': 'hi'})]\n\n \"\"\"\n\n if result is None:\n return\n\n viewer = find_viewer_ancestor(gui)\n if not viewer:\n return\n\n result = result if isinstance(result, list) else [result]\n try:\n result = ensure_list_of_layer_data_tuple(result)\n except TypeError:\n raise TypeError(\n f'magicgui function {gui} annotated with a return type of '\n 'napari.types.LayerDataTuple did not return LayerData tuple(s)'\n )\n\n for layer_datum in result:\n # if the layer data has a meta dict with a 'name' key in it...\n if (\n len(layer_datum) > 1\n and isinstance(layer_datum[1], dict)\n and layer_datum[1].get(\"name\")\n ):\n # then try to update the viewer layer with that name.\n try:\n layer = viewer.layers[layer_datum[1].get('name')]\n layer.data = layer_datum[0]\n for k, v in layer_datum[1].items():\n setattr(layer, k, v)\n continue\n except KeyError: # layer not in the viewer\n pass\n # otherwise create a new layer from the layer data\n layer = viewer._add_layer_from_data(*layer_datum)\n layer._source = gui\n\n\ndef find_viewer_ancestor(widget) -> Optional[Viewer]:\n \"\"\"Return the Viewer object if it is an ancestor of ``widget``, else None.\n\n Parameters\n ----------\n widget : QWidget\n A widget\n\n Returns\n -------\n viewer : napari.Viewer or None\n Viewer instance if one exists, else None.\n \"\"\"\n # magicgui v0.2.0 widgets are no longer QWidget subclasses, but the native\n # widget is available at widget.native\n if hasattr(widget, 'native') and hasattr(widget.native, 'parent'):\n parent = widget.native.parent()\n else:\n parent = widget.parent()\n while parent:\n if hasattr(parent, 'qt_viewer'):\n return parent.qt_viewer.viewer\n parent = parent.parent()\n return None\n\n\ndef get_layers(gui: 'CategoricalWidget') -> List[layers.Layer]:\n \"\"\"Retrieve layers matching gui.annotation, from the Viewer the gui is in.\n\n Parameters\n ----------\n gui : magicgui.widgets.Widget\n The instantiated MagicGui widget. May or may not be docked in a\n dock widget.\n\n Returns\n -------\n tuple\n Tuple of layers of type ``gui.annotation``\n\n Examples\n --------\n This allows the user to do this, and get a dropdown box in their GUI\n that shows the available image layers.\n\n >>> @magicgui\n ... def get_layer_mean(layer: napari.layers.Image) -> float:\n ... return layer.data.mean()\n\n \"\"\"\n viewer = find_viewer_ancestor(gui.native)\n if not viewer:\n return ()\n return [x for x in viewer.layers if isinstance(x, gui.annotation)]\n\n\ndef get_layers_data(gui: 'CategoricalWidget') -> List[Tuple[str, Any]]:\n \"\"\"Retrieve layers matching gui.annotation, from the Viewer the gui is in.\n\n As opposed to `get_layers`, this function returns just `layer.data` rather\n than the full layer object.\n\n Parameters\n ----------\n gui : magicgui.widgets.Widget\n The instantiated MagicGui widget. May or may not be docked in a\n dock widget.\n\n Returns\n -------\n tuple\n Tuple of layer.data from layers of type ``gui.annotation``\n\n Examples\n --------\n This allows the user to do this, and get a dropdown box in their GUI\n that shows the available image layers, but just get the data from the image\n as function input\n\n >>> @magicgui\n ... def get_layer_mean(data: napari.types.ImageData) -> float:\n ... return data.mean()\n\n \"\"\"\n\n viewer = find_viewer_ancestor(gui.native)\n if not viewer:\n return ()\n\n layer_type_name = gui.annotation.__name__.replace(\"Data\", \"\").title()\n layer_type = getattr(layers, layer_type_name)\n choices = []\n for layer in [x for x in viewer.layers if isinstance(x, layer_type)]:\n choice_key = f'{layer.name} (data)'\n choices.append((choice_key, layer.data))\n layer.events.data.connect(_make_choice_data_setter(gui, choice_key))\n\n return choices\n\n\n@lru_cache(maxsize=None)\ndef _make_choice_data_setter(gui: 'CategoricalWidget', choice_name: str):\n \"\"\"Return a function that sets the ``data`` for ``choice_name`` in ``gui``.\n\n Note, using lru_cache here so that the **same** function object is returned\n if you call this twice for the same widget/choice_name combination. This is\n so that when we connect it above in `layer.events.data.connect()`, it will\n only get connected once (because .connect() will not add a specific callback\n more than once)\n \"\"\"\n gui_ref = weakref.ref(gui)\n\n def setter(event):\n _gui = gui_ref()\n if _gui is not None:\n _gui.set_choice(choice_name, event.value)\n\n return setter\n\n\ndef add_layer_to_viewer(\n gui, result: Any, return_type: Type[layers.Layer]\n) -> None:\n \"\"\"Show a magicgui result in the viewer.\n\n Parameters\n ----------\n gui : MagicGui or QWidget\n The instantiated MagicGui widget. May or may not be docked in a\n dock widget.\n result : Any\n The result of the function call.\n return_type : type\n The return annotation that was used in the decorated function.\n\n Examples\n --------\n This allows the user to do this, and add the resulting layer to the viewer.\n\n >>> @magicgui\n ... def make_layer() -> napari.layers.Image:\n ... return napari.layers.Image(np.random.rand(64, 64))\n \"\"\"\n if result is None:\n return\n\n viewer = find_viewer_ancestor(gui)\n if not viewer:\n return\n\n viewer.add_layer(result)\n","repo_name":"zzalscv2/napari","sub_path":"napari/utils/_magicgui.py","file_name":"_magicgui.py","file_ext":"py","file_size_in_byte":10955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70993056364","text":"import re\nfrom bs4 import BeautifulSoup\n\nfrom use.tools import *\n\n\n######################################################################\n######################################################################\n# the search link, without the page token.\nSEARCH_LINK = \"https://www.ouedkniss.com/annonces/?c={}&wilaya=%2C{}\"\n\n# the search link, with the page token.\nSEARCH_LINK_PAGE = \"https://www.ouedkniss.com/annonces/?c={}&wilaya=%2C{}&p={}\"\n\n# The wilaya's(means states, thats how we name it in Algeria)\nwilaya = [\n \"Adrar\", \"Chlef\", \"Laghouat\", \"Oum El Bouaghi\", \"Batna\", \"Bejaia\", \"Biskra\",\n \"Béchar\", \"Blida\", \"Bouira\", \"Tamanrasset\", \"Tébessa\", \"Tlemcen\", \"Tiaret\",\n \"Tizi Ouzou\", \"Alger\", \"Djelfa\", \"Jijel\", \"Sétif\", \"Saïda\", \"Skikda\",\n \"Sidi Bel Abbes\", \"Annaba\", \"Guelma\", \"Constantine\", \"Medea\", \"Mostaganem\", \"M'Sila\",\n \"Mascara\", \"Ouargla\", \"Oran\", \"El Bayadh\", \"Illizi\", \"Bordj Bou Arreridj\", \"Boumerdes\",\n \"El Taref\", \"Tindouf\", \"Tissemsilt\", \"El Oued\", \"Khenchela\", \"Souk Ahras\", \"Tipaza\",\n \"Mila\", \"Aïn Defla\", \"Naama\", \"Aïn Temouchent\", \"Ghardaia\", \"Relizane\"]\n\n# The wilaya's(means states, that is how we name it in Algeria)\n# this form supports\nwilayaSearch = [\n \"Adrar\", \"Chlef\", \"Laghouat\", \"Oum+El+Bouaghi\", \"Batna\", \"Bejaia\", \"Biskra\",\n \"Bechar\", \"Blida\", \"Bouira\", \"Tamanrasset\", \"Tebessa\", \"Tlemcen\", \"Tiaret\",\n \"Tizi+Ouzou\", \"Alger\", \"Djelfa\", \"Jijel\", \"Setif\", \"Saida\", \"Skikda\",\n \"Sidi+Bel+Abbes\", \"Annaba\", \"Guelma\", \"Constantine\", \"Medea\", \"Mostaganem\", \"MSila\",\n \"Mascara\", \"Ouargla\", \"Oran\", \"El+Bayadh\", \"Illizi\", \"Bordj+Bou+Arreridj\", \"Boumerdes\",\n \"El+Taref\", \"Tindouf\", \"Tissemsilt\", \"El+Oued\", \"Khenchela\", \"Souk+Ahras\", \"Tipaza\",\n \"Mila\", \"Ain+Defla\", \"Naama\", \"Ain+Temouchent\", \"Ghardaia\", \"Relizane\"]\n\n# the categories\n# \"materiaux_equipement\", \"voyage\", \"services\", \"boutiques\"\ncategory = [\n \"telephones\", \"automobiles\", \"immobilier\", \"electronique\",\n \"informatique\", \"vetements\", \"maison\", \"loisirs_divertissements\",\n \"divers\", \"materiaux_equipement\", \"voyages\", \"services\"\n]\n\n\n######################################################################\n######################################################################\ndef getImgLink(page_link):\n \"\"\"\n To extract the link that directs us to the\n phone number's image, so we can download it\n later, and extract the phone number from it.\n :param page_link:\n :return:\n \"\"\"\n html = requests.get(str(page_link), stream=True)\n html = BeautifulSoup(html.text, 'html.parser')\n\n phone_link = html.find_all(\"img\", alt=\"phone\")\n phone_link = re.findall(r'//(.*\\.jpg)', str(phone_link))\n\n if len(phone_link) != 0:\n phone_link = phone_link[0]\n return \"https://\" + str(phone_link)\n\n else:\n return \"\"\n\n\ndef getLinks(link):\n \"\"\"\n To extract the links that directs us to the\n the pages, so we can download the images that\n contains the phone numbers.\n :param link:\n :return:\n \"\"\"\n html = requests.get(link)\n html = BeautifulSoup(html.text, 'html.parser')\n\n a_link = html.find_all(\"li\", class_=\"annonce_titre\")\n\n for go in re.findall(r'href=\"(.*)\" it', str(a_link)):\n yield \"https://ouedkniss.com/\" + go\n\n\ndef fetch(cat, wl, skip=-1):\n file = open(\"try.txt\", \"a+\")\n\n counter = 0\n\n # init the process\n page_counter = 1\n out = False\n\n while out is False:\n # make the search link\n link = SEARCH_LINK_PAGE.format(cat, wl, page_counter)\n\n # the links\n links = list(getLinks(link))\n # in this case the page is not valid\n # so we go to next wilaya\n if len(links) != 0:\n try:\n for an_link in links:\n if counter <= skip:\n print(counter, \"Page::\", page_counter)\n counter += 1\n continue\n # get the image link\n img_link = getImgLink(an_link)\n\n # if the link exists, download the image\n if len(img_link) != 0:\n\n # download the image\n downloadImg(img_link, \"try/\" + \"/\" + wl + \"__\" + str(counter))\n file.write(wl + \"__\" + str(counter) + \" \" + an_link)\n file.write(\"\\n\")\n\n print(counter, \"Page::\", page_counter, \"Wilaya::\", wl, \"Category::\", cat)\n counter += 1\n else:\n continue\n except Exception as e:\n # raise e\n pass\n else:\n out = True\n continue\n\n # access the next page\n page_counter += 1\n\n\nif __name__ == '__main__':\n fetch(\"immobilier\", \"Ain+Temouchent\", 789)\n for wl in wilayaSearch[46:]:\n fetch(\"immobilier\", wl)\n","repo_name":"agcashdaum/numCollect","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25605467536","text":"# AUTHOR :Ann\n# TIME :2022/4/25 20:31\n\nfrom sklearn.datasets import load_iris\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n'''数据准备'''\n# 鸢尾花数据集\niris = load_iris()\ndata = pd.DataFrame(iris.data, columns=iris.feature_names)\nX = np.array(data.iloc[:100, [0, 1]])\ny = iris.target[:100]\ny = [-1 if i==0 else 1 for i in y]\n# 数据集可视化\n#plt.scatter(X[0:50, 0], X[0:50, 1], c=\"red\", marker=\"x\")\n#plt.scatter(X[50:100, 0], X[50:100, 1], c=\"green\")\n\n'''参数初始化'''\nw = np.array([0, 0])\nb = 0\nlearning_rate = 1\n\n'''定义损失函数'''\n\n\ndef loss_func(x, y, w, b):\n loss = y * (np.dot(w, x) + b)\n return loss\n\n\n'''梯度下降函数'''\n\n\ndef gradient_func(x, y, w, b):\n w = w + learning_rate * y * x\n b = b + learning_rate * y\n return w, b\n\n\n'''模型训练'''\n\n\ndef train(X, y, w, b):\n mistake = []\n for i, x in enumerate(X):\n loss = loss_func(x, y[i], w, b)\n if loss <= 0:\n w, b = gradient_func(x, y[i], w, b)\n mistake.append(1)\n return w, b, mistake\n\n\nsum_mistake = 1\nwhile (sum_mistake > 0):\n w, b, mistake = train(X, y, w, b)\n sum_mistake = np.sum(mistake)\nprint(\"finish\")\n\n'''可视化结果'''\nprint(\"w:\", w)\nprint(\"b:\", b)\nx = np.linspace(4, 7, 10)\ny = -(w[0] * x + b) / w[1]\nplt.plot(x, y)\nplt.scatter(X[:50, 0], X[:50, 1])\nplt.scatter(X[50:100, 0], X[50:100, 1])\nplt.xlabel('feature1')\nplt.ylabel('feature2')\nplt.show()\n\n\n\n\n","repo_name":"Lixue37/MachineLearning","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15331980775","text":"import argparse\nimport glob\nimport subprocess\nimport sys\n\nimport cv2\nimport imutils\nimport numpy as np\n\n\ndef get_screen_resolution():\n output = subprocess.Popen(\n 'xrandr | grep \"\\*\" | cut -d\" \" -f4',\n shell=True,\n stdout=subprocess.PIPE\n ).communicate()[0]\n\n resolution = output.split()[0].split(b'x')\n\n return int(resolution[0]), int(resolution[1])\n\n\ndef show_window(window_name: str, img_mat, ratio=1.8):\n res_w, res_h = get_screen_resolution()\n\n cv2.namedWindow(window_name, cv2.WINDOW_KEEPRATIO)\n cv2.resizeWindow(window_name, int(res_w // ratio), int(res_h // ratio))\n\n cv2.imshow(window_name, img_mat)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef matching_all_objects(img_source, img_template):\n img_rgb = cv2.imread(img_source)\n template = cv2.imread(img_template)\n\n w, h = img_rgb.shape[:-1]\n\n method = cv2.TM_CCOEFF_NORMED\n\n res = cv2.matchTemplate(img_rgb, template, method)\n\n threshold = 0.8\n\n loc = np.where(res >= threshold)\n\n for pt in zip(*loc[::-1]):\n print(pt)\n cv2.rectangle(template, pt, (pt[0] + w, pt[1] + h), 255, 4)\n\n return template\n\n\ndef matching_object(img_source, img_template):\n img_rgb = cv2.imread(img_source)\n template = cv2.imread(img_template)\n\n w, h = img_rgb.shape[:-1]\n\n method = cv2.TM_CCOEFF_NORMED\n\n res = cv2.matchTemplate(img_rgb, template, method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\n top_left = max_loc\n bottom_right = (top_left[0] + w, top_left[1] + h)\n\n cv2.rectangle(template, top_left, bottom_right, 255, 4)\n\n return template\n\n\ndef matching_object_2(img_source, img_template):\n method = cv2.TM_SQDIFF_NORMED\n\n small_image = cv2.imread(img_source)\n large_image = cv2.imread(img_template)\n\n result = cv2.matchTemplate(small_image, large_image, method)\n\n mn, _, mnLoc, _ = cv2.minMaxLoc(result)\n print(cv2.minMaxLoc(result))\n\n MPx, MPy = mnLoc\n\n trows, tcols = small_image.shape[:2]\n\n cv2.rectangle(\n large_image,\n (MPx, MPy),\n (MPx+tcols, MPy+trows),\n (0, 255, 0),\n 4\n )\n\n return large_image\n\n\ndef matching_object_scale(img_source, img_template):\n template = cv2.imread(img_template, 0)\n template = cv2.Canny(template, 50, 200)\n (tH, tW) = template.shape[:2]\n\n img_s = cv2.imread(img_source)\n gray = cv2.cvtColor(img_s, cv2.COLOR_BGR2GRAY)\n found = None\n\n for scale in np.linspace(0.2, 1.0, 30)[::-1]:\n resized = imutils.resize(gray, width=int(gray.shape[1] * scale))\n ratio = gray.shape[1] / float(resized.shape[1])\n\n # print(resized.shape, ratio)\n if resized.shape[0] < tH or resized.shape[1] < tW:\n break\n\n edge = cv2.Canny(resized, 50, 200)\n result = cv2.matchTemplate(edge, template, cv2.TM_CCOEFF)\n (_, max_val, _, max_loc) = cv2.minMaxLoc(result)\n\n if found is None or max_val > found[0]:\n found = (max_val, max_loc, ratio)\n\n (_, max_loc, ratio) = found\n (start_x, start_y) = (int(max_loc[0] * ratio), int(max_loc[1] * ratio))\n (end_x, end_y) = (\n int((max_loc[0] + tW) * ratio),\n int((max_loc[1] + tH) * ratio)\n )\n\n cv2.rectangle(\n img_s,\n (start_x, start_y),\n (end_x, end_y),\n (0, 0, 255),\n 2\n )\n\n return img_s\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--source', required=True, help='Image source')\n parser.add_argument('-t', '--template', required=True,\n help='Image template')\n args = parser.parse_args()\n\n source_path = args.source\n template_path = args.template\n\n # result = matching_object(source_path, template_path)\n result = matching_object_scale(source_path, template_path)\n\n show_window('Output', result)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"demetriushenry/opencv-python-samples","sub_path":"obj_detector_matching.py","file_name":"obj_detector_matching.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25898045394","text":"def main():\n \n my_dict = {}\n\n for i in range (1, 101):\n if i % 3 != 0:\n my_dict[i] = i**3\n\n print('\\n--Print normal dict--')\n print(my_dict)\n\n challenge_dict = {i: i**3 for i in range(1, 101) if i % 3 != 0}\n\n print('\\n--Print as Dict. Comprehension--')\n print(challenge_dict)\n\n print('\\n--Print as Dict. Comprehension with Key, Value--')\n\n for key, value in challenge_dict:\n print(f'{key} - {value}')\n\nif __name__ == '__main__':\n main()","repo_name":"Daviixo/Platzi_Python","sub_path":"dict_comprehensions.py","file_name":"dict_comprehensions.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37637985488","text":"from rest_framework import serializers\n\nfrom .models import User\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = (\n 'id',\n 'phone',\n 'email',\n 'first_name',\n 'last_name',\n 'manager'\n )\n\n\nclass UserManageSerializer(serializers.ModelSerializer):\n flats_count = serializers.ReadOnlyField()\n subscription = serializers.DateField(format='%d.%m.%Y', input_formats=['%d.%m.%Y'])\n date_joined = serializers.DateTimeField(format='%d.%m.%Y %H:%M', input_formats=['%d.%m.%Y %H:%M'])\n\n class Meta:\n model = User\n fields = (\n 'id',\n 'phone',\n 'email',\n 'is_active',\n 'subscription',\n 'manager',\n 'date_joined',\n 'first_name',\n 'last_name',\n 'comment',\n 'flats_count'\n )\n","repo_name":"nyxdeveloper/realty_calendar","sub_path":"authentication/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27582254390","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 1 21:33:32 2022\n\n@author: Dallas McAllister\n\"\"\"\n#source code\n#https://www.youtube.com/watch?v=xREnpVUbkFI\n#Dr. Hu's code for SCC called scc.py\n#Dr. Hu's code for topological order of a digraph\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport time\nimport heapq\n#import resource\nfrom itertools import groupby\nfrom collections import defaultdict\n\n#The first half of the program creates the DiGraph\n# Use same seed for each generation (don't randomize)\nseed = 4\nnp.random.seed(seed)\n\nG = nx.DiGraph()\n#setting the edges of the graph\nG.add_edges_from([ ('4', '12'), ('4', '1'), ('1', '3')])\n\n#the inner edges of the graph\nG.add_edges_from([ ('4', '2'), ('2', '1'), ('3', '2')])\n\n#the outer edges of the graph\nG.add_edges_from([ ('3', '5'), ('5', '6'), ('6', '7')])\n\n#the inner edges of the graph\nG.add_edges_from([ ('5', '8'), ('6', '8'), ('8', '10')])\nG.add_edges_from([ ('8', '9'), ('9', '5'), ('9', '11')])\n\n#the outer edges of the graph\nG.add_edges_from([ ('7', '10'), ('10', '11'), ('11', '12')])\n\n#displaying the graph\npos = nx.spring_layout(G)\nnx.draw_networkx_nodes(G, pos, node_size=200)\nnx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='black')\nnx.draw_networkx_labels(G, pos)\nplt.show()\n#This marks the end of the first half of the program\n\n\n#The second half of this program shows the strongly connected components\nclass Tracker(object):\n \"\"\"Keeps track of the current time, current source, component leader,\n finish time of each node and the explored nodes.\n \n 'self.leader' is informs of {node: leader, ...}.\"\"\"\n\n def __init__(self):\n self.current_time = 0\n self.current_source = None\n self.leader = {}\n self.finish_time = {}\n self.explored = set()\n \ndef dfs(graph_dict, node, tracker):\n \"\"\"Inner loop explores all nodes in a SCC. Graph represented as a dict,\n {tail: [head_list], ...}. Depth first search runs recursively and keeps\n track of the parameters\"\"\"\n\n tracker.explored.add(node)\n tracker.leader[node] = tracker.current_source\n for head in graph_dict[node]:\n if head not in tracker.explored:\n dfs(graph_dict, head, tracker)\n tracker.current_time += 1\n tracker.finish_time[node] = tracker.current_time\n \ndef dfs_loop(graph_dict, nodes, tracker):\n \"\"\"Outer loop checks out all SCCs. Current source node changes when one\n SCC inner loop finishes.\"\"\"\n\n for node in nodes:\n if node not in tracker.explored:\n tracker.current_source = node\n dfs(graph_dict, node, tracker)\n \ndef graph_reverse(graph):\n \"\"\"Given a directed graph in forms of {tail:[head_list], ...}, compute\n a reversed directed graph, in which every edge changes direction.\"\"\"\n\n reversed_graph = defaultdict(list)\n for tail, head_list in graph.items():\n for head in head_list:\n reversed_graph[head].append(tail)\n return reversed_graph\n\ndef scc(graph):\n \"\"\"First runs dfs_loop on reversed graph with nodes in decreasing order,\n then runs dfs_loop on original graph with nodes in decreasing finish\n time order(obtained from first run). Return a dict of {leader: SCC}.\"\"\"\n\n out = defaultdict(list)\n tracker1 = Tracker()\n tracker2 = Tracker()\n nodes = set()\n reversed_graph = graph_reverse(graph)\n for tail, head_list in graph.items():\n nodes |= set(head_list)\n nodes.add(tail)\n nodes = sorted(list(nodes), reverse=True)\n dfs_loop(reversed_graph, nodes, tracker1)\n sorted_nodes = sorted(tracker1.finish_time,\n key=tracker1.finish_time.get, reverse=True)\n dfs_loop(graph, sorted_nodes, tracker2)\n for lead, vertex in groupby(sorted(tracker2.leader, key=tracker2.leader.get),\n key=tracker2.leader.get):\n out[lead] = list(vertex)\n return out\ndef main():\n start = time.time()\n ''' graph = defaultdict(list)\n with open('SCC.txt') as file_in:\n #with open('test.txt') as file_in:\n for line in file_in:\n x = line.strip().split()\n x1, x2 = int(x[0]), int(x[1])\n graph[x1].append(x2)'''\n graph = {\n '1': set(['3']),\n '2': set(['1']),\n '3': set(['2', '5']),\n '4': set(['1', '2', '12']),\n '5': set(['6', '8']),\n '6': set(['7','8']),\n '7': set(['10']),\n '8': set(['9', '10']),\n '9': set(['5', '11']),\n '10': set(['11']),\n '11': set(['12']),\n '12': set()\n }\n t1 = time.time() - start\n print (t1)\n groups = scc(graph)\n t2 = time.time() - start\n print (round(t2,4)) \n top_5 = heapq.nlargest(5, groups, key=lambda x: len(groups[x]))\n #sorted_groups = sorted(groups, key=lambda x: len(groups[x]), reverse=True)\n result = []\n for i in range(5):\n try:\n result.append(len(groups[top_5[i]]))\n #result.append(len(groups[sorted_groups[i]]))\n except:\n result.append(0)\n return result, groups\n\n\nif __name__ == '__main__':\n count, components = main()\nprint('Strongly connected components are:')\nfor key in components:\n print(components[key])\n#This marks the end of the second half of the program\n\n#This is the third part of the program,\n#making the graph in topological order\ndef dfs_tpl_order(graph,start,path):\n path = path + [start]\n global n\n for edge in graph[start]: \n if edge not in path:\n path = dfs_tpl_order(graph, edge,path)\n print (n, start)\n n -= 1\n return path\n \n\n# Graphing the original in topological order\ngraph = {'1': set(['3']),\n '2': set(['1']),\n '3': set(['2', '5']),\n '4': set(['1', '2', '12']),\n '5': set(['6', '8']),\n '6': set(['7','8']),\n '7': set(['10']),\n '8': set(['9', '10']),\n '9': set(['5', '11']),\n '10': set(['11']),\n '11': set(['12']),\n '12': set()}\n \nn = len(graph)\nprint('\\nTopological order starting from \\'1\\'')\nu = dfs_tpl_order(graph, '1', [])\nprint(u)\n#This marks the end of the program\n","repo_name":"Trent-Menard/Algorithms-Group-Project-3","sub_path":"Graph 2 (Directed).py","file_name":"Graph 2 (Directed).py","file_ext":"py","file_size_in_byte":6189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8168782533","text":"\nclass Hucre:\n\n def __init__(self, x,y,DNA,r,mit_sayisi,besin_mik,enerji,fotosentez_yapapilir_mi):\n self.x = x\n self.y = y\n self.DNA = DNA\n self.r = r\n self.mit_sayisi = mit_sayisi\n self.besin_mik = besin_mik\n self.enerji = enerji\n self.fotosentez_yapapilir_mi = fotosentez_yapapilir_mi\n\n def hareket_et(self,x_hareket,y_hareket):\n self.x += x_hareket\n self.y += y_hareket\n self.besin_mik -= (x_hareket+y_hareket)\n\n def beslen(self,besin):\n self.besin_mik += besin\n\n def sindir(self,besin):\n self.besin_mik -= besin\n self.enerji += besin\n\n def __str__(self) -> str:\n content = \"\"\n content += f\"Konum : \\nx: {self.x}\\ny: {self.y}\"\n content += f\"\\nBesin: {self.besin_mik}\"\n return content\n\nh1 = Hucre(10,7,\"ATGGTAAAAT\",4,10,415,49,True)\nh2 = Hucre(3,1,\"TTTTTAATTGA\",2,11,45,100,False)\nh3 = Hucre(13,100,\"TTTTTAATTGA\",2,11,45,100,False)\n\nprint(\"H1: \",h1)\nprint(\"H2: \",h2)\nprint(\"H3: \",h3)\n\nh2.hareket_et(3,1)\nh1.hareket_et(10,4)\n\nh1.beslen(1000)\n\n\nprint(\"H1: \",h1)\nprint(\"H2: \",h2)\nprint(\"H3: \",h3)\n","repo_name":"eminkartci/HucreBolunmesi","sub_path":"src/Hucre.py","file_name":"Hucre.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22411084474","text":"def level(string, lst=None):\n '''\n Parse new level by extracting paired ().\n :\n >>> level\"(1&(18|22))|(13&22)\"\n ['1&(18|22)', '13&22']\n '''\n\n if lst is None:\n lst = []\n\n while '(' in string:\n i = string.find('(')+1\n index = i\n step = 1\n\n while step != 0:\n if string[index] == '(':\n step += 1\n elif string[index] == ')':\n step -= 1\n index += 1\n\n lst.append(string[i:index - 1])\n string = string[index:]\n\n return lst\n\n\ndef amp(string):\n '''\n Combine integer preceeding '&' with all of level.\n :\n >>> amp('1&(18|22)')\n ['1&18|22']\n '''\n\n lst = []\n\n i = string.find('&(')\n tmp = string[0:i]\n child = []\n level(string[i:], child)\n\n lst.extend('{0}&{1}'.format(tmp, i) for i in child)\n\n return lst\n\n\ndef pipe(string):\n '''\n Splits pipe and combines amp with all in pipe.\n :\n >>> pipe('1&18|22')\n ['1&18', '1&22']\n '''\n\n lst = []\n\n if '&' not in string:\n lst += string.split('|')\n\n else:\n i = string.rfind('&')\n tmp = string[:i]\n child = string[i+1:].split('|')\n lst.extend('{0}&{1}'.format(tmp, e) for e in child)\n\n return lst\n\n\n# PARSER\n# ------\n\n\ndef parse(string):\n '''\n Processes current level, with '(' starting new level,\n '&(' starting new level with hierarchy, while '|' being\n within a level.\n '''\n\n if string[0] == '(':\n return level(string)\n\n elif '&(' in string:\n return amp(string)\n\n else:\n return pipe(string)\n\n\n# RECURSE\n# -------\n\n\ndef flatten(string):\n '''\n Recursively flattens clustered levels.\n string -- mod position string in hierarchical format\n\n >>> flatten(\"((1&(18|22))|(13&22))\")\n ['1&18', '1&22', '13&22']\n '''\n\n if (string[0] != '(') and not ('&(' in string or '|' in string):\n return [string]\n\n else:\n child = parse(string)\n lst = []\n for string in child:\n lst.extend(flatten(string))\n return lst\n","repo_name":"Alexhuszagh/XLDiscoverer","sub_path":"xldlib/xlpy/matched/protein_prospector/hierarchical.py","file_name":"hierarchical.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36834713665","text":"print(\"\\n\\n----------------------- 4 COMPLEX EXAMPLES - RECURSION -------------------\")\n\n\nprint(\"\\n\\n----------------------- 1. Example - Recursion ---------------------------\")\nprint(\"a.) Factorial\")\n# 120\nresult_fact = 1\ndef factorial_recursion_01(x):\n global result_fact\n result_fact *= x\n x -= 1\n if x > 0:\n factorial_recursion_01(x)\n else:\n print(result_fact)\nfactorial_recursion_01(5) \n\n\nprint(\"\\nb.) Factorial\")\n# 120\ndef factorial_recursion_02(y):\n if y == 0:\n return 1\n else:\n return y * factorial_recursion_02(y - 1)\nprint(factorial_recursion_02(5))\n\n\n\nprint(\"\\n\\n----------------------- 2. Example - Recursion ---------------------------\")\nprint(\"a.) Division of two numbers\")\n# 100\n# 50.0\n# 25.0\n# 12.5\n# 6.25\n# 3.125\n# 1.5625\ndef division_recursion_01(x):\n print(x)\n x = x / 2\n if x >= 1:\n division_recursion_01(x)\ndivision_recursion_01(100)\n\n\nprint(\"\\nb.) Division of two numbers\")\n# 3\ndef division_recursion_02(x, y):\n if x < y:\n return 0\n else:\n return 1 + division_recursion_02(x - y, y)\nprint(division_recursion_02(15, 5))\n\n\n\nprint(\"\\n\\n----------------------- 3. Example - Recursion ---------------------------\")\nprint(\"a.) Print Characters from the Front of a String\")\n# P\n# a\n# v\n# o\n# l\nx_add = 0\ndef char_from_front_01(my_string):\n global x_add\n print(my_string[x_add])\n x_add += 1\n if x_add < len(my_string):\n char_from_front_01(my_string)\nchar_from_front_01(\"Pavol\")\n\n\nprint(\"\\nb.) Print Characters from the Front of a String\")\n# Pavol\nxx_add = 0\nresult_string_front = \"\"\ndef char_from_front_02(my_string):\n global xx_add, result_string_front\n result_string_front += my_string[xx_add]\n xx_add += 1\n if xx_add < len(my_string):\n char_from_front_02(my_string)\n else:\n print(result_string_front)\nchar_from_front_02(\"Pavol\")\n\n\nprint(\"\\nc.) Print Characters from the Front of a String\")\n# John\ndef char_from_front_03(param_string):\n x = len(param_string)\n if x > 0:\n print(param_string[0], end=\"\")\n char_from_front_03(param_string[1:x])\nchar_from_front_03(\"John\")\n\n\n\nprint(\"\\n\\n\\n----------------------- 4. Example - Recursion ---------------------------\")\nprint(\"a.) Print Characters from the Back of a String\")\n# l\n# o\n# v\n# a\n# P\ny_add = 0\ndef char_from_back_01(my_string):\n global y_add\n y_add += 1\n index_from_back = len(my_string) - y_add\n \n char_string = my_string[index_from_back]\n print(char_string)\n\n if index_from_back > 0:\n char_from_back_01(my_string)\nchar_from_back_01(\"Pavol\")\n\n\nprint(\"\\nb.) Print Characters from the Back of a String\")\n# lovaP\nyy_add = 0\nresult_string_back = \"\"\ndef char_from_back_02(my_string):\n global yy_add, result_string_back\n \n yy_add += 1\n index_from_back = len(my_string) - yy_add\n \n char_string = my_string[index_from_back]\n result_string_back += char_string\n \n if index_from_back > 0:\n char_from_back_02(my_string)\n else:\n print(result_string_back)\nchar_from_back_02(\"Pavol\")\n\n\nprint(\"\\nc.) Print Characters from the Back of a String\")\n# lovaP\ndef char_from_back_03(word):\n x = len(word)\n if x > 1:\n char_from_back_03(word[1:x]) \n print(word[0], end=\"\")\nchar_from_back_03(\"Pavol\")\n# Pavol x=5 Pavol[1:5]=avol, avol x=4 avol[1:4], vol x=3 vol[1:3], ol x=2 ol[1:2], l x=1 \n# lovaP \n\n\nprint(\"\\n\\nd.) Print Characters from the Back of a String\")\n# nhoJ\ndef char_from_back_03(param_string):\n x = len(param_string)\n if x > 0:\n print(param_string[-1], end=\"\")\n char_from_back_03(param_string[0:-1])\nchar_from_back_03(\"John\")\n# John[-1]=n, Joh[-1]=h, Jo[-1]=o, J[-1]=J \n# nhoJ \n\n\n\nprint(\"\\n\")\n","repo_name":"PavolMilcik/programming-concepts-in-python","sub_path":"recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"29662813275","text":"#!/usr/bin/env python\n# coding:utf-8\n\nimport re\nimport os\nimport sys\nimport datetime\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))) )\n\nfrom modules.HttpClient import HttpClient\nfrom modules.ORM import ORM\n\n\nhttp = HttpClient()\ndb = ORM('./sqlite/movie.db')\nbody = http.setUrl(sys.argv[1]).sendGet()\nmovie_id = sys.argv[2]\nnow = datetime.datetime.today()\nnow = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\ntry:\n re.search('id=\\\"pagetitle\\\"', body).group(1)\nexcept:\n try:\n title = re.search('id=\\\"video_title\\\">(.+?)', body).group(1)\n data = db.select().table('movie').where({'id = ' : movie_id}).fetchAll()\n #まともな抜き出しからわからぬ\n for value in data:\n old_title = value['title']\n if title == old_title:\n raise error('error')\n except:\n exit()\n\n\ndb.delete('movie') \\\n .where({'id = ' : movie_id}) \\\n .deleteExe()\n","repo_name":"boxkot/erothon","sub_path":"_cli/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16081920568","text":"#!/usr/bin/env python3.4\n\nimport redditpaper as rp\n# must insert config here, so that it\n# works throughout both modules with onetime\n# setup\nrp.Config_logging()\nimport webbrowser\nimport os\nimport subprocess\nimport time\nimport threading\nfrom tkinter import *\nfrom tkinter import font\nfrom tkinter import StringVar\nfrom tkinter import ttk\nfrom PIL import Image\nfrom praw import errors\n\n\nclass Application(Tk):\n width = 525\n height = 555\n\n def __init__(self, master=None):\n Tk.__init__(self, master)\n\n # set title of application on titlebar\n self.wm_title(\"Reddit Paper\")\n\n # set theme\n theme = ttk.Style()\n theme.theme_use('clam')\n\n # set up frame to hold widgets\n root = Frame(self) # background=\"bisque\")\n root.pack(side = \"top\", fill = \"both\", expand = True)\n\n # set minsize of application\n self.setUpWindow()\n\n # set docked icon in system tray\n self.addIcon()\n\n # adds buttons and status bar for main page\n self.buttons = AddButtons(root, self)\n\n StatusBar(master)\n\n # window used to pack the pages into\n self.window = Frame(root)#bg = \"cyan\") \n self.window.pack()\n self.pages = {}\n for F in (CurrentImg, PastImgs, Settings, About):\n frame = F(self.window, self)\n self.pages[F] = frame\n frame.grid(row = 0, column = 0, sticky = \"nsew\")\n\n # frame to show on startup\n self.show_frame(CurrentImg)\n\n def show_frame(self, page):\n \"\"\"\n Input: the page to display\n Output: displays the page selected on button click\n \"\"\"\n frame = self.pages[page]\n # sets the focus on the itemFrame when the\n # PastImgs button is clicked so that the\n # list of pictures is scrollable\n if page is PastImgs:\n try:\n frame.canvas.focus_set()\n # Throws attribute error and also a _tkinter.TclError\n # which isn't a valid keyword for some reason\n except:\n rp.log.debug(\"Could not set focus to PastImgs, likely due to \"\n \"itemFrame not being available\", exc_info = True) \n # all images are likely deleted from\n # the itemFrame\n pass\n\n self.setButtonImages(page)\n frame.tkraise()\n\n def setButtonImages(self, page):\n \"\"\"\n Sets the button images for the top of the program to change \n background color depending on which page is active\n \"\"\"\n # images named by past image (p), currentimg (c),\n # about (a), settings (s), and then whether it will\n # be clicked (_c) or unclicked (_u)\n self.c_c = PhotoImage(file = './images/c_c.png')\n self.c_u = PhotoImage(file = './images/c_u.png')\n \n self.p_c = PhotoImage(file = './images/p_c.png')\n self.p_u = PhotoImage(file = './images/p_u.png')\n \n self.s_c = PhotoImage(file = './images/s_c.png')\n self.s_u = PhotoImage(file = './images/s_u.png')\n \n self.a_c = PhotoImage(file = './images/a_c.png')\n self.a_u = PhotoImage(file = './images/a_u.png')\n\n # if page is clicked, set that image to be '_c' (clicked)\n # and set all other pages to be 'unclicked'\n if page is CurrentImg:\n self.buttons.c.config(image = self.c_c)\n self.buttons.p.config(image = self.p_u)\n self.buttons.s.config(image = self.s_u)\n self.buttons.a.config(image = self.a_u)\n\n elif page is PastImgs:\n # past images page\n self.buttons.c.config(image = self.c_u)\n self.buttons.p.config(image = self.p_c)\n self.buttons.s.config(image = self.s_u)\n self.buttons.a.config(image = self.a_u)\n\n elif page is Settings:\n # settinsg page \n self.buttons.c.config(image = self.c_u)\n self.buttons.p.config(image = self.p_u)\n self.buttons.s.config(image = self.s_c)\n self.buttons.a.config(image = self.a_u)\n \n else:\n # about page\n self.buttons.c.config(image = self.c_u)\n self.buttons.p.config(image = self.p_u)\n self.buttons.s.config(image = self.s_u)\n self.buttons.a.config(image = self.a_c)\n\n \n def addIcon(self):\n self.img = PhotoImage(file = 'images/rp_sq.png')\n self.tk.call('wm', 'iconphoto', self._w, self.img)\n \n\n def setUpWindow(self):\n \"\"\" \n Aligns the GUI to open in the middle\n of the screen(s)\n credit: https://stackoverflow.com/questions/\n 14910858/how-to-specify-where-a-tkinter-window-opens\n \"\"\"\n ws = self.winfo_screenwidth()\n hs = self.winfo_screenheight()\n self.x = (ws//2) - (self.width//2)\n self.y = (hs//2) - (self.height//2)\n self.minsize(width = self.width, height = self.height)\n self.maxsize(width = self.width, height = self.height)\n self.geometry('{}x{}+{}+{}'.format(self.width, self.height, \n self.x, self.y))\n\n\n###############################################################################\nclass AboutInfo():\n \"\"\"\n Information about the GUI version, links to static sites (reddit,\n and PayPal), and author name and information\n \"\"\"\n _version = \"1.0\"\n _author = \"Cameron Gagnon\"\n _email = \"cameron.gagnon@gmail.com\"\n _redditAcct = \"https://www.reddit.com/message/compose/?to=camerongagnon\"\n _payPalAcct = \"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&\"\\\n \"business=PKYUCH3L9HJZ6&lc=US&item_name=Cameron%20Gagnon\"\\\n \"&item_number=81140022¤cy_code=USD&bn=PP%2dDonations\"\\\n \"BF%3abtn_donateCC_LG%2egif%3aNonHosted\"\n _github = \"https://github.com/cameron-gagnon/reddit-paper\"\n _subreddit = \"https://www.reddit.com/r/reddit_paper\"\n\n def version():\n return AboutInfo._version\n\n def author():\n return AboutInfo._author\n\n def reddit():\n return AboutInfo._redditAcct\n\n def subreddit():\n return AboutInfo._subreddit\n\n def PayPal():\n return AboutInfo._payPalAcct\n\n def email():\n return AboutInfo._email\n\n def GitHub():\n return AboutInfo._github\n\n\n################################################################################\nclass Fonts():\n _VERDANA = \"Verdana\"\n _CURSOR = \"hand2\"\n _HYPERLINK = \"#0000EE\"\n _XL = 16\n _L = 12\n _M = 10\n _S = 8\n _XS = 7\n _H1 = 25\n\n def XS():\n xs = font.Font(family = Fonts._VERDANA, size = Fonts._XS)\n return xs\n def XS_U():\n xs_u = font.Font(family = Fonts._VERDANA, size = Fonts._XS,\n underline = True)\n return xs_u\n\n def S():\n s = font.Font(family = Fonts._VERDANA, size = Fonts._S)\n return s\n def S_U():\n s_u = font.Font(family = Fonts._VERDANA, size = Fonts._S,\n underline = True)\n return s_u\n\n def M():\n m = font.Font(family = Fonts._VERDANA, size = Fonts._M)\n return m\n def M_U():\n med_u = font.Font(family = Fonts._VERDANA, size = Fonts._M,\n underline = True)\n return med_u\n\n def L():\n l = font.Font(family = Fonts._VERDANA, size = Fonts._L)\n return l\n def L_U():\n l_u = font.Font(family = Fonts._VERDANA, size = Fonts._L,\n underline = True)\n return l_u\n\n def XL():\n xl = font.Font(family = Fonts._VERDANA, size = Fonts._XL)\n return xl\n def XL_U():\n xl_u = font.Font(family = Fonts._VERDANA, size = Fonts._XL,\n underline = True)\n return xl_u\n\n def H1():\n h1 = font.Font(family = Fonts._VERDANA, size = Fonts._H1)\n return h1\n def H1_U():\n h1_u = font.Font(family = Fonts._VERDANA, size = Fonts._H1,\n underline = True)\n return h1_u\n\n\n######################## Classes for Messages #################################\nclass Message(Toplevel):\n\n def __init__(self, master, title):\n \"\"\"\n Creates popup as Toplevel() and sets its title in the window \n \"\"\"\n Toplevel.__init__(self, master)\n #self.popup = Toplevel() \n self.wm_title(title)\n self.addIcon('images/rp_sq.png')\n self.set_dimensions(master, 400, 400)\n self.inner_frame = Frame(self, width = 400, height = 400)\n self.inner_frame.pack()\n\n# self.pack_button()\n # bit of a hack to ensure that the window has grab_set applied to it \n # this is because the window may not be there when self.grab_set() is\n # called, so we wait until it happens without an error\n while True:\n try:\n self.grab_set()\n except TclError:\n pass\n else:\n break\n\n def set_dimensions(self, master, w, h):\n \"\"\"\n Sets the position and size on screen for the popup\n \"\"\"\n x = master.winfo_rootx()\n y = master.winfo_rooty()\n x = (Application.width // 2) + x - (w // 2) - 10\n y = (Application.height // 2) + y - 405\n # set permanent dimensions of popup\n self.minsize(width = w, height = h)\n self.maxsize(width = w, height = h)\n self.geometry('{}x{}+{}+{}'.format(w, h, x, y))\n\n def delete(self):\n \"\"\"\n Destroys the popup\n \"\"\"\n self.grab_release()\n self.destroy()\n\n def pack_label(self, text, pady = 8, font = None, anchor = \"center\",\n justify = None):\n \"\"\"\n Packs a label into the popup with the specified text\n \"\"\"\n # bit of a hack since Fonts.L() throws an error if present in the\n # function declaration\n if not font:\n font = Fonts.M()\n\n label = ttk.Label(self.inner_frame, anchor = anchor,\n text = text, wraplength = 420,\n font = font, justify = justify)\n label.pack(side = \"top\", fill = \"x\", pady = pady)\n\n def pack_button(self, pady = (10, 10)):\n \"\"\"\n Place a button at the bottom of the widget with the text \"Okay\"\n \"\"\"\n b = ttk.Button(self.inner_frame, text = \"Okay\", command = self.delete)\n b.pack(side = \"bottom\", pady = pady)\n\n def addIcon(self, file_name):\n \"\"\"\n Adds an error icon to the popup box\n \"\"\"\n self.img = PhotoImage(file = file_name)\n self.tk.call('wm', 'iconphoto', self._w, self.img)\n\n\nclass ErrorMsg(Message):\n\n def __init__(self, master, text, title = \"Error!\"):\n popup = Message.__init__(self, master, title)\n length = 0\n height = 0\n self.addIcon('images/error.png')\n\n if isinstance(text, list):\n if len(text) == 1:\n # if string, return length of string\n length = len(text[0])\n height = 130\n height += length // 60 * 15\n rp.log.debug(\"Length of error string is: {}, \"\n \"and height is: {}\".format(length, height))\n elif len(text) > 1:\n # find max length of string in the list of errors\n length = len(max(text))\n # length of the list is num of elts in list \n # so to get the height, we take this and\n # multiply it by a constant and add a base amount\n height = len(text) * 25 + 130\n height += length // 60 * 20\n rp.log.debug(\"Length of max error string is: {} \"\n \"and height is {}\".format(length, height))\n else:\n # no errors in CLArgs\n pass\n self.pack_label(\"Invalid Argument(s):\")\n\n\n else:\n # if just a regular string that we want an error message\n length = len(text)\n height = 125\n height += len(text) // 60 * 15\n self.pack_label(\"Invalid Argument(s):\")\n self.pack_label(text)\n rp.log.debug(\"Length of error string is: {}, \"\n \"and height is: {}\".format((length, height)))\n #length * 5 because each char is probably \n # about 5 px across. + 160 for padding\n width = length * 5 + 160\n if (length * 5 + 160) > 475:\n width = 475\n\n rp.log.debug(\"Width of ErrorMsg is {}\".format(width))\n rp.log.debug(\"Height of ErrorMsg is {}\".format(height))\n self.set_dimensions(master, width, height)\n self.pack_button()\n\nclass InvalidArg(ErrorMsg):\n\n def __init__(self, master, text):\n \"\"\"\n Used spcecifically to display the CLArguments\n \"\"\"\n\n ErrorMsg.__init__(self, master, text)\n\n if len(text) > 1:\n for string in text:\n self.pack_label(string)\n elif len(text) == 1:\n self.pack_label(text[0])\n else:\n rp.log.debug(\"No errors in CLArgs\")\n\n\nclass ConfirmMsg(Message):\n\n def __init__(self, master):\n \"\"\"\n Pop up box/message for confirmation of settings/deleting settings\n \"\"\"\n Message.__init__(self, master, \"Confirm!\")\n\n width = 180\n height = 75\n self.set_dimensions(master, width, height)\n \n self.pack_label(\"Are you sure?\")\n BFrame = Frame(self)\n BFrame.pack()\n B1 = ttk.Button(BFrame, text = \"Yes\", width = 8, command = lambda: master.del_sel(self))\n B1.pack_propagate(0)\n B2 = ttk.Button(BFrame, text = \"No\", width = 8, command = self.delete)\n B2.pack_propagate(0)\n B1.pack(side = \"left\", padx = (0, 5))\n B2.pack(side = \"left\")\n\n\nclass AutoScrollbar(ttk.Scrollbar):\n # a scrollbar that hides itself if it's not needed. only\n # works if you use the grid geometry manager.\n def set(self, lo, hi):\n if float(lo) <= 0.0 and float(hi) >= 1.0:\n # grid_remove is currently missing from Tkinter!\n self.tk.call(\"grid\", \"remove\", self)\n else:\n self.grid(sticky = 'nsew')\n\n Scrollbar.set(self, lo, hi)\n def pack(self, **kw):\n raise Exception(\"cannot use pack with this widget\")\n def place(self, **kw):\n raise Exception(\"cannot use place with this widget\")\n\n\nclass ImageFormat():\n\n def strip_file_ext(self, image_name):\n \"\"\"\n Used to remove the .jpg or other ending from im.image_name\n so that we can resave the thumbnail with .png\n \"\"\"\n index = image_name.rfind('.')\n im_name = image_name[:index]\n return im_name\n\n def add_png(self, image_name):\n \"\"\"\n Appends the .png to the end of im.image_name to save the\n thumbnail with .png\n \"\"\"\n im_name = image_name + \".png\"\n return im_name\n\n\nclass StatusBar(Frame):\n\n def __init__(self, master): \n Frame.__init__(self, master)\n \"\"\"\n Represents the statusbar at the bottom of the application.\n The statusbar is set up in AddButtons()\n It reads from the settings.conf file to get the statusbar\n text and then updates accordingly.\n Executes after every second.\n \"\"\"\n # statusbar for bottom of application\n self.text = StringVar()\n self.text.set(rp.Config.statusBar())\n self.statusBar = ttk.Label(master, text = self.text.get(), border=1,\n relief = SUNKEN, anchor = \"w\")\n \n # pack the labels/frame to window\n self.statusBar.pack(side = \"bottom\", fill = \"x\", anchor = \"w\")\n self.setText()\n\n def setText(self):\n \"\"\"\n Sets the text of the status bar to the string in the \n config file 'settings.conf' \n \"\"\"\n text = rp.Config.statusBar()\n \n if text == self.text:\n pass\n else:\n self.text = text\n self.statusBar.config(text = self.text)\n \n self.after(1000, lambda: self.setText())\n\n\n###############################################################################\nclass AddButtons(Frame):\n\n def __init__(self, master, cls):\n Frame.__init__(self, master)\n self.topbar = Frame(master)#bg=\"red\")\n\n # current image button\n self.cphoto = PhotoImage(file=\"./images/c_c.png\")\n self.c = Button(self.topbar, image = self.cphoto, \n width = 125, height = 125, cursor = Fonts._CURSOR,\n command = lambda: cls.show_frame(CurrentImg))\n self.c.grid(row = 0, column = 0, sticky = \"N\")\n\n # past image button\n self.pphoto = PhotoImage(file=\"./images/p_u.png\")\n self.p = Button(self.topbar, image = self.pphoto, \n width = 125, height = 125, cursor = Fonts._CURSOR,\n command = lambda: cls.show_frame(PastImgs))\n self.p.grid(row = 0, column = 1, sticky = \"N\")\n\n # settings buttons\n self.sphoto = PhotoImage(file=\"./images/s_u.png\")\n self.s = Button(self.topbar, image = self.sphoto, \n width = 125, height = 125, cursor = Fonts._CURSOR,\n command = lambda: cls.show_frame(Settings))\n self.s.grid(row=0, column = 2, sticky = \"N\")\n\n # about buttons\n self.aphoto = PhotoImage(file=\"./images/a_u.png\")\n self.a = Button(self.topbar, image = self.aphoto, \n width = 125, height = 125, cursor = Fonts._CURSOR,\n command = lambda: cls.show_frame(About))\n self.a.grid(row = 0, column = 3, sticky = \"N\")\n\n self.topbar.pack(side = \"top\")\n\n\n# **** Current Image Page **** #\n# Shows a thumbnail of the current image set as the \n# background, with a link to that submission.\nclass CurrentImg(Frame, ImageFormat):\n\n TIMER = 3000\n\n def __init__(self, parent, controller):\n \"\"\"\n Packs the frames needed, and initiaties \n the updateFrame to continuously call itself\n \"\"\"\n Frame.__init__(self, parent)\n # pack frames/labels\n self.frame = Frame(self, width = 525, height = 400)#, bg = \"#969696\") #bg = \"magenta\")\n self.frame.pack_propagate(0)\n self.frame.pack()\n \n self.get_past_img(parent)\n self.updateTimer()\n self.updateFrame(parent)\n\n def open_link(self, link):\n \"\"\"\n Opens the link provided in the default\n webbrowser\n \"\"\"\n webbrowser.open_new(link)\n\n def get_past_img(self, parent):\n \"\"\"\n looks up the most recent wallpaper set based on the\n config file and passes that info to set_past_img\n \"\"\"\n \n self.image_name = rp.Config.lastImg() \n if self.image_name:\n rp.log.debug(\"Last Wallpaper is: %s\" % self.image_name) \n\n try:\n im = rp.DBImg(self.image_name)\n im.link\n self.set_past_img(im)\n # AttributeError is in case the image returned\n # is incomplete\n except (AttributeError, TypeError):\n rp.log.debug(\"Attribute Error in get_past_img\")\n\n else:\n rp.log.debug(\"No image set as last image in settings.conf\")\n\n def set_past_img(self, im):\n \"\"\"\n Creates the inner frame within the main frame of\n CurrentImg and packs the picture thumbnail and title\n into it.\n \"\"\"\n\n # create subframe to pack widgets into, then destroy it\n # later\n self.image_name = im.image_name\n self.subFrame = Frame(self.frame, width = 525, height = 410)\n self.subFrame.pack_propagate(0)\n self.subFrame.pack()\n \n font_to_use = Fonts.L_U()\n # set font to be smaller if title is too long\n if len(im.title) > 150:\n font_to_use = Fonts.M_U()\n \n # create title link\n self.linkLabel = ttk.Label(self.subFrame,\n text = im.title,\n font = font_to_use,\n justify = 'center',\n foreground = Fonts._HYPERLINK,\n cursor = Fonts._CURSOR,\n wraplength = 500)\n self.linkLabel.pack(pady = (35, 10), padx = 10)\n self.linkLabel.bind(\"\", lambda event: self.open_link(im.post))\n \n try: \n # create image and convert it to thumbnail\n with open(im.save_location, 'rb') as image_file:\n imThumb = Image.open(image_file)\n im.strip_file_ext()\n im.updateSaveLoc()\n imThumb.thumbnail((400, 250), Image.ANTIALIAS)\n imThumb.save(im.thumb_save_loc_C, \"PNG\")\n # apply photolabel to page to display\n self.photo = PhotoImage(file = im.thumb_save_loc_C)\n self.photoLabel = ttk.Label(self.subFrame, image = self.photo)\n self.photoLabel.pack(side = \"bottom\", expand = True)\n except FileNotFoundError:\n pass\n\n def delSubframe(self):\n \"\"\"\n Clears up the widgets that are in the frame of the main\n CurrentImg, so that we can reset all the widgets\n \"\"\"\n try:\n self.photoLabel.destroy()\n self.linkLabel.destroy()\n self.subFrame.destroy()\n except AttributeError:\n # happens when no image is set at first run of program\n pass\n\n def updateFrame(self, parent):\n \"\"\"\n Calls itself to update the frame every self.TIMER \n to update the past image if it has changed\n \"\"\"\n if self.image_name != rp.Config.lastImg():\n self.updateTimer()\n self.delSubframe()\n self.get_past_img(parent)\n try:\n self.after(self.TIMER, lambda: self.updateFrame(parent))\n except AttributeError:\n # happens when settings.conf is not created yet\n pass\n\n def updateTimer(self):\n try:\n HR, MIN = rp.Config.cycletime()\n # converts hours and min to milliseconds \n # to be used by the tkinter after() fn\n self.TIMER = int(HR * 3600000 + MIN * 60000)\n except ValueError:\n # happens when settings.conf is not created yet\n pass\n \n def __str__(self):\n return \"Current Image\"\n\n# **** Past Images Page **** #\n# Gives a listing of past submissions, with a smaller thumbnail of the image\n# and the title/resolution of the images.\n# Includes: * checkboxes to delete the images selected\n# * Scrollable list of all images downloaded/used in the past\nclass PastImgs(Frame, ImageFormat):\n\n def __init__(self, parent, controller):\n Frame.__init__(self, parent)\n \n # select all box\n self.selVar = BooleanVar()\n self.selVar.set(False)\n self.selVar.trace('w', lambda e, x, y: self.change_all(e)) \n selectBox = ttk.Checkbutton(self, text = \"Select all\", variable = self.selVar)\n selectBox.pack(anchor = 'w', pady = (15, 2), padx = (35, 10))\n\n ### begin canvas/frame/picture list\n self.picFrame = Frame(self, width = 450, height = 300)\n \n self.picFrame.grid_rowconfigure(0, weight = 1)\n self.picFrame.grid_columnconfigure(0, weight = 1)\n self.picFrame.pack()\n \n self.canvas = Canvas(self.picFrame, width = 450, height = 300)\n self.canFrame = Frame(self.canvas)\n\n self.canvas.create_window((0,0), window = self.canFrame, anchor = 'nw')\n self.canvas.pack(side=\"left\")\n self.setScroll()\n\n # POPULATE CANVAS WITH IMAGES!!!!!!!!\n self.picList = self.findSavedPictures()\n # these lists save each checkbox and frame/photo so we can\n # identify them later when they need to be destroyed\n self.frames = []\n self.already_deleted = []\n self.itemFrame = []\n picThread = threading.Thread(target=self.populate,\n args=(self.canFrame, self.picList))\n picThread.start()\n# self.populate(self.canFrame, self.picList)\n\n\n # bottom frame for buttons\n self.bottomFrame = Frame(self)\n self.delete = ttk.Button(self.bottomFrame, text = \"Delete selected\", \n state = \"normal\",\n command = lambda: ConfirmMsg(self))\n # 'delete all' button 'delete selected' button\n self.delete.pack(side = \"right\", padx = (0, 3))\n\n # packs the frame that holds the delete buttons\n self.bottomFrame.pack(side = \"bottom\", anchor = \"e\",\n pady = (0, 15), padx = (0, 27))\n ### end canvas/frame/picture list\n\n self.updatePastImgs()\n\n def setScroll(self):\n # create frame to hold scrollbar so we can\n # use grid on the scrollbar\n try:\n self.scrollFrame.destroy()\n except:\n # no scrollbar yet created\n pass\n\n self.scrollFrame = Frame(self.picFrame)\n\n # set rows and column configures so we can\n # make scrollbar take up entire row/column\n self.scrollFrame.rowconfigure(1, weight = 1)\n self.scrollFrame.columnconfigure(1, weight = 1)\n self.scroll = AutoScrollbar(self.scrollFrame,\n orient = \"vertical\",\n command = self.canvas.yview)\n\n # set scrollbar as callback to the canvas\n self.canvas.configure(yscrollcommand = self.scroll.set)\n\n # set the scrollbar to be the height of the canvas\n self.scroll.grid(sticky = 'ns', row = 1, column = 0)\n\n # set the scrollbar to be packed on the right side\n self.scrollFrame.pack(side=\"right\", fill=\"y\")\n\n # bind the picture frame to the canvas\n self.picFrame.bind(\"\", self.setFrame) \n self.setFrame()\n\n def setFrame(self, event = None):\n \"\"\" Sets the canvas dimensions and the scroll area \"\"\"\n self.canvas.configure(scrollregion = self.canvas.bbox('all'))\n\n def setKeyBinds(self, widget):\n \n \"\"\"\n Sets the binds to the keys for the canvas movements\n when adding new elts\n \"\"\"\n widget.bind(\"\", self.onMouseWheel)# up scroll\n widget.bind(\"\", self.onMouseWheel)# down scroll \n widget.bind(\"\", self.onMouseWheel)\n widget.bind(\"\", self.onMouseWheel)\n \n def onMouseWheel(self, event):\n \"\"\"\n Scrolls the canvas up or down depending on the \n event entered (arrow keys/mouse scroll)\n \"\"\"\n keyNum = {116 : 1, # Down arrow key\n 111 : -1} # Up arrow key\n scrollNum = {4 : -1,\n 5 : 1}\n scrollVal = None\n \n # up/down arrows\n if event.keycode in keyNum:\n scrollVal = keyNum.get(event.keycode)\n # scroll wheel events\n elif event.num in scrollNum:\n scrollVal = scrollNum.get(event.num) \n\n self.canvas.yview_scroll(scrollVal, \"units\")\n\n def change_all(self, event):\n \"\"\"\n selects/deselects all the pictures (to be deleted)\n \"\"\"\n if self.selVar.get():\n self.selVar.set(True)\n for box in self.frames:\n box[0].set(True)\n else:\n self.selVar.set(False)\n for box in self.frames:\n box[0].set(False)\n\n def del_sel(self, popup):\n \"\"\"\n Delete all frames that have their checkbox\n checked.\n self.frames[i][2] ## image class\n self.frames[i][2].save_location\n ## file path to original img\n '/path/to/file/jkY32rv.jpg'\n self.frames[i][2].thumb_save_loc_P \n ## file path to _P.png thumbnail \n '/path/to/file/jkY32rv_P.png'\n self.frames[i][2].thumb_save_loc_C \n ## file path to _C.png thumbnail\n '/path/to/file/jkY32rv_C.png'\n self.frames[i][2].image_name ## original img name 'jkY32rv.jpg' \n self.frames[i][0] ## checkbox var\n self.frames[i][1] ## frame to destroy\n \"\"\"\n # create copy so we don't modify a list as we\n # loop over it\n to_check_list = self.frames[:]\n i = 0\n for frame in to_check_list:\n # if the checkbox var is True\n if frame[0].get() and len(self.picList):\n # deletes frame from canvas\n try:\n rp.log.debug(\"i is: {} frames len: {} picList len: {}\".format(i, len(self.frames), len(self.picList)))\n #print(self.frames)\n #print(self.picList)\n rp.log.debug(\"CANFRAME IS: {}\".format(self.canFrame.winfo_height()))\n to_del = self.frames.pop(i)\n rp.log.debug(\"LEN OF FRAME IS NOW: {}\".format(len(self.frames)))\n rp.log.debug(\"Popping: {}\".format(self.picList[i].image_name))\n self.picList.pop(i)\n rp.log.debug(\"LEN OF PICLIST IS NOW: {}\".format(len(self.picList)))\n item = self.itemFrame.pop(i)\n # delete visible frame\n #to_del[1].des\n item.destroy()\n # reset scrollbar\n self.scroll.destroy()\n self.scrollFrame.destroy()\n self.setScroll()\n\n except AttributeError:\n # occurs when a frame is supposed to be present\n # but actually isn't\n rp.log.debug(\"Frame isn't present\", exc_info = True)\n \n to_del_img = to_del[2]\n\n try:\n rp.log.debug(\"to_del P: %s\" % to_del_img.thumb_save_loc_P)\n rp.log.debug(\"to_del C: %s\" % to_del_img.thumb_save_loc_C)\n rp.log.debug(\"to_del : %s\" % to_del_img.save_location)\n # delete thumbnail_P\n os.remove(to_del_img.thumb_save_loc_P)\n rp.log.debug(\"Removed to_del_P\")\n # delete original file\n os.remove(to_del_img.save_location) \n rp.log.debug(\"Removed to_del\")\n \n # delete database entry\n rp.Database.del_img(to_del_img.image_name)\n \n # add to_del_img.image_name to list so we don't\n # add it again\n self.already_deleted.append(to_del_img.image_name)\n\n try:\n os.remove(to_del_img.thumb_save_loc_C)\n rp.log.debug(\"Removed to_del_C: %s\" % to_del_img.thumb_save_loc_C)\n except FileNotFoundError:\n # image was likely not set as current image, may not\n # have been correct dimensions\n rp.log.debug(\"It appears that the image %s was never \"\n \"set as a current image\" % to_del_img.thumb_save_loc_C)\n\n\n except (OSError, FileNotFoundError):\n rp.log.debug(\"File not found when deleting\", exc_info = True)\n rp.log.debug(to_del_img.image_name)\n else:\n i += 1\n\n self.setFrame()\n self.scroll.destroy()\n self.setScroll()\n self.selVar.set(False)\n # don't forget to destroy the popup!\n popup.destroy()\n \n def remove_C(self, photoPath, photo):\n \"\"\"\n Formats the photo name so that the photo name is\n the %PHOTONAME%_C.png and then prepend the file path\n to the photo, as it does not contain the path\n \"\"\"\n # take the .png off, add _C to it, then add .png\n # back on\n imageC = self.strip_file_ext(photo)\n imageC += \"_C\"\n imageC = self.add_png(imageC)\n\n\n # retrieves the download location based on \n # other image\n index = photoPath.rfind('/') + 1 \n path = photoPath[:index]\n imageC = path + imageC\n \n return imageC\n\n def populate(self, frame, picList):\n \"\"\"\n Fill the frame with more frames of the images\n \"\"\"\n rp.log.debug(\"Len of picList to populate is {}\".format(len(picList)))\n for i, im in enumerate(picList):\n rp.log.debug(\"I IS FRESH AND IS {}\".format(i))\n try:\n rp.log.debug(\"IMAGE SAVE LOC IS: {}\".format(im.save_location))\n with open(im.save_location, 'rb') as image_file:\n # create and save image thumbnail\n # PIL module used to create thumbnail\n imThumb = Image.open(image_file)\n im.strip_file_ext()\n im.updateSaveLoc()\n imThumb.thumbnail((50, 50), Image.ANTIALIAS)\n imThumb.save(im.thumb_save_loc_P, \"PNG\")\n\n except (FileNotFoundError, OSError):\n # usually a file that is not an actual image, such\n # as an html document\n rp.log.debug(\"ERROR IS:\", exc_info = True)\n rp.log.debug(\"FILE NOT FOUND, OR OS ERROR, I is {}\".format(i))\n i -= 1\n rp.log.debug(\"I SUBTRACTED {}\".format(i))\n continue \n \n # create frame to hold information for one picture\n item = Frame(frame, width = 450, height = 50)\n\n # self.picList has already been appended to before those pictures\n # that were appended were gridded. Therefore, we subtract the len\n # of the new images we are adding, since that will give us the \n # row of the last image that was added, and then we add our current\n # index to this so we arrive at the latest unoccupied row\n len_p_list = len(self.picList)\n len_list = len(picList)\n # only change the row if the p_list is a \n # different length of len_list\n if (len_p_list - len_list) != 0:\n rp.log.debug(\"I WAS {}\".format(i))\n i += (len_p_list - len_list)\n rp.log.debug(\"UPDATING I INDEX to {}\".format(i))\n\n rp.log.debug(\"I is now {}\".format(i))\n item.grid(row = i, column = 0)\n #rp.log.debug(\"LEN of item frame before append: \", len(self.itemFrame))\n self.itemFrame.append(item)\n #rp.log.debug(\"LEN OF ITEM FRAME IN POPULATE: \", len(self.itemFrame))\n item.pack_propagate(0)\n\n # checkbox to select/deselect the picture\n checkVar = BooleanVar(False)\n check = ttk.Checkbutton(item,\n variable = checkVar)\n check.pack(side = \"left\", padx = 5)\n \n # insert the thumbnail and make the frame have a minimum w/h so\n # that the im.title won't slide over to the left and off-center\n # itself\n photo = PhotoImage(file = im.thumb_save_loc_P)\n photoFrame = Frame(item, width = 75, height = 50)\n photoFrame.pack_propagate(0)\n photoLabel = ttk.Label(photoFrame, image = photo)\n photoFrame.pack(side = \"left\")\n photoLabel.image = photo # keep a reference per the docs!\n photoLabel.pack(side = \"left\", padx = 10)\n \n # text frame\n txtFrame = Frame(item)\n txtFrame.pack()\n\n # title label \n # slice and add ellipsis if title is too long \n font = Fonts.S()\n if len(im.title) > 110:\n im.title = im.title[:110] + '...'\n font = Fonts.XS()\n\n title = ttk.Label(txtFrame,\n text = im.title,\n font = font,\n wraplength = 325,\n justify = 'center')\n title.pack(side = \"top\", padx = 10)\n \n botTxtFrame = Frame(txtFrame)\n botTxtFrame.pack(side = \"bottom\", anchor = 'center')\n botTxtFrame.pack_propagate(0)\n \n # link to post\n link = ttk.Label(botTxtFrame,\n text = \"Link\",\n font = Fonts.M_U(),\n cursor = Fonts._CURSOR,\n foreground = Fonts._HYPERLINK)\n link.grid(row = 0, column = 0)\n \n \"\"\"\n how to remember variable/function in a for loop:\n https://stackoverflow.com/questions/14259072/\n tkinter-bind-function-with-variable-in-a-loop/\n 14260871#14260871\n \"\"\"\n link.bind(\"\", self.make_link(im))\n \n # set as wallpaper text\n setAs = ttk.Label(botTxtFrame,\n text = \"Set as Wallpaper\",\n font = Fonts.M_U(),\n cursor = Fonts._CURSOR,\n foreground = Fonts._HYPERLINK)\n setAs.grid(row = 0, column = 1)\n setAs.bind(\"\", self.make_wallpaper(im))\n\n # add to the past images frame to display pictures\n # self.itemFrame is added so we can delete the frame later on\n self.frames.append((checkVar, self.itemFrame, im))\n \n # for loop over children of itemFrame did not work\n # to set keybinds, so we manually set all keybinds\n # so scrolling is enabled for both mouse and arrow keys\n self.setKeyBinds(item)\n self.setKeyBinds(setAs)\n self.setKeyBinds(link)\n self.setKeyBinds(botTxtFrame)\n self.setKeyBinds(title)\n self.setKeyBinds(txtFrame)\n self.setKeyBinds(photoLabel)\n self.setKeyBinds(check)\n\n self.scroll.destroy()\n self.setScroll()\n self.setKeyBinds(self.canvas) \n\n def make_link(self, im):\n \"\"\" \n Returns a lambda so each past image corresponds\n to its own function and they don't all\n end up sharing the same function. See the\n link posted above.\n \"\"\"\n return lambda e: self.open_link(im.post)\n \n def make_wallpaper(self, im):\n \"\"\" \n Returns a lambda so each past image corresponds\n to its own function and they don't all\n end up sharing the same function. See the\n link posted above.\n \"\"\"\n return lambda e: im.setAsWallpaper()\n\n def findSavedPictures(self):\n \"\"\"\n Returns a list of pictures in the wallpaper.db\n \"\"\"\n pictures = rp.PictureList.list_pics()\n return pictures\n \n def open_link(self, link):\n \"\"\" Opens the link in the default webbrowser \"\"\"\n webbrowser.open_new(link)\n\n def updatePastImgs(self):\n \"\"\"\n Updates the past images with new ones that\n may have been downloaded. Updates happen\n every 1 second\n \"\"\"\n # get list of all pictures\n pictures = self.findSavedPictures()\n new_pictures = False\n new_pics = []\n # get all image names from database\n image_name_list = [pic.image_name for pic in self.picList]\n # loop through each picture\n\n for picture in pictures:\n # if picture is not already displayed\n # and if it hasn't been deleted.\n # then it probably wasn't there before\n # so we add it to the list to be displayed\n if (picture.image_name not in image_name_list):# and\\\n #(picture.image_name not in self.already_deleted):\n new_pictures = True\n new_pics.append(picture)\n self.picList.append(picture)\n\n if new_pictures:\n rp.log.debug(\"NEW PICTURES AREEEEEE\")\n for pic in new_pics:\n rp.log.debug(pic.image_name)\n rp.log.debug(\"ALREADY DELETED {}\".format(self.already_deleted))\n # pass in the frame to pack the new pictures in to \n self.populate(self.canFrame, new_pics)\n rp.log.debug(\"Past populate\")\n\n # destroy scrollbar so it doesn't make a new scrollbar each\n # time we update pastimages\n self.scroll.destroy()\n self.scrollFrame.destroy()\n self.setScroll()\n\n self.after(30000, lambda: self.updatePastImgs())\n\n def __str__(self):\n return \"Past Images\"\n\n# **** Settings Page **** #\n# This is where most of the users choices will be made\n# on the running of the program.\n# This includes: * nsfw filter box\n# * subreddits to query\n# * image resolutions\n# * multiple monitor setup\nclass Settings(Frame):\n\n def __init__(self, parent, controller):\n # force settings file to be created, so we have default\n # values the first time we run the GUI\n rp.Config.read_config()\n Frame.__init__(self, parent)\n self.top = Frame(self)\n # subreddit border\n self.subredditF = ttk.LabelFrame(self,\n text = \"Subreddits to pull from \"\\\n \"(separated by a space)\")\n # nsfw border\n self.midTop = Frame(self.top)\n self.checksFrame = ttk.LabelFrame(self.midTop, text = \"Adult Content\")\n self.checks = Frame(self.checksFrame)\n \n # width x height\n self.dimensions = ttk.LabelFrame(self.top, \n text = \"Picture Resolution\")\n self.res = Frame(self.dimensions)\n\n # maxposts\n self.maxLabel = ttk.LabelFrame(self.midTop, text = \"# of Posts\")\n self.maxFrame = Frame(self.maxLabel)\n self.maxTxt = ttk.Label(self.maxFrame, text = \"Max posts:\")\n self.maxTxt.pack(side = \"left\", padx = 5)\n self.maxE = ttk.Entry(self.maxFrame, width = 3)\n self.maxE.insert(0, rp.Config.maxposts())\n self.maxE.pack(side = \"left\", padx = 5, pady = 5)\n self.maxFrame.pack()#padx = 5)\n\n # cycletime border and frame\n self.topRt = Frame(self.top)\n self.ct = ttk.LabelFrame(self.topRt, text = \"Wallpaper Timer\")\n self.ctFrame = Frame(self.ct)\n \n # category border and frame\n self.cat = ttk.LabelFrame(self.topRt, text = \"Section\")\n self.catFrame = Frame(self.cat, width = 194, height = 30)\n self.catFrame.pack_propagate(0)\n\n # download location border\n self.dlFrame = ttk.LabelFrame(self, text = \"Picture download location\")\n \n # Single link border\n self.singleF = ttk.LabelFrame(self, text = \"Direct download link \"\\\n \"ex. https://i.imgur.com/rhd1TFF.jpg\")\n self.singleE = ttk.Entry(self.singleF, width = 44)\n self.singleE.pack(side = \"left\", pady = 5, padx = 10, anchor = 'w')\n self.singleB = ttk.Button(self.singleF, text = \"Get Image\")\n self.singleB.pack(side = \"right\", padx = 5, pady = 5)\n self.singleB.bind(\"\", lambda event: rp.Single_link(self.singleE.get()))\n\n # Buttons\n self.buttonFrame = Frame(self)\n self.letsGo = ttk.Button(self.buttonFrame, text = \"Let's Go!\")\n self.help = Button(self.buttonFrame, text = \"Help\",\n bg = \"#ff4500\") \n self.help.bind(\"\", lambda e: self.change_color())\n \n # subreddit entry\n self.subreddits = ttk.Entry(self.subredditF, width = 59)\n self.subreddits.insert(0, rp.Config.subreddits())\n self.subreddits.grid(row = 1, column = 2, columnspan = 2, padx = 5,\n sticky = \"w\", pady = 5, ipadx = 3)\n # \"download to\" entry\n self.dlTxt = ttk.Label(self.dlFrame, text = \"Download pictures to:\") \n self.dlTxt.grid(row = 0, column = 0, padx = 5, sticky = \"w\")\n self.dlLoc = ttk.Entry(self.dlFrame, width = 41)\n self.dlLoc.insert(0, rp.Config.downloadLoc())\n self.dlLoc.grid(row = 0, column = 1, sticky = \"w\", padx = 5, pady = 5,\n ipadx = 1)\n\n # Frames for width x height\n self.widthF = Frame(self.res)\n self.heightF = Frame(self.res)\n self.widthF.pack(side = \"top\")\n self.heightF.pack(side = \"top\")\n\n # Min width\n self.minWidthTxt = ttk.Label(self.widthF, text = \" Min-width:\")\n self.minWidthTxt.grid(row = 0, column = 0, sticky = \"e\", padx = 5, pady = (5, 0))\n # min width entry\n self.minwidth = ttk.Entry(self.widthF, width = 6)\n self.minwidth.insert(0, rp.Config.minwidth())\n self.minwidth.grid(row = 0, column = 1, padx = 5, pady = 5)\n # Min height\n minHeightTxt = ttk.Label(self.heightF, text = \"Min-height:\")\n minHeightTxt.grid(row = 1, column = 0, sticky = \"e\", padx = 5, pady = (0, 5))\n # min height entry\n self.minheight = ttk.Entry(self.heightF, width = 6)\n self.minheight.insert(0, rp.Config.minheight())\n self.minheight.grid(row = 1, column = 1, padx = 5, pady = (0, 5))\n \n # nsfw checkbutton\n # nsfw on text\n nsfwTxt = ttk.Label(self.checks, text = \"NSFW\\nfilter\")\n nsfwTxt.pack(side = \"left\", padx = 5)\n # nsfw var config\n self.onOff = BooleanVar()\n self.onOff.set(rp.Config.nsfw())\n # nsfw checkbutton config\n self.nsfw = ttk.Checkbutton(self.checks, text = \"On\",\n variable = self.onOff)\n \n # cycletime txt\n self.ctTxt = ttk.Label(self.ctFrame, text = \"Set for:\")\n self.ctTxt.grid(row = 0, column = 0, sticky = \"e\", padx = (5,0))\n # cycletime entry\n self.rpHr, self.rpMin = rp.Config.cycletime()\n # hour txt/entry\n self.ctHourE = ttk.Entry(self.ctFrame, width = 3)\n self.ctHourE.insert(0, self.rpHr)\n self.ctHourE.grid(row = 0, column = 1, padx = (5,0), pady = 5)\n self.ctHourTxt = ttk.Label(self.ctFrame, text = \"hrs\")\n self.ctHourTxt.grid(row = 0, column = 2, padx = (0, 5))\n # min txt/entry\n self.ctMinE = ttk.Entry(self.ctFrame, width = 4)\n self.ctMinE.insert(0, self.rpMin)\n self.ctMinE.grid(row = 0, column = 3)\n self.ctMinTxt = ttk.Label(self.ctFrame, text = \"mins\", anchor = \"w\")\n self.ctMinTxt.grid(row = 0, column = 4, padx = (0, 5))\n self.ctFrame.pack(side = \"top\")\n \n # category dropdown\n self.choices = [\"Top\", \"Hot\", \"New\", \"Rising\", \"Controversial\"]\n self.catVar = StringVar(self)\n self.optionVar = rp.Config.category()\n self.catVar.set(self.optionVar)\n self.catDD = ttk.OptionMenu(self.catFrame, self.catVar, self.optionVar, *self.choices)\n self.catDD.config(width = 10)\n self.catDD.pack(side = \"right\", anchor = \"e\", padx = (0, 5), pady = 5) \n self.catTxt = ttk.Label(self.catFrame, text = \"Category:\")\n self.catTxt.pack(side = \"left\", anchor = \"e\", padx = (5, 0))\n self.catFrame.pack(side = \"top\", ipady = 5)\n \n # packs/binds\n # button packs\n self.buttonFrame.pack(side = \"bottom\", pady = (10, 30))\n self.letsGo.pack(side = \"left\", padx = (200, 0))\n self.help.pack(side = \"left\", padx = (90, 0))\n self.help.bind(\"\", lambda event: self.help_box(parent))\n self.letsGo.bind(\"\", lambda event: self.get_pics())\n\n self.nsfw.pack(side = \"left\", anchor = \"nw\", pady = 5,\n padx = (0, 5))\n # top holds dimensions and user/pass labelFrames\n self.top.pack(side = \"top\", anchor = \"w\", pady = 10)\n self.subredditF.pack(side = \"top\", anchor = \"w\",\n padx = (15, 10))\n self.dlFrame.pack(side = \"top\", anchor = \"w\", pady = 10,\n padx = 15)\n self.singleF.pack(side = \"top\", anchor = 'w', padx = (15, 10))\n self.dimensions.pack(side = \"left\", anchor = \"nw\", pady = (0, 10),\n padx = (15, 5))\n self.res.pack(side = \"top\")\n self.midTop.pack(side = \"left\", padx = 5) \n self.checks.pack(side = \"top\")\n self.checksFrame.pack(side = \"top\", anchor = \"nw\",\n padx = 5)\n self.maxLabel.pack(side = \"top\", pady = 14)\n # cycletime and category frame\n self.cat.pack(side = \"top\")\n self.ct.pack(side = \"bottom\", pady = 5)\n self.topRt.pack(side = \"left\", anchor = \"nw\", padx = 5)\n\n def change_color(self):\n if self.help['bg'] == \"#9494ff\":\n self.help.configure(bg = \"#ff4500\")\n else:\n self.help.configure(bg = \"#9494ff\")\n \n def help_box(self, parent):\n \"\"\" \n Help box for when a user needs to better understand\n how the program works\n \"\"\"\n self.Message = Message(parent, \"Help\")\n self.Message.set_dimensions(parent, 450, 460)\n self.Message.pack_button()\n self.Message.pack_label(\"For extra help, please refer to the Feedback\"\n \" and Crash Report section on the next tab.\"\n \" An FAQ is also available at the\"\n \" subreddit r/reddit_paper.\",\n anchor = 'center',\n justify = 'center',\n pady = (10, 5))\n self.Message.pack_label(\"*Picture Resolution* Specifies the minimum\"\\\n \" width and height required to add a wallpaper\"\\\n \" to the queue.\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*Adult Content* When the box is checked it will\"\n \" filter out wallpapers that are NSFW.\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*Section* Specifies what category to pull from\"\n \" on Reddit. Most of the time when browsing Reddit\"\n \" you are browsing hot by default\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*# of Posts* The number of posts to search\"\n \" through. If using a single subreddit, the first\"\n \" X number of posts will be searched through. If\"\n \" using a multireddit, a breadth-first-search is\"\n \" performed.\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*Wallpaper Timer* How long the wallpaper will be\"\n \" set as the background.\",\n font = Fonts.M(),\n anchor = 'w', \n pady = 5)\n self.Message.pack_label(\"*Subreddits* Enter subreddits separated by a space.\"\n \" More than one subreddit to search through is supported.\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*Download Location* This is where the pictures will\"\n \" be downloaded to.\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n self.Message.pack_label(\"*Direct Download Link* Enter a full URL to a picture\"\n \" to be set as the wallpaper. This link is most commonly\"\n \" found by right clicking, then 'open image in new tab'\",\n font = Fonts.M(),\n anchor = 'w',\n pady = 5)\n def get_values(self):\n \"\"\" returns the values stored in the entry boxes \"\"\"\n self.values = {}\n self.values['-mw'] = self.minwidth.get()\n self.values['-mh'] = self.minheight.get()\n self.values['--nsfw'] = int(self.onOff.get()) # convert bool to int\n self.values['-s'] = self.subreddits.get().replace(\" \", \"+\")\n self.values['-dl'] = self.dlLoc.get()\n self.values['-c'] = self.catVar.get().lower()\n self.values['-mp'] = self.maxE.get()\n\n errors = self.test_values(self.values)\n \n try:\n # convert hours to minutes, then add it to minutes, so we \n # are only dealing with total minutes in the end\n hours = self.ctHourE.get()\n mins = self.ctMinE.get() \n totalTime = abs(float(hours)) * 60\n totalTime += abs(float(mins))\n print(\"TOTAL TIME IS:::: %.2f\" % totalTime)\n self.values['-t'] = totalTime # in minutes\n CurrentImg.TIMER = abs(float(self.ctHourE.get())) * 3600000 +\\\nabs(float(self.ctMinE.get())) * 60000 #totalTime * 60000 # in milliseconds\n\n except ValueError:\n errors.append((self.ctHourE.get(), self.ctMinE.get()))\n #errors.append(self.ctMinE.get())\n\n return self.values, errors\n\n def test_values(self, values):\n \"\"\"\n Returns a list of incorrectly entered\n values from the settings page\n \"\"\"\n # replace + with '' as we replaced ' ' with\n # '+' and + is not considered an alnum\n # so we remove it\n subs = values['-s'].replace('+', '')\n\n errors = []\n # if len(values) != 7:\n # errors.append(\"Please fill in all settings options\")\n # return errors\n if not str(values['-mw']).isdigit() or int(values['-mw']) < 0:\n errors.append(values['-mw'])\n if not str(values['-mh']).isdigit() or int(values['-mh']) < 0:\n errors.append(values['-mh'])\n if not str(values['-mp']).isdigit() or\\\n int(values['-mp']) > 99 or int(values['-mp']) < 0:\n errors.append(values['-mp'])\n if not subs.isalnum():\n errors.append(values['-s'])\n if values['-dl'][values['-dl'].rfind('/'):] != values['-dl'][-1:]:\n errors.append(\"Make sure path ends with a '/' \" + values['-dl'])\n\n return errors\n\n def get_pics(self):\n \"\"\" \n Makes the call to redditpaper.main() to\n start the wallpaper scraper part of the\n program. Also collects the values to\n start the program with.\n \"\"\"\n\n self.args, errors = self.get_values()\n if len(errors):\n rp.log.debug(\"ERRORS from CLArgs is: %s\",\n tuple(errors)) \n InvalidArg(self, errors)\n return\n\n rp.log.debug(\"No errors in CLArgs\") \n # create string for list of args\n self.argList = 'redditpaper.pyw'\n rp.log.debug(os.getcwd())\n\n for k, v in self.args.items():\n rp.log.debug(\"Key, Value in CLArgs is: \"\n + k + \" \" + str(v))\n if v:\n # add key and value to the string to be\n # passed as cmd line args\n # the key will be the switch for the arg\n self.argList += \" \" + k + \" \" + str(v)\n self.argList = \"python3.4 \" + self.argList\n # call main function with cmd line args\n rp.log.debug(\"Argument list is: \" + self.argList)\n \n # should have all valid arguments at this point\n try:\n # run program from shell-essentially\n subprocess.Popen(self.argList.split())\n except:\n # catch all errors from rp.main so we raise them\n # and they don't get swallowed\n raise\n\n def __str__(self):\n return \"Settings\"\n\n\n# **** About Page **** #\n# Displays information regarding the creator of the application,\n# where to ask questions, who to contact, etc.\n# This includes: * contact info (email, name, where to post for help)\n# * Donate option\n# * Feedback\n# * (Sending CrashReport)\nclass About(Frame):\n def __init__(self, parent, controller):\n Frame.__init__(self, parent)\n \n # frames\n self.authorFrame = ttk.LabelFrame(self, text = \"Author\")\n self.donateFrame = ttk.LabelFrame(self, text = \"Donations\")\n self.crashFrame = ttk.LabelFrame(self, text = \"Crash Report\")\n self.versionFrame = Frame(self.authorFrame)\n self.subAuthorFrame = Frame(self.authorFrame)\n self.feedFrame = ttk.LabelFrame(self, text = \"Feedback\")\n\n # author\n self.authorTxt = ttk.Label(self.subAuthorFrame,\n text = \"This program was created by: \",\\\n font = Fonts.M())\n self.authorLink = ttk.Label(self.subAuthorFrame, \n text=\"/u/camerongagnon\", \n font = Fonts.M_U(), \n foreground = Fonts._HYPERLINK,\n cursor = Fonts._CURSOR)\n\n # version number\n self.vNum = StringVar()\n self.vNum.set(\"Version: \" + rp.AboutInfo.version() + \".\" +\n AboutInfo.version())\n self.version = ttk.Label(self.versionFrame, text = self.vNum.get(),\n font = Fonts.M())\n \n # donate text/link\n self.donateTxt = ttk.Label(self.donateFrame,\n text = \"If you enjoy this program, \"\n \"please consider making a donation \",\n font = Fonts.M())\n self.subDonateFrame = Frame(self.donateFrame)\n self.donateTxt2 = ttk.Label(self.subDonateFrame,\n text = \"to the developer\",\n font = Fonts.M()) \n self.donateLink = ttk.Label(self.subDonateFrame, text = \"here.\",\n font = Fonts.M_U(),\n foreground = Fonts._HYPERLINK,\n cursor = Fonts._CURSOR) \n\n # feedback\n self.feedback = ttk.Label(self.feedFrame,\n text = \"To provide comments/feedback, please \"\n \"do one of the following: \",\n font = Fonts.M())\n self.subredditFrame = Frame(self.feedFrame)\n self.feedback1 = ttk.Label(self.subredditFrame, \n text = \"1. Go to\",\n font = Fonts.M())\n self.subredditLink = ttk.Label(self.subredditFrame,\n text = \"r/reddit_paper\",\n font = Fonts.M_U(),\n cursor = Fonts._CURSOR,\n foreground = Fonts._HYPERLINK)\n self.feedback12 = ttk.Label(self.subredditFrame,\n text = \"and create a new post.\",\n font = Fonts.M())\n self.feedback2 = ttk.Label(self.feedFrame,\n text = \"2. Follow the account \"\n \"link at the top and send me a PM.\",\n font = Fonts.M())\n self.feedback3 = ttk.Label(self.feedFrame,\n text = \"3. Email me directly at \"\n \"cameron.gagnon@gmail.com\",\n font = Fonts.M())\n self.githubFrame = Frame(self.feedFrame)\n self.number4 = ttk.Label(self.githubFrame,\n text = \"4.\",\n font = Fonts.M())\n self.githubLink = ttk.Label(self.githubFrame,\n text = \"File a bug/create a pull request\",\n font = Fonts.M_U(),\n foreground = Fonts._HYPERLINK,\n cursor = Fonts._CURSOR)\n self.feedback4 = ttk.Label(self.githubFrame,\n text = \"because this code is open source!!\",\n font = Fonts.M())\n\n # send crashReport\n self.crash_loc = StringVar()\n self.location = self.get_crash_location()\n self.crash_loc.set(self.location)\n\n self.report = ttk.Label(self.crashFrame,\n text = \"To send a crash report, browse to \"\n \"the location below and send the \",\n font = Fonts.M(),\n wraplength = 480)\n self.report1 = ttk.Label(self.crashFrame,\n text = \"log to cameron.gagnon@gmail.com.\", \n font = Fonts.M(), \n wraplength = 480)\n\n self.crash_loc = ttk.Label(self.crashFrame, text = self.crash_loc.get(),\n wraplength = 480)\n\n # packs/binds\n # author frame pack\n self.authorTxt.pack(side = \"left\", padx = (60, 0), pady = (5,0))\n self.authorLink.pack(side = \"left\", pady = (5,0))\n self.authorLink.bind(\"\", \n lambda event: self.open_link(AboutInfo.reddit()))\n self.subAuthorFrame.pack(side = \"top\")\n \n self.subredditLink.bind(\"\",\n lambda event: self.open_link(AboutInfo.subreddit()))\n self.githubLink.bind(\"\",\n lambda event: self.open_link(AboutInfo.GitHub()))\n\n # version frame pack within author frame\n self.version.pack(pady = (0,5))\n self.versionFrame.pack(side = \"top\")\n self.authorFrame.pack(side = \"top\", fill = \"x\", pady = (10, 0),\n padx = (10, 15))\n # donate frame pack\n self.donateTxt.pack(side = \"top\", pady = (5, 0), anchor = 'center')\n self.donateTxt2.pack(side = \"left\", pady = (0, 5), anchor = 'center')\n self.donateLink.pack(side = \"left\", pady = (0, 5))\n self.donateLink.bind(\"\", \n lambda event: self.open_link(AboutInfo.PayPal()))\n self.donateFrame.pack(side = \"top\", fill = \"x\", padx = (10, 15), \n pady = (10, 0))\n self.subDonateFrame.pack(side = \"top\")\n \n # feedback\n self.feedback.pack(side = \"top\", anchor = 'center', pady = (5, 0))\n self.subredditFrame.pack(side = \"top\")\n self.feedback1.pack(side = \"left\", anchor = 'center')\n self.subredditLink.pack(side = \"left\")\n self.feedback12.pack(side = \"left\", anchor = 'center')\n self.feedback2.pack(side = \"top\", anchor = 'center')\n self.feedback3.pack(side = \"top\", anchor = 'center')\n self.number4.pack(side = \"left\", anchor = 'center')\n self.githubLink.pack(side = \"left\", anchor = 'center')\n self.feedback4.pack(side = \"left\", anchor = 'center')\n self.githubFrame.pack(side = \"top\", anchor = 'center', pady = (0, 5))\n self.feedFrame.pack(side = \"top\", fill = \"x\", padx = (10, 15),\n pady = (10, 0))\n\n # crash report pack\n self.report.pack(side = \"top\", anchor = 'center')\n self.report1.pack(side = \"top\", anchor = 'center')\n self.crash_loc.pack(side = \"top\", pady = (0, 5))\n self.crashFrame.pack(side = \"top\", fill = \"x\", padx = (10, 15), \n pady = (10, 0))\n \n def open_link(self, link):\n webbrowser.open_new(link)\n\n def get_crash_location(self):\n # opens a file browser for the user to \n # search for the log file\n return os.path.realpath(\"CrashReport.log\")\n \n def __str__(self):\n return \"About\"\n\nif __name__ == \"__main__\":\n app = Application()\n app.mainloop()\n","repo_name":"cameron-gagnon/reddit-paper","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":65414,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"73040063402","text":"import numpy as np\nimport pandas as pd\nimport pytest\nfrom dask import array as da\n\nfrom napari.layers.utils.layer_utils import (\n calc_data_range,\n dataframe_to_properties,\n segment_normal,\n)\n\ndata_dask = da.random.random(\n size=(100_000, 1000, 1000), chunks=(1, 1000, 1000)\n)\n\ndata_dask_plane = da.random.random(\n size=(100_000, 100_000), chunks=(1000, 1000)\n)\n\n\ndef test_calc_data_range():\n # all zeros should return [0, 1] by default\n data = np.zeros((10, 10))\n clim = calc_data_range(data)\n assert np.all(clim == [0, 1])\n\n # all ones should return [0, 1] by default\n data = np.ones((10, 10))\n clim = calc_data_range(data)\n assert np.all(clim == [0, 1])\n\n # return min and max\n data = np.random.random((10, 15))\n data[0, 0] = 0\n data[0, 1] = 2\n clim = calc_data_range(data)\n assert np.all(clim == [0, 2])\n\n # return min and max\n data = np.random.random((6, 10, 15))\n data[0, 0, 0] = 0\n data[0, 0, 1] = 2\n clim = calc_data_range(data)\n assert np.all(clim == [0, 2])\n\n # Try large data\n data = np.zeros((1000, 2000))\n data[0, 0] = 0\n data[0, 1] = 2\n clim = calc_data_range(data)\n assert np.all(clim == [0, 2])\n\n # Try large data mutlidimensional\n data = np.zeros((3, 1000, 1000))\n data[0, 0, 0] = 0\n data[0, 0, 1] = 2\n clim = calc_data_range(data)\n assert np.all(clim == [0, 2])\n\n\ndef test_calc_data_fast_uint8():\n data = da.random.randint(\n 0,\n 100,\n size=(100_000, 1000, 1000),\n chunks=(1, 1000, 1000),\n dtype=np.uint8,\n )\n assert calc_data_range(data) == [0, 255]\n\n\n@pytest.mark.timeout(2)\ndef test_calc_data_range_fast_big():\n val = calc_data_range(data_dask)\n assert len(val) > 0\n\n\n@pytest.mark.timeout(2)\ndef test_calc_data_range_fast_big_plane():\n val = calc_data_range(data_dask_plane)\n assert len(val) > 0\n\n\ndef test_segment_normal_2d():\n a = np.array([1, 1])\n b = np.array([1, 10])\n\n unit_norm = segment_normal(a, b)\n assert np.all(unit_norm == np.array([1, 0]))\n\n\ndef test_segment_normal_3d():\n a = np.array([1, 1, 0])\n b = np.array([1, 10, 0])\n p = np.array([1, 0, 0])\n\n unit_norm = segment_normal(a, b, p)\n assert np.all(unit_norm == np.array([0, 0, -1]))\n\n\ndef test_dataframe_to_properties():\n properties = {'point_type': np.array(['A', 'B'] * 5)}\n properties_df = pd.DataFrame(properties)\n converted_properties, _ = dataframe_to_properties(properties_df)\n np.testing.assert_equal(converted_properties, properties)\n","repo_name":"zzalscv2/napari","sub_path":"napari/layers/utils/_tests/test_layer_utils.py","file_name":"test_layer_utils.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19785399676","text":"from collections import deque\r\nn = int(input())\r\nq = deque()\r\nfor i in range(1, n+1):\r\n q.append(i)\r\n\r\nlength = n\r\nwhile n != 1:\r\n q.popleft()\r\n n -= 1\r\n if n == 1:\r\n break\r\n else:\r\n q.append(q.popleft())\r\nprint(q[0])\r\n","repo_name":"industrial-engineering-person/AlgorithmSolve","sub_path":"백준/Silver/2164. 카드2/카드2.py","file_name":"카드2.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"75060133804","text":"import ipywidgets as widgets\nfrom bqplot import Axis, Figure, LinearScale, Lines\nimport os\nfrom greenflow.dataframe_flow.config_nodes_modules import load_modules\nload_modules(os.getenv('MODULEPATH')+'/rapids_modules/')\nfrom rapids_modules.cuindicator import macd as indicator_fun # noqa #F401\n\n\ndef get_para_widgets():\n para_selector = widgets.IntRangeSlider(value=[10, 30],\n min=3,\n max=60,\n step=1,\n description=\"MACD:\",\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True)\n para_selector_widgets = [para_selector]\n return para_selector_widgets\n\n\ndef get_parameters(stock_df, para_selector_widgets):\n widget = para_selector_widgets[0]\n return (stock_df[\"close\"], widget.value[0], widget.value[1])\n\n\ndef process_outputs(output, stock_df):\n output.MACD.index = stock_df.index\n output.MACDsign.index = stock_df.index\n output.MACDdiff.index = stock_df.index\n\n stock_df['out0'] = output.MACD\n stock_df['out0'] = stock_df['out0'].fillna(0)\n stock_df['out1'] = output.MACDsign\n stock_df['out1'] = stock_df['out1'].fillna(0)\n stock_df['out2'] = output.MACDdiff\n stock_df['out2'] = stock_df['out2'].fillna(0)\n return stock_df\n\n\ndef create_figure(stock, dt_scale, sc, color_id,\n f, indicator_figure_height, figure_width, add_new_indicator):\n sc_co = LinearScale()\n ax_y = Axis(label='MACD', scale=sc_co, orientation='vertical')\n new_line = Lines(x=stock.datetime.to_array(),\n y=[stock['out0'].to_array(),\n stock['out1'].to_array(),\n stock['out2'].to_array()],\n scales={'x': dt_scale, 'y': sc_co})\n new_fig = Figure(marks=[new_line], axes=[ax_y])\n new_fig.layout.height = indicator_figure_height\n new_fig.layout.width = figure_width\n figs = [new_line]\n # add new figure\n add_new_indicator(new_fig)\n return figs\n\n\ndef update_figure(stock, objects):\n line = objects[0]\n with line.hold_trait_notifications():\n line.y = [stock['out0'].to_array(),\n stock['out1'].to_array(), stock['out2'].to_array()]\n line.x = stock.datetime.to_array()\n","repo_name":"NVIDIA/fsi-samples","sub_path":"gQuant/plugins/gquant_plugin/notebooks/cuIndicator/viz/macd.py","file_name":"macd.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":263,"dataset":"github-code","pt":"19"} +{"seq_id":"18446540946","text":"import argparse\nimport torch\nimport json\nimport torch\n\nfrom torchvision import datasets, transforms, models\nfrom torch import nn, optim\n\nvgg13 = models.vgg13(pretrained=True)\n\nmodels = { 'vgg13': vgg13 }\n\n\ndef get_train_args():\n \n parser = argparse.ArgumentParser()\n \n parser.add_argument(\"data_dir\", type=str, help=\"set path to save get data\")\n parser.add_argument(\"--save_dir\", type=str, default='checkpoint.pth', help=\"set path to save checkpoints\")\n parser.add_argument(\"--arch\", type=str, default=\"vgg13\", help=\"set choose architecture\")\n parser.add_argument(\"--learning_rate\", type=float, default=0.01, help=\"set learning rate\")\n parser.add_argument(\"--hidden_units\", type=int, default=512, help=\"set hidden units\")\n parser.add_argument(\"--epochs\", type=int, default=20, help=\"set epochs\")\n parser.add_argument(\"--gpu\", action='store_true', help=\"set GPU or not\")\n \n return parser.parse_args()\n\ndef create_datasets(train_dir, valid_dir, test_dir):\n image_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n valid_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n test_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n image_ds = datasets.ImageFolder(train_dir, transform=image_transforms)\n valid_ds = datasets.ImageFolder(valid_dir, transform=valid_transforms)\n test_ds = datasets.ImageFolder(test_dir, transform=test_transforms) \n \n return [image_ds, valid_ds, test_ds]\n\ndef create_loaders(data_sets):\n \n dataloader = torch.utils.data.DataLoader(data_sets[0], batch_size=64, shuffle=True)\n validloader = torch.utils.data.DataLoader(data_sets[1], batch_size=64)\n testloader = torch.utils.data.DataLoader(data_sets[2], batch_size=64)\n \n return [dataloader, validloader, testloader]\n\ndef train_model(loaders, data_sets, params): \n device = 'cpu'\n if params['gpu'] and torch.cuda.is_available():\n device = 'cuda'\n \n print(f\"Device mode: { device }\")\n \n model = models[params['arch']] \n for param in model.parameters():\n param.requires_grad = False\n \n model.classifier = nn.Sequential(nn.Linear(25088, params['hidden_units']),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(params['hidden_units'], 102),\n nn.LogSoftmax(dim=1))\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), lr=params['learning_rate']) \n \n model = model.to(device) \n dataloader = loaders[0]\n validloader = loaders[1]\n testloader = loaders[2]\n \n running_loss = 0 \n accuracy = 0\n for epoch in range(params['epochs']):\n model.train()\n running_loss = 0\n\n print(f\"Running epoch: { epoch+1 }\")\n \n for inputs, labels in dataloader: \n inputs, labels = inputs.to(device), labels.to(device)\n print(\"Get input and labels from dataloader\")\n \n optimizer.zero_grad() \n outputs = model.forward(inputs)\n print(\"Get outputs from dataloader\")\n \n loss = criterion(outputs, labels) \n print(\"Get loss from dataloader\")\n \n loss.backward() \n optimizer.step()\n\n print(\"Sum loss\")\n running_loss += loss.item() \n \n print(f\"Epoch {epoch+1}/{params['epochs']}.. \"\n f\"Train loss: {running_loss/len(dataloader):.3f}.. \")\n\n model.eval()\n running_loss = 0\n\n for inputs, labels in validloader: \n inputs, labels = inputs.to(device), labels.to(device)\n print(\"Get input and labels from validloader\")\n \n optimizer.zero_grad() \n outputs = model.forward(inputs)\n print(\"Get outputs from validloader\")\n \n loss = criterion(outputs, labels) \n print(\"Get loss from validloader\")\n \n accuracy = calculate_accuracy(model, inputs, labels)\n print(\"Sum accuracy from validloader\")\n \n print(f\"Validation loss: {running_loss/len(validloader):.3f}.. \"\n f\"Test accuracy: {accuracy:.3f}\")\n\n validate_model(model, testloader, device)\n save_model(model, data_sets, params['filename'], params['hidden_units']) \n \ndef save_model(model, data_sets, filename, hidden_units): \n model.class_to_idx = data_sets[0].class_to_idx\n \n checkpoint = {\n 'arch': 'vgg13',\n 'state_dict': model.state_dict(),\n 'class_to_idx': model.class_to_idx,\n 'hidden_units': hidden_units\n }\n \n torch.save(checkpoint, filename)\n print(\"Model saved!\")\n\ndef calculate_accuracy(model, images, labels): \n output = model.forward(images)\n ps = torch.exp(output).data\n equality = (labels.data == ps.max(1)[1])\n return equality.type_as(torch.FloatTensor()).mean()\n \ndef validate_model(model, testloader, device):\n model = model.to(device)\n model.eval()\n accuracy = 0\n \n for data in testloader:\n count += 1\n images, labels = data \n images, labels = images.to(device), labels.to(device) \n print(\"Get input and labels from testloader\")\n \n accuracy += calculate_accuracy(model, images, labels)\n print(\"Sum accuracy from testloader\") \n \n print(f\"Final Accuracy: {accuracy/len(testloader):.3f}\") \n \ndef main():\n \n input_args = get_train_args()\n \n train_dir = input_args.data_dir + '/train'\n valid_dir = input_args.data_dir + '/valid'\n test_dir = input_args.data_dir + '/test'\n \n print(\"Creating datasets\")\n data_sets = create_datasets(train_dir, valid_dir, test_dir)\n print(\"Datasets created!\")\n \n print(\"Creating loaders\")\n loaders = create_loaders(data_sets)\n print(\"Loaders created!\")\n \n print(\"Starting training\")\n \n params = {\n 'arch': input_args.arch, \n 'learning_rate':input_args.learning_rate, \n 'gpu': input_args.gpu, \n 'epochs': input_args.epochs, \n 'hidden_units': input_args.hidden_units, \n 'filename': input_args.save_dir \n }\n \n train_model(loaders, data_sets, params)\n print(\"Finishing training\")\n \nif __name__ == \"__main__\": \n main()\n\n ","repo_name":"juliomurta/python-ia-udacity","sub_path":"final-project/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39729694350","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\n\n\nchrome_driver_path = \"/Users/dillonjohn/Sites/chromedriver-3\"\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--kiosk\")\ndriver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)\n\nPOLL_URL = \"https://docs.google.com/forms/d/e/1FAIpQLScRCi7B3\" \\\n \"Z6BzVtPb4CeO9umltSL3K5e4L4nDDSF_9a38fqe2Q/\" \\\n \"viewform?usp=sf_link\"\n\nZILLOW_URL = \"https://www.zillow.com/homes/for_rent/1-_beds/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22usersSearchTerm%22%3\" \\\n \"Anull%2C%22mapBounds%22%3A%7B%22west%22%3A-122.56276167822266%2C%22east%22%3A-122.30389632177734%2C%22south%22%3A37.6926134523046\" \\\n \"7%2C%22north%22%3A37.857877098316834%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22fr%22%3A%7B%22value%22%3Atrue%7D%2C%\" \\\n \"22fsba%22%3A%7B%22value%22%3Afalse%7D%2C%22fsbo%22%3A%7B%22value%22%3Afalse%7D%2C%22nc%22%3A%7B%22value%22%3Afalse%7D%2C%22cmsn%22%3\" \\\n \"A%7B%22value%22%3Afalse%7D%2C%22auc%22%3A%7B%22value%22%3Afalse%7D%2C%22fore%22%3A%7B%22value%22%3Afalse%7D%2C%22pmf%22%3A%7B%22value%2\" \\\n \"2%3Afalse%7D%2C%22pf%22%3A%7B%22value%22%3Afalse%7D%2C%22mp%22%3A%7B%22max%2\" \\\n \"2%3A3000%7D%2C%22price%22%3A%7B%22max%22%3A872627%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A12%7D\"\n\n\ndriver.get(ZILLOW_URL)\n\nlocation_name = input(\"Enter full city name followed by comma and state abbreviation EX: New York, NY\")\n\nlocation = driver.find_element(By.XPATH, '//*[@id=\"__c11n_fq416pfw\"]')\nlocation.send_keys(location_name)\n\nrent_button1 = driver.find_element(By.XPATH, '//*[@id=\"listing-type\"]')\nrent_button1.click()\n\ntime.sleep(3)\nrent_button2 = driver.find_element(By.XPATH, '//*[@id=\"__c11n_lkh2k\"]/span')\nrent_button2.click()\n\nprice_button1 = driver.find_element(By.XPATH, '//*[@id=\"price\"]')\nprice_button1.click()\n\nprice_min = input(\"Enter the minimum price you are willing to pay:\")\nprice_minbox = driver.find_element(By.XPATH, '//*[@id=\"price-exposed-min\"]')\nprice_minbox.send_keys(price_min)\n\nprice_max = input(\"Enter the maximum price you are willing to pay:\")\nprice_maxbox = driver.find_element(By.XPATH, '//*[@id=\"price-exposed-max\"]')\nprice_maxbox.clear()\nprice_maxbox.send_keys(price_max)\n\nprice_popup_close = driver.find_element(By.XPATH, '//*[@id=\"search-page-react-content\"]/section/div[2]/div/div[2]/div/div/div/button')\nprice_popup_close.click()\n\nsearch_submit = driver.find_element(By.XPATH, '//*[@id=\"__c11n_fq416pfy\"]/button')\nsearch_submit.click()\n\nsearch_url = driver.current_url\n\n\nsoup = BeautifulSoup(search_url,'html.parser')\n\nsoup.find_all()\n\n\n\n\n","repo_name":"Dillon1john/PythonProjects","sub_path":"Rental_property_search_/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"27345639301","text":"###################################\n#\n# 100 Days of code bootcamp 2021\n# (Udemy course by Angela Yu)\n# \n# Day 9 exercises - Christopher Hagan\n#\n###################################\n\n# Exercise 9-1 Grading program\nstudent_scores = {\n \"Harry\": 81,\n \"Ron\": 78,\n \"Hermione\": 99, \n \"Draco\": 74,\n \"Neville\": 62,\n}\n\nstudent_grades = {}\nfor student in student_scores:\n if student_scores[student] > 90:\n grade = 'Outstanding'\n elif student_scores[student] > 80:\n grade = 'Exceeds Expectations'\n elif student_scores[student] > 70:\n grade = 'Acceptable'\n else:\n grade = 'Fail'\n\n student_grades[student] = grade\n\nprint(student_grades)\n\n\n# Exercise 9-2 Travel log\ntravel_log = [\n{\n \"country\": \"France\",\n \"visits\": 12,\n \"cities\": [\"Paris\", \"Lille\", \"Dijon\"]\n},\n{\n \"country\": \"Germany\",\n \"visits\": 5,\n \"cities\": [\"Berlin\", \"Hamburg\", \"Stuttgart\"]\n},\n]\n\ndef add_new_country(country, visits, list_of_cities):\n new_country_entry = {}\n new_country_entry['country'] = country\n new_country_entry['visits'] = visits\n new_country_entry['cities'] = list_of_cities\n travel_log.append(new_country_entry)\n\nadd_new_country(\"Russia\", 2, [\"Moscow\", \"Saint Petersburg\"])\nprint('\\n\\n{}'.format(travel_log))\n","repo_name":"chagan1985/100DaysOfCode","sub_path":"Day9/day-9-dictionaries.py","file_name":"day-9-dictionaries.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"6666640903","text":"'''Imports and Variables'''\r\nimport random, math, time, asyncio, classes\r\nfrom tkinter import *\r\n\r\nmaster = Tk() #create new window or \"canvas\" called \"master\"\r\ncanvasWidth = 60 #canvas width\r\ncanvasHeight = 40 #canvas height\r\ncellSize = 10 #the size length of the cell; should fit evenly into both canvasWidth and canvasHeight\r\nstartingCells = int(canvasHeight / 2) #how many cells the game should start with\r\ncellColor = [\"#7ec2cc\", \"#a3dae3\"]\r\ncellSpacing = 2\r\nspeed = 0.1 #speed of cells (in seconds), or how often it should update to the next generation\r\nlistOfCells = set() #empty set, used to hold all alive cells while removing duplicates\r\ngameOn = False #Game starts turned off\r\n\r\n\r\ninProgress = True #disables settings; I'm not done with it\r\n\r\n'''Functions'''\r\ndef checkered(canvas, lineDistance): #draws lines\r\n #vertical lines, each lineDistance pixels apart\r\n for x in range(lineDistance, (canvasWidth * cellSize), lineDistance):\r\n canvas.create_line(x, 0, x, (canvasHeight * cellSize), fill=\"#dddddd\")\r\n #horizontal lines, each lineDistance pixels apart\r\n for y in range(lineDistance, (canvasHeight * cellSize), lineDistance):\r\n canvas.create_line(0, y, (canvasWidth * cellSize), y, fill=\"#dddddd\")\r\n\r\ndef startingBoard(): #places startingCells random cells, semi-near each other, for a starting board\r\n #picks the first random cells\r\n x = random.randint(0, canvasWidth)\r\n y = random.randint(0, canvasHeight)\r\n for i in range (startingCells): #spawns the first startingCells starting cubes\r\n #loops board\r\n if x > canvasWidth - 1:\r\n x = 0\r\n if x < 0:\r\n x = canvasWidth - 1\r\n if y > canvasHeight - 1:\r\n y = 0\r\n if y < 0:\r\n y = canvasHeight - 1\r\n game.cellList[x][y].alive = True\r\n #moves next cell up to cellSpacing squares away in any direction\r\n x += random.randint(-cellSpacing, cellSpacing)\r\n y += random.randint(-cellSpacing, cellSpacing)\r\n listOfCells = drawCells(game) #draws cube\r\n return listOfCells\r\n\r\ndef resetCanvas(): #resets the canvas\r\n pen.delete(\"all\") #clears canvas\r\n pen.create_rectangle(0, 0, (canvasWidth * cellSize), (canvasHeight * cellSize), fill=\"#ffffff\", outline=\"#dddddd\") #draws border\r\n for i in game.cellList: #deletes any alive drawn cells\r\n for j in i:\r\n j.alive = False\r\n pen.delete(j.rectangle)\r\n checkered(pen, cellSize) #draws grid\r\n listOfCells = startingBoard()\r\n cellCountText[\"text\"] = f\"Cell count: {len(listOfCells)}\"\r\n\r\ndef resumeGame(): #Start/stop loop\r\n global gameOn\r\n if gameOn: #if game is on; turns it off\r\n gameOn = False\r\n playPause[\"text\"] = \"Play\"\r\n playPause[\"bg\"] = \"#7df585\"\r\n playPause[\"fg\"] = \"#007a08\"\r\n else: #if game is off; turns it on\r\n gameOn = True\r\n playPause[\"text\"] = \"Pause\"\r\n playPause[\"bg\"] = \"#ff6b6b\"\r\n playPause[\"fg\"] = \"#8f0000\"\r\n checkIfOn()\r\n\r\ndef checkIfOn(): #Used to check if it should keep running; a while loop in resumeGame doesn't work; it won't draw any cells or enable buttons until the while loop finishes. It never will finish, causing the game to lag and eventually crash.\r\n global gameOn\r\n global listOfCells\r\n global cellCountText\r\n if gameOn:\r\n nextGen()\r\n cellCountText[\"text\"] = f\"Cell count: {len(listOfCells)}\" #won't work?\r\n master.after(int(speed * 1000), checkIfOn) #how long to wait before running the function again\r\n\r\ndef nextGen():\r\n listOfCells = set()\r\n for i in game.cellList:\r\n for j in i:\r\n if j.alive:\r\n cellsSet = set()\r\n neighbors = j.findNeighbors(canvasWidth, canvasHeight, game.cellList) #stores first 8 neighbors\r\n tempCellSet = j.updateCells(neighbors, cellsSet, game.cellList, canvasWidth, canvasHeight) #stores the 8 neighbors of each neighbor for the current cell, putting them in a set so that duplicates are removed\r\n for k in tempCellSet: #moves all the neighbors of the neighbors of the current cell to listOfCells; tempCellSet gets reset for each new current cell; listOfCells does not\r\n listOfCells.add(k)\r\n if not j in listOfCells: #for some reason, sometimes the original cell does not get added; adds it here\r\n listOfCells.add(j)\r\n checkCells(listOfCells)\r\n listOfCells = drawCells(game)\r\n return listOfCells\r\n\r\ndef checkCells(totalCells):\r\n for i in totalCells:\r\n coordsList = game.cellList[i.x][i.y].loopCells(canvasWidth, canvasHeight, i)\r\n #renames 8 neighbors to be the actual cells, and not a list of the two coords\r\n topLeft = game.cellList[coordsList[0][0]][coordsList[0][1]]\r\n topCent = game.cellList[coordsList[1][0]][coordsList[1][1]]\r\n topRight = game.cellList[coordsList[2][0]][coordsList[2][1]]\r\n midLeft = game.cellList[coordsList[3][0]][coordsList[3][1]]\r\n midRight = game.cellList[coordsList[4][0]][coordsList[4][1]]\r\n bottomLeft = game.cellList[coordsList[5][0]][coordsList[5][1]]\r\n bottomCent = game.cellList[coordsList[6][0]][coordsList[6][1]]\r\n bottomRight = game.cellList[coordsList[7][0]][coordsList[7][1]]\r\n neighbors = [topLeft.alive, topCent.alive, topRight.alive, midLeft.alive, midRight.alive, bottomLeft.alive, bottomCent.alive, bottomRight.alive].count(True) #counts the neighbors of the current cell\r\n #updates cell to whether it should be alive or not\r\n if i.alive:\r\n if neighbors > 3 or neighbors < 2:\r\n i.alive = False\r\n else:\r\n if neighbors == 3:\r\n i.alive = True\r\n\r\ndef drawCells(game): #deletes all cells, and then draws all alive cells\r\n listOfCells = set()\r\n for i in game.cellList:\r\n for j in i:\r\n pen.delete(j.rectangle) #deletes all living cells\r\n if j.alive:\r\n listOfCells.add(j)\r\n j.rectangle = pen.create_rectangle((j.x * cellSize), (j.y * cellSize), ((j.x * cellSize) + cellSize), ((j.y * cellSize) + cellSize), fill=cellColor[0], outline=cellColor[1]) #draws cell\r\n return listOfCells\r\n\r\ndef updateSettings(update, xSize, ySize, cellSizeBox, startingCellsBox, cellColorBox, cellSpacingBox, speedBox):\r\n #collects data\r\n global canvasWidth\r\n global canvasHeight\r\n global cellSize\r\n global startingCells\r\n global cellColor\r\n global cellSpacing\r\n global speed\r\n global master\r\n toCheck = [xSize, ySize, cellSizeBox, startingCellsBox, cellColorBox, cellSpacingBox, speedBox]\r\n toAssign = [canvasWidth, canvasHeight, cellSize, startingCells, cellColor, cellSpacing, speed]\r\n for i in toCheck:\r\n if len(i.get()) > 0: #only updates variables if there was an entry\r\n toAssign[toCheck.index(i)] = i.get()\r\n #update[\"text\"] = \"Updated!\"\r\n master.destroy()\r\n #create canvas\r\n master = Tk() #create new window or \"canvas\" called \"master\"\r\n master.title(\"Conway's Game of Life\") #window title\r\n pen = Canvas(master, width = (canvasWidth * cellSize), height = (canvasHeight * cellSize))\r\n pen.pack()\r\n game = classes.gameClass(canvasWidth, canvasHeight) #creates game class, where all cells will be held\r\n resetCanvas()\r\n #update[\"text\"] = \"Update\"\r\n\r\ndef adjustSettings(): #opens settings window; changes window/cell size, starting cells, cell color, etc.\r\n if inProgress:\r\n global canvasWidth\r\n global canvasHeight\r\n global cellSize\r\n global cellColor\r\n global speed\r\n gameOn = False #turns off the game so it isn't running while settings are being adjusted\r\n print(\"Settings opened\")\r\n #creates window\r\n settingsBox = Tk()\r\n settingsBox.title(\"Settings\")\r\n settingsBoxPen = Canvas(settingsBox, width = ((canvasWidth * cellSize) / 2), height = ((canvasHeight * cellSize) / 2))\r\n settingsBoxPen.pack()\r\n #labels\r\n xSizeLabel = Label(settingsBox, text=\"Canvas width:\", font = 50) #canvas x\r\n xSizeLabel.pack()\r\n ySizeLabel = Label(settingsBox, text=\"Canvas height:\", font = 50) #canvas y\r\n ySizeLabel.pack()\r\n cellSizeLabel = Label(settingsBox, text=\"Cell size:\", font = 50) #cell size\r\n cellSizeLabel.pack()\r\n startingCellsLabel = Label(settingsBox, text=\"Number of starting cells:\", font = 50) #starting cells\r\n startingCellsLabel.pack()\r\n cellColorLabel = Label(settingsBox, text=\"Cell color (provide hex code):\", font = 50) #cell color\r\n cellColorLabel.pack()\r\n cellSpacingLabel = Label(settingsBox, text=\"Cell spacing (How close together the cells generate):\", font = 50) #how close together the cells generate\r\n cellSpacingLabel.pack()\r\n speedLabel = Label(settingsBox, text=\"Game speed:\", font = 50) #game speed\r\n speedLabel.pack()\r\n #entry boxes\r\n xSize = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight, window=xSize)\r\n ySize = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 25, window=ySize)\r\n cellSizeBox = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 50, window=cellSizeBox)\r\n startingCellsBox = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 75, window=startingCellsBox)\r\n cellColorBox = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 100, window=cellColorBox)\r\n cellSpacingBox = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 125, window=cellSpacingBox)\r\n speedBox = Entry (settingsBox)\r\n settingsBoxPen.create_window(canvasWidth, canvasHeight + 150, window=speedBox)\r\n #buttons\r\n closeSettings = Button(settingsBox, command=lambda: quitSettings(settingsBox), text=\"Close\", bd=0, bg=\"#ff6b6b\", padx=10, pady=5, fg=\"#8f0000\", activebackground=\"#ff3636\", activeforeground=\"#690000\") #\"lambda\" is used so that the function can be called with arguments\r\n closeSettings.pack(side=\"right\")\r\n update = Button(settingsBox, command=lambda: updateSettings(update, xSize, ySize, cellSizeBox, startingCellsBox, cellColorBox, cellSpacingBox, speedBox), text=\"Update\", bd=0, bg=\"#ffe770\", padx=10, pady=5, fg=\"#877100\", activebackground=\"#ffe359\", activeforeground=\"#665500\")\r\n update.pack(side=\"right\")\r\n else:\r\n print(\"This feature is in progress. Come back soon!\")\r\n\r\ndef quit(): #closes the game\r\n master.destroy()\r\n\r\ndef quitSettings(settingsBox):\r\n settingsBox.destroy()\r\n\r\n'''code'''\r\n#create canvas\r\nmaster.title(\"Conway's Game of Life\") #window title\r\npen = Canvas(master, width = (canvasWidth * cellSize), height = (canvasHeight * cellSize))\r\npen.pack()\r\ngame = classes.gameClass(canvasWidth, canvasHeight) #creates game class, where all cells will be held\r\n\r\n#buttons\r\nquit = Button(master, command=quit, text=\"Quit\", bd=0, bg =\"#ff6b6b\", padx=15, pady=10, fg=\"#8f0000\", activebackground=\"#ff3636\", activeforeground=\"#690000\").pack(side=\"right\")\r\nreset = Button(master, command=resetCanvas, text=\"Reset\", bd=0, bg=\"#ffe770\", padx=15, pady=10, fg=\"#877100\", activebackground=\"#ffe359\", activeforeground=\"#665500\").pack(side=\"right\")\r\nplayPause = Button(master, command=resumeGame, text=\"Play\", bd=0, bg=\"#7df585\", padx=15, pady=10, fg=\"#007a08\", activebackground=\"#5ee067\", activeforeground=\"#005906\")\r\nplayPause.pack(side=\"right\")\r\nsettings = Button(master, command=adjustSettings, text=\"Settings\", bd=0, bg=\"#ffe770\", padx=15, pady=10, fg=\"#877100\", activebackground=\"#ffe359\", activeforeground=\"#665500\") #\"lambda\" is used so that the function can be called with arguments\r\nsettings.pack(side=\"right\")\r\n\r\n#labels/text in window\r\ncanvasTitle = Label(master, text=\"Conway's Game of Life\", font = 200)\r\ncanvasTitle.pack() #pack has to be separate for some reason; else will break\r\ncellCountText = Label(master, text=f\"Cell count: {len(listOfCells)}\", font = 100)\r\ncellCountText.pack()\r\n\r\nresetCanvas()\r\nmainloop() #dunno why this is here tbh, is used for Tkinter","repo_name":"BlackPanther5000/conwaysGameOfLife","sub_path":"conwaysGameOfLife/Previous Versions/conwaysGameOfLife v.1.0/conwaysGameOfLife.py","file_name":"conwaysGameOfLife.py","file_ext":"py","file_size_in_byte":12238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"27679172311","text":"# -*- coding: utf8 -*-\n\nimport pytest\nimport pytest_ansible_playbook\n\nfrom usmqe.api.tendrlapi import glusterapi\nfrom usmqe.api.tendrlapi.common import TendrlAuth\nfrom usmqe.usmqeconfig import UsmConfig\n\nCONF = UsmConfig()\n\n\n@pytest.fixture(\n scope=\"session\",\n params=[\n \"\",\n None,\n \"this_is_invalid_access_token_00000\",\n \"4e3459381b5b94fcd642fb0ca30eba062fbcc126a47c6280945a3405e018e824\",\n ])\ndef invalid_session_credentials(request):\n \"\"\"\n Return invalid access (for testing negative use cases), no login or logout\n is performed during setup or teardown.\n \"\"\"\n username = CONF.config[\"usmqe\"][\"username\"]\n invalid_token = request.param\n auth = TendrlAuth(token=invalid_token, username=username)\n return auth\n\n\n@pytest.fixture\ndef importfail_setup_nodeagent_stopped_on_one_node(\n request,\n unmanaged_cluster,\n valid_session_credentials):\n \"\"\"\n This fixture stops node agent on one storage machine. During teardown it\n makes sure that the node agent is back and then runs unmanage job to\n cleanup state after a failed import.\n\n Don't use this fixture if you are not running negative test cases for\n import cluster feature.\n \"\"\"\n with pytest_ansible_playbook.runner(\n request,\n [\"test_setup.tendrl_nodeagent_stopped_on_one_node.yml\"],\n [\"test_teardown.tendrl_nodeagent_stopped_on_one_node.yml\"]):\n yield\n # And now something completely different: we need to run unmanage because\n # the cluster is not managed after a failed import, which would block any\n # future import attempt.\n tendrl = glusterapi.TendrlApiGluster(auth=valid_session_credentials)\n job = tendrl.unmanage_cluster(unmanaged_cluster[\"cluster_id\"])\n tendrl.wait_for_job_status(job[\"job_id\"])\n","repo_name":"usmqe/usmqe-tests","sub_path":"usmqe_tests/api/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"34808740164","text":"import gi\nimport pprint\nimport quickgtk\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\nimport screenops as so\n\npp = pprint.PrettyPrinter(indent=4)\n\n\nclass DisplayArrangeWindow(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title=\"Display Arrange\")\n self.set_border_width(10)\n self.top_container = quickgtk.new_vbox()\n self.add(self.top_container)\n\n self.so = so.ScreenOps()\n self.render()\n\n def render(self):\n quickgtk.empty(self.top_container)\n self.render_favorites()\n self.render_new_favorite()\n self.show_all()\n\n def render_favorites(self):\n hbox = quickgtk.new_hbox()\n\n self.fav_model = self.so.get_favorites_as_list_store()\n self.fav_cb = Gtk.ComboBox.new_with_model(self.fav_model)\n fav_render = Gtk.CellRendererText()\n self.fav_cb.pack_start(fav_render, True)\n self.fav_cb.add_attribute(fav_render, \"text\", 0)\n self.fav_cb.set_active(self.so.find_index_of_current())\n\n apply_button = Gtk.Button(label='Apply')\n apply_button.connect(\"clicked\", self.apply_arrangement)\n\n delete_button = Gtk.Button(label='Delete')\n delete_button.connect(\"clicked\", self.delete_arrangement)\n\n quickgtk.add_all(hbox, [\n Gtk.Label('Select a favorite arrangement'),\n self.fav_cb,\n apply_button,\n delete_button\n ])\n self.top_container.add(hbox)\n\n def render_new_favorite(self):\n hbox = quickgtk.new_hbox()\n _, new_name_entry, fav_button = quickgtk.add_all(hbox, [\n Gtk.Label('Favorite the current screen arrangement'),\n Gtk.Entry(),\n Gtk.Button(\"Save\")\n ])\n self.top_container.add(hbox)\n\n def new_fav(_):\n self.so.favorite_current(new_name_entry.get_text())\n self.render()\n\n fav_button.connect('clicked', new_fav)\n\n def get_selected_favorite_name(self):\n fav_iter = self.fav_cb.get_active_iter()\n\n if fav_iter is not None:\n return self.fav_model[fav_iter][0]\n\n def apply_arrangement(self, _):\n name = self.get_selected_favorite_name()\n if (name):\n self.so.apply(name)\n\n def delete_arrangement(self, _):\n name = self.get_selected_favorite_name()\n if (name):\n self.so.delete(name)\n self.render()\n\n\n\nwin = DisplayArrangeWindow()\nwin.connect('destroy', Gtk.main_quit)\nGtk.main()\n","repo_name":"sheodox/display-arrange","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"8593326329","text":"from openapi_schema_pydantic.v3.v3_0_3 import Schema\n\nfrom winter_openapi.inspection import DataTypes\nfrom winter_openapi.inspection import TypeInfo\n\n\ndef convert_type_info_to_openapi_schema(value: TypeInfo, *, output: bool) -> Schema:\n if value.type_ == DataTypes.ANY:\n return Schema(\n description='Can be any value - string, number, boolean, array or object.',\n nullable=value.nullable,\n )\n\n data = {\n 'type': value.type_.value\n }\n if value.title:\n data['title'] = value.title if output else f'{value.title}Input'\n\n if value.description:\n data['description'] = value.description\n\n if value.format_ is not None:\n data['schema_format'] = value.format_.value\n\n if value.child is not None:\n data['items'] = convert_type_info_to_openapi_schema(value.child, output=output)\n\n if value.nullable:\n data['nullable'] = True\n\n if value.enum is not None:\n data['enum'] = value.enum\n\n if value.properties:\n data['properties'] = {\n key: convert_type_info_to_openapi_schema(value, output=output)\n for key, value in value.properties.items()\n }\n\n if output:\n required_properties = list(value.properties)\n else:\n required_properties = [\n property_name\n for property_name in value.properties\n if property_name not in value.properties_defaults\n and not value.properties[property_name].nullable\n and not value.properties[property_name].can_be_undefined\n ]\n\n if required_properties:\n data['required'] = required_properties\n\n return Schema(**data)\n","repo_name":"WinterFramework/winter","sub_path":"winter_openapi/type_info_converter.py","file_name":"type_info_converter.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"19"} +{"seq_id":"35368744528","text":"# Modified from Al Sweigart's: Automate The Boring Stuff With Python\n\nimport random\n\nnum = random.randint(1, 20)\n\nprint(\"Hello. What is your name?\")\nname = input()\nprint(f\"Hello {name}. I'm thinking of a number between 1 and 20.\\nTake a guess.\")\n\nguessed = False\ni = 0\n\nwhile not guessed:\n i += 1\n guess = int(input())\n if guess > num:\n print(f\"Your guess is too high {name}.\\nTake a guess.\")\n elif guess < num:\n print(f\"Your guess is too low {name}.\\nTake a guess.\")\n else:\n print(f\"Good job {name}. You have guessed my number in {i} guesses.\")\n guessed = True\n","repo_name":"ibrahimbayyinah/sololearn-codes","sub_path":"python/guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22178447796","text":"import logging\nimport os\nimport time\nimport pylab as P\nfrom cookbook.dicts import DictOf\nimport cookbook.pylab_utils as pylab_utils\nfrom cookbook.script_basics import setup_logging\nsetup_logging(__file__, level=logging.INFO)\n\nimport stempy\nimport stempy as stem\nimport stempy.meme as meme\nstempy.Pssm.max_samples_in_E_value_calc = 1000\n\n\ndef add_options(option_parser):\n stem.add_options(option_parser)\n meme.add_options(option_parser)\noptions, args = stempy.parse_options(add_options)\n\n\ndef small_fastas():\n \"@return: A few small fasta filenames.\"\n return [\n os.path.abspath(\n os.path.join(os.path.dirname(__file__), '../../fasta/%s.fa')) % f\n for f in (\n 'T00759-tiny',\n 'T00759-small',\n 'T00759trimRM-test-x2',\n )\n ]\n\n\ndef big_fastas():\n \"@return: A few big fasta files.\"\n return [\n '/home/john/Data/GappedPssms/apr-2009/T99006trimUN.fa',\n '/home/john/Data/GappedPssms/apr-2009/T99005trimUN.fa',\n '/home/john/Data/GappedPssms/apr-2009/T00759trimUN.fa',\n '/home/john/Data/GappedPssms/apr-2009/T00671trimUN.fa',\n '/home/john/Data/GappedPssms/Full-Sp1/Sp1-1000000.fa',\n ]\n\n\n# fasta = '/home/john/Data/NTNU-TF-search-dataset/datasets/model_real/M00724.fas'\n# fasta = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fasta/T00759trimRM-test-x2.fa'))\n# fasta = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fasta/T00759-tiny.fa'))\noutput_dir = os.path.abspath(os.path.join('output', 'speed-test'))\n\n\ndef timeit(fn):\n \"Time the execution of a function.\"\n start_time = time.time()\n fn()\n return time.time() - start_time\n\n\ndef time_method(method):\n \"Time a method/width pair.\"\n logging.info('Timing method %s for width %d', method, W)\n return timeit(lambda: method.Algorithm(options)(fasta))\n\nWs = [6, 8, 10, 12]\n#Ws = [6, 8]\n#fastas = small_fastas()\nfastas = big_fastas()\n\n\ndef save_timings():\n \"Graph the timings.\"\n P.figure()\n for W, colour in zip(Ws, pylab_utils.simple_colours):\n P.loglog(fasta_sizes, stem_timings[\n W], label='STEME W=%d' % W, ls='-', color=colour)\n P.loglog(fasta_sizes, meme_timings[\n W], label='MEME W=%d' % W, ls='-.', color=colour)\n P.legend(loc='upper left')\n P.xlabel('\\\\# bases in data set')\n P.ylabel('seconds')\n P.savefig(os.path.join(output_dir, 'timings.eps'))\n P.savefig(os.path.join(output_dir, 'timings.png'))\n P.close()\n\n\n#\n# do the timings.\n#\npylab_utils.set_rcParams_for_latex()\nstem_timings = DictOf(list)\nmeme_timings = DictOf(list)\nfasta_sizes = []\nfor fasta in fastas:\n for W in Ws:\n options.min_w = options.max_w = W\n options.output_dir = os.path.join(\n output_dir, 'W=%02d-%s' % (W, stempy.basename_wo_ext(fasta)))\n stempy.ensure_dir_exists(options.output_dir)\n stem_algorithm = stem.Algorithm(options)\n meme_algorithm = meme.Algorithm(options)\n stem_timings[W].append(timeit(lambda: stem_algorithm(fasta)))\n meme_timings[W].append(timeit(lambda: meme_algorithm(fasta)))\n fasta_sizes.append(stem_algorithm.num_bases)\n save_timings()\n","repo_name":"JohnReid/STEME","sub_path":"python/scripts/compare_speed.py","file_name":"compare_speed.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"1841958949","text":"\"\"\"\nMetric implementations taken from midaGAN\n\"\"\"\n\nimport numpy as np\nfrom scipy.stats import entropy\nfrom skimage.metrics import peak_signal_noise_ratio, structural_similarity\n\ndef mae(gt, pred):\n \"\"\"Compute Mean Absolute Error (MAE)\"\"\"\n mae_value = np.mean(np.abs(gt - pred))\n return float(mae_value)\n\n\ndef mse(gt, pred):\n \"\"\"Compute Mean Squared Error (MSE)\"\"\"\n mse_value = np.mean((gt - pred)**2)\n return float(mse_value)\n\n\ndef nmse(gt, pred):\n \"\"\"Compute Normalized Mean Squared Error (NMSE)\"\"\"\n nmse_value = np.linalg.norm(gt - pred)**2 / np.linalg.norm(gt)**2\n return float(nmse_value)\n\n\ndef psnr(gt, pred, maxval=None):\n \"\"\"Compute Peak Signal to Noise Ratio metric (PSNR)\"\"\"\n maxval = gt.max() if maxval is None else maxval\n psnr_value = peak_signal_noise_ratio(gt, pred, data_range=maxval)\n return float(psnr_value)\n\n\ndef ssim(gt, pred, maxval=None):\n \"\"\"Compute Structural Similarity Index Metric (SSIM)\"\"\"\n maxval = gt.max() if maxval is None else maxval\n\n size = (gt.shape[0] * gt.shape[1]) if gt.ndim == 4 else gt.shape[0]\n\n ssim_sum = 0\n for channel in range(gt.shape[0]):\n # Format is CxHxW or DxHxW\n if gt.ndim == 3:\n target = gt[channel]\n prediction = pred[channel]\n ssim_sum += structural_similarity(target, prediction, data_range=maxval)\n\n # Format is CxDxHxW\n elif gt.ndim == 4:\n for slice_num in range(gt.shape[1]):\n target = gt[channel, slice_num]\n prediction = pred[channel, slice_num]\n ssim_sum += structural_similarity(target, prediction, data_range=maxval)\n else:\n raise NotImplementedError(f\"SSIM for {gt.ndim} images not implemented\")\n\n return ssim_sum / size\n\n\ndef nmi(gt, pred):\n \"\"\"Normalized Mutual Information.\n Implementation taken from scikit-image 0.19.0.dev0 source --\n https://github.com/scikit-image/scikit-image/blob/main/skimage/metrics/simple_metrics.py#L193-L261\n Not using scikit-image because NMI is supported only in >=0.19.\n \"\"\"\n bins = 100 # 100 bins by default\n hist, bin_edges = np.histogramdd(\n [np.reshape(gt, -1), np.reshape(pred, -1)],\n bins=bins,\n density=True,\n )\n H0 = entropy(np.sum(hist, axis=0))\n H1 = entropy(np.sum(hist, axis=1))\n H01 = entropy(np.reshape(hist, -1))\n nmi_value = (H0 + H1) / H01\n return float(nmi_value)\n\n\ndef histogram_chi2(gt, pred):\n \"\"\"Chi-squared distance computed between histograms of the GT and the prediction.\n More about comparing two histograms --\n https://stackoverflow.com/questions/6499491/comparing-two-histograms\n \"\"\"\n bins = 100 # 100 bins by default\n\n # Compute histograms\n gt_histogram, gt_bin_edges = np.histogram(gt, bins=bins)\n pred_histogram, pred_bin_edges = np.histogram(pred, bins=bins)\n\n # Normalize the histograms to convert them into discrete distributions\n gt_histogram = gt_histogram / gt_histogram.sum()\n pred_histogram = pred_histogram / pred_histogram.sum()\n\n # Compute chi-squared distance\n bin_to_bin_distances = (pred_histogram - gt_histogram)**2 / (pred_histogram + gt_histogram)\n # Remove NaN values caused by 0/0 division. Equivalent to manually setting them as 0.\n bin_to_bin_distances = bin_to_bin_distances[np.logical_not(np.isnan(bin_to_bin_distances))]\n chi2_distance_value = np.sum(bin_to_bin_distances)\n return float(chi2_distance_value)\n\n\n\n","repo_name":"Maastro-CDS-Imaging-Group/HX4-PET-translation","sub_path":"scripts/utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25012066822","text":"from gym.envs.registration import register\nfrom config import *\n\nfor max_requests in MAX_REQUESTS:\n for cache_size in CACHE_SIZE:\n for file_index in FILE_INDEX:\n for task in TASKS:\n register(\n \"Cache-Bandit-C{}-Max{}-{}-{}-v0\".format(cache_size, max_requests, task, file_index),\n entry_point=\"rl_envs.cache_bandit:CacheBandit\",\n kwargs={\"cache_size\": cache_size, \"workload\": TASK_FILES[task].format(file_index), \"max_requests\": max_requests}\n )","repo_name":"chanb/MeLeCaR","sub_path":"rl_envs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5728737433","text":"import smtplib\nfrom email.message import EmailMessage\nfrom string import Template\nfrom pathlib import Path\n\n\nhtml = Template(Path('index.html').read_text())\nemail = EmailMessage()\nemail['from'] = 'Boni Legalzinho'\nemail['to'] = 'italovianelli@gmail.com'\nemail['subject'] = 'Email teste'\n\nemail.set_content(html.substitute(name='Italous'), 'html')\n\nwith smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:\n smtp.ehlo()\n smtp.starttls()\n smtp.login('testeitalov@gmail.com', 'Marketing2017')\n smtp.send_message(email)\n print('all good boss')\n","repo_name":"italoribeiroc/PythonZeroToMasteryExercises","sub_path":"email/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22402129293","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 31 22:50:18 2019\n\n@author: z.chen7\n\"\"\"\n\n# 293. Flip Game\n\n\"\"\"\nYou are playing the following Flip Game with your friend: Given a string that \ncontains only these two characters: + and -, you and your friend take turns to \nflip two consecutive \"++\" into \"--\". The game ends when a person can no longer \nmake a move and therefore the other person will be the winner.\n\nWrite a function to compute all possible states of the string after one valid move.\n\nExample:\n\nInput: s = \"++++\"\nOutput: \n[\n \"--++\",\n \"+--+\",\n \"++--\"\n]\n\"\"\"\n\nclass Solution(object):\n def generatePossibleNextMoves(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n if not s:\n return []\n \n result = []\n for i in range(len(s) - 1):\n if s[i:i+2] == '++':\n result.append(s[:i] + '--' + s[i+2:])\n \n return result","repo_name":"holmes1313/Leetcode","sub_path":"array_and_strings/293_Flip_Game.py","file_name":"293_Flip_Game.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37486992933","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef pronto_status(pronto_id):\r\n\turl = 'https://pronto.int.net.nokia.com/pronto/problemReportSearch.html?freeTextdropDownID=prId&searchTopText=' + pronto_id\r\n\treq = requests.get(url)\r\n\tweb_content = BeautifulSoup(req.text, 'lxml')\r\n\tweb_content = web_content.find('div',{\"class\" : 'My(6px) Pos(r) smartphone_Mt(6px)'})\r\n\tweb_content = web_content.find('span').text\r\n\r\n\treturn web_content","repo_name":"taojsy/python","sub_path":"mini_tool/pronto_test.py","file_name":"pronto_test.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25242438500","text":"import sys\nfrom os import environ, path\n\nsys.path.append(path.abspath(\"tests\"))\nfrom consts import *\n\nfrom brownie import accounts, StateChainGateway, FLIP\n\nFLIP_ADDRESS = environ[\"FLIP_ADDRESS\"]\nSC_GATEWAY_ADDRESS = environ[\"SC_GATEWAY_ADDRESS\"]\nAUTONOMY_SEED = environ[\"SEED\"]\nFLIP_AMOUNT = int(environ.get(\"FLIP_AMOUNT\", 10**3))\n\n# File should be formatted as a list of NODE_IDs separated by a newline\nNODE_ID_FILE = environ[\"NODE_ID_FILE\"]\n\nDEPLOYER_ACCOUNT_INDEX = int(environ.get(\"DEPLOYER_ACCOUNT_INDEX\") or 0)\n\ncf_accs = accounts.from_mnemonic(AUTONOMY_SEED, count=10)\n\nnode_ids = []\n\nfunding_amount = FLIP_AMOUNT * E_18\n\n\ndef main():\n flip = FLIP.at(f\"0x{cleanHexStr(FLIP_ADDRESS)}\")\n stateChainGateway = StateChainGateway.at(f\"0x{cleanHexStr(SC_GATEWAY_ADDRESS)}\")\n with open(NODE_ID_FILE, \"r\") as f:\n node_ids = f.readlines()\n f.close()\n funder = cf_accs[DEPLOYER_ACCOUNT_INDEX]\n to_approve = flip.balanceOf(funder)\n tx = flip.approve(\n stateChainGateway, to_approve, {\"from\": funder, \"required_confs\": 1}\n )\n print(f\"Approving {to_approve / E_18} FLIP in tx {tx.txid}\")\n for i, node_id in enumerate(node_ids):\n to_fund = funding_amount + (i * E_18)\n node_id = node_id.strip()\n tx = stateChainGateway.fundStateChainAccount(\n node_id,\n to_fund,\n {\"from\": funder, \"required_confs\": 0, \"gas_limit\": 1000000},\n )\n print(f\"Funding {to_fund / E_18} FLIP to node {node_id} in tx {tx.txid}\")\n\n\ndef cleanHexStr(thing):\n if isinstance(thing, int):\n thing = hex(thing)\n elif not isinstance(thing, str):\n thing = thing.hex()\n return thing[2:] if thing[:2] == \"0x\" else thing\n","repo_name":"chainflip-io/chainflip-eth-contracts","sub_path":"scripts/mass_funding.py","file_name":"mass_funding.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"70842470762","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nfrom sklearn.datasets import make_blobs\n\n\"\"\"\nmake_blobs 聚类数据生成器 n_samples 待生成的样本数,centers 要生成的样本中心数或者确定的中心点\nreturn X 生成的样本数据集 y 样本数据集的标签\n\n\"\"\"\n\nX, y = make_blobs(n_samples=40, centers=2, random_state=6) # X.shape(40,2) y.shape (40,)\n# print(X.shape)\n# print(y.shape)\nclf = svm.SVC(kernel='linear', C=1000)\nclf.fit(X, y)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=30)\nax = plt.gca()\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\n# print(xlim)\n# print(ylim)\nxx = np.linspace(xlim[0], xlim[1], 30)\n# print(xx)-\nyy = np.linspace(ylim[0], ylim[1], 30)\n# print(yy.shape)\nYY, XX = np.meshgrid(yy, xx)\nxy = np.vstack([XX.ravel(), YY.ravel()]).T\n# numpy.ravel() 将多维度数组降为一维数组 numpy.vstack() 沿竖直方向堆叠起来\nZ = clf.decision_function(xy).reshape(XX.shape)\n# 画出 decision boundary and margins\nax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])\n# 画出支持向量\nax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none')\nplt.show()\n","repo_name":"hangcheers/DailyPractice","sub_path":"algorithm/maximum margin.py","file_name":"maximum margin.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"41257512129","text":"\"\"\"\nDeep Learning Framework\nVersion 1.5\nAuthors: Benoit Vuillemin, Frederic Bertrand\nLicence: AGPL v3\n\"\"\"\nimport random\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nfrom DataPreparators.base_data_prep import *\nfrom Managers.encoder_manager import EncoderManager\nfrom generic_functions import get_total_chunk_number\n\n\nclass NextActivity(DataPreparator):\n def __init__(self):\n super().__init__()\n self.list = []\n self.dict_size = {}\n\n def build(self, input_chunk_size, output_chunk_size, batch_size, orchestrator):\n \"\"\"\n Assigns the necessary information to the preparator\n\n :param input_chunk_size: Size of a chunk (number of cases inside a chunk)\n :type input_chunk_size: int\n :param output_chunk_size: Number of cases per chunk\n :type output_chunk_size: int\n :param batch_size: Size of a batch to train the neural network\n :type batch_size: int\n :param orchestrator: Orchestrator\n :type orchestrator: Orchestrator\n \"\"\"\n super().build(input_chunk_size, output_chunk_size, batch_size, orchestrator)\n # Create the Train (0), Validation (1) and Test (2) sets with their respective probabilities\n values = (0, 1, 2)\n probabilities = (0.7, 0.2, 0.1)\n size = self.get_epoch_size_online()\n # Randomly separate data into Train, Validation and Test sets\n self.list = np.array(random.choices(values, probabilities, k=size))\n self.dict_size[0] = self.get_epoch_size_offline(0)\n self.dict_size[1] = self.get_epoch_size_offline(1)\n self.dict_size[2] = self.get_epoch_size_offline(2)\n # Create the output decoders\n # Get the first OneHot decoder, that is used for activities\n activity_decoder = None\n for encoder in self.input_decoders.encoders:\n if encoder.name == \"OneHot\":\n activity_decoder = encoder\n break\n if activity_decoder is None:\n raise RuntimeError('No activity encoder is present, thus preventing the Data Preparator to operate')\n self.output_decoders = EncoderManager([activity_decoder])\n\n def run_online(self, value=None, get_leftovers=False):\n \"\"\"\n Slices cases into suffixes and prefixes (online mode)\n\n \"\"\"\n while True:\n iterator = 0\n prefixes = []\n suffixes = []\n if get_leftovers:\n all_leftovers = []\n leftovers_names = self.orchestrator.encoder_manager.get_leftover_names()\n for case, leftover in self.orchestrator.process_online(self.input_chunk_size):\n if value is None or self.list[iterator] == value:\n i = 1\n while i < len(case):\n prefixes.append(case[:i])\n suffixes.append(case[i, :self.orchestrator.activity_counter])\n if get_leftovers:\n all_leftovers.append(leftover)\n i += 1\n if len(prefixes) == self.batch_size:\n prefixes = tf.keras.preprocessing.sequence.pad_sequences(prefixes, padding='post',\n maxlen=self.orchestrator.max_case_length-1,\n dtype=float)\n suffixes = np.array(suffixes, dtype=float)\n if get_leftovers:\n all_leftovers = pd.DataFrame(data=all_leftovers, columns=leftovers_names)\n yield prefixes, suffixes, all_leftovers\n else:\n yield prefixes, suffixes\n prefixes = []\n suffixes = []\n if get_leftovers:\n all_leftovers = []\n iterator += 1\n if len(prefixes) > 0:\n prefixes = tf.keras.preprocessing.sequence.pad_sequences(prefixes, padding='post',\n maxlen=self.orchestrator.max_case_length-1,\n dtype=float)\n suffixes = np.array(suffixes, dtype=float)\n if get_leftovers:\n all_leftovers = pd.DataFrame(data=all_leftovers, columns=leftovers_names)\n yield prefixes, suffixes, all_leftovers\n else:\n yield prefixes, suffixes\n\n def get_epoch_size_online(self, value=None):\n if value is None:\n total = 0\n for cases in self.orchestrator.edit_online(self.input_chunk_size, self.output_chunk_size):\n for case in cases:\n total += len(case) - 1\n print(total, \"cases\")\n else:\n total = np.count_nonzero(self.list == value)\n return total\n\n def run_offline(self):\n write_attribute = \"wb\"\n with open(\"Output/\" + self.orchestrator.output_name + \"/data.npy\", 'rb') as input_file:\n with tqdm(total=self.orchestrator.case_counter, desc='Slice into prefix/suffix') as pbar:\n case_counter = 0\n prefixes = []\n suffixes = []\n # Add all the cases to a list\n while case_counter < self.orchestrator.case_counter:\n case = np.load(input_file, allow_pickle=True)\n case_counter += 1\n pbar.update(1)\n i = 1\n while i < len(case):\n prefixes.append(case[:i])\n suffixes.append(case[i, :self.orchestrator.activity_counter])\n i += 1\n if len(prefixes) == self.output_chunk_size or case_counter == self.orchestrator.case_counter:\n # Write the results!\n # If we are in the first chunk, create a new file. Else, append\n with open(\"Output/\" + self.orchestrator.output_name + \"/prefixes.npy\",\n write_attribute) as output_file:\n for prefix in prefixes:\n np.save(output_file, prefix)\n with open(\"Output/\" + self.orchestrator.output_name + \"/suffixes.npy\",\n write_attribute) as output_file:\n for suffix in suffixes:\n np.save(output_file, suffix)\n if write_attribute == \"wb\":\n write_attribute = \"ab\"\n prefixes = []\n suffixes = []\n\n def read_offline(self, value=None):\n \"\"\"\n Slices cases into suffixes and prefixes (online mode)\n\n \"\"\"\n with open(\"Output/\" + self.orchestrator.output_name + \"/prefixes.npy\", 'rb') as input_file1:\n with open(\"Output/\" + self.orchestrator.output_name + \"/suffixes.npy\", 'rb') as input_file2:\n epoch_size = self.get_epoch_size_offline(value)\n while True:\n iterator = 0\n for chunk_index in range(\n get_total_chunk_number(epoch_size, self.batch_size)):\n prefixes = []\n suffixes = []\n counter = 0\n if chunk_index == get_total_chunk_number(epoch_size, self.batch_size) - 1:\n chunk_range = epoch_size % self.batch_size\n # Else, the number of cases if equal of the size of a chunk\n else:\n chunk_range = self.batch_size\n while counter < chunk_range:\n if value is None or self.list[iterator] == value:\n prefixes.append(np.load(input_file1, allow_pickle=True))\n suffixes.append(np.load(input_file2, allow_pickle=True))\n counter += 1\n iterator += 1\n prefixes = tf.keras.preprocessing.sequence.pad_sequences(prefixes, padding='post',\n maxlen=self.orchestrator.max_case_length-1,\n dtype=float)\n suffixes = np.array(suffixes)\n yield prefixes, suffixes\n input_file1.seek(0)\n input_file2.seek(0)\n\n def get_epoch_size_offline(self, value=None):\n if value is None:\n total = 0\n with open(\"Output/\" + self.orchestrator.output_name + \"/suffixes.npy\", 'rb') as input_file:\n while True:\n try:\n np.load(input_file, allow_pickle=True)\n total += 1\n except:\n break\n print(total, \"cases\")\n else:\n total = np.count_nonzero(self.list == value)\n return total\n\n def decode_single_input(self, input):\n return self.input_decoders.encode_case(input[~np.all(input == 0, axis=1)])\n\n def decode_single_output(self, output):\n raw_result = self.output_decoders.encode_case(output)\n sos_indices = np.where(raw_result == \"SoS\")\n if len(sos_indices) == 0 or len(sos_indices[0]) == 0:\n return raw_result\n else:\n cut = sos_indices[0][-1]\n return raw_result[cut:]\n\n","repo_name":"bvuillemin/DL4PA","sub_path":"DataPreparators/next_activity.py","file_name":"next_activity.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"32392418074","text":"# -*- coding: utf-8 -*-\nfrom pandas import Timedelta\n\n\ndef test_repr():\n assert (repr(Timedelta(10, unit='d')) ==\n \"Timedelta('10 days 00:00:00')\")\n assert (repr(Timedelta(10, unit='s')) ==\n \"Timedelta('0 days 00:00:10')\")\n assert (repr(Timedelta(10, unit='ms')) ==\n \"Timedelta('0 days 00:00:00.010000')\")\n assert (repr(Timedelta(-10, unit='ms')) ==\n \"Timedelta('-1 days +23:59:59.990000')\")\n\n\ndef test_isoformat():\n td = Timedelta(days=6, minutes=50, seconds=3,\n milliseconds=10, microseconds=10, nanoseconds=12)\n expected = 'P6DT0H50M3.010010012S'\n result = td.isoformat()\n assert result == expected\n\n td = Timedelta(days=4, hours=12, minutes=30, seconds=5)\n result = td.isoformat()\n expected = 'P4DT12H30M5S'\n assert result == expected\n\n td = Timedelta(nanoseconds=123)\n result = td.isoformat()\n expected = 'P0DT0H0M0.000000123S'\n assert result == expected\n\n # trim nano\n td = Timedelta(microseconds=10)\n result = td.isoformat()\n expected = 'P0DT0H0M0.00001S'\n assert result == expected\n\n # trim micro\n td = Timedelta(milliseconds=1)\n result = td.isoformat()\n expected = 'P0DT0H0M0.001S'\n assert result == expected\n\n # don't strip every 0\n result = Timedelta(minutes=1).isoformat()\n expected = 'P0DT0H1M0S'\n assert result == expected\n","repo_name":"ViralLeadership/Repositorios","sub_path":"pandas/pandas/tests/scalar/timedelta/test_formats.py","file_name":"test_formats.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24238778071","text":"import subprocess\nimport re\nimport sys\nimport time\n\ndef running_vms():\n try:\n verify_vms = subprocess.check_output([\"vboxmanage\", \"list\", \"runningvms\"]).decode(\"utf-8\")\n if verify_vms:\n vm_list = re.findall(\"\\\"(.*)\\\"\", verify_vms)\n print(\"Active VM's: \", vm_list)\n for i in vm_list:\n print(\"Saving state of: \", i) \n subprocess.call([\"vboxmanage\", \"controlvm\", \"%s\" % i , \"savestate\"])\n time.sleep(2)\n # Add some delay and kill VirtualBox Itself (if running) - Stopping VirtualBox is required to flush mem\n subprocess.call([\"kill\", \"VirtualBox\"])\n time.sleep(2)\n sys.exit(0)\n else:\n subprocess.call([\"kill\", \"VirtualBox\"])\n time.sleep(2)\n except:\n print(\"save_vm exception\")\n sys.exit(0)\n\nrunning_vms()\n","repo_name":"RonnieMcC/virtualbox_save_on_suspend","sub_path":"save_vm.py","file_name":"save_vm.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"48633970953","text":"from turtle import Turtle\nALIGNMENT = \"center\"\nFONT = ('Courier', 22, 'normal')\n\n\nclass Scoreboard(Turtle):\n\n def __init__(self):\n super().__init__()\n self.point = 0\n self.high_score = int(self.read_high_score())\n self.shape(\"square\")\n self.shapesize(stretch_wid=1, stretch_len=4)\n self.pencolor(\"white\")\n self.penup()\n self.fillcolor(\"black\")\n self.set_score()\n\n def set_score(self):\n self.goto(0, 270)\n self.clear()\n self.write(f\"Score: {self.point} High Score: {self.high_score}\", True, align=ALIGNMENT, font=FONT)\n self.hideturtle()\n\n def increment_score(self):\n self.point += 1\n self.clear()\n\n def reset(self):\n if self.point > self.high_score:\n self.high_score = self.point\n self.write_high_score()\n self.point = 0\n\n def read_high_score(self):\n with open(\"data.txt\") as file:\n return file.read()\n\n def write_high_score(self):\n with open(\"data.txt\", mode=\"w\") as file:\n file.write(str(self.point))\n","repo_name":"amanuel496/snake-game","sub_path":"scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25701979360","text":"#!/usr/bin/python\nimport os, sys, time, re\nif len(sys.argv) == 1:\n exit(\"Usage: {prog} [pkgdir] [libdir] [datadir] [dataname] [mod_pth] [queue]\".format(prog=sys.argv[0]))\n\npkgdir, libdir, datadir, dataname, mod_pth, queue = sys.argv[1:]\n\nseqname=\"seq.fasta\"\nhomoflag=\"real\"\nidcut=\"0.3\"\nuser = os.popen(\"whoami\").readline().strip()\n\nlogdir = '{datadir}/qsub_SSITE_log'.format(datadir=datadir)\nos.makedirs(logdir, exist_ok=True)\ntag = \"SS.{name}\".format(name=dataname)\nerr = \"{logdir}/err\".format(logdir=logdir)\nout = \"{logdir}/out\".format(logdir=logdir)\nresource = \"walltime=10:00:00\"\nrun_prog = \"{logdir}/run_prog.sh\".format(logdir=logdir)\n\n\n## check if the job exists\nstring = '\\n'.join(os.popen('/usr/local/bin/qstat -f | grep -B 1 \"Job_Owner.*{user}\"'.format(user=user)).readlines())\npattern = re.compile(tag)\nresult = pattern.findall(string)\nif result:\n print(\"job {tag} already running\".format(tag=tag))\n exit(0)\n\n\nf = open(mod_pth,'r')\na = f.read()\na = a.replace(\"!PKGDIR!\", pkgdir)\na = a.replace(\"!LIBDIR!\", libdir)\na = a.replace(\"!DATADIR!\", datadir)\na = a.replace(\"!OUTDIR!\", datadir)\na = a.replace(\"!NAME!\", dataname)\na = a.replace(\"!SEQNAME!\", seqname)\na = a.replace(\"!TAG!\", tag)\na = a.replace(\"!RUN!\", homoflag)\na = a.replace(\"!USER!\", user)\na = a.replace(\"!ID_CUT!\", idcut)\nf.close()\n\ng = open(run_prog, 'w+')\ng.write(a)\ng.close()\n\nos.system(\"chmod 700 %s\" %run_prog)\nos.system(queue)\n\nos.system(\"/usr/local/bin/qsub -e %s -o %s -l %s -N %s %s\" %(err,out,resource,tag,run_prog))\nprint('{run_prog} successfully submitted!'.format(run_prog=run_prog))\ntime.sleep(1)","repo_name":"ruiyangsong/DMBS","sub_path":"bin/run_ssite.py","file_name":"run_ssite.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70114535081","text":"#\n# https://leetcode.com/problems/insert-into-a-binary-search-tree/\n#\n# You are given the root node of a binary search tree (BST) and a value \n# to insert into the tree. Return the root node of the BST \n# after the insertion. It is guaranteed that the new value does not exist \n# in the original BST.\n#\n# Notice that there may exist multiple valid ways for the insertion, \n# as long as the tree remains a BST after insertion. \n# You can return any of them.\n#\n# Constraints:\n# - The number of nodes in the tree will be in the range [0, 10^4].\n# - -10^8 <= Node.val <= 10^8\n# - All the values Node.val are unique.\n# - -10^8 <= val <= 10^8\n# - It's guaranteed that val does not exist in the original BST.\n# \n\nfrom typing import List\nimport sys\nimport pdb\nbr = pdb.set_trace\n\nsolution_json = {\n \"date\": \"2022/?/??\",\n \"design\": 0,\n \"coding\": 0,\n \"runtime\": \"?? ms\",\n \"fasterThan\": \"\",\n \"memory\": \"?? MB\" \n}\n\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\nclass Solution:\n def __init__(self):\n self.module = sys.modules[__name__]\n\n def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:\n pass","repo_name":"CountChu/LeetCodePython","sub_path":"learn_15_binary_search_tree/problems/0701-insert-bst.py","file_name":"0701-insert-bst.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36208737375","text":"from itertools import *\nfrom collections import *\nfrom heapq import *\nfrom bisect import *\nfrom copy import *\nimport math\nimport sys\nsys.setrecursionlimit(1<<20)\nINF = float('inf')\nN = int(input())\nedges = []\nfor _ in range(N-1):\n a,b = map(int,input().split())\n a-=1\n b-=1\n edges.append((a,b))\n \n\ndef sumOfDistancesInTree(N, edges):\n graph = defaultdict(list)\n for i, j in edges:\n graph[i].append(j)\n graph[j].append(i)\n \n size, up, down = [1] * N, [0] * N, [0] * N\n\n def post(parent, i): \n for kid in graph[i]:\n if kid != parent:\n post(i, kid)\n size[i] += size[kid]\n up[i] += up[kid] + size[kid] \n \n def pre(parent, i):\n if parent!=-1:\n down[i] = down[parent] + (up[parent] - up[i] - size[i]) + (N-size[i])\n for kid in graph[i]: \n if kid != parent:\n pre(i, kid)\n \n post(-1, 0) \n pre(-1, 0) \n return [up[i]+down[i] for i in range(N)] \nans = sumOfDistancesInTree(N,edges)\nprint(*ans,sep='\\n')","repo_name":"to24toro/Atcoder","sub_path":"ABC220/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1547024820","text":"def isLeapYear(y):\n '''\n Check if the given year is a leap year\n params:\n y-the given year\n output\n True - if y is leap\n False - if y is not leap\n '''\n return (int(y)%4 == 0 and int(y)%100 != 0) or y%400 == 0\n\ndef countLeapYears(year1,year2):\n '''\n Counts the leap years between two years\n params:\n year1-the first year\n year2-the second year\n output\n leap years between year1 and year2(without counting them)\n '''\n count=0\n for i in range(year1+1,year2):\n if isLeapYear(i):\n count+=1\n return count\n\ndef monthDays(y):\n '''\n The number of days in every month, depending on year\n params:\n y-year given\n output\n a list with the days of every month\n '''\n if isLeapYear(y):\n return [31,29,31,30,31,30,31,31,30,31,30,31]\n else:\n return [31,28,31,30,31,30,31,31,30,31,30,31]\n\ndef toDays(date1,date2):\n\n '''\n The days between two dates\n params:\n date1-the first date\n date2-the second date\n output\n the number of days between two dates\n '''\n #add the years between dates\n x=countLeapYears(date1['year'],date2['year'])\n days=x*366+(date2['year']-date1['year']-x-1)*365\n\n #add days from the birth year\n months=monthDays(date1['year'])\n days+=months[date1['month']-1]-date1['day']+1 #add days from the birth month\n for i in range(date1['month'],12): #add days from the remaining months\n days+=months[i]\n\n #add days from the current year\n months=monthDays(date2['year']) \n days+=date2['day'] #add days from current month\n for i in range(0,date2['month']-1): #add days from the previous months of the current year\n days+=months[i]\n return days\n\nl=input('Give your date of birth (day/month/year): ').split(\"/\")\ndate1={'year':int(l[2]),'month':int(l[1]),'day':int(l[0])}\nl=input('Give current date (day/month/year): ').split(\"/\")\ndate2={'year':int(l[2]),'month':int(l[1]),'day':int(l[0])}\n\nprint('Your age in days is: ' + str(toDays(date1,date2)))\n","repo_name":"AndreeaCimpean/Uni","sub_path":"Sem1/FP/L1/ThirdSet12.py","file_name":"ThirdSet12.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7437584042","text":"import os\r\nimport time as t\r\nimport datetime as dt\r\nimport fnmatch as mask\r\nimport zipfile\r\n\r\nimport list_files_from_local_dir as fl\r\n\r\n\r\ndef compress_files(file_list, file_mask, target_dir, archive_name):\r\n os.chdir(target_dir) # change directory to target output dir\r\n with zipfile.ZipFile(file=archive_name, mode=\"w\", compression=zipfile.ZIP_DEFLATED) as zip:\r\n for file_path in file_list:\r\n f = os.path.basename(file_path)\r\n #print(f) #WinFormClientSmall.png\r\n if mask.fnmatch(f, file_mask):\r\n zip.write(file_path, f) # use f to prevent absolute path in archive\r\n print(\"All files matching file mask %s have been compressed successfully\" % file_mask)\r\n zip.close()\r\n\r\ndef print_compressed_files(archive_name):\r\n with zipfile.ZipFile(file=archive_name, mode=\"r\") as zip:\r\n for detail in zip.infolist():\r\n print(\"File Name: \" + detail.filename)\r\n print(\"\\tCompressed: \" + str(detail.compress_size) + \" bytes\")\r\n print(\"\\tDecompressed: \" + str(detail.file_size) + \" bytes\")\r\n zip.close()\r\n\r\ndef decompress_files(archive_name, target_dir):\r\n with zipfile.ZipFile(file=archive_name, mode=\"r\") as zip:\r\n #print(\"Archive Content:\")\r\n #zip.printdir()\r\n os.chdir(INPUT_DIR)\r\n print(\"Decompressing now...\")\r\n zip.extractall()\r\n #zip.extract(\"WinFormClientSmall.png\")\r\n print(\"Decompressing done\")\r\n zip.close()\r\n\r\n# ----------------------------------------------------------------------------------------------------\r\nDEBUG = False\r\n\r\nLOCAL_PATH = \"/dev/py/temp/\"\r\nFILE_MASK = \"*.png\"\r\nfiles = fl.list_files_from_local_dir(LOCAL_PATH, FILE_MASK)\r\n\r\nOUTPUT_DIR = \"/dev/py/data/output/\"\r\nARCHIVE_NAME = \"archive_\" + dt.datetime.fromtimestamp(t.time()).strftime('%Y%m%d%H%M%S') + \".zip\"\r\nINPUT_DIR = \"/dev/py/data/input/\"\r\n\r\nif __name__ == \"__main__\":\r\n f = files\r\n compress_files(f, FILE_MASK, OUTPUT_DIR, ARCHIVE_NAME)\r\n print_compressed_files(ARCHIVE_NAME)\r\n decompress_files(ARCHIVE_NAME, INPUT_DIR)\r\n\r\n","repo_name":"sjantke/Useful-Utils-Python","sub_path":"compress_decompress_files.py","file_name":"compress_decompress_files.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22136946468","text":"arr = []\r\nt = int(input())\r\nfor _ in range(t):\r\n arr.append(input())\r\nx = arr.count(arr[0])\r\nif x > int(t/2):\r\n print(arr[0])\r\nelse:\r\n for i in range(t):\r\n if arr[i] != arr[0]:\r\n print(arr[i])\r\n break\r\n\r\n \r\n\r\n ","repo_name":"mlabeeb03/codeforces","sub_path":"Football.py","file_name":"Football.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4006749964","text":"from tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_training_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.training import optimizer\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(v1=[\"train.AdagradDAOptimizer\"])\nclass AdagradDAOptimizer(optimizer.Optimizer):\n \"\"\"Adagrad Dual Averaging algorithm for sparse linear models.\n\n This optimizer takes care of regularization of unseen features in a mini batch\n by updating them when they are seen with a closed form update rule that is\n equivalent to having updated them on every mini-batch.\n\n AdagradDA is typically used when there is a need for large sparsity in the\n trained model. This optimizer only guarantees sparsity for linear models. Be\n careful when using AdagradDA for deep networks as it will require careful\n initialization of the gradient accumulators for it to train.\n\n References:\n Adaptive Subgradient Methods for Online Learning and Stochastic Optimization\n :[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html)\n ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf))\n \"\"\"\n\n def __init__(self,\n learning_rate,\n global_step,\n initial_gradient_squared_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0,\n use_locking=False,\n name=\"AdagradDA\"):\n \"\"\"Construct a new AdagradDA optimizer.\n\n Args:\n learning_rate: A `Tensor` or a floating point value. The learning rate.\n global_step: A `Tensor` containing the current training step number.\n initial_gradient_squared_accumulator_value: A floating point value.\n Starting value for the accumulators, must be positive.\n l1_regularization_strength: A float value, must be greater than or\n equal to zero.\n l2_regularization_strength: A float value, must be greater than or\n equal to zero.\n use_locking: If `True` use locks for update operations.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to \"AdagradDA\".\n\n Raises:\n ValueError: If the `initial_gradient_squared_accumulator_value` is\n invalid.\n \"\"\"\n if initial_gradient_squared_accumulator_value <= 0.0:\n raise ValueError(\"initial_gradient_squared_accumulator_value must be \"\n \"positive: %s\" %\n initial_gradient_squared_accumulator_value)\n super(AdagradDAOptimizer, self).__init__(use_locking, name)\n self._learning_rate = learning_rate\n self._initial_gradient_squared_accumulator_value = (\n initial_gradient_squared_accumulator_value)\n # Created in Initialize.\n self._learning_rate_tensor = None\n self._l1_regularization_strength = l1_regularization_strength\n self._l2_regularization_strength = l2_regularization_strength\n self._global_step = global_step\n self._global_step_on_worker = None\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n g_val = constant_op.constant(\n 0.0, shape=v.get_shape(), dtype=v.dtype.base_dtype)\n gg_val = constant_op.constant(\n self._initial_gradient_squared_accumulator_value,\n shape=v.get_shape(),\n dtype=v.dtype.base_dtype)\n self._get_or_make_slot(v, g_val, \"gradient_accumulator\", self._name)\n self._get_or_make_slot(v, gg_val, \"gradient_squared_accumulator\",\n self._name)\n\n def _prepare(self):\n self._learning_rate_tensor = ops.convert_to_tensor(\n self._learning_rate, name=\"learning_rate\")\n # Performance optimization so that worker creates a copy of the global step\n # to avoid overloading the parameter server holding the global step.\n with ops.colocate_with(self._learning_rate_tensor):\n self._global_step_on_worker = array_ops.identity(self._global_step) + 1\n\n def _apply_dense(self, grad, var):\n g_acc = self.get_slot(var, \"gradient_accumulator\")\n gg_acc = self.get_slot(var, \"gradient_squared_accumulator\")\n with ops.device(var.device):\n global_step = array_ops.identity(self._global_step_on_worker)\n return gen_training_ops.apply_adagrad_da(\n var,\n g_acc,\n gg_acc,\n grad,\n math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),\n math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype),\n math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype),\n global_step,\n use_locking=self._use_locking)\n\n def _resource_apply_dense(self, grad, var):\n g_acc = self.get_slot(var, \"gradient_accumulator\")\n gg_acc = self.get_slot(var, \"gradient_squared_accumulator\")\n with ops.device(var.device):\n global_step = array_ops.identity(self._global_step_on_worker)\n return gen_training_ops.resource_apply_adagrad_da(\n var.handle,\n g_acc.handle,\n gg_acc.handle,\n grad,\n math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype),\n math_ops.cast(self._l1_regularization_strength, grad.dtype.base_dtype),\n math_ops.cast(self._l2_regularization_strength, grad.dtype.base_dtype),\n global_step,\n use_locking=self._use_locking)\n\n def _apply_sparse(self, grad, var):\n g_acc = self.get_slot(var, \"gradient_accumulator\")\n gg_acc = self.get_slot(var, \"gradient_squared_accumulator\")\n with ops.device(var.device):\n global_step = array_ops.identity(self._global_step_on_worker)\n return gen_training_ops.sparse_apply_adagrad_da(\n var,\n g_acc,\n gg_acc,\n grad.values,\n grad.indices,\n math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),\n math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype),\n math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype),\n global_step,\n use_locking=self._use_locking)\n\n def _resource_apply_sparse(self, grad, var, indices):\n g_acc = self.get_slot(var, \"gradient_accumulator\")\n gg_acc = self.get_slot(var, \"gradient_squared_accumulator\")\n with ops.device(var.device):\n global_step = array_ops.identity(self._global_step_on_worker)\n return gen_training_ops.resource_sparse_apply_adagrad_da(\n var.handle,\n g_acc.handle,\n gg_acc.handle,\n grad,\n indices,\n math_ops.cast(self._learning_rate_tensor, grad.dtype),\n math_ops.cast(self._l1_regularization_strength, grad.dtype),\n math_ops.cast(self._l2_regularization_strength, grad.dtype),\n global_step,\n use_locking=self._use_locking)\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/training/adagrad_da.py","file_name":"adagrad_da.py","file_ext":"py","file_size_in_byte":6821,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"26962755453","text":"from openpyxl import load_workbook\nfrom src.matcher import *\nimport json\n\n# the index of the precondition\npre_index = 5\n\n\ndef json_directory(json_name):\n with open('json\\\\' + json_name) as f:\n return json.load(f)\n\n\ndata_sheet = json_directory('sheet_related.json')\nkeywords = json_directory('keywords.json')\nauto_case_list = json_directory('auto_case_id.json')\n\n\n# def tc_location_dict():\n# tc_location = load_workbook('TC_location.xlsx').active\n# # stored the data in a dictionary {test_case: location}\n# return {TCID: location for (TCID, location) in tc_location.iter_rows(\n# max_col=2, values_only=True) if TCID is not None}\n\n# Determine the phone type (iPhone or Android)\n\n\ndef phone_type(cell_data):\n iphone = keywords['iphone']\n android = keywords['android']\n phone_requirement = [0, 0]\n for cell in cell_data[pre_index:pre_index+2]:\n if matcher_split(iphone, cell):\n phone_requirement[0] = 1\n if matcher_slice(android, cell):\n phone_requirement[1] = 1\n if phone_requirement == [1, 0]:\n cell_data.append('iPhone')\n elif phone_requirement == [0, 1]:\n cell_data.append('Android')\n elif phone_requirement == [1, 1]:\n cell_data.append('Both')\n else:\n cell_data.append(' ')\n\n# Determine the sign-in or -out\n\n\ndef sign_status(cell_data):\n sign_out = keywords['sign_out']\n sign_in = keywords['sign_in']\n if matcher_slice(sign_out, cell_data[pre_index]):\n cell_data.append('sign_out')\n elif matcher_slice(sign_in, cell_data[pre_index]):\n cell_data.append('sign_in')\n else:\n cell_data.append('sign_out')\n\n\ndef connection(cell_data):\n offline = keywords['offline']\n if matcher_split(offline, cell_data[pre_index]):\n cell_data.append('Offline')\n else:\n cell_data.append('Online')\n\n\ndef user(cell_data):\n guest = keywords['guest']\n non_guest = keywords['non_guest']\n others = keywords['others']\n primary = keywords['primary']\n if (matcher_split(guest, cell_data[pre_index]) or matcher_split(guest, cell_data[pre_index+3])) and matcher_slice(non_guest, cell_data[pre_index]) is False:\n cell_data.append('Guest')\n elif matcher_slice(others, cell_data[pre_index]) or matcher_slice(non_guest, cell_data[pre_index]) or matcher_slice(others, cell_data[pre_index+3]):\n cell_data.append('Others')\n elif matcher_split(guest, cell_data[pre_index+1]) and (matcher_slice(others, cell_data[pre_index+1]) or matcher_split(primary, cell_data[pre_index+1])):\n cell_data.append('multiple')\n else:\n cell_data.append('Driver')\n","repo_name":"k1ngjet3r/precode-detector","sub_path":"src/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20393315458","text":"from PIL import Image\nimport os\nimport numpy as np\nfrom multiprocessing import Pool\nfrom glob import glob\nimport argparse\n\ndef evaluate(param):\n pred_name, gt_name = param\n mask = Image.open(pred_name)\n gt = Image.open(gt_name)\n\n mask = mask.resize(gt.size)\n mask = np.array(mask, dtype=np.float)\n mask = (mask - mask.min()) / (mask.max()-mask.min()+eps)\n\n gt = np.array(gt, dtype=np.uint8)\n\n if len(mask.shape) != 2:\n mask = mask[:, :, 0]\n\n if len(gt.shape) > 2:\n gt = gt[:, :, 0]\n gt[gt != 0] = 1\n\n precision = []\n recall = []\n\n mae = np.abs(gt-mask).mean()\n\n binary = np.zeros(mask.shape)\n th = 2*mask.mean()\n if th >1:\n th = 1\n\n binary[mask >= th] = 1\n sb = (binary * gt).sum()\n\n pre = sb / (binary.sum() + eps)\n rec = sb / (gt.sum() + eps)\n\n thfm = 1.3 * pre * rec / (0.3 * pre + rec + eps)\n\n for th in np.linspace(0,1,21):\n binary = np.zeros(mask.shape)\n binary[mask >= th] = 1\n pre = (binary * gt).sum() / (binary.sum()+eps)\n rec = (binary * gt).sum() / (gt.sum()+eps)\n precision.append(pre)\n recall.append(rec)\n precision = np.array(precision)\n recall = np.array(recall)\n return thfm, mae, recall, precision\n\n\n\ndef fm_and_mae(pred_dir, gt_dir, output_dir=None):\n if output_dir is not None and not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n pred_list = sorted(glob(pred_dir + \"/*\"))\n gt_list = sorted(glob(gt_dir + \"/*\"))\n\n pool = Pool(4)\n results = pool.map(evaluate, zip(pred_list, gt_list))\n thfm, meas, recs, pres = list(map(list, zip(*results)))\n m_mea = np.array(meas).mean()\n m_pres = np.array(pres).mean(0)\n m_recs = np.array(recs).mean(0)\n thfm = np.array(thfm).mean()\n\n fms = 1.3 * m_pres * m_recs / (0.3 * m_pres + m_recs + eps)\n maxfm = fms.max()\n meanfm = fms.mean()\n\n return maxfm, meanfm, m_mea, m_recs, m_pres\n\ndef f_measure(param):\n pres, recs = param\n return 1.3 * pres * recs / (0.3 * pres + recs + eps)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--pred_dir', default='results')\n parser.add_argument('--mask_dir', default='datasets/ECSSD/gt')\n\n args = parser.parse_args()\n\n maxfm, meanfm, m_mea, _, _ = fm_and_mae(pred_dir=args.pred_dir, gt_dir=args.mask_dir)\n\n print(\"Max F-measure: {:.4f}\".format(maxfm))\n print(\"Mean F-measure: {:.4f}\".format(meanfm))\n print(\"Mean Absolute Error: {:.4f}\".format(m_mea))","repo_name":"tiruss/PMNet","sub_path":"Evaluate.py","file_name":"Evaluate.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"42201941527","text":"'''\n VALIDATION CODE SHARED BY EACH ALGORITHMS\n MADE BY DOOSEOP CHOI (d1024.choi@etri.re.kr)\n DATE : 2019-12-06\n'''\n\n\nfrom sdd_model import Model\nfrom sdd_utils import DataLoader\nfrom sdd_functions import *\nimport pickle\nimport os\nimport argparse\nimport cv2\n#import matplotlib.pyplot as plt\n\ndef sigmoid(img):\n\n # sig = 1 / (1 + np.exp(-9.0 * (img - 0.5)))\n img = img -np.min(img[:])\n sig = img / np.max(img[:])\n\n return sig\n\ndef show_trajs_test(traj, map, is_gt):\n\n if (is_gt == True):\n color = (255, 255, 255)\n else:\n color = (0, 0, 255)\n\n # ground-truth traj\n for j in range(1, traj.shape[0]):\n\n cur_gt_x = int(traj[j, 0])\n cur_gt_y = int(traj[j, 1])\n pre_gt_x = int(traj[j-1, 0])\n pre_gt_y = int(traj[j-1, 1])\n\n if (j < 8):\n cv2.line(map, (pre_gt_x, pre_gt_y), (cur_gt_x, cur_gt_y), (255, 0, 0), 2)\n else:\n cv2.line(map, (pre_gt_x, pre_gt_y), (cur_gt_x, cur_gt_y), color, 2)\n\n return map\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset_num', type=int, default=0, help='target dataset number')\n parser.add_argument('--exp_id', type=int, default=0, help='experiment id')\n parser.add_argument('--gpu_num', type=int, default=0, help='target gpu')\n\n input_args = parser.parse_args()\n test(input_args)\n\n# ------------------------------------------------------\n# load saved network and parameters\n\ndef test(input_args):\n\n path = './save_' + str(input_args.dataset_num) + '_' + str(input_args.exp_id)\n\n # load parameter setting\n with open(os.path.join(path, 'config.pkl'), 'rb') as f:\n try:\n saved_args = pickle.load(f)\n print('>> cpkl file was created under python 3.x')\n except ValueError:\n saved_args = pickle.load(f, encoding='latin1')\n print('>> cpkl file was created under python 2.x')\n\n\n if (input_args.gpu_num == 0):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n elif (input_args.gpu_num == 1):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n elif (input_args.gpu_num == 2):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\n elif (input_args.gpu_num == 3):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n\n obs_len = saved_args.obs_length\n pred_len = saved_args.pred_length\n\n # define model structure\n model = Model(saved_args, True)\n\n # load trained weights\n ckpt = tf.train.get_checkpoint_state(path)\n sess = tf.InteractiveSession()\n saver = tf.train.Saver()\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\">> loaded model: \", ckpt.model_checkpoint_path)\n\n\n # ------------------------------------------------------\n # variable definition for validation\n\n init_state = np.zeros(shape=(1, 1, 2*saved_args.rnn_size))\n\n # load validation data\n data_loader = DataLoader(saved_args)\n\n ADE = []\n FDE = []\n traj = []\n EST_traj = []\n Pid_list = []\n Data_list = []\n cnt = 0\n\n printProgressBar(0, data_loader.num_test_scenes - 1, prefix='Progress:', suffix='Complete', length=50, epoch=0)\n for b in range(data_loader.num_test_scenes):\n\n # data load\n xo, xp, xoo, xpo, did, pid = data_loader.next_batch_test([b])\n mo = make_map_batch(xo, did, data_loader.map, saved_args.map_size)\n\n # prediction\n est_offset = np.squeeze(model.sample(sess, xoo, mo, init_state)) # modification\n\n # reconstrunction (est traj)\n est_offset_recon = np.concatenate([xoo[0].reshape(saved_args.obs_length, 2), est_offset], axis=0)\n est_offset_recon[0, :] = xo[0][0, :].reshape(1, 2)\n est_traj_recon = np.cumsum(est_offset_recon, axis=0)\n EST_traj.append(est_traj_recon)\n\n # reconstruction (original)\n x_recon = np.concatenate([xo[0].reshape(obs_len, 2), xp[0].reshape(pred_len, 2)], axis=0)\n traj.append(x_recon)\n\n if (True):\n\n map_show = np.copy(data_loader.map[int(did[0][0])])\n map_show = show_trajs_test(x_recon, map_show, True)\n map_show = show_trajs_test(est_traj_recon, map_show, False)\n\n cv2.imshow('', map_show.astype('uint8'))\n cv2.waitKey(0)\n\n\n # calculate error\n err_vector = (est_traj_recon - x_recon)[obs_len:] / 0.25\n displacement_error = np.sqrt(err_vector[:, 0] ** 2 + err_vector[:, 1] ** 2)\n\n ADE.append(displacement_error)\n FDE.append(displacement_error[pred_len-1])\n cnt += 1\n\n Pid_list.append(pid)\n Data_list.append(did)\n\n printProgressBar(b, data_loader.num_test_scenes - 1, prefix='Progress:', suffix='Complete', length=50, epoch=0)\n\n # save\n save_dir = './test_result_irl_%d.cpkl' % input_args.dataset_num\n f = open(save_dir, \"wb\")\n pickle.dump([traj, EST_traj, Data_list, Pid_list, data_loader.map, ADE, FDE], f, protocol=2)\n f.close()\n\nif __name__ == '__main__':\n main()","repo_name":"d1024choi/traj-pred-irl","sub_path":"SDD/sdd_test_visualization.py","file_name":"sdd_test_visualization.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"18"} +{"seq_id":"9658910720","text":"\nimport argparse\nfrom chainer import Chain, Variable, optimizers\nimport chainer.links as L\nimport chainer.functions as F\nimport numpy as np\nimport random\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-e', '--epoch', type=int, default=100)\nparser.add_argument('-n', '--max-num', type=int, default=100)\nargs = parser.parse_args()\n\nbinary_size = len(bin(args.max_num)) - 2\nin_num = binary_size\nhidden_num = 10\nout_num = 2\n\nmodel = Chain(l1 = L.Linear(in_num, hidden_num),\n l2 = L.Linear(hidden_num, hidden_num),\n l3 = L.Linear(hidden_num, out_num))\n\n\ndef to_input_binary(n, binary_size):\n fmt = '{0:%sb}' % (binary_size)\n res = list(fmt.format(n))\n res = [0 if x == ' ' else float(x) for x in res]\n return res\n\ndef to_output_binary(n):\n if n % 15 == 0:\n return [0, 0]\n elif n % 5 == 0:\n return [0, 1]\n elif n % 3 == 0:\n return [1, 0]\n else:\n return [1, 1]\n\ndef to_str(i, pred):\n pred = list(map(lambda x: int(round(x)), pred))\n if pred == [0, 0]:\n return 'FizzBuzz'\n elif pred == [0, 1]:\n return 'Buzz'\n elif pred == [1, 0]:\n return 'Fizz'\n else:\n return str(i)\n\ndef train(model, optimizer, epoch, max_num, binary_size):\n for _ in range(epoch):\n nums = list(range(1, max_num))\n random.shuffle(nums)\n for n in nums:\n x = Variable(np.asarray([to_input_binary(n, binary_size)], np.float32))\n t = Variable(np.asarray([to_output_binary(n)], np.float32))\n \n optimizer.zero_grads()\n h = F.relu(model.l1(x))\n h = F.relu(model.l2(h))\n y = model.l3(h)\n loss = F.mean_squared_error(y,t)\n loss.backward()\n optimizer.update()\n \n\ndef predict(model, num, binary_size):\n x = Variable(np.asarray([to_input_binary(num, binary_size)], np.float32))\n h = F.relu(model.l1(x))\n h = F.relu(model.l2(h))\n y = model.l3(h)\n return to_str(num, y.data[0])\n\n\n\noptimizer = optimizers.Adam()\noptimizer.setup(model)\n\ntrain(model, optimizer, args.epoch, args.max_num, binary_size)\n\nfor i in range(1, args.max_num):\n pred = predict(model, i, binary_size)\n print(pred)\n","repo_name":"tommyfms2/fizzbuzz","sub_path":"fizzbuzzbytommy.py","file_name":"fizzbuzzbytommy.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30025298839","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n# Script permettant de faire la segmentation du OC et du OD pour le diagnostic de glaucome grâce au CDR\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfrom skimage.measure import label, regionprops\r\nfrom scipy.spatial import distance as dis\r\nimport scipy.ndimage.measurements as snm\r\nimport csv\r\n\r\n# import xlsxwriter module \r\nimport xlsxwriter \r\n\r\n\r\ninput_folder = '../OC_OD_segmentation/'\r\n\r\noc_folder = input_folder + 'oc_results/'\r\noc_list = os.listdir(oc_folder)\r\noc_list.sort()\r\n\r\nod_folder = input_folder + 'od_results/'\r\nod_list = os.listdir(od_folder)\r\nod_list.sort()\r\n\r\n\r\n# Compute the vertical diameter of a convex region (OC or OD) \r\n \r\ndef vertical_diameter(binary_image):\r\n \r\n label_image = label(binary_image)\r\n \r\n # Compute the boundary box of each connected component in the label image\r\n for region in regionprops(label_image):\r\n minr, minc, maxr, maxc = region.bbox\r\n \r\n vertical = maxr - minr\r\n horizontal = maxc - minc\r\n \r\n return vertical, horizontal\r\n\r\n\r\n# Compute the location (x,y) of the four quadrants points of a convex region (OC or OD)\r\n \r\ndef quadrants(binary_image):\r\n \r\n label_image = label(binary_image)\r\n \r\n # Compute the boundary box of each connected component in the label image\r\n for region in regionprops(label_image):\r\n minr, minc, maxr, maxc = region.bbox\r\n \r\n inferior = (maxr, minc + int((maxc - minc)/2))\r\n superior = (minr, minc + int((maxc - minc)/2))\r\n \r\n nasal = (minr + int((maxr - minr)/2), minc)\r\n temporal = (minr + int((maxc - minr)/2), maxc)\r\n \r\n return inferior, superior, nasal, temporal\r\n\r\n\r\n\r\n# Notching function: if true, the ISNT is not respected and the optic nerve head potentially suffers from glaucoma\r\n \r\ndef notching(inferior_oc, superior_oc, nasal_oc, temporal_oc, inferior_od, superior_od, nasal_od, temporal_od):\r\n \r\n inf_sector = inferior_od[0] - inferior_oc[0]\r\n sup_sector = superior_oc[0] - superior_od[0]\r\n \r\n nasal_sector = nasal_oc[1] - nasal_od[1]\r\n temporal_sector = temporal_od[1] - temporal_oc[1]\r\n \r\n print(inf_sector)\r\n print(sup_sector)\r\n print(nasal_sector)\r\n print(temporal_sector)\r\n \r\n if ((inf_sector < sup_sector < nasal_sector) and (inf_sector < sup_sector < temporal_sector)):\r\n return True\r\n else:\r\n return False\r\n \r\n \r\ndef nrr_area(oc_image, od_image):\r\n \r\n oc_area = len(oc_image[oc_image != 0])\r\n od_area = len(od_image[od_image != 0])\r\n \r\n print(oc_area)\r\n print(od_area)\r\n \r\n rim_area = od_area - oc_area\r\n \r\n return rim_area\r\n \r\n \r\n\"\"\"\r\noc = cv2.imread(oc_folder + 'drishtiGS_002.png')\r\n\r\noc_image = cv2.imread(oc_folder + 'drishtiGS_002.png', 0)\r\nod_image = cv2.imread(od_folder + 'drishtiGS_002.png', 0)\r\n\r\nvertical_oc, horizontal_oc = vertical_diameter(oc_image)\r\nvertical_od, horizontal_od = vertical_diameter(od_image)\r\n\r\ncdr = vertical_oc/vertical_od\r\n\r\ninferior_oc, superior_oc, nasal_oc, temporal_oc = quadrants(oc_image)\r\ninferior_od, superior_od, nasal_od, temporal_od = quadrants(od_image)\r\n\r\nnotch = notching(inferior_oc, superior_oc, nasal_oc, temporal_oc, inferior_od, superior_od, nasal_od, temporal_od)\r\n\r\nrim_area = nrr_area(oc_image, od_image)\r\n\"\"\"\r\n\r\n\r\n\r\n\"\"\" ---------------------------------------------------------------------------------------------- \"\"\"\r\n\r\n\r\nmeasures = [['image', 'Vertical CDR', 'Notching', 'NRR area']]\r\n\r\nfor i, fichier in enumerate(oc_list):\r\n\r\n print(\"Processing sur l'image %d\" % (i+1))\r\n\r\n oc_image = cv2.imread(oc_folder + fichier, 0)\r\n od_image = cv2.imread(od_folder + fichier, 0)\r\n \r\n vertical_oc, horizontal_oc = vertical_diameter(oc_image)\r\n vertical_od, horizontal_od = vertical_diameter(od_image)\r\n \r\n cdr = vertical_oc/vertical_od\r\n \r\n inferior_oc, superior_oc, nasal_oc, temporal_oc = quadrants(oc_image)\r\n inferior_od, superior_od, nasal_od, temporal_od = quadrants(od_image)\r\n \r\n notch = notching(inferior_oc, superior_oc, nasal_oc, temporal_oc, inferior_od, superior_od, nasal_od, temporal_od)\r\n \r\n rim_area = nrr_area(oc_image, od_image)\r\n \r\n measure = [[fichier, cdr, notch, rim_area]]\r\n \r\n measures = np.concatenate((measures, measure))\r\n \r\n \r\n \r\nworkbook = xlsxwriter.Workbook('measures.xlsx') \r\n \r\n# By default worksheet names in the spreadsheet will be Sheet1, Sheet2 etc., but we can also specify a name. \r\nworksheet = workbook.add_worksheet(\"My sheet\") \r\n \r\n# Start from the first cell. Rows and columns are zero indexed. \r\nrow = 0\r\ncol = 0\r\n \r\n# Iterate over the data and write it out row by row. \r\nfor image, cdr, isnt, rim_area in (measures): \r\n \r\n worksheet.write(row, col, image) \r\n worksheet.write(row, col + 1, cdr)\r\n worksheet.write(row, col + 2, isnt)\r\n worksheet.write(row, col + 3, rim_area)\r\n row += 1\r\n \r\nworkbook.close() \r\n \r\n \r\n \r\n \r\n#cv2.circle(oc,(temporal[1], temporal[0]), 5, (0,0,255), -1)\r\n\r\n#plt.imshow(oc)\r\n#plt.imshow(od_image)\r\n#plt.show()\r\n\r\n\r\n\"\"\"\r\n# Fonction faisant le calcul de l'aire d'une image binaire\r\ndef calcul_aire(binary_image):\r\n \r\n binary_image = binary_image[binary_image != 0]\r\n aire = len(binary_image)\r\n \r\n return aire\r\n\r\n\r\n# Fonction établissant le diagnostic en fonction du ratio\r\ndef diagnostic(ratio):\r\n \r\n if ratio < 0.64:\r\n diag = 'Normal'\r\n \r\n elif 0.64 < ratio and ratio <= 1.0:\r\n diag = 'Glaucomatous'\r\n \r\n else:\r\n diag = 'Erreur de calcul'\r\n\r\n return diag\r\n\"\"\"","repo_name":"AMvoulana/Fully-Automated-Method-for-Glaucoma-Screening-Using-Cup-To-Disc-Ratio-Computation-in-Retinal-Images","sub_path":"Scripts/measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"25723208660","text":"\"\"\"\nTake form data and send it to the API.\n\nThis module contains a base class for API clients and a mock client, as well\nas functions to send form data to an API and instantiate an API client.\n\nAPIClient subclasses can be swapped out by providing the fully qualified class name to\nthe API_CLIENT setting. API keys can be set in an environment variable named API_KEY.\nThe URL of the API to upload documents to can be set in the API_URL setting.\n\nThe MockAPIClient class is provided for demonstration purposes. It contains an example\nof whaat a prepare_data() method might look like.\n\"\"\"\nfrom tempfile import TemporaryFile\n\nimport requests\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.utils.module_loading import import_string\n\nfrom .forms import UploadForm\n\n\ndef make_api_call(form):\n \"\"\"Pass form data to API client.\"\"\"\n api_key = settings.API_KEY\n client = get_api_client(api_key)\n response = client.send_data(form)\n return response\n\n\ndef get_api_client(api_key):\n \"\"\"Instantiate an API client.\"\"\"\n client = import_string(settings.API_CLIENT)\n return client(api_key)\n\n\nclass APIClient:\n \"\"\"\n Base class for API client.\n\n Subclasses must implement a prepare_data() method that takes an UploadForm and\n returns a dictionary of data prepared to match your API's requirements.\n \"\"\"\n\n def __init__(self, api_key):\n self.api_key = api_key\n\n def prepare_data(self, form):\n \"\"\"Prepare form data for API.\"\"\"\n raise NotImplementedError\n\n def send_data(self, form):\n \"\"\"\n Send prepared data to API.\n\n The file is read in chunks from Django's UploadedFile object and written to a\n temporary file to prevent the entire file from being loaded into memory.\n \"\"\"\n payload = self.prepare_data(form)\n with TemporaryFile() as f, open(\"log\"):\n for chunk in form.cleaned_data[\"userfile\"].chunks():\n f.write(chunk)\n f.seek(0)\n response = requests.post(\n settings.API_URL, data=payload, files={\"userfile\": f}\n )\n return response\n\n\nclass MockAPIClient(APIClient):\n \"\"\"\n Mock API client that returns a 200 response regardless of the request.\n\n This client implements a method for prepare_data() that manipulates the data\n for a hypothetical XML API.\n \"\"\"\n\n workflow = 101\n\n def prepare_data(self, form: UploadForm):\n \"\"\"Takes form data and prepares it in XML format.\"\"\"\n eta_date = form.cleaned_data[\"eta_date\"]\n eta_time = form.cleaned_data[\"eta_time\"]\n eta_date = eta_date.strftime(\"%Y%m%d\") if eta_date else None\n eta_time = eta_time.strftime(\"%H%M\") if eta_time else None\n\n payload = {}\n payload[\"api_key\"] = self.api_key\n payload[\"workflow\"] = self.workflow\n payload[\n \"field_data\"\n ] = f\"\"\"\n \n {form.cleaned_data[\"trans_num\"]}\n {form.cleaned_data[\"port_of_entry\"]}\n {form.cleaned_data[\"ccd_num\"]}\n {eta_date}\n {eta_time}\n \"\"\"\n\n return payload\n\n def send_data(self, form: UploadForm):\n \"\"\"This client returns a 200 response regardless of the request.\"\"\"\n return HttpResponse(\"OK\")\n","repo_name":"daustin391/customs-document-uploader","sub_path":"upload_app/api_clients.py","file_name":"api_clients.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1256851830","text":"from django.core.management.base import BaseCommand, CommandError\nfrom scores.models import Team, League\nimport http.client\nimport json\n\nclass Command(BaseCommand):\n\t\n\t\n\tdef handle(self, *args, **options):\n\t\tconnection = http.client.HTTPConnection('api.football-data.org')\n\t\theaders = { 'X-Auth-Token': '72a15670266e4d1f93b36cfc4e45b7e2' }\n\t\tconnection.request('GET', '/alpha/soccerseasons/', None, headers )\n\t\tresponse = json.loads(connection.getresponse().read().decode())\n\n\t\tfor seasons in response:\n\t\t\tself.stdout.write(seasons['league'] + ' Number of Teams: ' + str(seasons['numberOfTeams']))\n\t\t\tl = League(name = seasons['caption'], league_id = seasons['league'])\n\t\t\tl.save()\t\n\n\n\n\n\n\n","repo_name":"takumiharada/fantasypl","sub_path":"scores/management/commands/addData.py","file_name":"addData.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24811086231","text":"from . import test_auth_key, Plan, TestCase\n\n\nclass TestPlan(TestCase):\n def setUp(self):\n super(TestPlan, self).setUp()\n self.assertNotEqual(test_auth_key, None)\n self.plan = Plan(authorization_key=test_auth_key)\n\n def test_plan_setup_and_update(self):\n \"\"\"\n Integration test for creating plan and updating created plan\n \"\"\"\n\n initial_plan_detail = {'name': 'test_plan_1',\n 'amount': 1000*100,\n 'interval': 'weekly'}\n\n updated_plan_details = {'name': 'test_plan_1',\n 'amount': 300*100,\n 'interval': 'daily'}\n\n def create_plan():\n (status_code, status, response_msg,\n created_plan_data) = self.plan.create(**initial_plan_detail)\n self.assertEqual(status_code, 201)\n self.assertEqual(status, True)\n self.assertEqual(response_msg, 'Plan created')\n # assert if subset\n self.assertLessEqual(\n initial_plan_detail.items(), created_plan_data.items())\n return created_plan_data\n\n def update_plan():\n (status_code, status, response_msg, updated_plan_data) = self.plan.update(\n plan_id=created_plan_data['id'], **updated_plan_details)\n self.assertEqual(status_code, 200)\n self.assertEqual(status, True)\n self.assertEqual(\n response_msg, 'Plan updated. 0 subscription(s) affected')\n self.assertEqual(updated_plan_data, None)\n\n created_plan_data = create_plan()\n update_plan()\n","repo_name":"edwardpopoola/pypaystack","sub_path":"tests/test_04_plan.py","file_name":"test_04_plan.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"18"} +{"seq_id":"27800214322","text":"def solve():\n with open(\"04-01.txt\") as f:\n d = f.read()\n inp, *board = d.split(\"\\n\")\n data = []\n t = []\n board.append(\"\")\n for item in board[1:]:\n if item != \"\":\n t.append(item)\n else:\n data.append(t.copy())\n t.clear()\n\n classes = []\n for i in data:\n classes.append(matrix(i))\n for val in map(int, inp.split(\",\")):\n for i in classes:\n for j in i.inner:\n for k in j:\n if k.value == val:\n k.marked = True\n for i in classes:\n if i.check():\n return val * sum(\n [j.value for j in sum(i.inner, start=[]) if not j.marked]\n )\n\n\nclass num:\n def __init__(self, value, marked=False):\n self.value = value\n self.marked = marked\n\n\nclass matrix:\n def __init__(self, data):\n self.data = [list(map(int, i.split())) for i in data]\n self.inner = [[num(i) for i in j] for j in self.data]\n self.pos = ()\n\n def check(self):\n for i in self.inner:\n if all(j.marked for j in i):\n return True\n for i in zip(*self.inner):\n if all(j.marked for j in i):\n return True\n\n\nprint(solve())\n","repo_name":"Keo-K/AoC-2021","sub_path":"04-01s.py","file_name":"04-01s.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43332422104","text":"import json\nimport datetime as dt\n\n\ndef main(event, context):\n body = {\n \"message\": \"Function executed successfully!\",\n \"Output\": timenow(),\n }\n\n try:\n \n print(timenow())\n\n except Exception as ex:\n\n print(ex)\n \n\n response = {\"statusCode\": 200, \"body\": json.dumps(body)}\n return response\n \ndef timenow():\n\n dateTimeObj = dt.datetime.now()\n date = dateTimeObj.strftime(\"%d-%b-%Y_%H-%M-%S\")\n \n return date\n\nif __name__ == '__main__':\n main('{}','{}')","repo_name":"rgrhodesdev/terraform-lambda-for-each","sub_path":"environment/development/service/source/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"39503037636","text":"from ..builder import PIPELINES\nfrom .compose import Compose\nimport copy\n\n\n@PIPELINES.register_module()\nclass MultiBranch(object):\n def __init__(self, **transform_group):\n self.transform_group = {k: Compose(v)\n for k, v in transform_group.items()}\n\n def __call__(self, results):\n multi_results = dict()\n for k, v in self.transform_group.items():\n res = v(copy.deepcopy(results))\n if res is None:\n return None\n # res[\"img_metas\"][\"tag\"] = k\n multi_results[k] = res\n return multi_results\n","repo_name":"Adamdad/Repfusion","sub_path":"classification_distill/mmcls/datasets/pipelines/multiview.py","file_name":"multiview.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"18"} +{"seq_id":"4346502445","text":"import torch\nimport torch.nn as nn\n\nclass CompactnessLoss(nn.Module):\n def __init__(self, center):\n super(CompactnessLoss, self).__init__()\n self.center = center\n\n def forward(self, inputs):\n m = inputs.size(1)\n variances = (inputs - self.center).norm(dim=1).pow(2) / m\n return variances.mean()\n\n\nclass EWCLoss(nn.Module):\n def __init__(self, frozen_model, fisher, lambda_ewc=1e4):\n super(EWCLoss, self).__init__()\n self.frozen_model = frozen_model\n self.fisher = fisher\n self.lambda_ewc = lambda_ewc\n\n def forward(self, cur_model):\n loss_reg = 0\n for (name, param), (_, param_old) in zip(cur_model.named_parameters(), self.frozen_model.named_parameters()):\n if 'fc' in name:\n continue\n loss_reg += torch.sum(self.fisher[name]*(param_old-param).pow(2))/2\n return self.lambda_ewc * loss_reg\n\ndef coral(x, y):\n \n if len(x) <= 1 or len(y) <= 1:\n return None\n \n mean_x = x.mean(0, keepdim=True)\n mean_y = y.mean(0, keepdim=True)\n cent_x = x - mean_x\n cent_y = y - mean_y\n\n cova_x = (cent_x.t() @ cent_x) / (len(x) - 1)\n cova_y = (cent_y.t() @ cent_y) / (len(y) - 1)\n\n mean_diff = (mean_x - mean_y).pow(2).mean()\n cova_diff = (cova_x - cova_y).pow(2).mean()\n\n return mean_diff + cova_diff","repo_name":"kazukiyoda7/PANDA_DIFEX","sub_path":"losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"28294724996","text":"### Asignacion consecutivo COUPA\n\nimport pandas as pd\nimport os\nimport datetime\nfrom selenium import webdriver\n\nsubir = True\n\n# Para darle el nombre al archivo\nnow = datetime.datetime.now()\nif len(str(now.day)) ==1:\n dia = '0' + str(now.day)\nelse:\n dia = str(now.day)\n\nif len(str(now.month)) ==1:\n mes = '0' + str(now.month)\nelse:\n mes = str(now.month)\n\nos.chdir(r'G:\\Mi unidad\\Data\\Grupo Bios\\Automatizacion_Items\\asignacion consecutivo COUPA')\nconsecutivos_COUPA = pd.read_excel('ultimo_codigo_coupa.xlsx', header = 0, index_col = 0)\nconsecutivos_COUPA_AF = pd.read_excel('ultimo_codigo_coupa_AF.xlsx', header = 0, index_col = 0)\nsolicitudes_dia = pd.read_excel('solicitudes_del_dia.xlsx',header = 0)\ncarga_tabla_homologacion = pd.DataFrame(columns=['CoupaCode', \"CompanyCode\", 'itemAttribute', 'itemValue','UnidadNegocio', 'disponible'], index = [0])\ntabla_coupa = pd.DataFrame(columns = ['IdCompania','CoupaCode', 'Descripcion', 'Unidad','NomGrupoWA','NomSubgrupoWA','cCOUPA', 'ReferenciaSIESA', 'TipoInv','UnidadMedida', 'UnidadNegocio'],index = [0])\ntags_homologacion = pd.DataFrame(columns=['COUPA','SIESA'], index = [0])\ncarga_masiva = pd.DataFrame(columns=['Name*'], index = [0])\nverificar = pd.DataFrame(columns=['COUPA'],index = [0])\nnombre_archivo = []\nwith open(\"columnas_SIESA.txt\") as reader:\n for line in reader:\n a = str(line).replace('\\n','')\n carga_masiva[a] = \"\"\n\n\ndef asignacion_codigo():\n ix_homologacion = 0\n ix_carga = 0\n for x in range(0,len(solicitudes_dia)):\n if pd.isna(solicitudes_dia.loc[x,'CodigoCoupa']):\n if (solicitudes_dia.loc[x,'ActivoFijo'] ==\"Si\") | (solicitudes_dia.loc[x,'ActivoFijo'] ==\"SI\"):\n carga_masiva.loc[ix_carga,\"active*\"] = 'No'\n codigo_asignar = consecutivos_COUPA_AF.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo']\n codigo_siguiente = codigo_asignar + 1\n consecutivos_COUPA_AF.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo'] = codigo_siguiente\n ceros = 4 - len(str(consecutivos_COUPA_AF.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo']))\n codigo_string = str(codigo_siguiente)\n for i in range(0,ceros):\n codigo_string = \"0\" + codigo_string\n carga_masiva.loc[ix_carga,\"Supplier Part Num\"] = str(consecutivos_COUPA_AF.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'prefijo']) + codigo_string\n solicitudes_dia.loc[x,\"CodigoCoupa\"] = str(consecutivos_COUPA_AF.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'prefijo']) + codigo_string\n else:\n carga_masiva.loc[ix_carga,\"active*\"] = 'Yes'\n codigo_asignar = consecutivos_COUPA.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo']\n codigo_siguiente = codigo_asignar + 1\n consecutivos_COUPA.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo'] = codigo_siguiente\n ceros = 4 - len(str(consecutivos_COUPA.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'codigo']))\n codigo_string = str(codigo_siguiente)\n for i in range(0,ceros):\n codigo_string = \"0\" + codigo_string\n carga_masiva.loc[ix_carga,\"Supplier Part Num\"] = str(consecutivos_COUPA.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'prefijo']) + codigo_string\n solicitudes_dia.loc[x,\"CodigoCoupa\"] = str(consecutivos_COUPA.loc[solicitudes_dia.loc[x,\"NomSubgrupoWA\"], 'prefijo']) + codigo_string\n if (str(solicitudes_dia.loc[x,'NomSubgrupoWA']) == 'ADITIVOS') | (str(solicitudes_dia.loc[x,'NomSubgrupoWA']) == 'ADITIVOS MP'):\n consecutivos_COUPA.loc['ADITIVOS', 'codigo'] = max(consecutivos_COUPA.loc['ADITIVOS', 'codigo'],consecutivos_COUPA.loc['ADITIVOS MP', 'codigo'])\n consecutivos_COUPA.loc['ADITIVOS MP', 'codigo'] = max(consecutivos_COUPA.loc['ADITIVOS', 'codigo'],consecutivos_COUPA.loc['ADITIVOS MP', 'codigo'])\n\n carga_masiva.loc[ix_carga,\"Name*\"] = solicitudes_dia.loc[x,'Descripcion']\n carga_masiva.loc[ix_carga,\"Description*\"] = solicitudes_dia.loc[x,'Descripcion']\n carga_masiva.loc[ix_carga,\"UOM code*\"] = solicitudes_dia.loc[x,'Unidad']\n carga_masiva.loc[ix_carga,\"Item Number\"] = carga_masiva.loc[ix_carga,\"Supplier Part Num\"] \n carga_masiva.loc[ix_carga,\"Commodity\"] = solicitudes_dia.loc[x,'NomSubgrupoWA']\n carga_masiva.loc[ix_carga,\"Tags\"] = solicitudes_dia.loc[x,'ReferenciaSIESA']\n carga_masiva.loc[ix_carga,\"Supplier\"] = '00000-Servicios BIOS'\n carga_masiva.loc[ix_carga,\"Contract Number\"] = '00000-Servicios BIOS'\n carga_masiva.loc[ix_carga,\"Price\"] = '0'\n carga_masiva.loc[ix_carga,\"Currency\"] = 'COP'\n carga_masiva.loc[ix_carga,\"Supplier Part Num\"]\n carga_masiva.loc[ix_carga,\"Fixed asset\"] = 'No'\n carga_masiva.loc[ix_carga,\"Controlled Substance\"] = 'No'\n carga_masiva.loc[ix_carga,\"Storable\"] = 'Yes'\n carga_masiva.loc[ix_carga,\"Lot tracking\"] = 'No'\n verificar.loc[ix_carga, 'COUPA'] = carga_masiva.loc[ix_carga,\"Item Number\"]\n ix_carga = ix_carga+1\n\n else:\n tags_homologacion.loc[ix_homologacion,'COUPA'] = solicitudes_dia.loc[x,'CodigoCoupa']\n tags_homologacion.loc[ix_homologacion,'SIESA'] = solicitudes_dia.loc[x,'ReferenciaSIESA']\n ix_homologacion = ix_homologacion + 1\n \n solicitudes_dia.to_excel('resultado asignacion.xlsx', header=True,encoding='utf-8')\n consecutivos_COUPA.to_excel('nuevo_codigo_coupa.xlsx', header = True, encoding = 'utf-8')\n consecutivos_COUPA_AF.to_excel('nuevo_codigo_coupa_AF.xlsx', header = True, encoding = 'utf-8')\n now = datetime.datetime.now()\n carga_masiva_test = carga_masiva.copy()\n carga_masiva_test[\"Contract Number\"] = 'Servicios BIOS 00001'\n carga_masiva_test.to_csv('G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Servicios BIOS\\Carga Masiva Test.csv',index=None, header = True, encoding = 'utf-8')\n nombre2 = 'G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Servicios BIOS\\Servicios BIOS '+ dia + mes + str(now.year) + \".csv\"\n nombre_archivo.append(nombre2)\n carga_masiva.to_csv(nombre2, index=None, header = True, encoding = 'utf-8')\n verificar.to_excel(r'G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Tags\\verificar.xlsx', index = None, header = True, encoding = 'utf-8')\n tags_homologacion.to_excel('G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Tags\\homologacion.xlsx', header = True, encoding = 'utf-8')\n\ndef carga_tabla_homologacion_funcion():\n for x in range(0,len(solicitudes_dia)):\n carga_tabla_homologacion.loc[x,'CoupaCode'] = solicitudes_dia.loc[x,'CodigoCoupa']\n tabla_coupa.loc[x,'CoupaCode'] = solicitudes_dia.loc[x,'CodigoCoupa']\n tabla_coupa.loc[x,'cCOUPA']=tabla_coupa.loc[x,'CoupaCode']\n if solicitudes_dia.loc[x,'IdCompania'] == 1:\n carga_tabla_homologacion.loc[x,\"CompanyCode\"] = \"001\"\n tabla_coupa.loc[x,'IdCompania'] = \"001\"\n elif solicitudes_dia.loc[x,'IdCompania'] == 20:\n carga_tabla_homologacion.loc[x,\"CompanyCode\"] = \"020\"\n tabla_coupa.loc[x,'IdCompania'] = \"020\"\n else:\n carga_tabla_homologacion.loc[x,\"CompanyCode\"] = solicitudes_dia.loc[x,'IdCompania']\n tabla_coupa.loc[x,'IdCompania'] = solicitudes_dia.loc[x,'IdCompania']\n carga_tabla_homologacion.loc[x,'itemAttribute'] = 1\n carga_tabla_homologacion.loc[x,'itemValue'] = solicitudes_dia.loc[x,'ReferenciaSIESA']\n tabla_coupa.loc[x,'ReferenciaSIESA'] = solicitudes_dia.loc[x,'ReferenciaSIESA']\n if solicitudes_dia.loc[x,'UnidadNegocio'] == 99:\n carga_tabla_homologacion.loc[x,'UnidadNegocio'] = 99\n tabla_coupa.loc[x,'UnidadNegocio'] = 99\n elif solicitudes_dia.loc[x,'UnidadNegocio'] == 999:\n carga_tabla_homologacion.loc[x,'UnidadNegocio'] = 999\n tabla_coupa.loc[x,'UnidadNegocio'] = 999\n else:\n carga_tabla_homologacion.loc[x,'UnidadNegocio'] = \"0\" + str(solicitudes_dia.loc[x,'UnidadNegocio'])\n tabla_coupa.loc[x,'UnidadNegocio'] = \"0\" + str(solicitudes_dia.loc[x,'UnidadNegocio'])\n carga_tabla_homologacion.loc[x,'disponible'] = 1\n \n tabla_coupa.loc[x,'Descripcion'] = solicitudes_dia.loc[x,'Descripcion']\n tabla_coupa.loc[x,'Unidad'] = solicitudes_dia.loc[x,'Unidad']\n tabla_coupa.loc[x,'NomGrupoWA'] = solicitudes_dia.loc[x,'NomGrupoWA'] \n tabla_coupa.loc[x,'NomSubgrupoWA'] = solicitudes_dia.loc[x,'NomSubgrupoWA']\n tabla_coupa.loc[x,'TipoInv']= solicitudes_dia.loc[x,'TipoInventario']\n tabla_coupa.loc[x,'UnidadMedida']= solicitudes_dia.loc[x,'Unidad']\n \n now = datetime.datetime.now()\n nombre = 'G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Carga Tabla Homologación\\PIF '+ dia + mes + str(now.year) + \".csv\"\n carga_tabla_homologacion.to_csv(nombre,index = None, header = False, encoding = 'utf-8')\n tabla_coupa.to_excel('tabla_coupa.xlsx', index = None, header = True, encoding=\"utf-8\")\n \n\n\nif __name__ == \"__main__\":\n asignacion_codigo()\n carga_tabla_homologacion_funcion()\n if subir:\n browser_test = webdriver.Chrome(\"C:\\Python\\Python37\\chromedriver\")\n browser_test.get(\"https://grupobios-test.coupahost.com/\")\n nombre_usuario = browser_test.find_element_by_name(\"user[login]\")\n nombre_usuario.clear()\n nombre_usuario.send_keys('jbuitrago')\n contrasena = browser_test.find_element_by_name(\"user[password]\")\n contrasena.clear()\n contrasena.send_keys('valleyball1')\n browser_test.find_element_by_class_name(\"button\").click()\n browser_test.find_element_by_link_text('Items').click()\n browser_test.find_element_by_xpath('//*[@id=\"item_data_table_form_search\"]/div[1]/table/tbody/tr/td[1]/a[2]/span').click()\n browser_test.find_element_by_id(\"data_source_file\").send_keys('G:\\Mi unidad\\Data\\Grupo Bios\\Administración de ítems\\Servicios BIOS\\Carga Masiva Test.csv')\n browser_test.find_element_by_xpath('//*[@id=\"csv_upload\"]/li[4]/button/span').click()\n\n browser_prod = webdriver.Chrome(\"C:\\Python\\Python37\\chromedriver\")\n browser_prod.get(\"https://grupobios.coupahost.com/\")\n nombre_usuario = browser_prod.find_element_by_name(\"user[login]\")\n nombre_usuario.clear()\n nombre_usuario.send_keys('ParametaData')\n contrasena = browser_prod.find_element_by_name(\"user[password]\")\n contrasena.clear()\n contrasena.send_keys('Parametadata*')\n browser_prod.find_element_by_class_name(\"button\").click()\n browser_prod.find_element_by_link_text('Items').click()\n browser_prod.find_element_by_xpath('//*[@id=\"item_data_table_form_search\"]/div[1]/table/tbody/tr/td[1]/a[2]/span').click()\n browser_prod.find_element_by_id(\"data_source_file\").send_keys(nombre_archivo[0])\n browser_prod.find_element_by_xpath('//*[@id=\"csv_upload\"]/li[4]/button/span').click()\n ","repo_name":"jbuitrago-parameta/JeanCloud_Parameta","sub_path":"Bios/Automatizacion items/asignacion_consecutivo_COUPA.py","file_name":"asignacion_consecutivo_COUPA.py","file_ext":"py","file_size_in_byte":11194,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34357815450","text":"t = int(input())\nfor _ in range(t):\n n = int(input())\n arr = list(map(int, input().rstrip().split()))\n bestCase = float(\"inf\")\n worstCase = float(\"-inf\")\n for pos in range(len(arr)):\n back = pos\n affected = 1\n while back >= 1 and arr[back] - arr[back-1] <= 2:\n affected += 1\n back -= 1\n forward = pos\n while forward <= n-2 and arr[forward+1] - arr[forward] <= 2 :\n affected += 1\n forward += 1\n bestCase = min(bestCase, affected)\n worstCase = max(worstCase, affected)\n print(bestCase, worstCase)\n\n","repo_name":"subho2107/Codechef","sub_path":"May long challenge/Coronavirus spread.py","file_name":"Coronavirus spread.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"39475954783","text":"# BRUTE FORCE SOLUTION APPROACH\r\n\r\ndef LongestSubsetWithZeroSum(arr):\r\n \r\n # Initialize result\r\n maxLen = 0\r\n n = len(arr)\r\n\r\n # Pick a starting point\r\n for i in range(n):\r\n\r\n # Initialize currSum for every starting point\r\n currSum = 0\r\n\r\n # Try all subarrays starting with 'i'\r\n for j in range(i, n):\r\n currSum += arr[j]\r\n\r\n # If currSum becomes 0,then update maxLen if required\r\n\r\n if currSum == 0:\r\n maxLen = max(maxLen, j - i + 1)\r\n\r\n \r\n return maxLen\r\n\r\n\r\n# OPTIMISED APPROACH\r\n\r\n'''\r\n Time Complexity: O(N)\r\n Space Complexity: O(N)\r\n\r\n Where 'N' denotes the number of elements of the array\r\n'''\r\n\r\nfrom collections import OrderedDict\r\n\r\ndef LongestSubsetWithZeroSum(arr):\r\n\r\n # Map to store the previous sums\r\n presum = OrderedDict()\r\n\r\n sum = 0 # Initialize the sum of elements\r\n maxLen = 0 # Initialize result\r\n n = len(arr)\r\n\r\n # Traverse through the given array\r\n for i in range(n):\r\n # Add current element to sum\r\n sum += arr[i]\r\n\r\n if (arr[i] == 0 and maxLen == 0):\r\n maxLen = 1\r\n if sum == 0:\r\n maxLen = i + 1\r\n\r\n # Look for this sum in Hash table\r\n if (sum in presum):\r\n # If this sum is seen before, then update maxLen\r\n maxLen = max(maxLen, i - presum.get(sum))\r\n\r\n else:\r\n # Else insert this sum with index in hash table\r\n presum[sum] = i\r\n\r\n return maxLen\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"shivang257/Striver-SDE-Sheet-Challenge","sub_path":"Array Part 4/Largest Subarray with 0 sum/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"20157778890","text":"import load_dataset\nimport numpy as np\n\nfrom genetic_algorithm import *\n\nx, y = load_dataset.load_dataset('dataset')\n\nres = load_dataset.extract_frequent_pixels(x)\n\ntrain_x, train_y = load_dataset.normalize_data(res, y)\n\n# #TRAINING ALGO START\nga = GA(10, train_x, train_y, \n input_layer_len=train_x.shape[1], \n hidden_layer_len=150, \n output_layer_len=26)\n\nnum_generations = 5000\nga.evolve(num_generations)\n\nimport matplotlib.pyplot as plt\n\nplt.plot(list(range(num_generations)), ga.fitness_over_time, label = 'Fitness')\nplt.plot(list(range(num_generations)), ga.accuracy_over_time, label = 'Accuracy')\nplt.xlabel('number of generations')\nplt.ylabel('fitness score')\nplt.legend(['fitness', 'accuracy'])\nplt.show()\n\npopulation_accuracy = ga.test_accuracy()\n\n\nfor i in population_accuracy:\n print(i)","repo_name":"PetrJanousek/Neurogenetic_algorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38602759193","text":"# Python program to check Armstrong number\r\nnum = int(input(\"Enter a number\"))\r\nSUM = 0\r\ntemp = num\r\nwhile temp > 0:\r\n dig = temp % 10\r\n SUM += dig ** 3\r\n temp //= 10\r\nif SUM == num:\r\n print(\"number is an armstrong\")\r\nelse:\r\n print(\"number is not an armstrong number\")\r\n","repo_name":"sreelekha22/python","sub_path":"ArmstrongNum.py","file_name":"ArmstrongNum.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31390958132","text":"\"\"\"empty message\n\nRevision ID: 84db833f2c6e\nRevises: 24d226a61135\nCreate Date: 2020-08-17 18:57:37.040432\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '84db833f2c6e'\ndown_revision = '24d226a61135'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('attachment',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('menu_id', sa.Integer(), nullable=True),\n sa.Column('vk_active', sa.Boolean(), nullable=False),\n sa.Column('telegram_active', sa.Boolean(), nullable=False),\n sa.Column('vk_attachment', sa.String(length=120), nullable=True),\n sa.Column('telegram_attachment', sa.String(length=120), nullable=True),\n sa.ForeignKeyConstraint(['menu_id'], ['menu.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('attachment')\n # ### end Alembic commands ###\n","repo_name":"Kr1t1ka/library-api","sub_path":"migrations/versions/84db833f2c6e_.py","file_name":"84db833f2c6e_.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18466279993","text":"from flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\napp.secret_key = b'hello_world'\r\n\r\nSESSION_TYPE = 'filesystem'\r\nSESSION_USE_SIGNER = True\r\n\r\n\r\n@app.route('/', methods=[\"GET\", \"POST\"])\r\ndef entry_point():\r\n if request.method == \"GET\":\r\n return render_template(\"index.html\")\r\n elif request.method == \"POST\":\r\n if request.form.get(\"your-password\") == \"qwoerhinnbxc\":\r\n return render_template(\"qwoerhinnbxc.html\")\r\n else:\r\n return render_template(\"index.html\")\r\n\r\n\r\n@app.route('/qwoerhinnbxc.html', methods=[\"GET\", \"POST\"])\r\ndef get_flag():\r\n if request.method == \"GET\":\r\n return render_template(\"qwoerhinnbxc.html\")\r\n\r\n\r\n@app.route('/flag', methods=[\"GET\", \"POST\"])\r\ndef try_get_flag():\r\n if request.method == \"GET\":\r\n return \"Not bad but try again...\"\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=False, host='0.0.0.0', port=10000)\r\n sess.init_app(app)\r\n","repo_name":"danisins/web_tasks","sub_path":"web_js_obfus/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73845332199","text":"# Nathaniel Morin\r\n# 8/22/2021\r\n\r\nimport pygame\r\nimport math\r\nimport numpy as np\r\nimport itertools\r\n\r\npygame.init()\r\n\r\n# Body class\r\nclass Body:\r\n\tmax_speed = 0.01 # max initial speed (pixels/second)\r\n\tmax_trail_length = 75 # if it is -1 then there is no limit\r\n\r\n\tcolor = (220, 220, 220)\r\n\tvecColor = (255, 0, 0)\r\n\tgravColor = (0, 255, 0)\r\n\taggGravColor = (100, 100, 255) # the aggregate/net force of gravity\r\n\tfixedColor = (255, 150, 150)\r\n\ttrailColor = (168, 50, 121)\r\n\tcenterOfMassColor = (158, 181, 255)\r\n\r\n\t# What portion of the *radius* of the smaller body (between its and the other body's center) needs to be non-overlapping for it to not collide.\r\n\t# 1 means that it just needs to be tangential for a collision to be detected, since it means that the whole radius needs to be outside the other body for it not to collide\r\n\t# 0 means that it needs to be submerged up to its center before it collides\r\n\tcollisionDistanceFactor = 0.6\r\n\t# How many times longer the displayed vector is than the distance they will travel in the next frame\r\n\tvectorDisplayFactor = 10000\r\n\t# What portion of the real magnitude of the gravity vectors are displayed\r\n\tgravDisplayFactor = 1*10**-15\r\n\tdensity = 5000 # kg/m^3\r\n\tG = 6.67408*10**-11 # gravitational constant\r\n\tmpp = 1_000_000 # meters per pixel (1000 km)\r\n\tspf = 1200 # seconds per frame (20 min)\r\n\r\n\t# self, position of the center (x, y), vector, mass, surface\r\n\t# released stores whether the body has been launched\r\n\t# fixed stores whether the body is fixed at a certain point (cannot move)\r\n\tdef __init__(self, pos, vec, mass, srf, released = False, fixed = False):\r\n\t\tself.initPos = pos # initial position\r\n\t\tself.initVec = vec # initial vector\r\n\t\tself.initMass = mass # initial mass (kg)\r\n\t\tself.pos = pos # position [x, y]\r\n\t\tself.vec = vec # vector components [dx, dy]\r\n\t\tself.setMass(mass) # radius and mass\r\n\t\tself.trailList = [] # a list of points marking the trail of the body\r\n\t\tself.gravVecList = [] # a list of gravity vectors acting on the ball\r\n\t\tself.srf = srf # surface (the screen)\r\n\t\tself.released = released # whether the body has been launched\r\n\t\tself.fixed = fixed\r\n\r\n\t# Finds the volume of the body (sphere)\r\n\tdef findVolume(self):\r\n\t\treturn (4*math.pi*self.findPhysicsRad()**3)/3\r\n\r\n\t# Finds the radius that is used for physics calculations\r\n\tdef findPhysicsRad(self):\r\n\t\treturn self.displayRad * Body.mpp\r\n\r\n\t# sets a body's radius\r\n\tdef setDisplayRadius(self, newRad):\r\n\t\tself.displayRad = newRad\r\n\t\tself.mass = self.findVolume()*Body.density\r\n\t\treturn self\r\n\r\n\t# sets an body's mass\r\n\tdef setMass(self, newMass):\r\n\t\tself.mass = newMass\r\n\t\tnewVolume = self.mass/Body.density\r\n\t\tself.displayRad = ((3*newVolume/(4*math.pi))**(1/3))/self.mpp\r\n\t\treturn self\r\n\r\n\t# Returns the body's magnitude\r\n\tdef findMagnitude(self):\r\n\t\treturn np.sqrt(self.vec[0]**2 + self.vec[1]**2)\r\n\r\n\tdef findVelocity(self):\r\n\t\treturn self.findMagnitude()/self.mass\t\r\n\r\n\t# Updates the position of the body, applying intertia\r\n\tdef update(self):\r\n\t\tself.trailList.append(self.pos)\r\n\t\tif not Body.max_trail_length == -1 and len(self.trailList) > Body.max_trail_length:\r\n\t\t\tself.trailList = self.trailList[1:]\r\n\t\t# adjusting the position\r\n\t\tif not self.fixed:\r\n\t\t\tself.pos = [self.pos[0] + self.vec[0]/Body.mpp/self.mass*Body.spf, self.pos[1] + \\\r\n\t\t\tself.vec[1]/Body.mpp/self.mass*Body.spf]\r\n\t\telse:\r\n\t\t\tself.vec = [0, 0]\t\r\n\t\treturn self\r\n\r\n\t# Resets a body\r\n\tdef reset(self):\r\n\t\tself.vec = self.initVec\r\n\t\tself.pos = self.initPos\r\n\t\tself.setMass(self.initMass)\r\n\t\tself.trailList.clear()\r\n\t\treturn self\r\n\r\n\t# Distance formula\r\n\t@staticmethod\r\n\tdef findDisplayDistance(pos1, pos2):\r\n\t\treturn np.sqrt((pos2[0] - pos1[0])**2 + (pos2[1] - pos1[1])**2)\r\n\r\n\t@staticmethod\r\n\tdef findPhysicsDistance(pos1, pos2):\r\n\t\treturn Body.findDisplayDistance(pos1, pos2)*Body.mpp\r\n\r\n\t# Determines whether the two given bodies are colliding\r\n\t@staticmethod\r\n\tdef bodiesAreColliding(body1, body2):\r\n\t\tdistanceBetweenCenters = Body.findDisplayDistance(body1.pos, body2.pos)\r\n\t\t# returns true if the distance between their center is less than or equal two the sum of their radii\r\n\t\treturn distanceBetweenCenters <= body2.mass + body2.mass\r\n\r\n\t# Gets the angle (in radians) from the center of a circle (given in center_coords) to the point given in coords\r\n\t@staticmethod\r\n\tdef findRadianAngleFromCoords(center_coords, coords):\r\n\t\treturn np.arctan2(coords[1] - center_coords[1], coords[0] - center_coords[0])\r\n\r\n\t# Returns a list {dx, dy} for a Body vector based on the magnitude (speed) of the body and the angle that it is going at\r\n\t@staticmethod\r\n\tdef findVectorFromMagnitudeAndAngle(magnitude, angle):\r\n\t\t# defining dx and dy with this new vector angle\r\n\t\tdx, dy = magnitude * np.cos(angle), magnitude * np.sin(angle)\r\n\t\treturn [dx, dy]\r\n\r\n\t# Finds the force (magnitude) of gravitational attraction between two bodies (yes I know gravity isn't a force)\r\n\t@staticmethod\r\n\tdef findGravitationalAttraction(body1, body2):\r\n\t\treturn (Body.G * body1.mass * body2.mass)/(Body.findPhysicsDistance(body1.pos, body2.pos)**2)*Body.spf\r\n\r\n\t# Adds two vectors\r\n\t@staticmethod\r\n\tdef addVectors(vec1, vec2):\r\n\t\treturn [vec1[0]+vec2[0], vec1[1]+vec2[1]]\r\n\r\n\t# A function that iterates over a list of bodies and handles collisions between them\r\n\t# returns the new list of bodies (post-collisions)\r\n\t@staticmethod\r\n\tdef checkForBodyCollision(lst):\r\n\t\t# Iterates over all possible body combinations\r\n\t\tpairs = list(itertools.combinations(lst, 2))\r\n\t\tfor pair in pairs:\r\n\t\t\tbody1, body2 = pair[0], pair[1]\r\n\t\t\tif body1.released and body2.released:\r\n\t\t\t\tdist = Body.findDisplayDistance(body1.pos, body2.pos)\r\n\t\t\t\t# true if body1 is bigger and they are colliding\r\n\t\t\t\tabsorb = dist <= body1.displayRad + body2.displayRad*Body.collisionDistanceFactor and body1.mass >= body2.mass\r\n\t\t\t\t# if body2 is bigger and they are colliding\r\n\t\t\t\tif dist <= body2.displayRad + body1.displayRad*Body.collisionDistanceFactor and body2.mass >= body1.mass:\r\n\t\t\t\t\tabsorb = True\r\n\t\t\t\t\t# swapping them so that body1 refers to the larger\r\n\t\t\t\t\ttemp = body2\r\n\t\t\t\t\tbody2 = body1\r\n\t\t\t\t\tbody1 = temp\r\n\t\t\t\t# absorb = Body.collisionApproximationLinesAreIntersecting(body1, body2, body1.srf)\r\n\t\t\t\tif absorb:\r\n\t\t\t\t\tbody1.vec = Body.addVectors(body1.vec, body2.vec)\r\n\t\t\t\t\tbody1.setMass(body1.mass + body2.mass)\r\n\t\t\t\t\tif body2 in lst:\r\n\t\t\t\t\t\tlst.remove(body2)\t\t\t\t\r\n\r\n\t# function that iterates over a list of bodies and handles shifts to their vectors due to gravitational interactions\r\n\t@staticmethod\r\n\tdef applyGravity(lst):\r\n\t\tfor body in lst:\r\n\t\t\tbody.gravVecList.clear()\r\n\t\tpairs = list(itertools.combinations(lst, 2))\r\n\t\tfor pair in pairs:\r\n\t\t\tbody1, body2 = pair[0], pair[1]\r\n\t\t\tif body1.released and body2.released:\r\n\t\t\t\tattr = Body.findGravitationalAttraction(body1, body2)\r\n\t\t\t\tb1ToB2Angle = Body.findRadianAngleFromCoords(body1.pos, body2.pos)\r\n\t\t\t\tdx_grav, dy_grav = attr*np.cos(b1ToB2Angle), attr*np.sin(b1ToB2Angle)\r\n\t\t\t\tbody1.vec = Body.addVectors(body1.vec, [dx_grav, dy_grav])\r\n\t\t\t\tbody2.vec = Body.addVectors(body2.vec, [-dx_grav, -dy_grav])\r\n\t\t\t\tbody1.gravVecList.append([dx_grav, dy_grav])\r\n\t\t\t\tbody2.gravVecList.append([-dx_grav, -dy_grav])\r\n\r\n\t@staticmethod\r\n\tdef findCenterOfMass(lst):\r\n\t\ttotalMass = 0\r\n\t\taveragePos = [0, 0]\r\n\t\tfor b in lst:\r\n\t\t\ttotalMass += b.mass\r\n\t\t\taveragePos[0] += b.pos[0]*b.mass\r\n\t\t\taveragePos[1] += b.pos[1]*b.mass\r\n\t\treturn (averagePos[0]/totalMass, averagePos[1]/totalMass), totalMass\r\n\r\n\t@staticmethod\r\n\tdef drawCenterOfMass(lst, screen):\r\n\t\tcenterOfMassPos, totalMass = Body.findCenterOfMass(lst)\r\n\t\tcenterOfMassRad = (3*(totalMass/Body.density)/(4*math.pi))**(1/3)/Body.mpp\r\n\t\tpygame.draw.circle(screen, Body.centerOfMassColor, centerOfMassPos, centerOfMassRad)\r\n\r\n\t# Draws the body\t\r\n\tdef draw(self, drawVec = False, drawGrav = False, drawAgg = False, drawTrail = False):\r\n\t\t# drawing the body\r\n\t\tclr = Body.color if not self.fixed else Body.fixedColor\r\n\t\tpygame.draw.circle(self.srf, clr, self.pos, self.displayRad)\r\n\t\t# drawing the vector of the ball\r\n\t\tif drawVec:\r\n\t\t\tpygame.draw.line(self.srf, Body.vecColor, self.pos, \\\r\n\t\t\t\t[self.pos[0] + self.vec[0]/Body.mpp/self.mass*self.vectorDisplayFactor, \\\r\n\t\t\t\tself.pos[1] + self.vec[1]/Body.mpp/self.mass*self.vectorDisplayFactor])\r\n\t\t# drawing the vectors displaying all gravity effects\r\n\t\tif drawGrav:\r\n\t\t\tfor gVec in self.gravVecList:\r\n\t\t\t\tpygame.draw.line(self.srf, Body.gravColor, self.pos, \\\r\n\t\t\t\t\t(self.pos[0]+(gVec[0]/Body.spf/Body.mpp)*Body.gravDisplayFactor, self.pos[1]+(gVec[1]/Body.spf/Body.mpp)*Body.gravDisplayFactor))\r\n\t\t# drawing aggregate gravitational effect vector\r\n\t\tif drawAgg and len(self.gravVecList) > 0:\r\n\t\t\tgVecs = [[gV[0]/Body.spf/Body.mpp, gV[1]/Body.spf/Body.mpp] for gV in self.gravVecList]\r\n\t\t\tsumVec = gVecs[0]\r\n\t\t\tif len(gVecs) > 1:\r\n\t\t\t\tfor gVec in gVecs[1:]:\r\n\t\t\t\t\tsumVec = Body.addVectors(sumVec, gVec)\r\n\t\t\tpygame.draw.line(self.srf, Body.aggGravColor, self.pos, (self.pos[0]+sumVec[0]*Body.gravDisplayFactor, self.pos[1]+sumVec[1]*Body.gravDisplayFactor))\r\n\t\t# drawing the trail\r\n\t\tif drawTrail:\r\n\t\t\tif len(self.trailList) > 0:\r\n\t\t\t\tpygame.draw.lines(self.srf, Body.trailColor, False, self.trailList+[self.pos])\r\n\t\telse:\r\n\t\t\tself.trailList.clear() # saving spaces\r\n","repo_name":"EventHorizon150/Python-Orbit-Sim","sub_path":"Body.py","file_name":"Body.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"27520389758","text":"## http://danielhnyk.cz/creating-animation-blender-using-python/\n\nimport bpy \nfrom mathutils import Vector\n\n## useful shortcut\nscene = bpy.context.scene\nscene.render.engine = 'CYCLES'\nscene.render.resolution_x = 64\nscene.render.resolution_y = 64\nscene.cycles.samples = 512\nbpy.context.scene.cycles.filter_width = 0.01 ## turn off anti-aliasing\n\n\n## this shows you all objects in scene\n#scene.objects.keys()\n\n## when you start default Blender project, first object in scene is a Cube\n#kostka = scene.objects[0]\n\n## you can change location of object simply by setting the values\n#kostka.location = (1,2,0)\n\n## same with rotation\n#kostka.rotation_euler = (45,0,0)\n\n## this will make object cease from current scene\n#bpy.context.collection.objects.unlink(kostka)\n\n## clear everything for now\n#scene.camera = None \n#for obj in scene.objects: \n# bpy.context.collection.objects.unlink(obj)\nbpy.ops.object.select_all(action='SELECT')\nbpy.ops.object.delete(use_global=False)\n\n# create sphere and make it smooth\nbpy.ops.mesh.primitive_uv_sphere_add(radius = 3, location = (2,1,2)) \n#bpy.ops.object.shade_smooth() \nkule = bpy.context.object\n\n# create new cube\nbpy.ops.mesh.primitive_cube_add(size = 4, location = (-2,1,2)) \nkostka = bpy.context.object\n\n# create plane \nbpy.ops.mesh.primitive_plane_add(location=(0,0,0)) \nplane = bpy.context.object \nplane.dimensions = (20,20,0)\n\n## for every object add material - here represented just as color\n#for scale, ob in zip([3, 5, 7], [kule, kostka, plane]): \n# mat = bpy.data.materials.new(\"mat_\" + str(ob.name))\n# mat.use_nodes = True\n# matnodes = mat.node_tree.nodes\n# tex = matnodes.new('ShaderNodeTexVoronoi')\n# base_color = matnodes['Principled BSDF'].inputs['Base Color']\n# mat.node_tree.links.new(base_color, tex.outputs['Color'])\n# matnodes[\"Voronoi Texture\"].inputs[\"Scale\"].default_value = scale\n# ob.data.materials.append(mat)\n\nob = kule\nmat = bpy.data.materials.new(\"mat_\" + str(ob.name))\nmat.use_nodes = True\nmatnodes = mat.node_tree.nodes\ntex = matnodes.new('ShaderNodeTexVoronoi')\nbase_color = matnodes['Principled BSDF'].inputs['Base Color']\nmat.node_tree.links.new(base_color, tex.outputs['Color'])\nob.data.materials.append(mat)\n\nob = kostka\nmat = bpy.data.materials.new(\"mat_\" + str(ob.name))\nmat.use_nodes = True\nmatnodes = mat.node_tree.nodes\ntex = matnodes.new('ShaderNodeTexMagic')\ntex.inputs['Scale'].default_value = 1\ntex.inputs['Distortion'].default_value = 5\nbase_color = matnodes['Principled BSDF'].inputs['Base Color']\nmat.node_tree.links.new(base_color, tex.outputs['Color'])\nob.data.materials.append(mat)\n\nob = plane\nmat = bpy.data.materials.new(\"mat_\" + str(ob.name))\nmat.use_nodes = True\nmatnodes = mat.node_tree.nodes\ntex = matnodes.new('ShaderNodeTexBrick')\nbase_color = matnodes['Principled BSDF'].inputs['Base Color']\nmat.node_tree.links.new(base_color, tex.outputs['Color'])\nob.data.materials.append(mat)\n\n# now add some light\nlamp_data = bpy.data.lights.new(name=\"lampa\", type='POINT') \nlamp_object = bpy.data.objects.new(name=\"Lampicka\", object_data=lamp_data) \nbpy.context.collection.objects.link(lamp_object) \nlamp_object.location = (-3, 0, 7)\nlamp = bpy.data.lights[lamp_data.name]\nlamp.energy = 1000\n\n# and now set the camera\ncam_data = bpy.data.cameras.new(name=\"cam\") \ncam_ob = bpy.data.objects.new(name=\"Kamerka\", object_data=cam_data) \nbpy.context.collection.objects.link(cam_ob) \ncam_ob.location = (0, 1, 12) \ncam_ob.rotation_euler = (0,0,0.3) \ncam = bpy.data.cameras[cam_data.name] \ncam.lens = 25\nscene.camera = cam_ob\n\n\n### animation\npositions = (0,0,2),(0,1,2),(3,2,1),(3,4,1),(1,2,1)\n\n# start with frame 0\nnumber_of_frame = 0 \nbpy.context.scene.frame_end = 4\nbpy.context.scene.render.fps = 1\n\nfor pozice in positions:\n\n # now we will describe frame with number $number_of_frame\n scene.frame_set(number_of_frame)\n\n # set new location for sphere $kule and new rotation for cube $kostka\n kule.location = pozice\n kule.keyframe_insert(data_path=\"location\", index=-1)\n\n kostka.rotation_euler = pozice\n kostka.keyframe_insert(data_path=\"rotation_euler\", index=-1)\n\n plane.location += Vector(pozice)/5\n plane.keyframe_insert(data_path=\"location\", index=-1)\n # move next 10 frames forward - Blender will figure out what to do between this time\n number_of_frame += 1\n \n \n### ---------- save file -------------\nscene.use_nodes = True\nnodes = scene.node_tree.nodes\n\nbpy.context.scene.view_layers[\"View Layer\"].use_pass_vector = True\n\nrender_layers = nodes['Render Layers']\n\n\ndef create_file_node(nodes, base_path, \n format = 'OPEN_EXR', color_depth = '16'):\n file_node = nodes.new(\"CompositorNodeOutputFile\")\n file_node.base_path = base_path\n file_node.format.file_format = format\n file_node.format.color_depth = color_depth\n return file_node\n \n \n\n\noutput_file = nodes.new(\"CompositorNodeOutputFile\")\noutput_file.base_path = \"/Users/qian/Desktop/Vector\"\noutput_file.format.file_format = 'OPEN_EXR'\noutput_file.format.color_depth = '16'\n\nscene.node_tree.links.new(\n render_layers.outputs['Vector'],\n output_file.inputs['Image']\n)\n\noutput_file = nodes.new(\"CompositorNodeOutputFile\")\noutput_file.base_path = \"/Users/qian/Desktop/Depth\"\noutput_file.format.file_format = 'OPEN_EXR'\noutput_file.format.color_depth = '16'\n\nscene.node_tree.links.new(\n render_layers.outputs['Depth'],\n output_file.inputs['Image']\n)\n\noutput_file = nodes.new(\"CompositorNodeOutputFile\")\noutput_file.base_path = \"/Users/qian/Desktop/Image\"\noutput_file.format.color_depth = '16'\noutput_file.format.color_depth = '16'\n\nscene.node_tree.links.new(\n render_layers.outputs['Image'],\n output_file.inputs['Image']\n)\n\nbpy.ops.render.render(animation = True)","repo_name":"cianhwang/TrainingDataSynthesis","sub_path":"simple-animation.py","file_name":"simple-animation.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24081942822","text":"print(\"Welcome to the rollercoaster!\")\r\nheight = int(input(\"What is your height in cm? \"))\r\nbill = 0\r\n\r\nif height > 120:\r\n print(\"Welcome you can ride the rolecoaster\\n\")\r\n age = int(input(\"What is your age?\"))\r\n if age > 18:\r\n bill = 12\r\n print(\"Your ticket price is $12\")\r\n elif age < 12:\r\n bill = 5\r\n print(\"Your ticket price is $5\")\r\n else:\r\n bill = 7\r\n print(\"Your ticket price is $7\")\r\n\r\n if age < 55 and age > 45:\r\n print(\"your ticket is free!!\")\r\n bill = 0\r\nelse:\r\n msg = \"you cant ride into the roller coaster\"\r\n print(msg)\r\n\r\nphoto = \"do you want to click a photo you need to pay 3 dollars write 'yes' or 'no'\"\r\nif input(photo) == \"yes\":\r\n bill += 3\r\n\r\nprint(f\"You need to pay ${bill}\")","repo_name":"dxdelvin/python-100-days-project","sub_path":"RollerCoaster_entry_Day3.py","file_name":"RollerCoaster_entry_Day3.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23744503839","text":"import json\nimport requests\nimport os\nimport datetime\nimport urllib.parse\n\n\nclass API(object):\n\n def __init__(self, key, cache_dir, api):\n \"\"\"\n\n :param key: dictionary with name and value for passing key argument\n :param cache_dir: name of folder to do backups\n :param api: slice of url to make calls\n \"\"\"\n self.api = api\n self.key = key\n self.cache_dir = cache_dir\n\n def get_key(self):\n return self.key\n\n def get_url(self, service_name):\n return urllib.parse.urljoin(self.api, service_name)\n\n def get_cache(self, file_name, directory=None, ext=None):\n if directory is None:\n directory = self.cache_dir\n cache = os.path.join(directory, file_name)\n if ext:\n cache += ext\n if os.path.exists(cache):\n print('found the file, loading cache')\n with open(cache, 'r') as f:\n return json.load(f)\n return None\n\n def set_cache(self, file_name, json_data, directory=None, ext=None):\n if directory is None:\n directory = self.cache_dir\n cache = os.path.join(directory, file_name)\n if ext:\n cache += ext\n cache_base = os.path.dirname(cache)\n if not os.path.exists(cache_base):\n os.makedirs(cache_base)\n with open(cache, 'w') as f:\n json.dump(json_data, f, indent=4)\n\n def get_service_cache(self, service_name, cache=True, ext=None, **kwargs):\n if cache:\n cache_data = self.get_cache(service_name, ext=ext)\n if cache_data is not None:\n return cache_data\n print('did not find the file.')\n url = self.get_url(service_name)\n key = self.get_key()\n payload = kwargs\n if key is not None:\n payload.update(key)\n result = requests.get(url, params=payload)\n if result.status_code != 200:\n print('There was an error in the request. Code: {}'.format(result.status_code))\n return None\n json_data = result.json()\n if cache:\n print('writing cache.')\n self.set_cache(service_name, json_data, ext=ext)\n return json_data\n\n def get_timestamp(self, format=\"%Y-%m-%dT%H\"):\n \"\"\"\n Useful for naming downloaded files\n :return:\n \"\"\"\n return datetime.datetime.utcnow().strftime(format)","repo_name":"pchtsp/transport_api","sub_path":"api_consumer.py","file_name":"api_consumer.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24289656626","text":"import math\n\nfrom helpers.file_handling import raw_input_from_file\n\n\ndef most_common_bit(index: int, numbers: [int]):\n ones = 0\n for num in numbers:\n if num[index - 1] == '1':\n ones = ones + 1\n if math.ceil(len(numbers) / 2) <= ones:\n return 1\n else:\n return 0\n\n\ndef calculate_gamma_rate(binary_strings):\n gamma_rate = \"\"\n length = len(binary_strings[0])\n for index in range(length):\n gamma_rate += str(most_common_bit(index + 1, binary_strings))\n return int(gamma_rate, 2)\n\n\ndef calculate_epsilon_rate(binary_strings):\n epsilon_rate = \"\"\n length = len(binary_strings[0])\n for index in range(length):\n epsilon_rate += \"0\" if str(most_common_bit(index + 1, binary_strings)) == \"1\" else \"1\"\n\n return int(epsilon_rate, 2)\n\n\ndef parse_binary_strings(file_name):\n input_text = raw_input_from_file(file_name)\n return input_text.splitlines()\n\n\ndef find_oxygen_gen_rating(binary_strings):\n bin_list = list(binary_strings)\n index = 1\n while len(bin_list) != 1:\n most_common = most_common_bit(index, bin_list)\n if most_common == 1:\n bin_list = list(filter(lambda x: x[index - 1] == '1', bin_list))\n elif most_common == 0:\n bin_list = list(filter(lambda x: x[index - 1] == '0', bin_list))\n index = index + 1\n\n return int(bin_list[0], 2)\n\n\ndef find_co2_scrubber_rating(binary_strings):\n bin_list = list(binary_strings)\n index = 1\n while len(bin_list) != 1:\n most_common = most_common_bit(index, bin_list)\n if most_common == 1:\n bin_list = list(filter(lambda x: x[index - 1] == '0', bin_list))\n elif most_common == 0:\n bin_list = list(filter(lambda x: x[index - 1] == '1', bin_list))\n index = index + 1\n\n return int(bin_list[0], 2)\n","repo_name":"madsthom/advent-of-code-2021","sub_path":"day3/power_consumption.py","file_name":"power_consumption.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24759373590","text":"import os\nimport logging\nimport asyncio\nimport websockets\n\nfrom flask import json\nfrom flask import current_app as app\nfrom datetime import datetime\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\n\n\nclass ClosedSocket():\n \"\"\"Mimic closed socket to simplify logic when connection\n can't be estabilished at first place.\n \"\"\"\n def __init__(self):\n self.open = False\n\n def close(self):\n pass\n\n\ndef init_app(app):\n \"\"\"Create websocket connection and put it on app object.\"\"\"\n host = app.config['WS_HOST']\n port = app.config['WS_PORT']\n try:\n loop = asyncio.get_event_loop()\n app.notification_client = loop.run_until_complete(websockets.connect('ws://%s:%s/server' % (host, port)))\n logger.info('websocket connected on=%s:%s' % app.notification_client.local_address)\n except (RuntimeError, OSError):\n # not working now, but we can try later when actually sending something\n app.notification_client = ClosedSocket()\n\n\ndef _notify(**kwargs):\n \"\"\"Send out all kwargs as json string.\"\"\"\n kwargs.setdefault('_created', datetime.utcnow().isoformat())\n kwargs.setdefault('_process', os.getpid())\n message = json.dumps(kwargs)\n\n @asyncio.coroutine\n def send_message():\n yield from app.notification_client.send(message)\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(send_message())\n\n\ndef push_notification(name, **kwargs):\n \"\"\"Push notification to websocket.\n\n In case socket is closed it will try to reconnect.\n\n :param name: event name\n \"\"\"\n logger.info('pushing event {0} ({1})'.format(name, json.dumps(kwargs)))\n\n if not app.notification_client.open:\n app.notification_client.close()\n init_app(app)\n\n if not app.notification_client.open:\n logger.info('No connection to websocket server. Dropping event %s' % name)\n return\n\n try:\n _notify(event=name, extra=kwargs)\n except Exception as err:\n logger.exception(err)\n","repo_name":"plamut/superdesk-core","sub_path":"superdesk/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"24248905915","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nimport os\nimport webbrowser\nimport lib \nimport base64\nimport json\nimport argparse\nimport time\nfrom bs4 import BeautifulSoup\n\ndef ts_open(name,prefix):\n _name=str(name).upper().capitalize()\n _prefix=prefix\n _comp=str(name).lower()\n return \"\"\"/// \n class\"\"\" \" \"+_name+\" \"\"\"\"extends Component {\n constructor(){\n /*Llamado cuando el elemento es creado o actualizado*/\n super({open:\"open\",style:null,template:\"

coloca tus tags html aqui

\"})\n }\nconnectedCallback(){\n /*Llamado cuando el elemento se es insertado en el documento, incluyéndose en un árbol shadow*/\n}\ndisconnectedCallback(){\n /*Llamado cuando el elemento es eliminado de un documento*/\n\n}\nadoptedCallback(antiguoDocumento, nuevoDocumento){\n /*Llamado cuando un elemento es adoptado en otro nuevo documento*/\n}\n/*Observar los cambios en el atributo 'name'.\n*puedes tener una lista de atributos y manejarlo en el metodo \n*attributeChangueCallback\n*/\nstatic get observedAttributes() {return ['name']; }\n/*Responder a los cambios en el atributo.*/\nattributeChangedCallback(attr, oldValue, newValue) {\n /*Llamado cuando un atributo es cambiado, concatenado, eliminado o reemplazado en el elemento. Sólo llamado sobre atributos observados.*/\n if (attr == 'name') {\n /*Aqui realiza los cambios en tus compionentes = `Hello, ${newValue}`;*/\n }\n}\n}\nweb_component(\"\"\"+\"'{1}-{2}',{0}\".format(_name,_prefix,_comp)+\" );\"\n\n\ndef ts_closed(name,prefix):\n _name=str(name).upper().capitalize()\n _prefix=prefix\n _comp=str(name).lower()\n return \"\"\"/// \n class\"\"\" \" \"+_name+\" \"\"\"\"extends Component {\n constructor(){\n /*Llamado cuando el elemento es creado o actualizado*/\n super({open:\"open\",style:ReadCss,template:\"

coloca tus tags html aqui

\"})\n }\nconnectedCallback(){\n /*Llamado cuando el elemento se es insertado en el documento, incluyéndose en un árbol shadow*/\n}\ndisconnectedCallback(){\n /*Llamado cuando el elemento es eliminado de un documento*/\n\n}\nadoptedCallback(antiguoDocumento, nuevoDocumento){\n /*Llamado cuando un elemento es adoptado en otro nuevo documento*/\n}\n/*Observar los cambios en el atributo 'name'.\n*puedes tener una lista de atributos y manejarlo en el metodo \n*attributeChangueCallback\n*/\nstatic get observedAttributes() {return ['name']; }\n/*Responder a los cambios en el atributo.*/\nattributeChangedCallback(attr, oldValue, newValue) {\n /*Llamado cuando un atributo es cambiado, concatenado, eliminado o reemplazado en el elemento. Sólo llamado sobre atributos observados.*/\n if (attr == 'name') {\n /*Aqui realiza los cambios en tus compionentes = `Hello, ${newValue}`;*/\n }\n}\n}\nweb_component(\"\"\"+\"'{1}-{2}',{0}\".format(_name,_prefix,_comp)+\" );\"\n\n#iciar una aplicaion web -> meod-cli.pyc init nameproyect\n#export PATH=\"$PATH:`pwd`/flutter/bin\"\n#os.system(\"comando liux\")\ndef img64(name:str,img_str_64:str):\n imgdata = base64.b64decode(img_str_64)\n with open(name, 'wb') as f:\n f.write(imgdata)\n\npath:str=os.getcwd()\n\"sdf\".upper().capitalize()\n\nif sys.argv[1]==\"init\" and sys.argv[2]:\n if sys.argv[3]:\n prefix:str=sys.argv[3]\n else:\n prefix=\"app\"\n name_proyect:str=sys.argv[2]\n os.mkdir(\"{0}/{1}\".format(path,name_proyect))\n \n with open(\"{0}/{1}/meod-core.js\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Core.core)\n with open(\"{0}/{1}/meod-support-core.js\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Core.coreSupport)\n\n os.mkdir(\"{0}/{1}/css\".format(path,name_proyect))\n \n with open(\"{0}/{1}/css/main.scss\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Css.main)\n \n os.mkdir(\"{0}/{1}/css/components\".format(path,name_proyect))\n arch:dict={\"_aside.scss\":lib.Css.compAside,\"_button-float.scss\":lib.Css.compButton,\"_input.scss\":lib.Css.compInput,\"_switch.scss\":lib.Css.compSwitch}\n for k,v in arch.items():\n with open(\"{0}/{1}/css/components/{2}\".format(path,name_proyect,k),\"w\") as f:\n f.write(arch[k])\n\n with open(\"{0}/{1}/css/_material.scss\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Css.material)\n\n os.mkdir(\"{0}/{1}/fonts\".format(path,name_proyect))\n\n os.mkdir(\"{0}/{1}/layout\".format(path,name_proyect))\n os.mkdir(\"{0}/{1}/mipmap\".format(path,name_proyect))\n \n img:dict={\"back.png\":lib.Img.back,\"menuSd.png\":lib.Img.menuSd,\"menu.png\":lib.Img.menuBar,\"plus.png\":lib.Img.mas}\n for k,v in img.items():\n img64(f'{path}/{name_proyect}/mipmap/{k}',img[k])\n\n img64(\"{0}/{1}/mipmap/loader.gif\".format(path,name_proyect),lib.Img.loader)\n \n os.mkdir(\"{0}/{1}/test\".format(path,name_proyect))\n \n os.mkdir(\"{0}/{1}/values\".format(path,name_proyect))\n values:dict={\"color.js\":lib.Values.color,\"dimens.js\":lib.Values.dimens,\"fonts.js\":lib.Values.fonts,\"icons.js\":lib.Values.icons,\"strings.js\":\"\",\"support.js\":lib.Values.toolbarSupport,\"ux.js\":lib.Values.ux}\n for k,v in values.items():\n with open(\"{0}/{1}/values/{2}\".format(path,name_proyect,k),\"w\") as f:\n f.write(values[k])\n \n with open(\"{0}/{1}/com-v0.5.2.js\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.compresor)\n \n with open(\"{0}/{1}/manifest.js\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.manifest)\n \n with open(\"{0}/{1}/LICENCE\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.licencia)\n\n with open(\"{0}/{1}/readme.md\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.readme)\n with open(\"{0}/{1}/manual.txt\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.manual)\n \n meod_json:str=json.dumps({\"path\":path,\"name_proyect\":name_proyect,\"prefix\":prefix})\n with open(\"{0}/{1}/manifest.js\".format(path,name_proyect),\"w\") as f:\n f.write(lib.Fuera.manifest)\n\n with open(\"{0}/{1}/meod-cli.json\".format(path,name_proyect),\"w\") as f:\n f.write(meod_json)\nelse:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-new\", \"--new\", help=\"Nombre del nuevo componente\")\n parser.add_argument(\"-m\",\"--mode\",help=\"open | closed -> para crear un nodo del dom encapsulado o abierto \")\n parser.add_argument(\"-p\",\"--prefix\", help=\"El prefijo de tus componetes , te recomendamos un nombre corto\")\n parser.add_argument(\"-c\",\"--compresion\", help=\"Comprime el componente\")\n parser.add_argument(\"-vjs\",\"--versionjs\", help=\"Cual sera la versiono de js\")\n args = parser.parse_args()\n f=open(f\"{os.getcwd()}/meod-cli.json\",\"r\")\n meod_py =f.read()\n f.close()\n meod_py=json.loads(meod_py)\n#import time\n#time.strftime(\"%H:%M:%S\") #Formato de 24 horas\n#20:08:40\n#import time\n#time.strftime(\"%I:%M:%S\") #Formato de 12 horas\n#08:08:40\n#Imprimir la fecha actual:\n#Formato: dd/mm/yyyy\n#import time\n#print (time.strftime(\"%d/%m/%y\"))\n#22/05/14\n if args.new:\n os.mkdir(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.new}\")\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.new}/{meod_py['prefix']}.{args.new}.html\",\"w\") as f:\n f.write(f\"\"\"\n\n\n \n \n \n {args.new}\n\n\n

Estas a punto de crear yu primer componente

\n\n \"\"\")\n if args.mode==\"open\":\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/css/components/{meod_py['prefix']}.{args.new}.scss\",\"w\") as f:\n f.write(f\"/*Hoja de estilos del componente: {args.new} fecha:{time.strftime('%d/%m/%y')} , hora: {time.strftime('%H:%M:%S')}*/\")\n component:str=str(args.new).lower().capitalize()\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.new}/{meod_py['prefix']}.{args.new}.ts\",\"w\") as f:\n f.write(ts_open(component,meod_py[\"prefix\"]))\n else:\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.new}/{meod_py['prefix']}.{args.new}.scss\",\"w\") as f:\n f.write(f\"/*Hoja de estilos del componente: {args.new} fecha:{time.strftime('%d/%m/%y')} , hora: {time.strftime('%H:%M:%S')}*/\")\n component:str=str(args.new).lower().capitalize()\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.new}/{meod_py['prefix']}.{args.new}.ts\",\"w\") as f:\n f.write(ts_closed(component,meod_py[\"prefix\"]))\n if args.compresion:\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.compresion}/{meod_py['prefix']}.{args.compresion}.scss\",\"r\") as f:\n hoja=f.read()\n\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.compresion}/{meod_py['prefix']}.{args.compresion}.ts\",\"r\") as f:\n ho=f.read()\n print(hoja)\n res=ho.replace(\"ReadCss\",\"`{0}`\".format(hoja))\n with open(f\"{meod_py['path']}/{meod_py['name_proyect']}/layout/{args.compresion}/{meod_py['prefix']}.{args.compresion}.ts\",\"w+\") as f:\n f.write(str(res))\n ver=args.versionjs if args.versionjs else 'es6'\n os.system(f\"tsc {meod_py['path']}/{meod_py['name_proyect']}/layout/{args.compresion}/{meod_py['prefix']}.{args.compresion}.ts -t {ver}\")","repo_name":"lechesdarwin/meod","sub_path":"meod-cli2.py","file_name":"meod-cli2.py","file_ext":"py","file_size_in_byte":9428,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43396124064","text":"\"\"\"\nCreates the custom Live Production menu in Motionbuilder \nthat contains all the Live Production tools.\n\n\"\"\"\nfrom __future__ import print_function\nimport functools\nfrom pyfbsdk import FBMenuManager\n\n# constants\nMENU_NAME = 'Live-Production'\n\n# globals\nfunction_map = dict()\n\ndef event_menu(control, event):\n global function_map\n function_map[event.Id]()\n\ndef _pre_record_prep():\n import liveproduction.new_take\n reload(liveproduction.new_take)\n liveproduction.new_take.connect_master_constraints()\n \ndef _create_new_take():\n import liveproduction.popup\n reload(liveproduction.popup)\n liveproduction.popup.create_tool()\n \ndef _devices_offline():\n import liveproduction.next_take\n reload(liveproduction.next_take)\n liveproduction.next_take.devices_offline()\n \ndef _plot_camera():\n import liveproduction.next_take\n reload(liveproduction.next_take)\n liveproduction.next_take.plot_camera()\n \ndef _plot_characters():\n import liveproduction.next_take\n reload(liveproduction.next_take)\n liveproduction.next_take.plot_characters()\n \ndef _post_record_prep():\n import liveproduction.next_take\n reload(liveproduction.next_take)\n liveproduction.next_take.disconnect_master_constraints()\n \ndef _duplicate_cameras():\n import liveproduction.duplicate_cameras\n reload(liveproduction.duplicate_cameras)\n liveproduction.duplicate_cameras.find_master_cam()\n\n\nif __name__ == '__builtin__':\n # Look for the menu, otherwise make one\n if not FBMenuManager().GetMenu(MENU_NAME):\n FBMenuManager().InsertAfter(None, 'Help', MENU_NAME)\n menu = FBMenuManager().GetMenu(MENU_NAME)\n menu.OnMenuActivate.Add(event_menu)\n\n # Add items to the menu\n menu.InsertFirst('Turn Devices On + Connect Constraints', 1)\n menu.InsertLast('Create New Take', 2)\n menu.InsertLast('Devices Offline', 3)\n menu.InsertLast('Plot Camera', 4)\n menu.InsertLast('Plot Characters', 5)\n menu.InsertLast('Disconnect Constraints + Turn TP VCam Offline', 6)\n menu.InsertLast('Duplicate Cameras', 7)\n\n # Map menu items to functions\n function_map[1] = _pre_record_prep\n function_map[2] = _create_new_take\n function_map[3] = _devices_offline\n function_map[4] = _plot_camera\n function_map[5] = _plot_characters\n function_map[6] = _post_record_prep\n function_map[7] = _duplicate_cameras\n","repo_name":"Afische/MotionBuilderProductionSupport","sub_path":"production_menu.py","file_name":"production_menu.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36642513148","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n Author: pirogue \n Purpose: 日志列表分页\n Site: http://pirogue.org \n Created: 2018-08-06 18:33:29\n\"\"\"\n\n\nimport tornado\nimport json\nfrom service.paginationlog import listpage, total_atk_page, total_wit_page\nfrom handlers.base import BaseHandler\nfrom util.auth import jwtauth\n\n@jwtauth\nclass GetlistJsonHandler(BaseHandler):\n \"\"\" 获取日志列表 \"\"\"\n\n # 自定义错误页面\n def write_error(self,status_code,**kwargs):\n self.write(\"Unable to parse JSON.\")\n\n def post(self):\n # \n if self.request.headers[\"Content-Type\"].startswith(\"application/json\"):\n self.json_args = json.loads(self.request.body)\n else:\n self.json_args = None\n message = 'Unable to parse JSON.'\n self.send_error(status_code=400) # 向浏览器发送错误状态码,会调用write_error\n\n param = self.request.body.decode('utf-8')\n # print 'page start'\n\n # print type(param)\n \n param = json.loads(param)\n # print param\n viewres = listpage(param)\n # print param\n # print(type(param))\n self.write(viewres)\n\n def get(self):\n # 分页列表\n types = self.get_argument('type')\n if types:\n if int(types) == 1:\n self.write(str(total_wit_page()))\n elif int(types) == 2:\n self.write(str(total_atk_page()))\n","repo_name":"p1r06u3/opencanary_web","sub_path":"handlers/paginationlog.py","file_name":"paginationlog.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":654,"dataset":"github-code","pt":"18"} +{"seq_id":"71952281321","text":"# 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. \n\n# 입력 : 첫째 줄에 테스트 케이스의 개수 T가 주어진다. \n# 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) \n\n# 출력 : 각 테스트 케이스마다 A+B를 출력한다.\n\n# 파이썬 map 함수 : map(function, iterable) \n# 리스트 요소를 원하는 함수로 바꿔 새 리스트로 생성\n\n\nT= int(input())\n\nfor i in range (T):\n A,B = map(int,input().split())\n print (A + B)\n \n\n","repo_name":"man-ze/baekjoonForPython","sub_path":"Q10950.py","file_name":"Q10950.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20665812364","text":"import string\n\n\nemoji_trans = str.maketrans({p: '' for p in string.punctuation + ' '})\n\n\ndef wrap(to_wrap, wrap_with, sep=' '):\n return f\"{wrap_with}{sep}{to_wrap}{sep}{wrap_with}\"\n\n\ndef unique(it, key):\n new = []\n added = []\n for i in it:\n k = key(i)\n if k not in added:\n new.append(i)\n added.append(k)\n return new\n","repo_name":"tacopill/Pokebot","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"14356896282","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\nadmin.autodiscover()\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', 'gallery.views.view_images', name='view_images'),\n url(r'^upload-one/$', 'gallery.views.upload_one_image', name='upload_one_image'),\n url(r'^upload/$', 'gallery.views.upload_images', name='upload_images'),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n )\n","repo_name":"kmike/GearsUploader","sub_path":"examples/django_example/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26517092295","text":"from typing import Optional, Tuple\n\nfrom acme import adders\nfrom acme import core\nfrom acme import types\n# Internal imports.\nfrom acme.tf import utils as tf2_utils\nfrom acme.tf import variable_utils as tf2_variable_utils\n\nimport dm_env\nimport sonnet as snt\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\ntfd = tfp.distributions\n\n\nclass FeedForwardActor(core.Actor):\n \"\"\"A feed-forward actor.\n\n An actor based on a feed-forward policy which takes non-batched observations\n and outputs non-batched actions. It also allows adding experiences to replay\n and updating the weights from the policy on the learner.\n \"\"\"\n\n def __init__(\n self,\n policy_network: snt.Module,\n adder: Optional[adders.Adder] = None,\n variable_client: Optional[tf2_variable_utils.VariableClient] = None,\n ):\n \"\"\"Initializes the actor.\n\n Args:\n policy_network: the policy to run.\n adder: the adder object to which allows to add experiences to a\n dataset/replay buffer.\n variable_client: object which allows to copy weights from the learner copy\n of the policy to the actor copy (in case they are separate).\n \"\"\"\n\n # Store these for later use.\n self._adder = adder\n self._variable_client = variable_client\n self._policy_network = policy_network\n\n @tf.function\n def _policy(self, observation: types.NestedTensor) -> types.NestedTensor:\n # Add a dummy batch dimension and as a side effect convert numpy to TF.\n batched_observation = tf2_utils.add_batch_dim(observation)\n\n # Compute the policy, conditioned on the observation.\n policy = self._policy_network(batched_observation)\n\n # Sample from the policy if it is stochastic.\n action = policy.sample() if isinstance(policy, tfd.Distribution) else policy\n\n return action\n\n def select_action(self, observation: types.NestedArray) -> types.NestedArray:\n # Pass the observation through the policy network.\n action = self._policy(observation)\n\n # Return a numpy array with squeezed out batch dimension.\n return tf2_utils.to_numpy_squeeze(action)\n\n def observe_first(self, timestep: dm_env.TimeStep):\n if self._adder:\n self._adder.add_first(timestep)\n\n def observe(self, action: types.NestedArray, next_timestep: dm_env.TimeStep):\n if self._adder:\n self._adder.add(action, next_timestep)\n\n def update(self, wait: bool = False):\n if self._variable_client:\n self._variable_client.update(wait)\n\n\nclass RecurrentActor(core.Actor):\n \"\"\"A recurrent actor.\n\n An actor based on a recurrent policy which takes non-batched observations and\n outputs non-batched actions, and keeps track of the recurrent state inside. It\n also allows adding experiences to replay and updating the weights from the\n policy on the learner.\n \"\"\"\n\n def __init__(\n self,\n policy_network: snt.RNNCore,\n adder: Optional[adders.Adder] = None,\n variable_client: Optional[tf2_variable_utils.VariableClient] = None,\n store_recurrent_state: bool = True,\n ):\n \"\"\"Initializes the actor.\n\n Args:\n policy_network: the (recurrent) policy to run.\n adder: the adder object to which allows to add experiences to a\n dataset/replay buffer.\n variable_client: object which allows to copy weights from the learner copy\n of the policy to the actor copy (in case they are separate).\n store_recurrent_state: Whether to pass the recurrent state to the adder.\n \"\"\"\n # Store these for later use.\n self._adder = adder\n self._variable_client = variable_client\n self._network = policy_network\n self._state = None\n self._prev_state = None\n self._store_recurrent_state = store_recurrent_state\n\n @tf.function\n def _policy(\n self,\n observation: types.NestedTensor,\n state: types.NestedTensor,\n ) -> Tuple[types.NestedTensor, types.NestedTensor]:\n\n # Add a dummy batch dimension and as a side effect convert numpy to TF.\n batched_observation = tf2_utils.add_batch_dim(observation)\n\n # Compute the policy, conditioned on the observation.\n policy, new_state = self._network(batched_observation, state)\n\n # Sample from the policy if it is stochastic.\n action = policy.sample() if isinstance(policy, tfd.Distribution) else policy\n\n return action, new_state\n\n def select_action(self, observation: types.NestedArray) -> types.NestedArray:\n # Initialize the RNN state if necessary.\n if self._state is None:\n self._state = self._network.initial_state(1)\n\n # Step the recurrent policy forward given the current observation and state.\n policy_output, new_state = self._policy(observation, self._state)\n\n # Bookkeeping of recurrent states for the observe method.\n self._prev_state = self._state\n self._state = new_state\n\n # Return a numpy array with squeezed out batch dimension.\n return tf2_utils.to_numpy_squeeze(policy_output)\n\n def observe_first(self, timestep: dm_env.TimeStep):\n if self._adder:\n self._adder.add_first(timestep)\n\n # Set the state to None so that we re-initialize at the next policy call.\n self._state = None\n\n def observe(self, action: types.NestedArray, next_timestep: dm_env.TimeStep):\n if not self._adder:\n return\n\n if not self._store_recurrent_state:\n self._adder.add(action, next_timestep)\n return\n\n numpy_state = tf2_utils.to_numpy_squeeze(self._prev_state)\n self._adder.add(action, next_timestep, extras=(numpy_state,))\n\n def update(self, wait: bool = False):\n if self._variable_client:\n self._variable_client.update(wait)\n\n# Internal class 1.\n# Internal class 2.\n","repo_name":"deepmind/acme","sub_path":"acme/agents/tf/actors.py","file_name":"actors.py","file_ext":"py","file_size_in_byte":5600,"program_lang":"python","lang":"en","doc_type":"code","stars":3100,"dataset":"github-code","pt":"18"} +{"seq_id":"32077290013","text":"# pyright: strict\n\nfrom dataclasses import dataclass\n\nfrom ...makeentries import Entries\nfrom ...refdata import Facts\n\nfrom .production_branches import (\n ExtraEmission,\n ProductionSubBranch,\n ProductionSubBranchCO2viaFEC,\n ProductionBranch,\n ProductionSum,\n)\n\n\n@dataclass(kw_only=True)\nclass Production:\n\n total: ProductionSum\n\n miner: ProductionBranch\n miner_cement: ProductionSubBranch\n miner_chalk: ProductionSubBranch\n miner_glas: ProductionSubBranch\n miner_ceram: ProductionSubBranch\n\n chem: ProductionBranch\n chem_basic: ProductionSubBranch\n chem_ammonia: ProductionSubBranch\n chem_other: ProductionSubBranch\n\n metal: ProductionBranch\n metal_steel: ProductionSum\n metal_steel_primary: ProductionSubBranch\n metal_steel_secondary: ProductionSubBranch\n metal_nonfe: ProductionSubBranch\n\n other: ProductionBranch\n other_paper: ProductionSubBranch\n other_food: ProductionSubBranch\n other_further: ProductionSubBranchCO2viaFEC\n other_2efgh: ExtraEmission\n\n\ndef calc_production_by_co2e(\n entries: Entries,\n entries_germany: Entries,\n facts: Facts,\n production_germany: Production,\n) -> Production:\n fact = facts.fact\n\n co2e_miner_cement_corrected = (\n entries.i_dehst_miner_cement\n * production_germany.miner_cement.CO2e_total\n / entries_germany.i_dehst_miner_cement\n )\n miner_cement = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"cement\",\n co2e_sub_branch=co2e_miner_cement_corrected,\n )\n\n co2e_miner_chalk_corrected = (\n entries.i_dehst_miner_chalk\n * production_germany.miner_chalk.CO2e_total\n / entries_germany.i_dehst_miner_chalk\n )\n miner_chalk = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"chalk\",\n co2e_sub_branch=co2e_miner_chalk_corrected,\n )\n\n co2e_miner_glas_corrected = (\n entries.i_dehst_miner_glas\n * production_germany.miner_glas.CO2e_total\n / entries_germany.i_dehst_miner_glas\n )\n miner_glas = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"glas\",\n co2e_sub_branch=co2e_miner_glas_corrected,\n )\n\n co2e_miner_ceram_corrected = (\n entries.i_dehst_miner_ceram\n * production_germany.miner_ceram.CO2e_total\n / entries_germany.i_dehst_miner_ceram\n )\n miner_ceram = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"ceram\",\n co2e_sub_branch=co2e_miner_ceram_corrected,\n )\n\n miner = ProductionBranch.sum(\n sub_branch_list=[miner_cement, miner_chalk, miner_glas, miner_ceram]\n )\n\n co2e_chem_basic_corrected = (\n entries.i_dehst_chem_basic\n * production_germany.chem_basic.CO2e_total\n / entries_germany.i_dehst_chem_basic\n )\n chem_basic = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"basic\",\n co2e_sub_branch=co2e_chem_basic_corrected,\n )\n\n co2e_chem_ammonia_corrected = (\n entries.i_dehst_chem_ammonia\n * production_germany.chem_ammonia.CO2e_total\n / entries_germany.i_dehst_chem_ammonia\n )\n chem_ammonia = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"ammonia\",\n co2e_sub_branch=co2e_chem_ammonia_corrected,\n )\n\n co2e_chem_other_corrected = (\n entries.i_dehst_chem_other\n * production_germany.chem_other.CO2e_total\n / entries_germany.i_dehst_chem_other\n )\n chem_other = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"other\",\n co2e_sub_branch=co2e_chem_other_corrected,\n )\n\n chem = ProductionBranch.sum(sub_branch_list=[chem_basic, chem_ammonia, chem_other])\n\n co2e_metal_steel_primary_corrected = (\n entries.i_dehst_metal_steel_primary\n * production_germany.metal_steel_primary.CO2e_total\n / entries_germany.i_dehst_metal_steel_primary\n )\n metal_steel_primary = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"steel_primary\",\n co2e_sub_branch=co2e_metal_steel_primary_corrected,\n )\n\n co2e_metal_steel_secondary_corrected = (\n entries.i_dehst_metal_steel_secondary\n * production_germany.metal_steel_secondary.CO2e_total\n / entries_germany.i_dehst_metal_steel_secondary\n )\n metal_steel_secondary = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"steel_secondary\",\n co2e_sub_branch=co2e_metal_steel_secondary_corrected,\n )\n\n co2e_metal_nonfe_corrected = (\n entries.i_dehst_metal_nonfe\n * production_germany.metal_nonfe.CO2e_total\n / entries_germany.i_dehst_metal_nonfe\n )\n metal_nonfe = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"nonfe\",\n co2e_sub_branch=co2e_metal_nonfe_corrected,\n )\n\n metal_steel = ProductionSum.sum(\n metal_steel_primary,\n metal_steel_secondary,\n )\n\n metal = ProductionBranch.sum(sub_branch_list=[metal_steel, metal_nonfe])\n\n co2e_other_paper_corrected = (\n entries.i_dehst_other_paper\n * production_germany.other_paper.CO2e_total\n / entries_germany.i_dehst_other_paper\n )\n other_paper = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"other\",\n sub_branch=\"paper\",\n co2e_sub_branch=co2e_other_paper_corrected,\n )\n\n co2e_other_food_corrected = (\n entries.i_dehst_other_food\n * production_germany.other_food.CO2e_total\n / entries_germany.i_dehst_other_food\n )\n other_food = ProductionSubBranch.calc_sub_branch_by_co2e(\n facts=facts,\n branch=\"other\",\n sub_branch=\"food\",\n co2e_sub_branch=co2e_other_food_corrected,\n )\n\n # use old logic for calculation by area and energy for other_further and 2efgh\n i_energy_total = (\n (\n fact(\"Fact_I_S_coal_fec_2018\")\n + fact(\"Fact_I_S_diesel_fec_2018\")\n + fact(\"Fact_I_S_fueloil_fec_2018\")\n + fact(\"Fact_I_S_lpg_fec_2018\")\n + fact(\"Fact_I_S_gas_fec_2018\")\n + fact(\"Fact_I_S_opetpro_fec_2018\")\n + fact(\"Fact_I_S_biomass_fec_2018\")\n + fact(\"Fact_I_S_orenew_fec_2018\")\n + fact(\"Fact_I_S_ofossil_fec_2018\")\n + fact(\"Fact_I_S_elec_fec_2018\")\n + fact(\"Fact_I_S_heatnet_fec_2018\")\n )\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n energy_consumption_industry = i_energy_total\n i_fec_pct_of_other = fact(\"Fact_I_P_other_ratio_fec_to_industry_2018\")\n energy_consumption_other = energy_consumption_industry * i_fec_pct_of_other\n other_further = ProductionSubBranchCO2viaFEC.calc_sub_branch(\n facts=facts,\n branch=\"other\",\n sub_branch=\"further\",\n energy_consumption_branch=energy_consumption_other,\n )\n\n other_2efgh = ExtraEmission.calc_extra_emission(\n facts=facts,\n branch=\"other\",\n sub_branch=\"2efgh\",\n energy_consumption=other_further.energy,\n )\n\n other = ProductionBranch.sum(\n sub_branch_list=[other_paper, other_food],\n sub_branch_via_FEC_list=[other_further],\n extra_emission_list=[other_2efgh],\n )\n\n total = ProductionSum.sum(miner, chem, metal, other)\n\n return Production(\n total=total,\n miner=miner,\n miner_cement=miner_cement,\n miner_chalk=miner_chalk,\n miner_glas=miner_glas,\n miner_ceram=miner_ceram,\n chem=chem,\n chem_basic=chem_basic,\n chem_ammonia=chem_ammonia,\n chem_other=chem_other,\n metal=metal,\n metal_steel=metal_steel,\n metal_steel_primary=metal_steel_primary,\n metal_steel_secondary=metal_steel_secondary,\n metal_nonfe=metal_nonfe,\n other=other,\n other_paper=other_paper,\n other_food=other_food,\n other_further=other_further,\n other_2efgh=other_2efgh,\n )\n\n\ndef calc_production_by_energy(entries: Entries, facts: Facts) -> Production:\n fact = facts.fact\n\n # Calculation was performed in entries\n i_coal_fec = (\n fact(\"Fact_I_S_coal_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_diesel_fec = (\n fact(\"Fact_I_S_diesel_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_fueloil_fec = (\n fact(\"Fact_I_S_fueloil_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_lpg_fec = (\n fact(\"Fact_I_S_lpg_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_gas_fec = (\n fact(\"Fact_I_S_gas_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_opetpro_fec = (\n fact(\"Fact_I_S_opetpro_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_biomass_fec = (\n fact(\"Fact_I_S_biomass_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_orenew_fec = (\n fact(\"Fact_I_S_orenew_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_ofossil_fec = (\n fact(\"Fact_I_S_ofossil_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_elec_fec = (\n fact(\"Fact_I_S_elec_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n i_heatnet_fec = (\n fact(\"Fact_I_S_heatnet_fec_2018\")\n * entries.m_area_industry_com\n / entries.m_area_industry_nat\n )\n\n i_energy_total = (\n i_coal_fec\n + i_diesel_fec\n + i_fueloil_fec\n + i_lpg_fec\n + i_gas_fec\n + i_opetpro_fec\n + i_biomass_fec\n + i_orenew_fec\n + i_ofossil_fec\n + i_elec_fec\n + i_heatnet_fec\n )\n\n i_fec_pct_of_miner = fact(\"Fact_I_P_miner_ratio_fec_to_industry_2018\")\n i_fec_pct_of_chem = fact(\"Fact_I_S_chem_fec_ratio_to_industrie_2018\")\n i_fec_pct_of_metal = fact(\"Fact_I_P_fec_pct_of_metal_2018\")\n i_fec_pct_of_other = fact(\"Fact_I_P_other_ratio_fec_to_industry_2018\")\n\n energy_consumption_industry = i_energy_total\n\n energy_consumption_miner = energy_consumption_industry * i_fec_pct_of_miner\n\n miner_cement = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"cement\",\n energy_consumption_branch=energy_consumption_miner,\n )\n miner_chalk = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"chalk\",\n energy_consumption_branch=energy_consumption_miner,\n )\n miner_glas = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"glas\",\n energy_consumption_branch=energy_consumption_miner,\n )\n miner_ceram = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"miner\",\n sub_branch=\"ceram\",\n energy_consumption_branch=energy_consumption_miner,\n )\n miner = ProductionBranch.sum(\n sub_branch_list=[miner_cement, miner_chalk, miner_glas, miner_ceram]\n )\n\n energy_consumption_chemistry = energy_consumption_industry * i_fec_pct_of_chem\n chem_basic = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"basic\",\n energy_consumption_branch=energy_consumption_chemistry,\n )\n chem_ammonia = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"ammonia\",\n energy_consumption_branch=energy_consumption_chemistry,\n )\n chem_other = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"chem\",\n sub_branch=\"other\",\n energy_consumption_branch=energy_consumption_chemistry,\n )\n chem = ProductionBranch.sum(sub_branch_list=[chem_basic, chem_ammonia, chem_other])\n\n energy_consumption_metal = energy_consumption_industry * i_fec_pct_of_metal\n energy_consumption_metal_steel = energy_consumption_metal * fact(\n \"Fact_I_P_metal_fec_pct_of_steel\"\n )\n metal_steel_primary = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"steel_primary\",\n energy_consumption_branch=energy_consumption_metal_steel,\n )\n metal_steel_secondary = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"steel_secondary\",\n energy_consumption_branch=energy_consumption_metal_steel,\n )\n metal_steel = ProductionSum.sum(\n metal_steel_primary,\n metal_steel_secondary,\n )\n metal_nonfe = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"metal\",\n sub_branch=\"nonfe\",\n energy_consumption_branch=energy_consumption_metal,\n )\n metal = ProductionBranch.sum(sub_branch_list=[metal_steel, metal_nonfe])\n\n energy_consumption_other = energy_consumption_industry * i_fec_pct_of_other\n other_paper = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"other\",\n sub_branch=\"paper\",\n energy_consumption_branch=energy_consumption_other,\n )\n other_food = ProductionSubBranch.calc_sub_branch_by_energy(\n facts=facts,\n branch=\"other\",\n sub_branch=\"food\",\n energy_consumption_branch=energy_consumption_other,\n )\n other_further = ProductionSubBranchCO2viaFEC.calc_sub_branch(\n facts=facts,\n branch=\"other\",\n sub_branch=\"further\",\n energy_consumption_branch=energy_consumption_other,\n )\n other_2efgh = ExtraEmission.calc_extra_emission(\n facts=facts,\n branch=\"other\",\n sub_branch=\"2efgh\",\n energy_consumption=other_further.energy,\n )\n other = ProductionBranch.sum(\n sub_branch_list=[other_paper, other_food],\n sub_branch_via_FEC_list=[other_further],\n extra_emission_list=[other_2efgh],\n )\n\n total = ProductionSum.sum(miner, chem, metal, other)\n\n return Production(\n total=total,\n miner=miner,\n miner_cement=miner_cement,\n miner_chalk=miner_chalk,\n miner_glas=miner_glas,\n miner_ceram=miner_ceram,\n chem=chem,\n chem_basic=chem_basic,\n chem_ammonia=chem_ammonia,\n chem_other=chem_other,\n metal=metal,\n metal_steel=metal_steel,\n metal_steel_primary=metal_steel_primary,\n metal_steel_secondary=metal_steel_secondary,\n metal_nonfe=metal_nonfe,\n other=other,\n other_paper=other_paper,\n other_food=other_food,\n other_further=other_further,\n other_2efgh=other_2efgh,\n )\n","repo_name":"GermanZero-de/localzero-generator-core","sub_path":"src/climatevision/generator/industry2018/energy_demand/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15328,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"3813185639","text":"import numpy as np\n# import matplotlib.pyplot as plt\n\n\n###############################################################################\n# ES ##########################################################################\n###############################################################################\n\n\ndef selecao(x, fun, n):\n xnew = []\n x_sorted = sorted(x, key=fun)\n for i in range(n):\n xnew.append(x_sorted[i])\n return xnew\n\n\ndef recombinacao(x, fun, fun_penalizacao):\n xnew = []\n while len(xnew) < n:\n idxs = np.random.randint(0, n, 2)\n c = np.array([min(max((x[idxs[0]][i] + x[idxs[1]][i]) / 2, xmin[i]), xmax[i]) for i in range(len(x[idxs[0]]))])\n if fun_penalizacao(c) <= 0:\n xnew.append(c)\n elif (fun(c) < fun(x[idxs[0]])) or (fun_penalizacao(c) < fun_penalizacao(x[idxs[0]])):\n xnew.append(c)\n else:\n xnew.append(x[idxs[0]])\n return xnew\n\n\ndef mutacao(x, tau, step_size):\n xnew = []\n for idx in range(n):\n ps = np.random.random(len(x[idx]))\n sigmal = step_size*np.exp(tau*np.random.random(len(x[idx])))\n xnew.append(np.array([min(max(x[idx][i] + ps[i]*sigmal[i], xmin[i]), xmax[i]) for i in range(len(x[idx]))]))\n return xnew\n\n\ndef es(tau, step_size, mues, lambdaes, fun, fun_penalizacao):\n # inicializacao\n x = [np.random.random(len(xmin))*(xmax - xmin) + xmin for _ in range(n)]\n global_best = x[np.nanargmin([fun(x_i) for x_i in x])]\n\n # loop principal\n c = 1e9\n count = 0\n solutions = []\n color_plot = []\n\n while (c > eps) and (count < max_iter):\n x_children = recombinacao(x, fun, fun_penalizacao)\n x_children = mutacao(x_children, tau, step_size)\n x_mu = selecao(x, fun, int(n*mues))\n x_lambda = selecao(x_children, fun, max(n - int(n*mues), int(n*lambdaes)))\n x = x_mu + x_lambda\n f_x = [fun(x_i) for x_i in x]\n if np.isnan(f_x).all():\n break\n new_global_best = x[np.nanargmin(f_x)]\n c = sum(abs(new_global_best - global_best))\n global_best = new_global_best\n if fun_penalizacao(global_best) > 0:\n c = c + r\n solutions.append(fun(global_best))\n color_plot.append('red' if fun_penalizacao(global_best) > 0 else 'green')\n count = count + 1\n\n print(count, fun(global_best), fun_penalizacao(global_best) < eps, all(global_best >= xmin) and all(global_best <= xmax))\n\n # plt.scatter(range(count), solutions, c=color_plot)\n # plt.show()\n\n return (count, global_best, fun(global_best))\n\n\n###############################################################################\n# problema 1 ##################################################################\n###############################################################################\n\n# parametros\nn = 50\nxmin = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\nxmax = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1])\ntau = 0.15\nstep_size = 0.5\nmues = 1/7 # numero de pais selecionados\nlambdaes = 6/7 # numero de filhos gerados pelos pai\nr = 1000 # fator de penalizacao\neps = 1e-5\nmax_iter = 100000\n\n# penalizacao\ndef penalizacao1(x):\n phi1 = max(0, (2*x[0] + 2*x[1] + x[9] + x[10] - 10))\n phi2 = max(0, (2*x[0] + 2*x[2] + x[9] + x[11] - 10))\n phi3 = max(0, (2*x[1] + 2*x[2] + x[10] + x[11] - 10))\n phi4 = max(0, (-8*x[0] + x[9]))\n phi5 = max(0, (-8*x[1] + x[10]))\n phi6 = max(0, (-8*x[2] + x[11]))\n phi7 = max(0, (-2*x[3] - x[4] + x[9]))\n phi8 = max(0, (-2*x[5] - x[6] + x[10]))\n phi9 = max(0, (-2*x[7] - x[8] + x[11]))\n return r*(phi1*phi1 + phi2*phi2 + phi3*phi3 + phi4*phi4 + phi5*phi5 + phi6*phi6 + phi7*phi7 + phi8*phi8 + phi9*phi9)\n\n# funcao para minimizacao\ndef f1(x):\n return (5*x[0] + 5*x[1] + 5*x[2] + 5*x[3] +\n - 5*(x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3]) + \n - x[4]- x[5] - x[6] - x[7] - x[8]- x[9]- x[11] - x[12] +\n penalizacao1(x))\n\nbests = [es(tau, step_size, mues, lambdaes, f1, penalizacao1) for _ in range(30)]\nf_xs = [r[2] for r in bests]\nprint([np.min(f_xs), np.max(f_xs), np.mean(f_xs), np.std(f_xs), np.median(f_xs)])\nprint(np.mean([r[0] for r in bests]))\n\n\n###############################################################################\n# problema 2 ##################################################################\n###############################################################################\n\n\n# parametros\nn = 50\nxmin = np.array([-10, -10, -10, -10, -10, -10, -10])\nxmax = np.array([10, 10, 10, 10, 10, 10, 10])\ntau = 0.15\nstep_size = 0.5\nmues = 1/7 # numero de pais selecionados\nlambdaes = 6/7 # numero de filhos gerados pelos pai\nr = 1000 # fator de penalizacao\neps = 1e-5\nmax_iter = 100000\n\n# penalizacao\ndef penalizacao2(x):\n phi1 = max(0, -127 + 2*x[0]*x[0] + 3*x[1]*x[1]*x[1]*x[1] + x[2] + 4*x[3]*x[3] + 5*x[4])\n phi2 = max(0, -282 + 7*x[0] + 3*x[1] + 10*x[2]*x[2] + x[3] - x[4])\n phi3 = max(0, -196 + 23*x[0] + x[1]*x[1] + 6*x[5]*x[5] - 8*x[6])\n phi4 = max(0, 4*x[0]*x[0] + x[1]*x[1] - 3*x[0]*x[1] + 2*x[2]*x[2] + 5*x[5] - 11*x[6])\n return r*(phi1*phi1 + phi2*phi2 + phi3*phi3 + phi4*phi4)\n\n# funcao para minimizacao\ndef f2(x):\n return ((x[0] - 10)*(x[0] - 10) + 5*(x[1] - 12)*(x[1] - 12) + x[2]*x[2]*x[2]*x[2] +\n 3*(x[3] - 11)*x[3] - 11 + 10*x[5]*x[5]*x[5]*x[5]*x[5]*x[5] +\n 7*x[5]*x[5] + x[6]*x[6]*x[6]*x[6] - 4*x[5]*x[6] - 10*x[5] - 8*x[6] +\n penalizacao2(x))\n\nbests = [es(tau, step_size, mues, lambdaes, f2, penalizacao2) for _ in range(30)]\nf_xs = [r[2] for r in bests]\nprint([np.min(f_xs), np.max(f_xs), np.mean(f_xs), np.std(f_xs), np.median(f_xs)])\nprint(np.mean([r[0] for r in bests]))\n","repo_name":"leandrofturi/naturalComputing","sub_path":"es/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39162139777","text":"\"\"\"\nGiven two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.\n\nExample 1:\n\nInput: S = \"ab#c\", T = \"ad#c\"\nOutput: true\nExplanation: Both S and T become \"ac\".\nExample 2:\n\nInput: S = \"ab##\", T = \"c#d#\"\nOutput: true\nExplanation: Both S and T become \"\".\nExample 3:\n\nInput: S = \"a##c\", T = \"#a#c\"\nOutput: true\nExplanation: Both S and T become \"c\".\nExample 4:\n\nInput: S = \"a#c\", T = \"b\"\nOutput: false\nExplanation: S becomes \"c\" while T becomes \"b\".\nNote:\n\n1 <= S.length <= 200\n1 <= T.length <= 200\nS and T only contain lowercase letters and '#' characters.\nFollow up:\n\nCan you solve it in O(N) time and O(1) space?\n\n\"\"\"\nclass Solution(object):\n def backspaceCompare(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: bool\n \"\"\"\n def transform(s):\n r = []\n for c in s:\n if c == '#' and r:\n del r[-1]\n elif c == '#':\n pass\n else:\n r.append(c)\n return r\n\n # Simple solution\n # s = transform(S)\n # t = transform(T)\n # return s == t\n d1 = d2 = 0\n l1, l2 = len(S) - 1, len(T) - 1\n while l1 >= 0 or l2 >= 0:\n if l1 < 0:\n c1 = None\n else:\n c1 = S[l1]\n if c1 == '#':\n d1 += 1\n l1 -= 1\n c1 = None\n elif c1 != '#' and d1 > 0:\n d1 -= 1\n l1 -= 1\n c1 = None\n if l2 < 0:\n c2 = None\n else:\n c2 = T[l2]\n if c2 == '#':\n d2 += 1\n l2 -= 1\n c2 = None\n elif c2 != '#' and d2 > 0:\n d2 -= 1\n l2 -= 1\n c2 = None\n if c1 is not None and c2 is not None:\n if c1 != c2:\n return False\n else:\n l1 -= 1\n l2 -= 1\n elif (l1 < 0 and c2 is not None) or (l2 < 0 and c1 is not None):\n return False\n return True\n","repo_name":"franklingu/leetcode-solutions","sub_path":"questions/backspace-string-compare/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"30"} +{"seq_id":"33313711251","text":"\nfrom torch import nn, FloatTensor\nfrom .residual import ResidualStack\n\n\nclass Decoder(nn.Module):\n def __init__(self, in_ch: int, nh: int, res_ch: int, n_res_layers: int):\n super().__init__()\n self._layers = nn.Sequential(\n # Keep spatial dims unchanged\n nn.Conv2d(\n in_channels=in_ch,\n out_channels=nh,\n kernel_size=3, \n stride=1, \n padding=1),\n # Keep spatial dims unchanged\n ResidualStack(\n in_ch=nh,\n res_ch=res_ch,\n nlayers=n_res_layers),\n # Double spatial dim\n nn.ConvTranspose2d(\n in_channels=nh, \n out_channels=nh//2,\n kernel_size=4,\n stride=2, \n padding=1),\n nn.ReLU(),\n # Double Spatial dim\n nn.ConvTranspose2d(\n in_channels=nh//2, \n out_channels=1,\n kernel_size=4, \n stride=2, \n padding=1))\n\n def forward(self, x: FloatTensor) -> FloatTensor:\n return self._layers(x)\n","repo_name":"peternara/DALLE-2","sub_path":"modules/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"3046955674","text":"from rdkit import DataStructs as DataStructs\nfrom rdkit.Chem.Fingerprints import (\n FingerprintMols as FingerprintMols,\n MolSimilarity as MolSimilarity,\n)\nfrom rdkit.ML.Cluster import Murtagh as Murtagh\n\nmessage = FingerprintMols.message\nerror = FingerprintMols.error\n\ndef GetDistanceMatrix(data, metric, isSimilarity: int = ...): ...\ndef ClusterPoints(\n data,\n metric,\n algorithmId,\n haveLabels: bool = ...,\n haveActs: bool = ...,\n returnDistances: bool = ...,\n): ...\ndef ClusterFromDetails(details): ...\n\n_usageDoc: str\n","repo_name":"postera-ai/rdkit-stubs","sub_path":"rdkit-stubs/Chem/Fingerprints/ClusterMols.pyi","file_name":"ClusterMols.pyi","file_ext":"pyi","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"34306533758","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n#Consider quadratic Diophantine equations of the form:\n\n#x2 – Dy2 = 1\n\n#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.\n\n#It can be assumed that there are no solutions in positive integers when D is square.\n\n#By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:\n\n#32 – 2×22 = 1\n#22 – 3×12 = 1\n#92 – 5×42 = 1\n#52 – 6×22 = 1\n#82 – 7×32 = 1\n\n#Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.\n\n#Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.\n\n#Answer:\n\t#661\n\nfrom time import time; t=time()\n# http://zh.wikipedia.org/zh-cn/%E4%BD%A9%E5%B0%94%E6%96%B9%E7%A8%8B\n\nM = 1000\n\nmaxx = 0\nss = 0\nfor i in range(1, 31):\n nn = i*i\n for j in range(1, 2*i+1):\n n = nn + j\n if n > M: break\n p, q = i, j\n expan = [i]\n while True:\n r, s = 1, 0\n for k in expan:\n r, s = k*r+s, r\n if r*r - n*s*s == 1:\n if r > maxx:\n ss = n\n maxx = r\n break\n s = i + p\n k, p = s//q, s%q-i\n expan.insert(0, k)\n m = n - p*p\n assert m % q == 0\n p, q = -p, m//q\nprint(ss)#, time()-t\n","repo_name":"skydark/project-euler","sub_path":"066.py","file_name":"066.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"4219653015","text":"import sys\nfrom collections import deque\n\nsys.stdin = open(\"input.txt\", \"r\")\n\ndef bfs(a,b):\n\n global count\n\n queue = deque()\n\n ### 첫번째 노드 방문\n queue.append((a,b))\n board[a][b] = 0\n\n while queue:\n\n x, y = queue.popleft()\n\n for i in range(8):\n\n nx = x + dx[i]\n ny = y + dy[i]\n\n if 0<=nx next_start: # 멈추고 새로운 과제 시작\n rest = start+playtime - next_start\n stop.append((name, rest))\n break\n else: # 끝냈으면 다음 과제 시작하기 전까지 멈춘 과제 진행\n end.append(name)\n if not stop: # 멈춘 과제 없으면 다음 과제 시작까지 아무 일도 하지 않음\n break\n start = start+playtime\n name, playtime = stop.pop()\n end.append(plans[-1][0])\n while stop:\n end.append(stop.pop()[0])\n return end","repo_name":"hyh1016/programmers-with-python","sub_path":"python/level2/과제 진행하기.py","file_name":"과제 진행하기.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"71651657046","text":"\"\"\"\nDefine model's layers and the logic of the forward pass\n\"\"\"\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ConvNet(nn.Module):\n def __init__(self, num_classes=2):\n super(ConvNet, self).__init__()\n # input 3x128x64\n self.layer1 = nn.Sequential(\n nn.Conv2d(3, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.MaxPool2d(kernel_size=2, stride=2)) # 16x64x32\n self.layer2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.MaxPool2d(kernel_size=2, stride=2)) # 32x16x32\n self.layer3 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(64),\n nn.MaxPool2d(kernel_size=2, stride=2)) # 64x16x8\n self.layer4 = nn.Sequential(\n nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n nn.MaxPool2d(kernel_size=2, stride=2)) # 128x8x4\n self.fc1 = nn.Linear(8*4*128, 256) # 256\n self.fc2 = nn.Linear(256, num_classes) # 2\n\n def forward(self, x):\n conv0 = self.layer1(x)\n conv1 = self.layer2(conv0)\n conv2 = self.layer3(conv1)\n conv3 = self.layer4(conv2)\n conv3_flattened = conv3.view(-1, 8*4*128)\n out1 = F.relu(self.fc1(conv3_flattened))\n out2 = self.fc2(out1)\n\n # return output of all layers for visualization purpose\n return conv0, conv1, conv2, conv3, out1, out2\n\n\n","repo_name":"DanieleAngioni97/AI_Project","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21774229953","text":"from Weaponry import Weapons\nfrom AWP import Awp\n\n\n\nnama_senjata = []\ndamage_senjata = []\nrof_senjata = []\n\nfor index in range(2):\n input_nama = input(\"Input nama senjata: \")\n input_damage = input(\"Input nama damage: \")\n input_rof = input(\"Input nama rof: \")\n\n nama_senjata.append(input_nama)\n damage_senjata.append(input_damage)\n rof_senjata.append(input_rof)\n name = nama_senjata[index]\n damage = damage_senjata[index]\n rof = rof_senjata[index]\n\n senjata = Weapons(name, damage, rof)\n print(senjata.name)\n print(senjata.damage)\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# ak47 = Weapons()\n# ak47.name = \"AK-47\"\n# ak47.damage = 33\n# ak47.rof = 4 \n# ak47.scoping(has_scope = True)\n\n# uzi = Weapons\n# uzi.name = \"Uzi\"\n# uzi.damage = 17\n# uzi.rof = 7 \n\n# print(ak47.scoping())\n\n# awp = Awp()\n# print(awp.name)\n# print(awp.damage)\n# print(awp.rof)\n# print(awp.scoping(has_scope = True))\n","repo_name":"grilhami/Attar-Git-Practice","sub_path":"handzdirty/Kelas/csgo.py","file_name":"csgo.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13158504270","text":"from collections import deque\nINF = int(1e9)\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\n\n\ndef bfs(board, costs, x, y):\n q = deque()\n q.append((x, y))\n costs[x][y] = 1\n while q:\n x, y = q.popleft()\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n if 0 <= nx < n and 0 <= ny < n:\n if costs[nx][ny] == 0 or costs[nx][ny] > costs[x][y]+board[nx][ny]:\n q.append((nx, ny))\n costs[nx][ny] = costs[x][y]+board[nx][ny]\n\n\nif __name__ == '__main__':\n n = int(input())\n costs = [[INF]*(n) for i in range(n)]\n board = [list(map(int, list(input()))) for i in range(n)]\n for i in range(n):\n for j in range(n):\n board[i][j] = abs(board[i][j]-1)\n bfs(board, costs, 0, 0)\n\n print(costs[-1][-1]-1)\n","repo_name":"artdumb/CodingTestPrac","sub_path":"BAEKJOON/기출,실전대비/(bfs)2665-미로만들기.py","file_name":"(bfs)2665-미로만들기.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"40729554358","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom tkinter.ttk import Combobox\nfrom tkinter import Canvas\nfrom tkinter import ttk\nfrom tkinter import Label\nfrom tkinter import Button\nfrom tkinter import messagebox\nfrom tkinter import Entry\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegression\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\n\n\n#reading dataset\n\n\ndata = pd.read_csv('/Users/YAĞMUR/Downloads/heart.csv') # her kullanıcı kendi pathini koymalı\n\n\n#/Users/YAĞMUR/Downloads/heart.csv\n#/kaggle/input/heart-disease-uci/heart.csv\n\n\ndata.head() #1=male 0=female\ndata.shape\ndata.info()\n\n#YAĞMUR\nprint(\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n\\n\")\nprint('Statistical Measurements\\n')\n\npd.set_option(\"display.float\", \"{:.2f}\".format)\ndata.describe() #statistical measurements\n\n\n#missing value check\ndata.isnull().sum()\n\n\n\n\nwindow = tk.Tk()\n\nwindow.title(\"Heart Disease Prediction System\")\nwindow.configure(background='#F0F8FF')\nwindow.geometry(\"1700x900\")\n\n\ndef successMessage():\n messagebox.showinfo(title=\"Result\", message=\"No Risk! \\n\"\n )\n\ndef warningMessage():\n messagebox.showwarning(title=\"Result\", message=\"There is a risk!\"\n )\n\n\n\n\ndef predictionWindow():\n\n\n\n # Splitting to Features And Target\n\n X = data.drop(columns='target', axis=1)\n y = data['target']\n\n print(X) # target kolonun yok olduğunu gördük\n print(y) # targetı tek aldık\n\n\n # Splitting train and test data in dataset\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2, stratify=y)\n print(X.shape, X_train.shape, X_test.shape) # testsize kısmında verdiğimiz değerle oluşuyor\n\n # Model Traning\n\n\n \"\"\"\"\"\n #Decision Tree Accuracy: 0.6923076923076923\n from sklearn import tree\n dt_clf = tree.DecisionTreeClassifier(max_depth=5)\n dt_clf.fit(X_train, y_train)\n\n dt_clf.score(X_test, y_test)\n\n y_predict = dt_clf.predict(X_test)\n a = dt_clf.score(X_test, y_test)\n print('Testing Data Accuracy: ', (a * 100), '%') \n\n \"\"\"\n #Model training\n\n\n \"\"\"\"\"\n #Random Forest 0.8241758241758241\n from sklearn import ensemble\n rf_clf = ensemble.RandomForestClassifier(n_estimators=100)\n rf_clf.fit(X_train, y_train) # columnlarla target arası ilişkiyi kuruyor\n b= rf_clf.score(X_test, y_test)\n print('Testing Data Accuracy: ', (b * 100), '%')\n\n \"\"\"\"\"\n\n\n\n \"\"\"\"\"\n # logistic regression\n\n model = LogisticRegression()\n model.fit(X_train, y_train) \n\n X_train_predict = model.predict(X_train)\n accuracyOfTrainingData = accuracy_score(X_train_predict, y_train)\n print('Training Data Accuracy: ', (accuracyOfTrainingData * 100), '%')\n\n X_test_predict = model.predict(X_test)\n accuracyOfTestingData = accuracy_score(X_test_predict, y_test)\n\n print('Testing Data Accuracy: ', (accuracyOfTestingData * 100), '%')\n \"\"\"\n\n\n\n\n from sklearn.svm import SVC\n model = SVC(probability=True, kernel='linear')\n model.fit(X_train, y_train)\n\n c = model.score(X_train, y_train)\n d = model.score(X_test, y_test)\n print('Training Data Accuracy : ', (c * 100), '%')\n print('Testing Data Accuracy : ', (d * 100), '%')\n\n\n\n\n def get_birth():\n\n value=int(age_get.get())\n date=2022\n birthyear = (date - value)\n return birthyear\n\n\n def sexEdit():\n global sex\n sex_value=sex_get.get()\n if(sex_value == \"Female\"):\n sex=1\n elif(sex_value == \"Male\"):\n sex=0\n print(sex)\n\n def chestPainEdit():\n global cptype\n value = cpt_get.get()\n if(value == \"Typical angina\"):\n cptype=0\n elif(value == \"Atypical angina\" ):\n cptype=1\n elif(value == \"Non-anginal pain\"):\n cptype=2\n elif(value== \"Asymptomatic\"):\n cptype=3\n\n\n print(cptype)\n\n def trestEdit():\n\n trestbps= int(trest_get.get()) #return olarak döndürsek alırız\n\n return trestbps\n\n def fbsEdit():\n global fbs\n value= fbs_get.get()\n if(value== \"fasting blood sugar > 120 mg/dl\"):\n fbs= 1\n elif(value== \"fasting blood sugar < 120 mg/dl\" ):\n fbs=0\n print(fbs)\n\n\n def cholEdit():\n\n chol = int(chol_get.get())\n\n return chol\n\n def restecgEdit():\n global restecg\n value = ecg_get.get()\n if(value== \"Nothing to note\"):\n restecg=0\n elif(value== \"ST-T Wave abnormality\"):\n restecg =1\n elif(value== \"Definite left ventricular hypertrophy\" ):\n restecg= 2\n print(restecg)\n\n def thalachEdit():\n\n thalach= int(tha_get.get())\n return thalach\n\n def exangEdit():\n global exang\n value = ex_get.get()\n if(value == \"Yes\"):\n exang = 1\n elif(value == \"No\"):\n exang =0\n print(exang)\n\n\n\n def oldpeakEdit():\n\n oldpeak = float(oldpeak_get.get())\n return oldpeak\n\n def slopeEdit():\n global slope\n value = slope_get.get()\n if(value == \"Upsloping: better heart rate with excercise\"):\n slope = 0\n elif(value == \"Flatsloping: minimal change\" ):\n slope =1\n elif(value== \"Downslopins: signs of unhealthy heart\"):\n slope =2\n\n print(slope)\n\n\n def thalEdit():\n global thal\n value = thal_get.get()\n if(value == \"Normal\"):\n thal = 0\n elif(value== \"Fixed Defect\"):\n thal =1\n elif(value == \"Reversable Defect\"):\n thal =2\n\n print(thal)\n\n\n\n def caEdit():\n global ca\n value = ca_get.get()\n if (value == \"0\"):\n ca=0\n elif(value == \"1\"):\n ca=1\n elif(value == \"2\"):\n ca=2\n elif(value == \"3\"):\n ca=3\n print(ca)\n\n\n def resultWindow():\n\n a =get_birth()\n c= trestEdit()\n d= cholEdit()\n e =thalachEdit()\n f =oldpeakEdit()\n\n inputVariable = (a,sex,cptype,c,d,fbs,restecg,e,exang,f,slope,ca,thal) # biz bunu kullanıcıdan alıcaz\n #a,sex,b,c,d,fbs,restecg,e,exang,f,slope,ca,thal\n # change the input array to the numpy array\n inputNumpyArray = np.asarray(inputVariable)\n\n inputArrayReshape = inputNumpyArray.reshape(1, -1)\n\n prediction = model.predict(inputArrayReshape)\n\n print(\"Prediction result: \", prediction)\n\n #IŞIK\n\n if(prediction == [0]):\n successMessage()\n elif(prediction== [1]):\n warningMessage()\n\n\n\n\n\n\n\n\n\n preWindow = tk.Tk()\n preWindow.title(\"Prediction Of Heart Disease Risk\")\n preWindow.configure(background='#F0F8FF')\n preWindow.geometry(\"1700x900\")\n\n t_label = Label(preWindow, text=\"Prediction Of Heart Disease Risk\", font=\"helvetica 30\", borderwidth=20)\n t_label.place(x=20, y=20)\n t2_label = Label(preWindow, text=\"Please enter the patient information and press choose buttons\", font=\"helvetica 15\", borderwidth=10)\n t2_label.place(x=20, y=100)\n\n age_label = Label(preWindow, text=\"Enter birth year\", font=\"helvetica 12\", borderwidth=6)\n age_label.place(x=80, y=200)\n age_get = Entry(preWindow, width=10)\n age_get.place(x=80, y=250)\n\n\n sex_label = Label(preWindow, text=\"Enter Sex\", font=\"helvetica 12\", borderwidth=6)\n sex_label.place(x=250, y=200)\n\n sex_array =[\"Female\", \"Male\"]\n sex_get = Combobox(preWindow, values=sex_array)\n sex_get.place(x=250, y=250)\n\n sex_button= Button(preWindow, text=\"Choose\", command=sexEdit, font=\"helvetica 12\", borderwidth=3)\n sex_button.place(x=400, y=250)\n\n\n\n cpt_label = Label(preWindow, text=\"Choose chest pain type\"\n , font=\"helvetica 12\", borderwidth=6)\n cpt_label.place(x=500, y=200)\n\n cpt_array = [\"Typical angina\", \"Atypical angina\",\n \"Non-anginal pain\", \"Asymptomatic\"]\n cpt_get = Combobox(preWindow, values=cpt_array )\n cpt_get.place(x=500, y=250)\n\n cpt_button = Button(preWindow, text=\"Choose\", command=chestPainEdit, font=\"helvetica 12\", borderwidth=6)\n cpt_button.place(x=650, y=250)\n\n\n ###trestbps\n trest_label = Label(preWindow, text=\"Enter resting blood pressure (in mm Hg)\", font=\"helvetica 12\", borderwidth=6)\n trest_label.place(x=750, y=200)\n trest_get = Entry(preWindow, width=10)\n trest_get.place(x=750, y=250)\n\n\n\n ###fbs\n\n fbs_label = Label(preWindow, text=\"Enter fasting blood sugar\", font=\"helvetica 12\", borderwidth=6)\n fbs_label.place(x=1100, y=200)\n\n fbs_array = [\"fasting blood sugar > 120 mg/dl\", \"fasting blood sugar < 120 mg/dl\"]\n fbs_get = Combobox(preWindow, values=fbs_array, width=28)\n fbs_get.place(x=1100, y=250)\n\n fbs_button = Button(preWindow, text=\"Choose\", command=fbsEdit, font=\"helvetica 12\", borderwidth=3)\n fbs_button.place(x=1300, y=250)\n\n #### chol\n chol_label = Label(preWindow, text=\"Enter serum cholestoral\\n(in mg/dl\", font=\"helvetica 12\",\n borderwidth=6)\n chol_label.place(x=80, y=350)\n chol_get = Entry(preWindow, width=10)\n chol_get.place(x=80, y=400)\n\n ##### restecg\n\n ecg_label = Label(preWindow, text=\"Enter resting electrocardiographic results\", font=\"helvetica 12\", borderwidth=6)\n ecg_label.place(x=300, y=350)\n\n ecg_array = [\"Nothing to note\", \"ST-T Wave abnormality\", \"Definite left ventricular hypertrophy\"]\n ecg_get = Combobox(preWindow, values=ecg_array, width=30)\n ecg_get.place(x=300, y=400)\n\n ecg_button = Button(preWindow, text=\"Choose\", command=restecgEdit, font=\"helvetica 12\", borderwidth=3)\n ecg_button.place(x=530, y=400)\n\n ##thalach\n\n tha_label = Label(preWindow, text=\"Enter maximum heart rate achieved\", font=\"helvetica 12\",\n borderwidth=6)\n tha_label.place(x=650, y=350)\n tha_get = Entry(preWindow, width=10)\n tha_get.place(x=650, y=400)\n\n\n ##exang\n\n ex_label = Label(preWindow, text=\"Enter exercise induced angina\\n(yes;no)\", font=\"helvetica 12\", borderwidth=6)\n ex_label.place(x=950, y=350)\n\n ex_array = [\"Yes\", \"No\"]\n ex_get = Combobox(preWindow, values=ex_array)\n ex_get.place(x=950, y=400)\n\n ex_button = Button(preWindow, text=\"Choose\", command=exangEdit, font=\"helvetica 12\", borderwidth=3)\n ex_button.place(x=1100, y=400)\n\n\n ###oldpeak\n\n oldpeak_label = Label(preWindow, text=\"Enter ST depression induced by exercise\\nrelative to rest\\n(Ex:3.1)\", font=\"helvetica 12\",\n borderwidth=6)\n oldpeak_label.place(x=1200, y=350)\n oldpeak_get = Entry(preWindow, width=10)\n oldpeak_get.place(x=1200, y=400)\n\n\n ##slope\n\n slope_label = Label(preWindow, text=\"Enter the slope of the peak exercise ST segment\", font=\"helvetica 12\", borderwidth=6)\n slope_label.place(x=80, y=500)\n\n slope_array = [\"Upsloping: better heart rate with excercise\", \"Flatsloping: minimal change\", \"Downslopins: signs of unhealthy heart\"]\n slope_get = Combobox(preWindow, values=slope_array, width=35)\n slope_get.place(x=80, y=550)\n\n slope_button = Button(preWindow, text=\"Choose\", command=slopeEdit, font=\"helvetica 12\", borderwidth=3)\n slope_button.place(x=330, y=550)\n\n\n\n ##ca\n\n ca_label = Label(preWindow, text=\"Enter number of major vessels (0-3) colored by flourosopy\\n\"\n \"Note: The more blood movement the better \", font=\"helvetica 12\",\n borderwidth=6)\n ca_label.place(x=450, y=500)\n\n ca_array = [\"0\", \"1\", \"2\", \"3\"]\n ca_get = Combobox(preWindow, values=ca_array)\n ca_get.place(x=450, y=550)\n\n ca_button = Button(preWindow, text=\"Choose\", command=caEdit, font=\"helvetica 12\", borderwidth=3)\n ca_button.place(x=600, y=550)\n\n\n ###thal\n\n thal_label = Label(preWindow, text=\"Enter thalium stress result\", font=\"helvetica 12\", borderwidth=6)\n thal_label.place(x=900, y=500)\n\n thal_array = [\"Normal\", \"Fixed Defect\", \"Reversable Defect\"]\n thal_get = Combobox(preWindow, values=thal_array)\n thal_get.place(x=900, y=550)\n\n thal_button = Button(preWindow, text=\"Choose\", command=thalEdit, font=\"helvetica 12\", borderwidth=3)\n thal_button.place(x=1050, y=550)\n\n\n ##calculation button\n\n calculation_button = Button(preWindow, text=\"Predict the risk of Heart Disease\", command=resultWindow, font=\"helvetica 12\", borderwidth=10)\n calculation_button.place(x=650, y=650)\n\n\n\n\n\n\n\n##ana window\n\n#IŞIK\ntitle_label = Label(window, text=\"Anticipate The Risk Of Heart Disease\", font=\"helvetica 30\", borderwidth=20, padx=400, pady=20, background= \"#E0EEEE\" )\ntitle_label.place(x=20, y=20)\ntitle2_label = Label(window, text=\"Welcome to the YIZApp\\n\\n\\n\"\n \"Health Comes First\", font=\"helvetica 15\", borderwidth=15, padx=400, pady=20, background= \"#E0EEEE\" )\ntitle2_label.place(x=200, y=120)\n\n\n\nprediction_label = Label(text=\"Hit the Prediction Button to Find Out Heart Disease Risk\", font =\"helvetica 20\", borderwidth=20)\nprediction_label.place(x=400, y=300)\nprediction_button = Button(window, text=\"Prediction\", command=predictionWindow, font=\"helvetica 15\", borderwidth=6)\nprediction_button.place(x=700, y=400)\n\n\nwindow.mainloop()\n\n","repo_name":"ygmra/Heart-Disease-Prediction-App","sub_path":"heart_disease_project/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":13460,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"5903845796","text":"import graphene\nfrom graphene import relay, ObjectType\nfrom graphql_auth.bases import Output\n\nfrom django.utils.translation import gettext_lazy as _\n\nfrom api.helper import send_user_request_email\nfrom db.forms import UserRequestForm\nfrom db.models import UserRequest as UserRequestModel\n\n# pylint: disable=W0221\n\n\nclass UserRequest(Output, relay.ClientIDMutation):\n\n class Input:\n name = graphene.String(description=_('Name'), required=True)\n email = graphene.String(description=_('E-Mail'), required=True)\n message = graphene.String(description=_('Message'), required=True)\n\n class Meta:\n description = _('Creates a new user user request')\n\n @classmethod\n def mutate(cls, root, info, **form_data):\n errors = {}\n user_request_data = form_data.pop('input')\n user_request = None\n\n user_request_form = UserRequestForm(user_request_data)\n user_request_form.full_clean()\n\n if user_request_form.is_valid():\n user_request = UserRequestModel(**user_request_data)\n user_request.save()\n send_user_request_email(user_request, info.context)\n else:\n errors.update(user_request_form.errors.get_json_data())\n\n return UserRequest(success=not errors, errors=errors)\n\n\nclass UserRequestMutation(ObjectType):\n user_request = UserRequest.Field()\n","repo_name":"matchd-ch/matchd-backend","sub_path":"api/schema/user_request/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"15771621223","text":"import sys\nimport os\n\nenabled=False\ndef gui_test():\n\tglobal enabled\n\tfor arg in sys.argv:\n\t\tif arg.startswith(\"--\") and arg!=\"--load\":\n\t\t\tenabled=False\n\t\t\treturn\n\n\ttry:\n\t\tfrom PyQt5.QtWidgets import QWidget\n\t\tenabled=True\n\texcept:\n\t\tenabled=False\n\t\tpass\n\t\n\t\ndef set_gui(value):\n\tglobal enabled\n\tenabled=value\n\t\ndef gui_get():\n\tglobal enabled\n\treturn enabled\n\nclass QWidget():\n\tdef __init__(self):\n\t\treturn\n","repo_name":"roderickmackenzie/gpvdm","sub_path":"gpvdm_gui/gui/gui_enable.py","file_name":"gui_enable.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"30"} +{"seq_id":"38853489089","text":"import os\nfrom tqdm import tqdm\nimport pandas as pd\nimport shutil\nimport toloka.client as toloka\nimport psycopg2\n\n# YANDEX TOLOKA CREDENTIALS\nURL_API = \"https://toloka.yandex.ru/api/v1/\"\nOAUTH_TOKEN = 'OAUTH_TOKEN'\nHEADERS = {\"Authorization\": \"OAuth %s\" % OAUTH_TOKEN, \"Content-Type\": \"application/JSON\"}\ntoloka_client = toloka.TolokaClient(OAUTH_TOKEN, 'PRODUCTION')\n\n# DB CONNECT AND PUT ALL DATA TO DF\nconn = psycopg2.connect(\"\"\"\n host=host\n port=port\n sslmode=require\n dbname=dbname\n user=user\n password=password\n target_session_attrs=read-write\n\"\"\")\n\nq = conn.cursor()\n\nq.execute('''SELECT assignment_id, worker_id, assignment_nation, assignment_month,\n assignment_send_date, assignment_toloka_date, toloka_status,\n reward, account, pool_type, innodata_decision, reject_reason,\n hashes, gender FROM public.sets ''')\nall_sets_in_db_df = pd.DataFrame(q.fetchall(), columns = ['assignment_id', 'worker_id', 'assignment_nation', 'assignment_month', 'assignment_send_date', 'assignment_toloka_date', 'toloka_status', 'reward', 'account', 'pool_type', 'innodata_decision', 'reject_reason', 'hashes', 'gender'])\n\n# GET DATE AND MONTH FROM TABLE FILE NAME\nfor file in os.listdir('descriptors/credentials/table'):\n if 'db_sets_for' in file:\n daily_df = pd.read_excel(f'descriptors/credentials/table/{file}', sheet_name='Sheet1')\n date = file.split('_')[4].replace('.xlsx', '')\n month = file.split('_')[3]\n\nprint(daily_df)\n\npool_id_1 = 1\nassignment_id_1 = 1\n\nfull_df = pd.DataFrame()\n\n# GETTING ALL SET DATA FROM YANDEX TOLOKA TO DF\nfor assignment_id in daily_df['assignment_id']:\n try:\n print(assignment_id)\n account = 'account1'\n assignment_nation = daily_df[daily_df['assignment_id']==assignment_id]['ethnicity'].values[0]\n assignment_gender = daily_df[daily_df['assignment_id']==assignment_id]['gender'].values[0]\n assignment_hashes = daily_df[daily_df['assignment_id']==assignment_id]['hashes'].values[0]\n assignment_month = month\n assignment_send_date = date\n if assignment_id != assignment_id_1:\n if '--' in assignment_id:\n print('Getting data')\n assignment_request = toloka_client.get_assignment(assignment_id=assignment_id)\n pool_id = assignment_request.pool_id\n if pool_id_1 != pool_id:\n df_toloka = toloka_client.get_assignments_df(pool_id, status=['APPROVED', 'SUBMITTED', 'REJECTED'])\n pool_id_1 = pool_id\n assignment_toloka_date = df_toloka[df_toloka['ASSIGNMENT:assignment_id'] == assignment_id]['ASSIGNMENT:started'].values[0].split('T')[0]\n worker_id = df_toloka[df_toloka['ASSIGNMENT:assignment_id'] == assignment_id]['ASSIGNMENT:worker_id'].values[0]\n toloka_status = df_toloka[df_toloka['ASSIGNMENT:assignment_id'] == assignment_id]['ASSIGNMENT:status'].values[0]\n reward = assignment_request.reward\n pool_data = toloka_client.get_pool(pool_id=assignment_request.pool_id)\n pool_name = pool_data.private_name\n if 'new' in pool_name.lower() and not 'retry' in pool_name.lower() and not 'родствен' in pool_name.lower():\n pool_type = 'new'\n elif 'retry' in pool_name.lower():\n pool_type = 'retry'\n elif 'родствен' in pool_name.lower():\n pool_type = 'родственники'\n else:\n pool_type = None\n else:\n assignment_toloka_date = 'inhouse'\n worker_id = 'inhouse'\n toloka_status = 'inhouse'\n reward = 'inhouse'\n account = 'inhouse'\n pool_type = 'inhouse'\n innodata_decision = 'IN WORK'\n reject_reason = None\n data = {'assignment_id':[assignment_id], 'worker_id':[worker_id], 'assignment_nation':[assignment_nation], 'assignment_month':[assignment_month], 'assignment_send_date':[assignment_send_date], 'assignment_toloka_date':[assignment_toloka_date], 'toloka_status':[toloka_status], 'reward':[reward], 'account':[account], 'pool_type':[pool_type], 'innodata_decision':[innodata_decision], 'reject_reason':[reject_reason], 'hashes':[assignment_hashes], 'gender':[assignment_gender]}\n df = pd.DataFrame(data=data)\n full_df = pd.concat([full_df, df])\n assignment_id_1 = assignment_id\n else:\n pass\n# IF EXCEPTION - CHANGE ACCOUNT TO ANOTHER AND TRY AGAIN\n except Exception as e:\n if 'DoesNotExistApiError' in str(e):\n print('Change account')\n if OAUTH_TOKEN == 'OAUTH_TOKEN1':\n OAUTH_TOKEN = 'OAUTH_TOKEN2'\n account = 'account2'\n elif OAUTH_TOKEN == 'OAUTH_TOKEN2':\n OAUTH_TOKEN = 'OAUTH_TOKEN1'\n account = 'account1'\n HEADERS = {\"Authorization\": \"OAuth %s\" % OAUTH_TOKEN, \"Content-Type\": \"application/JSON\"}\n toloka_client = toloka.TolokaClient(OAUTH_TOKEN, 'PRODUCTION')\n else:\n print(e)\n\ndf = full_df\n\nq = conn.cursor()\n\n# PUT ALL DATA FROM OUR DF TO DB\nfor i in tqdm(df['assignment_id']):\n worker_id = str(df[df['assignment_id']==i]['worker_id'].values[0])\n assignment_nation = str(df[df['assignment_id']==i]['assignment_nation'].values[0])\n assignment_month = str(df[df['assignment_id']==i]['assignment_month'].values[0])\n assignment_send_date = str(df[df['assignment_id']==i]['assignment_send_date'].values[0])\n assignment_toloka_date = str(df[df['assignment_id']==i]['assignment_toloka_date'].values[0])\n innodata_decision = str(df[df['assignment_id']==i]['innodata_decision'].values[0])\n reject_reason = str(df[df['assignment_id']==i]['reject_reason'].values[0])\n toloka_status = str(df[df['assignment_id']==i]['toloka_status'].values[0])\n reward = str(df[df['assignment_id']==i]['reward'].values[0])\n account = str(df[df['assignment_id']==i]['account'].values[0])\n pool_type = str(df[df['assignment_id']==i]['pool_type'].values[0])\n hashes = str(df[df['assignment_id']==i]['hashes'].values[0])\n gender = str(df[df['assignment_id']==i]['gender'].values[0])\n # descriptor = str(df[df['assignment_id']==i]['descriptor'].values[0])\n print(f'{i}, {worker_id}, {assignment_nation}, {assignment_month}, {assignment_send_date}, {assignment_toloka_date}, {innodata_decision}, {reject_reason}')\n try:\n if i in all_sets_in_db_df['assignment_id'].unique():\n q.execute(f\"UPDATE public.sets SET worker_id = '{worker_id}', assignment_nation = '{assignment_nation}', assignment_month = '{assignment_month}', assignment_send_date = '{assignment_send_date}', assignment_toloka_date = '{assignment_toloka_date}', toloka_status = '{toloka_status}', reward = '{reward}', account = '{account}', pool_type = '{pool_type}', innodata_decision = '{innodata_decision}', reject_reason = '{reject_reason}', hashes = '{hashes}', gender = '{gender}' WHERE assignment_id = '{i}';\")\n print('Update set in DB')\n else:\n q.execute(f\"INSERT INTO public.sets (assignment_id, worker_id, assignment_nation, assignment_month, assignment_send_date, assignment_toloka_date, toloka_status, reward, account, pool_type, innodata_decision, reject_reason, hashes, gender) VALUES ('{i}', '{worker_id}', '{assignment_nation}', '{assignment_month}', '{assignment_send_date}', '{assignment_toloka_date}', '{toloka_status}', '{reward}', '{account}', '{pool_type}', '{innodata_decision}', '{reject_reason}', '{hashes}', '{gender}');\")\n print('Add set to DB')\n except Exception as e:\n print(e)\n pass\nconn.commit()\n\nconn.close()\n\n# MOVING ALL FILES TO STORAGE IF OK\nfinish = input('All right? ')\ndestination_path = 'destination_path'\n\nif finish == '+':\n for root, subdirectories, files in os.walk('.\\\\descriptors\\\\credentials\\\\table'):\n for subdirectory in subdirectories:\n pass\n for file in files:\n try:\n shutil.move(os.path.join(root, file), destination_path)\n except:\n pass","repo_name":"karturik/photo_dublicats_checker","sub_path":"db_data__insert.py","file_name":"db_data__insert.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4437047982","text":"import time\nimport random\nimport numpy as np\n\n\nclass MazeSolver:\n def __init__(self, application):\n self.maze_app = application\n self.path = []\n self.temperature = 0.9\n\n def initialize_start_state(self, n, m, maze, start, end):\n init_state = [[0 for i in range(n)] for j in range(m)]\n for i in range(n):\n for j in range(m):\n if i == start[0] and j == start[1]:\n init_state[i][j] = 's'\n elif i == end[0] and j == end[1]:\n init_state[i][j] = 'f'\n else:\n init_state[i][j] = int(maze[i][j])\n return init_state\n\n def is_final_state(self, state, position):\n for i in range(len(state)):\n for j in range(len(state[0])):\n if state[position[0]][position[1]] == 'f':\n return True\n return False\n\n def is_valid_transition(self, state, position):\n n = len(state)\n m = len(state[0])\n if position[0] > n or position[0] < 0 or position[1] > m or position[1] < 0:\n return False\n if state[position[0]][position[1]] == 1:\n return False\n return True\n\n def update_ui(self, position, color):\n self.maze_app.draw(position[0], position[1], color)\n time.sleep(0.1)\n self.maze_app.window.update()\n\n def new_transition(self, state, position, color):\n state[position[0]][position[1]] = 'r'\n self.update_ui(position, color)\n return state\n\n def get_neighbours(self,position):\n up = [position[0] + 1, position[1]]\n down = [position[0] - 1, position[1]]\n left = [position[0], position[1] - 1]\n right = [position[0], position[1] + 1]\n return [up, down, left, right]\n\n def backtracking_solve_maze(self, state, position):\n if not self.is_valid_transition(state, position) or state[position[0]][position[1]] == 'r':\n return False\n if self.is_final_state(state, position):\n state[position[0]][position[1]] = 'r'\n self.path.append(position)\n self.new_transition(state, position, \"blue\")\n return self.path\n if self.is_valid_transition(state, position):\n state = self.new_transition(state, position, \"blue\")\n self.path.append(position)\n for neigh in self.get_neighbours(position):\n if self.backtracking_solve_maze(state, neigh):\n return self.path\n self.path.pop()\n return False\n\n def get_adjacents(self,state, position):\n final = list()\n for i in self.get_neighbours(position):\n if self.is_valid_transition(state, i) and state[i[0]][i[1]] != 'r':\n final.append(i)\n return final\n\n def bfs_solve_maze(self, state, start):\n queue = [start]\n while len(queue) != 0:\n if queue[0] == start:\n path = [queue.pop(0)]\n else:\n path = queue.pop(0)\n position = path[-1]\n if self.is_final_state(state, position):\n self.new_transition(state, position, \"green\")\n return path\n elif state[position[0]][position[1]] != 'r':\n for i in self.get_adjacents(state, position):\n newPath = list(path)\n newPath.append(i)\n queue.append(newPath)\n self.new_transition(state, position, \"green\")\n return False\n\n def hillclimbing_solve_maze(self, state, start, end):\n random.seed(25)\n current_position = start\n self.new_transition(state, start, \"orange\")\n path = [current_position]\n while not self.is_final_state(state, current_position):\n prev_state = current_position\n neighbours = self.get_neighbours(current_position)\n random.shuffle(neighbours)\n for neighbour in neighbours:\n if self.is_valid_transition(state, neighbour):\n if self.is_final_state(state, neighbour):\n path.append(neighbour)\n self.new_transition(state, neighbour, \"orange\")\n return path\n if self.is_better(neighbour, current_position, end):\n current_position = neighbour\n break\n if current_position == prev_state:\n return False\n self.new_transition(state, current_position, \"orange\")\n path.append(current_position)\n return path\n\n def value(self, state, end):\n return abs(end[0] - state[0]) + abs(end[1] - state[1])\n\n def is_better(self, s1, s2, end):\n val1 = self.value(s1, end)\n val2 = self.value(s2, end)\n if val1 == val2:\n return s1[0] > s2[0]\n return val1 < val2\n\n def update_temperature(self):\n self.temperature = self.temperature - 0.01\n\n def simulated_solve_maze(self, state, start, end):\n self.temperature = 0.9\n current_position = start\n self.new_transition(state, start, \"pink\")\n path = [current_position]\n while not self.is_final_state(state, current_position):\n prev_state = current_position\n for neighbour in self.get_neighbours(current_position):\n if self.is_valid_transition(state, neighbour):\n if self.is_final_state(state, neighbour):\n path.append(neighbour)\n self.new_transition(state, neighbour, \"pink\")\n return path\n if self.is_better(neighbour, current_position, end):\n current_position = neighbour\n break\n elif random.uniform(0, 1) < np.exp(-abs(self.value(current_position, end) - self.value(neighbour, end)) / self.temperature):\n current_position = neighbour\n self.update_temperature()\n print(self.temperature)\n break\n if current_position == prev_state:\n return False\n self.new_transition(state, current_position, \"pink\")\n path.append(current_position)\n return path","repo_name":"StativaCamelia/InteligentaArticifiala","sub_path":"Tema1/MazeSolver.py","file_name":"MazeSolver.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31825388047","text":"#!/usr/bin/env python\n\nfrom ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter\nfrom ATK.Adaptive import DoubleRLSFilter\n\nfrom scipy.signal import butter, lfilter\n\nfs = 48000\n\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = butter(order, [low, high], btype='band')\n return b, a\n\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n y = lfilter(b, a, data)\n return y\n \nclass Filter:\n def __init__(self):\n self.rls = DoubleRLSFilter(5)\n self.rls.input_sampling_rate = fs\n self.rls.memory = 0.999\n\n def learn(self, input):\n self.rls.learning = True\n \n import numpy as np\n output = np.zeros(input.shape, dtype=np.float64)\n\n infilter = DoubleInPointerFilter(input, False)\n infilter.input_sampling_rate = fs\n self.rls.set_input_port(0, infilter, 0)\n outfilter = DoubleOutPointerFilter(output, False)\n outfilter.input_sampling_rate = fs\n outfilter.set_input_port(0, self.rls, 0)\n outfilter.process(input.shape[1])\n \n return output\n\n def process(self, input):\n self.rls.learning = False\n\n import numpy as np\n output = np.zeros(input.shape, dtype=np.float64)\n \n infilter = DoubleInPointerFilter(input, False)\n infilter.input_sampling_rate = fs\n self.rls.set_input_port(0, infilter, 0)\n outfilter = DoubleOutPointerFilter(output, False)\n outfilter.input_sampling_rate = fs\n outfilter.set_input_port(0, self.rls, 0)\n outfilter.process(input.shape[1])\n\n return output\n\ndef RLS_noise_test():\n import numpy as np\n from numpy.testing import assert_almost_equal\n \n import os\n dirname = os.path.dirname(__file__)\n \n filter = Filter()\n \n x = np.fromfile(dirname + os.sep + \"input_rls_noise.dat\", dtype=np.float64).reshape(1, -1)\n ref = np.fromfile(dirname + os.sep + \"output_rls_noise.dat\", dtype=np.float64).reshape(1, -1)\n out = filter.learn(x)\n assert_almost_equal(out, ref)\n\nif __name__ == \"__main__\":\n import numpy as np\n size = 48000\n window = size//10\n \n filter = Filter()\n \n lowcut = fs//10\n highcut = fs//5\n\n base = 100\n noise_amp = 0.5\n \n x = noise_amp*butter_bandpass_filter(np.random.randn(1, size), lowcut, highcut, fs)\n x.tofile(\"input_rls_noise.dat\")\n \n out = filter.learn(x)\n out.tofile(\"output_rls_noise.dat\")\n \n x1 = np.arange(size, dtype=np.float64).reshape(1, -1) / fs\n ref = np.sin(x1 * 2 * np.pi * base) + 1/3. * np.sin(x1 * 2 * np.pi * 3.1*base) + 1/5. * np.sin(x1 * 2 * np.pi * 4.95*base)\n d1 = ref + noise_amp*butter_bandpass_filter(np.random.randn(1, size), lowcut, highcut, fs)\n d1.tofile(\"input_with_noise.dat\")\n ref.tofile(\"input_without_noise.dat\")\n out1 = filter.process(d1)\n out1.tofile(\"output_noise_rls.dat\")\n\n import matplotlib.pyplot as plt\n plt.plot(x1[0], x[0], label=\"Training noise\")\n plt.plot(x1[0], out[0], label=\"Learnt noise\")\n plt.plot(x1[0], x[0] - out[0], label=\"Remaining noise\")\n plt.legend()\n plt.title(\"Noise learning stage\")\n\n print(\"Original noise power: \" + str(np.mean(x**2)))\n print(\"Learnt noise power: \" + str(np.mean(out**2)))\n print(\"Remaining noise power: \" + str(np.mean((x-out)**2)))\n\n plt.figure()\n plt.subplot(2,1,1)\n plt.plot(x1[0,size-window:size], d1[0,size-window:size], label=\"Noisy signal\")\n plt.plot(x1[0,size-window:size], d1[0,size-window:size] - out1[0,size-window:size], label=\"Filtered signal\")\n plt.plot(x1[0,size-window:size], ref[0,size-window:size], label=\"Original signal\")\n plt.title(\"Comparison between original and filtered signal\")\n plt.legend()\n plt.subplot(2,1,2)\n plt.plot(x1[0,size-window:size], d1[0,size-window:size] - ref[0,size-window:size], label=\"Original noise\")\n plt.plot(x1[0,size-window:size], out1[0,size-window:size], label=\"Estimated noise\")\n plt.plot(x1[0,size-window:size], d1[0,size-window:size] - ref[0,size-window:size] - out1[0,size-window:size], label=\"Remaining noise\")\n plt.title(\"Comparison between original and remaining noise\")\n plt.legend()\n\n print(\"Signal to noise ratio: \" + str(np.mean(ref**2)/np.mean((ref - d1)**2)))\n print(\"Signal to remaining noise ratio: \" + str(np.mean(ref**2)/np.mean((d1 - ref - out1)**2)))\n \n from scipy import signal\n print(filter.rls.w)\n w, h = signal.freqz(filter.rls.w)\n plt.figure()\n plt.loglog(w, np.abs(h), label=\"RLS filter\")\n plt.grid(True)\n plt.title(\"Frequency response\")\n\n from scipy.fftpack import fft\n \n freqs = np.arange(size//2+1)\n X = np.abs(fft(x[0])[:size//2+1])\n OUT = np.abs(fft(out[0])[:size//2+1])\n REM = np.abs(fft(out[0] - x[0])[:size//2+1])\n plt.figure()\n plt.semilogy(freqs, X, label=\"Training noise\")\n plt.semilogy(freqs, OUT, label=\"Learnt noise\")\n plt.semilogy(freqs, REM, label=\"Learnt noise\")\n plt.title(\"Power spectrum of the noise\")\n plt.legend()\n\n D1 = np.abs(fft(d1[0])[:size//2+1])\n OUT1 = np.abs(fft(d1[0] - out1[0])[:size//2+1])\n REF = np.abs(fft(ref[0])[:size//2+1])\n plt.figure()\n plt.subplot(2,1,1)\n plt.semilogy(freqs[:601], D1[:601], label=\"Noisy signal\")\n plt.semilogy(freqs[:601], OUT1[:601], label=\"Filtered signal\")\n# plt.semilogy(freqs[:601], REF[:601], label=\"Original signal\")\n plt.title(\"Power spectrum of the signals (0-600Hz)\")\n plt.legend()\n plt.subplot(2,1,2)\n plt.semilogy(freqs[lowcut:highcut+1], D1[lowcut:highcut+1], label=\"Noisy signal\")\n plt.semilogy(freqs[lowcut:highcut+1], OUT1[lowcut:highcut+1], label=\"Filtered signal\")\n# plt.semilogy(freqs[lowcut:highcut+1], REF[lowcut:highcut+1], label=\"Original signal\")\n plt.title(\"Power spectrum of the signals (%i-%i Hz)\" % (lowcut,highcut))\n plt.legend()\n \n plt.show()\n","repo_name":"mbrucher/AudioTK","sub_path":"tests/Python/Adaptive/PyATKAdaptive_rls_filter_noise_test.py","file_name":"PyATKAdaptive_rls_filter_noise_test.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","stars":247,"dataset":"github-code","pt":"30"} +{"seq_id":"16423034384","text":"import json\nimport secrets\nimport arrow\nfrom flask import Blueprint, render_template, abort, jsonify\nfrom flask import Flask, send_from_directory, request, session, redirect, send_file, url_for\nfrom flask_cors import CORS, cross_origin\n\nfrom models import misc \nfrom models import errors\nfrom base import utils\nfrom functools import wraps\nimport arrow\n\nprefix = \"/appointment\"\ndb = None\ncom = Blueprint(\"appointment\", __name__)\nCORS(com)\nmasterdb = None\n\nsess = None\ns_data = lambda : sess[request.headers[\"Session-Token\"]]\n\ndef Load(_app, _db, session_data):\n global db, sess, masterdb\n db = _db.appointment\n app = _app\n masterdb= _db\n sess = session_data\n _app.register_blueprint(com, url_prefix=prefix)\n\n\ndef require_login(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n print(f\"[{f.__name__}] This endpoint requires to be logged in.\")\n token = request.headers.get(\"Session-Token\")\n if not token or token not in sess:\n abort(400, errors.account.e08)\n print(token)\n #pprint(session.__dict__)\n if sess[token].get(\"uid\") is None:\n print(\"Endpoint access failed.\")\n abort(400, errors.account.e00)\n else:\n print(\"Endpoint access success.\")\n return f(*args, **kwargs)\n return wrap\n\n\n@com.route(\"/request\", methods=[\"GET\", \"POST\"])\n@require_login\ndef request_appointment():\n required = [\"doctor\", \"date\", \"purpose\"]\n data = request.get_json(force=True)\n doctor_data = masterdb.account.get_one(uid=data[\"doctor\"], account_type=\"doctor\")\n\n if doctor_data.uid is None:\n abort(400, errors.account.e09)\n\n new_appointment = misc.Appointment(data)\n val = new_appointment.validate(required)\n if val:\n abort(400, errors.account.e02 + [val])\n\n new_appointment.uid = secrets.token_hex(8)\n new_appointment.user = s_data()[\"uid\"]\n new_appointment.status = \"pending\"\n new_appointment.active = \"true\"\n new_appointment.reason = [\"None\"]\n result = db.add(new_appointment)\n\n if errors.db.iserror(result):\n abort(400, result)\n\n new_appointment.__dict__[\"success\"] = True\n return jsonify(new_appointment.to_dict())\n\n\n\n@com.route(\"/get/\", methods=[\"GET\", \"POST\"])\n@require_login\ndef get_appointment(atype):\n if s_data()[\"userdata\"][\"account_type\"] == \"user\":\n data = db.get_many(user=s_data()[\"uid\"], status=atype)\n else:\n data = db.get_many(doctor=s_data()[\"uid\"], status=atype)\n print(data)\n final = []\n for d in data:\n d = d.to_dict()\n d[\"doctor\"] = masterdb.account.get_one(uid=d[\"doctor\"]).to_dict()\n d[\"doctor\"][\"clinic\"] = masterdb.clinic.get_one(uid=d[\"doctor\"][\"clinic\"]).to_dict()\n d[\"user\"] = masterdb.account.get_one(uid=d[\"user\"]).to_dict()\n final.append(d)\n\n # if not data:\n # abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n return jsonify(final)\n\n\n@com.route(\"/today\", methods=[\"GET\", \"POST\"])\n@require_login\ndef get_appointment_today():\n date = arrow.now().timestamp\n if s_data()[\"userdata\"][\"account_type\"] == \"user\":\n d = db.get_many(user=s_data()[\"uid\"], date=date)\n else:\n d = db.get_many(doctor=s_data()[\"uid\"], date=date)\n print(data)\n d = d.to_dict()\n d[\"doctor\"] = masterdb.account.get_one(uid=d[\"doctor\"]).to_dict()\n d[\"doctor\"][\"clinic\"] = masterdb.clinic.get_one(uid=d[\"doctor\"][\"clinic\"]).to_dict()\n d[\"user\"] = masterdb.account.get_one(uid=d[\"user\"]).to_dict()\n\n # if not data:\n # abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n return jsonify(d)\n\n\n@com.route(\"/get_single/\", methods=[\"GET\", \"POST\"])\n@require_login\ndef get_appointment_solo(uid):\n d = db.get_one(uid=uid).to_dict()\n print(d)\n d[\"doctor\"] = masterdb.account.get_one(uid=d[\"doctor\"]).to_dict()\n print(d[\"doctor\"])\n d[\"doctor\"][\"clinic\"] = masterdb.clinic.get_one(uid=d[\"doctor\"][\"clinic\"]).to_dict()\n d[\"user\"] = masterdb.account.get_one(uid=d[\"user\"]).to_dict()\n # if not data:\n # abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n return jsonify(d)\n\n\n@com.route(\"/accept/\", methods=[\"GET\", \"POST\"])\n@require_login\ndef accept_appointment(appointment_id):\n data = db.get_one(uid=appointment_id, status=\"pending\")\n print(data.to_dict())\n if data.uid is None:\n abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n if data.doctor != s_data()[\"uid\"]:\n abort(400, [\"e00\", \"Mismatching credentials. Authorization denied.\"])\n\n\n result = db.update(data, {\"status\": \"approved\"})\n\n if result:\n return jsonify({\"success\": f\"Appointment '{appointment_id} ' approved by doctor.\"})\n else:\n abort(400, [\"db00\", \"Unknown database error.\"])\n\n\n@com.route(\"/decline/\", methods=[\"GET\", \"POST\"])\n@require_login\ndef decline_appointment(appointment_id):\n data = db.get_one(uid=appointment_id, status=\"pending\")\n print(data.to_dict())\n if data.uid is None:\n abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n if data.doctor != s_data()[\"uid\"]:\n abort(400, [\"e00\", \"Mismatching credentials. Authorization denied.\"])\n\n\n result = db.update(data, {\"status\": \"declined\"})\n\n if result:\n return jsonify({\"success\": f\"Appointment '{appointment_id} ' approved by doctor.\"})\n else:\n abort(400, [\"db00\", \"Unknown database error.\"])\n\n\n\n@com.route(\"/update/\", methods=[\"POST\"])\n@require_login\ndef update_appointment(appointment_id):\n filters = [\"uid\", \"status\", \"user\", \"timestamp\"]\n new_data = request.get_json(force=True)\n for filt in filters:\n if filt in new_data:\n new_data.pop(filt)\n\n data = db.get_one(uid=appointment_id, status=\"pending\")\n print(data.to_dict())\n if data.uid is None:\n abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n if data.doctor != s_data()[\"uid\"]:\n abort(400, [\"e00\", \"Mismatching credentials. Authorization denied.\"])\n\n result = db.update(data, new_data)\n\n if result:\n return jsonify({\"success\": f\"Appointment '{appointment_id} ' approved by doctor.\"})\n else:\n abort(400, [\"db00\", \"Unknown database error.\"])\n\n\n@com.route(\"/finish/\", methods=[\"GET\", \"POST\"])\n@require_login\ndef finish_appointment(appointment_id):\n data = db.get_one(uid=appointment_id, status=\"approved\")\n print(data.to_dict())\n if data.uid is None:\n abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n if data.doctor != s_data()[\"uid\"]:\n abort(400, \n [\"e00\", \"Mismatching credentials. Authorization denied.\"])\n\n result = db.update(data, {\"status\": \"done\"})\n\n if result:\n return jsonify({\"success\": f\"Appointment '{appointment_id} ' finished by doctor.\"})\n else:\n abort(400, [\"db00\", \"Unknown database error.\"])\n\n\n\n@com.route(\"/reschedule/\", methods=[\"POST\"])\n@require_login\ndef reschedule_appointment(appointment_id):\n new_data = request.get_json(force=True)\n data = db.get_one(uid=appointment_id, status=\"approved\")\n print(data.to_dict())\n if data.uid is None:\n abort(400, [\"e00\", \"Appointment does not exist.\"])\n\n data.date.append(new_data)\n result = db.update(data, {\"date\": data.date})\n\n if result:\n return jsonify({\"success\": f\"Appointment '{appointment_id} ' finished by doctor.\"})\n else:\n abort(400, [\"db00\", \"Unknown database error.\"])\n\n\n","repo_name":"nokusukun/navdoc-backend","sub_path":"api/appointment.py","file_name":"appointment.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"27164583758","text":"from typing import List\n\nclass Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n count = nums.count(0)\n for _ in range(count):\n nums.remove(0)\n nums.append(0)\n\n\n\n","repo_name":"Geunbaek/algorithm","sub_path":"leetcode/daily/day03/283.Move_Zeroes.py","file_name":"283.Move_Zeroes.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"74052904083","text":"from collections import Counter\nimport pandas as pd\nfrom sentencegetter import SentenceGetter\n\n\nclass Data(object):\n def __init__(self):\n self.corpus_loc = \"~/Projects/corpus/entity-annotated-corpus/ner_dataset.csv\"\n\n self.data = pd.read_csv(self.corpus_loc, encoding=\"latin1\").fillna(method=\"ffill\")\n\n self.getter = SentenceGetter(self.data)\n sentences = self.getter.sentences\n\n self.labels = [[s[2] for s in sent] for sent in sentences]\n self.sentences = [\" \".join([s[0] for s in sent]) for sent in sentences]\n\n word_cnt = Counter(self.data[\"Word\"].values)\n vocabulary = set(w[0] for w in word_cnt.most_common(5000))\n\n words = list(set(self.data[\"Word\"].values))\n tags = list(set(self.data[\"Tag\"].values))\n\n self.max_len = 50\n\n self.word2idx = {\"PAD\": 0, \"UNK\": 1}\n self.word2idx.update({w: i for i, w in enumerate(words) if w in vocabulary})\n self.tag2idx = {t: i for i, t in enumerate(tags)}\n\n # Vocabulary Key:tag_index -> Value:Label/Tag\n self.idx2tag = {i: w for w, i in self.tag2idx.items()}\n self.idx2word = {i: w for w, i in self.word2idx.items()}\n self.n_words = len(words)\n self.n_tags = len(tags)\n\n def count_data_points(self):\n words = list(set(self.data[\"Word\"].values))\n n_words = len(words)\n print(n_words)\n\n tags = list(set(self.data[\"Tag\"].values))\n n_tags = len(tags)\n print(n_tags)\n","repo_name":"glenkalarikkal/ner-lstm-crf","sub_path":"corpus_provider.py","file_name":"corpus_provider.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"44196875591","text":"from .local import *\n\nDATABASE_APPS_MAPPING = {\n 'auth': 'default',\n 'contenttypes': 'default',\n 'icommons_common': 'default',\n 'lti_permissions': 'default', # deprecated, but still around for migrations\n 'lti_school_permissions': 'default',\n 'manage_people': 'default',\n 'manage_sections': 'default',\n 'sessions': 'default',\n}\n\nDATABASE_MIGRATION_WHITELIST = ['default']\n\n# Make tests faster by using sqlite3\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(os.path.dirname(__file__), 'test.db'),\n }\n}\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache'\n },\n 'shared': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache'\n }\n}\n\n\"\"\"\nUnit tests should be able to run without talking to external services like\nredis/elasticache. Let's disable the caching middleware, and use the db\nto store session data.\n\"\"\"\nMIDDLEWARE = list(MIDDLEWARE)\nMIDDLEWARE[MIDDLEWARE.index('cached_auth.Middleware')] = \\\n 'django.contrib.auth.middleware.AuthenticationMiddleware'\nMIDDLEWARE = tuple(MIDDLEWARE)\nSESSION_ENGINE = 'django.contrib.sessions.backends.db'\n\n\"\"\"\nDon't assume we'll have oauth credentials set for us in secure.py, set\nthem up here instead.\n\"\"\"\nSECURE_SETTINGS.setdefault('lti_oauth_credentials', {}).update({'foo': 'bar'})\nif not LTI_OAUTH_CREDENTIALS:\n LTI_OAUTH_CREDENTIALS = {}\nLTI_OAUTH_CREDENTIALS.update({'foo': 'bar'})\nSECURE_SETTINGS.setdefault('canvas_token', 'foo')\nif not CANVAS_SDK_SETTINGS:\n CANVAS_SDK_SETTINGS = {}\nCANVAS_SDK_SETTINGS.update({'auth_token': 'foo'})\n","repo_name":"Harvard-University-iCommons/canvas_manage_course","sub_path":"canvas_manage_course/settings/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"32228772384","text":"import datetime\nimport os\nimport pipes\nimport random\nimport subprocess\n\nfrom pyvirtualdisplay import Display\nfrom StringIO import StringIO\nfrom tempfile import NamedTemporaryFile\n\nfrom django.conf import settings\nfrom django.db.models import Q\n\nfrom django.utils.translation import ugettext as _\n\nfrom dwb_book.models import Item, Copy\n\n\ndef apply_markers(text, markers):\n \"\"\"Docstring.\"\"\"\n if not text or len(text.strip()) == 0:\n return text # text is empty\n\n for marker in markers:\n # simple case\n placeholder = marker.placeholder\n text = text.replace(marker.placeholder, marker.replacement)\n\n # handle HTML  \n placeholder = marker.placeholder.replace(\" \", \" \")\n text = text.replace(placeholder, marker.replacement)\n\n return text\n\n\ndef get_table_of_content(book, copy=None):\n \"\"\"Docstring.\"\"\"\n # get index value of important headings\n if book.first_appendix_heading:\n appendix_index = book.first_appendix_heading._order\n else:\n appendix_index = None\n\n if book.first_payed_heading:\n payed_index = book.first_payed_heading._order\n else:\n payed_index = None\n\n if copy:\n access_max_index = get_last_item_for_access(book, copy.user)._order\n else:\n access_max_index = get_last_item_for_access(book, None)._order\n\n # find all headings\n items = Item.objects.filter(\n (Q(item_type=\"h1\") | Q(item_type=\"h2\") | Q(item_type=\"h3\")) &\n Q(book=book)\n )\n toc = []\n\n for item in items:\n is_appendix = (appendix_index and item._order >= appendix_index)\n\n if is_appendix:\n is_free = True\n can_access = True\n else:\n is_free = (payed_index and item._order < payed_index)\n can_access = item._order <= access_max_index\n\n info = {\n \"item\": item,\n \"can_access\": can_access,\n \"is_appendix\": is_appendix,\n \"is_free\": is_free,\n }\n toc.append(info)\n\n # done\n return toc\n\n\ndef get_page_items(book, index):\n \"\"\"Docstring.\"\"\"\n # find heading for this item\n this_item = Item.objects.get(\n book=book,\n _order=index\n )\n\n if this_item.is_heading():\n first_item = this_item\n else:\n first_item = this_item.get_parent()\n\n # find headings for current items\n if first_item.item_type == \"h1\":\n headings = [\"h1\"]\n elif first_item.item_type == \"h2\":\n headings = [\"h1\", \"h2\"]\n elif first_item.item_type == \"h3\":\n headings = [\"h1\", \"h2\", \"h3\"]\n else:\n headings = []\n\n # find items under current heading\n items = [first_item]\n current_item = first_item\n has_content = False\n\n while True:\n try:\n current_item = current_item.get_next_item()\n except Item.DoesNotExist:\n break\n\n if current_item.is_heading():\n if current_item.item_type in headings:\n return items\n elif has_content:\n return items\n else:\n headings.append(current_item.item_type)\n else:\n has_content = True\n\n items.append(current_item)\n\n return items\n\n\ndef get_chapters_user_can_access(book, user):\n \"\"\"Return a list of h1 items that user can access.\"\"\"\n last_item = get_last_item_for_access(book, user)\n\n items = book.item_set.filter(\n item_type=\"h1\",\n _order__lte=last_item._order,\n )\n\n return items\n\n\ndef get_chapter_items(book, h1):\n \"\"\"Docstring.\"\"\"\n if h1.book != book:\n raise Exception(\n _(\"Chapter not found\"))\n\n # find H1 for this item\n if h1.item_type == \"h1\":\n first_item = h1\n else:\n first_item = h1.get_parent(item_type=\"h1\")\n\n # find items under this H1\n try:\n next_h1 = Item.objects.filter(\n book=book,\n item_type=\"h1\",\n _order__gt=first_item._order\n )[0]\n items = Item.objects.filter(\n book=book,\n _order__gte=first_item._order,\n _order__lt=next_h1._order\n ).all()\n except IndexError:\n # this was last H1\n items = Item.objects.filter(\n book=book,\n _order__gte=first_item._order\n ).all()\n\n return items\n\n\ndef get_last_item_for_access(book, user):\n \"\"\"Docstring.\"\"\"\n copy = None\n\n try:\n if user and user.is_authenticated():\n copy = Copy.objects.get(\n book=book,\n user=user,\n )\n except Copy.DoesNotExist:\n pass\n\n if copy and copy.status == \"completed\":\n # can access everything\n return book.item_set.last()\n\n if copy and copy.status == \"progress\":\n # can access current page and earlier\n if copy.current_item:\n page = get_page_items(book, copy.current_item._order)\n return page[-1]\n\n # preview access only\n if book.first_payed_heading:\n return book.first_payed_heading.get_previous_item()\n\n page = get_page_items(book, book.item_set.first()._order)\n\n return page[-1]\n\n\ndef can_user_access_item(user, item):\n \"\"\"Docstring.\"\"\"\n last_item = get_last_item_for_access(item.book, user)\n\n try:\n appendix_index = item.book.first_appendix_heading._order\n\n return item._order <= last_item._order or item._order >= appendix_index\n except:\n return item._order <= last_item._order\n\n\ndef update_progress(copy, new_item):\n \"\"\"Update progress to given item. Does not save copy.\"\"\"\n # sanity check\n if copy.book != new_item.book:\n raise Exception(\n _(\"Invalid item for book\"))\n\n if copy.status != \"completed\" and copy.status != \"progress\":\n return\n\n # make sure we don't go back in progress\n if copy.current_item and copy.current_item._order > new_item._order:\n return\n\n # calculate progress\n if copy.book.first_appendix_heading:\n appendix_index = copy.book.first_appendix_heading._order\n total_items = copy.book.item_set.filter(\n _order__lt=appendix_index\n ).count()\n else:\n appendix_index = None\n total_items = copy.book.item_set.count()\n\n if appendix_index and new_item._order >= appendix_index:\n copy.status = \"completed\"\n copy.current_item = None\n copy.overall_progress = 100\n\n if copy.certificate_number == 0:\n copy.completed_date = datetime.date.today()\n copy.certificate_number = random.randint(1000000, 9999999)\n else:\n copy.current_item = new_item\n copy.overall_progress = 100.0 * new_item._order / total_items\n\n\ndef delete_copy_data(copy):\n \"\"\"Docstring.\"\"\"\n copy.overall_progress = 0\n copy.current_item = None\n\n if copy.status == \"completed\":\n copy.status = \"progress\"\n\n copy.save()\n\n for response in copy.response_set.all():\n response.delete()\n\n\ndef html_to_pdf(html):\n \"\"\"Docstring.\"\"\"\n html_file = None\n pdf_file = None\n display = None\n\n try:\n display = Display(visible=0, size=(800, 600))\n display.start()\n\n html_file = NamedTemporaryFile(delete=False, suffix=\".html\")\n html_file.write(html.encode(\"utf-8\", \"ignore\"))\n html_file.close()\n\n pdf_file = NamedTemporaryFile(delete=False, suffix=\".pdf\")\n pdf_file.close()\n\n DEVNULL = open(os.devnull, \"wb\")\n\n cmd = [\n \"wkhtmltopdf\",\n html_file.name,\n pdf_file.name\n ]\n subprocess.call(\n cmd\n )\n DEVNULL.close()\n\n f = open(pdf_file.name, \"rb\")\n pdf_content = f.read()\n f.close()\n\n if not pdf_content:\n raise Exception(\n _(\"Failed to create PDF\"))\n\n return pdf_content\n\n finally:\n # clean up\n try:\n if display:\n display.stop()\n except:\n pass\n\n try:\n if html_file:\n os.unlink(html_file.name)\n except:\n pass\n\n try:\n if pdf_file:\n os.unlink(pdf_file.name)\n except:\n pass\n","repo_name":"ksbek/discleship","sub_path":"dwb_book/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"30033476835","text":"from flask import Flask, render_template, request\nimport searchTerms\n\ndef searchOutput(results):\n '''results is a list of search results and comprises of dictionaries\n where each dictionary is a single result'''\n display = []\n for d in results:\n display.append(d['name'])\n return display\n\ngameName = \"\"\ngenre = \"\"\ncategory = \"\"\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n global gameName\n global genre\n global category\n genre = \"\"\n gameName = \"\"\n category = \"\"\n return render_template(\"index.html\")\n\n@app.route('/genreMenu')\ndef genreMenu():\n global category\n category = \"genre\"\n return render_template('genre.html')\n\n@app.route('/franchiseMenu')\ndef franchiseMenu():\n global category\n category = \"franchise\"\n return render_template('franchise.html')\n\n@app.route('/platformMenu')\ndef platformMenu():\n global category\n category = \"platform\"\n return render_template('platform.html')\n\n@app.route('/ratingMenu')\ndef ratingMenu():\n global category\n category = \"rating\"\n return render_template('rating.html')\n\n@app.route('/handle_form', methods=['POST'])\ndef handle_the_form():\n global gameName\n global genre\n\n global category\n category = request.form[category]\n print(category)\n results = searchTerms.searchByCategory(category)\n return render_template(\"displayList.html\",data=results)\n\nif __name__ == '__main__':\n print('starting Flask app', app.name)\n app.run(debug=True)\n","repo_name":"spandysharma/507FinalProject","sub_path":"inputapp.py","file_name":"inputapp.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"17817950113","text":"from skywriting.lang.resume import BinaryExpressionRR,\\\n FunctionCallRR, ListRR, DictRR, StatementListRR, DoRR, IfRR, WhileRR, ForRR,\\\n ListIndexRR, AssignmentRR, ReturnRR, PlusRR, LessThanOrEqualRR, EqualRR,\\\n StarRR, ForceEvalRR, PlusAssignmentRR, IncludeRR\nfrom skywriting.lang.datatypes import map_leaf_values\n\nindent = 0\n\nclass Visitor:\n \n def visit(self, node):\n return getattr(self, \"visit_%s\" % (str(node.__class__).split('.')[-1], ))(node)\n\n#class SWFutureReference:\n# \n# def __init__(self, ref_id):\n# self.is_future = True\n# self.id = ref_id\n\n#class SWDataReference:\n# \n# def __init__(self, urls):\n# self.is_future = False\n# self.urls = urls\n\nclass SWDereferenceWrapper:\n \n def __init__(self, ref):\n self.ref = ref\n\nclass SWDynamicScopeWrapper:\n \n def __init__(self, identifier):\n self.identifier = identifier\n self.captured_bindings = {}\n\n def call(self, args_list, stack, stack_base, context):\n actual_function = context.value_of_dynamic_scope(self.identifier)\n return actual_function.call(args_list, stack, stack_base, context)\n\nclass StatementResult:\n pass\nRESULT_BREAK = StatementResult()\nRESULT_CONTINUE = StatementResult()\n\nclass StatementExecutorVisitor(Visitor):\n \n def __init__(self, context):\n self.context = context\n \n def visit(self, node, stack, stack_base):\n return getattr(self, \"visit_%s\" % (node.__class__.__name__, ))(node, stack, stack_base)\n \n def visit_statement_list(self, statements, stack, stack_base):\n if stack_base == len(stack):\n resume_record = StatementListRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n ret = None\n \n try:\n\n for i in range(resume_record.current_statement_index, len(statements)):\n resume_record.current_statement_index = i\n ret = self.visit(statements[i], stack, stack_base + 1)\n if ret is not None:\n break\n \n except:\n raise\n \n stack.pop()\n return ret\n \n def visit_Assignment(self, node, stack, stack_base):\n\n if stack_base == len(stack):\n resume_record = AssignmentRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n \n if resume_record.rvalue is None:\n resume_record.rvalue = ExpressionEvaluatorVisitor(self.context).visit(node.rvalue, stack, stack_base + 1)\n\n self.context.update_value(node.lvalue, resume_record.rvalue, stack, stack_base + 1)\n \n except:\n raise\n \n stack.pop()\n return None\n \n def visit_PlusAssignment(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = PlusAssignmentRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n try:\n if resume_record.rvalue is None:\n resume_record.rvalue = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.rvalue, stack, stack_base + 1)\n prev = self.context.value_of(node.lvalue.identifier)\n if isinstance(prev, list):\n prev.append(resume_record.rvalue)\n else:\n self.context.update_value(node.lvalue, prev + resume_record.rvalue, stack, stack_base + 1)\n except:\n raise\n stack.pop()\n return None\n\n def visit_Break(self, node, stack, stack_base):\n return RESULT_BREAK\n \n def visit_Continue(self, node, stack, stack_base):\n return RESULT_CONTINUE\n \n def visit_Do(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = DoRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n\n while True:\n # N.B. We may be resuming after having completed the body, but faulting on the condition test.\n if not resume_record.done_body:\n ret = self.visit_statement_list(node.body, stack, stack_base + 1)\n resume_record.done_body = True\n if ret is not None:\n if ret is RESULT_BREAK:\n ret = None\n break\n elif ret is RESULT_CONTINUE:\n continue\n else:\n break \n\n condition = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.condition, stack, stack_base + 1)\n\n if not condition:\n ret = None\n break\n \n resume_record.done_body = False\n\n except:\n raise\n\n stack.pop()\n return ret\n \n def visit_If(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = IfRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n if resume_record.condition is None:\n resume_record.condition = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.condition, stack, stack_base + 1)\n \n if resume_record.condition:\n ret = self.visit_statement_list(node.true_body, stack, stack_base + 1)\n elif node.false_body is not None:\n ret = self.visit_statement_list(node.false_body, stack, stack_base + 1)\n else:\n ret = None\n \n except:\n raise\n \n stack.pop()\n return ret\n \n def visit_Include(self, node, stack, stack_base):\n \n if node.included_script is None:\n \n if stack_base == len(stack):\n resume_record = IncludeRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n if resume_record.target_ref is None:\n resume_record.target_ref = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.target_expr, stack, stack_base + 1)\n \n node.included_script = self.context.include_script(resume_record.target_ref)\n \n except:\n raise\n \n stack.pop()\n \n self.visit(node.included_script, stack, stack_base)\n \n\n def visit_For(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = ForRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n \n if resume_record.iterator is None:\n resume_record.iterator = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.iterator, stack, stack_base + 1)\n\n indexer_lvalue = node.indexer \n ret = None \n for i in range(resume_record.i, len(resume_record.iterator)):\n resume_record.i = i\n self.context.update_value(indexer_lvalue, resume_record.iterator[i], stack, stack_base + 1)\n ret = self.visit_statement_list(node.body, stack, stack_base + 1)\n \n if ret is not None:\n if ret is RESULT_BREAK:\n ret = None\n break\n elif ret is RESULT_CONTINUE:\n continue\n else:\n break \n \n except:\n raise\n \n stack.pop()\n return ret\n\n def convert_wrapper_to_eager_dereference(self, value):\n if isinstance(value, SWDereferenceWrapper):\n return self.context.eager_dereference(value.ref)\n else:\n return value\n\n def visit_Return(self, node, stack, stack_base):\n if node.expr is None:\n return None\n \n if stack_base == len(stack):\n resume_record = ReturnRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try: \n if resume_record.ret is None:\n resume_record.ret = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.expr, stack, stack_base + 1)\n \n # We must scan through the return value to see if it contains any dereferenced references, and if so, yield so these can be fetched.\n eager_derefd_val = map_leaf_values(self.convert_wrapper_to_eager_dereference, resume_record.ret)\n \n stack.pop()\n return eager_derefd_val\n \n except:\n raise\n\n def visit_While(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = WhileRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n \n while True:\n \n if not resume_record.done_condition:\n condition = ExpressionEvaluatorVisitor(self.context).visit_and_force_eval(node.condition, stack, stack_base + 1)\n if not condition:\n ret = None\n break\n resume_record.done_condition = True\n \n ret = self.visit_statement_list(node.body, stack, stack_base + 1)\n if ret is not None:\n if ret is RESULT_BREAK:\n ret = None\n break\n elif ret is RESULT_CONTINUE:\n continue\n else:\n break\n \n resume_record.done_condition = False\n \n except:\n raise\n \n stack.pop()\n return ret\n\n def visit_Script(self, node, stack, stack_base):\n return self.visit_statement_list(node.body, stack, stack_base)\n\n def visit_NamedFunctionDeclaration(self, node, stack, stack_base):\n func = UserDefinedFunction(self.context, node)\n self.context.update_value(node.name, func, stack, stack_base)\n return None\n\nclass ExpressionEvaluatorVisitor:\n \n def __init__(self, context):\n self.context = context\n \n def visit(self, node, stack, stack_base):\n return getattr(self, \"visit_%s\" % (node.__class__.__name__, ))(node, stack, stack_base)\n \n def visit_and_force_eval(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = ForceEvalRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n if resume_record.maybe_wrapped is None:\n resume_record.maybe_wrapped = self.visit(node, stack, stack_base + 1)\n\n try:\n if isinstance(resume_record.maybe_wrapped, SWDereferenceWrapper):\n ret = self.context.eager_dereference(resume_record.maybe_wrapped.ref)\n elif isinstance(resume_record.maybe_wrapped, SWDynamicScopeWrapper):\n ret = self.context.value_of_dynamic_scope(resume_record.maybe_wrapped.identifier)\n else:\n ret = resume_record.maybe_wrapped\n\n stack.pop()\n return ret\n\n except:\n raise\n \n def visit_And(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left and rexpr\n\n except:\n raise\n \n def visit_Constant(self, node, stack, stack_base):\n return node.value\n \n def visit_Dereference(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = StarRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.reference, stack, stack_base + 1)\n \n star_function = self.context.value_of('__star__')\n \n ret = star_function.call([resume_record.left], stack, stack_base + 1, self.context)\n \n stack.pop()\n return ret\n \n except:\n raise\n\n def visit_Dict(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = DictRR(len(node.items))\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try: \n ret = {}\n for i in range(len(node.items)):\n if resume_record.contents[i] is None:\n resume_record.contents[i] = self.visit(node.items[i], stack, stack_base + 1)\n \n key, value = resume_record.contents[i]\n ret[key] = value\n stack.pop()\n \n return ret\n except:\n raise\n \n def visit_Equal(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = EqualRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left == rexpr\n\n except:\n raise\n \n def visit_SpawnedFunction(self, node, stack, stack_base):\n return node.function.call(node.args, stack, stack_base, self.context)\n \n def visit_FunctionCall(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = FunctionCallRR(len(node.args))\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n for i in range(len(node.args)):\n if resume_record.args[i] is None:\n resume_record.args[i] = self.visit(node.args[i], stack, stack_base + 1)\n \n # XXX: Dynamic scope hack -- we need to visit and force eval every time we resume (in case we\n # are now running on a different machine with a different implementation for the function).\n # This is okay because dynamic scope functions are all outwith Skywriting, so there will\n # not be any implementation-specific junk further down the stack.\n function = self.visit_and_force_eval(node.function, stack[0:stack_base+1], stack_base + 1)\n ret = function.call(resume_record.args, stack, stack_base + 1, self.context)\n \n stack.pop()\n return ret\n \n except:\n raise\n \n def visit_FunctionDeclaration(self, node, stack, stack_base):\n ret = UserDefinedFunction(self.context, node)\n return ret\n \n def visit_GreaterThan(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left > rexpr\n\n except:\n raise\n \n def visit_GreaterThanOrEqual(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left >= rexpr\n\n except:\n raise\n\n def visit_Identifier(self, node, stack, stack_base):\n return self.context.value_of(node.identifier)\n\n def visit_KeyValuePair(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n # We store the key in resume_record.left\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.key_expr, stack, stack_base + 1)\n \n value = self.visit_and_force_eval(node.value_expr, stack, stack_base + 1)\n \n except:\n raise\n\n stack.pop()\n return resume_record.left, value\n \n def visit_LambdaExpression(self, node, stack, stack_base):\n return UserDefinedLambda(self.context, node)\n \n def visit_LessThan(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left < rexpr\n\n except:\n raise\n \n def visit_LessThanOrEqual(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = LessThanOrEqualRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left <= rexpr\n\n except:\n raise\n \n def visit_List(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = ListRR(len(node.contents))\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n \n for i in range(len(node.contents)):\n if resume_record.items[i] is None:\n resume_record.items[i] = self.visit_and_force_eval(node.contents[i], stack, stack_base + 1)\n \n stack.pop()\n return resume_record.items\n \n except:\n raise\n \n def visit_ListIndex(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = ListIndexRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n \n try:\n if resume_record.list is None:\n resume_record.list = self.visit_and_force_eval(node.list_expr, stack, stack_base + 1)\n \n index = self.visit_and_force_eval(node.index, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.list[index]\n \n except:\n raise\n \n def visit_Minus(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left - rexpr\n\n except:\n raise\n \n def visit_Not(self, node, stack, stack_base):\n return not self.visit_and_force_eval(node.expr, stack, stack_base)\n \n def visit_UnaryMinus(self, node, stack, stack_base):\n return -self.visit_and_force_eval(node.expr, stack, stack_base)\n\n def visit_NotEqual(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left != rexpr\n\n except:\n raise\n \n def visit_Or(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = BinaryExpressionRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left or rexpr\n\n except:\n raise\n \n def visit_Plus(self, node, stack, stack_base):\n if stack_base == len(stack):\n resume_record = PlusRR()\n stack.append(resume_record)\n else:\n resume_record = stack[stack_base]\n\n try:\n if resume_record.left is None:\n resume_record.left = self.visit_and_force_eval(node.lexpr, stack, stack_base + 1)\n\n rexpr = self.visit_and_force_eval(node.rexpr, stack, stack_base + 1)\n \n stack.pop()\n return resume_record.left + rexpr\n\n except:\n raise\n \nclass UserDefinedLambda:\n \n def __init__(self, declaration_context, lambda_ast):\n self.lambda_ast = lambda_ast\n self.captured_bindings = {}\n \n body_bindings = FunctionDeclarationBindingVisitor()\n body_bindings.visit(lambda_ast.expr)\n \n for identifier in body_bindings.rvalue_object_identifiers:\n if declaration_context.has_binding_for(identifier) and not declaration_context.is_dynamic(identifier):\n self.captured_bindings[identifier] = declaration_context.value_of(identifier)\n \n def call(self, args_list, stack, stack_base, context):\n context.enter_context(self.captured_bindings)\n for (formal_param, actual_param) in zip(self.lambda_ast.variables, args_list):\n context.bind_identifier(formal_param, actual_param)\n ret = ExpressionEvaluatorVisitor(context).visit(self.lambda_ast.expr, stack, stack_base)\n context.exit_context()\n return ret\n\nclass UserDefinedFunction:\n \n def __init__(self, declaration_context, function_ast):\n self.function_ast = function_ast\n self.captured_bindings = {}\n \n body_bindings = FunctionDeclarationBindingVisitor()\n body_bindings.visit_statement_list(function_ast.body)\n \n\n formal_params = set(function_ast.formal_params)\n \n for variable in body_bindings.lvalue_object_identifiers:\n if declaration_context.has_binding_for(variable):\n # Free variables are read-only.\n raise\n elif variable in formal_params:\n # Formal parameters are read-only.\n raise\n \n #self.execution_context = execution_context\n \n for identifier in body_bindings.rvalue_object_identifiers:\n if declaration_context.has_binding_for(identifier):\n if not declaration_context.is_dynamic(identifier):\n self.captured_bindings[identifier] = declaration_context.value_of(identifier)\n elif function_ast.name is not None and identifier == function_ast.name.identifier:\n self.captured_bindings[identifier] = self\n #self.execution_context.bind_identifier(object, declaration_context.value_of(object))\n \n def __repr__(self):\n return 'UserDefinedFunction(name=%s)' % self.function_ast.name \n \n def call(self, args_list, stack, stack_base, context):\n context.enter_context(self.captured_bindings)\n #self.execution_context.enter_scope()\n for (formal_param, actual_param) in zip(self.function_ast.formal_params, args_list):\n context.bind_identifier(formal_param, actual_param)\n \n # Belt-and-braces approach to protect formal parameters (not strictly necessary).\n # TODO: runtime protection in case lists, etc. get aliased.\n context.enter_scope()\n ret = StatementExecutorVisitor(context).visit_statement_list(self.function_ast.body, stack, stack_base)\n context.exit_scope()\n\n context.exit_context()\n return ret\n \n# TODO: could do better than this by passing over the whole script at the start. But\n# let's take a simple approach for now.\nclass FunctionDeclarationBindingVisitor(Visitor):\n \n def __init__(self):\n self.lvalue_object_identifiers = set()\n self.rvalue_object_identifiers = set()\n \n def visit_statement_list(self, statements):\n for statement in statements:\n self.visit(statement)\n \n def visit_Assignment(self, node):\n self.visit(node.lvalue)\n self.visit(node.rvalue)\n \n def visit_Break(self, node):\n pass\n \n def visit_Continue(self, node):\n pass\n \n def visit_If(self, node):\n self.visit(node.condition)\n self.visit_statement_list(node.true_body)\n if node.false_body is not None:\n self.visit_statement_list(node.false_body)\n \n def visit_PlusAssignment(self, node):\n self.visit(node.lvalue)\n self.visit(node.rvalue)\n \n def visit_Return(self, node):\n if node.expr is not None:\n self.visit(node.expr)\n \n def visit_Do(self, node):\n self.visit_statement_list(node.body)\n self.visit(node.condition)\n \n def visit_For(self, node):\n self.visit(node.indexer)\n self.visit(node.iterator)\n self.visit_statement_list(node.body)\n \n def visit_While(self, node):\n self.visit(node.condition)\n self.visit_statement_list(node.body)\n \n def visit_IdentifierLValue(self, node):\n self.lvalue_object_identifiers.add(node.identifier)\n \n def visit_IndexedLValue(self, node):\n self.visit(node.base_lvalue)\n \n def visit_FieldLValue(self, node):\n self.visit(node.base_lvalue)\n\n def visit_Constant(self, node):\n pass\n\n def visit_Dereference(self, node):\n self.visit(node.reference)\n \n def visit_Dict(self, node):\n for item in node.items:\n self.visit(item)\n \n def visit_FieldReference(self, node):\n self.visit(node.object)\n\n def visit_FunctionCall(self, node):\n self.visit(node.function)\n for arg in node.args:\n self.visit(arg)\n \n def visit_NamedFunctionDeclaration(self, node):\n self.lvalue_object_identifiers.add(node.name)\n self.visit_statement_list(node.body)\n \n def visit_FunctionDeclaration(self, node):\n self.visit_statement_list(node.body)\n \n def visit_Identifier(self, node):\n self.rvalue_object_identifiers.add(node.identifier)\n \n def visit_KeyValuePair(self, node):\n self.visit(node.key_expr)\n self.visit(node.value_expr)\n \n def visit_LambdaExpression(self, node):\n self.visit(node.expr)\n \n def visit_List(self, node):\n for elem in node.contents:\n self.visit(elem)\n \n def visit_ListIndex(self, node):\n self.visit(node.list_expr)\n self.visit(node.index)\n \n def visit_Not(self, node):\n self.visit(node.expr)\n\n def visit_UnaryMinus(self, node):\n self.visit(node.expr)\n \n def visit_BinaryExpression(self, node):\n self.visit(node.lexpr)\n self.visit(node.rexpr)\n \n visit_And = visit_BinaryExpression\n visit_Equal = visit_BinaryExpression\n visit_GreaterThan = visit_BinaryExpression\n visit_GreaterThanOrEqual = visit_BinaryExpression\n visit_LessThan = visit_BinaryExpression\n visit_LessThanOrEqual = visit_BinaryExpression\n visit_Minus = visit_BinaryExpression\n visit_NotEqual = visit_BinaryExpression\n visit_Or = visit_BinaryExpression\n visit_Plus = visit_BinaryExpression\n","repo_name":"mrry/skywriting","sub_path":"src/python/skywriting/lang/visitors.py","file_name":"visitors.py","file_ext":"py","file_size_in_byte":29953,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"30"} +{"seq_id":"12805089381","text":"\"\"\"\nName: Gregory Olesinski\nAssignment 10.1: Your Own Class\nbike_class.py\n\nThis program:\nContains a class meant to modela bicycle\nA demo program to run said class\n\"\"\"\n\nclass Bicycle:\n # Class variables that all bicycles have\n pedal_num = 2\n has_motor = False\n\n def __init__(self, color, speed_mph=0, training_wheels=False, gears=None):\n # Sets the color, speed, whether the bike has training wheels, and the gears on the constructor arguments\n self.__color = color\n self.__speed = speed_mph\n self._training_wheels = training_wheels\n self._gears = gears\n\n def set_speed(self, speed_mph):\n # Checks to see if the speed if below zero\n if speed_mph < 0:\n print(\"Speed can not be a negative number\")\n # If it isn't, sets the speed\n else:\n speed = speed_mph\n self.__speed = speed\n \n # Returns the set speed\n def get_speed(self):\n return (self.__speed)\n\n def set_color(self, color):\n # Checks to see that color was inputted properly and then sets color\n if type(color) != type(\"\"):\n print(\"Must enter a valid color as a string\")\n else:\n self.__color = color\n\n # Returns the set color\n def get_color(self):\n return self.__color\n\n # Checks to see if training wheels are set to Tue or False\n def training_wheels_check(self):\n training_wheels = self._training_wheels\n # If the bike does have training wheels, says that there are four wheels, otherwise there are two\n if training_wheels == True:\n num_wheels = 4\n return num_wheels\n elif training_wheels == False:\n num_wheels = 2\n return num_wheels\n else:\n print(\"Enter True or False for Training Wheels\") \n\n def gear_check(self, slope):\n # Checks to see if the bike has gears or not.\n # Checks inputted slope as well, and sees if the bike can go up said slope with or without gears\n gears = self._gears\n if gears == True:\n slope_success = (\"You can bike up the slope!\")\n elif gears == False and slope >= 45:\n slope_success = (\"You can't bike up the slope slope!\")\n elif gears == False and slope < 45:\n slope_success = (\"You can bike up the slope!\")\n self._gears = slope_success\n return slope_success\n\n # String magic method \n def __str__(self):\n return (f\"Your Bike: Color = {self.__color}, Speed = {self.__speed}, Training Wheels = {self._training_wheels}, Gears = {self._gears}\")\n\n# Main\ndef main():\n # Creates 4 bikes with varying attributes\n green_bike = Bicycle(\"green\", 8, True, True)\n bike1 = Bicycle(\"yellow\", 0, True, True)\n bike2 = Bicycle(\"yellow\", 0, False, False)\n bike3 = Bicycle(\"yellow\", 0, False, True)\n\n # Returns a string of all the attributes of the created bike\n print(green_bike)\n\n # Accesses the get.color method and returns just the color of the bike and nothing else\n print(green_bike.get_color())\n\n # Accesses the get.speed method and returns just the speed of the bike and nothing else\n print(green_bike.get_speed())\n\n # Accesses the training_wheels_check method and returns just how many wheels the bike has based off whether training wheels is set to True or False\n print(green_bike.training_wheels_check())\n\n # Takes in a slope angle value, then checks to see if the bike has gears and returns whether said bike can go up the given slope\n print(green_bike.gear_check(46))\n x = 1\n for i in [bike1, bike2, bike3]:\n print(f\"Bike {x}:{i.gear_check(50)}\")\n x += 1\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gregoles/Bicycle_Class","sub_path":"bike_class.py","file_name":"bike_class.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"30144436477","text":"# -*- coding: utf-8 -*-\nimport os.path\nimport sys\nimport unittest\n\nfrom matka import matka, hae_kaupunki\n\n\nDB_NAME = \"kaupungit.db\"\n# ../kaupungit.db\nDB_PATH = os.path.join(os.path.pardir, DB_NAME)\n\n\nclass TestMatka(unittest.TestCase):\n\n def setUp(self):\n # Testdata with precalculated distances.\n self.data = [\n (('Acultzingo', 'Veracruz-Llave', 'MEXICO', 5801, 18.716667, -97.316667),\n ('Clonakilty', 'Cork', 'IRELAND', 4065, 51.6230556, -8.8705556),\n 8282.27029484201),\n\n (('Amsterdam', 'Noord-Holland', 'NETHERLANDS', 745811, 52.35, 4.916667),\n ('Teplyk', \"Vinnyts'ka Oblast'\", 'UKRAINE', 6604, 48.665658, 29.745035),\n 1793.3351423353665),\n\n (('Safotu', None, 'SAMOA', 1207, -13.45, -172.4),\n ('Oxford', 'Oxfordshire', 'UNITED KINGDOM', 154567, 51.75, -1.25),\n 15683.163263741253)\n ]\n\n def test1_matka_returns_float(self):\n \"\"\"Funktio matka palauttaa etäisyyden liukulukuna.\"\"\"\n returned_distance = matka(0.0, 0.0, 1.0, 1.0)\n self.assertIsInstance(\n returned_distance,\n float,\n \"Funktion matka palauttama etäisyys pitäisi olla tyyppiä {}, ei {}.\".format(float, type(returned_distance)))\n\n def test2_distance_between_two_cities(self):\n \"\"\"Funktio matka laskee kahden kaupungin etäisyyden oikein.\"\"\"\n accuracy = 3\n for city1, city2, distance in self.data:\n returned_distance = matka(city1[4], city1[5], city2[4], city2[5])\n self.assertAlmostEqual(\n returned_distance,\n distance,\n accuracy,\n \"Etäisyys alla olevien kaupunkien välillä pitäisi olla {} desimaalin tarkkuudella {:.4f}, mutta funktiosi palautti {:.4f}.\"\n .format(accuracy, distance, returned_distance) + \"\\n\\n\"\n + str(tuple(city1)) + \"\\n\" + str(tuple(city2)))\n\n def test3_hae_kaupunki_returns_tuple(self):\n \"\"\"Funktio hae_kaupunki palauttaa tietokannan rivin.\"\"\"\n city_name = self.data[0][0][0]\n returned_city = hae_kaupunki(city_name, DB_PATH)\n self.assertIsNotNone(\n returned_city,\n \"Funktiolle hae_kaupunki annettiin parametrina {}, mutta funktio palautti None.\"\n .format(city_name))\n self.assertEqual(\n len(returned_city),\n 7,\n \"Funktiolle hae_kaupunki annettiin parametrina {} ja funktion pitäisi palauttaa yksi tietokannan rivi, jossa on 7 arvoa, ei {}.\"\n .format(city_name, len(returned_city)) + \"\\n\\n\" +\n \"Funktio palautti rivin:\\n{}\".format(returned_city))\n\n def test4_hae_kaupunki_returns_city_with_largest_population(self):\n \"\"\"Funktio hae_kaupunki palauttaa kaupungin, jossa on annetulla nimella suurin asukasluku.\"\"\"\n def assert_city(city):\n city_name = city[0]\n returned_city = hae_kaupunki(city_name, DB_PATH)\n self.assertEqual(\n returned_city[1],\n city_name,\n \"Funktiolle hae_kaupunki annettiin parametrina {}, mutta funktio palautti:\\n\\n{}\"\n .format(city_name, returned_city))\n city_population = city[3]\n self.assertEqual(\n returned_city[1:],\n city,\n \"Funktiolle hae_kaupunki annettiin parametrina {}.\"\n .format(city_name) + \"\\n\\n\" +\n \"Funktion olisi pitänyt palauttaa kaupunki nimeltä {}, jolla on asukasluku {}, mutta funktio palautti alla olevan rivin.\"\n .format(city_name, city_population) + \"\\n\\n{}\".format(returned_city))\n\n for city1, city2, _ in self.data:\n assert_city(city1)\n assert_city(city2)\n\n\nif __name__ in (\"__main__\", \"tests\"):\n if not os.path.exists(DB_PATH):\n print(\"Tietokantaa ei löytynyt. Onko hakemistorakenne sama kuin zip-paketissa?\")\n print(\"Testit olettavat, että tietokanta on yhtä tasoa ylempänä kuin testit (testitiedostosta katsottuna {})\".format(DB_PATH))\n sys.exit(1)\n unittest.main(verbosity=2)\n\n","repo_name":"bythemark/sql","sub_path":"teht3/test_matka.py","file_name":"test_matka.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"44437192121","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# 1st solution\n# O(n) time | O(1) space\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n fast, slow = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n break\n if not fast or not fast.next:\n return None\n fast = head\n while fast != slow:\n fast = fast.next\n slow = slow.next\n return fast","repo_name":"yingzhuo1994/LeetCode","sub_path":"0142_LinkedListCycleII.py","file_name":"0142_LinkedListCycleII.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"40604563424","text":"import flexsolve as flx\nimport numpy as np\nfrom math import exp\nfrom thermosteam import functional as fn\nfrom .. import units_of_measure as thermo_units\nfrom ..base import PhaseHandle, MockPhaseTHandle, MockPhaseTPHandle, sparse\nfrom .ideal_mixture_model import (\n SinglePhaseIdealTMixtureModel,\n IdealTMixtureModel, \n IdealTPMixtureModel, \n IdealEntropyModel, \n IdealHvapModel\n)\nfrom .._chemicals import Chemical, CompiledChemicals, chemical_data_array\n\n__all__ = ('Mixture',)\n\n# %% Functions for building mixture models\n\ndef create_mixture_model(chemicals, var, Model):\n getfield = getattr\n isa = isinstance\n handles = []\n for chemical in chemicals:\n obj = getfield(chemical, var)\n if isa(obj, PhaseHandle):\n phase_handle = obj\n elif var == 'Cn':\n phase_handle = MockPhaseTHandle(var, obj)\n else:\n phase_handle = MockPhaseTPHandle(var, obj)\n handles.append(phase_handle)\n return Model(handles, var)\n \n\n# %% Energy balance\n\ndef iter_T_at_HP(T, H, H_model, phase, mol, P, Cn_model, Cn_cache):\n # Used to solve for temperature at given ethalpy \n counter, Cn = Cn_cache\n if not counter % 5: Cn_cache[1] = Cn = Cn_model(phase, mol, T)\n Cn_cache[0] += 1\n return T + (H - H_model(phase, mol, T, P)) / Cn\n\ndef xiter_T_at_HP(T, H, H_model, phase_mol, P, Cn_model, Cn_cache):\n # Used to solve for temperature at given ethalpy \n counter, Cn = Cn_cache\n if not counter % 5: Cn_cache[1] = Cn = Cn_model(phase_mol, T)\n Cn_cache[0] += 1\n return T + (H - H_model(phase_mol, T, P)) / Cn\n\ndef iter_T_at_SP(T, S, S_model, phase, mol, P, Cn_model, Cn_cache):\n # Used to solve for temperature at given entropy \n counter, Cn = Cn_cache\n if not counter % 5: Cn_cache[1] = Cn = Cn_model(phase, mol, T)\n Cn_cache[0] += 1\n return T * exp((S - S_model(phase, mol, T, P)) / Cn)\n\ndef xiter_T_at_SP(T, S, S_model, phase_mol, P, Cn_model, Cn_cache):\n # Used to solve for temperature at given entropy \n counter, Cn = Cn_cache\n if not counter % 5: Cn_cache[1] = Cn = Cn_model(phase_mol, T)\n Cn_cache[0] += 1\n return T * exp((S - S_model(phase_mol, T, P)) / Cn)\n\n\n# %% Ideal mixture\n\nclass Mixture:\n \"\"\"\n Create an Mixture object for estimating mixture properties.\n \n Parameters\n ----------\n rule : str\n Description of mixing rules used.\n Cn : function(phase, mol, T)\n Molar isobaric heat capacity mixture model [J/mol/K].\n H : function(phase, mol, T)\n Enthalpy mixture model [J/mol].\n S : function(phase, mol, T, P)\n Entropy mixture model [J/mol].\n H_excess : function(phase, mol, T, P)\n Excess enthalpy mixture model [J/mol].\n S_excess : function(phase, mol, T, P)\n Excess entropy mixture model [J/mol].\n mu : function(phase, mol, T, P)\n Dynamic viscosity mixture model [Pa*s].\n V : function(phase, mol, T, P)\n Molar volume mixture model [m^3/mol].\n kappa : function(phase, mol, T, P)\n Thermal conductivity mixture model [W/m/K].\n Hvap : function(mol, T)\n Heat of vaporization mixture model [J/mol]\n sigma : function(mol, T, P)\n Surface tension mixture model [N/m].\n epsilon : function(mol, T, P)\n Relative permitivity mixture model [-]\n MWs : 1d array[float]\n Component molecular weights [g/mol].\n include_excess_energies=False : bool\n Whether to include excess energies\n in enthalpy and entropy calculations.\n \n Notes\n -----\n Although the mixture models are on a molar basis, this is only if the molar\n data is normalized before the calculation (i.e. the `mol` parameter is \n normalized before being passed to the model).\n \n See also\n --------\n IdealTMixtureModel\n IdealTPMixtureModel\n \n Attributes\n ----------\n rule : str\n Description of mixing rules used.\n include_excess_energies : bool\n Whether to include excess energies\n in enthalpy and entropy calculations.\n Cn(phase, mol, T) : \n Mixture molar isobaric heat capacity [J/mol/K].\n mu(phase, mol, T, P) : \n Mixture dynamic viscosity [Pa*s].\n V(phase, mol, T, P) : \n Mixture molar volume [m^3/mol].\n kappa(phase, mol, T, P) : \n Mixture thermal conductivity [W/m/K].\n Hvap(mol, T, P) : \n Mixture heat of vaporization [J/mol]\n sigma(mol, T, P) : \n Mixture surface tension [N/m].\n epsilon(mol, T, P) : \n Mixture relative permitivity [-].\n MWs : 1d-array[float]\n Component molecular weights [g/mol].\n \n \"\"\"\n maxiter = 20\n T_tol = 1e-6\n __slots__ = ('rule',\n 'rigorous_energy_balance',\n 'include_excess_energies',\n 'Cn', 'mu', 'V', 'kappa',\n 'Hvap', 'sigma', 'epsilon',\n 'MWs', '_H', '_H_excess', '_S', '_S_excess',\n )\n \n def __init__(self, rule, Cn, H, S, H_excess, S_excess,\n mu, V, kappa, Hvap, sigma, epsilon,\n MWs, include_excess_energies=False):\n self.rule = rule\n self.include_excess_energies = include_excess_energies\n self.Cn = Cn\n self.mu = mu\n self.V = V\n self.kappa = kappa\n self.Hvap = Hvap\n self.sigma = sigma\n self.epsilon = epsilon\n self.MWs = MWs\n self._H = H\n self._S = S\n self._H_excess = H_excess\n self._S_excess = S_excess\n \n @classmethod\n def from_chemicals(cls, chemicals, \n include_excess_energies=False, \n rule='ideal',\n cache=True):\n \"\"\"\n Create a Mixture object from chemical objects.\n \n Parameters\n ----------\n chemicals : Iterable[Chemical]\n For retrieving pure component chemical data.\n include_excess_energies=False : bool\n Whether to include excess energies in enthalpy and entropy calculations.\n rule : str, optional\n Mixing rule. Defaults to 'ideal'.\n cache : optional\n Whether or not to use cached chemicals and cache new chemicals. Defaults to True.\n \n See also\n --------\n :class:`~.mixture.Mixture`\n :class:`~.IdealMixtureModel`\n \n Examples\n --------\n Calculate enthalpy of evaporation for a water and ethanol mixture:\n \n >>> from thermosteam import Mixture\n >>> mixture = Mixture.from_chemicals(['Water', 'Ethanol'])\n >>> mixture.Hvap([0.2, 0.8], 350)\n 39750.62\n\n Calculate density for a water and ethanol mixture in g/L:\n\n >>> from thermosteam import Mixture\n >>> mixture = Mixture.from_chemicals(['Water', 'Ethanol'])\n >>> mixture.get_property('rho', 'g/L', 'l', [0.2, 0.8], 350, 101325)\n 754.23\n \n \"\"\"\n if rule == 'ideal':\n isa = isinstance\n if isa(chemicals, CompiledChemicals):\n MWs = chemicals.MW\n chemicals = chemicals.tuple\n else:\n chemicals = [(i if isa(i, Chemical) else Chemical(i)) for i in chemicals]\n MWs = chemical_data_array(chemicals, 'MW')\n getfield = getattr\n Cn = create_mixture_model(chemicals, 'Cn', IdealTMixtureModel)\n H = create_mixture_model(chemicals, 'H', IdealTPMixtureModel)\n S = create_mixture_model(chemicals, 'S', IdealEntropyModel)\n H_excess = create_mixture_model(chemicals, 'H_excess', IdealTPMixtureModel)\n S_excess = create_mixture_model(chemicals, 'S_excess', IdealTPMixtureModel)\n mu = create_mixture_model(chemicals, 'mu', IdealTPMixtureModel)\n V = create_mixture_model(chemicals, 'V', IdealTPMixtureModel)\n kappa = create_mixture_model(chemicals, 'kappa', IdealTPMixtureModel)\n Hvap = IdealHvapModel(chemicals)\n sigma = SinglePhaseIdealTMixtureModel([getfield(i, 'sigma') for i in chemicals], 'sigma')\n epsilon = SinglePhaseIdealTMixtureModel([getfield(i, 'epsilon') for i in chemicals], 'epsilon')\n return cls(rule, Cn, H, S, H_excess, S_excess,\n mu, V, kappa, Hvap, sigma, epsilon, MWs, include_excess_energies)\n else:\n raise ValueError(\"rule '{rule}' is not available (yet)\")\n \n def MW(self, mol):\n \"\"\"Return molecular weight [g/mol] given molar array [mol].\"\"\"\n total_mol = sparse(mol).sum()\n return (mol * self.MWs).sum() / total_mol if total_mol else 0.\n \n def rho(self, phase, mol, T, P):\n \"\"\"Mixture density [kg/m^3]\"\"\"\n MW = self.MW(mol)\n return fn.V_to_rho(self.V(phase, mol, T, P), MW) if MW else 0.\n \n def Cp(self, phase, mol, T):\n \"\"\"Mixture isobaric heat capacity [J/g/K]\"\"\"\n MW = self.MW(mol)\n return self.Cn(phase, mol, T) / MW if MW else 0.\n \n def alpha(self, phase, mol, T, P):\n \"\"\"Mixture thermal diffusivity [m^2/s].\"\"\"\n Cp = self.Cp(phase, mol, T)\n return fn.alpha(self.kappa(phase, mol, T, P), \n self.rho(phase, mol, T, P), \n Cp * 1000.) if Cp else 0.\n \n def nu(self, phase, mol, T, P):\n \"\"\"Mixture kinematic viscosity [m^2/s].\"\"\"\n rho = self.rho(phase, mol, T, P)\n return fn.mu_to_nu(self.mu(phase, mol, T, P), \n rho) if rho else 0.\n \n def Pr(self, phase, mol, T, P):\n \"\"\"Mixture Prandtl number [-].\"\"\"\n Cp = self.Cp(phase, mol, T)\n return fn.Pr(Cp * 1000.,\n self.kappa(phase, mol, T, P), \n self.mu(phase, mol, T, P)) if Cp else 0.\n \n def xrho(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture density [kg/m3].\"\"\"\n return sum([self.rho(phase, mol, T, P) for phase, mol in phase_mol])\n \n def xCp(self, phase_mol, T):\n \"\"\"Multi-phase mixture isobaric heat capacity [J/g/K].\"\"\"\n return sum([self.Cp(phase, mol, T) for phase, mol in phase_mol])\n \n def xalpha(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture thermal diffusivity [m^2/s].\"\"\"\n return sum([self.alpha(phase, mol, T, P) for phase, mol in phase_mol])\n \n def xnu(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture kinematic viscosity [m^2/s].\"\"\"\n return sum([self.nu(phase, mol, T, P) for phase, mol in phase_mol])\n \n def xPr(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture Prandtl number [-].\"\"\"\n return sum([self.Pr(phase, mol, T, P) for phase, mol in phase_mol])\n \n def get_property(self, name, units, *args, **kwargs):\n \"\"\"\n Return property in requested units.\n\n Parameters\n ----------\n name : str\n Name of stream property.\n units : str\n Units of measure.\n *args, **kwargs :\n Phase, material and thermal condition.\n\n \"\"\"\n value = getattr(self, name)(*args, **kwargs)\n units_dct = thermo_units.chemical_units_of_measure\n if name in units_dct:\n original_units = units_dct[name]\n else:\n raise ValueError(f\"'{name}' is not thermodynamic property\")\n return original_units.convert(value, units)\n \n def H(self, phase, mol, T, P):\n \"\"\"Return enthalpy [J/mol].\"\"\"\n H = self._H(phase, mol, T, P)\n if self.include_excess_energies: H += self._H_excess(phase, mol, T, P)\n return H\n \n def S(self, phase, mol, T, P):\n \"\"\"Return entropy in [J/mol/K].\"\"\"\n total_mol = mol.sum()\n if total_mol == 0.: return 0.\n S = self._S(phase, mol, T, P)\n if self.include_excess_energies:\n S += self._S_excess(phase, mol, T, P)\n return S\n \n def solve_T_at_HP(self, phase, mol, H, T_guess, P):\n \"\"\"Solve for temperature in Kelvin.\"\"\"\n args = (H, self.H, phase, mol, P, self.Cn, [0, None])\n T_guess = flx.aitken(iter_T_at_HP, T_guess, self.T_tol, args, self.maxiter, checkiter=False)\n T = iter_T_at_HP(T_guess, *args)\n return (\n flx.aitken_secant(\n lambda T: self.H(phase, mol, T, P) - H,\n x0=T_guess, x1=T, xtol=self.T_tol, ytol=0.\n )\n if abs(T - T_guess) < self.T_tol else T\n )\n \n def xsolve_T_at_HP(self, phase_mol, H, T_guess, P):\n \"\"\"Solve for temperature in Kelvin.\"\"\"\n phase_mol = tuple(phase_mol)\n args = (H, self.xH, phase_mol, P, self.xCn, [0, None])\n T_guess = flx.aitken(xiter_T_at_HP, T_guess, self.T_tol, args, self.maxiter, checkiter=False)\n T = xiter_T_at_HP(T_guess, *args)\n return (\n flx.aitken_secant(\n lambda T: self.xH(phase_mol, T, P) - H,\n x0=T_guess, x1=T, xtol=self.T_tol, ytol=0.\n )\n if abs(T - T_guess) < self.T_tol else T\n )\n \n def solve_T_at_SP(self, phase, mol, S, T_guess, P):\n \"\"\"Solve for temperature in Kelvin.\"\"\"\n args = (S, self.S, phase, mol, P, self.Cn, [0, None])\n T_guess = flx.aitken(iter_T_at_SP, T_guess, self.T_tol, args, self.maxiter, checkiter=False)\n T = iter_T_at_SP(T_guess, *args)\n return (\n flx.aitken_secant(\n lambda T: self.S(phase, mol, T, P) - S,\n x0=T_guess, x1=T, xtol=self.T_tol, ytol=0.\n )\n if abs(T - T_guess) < self.T_tol else T\n )\n \n def xsolve_T_at_SP(self, phase_mol, S, T_guess, P):\n \"\"\"Solve for temperature in Kelvin.\"\"\"\n phase_mol = tuple(phase_mol)\n args = (S, self.xS, phase_mol, P, self.xCn, [0, None])\n T_guess = flx.aitken(xiter_T_at_SP, T_guess, self.T_tol, args, self.maxiter, checkiter=False)\n T = xiter_T_at_SP(T_guess, *args)\n return (\n flx.aitken_secant(\n lambda T: self.xS(phase_mol, T, P) - S,\n x0=T_guess, x1=T, xtol=self.T_tol, ytol=0.\n )\n if abs(T - T_guess) < self.T_tol else T\n )\n \n def xCn(self, phase_mol, T, P=None):\n \"\"\"Multi-phase mixture molar isobaric heat capacity [J/mol/K].\"\"\"\n return sum([self.Cn(phase, mol, T) for phase, mol in phase_mol])\n \n def xH(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture enthalpy [J/mol].\"\"\"\n H = self._H\n phase_mol = tuple(phase_mol)\n H_total = sum([H(phase, mol, T, P) for phase, mol in phase_mol])\n if self.include_excess_energies:\n H_excess = self._H_excess\n H_total += sum([H_excess(phase, mol, T, P) for phase, mol in phase_mol])\n return H_total\n \n def xS(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture entropy [J/mol/K].\"\"\"\n S = self._S\n phase_mol = tuple(phase_mol)\n S_total = sum([S(phase, mol, T, P) for phase, mol in phase_mol])\n if self.include_excess_energies:\n S_excess = self._S_excess\n S_total += sum([S_excess(phase, mol, T, P) for phase, mol in phase_mol])\n return S_total\n \n def xV(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture molar volume [mol/m^3].\"\"\"\n return sum([self.V(phase, mol, T, P) for phase, mol in phase_mol])\n \n def xmu(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture hydrolic [Pa*s].\"\"\"\n return sum([self.mu(phase, mol, T, P) for phase, mol in phase_mol])\n \n def xkappa(self, phase_mol, T, P):\n \"\"\"Multi-phase mixture thermal conductivity [W/m/K].\"\"\"\n return sum([self.kappa(phase, mol, T, P) for phase, mol in phase_mol])\n \n def __repr__(self):\n return f\"{type(self).__name__}(rule={repr(self.rule)}, ..., include_excess_energies={self.include_excess_energies})\"\n \n def _info(self):\n return (f\"{type(self).__name__}(\\n\"\n f\" rule={repr(self.rule)}, ...\\n\"\n f\" include_excess_energies={self.include_excess_energies}\\n\"\n \")\")\n \n def show(self):\n print(self._info())\n _ipython_display_ = show\n \n","repo_name":"BioSTEAMDevelopmentGroup/thermosteam","sub_path":"thermosteam/mixture/mixture.py","file_name":"mixture.py","file_ext":"py","file_size_in_byte":16117,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"30"} +{"seq_id":"3128750504","text":"import cv2\nimport numpy as np\nimport sys\nimport os\nfrom math import sin,cos,pi,copysign,tan,sqrt,hypot\n\nAREA_THRESHOLD=500\n\nFOV=59\n\nBLOCK=1.5 \n\n\n#Finds the blocks\ndef internal_find_blocks(img):\n hsv = cv2.cvtColor(img, cv2.cv.CV_BGR2HSV)\n\n hsv[:,:,1] = 255\n hsv[:,:,2] = 255\n\n \n hsv=cv2.cvtColor(hsv, cv2.cv.CV_HSV2BGR)\n \n\n for i in range(5):\n hsv = cv2.GaussianBlur(hsv,(3,3),0)\n\n valid = hsv[:,:,0] >= 220\n hsv = np.zeros(np.shape(valid), dtype=np.uint8)\n hsv[valid] = 255\n\n #hsv = cv2.inRange(hsv, (220,0,0), (255,255,255))\n \n contours = cv2.findContours(hsv, cv2.cv.CV_RETR_LIST, cv2.cv.CV_CHAIN_APPROX_SIMPLE)\n \n result=[]\n\n \n\n for c in contours[0]:\n if cv2.contourArea(c)>AREA_THRESHOLD:\n epsilon = 0.01*cv2.arcLength(c,True)\n approx = cv2.approxPolyDP(c,epsilon,True)\n rect = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(rect)\n box = np.int0(box)\n box = np.reshape(box, (4,1,2))\n ratio=cv2.contourArea(approx)/cv2.contourArea(box)\n if 1:#ratio>.75: #THIS IS TO FILTER OUT BAD PARTICLES Not in use.\n rect = cv2.minAreaRect(box)\n elif ratio>.25:\n continue\n\n\n \n result.append(rect)\n return result\n\n#Does math on the blocks\ndef block_math(rect, img, actual_dist=0, centered=False):\n cx=rect[0][0]\n cy=rect[0][1]\n thetad=rect[2]\n theta=thetad/360*2*pi\n w=rect[1][0]/2.0\n h=rect[1][1]/2.0\n if abs(thetad)>45:\n temp=h\n h=w\n w=temp\n theta-=pi/2\n thetad-=90\n thetad+=90\n thetad=copysign(90,thetad)-thetad\n imgh,imgw,_=np.shape(img)\n w*=2\n h*=2\n\n if cx-w/2<10 or cx+w/2>imgw-10:return None\n\n rpp = pi/180*FOV/imgw\n \n dist = 1.5/2/tan(w*FOV*pi/180/imgw/2)\n\n if centered:actual_dist=dist\n \n if cx < imgw/2:\n hoffset = actual_dist * tan((cx-w/2-imgw/2)*rpp) + BLOCK/2\n else:\n hoffset = actual_dist * tan((cx+w/2-imgw/2)*rpp) - BLOCK/2\n\n if cy < imgh/2:\n voffset = actual_dist * tan((cy-h/2-imgh/2)*rpp) + BLOCK/2\n else:\n voffset = actual_dist * tan((cy+h/2-imgh/2)*rpp) - BLOCK/2\n \n return hoffset,-voffset,dist\n\n\n#Returns a list of the lateral offsets for each block found. (inches)\n#You probably want the one closest to 0.\n#Call this first and then compensate\n#Assume distance should be what is reported by the IR/distance sensors in inches\ndef get_lateral_offset(img,assume_dist):\n blocks=internal_find_blocks(img)\n if len(blocks)==0:return -1\n\n results=[]\n \n for rect in blocks: \n coords=block_math(rect,img,assume_dist)\n if coords is not None:results.append(coords[0])\n #return x offset of blocks\n results=sorted(results, key=lambda x: abs(x))\n return results\n\n#Returns coordinates for each block found.\n#Again, probably want the one closest to 0.\n#Call get_lateral_offset first and center.\n# format (dx,dy,dz) in inches from where the arm is now.\ndef get_front_center(img):\n blocks=internal_find_blocks(img)\n if len(blocks)==0:return -1\n\n results=[]\n \n for rect in blocks:\n coords=block_math(rect,img,centered=True)\n if coords is not None:results.append(coords)\n\n results=sorted(results, key=lambda x: abs(x[0]))\n\n return results\n #return location vectors\n\n \n\n\n \n","repo_name":"IEEERobotics/bot","sub_path":"bot/hardware/complex_hardware/generic_blocks.py","file_name":"generic_blocks.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"30"} +{"seq_id":"19192230765","text":"\nt = int(input())\n\nfor i in range(t): \n n = int(input())\n arr = list(map(int, input().split()))\n\n freq_arr = []\n for j in range(1, len(arr)+1): \n freq_arr.append(j*(len(arr) - j + 1))\n\n res = 0\n for j in range(len(arr)): \n if freq_arr[j] % 2!= 0: \n res ^= arr[j]\n\n print(res)","repo_name":"chrislevn/Coding-Challenges","sub_path":"Orange/Bitwise/Sansa_and_XOR.py","file_name":"Sansa_and_XOR.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"250108784","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : OrangeCH3\n# @Time : 2021.10.27 10:41\n# @File : 08-子集问题.py\n# @Project : AGTD\n\n\n# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。\n# 说明:解集不能包含重复的子集。\n\n\nclass Solution(object):\n\n def subsets(self, nums):\n res = []\n path = []\n\n def backtrack(nums, start):\n res.append(path[:]) # 深复制,防止添加过的路径列表发生改变\n\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(nums, i+1)\n path.pop()\n\n backtrack(nums, 0)\n return res\n\n\nif __name__ == '__main__':\n nums = [1, 2, 3]\n s = Solution()\n res = s.subsets(nums)\n print(res)\n\n\n","repo_name":"OrangeCH3/Aphantasia","sub_path":"08-回溯算法/08-子集问题.py","file_name":"08-子集问题.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"5555119656","text":"\nclass Player:\n def __init(user):\n user.entity_numb = 1\n user.lives = 3\n user.can_become_incincible = True\n user.one_hit_kill = False\n user.hit_one_damage = True\n user.move_left_n_right = True\n user.move_up_n_down = True\n user.can_be_hit = True\n\nclass Goomba:\n def __init__(mob):\n mob.entity_numb = 2\n mob.lives = 1\n mob.can_stack = False\n mob.can_become_invincible = False\n mob.one_hit_kill = False\n mob.hit_one_damage = True\n mob.move_left_n_right = True\n mob.move_up_n_down = True\n mob.can_be_hit_above = True\n\n\n\n\nclass MystCube:\n def __init__(cube):\n cube.entity_numb = 1\n mob.lives = 1\n mob.can_stack = False\n mob.can_become_invincible = False\n mob.one_hit_kill = False\n mob.hit_one_damage = False\n mob.move_left_n_right = False\n mob.move_up_n_down = False\n cube.can_be_hit_below = True\n \n","repo_name":"bucs110FALL22/portfolio-Kayla-Elliott","sub_path":"ch06/exercises/gui_classes.py","file_name":"gui_classes.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"16904280853","text":"# !/user/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\ndate: 2021-02-09\nDescription :\nauther : wcy\n\"\"\"\n# import modules\nimport socket\nimport typing\n\n__all__ = []\n\n\n# define function\ndef start_server(port: int) -> typing.NoReturn:\n s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)\n s.bind((socket.gethostname(), port))\n s.listen(backlog=5)\n while 1:\n conn, addr = s.accept()\n msg = conn.recv(1024)\n conn.send(\"receive msg : {}\".format(msg.decode()).encode(\"utf-8\"))\n conn.close()\n\n\n# main\nif __name__ == '__main__':\n start_server(port=8080)\n","repo_name":"JDZW2014/python_full_stack","sub_path":"src/_2_python_base/11_socket/2_tcp_server.py","file_name":"2_tcp_server.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"71570775125","text":"import os, sys\nfrom scipy import array\nfrom Z_MoM import Z_MoM_triangles_arraysFromCube\nfrom ReadWriteBlitzArray import writeBlitzArrayToDisk\nfrom meshClass import CubeClass\nimport copy\n\ndef Z_nearPerCube(path, cube, CFIE, cubeNumber, w, eps_r, mu_r, ELEM_TYPE, Z_TMP_ELEM_TYPE, TDS_APPROX, Z_s, MOM_FULL_PRECISION):\n \"\"\"this function computes the part of the MoM Z matrix corresponding to\n the cube 'cubeNumber' as the observer cube and all its neighbors cubes,\n including itself, as the source cubes.\"\"\"\n # call of the C++ routine for computing the interaction matrix\n Z_CFIE_near_local = Z_MoM_triangles_arraysFromCube(cube, CFIE, w, eps_r, mu_r, TDS_APPROX, Z_s, MOM_FULL_PRECISION)\n # we create a 1-D array out of Z_CFIE_near_local\n Z_CFIE_nearPerCube = array(Z_CFIE_near_local.astype(ELEM_TYPE).flat)\n writeBlitzArrayToDisk(Z_CFIE_near_local.astype(Z_TMP_ELEM_TYPE), os.path.join(path, str(cubeNumber)))\n return Z_CFIE_nearPerCube\n\ndef chunk_of_Z_nearCRS_Computation(CFIE, cubesNumbers, w, eps_r, mu_r, ELEM_TYPE, Z_TMP_ELEM_TYPE, TDS_APPROX, Z_s, MOM_FULL_PRECISION, pathToSaveTo):\n \"\"\"this function computes a chunk of the near non-diagonal part of the MoM matrix,\n but saves all the atomic elements on the disk. These elements will later on be used\n by chunk_of_Z_nearCRS_Assembling and MgPrecondition\"\"\"\n pathToReadCubeFrom = pathToSaveTo\n list_cubes = compute_list_cubes(cubesNumbers, pathToReadCubeFrom)\n for cubeNumber, cube in list_cubes.items():\n Z_CFIE_near_tmp = Z_nearPerCube(pathToSaveTo, cube, CFIE, cubeNumber, w, eps_r, mu_r, ELEM_TYPE, Z_TMP_ELEM_TYPE, TDS_APPROX, Z_s, MOM_FULL_PRECISION)\n\ndef Z_nearCRS_Computation(my_id, processNumber_to_ChunksNumbers, chunkNumber_to_cubesNumbers, CFIE, MAX_BLOCK_SIZE, w, eps_r, mu_r, ELEM_TYPE, Z_TMP_ELEM_TYPE, TDS_APPROX, Z_s, MOM_FULL_PRECISION, pathToSaveTo):\n \"\"\"this function computes Z_CFIE_near by slices and stores them on the disk.\"\"\"\n index, percentage = 0, 0\n for chunkNumber in processNumber_to_ChunksNumbers[my_id]:\n if my_id==0:\n newPercentage = int(index * 100.0/len(processNumber_to_ChunksNumbers[my_id]))\n if (newPercentage - percentage)>=5:\n print(\"Process\", my_id, \": computing Z_CFIE_near chunk.\", newPercentage, \"% completed\")\n sys.stdout.flush()\n percentage = newPercentage\n pathToSaveToChunk = os.path.join(pathToSaveTo, \"chunk\" + str(chunkNumber))\n cubesNumbers = chunkNumber_to_cubesNumbers[chunkNumber]\n chunk_of_Z_nearCRS_Computation(CFIE, cubesNumbers, w, eps_r, mu_r, ELEM_TYPE, Z_TMP_ELEM_TYPE, TDS_APPROX, Z_s, MOM_FULL_PRECISION, pathToSaveToChunk)\n index += 1\n\ndef compute_list_cubes(cubesNumbers, pathToReadFrom):\n \"\"\"returns a list of cubes\"\"\"\n list_cubes = {}\n for i in range(len(cubesNumbers)):\n cubeNumber = cubesNumbers[i]\n pathToReadCubeFrom = pathToReadFrom\n cube = CubeClass()\n cube.setIntArraysFromFile(pathToReadCubeFrom, cubeNumber)\n list_cubes[cubeNumber] = copy.copy(cube)\n return list_cubes\n","repo_name":"Gjacquenot/Puma-EM","sub_path":"code/FMM_Znear.py","file_name":"FMM_Znear.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"30"} +{"seq_id":"33214966573","text":"import os\nfrom time import time, strftime, localtime\n\nimport torch\nimport torch.optim as opt\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.nn.functional import mse_loss, relu\nfrom sklearn.metrics import r2_score\nfrom copy import deepcopy\nimport sys\n\nsys.path.append(\"..\")\nfrom Matformer.msa_dist import build_model\nfrom utils.utils import parse_args, Logger, set_seed\nimport pdb\nfrom pymatgen.core.structure import Structure\nimport numpy as np\nimport pymatgen\n\ndef gen_super_structure(cif):\n \n struc=Structure.from_file(cif)\n coords=struc.cart_coords\n supersize=get_super(coords.shape[0])\n struc.make_supercell(supersize)\n \n dist=struc.distance_matrix\n return dist\n\ndef get_structure(cif):\n \n struc=Structure.from_file(cif)\n \n \n dist=struc.distance_matrix\n return dist\n\ndef get_super(i):\n size=[1,1,1]\n if i<=38:\n size=[3,3,3]\n elif i>38 and i<=57:\n size=[3,3,2]\n elif i>57 and i<=86:\n size=[3,2,2]\n elif i>86 and i<=128:\n size=[2,2,2]\n elif i>128 and i<=256:\n size=[2,2,1]\n elif i>256 and i<=512:\n size=[2,1,1]\n return size\n\n\nclass atomDataset(torch.utils.data.Dataset):\n def __init__(self, data_x,data_y,data_dist):\n self.data_x = data_x\n self.data_y = data_y\n self.data_dist = data_dist\n\n def __getitem__(self, index):\n\n cry = self.data_x[index]\n dist = self.data_dist[index]\n lab = self.data_y[index,:]\n return cry,lab,dist \n\n def __len__(self):\n return len(self.data_x)\n \ndef main():\n args = parse_args()\n save_path='save/'\n log = Logger(save_path + 'coremof_new/', f'msa_{strftime(\"%Y-%m-%d_%H-%M-%S\", localtime())}.log')\n \n \n set_seed(args.seed)\n\n args.dist_bar = [[3, 5, 8, 1e10]]\n args.fnn_dim=2048\n args.batch_size=8\n args.dropout=0.15\n args.embed_dim=512\n\n\n \n target_dict = ['LCD', 'PLD', 'LFPD', 'D', 'ASA', 'ASA', 'NASA', 'NASA', 'AVVF', 'AV', 'NAV', 'CO2', 'CO2']\n target = [0, 1, 3, 5, 8, 9, 12]\n \n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n \n seednum=34\n data_all=torch.load('../pre_data/coremof/coremof_super_all.pt')\n data_all_std=torch.load('../pre_data/coremof/coremof_all.pt')\n a=np.arange(len(data_all[0]))\n train_ratio=0.7\n val_ratio=0.15\n test_ratio=0.15\n \n np.random.seed(seednum)\n np.random.shuffle(a)\n train_idx=a[:int(len(a)*train_ratio)]\n val_idx=a[int(len(a)*train_ratio):-int(len(a)*test_ratio)]\n test_idx=a[-int(len(a)*test_ratio):]\n \n\n\n #for super\n data_x_all=data_all[0]\n data_c_all=torch.tensor([i.numpy() for i in (data_all[2])]).float()/2\n data_c_all = torch.cat((data_c_all, torch.ones(data_c_all.shape[0]).unsqueeze(1).double() * args.atom_class), dim=1) \n data_x_all =[torch.cat((data_c_all[i,:].unsqueeze(0), data_x_all[i]), dim=0) for i in range(len(data_x_all))]\n\n data_x_train = [data_x_all[i] for i in train_idx]\n data_x_val = [data_x_all[i] for i in val_idx]\n data_x_test = [data_x_all[i] for i in test_idx]\n \n data_y_all = torch.tensor([i.numpy() for i in (data_all[1])]).float()\n data_y_train=data_y_all[train_idx]\n data_y_val=data_y_all[val_idx]\n data_y_test=data_y_all[test_idx]\n \n data_cif_all=data_all[5]\n dist_all=[]\n \n f=0\n for cif in data_cif_all:\n if f%100==0:\n print(f)\n dist=gen_super_structure(os.path.join('../pre_data/coremof/coremof', cif+'.cif'))\n dist=np.row_stack((np.zeros(dist.shape[0]),dist))\n dist=np.column_stack((np.zeros(dist.shape[0]),dist))\n dist_all.append(dist)\n f+=1\n\n data_dist_train=[dist_all[i] for i in train_idx]\n data_dist_val=[dist_all[i] for i in val_idx]\n data_dist_test=[dist_all[i] for i in test_idx]\n \n scales = [[data_y_train[:, i].mean().item(), data_y_train[:, i].std().item()] for i in range(data_y_train.shape[-1])]\n for i in range(data_y_train.shape[-1]):\n data_y_train[:, i] = (data_y_train[:, i] - scales[i][0]) / scales[i][1]\n data_y_val[:, i] = (data_y_val[:, i] - scales[i][0]) / scales[i][1]\n data_y_test[:, i] = (data_y_test[:, i] - scales[i][0]) / scales[i][1]\n \n #for std\n data_x_all_std=data_all_std[0]\n data_c_all_std=torch.tensor([i.numpy() for i in (data_all_std[2])]).float()/2\n data_c_all_std = torch.cat((data_c_all_std, torch.ones(data_c_all_std.shape[0]).unsqueeze(1).double() * args.atom_class), dim=1) \n data_x_all_std =[torch.cat((data_c_all_std[i,:].unsqueeze(0), data_x_all_std[i]), dim=0) for i in range(len(data_x_all_std))]\n\n data_x_train_std = [data_x_all_std[i] for i in train_idx]\n \n \n data_y_all_std = torch.tensor([i.numpy() for i in (data_all_std[1])]).float()\n data_y_train_std=data_y_all_std[train_idx]\n \n \n data_cif_all_std=data_all_std[5]\n data_cif_all_std_train=[data_cif_all_std[i] for i in train_idx]\n dist_all_std_train=[]\n \n f=0\n for cif in data_cif_all_std_train:\n if f%100==0:\n print(f)\n dist=get_structure(os.path.join('../pre_data/coremof/coremof', cif+'.cif'))\n dist=np.row_stack((np.zeros(dist.shape[0]),dist))\n dist=np.column_stack((np.zeros(dist.shape[0]),dist))\n dist_all_std_train.append(dist)\n f+=1\n\n \n \n \n for i in range(data_y_train_std.shape[-1]):\n data_y_train_std[:, i] = (data_y_train_std[:, i] - scales[i][0]) / scales[i][1]\n \n data_x_train=data_x_train+data_x_train_std\n del data_x_train_std\n data_y_train=torch.cat((data_y_train,data_y_train_std))\n data_dist_train=data_dist_train+dist_all_std_train \n\n train_dataset=atomDataset(data_x_train, data_y_train,data_dist_train)\n dev_dataset=atomDataset(data_x_val, data_y_val,data_dist_val)\n test_dataset=atomDataset(data_x_test, data_y_test,data_dist_test)\n \n train_loader = DataLoader(train_dataset, batch_size=1,shuffle=True)\n dev_loader = DataLoader(dev_dataset, batch_size=1)\n test_dataset = DataLoader(test_dataset, batch_size=1)\n \n train_size=len(data_x_train)\n val_size=len(data_x_val)\n test_size=len(data_x_test)\n criterion = torch.nn.MSELoss()\n log.logger.info('{} CORE-MOF_expand {}\\nMax_len: {}; Train: {}; Dev: {}; Test: {}\\nTarget: {}\\nGPU: {}; Batch_size: {}; lr: {}; fnn_dim: {}; embed_dim: {}; dropout: {}'\n .format(\"=\" * 40, \"=\" * 40, 0, len(data_x_train), len(data_x_val), len(data_x_test),\n [target_dict[i] for i in target], args.gpu_id, args.batch_size, args.lr, args.fnn_dim, args.embed_dim, args.dropout))\n\n \n log.logger.info('{} Start Training- Dist: {} {}'.format(\"=\" * 40, args.dist_bar, \"=\" * 40))\n best_loss, best_mse = 1e9, 1e9\n t0 = time()\n early_stop = 0\n\n model=build_model(vocab=(args.atom_class + 1), tgt=len(target), dist_bar=args.dist_bar, N=6, embed_dim=args.embed_dim, ffn_dim=args.fnn_dim,dropout=args.dropout).cuda()\n print('model_build_successful!')\n if len(args.gpu_id) > 1: model = torch.nn.DataParallel(model)\n optimizer = opt.Adam(model.parameters(), lr=args.lr)\n lr_scheduler = opt.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.7, patience=10, min_lr=5e-7)\n\n for epoch in range(0,500):\n model.train()\n loss = 0.0\n t1 = time()\n\n for crystal, labels,dist in train_loader:\n dist=dist.cuda()\n crystal=crystal.cuda()\n labels=labels.cuda()# crystal [8, 1024, 4]\n crystal_atom = crystal[..., 3].long() # [8, 1024]\n crystal_pos = crystal[..., :3] # [8, 1024, 3]\n crystal_mask = (crystal_atom != 0).unsqueeze(1) \n pred = model(crystal_atom, crystal_mask, crystal_pos,dist)\n loss_batch = criterion(pred, labels)\n loss += loss_batch.item()\n optimizer.zero_grad()\n loss_batch.backward()\n optimizer.step()\n del pred\n torch.cuda.empty_cache()\n\n model.eval()\n mse = 0\n for crystal, labels,dist in dev_loader:\n crystal=crystal.cuda()\n labels=labels.cuda()\n dist=dist.cuda()\n dev_atom = crystal[..., 3].long()\n dev_mask = (dev_atom != 0).unsqueeze(1)\n dev_pos = crystal[..., :3]\n \n\n \n with torch.no_grad(): pred = model(dev_atom, dev_mask, dev_pos,dist)\n mse += mse_loss(pred[:, -1], labels[:, -1], reduction='sum').item() / test_size * scales[-1][1]\n\n if mse < best_mse:\n best_mse = deepcopy(mse)\n best_model = deepcopy(model)\n best_epoch = epoch + 1\n if loss < best_loss:\n best_loss = deepcopy(loss)\n early_stop = 0\n else:\n early_stop += 1\n log.logger.info('Epoch: {} | Time: {:.1f}s | Loss: {:.2f} | MSE: {:.2f} | Lr: {:.1f}'.\n format(epoch + 1, time() - t1, loss, mse, optimizer.param_groups[0]['lr'] * 1e5))\n if early_stop >= 40:\n log.logger.info(f'Early Stopping!!! No Improvement on Loss for 20 Epochs.')\n break\n lr_scheduler.step(mse)\n test_pred, test_label = [], []\n best_model.eval()\n for crystal, labels,dist in test_dataset:\n dist=dist.cuda()\n crystal=crystal.cuda()\n labels=labels.cuda()\n test_atom = crystal[:, :, 3].long()\n test_mask = (test_atom != 0).unsqueeze(1)\n test_pos = crystal[:, :, :3]\n\n with torch.no_grad():\n pred = best_model(test_atom, test_mask, test_pos,dist)\n test_pred.append(pred)\n test_label.append(labels)\n test_pred = torch.cat(test_pred)\n test_label = torch.cat(test_label)\n\n test_pred[:, -1] = relu(test_pred[:, -1] * scales[-1][1] + scales[-1][0])\n test_label[:, -1] = test_label[:, -1] * scales[-1][1] + scales[-1][0]\n r2 = round(r2_score(test_label[:, -1].cpu().numpy(), test_pred[:, -1].cpu().numpy()), 3)\n log.logger.info(f'Test R2: {r2}\\n\\n')\n \n log.logger.info('{} End Training (Time: {:.2f}h) {}'.format(\"=\" * 40, (time() - t0) / 3600, \"=\" * 40))\n log.logger.info('Dist_bar: {} | Best Epoch: {} | Dev_MSE: {:.2f}'.format(args.dist_bar, best_epoch, best_mse))\n checkpoint = {'model': best_model.state_dict(), 'n_tgt': len(target), 'dist_bar': args.dist_bar,\n 'epochs': best_epoch, 'lr': optimizer.param_groups[0]['lr'],'scales':scales}\n if len(args.gpu_id) > 1: checkpoint['model'] = best_model.module.state_dict()\n torch.save(checkpoint, save_path + 'coremof_new/' + 'Coremof_newpos_Tgt_aug_fnndim{}_embeddim{}_lr{}_batchsize{}_dropout{}.pt'.format(args.fnn_dim,args.embed_dim, args.lr, args.batch_size, args.dropout))\n log.logger.info('Save the best model as Coremof_newpos_Tgt_fnndim{}_embeddim{}_lr{}_batchsize{}_dropout{}.pt'.format(args.fnn_dim,args.embed_dim, args.lr, args.batch_size, args.dropout))\nif __name__ == '__main__':\n main()","repo_name":"DeepSorption/DeepSorption1.0","sub_path":"train_and_predict/CoREMOF/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11078,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"8575492095","text":"import csv\nimport os\nimport pandas as pd\n#clean the weather data, we need to assure that each useful record has at least one attribute about temperature\n#the file is too big so we have chunksize 1000000 and then we use merege.py to link them\ntable = pd.read_csv(\"/home/kkyykk/Desktop/ontario_1_2.csv\",chunksize=1000000,low_memory=False)\ni=0\nos.mkdir(\"/home/kkyykk/Desktop/ontario_1_2\")\nfor data in table:\n #data=data.dropna(axis=0,thresh=14)\n #at least 7 attri to analyse\n data = data[data['Temp...C.'].notnull()]\n clean_data=data.loc[data['X.U.FEFF..Station.Name.'].str.contains('OTTAWA|TORONTO')]\n print(clean_data.head(5))\n if clean_data.empty:\n print(\"eeeeeempty df\")\n continue\n clean_data.to_csv(\"/home/kkyykk/Desktop/ontario_1_2/ontario_1_2--\"+str(i)+\".csv\")\n i=i+1\n","repo_name":"jinyanghuang/data-warehouse","sub_path":"collision_weather/Weather_Clean.py","file_name":"Weather_Clean.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"17164204789","text":"import gc\nimport multiprocessing\nimport os\nimport signal\nimport socket\nfrom queue import Empty\nfrom time import sleep\n\nimport requests\nfrom honcho.process import Process\n\n\ndef get_free_port():\n \"\"\"Get free port.\"\"\"\n sock = socket.socket()\n sock.bind((\"localhost\", 0))\n port = sock.getsockname()[1]\n sock.close()\n del sock\n gc.collect()\n return port\n\n\ndef test_create_file(tmpdir):\n old_wd = os.getcwd()\n os.chdir(str(tmpdir))\n print(str(tmpdir))\n try:\n os.system(\"python -m django_zero create --no-input project foo\")\n print(str(tmpdir.join(\"foo\")))\n os.chdir(str(tmpdir.join(\"foo\")))\n\n # TODO: move back into make install\n os.system(\"python -m django_zero install\")\n os.system(\"yarn install\")\n\n os.system(\"python -m django_zero manage migrate\")\n\n # Run the webpack assets builder\n os.system(\"python -m django_zero webpack\")\n\n target = \"127.0.0.1\", get_free_port()\n print(\"Target:\", *target)\n\n events = multiprocessing.Queue()\n server_command = \"python -m django_zero manage runserver {0}:{1}\".format(*target)\n print(\"Command:\", server_command)\n server = Process(server_command, name=\"server\")\n server_process = multiprocessing.Process(name=\"server\", target=server.run, args=(events, True))\n\n try:\n server_process.start()\n exit = False\n pid = None\n\n while 1:\n try:\n msg = events.get(timeout=0.1)\n except Empty:\n if exit:\n break\n else:\n # print(msg)\n if msg.type == \"start\":\n pid = msg.data[\"pid\"]\n\n conn_ok = False\n for i in range(10):\n try:\n s = socket.create_connection(target, 1)\n s.close()\n conn_ok = True\n except socket.error:\n sleep(1)\n assert conn_ok\n\n try:\n target = \"http://{}:{}\".format(*target)\n resp = requests.get(target + \"/\")\n assert resp.status_code == 200\n\n resp = requests.get(target + \"/static/bootstrap.css\")\n assert resp.status_code == 200\n\n resp = requests.get(target + \"/static/bootstrap.js\")\n assert resp.status_code == 200\n finally:\n os.killpg(pid, signal.SIGKILL)\n elif msg.type == \"line\":\n print(\">>>\", msg.data.decode(\"utf-8\"), end=\"\")\n elif msg.type == \"stop\":\n pid = None\n exit = True\n finally:\n server_process.terminate()\n server_process.join(timeout=2)\n if server_process.is_alive() and pid:\n try:\n os.killpg(pid, signal.SIGTERM)\n except ProcessLookupError:\n pass\n\n finally:\n os.chdir(old_wd)\n","repo_name":"django-zero/django-zero","sub_path":"tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"30"} +{"seq_id":"7531763549","text":"import random\n\noptions = [ [\"Pregunta 1: Dis-me l'arrel de quadrada de 4.\",\"1. 1.5\\n2. 2\\n3. 5\",2],\n [\"Pregunta 2: Dis-me l'arrel de quadrada de 16.\",\"1. 4\\n2. 2\\n3. 6\",1,],\n [\"Pregunta 3: Quin és el record dels 100 metros llisos en segons?\",\"1. 9,58\\n2. 10\\n3. 9,78\",1],\n [\"Pregunta 4: Quants milions de persones viuen a españa?\",\"1. 47\\n2. 50\\n3. 55\",1],\n [\"Pregunta 5: En quin segle estem?\",\"1. 22\\n2. 20\\n3. 21\",3],\n [\"Pregunta 6: Quin nivell d'anglès és el més alt?\",\"1. C2\\n2. C1\\n3. B2\",1],\n [\"Pregunta 7: Quin edifici és el més alt del món?\",\"1. Burj Khalifa\\n2. Torre de Shanghái\\n3. One World Trade Center\",1],\n [\"Pregunta 8: En quin any va acabar la segona guerra mundial?\",\"1. 1934\\n2. 1945\\n3. 1915\",2],\n [\"Pregunta 9: Quin és millor mestre d'ASIX?\",\"1. Mireia\\n2. Jordi Varas\\n3. Gonçal\",3],\n [\"Pregunta 10: Dis-me l'arrel quadrada de 25.\",\"1. 7\\n2. 5\\n3. 6\",2] ]\n\nvictoria_j1 = 0\nvictoria_j2 = 0\nvictoria_j3 = 0\nvictoria_j4 = 0\n\nwhile True:\n partida = input(\"Amb quants jugadors vols jugar?\\n Per triar una partida de dos jugadors escriu '2'\\n Per triar una partida de quatre jugadors escriu '4'\\n Elecció: \")\n if partida == \"2\":\n torn = random.randint(1, 2)\n break\n elif partida == \"4\":\n torn = random.randint(1, 4)\n print (torn)\n break\n else:\n print(\"Escriu correctament el nombre de jugadors!\")\n continue\n\nwhile True:\n if (victoria_j1 > 2) or (victoria_j2 > 2) or (victoria_j3 > 2) or (victoria_j4 > 2):\n print (\"Ha guanyat el jugador\",torn)\n break\n elif len(options) != 0:\n aleatori = random.choice(options)\n response = options.index(aleatori)\n print (aleatori[0]+\"\\n\"+aleatori[1])\n if torn == 1:\n answer = int(input(\"Jugador 1 (RESPOSTA): \"))\n if answer == aleatori[2]:\n victoria_j1 += 1\n print(\"Resposta correcta!\\n --- MARCADOR ---\\n Preguntes encertades :\",victoria_j1);\n else: \n print(\"Resposta incorrecta!\")\n torn = 2\n elif torn == 2:\n answer = int(input(\"Jugador 2 (RESPOSTA): \"))\n if answer == aleatori[2]:\n victoria_j2 += 1\n print(\"Resposta correcta!\\n --- MARCADOR ---\\n Preguntes encertades :\",victoria_j2);\n else: \n print(\"Resposta incorrecta!\")\n torn = 3\n elif torn == 3:\n answer = int(input(\"Jugador 3 (RESPOSTA): \"))\n if answer == aleatori[2]:\n victoria_j3 += 1\n print(\"Resposta correcta!\\n --- MARCADOR ---\\n Preguntes encertades :\",victoria_j3);\n else: \n print(\"Resposta incorrecta!\")\n torn = 4\n elif torn == 4:\n answer = int(input(\"Jugador 4 (RESPOSTA): \"))\n if answer == aleatori[2]:\n victoria_j4 += 1\n print(\"Resposta correcta!\\n --- MARCADOR ---\\n Preguntes encertades :\",victoria_j4);\n else: \n print(\"Resposta incorrecta!\")\n torn = 1\n del options[response]\n else:\n print(\"No hi ha més preguntes, el joc s'acabat\")\n break\n\n'''#Dos jugadors, el primer que encerta 3 preguntes guanya!!'''\n'''#El format de les preguntes serà:\n#Enunciat pregunta:\n#Resposta 1\n#Resposta 2\n#Resposta 3'''\n'''#S'ha de mostrar un marcador de preguntes encertades per cada jugador.'''\n'''# Cada jugador anirà responent preguntes fins que falli.'''\n'''#El torn d'inici serà aleatori.'''\n'''#Si S'han realitzat 10 preguntes i no hi ha guanyador el joc acaba.'''\n'''#Les preguntes es mostraran en ordre aleatori.'''\n'''#Heu de controlar quines preguntes ja s'han plantejat als jugadors.'''\n\n#OPCIONAL:\n#Les respostes es mostraran en ordre aleatori.\n'''#Podem escollir el nombre de jugadors entre 2 i 4'''","repo_name":"EricSefo/Python","sub_path":"UF1/Projecte_old.py","file_name":"Projecte_old.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"ca","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71743397481","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nYou're now a baseball game point recorder.\n\nGiven a list of strings, each string can be one of the 4 following types:\n\nInteger (one round's score): Directly represents the number of points you get in this round.\n\"+\" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.\n\"D\" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.\n\"C\" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.\nEach round's operation is permanent and could have an impact on the round before and the round after.\n\nYou need to return the sum of the points you could get in all the rounds.\n\nExample 1:\nInput: [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput: 30\nExplanation:\nRound 1: You could get 5 points. The sum is: 5.\nRound 2: You could get 2 points. The sum is: 7.\nOperation 1: The round 2's data was invalid. The sum is: 5.\nRound 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.\nRound 4: You could get 5 + 10 = 15 points. The sum is: 30.\nExample 2:\nInput: [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput: 27\nExplanation:\nRound 1: You could get 5 points. The sum is: 5.\nRound 2: You could get -2 points. The sum is: 3.\nRound 3: You could get 4 points. The sum is: 7.\nOperation 1: The round 3's data is invalid. The sum is: 3.\nRound 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.\nRound 5: You could get 9 points. The sum is: 8.\nRound 6: You could get -4 + 9 = 5 points. The sum is 13.\nRound 7: You could get 9 + 5 = 14 points. The sum is 27.\nNote:\nThe size of the input list will be between 1 and 1000.\nEvery integer represented in the list will be between -30000 and 30000.\n\"\"\"\n\n\nclass Solution(object):\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n return self.ans(ops)\n\n def ans(self, ops):\n symbles = (\"+\", \"C\", \"D\")\n stack = []\n for item in ops:\n if item not in symbles:\n stack.append(int(item))\n else:\n self.stack_operation(item, stack)\n\n return sum(stack)\n\n def stack_operation(self, operator, stack):\n if operator == \"C\":\n stack.pop()\n elif operator == \"D\":\n top = stack[-1]\n stack.append(top * 2)\n elif operator == \"+\":\n first = stack[-1]\n second = stack[-2]\n stack.append(first + second)\n else:\n raise ValueError\n\n\nif __name__ == \"__main__\":\n test_input = [\"5\",\"2\",\"C\",\"D\",\"+\"]\n test_input = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\n print(Solution().calPoints(test_input))\n\n\n","repo_name":"buxizhizhoum/leetcode","sub_path":"baseball_game.py","file_name":"baseball_game.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"71427454440","text":"import numpy as np\n\nimport pandas as pd\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom pandas.io.json import json_normalize\n\nimport json\n\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\n\nfrom sklearn.preprocessing import Imputer\n\nfrom sklearn import preprocessing\n\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\ntrain = pd.read_csv('../input/train.csv',dtype={'fullVisitorId': 'str'})\ntest = pd.read_csv('../input/test.csv',dtype={'fullVisitorId': 'str'})\nprint(train.head())\ntrain_device = pd.DataFrame(list(train.device.apply(json.loads)))\ntrain_geoNetwork = pd.DataFrame(list(train.geoNetwork.apply(json.loads)))\ntrain_totals = pd.DataFrame(list(train.totals.apply(json.loads)))\ntrain_trafficSource = pd.DataFrame(list(train.trafficSource.apply(json.loads)))\ntrain_trafficSource_adwordsClickInfo = pd.DataFrame(list(train_trafficSource['adwordsClickInfo'].apply(json.dumps).apply(json.loads)))\n\ntest_device = pd.DataFrame(list(test.device.apply(json.loads)))\ntest_geoNetwork = pd.DataFrame(list(test.geoNetwork.apply(json.loads)))\ntest_totals = pd.DataFrame(list(test.totals.apply(json.loads)))\ntest_trafficSource = pd.DataFrame(list(test.trafficSource.apply(json.loads)))\ntest_trafficSource_adwordsClickInfo = pd.DataFrame(list(test_trafficSource['adwordsClickInfo'].apply(json.dumps).apply(json.loads)))\ntrain = pd.concat(\n [\n train[\n [\n 'channelGrouping',\n 'date',\n 'fullVisitorId',\n 'sessionId',\n 'socialEngagementType',\n 'visitId',\n 'visitNumber',\n 'visitStartTime'\n ]\n ],\n train_device,\n train_geoNetwork,\n train_totals,\n train_trafficSource,\n train_trafficSource_adwordsClickInfo\n ],\n axis = 1\n)\n\n# columns with no data or are JSON columns which have been flattened\ntrain = train.drop(\n [\n 'socialEngagementType',\n 'browserSize',\n 'browserVersion',\n 'flashVersion',\n 'mobileDeviceBranding',\n 'mobileDeviceInfo',\n 'mobileDeviceMarketingName',\n 'mobileDeviceModel',\n 'mobileInputSelector',\n 'operatingSystemVersion',\n 'screenColors',\n 'screenResolution',\n 'cityId',\n 'latitude',\n 'longitude',\n 'networkLocation',\n 'adNetworkType',\n 'criteriaParameters',\n 'gclId',\n 'isVideoAd',\n 'page',\n 'slot',\n 'targetingCriteria',\n 'adwordsClickInfo'\n ],\n axis = 1\n)\n\ntest = pd.concat(\n [\n test[[\n 'channelGrouping',\n 'date',\n 'fullVisitorId',\n 'sessionId',\n 'socialEngagementType',\n 'visitId',\n 'visitNumber',\n 'visitStartTime'\n ]],\n test_device,\n test_geoNetwork,\n test_totals,\n test_trafficSource,\n test_trafficSource_adwordsClickInfo\n ], \n axis = 1\n)\n\n# columns with no data or are JSON columns which have been flattened\ntest = test.drop(\n [\n 'socialEngagementType',\n 'browserSize',\n 'browserVersion',\n 'flashVersion',\n 'mobileDeviceBranding',\n 'mobileDeviceInfo',\n 'mobileDeviceMarketingName',\n 'mobileDeviceModel',\n 'mobileInputSelector',\n 'operatingSystemVersion',\n 'screenColors',\n 'screenResolution',\n 'cityId',\n 'latitude',\n 'longitude',\n 'networkLocation',\n 'adNetworkType',\n 'criteriaParameters',\n 'gclId',\n 'isVideoAd',\n 'page',\n 'slot',\n 'targetingCriteria',\n 'adwordsClickInfo'\n ],\n axis = 1\n)\n\ndel train_device\ndel train_geoNetwork\ndel train_totals\ndel train_trafficSource\ndel train_trafficSource_adwordsClickInfo\ndel test_device\ndel test_geoNetwork\ndel test_totals\ndel test_trafficSource\ndel test_trafficSource_adwordsClickInfo\ntrain['visitStartTime'].astype(str).astype(int)\ntrain['visitId'].astype(str).astype(int)\ntrain['transactionRevenue'].fillna(value = '0', inplace = True)\ntrain['transactionRevenue'] = train['transactionRevenue'].astype(int)\ntrain['visitNumber'].astype(str).astype(int)\ntrain['hits'] = train['hits'].astype(int)\ntrain['pageviews'].fillna(value = '0', inplace = True)\ntrain['pageviews'] = train['pageviews'].astype(int)\n\ntest['visitStartTime'].astype(str).astype(int)\ntest['visitId'].astype(str).astype(int)\ntest['visitNumber'].astype(str).astype(int)\ntest['hits'] = test['hits'].astype(int)\ntest['pageviews'].fillna(value = '0', inplace = True)\ntest['pageviews'] = test['pageviews'].astype(int)\nunique_vals = train.nunique().sort_values(ascending = False)\nunique_vals = unique_vals.to_frame()\nunique_vals = unique_vals.reset_index()\nunique_vals.columns = ['column', 'cnt']\n\ndtypes = train.dtypes.to_frame()\ndtypes = dtypes.reset_index()\ndtypes.columns = ['column', 'type']\n\nprofile = pd.merge(\n unique_vals,\n dtypes,\n on = 'column',\n how = 'inner'\n)\n\nprint(profile.loc[profile['type'] == 'object'])\nnetworkDomain_encoder = preprocessing.LabelEncoder()\nkeyword_encoder = preprocessing.LabelEncoder()\nreferralPath_encoder = preprocessing.LabelEncoder()\ncity_encoder = preprocessing.LabelEncoder()\nvisitNumber_encoder = preprocessing.LabelEncoder()\nsource_encoder = preprocessing.LabelEncoder()\nregion_encoder = preprocessing.LabelEncoder()\ndate_encoder = preprocessing.LabelEncoder()\ncountry_encoder = preprocessing.LabelEncoder()\nmetro_encoder = preprocessing.LabelEncoder()\nbrowser_encoder = preprocessing.LabelEncoder()\nadContent_encoder = preprocessing.LabelEncoder()\nsubContinent_encoder = preprocessing.LabelEncoder()\noperatingSystem_encoder = preprocessing.LabelEncoder()\ncampaign_encoder = preprocessing.LabelEncoder()\n\nnetworkDomain_encoder.fit(train['networkDomain'])\ntrain['keyword'].fillna(value = '0', inplace = True)\nkeyword_encoder.fit(train['keyword'])\ntrain['referralPath'].fillna(value = '0', inplace = True)\nreferralPath_encoder.fit(train['referralPath'])\ncity_encoder.fit(train['city'])\nvisitNumber_encoder.fit(train['visitNumber'])\nsource_encoder.fit(train['source'])\nregion_encoder.fit(train['region'])\ndate_encoder.fit(train['date'])\ncountry_encoder.fit(train['country'])\nmetro_encoder.fit(train['metro'])\nbrowser_encoder.fit(train['browser'])\n\ntrain['adContent'].fillna(value = '0', inplace = True)\nadContent_encoder.fit(train['adContent'])\nsubContinent_encoder.fit(train['subContinent'])\noperatingSystem_encoder.fit(train['operatingSystem'])\ncampaign_encoder.fit(train['campaign'])\n\ntrain['networkDomain_encoder'] = networkDomain_encoder.transform(train['networkDomain'])\ntrain['keyword_encoder'] = keyword_encoder.transform(train['keyword'])\ntrain['referralPath_encoder'] = referralPath_encoder.transform(train['referralPath'])\ntrain['city_encoder'] = city_encoder.transform(train['city'])\ntrain['visitNumber_encoder'] = visitNumber_encoder.transform(train['visitNumber'])\ntrain['source_encoder'] = source_encoder.transform(train['source'])\ntrain['region_encoder'] = region_encoder.transform(train['region'])\ntrain['date_encoder'] = date_encoder.transform(train['date'])\ntrain['country_encoder'] = country_encoder.transform(train['country'])\ntrain['metro_encoder'] = metro_encoder.transform(train['metro'])\ntrain['browser_encoder'] = browser_encoder.transform(train['browser'])\ntrain['adContent_encoder'] = adContent_encoder.transform(train['adContent'])\ntrain['subContinent_encoder'] = subContinent_encoder.transform(train['subContinent'])\ntrain['operatingSystem_encoder'] = operatingSystem_encoder.transform(train['operatingSystem'])\ntrain['campaign_encoder'] = campaign_encoder.transform(train['campaign'])\n\ntest_networkDomain_encoder = preprocessing.LabelEncoder()\ntest_keyword_encoder = preprocessing.LabelEncoder()\ntest_referralPath_encoder = preprocessing.LabelEncoder()\ntest_city_encoder = preprocessing.LabelEncoder()\ntest_visitNumber_encoder = preprocessing.LabelEncoder()\ntest_source_encoder = preprocessing.LabelEncoder()\ntest_region_encoder = preprocessing.LabelEncoder()\ntest_date_encoder = preprocessing.LabelEncoder()\ntest_country_encoder = preprocessing.LabelEncoder()\ntest_metro_encoder = preprocessing.LabelEncoder()\ntest_browser_encoder = preprocessing.LabelEncoder()\ntest_adContent_encoder = preprocessing.LabelEncoder()\ntest_subContinent_encoder = preprocessing.LabelEncoder()\ntest_operatingSystem_encoder = preprocessing.LabelEncoder()\ntest_campaign_encoder = preprocessing.LabelEncoder()\n\ntest['keyword'].fillna(value = '0', inplace = True)\ntest_keyword_encoder.fit(test['keyword'])\n\ntest['referralPath'].fillna(value = '0', inplace = True)\ntest_referralPath_encoder.fit(test['referralPath'])\ntest_city_encoder.fit(test['city'])\ntest_visitNumber_encoder.fit(test['visitNumber'])\ntest_source_encoder.fit(test['source'])\ntest_region_encoder.fit(test['region'])\ntest_date_encoder.fit(test['date'])\ntest_country_encoder.fit(test['country'])\ntest_metro_encoder.fit(test['metro'])\ntest_browser_encoder.fit(test['browser'])\ntest_networkDomain_encoder.fit(test['networkDomain'])\ntest['adContent'].fillna(value = '0', inplace = True)\ntest_adContent_encoder.fit(test['adContent'])\ntest_subContinent_encoder.fit(test['subContinent'])\ntest_operatingSystem_encoder.fit(test['operatingSystem'])\ntest_campaign_encoder.fit(test['campaign'])\n\ntest['networkDomain_encoder'] = test_networkDomain_encoder.transform(test['networkDomain'])\ntest['keyword_encoder'] = test_keyword_encoder.transform(test['keyword'])\ntest['referralPath_encoder'] = test_referralPath_encoder.transform(test['referralPath'])\ntest['city_encoder'] = test_city_encoder.transform(test['city'])\ntest['visitNumber_encoder'] = test_visitNumber_encoder.transform(test['visitNumber'])\ntest['source_encoder'] = test_source_encoder.transform(test['source'])\ntest['region_encoder'] = test_region_encoder.transform(test['region'])\ntest['date_encoder'] = test_date_encoder.transform(test['date'])\ntest['country_encoder'] = test_country_encoder.transform(test['country'])\ntest['metro_encoder'] = test_metro_encoder.transform(test['metro'])\ntest['browser_encoder'] = test_browser_encoder.transform(test['browser'])\ntest['adContent_encoder'] = test_adContent_encoder.transform(test['adContent'])\ntest['subContinent_encoder'] = test_subContinent_encoder.transform(test['subContinent'])\ntest['operatingSystem_encoder'] = test_operatingSystem_encoder.transform(test['operatingSystem'])\ntest['campaign_encoder'] = test_campaign_encoder.transform(test['campaign'])\ntrain_one_hot = train[\n [\n 'channelGrouping',\n 'deviceCategory',\n 'isMobile',\n 'language',\n 'continent',\n 'medium',\n 'newVisits',\n 'visits',\n 'campaignCode',\n 'isTrueDirect',\n 'bounces'\n ]\n]\n\ntrain_one_hot = pd.get_dummies(train_one_hot)\n\ntrain = pd.concat(\n [\n train,\n train_one_hot\n ],\n axis = 1\n)\n\ntest_one_hot = test[\n [\n 'channelGrouping',\n 'deviceCategory',\n 'isMobile',\n 'language',\n 'continent',\n 'medium',\n 'newVisits',\n 'visits',\n 'isTrueDirect',\n 'bounces'\n ]\n]\n\ntest_one_hot = pd.get_dummies(test_one_hot)\n\ntest = pd.concat(\n [\n test,\n test_one_hot\n ],\n axis = 1\n)\n\ndel train_one_hot\ndel test_one_hot\ntrain['date'] = pd.to_datetime(train['date'], format = '%Y%m%d')\ntrain['month'] = pd.DatetimeIndex(train['date']).month\ntrain['year'] = pd.DatetimeIndex(train['date']).year\ntrain['day'] = pd.DatetimeIndex(train['date']).day\ntrain['quarter'] = pd.DatetimeIndex(train['date']).quarter\ntrain['weekday'] = pd.DatetimeIndex(train['date']).weekday\ntrain['weekofyear'] = pd.DatetimeIndex(train['date']).weekofyear\ntrain['is_month_start'] = pd.DatetimeIndex(train['date']).is_month_start\ntrain['is_month_end'] = pd.DatetimeIndex(train['date']).is_month_end\ntrain['is_quarter_start'] = pd.DatetimeIndex(train['date']).is_quarter_start\ntrain['is_quarter_end'] = pd.DatetimeIndex(train['date']).is_quarter_end\ntrain['is_year_start'] = pd.DatetimeIndex(train['date']).is_year_start\ntrain['is_year_end'] = pd.DatetimeIndex(train['date']).is_year_end\nprint(train[['month','day','year','quarter','weekday','weekofyear','date']].head())\n\ntest['date'] = pd.to_datetime(test['date'], format = '%Y%m%d')\ntest['month'] = pd.DatetimeIndex(test['date']).month\ntest['year'] = pd.DatetimeIndex(test['date']).year\ntest['day'] = pd.DatetimeIndex(test['date']).day\ntest['quarter'] = pd.DatetimeIndex(test['date']).quarter\ntest['weekday'] = pd.DatetimeIndex(test['date']).weekday\ntest['weekofyear'] = pd.DatetimeIndex(test['date']).weekofyear\ntest['is_month_start'] = pd.DatetimeIndex(test['date']).is_month_start\ntest['is_month_end'] = pd.DatetimeIndex(test['date']).is_month_end\ntest['is_quarter_start'] = pd.DatetimeIndex(test['date']).is_quarter_start\ntest['is_quarter_end'] = pd.DatetimeIndex(test['date']).is_quarter_end\ntest['is_year_start'] = pd.DatetimeIndex(test['date']).is_year_start\ntest['is_year_end'] = pd.DatetimeIndex(test['date']).is_year_end\nprint(test[['month','day','year','quarter','weekday','weekofyear','date']].head())\ntrain['visitStartTime'] = pd.to_datetime(train['visitStartTime'], unit = 's')\ntrain['hour'] = pd.DatetimeIndex(train['visitStartTime']).hour\ntrain['minute'] = pd.DatetimeIndex(train['visitStartTime']).minute\nprint(train[['visitStartTime','hour','minute']].head())\n\ntest['visitStartTime'] = pd.to_datetime(test['visitStartTime'], unit = 's')\ntest['hour'] = pd.DatetimeIndex(test['visitStartTime']).hour\ntest['minute'] = pd.DatetimeIndex(test['visitStartTime']).minute\nprint(test[['visitStartTime','hour','minute']].head())\ntrain_staging = train.select_dtypes(exclude = 'object')\ntrain_staging = train_staging.select_dtypes(exclude = 'datetime')\ntrain_staging = train_staging.select_dtypes(exclude = 'bool')\n\nprint(train_staging.dtypes)\n\ntest_staging = test.select_dtypes(exclude = 'object')\ntest_staging = test_staging.select_dtypes(exclude = 'datetime')\ntest_staging = test_staging.select_dtypes(exclude = 'bool')\n\nprint(test_staging.dtypes)\ntrain_staging_columns = train_staging.columns\n\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(strategy = 'mean')\ntrain_staging = imputer.fit_transform(train_staging)\ntrain_staging = pd.DataFrame(\n data = train_staging,\n columns = train_staging_columns\n)\nprint(train_staging.isna().any())\n\ntest_staging_columns = test_staging.columns\n\ntest_staging = imputer.fit_transform(test_staging)\ntest_staging = pd.DataFrame(\n data = test_staging,\n columns = test_staging_columns\n)\nprint(test_staging.isna().any())\ntrain_staging, test_staging = train_staging.align(test_staging, join = 'inner', axis = 1)\ntrain_staging['transactionRevenue'] = train['transactionRevenue']\ntest_staging['fullVisitorId'] = test['fullVisitorId']\ntrain_staging['fullVisitorId'] = train['fullVisitorId']\nprint(train_staging.head())\ntrain_agg = train_staging \\\n .groupby(['fullVisitorId']) \\\n .agg(['count','mean','min','max','sum']) \\\n .reset_index()\n\ntest_agg = test_staging \\\n .groupby(['fullVisitorId']) \\\n .agg(['count','mean','min','max','sum']) \\\n .reset_index()\ncolumns_train = ['fullVisitorId']\n\n# Convert multi-level index from .agg() into clean columns\n# borrowing from: https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering\nfor var in train_agg.columns.levels[0]:\n if var != 'fullVisitorId':\n for stat in train_agg.columns.levels[1][:-1]:\n columns_train.append('%s_%s' % (var, stat))\n\ntrain_agg.columns = columns_train\n\ncolumns_test = ['fullVisitorId']\n\n# Convert multi-level index from .agg() into clean columns\n# borrowing from: https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering\nfor var in test_agg.columns.levels[0]:\n if var != 'fullVisitorId':\n for stat in test_agg.columns.levels[1][:-1]:\n columns_test.append('%s_%s' % (var, stat))\n\ntest_agg.columns = columns_test\ndel train_staging\ndel train\n\ndel test_staging\ndel test\nprint(train_agg.dtypes)\nimport math\n\ndef create_target(rev):\n if rev == 0:\n return 0\n else:\n return math.log(rev)\n\ntrain_agg['TARGET'] = train_agg['transactionRevenue_sum'].apply(create_target)\n\ntrain_agg = train_agg.drop(\n [\n 'transactionRevenue_count',\n 'transactionRevenue_mean',\n 'transactionRevenue_min',\n 'transactionRevenue_max',\n 'transactionRevenue_sum'\n ],\n axis = 1\n)\ntrain_agg_corr = train_agg.corr()\nprint(train_agg_corr['TARGET'].sort_values(ascending = False))\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nid_train = train_agg['fullVisitorId']\nx = train_agg.drop(['TARGET','fullVisitorId'], axis = 1)\ny = train_agg['TARGET']\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.33, random_state = 0)\n\nmodel = RandomForestRegressor()\nmodel.fit(x_train, y_train)\npredictions = model.predict(x_test)\n\nrms = sqrt(mean_squared_error(y_test, predictions))\n\nprint('RMSE train:', rms)\nimportances = model.feature_importances_\nimportances_df = pd.DataFrame(\n data = {'column' : x.columns, 'importance' : importances}\n)\n\nimportances_df = importances_df.sort_values(by = 'importance', ascending = False)\n\nimportances_df['weighted'] = importances_df['importance'] / importances_df['importance'].sum()\n\nplt.figure()\nplt.title('Feature Importances')\nplt.barh(\n importances_df['column'].head(15),\n importances_df['weighted'].head(15)\n)\nplt.show()\ndel train_agg\ndel Imputer\ndel RandomForestRegressor\ndel adContent_encoder\ndel auc\ndel browser_encoder\ndel campaign_encoder \ndel city_encoder \ndel columns_test \ndel columns_train\ndel country_encoder, create_target, date_encoder, imputer, json, json_normalize, keyword_encoder, math, metro_encoder, networkDomain_encoder, operatingSystem_encoder, parameters, plt, preprocessing\ndel referralPath_encoder\ndel region_encoder\ndel sns\ndel source_encoder\ndel stat\ndel subContinent_encoder\ndel test_adContent_encoder\ndel test_browser_encoder\ndel test_campaign_encoder\ndel test_city_encoder\ndel test_country_encoder\ndel test_date_encoder\ndel test_keyword_encoder\ndel test_metro_encoder\ndel test_networkDomain_encoder \ndel test_operatingSystem_encoder\ndel test_referralPath_encoder\ndel test_region_encoder\ndel test_source_encoder\ndel test_staging_columns\ndel test_subContinent_encoder\ndel test_visitNumber_encoder\ndel train_staging_columns\ndel train_test_split\ndel var\ndel visitNumber_encoder\ndel warnings\n#import lightgbm as lightgbm\n#from sklearn.model_selection import train_test_split\n#from math import sqrt\n#from sklearn.metrics import mean_squared_error\n\n#x_train = lightgbm.Dataset(x_train)\n#y_train = lightgbm.Dataset(y_train)\n\n#parameters = {\n# 'num_leaves':31,\n# 'colsample_bytree' : .9,\n# 'metric':'l2_root',\n# 'learning_rate':0.03,\n# 'subsample' : 0.9, \n# 'random_state' : 1,\n# 'n_estimators': 1000\n#}\n\n#lgbm = lightgbm.train(\n# parameters,\n# x_train,\n# y_train\n#)\n\n#p = lgbm.predict(x_test)\n\n#rms = sqrt(mean_squared_error(y_test, p))\n\n#print('LGBM RMSE train:', rms)\npredictions_test = model.predict(test_agg.drop(['fullVisitorId'], axis = 1))\n\nsubmission = pd.DataFrame({\n \"fullVisitorId\": test_agg['fullVisitorId'].astype(str),\n \"PredictedLogRevenue\": predictions_test\n })\n\nsubmission['fullVisitorId'] = submission['fullVisitorId'].astype(str)\n\nimport csv\n\nsubmission.to_csv('submission_rf.csv', quoting=csv.QUOTE_NONNUMERIC, index = False)\n#predictions_test_lgbm = lgbm.predict(test_agg.drop(['fullVisitorId'], axis = 1))\n\n#submission_lgbm = pd.DataFrame({\n# \"fullVisitorId\": test_agg['fullVisitorId'].astype(str),\n# \"PredictedLogRevenue\": predictions_test_lgbm\n# })\n\n#submission_lgbm['fullVisitorId'] = submission_lgbm['fullVisitorId'].astype(str)\n\n#import csv\n\n#submission_lgbm.to_csv('submission_lgbm.csv', quoting=csv.QUOTE_NONNUMERIC, index = False)","repo_name":"aorursy/new-nb-3","sub_path":"jacksmengel_gstore-random-forest-walkthrough.py","file_name":"jacksmengel_gstore-random-forest-walkthrough.py","file_ext":"py","file_size_in_byte":20137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5187678889","text":"'''\nCheck whether a given term represents a binary tree\n Write a predicate istree which returns true if and only if its argument is a list representing a binary tree.\n Example:\n * (istree (a (b nil nil) nil))\n T\n * (istree (a (b nil nil)))\n NIL\n'''\n\n\ndef isTree(tree):\n if len(tree) != 3: # checking if subtree or tree contains all root ,left and right nodes or not\n return False # if not then it is nit a binary tree\n for node in tree:\n if isinstance(node, list): # checking further nodes present or not\n if not isTree(node): # then recursive calling with subtree\n return False\n\n return True\n\n\n# declaring two trees in a form of list nested list represents subtree\ntree_1 = ['a', ['b', None, None]]\ntree_2 = ['a', ['b', None, None], None]\n\nprint(isTree(tree_1))\nprint(isTree(tree_2))\n","repo_name":"gauravdaunde/training-assignments","sub_path":"99Problems/Trees/P54.py","file_name":"P54.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20281621285","text":"#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\n\r\n\"\"\"#函数\"\"\"\r\n#语法:\r\ndef fun(str):\r\n print(str)\r\n return\r\n#调用函数,函数的参数不能为空,为空将会报错\r\nfun(\"hello\")\r\nfun(str=\"meng\")\r\n\r\n\r\n\"\"\"传可变对象\"\"\"\r\n# 可写函数说明\r\ndef changeme(mylist):\r\n \"修改传入的列表\"\r\n mylist.append([1, 2, 3, 4]);\r\n print(\"函数内取值: \", mylist)\r\n return\r\n\r\n\r\n# 调用changeme函数\r\nmylist = [10, 20, 30];\r\nchangeme(mylist);\r\nprint(\"函数外取值: \", mylist)\r\n\r\n\r\n\"\"\"#不定长参数\"\"\"\r\ndef p( arg1, *arg2):\r\n print(\"输出:\")\r\n print(arg1)\r\n for a in arg2:\r\n print(a)\r\n return\r\np(3)\r\np(10,90,23)#自动匹配for\r\n\r\n\r\n\"\"\"#匿名函数:\"\"\"\r\n#1、 lambda只是一个表达式,函数体比def简单很多。\r\n#2、 lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。\r\n#3、 lambda函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。\r\n#4、 虽然lambda函数看起来只能写一行,却不等同于C或C + +的内联函数,后者的目的是调用小函数\r\n# 时不占用栈内存从而增加运行效率。\r\n\r\ns = lambda a1, a2: a1 + a2\r\nprint(s(12, 90))\r\n\r\n\r\n\"\"\"列表翻转\"\"\"\r\n# #翻转1\r\n# def reverse(li):\r\n# for i in range(0, len(li)/2):\r\n# temp = li[i]\r\n# li[i] = li[-i-1]\r\n# li[-i-1] = temp\r\n#\r\n# m = [1, 2, 3, 4, 5]\r\n# reverse(m)\r\n# print(m)\r\n#\r\n# #翻转2\r\n# def reverse(ListInput):\r\n# RevList=[]\r\n# for i in range (len(ListInput)):\r\n# RevList.append(ListInput.pop())\r\n# return RevList\r\n#\r\n# #简化翻转\r\n# def reverse(li):\r\n# for i in range(0, len(li)/2):\r\n# li[i], li[-i - 1] = li[-i - 1], li[i]\r\n# l = [1, 2, 3, 4, 5]\r\n# reverse(l)\r\n# print(l)","repo_name":"Faithlmy/Python_base","sub_path":"P_base/faith_base/def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37332901651","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\ntry:\n from typing import Dict, Union\nexcept ImportError:\n # Satisfy Python 2 which doesn't have typing.\n Dict = Union = None\n\nimport json\nfrom ansible.module_utils.urls import open_url\nfrom ansible.module_utils.six.moves.urllib.parse import urlencode\nfrom ansible_collections.yadro.obmc.plugins.module_utils.redfish.client.exceptions import HTTPClientError\nfrom ansible_collections.yadro.obmc.plugins.module_utils.redfish.client.response import HTTPClientResponse\nfrom ansible_collections.yadro.obmc.plugins.module_utils.redfish.auth import AuthMethod, NoAuth, BasicAuth, SessionAuth\n\n\ndef build_url(base, path, query_params=None): # type: (str, str, Dict) -> str\n url = \"{0}/{1}\".format(base.rstrip(\"/\"), path.lstrip(\"/\"))\n if query_params:\n url += \"?\" + urlencode(query_params)\n return url\n\n\nclass HTTPClient:\n\n def __init__(self, hostname, port, validate_certs, timeout, auth):\n # type: (str, int, bool, int, AuthMethod) -> None\n if \"://\" in hostname:\n self._protocol, self._hostname = hostname.split(\"://\")\n else:\n self._protocol = \"https\"\n self._hostname = hostname\n\n self._port = port\n self._base_url = \"{0}://{1}:{2}\".format(self._protocol, self._hostname, self._port)\n\n self._auth = auth\n\n self.validate_certs = validate_certs\n self.timeout = timeout\n\n def get_base_url(self):\n return self._base_url\n\n def make_request(self, path, method, query_params=None, body=None, headers=None):\n # type: (str, str, Dict, Union[Dict, bytes], Dict) -> HTTPClientResponse\n return self._make_request(path, method, query_params, body, headers)\n\n def _make_request(self, path, method, query_params, body, headers):\n # type: (str, str, Dict, Union[Dict, bytes], Dict) -> HTTPClientResponse\n request_kwargs = {\n \"follow_redirects\": \"all\",\n \"force_basic_auth\": False,\n \"headers\": {},\n \"method\": method,\n \"timeout\": self.timeout,\n \"use_proxy\": True,\n \"validate_certs\": self.validate_certs,\n }\n\n if body:\n if isinstance(body, dict) or isinstance(body, list):\n request_kwargs[\"headers\"][\"Content-Type\"] = \"application/json\"\n request_body = json.dumps(body)\n elif isinstance(body, bytes):\n request_kwargs[\"headers\"][\"Content-Type\"] = \"application/octet-stream\"\n request_body = body\n else:\n raise HTTPClientError(\"Unsupported body type: {0}\".format(type(body)))\n else:\n request_body = None\n\n if isinstance(self._auth, NoAuth):\n pass\n elif isinstance(self._auth, BasicAuth):\n request_kwargs[\"force_basic_auth\"] = True\n request_kwargs[\"url_username\"] = self._auth.username\n request_kwargs[\"url_password\"] = self._auth.password\n elif isinstance(self._auth, SessionAuth):\n request_kwargs[\"headers\"][\"X-Auth-Token\"] = self._auth.token\n else:\n raise HTTPClientError(\"Unsupported auth type: {0}\".format(type(self._auth)))\n\n if headers:\n request_kwargs[\"headers\"].update(headers)\n\n url = build_url(self._base_url, path, query_params=query_params)\n response = open_url(url=url, data=request_body, **request_kwargs)\n return HTTPClientResponse(response)\n\n def get(self, path, query_params=None, headers=None): # type: (str, Dict, Dict) -> HTTPClientResponse\n return self.make_request(path, method=\"GET\", query_params=query_params, headers=headers)\n\n def post(self, path, body=None, headers=None): # type: (str, Union[Dict, bytes], Dict) -> HTTPClientResponse\n return self.make_request(path, method=\"POST\", body=body, headers=headers)\n\n def delete(self, path, headers=None): # type: (str, Dict) -> HTTPClientResponse\n return self.make_request(path, method=\"DELETE\", headers=headers)\n\n def patch(self, path, body=None, headers=None): # type: (str, Dict, Dict) -> HTTPClientResponse\n return self.make_request(path, method=\"PATCH\", body=body, headers=headers)\n","repo_name":"YADRO-KNS/yadro-ansible-modules","sub_path":"plugins/module_utils/redfish/client/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"31237496320","text":"from models import YoloNet\nfrom dataset import create_image, reset_random, colors\nimport cv2\n\n\ndef draw_bbox(img, x, y, w, h, color, t):\n x1, y1, x2, y2 = x - w/2, y - h/2, x + w/2, y + h/2\n res_x, res_y = img.shape[1], img.shape[0]\n x1, y1, x2, y2 = int(res_x * x1), int(res_y * y1), int(res_x * x2), int(res_y * y2)\n cv2.rectangle(img, (x1, y1), (x2, y2), color, t)\n return img\n\n\ndef main():\n net: YoloNet = YoloNet(len(colors))\n net.load_from_file(\"saved.weights\")\n reset_random()\n for n in range(30):\n img, _, _, _, _, _ = create_image(416)\n xs, ys, ws, hs, cs = net.predict(img, 0.1, 0.1)\n cv2.imshow(\"img raw\", img)\n for x, y, w, h, c in zip(xs, ys, ws, hs, cs):\n co = colors[c]\n img = draw_bbox(img, x, y, w, h, [co[0]+50, co[1]+50, co[2]+50], 2)\n cv2.imshow(\"img\", img)\n cv2.waitKey()\n print(\"done detect\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kongfanhe/pytorch-yolo-v3-tiny","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"37303273994","text":"t = int(input())\n\ndef SQRT(N):\n end = 1\n while end * end < N:\n end *= 2\n beg = end // 2\n res = 1\n while beg <= end:\n mid = (beg + end) // 2\n if mid * mid <= N:\n res = mid\n beg = mid + 1\n else:\n end = mid - 1\n return res\n\ndef CBRT(N):\n end = 1\n while end * end * end < N:\n end *= 2\n beg = end // 2\n res = 1\n while beg <= end:\n mid = (beg + end) // 2\n if mid * mid * mid <= N:\n res = mid\n beg = mid + 1\n else:\n end = mid - 1\n return res\n\nfor i in range(100, 201):\n print(i, SQRT(i) - CBRT(i))\n\ndef f(n):\n ctr = {}\n for k in range(n, n + 5):\n curr = SQRT(k) - CBRT(k)\n ctr[curr] = ctr.get(curr, 0) + 1\n return max(ctr.keys(), key = lambda x: ctr[x])\n\nfor _ in range(t):\n x = int(input())\n end = 1\n while f(end) < x:\n end *= 2\n beg = end // 2\n res = end\n while beg <= end:\n mid = (beg + end) // 2\n if f(mid) >= x:\n res = mid\n end = mid - 1\n else:\n beg = mid + 1\n print(res)","repo_name":"theabbie/leetcode","sub_path":"miscellaneous/square_cube.py","file_name":"square_cube.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"18"} +{"seq_id":"22278529240","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\n\ndef build_layers(img_sz, img_fm, init_fm, max_fm, n_layers, n_attr, n_skip,\n deconv_method, instance_norm, enc_dropout, dec_dropout):\n \"\"\"\n Build auto-encoder layers.\n \"\"\"\n assert init_fm <= max_fm\n assert n_skip <= n_layers - 1\n assert np.log2(img_sz).is_integer()\n assert n_layers <= int(np.log2(img_sz))\n assert type(instance_norm) is bool\n assert 0 <= enc_dropout < 1\n assert 0 <= dec_dropout < 1\n norm_fn = nn.InstanceNorm2d if instance_norm else nn.BatchNorm2d\n\n enc_layers = []\n dec_layers = []\n\n n_in = img_fm\n n_out = init_fm\n\n for i in range(n_layers):\n enc_layer = []\n dec_layer = []\n skip_connection = n_layers - (n_skip + 1) <= i < n_layers - 1\n n_dec_in = n_out + n_attr + (n_out if skip_connection else 0)\n n_dec_out = n_in\n\n # encoder layer\n enc_layer.append(nn.Conv2d(n_in, n_out, 4, 2, 1))\n if i > 0:\n enc_layer.append(norm_fn(n_out, affine=True))\n enc_layer.append(nn.LeakyReLU(0.2, inplace=True))\n if enc_dropout > 0:\n enc_layer.append(nn.Dropout(enc_dropout))\n\n # decoder layer\n if deconv_method == 'upsampling':\n dec_layer.append(nn.UpsamplingNearest2d(scale_factor=2))\n dec_layer.append(nn.Conv2d(n_dec_in, n_dec_out, 3, 1, 1))\n elif deconv_method == 'convtranspose':\n dec_layer.append(nn.ConvTranspose2d(n_dec_in, n_dec_out, 4, 2, 1, bias=False))\n else:\n assert deconv_method == 'pixelshuffle'\n dec_layer.append(nn.Conv2d(n_dec_in, n_dec_out * 4, 3, 1, 1))\n dec_layer.append(nn.PixelShuffle(2))\n if i > 0:\n dec_layer.append(norm_fn(n_dec_out, affine=True))\n if dec_dropout > 0 and i >= n_layers - 3:\n dec_layer.append(nn.Dropout(dec_dropout))\n dec_layer.append(nn.ReLU(inplace=True))\n else:\n dec_layer.append(nn.Tanh())\n\n # update\n n_in = n_out\n n_out = min(2 * n_out, max_fm)\n enc_layers.append(nn.Sequential(*enc_layer))\n dec_layers.insert(0, nn.Sequential(*dec_layer))\n\n return enc_layers, dec_layers\n\n\nclass AutoEncoder(nn.Module):\n\n def __init__(self, params):\n super(AutoEncoder, self).__init__()\n\n self.img_sz = params.img_sz\n self.img_fm = params.img_fm\n self.instance_norm = params.instance_norm\n self.init_fm = params.init_fm\n self.max_fm = params.max_fm\n self.n_layers = params.n_layers\n self.n_skip = params.n_skip\n self.deconv_method = params.deconv_method\n self.dropout = params.dec_dropout\n self.attr = params.attr\n self.n_attr = params.n_attr\n\n enc_layers, dec_layers = build_layers(self.img_sz, self.img_fm, self.init_fm,\n self.max_fm, self.n_layers, self.n_attr,\n self.n_skip, self.deconv_method,\n self.instance_norm, 0, self.dropout)\n self.enc_layers = nn.ModuleList(enc_layers)\n self.dec_layers = nn.ModuleList(dec_layers)\n\n def encode(self, x):\n assert x.size()[1:] == (self.img_fm, self.img_sz, self.img_sz)\n\n enc_outputs = [x]\n for layer in self.enc_layers:\n enc_outputs.append(layer(enc_outputs[-1]))\n\n assert len(enc_outputs) == self.n_layers + 1\n return enc_outputs\n\n def decode(self, enc_outputs, y):\n bs = enc_outputs[0].size(0)\n assert len(enc_outputs) == self.n_layers + 1\n assert y.size() == (bs, self.n_attr)\n\n dec_outputs = [enc_outputs[-1]]\n y = y.unsqueeze(2).unsqueeze(3)\n for i, layer in enumerate(self.dec_layers):\n size = dec_outputs[-1].size(2)\n # attributes\n input = [dec_outputs[-1], y.expand(bs, self.n_attr, size, size)]\n # skip connection\n if 0 < i <= self.n_skip:\n input.append(enc_outputs[-1 - i])\n input = torch.cat(input, 1)\n dec_outputs.append(layer(input))\n\n assert len(dec_outputs) == self.n_layers + 1\n assert dec_outputs[-1].size() == (bs, self.img_fm, self.img_sz, self.img_sz)\n return dec_outputs\n\n def forward(self, x, y):\n enc_outputs = self.encode(x)\n dec_outputs = self.decode(enc_outputs, y)\n return enc_outputs, dec_outputs\n\n\nclass LatentDiscriminator(nn.Module):\n\n def __init__(self, params):\n super(LatentDiscriminator, self).__init__()\n\n self.img_sz = params.img_sz\n self.img_fm = params.img_fm\n self.init_fm = params.init_fm\n self.max_fm = params.max_fm\n self.n_layers = params.n_layers\n self.n_skip = params.n_skip\n self.hid_dim = params.hid_dim\n self.dropout = params.lat_dis_dropout\n self.attr = params.attr\n self.n_attr = params.n_attr\n\n self.n_dis_layers = int(np.log2(self.img_sz))\n self.conv_in_sz = self.img_sz / (2 ** (self.n_layers - self.n_skip))\n self.conv_in_fm = min(self.init_fm * (2 ** (self.n_layers - self.n_skip - 1)), self.max_fm)\n self.conv_out_fm = min(self.init_fm * (2 ** (self.n_dis_layers - 1)), self.max_fm)\n\n # discriminator layers are identical to encoder, but convolve until size 1\n enc_layers, _ = build_layers(self.img_sz, self.img_fm, self.init_fm, self.max_fm,\n self.n_dis_layers, self.n_attr, 0, 'convtranspose',\n False, self.dropout, 0)\n\n self.conv_layers = nn.Sequential(*(enc_layers[self.n_layers - self.n_skip:]))\n self.proj_layers = nn.Sequential(\n nn.Linear(self.conv_out_fm, self.hid_dim),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(self.hid_dim, self.n_attr)\n )\n\n def forward(self, x):\n assert x.size()[1:] == (self.conv_in_fm, self.conv_in_sz, self.conv_in_sz)\n conv_output = self.conv_layers(x)\n assert conv_output.size() == (x.size(0), self.conv_out_fm, 1, 1)\n return self.proj_layers(conv_output.view(x.size(0), self.conv_out_fm))\n\n\nclass PatchDiscriminator(nn.Module):\n def __init__(self, params):\n super(PatchDiscriminator, self).__init__()\n\n self.img_sz = params.img_sz\n self.img_fm = params.img_fm\n self.init_fm = params.init_fm\n self.max_fm = params.max_fm\n self.n_patch_dis_layers = 3\n\n layers = []\n layers.append(nn.Conv2d(self.img_fm, self.init_fm, kernel_size=4, stride=2, padding=1))\n layers.append(nn.LeakyReLU(0.2, True))\n\n n_in = self.init_fm\n n_out = min(2 * n_in, self.max_fm)\n\n for n in range(self.n_patch_dis_layers):\n stride = 1 if n == self.n_patch_dis_layers - 1 else 2\n layers.append(nn.Conv2d(n_in, n_out, kernel_size=4, stride=stride, padding=1))\n layers.append(nn.BatchNorm2d(n_out))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n if n < self.n_patch_dis_layers - 1:\n n_in = n_out\n n_out = min(2 * n_out, self.max_fm)\n\n layers.append(nn.Conv2d(n_out, 1, kernel_size=4, stride=1, padding=1))\n layers.append(nn.Sigmoid())\n\n self.layers = nn.Sequential(*layers)\n\n def forward(self, x):\n assert x.dim() == 4\n return self.layers(x).view(x.size(0), -1).mean(1).view(x.size(0))\n\n\nclass Classifier(nn.Module):\n\n def __init__(self, params):\n super(Classifier, self).__init__()\n\n self.img_sz = params.img_sz\n self.img_fm = params.img_fm\n self.init_fm = params.init_fm\n self.max_fm = params.max_fm\n self.hid_dim = params.hid_dim\n self.attr = params.attr\n self.n_attr = params.n_attr\n\n self.n_clf_layers = int(np.log2(self.img_sz))\n self.conv_out_fm = min(self.init_fm * (2 ** (self.n_clf_layers - 1)), self.max_fm)\n\n # classifier layers are identical to encoder, but convolve until size 1\n enc_layers, _ = build_layers(self.img_sz, self.img_fm, self.init_fm, self.max_fm,\n self.n_clf_layers, self.n_attr, 0, 'convtranspose',\n False, 0, 0)\n\n self.conv_layers = nn.Sequential(*enc_layers)\n self.proj_layers = nn.Sequential(\n nn.Linear(self.conv_out_fm, self.hid_dim),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(self.hid_dim, self.n_attr)\n )\n\n def forward(self, x):\n assert x.size()[1:] == (self.img_fm, self.img_sz, self.img_sz)\n conv_output = self.conv_layers(x)\n assert conv_output.size() == (x.size(0), self.conv_out_fm, 1, 1)\n return self.proj_layers(conv_output.view(x.size(0), self.conv_out_fm))\n\n\ndef get_attr_loss(output, attributes, flip, params):\n \"\"\"\n Compute attributes loss.\n \"\"\"\n assert type(flip) is bool\n k = 0\n loss = 0\n for (_, n_cat) in params.attr:\n # categorical\n x = output[:, k:k + n_cat].contiguous()\n y = attributes[:, k:k + n_cat].max(1)[1].view(-1)\n if flip:\n # generate different categories\n shift = torch.LongTensor(y.size()).random_(n_cat - 1) + 1\n y = (y + Variable(shift.cuda())) % n_cat\n loss += F.cross_entropy(x, y)\n k += n_cat\n return loss\n\n\ndef update_predictions(all_preds, preds, targets, params):\n \"\"\"\n Update discriminator / classifier predictions.\n \"\"\"\n assert len(all_preds) == len(params.attr)\n k = 0\n for j, (_, n_cat) in enumerate(params.attr):\n _preds = preds[:, k:k + n_cat].max(1)[1]\n _targets = targets[:, k:k + n_cat].max(1)[1]\n all_preds[j].extend((_preds == _targets).tolist())\n k += n_cat\n assert k == params.n_attr\n\n\ndef get_mappings(params):\n \"\"\"\n Create a mapping between attributes and their associated IDs.\n \"\"\"\n if not hasattr(params, 'mappings'):\n mappings = []\n k = 0\n for (_, n_cat) in params.attr:\n assert n_cat >= 2\n mappings.append((k, k + n_cat))\n k += n_cat\n assert k == params.n_attr\n params.mappings = mappings\n return params.mappings\n\n\ndef flip_attributes(attributes, params, attribute_id, new_value=None):\n \"\"\"\n Randomly flip a set of attributes.\n \"\"\"\n assert attributes.size(1) == params.n_attr\n mappings = get_mappings(params)\n attributes = attributes.data.clone().cpu()\n\n def flip_attribute(attribute_id, new_value=None):\n bs = attributes.size(0)\n i, j = mappings[attribute_id]\n attributes[:, i:j].zero_()\n if new_value is None:\n y = torch.LongTensor(bs).random_(j - i)\n else:\n assert new_value in range(j - i)\n y = torch.LongTensor(bs).fill_(new_value)\n attributes[:, i:j].scatter_(1, y.unsqueeze(1), 1)\n\n if attribute_id == 'all':\n assert new_value is None\n for attribute_id in range(len(params.attr)):\n flip_attribute(attribute_id)\n else:\n assert type(new_value) is int\n flip_attribute(attribute_id, new_value)\n\n return Variable(attributes.cuda())\n","repo_name":"facebookresearch/FaderNetworks","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11351,"program_lang":"python","lang":"en","doc_type":"code","stars":755,"dataset":"github-code","pt":"18"} +{"seq_id":"14951219411","text":"# A part of NonVisual Desktop Access (NVDA)\r\n# Copyright (C) 2016-2021 Tyler Spivey, NV Access Limited, James Teh, Leonard de Ruijter\r\n# This file is covered by the GNU General Public License.\r\n# See the file COPYING for more details.\r\n\r\n\"\"\"Synth driver for Windows OneCore voices.\r\n\"\"\"\r\n\r\nimport os\r\nfrom typing import (\r\n\tAny,\r\n\tCallable,\r\n\tGenerator,\r\n\tList,\r\n\tOptional,\r\n\tSet,\r\n\tTuple,\r\n\tUnion\r\n)\r\nfrom collections import OrderedDict\r\nimport ctypes\r\nimport winreg\r\nimport wave\r\nfrom synthDriverHandler import (\r\n\tfindAndSetNextSynth,\r\n\tisDebugForSynthDriver,\r\n\tSynthDriver,\r\n\tsynthDoneSpeaking,\r\n\tsynthIndexReached,\r\n\tVoiceInfo,\r\n)\r\nimport io\r\nfrom logHandler import log\r\nimport config\r\nimport nvwave\r\nimport queueHandler\r\nfrom speech.types import SpeechSequence\r\nimport speech\r\nimport speechXml\r\nimport languageHandler\r\nimport winVersion\r\nimport NVDAHelper\r\n\r\nfrom speech.commands import (\r\n\tIndexCommand,\r\n\tCharacterModeCommand,\r\n\tLangChangeCommand,\r\n\tBreakCommand,\r\n\tPitchCommand,\r\n\tRateCommand,\r\n\tVolumeCommand,\r\n\tPhonemeCommand,\r\n)\r\n\r\n#: The number of 100-nanosecond units in 1 second.\r\nHUNDRED_NS_PER_SEC = 10000000 # 1000000000 ns per sec / 100 ns\r\nWAVE_HEADER_LENGTH = 46\r\nocSpeech_Callback = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p)\r\n\r\nclass _OcSsmlConverter(speechXml.SsmlConverter):\r\n\tdef __init__(\r\n\t\t\tself,\r\n\t\t\tdefaultLanguage: str,\r\n\t\t\tavailableLanguages: Set[str],\r\n\t):\r\n\t\t\"\"\"\r\n\t\tUsed for newer OneCore installations (OneCore API > 5)\r\n\t\twhere supportsProsodyOptions is True.\r\n\t\tThis allows for changing rate, volume and pitch after initialization.\r\n\r\n\t\t@param defaultLanguage: language with locale, installed by OneCore (e.g. 'en_US')\r\n\t\t@param availableLanguages: languages with locale, installed by OneCore (e.g. 'zh_HK', 'en_US')\r\n\t\t\"\"\"\r\n\t\tself.lowerCaseAvailableLanguages = {language.lower() for language in availableLanguages}\r\n\t\tself.availableLanguagesWithoutLocale = {\r\n\t\t\tlanguage.split(\"_\")[0] for language in self.lowerCaseAvailableLanguages\r\n\t\t}\r\n\t\tsuper().__init__(defaultLanguage)\r\n\r\n\tdef _convertProsody(self, command, attr, default, base=None):\r\n\t\tif base is None:\r\n\t\t\tbase = default\r\n\t\tif command.multiplier == 1 and base == default:\r\n\t\t\t# Returning to synth default.\r\n\t\t\treturn speechXml.DelAttrCommand(\"prosody\", attr)\r\n\t\telse:\r\n\t\t\t# Multiplication isn't supported, only addition/subtraction.\r\n\t\t\t# The final value must therefore be relative to the synthesizer's default.\r\n\t\t\tval = base * command.multiplier - default\r\n\t\t\treturn speechXml.SetAttrCommand(\"prosody\", attr, \"%d%%\" % val)\r\n\r\n\tdef convertRateCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"rate\", 50)\r\n\r\n\tdef convertPitchCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"pitch\", 50)\r\n\r\n\tdef convertVolumeCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"volume\", 100)\r\n\r\n\tdef convertCharacterModeCommand(self, command):\r\n\t\t# OneCore's character speech sounds weird and doesn't support pitch alteration.\r\n\t\t# Therefore, we don't use it.\r\n\t\treturn None\r\n\r\n\tdef convertLangChangeCommand(self, command: LangChangeCommand) -> Optional[speechXml.SetAttrCommand]:\r\n\t\tlcid = languageHandler.localeNameToWindowsLCID(command.lang)\r\n\t\tif lcid is languageHandler.LCID_NONE:\r\n\t\t\tlog.debugWarning(f\"Invalid language: {command.lang}\")\r\n\t\t\treturn None\r\n\r\n\t\tnormalizedLanguage = command.lang.lower().replace(\"-\", \"_\")\r\n\t\tnormalizedLanguageWithoutLocale = normalizedLanguage.split(\"_\")[0]\r\n\t\tif (\r\n\t\t\tnormalizedLanguage not in self.lowerCaseAvailableLanguages\r\n\t\t\tand normalizedLanguageWithoutLocale not in self.availableLanguagesWithoutLocale\r\n\t\t):\r\n\t\t\tlog.warning(f\"Language {command.lang} not supported ({self.lowerCaseAvailableLanguages})\")\r\n\t\t\treturn None\r\n\r\n\t\treturn super().convertLangChangeCommand(command)\r\n\r\nclass _OcPreAPI5SsmlConverter(_OcSsmlConverter):\r\n\r\n\tdef __init__(\r\n\t\t\tself,\r\n\t\t\tdefaultLanguage: str,\r\n\t\t\tavailableLanguages: Set[str],\r\n\t\t\trate: float,\r\n\t\t\tpitch: float,\r\n\t\t\tvolume: float,\r\n\t):\r\n\t\t\"\"\"\r\n\t\tUsed for older OneCore installations (OneCore API < 5),\r\n\t\twhere supportsProsodyOptions is False.\r\n\t\tThis means we must initially set a good default for rate, volume and pitch,\r\n\t\tas this can't be changed after initialization.\r\n\r\n\t\t@param defaultLanguage: language with locale, installed by OneCore (e.g. 'en_US')\r\n\t\t@param availableLanguages: languages with locale, installed by OneCore (e.g. 'zh_HK', 'en_US')\r\n\t\t@param rate: from 0-100\r\n\t\t@param pitch: from 0-100\r\n\t\t@param volume: from 0-100\r\n\t\t\"\"\"\r\n\t\tsuper().__init__(defaultLanguage, availableLanguages)\r\n\t\tself._rate = rate\r\n\t\tself._pitch = pitch\r\n\t\tself._volume = volume\r\n\r\n\tdef generateBalancerCommands(self, speechSequence: SpeechSequence) -> Generator[Any, None, None]:\r\n\t\tcommands = super().generateBalancerCommands(speechSequence)\r\n\t\t# The EncloseAllCommand from SSML must be first.\r\n\t\tyield next(commands)\r\n\t\t# OneCore didn't provide a way to set base prosody values before API version 5.\r\n\t\t# Therefore, the base values need to be set using SSML.\r\n\t\tyield self.convertRateCommand(RateCommand(multiplier=1))\r\n\t\tyield self.convertVolumeCommand(VolumeCommand(multiplier=1))\r\n\t\tyield self.convertPitchCommand(PitchCommand(multiplier=1))\r\n\t\tfor command in commands:\r\n\t\t\tyield command\r\n\r\n\tdef convertRateCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"rate\", 50, self._rate)\r\n\r\n\tdef convertPitchCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"pitch\", 50, self._pitch)\r\n\r\n\tdef convertVolumeCommand(self, command):\r\n\t\treturn self._convertProsody(command, \"volume\", 100, self._volume)\r\n\r\n\r\nclass OneCoreSynthDriver(SynthDriver):\r\n\r\n\tMIN_PITCH = 0.0\r\n\tMAX_PITCH = 2.0\r\n\tMIN_RATE = 0.5\r\n\tDEFAULT_MAX_RATE = 1.5\r\n\tBOOSTED_MAX_RATE = 6.0\r\n\tMAX_CONSECUTIVE_SPEECH_FAILURES = 5\r\n\r\n\tname = \"oneCore\"\r\n\t# Translators: Description for a speech synthesizer.\r\n\tdescription = _(\"Windows OneCore voices\")\r\n\tsupportedCommands = {\r\n\t\tIndexCommand,\r\n\t\tCharacterModeCommand,\r\n\t\tLangChangeCommand,\r\n\t\tBreakCommand,\r\n\t\tPitchCommand,\r\n\t\tRateCommand,\r\n\t\tVolumeCommand,\r\n\t\tPhonemeCommand,\r\n\t}\r\n\tsupportedNotifications = {synthIndexReached, synthDoneSpeaking}\r\n\r\n\t@classmethod\r\n\tdef check(cls):\r\n\t\t# Only present this as an available synth if this is Windows 10.\r\n\t\treturn winVersion.getWinVer() >= winVersion.WIN10\r\n\r\n\tdef _get_supportsProsodyOptions(self):\r\n\t\tself.supportsProsodyOptions = self._dll.ocSpeech_supportsProsodyOptions()\r\n\t\treturn self.supportsProsodyOptions\r\n\r\n\tdef _get_supportedSettings(self):\r\n\t\tself.supportedSettings = settings = [\r\n\t\t\tSynthDriver.VoiceSetting(),\r\n\t\t\tSynthDriver.RateSetting(),\r\n\t\t]\r\n\t\tif self.supportsProsodyOptions:\r\n\t\t\tsettings.append(SynthDriver.RateBoostSetting())\r\n\t\tsettings.extend([\r\n\t\t\tSynthDriver.PitchSetting(),\r\n\t\t\tSynthDriver.VolumeSetting(),\r\n\t\t])\r\n\t\treturn settings\r\n\r\n\tdef __init__(self):\r\n\t\tsuper().__init__()\r\n\t\tself._dll = NVDAHelper.getHelperLocalWin10Dll()\r\n\t\tself._dll.ocSpeech_getCurrentVoiceLanguage.restype = ctypes.c_wchar_p\r\n\t\t# Set initial values for parameters that can't be queried when prosody is not supported.\r\n\t\t# This initialises our cache for the value.\r\n\t\t# When prosody is supported, the values are used for cachign reasons.\r\n\t\tself._rate: int = 50\r\n\t\tself._pitch: int = 50\r\n\t\tself._volume: int = 100\r\n\r\n\t\tif self.supportsProsodyOptions:\r\n\t\t\tself._dll.ocSpeech_getPitch.restype = ctypes.c_double\r\n\t\t\tself._dll.ocSpeech_getVolume.restype = ctypes.c_double\r\n\t\t\tself._dll.ocSpeech_getRate.restype = ctypes.c_double\r\n\t\telse:\r\n\t\t\tlog.debugWarning(\"Prosody options not supported\")\r\n\r\n\t\tself._earlyExitCB = False\r\n\t\tself._callbackInst = ocSpeech_Callback(self._callback)\r\n\t\tself._ocSpeechToken: Optional[ctypes.POINTER] = self._dll.ocSpeech_initialize(self._callbackInst)\r\n\t\tself._dll.ocSpeech_getVoices.restype = NVDAHelper.bstrReturn\r\n\t\tself._dll.ocSpeech_getCurrentVoiceId.restype = ctypes.c_wchar_p\r\n\t\tself._player= None\r\n\t\t# Initialize state.\r\n\t\tself._queuedSpeech: List[Union[str, Tuple[Callable[[ctypes.POINTER, float], None], float]]] = []\r\n\r\n\t\tself._wasCancelled = False\r\n\t\tself._isProcessing = False\r\n\t\t# Initialize the voice to a sane default\r\n\t\tself.voice=self._getDefaultVoice()\r\n\t\tself._consecutiveSpeechFailures = 0\r\n\r\n\tdef _maybeInitPlayer(self, wav):\r\n\t\t\"\"\"Initialize audio playback based on the wave header provided by the synthesizer.\r\n\t\tIf the sampling rate has not changed, the existing player is used.\r\n\t\tOtherwise, a new one is created with the appropriate parameters.\r\n\t\t\"\"\"\r\n\t\tsamplesPerSec = wav.getframerate()\r\n\t\tif self._player and self._player.samplesPerSec == samplesPerSec:\r\n\t\t\treturn\r\n\t\tif self._player:\r\n\t\t\t# Finalise any pending audio.\r\n\t\t\tself._player.idle()\r\n\t\tbytesPerSample = wav.getsampwidth()\r\n\t\tself._bytesPerSec = samplesPerSec * bytesPerSample\r\n\t\tself._player = nvwave.WavePlayer(\r\n\t\t\tchannels=wav.getnchannels(),\r\n\t\t\tsamplesPerSec=samplesPerSec,\r\n\t\t\tbitsPerSample=bytesPerSample * 8,\r\n\t\t\toutputDevice=config.conf[\"speech\"][\"outputDevice\"]\r\n\t\t)\r\n\r\n\tdef terminate(self):\r\n\t\t# prevent any pending callbacks from interacting further with the synth.\r\n\t\tself._earlyExitCB = True\r\n\t\tsuper().terminate()\r\n\t\t# Terminate the synth, the callback function should no longer be called after this returns.\r\n\t\tself._dll.ocSpeech_terminate(self._ocSpeechToken)\r\n\t\t# Drop the ctypes function instance for the callback and handle,\r\n\t\t# as it is holding a reference to an instance method, which causes a reference cycle.\r\n\t\tself._ocSpeechToken = None\r\n\t\tself._callbackInst = None\r\n\r\n\tdef cancel(self):\r\n\t\t# Set a flag to tell the callback not to push more audio.\r\n\t\tself._wasCancelled = True\r\n\t\tif isDebugForSynthDriver():\r\n\t\t\tlog.debug(\"Cancelling\")\r\n\t\t# There might be more text pending. Throw it away.\r\n\t\tif self.supportsProsodyOptions:\r\n\t\t\t# In this case however, we must keep any parameter changes.\r\n\t\t\tself._queuedSpeech = [item for item in self._queuedSpeech\r\n\t\t\t\tif not isinstance(item, str)]\r\n\t\telse:\r\n\t\t\tself._queuedSpeech = []\r\n\t\tif self._player:\r\n\t\t\tself._player.stop()\r\n\r\n\tdef speak(self, speechSequence: SpeechSequence) -> None:\r\n\t\tif self.supportsProsodyOptions:\r\n\t\t\tconv = _OcSsmlConverter(self.language, self.availableLanguages)\r\n\t\telse:\r\n\t\t\tconv = _OcPreAPI5SsmlConverter(\r\n\t\t\t\tself.language,\r\n\t\t\t\tself.availableLanguages,\r\n\t\t\t\tself._rate,\r\n\t\t\t\tself._pitch,\r\n\t\t\t\tself._volume\r\n\t\t\t)\r\n\t\ttext = conv.convertToXml(speechSequence)\r\n\t\t# #7495: Calling WaveOutOpen blocks for ~100 ms if called from the callback\r\n\t\t# when the SSML includes marks.\r\n\t\t# We're not quite sure why.\r\n\t\t# To work around this, open the device before queuing.\r\n\t\tif self._player:\r\n\t\t\tself._player.open()\r\n\t\tself._queueSpeech(text)\r\n\r\n\tdef _queueSpeech(self, item: str) -> None:\r\n\t\tself._queuedSpeech.append(item)\r\n\t\t# We only process the queue here if it isn't already being processed.\r\n\t\tif not self._isProcessing:\r\n\t\t\tself._processQueue()\r\n\r\n\t@classmethod\r\n\tdef _percentToParam(self, percent, min, max):\r\n\t\t\"\"\"Overrides SynthDriver._percentToParam to return floating point parameter values.\r\n\t\t\"\"\"\r\n\t\treturn float(percent) / 100 * (max - min) + min\r\n\r\n\tdef _get_pitch(self):\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn self._pitch\r\n\t\trawPitch = self._dll.ocSpeech_getPitch(self._ocSpeechToken)\r\n\t\treturn self._paramToPercent(rawPitch, self.MIN_PITCH, self.MAX_PITCH)\r\n\r\n\tdef _set_pitch(self, pitch):\r\n\t\tself._pitch = pitch\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn\r\n\t\trawPitch = self._percentToParam(pitch, self.MIN_PITCH, self.MAX_PITCH)\r\n\t\tself._queuedSpeech.append((self._dll.ocSpeech_setPitch, rawPitch))\r\n\r\n\tdef _get_volume(self) -> int:\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn self._volume\r\n\t\trawVolume = self._dll.ocSpeech_getVolume(self._ocSpeechToken)\r\n\t\treturn int(rawVolume * 100)\r\n\r\n\tdef _set_volume(self, volume: int):\r\n\t\tself._volume = volume\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn\r\n\t\trawVolume = volume / 100.0\r\n\t\tself._queuedSpeech.append((self._dll.ocSpeech_setVolume, rawVolume))\r\n\r\n\tdef _get_rate(self):\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn self._rate\r\n\t\trawRate = self._dll.ocSpeech_getRate(self._ocSpeechToken)\r\n\t\tmaxRate = self.BOOSTED_MAX_RATE if self._rateBoost else self.DEFAULT_MAX_RATE\r\n\t\treturn self._paramToPercent(rawRate, self.MIN_RATE, maxRate)\r\n\r\n\tdef _set_rate(self, rate):\r\n\t\tself._rate = rate\r\n\t\tif not self.supportsProsodyOptions:\r\n\t\t\treturn\r\n\t\tmaxRate = self.BOOSTED_MAX_RATE if self._rateBoost else self.DEFAULT_MAX_RATE\r\n\t\trawRate = self._percentToParam(rate, self.MIN_RATE, maxRate)\r\n\t\tself._queuedSpeech.append((self._dll.ocSpeech_setRate, rawRate))\r\n\r\n\t_rateBoost = False\r\n\r\n\tdef _get_rateBoost(self):\r\n\t\treturn self._rateBoost\r\n\r\n\tdef _set_rateBoost(self, enable):\r\n\t\tif enable == self._rateBoost:\r\n\t\t\treturn\r\n\t\t# Use the cached rate to calculate the new rate with rate boost enabled.\r\n\t\t# If we don't, getting the rate property will return the default rate when initializing the driver and applying settings.\r\n\t\trate = self._rate\r\n\t\tself._rateBoost = enable\r\n\t\tself.rate = rate\r\n\r\n\tdef _processQueue(self):\r\n\t\tif not self._queuedSpeech and self._player is None:\r\n\t\t\t# If oneCore speech has not been successful yet the player will not have initialised. (#11544)\r\n\t\t\t# We can't sync the player in this instance.\r\n\t\t\tlog.debugWarning(\"Cannot process speech queue as player not set and no speech queued\")\r\n\t\t\treturn\r\n\t\tif not self._queuedSpeech:\r\n\t\t\t# There are no more queued utterances at this point, so call sync.\r\n\t\t\t# This blocks while waiting for the final chunk to play,\r\n\t\t\t# so by the time this is done, there might be something queued.\r\n\t\t\t# #10721: We use sync instead of idle because idle closes the audio\r\n\t\t\t# device. If there's something in the queue after playing the final chunk,\r\n\t\t\t# that will result in WaveOutOpen being called in the callback when we\r\n\t\t\t# push the next chunk of audio. We *really* don't want this because calling\r\n\t\t\t# WaveOutOpen blocks for ~100 ms if called from the callback when the SSML\r\n\t\t\t# includes marks, resulting in lag between utterances.\r\n\t\t\tif isDebugForSynthDriver():\r\n\t\t\t\tlog.debug(\"Calling sync on audio player\")\r\n\t\t\tself._player.sync()\r\n\t\tif not self._queuedSpeech:\r\n\t\t\t# There's still nothing in the queue, so it's okay to call idle now.\r\n\t\t\tif isDebugForSynthDriver():\r\n\t\t\t\tlog.debug(\"Calling idle on audio player\")\r\n\t\t\tself._player.idle()\r\n\t\t\tsynthDoneSpeaking.notify(synth=self)\r\n\t\twhile self._queuedSpeech:\r\n\t\t\titem = self._queuedSpeech.pop(0)\r\n\t\t\tif isinstance(item, tuple):\r\n\t\t\t\t# Parameter change.\r\n\t\t\t\t# Note that, if prosody otions aren't supported, this code will never be executed.\r\n\t\t\t\tfunc, value = item\r\n\t\t\t\tvalue = ctypes.c_double(value)\r\n\t\t\t\tfunc(self._ocSpeechToken, value)\r\n\t\t\t\tcontinue\r\n\t\t\tself._wasCancelled = False\r\n\t\t\tif isDebugForSynthDriver():\r\n\t\t\t\tlog.debug(\"Begin processing speech\")\r\n\t\t\tself._isProcessing = True\r\n\t\t\t# ocSpeech_speak is async.\r\n\t\t\t# It will call _callback in a background thread once done,\r\n\t\t\t# which will eventually process the queue again.\r\n\t\t\tself._dll.ocSpeech_speak(self._ocSpeechToken, item)\r\n\t\t\treturn\r\n\t\tif isDebugForSynthDriver():\r\n\t\t\tlog.debug(\"Queue empty, done processing\")\r\n\t\tself._isProcessing = False\r\n\r\n\tdef _handleSpeechFailure(self):\r\n\t\t# The C++ code will log an error with details.\r\n\t\tlog.error(\"OneCore synthesizer failed to speak\") # so a warning beep is played when speech fails\r\n\t\ttry:\r\n\t\t\tself._processQueue()\r\n\t\tfinally:\r\n\t\t\tself._consecutiveSpeechFailures += 1\r\n\t\t\tif self._consecutiveSpeechFailures >= self.MAX_CONSECUTIVE_SPEECH_FAILURES:\r\n\t\t\t\tlog.debugWarning(\"Too many consecutive speech failures, changing synth\")\r\n\t\t\t\tqueueHandler.queueFunction(queueHandler.eventQueue, findAndSetNextSynth, self.name)\r\n\t\t\t\tself._consecutiveSpeechFailures = 0\r\n\r\n\tdef _callback(self, bytes, len, markers):\r\n\t\tif self._earlyExitCB:\r\n\t\t\t# prevent any pending callbacks from interacting further with the synth.\r\n\t\t\t# used during termination.\r\n\t\t\treturn\r\n\t\tif len == 0:\r\n\t\t\t# Speech failed\r\n\t\t\tself._handleSpeechFailure()\r\n\t\t\treturn\r\n\t\telse:\r\n\t\t\tself._consecutiveSpeechFailures = 0\r\n\t\t# This gets called in a background thread.\r\n\t\tstream = io.BytesIO(ctypes.string_at(bytes, WAVE_HEADER_LENGTH))\r\n\t\twav = wave.open(stream, \"r\")\r\n\t\tself._maybeInitPlayer(wav)\r\n\t\tdata = bytes + WAVE_HEADER_LENGTH\r\n\t\tdataLen = wav.getnframes() * wav.getnchannels() * wav.getsampwidth()\r\n\t\tif markers:\r\n\t\t\tmarkers = markers.split('|')\r\n\t\telse:\r\n\t\t\tmarkers = []\r\n\t\tprevPos = 0\r\n\r\n\t\t# Push audio up to each marker so we can sync the audio with the markers.\r\n\t\tfor marker in markers:\r\n\t\t\tif self._wasCancelled:\r\n\t\t\t\tbreak\r\n\t\t\tname, pos = marker.split(':')\r\n\t\t\tindex = int(name)\r\n\t\t\tpos = int(pos)\r\n\t\t\t# pos is a time offset in 100-nanosecond units.\r\n\t\t\t# Convert this to a byte offset.\r\n\t\t\t# Order the equation so we don't have to do floating point.\r\n\t\t\tpos = pos * self._bytesPerSec // HUNDRED_NS_PER_SEC\r\n\t\t\t# Push audio up to this marker.\r\n\t\t\tself._player.feed(\r\n\t\t\t\tctypes.c_void_p(data + prevPos),\r\n\t\t\t\tsize=pos - prevPos,\r\n\t\t\t\tonDone=lambda index=index: synthIndexReached.notify(synth=self, index=index)\r\n\t\t\t)\r\n\t\t\tprevPos = pos\r\n\t\tif self._wasCancelled:\r\n\t\t\tif isDebugForSynthDriver():\r\n\t\t\t\tlog.debug(\"Cancelled, stopped pushing audio\")\r\n\t\telse:\r\n\t\t\tself._player.feed(ctypes.c_void_p(data + prevPos), size=dataLen - prevPos)\r\n\t\t\tif isDebugForSynthDriver():\r\n\t\t\t\tlog.debug(\"Done pushing audio\")\r\n\t\tself._processQueue()\r\n\r\n\tdef _getVoiceInfoFromOnecoreVoiceString(self, voiceStr):\r\n\t\t\"\"\"\r\n\t\tProduces an NVDA VoiceInfo object representing the given voice string from Onecore speech.\r\n\t\t\"\"\"\r\n\t\t# The voice string is made up of the ID, the language, and the display name.\r\n\t\tID,language,name=voiceStr.split(':')\r\n\t\tlanguage=language.replace('-','_')\r\n\t\treturn VoiceInfo(ID,name,language=language)\r\n\r\n\tdef _getAvailableVoices(self):\r\n\t\tvoices = OrderedDict()\r\n\t\t# Fetch the full list of voices that OneCore speech knows about.\r\n\t\t# Note that it may give back voices that are uninstalled or broken.\r\n\t\t# Refer to _isVoiceValid for information on uninstalled or broken voices.\r\n\t\tvoicesStr = self._dll.ocSpeech_getVoices(self._ocSpeechToken).split('|')\r\n\t\tfor index,voiceStr in enumerate(voicesStr):\r\n\t\t\tvoiceInfo=self._getVoiceInfoFromOnecoreVoiceString(voiceStr)\r\n\t\t\t# Filter out any invalid voices.\r\n\t\t\tif not self._isVoiceValid(voiceInfo.id):\r\n\t\t\t\tcontinue\r\n\t\t\tvoiceInfo.onecoreIndex=index\r\n\t\t\tvoices[voiceInfo.id] = voiceInfo\r\n\t\treturn voices\r\n\r\n\tdef _isVoiceValid(self, ID: str) -> bool:\r\n\t\tr\"\"\"\r\n\t\tChecks that the given voice actually exists and is valid.\r\n\t\tIt checks the Registry, and also ensures that its data files actually exist on this machine.\r\n\t\t@param ID: the ID of the requested voice.\r\n\t\t@returns: True if the voice is valid, False otherwise.\r\n\r\n\t\tOneCore keeps specific registry caches of OneCore for AT applications.\r\n\t\tInstalled copies of NVDA have a OneCore cache in:\r\n\t\t`HKEY_CURRENT_USER\\Software\\Microsoft\\Speech_OneCore\\Isolated\\Ny37kw9G-o42UiJ1z6Qc_sszEKkCNywTlrTOG0QKVB4`.\r\n\t\tThe caches contain a subtree which is meant to mirror the path:\r\n\t\t`HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech_OneCore\\*`.\r\n\r\n\t\tFor example:\r\n\t\t`HKEY_CURRENT_USER\\Software\\Microsoft\\Speech_OneCore\\Isolated\\Ny37kw9G-o42UiJ1z6Qc_sszEKkCNywTlrTOG0QKVB4\\\r\n\t\tHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech_OneCore\\Voices\\Tokens\\MSTTS_V110_enUS_MarkM`\r\n\t\trefers to `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech_OneCore\\Voices\\Tokens\\MSTTS_V110_enUS_MarkM`.\r\n\r\n\t\tLanguages which have been used by an installed copy of NVDA,\r\n\t\tbut uninstalled from the system are kept in the cache.\r\n\t\tFor installed copies of NVDA, OneCore will still attempt to use these languages,\r\n\t\tso we must check if they are valid first.\r\n\t\tFor portable copies, the cache is bypassed and `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech_OneCore\\`\r\n\t\tis read directly.\r\n\r\n\t\tFor more information, refer to:\r\n\t\thttps://github.com/nvaccess/nvda/issues/13732#issuecomment-1149386711\r\n\t\t\"\"\"\r\n\t\tIDParts = ID.split('\\\\')\r\n\t\trootKey = getattr(winreg, IDParts[0])\r\n\t\tsubkey = \"\\\\\".join(IDParts[1:])\r\n\t\ttry:\r\n\t\t\thkey = winreg.OpenKey(rootKey, subkey)\r\n\t\texcept WindowsError as e:\r\n\t\t\tlog.debugWarning(\"Could not open registry key %s, %r\" % (ID, e))\r\n\t\t\treturn False\r\n\t\ttry:\r\n\t\t\tlangDataPath = winreg.QueryValueEx(hkey, 'langDataPath')\r\n\t\texcept WindowsError as e:\r\n\t\t\tlog.debugWarning(\"Could not open registry value 'langDataPath', %r\" % e)\r\n\t\t\treturn False\r\n\t\tif not langDataPath or not isinstance(langDataPath[0], str):\r\n\t\t\tlog.debugWarning(\"Invalid langDataPath value\")\r\n\t\t\treturn False\r\n\t\tif not os.path.isfile(os.path.expandvars(langDataPath[0])):\r\n\t\t\tlog.debugWarning(\"Missing language data file: %s\" % langDataPath[0])\r\n\t\t\treturn False\r\n\t\ttry:\r\n\t\t\tvoicePath = winreg.QueryValueEx(hkey, 'voicePath')\r\n\t\texcept WindowsError as e:\r\n\t\t\tlog.debugWarning(\"Could not open registry value 'langDataPath', %r\" % e)\r\n\t\t\treturn False\r\n\t\tif not voicePath or not isinstance(voicePath[0],str):\r\n\t\t\tlog.debugWarning(\"Invalid voicePath value\")\r\n\t\t\treturn False\r\n\t\tif not os.path.isfile(os.path.expandvars(voicePath[0] + '.apm')):\r\n\t\t\tlog.debugWarning(\"Missing voice file: %s\" % voicePath[0] + \".apm\")\r\n\t\t\treturn False\r\n\t\treturn True\r\n\r\n\tdef _get_voice(self):\r\n\t\treturn self._dll.ocSpeech_getCurrentVoiceId(self._ocSpeechToken)\r\n\r\n\tdef _set_voice(self, id):\r\n\t\tvoices = self.availableVoices\r\n\t\t# Try setting the requested voice\r\n\t\tfor voice in voices.values():\r\n\t\t\tif voice.id == id:\r\n\t\t\t\tself._dll.ocSpeech_setVoice(self._ocSpeechToken, voice.onecoreIndex)\r\n\t\t\t\treturn\r\n\t\traise LookupError(\"No such voice: %s\"%id)\r\n\r\n\tdef _getDefaultVoice(self, pickAny: bool = True) -> str:\r\n\t\t\"\"\"\r\n\t\tFinds the best available voice that can be used as a default.\r\n\t\tIt first tries finding a voice with the same language as the user's configured NVDA language\r\n\t\telse one that matches the system language.\r\n\t\telse any voice if pickAny is True.\r\n\t\tUses the Windows locale (eg en_AU) to provide country information for the voice where possible.\r\n\t\t@returns: the ID of the voice, suitable for passing to self.voice for setting.\r\n\t\t\"\"\"\r\n\t\tvoices = self.availableVoices\r\n\t\tfullWindowsLanguage = languageHandler.getWindowsLanguage()\r\n\t\tbaseWindowsLanguage = fullWindowsLanguage.split('_')[0]\r\n\t\tNVDALanguage = languageHandler.getLanguage()\r\n\t\tif NVDALanguage.startswith(baseWindowsLanguage):\r\n\t\t\t# add country information if it matches\r\n\t\t\tNVDALanguage = fullWindowsLanguage\r\n\t\t# Try matching to the NVDA language\r\n\t\tfor voice in voices.values():\r\n\t\t\tif voice.language.startswith(NVDALanguage):\r\n\t\t\t\treturn voice.id\r\n\t\t# Try matching to the system language and country\r\n\t\tif fullWindowsLanguage != NVDALanguage:\r\n\t\t\tfor voice in voices.values():\r\n\t\t\t\tif voice.language == fullWindowsLanguage:\r\n\t\t\t\t\treturn voice.id\r\n\t\t# Try matching to the system language\r\n\t\tif baseWindowsLanguage not in {fullWindowsLanguage, NVDALanguage}:\r\n\t\t\tfor voice in voices.values():\r\n\t\t\t\tif voice.language.startswith(baseWindowsLanguage):\r\n\t\t\t\t\treturn voice.id\r\n\t\tif pickAny:\r\n\t\t\tfor voice in voices.values():\r\n\t\t\t\treturn voice.id\r\n\t\t\traise VoiceUnsupportedError(\"No voices available\")\r\n\t\traise VoiceUnsupportedError(\"No voices available that match the user language\")\r\n\r\n\tdef pause(self, switch):\r\n\t\tif self._player:\r\n\t\t\tself._player.pause(switch)\r\n\r\n\r\n# Alias to allow look up by name \"SynthDriver\"\r\nSynthDriver = OneCoreSynthDriver\r\n\r\n\r\nclass VoiceUnsupportedError(RuntimeError):\r\n\tpass\r\n","repo_name":"nvaccess/nvda","sub_path":"source/synthDrivers/oneCore.py","file_name":"oneCore.py","file_ext":"py","file_size_in_byte":23206,"program_lang":"python","lang":"en","doc_type":"code","stars":1802,"dataset":"github-code","pt":"18"} +{"seq_id":"74416838759","text":"\"\"\"Employee api endpoints tests\"\"\"\n\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\nfrom core.helpers import create_user, create_department\nfrom core.models import Employee\nfrom personnel.serializers import EmployeeSerializer, EmployeeDetailsSerializer\n\nEMP_URL = reverse('personnel:employee-list')\n\n\ndef create_emp(**params):\n\n dept = create_department(\n dept_name='Test department',\n hod='Test Head of Department',\n description='Test department description'\n )\n\n defaults = {\n 'first_name': 'Paul',\n 'last_name': 'David',\n 'date_of_birth': '1990-01-01',\n 'hired_date': '2010-01-01',\n 'identity_type': 'country_id',\n 'highest_qualification': 'associates_degree',\n 'postal_address': 'P O Box 11000',\n 'department': dept,\n 'emp_code': 123\n }\n\n defaults.update(params)\n\n emp = Employee.objects.create(**defaults)\n return emp\n\n\ndef detail_url(emp_id):\n \"\"\"Return the details url\"\"\"\n return reverse('personnel:employee-detail', args=[emp_id])\n\n\nclass PublicEmployeeTest(TestCase):\n \"\"\"Tests for unathenticated users\"\"\"\n def setUp(self) -> None:\n self.client = APIClient()\n\n def test_auth_required(self):\n \"\"\"Test auth required\"\"\"\n res = self.client.get(EMP_URL)\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateEmployeeTest(TestCase):\n \"\"\"Tests for authenticated users\"\"\"\n\n def setUp(self) -> None:\n self.client = APIClient()\n\n self.user = create_user(\n email='testuser@example.com',\n password='testpassword'\n )\n\n self.client.force_authenticate(self.user)\n\n def test_retrieve_employees(self):\n \"\"\"Test retrieve employees\"\"\"\n\n create_emp()\n create_emp()\n\n res = self.client.get(EMP_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(Employee.objects.all().count(), 2)\n emps = Employee.objects.all().order_by('-id')\n serializer = EmployeeSerializer(emps, many=True)\n\n self.assertEqual(res.data, serializer.data)\n\n def test_create_employee(self):\n \"\"\"Test create employee\"\"\"\n\n dept = create_department(\n dept_name='Test department',\n hod='Test Head of Department',\n description='Test department description'\n )\n\n payload = {\n 'first_name': 'Pearl',\n 'last_name': 'David',\n 'date_of_birth': '1990-01-01',\n 'hired_date': '2010-01-01',\n 'identity_type': 'country_id',\n 'highest_qualification': 'associates_degree',\n 'postal_address': 'P O Box 11000',\n 'department': dept.id,\n 'emp_code': 123\n }\n\n res = self.client.post(EMP_URL, payload, format='json')\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n\n emp = Employee.objects.get(id=res.data['id'])\n self.assertEqual(payload['first_name'], emp.first_name)\n\n def test_delete_employee(self):\n \"\"\"Test detele employee\"\"\"\n\n emp = create_emp()\n url = detail_url(emp.id)\n res = self.client.delete(url)\n\n self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)\n self.assertFalse(Employee.objects.filter(id=emp.id).exists())\n\n def test_partial_update(self):\n \"\"\"Test partial update\"\"\"\n emp = create_emp()\n url = detail_url(emp.id)\n\n payload = {\n 'first_name': 'Update'\n }\n\n res = self.client.patch(url, payload)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n emp.refresh_from_db()\n\n self.assertEqual(emp.first_name, payload['first_name'])\n\n def test_full_update(self):\n \"\"\"Test full update\"\"\"\n\n dept = create_department(\n dept_name='Test department update',\n hod='Test update',\n description='Test description update'\n )\n\n defaults = {\n 'first_name': 'Test Update',\n 'last_name': 'Updated',\n 'date_of_birth': '1991-01-01',\n 'hired_date': '2020-01-01',\n 'identity_type': 'country_id',\n 'highest_qualification': 'diploma',\n 'postal_address': 'P O Box 11100',\n 'department': dept,\n 'emp_code': 3212\n }\n\n self.emp = create_emp(**defaults)\n url = detail_url(self.emp.id)\n payload = {\n 'first_name': 'Test Frank',\n 'emp_code': 321\n }\n\n res = self.client.patch(url, payload)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.emp.refresh_from_db()\n\n for k, v in payload.items():\n if k == 'department':\n self.assertEqual(getattr(self.emp, k).id, v)\n else:\n self.assertEqual(getattr(self.emp, k), v)\n\n def test_get_employee_details(self):\n \"\"\"Test get employee details\"\"\"\n emp = create_emp()\n url = detail_url(emp.id)\n\n res = self.client.get(url)\n\n serializer = EmployeeDetailsSerializer(emp)\n\n self.assertEqual(res.data, serializer.data)\n","repo_name":"samKenpachi011/ERP-API","sub_path":"app/personnel/tests/test_employee_api.py","file_name":"test_employee_api.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14638681678","text":"import cv2\nimport numpy as np\nimport time\nimport argparse\n\n# own modules\nimport utills, plot\n\nconfid = 0.5\nthresh = 0.5\nmouse_pts = []\n\n\n# We take 8 points as input and store their raw co-ordinates, first 4 points help us determine the region in which we would to do the surveillance, the 4 points will be quadrilateral's 4 vertices in anti-clockwise order.\n# Then 5-6 points will determine the ratio of 180 cm to pixels in horizontal direction\n# Then 6-7 points will determine the ratio of 180 cm to pixels in vertical direction\n# Point 8 determines that all inputs have been taken\n\ndef store_mouse_clicks(event, x, y, flags, param):\n\n global mouse_pts\n if event == cv2.EVENT_LBUTTONDOWN:\n if len(mouse_pts) < 4:\n cv2.circle(image, (x, y), 5, (0, 0, 255), 10)\n else:\n cv2.circle(image, (x, y), 5, (255, 0, 0), 10)\n \n if len(mouse_pts) >= 1 and len(mouse_pts) <= 3:\n cv2.line(image, (x, y), (mouse_pts[len(mouse_pts)-1][0], mouse_pts[len(mouse_pts)-1][1]), (70, 70, 70), 2)\n if len(mouse_pts) == 3:\n cv2.line(image, (x, y), (mouse_pts[0][0], mouse_pts[0][1]), (70, 70, 70), 2)\n \n if \"mouse_pts\" not in globals():\n mouse_pts = []\n mouse_pts.append((x, y))\n \n\n# Main function of the project\ndef COVID_protocol_monitor(vid_path, net, output_dir, output_vid, ln1):\n \n count = 0\n vs = cv2.VideoCapture(vid_path) \n\n # Video's dimensions and frame per second\n height = int(vs.get(cv2.CAP_PROP_FRAME_HEIGHT))\n width = int(vs.get(cv2.CAP_PROP_FRAME_WIDTH))\n fps = int(vs.get(cv2.CAP_PROP_FPS))\n \n # Set scale for birds eye view\n # Bird's eye view will only show ROI\n scale_w, scale_h = utills.change_scale(width, height)\n\n points = []\n global image\n \n while True:\n\n (grabbed, frame) = vs.read()\n\n if not grabbed:\n print('here')\n break\n \n (H, W) = frame.shape[:2]\n \n # For, first frame we pause it to take the Mouse point inputs\n if count == 0:\n while True:\n image = frame\n cv2.imshow(\"image\", image)\n cv2.waitKey(1)\n if len(mouse_pts) == 8:\n cv2.destroyWindow(\"image\")\n break\n \n points = mouse_pts \n \n # Using the first 4 points to determine and set the Bird's eye correspondence to the given view\n # by using homography through OpenCV's getPerspectiveTransform()\n src = np.float32(np.array(points[:4]))\n dst = np.float32([[0, H], [W, H], [W, 0], [0, 0]])\n prespective_transform = cv2.getPerspectiveTransform(src, dst)\n\n # Getting the Bird's eye view coordinates from raw co-ordinates using the previously set PerspectiveTransform() object\n pts = np.float32(np.array([points[4:7]]))\n warped_pt = cv2.perspectiveTransform(pts, prespective_transform)[0]\n \n # Using Pythagorus theorem to get the distance between point 5 and 6 and distance between 6 and 7\n # which are the pixel distance in Bird's view corresponding to 180cm in real life\n distance_w = np.sqrt((warped_pt[0][0] - warped_pt[1][0]) ** 2 + (warped_pt[0][1] - warped_pt[1][1]) ** 2)\n distance_h = np.sqrt((warped_pt[0][0] - warped_pt[2][0]) ** 2 + (warped_pt[0][1] - warped_pt[2][1]) ** 2)\n pnts = np.array(points[:4], np.int32)\n cv2.polylines(frame, [pnts], True, (70, 70, 70), thickness=2)\n \n ####################################################################################\n \n # Inputting the frame image into the pre-trained YOLO v3 model\n blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)\n net.setInput(blob)\n start = time.time()\n layerOutputs = net.forward(ln1)\n end = time.time()\n boxes = []\n confidences = []\n classIDs = [] \n \n for output in layerOutputs:\n for detection in output:\n scores = detection[5:]\n classID = np.argmax(scores)\n confidence = scores[classID]\n # Checking if humans are present or not\n if classID == 0:\n\n if confidence > confid:\n\n box = detection[0:4] * np.array([W, H, W, H])\n (centerX, centerY, width, height) = box.astype(\"int\")\n\n x = int(centerX - (width / 2))\n y = int(centerY - (height / 2))\n\n boxes.append([x, y, int(width), int(height)])\n confidences.append(float(confidence))\n classIDs.append(classID)\n \n idxs = cv2.dnn.NMSBoxes(boxes, confidences, confid, thresh)\n font = cv2.FONT_HERSHEY_PLAIN\n boxes1 = []\n for i in range(len(boxes)):\n if i in idxs:\n boxes1.append(boxes[i])\n x,y,w,h = boxes[i]\n \n if len(boxes1) == 0:\n count = count + 1\n continue\n\n # We will treat a person as two dimensional coordinates in which the height part is set zero and\n # only x and y coordinates from origin are of importance and origin is defined by the fourth click by the user\n person_points = utills.birds_view_coordinates(boxes1, prespective_transform)\n \n # Generating a distance matrix \n distances_mat, bxs_mat = utills.closeness_calculator(boxes1, person_points, distance_w, distance_h)\n risk_count = utills.count_risk(distances_mat)\n \n frame1 = np.copy(frame)\n \n # Plot circles for humans with colours corresponding to their risk level \n bird_image = plot.plot_top_view(frame, distances_mat, person_points, scale_w, scale_h, risk_count)\n img = plot.frame_view(frame1, bxs_mat, boxes1, risk_count)\n \n # Write output to the respective locations \n # For Bird eye window, it is OpenCV window\n # For Frame view, it will be output folder\n if count != 0:\n \n cv2.imshow('Bird Eye View', bird_image)\n cv2.imwrite(output_dir+\"frame%d.jpg\" % count, img)\n cv2.imwrite(output_dir+\"plot_top_view/frame%d.jpg\" % count, bird_image)\n \n count = count + 1\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n vs.release()\n cv2.destroyAllWindows() \n \n\nif __name__== \"__main__\":\n\n # Receives arguements specified by user\n parser = argparse.ArgumentParser()\n \n parser.add_argument('-v', '--video_path', action='store', dest='video_path', default='C:/Users/humbl/Documents/Social/data/example.mp4' ,\n help='Path for input video')\n \n parser.add_argument('-o', '--output_dir', action='store', dest='output_dir', default='C:/Users/humbl/Documents/Social/output/' ,\n help='Path for Output images')\n\n parser.add_argument('-O', '--output_vid', action='store', dest='output_vid', default='C:/Users/humbl/Documents/Social/output_vid/' ,\n help='Path for Output videos')\n\n parser.add_argument('-m', '--model', action='store', dest='model', default='C:/Users/humbl/Documents/Social/models/',\n help='Path for models directory')\n \n parser.add_argument('-u', '--uop', action='store', dest='uop', default='NO',\n help='Use open pose or not (YES/NO)')\n \n values = parser.parse_args()\n \n model_path = values.model\n if model_path[len(model_path) - 1] != '/':\n model_path = model_path + '/'\n \n output_dir = values.output_dir\n if output_dir[len(output_dir) - 1] != '/':\n output_dir = output_dir + '/'\n \n output_vid = values.output_vid\n if output_vid[len(output_vid) - 1] != '/':\n output_vid = output_vid + '/'\n\n\n # Load YOLO v3 model\n \n weightsPath = model_path + \"yolov3.weights\"\n configPath = model_path + \"yolov3.cfg\"\n\n net_yl = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n ln = net_yl.getLayerNames()\n ln1 = [ln[i[0] - 1] for i in net_yl.getUnconnectedOutLayers()]\n\n # Set mouse back\n\n cv2.namedWindow(\"image\")\n cv2.setMouseCallback(\"image\", store_mouse_clicks)\n np.random.seed(42)\n \n COVID_protocol_monitor(values.video_path, net_yl, output_dir, output_vid, ln1)\n\n\n\n","repo_name":"humblethinker/ML","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"74446482601","text":"def function(s: str):\n curr_ch = s[0]\n cnt = 1\n result_str = \"\"\n\n for i in range(1, len(s)):\n if s[i] != curr_ch:\n result_str += curr_ch + str(cnt)\n curr_ch = s[i]\n cnt = 1\n else:\n cnt += 1\n\n result_str += curr_ch + str(cnt)\n\n if len(s) < len(result_str):\n return s\n else:\n return result_str\n\n\nif __name__ == \"__main__\":\n print(function(s=\"aabcccccaaa\"))\n","repo_name":"dkim94/coding_interview_problems","sub_path":"ch01/1-6.py","file_name":"1-6.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40308165563","text":"# Creating a Thread without using any class\n\n# from threading import *\n\n# def show():\n# for i in range(1,11):\n# print(\"Child Thread\")\n\n# t = Thread(target=show) #creating a thread object\n# t.start()\n# for i in range(1,11):\n# print(\"Main Thread\")\n\n\n# # Creating a Thread by extending Thread class\n\n# from threading import *\n\n# print(current_thread().getName())\n# print(current_thread().setName(\"RAJ\"))\n# print(current_thread().getName())\n\n\n# Creating a Thread without extending Thread class\nfrom threading import *\nclass MyThread:\n def run(self):\n for i in range(1,11):\n print(\"Child Thread\")\n\nm = MyThread()\nt = Thread(target=m.run)\nt.join()\nfor x in range(1,11):\n print(\"Main Thread\")\n\n\n\n","repo_name":"vivekPatil45/Python-ESDP","sub_path":"Multithread.py","file_name":"Multithread.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73701121000","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 ('kirppu', '0005_add_model_itemstatelog'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='item',\n name='lost_property',\n field=models.BooleanField(default=False, help_text='Forgotten or lost property/item'),\n preserve_default=True,\n ),\n ]\n","repo_name":"jlaunonen/kirppu","sub_path":"kirppu/migrations/0006_item_lost_property.py","file_name":"0006_item_lost_property.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30843830960","text":"import json\n\nFILE = './sifu_results/unit_test.json'\n\nwith open(FILE, 'r+') as f:\n # read json\n # =========\n data = json.load(f)\n\n\n # modify json\n # ===========\n # add tag to analyze.py's heap overflow finding only if checker.py labelled that finding\n # with the n=0 identifier\n for finding in data:\n if 'identifier' in finding \\\n and finding['identifier'] == \"all failed test suites contain n=0 test case\":\n msg = finding['msg'].lower()\n if 'error' in msg and 'heap' in msg and 'buffer' in msg and 'flow' in msg:\n finding['tag'] = 'INCREMENTAL_4_COPY_STRINGS__N_EQUAL_TO_ZERO_EDGE_CASE_'\n \n\n # write json back\n # ===============\n f.seek(0)\n json.dump(data, f, indent=2)\n f.truncate()\n","repo_name":"saucec0de/sifu","sub_path":"Challenges/C_CPP/0014_copy_strings/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"70872903721","text":"from bs4 import BeautifulSoup\nfrom datetime import datetime\nimport facebook\nimport feedparser\nimport json\nimport logging\nimport os\nimport sqlite3\nfrom time import mktime\nimport urllib.request\n\n#setup logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nfhandler = logging.FileHandler('fb_feed.log')\nfhandler.setLevel(logging.INFO)\nshandler = logging.StreamHandler()\nshandler.setLevel(logging.INFO)\n\nlogger.addHandler(fhandler)\nlogger.addHandler(shandler)\n\n#load config\nconfig = json.load( open('facebook.json') )\n\n#Check if images dir exists\nimages_dir = \"images/\"\nif not os.path.exists(images_dir):\n logger.info(\"making image dir\")\n os.makedirs(images_dir)\n\n#check if db exists\ndbFile = \"fb_feed.db\"\ndbExists = False\n\nif os.path.isfile(dbFile):\n logger.info(\"database exists\")\n dbExists = True\n\ndb = sqlite3.connect(dbFile)\n\n#make db\ncursor = db.cursor()\nif not dbExists :\n logger.info(\"making database\")\n cursor.execute('''\n CREATE TABLE channel(id INTEGER PRIMARY KEY, name TEXT, title TEXT, url TEXT\n lastBuildDate TEXT)\n ''')\n cursor.execute('''\n CREATE TABLE item(id INTEGER PRIMARY KEY, channel INTEGER, guid TEXT,\n pubDate TEXT)\n ''')\n db.commit()\n\n#get fb tokens\ntoken = config['fb_app_token']\npaget = config['fb_page_token']\n\n#connect to fb graph\ngraph = facebook.GraphAPI(paget)\n\n#check each RSS feed\nfor feed in config['feeds']:\n \n #open feed\n logger.info(\"connecting to \"+feed['name']+\" feed:\"+feed['url'])\n rss = feedparser.parse(feed['url'])\n num_items = 0\n\n #if channel doesn't exist, create it\n logger.info(\"feed is:\"+rss['feed']['title'])\n cursor.execute(\"SELECT id, name, title FROM channel WHERE name = ?\",(feed['name'],))\n all_rows = cursor.fetchall()\n\n if (len(all_rows) <=0):\n logger.info(\"creating feed \"+feed['name']+\": \"+rss['feed']['title']+\" in database\")\n cursor.execute('''INSERT INTO channel(name,title,url)\n VALUES(?,?,?)''', (feed['name'],rss['feed']['title'],feed['url']) )\n channel_id = cursor.lastrowid\n db.commit()\n else:\n channel_id = all_rows[0][0]\n #post a link to the article on the website\n if(feed['type'] == 'link'):\n logger.info(\"posting links\")\n for item in rss['entries']:\n #limit number of posts each update\n if num_items >= feed['max_posts']:\n break\n \n itemDate = datetime.fromtimestamp(mktime(item['published_parsed']))\n\n #skip if already published\n cursor.execute(\"SELECT id, channel, guid, pubDate FROM item WHERE guid = ? AND pubDate = ?\",(item['id'],itemDate.isoformat()))\n item_rows = cursor.fetchall()\n if(len(item_rows) > 0):\n continue\n \n #post a link\n num_items += 1\n try:\n graph.put_object(\n parent_object=\"me\",\n connection_name=\"feed\",\n message=\"\",\n link=item['link'])\n logger.info(\" posted: \"+item['link'])\n\n #update database\n cursor.execute('''INSERT INTO item(channel, guid, pubDate)\n VALUES(?,?,?)''', (channel_id, item['id'], itemDate.isoformat()) )\n db.commit()\n except Exception as e:\n logger.error( e )\n pass\n #post an image to the timeline along with the description\n elif(feed['type'] == 'short'):\n logger.info(\"posting summary\")\n for item in rss['entries']:\n #limit number of posts each update\n if num_items >= feed['max_posts']:\n break\n \n itemDate = datetime.fromtimestamp(mktime(item['published_parsed']))\n\n #skip if already published\n cursor.execute(\"SELECT id, channel, guid, pubDate FROM item WHERE guid = ? AND pubDate = ?\",(item['id'],itemDate.isoformat()))\n item_rows = cursor.fetchall()\n if(len(item_rows) > 0):\n continue\n \n #download image\n soup = BeautifulSoup(item['summary'],features=\"html.parser\")\n img_url = soup.find('img')['src']\n filename = img_url[img_url.rfind(\"/\")+1:]\n logger.info(\"saving image \" + filename)\n urllib.request.urlretrieve(img_url, images_dir+filename)\n \n #post a photo\n num_items += 1\n try:\n graph.put_photo(image=open(images_dir+filename, 'rb'),\n message=item['summary'])\n logger.info(\" posted: \"+item['summary'][0,50]+ \"...\")\n\n #update database\n cursor.execute('''INSERT INTO item(channel, guid, pubDate)\n VALUES(?,?,?)''', (channel_id, item['id'], itemDate.isoformat()) )\n db.commit()\n except Exception as e:\n logger.error( e )\n\n #delete image\n os.remove(images_dir+filename)\n pass\n #post an image to the timeline along with the content-encoded\n elif(feed['type'] == 'long'):\n logger.info(\"posting content-encoded\")\n for item in rss['entries']:\n #limit number of posts each update\n if num_items >= feed['max_posts']:\n break\n \n itemDate = datetime.fromtimestamp(mktime(item['published_parsed']))\n\n #skip if already published\n cursor.execute(\"SELECT id, channel, guid, pubDate FROM item WHERE guid = ? AND pubDate = ?\",(item['id'],itemDate.isoformat()))\n item_rows = cursor.fetchall()\n if(len(item_rows) > 0):\n continue\n \n #download image\n soup = BeautifulSoup(item['summary'],features=\"html.parser\")\n img_url = soup.find('img')['src']\n filename = img_url[img_url.rfind(\"/\")+1:]\n logger.info(\"saving image \" + filename)\n urllib.request.urlretrieve(img_url, images_dir+filename)\n \n #post a photo\n num_items += 1\n try:\n graph.put_photo(image=open(images_dir+filename, 'rb'),\n message=item['content'][0]['value'])\n logger.info(\" posted: \"+item['content'][0]['value'][0,50]+ \"...\")\n\n #update database\n cursor.execute('''INSERT INTO item(channel, guid, pubDate)\n VALUES(?,?,?)''', (channel_id, item['id'], itemDate.isoformat()) )\n db.commit()\n except Exception as e:\n logger.error( e )\n \n #delete image\n os.remove(images_dir+filename)\n pass\n\nlogger.info(\"Shutting down\")\ndb.close()\n","repo_name":"karmacop/socialRSS","sub_path":"facebookfeed.py","file_name":"facebookfeed.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71732237480","text":"kleur_kaas = input(\"Welke kleur is de kaas: \")\nif kleur_kaas == \"geel\":\n gaten_kaas = input(\"Zitten er gaten in? \")\n if gaten_kaas == \"ja\":\n duur_kaas = input(\"Is de kaas belachelijk duur? \")\n if duur_kaas == \"ja\":\n print(\"Emmenthaler\")\n else:\n print(\"Leerdammer\")\n else:\n harde_kaas = input(\"Is de kaas hard als steen? \")\n if harde_kaas == \"ja\":\n print(\"Parmigiano Reggiano\")\n else:\n print(\"Goudsee Kaas\")\nelse:\n blauwe_schimmel = input(\"Heeft de kaas blauwe schimmel? \")\n if blauwe_schimmel == \"ja\":\n harde_korst = input(\"Heeft de kaas een harde korst? \")\n if harde_korst == \"ja\":\n print(\"Blue de Rochbaron \")\n else:\n print(\"foume d'Ambert \")\n else:\n korst = input(\"Heeft de kaas een korst? \")\n if korst == \"ja\":\n print(\"Camembert\")\n else:\n print(\"mozzarella\")\n\n","repo_name":"JasperRutte/leren-programeren","sub_path":"projects/Leren-programmeren/Module-02/kaasflow.py","file_name":"kaasflow.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9456649542","text":"#!/usr/bin/env python3\n\nimport pandas as pd\n\n\n#---------------------\n# DataFrame\n#---------------------\n\ndf01 = pd.DataFrame({'Yes': [50, 21], 'No': [131, 2]})\nprint(df01)\n\ndf02 = pd.DataFrame({'Bob': ['I like it.', 'It was awful.'], 'Sue': ['Pretty good.', 'Bland.']})\nprint(df02)\n\n\ndf03 = pd.DataFrame({'Bob': ['I like it.', 'It was awful.'],\n 'Sue': ['Pretty good.', 'Bland.']},\n index=['Product A', 'Product B'])\nprint(df03)\n\n\n#-------------------\n# Series\n#-------------------\n\ns01 = pd.Series([1, 2, 3, 4, 5])\nprint(s01)\n\ns02 = pd.Series([30, 25, 40],\n index=['2015 Sales', '2016 Sales', '2017 Sales'],\n name='Product A')\nprint(s02)\n\n\n#----------------------------\n# Reading data files\n#----------------------------\n\nfile01 = pd.read_csv(\"../data/melb_data.csv\")\n\n# sometimes, your data files may already have a built-in index that you can use instead\n# (pd will make an index for you by default, in which case you'll have 2 index columns)\n# here, I say I want to use the first column from my ingested data as the index column\n#file01 = pd.read_csv(\"../data/melb_data.csv\", index_col=0)\n\n# shape returns (num rows, num columns)\nprint(file01.shape)\n\n# write to file, exclude index\nfile01.to_csv('output_file.csv', index=False)\n\n# if you want the index be included in the output\n#file01.to_csv('output_file.csv')\n","repo_name":"Neutrollized/learning-machine-learning","sub_path":"pandas/00_basics.py","file_name":"00_basics.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3047926371","text":"import logging\n\nfrom aiogram import Bot\n\n__all__ = (\"TelegramService\")\n\nlogger = logging.getLogger(__name__)\n\n\nclass TelegramService:\n \"\"\"\n The class encapsulate logic with TG api via aiogram package\n \"\"\"\n def __init__(self, token: str, chat_id: str) -> None:\n self.__bot = Bot(token=token)\n self.__chat_id = chat_id\n\n async def send_text_message(self, text: str) -> None:\n \"\"\"\n Sends text message to telegram chat\n \"\"\"\n logger.debug(f\"TG API send text message: '{text}'\")\n\n await self.__bot.send_message(chat_id=self.__chat_id, text=text)\n\n logger.debug(f\"TG message has been sent.\")\n","repo_name":"WISEPLAT/python-code","sub_path":" invest-robot-contest_invest-bot-main/tg_api/telegram_service.py","file_name":"telegram_service.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"18"} +{"seq_id":"37434153249","text":"# import random\n# list1 = []\n# for i in range(20):\n# randomnum = random.randint(1,100)\n# list1.append(randomnum)\n# # if randomnum==mynum:\n# # list1.remove(randomnum)\n#\n# print(list1)\n#\n# mynum=int(input(\"choose a number between 1-100:\"))\n#\n# for i in list1:\n# if randomnum==mynum:\n# list1.remove(randomnum)\n\nfrom random import randint\nlist1=[randint (1,100) for i in range (20)]\nprint (list1)\nnum=int(input(\"enter number to remove:\"))\n\nwhile num in list1:\n list1.remove(num)\n\nprint(list1)","repo_name":"shlomi7600/pythonProject","sub_path":"qa/list/list_ex_13.py","file_name":"list_ex_13.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38806064007","text":"# Most applications are configured to log to a file. Use the basicConfig() function to set up\r\n# the default handler so that debug messages are written to a file.\r\n# Running the script in the listing repeatedly causes more messages to be appended\r\n# to the file.\r\n\r\nimport logging\r\n\r\nLOG_FILENAME = 'logging_example.out'\r\n\r\nlogging.basicConfig(\r\nfilename=LOG_FILENAME,\r\nlevel=logging.DEBUG,\r\n)\r\nlogging.debug('This message should go to the log file') #input\r\nwith open(LOG_FILENAME, 'rt') as f:\r\n\tbody = f.read()\r\nprint('FILE:')\r\nprint(body)\r\n","repo_name":"yeboahd24/Python201","sub_path":"PYTHON LIBRARY/SUB_15/logging_file_example.py","file_name":"logging_file_example.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"15857499233","text":"import requests\nimport sys\n\ndef getChangedFiles(TRAVIS_PULL_REQUEST):\n response = requests.get(\"https://api.github.com/repos/Rohan-Shinde-98/test-pr-files/pulls/\"+str(TRAVIS_PULL_REQUEST)+\"/files\")\n \n file = open('changed_files.txt','a')\n for object in response.json():\n string = object['filename'] + \" \" + object['raw_url'] +\"\\n\" \n file.write(string)\n file.close()\n\nif __name__==\"__main__\":\n getChangedFiles(sys.argv[1])\n","repo_name":"Rohan-Shinde-98/test-pr-files","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11494884141","text":"from os import listdir\nimport numpy as np\nimport operator\n\ndef dataSet():\n\tgroup = np.array([[1., 1.1], [1.0,1.0],[0,0],[0,0.1]])\n\tlabels = np.array(['A', 'A', 'B', 'B'])\n\treturn group, labels\n\ndef classify0(X, dataS, labels, k):\n\tdataSize = dataS.shape[0]\n\tdiffMat = np.tile(X, (dataSize, 1)) - dataS\n\tsqDiff = diffMat**2\n\tsqDistance = sqDiff.sum(axis=1)\n\tdist = sqDistance**0.5\n\tdistSort = dist.argsort()\n\tclassCount={}\n\tfor x in range(k):\n\t\tvoteLabels = labels[distSort[x]]\n\t\tclassCount[voteLabels] = classCount.get(voteLabels, 0) + 1\n\tsortClassCount = sorted(classCount.iteritems(),\n\t\tkey= operator.itemgetter(1), reverse=True)\n\treturn sortClassCount[0][0]\n\ndef fileToMatrix(filename):\n\tfileread = open(filename)\n\tcountLines = len(fileread.readlines())\n\treturnMat = np.zeros((countLines, 3))\n\tclassLabels = []\n\tfileread = open(filename)\n\n\tindex = 0\n\n\tfor line in fileread.readlines():\n\t\tline = line.strip() \n\t\tlFromLine = line.split('\\t')\n\t\treturnMat[index, :] = lFromLine[0:3]\n\t\tlabels = {'didntLike':1, 'smallDoses':2, 'largeDoses':3}\n\t\tclassLabels.append(labels[lFromLine[-1]])\n\t\tindex += 1\n\treturn returnMat, classLabels\ndef normalize(dataSet):\n\tminVal = dataSet.min(0)\n\tmaxVal = dataSet.max(0)\n\tranges = maxVal - minVal\n\tnormDataSet = np.zeros(np.shape(dataSet))\n\tm = dataSet.shape[0]\n\tnormDataSet = dataSet - np.tile(minVal, (m,1))\n\tnormDataSet = normDataSet / np.tile(ranges, (m, 1))\n\treturn normDataSet, ranges, minVal\n\ndef datingClassTest():\n\n\thoRatio = 0.10\n\tdatingDataMat, datingLabels = fileToMatrix('datingTestSet.txt')\n\tnormMat, ranges, minVals = normalize(datingDataMat)\n\tm = normMat.shape[0]\n\tnumTestVecs = int(m*hoRatio)\n\terrorCount = 0.0\n\n\tfor i in range(numTestVecs):\n\t\tclassifierResult = classify0(normMat[i, :], normMat[numTestVecs:m,:], datingLabels[numTestVecs:m],3)\n\t\tprint('the class came back with: %d, the real answer is %d' % (classifierResult, datingLabels[i]))\n\n\t\tif(classifierResult != datingLabels[i]): errorCount += 1.0\n\tprint('the total error rate is: %f' % (errorCount/float(numTestVecs)))\n\ndef classifyPerson():\n\n\tresultList = ['not at all', 'in small doses', 'in large doses']\n\tpersentTats = float(raw_input('percentage of time spent playing games? '))\n\tffMiles = float(raw_input('frquent flier miles earned /year? '))\n\ticeCream = float(raw_input('liters of ice cream consumed /year? '))\n\tdatingDataMat, datingLabels = fileToMatrix('datingTestSet.txt')\n\tnormMat, ranges, minVals = normalize(datingDataMat)\n\tinArr = np.array([ffMiles, persentTats, iceCream])\n\tclassifierResult = classify0((inArr-minVals) / ranges, normMat, datingLabels, 3)\n\tprint('You\\'ll probably like this person: ', resultList[classifierResult - 1])\n\ndef imgToVec(filename):\n\treturnVect = np.zeros((1,1024))\n\tfileread = open(filename)\n\tfor i in range(32):\n\t\tlineStr = fileread.readline()\n\t\tfor j in range(32):\n\t\t\treturnVect[0, 32*i+j] = int(lineStr[j])\n\treturn returnVect\ndef handwritingClassify0():\n\thwLabels = []\n\ttrainingFileList = listdir('trainingDigits')\n\tm = len(trainingFileList)\n\ttrainingMat = np.zeros((m, 1024))\n\tfor i in range(m):\n\t\tfileNameStr = trainingFileList[i]\n\t\tfileStr = fileNameStr.split('.')[0]\n\t\tclassNumStr = int(fileStr.split('_')[0])\n\t\thwLabels.append(classNumStr)\n\t\ttrainingMat[i, :] = imgToVec('trainingDigits/%s' % fileNameStr)\n\t\ttestFileList = listdir('testDigits')\n\t\terrorCount = 0.0\n\t\tmTest = len(testFileList)\n\t\tfor i in range(mTest):\n\t\t\tfileNameStr = testFileList[i]\n\t\t\tfileStr = fileNameStr.split('.')[0]\n\t\t\tclassNumStr = int(fileStr.split('_')[0])\n\t\t\tvectorUnderTest = imgToVec('testDigits/%s' % fileNameStr)\n\t\t\tclassifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)\n\t\t\tprint('classifier with: %d, real answer: %d' % (classifierResult, classNumStr))\n\t\t\tif(classifierResult != classNumStr): errorCount += 1.0\n\t\tprint('total number of errors: %d' % errorCount)\n\t\tprint('error rate: %f' % (errorCount/float(mTest)))","repo_name":"mickymount/mlinaction","sub_path":"kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26906332534","text":"import xml.etree.ElementTree as ET\nfrom os import path\n\nfrom tinydb import Query, where\n\nimport config\nimport random\nimport time\n\nfrom fastapi import APIRouter, Request, Response\n\nfrom core_common import core_process_request, core_prepare_response, E\nfrom core_database import get_db\n\nrouter = APIRouter(prefix=\"/local\", tags=[\"local\"])\nrouter.model_whitelist = [\"REC\"]\n\n\ndef get_profile(cid):\n return get_db().table(\"dancerush_profile\").get(where(\"card\") == cid)\n\n\ndef get_game_profile(cid, game_version):\n profile = get_profile(cid)\n\n return profile[\"version\"].get(str(game_version), None)\n\n\ndef get_id_from_profile(cid):\n profile = get_db().table(\"dancerush_profile\").get(where(\"card\") == cid)\n\n djid = \"%08d\" % profile[\"drs_id\"]\n djid_split = \"-\".join([djid[:4], djid[4:]])\n\n return profile[\"drs_id\"], djid_split\n\n\n@router.post(\"/{gameinfo}/game/get_common\")\nasync def drs_game_get_common(request: Request):\n request_info = await core_process_request(request)\n\n songs = {}\n\n # TODO: server side song unlock is incomplete, use hex edits for now\n for f in (\n path.join(\"modules\", \"drs\", \"music-info-base.xml\"),\n path.join(\"music-info-base.xml\"),\n ):\n if path.exists(f):\n with open(f, \"r\", encoding=\"utf-8\") as fp:\n tree = ET.parse(fp, ET.XMLParser())\n root = tree.getroot()\n\n for entry in root:\n mid = entry.get(\"id\")\n songs[mid] = {}\n for atr in (\n \"title_name\",\n \"title_yomigana\",\n \"artist_name\",\n \"artist_yomigana\",\n \"bpm_max\",\n \"bpm_min\",\n # \"distribution_date\",\n \"volume\",\n \"bg_no\",\n \"region\",\n # \"limitation_type\",\n # \"price\",\n \"genre\",\n \"play_video_flags\",\n \"is_fixed\",\n \"version\",\n \"demo_pri\",\n \"license\",\n \"color1\",\n \"color2\",\n \"color3\",\n ):\n songs[mid][atr] = entry.find(f\"info/{atr}\").text\n if songs[mid][atr] == None:\n songs[mid][atr] = \"\"\n for atr in (\n \"1b\",\n \"1a\",\n \"2b\",\n \"2a\",\n ):\n songs[mid][f\"{atr}_difnum\"] = entry.find(\n f\"difficulty/fumen_{atr}/difnum\"\n ).text\n # songs[mid][f\"{atr}_playable\"] = entry.find(f\"difficulty/fumen_{atr}/playable\").text\n break\n\n response = E.response(\n E.game(\n E.mdb(\n *[\n E.music(\n E.info(\n E.title_name(songs[s][\"title_name\"], __type=\"str\"),\n E.title_yomigana(songs[s][\"title_yomigana\"], __type=\"str\"),\n E.artist_name(songs[s][\"artist_name\"], __type=\"str\"),\n E.artist_yomigana(\n songs[s][\"artist_yomigana\"], __type=\"str\"\n ),\n E.bpm_max(songs[s][\"bpm_max\"], __type=\"u32\"),\n E.bpm_min(songs[s][\"bpm_min\"], __type=\"u32\"),\n E.distribution_date(20180427, __type=\"u32\"),\n E.volume(songs[s][\"volume\"], __type=\"u16\"),\n E.bg_no(songs[s][\"bg_no\"], __type=\"u16\"),\n E.region(\"JUAKYC\", __type=\"str\"),\n E.limitation_type(3, __type=\"u8\"),\n E.price(0, __type=\"s32\"),\n E.genre(songs[s][\"genre\"], __type=\"u32\"),\n E.play_video_flags(\n songs[s][\"play_video_flags\"], __type=\"u32\"\n ),\n E.is_fixed(songs[s][\"is_fixed\"], __type=\"u8\"),\n E.version(songs[s][\"version\"], __type=\"u8\"),\n E.demo_pri(songs[s][\"demo_pri\"], __type=\"u8\"),\n E.license(songs[s][\"license\"], __type=\"str\"),\n E.color1(int(songs[s][\"color1\"], 16), __type=\"u32\"),\n E.color2(int(songs[s][\"color2\"], 16), __type=\"u32\"),\n E.color3(int(songs[s][\"color3\"], 16), __type=\"u32\"),\n ),\n E.difficulty(\n E.fumen_1b(\n E.difnum(songs[s][\"1b_difnum\"], __type=\"u8\"),\n E.playable(1, __type=\"u8\"),\n ),\n E.fumen_1a(\n E.difnum(songs[s][\"1a_difnum\"], __type=\"u8\"),\n E.playable(1, __type=\"u8\"),\n ),\n E.fumen_2b(\n E.difnum(songs[s][\"2b_difnum\"], __type=\"u8\"),\n E.playable(1, __type=\"u8\"),\n ),\n E.fumen_2a(\n E.difnum(songs[s][\"2a_difnum\"], __type=\"u8\"),\n E.playable(1, __type=\"u8\"),\n ),\n ),\n id=s,\n )\n for s in songs\n ],\n ),\n E.extra(*[E.info(E.music_id(i, __type=\"s32\")) for i in songs]),\n E.contest(\n *[\n E.info(\n E.contest_id(i, __type=\"s32\"),\n E.start_date(1683422123358, __type=\"u64\"),\n E.end_date(1693422123358, __type=\"u64\"),\n E.title(\"\", __type=\"str\"),\n E.regulation(i, __type=\"s32\"),\n E.target_music(\n E.music(\n E.music_id(1, __type=\"s32\"),\n E.music_type(\"1b\", __type=\"str\"),\n )\n ),\n )\n for i in range(1, 3)\n ]\n ),\n E.event(\n *[\n E.info(\n E.event_id(e, __type=\"s32\"),\n E.start_date(1683422123358, __type=\"u64\"),\n E.end_date(1693422123358, __type=\"u64\"),\n E.param(\"\", __type=\"str\"),\n )\n for e in range(1, 14)\n ]\n ),\n # E.kac2020(\n # E.reward(\n # E.data(\n # E.music_id(1, __type=\"s32\"),\n # E.is_available(1, __type=\"bool\"),\n # )\n # )\n # ),\n # E.silhouette(E.info(E.silhouette_id(i, __type=\"s32\"))),\n # E.music_condition(*[E.music(E.conditions(), id=s) for s in songs]),\n )\n )\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/get_playdata_{player}\")\nasync def drs_game_get_playdata(player: str, request: Request):\n request_info = await core_process_request(request)\n game_version = request_info[\"game_version\"]\n\n dataid = request_info[\"root\"][0].find(\"userid/refid\").text\n profile = get_game_profile(dataid, game_version)\n\n if profile:\n djid, djid_split = get_id_from_profile(dataid)\n\n response = E.response(\n E.game(\n E.result(0, __type=\"s32\"),\n E.userid(E.code(djid, __type=\"s32\")),\n E.profile(E.name(profile[\"name\"], __type=\"str\")),\n E.playinfo(\n E.softcode(\"\", __type=\"str\"),\n E.start_date(1683422123358, __type=\"u64\"),\n E.end_date(1683422123358, __type=\"u64\"),\n E.mode_id(profile[\"mode_id\"], __type=\"s32\"),\n E.music_id(profile[\"music_id\"], __type=\"s32\"),\n E.music_type(profile[\"music_type\"], __type=\"str\"),\n E.pcbid(\"0\", __type=\"str\"),\n E.locid(\"EA000001\", __type=\"str\"),\n ),\n E.paramdata(\n *[\n E.data(\n E.data_type(p[0], __type=\"s32\"),\n E.data_id(p[1], __type=\"s32\"),\n E.param_list(p[2], __type=\"s32\"),\n )\n for p in profile[\"params\"]\n ]\n ),\n E.dance_dance_rush(E.data()),\n E.summer_dance_damp(E.data()),\n E.kac2020(),\n E.hidden_param(0, __type=\"s32\"),\n E.play_count(1001, __type=\"u32\"),\n E.daily_count(301, __type=\"u32\"),\n E.play_chain(31, __type=\"u32\"),\n )\n )\n\n else:\n response = E.response(\n E.game(\n E.result(1, __type=\"s32\"),\n )\n )\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/lock_multi_login_{player}\")\nasync def drs_game_lock_multi_login(player: str, request: Request):\n request_info = await core_process_request(request)\n\n response = E.response(E.game())\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/sign_up_{player}\")\nasync def drs_game_sign_up(player: str, request: Request):\n request_info = await core_process_request(request)\n game_version = request_info[\"game_version\"]\n\n root = request_info[\"root\"][0]\n\n dataid = root.find(\"userid/dataid\").text\n cardno = root.find(\"userid/cardno\").text\n name = root.find(\"profile/name\").text\n\n db = get_db().table(\"dancerush_profile\")\n all_profiles_for_card = db.get(Query().card == dataid)\n\n if all_profiles_for_card is None:\n all_profiles_for_card = {\"card\": dataid, \"version\": {}}\n\n if \"drs_id\" not in all_profiles_for_card:\n drs_id = random.randint(10000000, 99999999)\n all_profiles_for_card[\"drs_id\"] = drs_id\n\n all_profiles_for_card[\"version\"][str(game_version)] = {\n \"game_version\": game_version,\n \"name\": name,\n \"mode_id\": 0,\n \"music_id\": 1,\n \"music_type\": \"1a\",\n \"params\": [],\n }\n\n db.upsert(all_profiles_for_card, where(\"card\") == dataid)\n\n response = E.response(E.game())\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/get_musicscore_{player}\")\nasync def drs_get_musicscore(player: str, request: Request):\n request_info = await core_process_request(request)\n game_version = request_info[\"game_version\"]\n\n scores = []\n db = get_db()\n for record in db.table(\"drs_scores_best\").search(\n (where(\"game_version\") == game_version)\n ):\n scores.append(\n [\n record[\"music_id\"],\n record[\"music_type\"],\n record[\"score\"],\n record[\"rank\"],\n record[\"combo\"],\n record[\"param\"],\n ]\n )\n\n response = E.response(\n E.game(\n E.scoredata(\n *[\n E.music(\n E.music_id(s[0], __type=\"s32\"),\n E.music_type(s[1], __type=\"str\"),\n E.play_cnt(1, __type=\"s32\"),\n E.score(s[2], __type=\"s32\"),\n E.rank(s[3], __type=\"s32\"),\n E.combo(s[4], __type=\"s32\"),\n E.param(s[5], __type=\"s32\"),\n E.bestscore_date(1683422123358, __type=\"u64\"),\n E.lastplay_date(1683422123358, __type=\"u64\"),\n )\n for s in scores\n ],\n ),\n ),\n )\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/save_musicscore\")\nasync def drs_save_musicscore(request: Request):\n request_info = await core_process_request(request)\n game_version = request_info[\"game_version\"]\n\n timestamp = time.time()\n\n root = request_info[\"root\"][0][0]\n\n dataid = root.find(\"userid/refid\").text\n profile = get_game_profile(dataid, game_version)\n djid, djid_split = get_id_from_profile(dataid)\n\n music_id = int(root.find(\"music_id\").text)\n music_type = root.find(\"music_type\").text\n mode = int(root.find(\"mode\").text)\n score = int(root.find(\"score\").text)\n rank = int(root.find(\"rank\").text)\n combo = int(root.find(\"combo\").text)\n param = int(root.find(\"param\").text)\n perfect = int(root.find(\"member/perfect\").text)\n great = int(root.find(\"member/great\").text)\n good = int(root.find(\"member/good\").text)\n bad = int(root.find(\"member/bad\").text)\n\n db = get_db()\n db.table(\"drs_scores\").insert(\n {\n \"timestamp\": timestamp,\n \"game_version\": game_version,\n \"drs_id\": djid,\n \"music_id\": music_id,\n \"music_type\": music_type,\n \"mode\": mode,\n \"score\": score,\n \"rank\": rank,\n \"combo\": combo,\n \"param\": param,\n \"perfect\": perfect,\n \"great\": great,\n \"good\": good,\n \"bad\": bad,\n },\n )\n\n best = db.table(\"drs_scores_best\").get(\n (where(\"drs_id\") == djid)\n & (where(\"game_version\") == game_version)\n & (where(\"music_id\") == music_id)\n & (where(\"music_type\") == music_type)\n )\n best = {} if best is None else best\n\n best_score_data = {\n \"game_version\": game_version,\n \"drs_id\": djid,\n \"name\": profile[\"name\"],\n \"music_id\": music_id,\n \"music_type\": music_type,\n \"score\": max(score, best.get(\"score\", score)),\n \"rank\": max(rank, best.get(\"rank\", rank)),\n \"combo\": max(combo, best.get(\"combo\", combo)),\n \"param\": param,\n }\n\n db.table(\"drs_scores_best\").upsert(\n best_score_data,\n (where(\"drs_id\") == djid)\n & (where(\"game_version\") == game_version)\n & (where(\"music_id\") == music_id)\n & (where(\"music_type\") == music_type),\n )\n\n response = E.response(E.game())\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n\n\n@router.post(\"/{gameinfo}/game/save_playdata\")\nasync def drs_save_musicscore(request: Request):\n request_info = await core_process_request(request)\n game_version = request_info[\"game_version\"]\n\n root = request_info[\"root\"][0][0]\n\n dataid = root.find(\"userid/refid\").text\n\n profile = get_profile(dataid)\n game_profile = profile[\"version\"].get(str(game_version), {})\n\n game_profile[\"mode_id\"] = int(root.find(\"playinfo/mode_id\").text)\n game_profile[\"music_id\"] = int(root.find(\"playinfo/music_id\").text)\n game_profile[\"music_type\"] = root.find(\"playinfo/music_type\").text\n\n old_params = game_profile[\"params\"]\n params = {}\n\n for old in old_params:\n t = str(old[0])\n i = str(old[1])\n p = old[2]\n if t not in params:\n params[t] = {}\n if i not in params[t]:\n params[t][i] = {}\n params[t][i] = p\n\n for info in root.find(\"paramdata\"):\n t = info.find(\"data_type\").text\n i = info.find(\"data_id\").text\n p = info.find(\"param_list\")\n\n if t not in params:\n params[t] = {}\n if i not in params[t]:\n params[t][i] = {}\n params[t][i] = [int(x) for x in p.text.split(\" \")]\n\n params_list = []\n\n for t in params:\n for i in params[t]:\n params_list.append([int(t), int(i), params[t][i]])\n\n game_profile[\"params\"] = params_list\n\n profile[\"version\"][str(game_version)] = game_profile\n\n get_db().table(\"dancerush_profile\").upsert(profile, where(\"card\") == dataid)\n\n response = E.response(E.game())\n\n response_body, response_headers = await core_prepare_response(request, response)\n return Response(content=response_body, headers=response_headers)\n","repo_name":"drmext/MonkeyBusiness","sub_path":"modules/drs/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":17164,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"18"} +{"seq_id":"13366198777","text":"\"\"\"\n求一个数的最大约数\n\n\n1、这种算法,效率是比较高的:\n 能够被2整除的约数最大,\n 因此先找到可能的最大约数, 然后让这个数依次减1是否能被输入的数整除\n\n2、else\n while 循环中没有异常和中断语句,就会执行else中的内容。\n\"\"\"\ndef showMaxFactor(num):\n\n n = num // 2\n c = 0\n while n > 1:\n c += 1\n if num % n == 0:\n print(\"%d的最大约数是%d\" % (num, n) )\n break\n n -= 1\n else:\n #素数:只能被1和自身整除的数\n print(\"%d是一个素数\" % num)\n print(\"循环次数:%d\" % c)\ntry:\n input_no = int(input(\"请输入一个数字:\"))\n showMaxFactor(input_no)\nexcept ValueError as reason:\n print(\"你输入的不是数字!!!%s\" % reason)\n","repo_name":"mymusic56/python-hello-world","sub_path":"day-02/3-while-else.py","file_name":"3-while-else.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25869802899","text":"# Requires Python >= 3.10 (insort uses the new 'key' param).\nfrom bisect import insort\nfrom collections import defaultdict\nimport math\n\n\ndef find(grid, vals):\n for k, v in grid.items():\n if v in vals:\n yield k\n\n\ndef get_neighbors(grid, pos):\n row, col = pos\n for target in ((row - 1, col), (row, col - 1), (row, col + 1), (row + 1, col)):\n if target in grid and ord(grid[target]) <= ord(grid[pos]) + 1:\n yield target\n\n\ndef shortest_path(grid, start, end):\n path_costs = defaultdict(lambda: math.inf, {k: 0 for k in start})\n heap = start # poor man's min-heap\n heap.sort(key=lambda x: path_costs[x], reverse=True)\n while heap:\n node = heap[-1]\n if node == end:\n return path_costs[end]\n heap.pop()\n for neighbor in get_neighbors(grid, node):\n if path_costs[node] + 1 < path_costs[neighbor]:\n path_costs[neighbor] = path_costs[node] + 1\n insort(heap, neighbor, key=lambda x: -path_costs[x])\n return None\n\n\ndef main():\n with open(\"day12/input.txt\", mode=\"r\", encoding=\"utf-8\") as file:\n grid = {(i, j): v for j, row in enumerate(file) for i, v in enumerate(row[:-1])}\n start, end = find(grid, set(\"SE\"))\n grid[start], grid[end] = \"a\", \"z\"\n print(\"1:\", shortest_path(grid, [start], end))\n print(\"2:\", shortest_path(grid, [k for k in grid if grid[k] == \"a\"], end))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alexcsf/aoc2022","sub_path":"day12/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18353770911","text":"products = []\r\n\r\ndef is_pan(string: str) -> bool:\r\n for i in range(len(string)):\r\n if string.count(string[i]) > 1: return False\r\n return True\r\n\r\nfor a in range(2, 291):\r\n for b in range(1, int(78885/a)+2):\r\n term = str(a) + str(b) + str(a*b)\r\n if is_pan(term) and len(term) == 9 and term.count(\"0\") == 0 and not a*b in products: products.append(a*b) \r\n \r\nprint(sum(products))\r\n","repo_name":"colo1701/projecteuler.net_python","sub_path":"pe_032.py","file_name":"pe_032.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38921844377","text":"from argparse import ArgumentParser\n\nfrom .nblyzer import NBLyzer\nfrom .events import RunBatchEvent\nfrom .resource_utils.rsrc_mngr import ResourceManager\nfrom .resource_utils.utils import is_script\n\ndef nblyzer(filename, notebook, analyses, start, level=5):\n code_nblyzer = NBLyzer(level = level)\n assert(not (filename and notebook))\n mng = ResourceManager()\n if (notebook is None):\n assert(filename)\n if is_script(filename):\n notebook = mng.grab_local_file(filename)\n code_nblyzer.load_script(notebook)\n else:\n notebook = mng.grab_local_json(filename)\n code_nblyzer.load_notebook(notebook[\"cells\"])\n else:\n code_nblyzer.load_notebook(notebook[\"cells\"])\n \n code_nblyzer.add_analyses(analyses)\n event = RunBatchEvent(start)\n results = code_nblyzer.execute_event(event).dumps(True)\n\n return results\n\ndef main():\n parser = ArgumentParser(description=\"NBLyzer version 1.0 \")\n group = parser.add_mutually_exclusive_group(required=True)\n\n group.add_argument(\"-f\", \"--filename\", type=str, help='Filename of notebook.')\n group.add_argument(\"-n\", \"--notebook\", type=str, help='Notebook json string.')\n parser.add_argument(\"-a\", \"--analyses\", nargs=\"+\", type=str, default=[], help='Analyses to perform.')\n parser.add_argument(\"-s\", \"--start\", type=int, default=0, help='Starting cell ID (default is 0).')\n parser.add_argument(\"-l\", \"--level\", nargs=\"?\", type=int, default=5, help='Depth level of the analysis (default is inf).')\n args = parser.parse_args()\n\n results = nblyzer(args.filename, args.notebook, args.analyses, args.start, args.level)\n print(results)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"microsoft/NBLyzer","sub_path":"framework/nblyzer/src/nblyzer_cli.py","file_name":"nblyzer_cli.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"5910148242","text":"def transform_list(part_list): #transforming list form\r\n Liste = []\r\n for i in range(len(part_list)):\r\n Liste.append([])\r\n for k in range(len(part_list[i])):\r\n if type(part_list[i][k]) == tuple:\r\n Liste[-1].append(list(part_list[i][k]))\r\n else:\r\n Liste[-1].append(part_list[i][k])\r\n return Liste\r\n\r\ndef searching_nodes(Liste,item): #inserting nodes into tree\r\n for i in range(len(Liste)):\r\n if type(Liste[i]) == list:\r\n searching_nodes(Liste[i],item)\r\n elif Liste[i]== item[0]:\r\n Liste += item[1:]\r\n\r\ndef sorting_list(queue):\r\n flat = []\r\n root = None\r\n for k in range(len(queue)):\r\n for i in range(len(queue[k])):\r\n if type(queue[k][i])==list:\r\n for j in range(len(queue[k][i])):\r\n if type(queue[k][i][j])== str:\r\n flat.append(queue[k][i][j]) \r\n elif type(queue[k][i]) == str:\r\n flat.append(queue[k][i])\r\n for i in flat:\r\n a = flat.count(i)\r\n if a ==1:\r\n root = i\r\n #print(root)\r\n for i in range(len(queue)):\r\n if queue[i][0]==root:\r\n queue = queue[:i]+ queue[i+1:]+ [queue[i]]\r\n return queue\r\n \r\ndef create_tree(part_list): #creating tree completely\r\n part_list = transform_list(part_list)\r\n queue = sorting_list(part_list)\r\n #print(queue)\r\n while len(queue)>1:\r\n item = queue.pop(0)\r\n searching_nodes(queue,item)\r\n return [1] + queue[0] \r\n \r\ndef calculate_price(part_list):\r\n part_list = create_tree(part_list)\r\n price = [0]\r\n def calculate_price_helper(part_list_new,number):\r\n if type(part_list_new[-1]) == float:\r\n price[0] += number*part_list_new[0]*part_list_new[-1]\r\n else:\r\n for i in part_list_new[2:]:\r\n calculate_price_helper(i,part_list_new[0]*number)\r\n return price[0]\r\n return calculate_price_helper(part_list,1)\r\n\r\ndef required_parts(part_list):\r\n part_list = create_tree(part_list)\r\n required_list = []\r\n def required_parts_helper(part_list,time):\r\n total = time\r\n number = part_list[0]\r\n children = part_list[2:]\r\n if type(part_list[-1]) == float:\r\n total *= number\r\n required_list.append((int(total),part_list[1]))\r\n else:\r\n total *= number\r\n for i in children:\r\n #print(total,i)\r\n required_parts_helper(i,total)\r\n return required_list\r\n return required_parts_helper(part_list,1)\r\n\r\ndef stock_check(part_list,stock_list):\r\n required_list_new = required_parts(part_list)\r\n required_stock = []\r\n while required_list_new:\r\n item = required_list_new.pop(0)\r\n occur = False\r\n for j in range(len(stock_list)):\r\n r_number = item[0]\r\n r_item = item[1]\r\n s_number = stock_list[j][0]\r\n s_item = stock_list[j][1] \r\n if r_item == s_item:\r\n if r_number > s_number :\r\n number = r_number - s_number\r\n required_stock.append((r_item,number))\r\n occur= True \r\n if occur == False:\r\n required_stock.append((item[1],item[0]))\r\n return required_stock\r\n\r\n#print(required_parts(L))\r\n#print(stock_check(L,s))\r\n#print(calculate_price(L))","repo_name":"gurhanadiguzel/METU-Ceng","sub_path":"CENG111/THE3/the3.py","file_name":"the3.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31294072304","text":"\"\"\"Test simple vision pixel matching baseline on Flickr one-shot image task.\n\nAuthor: Ryan Eloff\nContact: ryan.peter.eloff@gmail.com\nDate: September 2019\n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport datetime\nimport os\n\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\n\nimport numpy as np\nimport tensorflow as tf\n\n\nfrom moonshot.baselines import dataset\nfrom moonshot.baselines import experiment\n\nfrom moonshot.experiments.flickr_vision import flickr_vision\n\nfrom moonshot.utils import file_io\nfrom moonshot.utils import logging as logging_utils\n\n\nFLAGS = flags.FLAGS\n\n\n# one-shot evaluation options\nflags.DEFINE_integer(\"episodes\", 400, \"number of L-way K-shot learning episodes\")\nflags.DEFINE_integer(\"L\", 10, \"number of classes to sample in a task episode (L-way)\")\nflags.DEFINE_integer(\"K\", 1, \"number of task learning samples per class (K-shot)\")\nflags.DEFINE_integer(\"N\", 15, \"number of task evaluation samples\")\nflags.DEFINE_integer(\"k_neighbours\", 1, \"number of nearest neighbours to consider\")\nflags.DEFINE_string(\"metric\", \"cosine\", \"distance metric to use for nearest neighbours matching\")\nflags.DEFINE_boolean(\"random\", False, \"random action baseline\")\nflags.DEFINE_integer(\"seed\", 42, \"that magic number\")\n\n# image preprocessing\nflags.DEFINE_integer(\"crop_size\", 256, \"size to resize image square crop taken along shortest edge\")\n\n# logging options\nflags.DEFINE_string(\"output_dir\", None, \"directory where logs will be stored\"\n \"(defaults to logs/)\")\nflags.DEFINE_bool(\"debug\", False, \"log with debug verbosity level\")\n\n\ndef data_preprocess_func(image_paths):\n \"\"\"Data batch preprocessing function for input to the baseline model.\n\n Takes a batch of file paths, loads image data and preprocesses the images.\n \"\"\"\n images = []\n for image_path in image_paths:\n images.append(\n dataset.load_and_preprocess_image(\n image_path, crop_size=FLAGS.crop_size))\n\n # stack and flatten image arrays\n images = np.stack(images)\n images = np.reshape(images, (images.shape[0], -1))\n\n return images\n\n\ndef test():\n \"\"\"Test baseline image matching model for one-shot learning.\"\"\"\n\n # load Flickr 8k one-shot experiment\n one_shot_exp = flickr_vision.FlickrVision(\n keywords_split=\"one_shot_evaluation\",\n flickr8k_image_dir=os.path.join(\"data\", \"external\", \"flickr8k_images\"),\n preprocess_func=data_preprocess_func)\n\n # test model on L-way K-shot task\n task_accuracy, _, conf_interval_95 = experiment.test_l_way_k_shot(\n one_shot_exp, FLAGS.K, FLAGS.L, n=FLAGS.N, num_episodes=FLAGS.episodes,\n k_neighbours=FLAGS.k_neighbours, metric=FLAGS.metric,\n random=FLAGS.random)\n\n logging.log(\n logging.INFO,\n f\"{FLAGS.L}-way {FLAGS.K}-shot accuracy after {FLAGS.episodes} \"\n f\"episodes: {task_accuracy:.3%} +- {conf_interval_95*100:.4f}\")\n\n\ndef main(argv):\n del argv # unused\n\n logging.log(logging.INFO, \"Logging application {}\".format(__file__))\n if FLAGS.debug:\n logging.set_verbosity(logging.DEBUG)\n logging.log(logging.DEBUG, \"Running in debug mode\")\n\n physical_devices = tf.config.experimental.list_physical_devices(\"GPU\")\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\n # create output directory if none specified\n if FLAGS.output_dir is None:\n output_dir = os.path.join(\n \"logs\", __file__, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n file_io.check_create_dir(output_dir)\n\n # output directory specified, load model options if found\n else:\n output_dir = FLAGS.output_dir\n\n # print flag options\n flag_options = {}\n for flag in FLAGS.get_key_flags_for_module(__file__):\n flag_options[flag.name] = flag.value\n\n # logging\n logging_utils.absl_file_logger(output_dir, f\"log.test\")\n\n logging.log(logging.INFO, f\"Model directory: {output_dir}\")\n logging.log(logging.INFO, f\"Flag options: {flag_options}\")\n\n # set seeds for reproducibility\n np.random.seed(FLAGS.seed)\n tf.random.set_seed(FLAGS.seed)\n\n # test baseline matching model (no background training step)\n test()\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","repo_name":"rpeloff/moonshot","sub_path":"src/moonshot/baselines/vision/pixel_match/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"28481908744","text":"#values that will be printed\nPLAYER_1_PIECE = '1'\nPLAYER_2_PIECE = '2'\n#encoding of board values\nEMPTY_VAL = 100\nPLAYER_1_VAL = 1\nPLAYER_2_VAL = -1\n\nGAME_STATE_DRAW = 0\nGAME_NOT_OVER = 2\n\n#standard connect 4 board size\nNUM_ROW = 6\nNUM_COL = 7\nEMPTY = ' '\n","repo_name":"eric-m-chan/connect4-nn","sub_path":"const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72990131239","text":"from django.urls import path\nfrom . import views\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\n\nrouter.register(\"participants\", views.ParticipantsViewSet, basename=\"participants\")\n\nurlpatterns = [\n path(\"\", views.EventListView.as_view(), name=\"events-list\"),\n path(\"create/\", views.EventCreateView.as_view(), name=\"events-create\"),\n path(\"Detail//\", views.EventDetailView.as_view(), name=\"event-detail\"),\n path(\"modify//\", views.EventUpdateDestroyView.as_view(), name=\"event-update-delete\"),\n]\n\nurlpatterns += router.urls\n","repo_name":"MahmoudSaeed13/GYM-management-System","sub_path":"gymAPI/events/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4453871009","text":"\"\"\"\nd[0] = 1\nd[1] = sum { d[0] } // d[-1] , d[-2] : 1 = 1\nd[2] = sum { d[1], d[0] } // d[-1] : 1 + 1 = 2\nd[3] = sum { d[2], d[1], d[0] } : 2 + 1 + 1 = 4 \nd[4] = sum { d[3], d[2], d[1] } : 4 + 2 + 1 = 7\nd[5] ...\n\"\"\"\nimport sys\nread = lambda: sys.stdin.readline()\n\nT = int(read()) \nlist_n = []\nfor _ in range(T):\n n = int(read())\n list_n.append(n)\nmax_n = max(list_n)\n\n\ndef solve(n):\n d = [0] * (n + 1)\n d[0] = 1\n for i in range(1, n + 1):\n value = 0\n for count in range(1, 4):\n temp = i - count\n if temp < 0:\n break\n value += d[temp]\n d[i] = value\n return d\n\nd = solve(max_n)\nfor n in list_n:\n print(d[n])\n\n\n","repo_name":"prography-algorithm/HyeongSeon","sub_path":"9강_DP/9095.py","file_name":"9095.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38339308740","text":"# Programmer: Noah Osterhout\r\n# Date: February 2nd 2017 12:21PM EST\r\n# Project: raceCarV1.py\r\n\r\nimport pygame\r\nimport time\r\nimport random\r\n\r\npygame.init()\r\npygame.mixer.init()\r\n\r\ncrash_sound = pygame.mixer.Sound(\"ScreamingGoatOGG.ogg\")\r\npygame.mixer.music.load(\"DSOGG.ogg\")\r\n \r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\n\r\nplayGame = (3,155,229)\r\nquitGame = (255,87,34)\r\n\r\npgHover = (255,87,34)\r\nqgHover = (3,155,229)\r\n\r\nblock_color = (2, 119, 189)\r\n\r\ncar_width = 73\r\n\r\ncrash = True\r\npause = False\r\n \r\ndisplay_width = 800\r\ndisplay_height = 600\r\nscreen = pygame.display.set_mode((display_width,display_height))\r\n \r\npygame.display.set_caption(\"Race Game\")\r\n\r\ncaring = pygame.image.load('racecar.png')\r\n\r\npygame.display.set_icon(caring)\r\n\r\ndef things_dodged(count):\r\n font = pygame.font.SysFont(None, 25)\r\n text = font.render(\"Dodged: \" + str(count), True, BLACK)\r\n screen.blit(text, (0,0))\r\n\r\ndef things(thingx, thingy, thingw, thingh, color):\r\n pygame.draw.rect(screen, color, [thingx, thingy, thingw, thingh])\r\n\r\ndef car(x,y):\r\n screen.blit(caring,(x,y))\r\n\r\ndef text_objects(text, font):\r\n textSurface = font.render(text, True, BLACK)\r\n return textSurface, textSurface.get_rect()\r\n\r\ndef message_display(text):\r\n largeText = pygame.font.Font(\"OpenSans-Light.ttf\", 115)\r\n TextSurf, TextRect = text_objects(text, largeText)\r\n TextRect.center = ((display_width / 2), (display_height / 2))\r\n screen.blit(TextSurf, TextRect)\r\n\r\n pygame.display.update()\r\n \r\n time.sleep(2)\r\n\r\n game_loop()\r\n\r\ndef crash():\r\n\r\n pygame.mixer.music.stop()\r\n pygame.mixer.Sound.play(crash_sound)\r\n \r\n largeText = pygame.font.Font(\"OpenSans-Light.ttf\", 115)\r\n TextSurf, TextRect = text_objects(\"You Crashed!\", largeText)\r\n TextRect.center = ((display_width / 2), (display_height / 2))\r\n screen.blit(TextSurf, TextRect)\r\n\r\n while crash:\r\n for event in pygame.event.get():\r\n #print(event)\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n button(\"Replay\",150,450,100,50,pgHover,playGame,game_loop)\r\n button(\"Quit\",550,450,100,50,qgHover,quitGame,quit_game)\r\n \r\n pygame.display.update()\r\n\r\ndef button(msg,x,y,w,h,ic,ac,action=None):\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\r\n pygame.draw.rect(screen, ac, (x, y, w, h))\r\n if click[0] == 1 and action != None:\r\n action()\r\n #if action == \"Started\":\r\n # game_loop()\r\n #elif action == \"Quited\":\r\n # pygame.quit()\r\n # quit()\r\n else:\r\n pygame.draw.rect(screen, ic, (x, y, w, h))\r\n\r\n smallText = pygame.font.Font(\"OpenSans-Bold.ttf\", 20)\r\n textSurf, textRect = text_objects(msg, smallText)\r\n textRect.center = ( (x + (w / 2)), (y + (h / 2)))\r\n screen.blit(textSurf, textRect)\r\n\r\ndef quit_game():\r\n pygame.quit()\r\n quit()\r\n\r\ndef unpause():\r\n global pause\r\n pygame.mixer.music.unpause()\r\n pause = False\r\n \r\ndef paused():\r\n\r\n pygame.mixer.music.pause()\r\n \r\n largeText = pygame.font.Font(\"OpenSans-Light.ttf\", 115)\r\n TextSurf, TextRect = text_objects(\"Paused\", largeText)\r\n TextRect.center = ((display_width / 2), (display_height / 2))\r\n screen.blit(TextSurf, TextRect)\r\n\r\n while pause:\r\n for event in pygame.event.get():\r\n #print(event)\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n screen.fill(WHITE)\r\n\r\n button(\"Continue\",150,450,100,50,pgHover,playGame,unpause)\r\n button(\"Quit\",550,450,100,50,qgHover,quitGame,quit_game)\r\n \r\n pygame.display.update()\r\n \r\n #clock.tick(15)\r\n\r\ndef game_intro():\r\n intro = True\r\n while intro:\r\n for event in pygame.event.get():\r\n #print(event)\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n screen.fill(WHITE)\r\n largeText = pygame.font.Font(\"OpenSans-Light.ttf\", 115)\r\n TextSurf, TextRect = text_objects(\"8 Bit Racey\", largeText)\r\n TextRect.center = ((display_width / 2), (display_height / 2))\r\n screen.blit(TextSurf, TextRect)\r\n\r\n button(\"Start\",150,450,100,50,pgHover,playGame,game_loop)\r\n button(\"Quit\",550,450,100,50,qgHover,quitGame,quit_game)\r\n \r\n pygame.display.update()\r\n \r\n clock.tick(15)\r\n \r\ndef game_loop():\r\n global pause\r\n\r\n pygame.mixer.music.play(-1)\r\n \r\n x = (display_width * 0.45)\r\n y = (display_height * 0.8)\r\n\r\n x_change = 0\r\n\r\n thing_startx = random.randrange(0, display_width)\r\n thing_starty = -600\r\n thing_speed = 3\r\n thing_width = 100\r\n thing_height = 100\r\n\r\n thing_count = 1\r\n\r\n dodged = 0\r\n \r\n gameExit = False\r\n \r\n clock = pygame.time.Clock()\r\n \r\n while not gameExit:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x_change = -5\r\n if event.key == pygame.K_RIGHT:\r\n x_change = 5\r\n if event.key == pygame.K_ESCAPE:\r\n pause = True\r\n paused()\r\n\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n x_change = 0\r\n \r\n x += x_change\r\n \r\n screen.fill(WHITE)\r\n\r\n things(thing_startx, thing_starty, thing_width, thing_height, block_color)\r\n \r\n thing_starty += thing_speed\r\n car(x,y)\r\n things_dodged(dodged)\r\n\r\n if x > display_width - car_width or x < 0:\r\n crash()\r\n\r\n if thing_starty > display_height:\r\n thing_starty = 0 - thing_height\r\n thing_startx = random.randrange(0, display_width)\r\n dodged += 1\r\n thing_speed += 1\r\n thing_width += (dodged * 1.2)\r\n\r\n if y < thing_starty + thing_height:\r\n print(\"y crossover\")\r\n if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:\r\n print(\"x crossover\")\r\n crash()\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\ngame_intro()\r\ngame_loop()\r\npygame.quit()\r\n","repo_name":"NoahFlowa/Race_Car","sub_path":"raceCarV11.py","file_name":"raceCarV11.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25792761381","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework import status\n\nfrom .serializers import MySerializer, ShowPlayerSerializer, CreatePlayerSerializer\nfrom .models import Player\n\nimport mygame\n# Create your views here.\n\n\nclass Game(APIView):\n \n authentication_classes = [SessionAuthentication]\n \n \n #all players\n def get(self, request):\n data = Player.objects.all()\n serializer = MySerializer(data, many=True)\n \n print(mygame.genereta_all())\n return Response(serializer.data)\n \n\n \n #create player\n def post(self, request):\n res = request.data #data = {\"user\":123456}\n data = mygame.createBoard(res[\"user\"])\n try:\n instance = Player.objects.get(user=res[\"user\"])\n serializer = CreatePlayerSerializer(instance=instance, data=data)\n print('user exist')\n except Player.DoesNotExist:\n serializer = CreatePlayerSerializer(data=data)\n print('user created')\n \n if serializer.is_valid():\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)\n \n \n \nclass EditBoard(APIView):\n \n authentication_classes = [SessionAuthentication]\n \n \n #show player detail\n def get(self, request):\n new = request.META[\"HTTP_USER\"]\n try:\n data = Player.objects.get(user=new)\n except Player.DoesNotExist:\n return Response({\"User\": \"Not Found\"}, status=status.HTTP_404_NOT_FOUND)\n \n \n serializer = ShowPlayerSerializer(data)\n return Response(serializer.data)\n \n\n \n #move player and win or loss\n def put(self, request):\n user = request.META[\"HTTP_USER\"] #INSTANCE={\"loc_x\": 5} ---> DATA={\"loc_x\": -1}\n try:\n instance = Player.objects.get(user=user)\n except Player.DoesNotExist:\n return Response({\"User\": \"Not Found\"}, status=status.HTTP_404_NOT_FOUND)\n \n data = request.data\n data = mygame.moveX(instance, data)\n \n\n #end game /win or loss\n if True in data.values():\n serializer = MySerializer(instance=instance, data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)\n \n #countinue\n serializer = ShowPlayerSerializer(instance=instance, data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n \n return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)\n \n \n #delete player\n def delete(self, request):\n user = request.META[\"HTTP_USER\"]\n try:\n data = Player.objects.get(user=user)\n except Player.DoesNotExist:\n return Response({\"User\": \"Not Found\"}, status=status.HTTP_404_NOT_FOUND)\n \n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n ","repo_name":"MoryDalton/mynewgameapi","sub_path":"board_game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39298622012","text":"# https://projecteuler.net/problem=41\n\n# This is equivalent to two+ mediums on LeetCode:\n# https://leetcode.com/problems/permutations/ - Problem #46 Medium\n# https://leetcode.com/problems/count-primes/ - Problem #204 Medium\n\nif __name__ == '__main__':\n\n try:\n\n LOW_PRIMES = [2,3,5,7,11,13,17]\n\n # This is Greedily coded to find prime numbers above 17.\n # E.g. - it won'y return 17 as prime!\n def find_primes(pandigital_numbers, largest):\n pandigital_numbers.sort(reverse=True)\n\n for x in range(0, len(pandigital_numbers), 1):\n orig_num = pandigital_numbers[x]\n num = pandigital_numbers[x]\n\n if num < largest:\n # print(str(num) + \" skipped since it's lower than: \" + str(largest))\n continue\n\n not_prime = False\n for y in range(0, len(LOW_PRIMES), 1):\n prime = LOW_PRIMES[y]\n\n # Either a number is Prime\n # Or it has 2 or more Prime Factors\n # So, if this is >= 1, it's not Prime\n while (num % prime == 0):\n not_prime = True\n break\n\n if not_prime:\n # print(str(orig_num) + \" is not prime \")\n continue\n\n not_prime = False\n\n for y in range(18, num / 2, 1):\n if num % y == 0:\n not_prime = True\n break\n \n if not_prime:\n # print(str(orig_num) + \" is not prime \")\n continue\n \n # This massively speeds things up!\n if num > largest:\n largest = num\n print(\" ============================= \")\n print(\"New Largest Prime Pandigital found: \" + str(largest))\n\n # ----------------- #\n\n def make_key(arr):\n string_result = \"\"\n\n for x in range(0, len(arr), 1):\n string_result = string_result + str(arr[x])\n\n return string_result\n\n def permute(original_arr, largest):\n # print(original_arr)\n transfer_arr = original_arr\n heaps_results = {}\n\n def swap(end, begin):\n original = transfer_arr[begin]\n transfer_arr[begin] = transfer_arr[end]\n transfer_arr[end] = original\n\n def heaps_algorithm(n):\n if n == 1: \n key = make_key(transfer_arr)\n if int(key) > largest:\n heaps_results[key] = int(key)\n # else:\n # print(key + \" skipped since it's lower than: \" + str(largest) + \" during heaps\")\n return\n \n for i in range(0, n, 1):\n heaps_algorithm(n-1)\n v = 0\n if n % 2 == 0:\n v = i\n swap(n-1, v)\n\n heaps_algorithm(len(original_arr))\n return heaps_results\n\n # ----------------- #\n\n # Oops - save this probably useful later on - cannot include 0!\n # A Pandigital number of length n must include all numbers from 1 to n.\n\n def deep_copy(arr):\n new_arr = []\n\n for x in range(0, len(arr), 1):\n new_arr.append(arr[x])\n\n return new_arr\n\n def combination(n, k):\n ORIG_K = k\n result = []\n temp = []\n\n def inner(n, l, k):\n if len(temp) == ORIG_K:\n new_arr = deep_copy(temp)\n # print(new_arr)\n result.append(new_arr)\n\n for x in range(l, n + 1, 1):\n temp.append(x)\n inner(n, x + 1, k - 1)\n\n # Modified from:\n # https://www.geeksforgeeks.org/make-combinations-size-k/?ref=gcse\n # Super helpful!\n temp.pop()\n\n inner(n, 0, k)\n print(\" ========= Combinations: ========= \")\n print(result)\n return result\n\n # ----------------- #\n\n # The largest such n-digit Pandigital Number will be less than or equal to 9876543210.\n # A Pandigital number of length n must include ALL numbers from 1 to n!\n # The below solves for the looser scenario where a number of length n need only have no two digits repeated.\n\n # This is here to discharge the hashmap dict from memory rather \n # than both passing the hashmap and calling the values() method.\n # It's unneeded in solve_b() but was a small memory optimization technique since I was hitting a billion+ numbers.\n def map_to_arr(hm):\n result = []\n hmv = hm.values()\n\n for x in range(0, len(hmv), 1):\n result.append(int(hmv[x]))\n\n return result\n\n def solve_a(set_largest, starting_length):\n largest = set_largest\n for x in range(starting_length, 11, 1):\n\n combos = combination(9, x)\n for y in range(0, len(combos), 1):\n\n # Pass in largest to optimize!!!\n heaps = permute(combos[y], largest)\n\n # Pass in largest to optimize!!!\n find_primes(map_to_arr(heaps), largest)\n\n print(\" ============================= \")\n print(\"Largest Prime Pandigital is: \" + str(largest))\n return largest\n\n\n # solve_a(0, 2)\n\n # ----------------- # \n\n def solve_b():\n largest = 1234\n heaps = permute([2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([5,4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([6,5,4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([7,6,5,4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([8,7,6,5,4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n heaps = permute([9,8,7,6,5,4,3,2,1], largest)\n find_primes(map_to_arr(heaps), largest)\n\n solve_b()\n\n # ----------------- # \n\n except Exception as ex:\n\n print('Exception: ' + str(ex))\n","repo_name":"Thoughtscript/_project_euler","sub_path":"_finished/project_euler_41.py","file_name":"project_euler_41.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19416624884","text":"class Solution:\n def originalDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n res, dic = '', {}\n comp = {'w':'2','u':'4','g':'8','z':'0','x':'6','s':'7','v':'5','h':'3','o':'1','i':'9'}\n comp1 ={'w':'two','u':'four','g':'eight','z':'zero','x':'six','s':'seven','v':'five','h':'three','o':'one','i':'nine'}\n for x in s:\n dic[x] = dic.get(x, 0) + 1\n for x, word in comp1.items():\n t = dic.get(x,0)\n if t > 0:\n res += comp[x] * t\n for w in word:\n dic[w] -= t\n return ''.join(sorted(res))","repo_name":"lilyandcy/python3","sub_path":"leetcode/originalDigits.py","file_name":"originalDigits.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32375772414","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n \n def sameTree(a,b):\n if not a and not b:\n return True # base case\n elif a and b and a.val == b.val:\n return sameTree(a.right, b.right) and sameTree(a.left, b.left)\n else:\n return False\n\n # base case\n if not subRoot:\n return True\n elif not root:\n return False\n \n if sameTree(root,subRoot):\n return True\n\n return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)\n\n\n","repo_name":"thormander/leetcode-practice","sub_path":"subtree of another tree.py","file_name":"subtree of another tree.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19478449152","text":"import chromaprint\nfrom acoustid.script import run_script\nfrom acoustid.data.track import find_duplicates\nfrom acoustid.data.fingerprint import FingerprintSearcher\n\n\ndef main(script, opts, args):\n conn = script.engine.connect()\n find_duplicates(conn, index=script.index)\n searcher = FingerprintSearcher(conn, index)\n matches = searcher.search(fingerprint['fingerprint'], fingerprint['length'])\n track_gid = None\n for m in matches:\n track_gid = m['track_gid']\n break\n\nrun_script(main)\n\n","repo_name":"userid/acoustid-server","sub_path":"scripts/deduplicate_fingerprints.py","file_name":"deduplicate_fingerprints.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19333708154","text":"from pyflink.dataset import ExecutionEnvironment\nfrom pyflink.table import TableConfig, DataTypes, BatchTableEnvironment\nfrom pyflink.table.descriptors import Schema, OldCsv, FileSystem\n\nexec_env = ExecutionEnvironment.get_execution_environment()\nexec_env.set_parallelism(1)\nt_config = TableConfig()\nt_env = BatchTableEnvironment.create(exec_env, t_config)\n\nt_env.connect(FileSystem().path('../production_data/input')) \\\n .with_format(OldCsv()\n .field('word', DataTypes.STRING())) \\\n .with_schema(Schema()\n .field('word', DataTypes.STRING())) \\\n .register_table_source('mySource')\n\nt_env.connect(FileSystem().path('../production_data/output')) \\\n .with_format(OldCsv()\n .field_delimiter('\\t')\n .field('word', DataTypes.STRING())\n .field('count', DataTypes.BIGINT())) \\\n .with_schema(Schema()\n .field('word', DataTypes.STRING())\n .field('count', DataTypes.BIGINT())) \\\n .register_table_sink('mySink')\n\nt_env.scan('mySource') \\\n .group_by('word') \\\n .select('word, count(1)') \\\n .insert_into('mySink')\n\nt_env.execute(\"tutorial_job\")","repo_name":"youngsheep7/Flink_with_Python","sub_path":"prj/demo_codes/demo_WordCount.py","file_name":"demo_WordCount.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"22839012183","text":"import tensorflow as tf\nfrom numpy.random import RandomState\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import (Session, Variable, argmax, cast, equal, float32,\n global_variables_initializer, nn, placeholder,\n random_normal, reduce_mean, summary, train)\n\n\ndef main(x, y, training_fraction=0.80,\n learning_rate=0.001,\n epochs=1000, batch_size=1000, update_summary_at=100):\n \"\"\"\n :param x: shape = m * 786\n :param y: shape = m * 10\n :param training_fraction:\n :param epochs:\n :param batch_size:\n :param update_summary_at:\n :return:\n \"\"\"\n training_size = int(len(x) * training_fraction)\n\n # if last batch size is less than half of desired batch size then throwing exception.\n # In future, instead of throwing exception we may avoid using this last batch.\n\n assert training_size % batch_size == 0 or training_size % batch_size > batch_size / 2\n last_batch_size = training_size % batch_size\n\n _data = train_test_split(x, y, train_size=training_fraction, stratify=y.argmax(1), random_state=0)\n\n # training_data_x, training_data_y = x[:training_size], y[:training_size]\n # testing_data_x, testing_data_y = x[training_size:], y[training_size:]\n\n training_data_x, training_data_y = _data[0], _data[2]\n testing_data_x, testing_data_y = _data[1], _data[3]\n\n feature_size = training_data_x.shape[1]\n hidden_nu = 20\n output_size = training_data_y.shape[1]\n\n x = placeholder(float32, [None, feature_size], name='x')\n y = placeholder(float32, [None, output_size], name='y')\n\n # also check xavier_initializer\n W1 = Variable(random_normal([feature_size, hidden_nu], seed=1, dtype=float32), name='W1')\n b1 = Variable(random_normal([hidden_nu], dtype=float32, seed=2), name='b1') # use zeros also\n\n W2 = Variable(random_normal([hidden_nu, output_size], seed=3, dtype=float32), name='W2')\n b2 = Variable(random_normal([output_size], dtype=float32, seed=4), name='b2')\n\n L0_L1 = x @ W1 + b1\n L1_L1 = nn.relu(L0_L1)\n\n L1_L2 = L1_L1 @ W2 + b2\n L2_L2 = nn.softmax(L1_L2)\n\n cost = reduce_mean(nn.softmax_cross_entropy_with_logits_v2(logits=L2_L2, labels=y),\n name='cost')\n\n optimization = train.AdamOptimizer(learning_rate=learning_rate).minimize(cost, name='optimization')\n\n init = global_variables_initializer()\n\n current_predictions = equal(argmax(L2_L2, axis=1), argmax(y, axis=1))\n\n accuracy = tf.round(10000 * reduce_mean(cast(current_predictions, float32))) / 100\n\n with Session() as sess:\n writer = summary.FileWriter('mnist/visualize', graph=sess.graph)\n\n cost_summary = summary.scalar('cost', cost)\n training_accuracy_summary = summary.scalar('training accuracy', accuracy)\n testing_accuracy_summary = summary.scalar('testing accuracy', accuracy)\n\n sess.run(init)\n\n # ---------------------------------------------------------------------------------\n\n for e in range(epochs):\n\n _idx = RandomState(e).permutation(training_size) # check how much does it matter to add\n # uniformity of data in each batch.\n\n total_cost = 0\n\n def mini_batch(start_idx, end_idx):\n curr_idx = _idx[start_idx:end_idx]\n\n _x = training_data_x[curr_idx]\n _y = training_data_y[curr_idx]\n\n _, c = sess.run([optimization, cost],\n feed_dict={x: _x, y: _y})\n\n return (end_idx - start_idx) * c\n\n for i in range(0, training_size, batch_size):\n total_cost += mini_batch(i, min(i + batch_size, training_size))\n\n if last_batch_size != 0:\n total_cost += mini_batch(training_size - last_batch_size, training_size)\n\n print('epoch:', e, 'total cost:',\n round(total_cost, 3)) # check how this 'total_cost' can be fed into summary.\n\n if e % update_summary_at == 0:\n _total_cost, training_accuracy = sess.run([cost_summary, training_accuracy_summary],\n feed_dict={x: training_data_x, y: training_data_y})\n writer.add_summary(_total_cost, e)\n writer.add_summary(training_accuracy, e)\n\n testing_accuracy = sess.run(testing_accuracy_summary,\n feed_dict={x: testing_data_x, y: testing_data_y})\n writer.add_summary(testing_accuracy, e)\n\n writer.close()\n\n\nif __name__ == '__main__':\n import pickle as pkl\n\n with open('data.pkl', 'rb') as f: # to generate this file, see generate_data.py file.\n data = pkl.load(f)\n x, y = data['x'], data['y']\n x = x.reshape(len(x), -1)\n x = x / 255 # check other normalization techniques\n epochs = 1000\n batch_size = 1000\n\n # experiment with:\n # 1) Initialization methods\n # 2) batch size\n # 3) batch normalizations\n # 4) number of hidden neurons\n # 5) Regularization techniques\n # 6) learning rate\n # 7) Optimizer\n\n main(x, y, epochs=epochs, batch_size=batch_size, update_summary_at=10)\n","repo_name":"ShivKJ/experiment","sub_path":"ann/digit_classicification.py","file_name":"digit_classicification.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23187157433","text":"from distutils.command.build_scripts import first_line_re\nfrom typing import Text,Any, Dict\n\nfrom rasa_sdk import Tracker, FormValidationAction, Action\nfrom rasa_sdk.executor import CollectingDispatcher\nfrom rasa_sdk.types import DomainDict\nfrom random import randrange\n\nfirst_number = 0\nsecond_number = 0\noperation = ''\n\n\nclass ActionGenerateRandomEquation(Action):\n def name(self):\n return \"action_generate_random_equation\"\n\n def run(self, dispatcher, tracker, domain):\n global first_number\n global second_number\n global operation\n first_number = randrange(10)\n second_number = randrange(10)\n operation = ['*', '+', '-'][randrange(3)]\n return []\n\nclass ActionAskEquationSolution(Action):\n def name(self):\n return \"action_ask_equation_solution\"\n\n def run(self, dispatcher, tracker, domain):\n global first_number\n global second_number\n global operation\n print(operation)\n if (operation == '*'): dispatcher.utter_message(text=f\"Quanto fa {first_number} per {second_number}?\")\n elif (operation == '+'): dispatcher.utter_message(text=f\"Quanto fa {first_number} più {second_number}?\")\n elif (operation == '-'): dispatcher.utter_message(text=f\"Quanto fa {first_number} meno {second_number}?\")\n return []\n\n\nclass ValidateEquationForm(FormValidationAction):\n def name(self) -> Text:\n return \"validate_equation_form\"\n\n def validate_equation_solution(\n self,\n slot_value: Any,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: DomainDict,\n ) -> Dict[Text, Any]:\n \"\"\"Validate `equation` value.\"\"\"\n\n global first_number\n global second_number\n global operation\n\n result = 0\n if (operation == '*'): result = first_number * second_number\n elif (operation == '+'): result = first_number + second_number\n elif (operation == '-'): result = first_number - second_number\n\n #No entities detected, answer doesn't contain any number\n if (len(tracker.latest_message['entities']) == 0):\n dispatcher.utter_message(f\"Mi dispiace, ma non mi pare tu abbia detto un numero.\")\n return {\"equation_solution\": \"Wrong\"}\n\n #Can't convert to int, given answer is not a number, closing the form\n if (tracker.latest_message['entities'][0]['entity'] != 'number'):\n dispatcher.utter_message(f\"Mi dispiace, ma non mi pare tu abbia detto un numero.\")\n return {\"equation_solution\": \"Wrong\"}\n\n answer_value = int(tracker.latest_message['entities'][0]['value'])\n\n print(\"User inserted answer: \", answer_value)\n \n if (result == answer_value): \n dispatcher.utter_message(f\"Bravo, il risultato è corretto.\")\n return {\"equation_solution\":answer_value}\n else: \n dispatcher.utter_message(f\"Il risultato non è corretto, riprova.\")\n return {\"equation_solution\":None}\n","repo_name":"framilano/TesiTriennaleMilano","sub_path":"webservers/Rasa-ROS-WebServer/[it]test_package/actions/action_equationform.py","file_name":"action_equationform.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4969791416","text":"import time\nfrom resource import getrusage, RUSAGE_SELF\nfrom utility import *\n\nclass Algos:\n \"\"\"\n This is an abstract class that defines the required methods to apply\n search algorithms as seen in class\n \"\"\"\n\n def getStartState(self):\n raise NotImplementedError\n\n def isGoalState(self):\n raise NotImplementedError\n\n def getSuccessors(self):\n raise NotImplementedError\n\n def getCostOfAction(self):\n raise NotImplementedError\n\nclass Solver:\n \"\"\"\n This class contains methods that use search algorithms seen in class, and computes\n some statistics about the methods given a problem.\n \"\"\"\n def __init__(self):\n self.path = []\n self.cost_of_path = 0\n self.nodes_expanded = 0\n self.fringe_size = 1\n self.max_fringe_size = 1\n self.search_depth = 0\n self.max_search_depth = 0\n self.running_time = 0\n self.max_ram_usage = 0\n \n \n def depthLimitedSearch(self, problem, limit):\n \"\"\"\n Implements Depth Limited Search Strategy\n \"\"\"\n start_time = time.time()\n frontier = Stack()\n frontier.push(problem.getStartState())\n while not frontier.isEmpty():\n state = frontier.pop()\n self.fringe_size -= 1\n if problem.isGoalState(state):\n curr = state\n path = []\n while curr.prev != None:\n path.insert(0, curr.action)\n curr = curr.prev\n self.cost_of_path = state.cost\n self.path = path\n self.search_depth = state.depth\n self.running_time = time.time() - start_time\n return True\n\n if state.depth < limit:\n neighbors = problem.getSuccessors(state)\n self.nodes_expanded += 1\n neighbors.reverse()\n for neighbor in neighbors:\n neighbor.depth = state.depth + 1\n frontier.push(neighbor)\n self.fringe_size += 1\n if self.fringe_size > self.max_fringe_size:\n self.max_fringe_size = self.fringe_size\n if neighbor.depth > self.max_search_depth:\n self.max_search_depth = neighbor.depth\n ram = getrusage(RUSAGE_SELF).ru_maxrss / 1024\n if ram > self.max_ram_usage:\n self.max_ram_usage = ram\n self.running_time = time.time() - start_time\n return False\n\n def iterativeDeepening(self, problem, maxDepth=100):\n \"\"\"\n Search for a solution using IDS strategy\n \"\"\"\n \n # Initial depth\n k = 0\n\n total_time = 0.0\n total_nodes = 0\n # Applies DLS using different depths\n \n while not self.depthLimitedSearch(problem, k):\n total_time += self.running_time\n total_nodes += self.nodes_expanded\n self.path = []\n self.cost_of_path = 0\n self.nodes_expanded = 0\n self.fringe_size = 1\n self.max_fringe_size = 1\n self.search_depth = 0\n self.max_search_depth = 0\n self.running_time = 0\n self.max_ram_usage = 0\n k += 1\n if k > maxDepth:\n return False\n total_time = self.running_time if total_time < self.running_time else total_time\n total_nodes = self.nodes_expanded if total_nodes < self.nodes_expanded else total_nodes\n self.running_time = total_time\n self.nodes_expanded = total_nodes\n return True \n","repo_name":"singh0021/AI_Project","sub_path":"Iterative Deepening Algorithm/SearchAlgo.py","file_name":"SearchAlgo.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42276341629","text":"import atomman as am\nimport numpy as np\nimport time\nimport sys\n\nif len(sys.argv) != 4:\n print('Incorrect arguments: [ref filename, end filename, timestep]')\nelse:\n ref_filename = sys.argv[1]\n end_filename = sys.argv[2]\n timestep = int(sys.argv[3])\n split = end_filename.split(\".\")\n descriptor = split[1]\n end = int(split[-1])\n start = int(ref_filename.split(\".\")[-1])\n times = range(timestep,end+timestep,timestep)\n\nt_0 = time.time()\nd0 = am.load('atom_dump', ref_filename, symbols='Al')\n\nne11 = am.NeighborList(system=d0, cutoff=4.07)\nne12 = am.NeighborList(system=d0, cutoff=3.52)\nne23 = am.NeighborList(system=d0, cutoff=2.86)\ntol = 2.86/np.sqrt(3)/2\n\nload = time.time()\nload_time = round(load-t_0,3)\nprint(\"Load time: \",load_time)\nfor t in times:\n st = time.time()\n def_filename = 'out.{}.{}'.format(descriptor,t)\n\n dd = am.load('atom_dump', def_filename, symbols='Al')\n dd.atoms.slip_vec = np.zeros([1,3])\n dd.atoms.slip_mag = 0.0\n for ind in range(len(d0)):\n atype = d0.atoms[ind].atype\n l1 = ne11[ind]\n l2 = ne12[ind]\n l3 = ne23[ind]\n if atype == [1]:\n types_1 = d0.atoms.prop(key='atype',index=l1)\n types_2 = d0.atoms.prop(key='atype',index=l2)\n ones = np.nonzero(types_1 == 1)\n twos = np.nonzero(types_2 == 2)\n one_ne = l1[ones]\n two_ne = l2[twos]\n nes = np.concatenate((one_ne,two_ne))\n if atype == [2]:\n types_2 = d0.atoms.prop(key='atype',index=l2)\n types_3 = d0.atoms.prop(key='atype',index=l3)\n twos = np.nonzero(types_2 == 1)\n thrs = np.nonzero(types_3 == 3)\n one_ne = l2[twos]\n thr_ne = l3[thrs]\n nes = np.concatenate((one_ne,thr_ne))\n if atype == [3]:\n types_2 = d0.atoms.prop(key='atype',index=l3)\n twos = np.nonzero(types_2 == 2)\n nes = l3[twos]\n \n me_r = d0.atoms.prop(key='pos',index=ind)\n me_d = dd.atoms.prop(key='pos',index=ind)\n r = d0.atoms.prop(key='pos',index=nes)\n d = dd.atoms.prop(key='pos',index=nes)\n\n del_r = am.dvect(me_r,r,d0.box,d0.pbc)\n del_d = am.dvect(me_d,d,dd.box,dd.pbc)\n\n full_del = del_d - del_r\n\n slipmag = np.linalg.norm(full_del,axis=1)\n\n check = slipmag > tol\n inds = np.nonzero(check)\n ns = len(inds)\n\n\n slip_vec = full_del[inds].sum(axis=0)/-ns\n slip_mag = np.linalg.norm(slip_vec)\n \n dd.atoms.prop('slip_vec',ind,slip_vec)\n dd.atoms.prop('slip_mag',ind,slip_mag)\n\n\n atom_dump = dd.dump('atom_dump')\n slip_filename = 'out.{}.slip.{}_me'.format(descriptor,timestep)\n f = open(slip_filename, \"w\")\n f.write(atom_dump)\n done = time.time()\n run_time = round(done-st,3)\n print(\"Wrote: {} in {} s\".format(slip_filename,run_time))\n\n\n \n \n","repo_name":"srgoldy32/md_tools","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15457636214","text":"import errno\nimport socket\nimport time\nimport json\n\nimport eventlet\neventlet.patcher.monkey_patch(all=False, socket=True)\nimport eventlet.wsgi\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_log import loggers\nfrom oslo_service import service\nfrom oslo_service import sslutils\nimport routes.middleware\nimport webob.dec\nimport webob.exc\n\nwsgi_opts = [\n cfg.IntOpt('backlog',\n default=4096,\n help=\"Number of backlog requests to configure the socket with\"),\n cfg.IntOpt('tcp_keepidle',\n default=600,\n help=\"Sets the value of TCP_KEEPIDLE in seconds for each \"\n \"server socket. Not supported on OS X.\"),\n cfg.IntOpt('max_header_line',\n default=16384,\n help=\"Maximum line size of message headers to be accepted. \"\n \"max_header_line may need to be increased when using \"\n \"large tokens (typically those generated by the \"\n \"Keystone v3 API with big service catalogs).\"),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(wsgi_opts)\n\nLOG = logging.getLogger(__name__)\n\n\nclass Service(service.Service):\n\n def __init__(self, application, port,\n host='0.0.0.0', backlog=4096, threads=1000):\n self.application = application\n self._port = port\n self._host = host\n self._backlog = backlog if backlog else CONF.backlog\n super(Service, self).__init__(threads)\n\n def _get_socket(self, host, port, backlog):\n info = socket.getaddrinfo(host,\n port,\n socket.AF_UNSPEC,\n socket.SOCK_STREAM)[0]\n family = info[0]\n bind_addr = info[-1]\n\n sock = None\n retry_until = time.time() + 30\n while not sock and time.time() < retry_until:\n try:\n sock = eventlet.listen(bind_addr,\n backlog=backlog,\n family=family)\n if sslutils.is_enabled(CONF):\n sock = sslutils.wrap(CONF, sock)\n\n except socket.error as err:\n if err.args[0] != errno.EADDRINUSE:\n raise\n eventlet.sleep(0.1)\n if not sock:\n raise RuntimeError(\"Could not bind to %(host)s:%(port)s \"\n \"after trying for 30 seconds\" %\n {'host': host, 'port': port})\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\n if hasattr(socket, 'TCP_KEEPIDLE'):\n sock.setsockopt(socket.IPPROTO_TCP,\n socket.TCP_KEEPIDLE,\n CONF.tcp_keepidle)\n\n return sock\n\n def start(self):\n super(Service, self).start()\n self._socket = self._get_socket(self._host, self._port, self._backlog)\n self.tg.add_thread(self._run, self.application, self._socket)\n\n @property\n def backlog(self):\n return self._backlog\n\n @property\n def host(self):\n return self._socket.getsockname()[0] if self._socket else self._host\n\n @property\n def port(self):\n return self._socket.getsockname()[1] if self._socket else self._port\n\n def stop(self):\n super(Service, self).stop()\n\n def reset(self):\n super(Service, self).reset()\n logging.setup(cfg.CONF, 'murano')\n\n def _run(self, application, socket):\n logger = logging.getLogger('eventlet.wsgi')\n eventlet.wsgi.MAX_HEADER_LINE = CONF.max_header_line\n eventlet.wsgi.server(socket,\n application,\n custom_pool=self.tg.pool,\n log=loggers.WritableLogger(logger))\n\n\nclass Router(object):\n def __init__(self, mapper):\n self.map = mapper\n self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map)\n\n @webob.dec.wsgify\n def __call__(self, req):\n return self._router\n\n @staticmethod\n @webob.dec.wsgify\n def _dispatch(req):\n match = req.environ['wsgiorg.routing_args'][1]\n if not match:\n return webob.exc.HTTPNotFound()\n app = match['controller']\n return app\n\n\nclass Request(webob.Request):\n pass\n\n\nclass Resource(object):\n\n def __init__(self, controller):\n self.controller = controller\n\n @webob.dec.wsgify(RequestClass=Request)\n def __call__(self, request):\n action, action_args = self.deserialize_request(request)\n action_result = self.dispatch(self.controller, action, request, **action_args)\n return self.serialize_response(action_result)\n\n def deserialize_request(self, request):\n action_args = self.get_action_args(request.environ)\n action = action_args.pop('action', 'index')\n action_args.pop('path', None)\n\n return action, action_args\n\n def serialize_response(self, result):\n if isinstance(result, webob.Response):\n return result\n\n response = webob.Response()\n\n response.headers['Content-Type'] = 'application/json'\n response.body = json.dumps(result)\n\n return response\n\n def dispatch(self, obj, action, *args, **kwargs):\n try:\n method = getattr(obj, action)\n except AttributeError:\n method = getattr(obj, 'default')\n\n return method(*args, **kwargs)\n\n def get_action_args(self, request_environment):\n try:\n args = request_environment['wsgiorg.routing_args'][1].copy()\n except Exception:\n return {}\n\n try:\n del args['controller']\n except KeyError:\n pass\n\n try:\n del args['format']\n except KeyError:\n pass\n\n return args","repo_name":"Mirantis/celebrer","sub_path":"celebrer/common/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12629622900","text":"from argparse import ArgumentParser\nfrom alchemist.laboratory import Laboratory\nimport yaml\n\n\ndef process():\n parser = ArgumentParser(\n description=\"Output the result of reacting substances together from two different shelves\")\n # option flag for only display total no of reactions\n parser.add_argument('-r', '--reactions', action='store_true', help='only displays the number of total reactions')\n parser.add_argument('yamlfile')\n\n arguments = parser.parse_args()\n lab_yaml = yaml.load(open(arguments.yamlfile))\n # creating the laboratory from input\n laboratory = Laboratory(lab_yaml['lower'], lab_yaml['upper'])\n #output the result of the experiment\n print(laboratory.run_full_experiment(arguments.reactions))\n\nif __name__ == \"__main__\":\n process()\n","repo_name":"Soupupup/2018Exam","sub_path":"Python/Coursework 1/15015126/alchemist/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28394698773","text":"import re\nimport sys\nimport math\n\n\nfp = open(sys.argv[1])\nc = fp.readline()\nc = fp.readline()\nmainArray = []\n\n#read input\nwhile c != '':\n c = fp.readline()\n if c == '':\n break\n mainArray.append(c.split(','))\n\neverything = {}\ntotalSet = []\ntheAverages = []\nusableDataArray = []\ntotalSetCounter = 0;\n\n#convert input to floats\nfor i in range(len(mainArray)):\n usableDataArray.append([])\n for j in range(len(mainArray[i]) - 2):\n usableDataArray[i].append(float(mainArray[i][j + 2]))\n\n#normalize measurements\nrotated = list(zip(*usableDataArray[::-1]))\nfor j in range(len(rotated)):\n maxNum = max(rotated[j])\n minNum = min(rotated[j])\n for k in range(len(rotated[j])):\n if(maxNum != minNum):\n usableDataArray[k][j] = (usableDataArray[k][j] - minNum)/(maxNum - minNum)\n\n#build the three dementional array\nlast = -1\nfor i in range(len(usableDataArray)):\n #print(i)\n if(last != int(mainArray[i][1])):\n last = int(mainArray[i][1])\n totalSet.append([])\n totalSet[int(mainArray[i][1])].append(usableDataArray[i])\n\n#Sum the rows together\nfor i in range(len(totalSet)):\n theAverages.append(list(map(sum , zip(*totalSet[i]))))\n\n \nanswer = -1\naverages = []\ncorrect = []\ntotal = []\nchange = -1\n#calulate the average for each data point\nfor i in range(len(usableDataArray)):\n smallest = -1\n #sum the rest of the data points up and find which group is closest to the data set\n for j in range(len(theAverages)):\n c = [a - b for a, b in zip(theAverages[j], usableDataArray[i])]\n c = [x / (len(totalSet[j])-1) for x in c]\n sumTotal = 0\n for x in range(len(c)):\n sumTotal += (c[x] - usableDataArray[i][x]) * (c[x] - usableDataArray[i][x])\n if sumTotal < smallest or smallest == -1:\n smallest = sumTotal\n answer = j\n #Switch to a new correct and total if the number changed\n if(int(mainArray[i][1]) != change):\n change = int(mainArray[i][1])\n correct.append(0)\n total.append(0)\n #record wheather it was correct and display the numbers\n if(int(mainArray[i][1]) == answer):\n correct[int(mainArray[i][1])] += 1\n total[int(mainArray[i][1])] += 1\n if (int(mainArray[i][1]) != answer):\n print(mainArray[i][0] + ',' + mainArray[i][1] + ',' + str(answer) + ',*')\n else:\n print(mainArray[i][0] + ',' + mainArray[i][1] + ',' + str(answer))\n \n\nfor i in range(len(total)):\n print(str(i) + ',' + str(total[i]) + ',' + str(100.0 * correct[i] / total[i]) + \"\\n\")\n\nsys.stdout.flush()\n","repo_name":"alexHerman/Data-Mining","sub_path":"projectOne.py","file_name":"projectOne.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38481652868","text":"import argparse\nimport sys\nimport signal\nimport time\nimport os\nimport colorama\n\nfrom multiprocessing import Process, freeze_support\nfrom termcolor import colored\n\nfrom vlc_comm import player\nfrom util import (\n get_videos,\n getLocalIP,\n spawn_server,\n platform_dependent,\n Unbuffered,\n nop,\n)\nfrom audio_extract import convert_async, path2title\n\nimport linux_util\nimport win_util\nimport osx_util\n\n\nTO_CLEAR = [\"cache\", \"invite_link.txt\", \"invite_link.png\", \"debug.log\"]\n\n\ndef parse():\n parser = argparse.ArgumentParser(\n description=\"Route audio of a video file through a local server.\"\n )\n group = parser.add_mutually_exclusive_group()\n\n parser.add_argument(\n \"-f\",\n \"--file\",\n required=True,\n dest=\"f\",\n help=\"Path to video files or directory containing video files\",\n type=str,\n action=\"append\",\n )\n parser.add_argument(\n \"--qr\", help=\"Show qr code with the link\", dest=\"qr\", action=\"store_true\"\n )\n parser.add_argument(\n \"--control\",\n help=\"only host can control play/pause signals\",\n dest=\"onlyHost\",\n action=\"store_true\",\n )\n # parser.add_argument(\n # \"--force-rebuild\",\n # help=\"Force rebuild of the local server\",\n # dest=\"rebuild\",\n # action=\"store_true\",\n # )\n # parser.add_argument(\n # \"--audio-quality\",\n # dest=\"q\",\n # help=\"Audio quality to sync from\",\n # choices=[\"low\", \"medium\", \"good\", \"high\"],\n # type=str,\n # default=\"medium\",\n # )\n\n group.add_argument(\n \"--web\",\n help=\"Force routing through a web server\",\n dest=\"web\",\n action=\"store_true\",\n )\n args = parser.parse_args()\n args.localIP = getLocalIP()\n\n videos = []\n for i in range(len(args.f)):\n args.f[i] = os.path.abspath(args.f[i])\n files = []\n if not os.path.exists(args.f[i]):\n print(\"Path doesnot exist: \", args.f[i])\n if os.path.isdir(args.f[i]):\n for file in os.listdir(args.f[i]):\n files.append(os.path.join(args.f[i], file))\n elif os.path.isfile(args.f[i]):\n files = [args.f[i]]\n videos.extend(files)\n # videos.extend(get_videos(args.f[i], TO_CLEAR))\n args.f = videos\n return args\n\n\ndef initialize(video_paths, server, first=False):\n converted = convert_async(video_paths, args)\n # print(\"Video paths: \", video_paths, \"converted: \", converted)\n if first and converted[0] == (None, None):\n raise ValueError(\"Invalid video path\")\n\n for video_path, (audio_path, temp_mkv) in zip(video_paths, converted):\n if temp_mkv is not None:\n video_path = temp_mkv\n TO_CLEAR.append(temp_mkv)\n \n if args.web:\n server.upload(video_path, audio_path)\n else:\n server.addAudioPath(video_path, audio_path)\n TO_CLEAR.append(audio_path)\n\n platform_dependent(video_path, linux=player.enqueue)\n\n if first:\n server.create_room()\n\n def init_player(player):\n player.play()\n player.pause()\n player.seek(0)\n\n platform_dependent(player, linux=init_player)\n\n server.add_track(video_path)\n\n\ndef clear_files():\n for file in TO_CLEAR:\n if os.path.exists(os.path.abspath(file)):\n try:\n os.remove(file)\n except:\n pass\n\n\ndef exitHandler(*args, **kwargs):\n platform_dependent(\n linux=linux_util.kill_dependencies,\n windows=win_util.kill_dependencies,\n osx=osx_util.kill_dependencies,\n )\n clear_files()\n platform_dependent(\n linux=linux_util.kill_self, windows=win_util.kill_self, osx=osx_util.kill_self\n )\n\n\nif __name__ == \"__main__\":\n print(sys.argv)\n\n platform_dependent(windows=freeze_support, osx=freeze_support)\n\n sys.stdout = Unbuffered(sys.stdout)\n signal.signal(signal.SIGINT, exitHandler)\n platform_dependent(windows=colorama.init)\n args = parse()\n\n platform_dependent(\n linux=nop if args.web else spawn_server,\n windows=spawn_server,\n osx=nop if args.web else spawn_server,\n )\n\n platform_dependent(linux=player.launch)\n server = platform_dependent(\n args,\n linux=linux_util.start_server,\n windows=win_util.start_server,\n osx=osx_util.start_server,\n )\n platform_dependent(linux=Process(\n target=player.update, args=(server,)).start)\n done = False\n while not done and len(args.f) > 0:\n try:\n initialize([args.f[0]], server=server, first=True)\n done = True\n args.f.pop(0)\n except ValueError:\n args.f.pop(0)\n \n\n if len(args.f) > 0:\n initialize(args.f, server)\n\n print(\"\\n\" + colored(\"#\" * 70, \"green\") + \"\\n\")\n sys.stdout.flush()\n while True:\n time.sleep(1)\n","repo_name":"Harsh14901/AudioShare","sub_path":"CLI/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"15846098942","text":"#!/usr/bin/env python\nimport RPi.GPIO as GPIO\nimport time\nimport sys\nimport logging\nimport os\n\n\nlogging.basicConfig(filename=\"rgb.log\")\n\nlogging.debug(\"running\")\n\nR = 11\nG = 13\nB = 15\n\n# r_value = int(sys.argv[1])\n# g_value = int(sys.argv[2])\n# b_value = int(sys.argv[3])\n\ndef setup(Rpin, Gpin, Bpin):\n\tglobal pins\n\tglobal p_R, p_G, p_B\n\tpins = {'pin_R': Rpin, 'pin_G': Gpin, 'pin_B': Bpin}\n\tGPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location\n\tfor i in pins:\n\t\tGPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output\n\t\tGPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led\n\t\n\tp_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz\n\tp_G = GPIO.PWM(pins['pin_G'], 1999)\n\tp_B = GPIO.PWM(pins['pin_B'], 5000)\n\t\n\tp_R.start(100) # Initial duty Cycle = 0(leds off)\n\tp_G.start(100)\n\tp_B.start(100)\n\ndef map(x, in_min, in_max, out_min, out_max):\n\treturn (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n\ndef off():\n\tfor i in pins:\n\t\tGPIO.output(pins[i], GPIO.HIGH) # Turn off all leds\n\ndef setColor(r_value, g_value, b_value): # For example : col = 0x112233\n\tR_val = map(r_value, 0, 255, 0, 100)\n\tG_val = map(g_value, 0, 255, 0, 100)\n\tB_val = map(b_value, 0, 255, 0, 100)\n\n\tlogging.debug(\"R_val \")\n\tlogging.debug(R_val)\n\tlogging.debug(\"G_val \")\n\tlogging.debug(G_val)\n\tlogging.debug(\"B_val \")\n\tlogging.debug(B_val)\n\t\n\tp_R.ChangeDutyCycle(R_val) # Change duty cycle\n\tp_G.ChangeDutyCycle(G_val)\n\tp_B.ChangeDutyCycle(B_val)\n\ndef loop(r_value, g_value, b_value):\n\twhile True:\n\t\tsetColor(r_value, g_value, b_value)\n\ndef destroy():\n\tlogging.debug(\"end it\")\n\tp_R.stop()\n\tp_G.stop()\n\tp_B.stop()\n\toff()\n\tGPIO.cleanup()\n\ndef main(r_value, g_value, b_value):\n\tprint(\"the pid of rgbexp.py is \" + str(os.getpid()))\n\tf = open(\"pid\", \"w\")\n\tf.write(str(os.getpid()))\n\tf.close()\n\ttry:\n\t\tsetup(R, G, B)\n\t\tloop(r_value, g_value, b_value)\n\texcept KeyboardInterrupt:\n\t\tdestroy()\n\nif __name__ == \"__main__\":\n\tmain(r_value, g_value, b_value)\t\n","repo_name":"ccoxwell/colorpi","sub_path":"rgbexp.py","file_name":"rgbexp.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13166006212","text":"class Snake:\n\n def __init__(self,x,y,size,col,left,right):\n self.size = size\n self.col = col\n self.left = left\n self.right = right\n\n self.n = width/self.size\n self.dir = 0\n self.body = [PVector(x,y)] # square numbers\n self.dirs = [PVector(1,0),PVector(0,-1),PVector(-1,0),PVector(0,1)]\n\n def collision(self,other):\n head = self.body[-1]\n if self==other:\n return head in self.body[:-1]\n else:\n return head in self.body[:-1] or head in other.body\n \n def draw(self):\n fill(self.col)\n for item in self.body:\n n = self.size\n rect(item.x*n, item.y*n, n, n)\n\n def turn(self, key):\n if key == self.left: self.dir = (self.dir+1) % 4\n if key == self.right: self.dir = (self.dir-1) % 4\n \n def update(self):\n if frameCount % 5 != 0: return\n head = self.body[-1]\n d = self.dirs[self.dir]\n p = PVector((head.x+d.x) % self.n, (head.y+d.y) % self.n) \n self.body.append(p)\n if frameCount % 50 != 0: self.body.pop(0)\n\n ","repo_name":"ChristerNilsson/KosmosTeacher","sub_path":"A90_Snake/Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70441491240","text":"# Fazer um programa que diz se um ano é bissexto.\n# -- Ler o Ano e verificar input\nwhile True:\n while True:\n try:\n a = int(input('Digite um ano: '))\n if a == 0: raise Exception\n break\n except ValueError:\n print(\"Parece que você não digitou um ano corretamente.\")\n except Exception:\n print('\"0\" Não pode ser um ano. duhh...')\n # ---\n if a >= 400 and a % 4 == 0:\n if a % 100 == 0 and a % 400 == 0:\n b = 1\n if a < 400 and a % 4 == 0 and a != 0:\n if a % 100 == 0:\n b = 0\n if a < 100:\n b = 1\n else: b = 0\n print('Este é um ano bissexto.') if b == 1 else print('Este não é um ano bissexto')\n","repo_name":"Baeth/CeV-Python","sub_path":"Desafio032.py","file_name":"Desafio032.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"22240325869","text":"\"\"\"geostpatial status\n\nRevision ID: 2c45f8ce631b\nRevises: 840a06f04da9\nCreate Date: 2022-10-18 12:06:28.211101\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2c45f8ce631b'\ndown_revision = '840a06f04da9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n # op.drop_table('spatial_ref_sys')\n op.add_column('geospatialindex', sa.Column('status', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_geospatialindex_geohash'), 'geospatialindex', ['geohash'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_geospatialindex_geohash'), table_name='geospatialindex')\n op.drop_column('geospatialindex', 'status')\n op.create_table('spatial_ref_sys',\n sa.Column('srid', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('auth_name', sa.VARCHAR(length=256), autoincrement=False, nullable=True),\n sa.Column('auth_srid', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('srtext', sa.VARCHAR(length=2048), autoincrement=False, nullable=True),\n sa.Column('proj4text', sa.VARCHAR(length=2048), autoincrement=False, nullable=True),\n sa.CheckConstraint('(srid > 0) AND (srid <= 998999)', name='spatial_ref_sys_srid_check'),\n sa.PrimaryKeyConstraint('srid', name='spatial_ref_sys_pkey')\n )\n # ### end Alembic commands ###\n","repo_name":"SebOpo/backend","sub_path":"alembic/versions/2c45f8ce631b_geostpatial_status.py","file_name":"2c45f8ce631b_geostpatial_status.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22894138534","text":"'''\n Dados um inteiro positivo n e uma sequência de n números inteiros,\n imprimí-los em ordem crescente.\n'''\n\ndef main():\n n = int(input(\"Digite o número de elementos da sequência: \"))\n seq_inser = []\n seq_sele = []\n seq_eu = []\n for i in range(1, n+1):\n num = int(input(f\"Digite o {i}° número da sequência: \"))\n seq_sele.append(num)\n seq_inser.append(num)\n seq_eu.append(num)\n \n ordena_selecao(seq_sele)\n ordena_insercao(seq_inser) # está dando errado\n minha_solucao(seq_eu)\n\n print(\"\\nAs listas ordenadas usando os diferentes métodos são: \\n\")\n print(seq_sele, seq_inser, seq_eu, sep=\"\\n\")\n\n\ndef ordena_selecao(lista):\n '''\n (list) -> NoneType\n Recebe uma lista e a reorganiza em ordem crescente usando o metódo de selecionar o número\n menor e inserir no lugar do maior fora de ordem.\n '''\n n = len(lista)\n\n for i in range(0, n-1):\n indmenor = i\n for j in range(i+1, n):\n if lista[indmenor] > lista[j]:\n indmenor = j\n\n if indmenor != i:\n lista[i], lista[indmenor] = lista[indmenor], lista[i]\n\n\ndef ordena_insercao(lista):\n '''\n (list) -> NoneType\n Recebe uma lista e a reorganiza em ordem crescente usando o metódo de selecionar o número\n menor no lugar do maior fora de ordem.\n '''\n n = len(lista)\n\n for i in range(1, n):\n item = lista[i]\n j = i-1\n while j >= 0 and lista[j] > item:\n lista[j+1] = lista[j]\n j = j - 1\n lista[j+1] = item\n\n\ndef minha_solucao(lista):\n '''\n (list) -> NoneType\n Adaptação da ordena_selecao menos eficiente.\n '''\n n = len(lista)\n for k in range(n):\n for i in range(n):\n for j in range(i+1, n):\n if lista[i] > lista[j]:\n lista[i], lista[j] = lista[j], lista[i]\n\n\nmain()\n","repo_name":"baldoinov/introducao-a-computacao","sub_path":"aulas-intro-a-computacao-mac0110/pordena_ex.py","file_name":"pordena_ex.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23502078439","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Any class / function which can be used for other testing modules.\"\"\"\n\nimport time\n\n\nclass Timer(object):\n \"\"\"Record the elapsed time for the duration of this context.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the base, default variables.\"\"\"\n super(Timer, self).__init__()\n\n self._start = -1\n self._end = -1\n\n def get_recorded_delta(self):\n \"\"\"Find the seconds which occurred during the execution of this instance's context.\n\n Raises:\n RuntimeError:\n If for some reason the start / end times are not defined\n or have unexpected values.\n\n Returns:\n float: Each second that has passed.\n\n \"\"\"\n if self._start == -1:\n raise RuntimeError(\"Start is not set. Cannot continue.\")\n\n if self._end == -1:\n raise RuntimeError(\"End is not set. Cannot continue.\")\n\n if self._end < self._start:\n raise RuntimeError(\n 'End \"{self._end}\" is less than \"{self._start}\". This should never happen.'.format(\n self=self\n )\n )\n\n return self._end - self._start\n\n def __enter__(self):\n \"\"\":class:`Timer`: Keep track of the user's current time.\"\"\"\n self._start = time.time()\n\n return self\n\n def __exit__(self, exec_type, exec_value, traceback):\n \"\"\"Mark the current time as the end of this context's execution.\"\"\"\n self._end = time.time()\n","repo_name":"ColinKennedy/usd_cpp_utilities","sub_path":"tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"14247819385","text":"# Super Resolution model definition in PyTorch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport io\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.utils.model_zoo as model_zoo\nimport torch.onnx\nimport onnxruntime\nimport onnx\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\n\nclass SuperResolutionNet(nn.Module):\n def __init__(self, upscale_factor, inplace=False):\n super(SuperResolutionNet, self).__init__()\n\n self.relu = nn.ReLU(inplace=inplace)\n self.conv1 = nn.Conv2d(1, 64, (5, 5), (1, 1), (2, 2))\n self.conv2 = nn.Conv2d(64, 64, (3, 3), (1, 1), (1, 1))\n self.conv3 = nn.Conv2d(64, 32, (3, 3), (1, 1), (1, 1))\n self.conv4 = nn.Conv2d(32, upscale_factor ** 2, (3, 3), (1, 1), (1, 1))\n self.pixel_shuffle = nn.PixelShuffle(upscale_factor)\n\n self._initialize_weights()\n\n def forward(self, x):\n x = self.relu(self.conv1(x))\n x = self.relu(self.conv2(x))\n x = self.relu(self.conv3(x))\n x = self.pixel_shuffle(self.conv4(x))\n return x\n\n def _initialize_weights(self):\n init.orthogonal_(self.conv1.weight, init.calculate_gain('relu'))\n init.orthogonal_(self.conv2.weight, init.calculate_gain('relu'))\n init.orthogonal_(self.conv3.weight, init.calculate_gain('relu'))\n init.orthogonal_(self.conv4.weight)\n\n\n# Create the super-resolution model by using the above model definition.\ntorch_model = SuperResolutionNet(upscale_factor=3)\n\nbatch_size = 1 # just a random number\n\n# Initialize model with the pretrained weights\nmap_location = lambda storage, loc: storage\nif torch.cuda.is_available():\n map_location = None\ntorch_model.load_state_dict(torch.load(\"model/superres_epoch100-44c6958e.pth\"))\n\n# set the model to inference mode\ntorch_model.eval()\n# 将模型打包为ONNX\n# Input to the model\nx = torch.randn(batch_size, 1, 224, 224, requires_grad=True)\ntorch_out = torch_model(x)\n# # Export the model\n\n\n# # 测试\n\nonnx_model = onnx.load(\"super_resolution.onnx\")\nonnx.checker.check_model(onnx_model)\n\n\nort_session = onnxruntime.InferenceSession(\"super_resolution.onnx\")\n\n\ndef to_numpy(tensor):\n return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\n\n\n# compute ONNX Runtime output prediction\nort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}\nort_outs = ort_session.run(None, ort_inputs)\n\n# compare ONNX Runtime and PyTorch results\nnp.testing.assert_allclose(to_numpy(torch_out), ort_outs[0], rtol=1e-03, atol=1e-05)\n\nprint(\"Exported model has been tested with ONNXRuntime, and the result looks good!\")\n\n# 运行ONNX\n\nimg = Image.open(\"img_data/cat.jpg\")\n\nresize = transforms.Resize([224, 224])\nimg = resize(img)\n\nimg_ycbcr = img.convert('YCbCr')\nimg_y, img_cb, img_cr = img_ycbcr.split()\n\nto_tensor = transforms.ToTensor()\nimg_y = to_tensor(img_y)\nimg_y.unsqueeze_(0)\n\nort_inputs = {ort_session.get_inputs()[0].name: to_numpy(img_y)}\nort_outs = ort_session.run(None, ort_inputs)\nimg_out_y = ort_outs[0]\n\nimg_out_y = Image.fromarray(np.uint8((img_out_y[0] * 255.0).clip(0, 255)[0]), mode='L')\n\n# get the output image follow post-processing step from PyTorch implementation\nfinal_img = Image.merge(\n \"YCbCr\", [\n img_out_y,\n img_cb.resize(img_out_y.size, Image.BICUBIC),\n img_cr.resize(img_out_y.size, Image.BICUBIC),\n ]).convert(\"RGB\")\n\n# Save the image, we will compare this with the output image from mobile device\nfinal_img.save(\"img_data/cat_superres_with_ort.jpg\")\n","repo_name":"Ginger123319/CV","sub_path":"onnx_deploy/test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"33579082054","text":"def find_epsilon(dfa_start_state,transition_matrix):\n while True:\n dummy_set = set()\n for state in dfa_start_state:\n dummy_set.add(state)\n for move in transition_matrix:\n if(move[0]==state and move[1]=='$'):\n dummy_set.add(move[2])\n if(dfa_start_state==dummy_set):\n break\n dfa_start_state = dummy_set\n return dfa_start_state\n\n\ndef find_next_state(state, transition_matrix, letter):\n final_set = set()\n for j in transition_matrix:\n if(j[1]==letter):\n if(j[0] in state):\n final_set.add(j[2])\n for k in find_epsilon(j[2], transition_matrix):\n final_set.add(k)\n return final_set\n\n\ndef compare_lists(list1,list2):\n for i in list1:\n if not i in list2:\n return 0\n\n for j in list2:\n if not j in list1:\n return 0\n \n return 1\n\n\ndef powerset(s):\n x = len(s)\n masks = [1 << i for i in range(x)]\n for i in range(1 << x):\n yield [ss for mask, ss in zip(masks, s) if i & mask]","repo_name":"tushar994/automata","sub_path":"Q2/find_epsilon.py","file_name":"find_epsilon.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43425227190","text":"import numpy as np\r\nfrom keras.datasets import mnist\r\n\r\nfrom NN.helper import calculate_accuracy, ModelSaver, LRScheduler\r\nimport NN.models as NN\r\nimport NN.regularizations as regularizations\r\nimport NN.layers as layers\r\nimport NN.activations as activations\r\nimport NN.losses as losses\r\nimport NN.optimizers as optimizers\r\n\r\nnum_classes = 10\r\n\r\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\r\n\r\nimg_h = x_train.shape[1]\r\nimg_w = x_train.shape[2]\r\nimg_ch = 1\r\nx_train = x_train.reshape(x_train.shape[0], img_ch, img_h, img_w).astype('float32') / 255\r\nx_test = x_test.reshape(x_test.shape[0], img_ch, img_h, img_w).astype('float32') / 255\r\ny_train = np.array([np.array(np.eye(M=num_classes, N=1, k=int(d)).flat) for d in y_train])\r\ny_test = np.array([np.array(np.eye(M=num_classes, N=1, k=int(d)).flat) for d in y_test])\r\n\r\nprint('x_train.shape', x_train.shape)\r\nprint('y_train.shape', y_train.shape)\r\nprint('x_test.shape', x_test.shape)\r\nprint('y_test.shape', y_test.shape)\r\n\r\nnn = NN.NeuralNetwork(classification=True)\r\n# saved_nn_file = None\r\nsaved_nn_file = './mnist_models/cnn_5.pickle'\r\n\r\n# regularization = regularizations.L2Regularization(1e-10)\r\nregularization = regularizations.NoRegularization()\r\n\r\nif saved_nn_file:\r\n nn.load(saved_nn_file)\r\nelse:\r\n nn.push_layer(layers.Convolution2D(input_shape=(None, img_ch, img_h, img_w), filter_shape=(3, 3),\r\n activation=activations.ReLU(), stride=1, padding=1, depth=12))\r\n nn.push_layer(layers.MaxPool2D(window_shape=(2, 2), stride=2, connected_to=nn.layers[-1]))\r\n\r\n nn.push_layer(layers.Convolution2D(filter_shape=(3, 3), activation=activations.ReLU(), stride=1,\r\n padding=1, depth=24, connected_to=nn.layers[-1]))\r\n nn.push_layer(layers.MaxPool2D(window_shape=(2, 2), stride=2, connected_to=nn.layers[-1]))\r\n\r\n nn.push_layer(layers.Convolution2D(filter_shape=(3, 3), activation=activations.ReLU(), stride=1,\r\n padding=1, depth=48, connected_to=nn.layers[-1]))\r\n\r\n nn.push_layer(layers.Flatten(connected_to=nn.layers[-1]))\r\n nn.push_layer(layers.BatchNormalization(connected_to=nn.layers[-1]))\r\n nn.push_layer(\r\n layers.FullyConnected(outputs=nn.layers[-1].output_shape[-1] // 2, activation=activations.ReLU(),\r\n regularization=regularization, connected_to=nn.layers[-1]))\r\n nn.push_layer(\r\n layers.FullyConnected(outputs=num_classes, activation=activations.SoftMax(),\r\n regularization=regularization, connected_to=nn.layers[-1]))\r\n\r\nprint(nn)\r\n\r\nmax_epochs = 5\r\nl_rate = 1e-5\r\n\r\nloss_f = losses.CrossEntropy()\r\noptimizer = optimizers.Adam(nn.layers, lr_scheduler=LRScheduler(l_rate), loss_function=loss_f)\r\n\r\npred_test = nn.forward_pass(x_test, report=1)\r\ntest_acc = calculate_accuracy(prediction=pred_test, target=y_test, one_hot_encoding=True, classification=True)\r\nprint('Accuracy on the test set:', test_acc)\r\n\r\ntrain_loss_list, train_accuracy_list, valid_loss_list, valid_accuracy_list = nn.fit(\r\n train_set=(x_train, y_train),\r\n valid_set=(x_test, y_test),\r\n batch_size=500,\r\n max_epochs=max_epochs,\r\n optimizer=optimizer,\r\n model_saver=ModelSaver(model_name='cnn', folder_name='mnist_models', save_best=True),\r\n report=1,\r\n batch_report=1)\r\n","repo_name":"abrbird/NNNumpy","sub_path":"NN_tests/mnist_cnn_test.py","file_name":"mnist_cnn_test.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8497140075","text":"from http import client\nimport re\nimport requests\nfrom sys import argv\n\ndef main():\n\n user_info = argv[1]\n user_info = get_user_info(10)\n if user_info: \n pastebin_strings = get_pastebin_strings(user_info)\n pastebin_url = post_to_pastebin(pastebin_strings[0], pastebin_strings[1])\n\n print(pastebin_url)\n \ndef post_to_pastebin(title, body_text):\n\n print(\"Posting to Paste...\", end='')\n\n pastebin_params = {\n 'api_dev_key': \"f4R0OTFza_qTQ1NZJYLjoCeLqoHQux4X\",\n 'api_option': 'paste',\n 'api_paste_code': body_text,\n 'api_paste_name': title\n }\n\n response = requests.post('https://pastebin.com/api/api_post.php', data=pastebin_params)\n\n if response.status_code == 200:\n print('success')\n return response.text\n else:\n print('Uh Oh, got',response.status_code)\n return response.status_code\n\n\ndef get_pastebin_strings(user_dict):\n\n title = user_dict['name'] + \"'s Geographical Location\"\n body_text = \"Latitude:\" + user_dict['address']['geo']['lat'] + \"\\n\"\n body_text += \"Longitude: \" + user_dict['address']['geo']['lng']\n return (title, body_text)\n\ndef get_user_info(user_num):\n print(\"Getting user information...\", end='')\n response = requests.get('https://jsonplaceholder.typicode.com/users/' + str(user_num))\n\n if response.status_code == 200:\n print('success')\n return response.json()\n else:\n print('Uh Oh, got',response.status_code)\n return\n\nmain() ","repo_name":"TrickyHickey/COMP593-Lab6","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2658363362","text":"import pytest\n\nfrom wagtail_helpdesk.tests.factories import (\n AnswerFactory,\n AnswerIndexPageFactory,\n ExpertAnswerOverviewPageFactory,\n ExpertFactory,\n)\n\npytestmark = pytest.mark.django_db\n\n\ndef test_homepage_context(django_app, home_page):\n featured_answers = AnswerFactory.create_batch(size=2, featured=True)\n not_featured_answer = AnswerFactory(featured=False)\n\n featured_experts = ExpertFactory.create_batch(size=2, featured=True)\n not_featured_expert = ExpertFactory(featured=False)\n answer_index_page = AnswerIndexPageFactory(parent=home_page, slug=\"answers\")\n expert_answers_overview_page = ExpertAnswerOverviewPageFactory(\n parent=home_page, slug=\"experts\"\n )\n\n response = django_app.get(\"/\")\n context = response.context\n\n assert context[\"answer_index_page\"] == answer_index_page\n assert context[\"expert_answers_overview_page\"] == expert_answers_overview_page\n\n assert len(context[\"featured_answers\"]) == 2\n for featured_answer in featured_answers:\n assert featured_answer in context[\"featured_answers\"]\n assert not_featured_answer not in context[\"featured_answers\"]\n\n assert len(context[\"featured_experts\"]) == 2\n for expert in featured_experts:\n assert expert in context[\"featured_experts\"]\n assert not_featured_expert not in context[\"featured_experts\"]\n","repo_name":"Klimaat-Helpdesk/wagtail-helpdesk","sub_path":"wagtail_helpdesk/tests/test_home.py","file_name":"test_home.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"29728624130","text":"from Crypto.Cipher import AES\nimport Crypto.Cipher.AES\nfrom binascii import hexlify, unhexlify\n\nimport os\nimport subprocess\n\n\n\n\ndef solve(cracked):\n\ttestbyte = b''\n\twith open(\"id.pdf.enc\",\"rb\") as f:\n\t\ttestbyte = f.read()\n\tkey = unhexlify(cracked)\n\tiv = unhexlify('7f74c97196b7e99a0a40771c4f51cc61') #This value was given as part of the encrypted file\n\tcipher = AES.new(key,AES.MODE_CBC,iv) #This cipher information was solved in previous NSA codebreaker challenge problems\n\tdecipher = cipher.decrypt(testbyte)\n\tif b'PDF' in decipher:\n\t\tprint(decipher[:20])\n\twith open(\"decrypted.pdf\",\"wb\") as g:\n\t\tg.write(decipher)\n","repo_name":"ahessmat/codebreaker_t9","sub_path":"unransom.py","file_name":"unransom.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43313880113","text":"# Une itération (boucle) consiste à reproduire des instructions un certain nombre de fois\n\n#affiche \"Bonjour\" 5 fois. Approche \"naïve\"\n'''print(\"Bonjour\")\nprint(\"Bonjour\")\nprint(\"Bonjour\")\nprint(\"Bonjour\")\nprint(\"Bonjour\")'''\n# ctrl+/ permet de commenter automatiquement\n\n# utilisation de la boucle while (tant que). Cette boucle a besoin d'une condition.\n# while permet de faire une condition multiple.\n# --> Le nombre d'itération est connue à l'avance. Ce sont des boucles finies\n\n# incrémentation\ncpt = 0\nwhile cpt < 5 :\n print(\"Bonjour\", cpt +1, \"fois\") # pour ne pas avoir le 0 fois, on peut commencer le cpt à 1 et finir la boucle à 6\n cpt +=1\n\n# décrémentation\ncpt2 = 5\nwhile cpt2 != 0 :\n print(\"Au revoir\", cpt2, \"fois\") # pour ne pas avoir le 0 fois, on peut commencer le cpt à 1 et finir la boucle à 6\n cpt2 -=1\n\ncpt3 = 5\nwhile cpt3 > 0 :\n print(\"Au revoir\", cpt3, \"fois\") # pour ne pas avoir le 0 fois, on peut commencer le cpt à 1 et finir la boucle à 6\n cpt3 -=1\n\n\n# Utilisation de la boucle for...in (pour chaque). \n# Boucle adaptée au parcours de collection de données\n# range renvoie ici un ensemble de 5 éléments\nfor i in range(5): # borne 5 non incluse\n print(\"Bonjour\", i+1, \"fois\")","repo_name":"Lilowl06/pythonFormationCloud","sub_path":"iterations.py","file_name":"iterations.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3840152897","text":"from flask import Flask, request, redirect, send_file, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom datetime import datetime\nimport bcrypt\nimport random\nimport json\nfrom io import BytesIO\nfrom decouple import config\nfrom base64 import b64decode\nimport boto3\nimport os\nimport pyotp\nfrom collections import deque\n\nfrom send_verification_email import send_verification_email\nfrom twoFA import generate_twoFA_code, compare_twoFA_code\nfrom utils import pil_img_to_io, send_200, send_404, remove_files, reset_lp, directory_to_dict, file_to_dict\nfrom fc import compare_face_data\n\ndev_mode = False\n\napp = Flask(__name__)\nCORS(app)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = config(\"DATABASE_URL\")\ndb = SQLAlchemy(app)\nsession = boto3.Session(\n aws_access_key_id=config(\"AWS_ACCESS_KEY\"),\n aws_secret_access_key=config(\"AWS_SECRET_KEY\"),\n profile_name=\"default\"\n)\ns3_client = session.client(\"s3\")\n# bucket = s3.Bucket(config(\"AWS_BUCKET_NAME\"))\n\n\nclass VerificationCode(db.Model):\n username = db.Column(db.String(100), primary_key=True)\n code = db.Column(db.String(6), nullable=False)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n verified = db.Column(db.Boolean, default=False)\n\n\nclass TwoFACode(db.Model):\n username = db.Column(db.String(100), primary_key=True)\n key = db.Column(db.String(100), nullable=False)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n verified = db.Column(db.Boolean, default=False)\n\n\nclass FaceRecognition(db.Model):\n username = db.Column(db.String(100), primary_key=True)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n verified = db.Column(db.Boolean, default=False)\n\n\nclass User(db.Model):\n username = db.Column(db.String(100), primary_key=True)\n password = db.Column(db.String(200), nullable=False)\n security_question = db.Column(db.String(20), nullable=False)\n security_answer = db.Column(db.String(100), nullable=False)\n secret = db.Column(db.String(100), default=\"\")\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n entry_directory = db.Column(db.Integer, nullable=False)\n\n\nclass LoginProcess(db.Model):\n username = db.Column(db.String(100), primary_key=True)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n window_id = db.Column(db.String(100), nullable=False)\n twoFA_verified = db.Column(db.Boolean, default=False)\n fc_verified = db.Column(db.Boolean, default=False)\n\n\nclass Directory(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n parent_id = db.Column(db.Integer)\n name = db.Column(db.String(100), nullable=False)\n username = db.Column(db.String(100), nullable=False)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n\n\nclass File(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n directory_id = db.Column(db.Integer, nullable=False)\n username = db.Column(db.String(100), nullable=False)\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\n name = db.Column(db.String(100), nullable=False)\n s3_name = db.Column(db.String(100))\n content_type = db.Column(db.String(45), nullable=False)\n\n\nwith app.app_context():\n db.create_all()\n \n\ndef validate_lp(username, window_id):\n lp = LoginProcess.query.get(username)\n if not lp:\n return False\n if (\n (datetime.utcnow() - lp.date_created).total_seconds() > 6000 or\n window_id != lp.window_id or\n not lp.twoFA_verified #or\n # not lp.fc_verified\n ):\n reset_lp(lp, window_id)\n return False\n return True\n\n@app.route(\"/get_entry_directory\")\ndef get_entry_directory():\n username = request.args.get(\"username\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and window_id):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n user = User.query.get(username)\n if not user:\n return send_404(\"no user found\")\n if not user.entry_directory:\n return send_404(\"no entry directory found\")\n data = '{\"entryDirectoryId\":\"' + str(user.entry_directory) + \\\n '\", \"successMessage\":\"entry found\"}'\n return send_200(\"\", data=data)\n except Exception as e:\n print(e)\n return send_404(\"db error\")\n\n\n@app.route(\"/get_directory\")\ndef get_directory():\n username = request.args.get(\"username\", None)\n directory_id = request.args.get(\"directoryId\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and directory_id and window_id):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n directory = Directory.query.get(directory_id)\n subdirectories = Directory.query.filter_by(\n parent_id=directory_id).all()\n for i, subdirectory in enumerate(subdirectories):\n subdirectories[i] = directory_to_dict(subdirectory)\n files = File.query.filter_by(directory_id=directory_id).all()\n for i, file in enumerate(files):\n files[i] = file_to_dict(file)\n return jsonify({\n \"id\": directory.id,\n \"name\": directory.name,\n \"subdirectories\": subdirectories,\n \"files\": files\n })\n except Exception as e:\n print(e)\n return send_404(\"db error\")\n\n\n@app.route(\"/create_directory\")\ndef create_directory():\n username = request.args.get(\"username\", None)\n directory_name = request.args.get(\"directoryName\", None)\n parent_directory_id = request.args.get(\"parentDirectoryId\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and directory_name and parent_directory_id and window_id):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n duplicates = Directory.query.filter_by(parent_id = parent_directory_id, name=directory_name, username=username).all()\n if duplicates:\n return send_404(\"directory already exists\")\n new_directory = Directory(parent_id=parent_directory_id, name=directory_name, username=username)\n db.session.add(new_directory)\n db.session.commit()\n new_directory = Directory.query.filter_by(parent_id = parent_directory_id, name=directory_name, username=username).first()\n return jsonify(directory_to_dict(new_directory))\n except Exception as e:\n print(e)\n return send_404(\"db failed\")\n\n\n@app.route(\"/delete_directory\")\ndef delete_directory():\n username = request.args.get(\"username\", None)\n directory_name = request.args.get(\"directoryName\", None)\n directory_id = request.args.get(\"directoryId\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and directory_name and directory_id and window_id):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n directory = Directory.query.get(directory_id)\n if not directory:\n return send_404(\"no directory found\")\n directoriesToDelete = deque([directory])\n layer = 0\n while directoriesToDelete:\n for _ in range(len(directoriesToDelete)):\n curr = directoriesToDelete.popleft()\n children = Directory.query.filter_by(parent_id=curr.id).all()\n if children and layer < 10:\n directoriesToDelete.extend(children) \n db.session.delete(curr)\n layer += 1\n db.session.commit()\n return send_200(\"directory deleted\")\n except:\n return send_404(\"db failed\")\n\n\n@app.route(\"/get_file\")\ndef get_file():\n username = request.args.get(\"username\", None)\n window_id = request.args.get(\"windowId\", None)\n file_name = request.args.get(\"fileName\", None)\n file_id = request.args.get(\"fileId\", None)\n file_s3_name = request.args.get(\"fileS3Name\", None)\n if not (username and window_id and file_name and file_id and file_s3_name):\n return send_404(\"no credentials found\")\n if file_id == -1 or file_s3_name == \"dummyData\":\n return send_200(\"dummy\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n res = s3_client.get_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=file_s3_name,\n )\n content_type = res.get(\"ContentType\", None)\n file_data = res.get(\"Body\", None)\n print(content_type)\n if not (file_data and content_type):\n return send_404(\"incomplete file\")\n return send_file(\n file_data,\n mimetype=content_type,\n # as_attachment=True,\n download_name=file_name\n )\n except:\n return send_404(\"db failed\")\n\n\n@app.route(\"/create_file\", methods=[\"GET\", \"POST\"])\ndef create_file():\n file = request.files.get(\"file\", None)\n data = request.files.get(\"data\", None)\n if not (file and data):\n return send_404(\"missing information\")\n try:\n request_json = data.read().decode('utf-8')\n request_data = json.loads(request_json)\n except Exception as e:\n print(e)\n return send_404(\"could not decode request data\")\n username = request_data.get(\"username\", None)\n window_id = request_data.get(\"windowId\", None)\n file_name = request_data.get(\"fileName\", None)\n directory_id = request_data.get(\"directoryId\", None)\n content_type = request_data.get(\"contentType\", None)\n if not content_type:\n content_type = \"text/plain\"\n if not (username and window_id and file_name and directory_id and content_type):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n if content_type == \"text/plain\":\n file_extension = file_name.split(\".\")[-1]\n else:\n file_extension = content_type.split(\"/\")[-1]\n if not file_extension:\n return send_404(\"no file extension\")\n duplicates = File.query.filter_by(directory_id=directory_id, name=file_name, content_type=content_type).all()\n if duplicates:\n toDelete = []\n for duplicate in duplicates:\n if not duplicate.s3_name:\n toDelete.append(duplicate)\n for duplicate in toDelete:\n db.session.delete(duplicate)\n db.session.commit()\n duplicates = File.query.filter_by(directory_id=directory_id, name=file_name, content_type=content_type).all()\n if duplicates:\n file_name += f\"({len(duplicates)})\"\n new_file = File(directory_id=directory_id, name=file_name, content_type=content_type, username=username)\n db.session.add(new_file)\n db.session.commit()\n new_file = File.query.filter_by(directory_id=directory_id, name=file_name, content_type=content_type).first()\n new_file_id = new_file.id\n s3_name = f\"file-{str(new_file_id)}.{file_extension}\"\n new_file.s3_name = s3_name\n db.session.commit()\n s3_client.put_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=s3_name,\n Body=file\n )\n new_file = File.query.get(new_file_id)\n if not new_file:\n return send_404(\"wtf\")\n return jsonify(file_to_dict(new_file))\n except Exception as e:\n print(e)\n return send_404(\"db failed\")\n\n\n@app.route(\"/delete_file\")\ndef delete_file():\n username = request.args.get(\"username\", None)\n window_id = request.args.get(\"windowId\", None)\n file_id = request.args.get(\"fileId\", None)\n file_name = request.args.get(\"fileName\", None)\n file_s3_name = request.args.get(\"fileS3Name\", None)\n if not (username and window_id and file_id and file_name and file_s3_name):\n return send_404(\"no credentials found\")\n try:\n if not validate_lp(username, window_id) and not dev_mode:\n return send_404(\"invalid session\")\n file = File.query.get(file_id)\n if not file:\n return send_404(\"no file found\")\n file_copy = file_to_dict(file)\n db.session.delete(file)\n db.session.commit()\n s3_client.delete_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=file_s3_name\n )\n return jsonify(file_copy)\n except Exception as e:\n return send_404(\"db failed\")\n\n\n@app.route(\"/password_login\")\ndef password_login():\n username = request.args.get(\"username\", None)\n password = request.args.get(\"password\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and password and window_id):\n return send_404(\"no credentials found\")\n user = User.query.get(username)\n if not user:\n return send_404(\"user does not exist\")\n if not bcrypt.checkpw(password.encode(\"utf8\"), user.password.encode(\"utf8\")):\n return send_404(\"password incorrect\")\n try:\n lp = LoginProcess.query.get(username)\n if not lp:\n lp = LoginProcess(username=username, window_id=window_id)\n db.session.add(lp)\n db.session.commit()\n else:\n if lp.window_id != window_id:\n reset_lp(lp, window_id)\n db.session.commit()\n return send_200(\"password correct\")\n except:\n return send_404(\"db failed\")\n\n\n@app.route(\"/twoFA_login\")\ndef twoFA_login():\n username = request.args.get(\"username\", None)\n code = request.args.get(\"code\", None)\n window_id = request.args.get(\"windowId\", None)\n if not (username and code and window_id):\n return send_404(\"no credentials found\")\n twoFA = TwoFACode.query.get(username)\n if not twoFA:\n return send_404(\"no twoFA row found\")\n lp = LoginProcess.query.get(username)\n if not lp:\n return send_404(\"no lp found\")\n if (datetime.utcnow() - lp.date_created).total_seconds() > 600:\n reset_lp(lp, window_id)\n db.session.commit()\n return send_404(\"login session expired\")\n if lp.twoFA_verified:\n return send_200(\"twoFA already verifyed\")\n try:\n if compare_twoFA_code(twoFA.key, code):\n lp.twoFA_verified = True\n db.session.commit()\n return send_200(\"twoFA verified\")\n else:\n return send_404(\"invalid twoFA code\")\n except:\n return send_404(\"failed to compare twoFA code\")\n\n\n@app.route(\"/fc_login\", methods=[\"GET\", \"POST\"])\ndef fc_login():\n try:\n request_json = json.loads(request.data)\n request_data = request_json[\"data\"]\n except:\n return send_404(\"could not decode request data\")\n username = request_data.get(\"username\", None)\n picture_data_uri = request_data.get(\"pictureData\", None)\n window_id = request_data.get(\"windowId\", None)\n if not (username and picture_data_uri and window_id):\n return send_404(\"no credentials found\")\n lp = LoginProcess.query.get(username)\n if not lp:\n return send_404(\"no lp found\")\n if (datetime.utcnow() - lp.date_created).total_seconds() > 600:\n reset_lp(lp, window_id)\n db.session.commit()\n return send_404(\"login session expired\")\n if lp.fc_verified:\n return send_200(\"fc already verifyed\")\n try:\n input_filename = f\"./fc_images/{username}_input.png\"\n reference_filename = f\"./fc_images/{username}_reference.png\"\n _, encoded = picture_data_uri.split(\",\", 1)\n input_data = b64decode(encoded)\n with open(input_filename, \"wb\") as f:\n f.write(input_data)\n res = s3_client.get_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=f\"{username}_reference.png\",\n )\n\n reference_data = res.get(\"Body\", None)\n if not reference_data:\n return send_404(\"could not download reference\")\n with open(reference_filename, \"wb\") as f:\n f.write(reference_data.read())\n\n if compare_face_data(input_filename, reference_filename):\n lp.fc_verified = True\n db.session.commit()\n remove_files([input_filename, reference_filename])\n return send_200(\"fc verified\")\n else:\n remove_files([input_filename, reference_filename])\n return send_404(\"invalid fc\")\n except Exception as e:\n print(e)\n remove_files([input_filename, reference_filename])\n return send_404(\"failed to verify fc\")\n\n\n@app.route(\"/validate_username\")\ndef validate_username():\n username = request.args.get(\"username\", None)\n if not username:\n return send_404(\"no username found\")\n user = User.query.get(username)\n if user:\n return send_404(\"user already exists\")\n else:\n return send_200(\"username usable\")\n\n\n@app.route(\"/send_verification\")\ndef send_verification():\n username = request.args.get(\"username\", None)\n if not username:\n return send_404(\"no username found\")\n user = User.query.get(username)\n if user:\n return send_404(\"user already exists\")\n code = \"\".join([str(random.randint(0, 9)) for _ in range(6)])\n vc = VerificationCode.query.get(username)\n if not vc:\n vc = VerificationCode(username=username, code=code)\n try:\n db.session.add(vc)\n db.session.commit()\n except Exception as e:\n print(e)\n return send_404(\"failed to create new vc row\")\n else:\n vc.code = code\n try:\n db.session.commit()\n except Exception as e:\n print(e)\n return send_404(\"failed to updated exisitng vc row\")\n try:\n send_verification_email(username, code)\n except Exception as e:\n print(e)\n return send_404(\"failed to send verification email\")\n return send_200(\"verification email sent\")\n\n\n@app.route(\"/validate_verification\")\ndef validate_verification():\n username = request.args.get(\"username\", None)\n code = request.args.get(\"code\", None)\n if not username or not code:\n return send_404(\"no credentials found\")\n vc = VerificationCode.query.get(username)\n if not vc:\n return send_404(\"no valid vc found\")\n if vc.code != code:\n print(f\"correct code: ${vc.code}, input code: {code}\")\n return send_404(\"invalid verification code\")\n try:\n vc.verified = True\n db.session.commit()\n return send_200(\"email verified\")\n except:\n return send_404(\"vc db failed\")\n\n\n@app.route(\"/send_twoFA_code\")\ndef send_twoFA_code():\n username = request.args.get(\"username\", None)\n if not username:\n return send_404(\"no username found\")\n user = User.query.get(username)\n if user:\n return send_404(\"user already exists\")\n try:\n twoFA = TwoFACode.query.get(username)\n if not twoFA:\n code_img, key = generate_twoFA_code(username)\n twoFA = TwoFACode(username=username, key=key)\n db.session.add(twoFA)\n db.session.commit()\n else:\n code_img, _ = generate_twoFA_code(username, twoFA.key)\n img_io = pil_img_to_io(code_img)\n return send_file(img_io, mimetype=\"image/png\")\n except:\n return send_404(\"2FA code generation failed\")\n\n\n@app.route(\"/send_twoFA_code_refresh\")\ndef send_twoFA_code_refresh():\n username = request.args.get(\"username\", None)\n if not username:\n return send_404(\"no username found\")\n return redirect(f\"/send_twoFA_code?username={username}\", 302)\n\n\n@app.route(\"/validate_twoFA_code\")\ndef validate_twoFA_code():\n username = request.args.get(\"username\", None)\n code = request.args.get(\"code\", None)\n if not username or not code:\n return send_404(\"no credentials found\")\n twoFA = TwoFACode.query.get(username)\n if not twoFA:\n return send_404(\"no twoFA row found\")\n try:\n if compare_twoFA_code(twoFA.key, code):\n twoFA.verified = True\n db.session.commit()\n return send_200(\"twoFA verified\")\n else:\n return send_404(\"invalid twoFA code\")\n except:\n return send_404(\"failed to compare twoFA code\")\n\n\n@app.route(\"/face_recognition_setup\", methods=[\"GET\", \"POST\"])\ndef face_recognition_setup():\n try:\n request_json = json.loads(request.data)\n request_data = request_json[\"data\"]\n except:\n return send_404(\"could not decode request data\")\n username = request_data.get(\"username\", None)\n picture_data_uri = request_data.get(\"pictureData\", None)\n if not username or not picture_data_uri:\n return send_404(\"no credentials found\")\n user = User.query.get(username)\n if user:\n return send_404(\"user already exists\")\n try:\n _, encoded = picture_data_uri.split(\",\", 1)\n picture_data = b64decode(encoded)\n # with open(\"yee.png\", \"wb\") as f:\n # f.write(picture_data)\n picture_data = BytesIO(picture_data)\n picture_data.seek(0)\n s3_client.put_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=f\"{username}_reference.png\",\n Body=picture_data\n )\n fc = FaceRecognition(username=username)\n db.session.add(fc)\n db.session.commit()\n return send_200(\"picture uploaded\")\n except:\n return send_404(\"failed to upload picture\")\n\n\n@app.route(\"/validate_face_recognition\", methods=[\"GET\", \"POST\"])\ndef validate_face_recognition():\n try:\n request_json = json.loads(request.data)\n request_data = request_json[\"data\"]\n except:\n return send_404(\"could not decode request data\")\n username = request_data.get(\"username\", None)\n picture_data_uri = request_data.get(\"pictureData\", None)\n if not username or not picture_data_uri:\n return send_404(\"no credentials found\")\n try:\n input_filename = f\"./fc_images/{username}_input.png\"\n reference_filename = f\"./fc_images/{username}_reference.png\"\n _, encoded = picture_data_uri.split(\",\", 1)\n input_data = b64decode(encoded)\n with open(input_filename, \"wb\") as f:\n f.write(input_data)\n res = s3_client.get_object(\n Bucket=config(\"AWS_BUCKET_NAME\"),\n Key=f\"{username}_reference.png\",\n )\n\n reference_data = res.get(\"Body\", None)\n if not reference_data:\n return send_404(\"could not download reference\")\n with open(reference_filename, \"wb\") as f:\n f.write(reference_data.read())\n\n if compare_face_data(input_filename, reference_filename):\n fc = FaceRecognition.query.get(username)\n if not fc:\n raise Exception(\"no fc found\")\n fc.verified = True\n db.session.commit()\n remove_files([input_filename, reference_filename])\n return send_200(\"input matches reference\")\n else:\n remove_files([input_filename, reference_filename])\n return send_404(\"input does not match reference\")\n except Exception as e:\n print(e)\n remove_files([input_filename, reference_filename])\n return send_404(\"failed to compare input and reference\")\n\n\n@app.route(\"/create_user\")\ndef create_user():\n username = request.args.get(\"username\", None)\n password = request.args.get(\"password\", None)\n security_question = request.args.get(\"securityQuestion\", None)\n security_answer = request.args.get(\"securityAnswer\", None)\n if not (username and password and security_question and security_answer):\n return send_404(\"no credentials found\")\n vc = VerificationCode.query.filter_by(username=username).one()\n if not vc:\n return send_404(\"no vc found\")\n if not vc.verified:\n return send_404(\"vc not verified\")\n twoFA = TwoFACode.query.filter_by(username=username).one()\n if not twoFA:\n return send_404(\"no twoFA found\")\n if not twoFA.verified:\n return send_404(\"twoFA not verified\")\n # fc = FaceRecognition.query.filter_by(username=username).one()\n # if not fc:\n # return send_404(\"no fc found\")\n # if not fc.verified:\n # return send_404(\"fc not verified\")\n user = User.query.filter_by(username=username).all()\n if user:\n return send_404(\"user already created\")\n try:\n entry_directory = Directory(username=username, name=\"entry\")\n db.session.add(entry_directory)\n db.session.commit()\n entry_directory = Directory.query.filter_by(username=username).all()\n\n if len(entry_directory) > 1:\n for directory in entry_directory[1:]:\n db.session.delete(directory)\n db.session.commit()\n\n entry_directory = entry_directory[0]\n secret = \"S4_SECRET_\" + pyotp.random_base32()\n user = User(username=username, password=password, security_question=security_question,\n security_answer=security_answer, secret=secret, entry_directory=entry_directory.id)\n db.session.add(user)\n db.session.commit()\n data = '{\"secret\":\"' + secret + '\", \"successMessage\":\"user created\"}'\n return send_200(\"\", data=data)\n except Exception as e:\n print(e)\n return send_404(\"failed to create user\")\n\n\n@app.route(\"/\")\ndef test_route():\n return send_200(\"server up\")\n\n\nif __name__ == \"__main__\":\n # port = int(os.environ.get('PORT', 5000))\n port = 5000\n app.run(debug=True, port=port)\n","repo_name":"jayc809/s4-backend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":25814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8923886986","text":"#!/usr/bin/python\n\n# This file is part of pulseaudio-dlna.\n\n# pulseaudio-dlna is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# pulseaudio-dlna is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with pulseaudio-dlna. If not, see .\n\n\"\"\"A module which runs things without importing unicode_literals\n\nSometimes you want pythons builtin functions just to run on raw bytes. Since\nthe unicode_literals module changes that behavior for many string manipulations\nthis module is a workarounds for not using future.utils.bytes_to_native_str\nmethod.\n\n\"\"\"\n\nimport re\n\n\ndef repair_xml(bytes):\n\n def strip_namespaces(match):\n return 'xmlns{prefix}=\"{content}\"'.format(\n prefix=match.group(1) if match.group(1) else '',\n content=match.group(2).strip(),\n )\n\n bytes = re.sub(\n r'xmlns(:.*?)?=\"(.*?)\"', strip_namespaces, bytes,\n flags=re.IGNORECASE)\n\n return bytes\n","repo_name":"masmu/pulseaudio-dlna","sub_path":"pulseaudio_dlna/plugins/dlna/pyupnpv2/byto.py","file_name":"byto.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":1230,"dataset":"github-code","pt":"19"} +{"seq_id":"72468828843","text":"class ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n start = maxLength = 0\n usedChar = {}\n\n for i in range(len(s)):\n print(\"------\\n i = %d\" % i)\n print(usedChar)\n if s[i] in usedChar and start <= usedChar[s[i]]:\n start = usedChar[s[i]] + 1\n else:\n maxLength = max(maxLength, i - start + 1)\n\n usedChar[s[i]] = i\n\n return maxLength\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n roma = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n sum = 0\n for i in range(len(s)):\n if i < len(s) - 1 and roma[s[i]] < roma[s[i + 1]]:\n sum -= roma[s[i]]\n else:\n sum += roma[s[i]]\n return sum\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n s = ''\n ss = sorted(strs)\n print(ss)\n if len(ss) == 0:\n return ''\n if len(ss) == 1:\n return ss[0]\n for i in range(len(ss[0])):\n if ss[0][i] == ss[-1][i]:\n s += ss[0][i]\n else:\n break\n return s\n\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stack = []\n p = {')':'(',']':'[','}':'{'}\n for i in s:\n if i in p.values():\n stack.append(i)\n elif i in p.keys():\n if stack == [] or p[i] != stack.pop():\n return False\n else:\n return False\n return stack == []\n\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n\n\nif __name__ == '__main__':\n solution = Solution()\n q = '()'\n print(solution.isValid(q))","repo_name":"Carbonjkj/leetcode","sub_path":"leetcode.py","file_name":"leetcode.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34740223336","text":"import sys\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy.interpolate import UnivariateSpline\r\nimport matplotlib.pyplot as plt\r\nimport geopy.distance\r\nfrom dateutil import parser\r\nfrom csv import writer\r\nimport os\r\n\r\n\r\ndef menu(location):\r\n data = pd.read_csv(location)\r\n Longitude = data.ISSLongitude\r\n Latitude = data.ISSLatitude\r\n Elevation = data.ISSElevation\r\n Magnetometer = data.MagMagnitude\r\n MagX = data.MagX\r\n MagY = data.MagY\r\n MagZ = data.MagZ\r\n DateTime = data.DateTime\r\n os.system(\"cls\")\r\n print(\"--------------------------------MENU------------------------------------\")\r\n print(\"1) Plot graph of raw magnetic field strength against distance travelled\")\r\n print(\"2) Format longitude and latitude from degrees to decimal\")\r\n print(\"3) Get distance travelled of the ISS from longitude and latitude\")\r\n print(\"4) Create univariate interpolated spline of raw data and plot graph\")\r\n print(\"5) Plot graph of elevation against time\")\r\n print(\"6) Plot magnetic field strength against time\")\r\n print(\"7) Plot magnetic field strength in 3D\")\r\n print(\"8) End program\")\r\n UserChoice = input(\"Enter your choice: \")\r\n if UserChoice == \"1\":\r\n option1(Magnetometer,location)\r\n elif UserChoice == \"2\":\r\n option2(Longitude, Latitude, location)\r\n elif UserChoice == \"3\":\r\n option3(Latitude, Longitude, location)\r\n elif UserChoice == \"4\":\r\n option4(Magnetometer, location)\r\n elif UserChoice == \"5\":\r\n option5(Elevation, DateTime, location)\r\n elif UserChoice == \"6\":\r\n option6(DateTime,Magnetometer, location)\r\n elif UserChoice == \"7\":\r\n option7(MagX,MagY,MagZ,location)\r\n elif UserChoice == \"8\":\r\n sys.exit()\r\n\r\n\r\ndef option1(Magnetometer,Location):\r\n data = pd.read_csv(location)\r\n DistanceTravelled = data.DistanceTravelled\r\n plt.plot(DistanceTravelled, Magnetometer, label=\"Raw Data\")\r\n plt.xlabel(\"Distance Travelled / 1000 km\")\r\n plt.ylabel(\"Magnetic Field Strength / T\")\r\n plt.legend()\r\n plt.show()\r\n menu(Location)\r\n\r\n\r\ndef option2(Longitude, Latitude,Location):\r\n Distance = []\r\n for i in range(1, len(Longitude)):\r\n x = []\r\n data = []\r\n y = []\r\n x = Longitude[i].split(\" \")\r\n y = Latitude[i].split(\" \")\r\n z = x[2]\r\n z = z[:-1]\r\n b = y[2]\r\n b = b[:-1]\r\n DecimalLongitude = (float(x[0].replace(\"deg\", \"\")) + float(x[1].replace(\"'\", \"\")) / 60 + float(z) / (60 * 60))\r\n DecimalLatitude = (float(y[0].replace(\"deg\", \"\")) + float(y[1].replace(\"'\", \"\")) / 60 + float(b) / (60 * 60))\r\n data.append(DecimalLatitude)\r\n data.append(DecimalLongitude)\r\n with open('Longitude&Latitude.csv', 'a', buffering=1, newline='') as f:\r\n data_writer = writer(f)\r\n data_writer.writerow(data)\r\n menu(Location)\r\n\r\n\r\ndef option3(Latitude, Longitude,Location):\r\n Distance = []\r\n for i in range(1, len(Longitude)):\r\n Distance.append(Distance[i - 1] + geopy.distance.geodesic((Latitude[i - 1], Longitude[i - 1]),\r\n (Latitude[i], Longitude[i])).km)\r\n for i in range(0, len(Distance)):\r\n with open(\"DistanceTravelled\", \"a\", buffering=1, newline=\" \") as f:\r\n DataWriter = writer(f)\r\n DataWriter.writerow(Distance[i])\r\n menu(Location)\r\n\r\ndef option4(Magnetometer,Location):\r\n data = pd.read_csv(location)\r\n DistanceTravelled = data.DistanceTravelled\r\n spl = UnivariateSpline(DistanceTravelled, Magnetometer, k=5)\r\n xs = np.linspace(0, 182, 1000)\r\n plt.xlabel(\"Distance Travelled / 1000 km\")\r\n plt.ylabel(\"Magnetic Field Strength / T\")\r\n plt.plot(xs, spl(xs), label=\"Fitted Line\")\r\n plt.legend()\r\n plt.show()\r\n menu(Location)\r\n\r\ndef option5(Elevation, DateTime,Location):\r\n FormattedDateTime = []\r\n for i in range(0, len(DateTime)):\r\n ParsedDateTime = parser.parse(DateTime)\r\n FormattedDateTime.append(ParsedDateTime)\r\n plt.xlabel(\"Time\")\r\n plt.ylabel(\"Elevation / km\")\r\n plt.plot(FormattedDateTime, Elevation)\r\n plt.show()\r\n menu(Location)\r\n\r\n\r\ndef option6(DateTime, MagneticFieldStrength,Location):\r\n FormattedDateTime = []\r\n for i in range(0, len(DateTime)):\r\n ParsedDateTime = parser.parse(DateTime)\r\n FormattedDateTime.append(ParsedDateTime)\r\n plt.xlabel(\"Time\")\r\n plt.ylabel(\"Magnetic Field Strength\")\r\n plt.plot(FormattedDateTime, MagneticFieldStrength)\r\n plt.show()\r\n menu(Location)\r\n\r\ndef option7(MagX, MagY, MagZ, Location):\r\n fig = plt.figure()\r\n ax = plt.axes(projection=\"3d\")\r\n ax.scatter3D(MagX, MagY, MagZ)\r\n ax.set_xlabel(\"Magnetometer X\")\r\n ax.set_ylabel(\"Magnetometer Y\")\r\n ax.set_zlabel(\"Magnetometer Z\")\r\n plt.show()\r\n menu(Location)\r\n\r\nlocation = input(\"Enter location of csv file: \")\r\nmenu(location)\r\n","repo_name":"HHorizon2023/HHorizon-AstroPi-2022-2023","sub_path":"DataAnalysis.py","file_name":"DataAnalysis.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33034792841","text":"from dateutil.relativedelta import relativedelta\nfrom datetime import datetime\n\ndef declination(value):\n '''получить правильное склонение'''\n if value % 10 == 1 and value % 100 != 11:\n return 0\n elif 2 <= value % 10 <= 4 and (value % 100 < 10 or value % 100 >= 20):\n return 1\n else:\n return 2\n\ndef get_duration(date_start, date_end):\n years_declination = ['год', 'года', 'лет']\n months_declination = ['месяц', 'месяца', 'месяцев']\n days_declination = ['день', 'дня', 'дней']\n try:\n date_end = datetime.date(date_end)\n date_start = datetime.date(date_start)\n except TypeError:\n pass\n duration = relativedelta(date_end, date_start)\n duration = f'''{duration.years} {years_declination[declination(duration.years)]} {duration.months} {months_declination[declination(duration.months)]} {duration.days} {days_declination[declination(duration.days)]}'''\n return duration\n \n","repo_name":"loobinsk/md","sub_path":"project_sales/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2735235325","text":"import pymysql\nimport requests\nimport random\n\ndef get_token():\n get_param_data = {\n 'grant_type': 'client_credential',\n 'appid': 'wx116dfe67cf36b5db',\n 'secret': '4fa8e58c98667a8f5cdb1f397d0290d1'\n\n }\n response = requests.get(url='https://api.weixin.qq.com/cgi-bin/token', params=get_param_data)\n\n return response.json()['access_token']\n\n\n\n# def setup_case(case_name):\n# print('测试用例%s开始执行'%case_name)\n#\n# def teardown_case(case_name):\n# print('测试用例%s结束执行'%case_name)\n#\n# def setup_step(case_step):\n# print('测试步骤%s开始执行'%case_step)\n#\n# def teardown_step(case_step):\n# print('测试步骤%s结束执行'%case_step)\n\n\ndef get_random_int():\n random_list =[]\n random_list.append(random.randint(1,10))\n random_list.append(random.randint(1,10))\n return random_list\n\ndef get_random_ints(min,max,count=10):\n random_list =[]\n for i in range(count):\n random_list.append(random.randint(min, max))\n return random_list\n\ndef get_str(randomlength=18,count=3):\n base_str='0123456789'\n length = len(base_str)-1\n for i in range(count):\n ran_str =''\n for j in range(randomlength):\n ran_str += base_str[random.randint(0,length)]\n return ran_str\n\ndef get_random_mobilenumber(count=3):\n phone_list=[]\n for i in range(count):\n start_phone = random.choice(['130', '131', '132', '133', '134', '135', '136', '156', '177', '188'])\n end_phone = ''.join(random.sample('0123456789', 8)) # 从0~9找到8个数字,join 将一个字符列表转换成字符串\n phone_list.append(start_phone+end_phone)\n return phone_list\n\ndef decode_iso88591(string):\n return string.encode('utf8').decode('iso8859-1')\n\n\ndef decode_utf8(string):\n return string.encode('iso8859-1').decode('utf8',\"ignore\")\n\nif __name__=='__main__':\n # print(get_random_ints(min=1,max=100))\n # print(get_random_mobilenumber())\n # print(get_random_int())\n # print(get_random_mobilenumber())\n # print(get_str())\n # print('端午'.encode('utf8').decode('iso8859-1'))\n # print('端å'.encode('iso8859-1').decode('utf8',\"ignore\"))\n connect =pymysql.connect(\n host='127.0.0.1',\n port=3306,\n user='root',\n password='123456',\n database='easybuy',\n charset='utf8',\n cursorclass =pymysql.cursors.DictCursor\n )\n\n cur =connect.cursor(pymysql.cursors.DictCursor)\n cur.execute(\"select * from esaybuy_user;\")\n value1 =cur.fetchone() # 取某一行值\n value2 = cur.fetchmany(4) #取4行值\n value3 = cur.fetchall() #取所有行\n print(value1)\n print(value2)\n print(value3)\n cur.execute(\"update %s set userName=%s where loginName=%s;%('esaybuy_user','浙江','szz')\")\n connect.commit()\n connect.close()\n\n\n\n\n\n\n\n","repo_name":"chaoabc/VXAPIHttprunnerProject","sub_path":"debugtalk.py","file_name":"debugtalk.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43213701654","text":"import csv\n# Write to csv file\n# field names\nfields = [\"TECHNOLOGY\", \"FREQ_MHZ\", \"DATA_RATE*\", \"TEST*\", \"TX_POWER_DBM*\", \"ANTENNA\"]\n\n# data rows of csv file\nrows1 = [['11AC', 2422, 'DSSS-1', 'E,M,P', 15.0, (1,0,0,0)],\n [ \"\" , 2457, 'CCK_5-5', 'E,M,P,S', \"\" ,\"\" ],\n [ \"\" , 2484, \"\" , \"L,H,S\", \"\" , \"\" ]\n ]\nrows2 = [['11AX', 2422, 'DSSS-1', 'E,M,P', 15.0, (1,0,0,0)],\n [ 2457, 'CCK_5-5', 'E,M,P,S', \"\" ,\"\" ],\n [ 2484, \"\" , \"L,H,S\", \"\" , \"\" ]\n ]\n# name of csv file\nfilename = \"csv_data3.csv\"\n\nwith open(filename, \"w\") as fout:\n csvWriter = csv.writer(fout)\n csvWriter.writerow(fields)\n csvWriter.writerows(rows1)\n\n","repo_name":"TrellixVulnTeam/Desk_2_B4NW","sub_path":"Py_op/File_op/CSV/csv_test.py","file_name":"csv_test.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35463241451","text":"import sys\r\nimport os\r\nimport hashlib\r\n\r\ndef wrong_input(x, y):\r\n user_choice = input(x)\r\n while user_choice not in y:\r\n user_choice = input(\"\\nWrong option\\n\\n\")\r\n return user_choice\r\n\r\ndef file_size(a, b):\r\n return os.path.getsize(os.path.join(a, b))\r\n\r\nif len(sys.argv) == 1:\r\n print(\"Directory is not specified\")\r\nelse:\r\n file_format = input(\"Enter file format:\\n\")\r\n print(\"\\nSize sorting options:\", \"1. Descending\", \"2. Ascending\\n\", sep=\"\\n\")\r\n \r\n sorting_option = wrong_input(\"Enter a sorting option:\\n\", [\"1\", \"2\"])\r\n\r\n output = {}\r\n for root, dirs, files in os.walk(sys.argv[1]):\r\n for name in files:\r\n if name.endswith(file_format):\r\n output.setdefault(file_size(root, name), []) \r\n output[file_size(root, name)] += [os.path.join(root, name)]\r\n \r\n for i in sorted(output, reverse=True if sorting_option == \"1\" else False):\r\n print(f\"\\n{i} bytes\", *output[i], sep=\"\\n\")\r\n \r\n if wrong_input(\"\\nCheck for duplicates?\\n\", (\"yes\", \"no\")) == \"yes\":\r\n hashs = {}\r\n for i in output:\r\n for ii in output[i]:\r\n with open(ii, \"rb\") as item_to_hash:\r\n hashing = hashlib.md5()\r\n hashing.update(item_to_hash.read())\r\n hashs.setdefault(i, {})\r\n hashs[i].setdefault(hashing.hexdigest(), [])\r\n hashs[i][hashing.hexdigest()] += [ii]\r\n\r\n for size, hash_n_list in hashs.items():\r\n for hash in list(hash_n_list.keys()):\r\n if len(hash_n_list[hash]) == 1:\r\n del hash_n_list[hash]\r\n \r\n n = 1\r\n file_list = [] \r\n for size, hash_n_list in sorted(hashs.items(), reverse=True if sorting_option == \"1\" else False):\r\n print(f\"\\n{size} bytes\")\r\n for hash, paths in hash_n_list.items():\r\n print(f\"Hash: {hash}\")\r\n for path in paths:\r\n print(f\"{n}. {path}\")\r\n file_list.append((size, path))\r\n n += 1\r\n \r\n if wrong_input(\"\\nDelete files?\\n\", (\"yes\", \"no\")) == \"yes\":\r\n user_choice = input(\"\\nEnter file numbers to delete:\\n\").split()\r\n while len(user_choice) == 0 or all([True if i in [str(i) for i in range(1, len(file_list) + 1)] else False for i in user_choice]) != True:\r\n user_choice = input(\"\\nWrong option\\n\\nEnter file numbers to delete:\\n\").split()\r\n sum_to_show = []\r\n for path in user_choice:\r\n os.remove(file_list[int(path) - 1][1])\r\n sum_to_show.append(file_list[int(path) - 1][0])\r\n print(\"\\nTotal freed up space:\", sum(sum_to_show))","repo_name":"Breathe-of-fate/python_learning_hyperskills","sub_path":"Duplicate File Handler.py","file_name":"Duplicate File Handler.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"40829232019","text":"import sys # better management of the exceptions\nfrom astroquery.simbad import Simbad # integration with simbad\nimport astropy.units as u # managing units of measure\nfrom astropy.coordinates import SkyCoord # managing coordinate systems\n\n######### defining class which will retrieve the Messier Catalogue\nclass megalo_catalogueretriever:\n def __init__(self):\n self.messierObjects = []\n self.typeObjects = set()\n try:\n self.messierObjects, self.typeObjects = self.retrieving()\n except Exception as e:\n print(str(e))\n\n def retrieving(self):\n try:\n Simbad.add_votable_fields('otype(V)') # verbose - type\n messier_catalog = Simbad.query_catalog('Messier') # retrieving messier catalog\n messierObjects = [] # here I will store the 110 objects\n type_messierObjects = set() # here I will store the object types\n for messier_object in messier_catalog:\n # creating a single object\n mo = generatingMessierObject(messier_object['MAIN_ID'],\n messier_object['OTYPE_V'],\n messier_object['RA'],\n messier_object['DEC'])\n messierObjects.append(mo)\n type_messierObjects.add(mo.type)\n return messierObjects, type_messierObjects\n except Exception as e:\n print(str(e))\n\n######### defining wrapper class for Messier Objects\nclass MessierObject(object):\n name = \"\"\n type = \"\"\n galacticLatitude = 0\n galacticLongitude = 0\n\n def __init__(self, name, type, ra, dec):\n c = SkyCoord(str(ra) + ' ' + str(dec), unit=(u.hourangle, u.deg))\n self.name = name.decode('utf-8').replace(\" \",\"\")\n self.type = type.decode('utf-8')\n self.galacticLatitude = c.galactic.l # from ra to gal_lat\n self.galacticLongitude = c.galactic.b # from dec to gal_long\n\ndef generatingMessierObject(name, type, ra, dec):\n messierObject = MessierObject(name, type, ra, dec)\n return messierObject\n","repo_name":"robertobastone/MEGALO","sub_path":"megalo_catalogueretriever.py","file_name":"megalo_catalogueretriever.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23667935771","text":"import bm3d\r\nimport cv2\r\nimport numpy as np\r\nfrom skimage.util import noise, random_noise\r\nfrom skimage.metrics import structural_similarity\r\n\r\n# Eventually we can perform sigma_psd optimization on different types of noisy images\r\n# Have to make sure we display what's going on in terminal as these steps can take a\r\n# ---- long time to process\r\n\r\n# Normalizes img at fileName, repeatedly calls compareBM3D() to find optimal sigma_psd\r\ndef processImage(file_name,noise_types,starting_sigma=0.2,starting_noise_variance=0.1):\r\n # read in original image\r\n img = cv2.imread(file_name)\r\n\r\n # apply random_noise (automatically normalizes image)\r\n # ---- mode -> gaussian, s&p, possion, or speckle\r\n noisy_images = addNoise(img,noise_types=noise_types,variance=starting_noise_variance)\r\n\r\n for index,noisy_image in enumerate(noisy_images):\r\n print('Processing '+noise_types[index]+' noise at '+str(starting_noise_variance) +' variance')\r\n fimg = compareBM3D(noisy_image,img,sigma=starting_sigma,noise_type=noise_types[index])\r\n cv2.imwrite(noise_types[index]+str(starting_noise_variance)+'_sig'+fimg[1]+'_'+file_name,fimg[0])\r\n return 1.0\r\n\r\n# Applies BM3D with initial sigma_psd=0.2,compares sigma_psd=0.1,and sigma_pds=0.3\r\n# ---- by using psnr() and ssim(). specificity, 1 changes sigma by 0.1\r\n# ---- specificty of 1 tells sigma to change by 0.01 (0=tenth,1=hundredth)\r\n# ---- stage_arg -> HARD_THRESHOLDING or ALL_STAGES (slower but better)\r\ndef compareBM3D(normalized_noisy_img, original_img, sigma=0.2, specificity=0,noise_type=''):\r\n specificity_value = round(0.1-specificity*0.09,2)\r\n lesser_sigma = sigma-specificity_value\r\n greater_sigma = sigma+specificity_value\r\n if greater_sigma > 1.0:\r\n greater_sigma = 1.0\r\n if lesser_sigma <= 0:\r\n lesser_sigma = 0.01\r\n\r\n print('Processing BM3D (1/3)',end='\\r')\r\n lesser_img = bm3d.bm3d(normalized_noisy_img, sigma_psd=lesser_sigma,stage_arg=bm3d.BM3DStages.ALL_STAGES)\r\n print('Processing BM3D (2/3)',end='\\r')\r\n img = bm3d.bm3d(normalized_noisy_img, sigma_psd=sigma,stage_arg=bm3d.BM3DStages.ALL_STAGES)\r\n print('Processing BM3D (3/3)',end='\\r')\r\n greater_img = bm3d.bm3d(normalized_noisy_img, sigma_psd=greater_sigma,stage_arg=bm3d.BM3DStages.ALL_STAGES)\r\n print('Processing BM3D (3/3) Finished')\r\n\r\n # Compare PSNR and SSIM test results for each variation with terminal feedback\r\n norm_image = cv2.normalize(original_img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n\r\n ssim_lesser = calc_ssim(norm_image,lesser_img)\r\n ssim_starting = calc_ssim(norm_image,img)\r\n ssim_greater = calc_ssim(norm_image,greater_img)\r\n print('SSIM value at '+str(round(lesser_sigma,2))+' sigma:'+str(ssim_lesser))\r\n print('SSIM value at '+str(round(sigma,4))+' sigma:'+str(ssim_starting))\r\n print('SSIM value at '+str(round(greater_sigma,4))+' sigma:'+str(ssim_greater))\r\n\r\n display_results = False\r\n greatest = compareSSIM(ssim_lesser,ssim_starting,ssim_greater)\r\n if greatest == 0:\r\n # search finished or need to increase specificity\r\n if specificity == 1:\r\n print('Best Sigma '+str(round(sigma,4))+' for '+str(noise_type))\r\n display_results = True\r\n if specificity == 0:\r\n print('Increasing Precision')\r\n return compareBM3D(normalized_noisy_img,original_img,sigma=sigma,specificity=1,noise_type=noise_type)\r\n elif greatest == 1:\r\n print('Increasing sigma by '+str(specificity_value))\r\n return compareBM3D(normalized_noisy_img,original_img,sigma=greater_sigma,specificity=specificity,noise_type=noise_type)\r\n else:\r\n print('Decreasing sigma by '+str(specificity_value))\r\n return compareBM3D(normalized_noisy_img,original_img,sigma=lesser_sigma,specificity=specificity,noise_type=noise_type)\r\n\r\n\r\n if display_results:\r\n print('Finished, close window to continue')\r\n # This if statement needs to be turned to true when processing grayscale images\r\n if False:\r\n normalized_noisy_img = cv2.cvtColor(normalized_noisy_img.astype('float32'), cv2.COLOR_BGR2GRAY)\r\n img = cv2.cvtColor(img.astype('float32'), cv2.COLOR_BGR2GRAY)\r\n norm_image = cv2.cvtColor(norm_image.astype('float32'), cv2.COLOR_BGR2GRAY)\r\n cv2.imshow(\r\n 'Before | '+noise_type+' | BM3D '+str(round(sigma,2)),\r\n np.concatenate((norm_image,normalized_noisy_img,img),axis=1)\r\n )\r\n cv2.waitKey()\r\n img_out = np.concatenate((norm_image,normalized_noisy_img,img),axis=1)\r\n # img_out = np.concatenate((normalized_noisy_img,img),axis=1)\r\n img_out = img_out*255\r\n img_out = img_out.astype('uint8')\r\n return (img_out , str(round(sigma,2)))\r\n\r\n# returns SSIM with most similarity to original\r\ndef compareSSIM(less,origin,greater):\r\n if less > origin and less >= greater:\r\n return -1\r\n if origin >= less and origin >= greater:\r\n return 0\r\n return 1\r\n\r\n# Adds noise to an image before/after normalization (not sure yet depends on implementation)\r\n# ---- type -> type of noise\r\ndef addNoise(img, noise_types=['gaussian'],variance=0.2):\r\n noisy_images = []\r\n for noise_type in noise_types:\r\n noisy_images.append(random_noise(img,mode=noise_type,var=variance**2))\r\n return noisy_images\r\n\r\n#This site made these pretty trivial https://cvnote.ddlee.cc/2019/09/12/psnr-ssim-python\r\n# am smol bran, let me know if i can try to fix this, if no work good.\r\n# PSNR testing, returns PSNR values from img and post_img comparison\r\ndef psnr(img, post_img):\r\n psnr = cv2.PSNR(img, post_img)\r\n return psnr\r\n\r\n#this calls ssim, to stay consistent with the implementation I'm basing all of this off of\r\n#should this maybe call compareBM3D rather than ssim?\r\ndef calc_ssim(img, post_img):\r\n if (img.shape == post_img.shape):\r\n if(img.ndim == 2):\r\n return ssim(img, post_img)\r\n elif(img.ndim == 3):\r\n if(img.shape[2] == 3):\r\n _ssim = []\r\n for i in range(3):\r\n _ssim.append(ssim(img,post_img))\r\n return np.array(_ssim).mean()\r\n elif(img.shape[2]==1):\r\n return ssim(np.squeeze(img), np.squeeze(post_img))\r\n else:\r\n return(\"error with image dimesions in calc_ssim\")\r\n\r\n# SSIM testing, returns SSIM values from img and post_img comparison\r\n# does the sigma value need to be changed here?\r\ndef ssim(img, post_img):\r\n C1 = (0.01 * 255) ** 2\r\n C2 = (0.03 * 255) ** 2\r\n\r\n gkernal = cv2.getGaussianKernel(11, 1.5)\r\n window = np.outer(gkernal, gkernal.transpose())\r\n\r\n mu1 = cv2.filter2D(img, -1, window)[5:-5, 5:-5]\r\n mu2 = cv2.filter2D(post_img, -1, window)[5:-5, 5:-5]\r\n sigma1_sq = cv2.filter2D(img**2, -1, window)[5:-5, 5:-5] - (mu1**2)\r\n sigma2_sq = cv2.filter2D(post_img**2, -1, window)[5:-5, 5:-5] - (mu2**2)\r\n sigma12 = cv2.filter2D(img * post_img, -1, window)[5:-5, 5:-5] - (mu1*mu2)\r\n\r\n ssim_map = ((2 * mu1* mu2 + C1) * (2 * sigma12 + C2)) / ((mu1**2 + mu2**2 + C1) * (sigma1_sq + sigma2_sq + C2))\r\n return ssim_map.mean()\r\n\r\n# Demo try various commented commands below for different examples\r\nprocessImage('Lenna.png',['gaussian'],starting_sigma=0.1, starting_noise_variance=0.12)\r\n# Super Noisy image low detail retention\r\n# processImage('peppers.jpg.png',['gaussian'],starting_noise_variance=0.75)\r\n# Medium Noise levels Blobby but maintained areas of interest\r\n# processImage('Lenna.png',['gaussian'],starting_noise_variance=0.5)\r\n# processImage('Lenna.png',['gaussian'],starting_noise_variance=0.3)\r\n","repo_name":"Zeus-The-Cat/cis465-project","sub_path":"termproject.py","file_name":"termproject.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2483015615","text":"from random import randint\nyear=0\nmenores=0\nmayores=0\nfor i in range(1,46):\n edad= randint(18,70)\n print(edad,end=\" \")\n year+=edad\n promedio = year/45\n if edad<=30:\n menores+=1\n elif edad>30:\n mayores+=1\n\nprint(\"\\nEL promedio es: \",round(promedio,2))\nprint(\"Menores o iguales a 30 es: \",str(menores))\nprint(\"Mayores de 30 es: \",str(mayores))\n","repo_name":"inoricode28/Python","sub_path":"Idat_Python/Primer_Ciclo/Semana09/ejer19.py","file_name":"ejer19.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"5336602677","text":"#import wave\nimport numpy as np\nimport scipy.signal\nfrom scipy.io.wavfile import read\nfrom scipy.fftpack import realtransforms\n\nimport matplotlib.pyplot as plt\n\n# Linear Frequency Cepstral Coefficients(LFCCs)\n#beginning of class LFCC\nclass LFCC(object):\n\n#public method\n def __init__(self, wavfile=\"record.wav\"):\n #%time wave.open(str(wavfile), mode=\"rb\")\n #%time read(wavfile)\n self._sr, self._waveform = read(wavfile)\n \n def get_audio_signal(self):\n return self._waveform\n \n def get_sampling_rate(self):\n return self._sr\n \n def get_lfcc(self, p=0.97, nfft=512, nchannels=24, nceps=12):\n \n # define a convolute preEmphasis filter\n self._waveform = self._preEmphasis(self._waveform, p)\n #print(type(self._waveform))\n \n # define a hamming window\n self._nfft = nfft\n hammingWindow = np.hamming(self._nfft)\n \n self._hop_length = self._nfft//2\n # make a spectrogram\n spec = self._stft(wave=self._waveform, window=hammingWindow, step=self._hop_length)\n # n: fft_bin, d: cycle time\n freq = np.fft.fftfreq(n=self._nfft//2, d=1.0/self._sr)\n\n \"\"\"\n for i, sp in enumerate(spec):\n plt.plot(freq, sp)\n plt.show()\n \"\"\"\n \"\"\"\n import scipy.io.wavfile as wav\n import scipy.signal as signal\n import librosa\n\n f, t, Zxx = signal.stft(self._waveform, fs=self._sr)\n #plt.pcolormesh(t, f, , shading='gouraud')\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [sec]')\n plt.pcolormesh(t, f, np.abs(Zxx), shading='gouraud')\n plt.show()\n\n #DB = librosa.amplitude_to_db(Zxx, ref=np.max)\n #lirosa.display.specshow(DB, sr=self._sr, hop_length=self._nfft, x_axis='time', y_axis='log')\n #plt.colorbar(format='%+2.0fdB')\n \"\"\"\n\n #linearfilterbank\n df = self._sr / self._nfft # frequency resolution\n print(\"sampling rate: {}, freq resolution: {}\".format(self._sr, df))\n filterbank = self._linearFilterBank(nchannels=nchannels)\n print(filterbank.shape)\n\n \"\"\"\n for c in np.arange(0, nchannels):\n plt.plot(np.arange(0, self._nfft//2) * df, filterbank[c])\n plt.show()\n \"\"\"\n # apply linearfilterbanks for each vector, then sum all and take log\n linear_spec = np.log10(np.dot(spec, filterbank.T))\n print(\"linear_spec:\", linear_spec.shape)\n \n # obtain a cepstrum by applying discrete cosine transform to log-linear spectrum\n cepstrum = self._dct(linear_spec).T\n \n # cepstrum = (n-dimensional feature, shift), nceps is the number of features to use\n lfccs = cepstrum[:nceps]\n\n return lfccs\n\n #pre-emphasis filter\n def _preEmphasis(self, signal, p):\n #signal := voice_signal, p := coefficient\n #make FIR filter such that coefficients are (1.0, p)\n return scipy.signal.lfilter([1.0, -p], 1.0, signal)\n \n #convert hz to mel\n def _hz2mel(self, f):\n return 1125.0 * np.log(f/700.0 + 1.0)\n \n #convert mel to hz\n def _mel2hz(self, m):\n return 700.0 * (np.exp(m/1125.0) - 1.0)\n \n #Short Time Fourier Transform: STFT\n def _stft(self, wave, window, step):\n # wave: waveform (numpy.ndarray)\n # window: hammingWindow (numpy.ndarray)\n # step: overlapping length\n wavelen = wave.shape[0]\n windowlen = window.shape[0] # windowLength, fft_bin, cripping_size\n shift = (wavelen - windowlen + step-1) // step + 1\n print(\"wavelen: {}, fft_bin: {}, shift: {}\".format(wavelen, windowlen, shift))\n\n #padded_wave = np.zeros(wavelen+step)\n #padded_wave = np.zeros(windowlen+(shift*step))\n #padded_wave[:wavelen] = wave # waveform has to be reformed to fit the sliding window \n \n X = np.array([]) # X: spectrum will have to be (shift, windowlen)\n for m in range(shift):\n start = step * m\n x = np.fft.fft(wave[start:start+windowlen]*window, norm='ortho')[:self._nfft//2]\n if m == 0:\n X = np.hstack((X, x))\n else:\n X = np.vstack((X, x))\n \"\"\"\n if m == 120:\n plt.plot(np.arange(0, windowlen), wave[start:start+windowlen]*window)\n plt.show()\n plt.plot(np.fft.fftfreq(n=self._nfft, d=1.0/self._sr)[:self._nfft//2], np.abs(x)**2)\n plt.show()\n \"\"\"\n print(X.shape)\n # return power-spectrum\n return np.abs(X)**2/self._nfft\n \n #generate linearfilterbank\n def _linearFilterBank(self, nchannels=40):\n freq_min = 0\n freq_max = self._sr//2\n linear_centers = np.linspace(freq_min, freq_max, nchannels+2)\n bins = np.floor((self._nfft+1)*linear_centers/self._sr)\n #print(bins)\n\n filterbank = np.zeros((nchannels, self._nfft//2))\n for m in range(1, nchannels+1):\n f_m_minus = int(bins[m - 1]) # left\n f_m = int(bins[m]) # center\n f_m_plus = int(bins[m + 1]) # right\n\n for k in range(f_m_minus, f_m):\n filterbank[m - 1, k] = (k - bins[m - 1]) / (bins[m] - bins[m - 1])\n for k in range(f_m, f_m_plus):\n filterbank[m - 1, k] = (bins[m + 1] - k) / (bins[m + 1] - bins[m])\n\n return filterbank\n \n #discrete cosine transform\n def _dct(self, mspec):\n return realtransforms.dct(mspec, type=2, norm='ortho', axis=-1)\n \n#end of class LFCC\n\nif __name__ == \"__main__\":\n #import librosa\n\n lfcc = LFCC(\"utterance3.wav\").get_lfcc().T\n \n# y, sr = librosa.load(\"utterance3.wav\", sr=22050)\n# mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=12).T\n\n print(lfcc[100], lfcc.shape)\n# print(mfcc[100], mfcc.shape)","repo_name":"ReonNamatame/ASV_anti-spoofing","sub_path":"baseline/lfcc.py","file_name":"lfcc.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"38426037036","text":"import sys\nimport chilkat\n\n# This example requires the Chilkat SFTP API to have been previously unlocked.\n# See Unlock Chilkat SFTP for sample code.\nglob = chilkat.CkGlobal()\nsuccess = glob.UnlockBundle(\"Anything for 30-day trial\")\nsftp = chilkat.CkSFtp()\n\nsuccess = sftp.Connect(\"sb-emea.avl.com\",22)\nif (success == True):\n success = sftp.AuthenticatePw(\"abhishek.hingwasia@avl.com\",\"AvlAvl2931!!\")\n\nif (success == True):\n success = sftp.InitializeSftp()\n\nif (success != True):\n print(sftp.lastErrorText())\n sys.exit()\n\n# Synchronize (by uploading) the local directory tree rooted at \"qa_data/sftpUploadTree\"\n# with the remote directory tree rooted at \"syncUploadTest\"\n# Both directories are relative paths. The remote directory\n# is relative to the HOME directory of the SSH user account.\n# The local directory is relative to the current working directory of the process.\n# It is also possible to use absolute paths.\n\nremoteDir = \"/Cummins_CTCI_NB/sftp_image_test/\"\nlocalDir = \"D:/python_iot1\"\n\n# Possible modes that can be passed to the SyncTreeUpload method are:\n# mode=0: Upload all files\n# mode=1: Upload all files that do not exist on the server.\n# mode=2: Upload newer or non-existant files.\n# mode=3: Upload only newer files. If a file does not already exist on the server, it is not uploaded.\n# mode=4: transfer missing files or files with size differences.\n# mode=5: same as mode 4, but also newer files.\n\n# This example will use mode 5 to upload missing, newer, or files with size differences.\nmode = 5\n# This example turns on recursion to synchronize the entire tree.\n# Recursion can be turned off to synchronize the files of a single directory.\nrecursive = True\nsuccess = sftp.SyncTreeUpload(localDir,remoteDir,mode,recursive)\nif (success != True):\n print(sftp.lastErrorText())\n sys.exit()\n\nprint(\"Success.\")\n","repo_name":"kamalsingh-engg/CVopenTutorial_python","sub_path":"chilkatrr.py","file_name":"chilkatrr.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21894623135","text":"# 1.侦测鼠标事件\nimport cv2\nimg = cv2.imread(\"meme.jpg\")\n\ndef show_xy(event,x,y,flags,userdata):\n print(event,x,y,flags)\n # 印出相关参数的数值,userdata 可透过 setMouseCallback 第三个参数垂递给函式\n\ncv2.imshow(\"oxxostudio\", img)\ncv2.setMouseCallback(\"oxxostudio\", show_xy) # 设定侦测事件的函式与视窗\n\ncv2.waitKey(0) # 按下任意键停止\ncv2.destroyAllWindows()\n\n\n# 2.鼠标 event 与 flag 列表\n# 代号\t 事件\t 说明\n# 0\tcv2.EVENT_MOUSEMOVE\t 滑动\n# 1\tcv2.EVENT_LBUTTONDOWN\t 左键点击\n# 2\tcv2.EVENT_RBUTTONDOWN\t 右键点击\n# 3\tcv2.EVENT_MBUTTONDOWN\t 中键点击\n# 4\tcv2.EVENT_LBUTTONUP\t 左键放开\n# 5\tcv2.EVENT_RBUTTONUP\t 右键放开\n# 6\tcv2.EVENT_MBUTTONUP\t 中键放开\n# 7\tcv2.EVENT_LBUTTONDBLCLK\t 左键双击\n# 8\tcv2.EVENT_RBUTTONDBLCLK\t 右键双击\n# 9\tcv2.EVENT_MBUTTONDBLCLK\t 中键双击\n\n# 代号\t flag\t 说明\n# 1\t cv2.EVENT_FLAG_LBUTTON\t 左键拖曳\n# 2\t cv2.EVENT_FLAG_RBUTTON\t 右键拖曳\n# 4\t cv2.EVENT_FLAG_MBUTTON\t 中键拖曳\n# 8~15\t cv2.EVENT_FLAG_CTRLKEY\t按 Ctrl 不放事件\n# 16~31\tcv2.EVENT_FLAG_SHIFTKEY\t按 Shift 不放事件\n# 32~39\tcv2.EVENT_FLAG_ALTKEY\t按 Alt 不放事件\n\n\n# 3.透过鼠标点击,取得像素的颜色\nimport cv2\nimg = cv2.imread(\"meme.jpg\")\n\ndef show_xy(event,x,y,flags,param):\n if event == 0:\n img2 = img.copy() # 当鼠标移动时,复制原本的图片\n cv2.circle(img2, (x,y), 10, (0,0,0), 1) # 绘制黑色空心圆\n cv2.imshow(\"oxxostudio\", img2) # 显示绘制后的影像\n if event == 1:\n color = img[y,x] # 当鼠标点击时\n print(color) # 印出颜色\n\ncv2.imshow(\"oxxostudio\", img)\ncv2.setMouseCallback(\"oxxostudio\", show_xy)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n# 4.透过鼠标点击,绘制多边形\nimport cv2\nimg = cv2.imread(\"meme.jpg\")\n\ndots = [] # 记录座标的空串列\ndef show_xy(event,x,y,flags,param):\n if event == 1:\n dots.append([x, y]) # 记录座标\n cv2.circle(img, (x, y), 10, (0,0,255), -1) # 在点击的位置,绘制圆形\n num = len(dots) # 目前有几个座标\n if num > 1: # 如果有两个点以上\n x1 = dots[num-2][0]\n y1 = dots[num-2][1]\n x2 = dots[num-1][0]\n y2 = dots[num-1][1]\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) # 取得最后的两个座标,绘制直线\n cv2.imshow(\"oxxostudio\", img)\n\ncv2.imshow(\"oxxostudio\", img)\ncv2.setMouseCallback(\"oxxostudio\", show_xy)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"AlexHsieh19960510/OpenCV","sub_path":"偵測滑鼠事件.py","file_name":"偵測滑鼠事件.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71415462444","text":"# Databricks notebook source\n# Create reset_workspace widget\ndbutils.widgets.dropdown(\"reset_workspace\", \"False\", [\"True\", \"False\"])\n\n# COMMAND ----------\n\ndef get_params():\n import json\n params = json.loads(dbutils.notebook.run('./config/99_config',timeout_seconds=60))\n project_directory = params['project_directory']\n database_name = params['database_name']\n data_gen_path = \"/dbfs{}/raw/attribution_data.csv\".format(project_directory)\n raw_data_path = \"dbfs:{}/raw\".format(project_directory)\n bronze_tbl_path = \"dbfs:{}/bronze\".format(project_directory)\n gold_user_journey_tbl_path = \"dbfs:{}/gold_user_journey\".format(project_directory)\n gold_attribution_tbl_path = \"dbfs:{}/gold_attribution\".format(project_directory)\n gold_ad_spend_tbl_path = \"dbfs:{}/gold_ad_spend\".format(project_directory)\n\n params = {\"project_directory\": project_directory,\n \"database_name\": database_name,\n \"data_gen_path\": data_gen_path,\n \"raw_data_path\": raw_data_path,\n \"bronze_tbl_path\": bronze_tbl_path,\n \"gold_user_journey_tbl_path\": gold_user_journey_tbl_path,\n \"gold_attribution_tbl_path\": gold_attribution_tbl_path,\n \"gold_ad_spend_tbl_path\": gold_ad_spend_tbl_path,\n }\n \n return params\n\n# COMMAND ----------\n\ndef reset_workspace(reset_flag=\"False\"):\n params = get_params()\n project_directory = params['project_directory']\n database_name = params['database_name']\n raw_data_path = params['raw_data_path']\n \n if reset_flag == \"True\":\n # Replace existing project directory with new one\n dbutils.fs.rm(project_directory, recurse=True)\n #dbutils.fs.mkdirs(project_directory)\n dbutils.fs.mkdirs(raw_data_path)\n \n # Replace existing database with new one\n spark.sql(\"DROP DATABASE IF EXISTS \" +database_name+ \" CASCADE\")\n spark.sql(\"CREATE DATABASE \" + database_name)\n elif dbutils.fs.ls(raw_data_path) == False:\n dbutils.fs.mkdirs(raw_data_path)\n return None\n\n# COMMAND ----------\n\n\n","repo_name":"databricks-industry-solutions/multi-touch-attribution","sub_path":"config/99_utils.py","file_name":"99_utils.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"34436947269","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport sys\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom splinter import Browser\nfrom selenium import webdriver\nimport time\nimport tkinter as tk\n\n\n\ndef download(url,user_agent=\"wswp\",num_retries=2,charset='utf-8',proxy=None):\n\tprint(\"Downloading:\",url)\n\trequest = urllib.request.Request(url)\n\trequest.add_header(\"User-agent\",user_agent)\n\ttry:\n\t\tif proxy:\n\t\t\tproxy_support = urllib.request.ProxyHandler({'http':proxy})\n\t\t\topener = urllib.request.build_opener(proxy_support)\n\t\t\turllib.request.install_opener(opener)\n\t\tresp = urllib.request.urlopen(request)\n\t\tcs = resp.headers.get_content_charset()\n\t\tif not cs:\n\t\t\tcs = charset\n\t\thtml = resp.read().decode(cs)\n\texcept (urllib.error.URLError,urllib.error.HTTPError) as e:\n\t\tprint(\"Download error:\",e.reason)\n\t\thtml = None\n\t\tif num_retries > 0:\n\t\t\tif hasattr(e,'code') and 500 <= e.code < 600:\n\t\t\t\treturn download(url,num_retries-1)\n\treturn html\ndef parser_html():\n\tarr_node = []\n\tpage = \"\"\n\tarr_obj = {}\n\tcount = 1\n\tstr_num = ''\n\twhile count <= 10:\n\t\tpage = \"https://www.ximalaya.com/search/zhubo/%E8%82%A1%E7%A5%A8/p\" +str(count)\n\t\thtmls = download(page)\n\t\tbsObj = BeautifulSoup(htmls,\"html5lib\")\n\t\tnodes = bsObj.findAll(\"a\",{'class':\"anchor-link Qgwp\"})\n\t\tcount = count+1\n\t\tfor node in nodes:\n\n\t\t\tstr_num = str(node['href'].split('/')[-2])\n\t\t\tprint(str_num)\n\t\t\tarr_node.append(str_num)\n\t\t\t# print(read_txt()[str_num])\n\t\t\tif (str_num in read_txt() )and read_txt()[str_num] == 1:\n\t\t\t\tarr_obj[str_num] = 1\n\t\t\telse:\n\t\t\t\tarr_obj[str_num] = 0\n\twrite_txt(arr_obj)\n\treturn arr_node\n\nif __name__ == '__main__':\n\thtml = download(\"http://admin.xuanqiquan.com/cash.html\")\n\tprint(html)\n","repo_name":"liudong9393/code_py","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1590521965","text":"texto=\"hola mundo\"\r\ndiccionario=dict()\r\nconstador = 0\r\nfor x,y in enumerate(texto.split()):\r\n\tdiccionario[y]=constador\r\n\tconstador+=1\r\n\r\nprint(diccionario)\r\n\r\n\r\nenumerate(['la', 'vida', 'es', 'bella', 'faveriana', 'terminal'])\r\n\r\nprint(\"************************\")\r\nfor x in ((0,'la'),(1,'vida'),(2,'es'),(3,'bella'),(4,'faverian'),(5,'terminal')):\r\n print(x[0], x[1]) ","repo_name":"WilliamPerezBeltran/studying_python","sub_path":"clases-daniel_python/estructuras_de_datos/matrices/11_diccionary.py","file_name":"11_diccionary.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24259200548","text":"import argparse\nimport data_loader.data_loaders as module_data\nimport data_loader.processor as module_processor\nfrom pytorch_pretrained_bert.modeling import BertConfig\nimport model.model as module_arch\nfrom parse_config import ConfigParser\nfrom agent import Agent\n\ndef predict(config, s1, s2):\n logger = config.get_logger('test')\n # setup data_loader instances\n processor = config.initialize('processor', module_processor, logger, config)\n # build model architecture, then print to console\n if config.bert_config_path:\n bert_config = BertConfig(config.bert_config_path)\n model = config.initialize('arch', module_arch, config=bert_config, num_labels=processor.nums_label())\n else:\n model = config.initialize_bert_model('arch', module_arch, num_labels=processor.nums_label())\n #logger.info(model)\n agent = Agent(model, config=config)\n\n batch = processor.handle_bert_on_batch(s1, s2)\n print(batch)\n print(agent.predict(batch))\n\n\nif __name__ == '__main__':\n args = argparse.ArgumentParser(description='PyTorch Template')\n\n args.add_argument('-r', '--resume', default=None, type=str,\n help='path to latest checkpoint (default: None)')\n args.add_argument('-d', '--device', default=None, type=str,\n help='indices of GPUs to enable (default: all)')\n\n args.add_argument('-s1', '--sentence1', default=\" \", type=str,\n help='s1')\n args.add_argument('-s2', '--sentence2', default=\" \", type=str,\n help='s2')\n\n #config = MockConfigParser(resume='saved/models/ATEC_ESIM/0530_101350/model_best.pth')\n config = ConfigParser(args)\n args = args.parse_args()\n # for arg in sys.argv:\n # print(arg)\n print(args.sentence1, args.sentence2)\n predict(config, [args.sentence1], [args.sentence2])\n\n","repo_name":"MrXJC/pytorch-bert-template","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"19"} +{"seq_id":"22033303395","text":"from typing import Any\nfrom uuid import uuid4\n\nfrom ..project import Project\nfrom ..environ.data import Mapping\nfrom ..schema import Table\nfrom ..schema import Field\nfrom .. import const\n\nfrom .data import DataModel\nfrom .data import GridColumn\nfrom .data import DataInfo\nfrom . import column\n\n\ndef build(proj: Project, map: Mapping, dm: DataModel, table: Table, data: Any) -> DataInfo:\n # フィールドを設定に従って展開する。ForeignKeyなども設定に含まれるものとする。\n columns = _build_columns(proj, map, dm, table)\n rows = [column.build_one_row(columns, d) for d in data]\n\n return DataInfo(\n grid_columns=columns,\n grid_rows=rows,\n allow_line_addition_and_removal=True\n )\n\n\ndef build_one_row(proj: Project, map: Mapping, dm: DataModel, table: Table) -> dict[str, Any]:\n columns = _build_columns(proj, map, dm, table)\n return column.build_one_row(columns, {})\n\n\ndef _build_columns(proj: Project, map: Mapping, dm: DataModel, table: Table) -> list[GridColumn]:\n columns = []\n for field in table.fields:\n if field.column_name in dm.settings:\n grid_column = _make_grid_column_from_setting(proj, map, dm, field)\n else:\n grid_column = column.make_grid_column(\n field.column_name,\n field.display_name)\n\n columns.append(grid_column)\n return columns\n\n\ndef _make_grid_column_from_setting(proj: Project, map: Mapping, dm: DataModel, field: Field):\n setting = dm.settings[field.column_name]\n if setting['type'] == const.BIND_TYPE_REF_ID:\n # 固定値と同じものとする\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n editable=False,\n hide=True,\n reference='id')\n if setting['type'] == const.BIND_TYPE_FOREIGN_KEY:\n # 選択肢は外部データを参照する以外は選択型と同じ\n items = column.load_for_select_items(proj.folder, map, dm.instance, setting['value'])\n if items is None:\n # データが見つからなければ空の配列とする\n items = []\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n items=items)\n if setting['type'] == const.BIND_TYPE_EMBEDDED_DATA:\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n items=setting['values'])\n\n bind = proj.bindings[setting['type']]\n if bind.type == const.BIND_TYPE_FIXED:\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n editable=False,\n hide=True,\n fixed_value=bind.value)\n if bind.type == const.BIND_TYPE_CALL:\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n editable=False,\n call_value=bind.value)\n if bind.type == const.BIND_TYPE_SELECTABLE:\n return column.make_grid_column(\n field.column_name,\n field.display_name,\n items=bind.items)\n raise RuntimeError('Unknown Data Type')\n\n\ndef parse(proj: Project, map: Mapping, dm: DataModel, table: Table, rows: object) -> list[dict[str, Any]]:\n # idカラムを除いて返却する。\n columns = _build_columns(proj, map, dm, table)\n data = [column.build_one_row(columns, d, False) for d in rows]\n return data\n","repo_name":"tamuto/dbgear","sub_path":"dbgear/models/datagrid/layout_table.py","file_name":"layout_table.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"75042415404","text":"import numpy as np\n\n\ndef biting(temperature):\n\n n_temp = temperature.shape[0]\n\n # Initialize\n biting_rate = np.zeros((n_temp,))\n\n for i in range(n_temp):\n\n temp_i = temperature[i]\n\n if temp_i >= 0:\n biting_rate[i] = max(0.000203 * temp_i * (temp_i - 11.7) * np.sqrt(42.3 - temp_i), 0)\n\n return biting_rate\n\n\ndef deposition(temperature):\n\n n_temp = temperature.shape[0]\n\n # Initialize\n deposition_rate = np.zeros((n_temp,))\n\n for i in range(n_temp):\n\n temp_i = temperature[i]\n\n deposition_rate[i] = max(-0.153 * (temp_i ** 2) + 8.61 * temp_i - 97.7, 0)\n\n return deposition_rate\n\n\ndef immature_death(temperature):\n\n n_temp = temperature.shape[0]\n\n # Initialize\n death_rate = np.zeros((n_temp,))\n\n for i in range(n_temp):\n\n temp_i = temperature[i]\n\n death_rate[i] = min(0.002 * np.exp(((temp_i - 23) / 6.05) ** 2), 1)\n\n return death_rate\n\n\ndef mature_death(temperature):\n\n n_temp = temperature.shape[0]\n\n # Initialize\n death_rate = np.zeros((n_temp,))\n\n for i in range(n_temp):\n\n temp_i = temperature[i]\n\n if temp_i > 15:\n if temp_i < 32:\n death_rate[i] = 1 / 30\n else:\n death_rate[i] = -29 / 30 / 19 * (-temp_i + 51) + 1\n elif temp_i < -4:\n death_rate[i] = 1\n else:\n death_rate[i] = -29 / 30 / 19 * (temp_i + 4) + 1\n\n return death_rate\n\n\ndef maturation(temperature, rainfall_avg):\n\n n_temp = temperature.shape[0]\n\n R_L = 76\n R = rainfall_avg\n\n # Initialize\n maturation_rate = np.zeros((n_temp,))\n\n for i in range(n_temp):\n\n temp_i = temperature[i]\n\n if (temp_i >= 16.5) and (temp_i <= 35.6):\n f = -0.153 * (temp_i ** 2) + 8.61 * temp_i - 97.7\n e = f / mature_death(np.array([temp_i]))\n p_E = 3.6 * R * (R_L - R) / (R_L ** 2)\n if p_E < 0:\n p_E = 0\n p_L = np.exp(-0.00554 * temp_i + 0.06737) * R * (R_L - R) / (R_L ** 2)\n p_P = 3 * R * (R_L - R) / (R_L ** 2)\n tau_EA = 1 / (-0.00094 * (temp_i ** 2) + 0.049 * temp_i - 0.552)\n maturation_rate[i] = e * p_E * p_L * p_P / tau_EA\n\n return maturation_rate","repo_name":"yoon-gu/epirl","sub_path":"mesa_examples/malaria/src/temp_parameters.py","file_name":"temp_parameters.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35784774378","text":"from typing import List\nfrom nose.tools import assert_equal\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n return max(nums[0], self.choose_rob(nums[1:]), self.choose_rob(nums[:-1]))\n\n def choose_rob(self, nums: List[int]) -> int:\n rob1 = 0\n rob2 = 0\n\n for i in nums:\n temp = max(rob1 + i, rob2)\n rob1 = rob2\n rob2 = temp\n\n return rob2\n\n\nclass testSuits:\n\n @staticmethod\n def test(sol):\n assert_equal(sol([2, 3, 2]), 3)\n assert_equal(sol([1, 2, 3, 1]), 4)\n assert_equal(sol([1, 2, 3]), 3)\n print('ALL TEST CASES PASSED')\n\n\ns = Solution()\nt = testSuits()\nt.test(s.rob)\n","repo_name":"Purushotam-Thakur/data-structures-and-algorithms","sub_path":"leetcode/Hause Robber/213. House Robber II.py","file_name":"213. House Robber II.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42108687309","text":"# coding=utf-8\n# TODO: make the next two lines unnecessary\n# pylint: disable=line-too-long\n# pylint: disable=missing-docstring\n# pylint: disable=method-hidden\nimport logging\nimport os\nimport pwd\nimport re\nimport sys\nimport time\nimport datetime\nimport yaml\nfrom urllib.parse import urljoin\nfrom abc import ABC, abstractmethod\n\nfrom queue import Empty, Queue\nfrom builtins import str\nimport requests\nimport threading\n\nfrom ...common.interfaces import AbstractPlugin, \\\n MonitoringDataListener, AggregateResultListener, AbstractInfoWidget\nfrom ...common.util import expand_to_seconds\nfrom ..Autostop import Plugin as AutostopPlugin\nfrom ..Console import Plugin as ConsolePlugin\nfrom .client import APIClient, OverloadClient, LPRequisites, CloudGRPCClient\nfrom ...common.util import FileScanner\nfrom .loadtesting_agent import create_loadtesting_agent\n\nfrom yandextank.contrib.netort.netort.data_processing import Drain\nfrom yandex.cloud.loadtesting.agent.v1 import test_service_pb2\n\nlogger = logging.getLogger(__name__) # pylint: disable=C0103\n\nLOADTESTING_CONFIG_PATH = '/etc/tank_client/config.yaml'\nLOADTESTING_CONFIG_PATH_ENV = 'LOADTESTING_AGENT_CONFIG'\n\n\nclass BackendTypes(object):\n OVERLOAD = 'OVERLOAD'\n LUNAPARK = 'LUNAPARK'\n CLOUD = 'CLOUD'\n\n @classmethod\n def identify_backend(cls, api_address, cfg_section_name):\n clues = [\n ('overload', cls.OVERLOAD),\n ('lunapark', cls.LUNAPARK),\n ('loadtesting', cls.CLOUD),\n ]\n for clue, backend_type in clues:\n if clue in api_address:\n return backend_type\n else:\n for clue, backend_type in clues:\n if clue in cfg_section_name:\n return backend_type\n else:\n raise KeyError(\n 'Can not identify backend: neither api address nor section name match any of the patterns:\\n%s' %\n '\\n'.join(['*%s*' % ptrn[0] for ptrn in clues]))\n\n\nclass Job(ABC):\n\n def __init__(self):\n pass\n\n @abstractmethod\n def push_test_data(self):\n \"\"\"method for pushing test data to server\"\"\"\n\n @abstractmethod\n def edit_metainfo(self):\n \"\"\"method for sending job metainfo to server\"\"\"\n\n @property\n @abstractmethod\n def number(self):\n \"\"\"property with job number\"\"\"\n\n @abstractmethod\n def close(self):\n \"\"\"method for closing job\"\"\"\n\n @abstractmethod\n def create(self):\n \"\"\"method for creating job\"\"\"\n\n @abstractmethod\n def send_status(self):\n \"\"\"method for sending status to server\"\"\"\n\n @abstractmethod\n def send_config(self):\n \"\"\"method for sending test config to server\"\"\"\n\n @abstractmethod\n def push_monitoring_data(self):\n \"\"\"method for pushing monitoring data\"\"\"\n\n @abstractmethod\n def push_events_data(self):\n \"\"\"method for pushing event data\"\"\"\n\n @abstractmethod\n def lock_target(self):\n \"\"\"method for locking target during...\"\"\"\n\n @abstractmethod\n def set_imbalance_and_dsc(self):\n \"\"\"method for imbalance detection\"\"\"\n\n @abstractmethod\n def is_target_locked(self):\n \"\"\"method for checking target lock\"\"\"\n\n\ndef chop(data_list, chunk_size):\n if sys.getsizeof(str(data_list)) <= chunk_size:\n return [data_list]\n elif len(data_list) == 1:\n logger.info(\"Too large piece of Telegraf data. Might experience upload problems.\")\n return [data_list]\n else:\n mid = int(len(data_list) / 2)\n return chop(data_list[:mid], chunk_size) + chop(data_list[mid:], chunk_size)\n\n\nclass Plugin(AbstractPlugin, AggregateResultListener,\n MonitoringDataListener):\n RC_STOP_FROM_WEB = 8\n VERSION = '3.0'\n SECTION = 'uploader'\n\n def __init__(self, core, cfg, name):\n AbstractPlugin.__init__(self, core, cfg, name)\n self.data_queue = Queue()\n self.monitoring_queue = Queue()\n if self.core.error_log:\n self.events_queue = Queue()\n self.events_reader = EventsReader(self.core.error_log)\n self.events_processing = Drain(self.events_reader, self.events_queue)\n self.add_cleanup(self.stop_events_processing)\n self.events_processing.start()\n self.events = threading.Thread(target=self.__events_uploader)\n self.events.daemon = True\n\n self.retcode = -1\n self._target = None\n self.task_name = ''\n self.token_file = None\n self.version_tested = None\n self.send_status_period = 10\n\n self.status_sender = threading.Thread(target=self.__send_status)\n self.status_sender.daemon = True\n\n self.upload = threading.Thread(target=self.__data_uploader)\n self.upload.daemon = True\n\n self.monitoring = threading.Thread(target=self.__monitoring_uploader)\n self.monitoring.daemon = True\n\n self._is_telegraf = None\n self.backend_type = BackendTypes.identify_backend(self.cfg['api_address'], self.cfg_section_name)\n self._task = None\n self._api_token = ''\n self._lp_job = None\n self._lock_duration = None\n self._info = None\n self.locked_targets = []\n self.web_link = None\n self.finished = False\n\n def set_option(self, option, value):\n self.cfg.setdefault('meta', {})[option] = value\n self.core.publish(self.SECTION, 'meta.{}'.format(option), value)\n\n @staticmethod\n def get_key():\n return __file__\n\n @property\n def lock_duration(self):\n if self._lock_duration is None:\n info = self.get_generator_info()\n self._lock_duration = info.duration if info.duration else \\\n expand_to_seconds(self.get_option(\"target_lock_duration\"))\n return self._lock_duration\n\n def get_available_options(self):\n opts = [\n \"api_address\",\n \"writer_endpoint\",\n \"task\",\n \"job_name\",\n \"job_dsc\",\n \"notify\",\n \"ver\", \"component\",\n \"operator\",\n \"jobno_file\",\n \"ignore_target_lock\",\n \"target_lock_duration\",\n \"lock_targets\",\n \"jobno\",\n \"upload_token\",\n 'connection_timeout',\n 'network_attempts',\n 'api_attempts',\n 'maintenance_attempts',\n 'network_timeout',\n 'api_timeout',\n 'maintenance_timeout',\n 'strict_lock',\n 'send_status_period',\n 'log_data_requests',\n 'log_monitoring_requests',\n 'log_status_requests',\n 'log_other_requests',\n 'threads_timeout',\n 'chunk_size'\n ]\n return opts\n\n def configure(self):\n self.core.publish(self.SECTION, 'component', self.get_option('component'))\n self.core.publish(self.SECTION, 'task', self.get_option('task'))\n self.core.publish(self.SECTION, 'job_name', self.get_option('job_name'))\n\n def check_task_is_open(self):\n if self.backend_type != BackendTypes.LUNAPARK:\n return\n TASK_TIP = 'The task should be connected to Lunapark.' \\\n 'Open startrek task page, click \"actions\" -> \"load testing\".'\n\n logger.debug(\"Check if task %s is open\", self.task)\n try:\n task_data = self.lp_job.get_task_data(self.task)[0]\n try:\n task_status = task_data['status']\n if task_status == 'Open':\n logger.info(\"Task %s is ok\", self.task)\n self.task_name = str(task_data['name'])\n else:\n logger.info(\"Task %s:\", self.task)\n logger.info(task_data)\n raise RuntimeError(\"Task is not open\")\n except KeyError:\n try:\n error = task_data['error']\n raise RuntimeError(\n \"Task %s error: %s\\n%s\", self.task, error, TASK_TIP)\n except KeyError:\n raise RuntimeError(\n 'Unknown task data format:\\n{}'.format(task_data))\n except requests.exceptions.HTTPError as ex:\n logger.error(\n \"Failed to check task status for '%s': %s\", self.task, ex)\n if ex.response.status_code == 404:\n raise RuntimeError(\"Task not found: %s\\n%s\" % (self.task, TASK_TIP))\n elif ex.response.status_code == 500 or ex.response.status_code == 400:\n raise RuntimeError(\n \"Unable to check task staus, id: %s, error code: %s\" %\n (self.task, ex.response.status_code))\n raise ex\n\n @staticmethod\n def search_task_from_cwd(cwd):\n issue = re.compile(\"^([A-Za-z]+-[0-9]+)(-.*)?\")\n while cwd:\n logger.debug(\"Checking if dir is named like JIRA issue: %s\", cwd)\n if issue.match(os.path.basename(cwd)):\n res = re.search(issue, os.path.basename(cwd))\n return res.group(1).upper()\n\n newdir = os.path.abspath(os.path.join(cwd, os.path.pardir))\n if newdir == cwd:\n break\n else:\n cwd = newdir\n\n raise RuntimeError(\n \"task=dir requested, but no JIRA issue name in cwd: %s\" %\n os.getcwd())\n\n def prepare_test(self):\n info = self.get_generator_info()\n port = info.port\n instances = info.instances\n if info.ammo_file is not None:\n if info.ammo_file.startswith(\"http://\") or info.ammo_file.startswith(\"https://\"):\n ammo_path = info.ammo_file\n else:\n ammo_path = os.path.realpath(info.ammo_file)\n else:\n logger.warning('Failed to get info about ammo path')\n ammo_path = 'Undefined'\n loop_count = int(info.loop_count)\n\n try:\n lp_job = self.lp_job\n self.add_cleanup(self.unlock_targets)\n self.locked_targets = self.check_and_lock_targets(strict=self.get_option('strict_lock'),\n ignore=self.get_option('ignore_target_lock'))\n if lp_job._number:\n self.make_symlink(lp_job._number)\n self.check_task_is_open()\n else:\n self.check_task_is_open()\n lp_job.create()\n self.make_symlink(lp_job.number)\n self.publish('job_no', lp_job.number)\n except (APIClient.JobNotCreated, APIClient.NotAvailable, APIClient.NetworkError) as e:\n logger.error(e)\n logger.error(\n 'Failed to connect to Lunapark, disabling DataUploader')\n self.start_test = lambda *a, **kw: None\n self.post_process = lambda *a, **kw: None\n self.on_aggregated_data = lambda *a, **kw: None\n self.monitoring_data = lambda *a, **kw: None\n return\n\n cmdline = ' '.join(sys.argv)\n lp_job.edit_metainfo(\n instances=instances,\n ammo_path=ammo_path,\n loop_count=loop_count,\n regression_component=self.get_option(\"component\"),\n cmdline=cmdline,\n )\n\n self.core.job.subscribe_plugin(self)\n\n try:\n console = self.core.get_plugin_of_type(ConsolePlugin)\n except KeyError as ex:\n logger.debug(ex)\n console = None\n\n if console:\n console.add_info_widget(JobInfoWidget(self))\n\n self.set_option('target_host', self.target)\n self.set_option('target_port', port)\n self.set_option('cmdline', cmdline)\n self.set_option('ammo_path', ammo_path)\n self.set_option('loop_count', loop_count)\n self.__save_conf()\n\n def start_test(self):\n self.add_cleanup(self.join_threads)\n self.status_sender.start()\n self.upload.start()\n self.monitoring.start()\n if self.core.error_log:\n self.events.start()\n\n self.web_link = urljoin(self.lp_job.api_client.base_url, str(self.lp_job.number))\n logger.info(\"Web link: %s\", self.web_link)\n\n self.publish(\"jobno\", self.lp_job.number)\n self.publish(\"web_link\", self.web_link)\n\n jobno_file = self.get_option(\"jobno_file\", '')\n if jobno_file:\n logger.debug(\"Saving jobno to: %s\", jobno_file)\n with open(jobno_file, 'w') as fdes:\n fdes.write(str(self.lp_job.number))\n self.core.add_artifact_file(jobno_file)\n self.__save_conf()\n\n def is_test_finished(self):\n return self.retcode\n\n def end_test(self, retcode):\n if retcode != 0:\n self.lp_job.interrupted.set()\n self.__save_conf()\n self.unlock_targets()\n return retcode\n\n def close_job(self):\n self.lp_job.close(self.retcode)\n\n def join_threads(self):\n self.lp_job.interrupted.set()\n if self.monitoring.is_alive():\n self.monitoring.join()\n if self.upload.is_alive():\n self.upload.join()\n\n def stop_events_processing(self):\n self.events_queue.put(None)\n self.events_reader.close()\n self.events_processing.close()\n if self.events_processing.is_alive():\n self.events_processing.join()\n if self.events.is_alive():\n self.lp_job.interrupted.set()\n self.events.join()\n\n def post_process(self, rc):\n self.retcode = rc\n self.monitoring_queue.put(None)\n self.data_queue.put(None)\n if self.core.error_log:\n self.events_queue.put(None)\n self.events_reader.close()\n self.events_processing.close()\n self.events.join()\n logger.info(\"Waiting for sender threads to join.\")\n if self.monitoring.is_alive():\n self.monitoring.join()\n if self.upload.is_alive():\n self.upload.join()\n self.finished = True\n logger.info(\n \"Web link: %s\", self.web_link)\n autostop = None\n try:\n autostop = self.core.get_plugin_of_type(AutostopPlugin)\n except KeyError as ex:\n logger.debug(ex)\n\n if autostop and autostop.cause_criterion and autostop.imbalance_timestamp:\n self.lp_job.set_imbalance_and_dsc(\n autostop.imbalance_rps,\n autostop.cause_criterion.explain(),\n autostop.imbalance_timestamp\n )\n\n else:\n logger.debug(\"No autostop cause detected\")\n self.__save_conf()\n return rc\n\n def on_aggregated_data(self, data, stats):\n \"\"\"\n @data: aggregated data\n @stats: stats about gun\n \"\"\"\n if not self.lp_job.interrupted.is_set():\n self.data_queue.put((data, stats))\n\n def monitoring_data(self, data_list):\n if not self.lp_job.interrupted.is_set():\n if len(data_list) > 0:\n [self.monitoring_queue.put(chunk) for chunk in chop(data_list, self.get_option(\"chunk_size\"))]\n\n def __send_status(self):\n logger.info('Status sender thread started')\n lp_job = self.lp_job\n while not lp_job.interrupted.is_set():\n try:\n self.lp_job.send_status(self.core.info.get_info_dict())\n time.sleep(self.get_option('send_status_period'))\n except (APIClient.NetworkError, APIClient.NotAvailable) as e:\n logger.warn('Failed to send status')\n logger.debug(e)\n break\n except APIClient.StoppedFromOnline:\n logger.info(\"Test stopped from Lunapark\")\n self.retcode = self.RC_STOP_FROM_WEB\n break\n if self.finished:\n break\n logger.info(\"Closed Status sender thread\")\n\n def __uploader(self, queue, sender_method, name='Uploader'):\n logger.info('{} thread started'.format(name))\n while not self.lp_job.interrupted.is_set():\n try:\n entry = queue.get(timeout=1)\n if entry is None:\n logger.info(\"{} queue returned None\".format(name))\n break\n sender_method(entry)\n except Empty:\n continue\n except APIClient.StoppedFromOnline:\n logger.warning(\"Lunapark is rejecting {} data\".format(name))\n break\n except (APIClient.NetworkError, APIClient.NotAvailable, APIClient.UnderMaintenance) as e:\n logger.warn('Failed to push {} data'.format(name))\n logger.warn(e)\n self.lp_job.interrupted.set()\n except Exception:\n logger.exception(\"Unhandled exception occured. Skipping data chunk...\")\n # purge queue\n while not queue.empty():\n if queue.get_nowait() is None:\n break\n logger.info(\"Closing {} thread\".format(name))\n\n def __data_uploader(self):\n self.__uploader(self.data_queue,\n lambda entry: self.lp_job.push_test_data(*entry),\n 'Data Uploader')\n\n def __monitoring_uploader(self):\n self.__uploader(self.monitoring_queue,\n self.lp_job.push_monitoring_data,\n 'Monitoring Uploader')\n\n def __events_uploader(self):\n self.__uploader(self.events_queue,\n self.lp_job.push_events_data,\n 'Events Uploader')\n\n # TODO: why we do it here? should be in core\n def __save_conf(self):\n for requisites, content in self.core.artifacts_to_send:\n self.lp_job.send_config(requisites, content)\n\n def parse_lock_targets(self):\n # prepare target lock list\n locks_list_cfg = self.get_option('lock_targets', 'auto')\n\n def no_target():\n logging.warn(\"Target lock set to 'auto', but no target info available\")\n return {}\n\n locks_set = {self.target} or no_target() if locks_list_cfg == 'auto' else set(locks_list_cfg)\n targets_to_lock = [host for host in locks_set if host]\n return targets_to_lock\n\n def lock_targets(self, targets_to_lock, ignore, strict):\n locked_targets = [target for target in targets_to_lock\n if self.lp_job.lock_target(target, self.lock_duration, ignore, strict)]\n return locked_targets\n\n def unlock_targets(self):\n logger.info(\"Unlocking targets: %s\", self.locked_targets)\n for target in self.locked_targets:\n logger.info(target)\n self.lp_job.api_client.unlock_target(target)\n\n def check_and_lock_targets(self, strict, ignore):\n targets_list = self.parse_lock_targets()\n logger.info('Locking targets: %s', targets_list)\n locked_targets = self.lock_targets(targets_list, ignore=ignore, strict=strict)\n logger.info('Locked targets: %s', locked_targets)\n return locked_targets\n\n def make_symlink(self, name):\n PLUGIN_DIR = os.path.join(self.core.artifacts_base_dir, 'lunapark')\n if not os.path.exists(PLUGIN_DIR):\n os.makedirs(PLUGIN_DIR)\n try:\n os.symlink(\n os.path.relpath(\n self.core.artifacts_dir,\n PLUGIN_DIR),\n os.path.join(\n PLUGIN_DIR,\n str(name)))\n # this exception catch for filesystems w/o symlinks\n except OSError:\n logger.warning('Unable to create symlink for artifact: %s', name)\n\n def _get_user_agent(self):\n plugin_agent = 'Uploader/{}'.format(self.VERSION)\n return ' '.join((plugin_agent,\n self.core.get_user_agent()))\n\n def __get_operator(self):\n try:\n return self.get_option(\n 'operator') or pwd.getpwuid(\n os.geteuid())[0]\n except: # noqa: E722\n logger.error(\n \"Couldn't get username from the OS. Please, set the 'meta.operator' option explicitly in your config \"\n \"file.\")\n raise\n\n def __get_api_client(self):\n logging.info('Using {} backend'.format(self.backend_type))\n self._api_token = None\n if self.backend_type == BackendTypes.LUNAPARK:\n client = APIClient\n elif self.backend_type == BackendTypes.OVERLOAD:\n client = OverloadClient\n self._api_token = self.read_token(self.get_option(\"token_file\"))\n elif self.backend_type == BackendTypes.CLOUD:\n loadtesting_agent = create_loadtesting_agent(backend_url=self.get_option('api_address'),\n config=os.getenv(LOADTESTING_CONFIG_PATH_ENV, LOADTESTING_CONFIG_PATH))\n return CloudGRPCClient(core_interrupted=self.interrupted,\n loadtesting_agent=loadtesting_agent,\n api_attempts=self.get_option('api_attempts'),\n connection_timeout=self.get_option('connection_timeout'))\n else:\n raise RuntimeError(\"Backend type doesn't match any of the expected\")\n\n return client(base_url=self.get_option('api_address'),\n writer_url=self.get_option('writer_endpoint'),\n network_attempts=self.get_option('network_attempts'),\n api_attempts=self.get_option('api_attempts'),\n maintenance_attempts=self.get_option('maintenance_attempts'),\n network_timeout=self.get_option('network_timeout'),\n api_timeout=self.get_option('api_timeout'),\n maintenance_timeout=self.get_option('maintenance_timeout'),\n connection_timeout=self.get_option('connection_timeout'),\n user_agent=self._get_user_agent(),\n api_token=self.api_token,\n core_interrupted=self.interrupted)\n\n @property\n def lp_job(self):\n \"\"\"\n\n :rtype: LPJob\n \"\"\"\n if self._lp_job is None:\n self._lp_job = self.__get_lp_job()\n if isinstance(self._lp_job, LPJob):\n self.core.publish(self.SECTION, 'job_no', self._lp_job.number)\n self.core.publish(self.SECTION, 'web_link', self._lp_job.web_link)\n self.core.publish(self.SECTION, 'job_name', self._lp_job.name)\n self.core.publish(self.SECTION, 'job_dsc', self._lp_job.description)\n self.core.publish(self.SECTION, 'person', self._lp_job.person)\n self.core.publish(self.SECTION, 'task', self._lp_job.task)\n self.core.publish(self.SECTION, 'version', self._lp_job.version)\n self.core.publish(self.SECTION, 'component', self.get_option('component'))\n self.core.publish(self.SECTION, 'meta', self.cfg.get('meta', {}))\n return self._lp_job\n\n def __get_lp_job(self):\n \"\"\"\n\n :rtype: LPJob\n \"\"\"\n api_client = self.__get_api_client()\n\n info = self.get_generator_info()\n port = info.port\n loadscheme = [] if isinstance(info.rps_schedule, (str, dict)) else info.rps_schedule\n\n if self.backend_type == BackendTypes.CLOUD:\n lp_job = CloudLoadTestingJob(client=api_client,\n target_host=self.target,\n target_port=port,\n tank_job_id=self.core.test_id,\n storage=self.core.storage,\n name=self.get_option('job_name', 'untitled'),\n description=self.get_option('job_dsc'),\n config=self.core.configinitial,\n load_scheme=loadscheme)\n else:\n lp_job = LPJob(client=api_client,\n target_host=self.target,\n target_port=port,\n number=self.cfg.get('jobno'),\n token=self.get_option('upload_token'),\n person=self.__get_operator(),\n task=self.task,\n name=self.get_option('job_name', 'untitled'),\n description=self.get_option('job_dsc'),\n tank=self.core.job.tank,\n notify_list=self.get_option(\"notify\"),\n load_scheme=loadscheme,\n version=self.get_option('ver'),\n log_data_requests=self.get_option('log_data_requests'),\n log_monitoring_requests=self.get_option('log_monitoring_requests'),\n log_status_requests=self.get_option('log_status_requests'),\n log_other_requests=self.get_option('log_other_requests'),\n add_cleanup=lambda: self.add_cleanup(self.close_job))\n lp_job.send_config(LPRequisites.CONFIGINITIAL, yaml.dump(self.core.configinitial))\n return lp_job\n\n @property\n def task(self):\n if self._task is None:\n task = self.get_option('task')\n if task == 'dir':\n task = self.search_task_from_cwd(os.getcwd())\n self._task = task\n return self._task\n\n @property\n def api_token(self):\n if self._api_token == '':\n if self.backend_type in [BackendTypes.LUNAPARK, BackendTypes.CLOUD]:\n self._api_token = None\n elif self.backend_type == BackendTypes.OVERLOAD:\n self._api_token = self.read_token(self.get_option(\"token_file\", \"\"))\n else:\n raise RuntimeError(\"Backend type doesn't match any of the expected\")\n return self._api_token\n\n @staticmethod\n def read_token(filename):\n if filename:\n logger.debug(\"Trying to read token from %s\", filename)\n try:\n with open(filename, 'r') as handle:\n data = handle.read().strip()\n logger.info(\n \"Read authentication token from %s, \"\n \"token length is %d bytes\", filename, len(str(data)))\n except IOError:\n logger.error(\n \"Failed to read Overload API token from %s\", filename)\n logger.info(\n \"Get your Overload API token from https://overload.yandex.net and provide it via 'overload.token_file' parameter\"\n )\n raise RuntimeError(\"API token error\")\n return data\n else:\n logger.error(\"Overload API token filename is not defined\")\n logger.info(\n \"Get your Overload API token from https://overload.yandex.net and provide it via 'overload.token_file' parameter\"\n )\n raise RuntimeError(\"API token error\")\n\n def get_generator_info(self):\n return self.core.job.generator_plugin.get_info()\n\n @property\n def target(self):\n if self._target is None:\n self._target = self.get_generator_info().address\n logger.info(\"Detected target: %s\", self._target)\n return self._target\n\n\nclass JobInfoWidget(AbstractInfoWidget):\n def __init__(self, sender):\n # type: (Plugin) -> object\n AbstractInfoWidget.__init__(self)\n self.owner = sender\n\n def get_index(self):\n return 1\n\n def render(self, screen):\n template = \"Author: \" + screen.markup.RED + \"%s\" + \\\n screen.markup.RESET + \\\n \"%s\\n Job: %s %s\\n Task: %s %s\\n Web: %s%s\"\n data = (self.owner.lp_job.person[:1], self.owner.lp_job.person[1:],\n self.owner.lp_job.number, self.owner.lp_job.name, self.owner.lp_job.task,\n # todo: task_name from api_client.get_task_data()\n self.owner.lp_job.task, self.owner.lp_job.api_client.base_url,\n self.owner.lp_job.number)\n\n return template % data\n\n\nclass LPJob(Job):\n def __init__(\n self,\n client,\n target_host,\n target_port,\n person,\n task,\n name,\n description,\n tank,\n log_data_requests=False,\n log_other_requests=False,\n log_status_requests=False,\n log_monitoring_requests=False,\n number=None,\n token=None,\n notify_list=None,\n version=None,\n detailed_time=None,\n load_scheme=None,\n add_cleanup=lambda: None\n ):\n \"\"\"\n :param client: APIClient\n :param log_data_requests: bool\n :param log_other_request: bool\n :param log_status_requests: bool\n :param log_monitoring_requests: bool\n \"\"\"\n assert bool(number) == bool(\n token), 'Job number and upload token should come together'\n self.log_other_requests = log_other_requests\n self.log_data_requests = log_data_requests\n self.log_status_requests = log_status_requests\n self.log_monitoring_requests = log_monitoring_requests\n self.name = name\n self.tank = tank\n self.target_host = target_host\n self.target_port = target_port\n self.person = person\n self.task = task\n self.interrupted = threading.Event()\n self._number = number\n self._token = token\n self.api_client = client\n self.notify_list = notify_list\n self.description = description\n self.version = version\n self.detailed_time = detailed_time\n self.load_scheme = load_scheme\n self.is_finished = False\n self.web_link = ''\n self.add_cleanup = add_cleanup\n if self._number:\n self.add_cleanup()\n\n def push_test_data(self, data, stats):\n if not self.interrupted.is_set():\n try:\n self.api_client.push_test_data(\n self.number, self.token, data, stats, self.interrupted, trace=self.log_data_requests)\n except (APIClient.NotAvailable, APIClient.NetworkError, APIClient.UnderMaintenance):\n logger.warn('Failed to push test data')\n self.interrupted.set()\n\n def edit_metainfo(\n self,\n instances=0,\n ammo_path=None,\n loop_count=None,\n regression_component=None,\n cmdline=None,\n is_starred=False,\n tank_type=1\n ):\n try:\n self.api_client.edit_job_metainfo(jobno=self.number,\n job_name=self.name,\n job_dsc=self.description,\n instances=instances,\n ammo_path=ammo_path,\n loop_count=loop_count,\n version_tested=self.version,\n component=regression_component,\n cmdline=cmdline,\n is_starred=is_starred,\n tank_type=tank_type,\n trace=self.log_other_requests)\n except (APIClient.NotAvailable, APIClient.StoppedFromOnline, APIClient.NetworkError,\n APIClient.UnderMaintenance) as e:\n logger.warn('Failed to edit job metainfo on Lunapark')\n logger.warn(e)\n\n @property\n def number(self):\n if not self._number:\n self.create()\n return self._number\n\n @property\n def token(self):\n if not self._token:\n self.create()\n return self._token\n\n def close(self, rc):\n if self._number:\n return self.api_client.close_job(self.number, rc, trace=self.log_other_requests)\n else:\n return True\n\n def create(self):\n self._number, self._token = self.api_client.new_job(task=self.task,\n person=self.person,\n tank=self.tank,\n loadscheme=self.load_scheme,\n target_host=self.target_host,\n target_port=self.target_port,\n detailed_time=self.detailed_time,\n notify_list=self.notify_list,\n trace=self.log_other_requests)\n self.add_cleanup()\n logger.info('Job created: {}'.format(self._number))\n self.web_link = urljoin(self.api_client.base_url, str(self._number))\n\n def send_status(self, status):\n if self._number and not self.interrupted.is_set():\n self.api_client.send_status(\n self.number,\n self.token,\n status,\n trace=self.log_status_requests)\n\n def get_task_data(self, task):\n return self.api_client.get_task_data(\n task, trace=self.log_other_requests)\n\n def send_config(self, lp_requisites, content):\n self.api_client.send_config(self.number, lp_requisites, content, trace=self.log_other_requests)\n\n def push_monitoring_data(self, data):\n if not self.interrupted.is_set():\n self.api_client.push_monitoring_data(\n self.number, self.token, data, self.interrupted, trace=self.log_monitoring_requests)\n\n def push_events_data(self, data):\n if not self.interrupted.is_set():\n self.api_client.push_events_data(self.number, self.person, data)\n\n def lock_target(self, lock_target, lock_target_duration, ignore, strict):\n lock_wait_timeout = 10\n maintenance_timeouts = iter([0]) if ignore else iter(lambda: lock_wait_timeout, 0)\n while True:\n try:\n self.api_client.lock_target(lock_target,\n lock_target_duration,\n trace=self.log_other_requests,\n maintenance_timeouts=maintenance_timeouts,\n maintenance_msg=\"Target is locked.\\nManual unlock link: %s/%s\" % (\n self.api_client.base_url,\n self.api_client.get_manual_unlock_link(lock_target)\n ))\n return True\n except (APIClient.NotAvailable, APIClient.StoppedFromOnline) as e:\n logger.info('Target is not locked due to %s', e)\n if ignore:\n logger.info('ignore_target_locks = 1')\n return False\n elif strict:\n raise e\n else:\n logger.info('strict_lock = 0')\n return False\n except APIClient.UnderMaintenance:\n logger.info('Target is locked')\n if ignore:\n logger.info('ignore_target_locks = 1')\n return False\n logger.info(\"Manual unlock link: %s/%s\",\n self.api_client.base_url,\n self.api_client.get_manual_unlock_link(lock_target))\n continue\n\n def set_imbalance_and_dsc(self, rps, comment, timestamp):\n return self.api_client.set_imbalance_and_dsc(self.number, rps, comment, timestamp)\n\n def is_target_locked(self, host, strict):\n while True:\n try:\n return self.api_client.is_target_locked(\n host, trace=self.log_other_requests)\n except APIClient.UnderMaintenance:\n logger.info('Target is locked, retrying...')\n continue\n except (APIClient.StoppedFromOnline, APIClient.NotAvailable, APIClient.NetworkError):\n logger.info('Can\\'t check whether target is locked\\n')\n if strict:\n logger.warn('Stopping test due to strict_lock')\n raise\n else:\n logger.warn('strict_lock is False, proceeding')\n return {'status': 'ok'}\n\n\nclass CloudLoadTestingJob(Job):\n\n def __init__(\n self,\n client,\n target_host,\n target_port,\n name,\n description,\n tank_job_id,\n storage,\n config,\n load_scheme=None,\n log_monitoring_requests=False,\n ):\n self.target_host = target_host\n self.target_port = target_port\n self.tank_job_id = tank_job_id\n self.name = name\n self.description = description\n self._number = None # cloud job id\n self.api_client = client\n self.load_scheme = load_scheme\n self.interrupted = threading.Event()\n self.storage = storage\n self._raw_config = config\n self._config = None\n self.log_monitoring_requests = log_monitoring_requests\n\n self.create() # FIXME check it out, maybe it is useless\n\n def push_test_data(self, data, stats):\n if not self.interrupted.is_set():\n try:\n self.api_client.push_test_data(\n self.number, data, stats, self.interrupted)\n except (CloudGRPCClient.NotAvailable, CloudGRPCClient.AgentIdNotFound, RuntimeError):\n logger.warn('Failed to push test data')\n self.interrupted.set()\n\n def edit_metainfo(self, *args, **kwargs):\n logger.info('Cloud service has already set metainfo')\n\n # cloud job id\n @property\n def number(self):\n if not self._number:\n raise self.UnknownJobNumber('Job number is unknown')\n return self._number\n\n @property\n def config(self):\n if self._config is None and self._raw_config is not None:\n self._config = yaml.dump(self._raw_config)\n return self._config\n\n def close(self, *args, **kwargs):\n logger.debug('Cannot close job in the cloud mode')\n\n def create(self):\n cloud_job_id = self.storage.get_cloud_job_id(self.tank_job_id)\n if cloud_job_id is None:\n response = self.api_client.create_test(self.target_host, self.target_port, self.name, self.description, self.load_scheme, self.config)\n metadata = test_service_pb2.CreateTestMetadata()\n response.metadata.Unpack(metadata)\n self._number = metadata.test_id\n logger.info('Job was created: %s', self.number)\n self.storage.push_job(self.number, self.tank_job_id)\n else:\n self._number = cloud_job_id\n\n def send_status(self, *args, **kwargs):\n logger.debug('Tank client is sending the status')\n\n def send_config(self, *args, **kwargs):\n logger.debug('Do not send config to the cloud service')\n\n def push_monitoring_data(self, data):\n if not self.interrupted.is_set():\n self.api_client.push_monitoring_data(\n self.number, data, self.interrupted, trace=self.log_monitoring_requests)\n\n def push_events_data(self, *args, **kwargs):\n logger.debug('Do not push event data for cloud service')\n\n def lock_target(self, *args, **kwargs):\n logger.debug('Target locking is not implemented for cloud')\n\n def set_imbalance_and_dsc(self, rps, comment, timestamp):\n return self.api_client.set_imbalance_and_dsc(self.number, rps, comment, timestamp)\n\n def is_target_locked(self, *args, **kwargs):\n logger.debug('Target locking is not implemented for cloud')\n\n\nclass EventsReader(FileScanner):\n \"\"\"\n Parse lines and return stats\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(EventsReader, self).__init__(*args, **kwargs)\n\n def _read_data(self, lines):\n results = []\n for line in lines:\n # 2018-03-30 13:40:50,541\\tCan't get monitoring config\n data = line.split(\"\\t\")\n if len(data) > 1:\n timestamp, message = data[0], data[1]\n dt = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S,%f')\n unix_ts = int(time.mktime(dt.timetuple()))\n results.append([unix_ts, message])\n return results\n","repo_name":"yandex/yandex-tank","sub_path":"yandextank/plugins/DataUploader/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":40864,"program_lang":"python","lang":"en","doc_type":"code","stars":2344,"dataset":"github-code","pt":"19"} +{"seq_id":"4273514513","text":"import asyncio\nimport json\nfrom abc import ABC, abstractmethod\n\n# TODO: replace Any here\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nimport aiohttp\nimport ya_activity\nimport ya_market\nimport ya_payment\n\n\nclass YagnaEventCollector(ABC):\n _event_collecting_task: Optional[asyncio.Task] = None\n\n def start_collecting_events(self) -> None:\n if self._event_collecting_task is None:\n task = asyncio.get_event_loop().create_task(self._collect_yagna_events())\n self._event_collecting_task = task\n\n def stop_collecting_events(self) -> None:\n if self._event_collecting_task is not None:\n self._event_collecting_task.cancel()\n self._event_collecting_task = None\n\n async def _collect_yagna_events(self) -> None:\n # TODO: All of the logic related to \"what if collecting fails\" is now copied from\n # yapapi pooling batch logic. Also, is quite ugly.\n # https://github.com/golemfactory/golem-core-python/issues/50\n gsb_endpoint_not_found_cnt = 0\n MAX_GSB_ENDPOINT_NOT_FOUND_ERRORS = 3\n\n while True:\n args = self._collect_events_args()\n kwargs = self._collect_events_kwargs()\n try:\n events = await self._collect_events_func(*args, **kwargs)\n except Exception as e:\n if is_intermittent_error(e):\n continue\n elif is_gsb_endpoint_not_found_error(e): # type: ignore[arg-type]\n gsb_endpoint_not_found_cnt += 1\n if gsb_endpoint_not_found_cnt <= MAX_GSB_ENDPOINT_NOT_FOUND_ERRORS:\n await asyncio.sleep(3)\n continue\n\n raise\n\n gsb_endpoint_not_found_cnt = 0\n if events:\n for event in events:\n await self._process_event(event)\n\n @property\n @abstractmethod\n def _collect_events_func(self) -> Callable:\n raise NotImplementedError\n\n @abstractmethod\n async def _process_event(self, event: Any) -> None:\n raise NotImplementedError\n\n def _collect_events_args(self) -> List:\n return []\n\n def _collect_events_kwargs(self) -> Dict:\n return {}\n\n\ndef is_intermittent_error(e: Exception) -> bool:\n \"\"\"Check if `e` indicates an intermittent communication failure such as network timeout.\"\"\"\n\n is_timeout_exception = isinstance(e, asyncio.TimeoutError) or (\n isinstance(\n e,\n (ya_activity.ApiException, ya_market.ApiException, ya_payment.ApiException),\n )\n and e.status in (408, 504)\n )\n\n return (\n is_timeout_exception\n or isinstance(e, aiohttp.ServerDisconnectedError)\n # OS error with errno 32 is \"Broken pipe\"\n or (isinstance(e, aiohttp.ClientOSError) and e.errno == 32)\n )\n\n\ndef is_gsb_endpoint_not_found_error(\n err: Union[ya_activity.ApiException, ya_market.ApiException, ya_payment.ApiException]\n) -> bool:\n \"\"\"Check if `err` is caused by \"Endpoint address not found\" GSB error.\"\"\"\n\n if err.status != 500:\n return False\n try:\n msg = json.loads(err.body)[\"message\"]\n return \"GSB error\" in msg and \"endpoint address not found\" in msg\n except Exception:\n return False\n","repo_name":"golemfactory/golem-core-python","sub_path":"golem/utils/low/event_collector.py","file_name":"event_collector.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"331814543","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\nclass jardinero(models.Model):\n _name = 'upogarden.jardinero'\n _inherit = 'upogarden.trabajador'\n turno = fields.Char('Turno', size=64, required=True)\n servicios_ids = fields.Many2many('upogarden.servicio',string=\"Servicios\")\n \n def baja_jardinero(self):\n self.write({'servicios_ids':[(5, ) ]})","repo_name":"Juanorma16/UPOGarden","sub_path":"upogarden/models/jardinero.py","file_name":"jardinero.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20691579983","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 11 10:11:55 2021\r\n\r\n@author: Sezal\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn import preprocessing \r\nfrom scipy.spatial import distance\r\nimport math\r\nfrom selfrepresentation import SparseSubspaceClusteringOMP\r\n\r\nclass paper:\r\n def __init__(self,pid, ID, title, year):\r\n self.pid = pid\r\n self.ID = ID\r\n self.title = title\r\n self.year = year\r\n \r\npapers={}\r\n\r\nwith open(\"datasets_inUse/paper_ids.txt\",\"r\", encoding=\"utf8\") as file:\r\n pid=0\r\n for i in file.readlines():\r\n l=i.split()\r\n # making the entire title sentence\r\n title=' '.join(l[1:len(l)-1])\r\n # paper id pid is increasing values of 1 with eveyr loop\r\n papers[l[0]]=paper(pid, l[0], title, l[-1])\r\n pid+=1\r\n\r\n\r\n#Number of papers in total\r\nnop=len(papers)\r\n\r\n\"\"\"\"Paper Citation matrix\"\"\"\r\n\r\ndef paper_citation_matrix():\r\n with open(\"datasets_inUse/paper-citation-network-nonself.txt\",'r') as file:\r\n matrix=np.zeros((nop,nop))\r\n for i in tqdm(file.readlines()):\r\n l=i.split()\r\n #print(papers[l[0]].pid,\" \" , papers[l[2]].pid,\" -------------------\")\r\n matrix[papers[l[0]].pid,papers[l[2]].pid]=1\r\n return pd.DataFrame(matrix)\r\n\r\n\r\n\r\n\r\n\r\n\r\ndata=paper_citation_matrix()\r\nprint(data.shape)\r\n\r\n#Pickling the Citation Matrix\r\n#pickling_on = open(\"CitationMatrix.pickle\",\"wb\")\r\n#pickle.dump(data, pickling_on,protocol=4)\r\n#pickling_on.close()\r\n\r\n\r\n\r\n \r\ndef calculate(trainingData, testingData, distanceMeasure, n_clusters, affinity): \r\n\r\n ssc = SparseSubspaceClusteringOMP(n_clusters, affinity=affinity)\r\n clusterTrain = ssc.fit(trainingData)\r\n TrainingClusters=clusterTrain.labels_\r\n clusteringTest = ssc.fit_predict(testingData)\r\n\r\n return TrainingClusters,clusteringTest\r\n \r\n\r\n\r\n\r\n#FIND RECOMMENDATIONS ------------------------------------------------------\r\n \r\nPOI_ID = \"P12-1041\"\r\nPOI_INDEX = papers[POI_ID].pid\r\n\r\n\r\n#Making Training Data\r\ntrainingData = data.drop(POI_INDEX, axis=0, inplace=False)\r\ntrainingData.drop(POI_INDEX, axis=1, inplace=True)\r\n\r\n#Making Testing Data\r\ntestingData = data.iloc[POI_INDEX]\r\ntestingData.drop(POI_INDEX, inplace=True)\r\n\r\n\r\n#Training -----------------------\r\n\r\n#affinity = ['symmetrize','nearest_neighbors']\r\naffinity = 'symmetrize'\r\nssc = SparseSubspaceClusteringOMP(n_clusters=10, affinity=affinity)\r\nclusterTrain = ssc.fit(trainingData)\r\nAllotedClustersTraining=clusterTrain.labels_\r\n\r\nAllotedCluster = ssc.fit_predict(testingData)\r\nfrom scipy import stats\r\nfrom collections import Counter\r\n\r\nm = stats.mode(AllotedCluster)\r\nprint(m)\r\nAlloted = 0\r\nCounter(AllotedCluster)\r\n\r\n#%%\r\n\r\n# Finding Predictions\r\nclusterArray = []\r\nnonclusterArray = []\r\nfor i in range(len(AllotedClustersTraining)):\r\n if(AllotedClustersTraining[i]==Alloted):\r\n clusterArray.append(i)\r\n else:\r\n nonclusterArray.append(i)\r\n \r\n#%%\r\ntestingData = testingData.T\r\nprint(testingData.shape)\r\n\r\n#%%\r\n#distanceMeasure = 'euclidean'\r\n#distanceMeasure = 'cosine'\r\ndistanceMeasure = 'jaccard'\r\ndistanceArray = {}\r\nfor i in range(len(clusterArray)):\r\n trainingclusterCitations = trainingData.iloc[clusterArray[i]].values.reshape(1,-1) \r\n d = distance.cdist(trainingclusterCitations, testingData, distanceMeasure)\r\n distanceArray[clusterArray[i]] = d[0][0]\r\n \r\n \r\nsorted_dict = [(value, key) for (key, value) in distanceArray.items()]\r\nsorted_dict.sort(reverse=True)\r\n#%% \r\n\r\n#Finding Recommendations \r\nprint(\"Index of paper of Interest- \", POI_INDEX)\r\nprint(\"Papers Recommended for Paper ID- \", POI_ID)\r\nprint(\"Title- \" , papers[POI_ID].title)\r\ntopKPapers = 5\r\nfor i in range(topKPapers):\r\n pid = list(distanceArray.keys())[i]\r\n for j in papers:\r\n if(papers[j].pid==pid):\r\n print(i+1, \". \", papers[j].title , \" \" , j)\r\n\r\n\r\n#%%\r\n#total citations in POI\r\ncitationsOriginal = data.iloc[POI_INDEX].values\r\ncitationsOriginal = np.delete(citationsOriginal, POI_INDEX)\r\ntotalOriginalCitations = np.count_nonzero(citationsOriginal == 1) #22\r\nc1 = np.where(citationsOriginal == 1)[0]\r\nprint(len(c1))\r\nprint(totalOriginalCitations)\r\n#%%\r\n\r\n#%%\r\n \r\n#Find citations which are common with POI and papers ourside our clusters\r\n#this means they were true but model marked them as negative\r\nFalseNegative = 0\r\nfor i in range(len(nonclusterArray)):\r\n trainingNonclusterCitations = data.iloc[nonclusterArray[i]].values\r\n \r\n c2 = np.where(trainingNonclusterCitations == 1)[0]\r\n #print(len(c2))\r\n c = np.sum(c1 == c2)\r\n \r\n# if(c>0):\r\n# print(c,\" \" ,c1,\" \", c2)\r\n# print(nonclusterArray[i])\r\n FalseNegative += (c/totalOriginalCitations)\r\nprint('FalseNegative', FalseNegative) \r\n#%%\r\n \r\n#Find citations which are not common with POI and papers ourside our clusters\r\n#this means they were false and model marked them as negative\r\nTrueNegative = 0\r\nfor i in range(len(nonclusterArray)):\r\n trainingNonclusterCitations = data.iloc[nonclusterArray[i]].values\r\n\r\n c = np.sum(citationsOriginal != trainingNonclusterCitations)\r\n# if(c>1):\r\n# print(c)\r\n# print(nonclusterArray[i])\r\n TrueNegative += (c/len(citationsOriginal))\r\nprint('TrueNegative', TrueNegative)\r\n\r\n\r\n#%%\r\nk = 15\r\nrecallArray = []\r\nprecisionArray = []\r\naccuracyArray=[]\r\n\r\nfor i in range(1,k+1):\r\n topKPapers = [key for (value,key) in sorted_dict[:i]]\r\n #print(topKPapers)\r\n \r\n FalsePositive = 0\r\n TruePositive = 0\r\n for i in range(len(topKPapers)):\r\n trainingclusterCitations = data.iloc[topKPapers[i]].values\r\n c2 = np.where(trainingclusterCitations == 1)[0]\r\n \r\n common =0 \r\n for i in range(len(citationsOriginal)):\r\n if(citationsOriginal[i]==1 and citationsOriginal[i] == trainingclusterCitations[i]):\r\n common += 1\r\n if(len(c1)!=0 and len(c2)!=0):\r\n FalsePositive += ((len(c2) - common)/len(c2))\r\n TruePositive += (common/len(c1))\r\n print('Common', common) \r\n print('FalsePositive', FalsePositive)\r\n print('TruePositive', TruePositive)\r\n print(topKPapers)\r\n if(TruePositive!=0 or FalsePositive!=0):\r\n recall = TruePositive / (TruePositive + FalseNegative)\r\n precision = TruePositive / (TruePositive + FalsePositive)\r\n accuracy = (TruePositive + TrueNegative) / (TruePositive + TrueNegative + FalsePositive + FalseNegative)\r\n \r\n recallArray.append(recall)\r\n precisionArray.append(precision)\r\n accuracyArray.append(accuracy)\r\n\r\n \r\n#%%\r\naccuracyArray = np.cumsum(accuracyArray)\r\nPlotAccuracy = [accuracyArray[i]/(i+1) for i in range(len(accuracyArray))]\r\n\r\nrecallArray = np.cumsum(recallArray)\r\nPlotRecall = [recallArray[i]/(i+1) for i in range(len(recallArray))]\r\n\r\nprecisionArray = np.cumsum(precisionArray)\r\nPlotPrecision = [precisionArray[i]/(i+1) for i in range(len(precisionArray))]\r\n\r\n\r\n#%%\r\nimport matplotlib.pyplot as plt\r\n \r\nXaxis = [i for i in range(15)]\r\n \r\nplt.plot(Xaxis, PlotRecall, c='red', label='Recall')\r\nplt.plot(Xaxis, PlotPrecision, c='blue', label ='Precision')\r\nplt.title('Recall and Precision Graph')\r\nplt.xlabel('List of top K Recommended Papers')\r\nplt.ylabel('Cummulative Average Scores')\r\nplt.legend()\r\nname = 'Subspace_' + distanceMeasure + POI_ID + '.png'\r\nplt.savefig(name)\r\nplt.show() \r\n \r\n \r\n","repo_name":"raghav17083/Collaborative-Filtering","sub_path":"project/subspaceClustering.py","file_name":"subspaceClustering.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"28617186064","text":"def solution(dirs):\n answer = 0\n visited = set()\n move_types = ['L', 'R', 'U', 'D']\n dx = [0, 0, -1, 1]\n dy = [-1, 1, 0, 0]\n x, y = 5, 5\n for dir in dirs:\n for i in range(len(move_types)):\n if dir == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 0 or ny < 0 or nx > 10 or ny > 10:\n continue\n if (x, y, nx, ny) not in visited and (nx, ny, x, y) not in visited:\n visited.add((x,y,nx,ny))\n answer += 1\n x, y = nx , ny\n \n return answer\n\n\nprint(solution(\"ULURRDLLU\"))","repo_name":"98-jeonghoon/Algorithm","sub_path":"Programmers/방문 길이.py","file_name":"방문 길이.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22461002705","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n@author: amaldonadop\r\n@author: vapaternina\r\n@author: raulj\r\n\r\n\"\"\"\r\n#Librerias\r\nimport numpy as np\r\nfrom matplotlib import mlab as ml\r\nimport graph as g\r\n#vector costo que es global\r\n#vector pred que es global\r\n# n = número de nodos\r\n#---------------------------------------------------\r\ndef relax(u, v, w):\r\n \r\n if costo[v] > costo[u] + w[u,v]:\r\n costo[v] = costo[u] + w[u,v]\r\n pred[v]= u\r\n\r\n#---------------------------------------------------\r\ndef initSource(w, s):\r\n for v in range(len(w)):\r\n costo[v]=99999999\r\n pred[v]= -1\r\n \r\n costo[s]= 0\r\n#---------------------------------------------------\r\ndef bellmanFord(w, s):\r\n initSource(w, s)\r\n n = len(w);\r\n for k in range(n):\r\n for i in range(n):\r\n for j in range(n):\r\n if w[i,j] != 0:\r\n relax(i,j,w)\r\n print(costo)\r\n print(pred)\r\n dest = ml.find(costo == max(costo))[0]\r\n for i in range(n-1):\r\n for j in range(n-1):\r\n if costo[j]>costo[i]+w[i,j]:\r\n print('Hay ciclo negativo en el grafo');\r\n sw=False\r\n return sw, dest \r\n \r\n sw = True\r\n return sw, dest\r\n#---------------------------------------------------\r\n \r\n#Programa principal\r\n\r\nprint(\"Ingrese matriz de pesos de la forma: 0 0;0 0\")\r\np = input(\"Ingrese matriz de pesos w = \")\r\ns = int(input(\"Ingrese el nodo fuente s = \"))\r\n\r\np = p.split(';') #len(p) corresponde al número de nodos\r\nn = len(p)\r\nw = np.zeros((n,n))\r\n\r\nfor i in range(n):\r\n sb = p[i].split(' ')\r\n for j in range(len(sb)):\r\n w[i,j]=sb[j]\r\n\r\ncosto = np.zeros(n)\r\npred= np.zeros(n)\r\nl = g.obt(w)\r\ng.dibG(l,n)\r\nsw, dest = bellmanFord(w,s)\r\n\r\nprint(dest)\r\n\r\nc = []\r\ni = ml.find(pred == s)[0]#Encontramos el nodo fuente y obtenemos su indice que es la primera pareja\r\nc.append((str(s), str(i)))\r\nif i == dest:\r\n t= False\r\nelse:\r\n t= True\r\n \r\nwhile t:\r\n j = ml.find(pred == i)[0]\r\n c.append((str(i), str(j)))\r\n i=j\r\n if i == dest:\r\n t = False\r\n\r\ng.dibC(l,c)\r\n \r\n\r\n","repo_name":"rjuliao/Caminos-Minimos","sub_path":"grafos.py","file_name":"grafos.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3402976791","text":"import pytest\nimport yaml\n\nfrom argo_workflow_tools import dsl, Workflow\n\n\ndef say_hello(name):\n message = f\"hello {name}\"\n print(message)\n return message\n\n\n@dsl.DAG()\ndef say_hello_dag(name):\n return say_hello(name)\n\n\ndef test_entrypoint_without_decorator():\n with pytest.raises(ValueError):\n workflow = Workflow(\n name=\"hello-world\", entrypoint=say_hello, arguments={\"name\": \"Brian\"}\n )\n workflow.to_model()\n\n\ndef test_inner_task_without_decorator():\n with pytest.raises(TypeError):\n workflow = Workflow(\n name=\"hello-world\", entrypoint=say_hello_dag, arguments={\"name\": \"Brian\"}\n )\n workflow.to_model()\n\n\n@dsl.Task(image=\"python:3\")\ndef say_hello_task_mismatch(name):\n print(\"hello\")\n\n\n@dsl.Task(image=\"python:3\")\ndef say_hello_task_no_args_mismatch():\n print(\"hello\")\n\n\n@dsl.DAG()\ndef say_hello_dag_mismatch(name):\n return say_hello_task_mismatch(not_name=name)\n\n\n@dsl.DAG()\ndef say_hello_dag_args_mismatch(name):\n return say_hello_task_no_args_mismatch(name)\n\n\ndef test_dag_signature_kwargs_mismatch():\n with pytest.raises(TypeError):\n workflow = Workflow(\n name=\"hello-world\",\n entrypoint=say_hello_dag_mismatch,\n arguments={\"name\": \"Brian\"},\n )\n workflow.to_model()\n\n\ndef test_dag_signature_args_mismatch():\n with pytest.raises(TypeError):\n workflow = Workflow(\n name=\"hello-world\",\n entrypoint=say_hello_dag_args_mismatch,\n arguments={\"name\": \"Brian\"},\n )\n workflow.to_model()\n","repo_name":"DiagnosticRobotics/argo-workflow-tools","sub_path":"tests/argo_workflow_tools/dsl/test_dag_errors.py","file_name":"test_dag_errors.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"19"} +{"seq_id":"1814090553","text":"# pylint:disable=invalid-name, too-many-locals, too-many-arguments\n\"\"\"Show\n\nAnimated displays of image transformations\n\nAssembles lists of images into named 2-grids, assembles multiples of\nthese image grids in a single output view, and allows real-time\nupdating of their contents with successive calls to show_images.\n\n\"\"\"\nfrom __future__ import division, print_function\nfrom itertools import product\nfrom collections import OrderedDict, namedtuple\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nImgarray = namedtuple('Imgarray', 'contents axis count')\nimgarrays = OrderedDict() # composite images to display, by title\n\ndef show_images(Image, shape, title=\"\", spacing=2):\n \"\"\"Create a grid of images and display them\n\n Parameters\n ----------\n Image : list of ndarray(h, v)\n images to composite. must all have same shape\n shape : tuple\n shape of tiled image array. Must agree with len(Image)\n title : string\n title to display above this image array, and to look up\n the array for future updating calls.\n spacing : int\n number of pixels spacing between tiled images\n\n \"\"\"\n imshape = (np.max([image.shape[0] for image in Image]),\n np.max([image.shape[1] for image in Image]))\n (rows, cols), (hgt, wid) = shape, imshape\n bhgt, bwid = (hgt + spacing, wid + spacing)\n composite = np.ones((bhgt * rows, bwid * cols)) * np.nan\n for row, col in product(range(rows), range(cols)):\n image = Image[row * cols + col]\n composite[row * bhgt:row * bhgt + image.shape[0],\n col * bwid:col * bwid + image.shape[1]] = image\n\n if not imgarrays.has_key(title):\n # allocate a new row beneath existing imgarrays\n plt.close()\n _, axes = plt.subplots(nrows=len(imgarrays) + 1, ncols=1, squeeze=False)\n plt.gray()\n # transfer the imgarrays to their new axes\n imgarrays[title] = Imgarray(composite, None, 1)\n for (title, ia), axis in zip(imgarrays.items(), axes[:, 0]):\n imgarrays[title] = Imgarray(ia.contents, axis, ia.count)\n titlefmt = title + (\"({})\".format(ia.count) if ia.count > 1 else \"\")\n axis.set_title(titlefmt)\n axis.imshow(ia.contents)\n axis.axis('off')\n else:\n # update the contents of an existing imgarray in place\n ia = imgarrays[title]\n imgarrays[title] = Imgarray(composite, ia.axis, ia.count + 1)\n titlefmt = title + \"({})\".format(ia.count + 1)\n ia.axis.set_title(titlefmt)\n ia.axis.imshow(composite)\n plt.pause(.001)\n\ndef show_vec_images(imat, imshape, shape, title=\"\", spacing=2):\n \"\"\"like show_images, but for images stored as columns in a matrix.\n\n Parameters\n ----------\n imat : ndarray(npixels, nimages)\n each column is a flattened image to composite.\n imshape : tuple\n (h, v) for flattened images in imat\n shape : tuple\n shape of tiled image array. Must agree with len(Image)\n title : string\n title to display above this image array, and to look up\n the array for future updating calls.\n spacing : int\n number of pixels spacing between tiled images\n\n \"\"\"\n Image = [imat[:, i].reshape(imshape) for i in range(shape[0] * shape[1])]\n show_images(Image, title=title, spacing=spacing, shape=shape)\n","repo_name":"welch/rasl","sub_path":"rasl/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"19"}